diff --git a/.appveyor.yml b/.appveyor.yml deleted file mode 100644 index 3e8f2dde6..000000000 --- a/.appveyor.yml +++ /dev/null @@ -1,11 +0,0 @@ -version: 0.8.{build} -pull_requests: - do_not_increment_build_number: true -image: -- Visual Studio 2019 Preview -install: -- sh: sudo apt-get -y install libblas-dev liblapack-dev -build: off -test_script: -- pwsh: "&($env:APPVEYOR_BUILD_FOLDER + '/GenerateCode.ps1')" -- pwsh: "&($env:APPVEYOR_BUILD_FOLDER + '/ExecuteUnitTests.ps1')" diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md new file mode 100644 index 000000000..09d1f3c73 --- /dev/null +++ b/.claude/CLAUDE.md @@ -0,0 +1,636 @@ +# NumSharp Project Instructions + +NumSharp is a .NET port of Python's NumPy library targeting **1-to-1 API and behavioral compatibility with NumPy 2.x**. + +## NumPy Reference Source + +A full clone of the NumPy repository is available at `src/numpy/`. Use this as the authoritative reference for API behavior, edge cases, and implementation details when implementing or verifying NumSharp functions. + +## Core Principles + +1. **Match NumPy Exactly**: Run actual Python/NumPy code first, observe behavior, replicate in C# +2. **Match NumPy Implementation Patterns**: Don't just match behavior - match NumPy's implementation structure. If NumPy has a clean approach and NumSharp has spaghetti code, refactor to match NumPy's design +3. **Edge Cases Matter**: NaN handling, empty arrays, type promotion, broadcasting, negative axis +4. **Breaking Changes OK**: Breaking changes are acceptable to match NumPy +5. **Test From NumPy Output**: Tests should be based on running actual NumPy code + +**When fixing bugs:** Don't just patch symptoms. Check `src/numpy/` for how NumPy implements the same functionality, then refactor NumSharp to match NumPy's structure. + +## Definition of Done (DOD) - Operations + +Every np.* function and DefaultEngine operation MUST satisfy these criteria: + +### Memory Layout Support +- **Contiguous arrays**: Works correctly with C-contiguous memory (SIMD fast path) +- **Non-contiguous arrays**: Works correctly with sliced/strided/transposed views +- **Broadcast arrays**: Works correctly with stride=0 dimensions (read-only) +- **Sliced views**: Correctly handles Shape.offset for base address calculation + +### Dtype Support +All 12 NumSharp types must be handled (or explicitly documented as unsupported): +Boolean, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Char, Single, Double, Decimal + +### NumPy API Parity +- Function signature matches NumPy (parameter names, order, defaults) +- Type promotion matches NumPy 2.x (NEP50) +- Edge cases match NumPy (empty arrays, scalars, NaN handling, broadcasting) +- Return dtype matches NumPy exactly + +### Testing +- Unit tests based on actual NumPy output +- Edge case tests (empty, scalar, broadcast, strided) +- Dtype coverage tests + +**Full audit tracking:** See `docs/KERNEL_API_AUDIT.md` + +## Supported Types (12) + +| NPTypeCode | C# Type | NPTypeCode | C# Type | +|------------|---------|------------|---------| +| Boolean | bool | Int64 | long | +| Byte | byte | UInt64 | ulong | +| Int16 | short | Char | char | +| UInt16 | ushort | Single | float | +| Int32 | int | Double | double | +| UInt32 | uint | Decimal | decimal | + +All operations must handle all 12 types via type switch pattern. + +## Architecture + +``` +NDArray Main class (like numpy.ndarray) +├── Storage UnmanagedStorage (raw pointers, not managed arrays) +├── Shape Dimensions, strides, offset calculation +└── TensorEngine Computation backend (DefaultEngine = pure C#) + +np Static API class (like `import numpy as np`) +├── np.random NumPyRandom (1-to-1 seed/state with NumPy) +└── np.* Functions in Creation/, Math/, Statistics/, Logic/, etc. +``` + +## Key Design Decisions + +| Decision | Rationale | +|----------|-----------| +| Unmanaged memory | Benchmarked fastest; optimized for performance | +| C-order only | Only row-major (C-order) memory layout. Uses `ArrayFlags.C_CONTIGUOUS` flag. No F-order/column-major support. The `order` parameter on `ravel`, `flatten`, `copy`, `reshape` is accepted but ignored. | +| Regen templating | Type-specific code generation (legacy, mostly replaced by ILKernel) | +| TensorEngine abstract | Future GPU/SIMD backends possible | +| View semantics | Slicing returns views (shared memory), not copies | +| Shape readonly struct | Immutable after construction (NumPy-aligned). Contains `ArrayFlags` for cached O(1) property access | +| Broadcast write protection | Broadcast views are read-only (`IsWriteable = false`), matching NumPy behavior | +| ILKernelGenerator | Runtime IL emission (~21K lines) with SIMD V128/V256/V512; replaces Regen templates | + +## ILKernelGenerator + +Runtime IL generation via `System.Reflection.Emit.DynamicMethod` for high-performance kernels. + +**Partial Class Structure (27 files):** +| Category | Files | +|----------|-------| +| Core | `ILKernelGenerator.cs` (type mapping, SIMD detection), `.Scalar.cs` | +| Binary | `.Binary.cs`, `.MixedType.cs`, `.Shift.cs` | +| Unary | `.Unary.cs`, `.Unary.Math.cs`, `.Unary.Decimal.cs`, `.Unary.Vector.cs`, `.Unary.Predicate.cs` | +| Comparison | `.Comparison.cs` | +| Reduction | `.Reduction.cs`, `.Reduction.Arg.cs`, `.Reduction.Boolean.cs`, `.Reduction.Axis.cs`, `.Reduction.Axis.Arg.cs`, `.Reduction.Axis.Simd.cs`, `.Reduction.Axis.NaN.cs`, `.Reduction.Axis.VarStd.cs` | +| Scan | `.Scan.cs` (CumSum, CumProd) | +| Masking | `.Masking.cs`, `.Masking.Boolean.cs`, `.Masking.NaN.cs`, `.Masking.VarStd.cs` | +| Other | `.Clip.cs`, `.Modf.cs`, `.MatMul.cs` | + +**Execution Paths:** +1. **SimdFull** - Both operands contiguous, SIMD-capable dtype → Vector loop + scalar tail +2. **ScalarFull** - Both contiguous, non-SIMD dtype (Decimal) → Scalar loop +3. **General** - Strided/broadcast → Coordinate-based iteration + +**NEP50 Dtype Alignment (NumPy 2.x):** +| Operation | Returns | +|-----------|---------| +| `sum(int32)` | `int64` | +| `prod(int32)` | `int64` | +| `cumsum(int32)` | `int64` | +| `abs(int32)` | `int32` (preserves) | +| `sign(int32)` | `int32` (preserves) | +| `power(int32, float)` | `float64` | + +**ILKernel Coverage:** +| Category | Operations | +|----------|------------| +| Binary | Add, Sub, Mul, Div, Power, FloorDivide, BitwiseAnd/Or/Xor | +| Shift | LeftShift, RightShift (SIMD for scalar, scalar loop for array) | +| Unary | Negate, Abs, Sign, Sqrt, Cbrt, Square, Reciprocal, Floor, Ceil, Truncate, Trig, Exp, Log, BitwiseNot | +| Reduction | Sum, Prod, Min, Max, Mean, ArgMax, ArgMin, All, Any, Std, Var | +| Scan | CumSum, CumProd (element-wise SIMD + axis support) | +| Comparison | Equal, NotEqual, Less, Greater, LessEqual, GreaterEqual | +| Clip/Modf | Clip, Modf (SIMD helpers) | +| Axis reductions | Sum, Prod, Min, Max, Mean, Std, Var (iterator path) | + +## Shape Architecture (NumPy-Aligned) + +Shape is a `readonly struct` with cached `ArrayFlags` computed at construction: + +```csharp +public readonly partial struct Shape +{ + internal readonly int _flags; // Cached ArrayFlags bitmask + internal readonly int _hashCode; // Precomputed hash code + internal readonly int size; // Total element count + internal readonly int[] dimensions; // Dimension sizes + internal readonly int[] strides; // Stride values (0 = broadcast dimension) + internal readonly int bufferSize; // Size of underlying buffer + internal readonly int offset; // Base offset into storage +} +``` + +**ArrayFlags enum** (matches NumPy's `ndarraytypes.h`): +| Flag | Value | Meaning | +|------|-------|---------| +| `C_CONTIGUOUS` | 0x0001 | Data is row-major contiguous | +| `F_CONTIGUOUS` | 0x0002 | Reserved (always false for NumSharp) | +| `OWNDATA` | 0x0004 | Array owns its data buffer | +| `ALIGNED` | 0x0100 | Always true for managed allocations | +| `WRITEABLE` | 0x0400 | False for broadcast views | +| `BROADCASTED` | 0x1000 | Has stride=0 with dim > 1 | + +**Key Shape properties:** +- `IsContiguous` — O(1) check via `C_CONTIGUOUS` flag +- `IsBroadcasted` — O(1) check via `BROADCASTED` flag +- `IsWriteable` — False for broadcast views (prevents corruption) +- `IsSliced` — True if offset != 0, different size, or non-contiguous +- `IsSimpleSlice` — IsSliced && !IsBroadcasted (fast offset path) + +## Critical: View Semantics + +**Slicing returns views, not copies!** Memory is shared: +```csharp +var view = original["2:5"]; // Shares memory with original +view[0] = 999; // Modifies original[2]! +var copy = original["2:5"].copy(); // Explicit copy +``` + +## Slicing Syntax + +```csharp +nd[":"] // All elements +nd["1:5"] // Elements 1-4 (stop exclusive) +nd["::2"] // Every 2nd element +nd["-1"] // Last element (reduces dimension) +nd["::-1"] // Reversed +nd[":, 0"] // All rows, first column +nd["..., -1"] // Ellipsis fills dimensions +``` + +--- + +## Missing Functions (20) + +These NumPy functions are **not implemented**: + +| Category | Functions | +|----------|-----------| +| Sorting | `np.sort` | +| Selection | `np.where` | +| Manipulation | `np.flip`, `np.fliplr`, `np.flipud`, `np.rot90`, `np.tile`, `np.pad` | +| Splitting | `np.split`, `np.array_split`, `np.hsplit`, `np.vsplit`, `np.dsplit` | +| Diagonal | `np.diag`, `np.diagonal`, `np.trace` | +| Cumulative | `np.diff`, `np.gradient`, `np.ediff1d` | +| Rounding | `np.round` (use `np.round_` or `np.around`) | + +--- + +## Supported np.* APIs + +Tested against NumPy 2.x. + +### Array Creation +`arange`, `array`, `asanyarray`, `asarray`, `copy`, `empty`, `empty_like`, `eye`, `frombuffer`, `full`, `full_like`, `identity`, `linspace`, `meshgrid`, `mgrid`, `ones`, `ones_like`, `zeros`, `zeros_like` + +### Shape Manipulation +`atleast_1d`, `atleast_2d`, `atleast_3d`, `concatenate`, `dstack`, `expand_dims`, `flatten`, `hstack`, `moveaxis`, `ravel`, `repeat`, `reshape`, `roll`, `rollaxis`, `squeeze`, `stack`, `swapaxes`, `transpose`, `unique`, `vstack` + +### Broadcasting +`are_broadcastable`, `broadcast`, `broadcast_arrays`, `broadcast_to` + +### Math — Arithmetic +`abs`, `absolute`, `add`, `cbrt`, `ceil`, `clip`, `convolve`, `divide`, `exp`, `exp2`, `expm1`, `floor`, `floor_divide`, `log`, `log10`, `log1p`, `log2`, `mod`, `modf`, `multiply`, `negative`, `positive`, `power`, `reciprocal`, `sign`, `sin`, `cos`, `tan`, `sqrt`, `square`, `subtract`, `true_divide`, `trunc` + +### Math — Reductions +`all`, `amax`, `amin`, `any`, `argmax`, `argmin`, `count_nonzero`, `cumprod`, `cumsum`, `max`, `mean`, `min`, `prod`, `std`, `sum`, `var` + +### Math — NaN-Aware +`nanmax`, `nanmean`, `nanmin`, `nanprod`, `nanstd`, `nansum`, `nanvar` + +### Bitwise +`bitwise_and`, `bitwise_or`, `bitwise_xor`, `invert`, `left_shift`, `right_shift` + +### Comparison & Logic +`all`, `allclose`, `any`, `array_equal`, `find_common_type`, `isclose`, `isfinite`, `isinf`, `isnan`, `isscalar`, `maximum`, `minimum` + +### Sorting & Searching +`argmax`, `argmin`, `argsort`, `nonzero`, `searchsorted` + +### Linear Algebra +`dot`, `matmul`, `outer` + +### Random (`np.random.*`) +`bernoulli`, `beta`, `binomial`, `chisquare`, `choice`, `exponential`, `gamma`, `geometric`, `lognormal`, `normal`, `permutation`, `poisson`, `rand`, `randint`, `randn`, `seed`, `shuffle`, `standard_normal`, `uniform` + +### File I/O +`fromfile`, `load`, `save`, `tofile` + +### Other +`around`, `copyto`, `round_`, `size` + +### Operators +- Arithmetic: `+`, `-`, `*`, `/`, `%`, unary `-` +- Comparison: `==`, `!=`, `<`, `>`, `<=`, `>=` +- Logical: `&`, `|`, `!` + +### Indexing +- Integer and slice indexing (`nd[0]`, `nd[1:3]`, `nd[::-1]`) +- Boolean masking (`nd[mask]`) — read-only +- Fancy indexing (`nd[indices]`) + +--- + +## Core Source Files + +| Component | Location | +|-----------|----------| +| NDArray | `Backends/NDArray.cs` | +| UnmanagedStorage | `Backends/Unmanaged/UnmanagedStorage.cs` | +| Shape | `View/Shape.cs` | +| Slice | `View/Slice.cs` | +| TensorEngine | `Backends/TensorEngine.cs` | +| DefaultEngine | `Backends/Default/DefaultEngine.*.cs` | +| np API | `APIs/np.cs` | +| Iterators | `Backends/Iterators/NDIterator.cs`, `MultiIterator.cs` | +| Type info | `Utilities/InfoOf.cs` | +| Generic NDArray | `Generics/NDArray\`1.cs` | + +--- + +## Implementation Patterns + +### Pattern 1: Compose existing np functions +```csharp +public static NDArray std(NDArray a, int? axis = null, ...) +{ + var mean_val = np.mean(a, axis, keepdims: true); + return np.sqrt(np.mean(np.power(a - mean_val, 2), axis)); +} +``` + +### Pattern 2: Delegate to TensorEngine +```csharp +public static NDArray sum(NDArray a, int? axis = null, ...) +{ + return a.TensorEngine.Sum(a, axis, typeCode, keepdims); +} +``` +Use Pattern 2 when low-level optimization is needed. + +## Type Switch Pattern + +```csharp +switch (nd.typecode) +{ + case NPTypeCode.Boolean: return Process(nd); + case NPTypeCode.Byte: return Process(nd); + case NPTypeCode.Int16: return Process(nd); + case NPTypeCode.UInt16: return Process(nd); + case NPTypeCode.Int32: return Process(nd); + case NPTypeCode.UInt32: return Process(nd); + case NPTypeCode.Int64: return Process(nd); + case NPTypeCode.UInt64: return Process(nd); + case NPTypeCode.Char: return Process(nd); + case NPTypeCode.Double: return Process(nd); + case NPTypeCode.Single: return Process(nd); + case NPTypeCode.Decimal: return Process(nd); + default: throw new NotSupportedException(); +} +``` + +## GitHub Issues + +Create issues on `SciSharp/NumSharp` via `gh issue create`. `GH_TOKEN` is available via the `env-tokens` skill. + +### Feature / Enhancement + +- **Overview**: 1-2 sentence summary of what and why +- **Problem**: What's broken or missing, why it matters +- **Proposal**: What to change, with a task checklist (`- [ ]`) +- **Evidence**: Data, benchmarks, or references supporting the proposal +- **Scope / Non-goals**: What this issue does NOT cover (prevent scope creep) +- **Benchmark / Performance** (if applicable): Before/after numbers, methodology, what to measure +- **Breaking changes** table (if any): Change | Impact | Migration +- **Related issues**: Link dependencies + +### Bug Report + +- **Overview**: 1-2 sentence summary of the bug and its impact +- **Reproduction**: Minimal code to trigger the bug +- **Expected**: Correct behavior (include NumPy output as source of truth) +- **Actual**: What NumSharp does instead (error message, wrong output, crash) +- **Workaround** (if any): How users can avoid the bug today +- **Root cause** (if known): File, line, why it happens +- **Related issues**: Link duplicates or upstream causes + +## Build & Test + +```bash +# Build (silent, errors only) +dotnet build -v q --nologo "-clp:NoSummary;ErrorsOnly" -p:WarningLevel=0 +``` + +### Running Tests + +Tests use **MSTest v3** framework with source-generated test discovery. + +```bash +# Run from test directory +cd test/NumSharp.UnitTest + +# All tests (includes OpenBugs - expected failures) +dotnet test --no-build + +# Exclude OpenBugs (CI-style - only real failures) +dotnet test --no-build --filter "TestCategory!=OpenBugs" + +# Run ONLY OpenBugs tests +dotnet test --no-build --filter "TestCategory=OpenBugs" + +# Exclude multiple categories +dotnet test --no-build --filter "TestCategory!=OpenBugs&TestCategory!=HighMemory" + +# Run specific test class +dotnet test --no-build --filter "ClassName~BinaryOpTests" + +# Run specific test method +dotnet test --no-build --filter "Name~Add_Int32_SameType" +``` + +### Output Formatting + +```bash +# Results only (no messages, no stack traces) +dotnet test --no-build 2>&1 | grep -E "^(failed|skipped|Test run| total:| failed:| succeeded:| skipped:| duration:)" + +# Results with messages (no stack traces) +dotnet test --no-build 2>&1 | grep -v "^ at " | grep -v "^ at " | grep -v "^ ---" | grep -v "^ from K:" | sed 's/AssertFailedException: //' + +# Verbose output (shows passed tests too) +dotnet test --no-build -v normal +``` + +## Test Categories + +Tests use typed category attributes defined in `TestCategory.cs`. Adding new bug reproductions or platform-specific tests only requires the right attribute — no CI workflow changes. + +| Category | Attribute | Purpose | CI Behavior | +|----------|-----------|---------|-------------| +| `OpenBugs` | `[OpenBugs]` | Known-failing bug reproductions. Remove when fixed. | **EXCLUDED** via filter | +| `Misaligned` | `[Misaligned]` | Documents NumSharp vs NumPy behavioral differences. | Runs (tests pass) | +| `WindowsOnly` | `[WindowsOnly]` | Requires GDI+/System.Drawing.Common | Excluded on non-Windows | +| `HighMemory` | `[HighMemory]` | Requires 8GB+ RAM | **EXCLUDED** via filter | + +### How CI Excludes Categories + +The CI pipeline (`.github/workflows/build-and-release.yml`) uses MSTest's `--filter` to exclude categories: + +```yaml +- name: Test (net10.0) + run: | + dotnet test test/NumSharp.UnitTest/NumSharp.UnitTest.csproj \ + --configuration Release --no-build --framework net10.0 \ + --filter "TestCategory!=OpenBugs&TestCategory!=HighMemory" +``` + +This filter excludes all tests with `[OpenBugs]` or `[HighMemory]` attributes from CI runs. Tests pass locally when the bug is fixed — then remove the `[OpenBugs]` attribute. + +### Usage + +```csharp +// Class-level (all tests in class) +[TestClass] +[OpenBugs] +public class BroadcastBugTests { ... } + +// Method-level +[TestMethod] +[OpenBugs] +public void BroadcastWriteCorruptsData() { ... } + +// Documenting behavioral differences (NOT excluded from CI) +[TestMethod] +[Misaligned] +public void BroadcastSlice_MaterializesInNumSharp() { ... } +``` + +### Local Filtering + +```bash +# Exclude OpenBugs (same as CI) +dotnet test --filter "TestCategory!=OpenBugs" + +# Run ONLY OpenBugs tests (to verify fixes) +dotnet test --filter "TestCategory=OpenBugs" + +# Run ONLY Misaligned tests +dotnet test --filter "TestCategory=Misaligned" + +# Combine multiple exclusions +dotnet test --filter "TestCategory!=OpenBugs&TestCategory!=HighMemory&TestCategory!=WindowsOnly" +``` + +**OpenBugs files**: `OpenBugs.cs` (general), `OpenBugs.Bitmap.cs` (bitmap), `OpenBugs.ApiAudit.cs` (API audit), `OpenBugs.ILKernelBattle.cs` (IL kernel). + +## CI Pipeline + +`.github/workflows/build-and-release.yml` — test on 3 OSes (Windows/Ubuntu/macOS), build NuGet on tag push, create GitHub Release, publish to nuget.org. + +## Scripting with `dotnet run` (.NET 10 file-based apps) + +### Accessing Internal Members + +NumSharp has many key types/fields/methods marked `internal` (Shape.dimensions, Shape.strides, NDArray.Storage, np._FindCommonType, etc.). To access them from a `dotnet run` script, override the assembly name to match an existing `InternalsVisibleTo` entry: + +```csharp +#:project path/to/src/NumSharp.Core +#:property AssemblyName=NumSharp.DotNetRunScript +#:property PublishAot=false +``` + +**How it works:** NumSharp declares `[assembly: InternalsVisibleTo("NumSharp.DotNetRunScript")]` in `src/NumSharp.Core/Assembly/Properties.cs`. The `#:property AssemblyName=NumSharp.DotNetRunScript` directive overrides the script's assembly name (which normally derives from the filename) to match, granting full access to all `internal` and `protected internal` members. + +### Accessing Unsafe code +NumSharp uses unsafe in many places, hence include `#:property AllowUnsafeBlocks=true` in scripts. + +### Script Template (copy-paste ready) + +```csharp +#:project path/to/src/NumSharp.Core +#:property AssemblyName=NumSharp.DotNetRunScript +#:property PublishAot=false +#:property AllowUnsafeBlocks=true +``` + +### Key Internal Members Available + +| Member | What it exposes | +|--------|----------------| +| `shape.dimensions` | Raw int[] of dimension sizes | +| `shape.strides` | Raw int[] of stride values | +| `shape.size` | Internal field: total element count | +| `shape.offset` | Base offset into storage (NumPy-aligned) | +| `shape.bufferSize` | Size of underlying buffer | +| `shape._flags` | Cached ArrayFlags bitmask | +| `shape.IsWriteable` | False for broadcast views (NumPy behavior) | +| `shape.IsBroadcasted` | Has any stride=0 with dimension > 1 | +| `shape.IsSimpleSlice` | IsSliced && !IsBroadcasted | +| `shape.OriginalSize` | Product of non-broadcast dimensions | +| `arr.Storage` | Underlying `UnmanagedStorage` | +| `arr.GetTypeCode` | `NPTypeCode` of the array | +| `arr.Array` | `IArraySlice` — raw data access | +| `np._FindCommonType(...)` | Type promotion logic | +| `np.powerOrder` | Type promotion ordering | +| `NPTypeCode.GetGroup()` | Type category (int/uint/float/etc.) | +| `NPTypeCode.GetPriority()` | Type priority for promotion | +| `NPTypeCode.AsNumpyDtypeName()` | NumPy dtype name (e.g. "int32") | +| `Shape.NewScalar()` | Create scalar shapes | + +### Common Public NDArray Properties + +| Property | Description | +|----------|-------------| +| `nd.shape` | Dimensions as `int[]` | +| `nd.ndim` | Number of dimensions | +| `nd.size` | Total element count | +| `nd.dtype` | Element type as `Type` | +| `nd.typecode` | Element type as `NPTypeCode` | +| `nd.T` | Transpose (swaps axes) | +| `nd.flat` | 1D iterator over elements | + +## Adding New Features + +1. Read NumPy docs for the function +2. **Run actual Python code** to observe exact behavior and fuzzy all possible inputs to define a behavior matrix. +3. Check existing similar implementations +4. Implement behavior matching exactly that of numpy. +5. Write tests based on observed NumPy output +6. Handle all 12 dtypes + +--- + +## Q&A - Design & Architecture + +**Q: Why unmanaged memory instead of Span/Memory?** +A: Benchmarking showed unmanaged memory was fastest. NDArray is self-managed memory allocation optimized for performance. + +**Q: Why Regen templating instead of T4 or source generators?** +A: Original needs felt too complicated for alternatives. Regen is mostly replaced by ILKernelGenerator which uses runtime IL emission. + +**Q: Why is TensorEngine abstracted?** +A: To support potential future backends (GPU/CUDA, SIMD intrinsics, MKL/BLAS). Not implemented yet, but the architecture allows it. + +**Q: How closely does the API match NumPy?** +A: Goal is as close as possible - all edge cases included (NaN handling, multi-type operations, broadcasting). Target is NumPy 2.x. + +**Q: Does np.random match NumPy's random state/seed behavior?** +A: Yes, 1-to-1 matching. + +**Q: What are the primary use cases?** +A: Anything that can use the capabilities - porting Python ML code, standalone .NET scientific computing, integration with TensorFlow.NET/ML.NET. + +**Q: Are there areas of known fragility?** +A: Slicing/broadcasting system is complex — offset/stride calculations with contiguity detection require careful handling. The `readonly struct Shape` with `ArrayFlags` simplifies this but edge cases remain. + +**Q: How is NumPy compatibility validated?** +A: Written by hand based on NumPy docs and original tests. Testing philosophy: run actual NumPy code, observe output, replicate 1-to-1 in C#. + +**Q: What's the pattern for adding new np.* functions?** +A: Sometimes uses other np functions (no DefaultEngine needed). Sometimes requires DefaultEngine for optimization. Tests should be based on actually running NumPy code and imitating the outcome. + +**Q: Are breaking changes acceptable?** +A: Yes - breaking changes are accepted to align with NumPy 2.x behavior. + +**Q: What needs the most work?** +A: Implementations that differ from NumPy 2.x behavior. See the Missing Functions section. + +--- + +## Q&A - Core Components + +**Q: What are the three pillars of NumSharp?** +A: `NDArray` (user-facing API), `UnmanagedStorage` (raw memory management), and `Shape` (dimensions, strides, coordinate translation). They work together: NDArray wraps Storage which uses Shape for offset calculations. + +**Q: What is Shape responsible for?** +A: Shape is a `readonly struct` containing dimensions, strides, offset, bufferSize, and cached `ArrayFlags`. Key properties: `IsScalar`, `IsContiguous`, `IsSliced`, `IsBroadcasted`, `IsWriteable`, `IsSimpleSlice`. Methods: `GetOffset(coords)`, `GetCoordinates(offset)`. NumPy-aligned: broadcast views are read-only (`IsWriteable = false`). + +**Q: How does slicing work internally?** +A: The `Slice` class parses Python notation (e.g., "1:5:2") into `Start`, `Stop`, `Step`. It converts to `SliceDef` (absolute indices) for computation. `SliceDef.Merge()` handles recursive slicing (slice of a slice). + +**Q: What are the special Slice instances?** +A: `Slice.All` (`:` - all elements), `Slice.Ellipsis` (`...` - fill dimensions), `Slice.NewAxis` (insert dimension), `Slice.Index(n)` (single element, reduces dimensionality). + +**Q: What is NDIterator used for?** +A: Traversing arrays with different memory layouts. Handles contiguous (fast pointer increment) and sliced (uses GetOffset) arrays. Has `MoveNext()`, `HasNext()`, `Reset()`. AutoReset mode for broadcasting smaller arrays. + +**Q: What is MultiIterator?** +A: Handles paired iteration for broadcasting. `MultiIterator.Assign(lhs, rhs)` copies with broadcasting. `GetIterators(lhs, rhs, broadcast)` creates synchronized iterators. + +**Q: How does broadcasting work?** +A: Shapes align from the right. Dimensions must be equal OR one must be 1. Dimension of 1 "stretches" to match. Implemented via `DefaultEngine.Broadcast()` which resolves compatible shapes. + +**Q: What is InfoOf?** +A: Static type information cache to avoid runtime reflection. Provides `InfoOf.Size` (bytes), `InfoOf.NPTypeCode`, `InfoOf.Zero`, `InfoOf.MaxValue/MinValue`. + +**Q: What is NDArray?** +A: Generic typed wrapper providing type-safe access. Returns `T` from indexer instead of NDArray. Has typed `Address` pointer (`T*`) and `Array` property (`ArraySlice`). + +**Q: When does DefaultEngine use parallelization?** +A: Parallelization is minimal. Most operations use SIMD vectorization instead for performance. + +--- + +## Q&A - Operations & Operators + +**Q: How do arithmetic operators work?** +A: All operators (`+`, `-`, `*`, `/`, `%`, unary `-`) are defined in `NDArray.Primitive.cs`. They delegate to `TensorEngine.Add()`, `Subtract()`, etc. Scalar operands are wrapped via `NDArray.Scalar()`. + +**Q: How do comparison operators work?** +A: Element-wise comparisons (`==`, `!=`, `>`, `<`, etc.) return `NDArray`. Defined in `NDArray.Equals.cs`, `NDArray.Greater.cs`, etc. Support broadcasting. + +**Q: What indexing modes are supported?** +A: Integer indices, string slices (`"1:3, :"`), Slice objects, boolean masks, fancy indexing (NDArray indices), and mixed combinations. All in `Selection/NDArray.Indexing*.cs`. + +**Q: How is linear algebra implemented?** +A: Core ops (`dot`, `matmul`) in `LinearAlgebra/`. Advanced decompositions (`inv`, `qr`, `svd`, `lstsq`) are stub methods that return null/default — the LAPACK native bindings they depended on have been removed. + +--- + +## Q&A - Development + +**Q: What's in the test suite?** +A: MSTest v3 framework in `test/NumSharp.UnitTest/`. Many tests adapted from NumPy's own test suite. Decent coverage but gaps in edge cases. Uses source-generated test discovery (no special flags needed). + +**Q: What .NET version is targeted?** +A: Library multi-targets `net8.0` and `net10.0`. Tests also multi-target both frameworks. + +**Q: What are the main dependencies?** +A: No external runtime dependencies. `System.Memory` and `System.Runtime.CompilerServices.Unsafe` (previously NuGet packages) are built into the .NET 8+ runtime. + +**Q: What projects use NumSharp?** +A: TensorFlow.NET, ML.NET integrations, Gym.NET, Pandas.NET, and various scientific computing projects. + +**Q: Can I save/load NumPy files?** +A: Yes. `np.save()` writes `.npy` files, `np.load()` reads both `.npy` and `.npz` archives. Compatible with Python NumPy files. + +**Q: What random distributions are supported?** +A: Uniform, normal (randn), integers, beta, binomial, gamma, poisson, exponential, geometric, lognormal, chi-square, bernoulli. All in `RandomSampling/`. + +--- + +## Detailed Documentation + +@ARCHITECTURE.md for comprehensive technical details and @CONTRIBUTING.md for development workflow. diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 000000000..0967ef424 --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1 @@ +{} diff --git a/.claude/skills/np-function/SKILL.md b/.claude/skills/np-function/SKILL.md new file mode 100644 index 000000000..c6368031a --- /dev/null +++ b/.claude/skills/np-function/SKILL.md @@ -0,0 +1,37 @@ +--- +name: np-function +description: Implement numpy np.* functions in NumSharp with full API parity. Use when adding new numpy functions, implementing np.* methods, or aligning NumSharp behavior with numpy 2.4.2. +--- + +We are looking to support numpy's np.* to the fullest. we are aligning with numpy 2.4.2 as source of truth and are to provide exact same API (np.* overloading) as numpy does. +This session we focusing on: """$ARGUMENTS""" +You job is around interacting with np.* functions (no more than a few. more than one ONLY if they are closely related). + +To interact/develop/create a np.* / function, high-level development cycle is as follows: +1. Read how numpy (K:\source\NumSharp\src\numpy) exposes the np function/s you are about to implement. Remember, numpy is the source of truth and if numpy does A, we do A but in NumSharp's C# way. +Definition of Done: +- At the end of this step you understand to 100% how the np function both works, behaves and accepts. +If numpy function uses other np.* functions then you are to report them to the team leader and wait for further instructions. If the function is relative to you then take ownership over it and add it to your group of functions. +2. Implement np methods in the appropriate np class and if custom calculation/math is required via backend then follow the Tensor and IL Kernel way. You are not allowed to implement a hardcoded loop per dtype. Usually other np.* calls is all a numpy function requires. Always reuse existing architecture rather than create a new one. +Definition of Done: + - What Numpy supports, we support. + - We support all dtypes (no hardcoded loops, use il generation via our backend if necessary). + - We have all the apis the np function has and all the overloads. + - We calculate exactly like numpy because only that way we can capture all the design edge cases and implicit behaviors. +3. Then migrate the tests that numpy has from numpy to C# and then produce your own set of tests covering all aspects of the api that you will battletest. Any bugs should be fixed on the spot. +Definition of Done: + - All numpy tests have been migrated to NumSharp C#. + - We used battletesting to find edge cases and other bugs in our implementation where numpy works. Our source of truth for behavior is numpy! +4. Review the implementation, definitions of done and confirm alignment to numpy is as close as possible. Ensure documentation in code. +5. Commit and report completion. + +## Tools: +### Battletesting +Use battletesting to test and validate assumptions or even hunt edge cases: which is using 'dotnet run << 'EOF'' and 'python << 'EOF'' to run any code for any of these purposes. + +## Instructions to Team Leader +- Create at-least 4 users if the task can be parallelised to that level and if not then use less + - Do not wait for other teammates to complete, always have N teammates developing until all the work is completed by definition of done. + - If user asked for 1 of something there there is only a reason to launch one teammate and not five. +- When the teammate have completed development all the way to last step and all definition of done: finish and shutdown the teammate. +- You are to give the instructions to the teammates word-for-word based on this document with your own adaptation below the original version. \ No newline at end of file diff --git a/.claude/skills/np-tests/SKILL.md b/.claude/skills/np-tests/SKILL.md new file mode 100644 index 000000000..fade72443 --- /dev/null +++ b/.claude/skills/np-tests/SKILL.md @@ -0,0 +1,54 @@ +--- +name: np-tests +description: Write and migrate numpy tests for NumSharp functions. Use when adding tests for np.* methods, migrating numpy test suites, or battletesting NumSharp implementations against numpy 2.4.2. +--- + +We are looking to test numpy's np.* implementations to the fullest. we are aligning with numpy 2.4.2 as source of truth and are to validate exact same behavior as numpy does. +This session we focusing on: """$ARGUMENTS""" +Your job is around writing tests for np.* functions (no more than a few. more than one ONLY if they are closely related). + +To interact/develop/create tests for np.* functions, high-level development cycle is as follows: +1. Find and read numpy's tests for the function/s you are about to test. Tests are in K:\source\NumSharp\src\numpy under numpy/_core/tests/, numpy/lib/tests/, etc. Remember, numpy is the source of truth. +Definition of Done: +- At the end of this step you understand 100% what numpy tests: inputs, outputs, edge cases, error conditions, dtype behaviors. +- You have identified all test files and test methods related to your function. +2. Migrate numpy's tests to C# following MSTest v3 framework patterns in test/NumSharp.UnitTest. Match numpy's test structure and assertions exactly. +Definition of Done: + - Every numpy test case has a corresponding C# test. + - We cover all dtypes NumSharp supports (Boolean, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Char, Single, Double, Decimal). + - Test names reflect what they test (e.g., Test_Sort_Axis0_Int32). + - Assertions match numpy's expected values exactly. +3. Battletest to find gaps. Run python and dotnet side-by-side to discover edge cases numpy handles that we might miss. +Definition of Done: + - All numpy tests pass in NumSharp. + - Additional edge cases discovered via battletesting are covered. + - Any bugs found are reported to implementation teammate or fixed on the spot. +4. Review test coverage: empty arrays, scalar inputs, negative axis, broadcasting, NaN/Inf handling, dtype promotion, error conditions. +5. Commit and report completion. + +## Tools: +### Battletesting +Use battletesting to validate behavior matches numpy: 'dotnet run << 'EOF'' and 'python << 'EOF'' side-by-side comparison. + +### Test Patterns +```csharp +[TestMethod] +public void FunctionName_Scenario_Dtype() +{ + // Arrange + var input = np.array(new[] { 3, 1, 2 }); + + // Act + var result = np.sort(input); + + // Assert - values from running actual numpy + Assert.IsTrue(result.IsContiguous); + Assert.AreEqual(1, result.GetAtIndex(0)); +} +``` + +## Instructions to Team Leader +- Create at-least 4 users if the task can be parallelised to that level and if not then use less + - Do not wait for other teammates to complete, always have N teammates developing until all the work is completed by definition of done. + - If user asked for 1 of something there there is only a reason to launch one teammate and not five. +- When the teammate have completed development all the way to last step and all definition of done: finish and shutdown the teammate. diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..0884d2396 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,180 @@ +# EditorConfig is awesome:http://EditorConfig.org + +# top-most EditorConfig file +root = true + +# Don't use tabs for indentation. +[*] +indent_style = space +# (Please don't specify an indent_size here; that has too many unintended consequences.) + +# Code files +[*.{cs,csx,vb,vbx}] +indent_size = 4 +insert_final_newline = true +charset = utf-8-bom + +# Xml project files +[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}] +indent_size = 2 + +# Xml config files +[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}] +indent_size = 2 + +# JSON files +[*.json] +indent_size = 2 + +[*.{sh}] +end_of_line = lf +indent_size = 2 + +# Dotnet code style settings: +[*.{cs,vb}] +# Sort using and Import directives with System.* appearing first +dotnet_sort_system_directives_first = true +# Avoid "this." and "Me." if not necessary +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_property = false:suggestion +dotnet_style_qualification_for_method = false:suggestion +dotnet_style_qualification_for_event = false:suggestion + +# Use language keywords instead of framework type names for type references +dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion +dotnet_style_predefined_type_for_member_access = true:suggestion + +# Suggest more modern language features when available +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion + +# Non-private static fields are PascalCase +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.symbols = non_private_static_fields +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.style = non_private_static_field_style + +dotnet_naming_symbols.non_private_static_fields.applicable_kinds = field +dotnet_naming_symbols.non_private_static_fields.applicable_accessibilities = public, protected, internal, protected internal, private protected +dotnet_naming_symbols.non_private_static_fields.required_modifiers = static + +dotnet_naming_style.non_private_static_field_style.capitalization = pascal_case + +# Constants are PascalCase +dotnet_naming_rule.constants_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.constants_should_be_pascal_case.symbols = constants +dotnet_naming_rule.constants_should_be_pascal_case.style = constant_style + +dotnet_naming_symbols.constants.applicable_kinds = field, local +dotnet_naming_symbols.constants.required_modifiers = const + +dotnet_naming_style.constant_style.capitalization = pascal_case + +# Static fields are camelCase and start with s_ +dotnet_naming_rule.static_fields_should_be_camel_case.severity = suggestion +dotnet_naming_rule.static_fields_should_be_camel_case.symbols = static_fields +dotnet_naming_rule.static_fields_should_be_camel_case.style = static_field_style + +dotnet_naming_symbols.static_fields.applicable_kinds = field +dotnet_naming_symbols.static_fields.required_modifiers = static + +dotnet_naming_style.static_field_style.capitalization = camel_case +dotnet_naming_style.static_field_style.required_prefix = s_ + +# Instance fields are camelCase and start with _ +dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion +dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields +dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style + +dotnet_naming_symbols.instance_fields.applicable_kinds = field + +dotnet_naming_style.instance_field_style.capitalization = camel_case +dotnet_naming_style.instance_field_style.required_prefix = _ + +# Locals and parameters are camelCase +dotnet_naming_rule.locals_should_be_camel_case.severity = suggestion +dotnet_naming_rule.locals_should_be_camel_case.symbols = locals_and_parameters +dotnet_naming_rule.locals_should_be_camel_case.style = camel_case_style + +dotnet_naming_symbols.locals_and_parameters.applicable_kinds = parameter, local + +dotnet_naming_style.camel_case_style.capitalization = camel_case + +# Local functions are PascalCase +dotnet_naming_rule.local_functions_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.local_functions_should_be_pascal_case.symbols = local_functions +dotnet_naming_rule.local_functions_should_be_pascal_case.style = local_function_style + +dotnet_naming_symbols.local_functions.applicable_kinds = local_function + +dotnet_naming_style.local_function_style.capitalization = pascal_case + +# By default, name items with PascalCase +dotnet_naming_rule.members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.members_should_be_pascal_case.symbols = all_members +dotnet_naming_rule.members_should_be_pascal_case.style = pascal_case_style + +dotnet_naming_symbols.all_members.applicable_kinds = * + +dotnet_naming_style.pascal_case_style.capitalization = pascal_case + +# CSharp code style settings: +[*.cs] +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_switch_labels = true +csharp_indent_labels = flush_left + +# Prefer "var" everywhere +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +csharp_style_var_elsewhere = true:suggestion + +# Prefer method-like constructs to have a block body +csharp_style_expression_bodied_methods = false:none +csharp_style_expression_bodied_constructors = false:none +csharp_style_expression_bodied_operators = false:none + +# Prefer property-like constructs to have an expression-body +csharp_style_expression_bodied_properties = true:none +csharp_style_expression_bodied_indexers = true:none +csharp_style_expression_bodied_accessors = true:none + +# Suggest more modern language features when available +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_throw_expression = true:suggestion +csharp_style_conditional_delegate_call = true:suggestion + +# Newline settings +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true + +# Spacing +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_around_binary_operators = before_and_after +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false + +# Blocks are allowed +csharp_prefer_braces = true:silent +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 000000000..ea952afa6 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,11 @@ +# TUnit to MSTest v3 attribute migration +ac020336 + +# TUnit assertions to AwesomeAssertions migration +b1d1d543 + +# Add [TestClass] attributes for MSTest discovery +e0db3c3e + +# Convert async Task to void for sync test methods +4eea9644 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..0299793d1 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,36 @@ +# Auto detect text files and normalize to LF in repo +* text=auto eol=lf + +# Explicit text files +*.cs text eol=lf +*.csproj text eol=lf +*.sln text eol=lf +*.md text eol=lf +*.json text eol=lf +*.xml text eol=lf +*.yml text eol=lf +*.yaml text eol=lf +*.txt text eol=lf +*.sh text eol=lf +*.ps1 text eol=lf +*.py text eol=lf +*.config text eol=lf +*.props text eol=lf +*.targets text eol=lf +*.editorconfig text eol=lf +*.gitignore text eol=lf +*.gitattributes text eol=lf + +# Binary files +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.ico binary +*.snk binary +*.npy binary +*.npz binary +*.dll binary +*.exe binary +*.pdb binary +*.zip binary diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000..b8162b2f6 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: ['https://bit.ly/2op1mu5'] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml new file mode 100644 index 000000000..3b140f7a1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -0,0 +1,54 @@ +name: Bug Report +description: Report a bug or incorrect behavior +labels: ["bug"] +body: + - type: textarea + id: overview + attributes: + label: Overview + description: 1-2 sentence summary of the bug and its impact. + validations: + required: true + + - type: textarea + id: reproduction + attributes: + label: Reproduction + description: Minimal code to trigger the bug. + render: csharp + validations: + required: true + + - type: textarea + id: expected + attributes: + label: Expected + description: Correct behavior. Include NumPy output as source of truth where applicable. + validations: + required: true + + - type: textarea + id: actual + attributes: + label: Actual + description: What NumSharp does instead (error message, wrong output, crash). + validations: + required: true + + - type: textarea + id: workaround + attributes: + label: Workaround + description: How users can avoid the bug today (if any). + + - type: textarea + id: root-cause + attributes: + label: Root cause + description: File, line, why it happens (if known). + + - type: textarea + id: related + attributes: + label: Related issues + description: Link duplicates or upstream causes. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000..0086358db --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: true diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml new file mode 100644 index 000000000..20361c9b6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature.yml @@ -0,0 +1,60 @@ +name: Feature / Enhancement +description: Propose a new feature or improvement +labels: ["enhancement"] +body: + - type: textarea + id: overview + attributes: + label: Overview + description: 1-2 sentence summary of what and why. + validations: + required: true + + - type: textarea + id: problem + attributes: + label: Problem + description: What's broken or missing, and why it matters. + validations: + required: true + + - type: textarea + id: proposal + attributes: + label: Proposal + description: What to change. Use a task checklist (`- [ ]`) for individual steps. + placeholder: | + - [ ] Step 1 + - [ ] Step 2 + validations: + required: true + + - type: textarea + id: evidence + attributes: + label: Evidence + description: Data, benchmarks, references, or NumPy behavior supporting the proposal. + + - type: textarea + id: scope + attributes: + label: Scope / Non-goals + description: What this issue does NOT cover (prevent scope creep). + + - type: textarea + id: benchmark + attributes: + label: Benchmark / Performance + description: Before/after numbers, methodology, what to measure (if applicable). + + - type: textarea + id: breaking-changes + attributes: + label: Breaking changes + description: Use a table if needed (Change | Impact | Migration). + + - type: textarea + id: related + attributes: + label: Related issues + description: Link dependencies or related issues. diff --git a/.github/workflows/build-and-release.yml b/.github/workflows/build-and-release.yml new file mode 100644 index 000000000..285c9a591 --- /dev/null +++ b/.github/workflows/build-and-release.yml @@ -0,0 +1,288 @@ +name: Build and Release + +on: + push: + branches: [ "master", "main" ] + tags: [ "v*" ] + pull_request: + branches: [ "master", "main" ] + workflow_dispatch: + +permissions: write-all + +env: + # Suppress noisy build warnings that clutter CI annotations. + # Uses %3B (URL-encoded semicolon) because MSBuild CLI treats raw ; and , as property separators. + # XML doc warnings (CS15xx, CS17xx): ~7,200 of ~8,700 total — malformed/missing doc comments + # CS8981: 'np' only contains lowercase chars — intentional for NumPy API compat + # NU5048: PackageIconUrl deprecated — cosmetic NuGet warning + DOTNET_NOWARN: CS1570%3BCS1571%3BCS1572%3BCS1573%3BCS1574%3BCS1587%3BCS1591%3BCS1711%3BCS1734%3BCS8981%3BNU5048 + +jobs: + test: + strategy: + fail-fast: false + matrix: + os: [ windows-latest, ubuntu-latest, macos-latest ] + + runs-on: ${{ matrix.os }} + # Ubuntu has intermittent OOM issues - allow failure while investigating + continue-on-error: ${{ matrix.os == 'ubuntu-latest' }} + + steps: + - uses: actions/checkout@v4 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: | + 8.0.x + 10.0.x + dotnet-quality: 'preview' + + - name: Build + run: dotnet build test/NumSharp.UnitTest/NumSharp.UnitTest.csproj --configuration Release -p:NoWarn=${{ env.DOTNET_NOWARN }} + + # Test filtering: + # - OpenBugs: excluded (known-failing bug reproductions) + # - HighMemory: excluded (requires 8GB+ RAM, too much for CI runners) + # - WindowsOnly: excluded on non-Windows runners + - name: Test (net8.0) + shell: bash + timeout-minutes: 10 + run: | + echo "Starting test run (net8.0)..." + echo "dotnet version: $(dotnet --version)" + echo "Available memory: $(free -h 2>/dev/null || echo 'N/A')" + FILTER="TestCategory!=OpenBugs&TestCategory!=HighMemory" + if [[ "$RUNNER_OS" != "Windows" ]]; then + FILTER="$FILTER&TestCategory!=WindowsOnly" + fi + dotnet test test/NumSharp.UnitTest/NumSharp.UnitTest.csproj \ + --configuration Release --no-build --framework net8.0 \ + --filter "$FILTER" --logger "trx" + + - name: Test (net10.0) + shell: bash + timeout-minutes: 10 + run: | + echo "Starting test run (net10.0)..." + echo "dotnet version: $(dotnet --version)" + echo "Available memory: $(free -h 2>/dev/null || echo 'N/A')" + FILTER="TestCategory!=OpenBugs&TestCategory!=HighMemory" + if [[ "$RUNNER_OS" != "Windows" ]]; then + FILTER="$FILTER&TestCategory!=WindowsOnly" + fi + dotnet test test/NumSharp.UnitTest/NumSharp.UnitTest.csproj \ + --configuration Release --no-build --framework net10.0 \ + --filter "$FILTER" --logger "trx" + + - name: Upload Test Results + uses: actions/upload-artifact@v4 + if: always() + with: + name: test-results-${{ matrix.os }} + path: ${{ github.workspace }}/**/TestResults/**/*.trx + retention-days: 5 + + validate-release: + needs: test + if: startsWith(github.ref, 'refs/tags/v') + runs-on: ubuntu-latest + outputs: + is_valid: ${{ steps.check.outputs.is_valid }} + version: ${{ steps.check.outputs.version }} + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Verify tag is on master branch + id: check + run: | + TAG_COMMIT=$(git rev-parse HEAD) + VERSION="${GITHUB_REF#refs/tags/v}" + echo "version=$VERSION" >> $GITHUB_OUTPUT + + # Check if the tagged commit is reachable from origin/master + if git merge-base --is-ancestor "$TAG_COMMIT" origin/master; then + echo "Tag v$VERSION is on master branch" + echo "is_valid=true" >> $GITHUB_OUTPUT + else + echo "::error::Tag v$VERSION is NOT on master branch. Releases must be tagged from master." + echo "is_valid=false" >> $GITHUB_OUTPUT + exit 1 + fi + + build-nuget: + needs: validate-release + if: needs.validate-release.outputs.is_valid == 'true' + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: | + 8.0.x + 10.0.x + dotnet-quality: 'preview' + + - name: Get version info + id: version + shell: bash + run: | + VERSION="${GITHUB_REF#refs/tags/v}" + ASSEMBLY_VERSION="${VERSION%%-*}" + COMMIT_SHA="${GITHUB_SHA:0:7}" + echo "VERSION=$VERSION" >> $GITHUB_OUTPUT + echo "ASSEMBLY_VERSION=$ASSEMBLY_VERSION" >> $GITHUB_OUTPUT + echo "COMMIT_SHA=$COMMIT_SHA" >> $GITHUB_OUTPUT + echo "Building version $VERSION (assembly: $ASSEMBLY_VERSION) +$COMMIT_SHA" + + - name: Build + run: | + dotnet build src/NumSharp.Core/NumSharp.Core.csproj \ + --configuration Release \ + -p:NoWarn=${{ env.DOTNET_NOWARN }} \ + -p:Version=${{ steps.version.outputs.VERSION }} \ + -p:AssemblyVersion=${{ steps.version.outputs.ASSEMBLY_VERSION }} \ + -p:FileVersion=${{ steps.version.outputs.ASSEMBLY_VERSION }} \ + -p:PackageVersion=${{ steps.version.outputs.VERSION }} \ + -p:SourceRevisionId=${{ steps.version.outputs.COMMIT_SHA }} + + dotnet build src/NumSharp.Bitmap/NumSharp.Bitmap.csproj \ + --configuration Release \ + -p:NoWarn=${{ env.DOTNET_NOWARN }} \ + -p:Version=${{ steps.version.outputs.VERSION }} \ + -p:AssemblyVersion=${{ steps.version.outputs.ASSEMBLY_VERSION }} \ + -p:FileVersion=${{ steps.version.outputs.ASSEMBLY_VERSION }} \ + -p:PackageVersion=${{ steps.version.outputs.VERSION }} \ + -p:SourceRevisionId=${{ steps.version.outputs.COMMIT_SHA }} + + - name: Pack + run: | + mkdir -p artifacts/nuget + + dotnet pack src/NumSharp.Core/NumSharp.Core.csproj \ + --configuration Release \ + --no-build \ + --output artifacts/nuget \ + -p:NoWarn=${{ env.DOTNET_NOWARN }} \ + -p:Version=${{ steps.version.outputs.VERSION }} \ + -p:AssemblyVersion=${{ steps.version.outputs.ASSEMBLY_VERSION }} \ + -p:FileVersion=${{ steps.version.outputs.ASSEMBLY_VERSION }} \ + -p:PackageVersion=${{ steps.version.outputs.VERSION }} + + dotnet pack src/NumSharp.Bitmap/NumSharp.Bitmap.csproj \ + --configuration Release \ + --no-build \ + --output artifacts/nuget \ + -p:NoWarn=${{ env.DOTNET_NOWARN }} \ + -p:Version=${{ steps.version.outputs.VERSION }} \ + -p:AssemblyVersion=${{ steps.version.outputs.ASSEMBLY_VERSION }} \ + -p:FileVersion=${{ steps.version.outputs.ASSEMBLY_VERSION }} \ + -p:PackageVersion=${{ steps.version.outputs.VERSION }} + + echo "Packages built:" + ls -la artifacts/nuget/ + + - name: Upload NuGet Packages + uses: actions/upload-artifact@v4 + with: + name: nuget-packages + path: artifacts/nuget/*.nupkg + retention-days: 5 + + create-release: + needs: [validate-release, build-nuget] + if: needs.validate-release.outputs.is_valid == 'true' + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Extract version + id: version + run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT + + - name: Download NuGet Packages + uses: actions/download-artifact@v4 + with: + name: nuget-packages + path: artifacts + + - name: Generate checksums + run: | + cd artifacts + for f in *.nupkg; do + sha256sum "$f" | cut -d' ' -f1 > "${f}.sha256" + echo "${f}: $(cat ${f}.sha256)" + done + + - name: Check if prerelease + id: prerelease + run: | + if [[ "${{ steps.version.outputs.VERSION }}" == *"-"* ]]; then + echo "IS_PRERELEASE=true" >> $GITHUB_OUTPUT + else + echo "IS_PRERELEASE=false" >> $GITHUB_OUTPUT + fi + + - name: Create Release + uses: softprops/action-gh-release@v2 + with: + files: | + artifacts/*.nupkg + artifacts/*.sha256 + draft: false + prerelease: ${{ steps.prerelease.outputs.IS_PRERELEASE }} + generate_release_notes: true + body: | + ## NumSharp v${{ steps.version.outputs.VERSION }} + + ### Install via NuGet + + ``` + dotnet add package NumSharp --version ${{ steps.version.outputs.VERSION }} + dotnet add package NumSharp.Bitmap --version ${{ steps.version.outputs.VERSION }} + ``` + + ### Packages + + | Package | NuGet | + |---------|-------| + | NumSharp | [![NuGet](https://img.shields.io/nuget/v/NumSharp.svg)](https://www.nuget.org/packages/NumSharp/${{ steps.version.outputs.VERSION }}) | + | NumSharp.Bitmap | [![NuGet](https://img.shields.io/nuget/v/NumSharp.Bitmap.svg)](https://www.nuget.org/packages/NumSharp.Bitmap/${{ steps.version.outputs.VERSION }}) | + + publish-nuget: + needs: [validate-release, build-nuget] + if: needs.validate-release.outputs.is_valid == 'true' + runs-on: ubuntu-latest + + steps: + - name: Download NuGet Packages + uses: actions/download-artifact@v4 + with: + name: nuget-packages + path: artifacts + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '8.0.x' + + - name: Push to NuGet + run: | + for package in artifacts/*.nupkg; do + echo "Pushing $package..." + dotnet nuget push "$package" \ + --api-key ${{ secrets.NUGETAPIKEY }} \ + --source https://api.nuget.org/v3/index.json \ + --skip-duplicate + done diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 000000000..00e82720c --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,57 @@ +name: Deploy Docs + +on: + push: + branches: ["master", "main"] + paths: + - 'src/**' + - 'docs/website-src/**' + workflow_dispatch: + +permissions: + contents: read + pages: write + id-token: write + +concurrency: + group: "pages" + cancel-in-progress: false + +jobs: + build-and-deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '8.0.x' + + - name: Install DocFX + run: dotnet tool install -g docfx + + - name: Build docs + run: docfx docs/website-src/docfx.json + + - name: Generate AI-friendly docs (llms.txt) + run: | + cd docs/website-src + chmod +x scripts/generate-llms-txt.sh + ./scripts/generate-llms-txt.sh ../website + + - name: Setup Pages + uses: actions/configure-pages@v5 + + - name: Upload artifact + uses: actions/upload-pages-artifact@v3 + with: + path: 'docs/website' + + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore index c63a0c20b..14bbf94a6 100644 --- a/.gitignore +++ b/.gitignore @@ -352,3 +352,12 @@ src/NumSharp.Python/Ironpython/DLLs/IronPython.SQLite.dll src/NumSharp.Python/NumSharpPy/NumSharp.dll docfx_project/src /coverage.xml +test/NumSharp.Benchmark/LocalBenches.cs +test/NumSharp.UnitTest/DevTests*.cs + +# Local design documents (not tracked in git) +docs/DESIGN.md + +# Claude Code worktrees (local only) +.claude/worktrees/ +!docs/releases/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 000000000..2c93a7fe7 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "src/numpy"] + path = src/numpy + url = https://github.com/numpy/numpy.git diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index 89a4a5014..000000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - // Use IntelliSense to find out which attributes exist for C# debugging - // Use hover for the description of the existing attributes - // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md - "version": "0.2.0", - "configurations": [ - { - "type": "PowerShell", - "request": "launch", - "name": "PowerShell Launch Current File", - "script": "${file}", - "args": [], - "cwd": "${file}" - }, - { - "name": "NumSharp Example - Water equation", - "type": "coreclr", - "request": "launch", - "preLaunchTask": "build", - // If you have changed target frameworks, make sure to update the program path. - "program": "${workspaceFolder}/test/NumSharp.Examples/ShallowWater/bin/Debug/netcoreapp3.0/ShallowWater.dll", - "args": [], - "cwd": "${workspaceFolder}/test/NumSharp.Benchmark", - // For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window - "console": "internalConsole", - "stopAtEntry": false, - "internalConsoleOptions": "openOnSessionStart" - }, - { - "name": ".NET Core Launch (console)", - "type": "coreclr", - "request": "launch", - "preLaunchTask": "build", - // If you have changed target frameworks, make sure to update the program path. - "program": "${workspaceFolder}/test/NumSharp.Benchmark/bin/Debug/netcoreapp2.1/NumSharp.Benchmark.dll", - "args": [], - "cwd": "${workspaceFolder}/test/NumSharp.Benchmark", - // For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window - "console": "internalConsole", - "stopAtEntry": false, - "internalConsoleOptions": "openOnSessionStart" - }, - { - "name": ".NET Core Attach", - "type": "coreclr", - "request": "attach", - "processId": "${command:pickProcess}" - } - ,] -} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json deleted file mode 100644 index e2379cc33..000000000 --- a/.vscode/tasks.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "version": "2.0.0", - "tasks": [ - { - "label": "build", - "command": "dotnet", - "type": "process", - "args": [ - "build", - "${workspaceFolder}/test/NumSharp.Benchmark/NumSharp.Benchmark.csproj" - ], - "problemMatcher": "$msCompile" - } - ] -} \ No newline at end of file diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 000000000..1debe7ab8 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,690 @@ +# NumSharp Architecture Guide + +This document provides an in-depth technical overview of the NumSharp library internals, design decisions, and development practices. + +## Table of Contents + +1. [Project Overview](#project-overview) +2. [Core Architecture](#core-architecture) +3. [Memory Management](#memory-management) +4. [Type System](#type-system) +5. [API Layer](#api-layer) +6. [Slicing and Views](#slicing-and-views) +7. [Broadcasting](#broadcasting) +8. [Iterator System](#iterator-system) +9. [Code Generation](#code-generation) +10. [Development Workflow](#development-workflow) +11. [Technical Debt & Known Issues](#technical-debt--known-issues) +12. [Future Roadmap](#future-roadmap) + +--- + +## Project Overview + +NumSharp is a .NET port of Python's NumPy library, providing n-dimensional array operations for scientific computing in C#. The library aims to match NumPy's API as closely as possible, including edge cases like NaN handling, multi-type operations, and broadcasting semantics. + +### Goals + +- **API Compatibility**: Match NumPy 2.x API (upgraded from original 1.x target) +- **1-to-1 Behavior**: Replicate NumPy behavior exactly, including random state/seed +- **Performance**: Achieve competitive performance through unmanaged memory and unsafe code +- **Ecosystem Integration**: Support TensorFlow.NET, ML.NET, and other .NET ML frameworks + +### Project Structure + +``` +NumSharp/ +├── src/ +│ └── NumSharp.Core/ # Main library +│ ├── APIs/ # np.* static entry points +│ ├── Backends/ # TensorEngine, Storage, Iterators +│ │ ├── Default/ # Pure C# engine implementation +│ │ ├── Unmanaged/ # Memory management +│ │ ├── Iterators/ # NDIterator system +│ │ └── LAPACK/ # Linear algebra bindings +│ ├── Creation/ # np.zeros, np.arange, np.ones, etc. +│ ├── Math/ # np.sum, np.sin, np.log, etc. +│ ├── LinearAlgebra/ # np.dot, np.matmul, np.linalg.* +│ ├── Manipulation/ # reshape, transpose, flatten +│ ├── RandomSampling/ # np.random.* +│ ├── Statistics/ # mean, std, var, argmax +│ ├── Logic/ # np.all, np.any, np.allclose +│ ├── Selection/ # Indexing, slicing, masking +│ ├── Generics/ # NDArray typed wrapper +│ ├── View/ # Shape, Slice, ViewInfo +│ ├── Operations/ # Operator overloads +│ └── Utilities/ # Type helpers, converters +├── test/ +│ └── NumSharp.UnitTest/ # MSTest unit tests +├── examples/ +│ └── NeuralNetwork.NumSharp/ # Neural network example +└── docs/ # Documentation assets +``` + +--- + +## Core Architecture + +### Three Pillars: NDArray, UnmanagedStorage, Shape + +The library is built on three fundamental classes that work together: + +``` +┌─────────────────────────────────────────────────────────┐ +│ NDArray │ +│ - Public API surface │ +│ - Operator overloads (+, -, *, /, indexing) │ +│ - References TensorEngine for computations │ +├─────────────────────────────────────────────────────────┤ +│ UnmanagedStorage │ +│ - Holds raw data in unmanaged memory │ +│ - Manages ArraySlice for each dtype │ +│ - Handles allocation, slicing views, data access │ +├─────────────────────────────────────────────────────────┤ +│ Shape │ +│ - Dimensions and strides │ +│ - Coordinate ↔ offset translation │ +│ - Slicing, broadcasting, contiguity tracking │ +└─────────────────────────────────────────────────────────┘ +``` + +### NDArray + +`NDArray` is the primary user-facing class, analogous to `numpy.ndarray`: + +```csharp +// Key properties +public Shape Shape { get; } // Dimensions +public Type dtype { get; } // Element type +public int ndim { get; } // Number of dimensions +public int size { get; } // Total element count +public int[] strides { get; } // Byte strides per dimension +public UnmanagedStorage Storage { get; } +public TensorEngine TensorEngine { get; } + +// Key operations +public NDArray this[string slice] { get; set; } // "1:3, :, -1" +public NDArray reshape(params int[] shape); +public NDArray T { get; } // Transpose +public NDArray astype(Type dtype); +``` + +### TensorEngine + +`TensorEngine` is an abstract class defining all computational operations. This abstraction exists to potentially support alternative backends (GPU, SIMD, MKL) in the future. + +```csharp +public abstract class TensorEngine +{ + // Allocation + public abstract UnmanagedStorage GetStorage(NPTypeCode typeCode); + + // Arithmetic + public abstract NDArray Add(in NDArray lhs, in NDArray rhs); + public abstract NDArray Subtract(in NDArray lhs, in NDArray rhs); + public abstract NDArray Multiply(NDArray lhs, NDArray rhs); + public abstract NDArray Divide(in NDArray lhs, in NDArray rhs); + + // Reduction + public abstract NDArray ReduceAdd(in NDArray arr, int? axis_, bool keepdims, ...); + public abstract NDArray ReduceArgMax(NDArray arr, int? axis_); + + // Unary functions + public abstract NDArray Sqrt(in NDArray nd, NPTypeCode? typeCode); + public abstract NDArray Log(in NDArray nd, NPTypeCode? typeCode); + public abstract NDArray Exp(in NDArray nd, NPTypeCode? typeCode); + // ... 30+ more operations + + // Linear algebra + public abstract NDArray Dot(in NDArray x, in NDArray y); + public abstract NDArray Matmul(NDArray lhs, NDArray rhs); +} +``` + +The `DefaultEngine` is the current implementation - pure micro-optimized C# that uses `Parallel.For` for arrays exceeding 85,000 elements. + +--- + +## Memory Management + +### Why Unmanaged Memory? + +NumSharp uses unmanaged memory (raw pointers) rather than managed arrays or `Span`/`Memory`. This decision was made ~5 years ago based on extensive benchmarking when Span/Memory were not yet properly supported across the .NET ecosystem. + +**Benefits:** +- Zero-copy slicing (views share underlying memory) +- Direct pointer arithmetic for maximum performance +- No GC pressure for large arrays +- Interop-friendly for native libraries + +**Trade-offs:** +- Requires careful memory management +- Must use `unsafe` code blocks +- Manual disposal considerations + +### UnmanagedStorage + +```csharp +public class UnmanagedStorage +{ + internal IArraySlice InternalArray; // Type-erased ArraySlice + + public Shape Shape { get; } + public Type DType { get; } + public NPTypeCode TypeCode { get; } + public unsafe void* Address { get; } // Raw pointer to data + + // Get typed view + public ArraySlice GetData() where T : unmanaged; + + // Slicing returns views, not copies + public UnmanagedStorage GetView(params Slice[] slices); +} +``` + +### ArraySlice + +The generic `ArraySlice` wraps unmanaged memory with type safety: + +```csharp +public readonly struct ArraySlice : IArraySlice where T : unmanaged +{ + public readonly unsafe T* Address; + public readonly int Count; + + public ref T this[int index] { get; } + public Span AsSpan(); +} +``` + +--- + +## Type System + +### Supported Types (NPTypeCode) + +NumSharp supports 12 primitive types: + +| NPTypeCode | C# Type | Size (bytes) | +|------------|---------|--------------| +| Boolean | bool | 1 | +| Byte | byte | 1 | +| Int16 | short | 2 | +| UInt16 | ushort | 2 | +| Int32 | int | 4 | +| UInt32 | uint | 4 | +| Int64 | long | 8 | +| UInt64 | ulong | 8 | +| Char | char | 2 | +| Single | float | 4 | +| Double | double | 8 | +| Decimal | decimal | 16 | + +### InfoOf - Type Information Cache + +To avoid runtime reflection costs, type information is cached statically: + +```csharp +public class InfoOf +{ + public static readonly int Size; // Byte size + public static readonly NPTypeCode NPTypeCode; + public static readonly T Zero; // default(T) + public static readonly T MaxValue; + public static readonly T MinValue; +} + +// Usage +var size = InfoOf.Size; // 8 +var code = InfoOf.NPTypeCode; // NPTypeCode.Single +``` + +### NDArray - Generic Typed Wrapper + +For type-safe operations, `NDArray` provides a generic wrapper: + +```csharp +public class NDArray : NDArray where T : unmanaged +{ + public new T this[params int[] indices] { get; set; } + public new ArraySlice Array { get; } + public new unsafe T* Address { get; } + public new NDArray this[string slice] { get; } +} + +// Usage +NDArray arr = np.zeros(3, 4); +float val = arr[1, 2]; // Direct typed access +``` + +--- + +## API Layer + +### The `np` Static Class + +The `np` class is the primary entry point, mirroring Python's `import numpy as np`: + +```csharp +public static partial class np +{ + // Type aliases (matching NumPy) + public static readonly Type float64 = typeof(double); + public static readonly Type float32 = typeof(float); + public static readonly Type int32 = typeof(int); + public static readonly Type int64 = typeof(long); + public static readonly Type bool_ = typeof(bool); + + // Constants + public const double pi = Math.PI; + public const double e = Math.E; + public static readonly double nan = double.NaN; + public static readonly double inf = double.PositiveInfinity; + + // Random module + public static NumPyRandom random { get; } + + // Creation: np.zeros, np.ones, np.arange, np.linspace, etc. + // Math: np.sum, np.mean, np.sin, np.cos, np.exp, np.log, etc. + // Linear algebra: np.dot, np.matmul, np.linalg.* + // Manipulation: np.reshape, np.transpose, np.concatenate, etc. +} +``` + +### Function Implementation Patterns + +There are two patterns for implementing `np.*` functions: + +**Pattern 1: Delegating to TensorEngine** +```csharp +// np.sum delegates to engine +public static NDArray sum(NDArray a, int? axis = null, ...) +{ + return a.TensorEngine.Sum(a, axis, typeCode, keepdims); +} +``` + +**Pattern 2: Composing other np functions** +```csharp +// np.std composes np.mean and other operations +public static NDArray std(NDArray a, int? axis = null, ...) +{ + var mean = np.mean(a, axis, keepdims: true); + var diff = a - mean; + var sq = np.power(diff, 2); + return np.sqrt(np.mean(sq, axis, keepdims: keepdims)); +} +``` + +--- + +## Slicing and Views + +### Slice Class + +The `Slice` class parses and represents Python-style slice notation: + +```csharp +public class Slice +{ + public int? Start; // null = from beginning + public int? Stop; // null = to end + public int Step; // default 1 + public bool IsIndex; // Single element, reduces dimension + public bool IsEllipsis; // ... fills remaining dimensions + public bool IsNewAxis; // np.newaxis inserts dimension + + // Special instances + public static readonly Slice All; // ":" + public static readonly Slice None; // "0:0" + public static readonly Slice Ellipsis; // "..." + public static readonly Slice NewAxis; // "np.newaxis" + + // Parsing + public static Slice[] ParseSlices(string notation); // "1:3, :, -1" +} +``` + +### Slice Examples + +```csharp +nd[":"] // All elements +nd["1:5"] // Elements 1-4 +nd["::2"] // Every other element +nd["-1"] // Last element (reduces dimension) +nd["1::-1"] // Reverse from index 1 +nd[":, 0"] // All rows, first column +nd["..., -1"] // Last element of last dimension +``` + +### View Semantics + +**Critical**: Slicing returns views, not copies. The view shares memory with the original: + +```csharp +var original = np.arange(10); +var view = original["2:5"]; // View, shares memory +view[0] = 999; // Modifies original[2]! + +var copy = original["2:5"].copy(); // Explicit copy +``` + +### SliceDef - Internal Representation + +For efficient computation, slices are converted to `SliceDef`: + +```csharp +public struct SliceDef +{ + public int Start; // Absolute start index + public int Step; // Step size (can be negative) + public int Count; // Number of elements (-1 = single index) + + // Merge handles recursive slicing + public SliceDef Merge(SliceDef other); +} +``` + +--- + +## Broadcasting + +Broadcasting allows operations between arrays of different shapes by virtually expanding dimensions: + +```csharp +var a = np.ones(3, 4); // Shape: (3, 4) +var b = np.ones(4); // Shape: (4,) +var c = a + b; // Broadcasting: b treated as (1, 4) → (3, 4) +``` + +### Broadcast Resolution + +```csharp +public static (Shape, Shape) Broadcast(Shape left, Shape right) +{ + // Rules: + // 1. Align shapes from the right + // 2. Dimensions must be equal OR one must be 1 + // 3. Dimension of 1 is "stretched" to match +} +``` + +### MultiIterator + +For element-wise operations with broadcasting: + +```csharp +public static class MultiIterator +{ + // Creates paired iterators with broadcasting + public static (NDIterator, NDIterator) GetIterators( + UnmanagedStorage lhs, + UnmanagedStorage rhs, + bool broadcast); + + // Assignment with broadcasting + public static void Assign(NDArray lhs, NDArray rhs); +} +``` + +--- + +## Iterator System + +### NDIterator + +The iterator system handles traversal of arrays with different memory layouts: + +```csharp +public class NDIterator where T : unmanaged +{ + public Func MoveNext; // Get next value + public MoveNextReferencedDelegate MoveNextReference; // Get reference + public Func HasNext; // Check if more elements + public Action Reset; // Reset to beginning + + public bool AutoReset; // For broadcasting (smaller array loops) + public IteratorType Type; // Scalar, Vector, Matrix, Tensor +} +``` + +### Iterator Types + +```csharp +public enum IteratorType +{ + Scalar, // Single element + Vector, // 1D array + Matrix, // 2D array + Tensor // 3D+ array +} +``` + +### Optimization Paths + +The iterator chooses different code paths based on: + +1. **Contiguous arrays**: Direct pointer increment +2. **Sliced arrays**: Coordinate-to-offset calculation +3. **Auto-reset mode**: For broadcasting smaller arrays + +```csharp +// Contiguous: fast path +MoveNext = () => *((T*)Address + index++); + +// Sliced: uses shape.GetOffset +MoveNext = () => *((T*)Address + shape.GetOffset(index++)); +``` + +--- + +## Code Generation + +### Regen Templating + +NumSharp uses Regen (a custom templating engine) to generate type-specific code. This results in approximately **200,000 lines of generated code**. + +The pattern appears in many files: + +```csharp +#if _REGEN + #region Compute + switch (typeCode) + { + %foreach supported_dtypes,supported_dtypes_lowercase% + case NPTypeCode.#1: return DoOperation<#2>(arr); + % + default: + throw new NotSupportedException(); + } + #endregion +#else + // Generated code follows... + switch (typeCode) + { + case NPTypeCode.Boolean: return DoOperation(arr); + case NPTypeCode.Byte: return DoOperation(arr); + case NPTypeCode.Int16: return DoOperation(arr); + // ... all 12 types + } +#endif +``` + +### Why Code Generation? + +- **Performance**: Avoids boxing and virtual dispatch +- **Type safety**: Compile-time checks for each type +- **NumPy compatibility**: Exact type handling behavior + +### Trade-offs + +- **Heavy codebase**: 200K lines of generated code +- **Maintenance burden**: Changes require regeneration +- **Compile time**: Longer builds + +> **Note**: Migration to T4 templates or C# source generators is possible but not currently prioritized. + +--- + +## Development Workflow + +### Adding a New np.* Function + +1. **Research NumPy behavior**: + - Read NumPy documentation + - Run actual Python/NumPy code + - Document edge cases (NaN, empty arrays, broadcasting) + +2. **Choose implementation pattern**: + - If needs low-level optimization → Add to `DefaultEngine` + - If can compose existing functions → Implement directly in `np.*` + +3. **Implement**: + ```csharp + // In np.newfunction.cs + public static partial class np + { + public static NDArray newfunction(NDArray a, int axis = -1) + { + // Implementation + } + } + ``` + +4. **Write tests**: + - Run NumPy code, capture exact outputs + - Replicate 1-to-1 in C# tests + - Include edge cases + +### Testing Philosophy + +Tests should be based on **actual NumPy execution**: + +```python +# Python +import numpy as np +a = np.array([1, 2, np.nan, 4]) +result = np.nanmean(a) +print(result) # 2.3333... +``` + +```csharp +// C# test +[TestMethod] +public void nanmean_WithNaN_IgnoresNaN() +{ + var a = np.array(new double[] { 1, 2, double.NaN, 4 }); + var result = np.nanmean(a); + Assert.AreEqual(2.333333, result.GetDouble(), 0.0001); +} +``` + +### Test Coverage + +- Tests use MSTest framework +- Many tests were adapted from NumPy's own test suite +- Coverage is decent but has gaps in edge cases + +--- + +## Implemented Capabilities + +NumSharp provides extensive NumPy-compatible functionality across multiple domains: + +### Array Creation +`np.array`, `np.zeros`, `np.ones`, `np.empty`, `np.full`, `np.arange`, `np.linspace`, `np.eye`, `np.meshgrid`, `np.mgrid`, `np.copy`, `np.asarray`, `np.frombuffer`, `np.zeros_like`, `np.ones_like`, `np.empty_like`, `np.full_like` + +### Stacking & Joining +`np.concatenate`, `np.stack`, `np.hstack`, `np.vstack`, `np.dstack` + +### Broadcasting +`np.broadcast`, `np.broadcast_to`, `np.broadcast_arrays`, `np.are_broadcastable` + +### Mathematical Functions +`np.sum`, `np.prod`, `np.cumsum`, `np.power`, `np.sqrt`, `np.abs`, `np.sign`, `np.floor`, `np.ceil`, `np.round`, `np.clip`, `np.modf`, `np.maximum`, `np.minimum`, `np.log`, `np.log2`, `np.log10`, `np.log1p`, `np.exp`, `np.exp2`, `np.expm1`, `np.sin`, `np.cos`, `np.tan` + +### Statistics +`np.mean`, `np.std`, `np.var`, `np.amax`, `np.amin`, `np.argmax`, `np.argmin` + +### Sorting & Searching +`np.argsort`, `np.searchsorted` + +### Linear Algebra +`np.dot`, `np.matmul`, `np.outer`, `np.linalg.norm`, `nd.inv()`, `nd.qr()`, `nd.svd()`, `nd.lstsq()`, `nd.multi_dot()`, `nd.matrix_power()` + +### Shape Manipulation +`np.reshape`, `np.transpose`, `np.ravel`, `np.squeeze`, `np.expand_dims`, `np.swapaxes`, `np.moveaxis`, `np.rollaxis`, `np.atleast_1d/2d/3d`, `np.unique`, `np.repeat`, `np.copyto`, `nd.flatten()`, `nd.roll()`, `nd.delete()` + +### Logic Functions +`np.all`, `np.any`, `np.allclose`, `np.array_equal`, `np.isnan`, `np.isinf`, `np.isfinite`, `np.find_common_type` + +### Operators +- Arithmetic: `+`, `-`, `*`, `/`, `%`, unary `-` +- Comparison: `==`, `!=`, `>`, `>=`, `<`, `<=` +- Logical: `&`, `|`, `!` + +### Indexing & Selection +Integer indexing, string slice notation, Slice objects, boolean masking, fancy indexing (NDArray indices), `np.nonzero` + +### Random Sampling +`np.random.rand`, `np.random.randn`, `np.random.randint`, `np.random.uniform`, `np.random.choice`, `np.random.shuffle`, `np.random.permutation`, `np.random.beta`, `np.random.binomial`, `np.random.gamma`, `np.random.poisson`, `np.random.exponential`, `np.random.geometric`, `np.random.lognormal`, `np.random.chisquare`, `np.random.bernoulli` + +### File I/O +`np.save` (`.npy`), `np.load` (`.npy`, `.npz`), `np.fromfile`, `nd.tofile()` + +--- + +## Future Roadmap + +### Near-term Goals + +1. **NumPy 2.x API Mapping**: Comprehensive audit of: + - Existing functions + - Missing functions + - Behavioral discrepancies + +2. **Behavioral Corrections**: Fix implementations that diverge from NumPy + +3. **Documentation**: API documentation and examples + +### Potential Future Directions + +1. **Alternative Backends**: GPU (CUDA), SIMD intrinsics, MKL/BLAS +2. **Source Generator Migration**: Replace Regen with C# source generators +3. **Span/Memory Integration**: Where beneficial without breaking changes + +### Breaking Changes + +The library accepts breaking changes - it was deprecated for an extended period and is being revitalized. API stability is not a constraint. + +--- + +## Appendix: Key Files Reference + +| Component | Primary Files | +|-----------|--------------| +| NDArray | `Backends/NDArray.cs`, `Backends/NDArray.*.cs` | +| Storage | `Backends/Unmanaged/UnmanagedStorage.cs` | +| Shape | `View/Shape.cs` | +| Slicing | `View/Slice.cs` | +| TensorEngine | `Backends/TensorEngine.cs`, `Backends/Default/DefaultEngine.*.cs` | +| Iterators | `Backends/Iterators/NDIterator.cs`, `MultiIterator.cs` | +| np API | `APIs/np.cs`, individual `np.*.cs` files | +| Operators | `Operations/Elementwise/NDArray.Primitive.cs` | +| Type Info | `Utilities/InfoOf.cs`, `Backends/NPTypeCode.cs` | +| Random | `RandomSampling/np.random.cs`, `NumPyRandom.cs` | +| Generic | `Generics/NDArray\`1.cs` | + +--- + +## Contributing + +When contributing to NumSharp: + +1. **Match NumPy exactly** - Run Python code, observe behavior, replicate +2. **Write tests first** - Based on actual NumPy output +3. **Handle all types** - Use Regen patterns or switch statements for all 12 dtypes +4. **Consider edge cases** - NaN, empty arrays, scalar vs array, broadcasting +5. **Document behavior** - Reference NumPy docs in comments + +See the test suite for examples of expected behavior patterns. diff --git a/Benchmark.ps1 b/Benchmark.ps1 deleted file mode 100644 index 0e1b94f6f..000000000 --- a/Benchmark.ps1 +++ /dev/null @@ -1,22 +0,0 @@ - -function Start-Benchmark { - - param ( - [Parameter(Position=0)] - [ValidateSet('amin','Linq','NDArray')] - [System.String]$Test - ) - - begin { - $currentPath = $pwd; - Set-Location -Path ./test/NumSharp.Benchmark/ - } - - process { - dotnet run -c release $Test - } - - end { - Set-Location $currentPath; - } -} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..d3386d360 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,531 @@ +# Contributing to NumSharp + +This guide covers the practical aspects of contributing to NumSharp. + +## Development Philosophy + +### The Golden Rule: Match NumPy Exactly + +NumSharp aims for **1-to-1 behavioral compatibility** with NumPy 2.x. This means: + +1. **Run actual NumPy code first** +2. **Observe and document the exact output** +3. **Replicate that behavior precisely in C#** + +```python +# Step 1: Run in Python +import numpy as np + +a = np.array([[1, 2], [3, 4]]) +b = np.sum(a, axis=0, keepdims=True) +print(b) # [[4 6]] +print(b.shape) # (1, 2) +print(b.dtype) # int64 +``` + +```csharp +// Step 2: Match in C# +[TestMethod] +public void sum_Axis0_Keepdims() +{ + var a = np.array(new int[,] { { 1, 2 }, { 3, 4 } }); + var b = np.sum(a, axis: 0, keepdims: true); + + Assert.AreEqual("[[4, 6]]", b.ToString()); + CollectionAssert.AreEqual(new[] { 1, 2 }, b.shape); + Assert.AreEqual(typeof(int), b.dtype); +} +``` + +### Edge Cases Matter + +NumPy has specific behavior for edge cases. Always test: + +- Empty arrays: `np.array([])` +- Scalars vs 0-d arrays: `np.array(5)` vs `5` +- NaN/Inf handling: `np.array([1, np.nan, 3])` +- Type promotion: `np.array([1, 2]) + np.array([1.5])` → float64 +- Broadcasting edge cases: shapes like `(3, 1)` + `(1, 4)` +- Negative axis values: `axis=-1` +- Out-of-bounds: What errors does NumPy raise? + +### Breaking Changes Are Acceptable + +We accept breaking changes to align with NumPy 2.x behavior. + +--- + +## Project Structure for Contributors + +### Where to Add New Functions + +| Category | Location | Example | +|----------|----------|---------| +| Creation | `src/NumSharp.Core/Creation/` | np.zeros, np.arange, np.concatenate | +| Math | `src/NumSharp.Core/Math/` | np.sum, np.sin, np.power | +| Statistics | `src/NumSharp.Core/Statistics/` | np.mean, np.std, np.var | +| Logic | `src/NumSharp.Core/Logic/` | np.all, np.any, np.allclose | +| Manipulation | `src/NumSharp.Core/Manipulation/` | np.reshape, np.transpose, np.squeeze | +| LinearAlgebra | `src/NumSharp.Core/LinearAlgebra/` | np.dot, np.matmul, np.linalg.* | +| Selection | `src/NumSharp.Core/Selection/` | Indexing, masking | +| Indexing | `src/NumSharp.Core/Indexing/` | np.nonzero | +| Sorting | `src/NumSharp.Core/Sorting_Searching_Counting/` | np.argsort, np.argmax | +| Random | `src/NumSharp.Core/RandomSampling/` | np.random.* | +| File I/O | `src/NumSharp.Core/APIs/` | np.save, np.load | + +### File Naming Convention + +``` +np.{function_name}.cs +``` + +Examples: +- `np.sum.cs` +- `np.arange.cs` +- `np.concatenate.cs` + +### Test Location + +``` +test/NumSharp.UnitTest/{Category}/{FunctionName}Tests.cs +``` + +--- + +## Implementation Patterns + +### Pattern 1: Simple np.* Function (Composing Others) + +When the function can be built from existing operations: + +```csharp +// File: src/NumSharp.Core/Statistics/np.std.cs +namespace NumSharp +{ + public static partial class np + { + /// + /// Compute the standard deviation along the specified axis. + /// + /// https://numpy.org/doc/stable/reference/generated/numpy.std.html + public static NDArray std(NDArray a, int? axis = null, NPTypeCode? dtype = null, bool keepdims = false) + { + var mean_val = np.mean(a, axis: axis, keepdims: true); + var diff = a - mean_val; + var sq = np.power(diff, 2); + var variance = np.mean(sq, axis: axis, keepdims: keepdims); + return np.sqrt(variance); + } + } +} +``` + +### Pattern 2: Function Requiring TensorEngine + +When you need low-level type-specific optimization: + +**Step 1: Add to TensorEngine abstract class** +```csharp +// Backends/TensorEngine.cs +public abstract NDArray NewOperation(in NDArray nd, int? axis = null); +``` + +**Step 2: Implement in DefaultEngine** +```csharp +// Backends/Default/DefaultEngine.NewOperation.cs +public partial class DefaultEngine +{ + public override NDArray NewOperation(in NDArray nd, int? axis = null) + { + // Type switch using Regen pattern + switch (nd.GetTypeCode) + { + case NPTypeCode.Double: return NewOperation_Double(nd, axis); + case NPTypeCode.Single: return NewOperation_Single(nd, axis); + // ... all types + } + } + + private NDArray NewOperation_Double(in NDArray nd, int? axis) + { + // Actual implementation + } +} +``` + +**Step 3: Add np.* wrapper** +```csharp +// Math/np.newoperation.cs +public static partial class np +{ + public static NDArray newoperation(NDArray a, int? axis = null) + { + return a.TensorEngine.NewOperation(a, axis); + } +} +``` + +### Pattern 3: Type Switch (Regen Style) + +For operations that need type-specific code: + +```csharp +#if _REGEN + switch (arr.typecode) + { + %foreach supported_dtypes,supported_dtypes_lowercase% + case NPTypeCode.#1: return Process<#2>(arr); + % + default: + throw new NotSupportedException(); + } +#else + switch (arr.typecode) + { + case NPTypeCode.Boolean: return Process(arr); + case NPTypeCode.Byte: return Process(arr); + case NPTypeCode.Int16: return Process(arr); + case NPTypeCode.UInt16: return Process(arr); + case NPTypeCode.Int32: return Process(arr); + case NPTypeCode.UInt32: return Process(arr); + case NPTypeCode.Int64: return Process(arr); + case NPTypeCode.UInt64: return Process(arr); + case NPTypeCode.Char: return Process(arr); + case NPTypeCode.Double: return Process(arr); + case NPTypeCode.Single: return Process(arr); + case NPTypeCode.Decimal: return Process(arr); + default: + throw new NotSupportedException(); + } +#endif +``` + +--- + +## Working with Core Types + +### Creating NDArrays in Code + +```csharp +// From shape (zeros) +var a = new NDArray(NPTypeCode.Double, new Shape(3, 4)); + +// From .NET array +var b = new NDArray(new double[] { 1, 2, 3, 4 }); +var c = new NDArray(new double[,] { { 1, 2 }, { 3, 4 } }); + +// Using np.* functions +var d = np.zeros(3, 4); +var e = np.arange(10); +var f = np.array(new[] { 1.0, 2.0, 3.0 }); +``` + +### Accessing Data + +```csharp +// Typed access (preferred for performance) +unsafe +{ + double* ptr = (double*)nd.Address; + for (int i = 0; i < nd.size; i++) + ptr[i] = i * 2.0; +} + +// Via ArraySlice +ArraySlice slice = nd.Storage.GetData(); +Span span = slice.AsSpan(); + +// Via iterator (handles sliced arrays correctly) +using var iter = new NDIterator(nd); +while (iter.HasNext()) +{ + double val = iter.MoveNext(); +} +``` + +### Working with Shape + +```csharp +// Create shape +Shape shape = new Shape(3, 4, 5); +Shape scalar = Shape.Scalar; +Shape vector = new Shape(10); + +// Properties +int ndim = shape.NDim; // 3 +int size = shape.size; // 60 +int[] dims = shape.Dimensions; // [3, 4, 5] +int[] strides = shape.Strides; // [20, 5, 1] + +// Checks +bool isScalar = shape.IsScalar; +bool isContiguous = shape.IsContiguous; +bool isSliced = shape.IsSliced; + +// Coordinate ↔ Offset +int offset = shape.GetOffset(1, 2, 3); // Linear index +int[] coords = shape.GetCoordinates(offset); +``` + +### Working with Slices + +```csharp +// Parse string notation +Slice[] slices = Slice.ParseSlices("1:3, :, -1"); + +// Programmatic slicing +var slice = new Slice(start: 1, stop: 5, step: 2); +var index = Slice.Index(3); // Single element + +// Apply to NDArray +NDArray view = nd[slices]; +NDArray view2 = nd[1, Slice.All, Slice.Index(-1)]; +``` + +--- + +## Testing Guidelines + +### Test File Structure + +```csharp +using Microsoft.VisualStudio.TestTools.UnitTesting; +using NumSharp; + +namespace NumSharp.UnitTest.Math +{ + [TestClass] + public class np_sum_Tests + { + [TestMethod] + public void sum_1DArray_ReturnsScalar() + { + // Arrange + var a = np.array(new[] { 1, 2, 3, 4, 5 }); + + // Act + var result = np.sum(a); + + // Assert + Assert.AreEqual(15, result.GetInt32()); + } + + [TestMethod] + public void sum_2DArray_Axis0_SumsColumns() + { + var a = np.array(new int[,] { { 1, 2 }, { 3, 4 } }); + var result = np.sum(a, axis: 0); + + CollectionAssert.AreEqual(new[] { 4, 6 }, result.ToArray()); + } + + [TestMethod] + public void sum_EmptyArray_ReturnsZero() + { + var a = np.array(new double[0]); + var result = np.sum(a); + + Assert.AreEqual(0.0, result.GetDouble()); + } + + [TestMethod] + public void sum_WithNaN_PropagatesNaN() + { + var a = np.array(new[] { 1.0, double.NaN, 3.0 }); + var result = np.sum(a); + + Assert.IsTrue(double.IsNaN(result.GetDouble())); + } + } +} +``` + +### What to Test + +1. **Basic functionality** - Normal use case +2. **All relevant dtypes** - int, float, double at minimum +3. **Different shapes** - 1D, 2D, 3D+ +4. **Axis parameter** - All valid axes, negative axes +5. **keepdims parameter** - true and false +6. **Edge cases**: + - Empty arrays + - Scalar inputs + - Single-element arrays + - NaN/Inf values + - Type promotion + +### Running Tests + +```bash +cd test/NumSharp.UnitTest +dotnet test +``` + +--- + +## Performance Considerations + +### Contiguous vs Sliced Arrays + +```csharp +// Fast path: contiguous memory +if (nd.Shape.IsContiguous) +{ + unsafe + { + double* ptr = (double*)nd.Address; + // Direct pointer arithmetic + } +} +else +{ + // Slow path: use iterator or shape.GetOffset + using var iter = new NDIterator(nd); + // ... +} +``` + +### Parallel Threshold + +DefaultEngine uses `Parallel.For` for arrays > 85,000 elements: + +```csharp +public const int ParallelAbove = 84999; + +if (size > ParallelAbove) +{ + Parallel.For(0, size, i => { /* ... */ }); +} +else +{ + for (int i = 0; i < size; i++) { /* ... */ } +} +``` + +### Avoid Allocations in Hot Paths + +```csharp +// Bad: allocates array each call +int[] indices = new int[ndim]; + +// Good: stackalloc for small, fixed-size +Span indices = stackalloc int[ndim]; + +// Good: reuse iterator +using var iter = new NDIterator(nd); +var moveNext = iter.MoveNext; // Cache delegate +while (iter.HasNext()) + moveNext(); +``` + +--- + +## Common Pitfalls + +### 1. Forgetting View Semantics (CRITICAL) + +```csharp +// WRONG: modifies original +var view = original["1:3"]; +view[0] = 999; // original[1] is now 999! + +// RIGHT: explicit copy if needed +var copy = original["1:3"].copy(); +copy[0] = 999; // original unchanged +``` + +### 2. Type Assumptions + +```csharp +// WRONG: assumes type +double val = nd.GetDouble(); // Throws if not double + +// RIGHT: check or convert +if (nd.dtype == typeof(double)) + double val = nd.GetDouble(); +// OR +var converted = nd.astype(np.float64); +``` + +### 3. Axis Handling + +```csharp +// WRONG: forgetting negative axis +if (axis >= nd.ndim) throw new ArgumentOutOfRangeException(); + +// RIGHT: normalize negative axis first +if (axis < 0) axis = nd.ndim + axis; +if (axis < 0 || axis >= nd.ndim) throw new ArgumentOutOfRangeException(); +``` + +### 4. Empty Array Edge Cases + +```csharp +// WRONG: crashes on empty +var result = arr[0]; // IndexOutOfRange if arr.size == 0 + +// RIGHT: check first +if (arr.size == 0) + return np.array(Array.Empty()); +``` + +--- + +## Documentation Standards + +### XML Documentation + +```csharp +/// +/// Return the sum of array elements over a given axis. +/// +/// Input array. +/// Axis or axes along which a sum is performed. +/// The default, axis=None, will sum all of the elements of the input array. +/// The type of the returned array and of the accumulator +/// in which the elements are summed. +/// If this is set to True, the axes which are reduced +/// are left in the result as dimensions with size one. +/// An array with the same shape as a, with the specified axis removed. +/// https://numpy.org/doc/stable/reference/generated/numpy.sum.html +public static NDArray sum(NDArray a, int? axis = null, NPTypeCode? dtype = null, bool keepdims = false) +``` + +### Always Include NumPy Reference Link + +```csharp +/// https://numpy.org/doc/stable/reference/generated/numpy.{function}.html +``` + +--- + +## Supported Types Reference + +All operations must handle these 12 types: + +| NPTypeCode | C# Type | NPTypeCode | C# Type | +|------------|---------|------------|---------| +| Boolean | bool | Int64 | long | +| Byte | byte | UInt64 | ulong | +| Int16 | short | Char | char | +| UInt16 | ushort | Single | float | +| Int32 | int | Double | double | +| UInt32 | uint | Decimal | decimal | + +Use `InfoOf` for type information without reflection: +```csharp +var size = InfoOf.Size; // 8 +var code = InfoOf.NPTypeCode; // NPTypeCode.Single +var zero = InfoOf.Zero; // 0 +``` + +--- + +## Questions? + +If you're unsure about implementation details: + +1. Check existing similar functions in the codebase +2. Run the Python equivalent and document behavior +3. Look at NumPy source code for complex edge cases +4. Open an issue for discussion before large changes diff --git a/ExecuteBuild.ps1 b/ExecuteBuild.ps1 deleted file mode 100644 index 63432010f..000000000 --- a/ExecuteBuild.ps1 +++ /dev/null @@ -1,10 +0,0 @@ -Write-Output "--------------------" -Write-Output "Start with building" -Write-Output "--------------------" - -$projectFolders = @{}; - -$projectFolders['projectRoot'] = $PSScriptRoot; -$projectFolders['Projects.Core'] = Join-Path $projectFolders['projectRoot'] src/NumSharp.Core/NumSharp.Core.csproj - -dotnet build $projectFolders['Projects.Core'] \ No newline at end of file diff --git a/ExecuteUnitTests.ps1 b/ExecuteUnitTests.ps1 deleted file mode 100644 index 942d7eafd..000000000 --- a/ExecuteUnitTests.ps1 +++ /dev/null @@ -1,40 +0,0 @@ -Write-Output "Starting unit Tests " -Write-Output "--------------------" -Write-Output "--------------------" -Write-Output "Start with building" -Write-Output "--------------------" - -$projectFolders = @{}; - -$projectFolders['projectRoot'] = $PSScriptRoot; -$projectFolders['UnitTest'] = Join-Path $projectFolders['projectRoot'] test/NumSharp.UnitTest; -$projectFolders['UnitTest.Bin'] = Join-Path $projectFolders['UnitTest'] bin -$projectFolders['UnitTest.CSPROJ'] = Join-Path $projectFolders['UnitTest'] NumSharp.UnitTest.csproj - -# clear all items before testing -if (Test-Path -Path ($projectFolders['UnitTest.Bin'] ) ) -{ - Write-Output "bin folder found - remove items"; - $puffer = Get-ChildItem -Path $projectFolders['UnitTest.Bin'] -Recurse; - - for($idx = 0;$idx -lt $puffer.Length;$idx++) - { - Write-Output (" - " + $puffer[$idx] ); - } - - Remove-Item -Path $projectFolders['UnitTest.Bin'] -Recurse -} - -dotnet build ./src/NumSharp.Core/NumSharp.Core.csproj -dotnet build ./test/NumSharp.UnitTest/NumSharp.UnitTest.csproj - -$generatedDlls = Get-ChildItem -Recurse -File -Path $projectFolders['UnitTest.Bin'] - -Write-Output "following items exist:" - -for($idx =0; $idx -lt $generatedDlls.Length;$idx++) -{ - Write-Output (" - " + $generatedDlls[$idx].Name) -} - -dotnet test $projectFolders['UnitTest.CSPROJ'] \ No newline at end of file diff --git a/GenerateCode.ps1 b/GenerateCode.ps1 deleted file mode 100644 index 98e9fb9cd..000000000 --- a/GenerateCode.ps1 +++ /dev/null @@ -1,84 +0,0 @@ -# first check if T4 engine is installed -if ( -not ( Get-Command t4 -errorAction SilentlyContinue)) -{ - Write-Host "T4 tool was not found - will be installed." - dotnet tool install -g dotnet-t4 - Write-Host "T4 has been installed." -} -else -{ - Write-Host "T4 tool is already installed." -} - -Write-Host ("location of T4 tool is : " + (Get-Command t4).Path); -Write-Host "----------------------------------------------------" -Write-Host "----------------------------------------------------" -Write-Host ("Test T4 before using it."); - -# set variables -$projectFolders = @{}; -$projectFolders['projectRoot'] = $PSScriptRoot; -$projectFolders['tmp'] = $projectFolders['projectRoot'] + '/tmp_' + [System.Guid]::NewGuid(); -$projectFolders['tt.elementwise'] = $projectFolders['projectRoot'] + "/src/NumSharp.Core/Operations/NdArray.ElementsWise.tt"; - -Write-Host ("new tmp folder at " + $projectFolders["tmp"]) - -$projectFolders['tmp.tt'] = $projectFolders['tmp'] + '/test.tt'; -$projectFolders['tmp.html'] = $projectFolders['tmp'] + '/date.html'; - -New-Item -ItemType Directory -Path $projectFolders['tmp']; - -'' > $projectFolders['tmp.tt']; -'The date and time now is: <#= DateTime.Now #>' >> $projectFolders['tmp.tt']; -'' >> $projectFolders['tmp.tt']; - -Write-Host ""; -Write-Host ("folder " + $projectFolders["tmp"] + " was created."); -Write-Host ""; - -t4 -o $projectFolders['tmp.html'] $projectFolders['tmp.tt'] - -if (Test-Path -Path ($projectFolders['tmp.html'])) -{ - Write-Host "html doc exist - was generated from tt." - Write-Host "Everything should be fine..." -} - -Write-Host "" -Write-Host "Tidy up now." -Write-Host "" - -Remove-Item -Recurse -Path $projectFolders["tmp"] - -Write-Host "Start true Code-Generation."; -Write-Host ""; -Write-Host "Generate element wise operations + , - , * , /"; -Write-Host ""; - -$supportDataType = New-Object 'System.Collections.Generic.List[System.String]'; - -$supportDataType.Add('System.Int32'); -$supportDataType.Add('System.Int64'); -$supportDataType.Add('System.Single'); -$supportDataType.Add('System.Double'); -$supportDataType.Add('System.Numerics.Complex'); -$supportDataType.Add('System.Numerics.Quaternion'); - - -$operationTypeString = [System.String]::Join(';',$supportDataType); - -$command = "t4 -o - -p:operationName='+' -p:operationTypesString='" + $operationTypeString + "' " + $projectFolders['tt.elementwise'] + " > " + $projectFolders['projectRoot'] + "\src\NumSharp.Core\Operations\Elementwise\NdArray.Addition.cs"; -Write-Host ("execute - " + $command); -Invoke-Expression $command; - -$command = "t4 -o - -p:operationName='*' -p:operationTypesString='" + $operationTypeString + "' " + $projectFolders['tt.elementwise'] + " > " + $projectFolders['projectRoot'] + "\src\NumSharp.Core\Operations\Elementwise\NdArray.Multiplication.cs"; -Write-Host ("execute - " + $command); -Invoke-Expression $command; - -$command = "t4 -o - -p:operationName='/' -p:operationTypesString='" + $operationTypeString + "' " + $projectFolders['tt.elementwise'] + " > " + $projectFolders['projectRoot'] + "\src\NumSharp.Core\Operations\Elementwise\NdArray.Division.cs"; -Write-Host ("execute - " + $command); -Invoke-Expression $command; - -$command = "t4 -o - -p:operationName='-' -p:operationTypesString='" + $operationTypeString + "' " + $projectFolders['tt.elementwise'] + " > " + $projectFolders['projectRoot'] + "\src\NumSharp.Core\Operations\Elementwise\NdArray.Substraction.cs"; -Write-Host ("execute - " + $command); -Invoke-Expression $command; diff --git a/GenerateDoc.ps1 b/GenerateDoc.ps1 deleted file mode 100644 index 34df9fe98..000000000 --- a/GenerateDoc.ps1 +++ /dev/null @@ -1,4 +0,0 @@ - -docfx metadata ./docfx_project/docfx.json - -docfx build ./docfx_project/docfx.json -o ./docs \ No newline at end of file diff --git a/NumSharp.sln b/NumSharp.sln deleted file mode 100644 index 0e8a9e9be..000000000 --- a/NumSharp.sln +++ /dev/null @@ -1,49 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.28010.2003 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NumSharp.UnitTest", "test\NumSharp.UnitTest\NumSharp.UnitTest.csproj", "{3EDDE7AA-8037-4663-9DD4-FFB85FF962E5}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NumSharp.Benchmark", "test\NumSharp.Benchmark\NumSharp.Benchmark.csproj", "{2D475706-0F69-4C9B-83B9-03AB1AE38186}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NumSharp.PowerShell", "src\NumSharp.PowerShell\NumSharp.PowerShell.csproj", "{CA5288B3-C1C9-441B-9D34-D2580E2920FB}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NumSharp.Python", "src\NumSharp.Python\NumSharp.Python.csproj", "{381613F6-A794-4255-B50E-D2315F8A8CEC}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NumSharp.Core", "src\NumSharp.Core\NumSharp.Core.csproj", "{190A2514-31CD-4738-AF20-3492DD47DE8C}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {3EDDE7AA-8037-4663-9DD4-FFB85FF962E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3EDDE7AA-8037-4663-9DD4-FFB85FF962E5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3EDDE7AA-8037-4663-9DD4-FFB85FF962E5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3EDDE7AA-8037-4663-9DD4-FFB85FF962E5}.Release|Any CPU.Build.0 = Release|Any CPU - {2D475706-0F69-4C9B-83B9-03AB1AE38186}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2D475706-0F69-4C9B-83B9-03AB1AE38186}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2D475706-0F69-4C9B-83B9-03AB1AE38186}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2D475706-0F69-4C9B-83B9-03AB1AE38186}.Release|Any CPU.Build.0 = Release|Any CPU - {CA5288B3-C1C9-441B-9D34-D2580E2920FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CA5288B3-C1C9-441B-9D34-D2580E2920FB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CA5288B3-C1C9-441B-9D34-D2580E2920FB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CA5288B3-C1C9-441B-9D34-D2580E2920FB}.Release|Any CPU.Build.0 = Release|Any CPU - {381613F6-A794-4255-B50E-D2315F8A8CEC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {381613F6-A794-4255-B50E-D2315F8A8CEC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {381613F6-A794-4255-B50E-D2315F8A8CEC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {381613F6-A794-4255-B50E-D2315F8A8CEC}.Release|Any CPU.Build.0 = Release|Any CPU - {190A2514-31CD-4738-AF20-3492DD47DE8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {190A2514-31CD-4738-AF20-3492DD47DE8C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {190A2514-31CD-4738-AF20-3492DD47DE8C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {190A2514-31CD-4738-AF20-3492DD47DE8C}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {4E76C21C-C7A8-4A7B-B408-D5F551E83BDD} - EndGlobalSection -EndGlobal diff --git a/README.md b/README.md index 55ac07b0e..ab1974b60 100644 --- a/README.md +++ b/README.md @@ -1,106 +1,115 @@ -# NumSharp - -NumPy port in C# .NET Standard +[![NumSharp](docs/website/images/numsharp.logo.png)](docs/website/images/numsharp.logo.png) +[![NuGet](https://img.shields.io/nuget/dt/NumSharp.svg)](https://www.nuget.org/packages/NumSharp) [![Join the chat at https://gitter.im/publiclab/publiclab](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/sci-sharp/community) [![AppVeyor](https://ci.appveyor.com/api/projects/status/bmaauxd9rx5lsq9i?svg=true)](https://ci.appveyor.com/project/Haiping-Chen/numsharp) [![codecov](https://codecov.io/gh/SciSharp/NumSharp/branch/master/graph/badge.svg)](https://codecov.io/gh/SciSharp/NumSharp) -[![NuGet](https://img.shields.io/nuget/dt/NumSharp.svg)](https://www.nuget.org/packages/NumSharp) +[![Badge](https://img.shields.io/badge/link-996.icu-red.svg)](https://996.icu/#/en_US) -Is it difficult to translate python machine learning code into C#? Because too many functions can’t be found in the corresponding code in the .Net SDK. NumSharp is the C# version of NumPy, which is as consistent as possible with the NumPy programming interface, including function names and parameter locations. By introducing the NumSharp tool library, you can easily convert from python code to C# code. Here is a comparison code between NumSharp and NumPy (left is python, right is C#): +**NumSharp** (NS) is a [NumPy](https://github.com/numpy/numpy) port to C# targetting .NET Standard.
+NumSharp is the fundamental package needed for scientific computing with C# and F#.
-![comparision](docfx_project/images/python-csharp-comparision.png) +Is it difficult to translate python machine learning code into .NET? Because too many functions can’t be found in the corresponding code in the .NET SDK. +NumSharp is the C# version of NumPy, which is as consistent as possible with the NumPy programming interface, including function names and parameter locations. By introducing the NumSharp tool library, you can easily convert from python code to C# or F# code. +Here is a comparison code between NumSharp and NumPy (left is python, right is C#): -If you want to read some more informations, we start a doc on https://scisharp.github.io/NumSharp/. +[![comparision](docs/website/images/python-csharp-comparision.png)](https://raw.githubusercontent.com/SciSharp/NumSharp/master/docs/website/images/python-csharp-comparision.png) -NumSharp has implemented the arange, array, max, min, reshape, normalize, unique interfaces. More and more interfaces will be added to the library gradually. If you want to use .NET to get started with machine learning, NumSharp will be your best tool library. +### Bold Features +* Use of Unmanaged Memory and fast unsafe algorithms. +* [Broadcasting](https://numpy.org/doc/stable/user/basics.broadcasting.html) n-d shapes against each other. ([intro](https://machinelearningmastery.com/broadcasting-with-numpy-arrays/)) +* [NDArray Slicing](https://numpy.org/doc/stable/user/basics.indexing.html) and nested/recusive slicing (`nd["-1, ::2"]["1::3, :, 0"]`) +* Axis iteration and support in all of our implemented functions. +* Full and precise (to numpy) automatic type resolving and conversion (upcasting, downcasting and other cases) +* Non-copy - most cases, similarly to numpy, does not perform copying but returns a view instead. +* Almost non-effort copy-pasting numpy code from python to C#. +* Wide support for `System.Drawing.Bitmap`. ([read more](https://github.com/SciSharp/NumSharp/wiki/Bitmap-Extensions)) ### Implemented APIs - The NumPy class is a high-level abstraction of NDArray that allows NumSharp to be used in the same way as Python's NumPy, minimizing API differences caused by programming language features, allowing .NET developers to maximize Utilize a wide range of NumPy code resources to seamlessly translate python code into .NET code. -* NumPy - * absolute - * amax - * amin - * arange - * array - * hstack - * linspace - * max - * power - * random - * normal - * randint - * randn - * stardard_normal - * reshape - * sin - * vstack - * zeros - -### How to use -```cs -using NumSharp.Core; +### Install NumSharp in NuGet +```sh +PM> Install-Package NumSharp ``` + +### How to use ```cs -// create a vector -var nd = np.arange(12) +using NumSharp; + +var nd = np.full(5, 12); //[5, 5, 5 .. 5] +nd = np.zeros(12); //[0, 0, 0 .. 0] +nd = np.arange(12); //[0, 1, 2 .. 11] // create a matrix +nd = np.zeros((3, 4)); //[0, 0, 0 .. 0] nd = np.arange(12).reshape(3, 4); // access data by index var data = nd[1, 1]; // create a tensor -nd = np.arange(12).reshape(2, 3, 2); +nd = np.arange(12); + +// reshaping +data = nd.reshape(2, -1); //returning ndarray shaped (2, 6) + +Shape shape = (2, 3, 2); +data = nd.reshape(shape); //Tuple implicitly casted to Shape + //or: +nd = nd.reshape(2, 3, 2); +// slicing tensor +data = nd[":, 0, :"]; //returning ndarray shaped (2, 1, 2) +data = nd[Slice.All, 0, Slice.All]; //equivalent to the line above. + +// nd is currently shaped (2, 3, 2) // get the 2nd vector in the 1st dimension -data = n[new Shape(1)]; +data = nd[1]; //returning ndarray shaped (3, 2) // get the 3rd vector in the (axis 1, axis 2) dimension -data = n[new Shape(1, 2)]; +data = nd[1, 2]; //returning ndarray shaped (2, ) + +// get flat representation of nd +data = nd.flat; //or nd.flatten() for a copy // interate ndarray -foreach (data in nd) +foreach (object val in nd) { - // data is a ndarray or a value + // val can be either boxed value-type or a NDArray. } -``` -### Install NumSharp in NuGet -``` -PM> Install-Package NumSharp -``` +var iter = nd.AsIterator(); //a different T can be used to automatically perform cast behind the scenes. +while (iter.HasNext()) +{ + //read + int val = iter.MoveNext(); -### How to make docs -- Download docfx and put on PATH → https://github.com/dotnet/docfx/releases -- ```docfx ./docfx_project/docfx.json -o ./docs``` + //write + iter.MoveNextReference() = 123; //set value to the next val + //note that setting is not supported when calling AsIterator() where T is not the dtype of the ndarray. +} +``` ### How to run benchmark ``` C: \> dotnet NumSharp.Benchmark.dll nparange ``` -Reference the [documents](https://scisharp.github.io/NumSharp) generated by DocFX. -Reference the [documents](https://numsharp.readthedocs.io) host on readthedocs.io. +### NumSharp is referenced by +* [dotnet/ML.NET](https://github.com/dotnet/machinelearning) +* [ScipSharp/TensorFlow.NET](https://github.com/SciSharp/TensorFlow.NET) +* [ScipSharp/Gym.NET](https://github.com/SciSharp/Gym.NET) +* [ScipSharp/Pandas.NET](https://github.com/SciSharp/Pandas.NET) +* [Oceania2018/Bigtree.MachineLearning](https://github.com/Oceania2018/Bigtree.MachineLearning) +* [Oceania2018/CherubNLP](https://github.com/Oceania2018/CherubNLP) +* [SciSharp/BotSharp](https://github.com/SciSharp/BotSharp) -NumSharp is referenced by: -* [Pandas.NET](https://github.com/SciSharp/Pandas.NET) -* [SciSharp-Learn](https://github.com/SciSharp/scisharp-learn) -* [TensorFlow.NET](https://github.com/SciSharp/TensorFlow.NET) -* [Bigtree.MachineLearning](https://github.com/Oceania2018/Bigtree.MachineLearning) -* [CherubNLP](https://github.com/Oceania2018/CherubNLP) -* [BotSharp](https://github.com/dotnetcore/BotSharp) +You might also be interested in NumSharp's sister project [Numpy.NET](https://github.com/SciSharp/Numpy.NET) which provides a more whole implementation of numpy by using [pythonnet](https://github.com/pythonnet/pythonnet) and [behind-the-scenes deployment of python](https://github.com/henon/Python.Included) ([read more](https://henon.wordpress.com/2019/06/05/using-python-libraries-in-net-without-a-python-installation/)). NumSharp is a member project of [SciSharp.org](https://github.com/SciSharp) which is the .NET based ecosystem of open-source software for mathematics, science, and engineering. -Welcome to fork and pull request to add more APIs, and make reference list longer. - - - -Star me on [Github](https://gitter.im/sci-sharp/community) if you like it. - -Scan QR code to join TIM group: -![SciSharp STACK](https://raw.githubusercontent.com/SciSharp/TensorFlow.NET/master/docs/TIM.jpg) +### Regen Templating +Our library contains over 150,000 lines of repetitive generated code, mostly for handling different data types without hurting performance.
+The templates can be recognized with `#if _REGEN` blocks and are powered by [Regen Templating Engine](https://github.com/Nucs/Regen).
+Regen is a powerful external tool (Visual studio extension, [download here](https://github.com/Nucs/Regen/tree/master/releases)) that generates on demand based on a C#-like `regen-lang`. diff --git a/SciSharp.NumSharp.sln b/SciSharp.NumSharp.sln new file mode 100644 index 000000000..fb5e466a6 --- /dev/null +++ b/SciSharp.NumSharp.sln @@ -0,0 +1,64 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29519.181 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NumSharp.UnitTest", "test\NumSharp.UnitTest\NumSharp.UnitTest.csproj", "{3EDDE7AA-8037-4663-9DD4-FFB85FF962E5}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NumSharp.Benchmark", "test\NumSharp.Benchmark\NumSharp.Benchmark.csproj", "{2D475706-0F69-4C9B-83B9-03AB1AE38186}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NumSharp.Core", "src\NumSharp.Core\NumSharp.Core.csproj", "{190A2514-31CD-4738-AF20-3492DD47DE8C}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Examples", "Examples", "{FB0CB349-D4C7-4C09-BCC5-679F2ABEC6B4}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NeuralNetwork.NumSharp", "Examples\NeuralNetwork.NumSharp\NeuralNetwork.NumSharp.csproj", "{B9253A77-0652-4091-A7F5-14E9FE2630FF}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NumSharp.Bitmap", "src\NumSharp.Bitmap\NumSharp.Bitmap.csproj", "{16C45DA5-D006-4229-B457-4F5E36D5DC55}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Publish|Any CPU = Publish|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3EDDE7AA-8037-4663-9DD4-FFB85FF962E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3EDDE7AA-8037-4663-9DD4-FFB85FF962E5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3EDDE7AA-8037-4663-9DD4-FFB85FF962E5}.Publish|Any CPU.ActiveCfg = Publish|Any CPU + {3EDDE7AA-8037-4663-9DD4-FFB85FF962E5}.Publish|Any CPU.Build.0 = Publish|Any CPU + {3EDDE7AA-8037-4663-9DD4-FFB85FF962E5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3EDDE7AA-8037-4663-9DD4-FFB85FF962E5}.Release|Any CPU.Build.0 = Release|Any CPU + {2D475706-0F69-4C9B-83B9-03AB1AE38186}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2D475706-0F69-4C9B-83B9-03AB1AE38186}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2D475706-0F69-4C9B-83B9-03AB1AE38186}.Publish|Any CPU.ActiveCfg = Publish|Any CPU + {2D475706-0F69-4C9B-83B9-03AB1AE38186}.Publish|Any CPU.Build.0 = Publish|Any CPU + {2D475706-0F69-4C9B-83B9-03AB1AE38186}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2D475706-0F69-4C9B-83B9-03AB1AE38186}.Release|Any CPU.Build.0 = Release|Any CPU + {190A2514-31CD-4738-AF20-3492DD47DE8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {190A2514-31CD-4738-AF20-3492DD47DE8C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {190A2514-31CD-4738-AF20-3492DD47DE8C}.Publish|Any CPU.ActiveCfg = Publish|Any CPU + {190A2514-31CD-4738-AF20-3492DD47DE8C}.Publish|Any CPU.Build.0 = Publish|Any CPU + {190A2514-31CD-4738-AF20-3492DD47DE8C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {190A2514-31CD-4738-AF20-3492DD47DE8C}.Release|Any CPU.Build.0 = Release|Any CPU + {B9253A77-0652-4091-A7F5-14E9FE2630FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B9253A77-0652-4091-A7F5-14E9FE2630FF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B9253A77-0652-4091-A7F5-14E9FE2630FF}.Publish|Any CPU.ActiveCfg = Release|Any CPU + {B9253A77-0652-4091-A7F5-14E9FE2630FF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B9253A77-0652-4091-A7F5-14E9FE2630FF}.Release|Any CPU.Build.0 = Release|Any CPU + {16C45DA5-D006-4229-B457-4F5E36D5DC55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {16C45DA5-D006-4229-B457-4F5E36D5DC55}.Debug|Any CPU.Build.0 = Debug|Any CPU + {16C45DA5-D006-4229-B457-4F5E36D5DC55}.Publish|Any CPU.ActiveCfg = Publish|Any CPU + {16C45DA5-D006-4229-B457-4F5E36D5DC55}.Publish|Any CPU.Build.0 = Publish|Any CPU + {16C45DA5-D006-4229-B457-4F5E36D5DC55}.Release|Any CPU.ActiveCfg = Release|Any CPU + {16C45DA5-D006-4229-B457-4F5E36D5DC55}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {B9253A77-0652-4091-A7F5-14E9FE2630FF} = {FB0CB349-D4C7-4C09-BCC5-679F2ABEC6B4} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {4E76C21C-C7A8-4A7B-B408-D5F551E83BDD} + EndGlobalSection +EndGlobal diff --git a/SciSharp.NumSharp.sln.DotSettings b/SciSharp.NumSharp.sln.DotSettings new file mode 100644 index 000000000..b0e3b2229 --- /dev/null +++ b/SciSharp.NumSharp.sln.DotSettings @@ -0,0 +1,10 @@ + + NO_INDENT + NO_INDENT + LIVE_MONITOR + True + True + True + True + True + True \ No newline at end of file diff --git a/ValidatePackage.ps1 b/ValidatePackage.ps1 deleted file mode 100644 index 5eef6427d..000000000 --- a/ValidatePackage.ps1 +++ /dev/null @@ -1,3 +0,0 @@ -dotnet build ./src/NumSharp.Core/NumSharp.Core.csproj - -dotnet run -p ./test/NumSharp.ConsumePackage/NumSharp.ConsumePackage.csproj \ No newline at end of file diff --git a/benchmark/.gitignore b/benchmark/.gitignore new file mode 100644 index 000000000..215b544ef --- /dev/null +++ b/benchmark/.gitignore @@ -0,0 +1,14 @@ +# Generated benchmark outputs (recreated by run-benchmarks.ps1) +# README.md and benchmark-report.md are tracked (results documentation) +# Only JSON and CSV are ignored as intermediate/machine-readable outputs +/benchmark-report.json +/benchmark-report.csv + +# Benchmark run outputs +*.txt + +# Python cache +__pycache__/ +*.pyc + + diff --git a/benchmark/CLAUDE.md b/benchmark/CLAUDE.md new file mode 100644 index 000000000..647356e88 --- /dev/null +++ b/benchmark/CLAUDE.md @@ -0,0 +1,1003 @@ +# NumSharp Benchmark Suite - Development Guide + +This document provides comprehensive guidance for working with the NumSharp benchmark infrastructure. It covers architecture, patterns, API usage, extending benchmarks, and troubleshooting. + +--- + +## Table of Contents + +1. [Overview](#overview) +2. [Directory Structure](#directory-structure) +3. [Architecture](#architecture) +4. [Infrastructure Classes](#infrastructure-classes) +5. [Benchmark Categories](#benchmark-categories) +6. [Python Benchmark System](#python-benchmark-system) +7. [Report Generation](#report-generation) +8. [Running Benchmarks](#running-benchmarks) +9. [Adding New Benchmarks](#adding-new-benchmarks) +10. [Type System](#type-system) +11. [NumSharp API Patterns](#numsharp-api-patterns) +12. [Common Issues & Solutions](#common-issues--solutions) +13. [Performance Interpretation](#performance-interpretation) +14. [CI Integration](#ci-integration) + +--- + +## Overview + +The benchmark suite provides fair, reproducible performance comparisons between NumSharp and NumPy. It was designed with these principles: + +- **Matching methodology**: Same operations, same array sizes, same random seeds +- **Comprehensive type coverage**: All 12 NumSharp-supported data types +- **Categorical organization**: Operations grouped by type (arithmetic, unary, reduction, etc.) +- **Automated reporting**: JSON export and Markdown report generation +- **Cross-platform**: Runs on Windows, Linux, macOS + +### Key Metrics + +| Metric | Current Coverage | +|--------|-----------------| +| Operations | 132+ | +| Data Types | 12 (all NumSharp types) | +| Suites | 12 (dispatch, fusion, arithmetic, unary, reduction, broadcast, creation, manipulation, slicing, multidim) | +| Array Sizes | 5 (Scalar, 100, 1K, 100K, 10M) | + +--- + +## Directory Structure + +``` +benchmark/ +├── CLAUDE.md # This file (development guide) +├── run-benchmarks.ps1 # PowerShell benchmark runner +├── README.md # Benchmark results (== benchmark-report.md) +├── benchmark-report.md # Generated report (after running) +├── benchmark-report.json # JSON results (after running) +│ +├── scripts/ # Helper scripts +│ └── merge-results.py # Merges NumPy and NumSharp results +│ +├── NumSharp.Benchmark.Python/ # Python/NumPy benchmarks +│ └── numpy_benchmark.py # NumPy benchmark implementation +│ +└── NumSharp.Benchmark.GraphEngine/ # C# BenchmarkDotNet project + ├── README.md # C# benchmark documentation + ├── Program.cs # Entry point with interactive menu + ├── NumSharp.Benchmark.GraphEngine.csproj + │ + ├── Infrastructure/ # Base classes and configuration + │ ├── BenchmarkConfig.cs # BenchmarkDotNet configurations + │ ├── BenchmarkBase.cs # Base class for all benchmarks + │ ├── TypeParameterSource.cs # Type parameter sources (NPTypeCode) + │ └── ArraySizeSource.cs # Standard array size constants + │ + └── Benchmarks/ # Benchmark implementations + ├── DispatchBenchmarks.cs # Original: DynamicMethod dispatch + ├── FusionBenchmarks.cs # Original: Kernel fusion patterns + ├── NumSharpBenchmarks.cs # Original: NumSharp baseline + ├── DynamicEmissionBenchmarks.cs # Original: Per-op DynMethod + │ + ├── Arithmetic/ # Binary arithmetic operations + │ ├── AddBenchmarks.cs + │ ├── SubtractBenchmarks.cs + │ ├── MultiplyBenchmarks.cs + │ ├── DivideBenchmarks.cs + │ └── ModuloBenchmarks.cs + │ + ├── Unary/ # Unary operations + │ ├── MathBenchmarks.cs # sqrt, abs, sign, floor, ceil, around, clip + │ ├── ExpLogBenchmarks.cs # exp, exp2, expm1, log, log2, log10, log1p + │ ├── TrigBenchmarks.cs # sin, cos, tan + │ └── PowerBenchmarks.cs # power with scalar exponents + │ + ├── Reduction/ # Reduction operations + │ ├── SumBenchmarks.cs # sum, cumsum + │ ├── MeanBenchmarks.cs # mean + │ ├── VarStdBenchmarks.cs # var, std + │ ├── MinMaxBenchmarks.cs # amin, amax, argmin, argmax + │ └── ProdBenchmarks.cs # prod + │ + ├── Broadcasting/ # Broadcasting operations + │ └── BroadcastBenchmarks.cs # Scalar, row, column, 3D, broadcast_to + │ + ├── MultiDim/ # Multi-dimensional comparisons + │ └── MultiDimBenchmarks.cs # 1D vs 2D vs 3D performance + │ + ├── Slicing/ # View and slice operations + │ └── SliceBenchmarks.cs # Contiguous, strided, reversed, copy + │ + ├── Creation/ # Array creation + │ └── CreationBenchmarks.cs # zeros, ones, empty, full, copy, *_like + │ + └── Manipulation/ # Shape manipulation + ├── ReshapeBenchmarks.cs # reshape, transpose, ravel, flatten + ├── StackBenchmarks.cs # concatenate, stack, hstack, vstack, dstack + └── DimsBenchmarks.cs # squeeze, expand_dims, swapaxes, moveaxis +``` + +--- + +## Architecture + +### Three-Tier Design + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ Report Generation Layer │ +│ run-benchmarks.ps1 → benchmark-report.md │ +└─────────────────────────────────────────────────────────────────┘ + ↑ +┌─────────────────────────────────────────────────────────────────┐ +│ Benchmark Execution Layer │ +│ ┌─────────────────────┐ ┌─────────────────────────────────┐ │ +│ │ C# / BenchmarkDotNet │ │ Python / NumPy │ │ +│ │ NumSharp.Benchmark │ │ numpy_benchmark.py │ │ +│ └─────────────────────┘ └─────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────────┘ + ↑ +┌─────────────────────────────────────────────────────────────────┐ +│ Infrastructure Layer │ +│ BenchmarkBase → TypeParameterSource → ArraySizeSource │ +└─────────────────────────────────────────────────────────────────┘ +``` + +### Data Flow + +``` +1. Setup Phase: + - CreateRandomArray(N, dtype, seed) → NDArray + - Same seed ensures reproducibility across C#/Python + +2. Benchmark Phase: + - BenchmarkDotNet / Python benchmark() wrapper + - Warmup iterations excluded + - Statistical analysis (mean, stddev, min, max) + +3. Export Phase: + - C#: JSON via BenchmarkDotNet exporters + - Python: JSON via --output flag + +4. Report Phase: + - PowerShell merges results + - Generates Markdown report with tables +``` + +--- + +## Infrastructure Classes + +### BenchmarkBase + +Base class providing array creation helpers. + +```csharp +public abstract class BenchmarkBase +{ + // Override in derived class + public virtual int N { get; set; } = ArraySizeSource.Large; + + // Reproducible random seed + protected const int Seed = 42; + + // Create typed random arrays + protected static NDArray CreateRandomArray(int n, NPTypeCode dtype, int seed = Seed); + protected static NDArray CreatePositiveArray(int n, NPTypeCode dtype, int seed = Seed); + protected static NDArray CreateRandomArray2D(int rows, int cols, NPTypeCode dtype, int seed = Seed); + protected static NDArray CreateRandomArray3D(int d1, int d2, int d3, NPTypeCode dtype, int seed = Seed); + + // Create scalar values for each type + protected static object GetScalar(NPTypeCode dtype, double value = 42.0); +} +``` + +### TypedBenchmarkBase + +Extension that adds dtype parameterization. + +```csharp +public abstract class TypedBenchmarkBase : BenchmarkBase +{ + [ParamsSource(nameof(Types))] + public NPTypeCode DType { get; set; } + + // Override to customize available types + public virtual IEnumerable Types => TypeParameterSource.CommonTypes; +} +``` + +### TypeParameterSource + +Static class providing type collections. + +```csharp +public static class TypeParameterSource +{ + // All 12 NumSharp types + public static IEnumerable AllNumericTypes; + + // Fast subset: int32, int64, float32, float64 + public static IEnumerable CommonTypes; + + // All except bool and char + public static IEnumerable ArithmeticTypes; + + // float32, float64, decimal (for sqrt, log, trig) + public static IEnumerable TranscendentalTypes; + + // Minimal: int32, float64 + public static IEnumerable MinimalTypes; + + // Integer types only + public static IEnumerable IntegerTypes; + + // Floating types only + public static IEnumerable FloatingTypes; + + // Helpers + public static string GetDtypeName(NPTypeCode code); // NumPy dtype name + public static string GetShortName(NPTypeCode code); // Display name +} +``` + +### ArraySizeSource + +Standard array sizes for consistency. + +```csharp +public static class ArraySizeSource +{ + public const int Small = 1_000; // L1 cache, per-element overhead + public const int Medium = 100_000; // L2/L3 cache, typical use + public const int Large = 10_000_000; // Memory-bound throughput + + public static IEnumerable StandardSizes; // All three + public static IEnumerable QuickSizes; // Large only + + // 2D/3D size tuples + public static IEnumerable<(int, int)> Matrix2DSizes; + public static IEnumerable<(int, int, int)> Tensor3DSizes; +} +``` + +--- + +## Benchmark Categories + +### Arithmetic (`Benchmarks/Arithmetic/`) + +Binary arithmetic operations between arrays and scalars. + +| File | Operations | Notes | +|------|------------|-------| +| `AddBenchmarks.cs` | `+`, `np.add`, scalar add, row/col broadcast | Tests both operator and function syntax | +| `SubtractBenchmarks.cs` | `-`, scalar subtract | Tests both directions (a-b, scalar-a) | +| `MultiplyBenchmarks.cs` | `*`, square, scalar multiply | Tests self-multiplication | +| `DivideBenchmarks.cs` | `/`, scalar divide | Uses positive arrays to avoid div-by-zero | +| `ModuloBenchmarks.cs` | `%`, scalar modulo | Limited to types supporting modulo | + +**Type coverage**: `ArithmeticTypes` (excludes bool, char) + +### Unary (`Benchmarks/Unary/`) + +Single-input mathematical functions. + +| File | Operations | Notes | +|------|------------|-------| +| `MathBenchmarks.cs` | sqrt, abs, sign, floor, ceil, around, clip | Basic math operations | +| `ExpLogBenchmarks.cs` | exp, exp2, expm1, log, log2, log10, log1p | Exponential/logarithmic | +| `TrigBenchmarks.cs` | sin, cos, tan | Trigonometric (expensive!) | +| `PowerBenchmarks.cs` | power(a, 2), power(a, 3), power(a, 0.5) | Scalar exponents only | + +**Type coverage**: `TranscendentalTypes` (float32, float64, decimal) + +**Note**: NumSharp `np.power` only supports scalar exponents (`ValueType`), not element-wise NDArray exponents. + +### Reduction (`Benchmarks/Reduction/`) + +Operations that reduce array dimensionality. + +| File | Operations | Notes | +|------|------------|-------| +| `SumBenchmarks.cs` | sum, sum(axis=0), sum(axis=1), cumsum | Full and axis reductions | +| `MeanBenchmarks.cs` | mean, mean(axis) | Returns floating-point | +| `VarStdBenchmarks.cs` | var, std (full and axis) | Multiple passes required | +| `MinMaxBenchmarks.cs` | amin, amax, argmin, argmax | Value and index operations | +| `ProdBenchmarks.cs` | prod (full and axis) | Uses small arrays to avoid overflow | + +**Type coverage**: `ArithmeticTypes` for sum/minmax, `TranscendentalTypes` for var/std + +### Broadcasting (`Benchmarks/Broadcasting/`) + +Operations involving shape broadcasting. + +| File | Operations | Notes | +|------|------------|-------| +| `BroadcastBenchmarks.cs` | scalar, row, column, 3D, broadcast_to | All broadcast patterns | + +**Broadcasting patterns**: +- Scalar: `(N,M) + scalar` +- Row: `(N,M) + (M,)` → broadcasts row across all rows +- Column: `(N,M) + (N,1)` → broadcasts column across all columns +- 3D: `(D,D,D) + (D,D)` → broadcasts 2D across first dimension + +### Creation (`Benchmarks/Creation/`) + +Array allocation and initialization. + +| File | Operations | Notes | +|------|------------|-------| +| `CreationBenchmarks.cs` | zeros, ones, empty, full, arange, linspace, copy, *_like | All creation patterns | + +**Key insight**: `zeros` and `empty` are O(1) lazy allocation (~0.01ms), while `ones` and `full` require initialization (~8-16ms for 10M elements). + +### Manipulation (`Benchmarks/Manipulation/`) + +Shape and dimension manipulation. + +| File | Operations | Notes | +|------|------------|-------| +| `ReshapeBenchmarks.cs` | reshape, transpose, ravel, flatten | View vs copy semantics | +| `StackBenchmarks.cs` | concatenate, stack, hstack, vstack, dstack | Combining arrays | +| `DimsBenchmarks.cs` | squeeze, expand_dims, swapaxes, moveaxis, rollaxis | Dimension manipulation | + +**Key insight**: View operations (reshape, transpose, ravel) are O(1), while copy operations (flatten, concatenate) are O(N). + +### Slicing (`Benchmarks/Slicing/`) + +Array slicing and view operations. + +| File | Operations | Notes | +|------|------------|-------| +| `SliceBenchmarks.cs` | contiguous, strided, reversed, row/col slices, copy | View creation and operations | + +**Key insight**: Strided slices are slower than contiguous due to non-sequential memory access. + +### MultiDim (`Benchmarks/MultiDim/`) + +Comparing 1D, 2D, and 3D array performance. + +| File | Operations | Notes | +|------|------------|-------| +| `MultiDimBenchmarks.cs` | add, sum, sqrt on 1D/2D/3D | Same total elements, different shapes | + +--- + +## Python Benchmark System + +### Structure + +```python +# Configuration +ARRAY_SIZES = {'small': 1_000, 'medium': 100_000, 'large': 10_000_000} +DTYPES = {'int32': np.int32, 'float64': np.float64, ...} +COMMON_DTYPES = ['int32', 'int64', 'float32', 'float64'] + +# Benchmark function +def benchmark(func, n, warmup=10, iterations=50) -> BenchmarkResult + +# Suite functions +def run_arithmetic_benchmarks(n, dtype_name, iterations) -> List[BenchmarkResult] +def run_unary_benchmarks(n, dtype_name, iterations) -> List[BenchmarkResult] +def run_reduction_benchmarks(n, dtype_name, iterations) -> List[BenchmarkResult] +def run_broadcast_benchmarks(n, iterations) -> List[BenchmarkResult] +def run_creation_benchmarks(n, dtype_name, iterations) -> List[BenchmarkResult] +def run_manipulation_benchmarks(n, iterations) -> List[BenchmarkResult] +def run_slicing_benchmarks(n, iterations) -> List[BenchmarkResult] +def run_dispatch_benchmarks(n, iterations) -> List[BenchmarkResult] +def run_fusion_benchmarks(n, iterations) -> List[BenchmarkResult] +``` + +### Command-Line Interface + +```bash +cd NumSharp.Benchmark.Python +python numpy_benchmark.py # All benchmarks +python numpy_benchmark.py --suite dispatch # Specific suite +python numpy_benchmark.py --quick # 10 iterations +python numpy_benchmark.py --type int32 # Specific dtype +python numpy_benchmark.py --size large # 10M elements +python numpy_benchmark.py --output results.json # JSON export +``` + +### Result Format + +```python +@dataclass +class BenchmarkResult: + name: str # "np.sum (float64)" + category: str # "Sum" + suite: str # "Reduction" + dtype: str # "float64" + n: int # 10000000 + mean_ms: float # 5.248 + stddev_ms: float # 0.395 + min_ms: float # 4.821 + max_ms: float # 6.134 + iterations: int # 50 + ops_per_sec: float # 190.55 +``` + +--- + +## Report Generation + +### PowerShell Script (`run-benchmarks.ps1`) + +```powershell +# Parameters +-Quick # Fewer iterations +-Suite # Specific suite (all, arithmetic, reduction, etc.) +-OutputPath # Report file path +-SkipCSharp # Skip C# benchmarks +-SkipPython # Skip Python benchmarks +-Type # Specific dtype +-Size # Array size preset +``` + +### Report Sections + +1. **Environment** - .NET SDK, Python, NumPy versions, CPU +2. **Executive Summary** - Operations tested, suites, array size +3. **NumPy Baseline Performance** - Grouped by suite with tables +4. **NumSharp Results** - BenchmarkDotNet tables (when C# runs) +5. **Performance Comparison Guide** - Legend and interpretation +6. **Key Insights** - Improvement areas and advantages +7. **Reproduction** - Command examples +8. **Type Coverage Matrix** - NumPy dtype to C# type mapping + +### Status Icons + +| Ratio | Icon | Meaning | +|-------|------|---------| +| ≤ 1.0 | ✅ | NumSharp faster or equal | +| 1.0 - 2.0 | 🟡 | Close to NumPy | +| 2.0 - 5.0 | 🟠 | Slower | +| > 5.0 | 🔴 | Much slower | + +--- + +## Running Benchmarks + +### Quick Start + +```powershell +# Full suite with report +.\run-benchmarks.ps1 + +# Quick NumPy-only +.\run-benchmarks.ps1 -Quick -SkipCSharp + +# Specific suite +.\run-benchmarks.ps1 -Suite arithmetic -Type float64 +``` + +### C# Interactive Menu + +```bash +cd NumSharp.Benchmark.GraphEngine +dotnet run -c Release -f net10.0 +``` + +Menu options: +1. Dispatch Mechanism Comparison +2. Fusion Pattern Benchmarks +3. NumSharp Current Performance +4. DynamicMethod Emission +5. Arithmetic Operations +6. Unary Operations +7. Reduction Operations +8. Broadcasting Operations +9. Array Creation Operations +10. Shape Manipulation +11. Slicing Operations +12. Multi-dimensional Arrays +A. All Benchmarks +Q. Quick smoke test + +### C# Command-Line + +```bash +# Filter by name pattern +dotnet run -c Release -- --filter "*Add*" + +# Specific job type +dotnet run -c Release -- --job Short --filter "*" + +# JSON export +dotnet run -c Release -- --exporters json + +# Multiple filters +dotnet run -c Release -- --filter "*Arithmetic*,*Reduction*" +``` + +### Python Standalone + +```bash +cd NumSharp.Benchmark.Python + +# All with JSON +python numpy_benchmark.py --output ../benchmark-report.json + +# Quick arithmetic only +python numpy_benchmark.py --quick --suite arithmetic + +# Specific type and size +python numpy_benchmark.py --type float32 --size medium +``` + +--- + +## Adding New Benchmarks + +### C# Benchmark Template + +```csharp +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.YourCategory; + +/// +/// Brief description of what this benchmarks. +/// +[BenchmarkCategory("YourCategory", "SubCategory")] +public class YourBenchmarks : TypedBenchmarkBase +{ + private NDArray _a = null!; + private NDArray _b = null!; + + // Array sizes to test + [Params(ArraySizeSource.Small, ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + // Types to test (override for custom selection) + public override IEnumerable Types => TypeParameterSource.CommonTypes; + + [GlobalSetup] + public void Setup() + { + _a = CreateRandomArray(N, DType); + _b = CreateRandomArray(N, DType, seed: 43); // Different seed + } + + [GlobalCleanup] + public void Cleanup() + { + _a = null!; + _b = null!; + GC.Collect(); + } + + [Benchmark(Description = "Operation description")] + [BenchmarkCategory("SubCategory")] + public NDArray YourOperation() => np.your_operation(_a); + + [Benchmark(Description = "Another operation")] + [BenchmarkCategory("AnotherSubCategory")] + public NDArray AnotherOperation() => _a + _b; +} +``` + +### Python Benchmark Template + +```python +def run_your_benchmarks(n: int, dtype_name: str, iterations: int) -> List[BenchmarkResult]: + """Benchmark your operations.""" + results = [] + dtype = DTYPES[dtype_name] + + # Setup + np.random.seed(42) + a = create_random_array(n, dtype_name, seed=42) + b = create_random_array(n, dtype_name, seed=43) + + # Benchmark 1 + def your_operation(): return np.your_operation(a) + r = benchmark(your_operation, n, iterations=iterations) + r.name = f"np.your_operation ({dtype_name})" + r.category = "YourCategory" + r.suite = "YourSuite" + r.dtype = dtype_name + results.append(r) + + # Benchmark 2 + def another_operation(): return a + b + r = benchmark(another_operation, n, iterations=iterations) + r.name = f"a + b ({dtype_name})" + r.category = "AnotherCategory" + r.suite = "YourSuite" + r.dtype = dtype_name + results.append(r) + + return results +``` + +### Adding to main() + +```python +# In main(): +if args.suite in ["yoursuite", "all"]: + for dtype in dtypes_to_run: + results = run_your_benchmarks(args.n, dtype, args.iterations) + all_results.extend(results) +``` + +### Updating Program.cs Menu + +```csharp +// Add to menu: +Console.WriteLine("13. Your New Benchmarks"); + +// Add to switch: +"13" => ["--filter", "*YourBenchmarks*"], +``` + +### Updating run-benchmarks.ps1 + +```powershell +# Add to $filter switch: +'yoursuite' { "*YourBenchmarks*" } + +# Add to ValidateSet: +[ValidateSet('all', ..., 'yoursuite')] +``` + +--- + +## Type System + +### NumSharp NPTypeCode to NumPy dtype Mapping + +| NPTypeCode | C# Type | NumPy dtype | Size (bytes) | +|------------|---------|-------------|--------------| +| Boolean | bool | bool | 1 | +| Byte | byte | uint8 | 1 | +| Int16 | short | int16 | 2 | +| UInt16 | ushort | uint16 | 2 | +| Int32 | int | int32 | 4 | +| UInt32 | uint | uint32 | 4 | +| Int64 | long | int64 | 8 | +| UInt64 | ulong | uint64 | 8 | +| Char | char | uint16 | 2 | +| Single | float | float32 | 4 | +| Double | double | float64 | 8 | +| Decimal | decimal | float128* | 16 | + +*Note: NumPy's float128 is platform-dependent and not exactly equivalent to C# decimal. + +### Type Selection Guidelines + +| Operation Type | Use Types | +|----------------|-----------| +| Arithmetic (+, -, *, /) | `ArithmeticTypes` | +| Transcendental (sqrt, exp, log, trig) | `TranscendentalTypes` | +| Reduction (sum, mean) | `ArithmeticTypes` | +| Variance/StdDev | `TranscendentalTypes` | +| Comparison | `AllNumericTypes` | +| Quick benchmarks | `CommonTypes` or `MinimalTypes` | + +--- + +## NumSharp API Patterns + +### Array Creation + +```csharp +// NumSharp requires Shape, not int +np.zeros(new Shape(N), typeCode); // NOT np.zeros(N, typeCode) +np.ones(new Shape(N), typeCode); +np.empty(new Shape(N), typeCode); +np.full(new Shape(N), value, typeCode); + +// Scalar creation +NDArray.Scalar(value, typeCode); // NOT np.array(value) +``` + +### Rounding + +```csharp +// NumSharp uses np.around or np.round_, NOT np.round +np.around(_a); +np.round_(_a); +``` + +### Power + +```csharp +// NumSharp np.power only accepts ValueType exponents +np.power(_a, 2); // OK +np.power(_a, 0.5); // OK +np.power(_a, _b); // NOT SUPPORTED - use _a * _b +``` + +### Type Conversion + +```csharp +// astype for conversion +_a.astype(NPTypeCode.Float64); +_a.astype(np.float64); + +// copy vs view +_a.copy(); // Always creates copy +np.copy(_a); // Same as above +``` + +### Slicing Syntax + +```csharp +// String-based slicing +_arr["100:1000"]; // Contiguous slice +_arr["::2"]; // Every 2nd element +_arr["::-1"]; // Reversed +_arr["10:100, :"]; // 2D row slice +_arr[":, 10:100"]; // 2D column slice (strided) +``` + +--- + +## Common Issues & Solutions + +### Build Error: Type object has no attribute 'type' + +**Python error**: `AttributeError: type object 'numpy.int32' has no attribute 'type'` + +**Cause**: Using `dtype.type(5)` instead of `dtype(5)` + +**Fix**: +```python +# Wrong +scalar = dtype.type(5) + +# Correct +scalar = dtype(5) +``` + +### Build Error: Cannot reshape array + +**Python error**: `ValueError: cannot reshape array of size X into shape (Y,Z)` + +**Cause**: Integer division means `rows * cols != n` + +**Fix**: +```python +rows = int(np.sqrt(n)) +cols = n // rows +actual_n = rows * cols # May be slightly less than n +arr_1d = np.random.random(actual_n) # Use actual_n +``` + +### Build Error: CS8377 - Type must be non-nullable value type + +**C# error**: `np.array(params T[])` fails when T is object + +**Cause**: `GetScalar` returns `object`, not `ValueType` + +**Fix**: +```csharp +// Wrong +_scalar = np.array(GetScalar(DType, 5.0)).astype(DType); + +// Correct +_scalar = NDArray.Scalar(GetScalar(DType, 5.0), DType); +``` + +### Build Error: CS0117 - 'np' does not contain definition for 'round' + +**Cause**: NumSharp uses `np.around` or `np.round_`, not `np.round` + +**Fix**: +```csharp +// Wrong +np.round(_a); + +// Correct +np.around(_a); +// or +np.round_(_a); +``` + +### Build Error: File is locked + +**Error**: `The file is locked by: "NumSharp.Benchmark.GraphEngine (PID)"` + +**Cause**: Previous benchmark run is still executing + +**Fix**: Wait for process to complete or kill it manually + +### PowerShell Variable Conflict + +**Error**: `The value Microsoft.PowerShell.Commands.GroupInfo is not a valid value for the Suite variable` + +**Cause**: Local variable `$suite` conflicts with parameter `$Suite` + +**Fix**: Rename local variable to `$suiteGroup` or similar + +--- + +## Performance Interpretation + +### What the Numbers Mean + +| Time Range | Interpretation | +|------------|----------------| +| < 0.1 ms | O(1) operation (view creation, metadata) | +| 0.1 - 1 ms | Small overhead + minimal computation | +| 1 - 10 ms | Cache-efficient operations | +| 10 - 50 ms | Memory-bound operations | +| 50 - 200 ms | Complex operations (trig, var/std) | +| > 200 ms | Multi-pass or unoptimized | + +### Memory Bandwidth Expectations + +For 10M elements: +- float32 (40 MB) read: ~5 ms theoretical minimum +- float64 (80 MB) read: ~10 ms theoretical minimum +- Operations should be within 2-5x of theoretical minimum + +### What Affects Performance + +1. **Memory layout**: Contiguous > strided > random access +2. **Cache utilization**: L1 > L2 > L3 > RAM +3. **SIMD**: Vectorized operations are 4-8x faster +4. **Type size**: Smaller types = more elements per cache line +5. **Complexity**: Arithmetic < transcendental < trig + +### NumPy Advantages (Why It's Fast) + +1. **BLAS/LAPACK**: Highly optimized linear algebra +2. **AVX/SSE**: SIMD vectorization throughout +3. **C implementation**: No GC overhead +4. **Memory pools**: Reduced allocation overhead +5. **Expression templates**: Some kernel fusion + +### NumSharp Advantages + +1. **.NET integration**: Type safety, tooling, ecosystem +2. **Unmanaged memory**: No GC pressure for large arrays +3. **View semantics**: Zero-copy slicing +4. **Future potential**: SIMD via DynamicMethod emission + +--- + +## CI Integration + +### JSON Export + +```bash +# Python (from benchmark/ directory) +python NumSharp.Benchmark.Python/numpy_benchmark.py --output benchmark-report.json + +# C# +cd NumSharp.Benchmark.GraphEngine +dotnet run -c Release -- --exporters json +# Results in BenchmarkDotNet.Artifacts/results/*.json +``` + +### CI Workflow Example + +```yaml +name: Benchmarks + +on: + push: + branches: [master] + schedule: + - cron: '0 0 * * 0' # Weekly + +jobs: + benchmark: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: Install NumPy + run: pip install numpy tabulate + + - name: Run NumPy benchmarks + run: | + cd benchmark + python NumSharp.Benchmark.Python/numpy_benchmark.py --quick --output benchmark-report.json + + - name: Run NumSharp benchmarks + run: | + cd benchmark/NumSharp.Benchmark.GraphEngine + dotnet run -c Release -- --job Short --exporters json + + - name: Upload results + uses: actions/upload-artifact@v4 + with: + name: benchmark-results + path: | + benchmark/benchmark-report.json + benchmark/NumSharp.Benchmark.GraphEngine/BenchmarkDotNet.Artifacts/ +``` + +### Regression Detection + +Compare current results against baseline: + +```python +import json + +def check_regression(current_file, baseline_file, threshold=1.2): + """Alert if any operation is >threshold slower than baseline.""" + current = json.load(open(current_file)) + baseline = json.load(open(baseline_file)) + + baseline_map = {r['name']: r['mean_ms'] for r in baseline} + + regressions = [] + for r in current: + if r['name'] in baseline_map: + ratio = r['mean_ms'] / baseline_map[r['name']] + if ratio > threshold: + regressions.append((r['name'], ratio)) + + return regressions +``` + +--- + +## Quick Reference + +### Common Commands + +```powershell +# Full benchmark with report +.\run-benchmarks.ps1 + +# Quick NumPy only +.\run-benchmarks.ps1 -Quick -SkipCSharp + +# Specific suite +.\run-benchmarks.ps1 -Suite arithmetic + +# C# interactive +cd NumSharp.Benchmark.GraphEngine && dotnet run -c Release + +# C# specific filter +dotnet run -c Release -- --filter "*Sum*" --job Short + +# Python specific +python NumSharp.Benchmark.Python/numpy_benchmark.py --suite reduction --type float64 --quick +``` + +### File Locations + +| Item | Location | +|------|----------| +| C# benchmarks | `NumSharp.Benchmark.GraphEngine/Benchmarks/` | +| Infrastructure | `NumSharp.Benchmark.GraphEngine/Infrastructure/` | +| Python benchmarks | `NumSharp.Benchmark.Python/numpy_benchmark.py` | +| Helper scripts | `scripts/merge-results.py` | +| Report generator | `run-benchmarks.ps1` | +| Generated report | `benchmark-report.md` (also `README.md`) | +| Results JSON | `benchmark-report.json` | +| C# JSON | `NumSharp.Benchmark.GraphEngine/BenchmarkDotNet.Artifacts/results/` | + +### Type Shorthand + +| Short | Full | NumPy | +|-------|------|-------| +| i32 | Int32 | int32 | +| i64 | Int64 | int64 | +| f32 | Single | float32 | +| f64 | Double | float64 | +| u8 | Byte | uint8 | +| bool | Boolean | bool | + +--- + +*Last updated: 2026-02-13* +*Benchmark suite version: 2.0 (comprehensive coverage)* diff --git a/benchmark/NumSharp.Benchmark.Exploration/.gitignore b/benchmark/NumSharp.Benchmark.Exploration/.gitignore new file mode 100644 index 000000000..8eaa49896 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Exploration/.gitignore @@ -0,0 +1,13 @@ +# Build outputs +bin/ +obj/ + +# Generated benchmark results (keep .gitkeep only) +Results/*.csv +Results/*.json +Results/*.md +Results/*.cs +Results/*.txt + +# BenchmarkDotNet artifacts +BenchmarkDotNet.Artifacts/ diff --git a/benchmark/NumSharp.Benchmark.Exploration/BenchmarkDotNet/BroadcastBenchmarks.cs b/benchmark/NumSharp.Benchmark.Exploration/BenchmarkDotNet/BroadcastBenchmarks.cs new file mode 100644 index 000000000..b83f12432 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Exploration/BenchmarkDotNet/BroadcastBenchmarks.cs @@ -0,0 +1,261 @@ +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Diagnosers; +using NumSharp.Benchmark.Exploration.Infrastructure; + +namespace NumSharp.Benchmark.Exploration.BenchmarkDotNet; + +/// +/// BenchmarkDotNet validation benchmarks for broadcasting scenarios. +/// Provides statistically rigorous validation of Stopwatch results. +/// +[MemoryDiagnoser] +[DisassemblyDiagnoser(maxDepth: 3)] +public unsafe class BroadcastBenchmarks +{ + private double* _lhs = null!; + private double* _rhs = null!; + private double* _result = null!; + + [Params(1_000, 100_000, 1_000_000, 10_000_000)] + public int Size { get; set; } + + [GlobalSetup] + public void Setup() + { + _lhs = SimdImplementations.AllocateAligned(Size); + _rhs = SimdImplementations.AllocateAligned(Size); + _result = SimdImplementations.AllocateAligned(Size); + + SimdImplementations.FillRandom(_lhs, Size, 42); + SimdImplementations.FillRandom(_rhs, Size, 43); + } + + [GlobalCleanup] + public void Cleanup() + { + SimdImplementations.FreeAligned(_lhs); + SimdImplementations.FreeAligned(_rhs); + SimdImplementations.FreeAligned(_result); + } + + [Benchmark(Baseline = true, Description = "Scalar loop")] + public void ScalarLoop() + { + SimdImplementations.AddScalarLoop_Float64(_lhs, _rhs, _result, Size); + } + + [Benchmark(Description = "SIMD Vector256")] + public void SimdFull() + { + SimdImplementations.AddFull_Float64(_lhs, _rhs, _result, Size); + } +} + +/// +/// BenchmarkDotNet benchmarks for scalar broadcast (S2). +/// +[MemoryDiagnoser] +public unsafe class ScalarBroadcastBenchmarks +{ + private double* _lhs = null!; + private double* _result = null!; + private double _scalar = 42.5; + + [Params(1_000, 100_000, 1_000_000, 10_000_000)] + public int Size { get; set; } + + [GlobalSetup] + public void Setup() + { + _lhs = SimdImplementations.AllocateAligned(Size); + _result = SimdImplementations.AllocateAligned(Size); + SimdImplementations.FillRandom(_lhs, Size, 42); + } + + [GlobalCleanup] + public void Cleanup() + { + SimdImplementations.FreeAligned(_lhs); + SimdImplementations.FreeAligned(_result); + } + + [Benchmark(Baseline = true, Description = "Scalar loop")] + public void ScalarLoop() + { + for (int i = 0; i < Size; i++) + { + _result[i] = _lhs[i] + _scalar; + } + } + + [Benchmark(Description = "SIMD Vector256")] + public void SimdScalar() + { + SimdImplementations.AddScalar_Float64(_lhs, _scalar, _result, Size); + } +} + +/// +/// BenchmarkDotNet benchmarks for row broadcast (S4). +/// +[MemoryDiagnoser] +public unsafe class RowBroadcastBenchmarks +{ + private double* _matrix = null!; + private double* _row = null!; + private double* _result = null!; + private int _rows; + private int _cols; + + [Params(100, 316, 1000, 3162)] + public int MatrixDim { get; set; } + + [GlobalSetup] + public void Setup() + { + _rows = MatrixDim; + _cols = MatrixDim; + int size = _rows * _cols; + + _matrix = SimdImplementations.AllocateAligned(size); + _row = SimdImplementations.AllocateAligned(_cols); + _result = SimdImplementations.AllocateAligned(size); + + SimdImplementations.FillRandom(_matrix, size, 42); + SimdImplementations.FillRandom(_row, _cols, 43); + } + + [GlobalCleanup] + public void Cleanup() + { + SimdImplementations.FreeAligned(_matrix); + SimdImplementations.FreeAligned(_row); + SimdImplementations.FreeAligned(_result); + } + + [Benchmark(Baseline = true, Description = "Scalar nested loops")] + public void ScalarLoop() + { + SimdImplementations.AddRowBroadcastScalar_Float64(_matrix, _row, _result, _rows, _cols); + } + + [Benchmark(Description = "SIMD-CHUNK (SIMD inner)")] + public void SimdChunk() + { + SimdImplementations.AddRowBroadcast_Float64(_matrix, _row, _result, _rows, _cols); + } +} + +/// +/// BenchmarkDotNet benchmarks for different dtypes. +/// +[MemoryDiagnoser] +public unsafe class DtypeBenchmarks +{ + private const int Size = 1_000_000; + + private byte* _byteLhs = null!; + private byte* _byteRhs = null!; + private byte* _byteResult = null!; + + private short* _shortLhs = null!; + private short* _shortRhs = null!; + private short* _shortResult = null!; + + private int* _intLhs = null!; + private int* _intRhs = null!; + private int* _intResult = null!; + + private long* _longLhs = null!; + private long* _longRhs = null!; + private long* _longResult = null!; + + private float* _floatLhs = null!; + private float* _floatRhs = null!; + private float* _floatResult = null!; + + private double* _doubleLhs = null!; + private double* _doubleRhs = null!; + private double* _doubleResult = null!; + + [GlobalSetup] + public void Setup() + { + _byteLhs = SimdImplementations.AllocateAligned(Size); + _byteRhs = SimdImplementations.AllocateAligned(Size); + _byteResult = SimdImplementations.AllocateAligned(Size); + SimdImplementations.FillRandom(_byteLhs, Size, 42); + SimdImplementations.FillRandom(_byteRhs, Size, 43); + + _shortLhs = SimdImplementations.AllocateAligned(Size); + _shortRhs = SimdImplementations.AllocateAligned(Size); + _shortResult = SimdImplementations.AllocateAligned(Size); + SimdImplementations.FillRandom(_shortLhs, Size, 42); + SimdImplementations.FillRandom(_shortRhs, Size, 43); + + _intLhs = SimdImplementations.AllocateAligned(Size); + _intRhs = SimdImplementations.AllocateAligned(Size); + _intResult = SimdImplementations.AllocateAligned(Size); + SimdImplementations.FillRandom(_intLhs, Size, 42); + SimdImplementations.FillRandom(_intRhs, Size, 43); + + _longLhs = SimdImplementations.AllocateAligned(Size); + _longRhs = SimdImplementations.AllocateAligned(Size); + _longResult = SimdImplementations.AllocateAligned(Size); + SimdImplementations.FillRandom(_longLhs, Size, 42); + SimdImplementations.FillRandom(_longRhs, Size, 43); + + _floatLhs = SimdImplementations.AllocateAligned(Size); + _floatRhs = SimdImplementations.AllocateAligned(Size); + _floatResult = SimdImplementations.AllocateAligned(Size); + SimdImplementations.FillRandom(_floatLhs, Size, 42); + SimdImplementations.FillRandom(_floatRhs, Size, 43); + + _doubleLhs = SimdImplementations.AllocateAligned(Size); + _doubleRhs = SimdImplementations.AllocateAligned(Size); + _doubleResult = SimdImplementations.AllocateAligned(Size); + SimdImplementations.FillRandom(_doubleLhs, Size, 42); + SimdImplementations.FillRandom(_doubleRhs, Size, 43); + } + + [GlobalCleanup] + public void Cleanup() + { + SimdImplementations.FreeAligned(_byteLhs); + SimdImplementations.FreeAligned(_byteRhs); + SimdImplementations.FreeAligned(_byteResult); + SimdImplementations.FreeAligned(_shortLhs); + SimdImplementations.FreeAligned(_shortRhs); + SimdImplementations.FreeAligned(_shortResult); + SimdImplementations.FreeAligned(_intLhs); + SimdImplementations.FreeAligned(_intRhs); + SimdImplementations.FreeAligned(_intResult); + SimdImplementations.FreeAligned(_longLhs); + SimdImplementations.FreeAligned(_longRhs); + SimdImplementations.FreeAligned(_longResult); + SimdImplementations.FreeAligned(_floatLhs); + SimdImplementations.FreeAligned(_floatRhs); + SimdImplementations.FreeAligned(_floatResult); + SimdImplementations.FreeAligned(_doubleLhs); + SimdImplementations.FreeAligned(_doubleRhs); + SimdImplementations.FreeAligned(_doubleResult); + } + + [Benchmark(Description = "byte SIMD")] + public void ByteSimd() => SimdImplementations.AddFull_Byte(_byteLhs, _byteRhs, _byteResult, Size); + + [Benchmark(Description = "int16 SIMD")] + public void Int16Simd() => SimdImplementations.AddFull_Int16(_shortLhs, _shortRhs, _shortResult, Size); + + [Benchmark(Description = "int32 SIMD")] + public void Int32Simd() => SimdImplementations.AddFull_Int32(_intLhs, _intRhs, _intResult, Size); + + [Benchmark(Description = "int64 SIMD")] + public void Int64Simd() => SimdImplementations.AddFull_Int64(_longLhs, _longRhs, _longResult, Size); + + [Benchmark(Description = "float32 SIMD")] + public void Float32Simd() => SimdImplementations.AddFull_Float32(_floatLhs, _floatRhs, _floatResult, Size); + + [Benchmark(Description = "float64 SIMD")] + public void Float64Simd() => SimdImplementations.AddFull_Float64(_doubleLhs, _doubleRhs, _doubleResult, Size); +} diff --git a/benchmark/NumSharp.Benchmark.Exploration/Infrastructure/BenchFramework.cs b/benchmark/NumSharp.Benchmark.Exploration/Infrastructure/BenchFramework.cs new file mode 100644 index 000000000..d6a9c3864 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Exploration/Infrastructure/BenchFramework.cs @@ -0,0 +1,328 @@ +using System.Diagnostics; +using System.Runtime; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace NumSharp.Benchmark.Exploration.Infrastructure; + +/// +/// Lightweight Stopwatch-based benchmark runner for fast iteration during exploration. +/// Provides consistent measurement methodology with warmup, GC control, and statistics. +/// +public static class BenchFramework +{ + /// Default warmup iterations to trigger JIT compilation. + public const int DefaultWarmup = 5; + + /// Default measurement iterations. + public const int DefaultMeasure = 20; + + /// Quick mode: still enough iterations for stable results. + public const int QuickMeasure = 10; + + /// + /// Run a benchmark with specified warmup and measurement iterations. + /// + /// The action to benchmark (should be self-contained). + /// Scenario identifier (e.g., "S1_contiguous"). + /// Strategy identifier (e.g., "SIMD-FULL"). + /// Data type name (e.g., "float64"). + /// Number of elements processed. + /// Size of each element in bytes. + /// Number of warmup iterations (default: 3). + /// Number of measurement iterations (default: 10). + /// Suite name for grouping. + /// Benchmark result with statistics. + public static BenchResult Run( + Action action, + string scenario, + string strategy, + string dtype, + int size, + int elementBytes, + int warmup = DefaultWarmup, + int measure = DefaultMeasure, + string suite = "") + { + // Force full GC before test to minimize interference + ForceGC(); + + // Warmup phase - trigger JIT, fill caches + for (int i = 0; i < warmup; i++) + { + action(); + } + + // Let any background GC settle + Thread.Sleep(1); + + // Measurement phase + var times = new double[measure]; + for (int i = 0; i < measure; i++) + { + var sw = Stopwatch.StartNew(); + action(); + sw.Stop(); + times[i] = sw.Elapsed.TotalMicroseconds; + } + + // Calculate statistics + var mean = times.Average(); + var variance = times.Select(t => (t - mean) * (t - mean)).Average(); + var stddev = Math.Sqrt(variance); + var min = times.Min(); + var max = times.Max(); + var gbps = BenchResult.CalculateGBps(size, elementBytes, mean); + + return new BenchResult + { + Scenario = scenario, + Strategy = strategy, + Dtype = dtype, + Size = size, + MeanUs = mean, + StdDevUs = stddev, + MinUs = min, + MaxUs = max, + GBps = gbps, + Reps = measure, + Timestamp = DateTime.UtcNow.ToString("O"), + Suite = suite + }; + } + + /// + /// Run a benchmark that returns a result (to prevent dead code elimination). + /// + public static BenchResult Run( + Func func, + string scenario, + string strategy, + string dtype, + int size, + int elementBytes, + int warmup = DefaultWarmup, + int measure = DefaultMeasure, + string suite = "") + { + T result = default!; + // Use block lambda to ensure it resolves as Action, not Func + // (assignment expressions return a value, which would cause infinite recursion) + return Run( + () => { result = func(); }, + scenario, strategy, dtype, size, elementBytes, warmup, measure, suite); + } + + /// + /// Run a benchmark with a setup action that runs before each measurement. + /// Useful when the benchmark modifies its inputs (e.g., in-place operations). + /// + public static BenchResult RunWithSetup( + Action setup, + Action benchmark, + string scenario, + string strategy, + string dtype, + int size, + int elementBytes, + int warmup = DefaultWarmup, + int measure = DefaultMeasure, + string suite = "") + { + ForceGC(); + + // Warmup + for (int i = 0; i < warmup; i++) + { + setup(); + benchmark(); + } + + Thread.Sleep(1); + + // Measurement + var times = new double[measure]; + for (int i = 0; i < measure; i++) + { + setup(); + + var sw = Stopwatch.StartNew(); + benchmark(); + sw.Stop(); + + times[i] = sw.Elapsed.TotalMicroseconds; + } + + var mean = times.Average(); + var variance = times.Select(t => (t - mean) * (t - mean)).Average(); + var stddev = Math.Sqrt(variance); + + return new BenchResult + { + Scenario = scenario, + Strategy = strategy, + Dtype = dtype, + Size = size, + MeanUs = mean, + StdDevUs = stddev, + MinUs = times.Min(), + MaxUs = times.Max(), + GBps = BenchResult.CalculateGBps(size, elementBytes, mean), + Reps = measure, + Timestamp = DateTime.UtcNow.ToString("O"), + Suite = suite + }; + } + + /// + /// Run a comparative benchmark with baseline and optimized versions. + /// + public static (BenchResult Baseline, BenchResult Optimized, double Speedup) RunComparison( + Action baseline, + Action optimized, + string scenario, + string dtype, + int size, + int elementBytes, + int warmup = DefaultWarmup, + int measure = DefaultMeasure, + string suite = "") + { + var baseResult = Run(baseline, scenario, "Baseline", dtype, size, elementBytes, warmup, measure, suite); + var optResult = Run(optimized, scenario, "Optimized", dtype, size, elementBytes, warmup, measure, suite); + + var speedup = baseResult.MeanUs / optResult.MeanUs; + + return ( + baseResult, + optResult with { SpeedupVsBaseline = speedup }, + speedup + ); + } + + /// + /// Force a full garbage collection to reduce interference. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ForceGC() + { + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true); + GC.WaitForPendingFinalizers(); + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true); + } + + /// + /// Print a formatted header for console output. + /// + public static void PrintHeader(string title) + { + Console.WriteLine(); + Console.WriteLine(new string('=', 80)); + Console.WriteLine($" {title}"); + Console.WriteLine(new string('=', 80)); + Console.WriteLine(); + Console.WriteLine($"{"Scenario",-12} {"Strategy",-10} {"Dtype",-8} {"Size",12} | {"Mean (us)",12} ± {"StdDev",8} | {"GB/s",8}"); + Console.WriteLine(new string('-', 80)); + } + + /// + /// Print a result line. + /// + public static void PrintResult(BenchResult result) + { + Console.WriteLine(result.ToString()); + } + + /// + /// Print a section divider. + /// + public static void PrintDivider(string? label = null) + { + if (label != null) + { + Console.WriteLine($"\n--- {label} ---"); + } + else + { + Console.WriteLine(new string('-', 80)); + } + } + + /// + /// Print environment information. + /// + public static void PrintEnvironment() + { + Console.WriteLine("Environment:"); + Console.WriteLine($" .NET Version: {RuntimeInformation.FrameworkDescription}"); + Console.WriteLine($" OS: {RuntimeInformation.OSDescription}"); + Console.WriteLine($" Architecture: {RuntimeInformation.ProcessArchitecture}"); + Console.WriteLine($" Processor Count: {Environment.ProcessorCount}"); + Console.WriteLine($" SIMD Enabled: {System.Numerics.Vector.IsHardwareAccelerated}"); + Console.WriteLine($" Vector256 Supported: {System.Runtime.Intrinsics.X86.Avx2.IsSupported}"); + Console.WriteLine(); + } +} + +/// +/// Standard array sizes for benchmarking. +/// +public static class ArraySizes +{ + /// Fits in L1 cache (32 KB). + public const int Tiny = 32; + + /// Fits in L1 cache (~8 KB for float64). + public const int Small = 1_000; + + /// Fits in L2/L3 cache (~800 KB for float64). + public const int Medium = 100_000; + + /// Exceeds L3 cache (~8 MB for float64). + public const int Large = 1_000_000; + + /// Memory-bound (~80 MB for float64). + public const int Huge = 10_000_000; + + /// Large memory-bound (~800 MB for float64). + public const int Massive = 100_000_000; + + /// Standard sizes for systematic testing. + public static readonly int[] Standard = [Small, Medium, Large, Huge]; + + /// Quick sizes for fast iteration. + public static readonly int[] Quick = [Medium, Huge]; + + /// Threshold discovery sizes (powers of 2). + public static readonly int[] Thresholds = [ + 8, 16, 32, 64, 128, 256, 512, + 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072 + ]; + + /// All sizes including edge cases. + public static readonly int[] All = [Tiny, Small, Medium, Large, Huge, Massive]; +} + +/// +/// Standard dtypes for benchmarking. +/// +public static class Dtypes +{ + /// All numeric types to test. + public static readonly string[] All = ["byte", "int16", "int32", "int64", "float32", "float64"]; + + /// Common types for quick tests. + public static readonly string[] Common = ["int32", "float64"]; + + /// All integer types. + public static readonly string[] Integer = ["byte", "int16", "int32", "int64"]; + + /// All floating types. + public static readonly string[] Float = ["float32", "float64"]; + + /// Types most benefiting from SIMD (more elements per vector). + public static readonly string[] SmallElements = ["byte", "int16"]; + + /// Types where SIMD benefit is smaller. + public static readonly string[] LargeElements = ["int64", "float64"]; +} diff --git a/benchmark/NumSharp.Benchmark.Exploration/Infrastructure/BenchResult.cs b/benchmark/NumSharp.Benchmark.Exploration/Infrastructure/BenchResult.cs new file mode 100644 index 000000000..727756e18 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Exploration/Infrastructure/BenchResult.cs @@ -0,0 +1,124 @@ +using System.Text.Json.Serialization; + +namespace NumSharp.Benchmark.Exploration.Infrastructure; + +/// +/// Result of a single benchmark run. +/// +public record BenchResult +{ + /// Broadcasting scenario identifier (S1-S7). + public required string Scenario { get; init; } + + /// SIMD strategy used (FULL, SCALAR, CHUNK, GATHER, LOOP). + public required string Strategy { get; init; } + + /// Data type tested (byte, int16, int32, int64, float32, float64). + public required string Dtype { get; init; } + + /// Number of elements in the array. + public required int Size { get; init; } + + /// Mean execution time in microseconds. + public required double MeanUs { get; init; } + + /// Standard deviation in microseconds. + public required double StdDevUs { get; init; } + + /// Minimum execution time in microseconds. + public required double MinUs { get; init; } + + /// Maximum execution time in microseconds. + public required double MaxUs { get; init; } + + /// Throughput in GB/s (based on read+write bytes). + public required double GBps { get; init; } + + /// Number of measurement repetitions. + public required int Reps { get; init; } + + /// ISO 8601 timestamp when benchmark was run. + public required string Timestamp { get; init; } + + /// Suite name for grouping. + public string Suite { get; init; } = ""; + + /// Additional notes or flags. + public string Notes { get; init; } = ""; + + /// Baseline comparison ratio (this / baseline). + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public double? SpeedupVsBaseline { get; init; } + + /// + /// Calculate throughput given element count and element size. + /// Assumes read LHS + read RHS + write result = 3 * elements * elementSize bytes. + /// + public static double CalculateGBps(int elements, int elementBytes, double microseconds) + { + // Binary op: read 2 inputs + write 1 output = 3 arrays + var totalBytes = (long)elements * elementBytes * 3; + var seconds = microseconds / 1_000_000.0; + return seconds > 0 ? (totalBytes / 1e9) / seconds : 0; + } + + /// + /// Create a formatted one-line summary for console output. + /// + public override string ToString() + { + var speedup = SpeedupVsBaseline.HasValue ? $" ({SpeedupVsBaseline:F2}x)" : ""; + return $"{Scenario,-12} {Strategy,-10} {Dtype,-8} {Size,12:N0} | {MeanUs,12:F2} us ± {StdDevUs,8:F2} | {GBps,8:F2} GB/s{speedup}"; + } +} + +/// +/// Aggregated results for multiple scenarios/dtypes/sizes. +/// +public class BenchResultSet +{ + public required string SuiteName { get; init; } + public required string Description { get; init; } + public required DateTime StartTime { get; init; } + public DateTime EndTime { get; set; } + public required string CpuModel { get; init; } + public required string DotNetVersion { get; init; } + public List Results { get; } = new(); + + public TimeSpan Duration => EndTime - StartTime; + + /// + /// Add a result and return this for fluent chaining. + /// + public BenchResultSet Add(BenchResult result) + { + Results.Add(result); + return this; + } +} + +/// +/// Element size lookup for each dtype. +/// +public static class DtypeInfo +{ + public static int GetElementSize(string dtype) => dtype.ToLowerInvariant() switch + { + "byte" or "uint8" or "bool" or "boolean" => 1, + "int16" or "short" or "uint16" or "ushort" => 2, + "int32" or "int" or "uint32" or "uint" or "float32" or "single" or "float" => 4, + "int64" or "long" or "uint64" or "ulong" or "float64" or "double" => 8, + "decimal" => 16, + _ => throw new ArgumentException($"Unknown dtype: {dtype}") + }; + + /// + /// Get the number of elements that fit in a Vector256. + /// + public static int GetVector256Count(string dtype) => 32 / GetElementSize(dtype); + + /// + /// Get the number of elements that fit in a Vector128. + /// + public static int GetVector128Count(string dtype) => 16 / GetElementSize(dtype); +} diff --git a/benchmark/NumSharp.Benchmark.Exploration/Infrastructure/OutputFormatters.cs b/benchmark/NumSharp.Benchmark.Exploration/Infrastructure/OutputFormatters.cs new file mode 100644 index 000000000..251e24801 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Exploration/Infrastructure/OutputFormatters.cs @@ -0,0 +1,281 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace NumSharp.Benchmark.Exploration.Infrastructure; + +/// +/// Output formatters for benchmark results. +/// Supports CSV, JSON, and Markdown table formats. +/// +public static class OutputFormatters +{ + private static readonly JsonSerializerOptions JsonOptions = new() + { + WriteIndented = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; + + /// + /// Export results to a CSV file. + /// + public static void ExportCsv(IEnumerable results, string filePath) + { + var sb = new StringBuilder(); + + // Header + sb.AppendLine("Scenario,Strategy,Dtype,Size,MeanUs,StdDevUs,MinUs,MaxUs,GBps,Reps,Timestamp,Suite,Notes,SpeedupVsBaseline"); + + // Data rows + foreach (var r in results) + { + sb.AppendLine(string.Join(",", + Escape(r.Scenario), + Escape(r.Strategy), + Escape(r.Dtype), + r.Size.ToString(CultureInfo.InvariantCulture), + r.MeanUs.ToString("F4", CultureInfo.InvariantCulture), + r.StdDevUs.ToString("F4", CultureInfo.InvariantCulture), + r.MinUs.ToString("F4", CultureInfo.InvariantCulture), + r.MaxUs.ToString("F4", CultureInfo.InvariantCulture), + r.GBps.ToString("F4", CultureInfo.InvariantCulture), + r.Reps.ToString(CultureInfo.InvariantCulture), + Escape(r.Timestamp), + Escape(r.Suite), + Escape(r.Notes), + r.SpeedupVsBaseline?.ToString("F4", CultureInfo.InvariantCulture) ?? "" + )); + } + + Directory.CreateDirectory(Path.GetDirectoryName(filePath)!); + File.WriteAllText(filePath, sb.ToString()); + Console.WriteLine($"CSV exported to: {filePath}"); + } + + /// + /// Export results to a JSON file. + /// + public static void ExportJson(BenchResultSet resultSet, string filePath) + { + var json = JsonSerializer.Serialize(resultSet, JsonOptions); + Directory.CreateDirectory(Path.GetDirectoryName(filePath)!); + File.WriteAllText(filePath, json); + Console.WriteLine($"JSON exported to: {filePath}"); + } + + /// + /// Export results to a JSON file (simple array format). + /// + public static void ExportJson(IEnumerable results, string filePath) + { + var json = JsonSerializer.Serialize(results.ToList(), JsonOptions); + Directory.CreateDirectory(Path.GetDirectoryName(filePath)!); + File.WriteAllText(filePath, json); + Console.WriteLine($"JSON exported to: {filePath}"); + } + + /// + /// Generate a Markdown table from results. + /// + public static string ToMarkdownTable(IEnumerable results, string title = "") + { + var sb = new StringBuilder(); + + if (!string.IsNullOrEmpty(title)) + { + sb.AppendLine($"## {title}"); + sb.AppendLine(); + } + + // Header + sb.AppendLine("| Scenario | Strategy | Dtype | Size | Mean (us) | StdDev | GB/s | Speedup |"); + sb.AppendLine("|----------|----------|-------|-----:|----------:|-------:|-----:|--------:|"); + + // Data rows + foreach (var r in results) + { + var speedup = r.SpeedupVsBaseline.HasValue ? $"{r.SpeedupVsBaseline:F2}x" : "-"; + sb.AppendLine($"| {r.Scenario} | {r.Strategy} | {r.Dtype} | {r.Size:N0} | {r.MeanUs:F2} | {r.StdDevUs:F2} | {r.GBps:F2} | {speedup} |"); + } + + return sb.ToString(); + } + + /// + /// Generate a compact comparison table (baseline vs optimized). + /// + public static string ToComparisonTable(IEnumerable results, string title = "") + { + var sb = new StringBuilder(); + + if (!string.IsNullOrEmpty(title)) + { + sb.AppendLine($"## {title}"); + sb.AppendLine(); + } + + // Group by scenario/dtype/size, show baseline and optimized side-by-side + var grouped = results + .GroupBy(r => (r.Scenario, r.Dtype, r.Size)) + .OrderBy(g => g.Key.Scenario) + .ThenBy(g => g.Key.Dtype) + .ThenBy(g => g.Key.Size); + + sb.AppendLine("| Scenario | Dtype | Size | Baseline (us) | Optimized (us) | Speedup |"); + sb.AppendLine("|----------|-------|-----:|--------------:|---------------:|--------:|"); + + foreach (var g in grouped) + { + var baseline = g.FirstOrDefault(r => r.Strategy == "Baseline"); + var optimized = g.FirstOrDefault(r => r.Strategy != "Baseline" && r.SpeedupVsBaseline.HasValue); + + if (baseline != null && optimized != null) + { + var icon = optimized.SpeedupVsBaseline switch + { + > 2.0 => " ✅", + > 1.2 => " 🟡", + > 1.0 => " 🟢", + _ => " 🔴" + }; + + sb.AppendLine($"| {g.Key.Scenario} | {g.Key.Dtype} | {g.Key.Size:N0} | {baseline.MeanUs:F2} | {optimized.MeanUs:F2} | {optimized.SpeedupVsBaseline:F2}x{icon} |"); + } + } + + return sb.ToString(); + } + + /// + /// Generate a pivot table with dtypes as columns and sizes as rows. + /// + public static string ToPivotTable(IEnumerable results, string scenario, string metric = "speedup") + { + var filtered = results.Where(r => r.Scenario == scenario && r.SpeedupVsBaseline.HasValue).ToList(); + if (!filtered.Any()) return ""; + + var sb = new StringBuilder(); + sb.AppendLine($"### {scenario} - Speedup Matrix"); + sb.AppendLine(); + + var dtypes = filtered.Select(r => r.Dtype).Distinct().OrderBy(d => d).ToList(); + var sizes = filtered.Select(r => r.Size).Distinct().OrderBy(s => s).ToList(); + + // Header + sb.Append("| Size |"); + foreach (var d in dtypes) sb.Append($" {d} |"); + sb.AppendLine(); + + sb.Append("|-----:|"); + foreach (var _ in dtypes) sb.Append("------:|"); + sb.AppendLine(); + + // Rows + foreach (var size in sizes) + { + sb.Append($"| {size:N0} |"); + foreach (var dtype in dtypes) + { + var result = filtered.FirstOrDefault(r => r.Dtype == dtype && r.Size == size); + if (result != null) + { + var value = metric switch + { + "speedup" => $"{result.SpeedupVsBaseline:F2}x", + "mean" => $"{result.MeanUs:F1}", + "gbps" => $"{result.GBps:F1}", + _ => "-" + }; + sb.Append($" {value} |"); + } + else + { + sb.Append(" - |"); + } + } + sb.AppendLine(); + } + + return sb.ToString(); + } + + /// + /// Export results to Markdown file. + /// + public static void ExportMarkdown(BenchResultSet resultSet, string filePath) + { + var sb = new StringBuilder(); + + sb.AppendLine($"# {resultSet.SuiteName}"); + sb.AppendLine(); + sb.AppendLine($"_{resultSet.Description}_"); + sb.AppendLine(); + sb.AppendLine("## Environment"); + sb.AppendLine(); + sb.AppendLine($"- **CPU**: {resultSet.CpuModel}"); + sb.AppendLine($"- **.NET**: {resultSet.DotNetVersion}"); + sb.AppendLine($"- **Start**: {resultSet.StartTime:u}"); + sb.AppendLine($"- **Duration**: {resultSet.Duration:hh\\:mm\\:ss}"); + sb.AppendLine(); + + // Group results by suite + var grouped = resultSet.Results.GroupBy(r => r.Suite).OrderBy(g => g.Key); + + foreach (var group in grouped) + { + var suiteName = string.IsNullOrEmpty(group.Key) ? "Results" : group.Key; + sb.AppendLine(ToMarkdownTable(group, suiteName)); + sb.AppendLine(); + } + + Directory.CreateDirectory(Path.GetDirectoryName(filePath)!); + File.WriteAllText(filePath, sb.ToString()); + Console.WriteLine($"Markdown exported to: {filePath}"); + } + + /// + /// Print a summary of results to console. + /// + public static void PrintSummary(IEnumerable results) + { + var list = results.ToList(); + + Console.WriteLine(); + Console.WriteLine("=== Summary ==="); + Console.WriteLine($"Total benchmarks: {list.Count}"); + + var withSpeedup = list.Where(r => r.SpeedupVsBaseline.HasValue).ToList(); + if (withSpeedup.Any()) + { + var avgSpeedup = withSpeedup.Average(r => r.SpeedupVsBaseline!.Value); + var maxSpeedup = withSpeedup.Max(r => r.SpeedupVsBaseline!.Value); + var minSpeedup = withSpeedup.Min(r => r.SpeedupVsBaseline!.Value); + var wins = withSpeedup.Count(r => r.SpeedupVsBaseline > 1.0); + + Console.WriteLine($"Comparisons: {withSpeedup.Count}"); + Console.WriteLine($" Wins (speedup > 1.0): {wins} ({100.0 * wins / withSpeedup.Count:F1}%)"); + Console.WriteLine($" Avg speedup: {avgSpeedup:F2}x"); + Console.WriteLine($" Max speedup: {maxSpeedup:F2}x"); + Console.WriteLine($" Min speedup: {minSpeedup:F2}x"); + + // Best result + var best = withSpeedup.OrderByDescending(r => r.SpeedupVsBaseline).First(); + Console.WriteLine($" Best: {best.Scenario} {best.Dtype} {best.Size:N0} = {best.SpeedupVsBaseline:F2}x"); + + // Worst result + var worst = withSpeedup.OrderBy(r => r.SpeedupVsBaseline).First(); + Console.WriteLine($" Worst: {worst.Scenario} {worst.Dtype} {worst.Size:N0} = {worst.SpeedupVsBaseline:F2}x"); + } + } + + private static string Escape(string s) + { + if (s.Contains(',') || s.Contains('"') || s.Contains('\n')) + { + return $"\"{s.Replace("\"", "\"\"")}\""; + } + return s; + } +} diff --git a/benchmark/NumSharp.Benchmark.Exploration/Infrastructure/SimdImplementations.cs b/benchmark/NumSharp.Benchmark.Exploration/Infrastructure/SimdImplementations.cs new file mode 100644 index 000000000..4f745206f --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Exploration/Infrastructure/SimdImplementations.cs @@ -0,0 +1,632 @@ +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; + +namespace NumSharp.Benchmark.Exploration.Infrastructure; + +/// +/// SIMD implementations for benchmarking different strategies. +/// These are raw implementations without NumSharp overhead for isolated testing. +/// +public static unsafe class SimdImplementations +{ + #region SIMD-FULL: Contiguous arrays, same shape + + /// + /// Add two contiguous float64 arrays using Vector256. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddFull_Float64(double* lhs, double* rhs, double* result, int count) + { + int i = 0; + + if (Avx2.IsSupported && count >= Vector256.Count) + { + int vectorCount = count - Vector256.Count + 1; + for (; i < vectorCount; i += Vector256.Count) + { + var va = Avx.LoadVector256(lhs + i); + var vb = Avx.LoadVector256(rhs + i); + var vr = Avx.Add(va, vb); + Avx.Store(result + i, vr); + } + } + + // Scalar tail + for (; i < count; i++) + { + result[i] = lhs[i] + rhs[i]; + } + } + + /// + /// Add two contiguous float32 arrays using Vector256. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddFull_Float32(float* lhs, float* rhs, float* result, int count) + { + int i = 0; + + if (Avx2.IsSupported && count >= Vector256.Count) + { + int vectorCount = count - Vector256.Count + 1; + for (; i < vectorCount; i += Vector256.Count) + { + var va = Avx.LoadVector256(lhs + i); + var vb = Avx.LoadVector256(rhs + i); + var vr = Avx.Add(va, vb); + Avx.Store(result + i, vr); + } + } + + for (; i < count; i++) + { + result[i] = lhs[i] + rhs[i]; + } + } + + /// + /// Add two contiguous int32 arrays using Vector256. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddFull_Int32(int* lhs, int* rhs, int* result, int count) + { + int i = 0; + + if (Avx2.IsSupported && count >= Vector256.Count) + { + int vectorCount = count - Vector256.Count + 1; + for (; i < vectorCount; i += Vector256.Count) + { + var va = Avx2.LoadVector256(lhs + i); + var vb = Avx2.LoadVector256(rhs + i); + var vr = Avx2.Add(va, vb); + Avx2.Store(result + i, vr); + } + } + + for (; i < count; i++) + { + result[i] = lhs[i] + rhs[i]; + } + } + + /// + /// Add two contiguous int64 arrays using Vector256. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddFull_Int64(long* lhs, long* rhs, long* result, int count) + { + int i = 0; + + if (Avx2.IsSupported && count >= Vector256.Count) + { + int vectorCount = count - Vector256.Count + 1; + for (; i < vectorCount; i += Vector256.Count) + { + var va = Avx2.LoadVector256(lhs + i); + var vb = Avx2.LoadVector256(rhs + i); + var vr = Avx2.Add(va, vb); + Avx2.Store(result + i, vr); + } + } + + for (; i < count; i++) + { + result[i] = lhs[i] + rhs[i]; + } + } + + /// + /// Add two contiguous int16 arrays using Vector256. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddFull_Int16(short* lhs, short* rhs, short* result, int count) + { + int i = 0; + + if (Avx2.IsSupported && count >= Vector256.Count) + { + int vectorCount = count - Vector256.Count + 1; + for (; i < vectorCount; i += Vector256.Count) + { + var va = Avx2.LoadVector256(lhs + i); + var vb = Avx2.LoadVector256(rhs + i); + var vr = Avx2.Add(va, vb); + Avx2.Store(result + i, vr); + } + } + + for (; i < count; i++) + { + result[i] = (short)(lhs[i] + rhs[i]); + } + } + + /// + /// Add two contiguous byte arrays using Vector256. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddFull_Byte(byte* lhs, byte* rhs, byte* result, int count) + { + int i = 0; + + if (Avx2.IsSupported && count >= Vector256.Count) + { + int vectorCount = count - Vector256.Count + 1; + for (; i < vectorCount; i += Vector256.Count) + { + var va = Avx2.LoadVector256(lhs + i); + var vb = Avx2.LoadVector256(rhs + i); + var vr = Avx2.Add(va, vb); + Avx2.Store(result + i, vr); + } + } + + for (; i < count; i++) + { + result[i] = (byte)(lhs[i] + rhs[i]); + } + } + + #endregion + + #region SIMD-SCALAR: One operand is a scalar + + /// + /// Add a scalar to a contiguous float64 array using Vector256. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddScalar_Float64(double* lhs, double scalar, double* result, int count) + { + int i = 0; + + if (Avx2.IsSupported && count >= Vector256.Count) + { + var vs = Vector256.Create(scalar); + int vectorCount = count - Vector256.Count + 1; + for (; i < vectorCount; i += Vector256.Count) + { + var va = Avx.LoadVector256(lhs + i); + var vr = Avx.Add(va, vs); + Avx.Store(result + i, vr); + } + } + + for (; i < count; i++) + { + result[i] = lhs[i] + scalar; + } + } + + /// + /// Add a scalar to a contiguous float32 array using Vector256. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddScalar_Float32(float* lhs, float scalar, float* result, int count) + { + int i = 0; + + if (Avx2.IsSupported && count >= Vector256.Count) + { + var vs = Vector256.Create(scalar); + int vectorCount = count - Vector256.Count + 1; + for (; i < vectorCount; i += Vector256.Count) + { + var va = Avx.LoadVector256(lhs + i); + var vr = Avx.Add(va, vs); + Avx.Store(result + i, vr); + } + } + + for (; i < count; i++) + { + result[i] = lhs[i] + scalar; + } + } + + /// + /// Add a scalar to a contiguous int32 array using Vector256. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddScalar_Int32(int* lhs, int scalar, int* result, int count) + { + int i = 0; + + if (Avx2.IsSupported && count >= Vector256.Count) + { + var vs = Vector256.Create(scalar); + int vectorCount = count - Vector256.Count + 1; + for (; i < vectorCount; i += Vector256.Count) + { + var va = Avx2.LoadVector256(lhs + i); + var vr = Avx2.Add(va, vs); + Avx2.Store(result + i, vr); + } + } + + for (; i < count; i++) + { + result[i] = lhs[i] + scalar; + } + } + + /// + /// Add a scalar to a contiguous int64 array using Vector256. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddScalar_Int64(long* lhs, long scalar, long* result, int count) + { + int i = 0; + + if (Avx2.IsSupported && count >= Vector256.Count) + { + var vs = Vector256.Create(scalar); + int vectorCount = count - Vector256.Count + 1; + for (; i < vectorCount; i += Vector256.Count) + { + var va = Avx2.LoadVector256(lhs + i); + var vr = Avx2.Add(va, vs); + Avx2.Store(result + i, vr); + } + } + + for (; i < count; i++) + { + result[i] = lhs[i] + scalar; + } + } + + /// + /// Add a scalar to a contiguous int16 array using Vector256. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddScalar_Int16(short* lhs, short scalar, short* result, int count) + { + int i = 0; + + if (Avx2.IsSupported && count >= Vector256.Count) + { + var vs = Vector256.Create(scalar); + int vectorCount = count - Vector256.Count + 1; + for (; i < vectorCount; i += Vector256.Count) + { + var va = Avx2.LoadVector256(lhs + i); + var vr = Avx2.Add(va, vs); + Avx2.Store(result + i, vr); + } + } + + for (; i < count; i++) + { + result[i] = (short)(lhs[i] + scalar); + } + } + + /// + /// Add a scalar to a contiguous byte array using Vector256. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddScalar_Byte(byte* lhs, byte scalar, byte* result, int count) + { + int i = 0; + + if (Avx2.IsSupported && count >= Vector256.Count) + { + var vs = Vector256.Create(scalar); + int vectorCount = count - Vector256.Count + 1; + for (; i < vectorCount; i += Vector256.Count) + { + var va = Avx2.LoadVector256(lhs + i); + var vr = Avx2.Add(va, vs); + Avx2.Store(result + i, vr); + } + } + + for (; i < count; i++) + { + result[i] = (byte)(lhs[i] + scalar); + } + } + + #endregion + + #region SIMD-CHUNK: Row broadcast (inner dimension contiguous) + + /// + /// Add a row vector to each row of a matrix using SIMD on inner dimension. + /// matrix[M, N] + row[N] = result[M, N] + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddRowBroadcast_Float64(double* matrix, double* row, double* result, int rows, int cols) + { + for (int r = 0; r < rows; r++) + { + var matrixRow = matrix + r * cols; + var resultRow = result + r * cols; + AddFull_Float64(matrixRow, row, resultRow, cols); + } + } + + /// + /// Add a row vector to each row of a matrix using SIMD on inner dimension. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddRowBroadcast_Float32(float* matrix, float* row, float* result, int rows, int cols) + { + for (int r = 0; r < rows; r++) + { + var matrixRow = matrix + r * cols; + var resultRow = result + r * cols; + AddFull_Float32(matrixRow, row, resultRow, cols); + } + } + + /// + /// Add a row vector to each row of a matrix using SIMD on inner dimension. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddRowBroadcast_Int32(int* matrix, int* row, int* result, int rows, int cols) + { + for (int r = 0; r < rows; r++) + { + var matrixRow = matrix + r * cols; + var resultRow = result + r * cols; + AddFull_Int32(matrixRow, row, resultRow, cols); + } + } + + #endregion + + #region Scalar loops (baseline) + + /// + /// Scalar add baseline for float64. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void AddScalarLoop_Float64(double* lhs, double* rhs, double* result, int count) + { + for (int i = 0; i < count; i++) + { + result[i] = lhs[i] + rhs[i]; + } + } + + /// + /// Scalar add baseline for float32. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void AddScalarLoop_Float32(float* lhs, float* rhs, float* result, int count) + { + for (int i = 0; i < count; i++) + { + result[i] = lhs[i] + rhs[i]; + } + } + + /// + /// Scalar add baseline for int32. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void AddScalarLoop_Int32(int* lhs, int* rhs, int* result, int count) + { + for (int i = 0; i < count; i++) + { + result[i] = lhs[i] + rhs[i]; + } + } + + /// + /// Scalar add baseline for int64. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void AddScalarLoop_Int64(long* lhs, long* rhs, long* result, int count) + { + for (int i = 0; i < count; i++) + { + result[i] = lhs[i] + rhs[i]; + } + } + + /// + /// Scalar add baseline for int16. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void AddScalarLoop_Int16(short* lhs, short* rhs, short* result, int count) + { + for (int i = 0; i < count; i++) + { + result[i] = (short)(lhs[i] + rhs[i]); + } + } + + /// + /// Scalar add baseline for byte. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void AddScalarLoop_Byte(byte* lhs, byte* rhs, byte* result, int count) + { + for (int i = 0; i < count; i++) + { + result[i] = (byte)(lhs[i] + rhs[i]); + } + } + + /// + /// Row broadcast baseline - scalar inner loop. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void AddRowBroadcastScalar_Float64(double* matrix, double* row, double* result, int rows, int cols) + { + for (int r = 0; r < rows; r++) + { + for (int c = 0; c < cols; c++) + { + result[r * cols + c] = matrix[r * cols + c] + row[c]; + } + } + } + + /// + /// Column broadcast baseline - scalar loop with strided access. + /// matrix[M, N] + col[M, 1] = result[M, N] + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void AddColBroadcastScalar_Float64(double* matrix, double* col, double* result, int rows, int cols) + { + for (int r = 0; r < rows; r++) + { + var colVal = col[r]; + for (int c = 0; c < cols; c++) + { + result[r * cols + c] = matrix[r * cols + c] + colVal; + } + } + } + + /// + /// Column broadcast with SIMD - each row uses same scalar from col. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddColBroadcast_Float64(double* matrix, double* col, double* result, int rows, int cols) + { + for (int r = 0; r < rows; r++) + { + var colVal = col[r]; + var matrixRow = matrix + r * cols; + var resultRow = result + r * cols; + AddScalar_Float64(matrixRow, colVal, resultRow, cols); + } + } + + #endregion + + #region Array allocation helpers + + /// + /// Result of pinned array allocation. + /// + public readonly struct PinnedArray : IDisposable where T : unmanaged + { + public readonly T[] Array; + public readonly GCHandle Handle; + public readonly IntPtr Pointer; + + public PinnedArray(int count) + { + Array = GC.AllocateArray(count, pinned: true); + Handle = GCHandle.Alloc(Array, GCHandleType.Pinned); + Pointer = Handle.AddrOfPinnedObject(); + } + + public T* Ptr => (T*)Pointer; + + public void Dispose() + { + if (Handle.IsAllocated) + Handle.Free(); + } + } + + /// + /// Allocate a pinned array and return a struct with the array, handle, and pointer. + /// + public static PinnedArray AllocatePinned(int count) where T : unmanaged + { + return new PinnedArray(count); + } + + /// + /// Allocate aligned memory using NativeMemory. + /// + public static T* AllocateAligned(int count, nuint alignment = 32) where T : unmanaged + { + return (T*)NativeMemory.AlignedAlloc((nuint)(count * sizeof(T)), alignment); + } + + /// + /// Free aligned memory. + /// + public static void FreeAligned(T* ptr) where T : unmanaged + { + NativeMemory.AlignedFree(ptr); + } + + /// + /// Fill array with random values. + /// + public static void FillRandom(double* ptr, int count, int seed = 42) + { + var rng = new Random(seed); + for (int i = 0; i < count; i++) + { + ptr[i] = rng.NextDouble() * 100; + } + } + + /// + /// Fill array with random float values. + /// + public static void FillRandom(float* ptr, int count, int seed = 42) + { + var rng = new Random(seed); + for (int i = 0; i < count; i++) + { + ptr[i] = (float)(rng.NextDouble() * 100); + } + } + + /// + /// Fill array with random int values. + /// + public static void FillRandom(int* ptr, int count, int seed = 42) + { + var rng = new Random(seed); + for (int i = 0; i < count; i++) + { + ptr[i] = rng.Next(0, 100); + } + } + + /// + /// Fill array with random long values. + /// + public static void FillRandom(long* ptr, int count, int seed = 42) + { + var rng = new Random(seed); + for (int i = 0; i < count; i++) + { + ptr[i] = rng.NextInt64(0, 100); + } + } + + /// + /// Fill array with random short values. + /// + public static void FillRandom(short* ptr, int count, int seed = 42) + { + var rng = new Random(seed); + for (int i = 0; i < count; i++) + { + ptr[i] = (short)rng.Next(0, 100); + } + } + + /// + /// Fill array with random byte values. + /// + public static void FillRandom(byte* ptr, int count, int seed = 42) + { + var rng = new Random(seed); + var bytes = new byte[count]; + rng.NextBytes(bytes); + for (int i = 0; i < count; i++) + { + ptr[i] = bytes[i]; + } + } + + #endregion +} diff --git a/benchmark/NumSharp.Benchmark.Exploration/Integration/NumSharpBroadcast.cs b/benchmark/NumSharp.Benchmark.Exploration/Integration/NumSharpBroadcast.cs new file mode 100644 index 000000000..aa9fcc602 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Exploration/Integration/NumSharpBroadcast.cs @@ -0,0 +1,314 @@ +using NumSharp.Benchmark.Exploration.Infrastructure; + +namespace NumSharp.Benchmark.Exploration.Integration; + +/// +/// Test NumSharp broadcasting performance through actual TensorEngine. +/// Measures overhead of NumSharp vs isolated implementations. +/// +public static class NumSharpBroadcast +{ + private const string Suite = "NumSharpIntegration"; + private const int Seed = 42; + + /// + /// Run all NumSharp integration benchmarks. + /// + public static List RunAll(bool quick = false) + { + var results = new List(); + var warmup = quick ? 2 : BenchFramework.DefaultWarmup; + var measure = quick ? 5 : BenchFramework.DefaultMeasure; + + var sizes = quick + ? new[] { 100_000, 1_000_000 } + : new[] { 1_000, 100_000, 1_000_000, 10_000_000 }; + + BenchFramework.PrintHeader($"{Suite}: NumSharp Broadcasting Performance"); + + long initialMemory = GC.GetTotalMemory(true); + const long MemoryThresholdBytes = 4L * 1024 * 1024 * 1024; // 4 GB + + foreach (var size in sizes) + { + BenchFramework.PrintDivider($"Size: {size:N0}"); + + results.AddRange(TestContiguousAdd(size, warmup, measure)); + CleanupAndCheckMemory(initialMemory, MemoryThresholdBytes, $"after ContiguousAdd size={size}"); + + results.AddRange(TestScalarBroadcast(size, warmup, measure)); + CleanupAndCheckMemory(initialMemory, MemoryThresholdBytes, $"after ScalarBroadcast size={size}"); + + results.AddRange(TestRowBroadcast(size, warmup, measure)); + CleanupAndCheckMemory(initialMemory, MemoryThresholdBytes, $"after RowBroadcast size={size}"); + } + + OutputFormatters.PrintSummary(results); + return results; + } + + /// + /// Force GC and check memory usage. + /// + private static void CleanupAndCheckMemory(long initialMemory, long threshold, string context) + { + // Force full GC collection + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true); + GC.WaitForPendingFinalizers(); + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true); + + long currentMemory = GC.GetTotalMemory(false); + long memoryGrowth = currentMemory - initialMemory; + + if (memoryGrowth > threshold) + { + Console.WriteLine($"[WARNING] Memory leak detected {context}: {memoryGrowth / 1024 / 1024} MB above baseline"); + } + } + + /// + /// Test contiguous array addition (S1 scenario). + /// + public static List TestContiguousAdd(int size, int warmup, int measure) + { + var results = new List(); + int elementBytes = 8; + + // Create NumSharp arrays + np.random.seed(Seed); + var a = np.random.rand(size); + var b = np.random.rand(size); + NDArray result = null!; + + // NumSharp contiguous add + var numsharp = BenchFramework.Run( + () => result = a + b, + "S1_contiguous", "NumSharp", "float64", size, elementBytes, warmup, measure, Suite); + results.Add(numsharp); + BenchFramework.PrintResult(numsharp); + + // Also test np.add function + var npAdd = BenchFramework.Run( + () => result = np.add(a, b), + "S1_contiguous", "np.add", "float64", size, elementBytes, warmup, measure, Suite); + npAdd = npAdd with { SpeedupVsBaseline = numsharp.MeanUs / npAdd.MeanUs }; + results.Add(npAdd); + BenchFramework.PrintResult(npAdd); + + // Cleanup: release references to allow GC + a = null!; + b = null!; + result = null!; + + return results; + } + + /// + /// Test scalar broadcast (S2 scenario). + /// + public static List TestScalarBroadcast(int size, int warmup, int measure) + { + var results = new List(); + int elementBytes = 8; + + np.random.seed(Seed); + var a = np.random.rand(size); + double scalar = 42.5; + NDArray result = null!; + + // NumSharp scalar add + var numsharp = BenchFramework.Run( + () => result = a + scalar, + "S2_scalar", "NumSharp", "float64", size, elementBytes, warmup, measure, Suite); + results.Add(numsharp); + BenchFramework.PrintResult(numsharp); + + // Cleanup + a = null!; + result = null!; + + return results; + } + + /// + /// Test row broadcast (S4 scenario). + /// + public static List TestRowBroadcast(int totalElements, int warmup, int measure) + { + var results = new List(); + int elementBytes = 8; + + // Create square-ish matrix + int rows = (int)Math.Sqrt(totalElements); + int cols = totalElements / rows; + int actualSize = rows * cols; + + np.random.seed(Seed); + var matrix = np.random.rand(rows, cols); + var row = np.random.rand(cols); + NDArray result = null!; + + // NumSharp row broadcast + var numsharp = BenchFramework.Run( + () => result = matrix + row, + "S4_rowBC", "NumSharp", "float64", actualSize, elementBytes, warmup, measure, Suite); + results.Add(numsharp); + BenchFramework.PrintResult(numsharp); + + // Cleanup + matrix = null!; + row = null!; + result = null!; + + return results; + } + + /// + /// Test various NumSharp operations to measure overhead. + /// + public static List TestOperationOverhead(int size, int warmup, int measure) + { + var results = new List(); + int elementBytes = 8; + + BenchFramework.PrintDivider($"Operation Overhead: Size = {size:N0}"); + + np.random.seed(Seed); + var a = np.random.rand(size); + var b = np.random.rand(size); + NDArray result = null!; + + // Test different operations + var ops = new (string name, Func op)[] + { + ("Add", () => a + b), + ("Sub", () => a - b), + ("Mul", () => a * b), + ("Div", () => a / b), + ("np.sqrt", () => np.sqrt(a)), + ("np.exp", () => np.exp(a)), + ("np.sum", () => np.sum(a)), + ("np.mean", () => np.mean(a)), + }; + + foreach (var (name, op) in ops) + { + var r = BenchFramework.Run( + () => result = op(), + "Overhead", name, "float64", size, elementBytes, warmup, measure, Suite); + results.Add(r); + BenchFramework.PrintResult(r); + + // Force GC between operations to prevent accumulation + result = null!; + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true); + GC.WaitForPendingFinalizers(); + } + + // Cleanup + a = null!; + b = null!; + + return results; + } + + /// + /// Compare NumSharp overhead vs raw pointer operations. + /// + public static unsafe List CompareOverhead(int size, int warmup, int measure) + { + var results = new List(); + int elementBytes = 8; + + BenchFramework.PrintDivider($"NumSharp vs Raw Pointer: Size = {size:N0}"); + + // Raw pointer implementation + var lhsRaw = SimdImplementations.AllocateAligned(size); + var rhsRaw = SimdImplementations.AllocateAligned(size); + var resultRaw = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhsRaw, size, 42); + SimdImplementations.FillRandom(rhsRaw, size, 43); + + // NumSharp arrays + np.random.seed(42); + var lhsNp = np.random.rand(size); + np.random.seed(43); + var rhsNp = np.random.rand(size); + NDArray resultNp = null!; + + // Raw SIMD + var raw = BenchFramework.Run( + () => SimdImplementations.AddFull_Float64(lhsRaw, rhsRaw, resultRaw, size), + "Overhead", "RawSIMD", "float64", size, elementBytes, warmup, measure, Suite); + results.Add(raw); + BenchFramework.PrintResult(raw); + + // NumSharp + var numsharp = BenchFramework.Run( + () => resultNp = lhsNp + rhsNp, + "Overhead", "NumSharp", "float64", size, elementBytes, warmup, measure, Suite); + numsharp = numsharp with + { + SpeedupVsBaseline = raw.MeanUs / numsharp.MeanUs, + Notes = $"Overhead: {numsharp.MeanUs / raw.MeanUs:F2}x" + }; + results.Add(numsharp); + BenchFramework.PrintResult(numsharp); + + // Cleanup raw memory + SimdImplementations.FreeAligned(lhsRaw); + SimdImplementations.FreeAligned(rhsRaw); + SimdImplementations.FreeAligned(resultRaw); + + // Cleanup NumSharp arrays + lhsNp = null!; + rhsNp = null!; + resultNp = null!; + + return results; + } + + /// + /// Test different dtypes through NumSharp. + /// + public static List TestDtypes(int size, int warmup, int measure) + { + var results = new List(); + + BenchFramework.PrintDivider($"NumSharp Dtype Performance: Size = {size:N0}"); + + var dtypes = new[] + { + (name: "byte", type: typeof(byte), bytes: 1), + (name: "int16", type: typeof(short), bytes: 2), + (name: "int32", type: typeof(int), bytes: 4), + (name: "int64", type: typeof(long), bytes: 8), + (name: "float32", type: typeof(float), bytes: 4), + (name: "float64", type: typeof(double), bytes: 8), + }; + + NDArray result = null!; + + foreach (var (name, type, bytes) in dtypes) + { + np.random.seed(Seed); + var a = np.random.randint(0, 100, new Shape(size), type); + var b = np.random.randint(0, 100, new Shape(size), type); + + var r = BenchFramework.Run( + () => result = a + b, + "DtypePerf", "Add", name, size, bytes, warmup, measure, Suite); + results.Add(r); + BenchFramework.PrintResult(r); + + // Cleanup after each dtype test + a = null!; + b = null!; + result = null!; + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true); + GC.WaitForPendingFinalizers(); + } + + return results; + } +} diff --git a/benchmark/NumSharp.Benchmark.Exploration/Isolated/BroadcastScenarios.cs b/benchmark/NumSharp.Benchmark.Exploration/Isolated/BroadcastScenarios.cs new file mode 100644 index 000000000..e24753bd3 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Exploration/Isolated/BroadcastScenarios.cs @@ -0,0 +1,608 @@ +using System.Runtime.InteropServices; +using NumSharp.Benchmark.Exploration.Infrastructure; + +namespace NumSharp.Benchmark.Exploration.Isolated; + +/// +/// Benchmark all 7 broadcasting scenarios to identify which benefit from SIMD. +/// +/// Scenarios: +/// S1: Both contiguous, same shape — SIMD-FULL +/// S2: Scalar broadcast (right) — SIMD-SCALAR +/// S3: Scalar broadcast (left) — SIMD-SCALAR +/// S4: Row broadcast (M,N) + (N,) — SIMD-CHUNK +/// S5: Column broadcast (M,N) + (M,1) — SIMD per-row scalar +/// S6: Mutual broadcast (M,1) + (1,N) — Outer product +/// S7: Strided arrays a[::2] + b[::2] — SCALAR/GATHER +/// +public static unsafe class BroadcastScenarios +{ + private const string Suite = "BroadcastScenarios"; + + /// + /// Run all broadcast scenario benchmarks. + /// + public static List RunAll(int[]? sizes = null, string[]? dtypes = null, bool quick = false) + { + sizes ??= quick ? ArraySizes.Quick : ArraySizes.Standard; + dtypes ??= quick ? Dtypes.Common : Dtypes.All; + var warmup = quick ? 2 : BenchFramework.DefaultWarmup; + var measure = quick ? BenchFramework.QuickMeasure : BenchFramework.DefaultMeasure; + + var results = new List(); + + BenchFramework.PrintHeader($"{Suite}: All 7 Broadcasting Scenarios"); + + foreach (var dtype in dtypes) + { + BenchFramework.PrintDivider($"dtype={dtype}"); + + foreach (var size in sizes) + { + // S1: Both contiguous, same shape + results.AddRange(RunS1_Contiguous(dtype, size, warmup, measure)); + + // S2: Scalar broadcast (right) + results.AddRange(RunS2_ScalarRight(dtype, size, warmup, measure)); + + // S3: Scalar broadcast (left) — same as S2 due to commutativity + // Skipped for brevity, same perf characteristics + + // S4: Row broadcast + results.AddRange(RunS4_RowBroadcast(dtype, size, warmup, measure)); + + // S5: Column broadcast + results.AddRange(RunS5_ColBroadcast(dtype, size, warmup, measure)); + } + } + + OutputFormatters.PrintSummary(results); + return results; + } + + #region S1: Contiguous same shape + + /// + /// S1: Both operands contiguous with same shape — ideal for SIMD-FULL. + /// + public static List RunS1_Contiguous(string dtype, int size, int warmup, int measure) + { + var results = new List(); + var elementBytes = DtypeInfo.GetElementSize(dtype); + + switch (dtype.ToLowerInvariant()) + { + case "float64" or "double": + { + var lhs = SimdImplementations.AllocateAligned(size); + var rhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + SimdImplementations.FillRandom(rhs, size, 43); + + // Baseline: scalar loop + var baseline = BenchFramework.Run( + () => SimdImplementations.AddScalarLoop_Float64(lhs, rhs, result, size), + "S1_contiguous", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + // SIMD-FULL + var simd = BenchFramework.Run( + () => SimdImplementations.AddFull_Float64(lhs, rhs, result, size), + "S1_contiguous", "SIMD-FULL", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + results.Add(simd); + BenchFramework.PrintResult(simd); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(rhs); + SimdImplementations.FreeAligned(result); + break; + } + + case "float32" or "single" or "float": + { + var lhs = SimdImplementations.AllocateAligned(size); + var rhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + SimdImplementations.FillRandom(rhs, size, 43); + + var baseline = BenchFramework.Run( + () => SimdImplementations.AddScalarLoop_Float32(lhs, rhs, result, size), + "S1_contiguous", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddFull_Float32(lhs, rhs, result, size), + "S1_contiguous", "SIMD-FULL", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + results.Add(simd); + BenchFramework.PrintResult(simd); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(rhs); + SimdImplementations.FreeAligned(result); + break; + } + + case "int32" or "int": + { + var lhs = SimdImplementations.AllocateAligned(size); + var rhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + SimdImplementations.FillRandom(rhs, size, 43); + + var baseline = BenchFramework.Run( + () => SimdImplementations.AddScalarLoop_Int32(lhs, rhs, result, size), + "S1_contiguous", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddFull_Int32(lhs, rhs, result, size), + "S1_contiguous", "SIMD-FULL", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + results.Add(simd); + BenchFramework.PrintResult(simd); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(rhs); + SimdImplementations.FreeAligned(result); + break; + } + + case "int64" or "long": + { + var lhs = SimdImplementations.AllocateAligned(size); + var rhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + SimdImplementations.FillRandom(rhs, size, 43); + + var baseline = BenchFramework.Run( + () => SimdImplementations.AddScalarLoop_Int64(lhs, rhs, result, size), + "S1_contiguous", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddFull_Int64(lhs, rhs, result, size), + "S1_contiguous", "SIMD-FULL", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + results.Add(simd); + BenchFramework.PrintResult(simd); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(rhs); + SimdImplementations.FreeAligned(result); + break; + } + + case "int16" or "short": + { + var lhs = SimdImplementations.AllocateAligned(size); + var rhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + SimdImplementations.FillRandom(rhs, size, 43); + + var baseline = BenchFramework.Run( + () => SimdImplementations.AddScalarLoop_Int16(lhs, rhs, result, size), + "S1_contiguous", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddFull_Int16(lhs, rhs, result, size), + "S1_contiguous", "SIMD-FULL", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + results.Add(simd); + BenchFramework.PrintResult(simd); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(rhs); + SimdImplementations.FreeAligned(result); + break; + } + + case "byte" or "uint8": + { + var lhs = SimdImplementations.AllocateAligned(size); + var rhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + SimdImplementations.FillRandom(rhs, size, 43); + + var baseline = BenchFramework.Run( + () => SimdImplementations.AddScalarLoop_Byte(lhs, rhs, result, size), + "S1_contiguous", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddFull_Byte(lhs, rhs, result, size), + "S1_contiguous", "SIMD-FULL", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + results.Add(simd); + BenchFramework.PrintResult(simd); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(rhs); + SimdImplementations.FreeAligned(result); + break; + } + } + + return results; + } + + #endregion + + #region S2: Scalar broadcast (right) + + /// + /// S2: Array + scalar — ideal for SIMD-SCALAR strategy. + /// + public static List RunS2_ScalarRight(string dtype, int size, int warmup, int measure) + { + var results = new List(); + var elementBytes = DtypeInfo.GetElementSize(dtype); + + switch (dtype.ToLowerInvariant()) + { + case "float64" or "double": + { + var lhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + double scalar = 42.5; + + // Baseline: scalar loop + var baseline = BenchFramework.Run( + () => + { + for (int i = 0; i < size; i++) result[i] = lhs[i] + scalar; + }, + "S2_scalar", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + // SIMD-SCALAR + var simd = BenchFramework.Run( + () => SimdImplementations.AddScalar_Float64(lhs, scalar, result, size), + "S2_scalar", "SIMD-SCALAR", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + results.Add(simd); + BenchFramework.PrintResult(simd); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(result); + break; + } + + case "float32" or "single" or "float": + { + var lhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + float scalar = 42.5f; + + var baseline = BenchFramework.Run( + () => + { + for (int i = 0; i < size; i++) result[i] = lhs[i] + scalar; + }, + "S2_scalar", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddScalar_Float32(lhs, scalar, result, size), + "S2_scalar", "SIMD-SCALAR", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + results.Add(simd); + BenchFramework.PrintResult(simd); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(result); + break; + } + + case "int32" or "int": + { + var lhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + int scalar = 42; + + var baseline = BenchFramework.Run( + () => + { + for (int i = 0; i < size; i++) result[i] = lhs[i] + scalar; + }, + "S2_scalar", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddScalar_Int32(lhs, scalar, result, size), + "S2_scalar", "SIMD-SCALAR", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + results.Add(simd); + BenchFramework.PrintResult(simd); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(result); + break; + } + + case "int64" or "long": + { + var lhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + long scalar = 42; + + var baseline = BenchFramework.Run( + () => + { + for (int i = 0; i < size; i++) result[i] = lhs[i] + scalar; + }, + "S2_scalar", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddScalar_Int64(lhs, scalar, result, size), + "S2_scalar", "SIMD-SCALAR", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + results.Add(simd); + BenchFramework.PrintResult(simd); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(result); + break; + } + + case "int16" or "short": + { + var lhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + short scalar = 42; + + var baseline = BenchFramework.Run( + () => + { + for (int i = 0; i < size; i++) result[i] = (short)(lhs[i] + scalar); + }, + "S2_scalar", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddScalar_Int16(lhs, scalar, result, size), + "S2_scalar", "SIMD-SCALAR", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + results.Add(simd); + BenchFramework.PrintResult(simd); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(result); + break; + } + + case "byte" or "uint8": + { + var lhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + byte scalar = 42; + + var baseline = BenchFramework.Run( + () => + { + for (int i = 0; i < size; i++) result[i] = (byte)(lhs[i] + scalar); + }, + "S2_scalar", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddScalar_Byte(lhs, scalar, result, size), + "S2_scalar", "SIMD-SCALAR", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + results.Add(simd); + BenchFramework.PrintResult(simd); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(result); + break; + } + } + + return results; + } + + #endregion + + #region S4: Row broadcast + + /// + /// S4: (M,N) + (N,) row broadcast — ideal for SIMD-CHUNK strategy. + /// + public static List RunS4_RowBroadcast(string dtype, int totalElements, int warmup, int measure) + { + // Use square-ish dimensions + int rows = (int)Math.Sqrt(totalElements); + int cols = totalElements / rows; + int actualSize = rows * cols; + + var results = new List(); + var elementBytes = DtypeInfo.GetElementSize(dtype); + + switch (dtype.ToLowerInvariant()) + { + case "float64" or "double": + { + var matrix = SimdImplementations.AllocateAligned(actualSize); + var row = SimdImplementations.AllocateAligned(cols); + var result = SimdImplementations.AllocateAligned(actualSize); + SimdImplementations.FillRandom(matrix, actualSize, 42); + SimdImplementations.FillRandom(row, cols, 43); + + // Baseline: nested scalar loops + var baseline = BenchFramework.Run( + () => SimdImplementations.AddRowBroadcastScalar_Float64(matrix, row, result, rows, cols), + "S4_rowBC", "Scalar", dtype, actualSize, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + // SIMD-CHUNK: SIMD on inner dimension + var simd = BenchFramework.Run( + () => SimdImplementations.AddRowBroadcast_Float64(matrix, row, result, rows, cols), + "S4_rowBC", "SIMD-CHUNK", dtype, actualSize, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + results.Add(simd); + BenchFramework.PrintResult(simd); + + SimdImplementations.FreeAligned(matrix); + SimdImplementations.FreeAligned(row); + SimdImplementations.FreeAligned(result); + break; + } + + case "float32" or "single" or "float": + { + var matrix = SimdImplementations.AllocateAligned(actualSize); + var row = SimdImplementations.AllocateAligned(cols); + var result = SimdImplementations.AllocateAligned(actualSize); + SimdImplementations.FillRandom(matrix, actualSize, 42); + SimdImplementations.FillRandom(row, cols, 43); + + var baseline = BenchFramework.Run( + () => + { + for (int r = 0; r < rows; r++) + for (int c = 0; c < cols; c++) + result[r * cols + c] = matrix[r * cols + c] + row[c]; + }, + "S4_rowBC", "Scalar", dtype, actualSize, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddRowBroadcast_Float32(matrix, row, result, rows, cols), + "S4_rowBC", "SIMD-CHUNK", dtype, actualSize, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + results.Add(simd); + BenchFramework.PrintResult(simd); + + SimdImplementations.FreeAligned(matrix); + SimdImplementations.FreeAligned(row); + SimdImplementations.FreeAligned(result); + break; + } + + case "int32" or "int": + { + var matrix = SimdImplementations.AllocateAligned(actualSize); + var row = SimdImplementations.AllocateAligned(cols); + var result = SimdImplementations.AllocateAligned(actualSize); + SimdImplementations.FillRandom(matrix, actualSize, 42); + SimdImplementations.FillRandom(row, cols, 43); + + var baseline = BenchFramework.Run( + () => + { + for (int r = 0; r < rows; r++) + for (int c = 0; c < cols; c++) + result[r * cols + c] = matrix[r * cols + c] + row[c]; + }, + "S4_rowBC", "Scalar", dtype, actualSize, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddRowBroadcast_Int32(matrix, row, result, rows, cols), + "S4_rowBC", "SIMD-CHUNK", dtype, actualSize, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + results.Add(simd); + BenchFramework.PrintResult(simd); + + SimdImplementations.FreeAligned(matrix); + SimdImplementations.FreeAligned(row); + SimdImplementations.FreeAligned(result); + break; + } + + // Other dtypes similar pattern... + default: + Console.WriteLine($" S4 row broadcast: dtype {dtype} not implemented yet"); + break; + } + + return results; + } + + #endregion + + #region S5: Column broadcast + + /// + /// S5: (M,N) + (M,1) column broadcast — use SIMD-SCALAR per row. + /// + public static List RunS5_ColBroadcast(string dtype, int totalElements, int warmup, int measure) + { + int rows = (int)Math.Sqrt(totalElements); + int cols = totalElements / rows; + int actualSize = rows * cols; + + var results = new List(); + var elementBytes = DtypeInfo.GetElementSize(dtype); + + switch (dtype.ToLowerInvariant()) + { + case "float64" or "double": + { + var matrix = SimdImplementations.AllocateAligned(actualSize); + var col = SimdImplementations.AllocateAligned(rows); + var result = SimdImplementations.AllocateAligned(actualSize); + SimdImplementations.FillRandom(matrix, actualSize, 42); + SimdImplementations.FillRandom(col, rows, 43); + + // Baseline: nested scalar loops + var baseline = BenchFramework.Run( + () => SimdImplementations.AddColBroadcastScalar_Float64(matrix, col, result, rows, cols), + "S5_colBC", "Scalar", dtype, actualSize, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + // SIMD per row (using scalar broadcast within each row) + var simd = BenchFramework.Run( + () => SimdImplementations.AddColBroadcast_Float64(matrix, col, result, rows, cols), + "S5_colBC", "SIMD-SCALAR", dtype, actualSize, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + results.Add(simd); + BenchFramework.PrintResult(simd); + + SimdImplementations.FreeAligned(matrix); + SimdImplementations.FreeAligned(col); + SimdImplementations.FreeAligned(result); + break; + } + + default: + Console.WriteLine($" S5 col broadcast: dtype {dtype} not implemented yet"); + break; + } + + return results; + } + + #endregion +} diff --git a/benchmark/NumSharp.Benchmark.Exploration/Isolated/CombinedOptimizations.cs b/benchmark/NumSharp.Benchmark.Exploration/Isolated/CombinedOptimizations.cs new file mode 100644 index 000000000..35d42e288 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Exploration/Isolated/CombinedOptimizations.cs @@ -0,0 +1,344 @@ +using System.Buffers; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using NumSharp.Benchmark.Exploration.Infrastructure; + +namespace NumSharp.Benchmark.Exploration.Isolated; + +/// +/// Test combinations of single-threaded optimizations (NO PARALLEL). +/// C1: Scalar baseline +/// C2: SIMD only +/// C3: SIMD + ArrayPool (chained ops) +/// C4: In-place (+=) +/// C5: SIMD + In-place +/// C6: SIMD + Buffer reuse +/// +public static unsafe class CombinedOptimizations +{ + private const string Suite = "CombinedOptimizations"; + + /// + /// Run all combined optimization tests. + /// + public static List RunAll(bool quick = false) + { + var results = new List(); + var warmup = quick ? 2 : BenchFramework.DefaultWarmup; + var measure = quick ? 5 : BenchFramework.DefaultMeasure; + + var sizes = quick + ? new[] { 100_000, 10_000_000 } + : new[] { 1_000, 100_000, 1_000_000, 10_000_000 }; + + BenchFramework.PrintHeader($"{Suite}: Single-Threaded Optimization Combinations"); + + // Test 1: Single operation optimizations + foreach (var size in sizes) + { + BenchFramework.PrintDivider($"Single Operation: Size = {size:N0}"); + results.AddRange(TestSingleOperation(size, warmup, measure)); + } + + // Test 2: Chained operations (a + b + c + d) + foreach (var size in sizes) + { + BenchFramework.PrintDivider($"Chained Operations (a+b+c+d): Size = {size:N0}"); + results.AddRange(TestChainedOperations(size, warmup, measure)); + } + + // Test 3: In-place operations (+=) + foreach (var size in sizes) + { + BenchFramework.PrintDivider($"In-Place Operations (+=): Size = {size:N0}"); + results.AddRange(TestInPlaceOperations(size, warmup, measure)); + } + + OutputFormatters.PrintSummary(results); + return results; + } + + /// + /// Test single operation optimizations. + /// + public static List TestSingleOperation(int size, int warmup, int measure) + { + var results = new List(); + int elementBytes = 8; + + var lhs = SimdImplementations.AllocateAligned(size); + var rhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + SimdImplementations.FillRandom(rhs, size, 43); + + // C1: Scalar baseline + var c1 = BenchFramework.Run( + () => SimdImplementations.AddScalarLoop_Float64(lhs, rhs, result, size), + "Single", "C1_Scalar", "float64", size, elementBytes, warmup, measure, Suite); + results.Add(c1); + BenchFramework.PrintResult(c1); + + // C2: SIMD only + var c2 = BenchFramework.Run( + () => SimdImplementations.AddFull_Float64(lhs, rhs, result, size), + "Single", "C2_SIMD", "float64", size, elementBytes, warmup, measure, Suite); + c2 = c2 with { SpeedupVsBaseline = c1.MeanUs / c2.MeanUs }; + results.Add(c2); + BenchFramework.PrintResult(c2); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(rhs); + SimdImplementations.FreeAligned(result); + + return results; + } + + /// + /// Test chained operations: a + b + c + d + /// Compare naive (4 allocations) vs pooled (1 allocation reused). + /// + public static List TestChainedOperations(int size, int warmup, int measure) + { + var results = new List(); + int elementBytes = 8; + + var a = SimdImplementations.AllocateAligned(size); + var b = SimdImplementations.AllocateAligned(size); + var c = SimdImplementations.AllocateAligned(size); + var d = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(a, size, 42); + SimdImplementations.FillRandom(b, size, 43); + SimdImplementations.FillRandom(c, size, 44); + SimdImplementations.FillRandom(d, size, 45); + + // Baseline: Scalar with allocations + var baseline = BenchFramework.RunWithSetup( + () => { }, // No setup needed + () => + { + var t1 = new double[size]; + var t2 = new double[size]; + var result = new double[size]; + + fixed (double* pt1 = t1, pt2 = t2, pr = result) + { + SimdImplementations.AddScalarLoop_Float64(a, b, pt1, size); + SimdImplementations.AddScalarLoop_Float64(pt1, c, pt2, size); + SimdImplementations.AddScalarLoop_Float64(pt2, d, pr, size); + } + }, + "Chained", "0_ScalarAlloc", "float64", size, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + // C1: SIMD with new allocations each time + var c1 = BenchFramework.RunWithSetup( + () => { }, + () => + { + var t1 = new double[size]; + var t2 = new double[size]; + var result = new double[size]; + + fixed (double* pt1 = t1, pt2 = t2, pr = result) + { + SimdImplementations.AddFull_Float64(a, b, pt1, size); + SimdImplementations.AddFull_Float64(pt1, c, pt2, size); + SimdImplementations.AddFull_Float64(pt2, d, pr, size); + } + }, + "Chained", "C1_SimdAlloc", "float64", size, elementBytes, warmup, measure, Suite); + c1 = c1 with { SpeedupVsBaseline = baseline.MeanUs / c1.MeanUs }; + results.Add(c1); + BenchFramework.PrintResult(c1); + + // C2: SIMD with pre-allocated buffers (simulates NumSharp output allocation) + var t1Pre = SimdImplementations.AllocateAligned(size); + var t2Pre = SimdImplementations.AllocateAligned(size); + var resultPre = SimdImplementations.AllocateAligned(size); + + var c2 = BenchFramework.Run( + () => + { + SimdImplementations.AddFull_Float64(a, b, t1Pre, size); + SimdImplementations.AddFull_Float64(t1Pre, c, t2Pre, size); + SimdImplementations.AddFull_Float64(t2Pre, d, resultPre, size); + }, + "Chained", "C2_SimdPreAlloc", "float64", size, elementBytes, warmup, measure, Suite); + c2 = c2 with { SpeedupVsBaseline = baseline.MeanUs / c2.MeanUs }; + results.Add(c2); + BenchFramework.PrintResult(c2); + + // C3: SIMD with ArrayPool + var c3 = BenchFramework.Run( + () => + { + var pool = ArrayPool.Shared; + var t1Arr = pool.Rent(size); + var t2Arr = pool.Rent(size); + var resultArr = pool.Rent(size); + + fixed (double* pt1 = t1Arr, pt2 = t2Arr, pr = resultArr) + { + SimdImplementations.AddFull_Float64(a, b, pt1, size); + SimdImplementations.AddFull_Float64(pt1, c, pt2, size); + SimdImplementations.AddFull_Float64(pt2, d, pr, size); + } + + pool.Return(t1Arr); + pool.Return(t2Arr); + pool.Return(resultArr); + }, + "Chained", "C3_SimdPool", "float64", size, elementBytes, warmup, measure, Suite); + c3 = c3 with { SpeedupVsBaseline = baseline.MeanUs / c3.MeanUs }; + results.Add(c3); + BenchFramework.PrintResult(c3); + + // C4: SIMD with single buffer reuse (ping-pong) + var buf1 = SimdImplementations.AllocateAligned(size); + var buf2 = SimdImplementations.AllocateAligned(size); + + var c4 = BenchFramework.Run( + () => + { + SimdImplementations.AddFull_Float64(a, b, buf1, size); + SimdImplementations.AddFull_Float64(buf1, c, buf2, size); + SimdImplementations.AddFull_Float64(buf2, d, buf1, size); + // Result is in buf1 + }, + "Chained", "C4_PingPong", "float64", size, elementBytes, warmup, measure, Suite); + c4 = c4 with { SpeedupVsBaseline = baseline.MeanUs / c4.MeanUs }; + results.Add(c4); + BenchFramework.PrintResult(c4); + + SimdImplementations.FreeAligned(a); + SimdImplementations.FreeAligned(b); + SimdImplementations.FreeAligned(c); + SimdImplementations.FreeAligned(d); + SimdImplementations.FreeAligned(t1Pre); + SimdImplementations.FreeAligned(t2Pre); + SimdImplementations.FreeAligned(resultPre); + SimdImplementations.FreeAligned(buf1); + SimdImplementations.FreeAligned(buf2); + + return results; + } + + /// + /// Test in-place operations (a += b). + /// + public static List TestInPlaceOperations(int size, int warmup, int measure) + { + var results = new List(); + int elementBytes = 8; + + var a = SimdImplementations.AllocateAligned(size); + var b = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(b, size, 43); + + // Baseline: Out-of-place scalar + var baseline = BenchFramework.RunWithSetup( + () => SimdImplementations.FillRandom(a, size, 42), + () => SimdImplementations.AddScalarLoop_Float64(a, b, result, size), + "InPlace", "0_OutOfPlace", "float64", size, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + // C1: In-place scalar (a += b) + var c1 = BenchFramework.RunWithSetup( + () => SimdImplementations.FillRandom(a, size, 42), + () => AddInPlace_Scalar(a, b, size), + "InPlace", "C1_InPlace", "float64", size, elementBytes, warmup, measure, Suite); + c1 = c1 with { SpeedupVsBaseline = baseline.MeanUs / c1.MeanUs }; + results.Add(c1); + BenchFramework.PrintResult(c1); + + // C2: Out-of-place SIMD + var c2 = BenchFramework.RunWithSetup( + () => SimdImplementations.FillRandom(a, size, 42), + () => SimdImplementations.AddFull_Float64(a, b, result, size), + "InPlace", "C2_SimdOut", "float64", size, elementBytes, warmup, measure, Suite); + c2 = c2 with { SpeedupVsBaseline = baseline.MeanUs / c2.MeanUs }; + results.Add(c2); + BenchFramework.PrintResult(c2); + + // C3: In-place SIMD (a += b) + var c3 = BenchFramework.RunWithSetup( + () => SimdImplementations.FillRandom(a, size, 42), + () => AddInPlace_Simd(a, b, size), + "InPlace", "C3_SimdIn", "float64", size, elementBytes, warmup, measure, Suite); + c3 = c3 with { SpeedupVsBaseline = baseline.MeanUs / c3.MeanUs }; + results.Add(c3); + BenchFramework.PrintResult(c3); + + SimdImplementations.FreeAligned(a); + SimdImplementations.FreeAligned(b); + SimdImplementations.FreeAligned(result); + + return results; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void AddInPlace_Scalar(double* a, double* b, int count) + { + for (int i = 0; i < count; i++) + { + a[i] += b[i]; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AddInPlace_Simd(double* a, double* b, int count) + { + // In-place: a += b, so result goes back to a + SimdImplementations.AddFull_Float64(a, b, a, count); + } + + /// + /// Test ArrayPool overhead specifically. + /// + public static List TestPoolOverhead(int size, int iterations, int warmup, int measure) + { + var results = new List(); + + BenchFramework.PrintDivider($"ArrayPool Overhead (size={size:N0}, iterations={iterations})"); + + // Baseline: New allocation each time + var baseline = BenchFramework.Run( + () => + { + for (int i = 0; i < iterations; i++) + { + var arr = new double[size]; + // Touch array to ensure allocation + arr[0] = 1.0; + arr[size - 1] = 1.0; + } + }, + "PoolOverhead", "New", "float64", size, 8, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + // ArrayPool + var pool = ArrayPool.Shared; + var pooled = BenchFramework.Run( + () => + { + for (int i = 0; i < iterations; i++) + { + var arr = pool.Rent(size); + arr[0] = 1.0; + arr[size - 1] = 1.0; + pool.Return(arr); + } + }, + "PoolOverhead", "ArrayPool", "float64", size, 8, warmup, measure, Suite); + pooled = pooled with { SpeedupVsBaseline = baseline.MeanUs / pooled.MeanUs }; + results.Add(pooled); + BenchFramework.PrintResult(pooled); + + return results; + } +} diff --git a/benchmark/NumSharp.Benchmark.Exploration/Isolated/DispatchOverhead.cs b/benchmark/NumSharp.Benchmark.Exploration/Isolated/DispatchOverhead.cs new file mode 100644 index 000000000..a437de5e3 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Exploration/Isolated/DispatchOverhead.cs @@ -0,0 +1,303 @@ +using System.Runtime.CompilerServices; +using NumSharp.Benchmark.Exploration.Infrastructure; + +namespace NumSharp.Benchmark.Exploration.Isolated; + +/// +/// Measure the overhead of different dispatch mechanisms. +/// Goal: Determine acceptable dispatch overhead budget. +/// +public static unsafe class DispatchOverhead +{ + private const string Suite = "DispatchOverhead"; + + /// + /// Run all dispatch overhead benchmarks. + /// + public static List RunAll(bool quick = false) + { + var results = new List(); + var warmup = quick ? 3 : BenchFramework.DefaultWarmup; + var measure = quick ? 15 : 30; // More iterations for small overhead measurement + + var sizes = quick + ? new[] { 1_000, 100_000 } + : new[] { 100, 1_000, 10_000, 100_000, 1_000_000 }; + + BenchFramework.PrintHeader($"{Suite}: Dispatch Mechanism Overhead"); + + foreach (var size in sizes) + { + BenchFramework.PrintDivider($"Size: {size:N0}"); + results.AddRange(MeasureDispatchOverhead(size, warmup, measure)); + } + + OutputFormatters.PrintSummary(results); + return results; + } + + /// + /// Measure overhead of various dispatch mechanisms. + /// + public static List MeasureDispatchOverhead(int size, int warmup, int measure) + { + var results = new List(); + int elementBytes = 8; + + var lhs = SimdImplementations.AllocateAligned(size); + var rhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + SimdImplementations.FillRandom(rhs, size, 43); + + // Test 1: Direct function call (baseline) + var baseline = BenchFramework.Run( + () => SimdImplementations.AddFull_Float64(lhs, rhs, result, size), + "Dispatch", "1_Direct", "float64", size, elementBytes, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + // Test 2: Single if/else dispatch + var ifElse = BenchFramework.Run( + () => DispatchIfElse(lhs, rhs, result, size, isContiguous: true), + "Dispatch", "2_IfElse", "float64", size, elementBytes, warmup, measure, Suite); + ifElse = ifElse with { SpeedupVsBaseline = baseline.MeanUs / ifElse.MeanUs }; + results.Add(ifElse); + BenchFramework.PrintResult(ifElse); + + // Test 3: Nested if/else dispatch (simulate shape checks) + var nested = BenchFramework.Run( + () => DispatchNested(lhs, rhs, result, size, isContiguous: true, isBroadcast: false, isScalar: false), + "Dispatch", "3_Nested", "float64", size, elementBytes, warmup, measure, Suite); + nested = nested with { SpeedupVsBaseline = baseline.MeanUs / nested.MeanUs }; + results.Add(nested); + BenchFramework.PrintResult(nested); + + // Test 4: Switch dispatch + var switchDisp = BenchFramework.Run( + () => DispatchSwitch(lhs, rhs, result, size, scenario: 0), + "Dispatch", "4_Switch", "float64", size, elementBytes, warmup, measure, Suite); + switchDisp = switchDisp with { SpeedupVsBaseline = baseline.MeanUs / switchDisp.MeanUs }; + results.Add(switchDisp); + BenchFramework.PrintResult(switchDisp); + + // Test 5: Virtual method dispatch + IAddOperation operation = new SimdAddOperation(); + var virtualDisp = BenchFramework.Run( + () => operation.Execute(lhs, rhs, result, size), + "Dispatch", "5_Virtual", "float64", size, elementBytes, warmup, measure, Suite); + virtualDisp = virtualDisp with { SpeedupVsBaseline = baseline.MeanUs / virtualDisp.MeanUs }; + results.Add(virtualDisp); + BenchFramework.PrintResult(virtualDisp); + + // Test 6: Delegate invocation + AddDelegate del = SimdImplementations.AddFull_Float64; + var delegateDisp = BenchFramework.Run( + () => del(lhs, rhs, result, size), + "Dispatch", "6_Delegate", "float64", size, elementBytes, warmup, measure, Suite); + delegateDisp = delegateDisp with { SpeedupVsBaseline = baseline.MeanUs / delegateDisp.MeanUs }; + results.Add(delegateDisp); + BenchFramework.PrintResult(delegateDisp); + + // Test 7: Function pointer + delegate* managed funcPtr = &SimdImplementations.AddFull_Float64; + var funcPtrDisp = BenchFramework.Run( + () => funcPtr(lhs, rhs, result, size), + "Dispatch", "7_FuncPtr", "float64", size, elementBytes, warmup, measure, Suite); + funcPtrDisp = funcPtrDisp with { SpeedupVsBaseline = baseline.MeanUs / funcPtrDisp.MeanUs }; + results.Add(funcPtrDisp); + BenchFramework.PrintResult(funcPtrDisp); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(rhs); + SimdImplementations.FreeAligned(result); + + return results; + } + + #region Dispatch Implementations + + private delegate void AddDelegate(double* lhs, double* rhs, double* result, int count); + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void DispatchIfElse(double* lhs, double* rhs, double* result, int size, bool isContiguous) + { + if (isContiguous) + { + SimdImplementations.AddFull_Float64(lhs, rhs, result, size); + } + else + { + SimdImplementations.AddScalarLoop_Float64(lhs, rhs, result, size); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void DispatchNested(double* lhs, double* rhs, double* result, int size, + bool isContiguous, bool isBroadcast, bool isScalar) + { + if (isScalar) + { + // Scalar path (not used in this test) + SimdImplementations.AddScalar_Float64(lhs, 0.0, result, size); + } + else if (isContiguous && !isBroadcast) + { + SimdImplementations.AddFull_Float64(lhs, rhs, result, size); + } + else if (isBroadcast) + { + // Broadcast path (not used in this test) + SimdImplementations.AddScalarLoop_Float64(lhs, rhs, result, size); + } + else + { + SimdImplementations.AddScalarLoop_Float64(lhs, rhs, result, size); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void DispatchSwitch(double* lhs, double* rhs, double* result, int size, int scenario) + { + switch (scenario) + { + case 0: // S1: Contiguous + SimdImplementations.AddFull_Float64(lhs, rhs, result, size); + break; + case 1: // S2: Scalar broadcast + SimdImplementations.AddScalar_Float64(lhs, 0.0, result, size); + break; + case 2: // S4: Row broadcast + SimdImplementations.AddScalarLoop_Float64(lhs, rhs, result, size); + break; + default: + SimdImplementations.AddScalarLoop_Float64(lhs, rhs, result, size); + break; + } + } + + private interface IAddOperation + { + void Execute(double* lhs, double* rhs, double* result, int size); + } + + private class SimdAddOperation : IAddOperation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Execute(double* lhs, double* rhs, double* result, int size) + { + SimdImplementations.AddFull_Float64(lhs, rhs, result, size); + } + } + + #endregion + + /// + /// Measure overhead of property checks (simulated shape properties). + /// + public static List MeasurePropertyCheckOverhead(int iterations, int warmup, int measure) + { + var results = new List(); + + BenchFramework.PrintDivider("Property Check Overhead"); + + // Simulate shape-like object with properties + var shape = new SimulatedShape(1000, 1000, isContiguous: true, isBroadcast: false); + + // Test 1: No property checks (baseline) + bool result1 = false; + var baseline = BenchFramework.Run( + () => + { + for (int i = 0; i < iterations; i++) + { + result1 = true; // Just assign + } + }, + "PropCheck", "0_None", "N/A", iterations, 1, warmup, measure, Suite); + results.Add(baseline); + BenchFramework.PrintResult(baseline); + + // Test 2: Single property check + var single = BenchFramework.Run( + () => + { + for (int i = 0; i < iterations; i++) + { + result1 = shape.IsContiguous; + } + }, + "PropCheck", "1_Single", "N/A", iterations, 1, warmup, measure, Suite); + single = single with { SpeedupVsBaseline = baseline.MeanUs / single.MeanUs }; + results.Add(single); + BenchFramework.PrintResult(single); + + // Test 3: Multiple property checks + var multi = BenchFramework.Run( + () => + { + for (int i = 0; i < iterations; i++) + { + result1 = shape.IsContiguous && !shape.IsBroadcast && shape.Size > 0; + } + }, + "PropCheck", "2_Multi", "N/A", iterations, 1, warmup, measure, Suite); + multi = multi with { SpeedupVsBaseline = baseline.MeanUs / multi.MeanUs }; + results.Add(multi); + BenchFramework.PrintResult(multi); + + // Test 4: Computed property + var computed = BenchFramework.Run( + () => + { + for (int i = 0; i < iterations; i++) + { + result1 = shape.IsContiguousComputed; + } + }, + "PropCheck", "3_Computed", "N/A", iterations, 1, warmup, measure, Suite); + computed = computed with { SpeedupVsBaseline = baseline.MeanUs / computed.MeanUs }; + results.Add(computed); + BenchFramework.PrintResult(computed); + + // Keep result to prevent optimization + _ = result1; + + return results; + } + + private class SimulatedShape + { + private readonly int[] _dimensions; + private readonly int[] _strides; + private readonly bool _isContiguous; + private readonly bool _isBroadcast; + + public SimulatedShape(int rows, int cols, bool isContiguous, bool isBroadcast) + { + _dimensions = [rows, cols]; + _strides = [cols, 1]; + _isContiguous = isContiguous; + _isBroadcast = isBroadcast; + } + + public bool IsContiguous => _isContiguous; + public bool IsBroadcast => _isBroadcast; + public int Size => _dimensions[0] * _dimensions[1]; + + // Computed property that checks strides + public bool IsContiguousComputed + { + get + { + int expected = 1; + for (int i = _dimensions.Length - 1; i >= 0; i--) + { + if (_strides[i] != expected) return false; + expected *= _dimensions[i]; + } + return true; + } + } + } +} diff --git a/benchmark/NumSharp.Benchmark.Exploration/Isolated/MemoryPatterns.cs b/benchmark/NumSharp.Benchmark.Exploration/Isolated/MemoryPatterns.cs new file mode 100644 index 000000000..6006ea5e9 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Exploration/Isolated/MemoryPatterns.cs @@ -0,0 +1,333 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +using NumSharp.Benchmark.Exploration.Infrastructure; + +namespace NumSharp.Benchmark.Exploration.Isolated; + +/// +/// Test memory access patterns and cache behavior. +/// Investigates when gather/scatter and prefetch help. +/// +public static unsafe class MemoryPatterns +{ + private const string Suite = "MemoryPatterns"; + + /// + /// Run all memory pattern tests. + /// + public static List RunAll(bool quick = false) + { + var results = new List(); + var warmup = quick ? 2 : BenchFramework.DefaultWarmup; + var measure = quick ? 5 : BenchFramework.DefaultMeasure; + + var sizes = quick + ? new[] { 100_000, 1_000_000 } + : new[] { 10_000, 100_000, 1_000_000, 10_000_000 }; + + BenchFramework.PrintHeader($"{Suite}: Memory Access Patterns & Cache Behavior"); + + // Test 1: Strided access patterns + foreach (var size in sizes) + { + results.AddRange(TestStridedAccess(size, warmup, measure)); + } + + // Test 2: Gather vs Copy-then-SIMD + foreach (var size in sizes) + { + results.AddRange(TestGatherVsCopy(size, warmup, measure)); + } + + OutputFormatters.PrintSummary(results); + return results; + } + + /// + /// Test strided access performance degradation. + /// + public static List TestStridedAccess(int totalElements, int warmup, int measure) + { + var results = new List(); + int elementBytes = 8; + + BenchFramework.PrintDivider($"Strided Access: {totalElements:N0} total elements"); + + var strides = new[] { 1, 2, 4, 8, 16, 32, 64 }; + + foreach (var stride in strides) + { + // Allocate enough to hold strided access + int actualSize = totalElements * stride; + if (actualSize > 100_000_000) continue; // Skip if too large + + var src = SimdImplementations.AllocateAligned(actualSize); + var dst = SimdImplementations.AllocateAligned(totalElements); + SimdImplementations.FillRandom(src, actualSize, 42); + + // Measure strided read + sequential write + var result = BenchFramework.Run( + () => StridedRead(src, dst, totalElements, stride), + "Strided", $"Stride{stride}", "float64", totalElements, elementBytes, warmup, measure, Suite); + results.Add(result); + + // Calculate effective bandwidth + var seqBandwidth = results.FirstOrDefault(r => r.Strategy == "Stride1")?.GBps ?? result.GBps; + var efficiency = result.GBps / seqBandwidth; + Console.WriteLine($" Stride {stride,2}: {result.MeanUs,10:F2} us | {result.GBps,8:F2} GB/s | Efficiency: {efficiency * 100:F1}%"); + + SimdImplementations.FreeAligned(src); + SimdImplementations.FreeAligned(dst); + } + + return results; + } + + /// + /// Compare Gather intrinsic vs Copy-to-contiguous-then-SIMD. + /// + public static List TestGatherVsCopy(int totalElements, int warmup, int measure) + { + var results = new List(); + int elementBytes = 8; + + BenchFramework.PrintDivider($"Gather vs Copy: {totalElements:N0} elements"); + + // Test with stride=2 (every other element) + int stride = 2; + int actualSize = totalElements * stride; + + var src = SimdImplementations.AllocateAligned(actualSize); + var other = SimdImplementations.AllocateAligned(totalElements); + var result = SimdImplementations.AllocateAligned(totalElements); + var tempContiguous = SimdImplementations.AllocateAligned(totalElements); + SimdImplementations.FillRandom(src, actualSize, 42); + SimdImplementations.FillRandom(other, totalElements, 43); + + // Method 1: Scalar strided loop + var scalar = BenchFramework.Run( + () => StridedAdd_Scalar(src, other, result, totalElements, stride), + "GatherVsCopy", "1_Scalar", "float64", totalElements, elementBytes, warmup, measure, Suite); + results.Add(scalar); + BenchFramework.PrintResult(scalar); + + // Method 2: Copy to contiguous, then SIMD + var copySimd = BenchFramework.Run( + () => + { + // Copy strided to contiguous + for (int i = 0; i < totalElements; i++) + { + tempContiguous[i] = src[i * stride]; + } + // SIMD add + SimdImplementations.AddFull_Float64(tempContiguous, other, result, totalElements); + }, + "GatherVsCopy", "2_CopySimd", "float64", totalElements, elementBytes, warmup, measure, Suite); + copySimd = copySimd with { SpeedupVsBaseline = scalar.MeanUs / copySimd.MeanUs }; + results.Add(copySimd); + BenchFramework.PrintResult(copySimd); + + // Method 3: AVX2 Gather (if supported) + if (Avx2.IsSupported && totalElements >= 4) + { + var gather = BenchFramework.Run( + () => StridedAdd_Gather(src, other, result, totalElements, stride), + "GatherVsCopy", "3_Gather", "float64", totalElements, elementBytes, warmup, measure, Suite); + gather = gather with { SpeedupVsBaseline = scalar.MeanUs / gather.MeanUs }; + results.Add(gather); + BenchFramework.PrintResult(gather); + } + else + { + Console.WriteLine(" 3_Gather: AVX2 not supported"); + } + + SimdImplementations.FreeAligned(src); + SimdImplementations.FreeAligned(other); + SimdImplementations.FreeAligned(result); + SimdImplementations.FreeAligned(tempContiguous); + + return results; + } + + #region Implementation + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void StridedRead(double* src, double* dst, int count, int stride) + { + for (int i = 0; i < count; i++) + { + dst[i] = src[i * stride]; + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void StridedAdd_Scalar(double* strided, double* contiguous, double* result, int count, int stride) + { + for (int i = 0; i < count; i++) + { + result[i] = strided[i * stride] + contiguous[i]; + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void StridedAdd_Gather(double* strided, double* contiguous, double* result, int count, int stride) + { + // Using AVX2 GatherVector256 for double + // Each gather loads 4 doubles at specified indices + + int i = 0; + int vecSize = Vector256.Count; // 4 + + if (Avx2.IsSupported && count >= vecSize) + { + // Create index vector: [0, stride, 2*stride, 3*stride] * sizeof(double) + var indices = Vector256.Create(0, stride, stride * 2, stride * 3); + + int vectorCount = count - vecSize + 1; + for (; i < vectorCount; i += vecSize) + { + // Gather from strided source + var gathered = Avx2.GatherVector256(strided + i * stride, indices, 8); + + // Load contiguous + var cont = Avx.LoadVector256(contiguous + i); + + // Add + var sum = Avx.Add(gathered, cont); + + // Store + Avx.Store(result + i, sum); + } + } + + // Scalar tail + for (; i < count; i++) + { + result[i] = strided[i * stride] + contiguous[i]; + } + } + + #endregion + + /// + /// Test cache line effects. + /// + public static List TestCacheLines(int warmup, int measure) + { + var results = new List(); + + BenchFramework.PrintDivider("Cache Line Effects"); + + // Test accessing elements at different cache line boundaries + // Typical cache line is 64 bytes = 8 doubles + var sizes = new[] { 8, 16, 32, 64, 128, 256, 512 }; // Elements per "chunk" + + int totalIterations = 1_000_000; + + foreach (var chunkSize in sizes) + { + int totalElements = chunkSize * 1000; // 1000 chunks + var data = SimdImplementations.AllocateAligned(totalElements); + SimdImplementations.FillRandom(data, totalElements, 42); + + double sum = 0; + var result = BenchFramework.Run( + () => + { + sum = 0; + for (int chunk = 0; chunk < totalElements / chunkSize; chunk++) + { + // Access first element of each chunk + sum += data[chunk * chunkSize]; + } + }, + "CacheLine", $"Chunk{chunkSize}", "float64", totalIterations / chunkSize, 8, warmup, measure, Suite); + results.Add(result); + Console.WriteLine($" Chunk size {chunkSize,4}: {result.MeanUs,10:F2} us | sum={sum:F2}"); + + SimdImplementations.FreeAligned(data); + } + + return results; + } + + /// + /// Test non-temporal (streaming) stores. + /// + public static List TestNonTemporalStores(int size, int warmup, int measure) + { + var results = new List(); + int elementBytes = 8; + + BenchFramework.PrintDivider($"Non-Temporal Stores: {size:N0} elements"); + + var src = SimdImplementations.AllocateAligned(size); + var dst = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(src, size, 42); + + // Normal stores + var normal = BenchFramework.Run( + () => CopyNormal(src, dst, size), + "NTStore", "Normal", "float64", size, elementBytes, warmup, measure, Suite); + results.Add(normal); + BenchFramework.PrintResult(normal); + + // Non-temporal stores (streaming) + if (Avx2.IsSupported) + { + var nt = BenchFramework.Run( + () => CopyNonTemporal(src, dst, size), + "NTStore", "NonTemp", "float64", size, elementBytes, warmup, measure, Suite); + nt = nt with { SpeedupVsBaseline = normal.MeanUs / nt.MeanUs }; + results.Add(nt); + BenchFramework.PrintResult(nt); + } + + SimdImplementations.FreeAligned(src); + SimdImplementations.FreeAligned(dst); + + return results; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void CopyNormal(double* src, double* dst, int count) + { + int i = 0; + if (Avx2.IsSupported && count >= Vector256.Count) + { + int vectorCount = count - Vector256.Count + 1; + for (; i < vectorCount; i += Vector256.Count) + { + var v = Avx.LoadVector256(src + i); + Avx.Store(dst + i, v); + } + } + for (; i < count; i++) + { + dst[i] = src[i]; + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void CopyNonTemporal(double* src, double* dst, int count) + { + int i = 0; + if (Avx2.IsSupported && count >= Vector256.Count) + { + int vectorCount = count - Vector256.Count + 1; + for (; i < vectorCount; i += Vector256.Count) + { + var v = Avx.LoadVector256(src + i); + Avx.StoreAlignedNonTemporal(dst + i, v); + } + } + for (; i < count; i++) + { + dst[i] = src[i]; + } + } +} diff --git a/benchmark/NumSharp.Benchmark.Exploration/Isolated/SimdStrategies.cs b/benchmark/NumSharp.Benchmark.Exploration/Isolated/SimdStrategies.cs new file mode 100644 index 000000000..675874319 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Exploration/Isolated/SimdStrategies.cs @@ -0,0 +1,340 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +using NumSharp.Benchmark.Exploration.Infrastructure; + +namespace NumSharp.Benchmark.Exploration.Isolated; + +/// +/// Compare different SIMD strategies for row broadcast scenario. +/// This is the most complex common scenario where multiple strategies are viable. +/// +public static unsafe class SimdStrategies +{ + private const string Suite = "SimdStrategies"; + + /// + /// Run all strategy comparisons. + /// + public static List RunAll(bool quick = false) + { + var results = new List(); + var warmup = quick ? 2 : BenchFramework.DefaultWarmup; + var measure = quick ? 5 : BenchFramework.DefaultMeasure; + + // Test with different matrix shapes + var shapes = quick + ? new[] { (100, 100), (1000, 1000) } + : new[] { (100, 100), (316, 316), (500, 500), (1000, 1000), (3162, 3162) }; + + BenchFramework.PrintHeader($"{Suite}: Row Broadcast Strategy Comparison"); + + foreach (var (rows, cols) in shapes) + { + BenchFramework.PrintDivider($"Shape: ({rows}, {cols}) = {rows * cols:N0} elements"); + results.AddRange(CompareStrategies_Float64(rows, cols, warmup, measure)); + } + + OutputFormatters.PrintSummary(results); + return results; + } + + /// + /// Compare all strategies for row broadcast with float64. + /// matrix[M, N] + row[N] = result[M, N] + /// + public static List CompareStrategies_Float64(int rows, int cols, int warmup, int measure) + { + var results = new List(); + int size = rows * cols; + int elementBytes = 8; + + var matrix = SimdImplementations.AllocateAligned(size); + var row = SimdImplementations.AllocateAligned(cols); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(matrix, size, 42); + SimdImplementations.FillRandom(row, cols, 43); + + // Strategy 1: Pure scalar with GetOffset-like indexing + var s1 = BenchFramework.Run( + () => Strategy1_ScalarGetOffset(matrix, row, result, rows, cols), + "S4_rowBC", "1_ScalarOfs", "float64", size, elementBytes, warmup, measure, Suite); + results.Add(s1); + BenchFramework.PrintResult(s1); + + // Strategy 2: Nested loops with scalar inner + var s2 = BenchFramework.Run( + () => Strategy2_NestedScalar(matrix, row, result, rows, cols), + "S4_rowBC", "2_Nested", "float64", size, elementBytes, warmup, measure, Suite); + s2 = s2 with { SpeedupVsBaseline = s1.MeanUs / s2.MeanUs }; + results.Add(s2); + BenchFramework.PrintResult(s2); + + // Strategy 3: Nested loops with SIMD inner (SIMD-CHUNK) + var s3 = BenchFramework.Run( + () => Strategy3_NestedSimdInner(matrix, row, result, rows, cols), + "S4_rowBC", "3_SimdChunk", "float64", size, elementBytes, warmup, measure, Suite); + s3 = s3 with { SpeedupVsBaseline = s1.MeanUs / s3.MeanUs }; + results.Add(s3); + BenchFramework.PrintResult(s3); + + // Strategy 4: Pretend contiguous (incorrect but shows ceiling) + // This strategy is NOT correct for broadcasting but shows max SIMD throughput + var s4 = BenchFramework.Run( + () => Strategy4_FlatSimd(matrix, row, result, rows, cols), + "S4_rowBC", "4_FlatSimd*", "float64", size, elementBytes, warmup, measure, Suite); + s4 = s4 with { SpeedupVsBaseline = s1.MeanUs / s4.MeanUs, Notes = "INCORRECT - ceiling only" }; + results.Add(s4); + BenchFramework.PrintResult(s4); + + // Strategy 5: Copy row to temp buffer, use flat SIMD + var rowExpanded = SimdImplementations.AllocateAligned(size); + var s5 = BenchFramework.Run( + () => Strategy5_ExpandThenSimd(matrix, row, rowExpanded, result, rows, cols), + "S4_rowBC", "5_Expand", "float64", size, elementBytes, warmup, measure, Suite); + s5 = s5 with { SpeedupVsBaseline = s1.MeanUs / s5.MeanUs }; + results.Add(s5); + BenchFramework.PrintResult(s5); + + // Strategy 6: Unrolled SIMD inner loop + var s6 = BenchFramework.Run( + () => Strategy6_UnrolledSimdInner(matrix, row, result, rows, cols), + "S4_rowBC", "6_Unrolled", "float64", size, elementBytes, warmup, measure, Suite); + s6 = s6 with { SpeedupVsBaseline = s1.MeanUs / s6.MeanUs }; + results.Add(s6); + BenchFramework.PrintResult(s6); + + SimdImplementations.FreeAligned(matrix); + SimdImplementations.FreeAligned(row); + SimdImplementations.FreeAligned(result); + SimdImplementations.FreeAligned(rowExpanded); + + return results; + } + + #region Strategy Implementations + + /// + /// Strategy 1: Pure scalar with linear index calculation (simulates GetOffset). + /// + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Strategy1_ScalarGetOffset(double* matrix, double* row, double* result, int rows, int cols) + { + for (int i = 0; i < rows * cols; i++) + { + int c = i % cols; // Simulates GetOffset calculation + result[i] = matrix[i] + row[c]; + } + } + + /// + /// Strategy 2: Nested loops with direct indexing, scalar inner. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Strategy2_NestedScalar(double* matrix, double* row, double* result, int rows, int cols) + { + for (int r = 0; r < rows; r++) + { + var offset = r * cols; + for (int c = 0; c < cols; c++) + { + result[offset + c] = matrix[offset + c] + row[c]; + } + } + } + + /// + /// Strategy 3: Nested loops with SIMD inner (SIMD-CHUNK strategy). + /// + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Strategy3_NestedSimdInner(double* matrix, double* row, double* result, int rows, int cols) + { + for (int r = 0; r < rows; r++) + { + var matrixRow = matrix + r * cols; + var resultRow = result + r * cols; + + int c = 0; + if (Avx2.IsSupported && cols >= Vector256.Count) + { + int vectorCount = cols - Vector256.Count + 1; + for (; c < vectorCount; c += Vector256.Count) + { + var vm = Avx.LoadVector256(matrixRow + c); + var vr = Avx.LoadVector256(row + c); + var vres = Avx.Add(vm, vr); + Avx.Store(resultRow + c, vres); + } + } + + // Scalar tail + for (; c < cols; c++) + { + resultRow[c] = matrixRow[c] + row[c]; + } + } + } + + /// + /// Strategy 4: Flat SIMD ignoring broadcast (INCORRECT but shows ceiling). + /// This pretends both arrays are the same shape - shows max possible throughput. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Strategy4_FlatSimd(double* matrix, double* row, double* result, int rows, int cols) + { + // NOTE: This is INCORRECT for broadcasting - it ignores row repetition + // It's only here to show the maximum throughput ceiling + int size = rows * cols; + SimdImplementations.AddFull_Float64(matrix, matrix, result, size); // Using matrix twice + } + + /// + /// Strategy 5: Expand row to full matrix, then flat SIMD. + /// Trades memory for simpler SIMD loop. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Strategy5_ExpandThenSimd(double* matrix, double* row, double* rowExpanded, double* result, int rows, int cols) + { + // Step 1: Expand row to full matrix + for (int r = 0; r < rows; r++) + { + Buffer.MemoryCopy(row, rowExpanded + r * cols, cols * sizeof(double), cols * sizeof(double)); + } + + // Step 2: Flat SIMD add + SimdImplementations.AddFull_Float64(matrix, rowExpanded, result, rows * cols); + } + + /// + /// Strategy 6: Unrolled SIMD inner loop (2x unroll). + /// + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Strategy6_UnrolledSimdInner(double* matrix, double* row, double* result, int rows, int cols) + { + const int Unroll = 2; + int vectorSize = Vector256.Count; + int unrollSize = vectorSize * Unroll; + + for (int r = 0; r < rows; r++) + { + var matrixRow = matrix + r * cols; + var resultRow = result + r * cols; + + int c = 0; + + if (Avx2.IsSupported && cols >= unrollSize) + { + int vectorCount = cols - unrollSize + 1; + for (; c < vectorCount; c += unrollSize) + { + // Load 2 vectors from matrix + var vm0 = Avx.LoadVector256(matrixRow + c); + var vm1 = Avx.LoadVector256(matrixRow + c + vectorSize); + + // Load 2 vectors from row + var vr0 = Avx.LoadVector256(row + c); + var vr1 = Avx.LoadVector256(row + c + vectorSize); + + // Add + var vres0 = Avx.Add(vm0, vr0); + var vres1 = Avx.Add(vm1, vr1); + + // Store + Avx.Store(resultRow + c, vres0); + Avx.Store(resultRow + c + vectorSize, vres1); + } + } + + // Non-unrolled SIMD + if (Avx2.IsSupported) + { + int vectorCount = cols - vectorSize + 1; + for (; c < vectorCount; c += vectorSize) + { + var vm = Avx.LoadVector256(matrixRow + c); + var vr = Avx.LoadVector256(row + c); + var vres = Avx.Add(vm, vr); + Avx.Store(resultRow + c, vres); + } + } + + // Scalar tail + for (; c < cols; c++) + { + resultRow[c] = matrixRow[c] + row[c]; + } + } + } + + #endregion + + /// + /// Test Vector256 vs Vector128 performance. + /// + public static List CompareVectorWidths(int size, int warmup, int measure) + { + var results = new List(); + int elementBytes = 8; + + var lhs = SimdImplementations.AllocateAligned(size); + var rhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + SimdImplementations.FillRandom(rhs, size, 43); + + BenchFramework.PrintDivider($"Vector Width Comparison (size={size:N0})"); + + // Scalar baseline + var scalar = BenchFramework.Run( + () => SimdImplementations.AddScalarLoop_Float64(lhs, rhs, result, size), + "VecWidth", "Scalar", "float64", size, elementBytes, warmup, measure, Suite); + results.Add(scalar); + BenchFramework.PrintResult(scalar); + + // Vector128 + var v128 = BenchFramework.Run( + () => AddVector128(lhs, rhs, result, size), + "VecWidth", "Vector128", "float64", size, elementBytes, warmup, measure, Suite); + v128 = v128 with { SpeedupVsBaseline = scalar.MeanUs / v128.MeanUs }; + results.Add(v128); + BenchFramework.PrintResult(v128); + + // Vector256 + var v256 = BenchFramework.Run( + () => SimdImplementations.AddFull_Float64(lhs, rhs, result, size), + "VecWidth", "Vector256", "float64", size, elementBytes, warmup, measure, Suite); + v256 = v256 with { SpeedupVsBaseline = scalar.MeanUs / v256.MeanUs }; + results.Add(v256); + BenchFramework.PrintResult(v256); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(rhs); + SimdImplementations.FreeAligned(result); + + return results; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AddVector128(double* lhs, double* rhs, double* result, int count) + { + int i = 0; + + if (Sse2.IsSupported && count >= Vector128.Count) + { + int vectorCount = count - Vector128.Count + 1; + for (; i < vectorCount; i += Vector128.Count) + { + var va = Sse2.LoadVector128(lhs + i); + var vb = Sse2.LoadVector128(rhs + i); + var vr = Sse2.Add(va, vb); + Sse2.Store(result + i, vr); + } + } + + for (; i < count; i++) + { + result[i] = lhs[i] + rhs[i]; + } + } +} diff --git a/benchmark/NumSharp.Benchmark.Exploration/Isolated/SizeThresholds.cs b/benchmark/NumSharp.Benchmark.Exploration/Isolated/SizeThresholds.cs new file mode 100644 index 000000000..917372444 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Exploration/Isolated/SizeThresholds.cs @@ -0,0 +1,372 @@ +using System.Runtime.InteropServices; +using NumSharp.Benchmark.Exploration.Infrastructure; + +namespace NumSharp.Benchmark.Exploration.Isolated; + +/// +/// Discover size thresholds where SIMD starts helping. +/// Tests fine-grained sizes to find crossover points per dtype. +/// +public static unsafe class SizeThresholds +{ + private const string Suite = "SizeThresholds"; + + /// + /// Size range optimized for threshold discovery. + /// + public static readonly int[] ThresholdSizes = [ + 8, 16, 24, 32, 48, 64, 96, 128, + 192, 256, 384, 512, 768, 1024, + 1536, 2048, 3072, 4096, 6144, 8192, + 12288, 16384, 24576, 32768, 49152, 65536, + 98304, 131072 + ]; + + /// + /// Run threshold discovery for all dtypes. + /// + public static List RunAll(string[]? dtypes = null, bool quick = false) + { + dtypes ??= quick ? Dtypes.Common : Dtypes.All; + var sizes = quick ? ThresholdSizes.Where(s => s >= 32 && (s <= 1024 || s >= 16384)).ToArray() : ThresholdSizes; + var warmup = quick ? 2 : BenchFramework.DefaultWarmup; + var measure = quick ? 5 : BenchFramework.DefaultMeasure; + + var results = new List(); + + BenchFramework.PrintHeader($"{Suite}: SIMD Threshold Discovery"); + + foreach (var dtype in dtypes) + { + BenchFramework.PrintDivider($"dtype={dtype}"); + results.AddRange(FindThreshold(dtype, sizes, warmup, measure)); + } + + // Summary: find crossover points + PrintCrossoverSummary(results); + + return results; + } + + /// + /// Find the threshold where SIMD becomes faster for a specific dtype. + /// + public static List FindThreshold(string dtype, int[] sizes, int warmup, int measure) + { + var results = new List(); + var elementBytes = DtypeInfo.GetElementSize(dtype); + + switch (dtype.ToLowerInvariant()) + { + case "float64" or "double": + { + foreach (var size in sizes) + { + var lhs = SimdImplementations.AllocateAligned(size); + var rhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + SimdImplementations.FillRandom(rhs, size, 43); + + var baseline = BenchFramework.Run( + () => SimdImplementations.AddScalarLoop_Float64(lhs, rhs, result, size), + "Threshold", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddFull_Float64(lhs, rhs, result, size), + "Threshold", "SIMD", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + + results.Add(baseline); + results.Add(simd); + + // Compact output for threshold discovery + var winner = simd.SpeedupVsBaseline > 1.0 ? "SIMD" : "Scalar"; + var icon = simd.SpeedupVsBaseline > 1.0 ? "✓" : " "; + Console.WriteLine($" {size,8:N0} | Scalar: {baseline.MeanUs,10:F2} us | SIMD: {simd.MeanUs,10:F2} us | {simd.SpeedupVsBaseline,6:F2}x {icon}"); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(rhs); + SimdImplementations.FreeAligned(result); + } + break; + } + + case "float32" or "single" or "float": + { + foreach (var size in sizes) + { + var lhs = SimdImplementations.AllocateAligned(size); + var rhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + SimdImplementations.FillRandom(rhs, size, 43); + + var baseline = BenchFramework.Run( + () => SimdImplementations.AddScalarLoop_Float32(lhs, rhs, result, size), + "Threshold", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddFull_Float32(lhs, rhs, result, size), + "Threshold", "SIMD", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + + results.Add(baseline); + results.Add(simd); + + var icon = simd.SpeedupVsBaseline > 1.0 ? "✓" : " "; + Console.WriteLine($" {size,8:N0} | Scalar: {baseline.MeanUs,10:F2} us | SIMD: {simd.MeanUs,10:F2} us | {simd.SpeedupVsBaseline,6:F2}x {icon}"); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(rhs); + SimdImplementations.FreeAligned(result); + } + break; + } + + case "int32" or "int": + { + foreach (var size in sizes) + { + var lhs = SimdImplementations.AllocateAligned(size); + var rhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + SimdImplementations.FillRandom(rhs, size, 43); + + var baseline = BenchFramework.Run( + () => SimdImplementations.AddScalarLoop_Int32(lhs, rhs, result, size), + "Threshold", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddFull_Int32(lhs, rhs, result, size), + "Threshold", "SIMD", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + + results.Add(baseline); + results.Add(simd); + + var icon = simd.SpeedupVsBaseline > 1.0 ? "✓" : " "; + Console.WriteLine($" {size,8:N0} | Scalar: {baseline.MeanUs,10:F2} us | SIMD: {simd.MeanUs,10:F2} us | {simd.SpeedupVsBaseline,6:F2}x {icon}"); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(rhs); + SimdImplementations.FreeAligned(result); + } + break; + } + + case "int64" or "long": + { + foreach (var size in sizes) + { + var lhs = SimdImplementations.AllocateAligned(size); + var rhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + SimdImplementations.FillRandom(rhs, size, 43); + + var baseline = BenchFramework.Run( + () => SimdImplementations.AddScalarLoop_Int64(lhs, rhs, result, size), + "Threshold", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddFull_Int64(lhs, rhs, result, size), + "Threshold", "SIMD", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + + results.Add(baseline); + results.Add(simd); + + var icon = simd.SpeedupVsBaseline > 1.0 ? "✓" : " "; + Console.WriteLine($" {size,8:N0} | Scalar: {baseline.MeanUs,10:F2} us | SIMD: {simd.MeanUs,10:F2} us | {simd.SpeedupVsBaseline,6:F2}x {icon}"); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(rhs); + SimdImplementations.FreeAligned(result); + } + break; + } + + case "int16" or "short": + { + foreach (var size in sizes) + { + var lhs = SimdImplementations.AllocateAligned(size); + var rhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + SimdImplementations.FillRandom(rhs, size, 43); + + var baseline = BenchFramework.Run( + () => SimdImplementations.AddScalarLoop_Int16(lhs, rhs, result, size), + "Threshold", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddFull_Int16(lhs, rhs, result, size), + "Threshold", "SIMD", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + + results.Add(baseline); + results.Add(simd); + + var icon = simd.SpeedupVsBaseline > 1.0 ? "✓" : " "; + Console.WriteLine($" {size,8:N0} | Scalar: {baseline.MeanUs,10:F2} us | SIMD: {simd.MeanUs,10:F2} us | {simd.SpeedupVsBaseline,6:F2}x {icon}"); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(rhs); + SimdImplementations.FreeAligned(result); + } + break; + } + + case "byte" or "uint8": + { + foreach (var size in sizes) + { + var lhs = SimdImplementations.AllocateAligned(size); + var rhs = SimdImplementations.AllocateAligned(size); + var result = SimdImplementations.AllocateAligned(size); + SimdImplementations.FillRandom(lhs, size, 42); + SimdImplementations.FillRandom(rhs, size, 43); + + var baseline = BenchFramework.Run( + () => SimdImplementations.AddScalarLoop_Byte(lhs, rhs, result, size), + "Threshold", "Scalar", dtype, size, elementBytes, warmup, measure, Suite); + + var simd = BenchFramework.Run( + () => SimdImplementations.AddFull_Byte(lhs, rhs, result, size), + "Threshold", "SIMD", dtype, size, elementBytes, warmup, measure, Suite); + simd = simd with { SpeedupVsBaseline = baseline.MeanUs / simd.MeanUs }; + + results.Add(baseline); + results.Add(simd); + + var icon = simd.SpeedupVsBaseline > 1.0 ? "✓" : " "; + Console.WriteLine($" {size,8:N0} | Scalar: {baseline.MeanUs,10:F2} us | SIMD: {simd.MeanUs,10:F2} us | {simd.SpeedupVsBaseline,6:F2}x {icon}"); + + SimdImplementations.FreeAligned(lhs); + SimdImplementations.FreeAligned(rhs); + SimdImplementations.FreeAligned(result); + } + break; + } + } + + return results; + } + + /// + /// Analyze results to find crossover points. + /// + private static void PrintCrossoverSummary(List results) + { + Console.WriteLine(); + Console.WriteLine("=== Crossover Summary ==="); + Console.WriteLine(); + + var byDtype = results + .Where(r => r.Strategy == "SIMD" && r.SpeedupVsBaseline.HasValue) + .GroupBy(r => r.Dtype); + + foreach (var group in byDtype.OrderBy(g => g.Key)) + { + var ordered = group.OrderBy(r => r.Size).ToList(); + + // Find first size where SIMD is consistently faster + int? threshold = null; + int consecutiveWins = 0; + const int requiredWins = 2; // Require N consecutive wins to call it a threshold + + foreach (var r in ordered) + { + if (r.SpeedupVsBaseline > 1.05) // 5% margin to avoid noise + { + consecutiveWins++; + if (consecutiveWins >= requiredWins && threshold == null) + { + // Backtrack to find the first win in this streak + var idx = ordered.IndexOf(r) - requiredWins + 1; + threshold = ordered[idx].Size; + } + } + else + { + consecutiveWins = 0; + } + } + + // Find maximum speedup + var maxSpeedup = ordered.MaxBy(r => r.SpeedupVsBaseline); + var minSpeedup = ordered.MinBy(r => r.SpeedupVsBaseline); + + Console.WriteLine($"{group.Key,-10}: Threshold = {threshold?.ToString("N0") ?? "N/A",-8} | " + + $"Max speedup = {maxSpeedup?.SpeedupVsBaseline:F2}x at {maxSpeedup?.Size:N0} | " + + $"Min speedup = {minSpeedup?.SpeedupVsBaseline:F2}x at {minSpeedup?.Size:N0}"); + } + + Console.WriteLine(); + Console.WriteLine("Legend: Threshold = smallest size where SIMD is consistently >5% faster"); + } + + /// + /// Generate recommended threshold constants based on results. + /// + public static string GenerateThresholdConstants(List results) + { + var lines = new List + { + "/// ", + "/// SIMD threshold constants discovered empirically.", + "/// Use SIMD when element count >= threshold.", + "/// ", + "public static class SimdThresholds", + "{" + }; + + var byDtype = results + .Where(r => r.Strategy == "SIMD" && r.SpeedupVsBaseline.HasValue) + .GroupBy(r => r.Dtype); + + foreach (var group in byDtype.OrderBy(g => g.Key)) + { + var ordered = group.OrderBy(r => r.Size).ToList(); + int? threshold = null; + int consecutiveWins = 0; + + foreach (var r in ordered) + { + if (r.SpeedupVsBaseline > 1.05) + { + consecutiveWins++; + if (consecutiveWins >= 2 && threshold == null) + { + var idx = ordered.IndexOf(r) - 1; + threshold = ordered[Math.Max(0, idx)].Size; + } + } + else + { + consecutiveWins = 0; + } + } + + var dtypeName = group.Key switch + { + "byte" => "Byte", + "int16" => "Int16", + "int32" => "Int32", + "int64" => "Int64", + "float32" => "Float32", + "float64" => "Float64", + _ => group.Key + }; + + lines.Add($" public const int MinSizeForSimd_{dtypeName} = {threshold ?? 32};"); + } + + lines.Add("}"); + + return string.Join(Environment.NewLine, lines); + } +} diff --git a/benchmark/NumSharp.Benchmark.Exploration/NumSharp.Benchmark.Exploration.csproj b/benchmark/NumSharp.Benchmark.Exploration/NumSharp.Benchmark.Exploration.csproj new file mode 100644 index 000000000..c14709386 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Exploration/NumSharp.Benchmark.Exploration.csproj @@ -0,0 +1,29 @@ + + + + Exe + net8.0;net10.0 + enable + enable + true + x64 + true + NumSharp.Benchmark.Exploration + NumSharp.Benchmark.Exploration + + + + + false + false + + + + + + + + + + + diff --git a/benchmark/NumSharp.Benchmark.Exploration/Program.cs b/benchmark/NumSharp.Benchmark.Exploration/Program.cs new file mode 100644 index 000000000..e86da5fce --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Exploration/Program.cs @@ -0,0 +1,399 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using BenchmarkDotNet.Running; +using NumSharp.Benchmark.Exploration.Infrastructure; +using NumSharp.Benchmark.Exploration.Isolated; +using NumSharp.Benchmark.Exploration.Integration; + +namespace NumSharp.Benchmark.Exploration; + +/// +/// NumSharp SIMD & Broadcasting Performance Exploration Suite. +/// +/// Usage: +/// dotnet run -c Release -- --suite broadcast-scenarios +/// dotnet run -c Release -- --all +/// dotnet run -c Release -- --quick +/// dotnet run -c Release -- --bdn BroadcastBenchmarks +/// +public class Program +{ + public static int Main(string[] args) + { + Console.WriteLine("╔═══════════════════════════════════════════════════════════════════════════════╗"); + Console.WriteLine("║ NumSharp SIMD & Broadcasting Performance Exploration Suite ║"); + Console.WriteLine("╚═══════════════════════════════════════════════════════════════════════════════╝"); + Console.WriteLine(); + + BenchFramework.PrintEnvironment(); + + // Parse arguments + var options = ParseArgs(args); + + if (options.ShowHelp) + { + PrintHelp(); + return 0; + } + + if (options.Interactive) + { + return RunInteractive(options); + } + + return RunSuites(options); + } + + private static int RunInteractive(Options options) + { + Console.WriteLine("Select benchmark suite:"); + Console.WriteLine(); + Console.WriteLine("=== Isolated Benchmarks (Raw SIMD) ==="); + Console.WriteLine("1. Broadcast Scenarios (S1-S7)"); + Console.WriteLine("2. Size Thresholds (crossover discovery)"); + Console.WriteLine("3. SIMD Strategies (row broadcast comparison)"); + Console.WriteLine("4. Dispatch Overhead"); + Console.WriteLine("5. Combined Optimizations (SIMD+Pool+InPlace)"); + Console.WriteLine("6. Memory Patterns (strided, gather)"); + Console.WriteLine(); + Console.WriteLine("=== Integration Benchmarks (NumSharp) ==="); + Console.WriteLine("7. NumSharp Broadcasting"); + Console.WriteLine("8. NumSharp vs Raw SIMD Overhead"); + Console.WriteLine(); + Console.WriteLine("=== Meta Options ==="); + Console.WriteLine("A. All Isolated Benchmarks"); + Console.WriteLine("I. All Integration Benchmarks"); + Console.WriteLine("Q. Quick smoke test"); + Console.WriteLine("B. BenchmarkDotNet (full validation)"); + Console.WriteLine(); + Console.Write("Select: "); + + var choice = Console.ReadLine()?.Trim().ToUpperInvariant(); + + switch (choice) + { + case "1": options.Suite = "broadcast-scenarios"; break; + case "2": options.Suite = "size-thresholds"; break; + case "3": options.Suite = "simd-strategies"; break; + case "4": options.Suite = "dispatch"; break; + case "5": options.Suite = "combined"; break; + case "6": options.Suite = "memory"; break; + case "7": options.Suite = "numsharp-broadcast"; break; + case "8": options.Suite = "numsharp-overhead"; break; + case "A": options.Suite = "all-isolated"; break; + case "I": options.Suite = "all-integration"; break; + case "Q": options.Suite = "all-isolated"; options.Quick = true; break; + case "B": options.UseBenchmarkDotNet = true; break; + default: options.Suite = "all-isolated"; break; + } + + return RunSuites(options); + } + + private static int RunSuites(Options options) + { + if (options.UseBenchmarkDotNet) + { + // Run BenchmarkDotNet + BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(options.RemainingArgs); + return 0; + } + + var allResults = new List(); + var timestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"); + + try + { + switch (options.Suite.ToLowerInvariant()) + { + case "broadcast-scenarios": + allResults.AddRange(BroadcastScenarios.RunAll( + options.GetSizes(), options.GetDtypes(), options.Quick)); + break; + + case "size-thresholds": + allResults.AddRange(SizeThresholds.RunAll(options.GetDtypes(), options.Quick)); + break; + + case "simd-strategies": + allResults.AddRange(SimdStrategies.RunAll(options.Quick)); + break; + + case "dispatch": + allResults.AddRange(DispatchOverhead.RunAll(options.Quick)); + break; + + case "combined": + allResults.AddRange(CombinedOptimizations.RunAll(options.Quick)); + break; + + case "memory": + allResults.AddRange(MemoryPatterns.RunAll(options.Quick)); + break; + + case "numsharp-broadcast": + allResults.AddRange(NumSharpBroadcast.RunAll(options.Quick)); + break; + + case "numsharp-overhead": + foreach (var size in options.GetSizes()) + { + allResults.AddRange(NumSharpBroadcast.CompareOverhead(size, 3, 10)); + } + break; + + case "all-isolated": + Console.WriteLine("Running ALL isolated benchmarks...\n"); + allResults.AddRange(BroadcastScenarios.RunAll(options.GetSizes(), options.GetDtypes(), options.Quick)); + allResults.AddRange(SizeThresholds.RunAll(options.GetDtypes(), options.Quick)); + allResults.AddRange(SimdStrategies.RunAll(options.Quick)); + allResults.AddRange(DispatchOverhead.RunAll(options.Quick)); + allResults.AddRange(CombinedOptimizations.RunAll(options.Quick)); + allResults.AddRange(MemoryPatterns.RunAll(options.Quick)); + break; + + case "all-integration": + Console.WriteLine("Running ALL integration benchmarks...\n"); + allResults.AddRange(NumSharpBroadcast.RunAll(options.Quick)); + foreach (var size in options.GetSizes()) + { + allResults.AddRange(NumSharpBroadcast.CompareOverhead(size, 3, 10)); + } + break; + + case "all": + Console.WriteLine("Running ALL benchmarks...\n"); + allResults.AddRange(BroadcastScenarios.RunAll(options.GetSizes(), options.GetDtypes(), options.Quick)); + allResults.AddRange(SizeThresholds.RunAll(options.GetDtypes(), options.Quick)); + allResults.AddRange(SimdStrategies.RunAll(options.Quick)); + allResults.AddRange(DispatchOverhead.RunAll(options.Quick)); + allResults.AddRange(CombinedOptimizations.RunAll(options.Quick)); + allResults.AddRange(MemoryPatterns.RunAll(options.Quick)); + allResults.AddRange(NumSharpBroadcast.RunAll(options.Quick)); + break; + + default: + Console.WriteLine($"Unknown suite: {options.Suite}"); + PrintHelp(); + return 1; + } + + // Export results + if (allResults.Any()) + { + var resultsDir = Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "Results"); + Directory.CreateDirectory(resultsDir); + + var csvPath = Path.Combine(resultsDir, $"{timestamp}_{options.Suite}.csv"); + var jsonPath = Path.Combine(resultsDir, $"{timestamp}_{options.Suite}.json"); + var mdPath = Path.Combine(resultsDir, $"{timestamp}_{options.Suite}.md"); + + OutputFormatters.ExportCsv(allResults, csvPath); + OutputFormatters.ExportJson(allResults, jsonPath); + + var resultSet = new BenchResultSet + { + SuiteName = options.Suite, + Description = $"SIMD & Broadcasting exploration - {options.Suite}", + StartTime = DateTime.UtcNow.AddSeconds(-allResults.Count * 0.5), // Approximate + CpuModel = GetCpuModel(), + DotNetVersion = RuntimeInformation.FrameworkDescription + }; + foreach (var r in allResults) resultSet.Add(r); + resultSet.EndTime = DateTime.UtcNow; + + OutputFormatters.ExportMarkdown(resultSet, mdPath); + + // If thresholds were run, generate threshold constants + if (options.Suite.Contains("threshold") || options.Suite == "all" || options.Suite == "all-isolated") + { + var thresholdResults = allResults.Where(r => r.Suite == "SizeThresholds").ToList(); + if (thresholdResults.Any()) + { + var constants = SizeThresholds.GenerateThresholdConstants(thresholdResults); + var constantsPath = Path.Combine(resultsDir, $"{timestamp}_thresholds.cs"); + File.WriteAllText(constantsPath, constants); + Console.WriteLine($"\nThreshold constants exported to: {constantsPath}"); + } + } + } + + Console.WriteLine("\n✓ Benchmark suite completed successfully."); + return 0; + } + catch (Exception ex) + { + Console.WriteLine($"\n✗ Error: {ex.Message}"); + Console.WriteLine(ex.StackTrace); + return 1; + } + } + + private static Options ParseArgs(string[] args) + { + var options = new Options(); + var remaining = new List(); + + for (int i = 0; i < args.Length; i++) + { + switch (args[i].ToLowerInvariant()) + { + case "--help" or "-h": + options.ShowHelp = true; + break; + + case "--suite" or "-s": + if (i + 1 < args.Length) + options.Suite = args[++i]; + break; + + case "--quick" or "-q": + options.Quick = true; + break; + + case "--all" or "-a": + options.Suite = "all"; + break; + + case "--bdn": + options.UseBenchmarkDotNet = true; + remaining.AddRange(args.Skip(i + 1)); + i = args.Length; // Stop parsing + break; + + case "--dtypes": + if (i + 1 < args.Length) + options.Dtypes = args[++i]; + break; + + case "--sizes": + if (i + 1 < args.Length) + options.Sizes = args[++i]; + break; + + case "--output" or "-o": + if (i + 1 < args.Length) + options.OutputPath = args[++i]; + break; + + default: + if (!args[i].StartsWith("-")) + options.Suite = args[i]; + else + remaining.Add(args[i]); + break; + } + } + + options.RemainingArgs = remaining.ToArray(); + + // If no suite specified and no args, go interactive + if (string.IsNullOrEmpty(options.Suite) && args.Length == 0) + { + options.Interactive = true; + } + + return options; + } + + private static void PrintHelp() + { + Console.WriteLine(@" +Usage: dotnet run -c Release -- [options] [suite] + +Options: + --help, -h Show this help + --suite, -s NAME Run specific suite + --quick, -q Quick mode (fewer iterations, smaller sizes) + --all, -a Run all suites + --bdn Use BenchmarkDotNet (followed by BDN args) + --dtypes TYPE Dtype filter: common (default), all + --sizes SIZE Size filter: quick, standard (default), all + --output, -o PATH Output file path + +Suites: + broadcast-scenarios All 7 broadcasting scenarios (S1-S7) + size-thresholds SIMD crossover point discovery + simd-strategies Row broadcast strategy comparison + dispatch Dispatch mechanism overhead + combined SIMD + Pool + InPlace combinations + memory Memory access patterns + numsharp-broadcast NumSharp integration tests + numsharp-overhead NumSharp vs raw SIMD overhead + all-isolated All isolated (raw SIMD) benchmarks + all-integration All NumSharp integration benchmarks + all Everything + +Examples: + dotnet run -c Release # Interactive menu + dotnet run -c Release -- broadcast-scenarios # Specific suite + dotnet run -c Release -- --quick --all # Quick full run + dotnet run -c Release -- --bdn *Broadcast* # BenchmarkDotNet filter +"); + } + + private static string GetCpuModel() + { + try + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + var psi = new ProcessStartInfo + { + FileName = "wmic", + Arguments = "cpu get name", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var proc = Process.Start(psi); + var output = proc?.StandardOutput.ReadToEnd() ?? ""; + var lines = output.Split('\n', StringSplitOptions.RemoveEmptyEntries); + if (lines.Length >= 2) + return lines[1].Trim(); + } + } + catch { } + + return "Unknown CPU"; + } + + private class Options + { + public string Suite { get; set; } = ""; + public bool Quick { get; set; } = false; + public bool ShowHelp { get; set; } = false; + public bool Interactive { get; set; } = false; + public bool UseBenchmarkDotNet { get; set; } = false; + public string Dtypes { get; set; } = "common"; + public string Sizes { get; set; } = "standard"; + public string OutputPath { get; set; } = ""; + public string[] RemainingArgs { get; set; } = []; + + public string[] GetDtypes() => Dtypes.ToLowerInvariant() switch + { + "all" => Exploration.Infrastructure.Dtypes.All, + _ => Exploration.Infrastructure.Dtypes.Common + }; + + public int[] GetSizes() => (Sizes.ToLowerInvariant(), Quick) switch + { + ("quick", _) or (_, true) => ArraySizes.Quick, + ("all", _) => ArraySizes.All, + _ => ArraySizes.Standard + }; + + public Options Clone() => new Options + { + Suite = Suite, + Quick = Quick, + ShowHelp = ShowHelp, + Interactive = Interactive, + UseBenchmarkDotNet = UseBenchmarkDotNet, + Dtypes = Dtypes, + Sizes = Sizes, + OutputPath = OutputPath, + RemainingArgs = RemainingArgs + }; + } +} diff --git a/benchmark/NumSharp.Benchmark.Exploration/Python/numpy_baseline.py b/benchmark/NumSharp.Benchmark.Exploration/Python/numpy_baseline.py new file mode 100644 index 000000000..b3516158f --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Exploration/Python/numpy_baseline.py @@ -0,0 +1,461 @@ +#!/usr/bin/env python3 +""" +NumPy baseline benchmarks for SIMD & Broadcasting investigation. + +This script runs the same benchmarks as the C# exploration suite to establish +NumPy performance baselines for comparison. + +Usage: + python numpy_baseline.py # All benchmarks + python numpy_baseline.py --suite broadcast # Specific suite + python numpy_baseline.py --quick # Quick mode + python numpy_baseline.py --output results.json # Export JSON +""" + +import argparse +import json +import time +import sys +from dataclasses import dataclass, asdict +from typing import List, Callable, Any +import numpy as np + +# Benchmark configuration +SEED = 42 +WARMUP = 3 +MEASURE = 10 +QUICK_MEASURE = 5 + +# Standard sizes matching C# ArraySizes +SIZES = { + 'tiny': 32, + 'small': 1_000, + 'medium': 100_000, + 'large': 1_000_000, + 'huge': 10_000_000, + 'massive': 100_000_000, +} + +STANDARD_SIZES = [SIZES['small'], SIZES['medium'], SIZES['large'], SIZES['huge']] +QUICK_SIZES = [SIZES['medium'], SIZES['huge']] + +# Dtypes matching C# Dtypes +DTYPES = { + 'byte': np.uint8, + 'int16': np.int16, + 'int32': np.int32, + 'int64': np.int64, + 'float32': np.float32, + 'float64': np.float64, +} + +COMMON_DTYPES = ['int32', 'float64'] +ALL_DTYPES = list(DTYPES.keys()) + + +@dataclass +class BenchResult: + scenario: str + strategy: str + dtype: str + size: int + mean_us: float + stddev_us: float + min_us: float + max_us: float + gbps: float + reps: int + timestamp: str + suite: str = "" + notes: str = "" + speedup_vs_baseline: float = None + + +def benchmark(func: Callable, size: int, element_bytes: int, + warmup: int = WARMUP, measure: int = MEASURE) -> tuple: + """Run a benchmark with warmup and measurement phases.""" + # Warmup + for _ in range(warmup): + func() + + # Measure + times = [] + for _ in range(measure): + start = time.perf_counter() + func() + end = time.perf_counter() + times.append((end - start) * 1_000_000) # Convert to microseconds + + mean_us = np.mean(times) + stddev_us = np.std(times) + min_us = np.min(times) + max_us = np.max(times) + + # Calculate GB/s (read 2 inputs + write 1 output = 3 arrays) + total_bytes = size * element_bytes * 3 + seconds = mean_us / 1_000_000 + gbps = (total_bytes / 1e9) / seconds if seconds > 0 else 0 + + return mean_us, stddev_us, min_us, max_us, gbps + + +def print_header(title: str): + """Print formatted header.""" + print() + print("=" * 80) + print(f" {title}") + print("=" * 80) + print() + print(f"{'Scenario':<12} {'Strategy':<10} {'Dtype':<8} {'Size':>12} | {'Mean (us)':>12} ± {'StdDev':>8} | {'GB/s':>8}") + print("-" * 80) + + +def print_result(r: BenchResult): + """Print a single result.""" + speedup = f" ({r.speedup_vs_baseline:.2f}x)" if r.speedup_vs_baseline else "" + print(f"{r.scenario:<12} {r.strategy:<10} {r.dtype:<8} {r.size:>12,} | {r.mean_us:>12.2f} ± {r.stddev_us:>8.2f} | {r.gbps:>8.2f}{speedup}") + + +def run_broadcast_scenarios(sizes: List[int], dtypes: List[str], measure: int) -> List[BenchResult]: + """Run all 7 broadcasting scenarios.""" + results = [] + suite = "BroadcastScenarios" + + print_header(f"{suite}: NumPy Baseline") + + for dtype_name in dtypes: + print(f"\n--- dtype={dtype_name} ---") + dtype = DTYPES[dtype_name] + element_bytes = np.dtype(dtype).itemsize + + for size in sizes: + np.random.seed(SEED) + + # S1: Contiguous same shape + a = np.random.rand(size).astype(dtype) + b = np.random.rand(size).astype(dtype) + + mean, std, min_t, max_t, gbps = benchmark( + lambda: a + b, size, element_bytes, measure=measure) + + r = BenchResult( + scenario="S1_contiguous", + strategy="NumPy", + dtype=dtype_name, + size=size, + mean_us=mean, + stddev_us=std, + min_us=min_t, + max_us=max_t, + gbps=gbps, + reps=measure, + timestamp=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + suite=suite + ) + results.append(r) + print_result(r) + + # S2: Scalar broadcast + scalar = dtype(42.5) if np.issubdtype(dtype, np.floating) else dtype(42) + + mean, std, min_t, max_t, gbps = benchmark( + lambda: a + scalar, size, element_bytes, measure=measure) + + r = BenchResult( + scenario="S2_scalar", + strategy="NumPy", + dtype=dtype_name, + size=size, + mean_us=mean, + stddev_us=std, + min_us=min_t, + max_us=max_t, + gbps=gbps, + reps=measure, + timestamp=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + suite=suite + ) + results.append(r) + print_result(r) + + # S4: Row broadcast + rows = int(np.sqrt(size)) + cols = size // rows + actual_size = rows * cols + + matrix = np.random.rand(rows, cols).astype(dtype) + row = np.random.rand(cols).astype(dtype) + + mean, std, min_t, max_t, gbps = benchmark( + lambda: matrix + row, actual_size, element_bytes, measure=measure) + + r = BenchResult( + scenario="S4_rowBC", + strategy="NumPy", + dtype=dtype_name, + size=actual_size, + mean_us=mean, + stddev_us=std, + min_us=min_t, + max_us=max_t, + gbps=gbps, + reps=measure, + timestamp=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + suite=suite + ) + results.append(r) + print_result(r) + + # S5: Column broadcast + col = np.random.rand(rows, 1).astype(dtype) + + mean, std, min_t, max_t, gbps = benchmark( + lambda: matrix + col, actual_size, element_bytes, measure=measure) + + r = BenchResult( + scenario="S5_colBC", + strategy="NumPy", + dtype=dtype_name, + size=actual_size, + mean_us=mean, + stddev_us=std, + min_us=min_t, + max_us=max_t, + gbps=gbps, + reps=measure, + timestamp=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + suite=suite + ) + results.append(r) + print_result(r) + + return results + + +def run_size_thresholds(dtypes: List[str], measure: int) -> List[BenchResult]: + """Find performance crossover points at different sizes.""" + results = [] + suite = "SizeThresholds" + + sizes = [8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, + 16384, 32768, 65536, 131072] + + print_header(f"{suite}: NumPy Performance by Size") + + for dtype_name in dtypes: + print(f"\n--- dtype={dtype_name} ---") + dtype = DTYPES[dtype_name] + element_bytes = np.dtype(dtype).itemsize + + for size in sizes: + np.random.seed(SEED) + a = np.random.rand(size).astype(dtype) + b = np.random.rand(size).astype(dtype) + + mean, std, min_t, max_t, gbps = benchmark( + lambda: a + b, size, element_bytes, measure=measure) + + r = BenchResult( + scenario="Threshold", + strategy="NumPy", + dtype=dtype_name, + size=size, + mean_us=mean, + stddev_us=std, + min_us=min_t, + max_us=max_t, + gbps=gbps, + reps=measure, + timestamp=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + suite=suite + ) + results.append(r) + print(f" {size:>8,} | {mean:>10.2f} us | {gbps:>8.2f} GB/s") + + return results + + +def run_memory_patterns(sizes: List[int], measure: int) -> List[BenchResult]: + """Test strided access patterns.""" + results = [] + suite = "MemoryPatterns" + + print_header(f"{suite}: Strided Access Performance") + + for size in sizes: + print(f"\n--- Size: {size:,} ---") + + strides = [1, 2, 4, 8, 16, 32, 64] + + for stride in strides: + actual_size = size * stride + if actual_size > 100_000_000: + continue + + np.random.seed(SEED) + src = np.random.rand(actual_size) + dst = np.empty(size) + + def strided_copy(): + dst[:] = src[::stride] + + mean, std, min_t, max_t, gbps = benchmark( + strided_copy, size, 8, measure=measure) + + r = BenchResult( + scenario="Strided", + strategy=f"Stride{stride}", + dtype="float64", + size=size, + mean_us=mean, + stddev_us=std, + min_us=min_t, + max_us=max_t, + gbps=gbps, + reps=measure, + timestamp=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + suite=suite + ) + results.append(r) + print(f" Stride {stride:>2}: {mean:>10.2f} us | {gbps:>8.2f} GB/s") + + return results + + +def run_chained_operations(sizes: List[int], measure: int) -> List[BenchResult]: + """Test chained operations (a + b + c + d).""" + results = [] + suite = "ChainedOps" + + print_header(f"{suite}: Chained Operations (a+b+c+d)") + + for size in sizes: + print(f"\n--- Size: {size:,} ---") + + np.random.seed(SEED) + a = np.random.rand(size) + b = np.random.rand(size) + c = np.random.rand(size) + d = np.random.rand(size) + + # Standard chained add + mean, std, min_t, max_t, gbps = benchmark( + lambda: a + b + c + d, size, 8, measure=measure) + + r = BenchResult( + scenario="Chained", + strategy="NumPy", + dtype="float64", + size=size, + mean_us=mean, + stddev_us=std, + min_us=min_t, + max_us=max_t, + gbps=gbps, + reps=measure, + timestamp=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + suite=suite + ) + results.append(r) + print_result(r) + + # Using np.add.reduce + arr = np.stack([a, b, c, d]) + mean, std, min_t, max_t, gbps = benchmark( + lambda: np.sum(arr, axis=0), size, 8, measure=measure) + + r = BenchResult( + scenario="Chained", + strategy="np.sum", + dtype="float64", + size=size, + mean_us=mean, + stddev_us=std, + min_us=min_t, + max_us=max_t, + gbps=gbps, + reps=measure, + timestamp=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + suite=suite + ) + results.append(r) + print_result(r) + + return results + + +def print_summary(results: List[BenchResult]): + """Print summary statistics.""" + print() + print("=== Summary ===") + print(f"Total benchmarks: {len(results)}") + + by_scenario = {} + for r in results: + key = r.scenario + if key not in by_scenario: + by_scenario[key] = [] + by_scenario[key].append(r) + + print("\nBy scenario:") + for scenario, rs in sorted(by_scenario.items()): + avg_gbps = np.mean([r.gbps for r in rs]) + print(f" {scenario}: {len(rs)} tests, avg {avg_gbps:.2f} GB/s") + + +def export_json(results: List[BenchResult], filepath: str): + """Export results to JSON.""" + data = [asdict(r) for r in results] + with open(filepath, 'w') as f: + json.dump(data, f, indent=2) + print(f"\nJSON exported to: {filepath}") + + +def print_environment(): + """Print environment information.""" + print("Environment:") + print(f" Python: {sys.version.split()[0]}") + print(f" NumPy: {np.__version__}") + print(f" BLAS: {np.show_config(mode='dicts').get('Build Dependencies', {}).get('blas', 'unknown')}") + print() + + +def main(): + parser = argparse.ArgumentParser(description="NumPy baseline benchmarks") + parser.add_argument("--suite", choices=["broadcast", "thresholds", "memory", "chained", "all"], + default="all", help="Suite to run") + parser.add_argument("--quick", action="store_true", help="Quick mode (fewer iterations)") + parser.add_argument("--output", type=str, help="JSON output file") + parser.add_argument("--dtypes", type=str, default="common", + choices=["common", "all"], help="Dtypes to test") + + args = parser.parse_args() + + print_environment() + + sizes = QUICK_SIZES if args.quick else STANDARD_SIZES + dtypes = COMMON_DTYPES if args.dtypes == "common" else ALL_DTYPES + measure = QUICK_MEASURE if args.quick else MEASURE + + all_results = [] + + if args.suite in ["broadcast", "all"]: + all_results.extend(run_broadcast_scenarios(sizes, dtypes, measure)) + + if args.suite in ["thresholds", "all"]: + all_results.extend(run_size_thresholds(dtypes, measure)) + + if args.suite in ["memory", "all"]: + all_results.extend(run_memory_patterns(sizes, measure)) + + if args.suite in ["chained", "all"]: + all_results.extend(run_chained_operations(sizes, measure)) + + print_summary(all_results) + + if args.output: + export_json(all_results, args.output) + + +if __name__ == "__main__": + main() diff --git a/benchmark/NumSharp.Benchmark.Exploration/Results/.gitkeep b/benchmark/NumSharp.Benchmark.Exploration/Results/.gitkeep new file mode 100644 index 000000000..ce3745efe --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Exploration/Results/.gitkeep @@ -0,0 +1,2 @@ +# Results directory for benchmark outputs +# CSV, JSON, and Markdown reports will be saved here diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Allocation/AllocationMicroBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Allocation/AllocationMicroBenchmarks.cs new file mode 100644 index 000000000..e91e45b6f --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Allocation/AllocationMicroBenchmarks.cs @@ -0,0 +1,83 @@ +using System.Runtime.InteropServices; +using BenchmarkDotNet.Attributes; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Allocation; + +/// +/// Micro-benchmarks comparing allocation primitives: +/// - Marshal.AllocHGlobal (current) +/// - NativeMemory.Alloc (proposed) +/// - NativeMemory.AlignedAlloc (for SIMD) +/// +/// These benchmarks inform issue #528: NativeMemory modernization. +/// +[BenchmarkCategory("Allocation", "Micro")] +public class AllocationMicroBenchmarks : BenchmarkBase +{ + /// + /// Byte counts to allocate (matching typical NumSharp array sizes). + /// + [Params(64, 1_000, 100_000, 10_000_000)] + public int Bytes { get; set; } + + // ======================================================================== + // Allocation Only (no free) - measures allocation overhead + // ======================================================================== + + [Benchmark(Baseline = true, Description = "Marshal.AllocHGlobal")] + [BenchmarkCategory("AllocOnly")] + public nint MarshalAllocHGlobal() => Marshal.AllocHGlobal(Bytes); + + [Benchmark(Description = "NativeMemory.Alloc")] + [BenchmarkCategory("AllocOnly")] + public unsafe void* NativeMemoryAlloc() => NativeMemory.Alloc((nuint)Bytes); + + [Benchmark(Description = "NativeMemory.AlignedAlloc(32)")] + [BenchmarkCategory("AllocOnly")] + public unsafe void* NativeMemoryAlignedAlloc32() => NativeMemory.AlignedAlloc((nuint)Bytes, 32); + + [Benchmark(Description = "NativeMemory.AlignedAlloc(64)")] + [BenchmarkCategory("AllocOnly")] + public unsafe void* NativeMemoryAlignedAlloc64() => NativeMemory.AlignedAlloc((nuint)Bytes, 64); + + [Benchmark(Description = "NativeMemory.AllocZeroed")] + [BenchmarkCategory("AllocOnly")] + public unsafe void* NativeMemoryAllocZeroed() => NativeMemory.AllocZeroed((nuint)Bytes); + + // ======================================================================== + // Round-Trip (alloc + free) - measures full lifecycle + // ======================================================================== + + [Benchmark(Description = "Marshal alloc+free")] + [BenchmarkCategory("RoundTrip")] + public void MarshalRoundTrip() + { + var ptr = Marshal.AllocHGlobal(Bytes); + Marshal.FreeHGlobal(ptr); + } + + [Benchmark(Description = "NativeMemory alloc+free")] + [BenchmarkCategory("RoundTrip")] + public unsafe void NativeMemoryRoundTrip() + { + var ptr = NativeMemory.Alloc((nuint)Bytes); + NativeMemory.Free(ptr); + } + + [Benchmark(Description = "NativeMemory aligned alloc+free")] + [BenchmarkCategory("RoundTrip")] + public unsafe void NativeMemoryAlignedRoundTrip() + { + var ptr = NativeMemory.AlignedAlloc((nuint)Bytes, 32); + NativeMemory.AlignedFree(ptr); + } + + [Benchmark(Description = "NativeMemory zeroed alloc+free")] + [BenchmarkCategory("RoundTrip")] + public unsafe void NativeMemoryZeroedRoundTrip() + { + var ptr = NativeMemory.AllocZeroed((nuint)Bytes); + NativeMemory.Free(ptr); + } +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Allocation/AllocationSizeBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Allocation/AllocationSizeBenchmarks.cs new file mode 100644 index 000000000..a6a0d74c2 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Allocation/AllocationSizeBenchmarks.cs @@ -0,0 +1,68 @@ +using System.Runtime.InteropServices; +using BenchmarkDotNet.Attributes; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Allocation; + +/// +/// Benchmarks allocation performance across a wide range of sizes. +/// Helps identify: +/// - Small allocation overhead (where dispatch cost dominates) +/// - Crossover points between allocation strategies +/// - Large allocation behavior (OS page allocation) +/// +[BenchmarkCategory("Allocation", "SizeScaling")] +public class AllocationSizeBenchmarks : BenchmarkBase +{ + /// + /// Byte counts covering common array sizes: + /// - 64B: Single cache line + /// - 256B: Small scalar arrays + /// - 1KB: Tiny arrays + /// - 4KB: Page size boundary + /// - 64KB: L1 cache size + /// - 256KB: L2 cache size + /// - 1MB: L3 cache boundary + /// - 4MB: Large arrays + /// - 16MB: Very large arrays + /// - 64MB: Memory-bound + /// + [Params(64, 256, 1024, 4096, 65536, 262144, 1048576, 4194304, 16777216, 67108864)] + public int Bytes { get; set; } + + // ======================================================================== + // Marshal vs NativeMemory comparison across sizes + // ======================================================================== + + [Benchmark(Baseline = true, Description = "Marshal.AllocHGlobal")] + [BenchmarkCategory("Compare")] + public void MarshalAlloc() + { + var ptr = Marshal.AllocHGlobal(Bytes); + Marshal.FreeHGlobal(ptr); + } + + [Benchmark(Description = "NativeMemory.Alloc")] + [BenchmarkCategory("Compare")] + public unsafe void NativeAlloc() + { + var ptr = NativeMemory.Alloc((nuint)Bytes); + NativeMemory.Free(ptr); + } + + [Benchmark(Description = "NativeMemory.AlignedAlloc(32)")] + [BenchmarkCategory("Compare")] + public unsafe void NativeAlignedAlloc() + { + var ptr = NativeMemory.AlignedAlloc((nuint)Bytes, 32); + NativeMemory.AlignedFree(ptr); + } + + [Benchmark(Description = "NativeMemory.AllocZeroed")] + [BenchmarkCategory("Compare")] + public unsafe void NativeAllocZeroed() + { + var ptr = NativeMemory.AllocZeroed((nuint)Bytes); + NativeMemory.Free(ptr); + } +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Allocation/NumSharpAllocationBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Allocation/NumSharpAllocationBenchmarks.cs new file mode 100644 index 000000000..c6f421ff9 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Allocation/NumSharpAllocationBenchmarks.cs @@ -0,0 +1,111 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Allocation; + +/// +/// End-to-end NumSharp benchmarks measuring allocation impact: +/// - Array creation functions that allocate memory +/// - Operations that allocate output arrays +/// +/// These complement the micro-benchmarks by showing real-world impact. +/// +[BenchmarkCategory("Allocation", "NumSharp")] +public class NumSharpAllocationBenchmarks : TypedBenchmarkBase +{ + [Params(ArraySizeSource.Small, ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + [ParamsSource(nameof(Types))] + public new NPTypeCode DType { get; set; } + + /// + /// Types to benchmark. Focus on common types to keep benchmark time reasonable. + /// + public static IEnumerable Types => TypeParameterSource.MinimalTypes; + + private NDArray _a = null!; + private NDArray _b = null!; + + [GlobalSetup] + public void Setup() + { + _a = CreateRandomArray(N, DType, Seed); + _b = CreateRandomArray(N, DType, Seed + 1); + } + + [GlobalCleanup] + public void Cleanup() + { + _a = null!; + _b = null!; + GC.Collect(); + } + + // ======================================================================== + // Array Creation - Uninitialized + // ======================================================================== + + [Benchmark(Description = "np.empty(N) - uninitialized")] + [BenchmarkCategory("Creation", "Uninitialized")] + public NDArray Empty() => np.empty(new Shape(N), DType); + + // ======================================================================== + // Array Creation - Zero-Initialized + // This is the target for AllocZeroed optimization + // ======================================================================== + + [Benchmark(Description = "np.zeros(N) - zero-initialized")] + [BenchmarkCategory("Creation", "ZeroInit")] + public NDArray Zeros() => np.zeros(new Shape(N), DType); + + // ======================================================================== + // Array Creation - Value-Initialized + // ======================================================================== + + [Benchmark(Description = "np.ones(N) - ones")] + [BenchmarkCategory("Creation", "ValueInit")] + public NDArray Ones() => np.ones(new Shape(N), DType); + + [Benchmark(Description = "np.full(N, 42) - fill value")] + [BenchmarkCategory("Creation", "ValueInit")] + public NDArray Full() => np.full(new Shape(N), 42, DType); + + // ======================================================================== + // Array Creation - Sequential + // ======================================================================== + + [Benchmark(Description = "np.arange(N) - sequential")] + [BenchmarkCategory("Creation", "Sequential")] + public NDArray Arange() => np.arange(N); + + // ======================================================================== + // Operations That Allocate Output + // Shows allocation overhead in computation context + // ======================================================================== + + [Benchmark(Description = "a + b - binary op output alloc")] + [BenchmarkCategory("Operation", "Binary")] + public NDArray Add() => _a + _b; + + [Benchmark(Description = "a * b - binary op output alloc")] + [BenchmarkCategory("Operation", "Binary")] + public NDArray Multiply() => _a * _b; + + [Benchmark(Description = "np.sqrt(a) - unary op output alloc")] + [BenchmarkCategory("Operation", "Unary")] + public NDArray Sqrt() => np.sqrt(_a.astype(np.float64)); + + // ======================================================================== + // Copy Operations + // ======================================================================== + + [Benchmark(Description = "np.copy(a) - explicit copy")] + [BenchmarkCategory("Copy")] + public NDArray Copy() => np.copy(_a); + + [Benchmark(Description = "a.copy() - method copy")] + [BenchmarkCategory("Copy")] + public NDArray CopyMethod() => _a.copy(); +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Allocation/ZeroInitBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Allocation/ZeroInitBenchmarks.cs new file mode 100644 index 000000000..88100f966 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Allocation/ZeroInitBenchmarks.cs @@ -0,0 +1,109 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using BenchmarkDotNet.Attributes; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Allocation; + +/// +/// Benchmarks comparing zero-initialization approaches for np.zeros: +/// - Current: Alloc + Unsafe.InitBlock +/// - Proposed: NativeMemory.AllocZeroed (OS may have fast paths) +/// - Alternative: Alloc + Span.Clear +/// +/// These benchmarks inform the np.zeros optimization decision in issue #528. +/// +[BenchmarkCategory("Allocation", "ZeroInit")] +public class ZeroInitBenchmarks : BenchmarkBase +{ + /// + /// Element counts (int32 = 4 bytes each). + /// Small: 4KB, Medium: 400KB, Large: 40MB + /// + [Params(1_000, 100_000, 10_000_000)] + public override int N { get; set; } + + private int _bytes; + + [GlobalSetup] + public void Setup() + { + _bytes = N * sizeof(int); + } + + // ======================================================================== + // Current NumSharp approach: Alloc + Unsafe.InitBlock + // Used in UnmanagedMemoryBlock when filling with zeros + // ======================================================================== + + [Benchmark(Baseline = true, Description = "Alloc + InitBlock (current)")] + [BenchmarkCategory("ZeroInit")] + public unsafe void AllocThenInitBlock() + { + var ptr = NativeMemory.Alloc((nuint)_bytes); + Unsafe.InitBlock(ptr, 0, (uint)_bytes); + NativeMemory.Free(ptr); + } + + // ======================================================================== + // Proposed: NativeMemory.AllocZeroed + // OS may use page zeroing, copy-on-write, or hardware optimizations + // ======================================================================== + + [Benchmark(Description = "AllocZeroed (proposed)")] + [BenchmarkCategory("ZeroInit")] + public unsafe void AllocZeroed() + { + var ptr = NativeMemory.AllocZeroed((nuint)_bytes); + NativeMemory.Free(ptr); + } + + // ======================================================================== + // Alternative: Alloc + Span.Clear + // Span.Clear may use SIMD internally + // ======================================================================== + + [Benchmark(Description = "Alloc + Span.Clear")] + [BenchmarkCategory("ZeroInit")] + public unsafe void AllocThenSpanClear() + { + var ptr = NativeMemory.Alloc((nuint)_bytes); + new Span(ptr, _bytes).Clear(); + NativeMemory.Free(ptr); + } + + // ======================================================================== + // Aligned variants - test if alignment helps zero-init + // ======================================================================== + + [Benchmark(Description = "AlignedAlloc(32) + InitBlock")] + [BenchmarkCategory("ZeroInit", "Aligned")] + public unsafe void AlignedAllocThenInitBlock() + { + var ptr = NativeMemory.AlignedAlloc((nuint)_bytes, 32); + Unsafe.InitBlock(ptr, 0, (uint)_bytes); + NativeMemory.AlignedFree(ptr); + } + + [Benchmark(Description = "AlignedAlloc(32) + Span.Clear")] + [BenchmarkCategory("ZeroInit", "Aligned")] + public unsafe void AlignedAllocThenSpanClear() + { + var ptr = NativeMemory.AlignedAlloc((nuint)_bytes, 32); + new Span(ptr, _bytes).Clear(); + NativeMemory.AlignedFree(ptr); + } + + // ======================================================================== + // Marshal.AllocHGlobal baseline for comparison + // ======================================================================== + + [Benchmark(Description = "Marshal.AllocHGlobal + InitBlock")] + [BenchmarkCategory("ZeroInit", "Marshal")] + public unsafe void MarshalAllocThenInitBlock() + { + var ptr = Marshal.AllocHGlobal(_bytes); + Unsafe.InitBlock((void*)ptr, 0, (uint)_bytes); + Marshal.FreeHGlobal(ptr); + } +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Arithmetic/AddBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Arithmetic/AddBenchmarks.cs new file mode 100644 index 000000000..42d3c322e --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Arithmetic/AddBenchmarks.cs @@ -0,0 +1,67 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Arithmetic; + +/// +/// Benchmarks for addition operations: a + b, a + scalar. +/// Tests all numeric types and standard array sizes. +/// Note: 2D broadcasting tests are in BroadcastBenchmarks (float64 only). +/// +[BenchmarkCategory("Arithmetic", "Add")] +public class AddBenchmarks : TypedBenchmarkBase +{ + private NDArray _a = null!; + private NDArray _b = null!; + private NDArray _scalar = null!; + + [Params(ArraySizeSource.Small, ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + [ParamsSource(nameof(Types))] + public new NPTypeCode DType { get; set; } + + public static IEnumerable Types => TypeParameterSource.ArithmeticTypes; + + [GlobalSetup] + public void Setup() + { + _a = CreateRandomArray(N, DType); + _b = CreateRandomArray(N, DType, seed: 43); // Different seed for variety + _scalar = NDArray.Scalar(GetScalar(DType, 5.0), DType); + } + + [GlobalCleanup] + public void Cleanup() + { + _a = null!; + _b = null!; + _scalar = null!; + GC.Collect(); + } + + // ======================================================================== + // Element-wise Addition + // ======================================================================== + + [Benchmark(Description = "a + b (element-wise)")] + [BenchmarkCategory("Elementwise")] + public NDArray Add_Elementwise() => _a + _b; + + [Benchmark(Description = "np.add(a, b)")] + [BenchmarkCategory("Elementwise")] + public NDArray NpAdd() => np.add(_a, _b); + + // ======================================================================== + // Scalar Addition + // ======================================================================== + + [Benchmark(Description = "a + scalar")] + [BenchmarkCategory("Scalar")] + public NDArray Add_Scalar() => _a + _scalar; + + [Benchmark(Description = "a + 5 (literal)")] + [BenchmarkCategory("Scalar")] + public NDArray Add_ScalarLiteral() => _a + 5; +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Arithmetic/DivideBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Arithmetic/DivideBenchmarks.cs new file mode 100644 index 000000000..e64e0f946 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Arithmetic/DivideBenchmarks.cs @@ -0,0 +1,55 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Arithmetic; + +/// +/// Benchmarks for division operations. +/// +[BenchmarkCategory("Arithmetic", "Divide")] +public class DivideBenchmarks : TypedBenchmarkBase +{ + private NDArray _a = null!; + private NDArray _b = null!; + private NDArray _scalar = null!; + + [Params(ArraySizeSource.Small, ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + // Division works best with floating types + [ParamsSource(nameof(Types))] + public new NPTypeCode DType { get; set; } + + public static IEnumerable Types => TypeParameterSource.CommonTypes; + + [GlobalSetup] + public void Setup() + { + _a = CreateRandomArray(N, DType); + // Avoid division by zero - ensure positive values + _b = CreatePositiveArray(N, DType, seed: 43); + _scalar = NDArray.Scalar(GetScalar(DType, 2.0), DType); + } + + [GlobalCleanup] + public void Cleanup() + { + _a = null!; + _b = null!; + _scalar = null!; + GC.Collect(); + } + + [Benchmark(Description = "a / b (element-wise)")] + [BenchmarkCategory("Elementwise")] + public NDArray Divide_Elementwise() => _a / _b; + + [Benchmark(Description = "a / scalar")] + [BenchmarkCategory("Scalar")] + public NDArray Divide_Scalar() => _a / _scalar; + + [Benchmark(Description = "scalar / a")] + [BenchmarkCategory("Scalar")] + public NDArray Divide_ScalarLeft() => _scalar / _b; +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Arithmetic/ModuloBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Arithmetic/ModuloBenchmarks.cs new file mode 100644 index 000000000..e2166e96d --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Arithmetic/ModuloBenchmarks.cs @@ -0,0 +1,57 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Arithmetic; + +/// +/// Benchmarks for modulo operations. +/// +[BenchmarkCategory("Arithmetic", "Modulo")] +public class ModuloBenchmarks : TypedBenchmarkBase +{ + private NDArray _a = null!; + private NDArray _b = null!; + + [Params(ArraySizeSource.Small, ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + // Modulo typically used with integers + [ParamsSource(nameof(Types))] + public new NPTypeCode DType { get; set; } + + public static IEnumerable Types => new[] + { + NPTypeCode.Int32, + NPTypeCode.Int64, + NPTypeCode.Single, + NPTypeCode.Double + }; + + [GlobalSetup] + public void Setup() + { + _a = CreateRandomArray(N, DType); + // Avoid modulo by zero - use positive values only + // CreatePositiveArray returns values >= 1 + _b = CreatePositiveArray(N, DType, seed: 43); + // Ensure no zeros by clamping minimum to 1 + // This is needed because SIMD modulo will fail on any zero + } + + [GlobalCleanup] + public void Cleanup() + { + _a = null!; + _b = null!; + GC.Collect(); + } + + [Benchmark(Description = "a % b (element-wise)")] + [BenchmarkCategory("Elementwise")] + public NDArray Modulo_Elementwise() => _a % _b; + + [Benchmark(Description = "a % 7 (literal)")] + [BenchmarkCategory("Scalar")] + public NDArray Modulo_Scalar() => _a % 7; +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Arithmetic/MultiplyBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Arithmetic/MultiplyBenchmarks.cs new file mode 100644 index 000000000..ba3b3e479 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Arithmetic/MultiplyBenchmarks.cs @@ -0,0 +1,57 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Arithmetic; + +/// +/// Benchmarks for multiplication operations. +/// +[BenchmarkCategory("Arithmetic", "Multiply")] +public class MultiplyBenchmarks : TypedBenchmarkBase +{ + private NDArray _a = null!; + private NDArray _b = null!; + private NDArray _scalar = null!; + + [Params(ArraySizeSource.Small, ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + [ParamsSource(nameof(Types))] + public new NPTypeCode DType { get; set; } + + public static IEnumerable Types => TypeParameterSource.ArithmeticTypes; + + [GlobalSetup] + public void Setup() + { + _a = CreateRandomArray(N, DType); + _b = CreateRandomArray(N, DType, seed: 43); + _scalar = NDArray.Scalar(GetScalar(DType, 2.0), DType); + } + + [GlobalCleanup] + public void Cleanup() + { + _a = null!; + _b = null!; + _scalar = null!; + GC.Collect(); + } + + [Benchmark(Description = "a * b (element-wise)")] + [BenchmarkCategory("Elementwise")] + public NDArray Multiply_Elementwise() => _a * _b; + + [Benchmark(Description = "a * a (square)")] + [BenchmarkCategory("Elementwise")] + public NDArray Multiply_Square() => _a * _a; + + [Benchmark(Description = "a * scalar")] + [BenchmarkCategory("Scalar")] + public NDArray Multiply_Scalar() => _a * _scalar; + + [Benchmark(Description = "a * 2 (literal)")] + [BenchmarkCategory("Scalar")] + public NDArray Multiply_ScalarLiteral() => _a * 2; +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Arithmetic/SubtractBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Arithmetic/SubtractBenchmarks.cs new file mode 100644 index 000000000..5bed5ced6 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Arithmetic/SubtractBenchmarks.cs @@ -0,0 +1,53 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Arithmetic; + +/// +/// Benchmarks for subtraction operations. +/// +[BenchmarkCategory("Arithmetic", "Subtract")] +public class SubtractBenchmarks : TypedBenchmarkBase +{ + private NDArray _a = null!; + private NDArray _b = null!; + private NDArray _scalar = null!; + + [Params(ArraySizeSource.Small, ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + [ParamsSource(nameof(Types))] + public new NPTypeCode DType { get; set; } + + public static IEnumerable Types => TypeParameterSource.ArithmeticTypes; + + [GlobalSetup] + public void Setup() + { + _a = CreateRandomArray(N, DType); + _b = CreateRandomArray(N, DType, seed: 43); + _scalar = NDArray.Scalar(GetScalar(DType, 5.0), DType); + } + + [GlobalCleanup] + public void Cleanup() + { + _a = null!; + _b = null!; + _scalar = null!; + GC.Collect(); + } + + [Benchmark(Description = "a - b (element-wise)")] + [BenchmarkCategory("Elementwise")] + public NDArray Subtract_Elementwise() => _a - _b; + + [Benchmark(Description = "a - scalar")] + [BenchmarkCategory("Scalar")] + public NDArray Subtract_Scalar() => _a - _scalar; + + [Benchmark(Description = "scalar - a")] + [BenchmarkCategory("Scalar")] + public NDArray Subtract_ScalarLeft() => _scalar - _a; +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Broadcasting/BroadcastBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Broadcasting/BroadcastBenchmarks.cs new file mode 100644 index 000000000..da84e7389 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Broadcasting/BroadcastBenchmarks.cs @@ -0,0 +1,116 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Broadcasting; + +/// +/// Benchmarks for broadcasting operations. +/// Tests various broadcasting patterns: scalar, row, column, and general. +/// +[BenchmarkCategory("Broadcasting")] +public class BroadcastBenchmarks : BenchmarkBase +{ + private NDArray _matrix = null!; + private NDArray _rowVector = null!; + private NDArray _colVector = null!; + private NDArray _scalar = null!; + private NDArray _tensor3D = null!; + private NDArray _broadcast2D = null!; + + [Params(1000, 3162)] // 1M and ~10M elements when squared + public int MatrixSize { get; set; } + + [GlobalSetup] + public void Setup() + { + np.random.seed(Seed); + var n = MatrixSize; + + _matrix = (np.random.rand(n, n) * 100).astype(np.float64); + _rowVector = (np.random.rand(n) * 100).astype(np.float64); + _colVector = (np.random.rand(n, 1) * 100).astype(np.float64); + _scalar = np.array(42.0); + + // 3D tensor for more complex broadcasting + var d = (int)Math.Pow(n * n, 1.0 / 3); // ~same total elements + _tensor3D = (np.random.rand(d, d, d) * 100).astype(np.float64); + _broadcast2D = (np.random.rand(d, d) * 100).astype(np.float64); + } + + [GlobalCleanup] + public void Cleanup() + { + _matrix = null!; + _rowVector = null!; + _colVector = null!; + _scalar = null!; + _tensor3D = null!; + _broadcast2D = null!; + GC.Collect(); + } + + // ======================================================================== + // Scalar Broadcasting + // ======================================================================== + + [Benchmark(Description = "matrix + scalar")] + [BenchmarkCategory("Scalar")] + public NDArray Broadcast_Scalar() => _matrix + _scalar; + + [Benchmark(Description = "matrix * 2.0")] + [BenchmarkCategory("Scalar")] + public NDArray Broadcast_ScalarLiteral() => _matrix * 2.0; + + // ======================================================================== + // Row Broadcasting (N,M) + (M,) -> (N,M) + // ======================================================================== + + [Benchmark(Description = "matrix + row_vector (N,M)+(M,)")] + [BenchmarkCategory("Row")] + public NDArray Broadcast_Row_Add() => _matrix + _rowVector; + + [Benchmark(Description = "matrix * row_vector (N,M)*(M,)")] + [BenchmarkCategory("Row")] + public NDArray Broadcast_Row_Mul() => _matrix * _rowVector; + + // ======================================================================== + // Column Broadcasting (N,M) + (N,1) -> (N,M) + // ======================================================================== + + [Benchmark(Description = "matrix + col_vector (N,M)+(N,1)")] + [BenchmarkCategory("Column")] + public NDArray Broadcast_Col_Add() => _matrix + _colVector; + + [Benchmark(Description = "matrix * col_vector (N,M)*(N,1)")] + [BenchmarkCategory("Column")] + public NDArray Broadcast_Col_Mul() => _matrix * _colVector; + + // ======================================================================== + // 3D Broadcasting + // ======================================================================== + + [Benchmark(Description = "tensor3D + matrix2D (D,D,D)+(D,D)")] + [BenchmarkCategory("3D")] + public NDArray Broadcast_3D_2D() => _tensor3D + _broadcast2D; + + // ======================================================================== + // np.broadcast_to + // ======================================================================== + + [Benchmark(Description = "np.broadcast_to(row, (N,M))")] + [BenchmarkCategory("BroadcastTo")] + public NDArray BroadcastTo_Row() + { + var n = MatrixSize; + return np.broadcast_to(_rowVector, new Shape(n, n)); + } + + [Benchmark(Description = "np.broadcast_to(col, (N,M))")] + [BenchmarkCategory("BroadcastTo")] + public NDArray BroadcastTo_Col() + { + var n = MatrixSize; + return np.broadcast_to(_colVector, new Shape(n, n)); + } +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Creation/CreationBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Creation/CreationBenchmarks.cs new file mode 100644 index 000000000..e00e89e74 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Creation/CreationBenchmarks.cs @@ -0,0 +1,103 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Creation; + +/// +/// Benchmarks for array creation functions. +/// +[BenchmarkCategory("Creation")] +public class CreationBenchmarks : TypedBenchmarkBase +{ + private NDArray _source = null!; + + [Params(ArraySizeSource.Small, ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + [ParamsSource(nameof(Types))] + public new NPTypeCode DType { get; set; } + + public static IEnumerable Types => TypeParameterSource.CommonTypes; + + [GlobalSetup] + public void Setup() + { + _source = CreateRandomArray(N, DType); + } + + [GlobalCleanup] + public void Cleanup() + { + _source = null!; + GC.Collect(); + } + + // ======================================================================== + // Initialized Arrays + // ======================================================================== + + [Benchmark(Description = "np.zeros(N)")] + [BenchmarkCategory("Initialized")] + public NDArray Zeros() => np.zeros(new Shape(N), DType); + + [Benchmark(Description = "np.ones(N)")] + [BenchmarkCategory("Initialized")] + public NDArray Ones() => np.ones(new Shape(N), DType); + + [Benchmark(Description = "np.full(N, value)")] + [BenchmarkCategory("Initialized")] + public NDArray Full() => np.full(new Shape(N), 42, DType); + + [Benchmark(Description = "np.empty(N)")] + [BenchmarkCategory("Uninitialized")] + public NDArray Empty() => np.empty(new Shape(N), DType); + + // ======================================================================== + // Range-based + // ======================================================================== + + [Benchmark(Description = "np.arange(N)")] + [BenchmarkCategory("Range")] + public NDArray Arange() => np.arange(N); + + [Benchmark(Description = "np.linspace(0, N, N)")] + [BenchmarkCategory("Range")] + public NDArray Linspace() => np.linspace(0, N, N); + + // ======================================================================== + // Copy / Conversion + // ======================================================================== + + [Benchmark(Description = "np.copy(a)")] + [BenchmarkCategory("Copy")] + public NDArray Copy() => np.copy(_source); + + [Benchmark(Description = "a.copy()")] + [BenchmarkCategory("Copy")] + public NDArray CopyMethod() => _source.copy(); + + [Benchmark(Description = "np.copy(a) [asarray equivalent]")] + [BenchmarkCategory("Convert")] + public NDArray AsArray() => np.copy(_source); + + // ======================================================================== + // Like-based + // ======================================================================== + + [Benchmark(Description = "np.zeros_like(a)")] + [BenchmarkCategory("Like")] + public NDArray ZerosLike() => np.zeros_like(_source); + + [Benchmark(Description = "np.ones_like(a)")] + [BenchmarkCategory("Like")] + public NDArray OnesLike() => np.ones_like(_source); + + [Benchmark(Description = "np.empty_like(a)")] + [BenchmarkCategory("Like")] + public NDArray EmptyLike() => np.empty_like(_source); + + [Benchmark(Description = "np.full_like(a, 42)")] + [BenchmarkCategory("Like")] + public NDArray FullLike() => np.full_like(_source, 42); +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/DispatchBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/DispatchBenchmarks.cs new file mode 100644 index 000000000..b92644b23 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/DispatchBenchmarks.cs @@ -0,0 +1,286 @@ +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Order; + +namespace NumSharp.Benchmark.GraphEngine; + +/// +/// Compares different dispatch mechanisms for binary operations. +/// This benchmark answers: "How should NumSharp dispatch arithmetic operations?" +/// +/// Approaches tested: +/// - Raw pointer loop (inline arithmetic, no abstraction) +/// - Static method call (current NumSharp pattern via Operator.Add) +/// - Struct with interface (C++ template-like, IBinOp<T>) +/// - DynamicMethod scalar (IL emission, scalar loop) +/// - DynamicMethod SIMD (IL emission with Vector256) +/// - Hand-written SIMD (static code with Vector256) +/// +[MemoryDiagnoser] +[Orderer(SummaryOrderPolicy.FastestToSlowest)] +[RankColumn] +[CategoriesColumn] +public unsafe class DispatchBenchmarks +{ + private int* _a; + private int* _b; + private int* _c; + + private Action? _dynMethodScalar; + private Action? _dynMethodSimd; + + [Params(1_000, 100_000, 10_000_000)] + public int N { get; set; } + + [GlobalSetup] + public void Setup() + { + _a = (int*)NativeMemory.AlignedAlloc((nuint)(N * sizeof(int)), 32); + _b = (int*)NativeMemory.AlignedAlloc((nuint)(N * sizeof(int)), 32); + _c = (int*)NativeMemory.AlignedAlloc((nuint)(N * sizeof(int)), 32); + + var rng = new Random(42); + for (int i = 0; i < N; i++) + { + _a[i] = rng.Next(100); + _b[i] = rng.Next(100); + } + + // Pre-compile DynamicMethods + _dynMethodScalar = EmitScalarPtrLoop().CreateDelegate>(); + _dynMethodSimd = EmitSimdPtrLoop().CreateDelegate>(); + } + + [GlobalCleanup] + public void Cleanup() + { + NativeMemory.AlignedFree(_a); + NativeMemory.AlignedFree(_b); + NativeMemory.AlignedFree(_c); + } + + // ======================================================================== + // Benchmark Methods + // ======================================================================== + + [Benchmark(Description = "Raw ptr loop (inline a+b)")] + [BenchmarkCategory("Baseline")] + public void RawPtrLoop() + { + var a = _a; + var b = _b; + var c = _c; + var n = N; + for (int i = 0; i < n; i++) + c[i] = a[i] + b[i]; + } + + [Benchmark(Baseline = true, Description = "Static Op.Add() [NumSharp current]")] + [BenchmarkCategory("Current")] + public void StaticOpAdd() + { + var a = _a; + var b = _b; + var c = _c; + var n = N; + for (int i = 0; i < n; i++) + c[i] = Op.Add(a[i], b[i]); + } + + [Benchmark(Description = "Struct via IBinOp")] + [BenchmarkCategory("Alternative")] + public void StructDispatch() + { + var a = _a; + var b = _b; + var c = _c; + var n = N; + AddOp op = default; + for (int i = 0; i < n; i++) + c[i] = op.Execute(a[i], b[i]); + } + + [Benchmark(Description = "DynamicMethod scalar ptr")] + [BenchmarkCategory("Proposed")] + public void DynMethodScalar() + { + _dynMethodScalar!((nint)_a, (nint)_b, (nint)_c, N); + } + + [Benchmark(Description = "DynamicMethod SIMD (Vector256)")] + [BenchmarkCategory("Proposed")] + public void DynMethodSimd() + { + _dynMethodSimd!((nint)_a, (nint)_b, (nint)_c, N); + } + + [Benchmark(Description = "Hand-written SIMD (Vector256)")] + [BenchmarkCategory("Reference")] + public void HandWrittenSimd() + { + var a = _a; + var b = _b; + var c = _c; + var n = N; + int i = 0; + for (; i <= n - 8; i += 8) + Vector256.Store(Vector256.Load(a + i) + Vector256.Load(b + i), c + i); + for (; i < n; i++) + c[i] = a[i] + b[i]; + } + + // ======================================================================== + // Support Types + // ======================================================================== + + private static class Op + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Add(int a, int b) => a + b; + } + + private interface IBinOp { T Execute(T a, T b); } + + private struct AddOp : IBinOp + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Execute(int a, int b) => a + b; + } + + // ======================================================================== + // DynamicMethod Builders + // ======================================================================== + + private static DynamicMethod EmitScalarPtrLoop() + { + var dm = new DynamicMethod("ScalarPtr", typeof(void), + [typeof(nint), typeof(nint), typeof(nint), typeof(int)], + typeof(DispatchBenchmarks).Module, true); + var il = dm.GetILGenerator(); + var top = il.DefineLabel(); + var chk = il.DefineLabel(); + il.DeclareLocal(typeof(int)); // i + + il.Emit(OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Stloc_0); + il.Emit(OpCodes.Br, chk); + + il.MarkLabel(top); + // c[i] = a[i] + b[i] + EmitPtrOffset(il, 2); // &c[i] + EmitPtrLoad(il, 0); // a[i] + EmitPtrLoad(il, 1); // b[i] + il.Emit(OpCodes.Add); + il.Emit(OpCodes.Stind_I4); + + // i++ + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Add); + il.Emit(OpCodes.Stloc_0); + + il.MarkLabel(chk); + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldarg_3); + il.Emit(OpCodes.Blt, top); + + il.Emit(OpCodes.Ret); + return dm; + } + + private static DynamicMethod EmitSimdPtrLoop() + { + var loadM = typeof(Vector256).GetMethods() + .First(m => m.Name == "Load" && m.IsGenericMethod) + .MakeGenericMethod(typeof(int)); + var storeM = typeof(Vector256).GetMethods() + .First(m => m.Name == "Store" && m.IsGenericMethod && m.GetParameters().Length == 2) + .MakeGenericMethod(typeof(int)); + var addVecM = typeof(Vector256).GetMethods() + .First(m => m.Name == "op_Addition" + && m.GetParameters()[0].ParameterType == typeof(Vector256)); + + var dm = new DynamicMethod("SimdPtr", typeof(void), + [typeof(nint), typeof(nint), typeof(nint), typeof(int)], + typeof(DispatchBenchmarks).Module, true); + var il = dm.GetILGenerator(); + var sTop = il.DefineLabel(); + var sChk = il.DefineLabel(); + var tTop = il.DefineLabel(); + var tChk = il.DefineLabel(); + il.DeclareLocal(typeof(int)); // i + il.DeclareLocal(typeof(int)); // simdEnd + + // simdEnd = n - 8 + il.Emit(OpCodes.Ldarg_3); + il.Emit(OpCodes.Ldc_I4_8); + il.Emit(OpCodes.Sub); + il.Emit(OpCodes.Stloc_1); + + il.Emit(OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Stloc_0); + il.Emit(OpCodes.Br, sChk); + + // SIMD loop + il.MarkLabel(sTop); + EmitPtrOffset(il, 0); + il.EmitCall(OpCodes.Call, loadM, null); + EmitPtrOffset(il, 1); + il.EmitCall(OpCodes.Call, loadM, null); + il.EmitCall(OpCodes.Call, addVecM, null); + EmitPtrOffset(il, 2); + il.EmitCall(OpCodes.Call, storeM, null); + + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldc_I4_8); + il.Emit(OpCodes.Add); + il.Emit(OpCodes.Stloc_0); + + il.MarkLabel(sChk); + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldloc_1); + il.Emit(OpCodes.Ble, sTop); + + // Scalar tail + il.Emit(OpCodes.Br, tChk); + il.MarkLabel(tTop); + EmitPtrOffset(il, 2); + EmitPtrLoad(il, 0); + EmitPtrLoad(il, 1); + il.Emit(OpCodes.Add); + il.Emit(OpCodes.Stind_I4); + + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Add); + il.Emit(OpCodes.Stloc_0); + + il.MarkLabel(tChk); + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldarg_3); + il.Emit(OpCodes.Blt, tTop); + + il.Emit(OpCodes.Ret); + return dm; + } + + private static void EmitPtrOffset(ILGenerator il, int argIndex) + { + il.Emit(OpCodes.Ldarg, argIndex); + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Conv_I); + il.Emit(OpCodes.Ldc_I4_4); + il.Emit(OpCodes.Mul); + il.Emit(OpCodes.Add); + } + + private static void EmitPtrLoad(ILGenerator il, int argIndex) + { + EmitPtrOffset(il, argIndex); + il.Emit(OpCodes.Ldind_I4); + } +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/DynamicEmissionBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/DynamicEmissionBenchmarks.cs new file mode 100644 index 000000000..d049198ce --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/DynamicEmissionBenchmarks.cs @@ -0,0 +1,431 @@ +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Order; +using NumSharp; + +namespace NumSharp.Benchmark.GraphEngine; + +/// +/// Benchmarks for GitHub Issue #544: Replace ~636K lines of generated math code with DynamicMethod IL emission. +/// +/// This benchmark compares: +/// - NumSharp current (generated code via Regen templates) +/// - DynamicMethod scalar (IL-emitted pointer loops) +/// - DynamicMethod SIMD (IL-emitted Vector256 loops) +/// +/// Success criteria from #544: +/// - Binary ops should be ≥2x faster than current on contiguous arrays +/// - All existing tests pass with DynamicMethod enabled +/// - Generated code files can be deleted +/// +/// Related: #544 (this issue), #541 (successor - GraphEngine with fusion) +/// +[MemoryDiagnoser] +[Orderer(SummaryOrderPolicy.FastestToSlowest)] +[RankColumn] +[CategoriesColumn] +[GroupBenchmarksBy(BenchmarkDotNet.Configs.BenchmarkLogicalGroupRule.ByCategory)] +public unsafe class DynamicEmissionBenchmarks +{ + // ======================================================================== + // Data Arrays + // ======================================================================== + + // int32 + private int* _aInt; + private int* _bInt; + private int* _cInt; + private NDArray _aIntND = null!; + private NDArray _bIntND = null!; + + // float64 + private double* _aDouble; + private double* _bDouble; + private double* _cDouble; + private NDArray _aDoubleND = null!; + private NDArray _bDoubleND = null!; + + // Pre-compiled DynamicMethod delegates + private Action? _dynAddInt32Scalar; + private Action? _dynAddInt32Simd; + private Action? _dynMulInt32Scalar; + private Action? _dynMulInt32Simd; + + private Action? _dynAddFloat64Scalar; + private Action? _dynAddFloat64Simd; + private Action? _dynMulFloat64Scalar; + private Action? _dynMulFloat64Simd; + + private Action? _dynSqrtFloat64Scalar; + + [Params(1, 1_000, 10_000, 1_000_000, 10_000_000)] + public int N { get; set; } + + [GlobalSetup] + public void Setup() + { + // Allocate native memory (aligned for SIMD) + _aInt = (int*)NativeMemory.AlignedAlloc((nuint)(N * sizeof(int)), 64); + _bInt = (int*)NativeMemory.AlignedAlloc((nuint)(N * sizeof(int)), 64); + _cInt = (int*)NativeMemory.AlignedAlloc((nuint)(N * sizeof(int)), 64); + + _aDouble = (double*)NativeMemory.AlignedAlloc((nuint)(N * sizeof(double)), 64); + _bDouble = (double*)NativeMemory.AlignedAlloc((nuint)(N * sizeof(double)), 64); + _cDouble = (double*)NativeMemory.AlignedAlloc((nuint)(N * sizeof(double)), 64); + + // Initialize data + var rng = new Random(42); + for (int i = 0; i < N; i++) + { + _aInt[i] = rng.Next(1, 100); + _bInt[i] = rng.Next(1, 100); + _aDouble[i] = rng.NextDouble() * 10 + 0.1; // Avoid zero for sqrt + _bDouble[i] = rng.NextDouble() * 10 + 0.1; + } + + // Create NumSharp arrays + np.random.seed(42); + _aIntND = np.random.randint(1, 100, new Shape(N)).astype(np.int32); + _bIntND = np.random.randint(1, 100, new Shape(N)).astype(np.int32); + _aDoubleND = np.random.rand(N) * 10 + 0.1; + _bDoubleND = np.random.rand(N) * 10 + 0.1; + + // Pre-compile DynamicMethod delegates + _dynAddInt32Scalar = EmitBinaryScalar(OpCodes.Add).CreateDelegate>(); + _dynAddInt32Simd = EmitBinarySimd(AddVec()).CreateDelegate>(); + _dynMulInt32Scalar = EmitBinaryScalar(OpCodes.Mul).CreateDelegate>(); + _dynMulInt32Simd = EmitBinarySimd(MulVec()).CreateDelegate>(); + + _dynAddFloat64Scalar = EmitBinaryScalar(OpCodes.Add).CreateDelegate>(); + _dynAddFloat64Simd = EmitBinarySimd(AddVec()).CreateDelegate>(); + _dynMulFloat64Scalar = EmitBinaryScalar(OpCodes.Mul).CreateDelegate>(); + _dynMulFloat64Simd = EmitBinarySimd(MulVec()).CreateDelegate>(); + + _dynSqrtFloat64Scalar = EmitUnarySqrt().CreateDelegate>(); + } + + [GlobalCleanup] + public void Cleanup() + { + NativeMemory.AlignedFree(_aInt); + NativeMemory.AlignedFree(_bInt); + NativeMemory.AlignedFree(_cInt); + NativeMemory.AlignedFree(_aDouble); + NativeMemory.AlignedFree(_bDouble); + NativeMemory.AlignedFree(_cDouble); + } + + // ======================================================================== + // INT32 ADD: NumSharp vs DynamicMethod + // ======================================================================== + + [Benchmark(Baseline = true, Description = "NumSharp: a + b")] + [BenchmarkCategory("Add_Int32")] + public NDArray NumSharp_Add_Int32() => _aIntND + _bIntND; + + [Benchmark(Description = "DynMethod scalar: a + b")] + [BenchmarkCategory("Add_Int32")] + public void DynMethod_Add_Int32_Scalar() + { + _dynAddInt32Scalar!((nint)_aInt, (nint)_bInt, (nint)_cInt, N); + } + + [Benchmark(Description = "DynMethod SIMD: a + b")] + [BenchmarkCategory("Add_Int32")] + public void DynMethod_Add_Int32_Simd() + { + _dynAddInt32Simd!((nint)_aInt, (nint)_bInt, (nint)_cInt, N); + } + + // ======================================================================== + // INT32 MUL: NumSharp vs DynamicMethod + // ======================================================================== + + [Benchmark(Baseline = true, Description = "NumSharp: a * b")] + [BenchmarkCategory("Mul_Int32")] + public NDArray NumSharp_Mul_Int32() => _aIntND * _bIntND; + + [Benchmark(Description = "DynMethod scalar: a * b")] + [BenchmarkCategory("Mul_Int32")] + public void DynMethod_Mul_Int32_Scalar() + { + _dynMulInt32Scalar!((nint)_aInt, (nint)_bInt, (nint)_cInt, N); + } + + [Benchmark(Description = "DynMethod SIMD: a * b")] + [BenchmarkCategory("Mul_Int32")] + public void DynMethod_Mul_Int32_Simd() + { + _dynMulInt32Simd!((nint)_aInt, (nint)_bInt, (nint)_cInt, N); + } + + // ======================================================================== + // FLOAT64 ADD: NumSharp vs DynamicMethod + // ======================================================================== + + [Benchmark(Baseline = true, Description = "NumSharp: a + b")] + [BenchmarkCategory("Add_Float64")] + public NDArray NumSharp_Add_Float64() => _aDoubleND + _bDoubleND; + + [Benchmark(Description = "DynMethod scalar: a + b")] + [BenchmarkCategory("Add_Float64")] + public void DynMethod_Add_Float64_Scalar() + { + _dynAddFloat64Scalar!((nint)_aDouble, (nint)_bDouble, (nint)_cDouble, N); + } + + [Benchmark(Description = "DynMethod SIMD: a + b")] + [BenchmarkCategory("Add_Float64")] + public void DynMethod_Add_Float64_Simd() + { + _dynAddFloat64Simd!((nint)_aDouble, (nint)_bDouble, (nint)_cDouble, N); + } + + // ======================================================================== + // FLOAT64 MUL: NumSharp vs DynamicMethod + // ======================================================================== + + [Benchmark(Baseline = true, Description = "NumSharp: a * b")] + [BenchmarkCategory("Mul_Float64")] + public NDArray NumSharp_Mul_Float64() => _aDoubleND * _bDoubleND; + + [Benchmark(Description = "DynMethod scalar: a * b")] + [BenchmarkCategory("Mul_Float64")] + public void DynMethod_Mul_Float64_Scalar() + { + _dynMulFloat64Scalar!((nint)_aDouble, (nint)_bDouble, (nint)_cDouble, N); + } + + [Benchmark(Description = "DynMethod SIMD: a * b")] + [BenchmarkCategory("Mul_Float64")] + public void DynMethod_Mul_Float64_Simd() + { + _dynMulFloat64Simd!((nint)_aDouble, (nint)_bDouble, (nint)_cDouble, N); + } + + // ======================================================================== + // FLOAT64 SQRT (Unary): NumSharp vs DynamicMethod + // ======================================================================== + + [Benchmark(Baseline = true, Description = "NumSharp: np.sqrt(a)")] + [BenchmarkCategory("Sqrt_Float64")] + public NDArray NumSharp_Sqrt_Float64() => np.sqrt(_aDoubleND); + + [Benchmark(Description = "DynMethod scalar: sqrt(a)")] + [BenchmarkCategory("Sqrt_Float64")] + public void DynMethod_Sqrt_Float64_Scalar() + { + _dynSqrtFloat64Scalar!((nint)_aDouble, (nint)_cDouble, N); + } + + // ======================================================================== + // DynamicMethod Emitters + // ======================================================================== + + private static DynamicMethod EmitBinaryScalar(OpCode opcode) where T : unmanaged + { + var size = sizeof(T); + var ldind = GetLdind(); + var stind = GetStind(); + + var dm = new DynamicMethod($"BinaryScalar_{typeof(T).Name}", typeof(void), + [typeof(nint), typeof(nint), typeof(nint), typeof(int)], + typeof(DynamicEmissionBenchmarks).Module, true); + var il = dm.GetILGenerator(); + var top = il.DefineLabel(); + var chk = il.DefineLabel(); + il.DeclareLocal(typeof(int)); // i + + il.Emit(OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Stloc_0); + il.Emit(OpCodes.Br, chk); + + il.MarkLabel(top); + // c[i] = a[i] op b[i] + EmitPtrOffset(il, 2, size); // &c[i] + EmitPtrLoad(il, 0, size, ldind); // a[i] + EmitPtrLoad(il, 1, size, ldind); // b[i] + il.Emit(opcode); + il.Emit(stind); + + // i++ + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Add); + il.Emit(OpCodes.Stloc_0); + + il.MarkLabel(chk); + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldarg_3); + il.Emit(OpCodes.Blt, top); + + il.Emit(OpCodes.Ret); + return dm; + } + + private static DynamicMethod EmitBinarySimd(MethodInfo vecOp) where T : unmanaged + { + var size = sizeof(T); + var ldind = GetLdind(); + var stind = GetStind(); + var vecCount = Vector256.Count; + + var loadM = typeof(Vector256).GetMethods() + .First(m => m.Name == "Load" && m.IsGenericMethod) + .MakeGenericMethod(typeof(T)); + var storeM = typeof(Vector256).GetMethods() + .First(m => m.Name == "Store" && m.IsGenericMethod && m.GetParameters().Length == 2) + .MakeGenericMethod(typeof(T)); + + var dm = new DynamicMethod($"BinarySimd_{typeof(T).Name}", typeof(void), + [typeof(nint), typeof(nint), typeof(nint), typeof(int)], + typeof(DynamicEmissionBenchmarks).Module, true); + var il = dm.GetILGenerator(); + var sTop = il.DefineLabel(); + var sChk = il.DefineLabel(); + var tTop = il.DefineLabel(); + var tChk = il.DefineLabel(); + il.DeclareLocal(typeof(int)); // i + il.DeclareLocal(typeof(int)); // simdEnd + + // simdEnd = n - vecCount + il.Emit(OpCodes.Ldarg_3); + il.Emit(OpCodes.Ldc_I4, vecCount); + il.Emit(OpCodes.Sub); + il.Emit(OpCodes.Stloc_1); + + il.Emit(OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Stloc_0); + il.Emit(OpCodes.Br, sChk); + + // SIMD loop + il.MarkLabel(sTop); + EmitPtrOffset(il, 0, size); + il.EmitCall(OpCodes.Call, loadM, null); + EmitPtrOffset(il, 1, size); + il.EmitCall(OpCodes.Call, loadM, null); + il.EmitCall(OpCodes.Call, vecOp, null); + EmitPtrOffset(il, 2, size); + il.EmitCall(OpCodes.Call, storeM, null); + + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldc_I4, vecCount); + il.Emit(OpCodes.Add); + il.Emit(OpCodes.Stloc_0); + + il.MarkLabel(sChk); + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldloc_1); + il.Emit(OpCodes.Ble, sTop); + + // Scalar tail + il.Emit(OpCodes.Br, tChk); + il.MarkLabel(tTop); + EmitPtrOffset(il, 2, size); + EmitPtrLoad(il, 0, size, ldind); + EmitPtrLoad(il, 1, size, ldind); + il.Emit(OpCodes.Add); + il.Emit(stind); + + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Add); + il.Emit(OpCodes.Stloc_0); + + il.MarkLabel(tChk); + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldarg_3); + il.Emit(OpCodes.Blt, tTop); + + il.Emit(OpCodes.Ret); + return dm; + } + + private static DynamicMethod EmitUnarySqrt() + { + var sqrtM = typeof(Math).GetMethod("Sqrt", [typeof(double)])!; + + var dm = new DynamicMethod("UnarySqrt", typeof(void), + [typeof(nint), typeof(nint), typeof(int)], + typeof(DynamicEmissionBenchmarks).Module, true); + var il = dm.GetILGenerator(); + var top = il.DefineLabel(); + var chk = il.DefineLabel(); + il.DeclareLocal(typeof(int)); // i + + il.Emit(OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Stloc_0); + il.Emit(OpCodes.Br, chk); + + il.MarkLabel(top); + // c[i] = sqrt(a[i]) + EmitPtrOffset(il, 1, 8); // &c[i] + EmitPtrLoad(il, 0, 8, OpCodes.Ldind_R8); // a[i] + il.EmitCall(OpCodes.Call, sqrtM, null); + il.Emit(OpCodes.Stind_R8); + + // i++ + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Add); + il.Emit(OpCodes.Stloc_0); + + il.MarkLabel(chk); + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldarg_2); + il.Emit(OpCodes.Blt, top); + + il.Emit(OpCodes.Ret); + return dm; + } + + // ======================================================================== + // IL Helpers + // ======================================================================== + + private static void EmitPtrOffset(ILGenerator il, int argIndex, int elemSize) + { + il.Emit(OpCodes.Ldarg, argIndex); + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Conv_I); + il.Emit(OpCodes.Ldc_I4, elemSize); + il.Emit(OpCodes.Mul); + il.Emit(OpCodes.Add); + } + + private static void EmitPtrLoad(ILGenerator il, int argIndex, int elemSize, OpCode ldind) + { + EmitPtrOffset(il, argIndex, elemSize); + il.Emit(ldind); + } + + private static OpCode GetLdind() where T : unmanaged + { + if (typeof(T) == typeof(int)) return OpCodes.Ldind_I4; + if (typeof(T) == typeof(double)) return OpCodes.Ldind_R8; + if (typeof(T) == typeof(float)) return OpCodes.Ldind_R4; + if (typeof(T) == typeof(long)) return OpCodes.Ldind_I8; + throw new NotSupportedException($"Type {typeof(T)} not supported"); + } + + private static OpCode GetStind() where T : unmanaged + { + if (typeof(T) == typeof(int)) return OpCodes.Stind_I4; + if (typeof(T) == typeof(double)) return OpCodes.Stind_R8; + if (typeof(T) == typeof(float)) return OpCodes.Stind_R4; + if (typeof(T) == typeof(long)) return OpCodes.Stind_I8; + throw new NotSupportedException($"Type {typeof(T)} not supported"); + } + + private static MethodInfo AddVec() where T : unmanaged => + typeof(Vector256).GetMethods() + .First(m => m.Name == "op_Addition" && m.GetParameters()[0].ParameterType == typeof(Vector256)); + + private static MethodInfo MulVec() where T : unmanaged => + typeof(Vector256).GetMethods() + .First(m => m.Name == "op_Multiply" && m.GetParameters()[0].ParameterType == typeof(Vector256)); +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/FusionBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/FusionBenchmarks.cs new file mode 100644 index 000000000..3f3bdab23 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/FusionBenchmarks.cs @@ -0,0 +1,508 @@ +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Order; + +namespace NumSharp.Benchmark.GraphEngine; + +/// +/// Compares multi-pass (current NumSharp) vs fused kernel approaches. +/// This benchmark answers: "How much faster can compound expressions be with kernel fusion?" +/// +/// Patterns tested: +/// - Pattern 1: c = a * a (DUP optimization) +/// - Pattern 2: c = a*a + 2*b (DUP + constant baking) +/// - Pattern 3: variance = sum((a-mean)²)/N (fused reduction) +/// - Pattern 4: c = a³ + a² + a (STLOC/LDLOC for 3+ uses) +/// - Pattern 5: c = sqrt(a² + b²) (multi-input DAG) +/// +[MemoryDiagnoser] +[Orderer(SummaryOrderPolicy.FastestToSlowest)] +[RankColumn] +public unsafe class FusionBenchmarks +{ + private double* _a; + private double* _b; + private double* _c; + private double* _t1; + private double* _t2; + private double* _t3; + private double _mean; + + // Pre-compiled fused kernels + private Action? _fusedSquare; + private Action? _fusedAaBb; + private Func? _fusedVariance; + private Action? _fusedPolynomial; + private Action? _fusedEuclidean; + + [Params(10_000_000)] + public int N { get; set; } + + [GlobalSetup] + public void Setup() + { + _a = (double*)NativeMemory.AlignedAlloc((nuint)(N * sizeof(double)), 64); + _b = (double*)NativeMemory.AlignedAlloc((nuint)(N * sizeof(double)), 64); + _c = (double*)NativeMemory.AlignedAlloc((nuint)(N * sizeof(double)), 64); + _t1 = (double*)NativeMemory.AlignedAlloc((nuint)(N * sizeof(double)), 64); + _t2 = (double*)NativeMemory.AlignedAlloc((nuint)(N * sizeof(double)), 64); + _t3 = (double*)NativeMemory.AlignedAlloc((nuint)(N * sizeof(double)), 64); + + var rng = new Random(42); + double sum = 0; + for (int i = 0; i < N; i++) + { + _a[i] = rng.NextDouble() * 10; + _b[i] = rng.NextDouble() * 10; + sum += _a[i]; + } + _mean = sum / N; + + // Pre-compile all fused kernels + _fusedSquare = EmitFusedSquare().CreateDelegate>(); + _fusedAaBb = EmitFusedAaBb().CreateDelegate>(); + _fusedVariance = EmitFusedVariance(_mean).CreateDelegate>(); + _fusedPolynomial = EmitFusedPolynomial().CreateDelegate>(); + _fusedEuclidean = EmitFusedEuclidean().CreateDelegate>(); + } + + [GlobalCleanup] + public void Cleanup() + { + NativeMemory.AlignedFree(_a); + NativeMemory.AlignedFree(_b); + NativeMemory.AlignedFree(_c); + NativeMemory.AlignedFree(_t1); + NativeMemory.AlignedFree(_t2); + NativeMemory.AlignedFree(_t3); + } + + // ======================================================================== + // Pattern 1: c = a * a + // ======================================================================== + + [Benchmark(Baseline = true, Description = "Multi-pass: t1=a*a, c=t1")] + [BenchmarkCategory("Pattern1_Square")] + public void Pattern1_MultiPass() + { + var a = _a; + var c = _c; + var n = N; + // Two memory reads per element (compiler may or may not optimize) + for (int i = 0; i < n; i++) + c[i] = a[i] * a[i]; + } + + [Benchmark(Description = "Fused DynMethod (DUP)")] + [BenchmarkCategory("Pattern1_Square")] + public void Pattern1_Fused() + { + _fusedSquare!((nint)_a, (nint)_c, N); + } + + // ======================================================================== + // Pattern 2: c = a*a + 2*b + // ======================================================================== + + [Benchmark(Baseline = true, Description = "3-pass: t1=a*a, t2=2*b, c=t1+t2")] + [BenchmarkCategory("Pattern2_AaBb")] + public void Pattern2_MultiPass() + { + var a = _a; + var b = _b; + var c = _c; + var t1 = _t1; + var t2 = _t2; + var n = N; + + for (int i = 0; i < n; i++) t1[i] = a[i] * a[i]; + for (int i = 0; i < n; i++) t2[i] = 2.0 * b[i]; + for (int i = 0; i < n; i++) c[i] = t1[i] + t2[i]; + } + + [Benchmark(Description = "Single raw loop")] + [BenchmarkCategory("Pattern2_AaBb")] + public void Pattern2_SingleLoop() + { + var a = _a; + var b = _b; + var c = _c; + var n = N; + for (int i = 0; i < n; i++) + c[i] = a[i] * a[i] + 2.0 * b[i]; + } + + [Benchmark(Description = "Fused DynMethod (DUP + const)")] + [BenchmarkCategory("Pattern2_AaBb")] + public void Pattern2_Fused() + { + _fusedAaBb!((nint)_a, (nint)_b, (nint)_c, N); + } + + // ======================================================================== + // Pattern 3: variance = sum((a - mean)²) / N + // ======================================================================== + + [Benchmark(Baseline = true, Description = "3-pass: t1=a-mean, t2=t1², sum(t2)/N")] + [BenchmarkCategory("Pattern3_Variance")] + public double Pattern3_MultiPass() + { + var a = _a; + var t1 = _t1; + var t2 = _t2; + var mean = _mean; + var n = N; + + for (int i = 0; i < n; i++) t1[i] = a[i] - mean; + for (int i = 0; i < n; i++) t2[i] = t1[i] * t1[i]; + double sum = 0; + for (int i = 0; i < n; i++) sum += t2[i]; + return sum / n; + } + + [Benchmark(Description = "Single raw loop")] + [BenchmarkCategory("Pattern3_Variance")] + public double Pattern3_SingleLoop() + { + var a = _a; + var mean = _mean; + var n = N; + double sum = 0; + for (int i = 0; i < n; i++) + { + var diff = a[i] - mean; + sum += diff * diff; + } + return sum / n; + } + + [Benchmark(Description = "Fused DynMethod (baked mean + reduction)")] + [BenchmarkCategory("Pattern3_Variance")] + public double Pattern3_Fused() + { + return _fusedVariance!((nint)_a, N) / N; + } + + // ======================================================================== + // Pattern 4: c = a³ + a² + a + // ======================================================================== + + [Benchmark(Baseline = true, Description = "4-pass: t1=a³, t2=a², t3=t1+t2, c=t3+a")] + [BenchmarkCategory("Pattern4_Polynomial")] + public void Pattern4_MultiPass() + { + var a = _a; + var c = _c; + var t1 = _t1; + var t2 = _t2; + var t3 = _t3; + var n = N; + + for (int i = 0; i < n; i++) t1[i] = a[i] * a[i] * a[i]; + for (int i = 0; i < n; i++) t2[i] = a[i] * a[i]; + for (int i = 0; i < n; i++) t3[i] = t1[i] + t2[i]; + for (int i = 0; i < n; i++) c[i] = t3[i] + a[i]; + } + + [Benchmark(Description = "Single raw loop")] + [BenchmarkCategory("Pattern4_Polynomial")] + public void Pattern4_SingleLoop() + { + var a = _a; + var c = _c; + var n = N; + for (int i = 0; i < n; i++) + { + var ai = a[i]; + c[i] = ai * ai * ai + ai * ai + ai; + } + } + + [Benchmark(Description = "Fused DynMethod (STLOC/LDLOC)")] + [BenchmarkCategory("Pattern4_Polynomial")] + public void Pattern4_Fused() + { + _fusedPolynomial!((nint)_a, (nint)_c, N); + } + + // ======================================================================== + // Pattern 5: c = sqrt(a² + b²) + // ======================================================================== + + [Benchmark(Baseline = true, Description = "4-pass: t1=a², t2=b², t3=t1+t2, c=sqrt(t3)")] + [BenchmarkCategory("Pattern5_Euclidean")] + public void Pattern5_MultiPass() + { + var a = _a; + var b = _b; + var c = _c; + var t1 = _t1; + var t2 = _t2; + var t3 = _t3; + var n = N; + + for (int i = 0; i < n; i++) t1[i] = a[i] * a[i]; + for (int i = 0; i < n; i++) t2[i] = b[i] * b[i]; + for (int i = 0; i < n; i++) t3[i] = t1[i] + t2[i]; + for (int i = 0; i < n; i++) c[i] = Math.Sqrt(t3[i]); + } + + [Benchmark(Description = "Single raw loop")] + [BenchmarkCategory("Pattern5_Euclidean")] + public void Pattern5_SingleLoop() + { + var a = _a; + var b = _b; + var c = _c; + var n = N; + for (int i = 0; i < n; i++) + { + var ai = a[i]; + var bi = b[i]; + c[i] = Math.Sqrt(ai * ai + bi * bi); + } + } + + [Benchmark(Description = "Fused DynMethod (multi-input STLOC)")] + [BenchmarkCategory("Pattern5_Euclidean")] + public void Pattern5_Fused() + { + _fusedEuclidean!((nint)_a, (nint)_b, (nint)_c, N); + } + + // ======================================================================== + // DynamicMethod Builders + // ======================================================================== + + private static DynamicMethod EmitFusedSquare() + { + // c[i] = a[i] * a[i] using DUP + var dm = new DynamicMethod("FusedSquare", typeof(void), + [typeof(nint), typeof(nint), typeof(int)], typeof(FusionBenchmarks).Module, true); + var il = dm.GetILGenerator(); + var top = il.DefineLabel(); + var chk = il.DefineLabel(); + il.DeclareLocal(typeof(int)); + + il.Emit(OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Stloc_0); + il.Emit(OpCodes.Br, chk); + + il.MarkLabel(top); + EmitPtrOfs8(il, 1); // &c[i] + EmitLoad8(il, 0); // a[i] + il.Emit(OpCodes.Dup); // a[i], a[i] - ONE load, DUP on stack + il.Emit(OpCodes.Mul); // a[i]² + il.Emit(OpCodes.Stind_R8); + EmitIncr(il); + + il.MarkLabel(chk); + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldarg_2); + il.Emit(OpCodes.Blt, top); + il.Emit(OpCodes.Ret); + return dm; + } + + private static DynamicMethod EmitFusedAaBb() + { + // c[i] = a[i]*a[i] + 2*b[i] + var dm = new DynamicMethod("FusedAaBb", typeof(void), + [typeof(nint), typeof(nint), typeof(nint), typeof(int)], typeof(FusionBenchmarks).Module, true); + var il = dm.GetILGenerator(); + var top = il.DefineLabel(); + var chk = il.DefineLabel(); + il.DeclareLocal(typeof(int)); + + il.Emit(OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Stloc_0); + il.Emit(OpCodes.Br, chk); + + il.MarkLabel(top); + EmitPtrOfs8(il, 2); // &c[i] + EmitLoad8(il, 0); // a[i] + il.Emit(OpCodes.Dup); // a[i], a[i] + il.Emit(OpCodes.Mul); // a[i]² + il.Emit(OpCodes.Ldc_R8, 2.0); // constant baked into IL + EmitLoad8(il, 1); // b[i] + il.Emit(OpCodes.Mul); // 2*b[i] + il.Emit(OpCodes.Add); // a[i]² + 2*b[i] + il.Emit(OpCodes.Stind_R8); + EmitIncr(il); + + il.MarkLabel(chk); + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldarg_3); + il.Emit(OpCodes.Blt, top); + il.Emit(OpCodes.Ret); + return dm; + } + + private static DynamicMethod EmitFusedVariance(double mean) + { + // returns sum((a[i] - mean)²) with mean baked as constant + var dm = new DynamicMethod("FusedVariance", typeof(double), + [typeof(nint), typeof(int)], typeof(FusionBenchmarks).Module, true); + var il = dm.GetILGenerator(); + var top = il.DefineLabel(); + var chk = il.DefineLabel(); + il.DeclareLocal(typeof(int)); // i + il.DeclareLocal(typeof(double)); // accumulator + + il.Emit(OpCodes.Ldc_R8, 0.0); + il.Emit(OpCodes.Stloc_1); + il.Emit(OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Stloc_0); + il.Emit(OpCodes.Br, chk); + + il.MarkLabel(top); + // diff = a[i] - mean + EmitLoad8(il, 0); // a[i] + il.Emit(OpCodes.Ldc_R8, mean); // mean BAKED as constant + il.Emit(OpCodes.Sub); // diff + il.Emit(OpCodes.Dup); // diff, diff + il.Emit(OpCodes.Mul); // diff² + // acc += diff² + il.Emit(OpCodes.Ldloc_1); + il.Emit(OpCodes.Add); + il.Emit(OpCodes.Stloc_1); + EmitIncr(il); + + il.MarkLabel(chk); + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Blt, top); + + il.Emit(OpCodes.Ldloc_1); + il.Emit(OpCodes.Ret); + return dm; + } + + private static DynamicMethod EmitFusedPolynomial() + { + // c[i] = a[i]³ + a[i]² + a[i] using STLOC/LDLOC + var dm = new DynamicMethod("FusedPolynomial", typeof(void), + [typeof(nint), typeof(nint), typeof(int)], typeof(FusionBenchmarks).Module, true); + var il = dm.GetILGenerator(); + var top = il.DefineLabel(); + var chk = il.DefineLabel(); + il.DeclareLocal(typeof(int)); // i + il.DeclareLocal(typeof(double)); // cached a[i] + + il.Emit(OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Stloc_0); + il.Emit(OpCodes.Br, chk); + + il.MarkLabel(top); + EmitPtrOfs8(il, 1); // &c[i] + EmitLoad8(il, 0); // a[i] - ONE memory read + il.Emit(OpCodes.Stloc_1); // save to local (becomes CPU register) + + // a[i]³ + il.Emit(OpCodes.Ldloc_1); + il.Emit(OpCodes.Ldloc_1); + il.Emit(OpCodes.Mul); + il.Emit(OpCodes.Ldloc_1); + il.Emit(OpCodes.Mul); + + // + a[i]² + il.Emit(OpCodes.Ldloc_1); + il.Emit(OpCodes.Ldloc_1); + il.Emit(OpCodes.Mul); + il.Emit(OpCodes.Add); + + // + a[i] + il.Emit(OpCodes.Ldloc_1); + il.Emit(OpCodes.Add); + + il.Emit(OpCodes.Stind_R8); + EmitIncr(il); + + il.MarkLabel(chk); + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldarg_2); + il.Emit(OpCodes.Blt, top); + il.Emit(OpCodes.Ret); + return dm; + } + + private static DynamicMethod EmitFusedEuclidean() + { + // c[i] = sqrt(a[i]² + b[i]²) + var sqrtM = typeof(Math).GetMethod("Sqrt", [typeof(double)])!; + + var dm = new DynamicMethod("FusedEuclidean", typeof(void), + [typeof(nint), typeof(nint), typeof(nint), typeof(int)], typeof(FusionBenchmarks).Module, true); + var il = dm.GetILGenerator(); + var top = il.DefineLabel(); + var chk = il.DefineLabel(); + il.DeclareLocal(typeof(int)); // i + il.DeclareLocal(typeof(double)); // a[i] + il.DeclareLocal(typeof(double)); // b[i] + + il.Emit(OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Stloc_0); + il.Emit(OpCodes.Br, chk); + + il.MarkLabel(top); + EmitPtrOfs8(il, 2); // &c[i] + + // Cache both inputs + EmitLoad8(il, 0); // a[i] + il.Emit(OpCodes.Stloc_1); + EmitLoad8(il, 1); // b[i] + il.Emit(OpCodes.Stloc_2); + + // a² + b² + il.Emit(OpCodes.Ldloc_1); + il.Emit(OpCodes.Ldloc_1); + il.Emit(OpCodes.Mul); + il.Emit(OpCodes.Ldloc_2); + il.Emit(OpCodes.Ldloc_2); + il.Emit(OpCodes.Mul); + il.Emit(OpCodes.Add); + + // sqrt + il.EmitCall(OpCodes.Call, sqrtM, null); + il.Emit(OpCodes.Stind_R8); + EmitIncr(il); + + il.MarkLabel(chk); + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldarg_3); + il.Emit(OpCodes.Blt, top); + il.Emit(OpCodes.Ret); + return dm; + } + + // ======================================================================== + // IL Helpers + // ======================================================================== + + private static void EmitPtrOfs8(ILGenerator il, int argIdx) + { + il.Emit(OpCodes.Ldarg, argIdx); + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Conv_I); + il.Emit(OpCodes.Ldc_I4_8); + il.Emit(OpCodes.Mul); + il.Emit(OpCodes.Add); + } + + private static void EmitLoad8(ILGenerator il, int argIdx) + { + EmitPtrOfs8(il, argIdx); + il.Emit(OpCodes.Ldind_R8); + } + + private static void EmitIncr(ILGenerator il) + { + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Add); + il.Emit(OpCodes.Stloc_0); + } +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Manipulation/DimsBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Manipulation/DimsBenchmarks.cs new file mode 100644 index 000000000..0608def3a --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Manipulation/DimsBenchmarks.cs @@ -0,0 +1,95 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Manipulation; + +/// +/// Benchmarks for dimension manipulation: squeeze, expand_dims, swapaxes, moveaxis. +/// +[BenchmarkCategory("Manipulation", "Dims")] +public class DimsBenchmarks : BenchmarkBase +{ + private NDArray _arr1D = null!; + private NDArray _arr2D = null!; + private NDArray _arr3D = null!; + private NDArray _arrWithSingleton = null!; + + [Params(ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + [GlobalSetup] + public void Setup() + { + np.random.seed(Seed); + _arr1D = np.random.rand(N) * 100; + + var rows = (int)Math.Sqrt(N); + var cols = N / rows; + _arr2D = np.random.rand(rows, cols) * 100; + + var d = (int)Math.Pow(N, 1.0 / 3); + _arr3D = np.random.rand(d, d, d) * 100; + + // Array with singleton dimensions for squeeze tests + _arrWithSingleton = np.random.rand(rows, 1, cols) * 100; + } + + [GlobalCleanup] + public void Cleanup() + { + _arr1D = null!; + _arr2D = null!; + _arr3D = null!; + _arrWithSingleton = null!; + GC.Collect(); + } + + // ======================================================================== + // Expand Dims + // ======================================================================== + + [Benchmark(Description = "np.expand_dims(a, axis=0)")] + [BenchmarkCategory("ExpandDims")] + public NDArray ExpandDims_Axis0() => np.expand_dims(_arr1D, axis: 0); + + [Benchmark(Description = "np.expand_dims(a, axis=-1)")] + [BenchmarkCategory("ExpandDims")] + public NDArray ExpandDims_AxisNeg1() => np.expand_dims(_arr1D, axis: -1); + + [Benchmark(Description = "np.expand_dims(a2D, axis=1)")] + [BenchmarkCategory("ExpandDims")] + public NDArray ExpandDims_2D_Axis1() => np.expand_dims(_arr2D, axis: 1); + + // ======================================================================== + // Squeeze + // ======================================================================== + + [Benchmark(Description = "np.squeeze(a)")] + [BenchmarkCategory("Squeeze")] + public NDArray Squeeze() => np.squeeze(_arrWithSingleton); + + [Benchmark(Description = "np.squeeze(a, axis=1)")] + [BenchmarkCategory("Squeeze")] + public NDArray Squeeze_Axis1() => np.squeeze(_arrWithSingleton, axis: 1); + + // ======================================================================== + // Swap / Move Axes + // ======================================================================== + + [Benchmark(Description = "np.swapaxes(a, 0, 1)")] + [BenchmarkCategory("SwapAxes")] + public NDArray SwapAxes_01() => np.swapaxes(_arr2D, 0, 1); + + [Benchmark(Description = "np.swapaxes(a3D, 0, 2)")] + [BenchmarkCategory("SwapAxes")] + public NDArray SwapAxes_3D_02() => np.swapaxes(_arr3D, 0, 2); + + [Benchmark(Description = "np.moveaxis(a, 0, -1)")] + [BenchmarkCategory("MoveAxis")] + public NDArray MoveAxis_0_to_Neg1() => np.moveaxis(_arr3D, 0, -1); + + [Benchmark(Description = "np.rollaxis(a, 2)")] + [BenchmarkCategory("RollAxis")] + public NDArray RollAxis() => np.rollaxis(_arr3D, 2); +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Manipulation/ReshapeBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Manipulation/ReshapeBenchmarks.cs new file mode 100644 index 000000000..ecaae90db --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Manipulation/ReshapeBenchmarks.cs @@ -0,0 +1,108 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Manipulation; + +/// +/// Benchmarks for reshape and transpose operations. +/// +[BenchmarkCategory("Manipulation", "Reshape")] +public class ReshapeBenchmarks : BenchmarkBase +{ + private NDArray _arr1D = null!; + private NDArray _arr2D = null!; + private NDArray _arr3D = null!; + + [Params(ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + [GlobalSetup] + public void Setup() + { + np.random.seed(Seed); + _arr1D = np.random.rand(N) * 100; + + var rows = (int)Math.Sqrt(N); + var cols = N / rows; + _arr2D = np.random.rand(rows, cols) * 100; + + var d = (int)Math.Pow(N, 1.0 / 3); + _arr3D = np.random.rand(d, d, d) * 100; + } + + [GlobalCleanup] + public void Cleanup() + { + _arr1D = null!; + _arr2D = null!; + _arr3D = null!; + GC.Collect(); + } + + // ======================================================================== + // Reshape + // ======================================================================== + + [Benchmark(Description = "reshape 1D -> 2D")] + [BenchmarkCategory("Reshape")] + public NDArray Reshape_1D_to_2D() + { + var rows = (int)Math.Sqrt(N); + var cols = N / rows; + return _arr1D.reshape(rows, cols); + } + + [Benchmark(Description = "reshape 2D -> 1D")] + [BenchmarkCategory("Reshape")] + public NDArray Reshape_2D_to_1D() => _arr2D.reshape(-1); + + [Benchmark(Description = "reshape 1D -> 3D")] + [BenchmarkCategory("Reshape")] + public NDArray Reshape_1D_to_3D() + { + var d = (int)Math.Pow(N, 1.0 / 3); + return _arr1D.reshape(d, d, -1); + } + + [Benchmark(Description = "np.reshape(a, shape)")] + [BenchmarkCategory("Reshape")] + public NDArray NpReshape() + { + var rows = (int)Math.Sqrt(N); + var cols = N / rows; + return np.reshape(_arr1D, new Shape(rows, cols)); + } + + // ======================================================================== + // Transpose + // ======================================================================== + + [Benchmark(Description = "a.T (transpose 2D)")] + [BenchmarkCategory("Transpose")] + public NDArray Transpose_2D() => _arr2D.T; + + [Benchmark(Description = "np.transpose(a)")] + [BenchmarkCategory("Transpose")] + public NDArray NpTranspose_2D() => np.transpose(_arr2D); + + [Benchmark(Description = "np.transpose(a, axes)")] + [BenchmarkCategory("Transpose")] + public NDArray NpTranspose_3D_Axes() => np.transpose(_arr3D, new[] { 2, 0, 1 }); + + // ======================================================================== + // Ravel / Flatten + // ======================================================================== + + [Benchmark(Description = "a.ravel() (view)")] + [BenchmarkCategory("Flatten")] + public NDArray Ravel() => _arr2D.ravel(); + + [Benchmark(Description = "np.ravel(a)")] + [BenchmarkCategory("Flatten")] + public NDArray NpRavel() => np.ravel(_arr2D); + + [Benchmark(Description = "a.flatten() (copy)")] + [BenchmarkCategory("Flatten")] + public NDArray Flatten() => _arr2D.flatten(); +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Manipulation/StackBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Manipulation/StackBenchmarks.cs new file mode 100644 index 000000000..9546403da --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Manipulation/StackBenchmarks.cs @@ -0,0 +1,94 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Manipulation; + +/// +/// Benchmarks for stacking and concatenation operations. +/// +[BenchmarkCategory("Manipulation", "Stack")] +public class StackBenchmarks : BenchmarkBase +{ + private NDArray _arr1D_a = null!; + private NDArray _arr1D_b = null!; + private NDArray _arr1D_c = null!; + private NDArray _arr2D_a = null!; + private NDArray _arr2D_b = null!; + + [Params(ArraySizeSource.Small, ArraySizeSource.Medium)] + public override int N { get; set; } + + [GlobalSetup] + public void Setup() + { + np.random.seed(Seed); + _arr1D_a = np.random.rand(N) * 100; + _arr1D_b = np.random.rand(N) * 100; + _arr1D_c = np.random.rand(N) * 100; + + var rows = (int)Math.Sqrt(N); + var cols = N / rows; + _arr2D_a = np.random.rand(rows, cols) * 100; + _arr2D_b = np.random.rand(rows, cols) * 100; + } + + [GlobalCleanup] + public void Cleanup() + { + _arr1D_a = null!; + _arr1D_b = null!; + _arr1D_c = null!; + _arr2D_a = null!; + _arr2D_b = null!; + GC.Collect(); + } + + // ======================================================================== + // Concatenate + // ======================================================================== + + [Benchmark(Description = "np.concatenate([a, b])")] + [BenchmarkCategory("Concatenate")] + public NDArray Concatenate_2() => np.concatenate(new[] { _arr1D_a, _arr1D_b }); + + [Benchmark(Description = "np.concatenate([a, b, c])")] + [BenchmarkCategory("Concatenate")] + public NDArray Concatenate_3() => np.concatenate(new[] { _arr1D_a, _arr1D_b, _arr1D_c }); + + [Benchmark(Description = "np.concatenate([a, b], axis=0)")] + [BenchmarkCategory("Concatenate")] + public NDArray Concatenate_2D_Axis0() => np.concatenate(new[] { _arr2D_a, _arr2D_b }, axis: 0); + + [Benchmark(Description = "np.concatenate([a, b], axis=1)")] + [BenchmarkCategory("Concatenate")] + public NDArray Concatenate_2D_Axis1() => np.concatenate(new[] { _arr2D_a, _arr2D_b }, axis: 1); + + // ======================================================================== + // Stack + // ======================================================================== + + [Benchmark(Description = "np.stack([a, b])")] + [BenchmarkCategory("Stack")] + public NDArray Stack_2() => np.stack(new[] { _arr1D_a, _arr1D_b }); + + [Benchmark(Description = "np.stack([a, b], axis=1)")] + [BenchmarkCategory("Stack")] + public NDArray Stack_2_Axis1() => np.stack(new[] { _arr1D_a, _arr1D_b }, axis: 1); + + // ======================================================================== + // HStack / VStack / DStack + // ======================================================================== + + [Benchmark(Description = "np.hstack([a, b])")] + [BenchmarkCategory("HVDStack")] + public NDArray HStack() => np.hstack(_arr1D_a, _arr1D_b); + + [Benchmark(Description = "np.vstack([a, b])")] + [BenchmarkCategory("HVDStack")] + public NDArray VStack() => np.vstack(_arr1D_a, _arr1D_b); + + [Benchmark(Description = "np.dstack([a, b])")] + [BenchmarkCategory("HVDStack")] + public NDArray DStack() => np.dstack(_arr2D_a, _arr2D_b); +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/MultiDim/MultiDimBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/MultiDim/MultiDimBenchmarks.cs new file mode 100644 index 000000000..12fc08693 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/MultiDim/MultiDimBenchmarks.cs @@ -0,0 +1,124 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.MultiDim; + +/// +/// Benchmarks comparing 1D, 2D, and 3D array operations. +/// Tests overhead of multi-dimensional indexing vs contiguous memory access. +/// +[BenchmarkCategory("MultiDim")] +public class MultiDimBenchmarks : BenchmarkBase +{ + private NDArray _arr1D = null!; + private NDArray _arr2D = null!; + private NDArray _arr3D = null!; + private NDArray _arr1D_b = null!; + private NDArray _arr2D_b = null!; + private NDArray _arr3D_b = null!; + + // Total elements constant across all dimensions + [Params(1_000_000, 10_000_000)] + public override int N { get; set; } + + [GlobalSetup] + public void Setup() + { + np.random.seed(Seed); + + // 1D: N elements + _arr1D = np.random.rand(N) * 100; + _arr1D_b = np.random.rand(N) * 100; + + // 2D: sqrt(N) x sqrt(N) ≈ N elements + var dim2d = (int)Math.Sqrt(N); + _arr2D = np.random.rand(dim2d, dim2d) * 100; + _arr2D_b = np.random.rand(dim2d, dim2d) * 100; + + // 3D: cbrt(N) x cbrt(N) x cbrt(N) ≈ N elements + var dim3d = (int)Math.Pow(N, 1.0 / 3); + _arr3D = np.random.rand(dim3d, dim3d, dim3d) * 100; + _arr3D_b = np.random.rand(dim3d, dim3d, dim3d) * 100; + } + + [GlobalCleanup] + public void Cleanup() + { + _arr1D = null!; + _arr2D = null!; + _arr3D = null!; + _arr1D_b = null!; + _arr2D_b = null!; + _arr3D_b = null!; + GC.Collect(); + } + + // ======================================================================== + // Element-wise Addition + // ======================================================================== + + [Benchmark(Description = "1D: a + b")] + [BenchmarkCategory("Add")] + public NDArray Add_1D() => _arr1D + _arr1D_b; + + [Benchmark(Description = "2D: a + b")] + [BenchmarkCategory("Add")] + public NDArray Add_2D() => _arr2D + _arr2D_b; + + [Benchmark(Description = "3D: a + b")] + [BenchmarkCategory("Add")] + public NDArray Add_3D() => _arr3D + _arr3D_b; + + // ======================================================================== + // Reductions + // ======================================================================== + + [Benchmark(Description = "1D: np.sum(a)")] + [BenchmarkCategory("Sum")] + public NDArray Sum_1D() => np.sum(_arr1D); + + [Benchmark(Description = "2D: np.sum(a)")] + [BenchmarkCategory("Sum")] + public NDArray Sum_2D() => np.sum(_arr2D); + + [Benchmark(Description = "3D: np.sum(a)")] + [BenchmarkCategory("Sum")] + public NDArray Sum_3D() => np.sum(_arr3D); + + // ======================================================================== + // Axis Reductions + // ======================================================================== + + [Benchmark(Description = "2D: np.sum(a, axis=0)")] + [BenchmarkCategory("SumAxis")] + public NDArray Sum_2D_Axis0() => np.sum(_arr2D, axis: 0); + + [Benchmark(Description = "2D: np.sum(a, axis=1)")] + [BenchmarkCategory("SumAxis")] + public NDArray Sum_2D_Axis1() => np.sum(_arr2D, axis: 1); + + [Benchmark(Description = "3D: np.sum(a, axis=0)")] + [BenchmarkCategory("SumAxis")] + public NDArray Sum_3D_Axis0() => np.sum(_arr3D, axis: 0); + + [Benchmark(Description = "3D: np.sum(a, axis=2)")] + [BenchmarkCategory("SumAxis")] + public NDArray Sum_3D_Axis2() => np.sum(_arr3D, axis: 2); + + // ======================================================================== + // Unary Operations + // ======================================================================== + + [Benchmark(Description = "1D: np.sqrt(a)")] + [BenchmarkCategory("Sqrt")] + public NDArray Sqrt_1D() => np.sqrt(_arr1D); + + [Benchmark(Description = "2D: np.sqrt(a)")] + [BenchmarkCategory("Sqrt")] + public NDArray Sqrt_2D() => np.sqrt(_arr2D); + + [Benchmark(Description = "3D: np.sqrt(a)")] + [BenchmarkCategory("Sqrt")] + public NDArray Sqrt_3D() => np.sqrt(_arr3D); +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/NumSharpBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/NumSharpBenchmarks.cs new file mode 100644 index 000000000..7f6d34b48 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/NumSharpBenchmarks.cs @@ -0,0 +1,117 @@ +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Order; +using NumSharp; + +namespace NumSharp.Benchmark.GraphEngine; + +/// +/// Benchmarks NumSharp's actual current performance. +/// This measures the real-world performance of the library as users experience it. +/// +[MemoryDiagnoser] +[Orderer(SummaryOrderPolicy.FastestToSlowest)] +[RankColumn] +public class NumSharpBenchmarks +{ + private NDArray _aInt32 = null!; + private NDArray _bInt32 = null!; + private NDArray _aFloat64 = null!; + private NDArray _bFloat64 = null!; + + [Params(1_000, 100_000, 10_000_000)] + public int N { get; set; } + + [GlobalSetup] + public void Setup() + { + np.random.seed(42); + _aInt32 = np.random.randint(0, 100, new Shape(N)).astype(np.int32); + _bInt32 = np.random.randint(0, 100, new Shape(N)).astype(np.int32); + _aFloat64 = np.random.rand(N) * 10; + _bFloat64 = np.random.rand(N) * 10; + } + + // ======================================================================== + // Binary Operations (int32) + // ======================================================================== + + [Benchmark(Description = "NumSharp: a + b (int32)")] + [BenchmarkCategory("Binary_Int32")] + public NDArray Add_Int32() => _aInt32 + _bInt32; + + [Benchmark(Description = "NumSharp: a - b (int32)")] + [BenchmarkCategory("Binary_Int32")] + public NDArray Subtract_Int32() => _aInt32 - _bInt32; + + [Benchmark(Description = "NumSharp: a * b (int32)")] + [BenchmarkCategory("Binary_Int32")] + public NDArray Multiply_Int32() => _aInt32 * _bInt32; + + // ======================================================================== + // Binary Operations (float64) + // ======================================================================== + + [Benchmark(Description = "NumSharp: a + b (float64)")] + [BenchmarkCategory("Binary_Float64")] + public NDArray Add_Float64() => _aFloat64 + _bFloat64; + + [Benchmark(Description = "NumSharp: a * a (float64)")] + [BenchmarkCategory("Binary_Float64")] + public NDArray Square_Float64() => _aFloat64 * _aFloat64; + + // ======================================================================== + // Compound Expressions (float64) + // ======================================================================== + + [Benchmark(Description = "NumSharp: a*a + 2*b")] + [BenchmarkCategory("Compound")] + public NDArray Compound_AaBb() => _aFloat64 * _aFloat64 + 2 * _bFloat64; + + [Benchmark(Description = "NumSharp: a*a*a + a*a + a")] + [BenchmarkCategory("Compound")] + public NDArray Compound_Polynomial() => _aFloat64 * _aFloat64 * _aFloat64 + _aFloat64 * _aFloat64 + _aFloat64; + + [Benchmark(Description = "NumSharp: sqrt(a*a + b*b)")] + [BenchmarkCategory("Compound")] + public NDArray Compound_Euclidean() => np.sqrt(_aFloat64 * _aFloat64 + _bFloat64 * _bFloat64); + + // ======================================================================== + // Reductions (float64) + // ======================================================================== + + [Benchmark(Description = "NumSharp: np.sum(a)")] + [BenchmarkCategory("Reduction")] + public NDArray Sum() => np.sum(_aFloat64); + + [Benchmark(Description = "NumSharp: np.mean(a)")] + [BenchmarkCategory("Reduction")] + public NDArray Mean() => np.mean(_aFloat64); + + [Benchmark(Description = "NumSharp: np.var(a)")] + [BenchmarkCategory("Reduction")] + public NDArray Variance() => np.var(_aFloat64); + + [Benchmark(Description = "NumSharp: np.std(a)")] + [BenchmarkCategory("Reduction")] + public NDArray StdDev() => np.std(_aFloat64); + + // ======================================================================== + // Unary Operations (float64) + // ======================================================================== + + [Benchmark(Description = "NumSharp: np.sqrt(a)")] + [BenchmarkCategory("Unary")] + public NDArray Sqrt() => np.sqrt(_aFloat64); + + [Benchmark(Description = "NumSharp: np.abs(a)")] + [BenchmarkCategory("Unary")] + public NDArray Abs() => np.abs(_aFloat64); + + [Benchmark(Description = "NumSharp: np.exp(a)")] + [BenchmarkCategory("Unary")] + public NDArray Exp() => np.exp(_aFloat64); + + [Benchmark(Description = "NumSharp: np.log(a)")] + [BenchmarkCategory("Unary")] + public NDArray Log() => np.log(_aFloat64); +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Reduction/MeanBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Reduction/MeanBenchmarks.cs new file mode 100644 index 000000000..9d59e0a22 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Reduction/MeanBenchmarks.cs @@ -0,0 +1,58 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Reduction; + +/// +/// Benchmarks for mean reduction operations. +/// +[BenchmarkCategory("Reduction", "Mean")] +public class MeanBenchmarks : TypedBenchmarkBase +{ + private NDArray _a1D = null!; + private NDArray _a2D = null!; + + [Params(ArraySizeSource.Small, ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + // Mean typically produces floating-point result + [ParamsSource(nameof(Types))] + public new NPTypeCode DType { get; set; } + + public static IEnumerable Types => TypeParameterSource.CommonTypes; + + [GlobalSetup] + public void Setup() + { + _a1D = CreateRandomArray(N, DType); + + var rows = (int)Math.Sqrt(N); + var cols = N / rows; + _a2D = CreateRandomArray(rows * cols, DType).reshape(rows, cols); + } + + [GlobalCleanup] + public void Cleanup() + { + _a1D = null!; + _a2D = null!; + GC.Collect(); + } + + [Benchmark(Description = "np.mean(a) [full]")] + [BenchmarkCategory("Full")] + public NDArray Mean_Full() => np.mean(_a1D); + + [Benchmark(Description = "a.mean() [method]")] + [BenchmarkCategory("Full")] + public NDArray Mean_Method() => _a1D.mean(); + + [Benchmark(Description = "np.mean(a, axis=0)")] + [BenchmarkCategory("Axis")] + public NDArray Mean_Axis0() => np.mean(_a2D, axis: 0); + + [Benchmark(Description = "np.mean(a, axis=1)")] + [BenchmarkCategory("Axis")] + public NDArray Mean_Axis1() => np.mean(_a2D, axis: 1); +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Reduction/MinMaxBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Reduction/MinMaxBenchmarks.cs new file mode 100644 index 000000000..31a47f500 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Reduction/MinMaxBenchmarks.cs @@ -0,0 +1,85 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Reduction; + +/// +/// Benchmarks for min/max reduction operations. +/// +[BenchmarkCategory("Reduction", "MinMax")] +public class MinMaxBenchmarks : TypedBenchmarkBase +{ + private NDArray _a1D = null!; + private NDArray _a2D = null!; + + [Params(ArraySizeSource.Small, ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + [ParamsSource(nameof(Types))] + public new NPTypeCode DType { get; set; } + + public static IEnumerable Types => TypeParameterSource.ArithmeticTypes; + + [GlobalSetup] + public void Setup() + { + _a1D = CreateRandomArray(N, DType); + + var rows = (int)Math.Sqrt(N); + var cols = N / rows; + _a2D = CreateRandomArray(rows * cols, DType).reshape(rows, cols); + } + + [GlobalCleanup] + public void Cleanup() + { + _a1D = null!; + _a2D = null!; + GC.Collect(); + } + + // ======================================================================== + // Min + // ======================================================================== + + [Benchmark(Description = "np.amin(a) [full]")] + [BenchmarkCategory("Min")] + public NDArray AMin_Full() => np.amin(_a1D); + + [Benchmark(Description = "a.amin() [method]")] + [BenchmarkCategory("Min")] + public NDArray AMin_Method() => _a1D.amin(); + + [Benchmark(Description = "np.amin(a, axis=0)")] + [BenchmarkCategory("Min")] + public NDArray AMin_Axis0() => np.amin(_a2D, axis: 0); + + // ======================================================================== + // Max + // ======================================================================== + + [Benchmark(Description = "np.amax(a) [full]")] + [BenchmarkCategory("Max")] + public NDArray AMax_Full() => np.amax(_a1D); + + [Benchmark(Description = "a.amax() [method]")] + [BenchmarkCategory("Max")] + public NDArray AMax_Method() => _a1D.amax(); + + [Benchmark(Description = "np.amax(a, axis=0)")] + [BenchmarkCategory("Max")] + public NDArray AMax_Axis0() => np.amax(_a2D, axis: 0); + + // ======================================================================== + // ArgMin / ArgMax + // ======================================================================== + + [Benchmark(Description = "np.argmin(a)")] + [BenchmarkCategory("ArgMin")] + public int ArgMin() => np.argmin(_a1D); + + [Benchmark(Description = "np.argmax(a)")] + [BenchmarkCategory("ArgMax")] + public int ArgMax() => np.argmax(_a1D); +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Reduction/ProdBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Reduction/ProdBenchmarks.cs new file mode 100644 index 000000000..1fd3a6b66 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Reduction/ProdBenchmarks.cs @@ -0,0 +1,62 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Reduction; + +/// +/// Benchmarks for product reduction operations. +/// +[BenchmarkCategory("Reduction", "Prod")] +public class ProdBenchmarks : TypedBenchmarkBase +{ + private NDArray _a1D = null!; + private NDArray _a2D = null!; + + // Use smaller arrays for prod to avoid overflow + [Params(100, 1000, 10000)] + public override int N { get; set; } + + // Use types that can hold larger products + [ParamsSource(nameof(Types))] + public new NPTypeCode DType { get; set; } + + public static IEnumerable Types => new[] + { + NPTypeCode.Int64, + NPTypeCode.Double + }; + + [GlobalSetup] + public void Setup() + { + // Use small values to avoid overflow + np.random.seed(Seed); + _a1D = (np.random.rand(N) * 0.5 + 0.5).astype(DType); // Values between 0.5 and 1.0 + + var rows = (int)Math.Sqrt(N); + var cols = N / rows; + np.random.seed(Seed); + _a2D = (np.random.rand(rows * cols) * 0.5 + 0.5).astype(DType).reshape(rows, cols); + } + + [GlobalCleanup] + public void Cleanup() + { + _a1D = null!; + _a2D = null!; + GC.Collect(); + } + + [Benchmark(Description = "a.prod() [full]")] + [BenchmarkCategory("Full")] + public NDArray Prod_Full() => _a1D.prod(); + + [Benchmark(Description = "a.prod(axis=0)")] + [BenchmarkCategory("Axis")] + public NDArray Prod_Axis0() => _a2D.prod(axis: 0); + + [Benchmark(Description = "a.prod(axis=1)")] + [BenchmarkCategory("Axis")] + public NDArray Prod_Axis1() => _a2D.prod(axis: 1); +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Reduction/SumBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Reduction/SumBenchmarks.cs new file mode 100644 index 000000000..4b045c450 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Reduction/SumBenchmarks.cs @@ -0,0 +1,74 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Reduction; + +/// +/// Benchmarks for sum reduction operations. +/// +[BenchmarkCategory("Reduction", "Sum")] +public class SumBenchmarks : TypedBenchmarkBase +{ + private NDArray _a1D = null!; + private NDArray _a2D = null!; + + [Params(ArraySizeSource.Small, ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + [ParamsSource(nameof(Types))] + public new NPTypeCode DType { get; set; } + + public static IEnumerable Types => TypeParameterSource.ArithmeticTypes; + + [GlobalSetup] + public void Setup() + { + _a1D = CreateRandomArray(N, DType); + + // 2D array for axis tests + var rows = (int)Math.Sqrt(N); + var cols = N / rows; + _a2D = CreateRandomArray(rows * cols, DType).reshape(rows, cols); + } + + [GlobalCleanup] + public void Cleanup() + { + _a1D = null!; + _a2D = null!; + GC.Collect(); + } + + // ======================================================================== + // Full Reduction + // ======================================================================== + + [Benchmark(Description = "np.sum(a) [full]")] + [BenchmarkCategory("Full")] + public NDArray Sum_Full() => np.sum(_a1D); + + [Benchmark(Description = "a.sum() [method]")] + [BenchmarkCategory("Full")] + public NDArray Sum_Method() => _a1D.sum(); + + // ======================================================================== + // Axis Reduction + // ======================================================================== + + [Benchmark(Description = "np.sum(a, axis=0) [columns]")] + [BenchmarkCategory("Axis")] + public NDArray Sum_Axis0() => np.sum(_a2D, axis: 0); + + [Benchmark(Description = "np.sum(a, axis=1) [rows]")] + [BenchmarkCategory("Axis")] + public NDArray Sum_Axis1() => np.sum(_a2D, axis: 1); + + // ======================================================================== + // Cumulative Sum + // ======================================================================== + + [Benchmark(Description = "np.cumsum(a)")] + [BenchmarkCategory("Cumulative")] + public NDArray CumSum() => np.cumsum(_a1D); +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Reduction/VarStdBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Reduction/VarStdBenchmarks.cs new file mode 100644 index 000000000..ec806ee1e --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Reduction/VarStdBenchmarks.cs @@ -0,0 +1,74 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Reduction; + +/// +/// Benchmarks for variance and standard deviation. +/// +[BenchmarkCategory("Reduction", "VarStd")] +public class VarStdBenchmarks : TypedBenchmarkBase +{ + private NDArray _a1D = null!; + private NDArray _a2D = null!; + + [Params(ArraySizeSource.Small, ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + // Variance/StdDev produce floating-point + [ParamsSource(nameof(Types))] + public new NPTypeCode DType { get; set; } + + public static IEnumerable Types => TypeParameterSource.TranscendentalTypes; + + [GlobalSetup] + public void Setup() + { + _a1D = CreateRandomArray(N, DType); + + var rows = (int)Math.Sqrt(N); + var cols = N / rows; + _a2D = CreateRandomArray(rows * cols, DType).reshape(rows, cols); + } + + [GlobalCleanup] + public void Cleanup() + { + _a1D = null!; + _a2D = null!; + GC.Collect(); + } + + // ======================================================================== + // Variance + // ======================================================================== + + [Benchmark(Description = "np.var(a) [full]")] + [BenchmarkCategory("Variance")] + public NDArray Var_Full() => np.var(_a1D); + + [Benchmark(Description = "a.var() [method]")] + [BenchmarkCategory("Variance")] + public NDArray Var_Method() => _a1D.var(); + + [Benchmark(Description = "np.var(a, axis=0)")] + [BenchmarkCategory("Variance")] + public NDArray Var_Axis0() => np.var(_a2D, axis: 0); + + // ======================================================================== + // Standard Deviation + // ======================================================================== + + [Benchmark(Description = "np.std(a) [full]")] + [BenchmarkCategory("StdDev")] + public NDArray Std_Full() => np.std(_a1D); + + [Benchmark(Description = "a.std() [method]")] + [BenchmarkCategory("StdDev")] + public NDArray Std_Method() => _a1D.std(); + + [Benchmark(Description = "np.std(a, axis=0)")] + [BenchmarkCategory("StdDev")] + public NDArray Std_Axis0() => np.std(_a2D, axis: 0); +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/SimdVsScalarBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/SimdVsScalarBenchmarks.cs new file mode 100644 index 000000000..922d24780 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/SimdVsScalarBenchmarks.cs @@ -0,0 +1,322 @@ +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Order; +using NumSharp; +using NumSharp.Backends.Kernels; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks; + +/// +/// Benchmarks for SIMD kernel performance analysis. +/// +/// Tests four categories: +/// 1. Binary operations (Add, Sub, Mul, Div) - current SIMD performance +/// 2. Full reductions (Sum, Max, Min, Prod, ArgMax, ArgMin, All, Any) - current SIMD performance +/// 3. Axis reductions (sum axis=0, axis=1) - currently scalar, identifies optimization targets +/// 4. Boolean helpers (NonZero, CountTrue, CopyMasked) - SIMD-accelerated boolean operations +/// +/// Array sizes: 100 (Tiny), 10K, 1M per task requirements. +/// Dtypes: float64 default; see SimdReductionTypeBenchmarks for int32/float32/float64. +/// +[MemoryDiagnoser] +[Orderer(SummaryOrderPolicy.FastestToSlowest)] +[RankColumn] +[CategoriesColumn] +[GroupBenchmarksBy(BenchmarkDotNet.Configs.BenchmarkLogicalGroupRule.ByCategory)] +public class SimdVsScalarBenchmarks : BenchmarkBase +{ + // Task sizes: 100, 10K, 1M + private const int Size100 = 100; + private const int Size10K = 10_000; + private const int Size1M = 1_000_000; + + private NDArray _a1D = null!; + private NDArray _b1D = null!; + private NDArray _a2D = null!; + private NDArray _boolArray = null!; + private NDArray _boolMask = null!; // For CopyMasked benchmark + private NDArray _prodArray = null!; + + [Params(Size100, Size10K, Size1M)] + public override int N { get; set; } + + [GlobalSetup] + public void Setup() + { + // Ensure SIMD is enabled + ILKernelGenerator.Enabled = true; + + // Create test arrays with float64 (best SIMD support) + np.random.seed(Seed); + _a1D = np.random.rand(N) * 100 - 50; + _b1D = np.random.rand(N) * 100 - 50 + 1; // +1 to avoid div-by-zero + + // 2D array for axis reductions + var rows = (int)Math.Sqrt(N); + var cols = N / rows; + _a2D = np.random.rand(rows * cols).reshape(rows, cols); + + // Boolean array for All/Any tests (mix of true/false, ~50% true) + _boolArray = (np.random.rand(N) > 0.5).astype(np.@bool); + + // Boolean mask for CopyMasked test (~30% true for realistic filtering) + _boolMask = (np.random.rand(N) > 0.7).astype(np.@bool); + + // Small values for Prod to avoid overflow + _prodArray = (np.random.rand(Math.Min(N, 1000)) * 0.5 + 0.5); // Values 0.5-1.0 + } + + [GlobalCleanup] + public void Cleanup() + { + _a1D = null!; + _b1D = null!; + _a2D = null!; + _boolArray = null!; + _boolMask = null!; + _prodArray = null!; + GC.Collect(); + } + + // ======================================================================== + // BINARY OPERATIONS (SIMD) + // ======================================================================== + + [Benchmark(Description = "Add (SIMD)")] + [BenchmarkCategory("Binary")] + public NDArray Add() => _a1D + _b1D; + + [Benchmark(Description = "Subtract (SIMD)")] + [BenchmarkCategory("Binary")] + public NDArray Subtract() => _a1D - _b1D; + + [Benchmark(Description = "Multiply (SIMD)")] + [BenchmarkCategory("Binary")] + public NDArray Multiply() => _a1D * _b1D; + + [Benchmark(Description = "Divide (SIMD)")] + [BenchmarkCategory("Binary")] + public NDArray Divide() => _a1D / _b1D; + + // ======================================================================== + // FULL REDUCTIONS (SIMD) + // ======================================================================== + + [Benchmark(Description = "Sum (SIMD)")] + [BenchmarkCategory("Reduction_Full")] + public NDArray Sum() => np.sum(_a1D); + + [Benchmark(Description = "Max (SIMD)")] + [BenchmarkCategory("Reduction_Full")] + public NDArray Max() => np.amax(_a1D); + + [Benchmark(Description = "Min (SIMD)")] + [BenchmarkCategory("Reduction_Full")] + public NDArray Min() => np.amin(_a1D); + + [Benchmark(Description = "ArgMax (SIMD)")] + [BenchmarkCategory("Reduction_Full")] + public int ArgMax() => np.argmax(_a1D); + + [Benchmark(Description = "ArgMin (SIMD)")] + [BenchmarkCategory("Reduction_Full")] + public int ArgMin() => np.argmin(_a1D); + + [Benchmark(Description = "All (SIMD)")] + [BenchmarkCategory("Reduction_Full")] + public bool All() => (bool)np.all(_boolArray); + + [Benchmark(Description = "Any (SIMD)")] + [BenchmarkCategory("Reduction_Full")] + public bool Any() => (bool)np.any(_boolArray); + + [Benchmark(Description = "Prod (SIMD)")] + [BenchmarkCategory("Reduction_Full")] + public NDArray Prod() => _prodArray.prod(); + + // ======================================================================== + // BOOLEAN HELPERS (SIMD) + // NonZero, CountTrue (via sum of bool array), CopyMasked (via boolean indexing) + // ======================================================================== + + [Benchmark(Description = "NonZero (SIMD)")] + [BenchmarkCategory("Boolean_Helpers")] + public NDArray[] NonZero() => np.nonzero(_boolArray); + + [Benchmark(Description = "CountTrue (sum of bool)")] + [BenchmarkCategory("Boolean_Helpers")] + public int CountTrue() => (int)np.sum(_boolArray.astype(np.int32)); + + [Benchmark(Description = "CopyMasked (boolean indexing)")] + [BenchmarkCategory("Boolean_Helpers")] + public NDArray CopyMasked() => _a1D[_boolMask]; + + // ======================================================================== + // AXIS REDUCTIONS: Optimization Targets + // (Currently scalar - measuring baseline for future SIMD optimization) + // ======================================================================== + + [Benchmark(Description = "Sum axis=0 (scalar)")] + [BenchmarkCategory("Reduction_Axis")] + public NDArray Sum_Axis0() => np.sum(_a2D, axis: 0); + + [Benchmark(Description = "Sum axis=1 (scalar)")] + [BenchmarkCategory("Reduction_Axis")] + public NDArray Sum_Axis1() => np.sum(_a2D, axis: 1); + + [Benchmark(Description = "Mean axis=0 (scalar)")] + [BenchmarkCategory("Reduction_Axis")] + public NDArray Mean_Axis0() => np.mean(_a2D, axis: 0); + + [Benchmark(Description = "Max axis=0 (scalar)")] + [BenchmarkCategory("Reduction_Axis")] + public NDArray Max_Axis0() => np.amax(_a2D, axis: 0); +} + +/// +/// Benchmarks for SIMD reduction operations across multiple data types. +/// Tests int32, float32, and float64 to identify type-specific performance characteristics. +/// Array sizes: 100, 10K, 1M per task requirements. +/// +[MemoryDiagnoser] +[Orderer(SummaryOrderPolicy.FastestToSlowest)] +[RankColumn] +[CategoriesColumn] +[GroupBenchmarksBy(BenchmarkDotNet.Configs.BenchmarkLogicalGroupRule.ByCategory)] +public class SimdReductionTypeBenchmarks : BenchmarkBase +{ + // Task sizes: 100, 10K, 1M + private const int Size100 = 100; + private const int Size10K = 10_000; + private const int Size1M = 1_000_000; + + public enum DType { Int32, Float32, Float64 } + + private NDArray _array = null!; + + [Params(Size100, Size10K, Size1M)] + public override int N { get; set; } + + [Params(DType.Int32, DType.Float32, DType.Float64)] + public DType Type { get; set; } + + [GlobalSetup] + public void Setup() + { + ILKernelGenerator.Enabled = true; + np.random.seed(Seed); + + _array = Type switch + { + DType.Int32 => np.random.randint(-1000, 1000, new Shape(N)), + DType.Float32 => (np.random.rand(N) * 100 - 50).astype(np.float32), + DType.Float64 => np.random.rand(N) * 100 - 50, + _ => throw new ArgumentException($"Unknown type: {Type}") + }; + } + + [GlobalCleanup] + public void Cleanup() + { + _array = null!; + GC.Collect(); + } + + [Benchmark(Description = "Sum")] + [BenchmarkCategory("Sum")] + public NDArray Sum() => np.sum(_array); + + [Benchmark(Description = "Max")] + [BenchmarkCategory("Max")] + public NDArray Max() => np.amax(_array); + + [Benchmark(Description = "Min")] + [BenchmarkCategory("Min")] + public NDArray Min() => np.amin(_array); + + [Benchmark(Description = "ArgMax")] + [BenchmarkCategory("ArgMax")] + public int ArgMax() => np.argmax(_array); + + [Benchmark(Description = "ArgMin")] + [BenchmarkCategory("ArgMin")] + public int ArgMin() => np.argmin(_array); +} + +/// +/// Benchmarks comparing contiguous vs non-contiguous array operations. +/// This shows the SIMD fast-path vs general iterator path difference. +/// Array sizes: 100, 10K, 1M per task requirements. +/// +[MemoryDiagnoser] +[Orderer(SummaryOrderPolicy.FastestToSlowest)] +[RankColumn] +[CategoriesColumn] +[GroupBenchmarksBy(BenchmarkDotNet.Configs.BenchmarkLogicalGroupRule.ByCategory)] +public class SimdContiguousVsSlicedBenchmarks : BenchmarkBase +{ + // Task sizes: 100, 10K, 1M + private const int Size100 = 100; + private const int Size10K = 10_000; + private const int Size1M = 1_000_000; + + private NDArray _contiguous = null!; + private NDArray _sliced = null!; // Every other element + private NDArray _transposed = null!; // Column-major access + + [Params(Size100, Size10K, Size1M)] + public override int N { get; set; } + + [GlobalSetup] + public void Setup() + { + ILKernelGenerator.Enabled = true; + np.random.seed(Seed); + + // Contiguous array + _contiguous = np.random.rand(N); + + // Sliced array (every other element = non-contiguous) + var full = np.random.rand(N * 2); + _sliced = full["::2"]; + + // Transposed 2D array (column-major access pattern) + var rows = (int)Math.Sqrt(N); + var cols = N / rows; + var matrix = np.random.rand(rows * cols).reshape(rows, cols); + _transposed = matrix.T; // Transpose makes it non-contiguous + } + + [GlobalCleanup] + public void Cleanup() + { + _contiguous = null!; + _sliced = null!; + _transposed = null!; + GC.Collect(); + } + + // ======================================================================== + // SUM: Contiguous vs Non-Contiguous + // ======================================================================== + + [Benchmark(Baseline = true, Description = "Sum contiguous (SIMD)")] + [BenchmarkCategory("Sum")] + public NDArray Sum_Contiguous() => np.sum(_contiguous); + + [Benchmark(Description = "Sum sliced (iterator)")] + [BenchmarkCategory("Sum")] + public NDArray Sum_Sliced() => np.sum(_sliced); + + // ======================================================================== + // ADD: Contiguous vs Non-Contiguous + // ======================================================================== + + [Benchmark(Baseline = true, Description = "Add contiguous (SIMD)")] + [BenchmarkCategory("Add")] + public NDArray Add_Contiguous() => _contiguous + _contiguous; + + [Benchmark(Description = "Add sliced (iterator)")] + [BenchmarkCategory("Add")] + public NDArray Add_Sliced() => _sliced + _sliced; +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Slicing/SliceBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Slicing/SliceBenchmarks.cs new file mode 100644 index 000000000..35fa2777e --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Slicing/SliceBenchmarks.cs @@ -0,0 +1,121 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Slicing; + +/// +/// Benchmarks for slicing and view operations. +/// Tests contiguous vs strided slices and their impact on subsequent operations. +/// +[BenchmarkCategory("Slicing")] +public class SliceBenchmarks : BenchmarkBase +{ + private NDArray _arr1D = null!; + private NDArray _arr2D = null!; + private NDArray _contiguousSlice = null!; + private NDArray _stridedSlice = null!; + private NDArray _rowSlice = null!; + private NDArray _colSlice = null!; + + [Params(ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + [GlobalSetup] + public void Setup() + { + np.random.seed(Seed); + + _arr1D = np.random.rand(N) * 100; + + var rows = (int)Math.Sqrt(N); + var cols = N / rows; + _arr2D = np.random.rand(rows, cols) * 100; + + // Pre-slice for operation benchmarks + _contiguousSlice = _arr1D["100:1000"]; // Contiguous view + _stridedSlice = _arr1D["::2"]; // Every other element (strided) + _rowSlice = _arr2D["10:100, :"]; // Row slice + _colSlice = _arr2D[":, 10:100"]; // Column slice (strided) + } + + [GlobalCleanup] + public void Cleanup() + { + _arr1D = null!; + _arr2D = null!; + _contiguousSlice = null!; + _stridedSlice = null!; + _rowSlice = null!; + _colSlice = null!; + GC.Collect(); + } + + // ======================================================================== + // Slice Creation (view creation time) + // ======================================================================== + + [Benchmark(Description = "a[100:1000] (contiguous slice)")] + [BenchmarkCategory("Create")] + public NDArray Slice_Contiguous() => _arr1D["100:1000"]; + + [Benchmark(Description = "a[::2] (strided slice)")] + [BenchmarkCategory("Create")] + public NDArray Slice_Strided() => _arr1D["::2"]; + + [Benchmark(Description = "a[::-1] (reversed)")] + [BenchmarkCategory("Create")] + public NDArray Slice_Reversed() => _arr1D["::-1"]; + + [Benchmark(Description = "a[10:100, :] (row slice 2D)")] + [BenchmarkCategory("Create")] + public NDArray Slice_Row2D() => _arr2D["10:100, :"]; + + [Benchmark(Description = "a[:, 10:100] (col slice 2D)")] + [BenchmarkCategory("Create")] + public NDArray Slice_Col2D() => _arr2D[":, 10:100"]; + + // ======================================================================== + // Operations on Slices (measure view overhead) + // ======================================================================== + + [Benchmark(Description = "np.sum(contiguous_slice)")] + [BenchmarkCategory("SumSlice")] + public NDArray Sum_ContiguousSlice() => np.sum(_contiguousSlice); + + [Benchmark(Description = "np.sum(strided_slice)")] + [BenchmarkCategory("SumSlice")] + public NDArray Sum_StridedSlice() => np.sum(_stridedSlice); + + [Benchmark(Description = "np.sum(row_slice)")] + [BenchmarkCategory("SumSlice")] + public NDArray Sum_RowSlice() => np.sum(_rowSlice); + + [Benchmark(Description = "np.sum(col_slice)")] + [BenchmarkCategory("SumSlice")] + public NDArray Sum_ColSlice() => np.sum(_colSlice); + + // ======================================================================== + // Slice + Operation (combined) + // ======================================================================== + + [Benchmark(Description = "a[100:1000] * 2")] + [BenchmarkCategory("SliceOp")] + public NDArray SliceAndOp_Contiguous() => _arr1D["100:1000"] * 2; + + [Benchmark(Description = "a[::2] * 2")] + [BenchmarkCategory("SliceOp")] + public NDArray SliceAndOp_Strided() => _arr1D["::2"] * 2; + + // ======================================================================== + // Copy vs View + // ======================================================================== + + [Benchmark(Description = "a[100:1000].copy()")] + [BenchmarkCategory("Copy")] + public NDArray SliceCopy() => _arr1D["100:1000"].copy(); + + [Benchmark(Description = "np.copy(a[100:1000])")] + [BenchmarkCategory("Copy")] + public NDArray NpCopy() => np.copy(_arr1D["100:1000"]); +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Unary/ExpLogBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Unary/ExpLogBenchmarks.cs new file mode 100644 index 000000000..d456cd35a --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Unary/ExpLogBenchmarks.cs @@ -0,0 +1,79 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Unary; + +/// +/// Benchmarks for exponential and logarithmic functions. +/// +[BenchmarkCategory("Unary", "ExpLog")] +public class ExpLogBenchmarks : TypedBenchmarkBase +{ + private NDArray _a = null!; + private NDArray _positive = null!; + private NDArray _smallPositive = null!; + + [Params(ArraySizeSource.Small, ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + [ParamsSource(nameof(Types))] + public new NPTypeCode DType { get; set; } + + public static IEnumerable Types => TypeParameterSource.TranscendentalTypes; + + [GlobalSetup] + public void Setup() + { + _a = CreateRandomArray(N, DType); + _positive = CreatePositiveArray(N, DType); + // Small positive for exp (avoid overflow) + np.random.seed(Seed); + _smallPositive = (np.random.rand(N) * 10).astype(DType); + } + + [GlobalCleanup] + public void Cleanup() + { + _a = null!; + _positive = null!; + _smallPositive = null!; + GC.Collect(); + } + + // ======================================================================== + // Exponential Functions + // ======================================================================== + + [Benchmark(Description = "np.exp(a)")] + [BenchmarkCategory("Exp")] + public NDArray Exp() => np.exp(_smallPositive); + + [Benchmark(Description = "np.exp2(a)")] + [BenchmarkCategory("Exp")] + public NDArray Exp2() => np.exp2(_smallPositive); + + [Benchmark(Description = "np.expm1(a)")] + [BenchmarkCategory("Exp")] + public NDArray Expm1() => np.expm1(_smallPositive); + + // ======================================================================== + // Logarithmic Functions + // ======================================================================== + + [Benchmark(Description = "np.log(a)")] + [BenchmarkCategory("Log")] + public NDArray Log() => np.log(_positive); + + [Benchmark(Description = "np.log2(a)")] + [BenchmarkCategory("Log")] + public NDArray Log2() => np.log2(_positive); + + [Benchmark(Description = "np.log10(a)")] + [BenchmarkCategory("Log")] + public NDArray Log10() => np.log10(_positive); + + [Benchmark(Description = "np.log1p(a)")] + [BenchmarkCategory("Log")] + public NDArray Log1p() => np.log1p(_positive); +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Unary/MathBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Unary/MathBenchmarks.cs new file mode 100644 index 000000000..d32679f22 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Unary/MathBenchmarks.cs @@ -0,0 +1,66 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Unary; + +/// +/// Benchmarks for basic unary math operations: sqrt, abs, sign, floor, ceil, round. +/// +[BenchmarkCategory("Unary", "Math")] +public class MathBenchmarks : TypedBenchmarkBase +{ + private NDArray _a = null!; + private NDArray _positive = null!; + + [Params(ArraySizeSource.Small, ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + [ParamsSource(nameof(Types))] + public new NPTypeCode DType { get; set; } + + public static IEnumerable Types => TypeParameterSource.TranscendentalTypes; + + [GlobalSetup] + public void Setup() + { + _a = CreateRandomArray(N, DType); + _positive = CreatePositiveArray(N, DType); + } + + [GlobalCleanup] + public void Cleanup() + { + _a = null!; + _positive = null!; + GC.Collect(); + } + + [Benchmark(Description = "np.sqrt(a)")] + [BenchmarkCategory("Sqrt")] + public NDArray Sqrt() => np.sqrt(_positive); + + [Benchmark(Description = "np.abs(a)")] + [BenchmarkCategory("Abs")] + public NDArray Abs() => np.abs(_a); + + [Benchmark(Description = "np.sign(a)")] + [BenchmarkCategory("Sign")] + public NDArray Sign() => np.sign(_a); + + [Benchmark(Description = "np.floor(a)")] + [BenchmarkCategory("Rounding")] + public NDArray Floor() => np.floor(_a); + + [Benchmark(Description = "np.ceil(a)")] + [BenchmarkCategory("Rounding")] + public NDArray Ceil() => np.ceil(_a); + + [Benchmark(Description = "np.around(a)")] + [BenchmarkCategory("Rounding")] + public NDArray Round() => np.around(_a); + + [Benchmark(Description = "np.clip(a, -10, 10)")] + [BenchmarkCategory("Clip")] + public NDArray Clip() => np.clip(_a, -10.0, 10.0); +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Unary/PowerBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Unary/PowerBenchmarks.cs new file mode 100644 index 000000000..131cb6701 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Unary/PowerBenchmarks.cs @@ -0,0 +1,59 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Unary; + +/// +/// Benchmarks for power operations. +/// Note: NumSharp only supports scalar exponents (ValueType), not element-wise NDArray exponents. +/// +[BenchmarkCategory("Unary", "Power")] +public class PowerBenchmarks : TypedBenchmarkBase +{ + private NDArray _a = null!; + private NDArray _positive = null!; + + [Params(ArraySizeSource.Small, ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + [ParamsSource(nameof(Types))] + public new NPTypeCode DType { get; set; } + + public static IEnumerable Types => TypeParameterSource.TranscendentalTypes; + + [GlobalSetup] + public void Setup() + { + _a = CreateRandomArray(N, DType); + _positive = CreatePositiveArray(N, DType); + } + + [GlobalCleanup] + public void Cleanup() + { + _a = null!; + _positive = null!; + GC.Collect(); + } + + [Benchmark(Description = "np.power(a, 2)")] + [BenchmarkCategory("Scalar")] + public NDArray Power_Square() => np.power(_a, 2); + + [Benchmark(Description = "np.power(a, 3)")] + [BenchmarkCategory("Scalar")] + public NDArray Power_Cube() => np.power(_a, 3); + + [Benchmark(Description = "np.power(a, 0.5) [sqrt]")] + [BenchmarkCategory("Scalar")] + public NDArray Power_SqrtEquivalent() => np.power(_positive, 0.5); + + [Benchmark(Description = "a * a (square via multiply)")] + [BenchmarkCategory("Alternative")] + public NDArray Power_SquareViaMul() => _a * _a; + + [Benchmark(Description = "a * a * a (cube via multiply)")] + [BenchmarkCategory("Alternative")] + public NDArray Power_CubeViaMul() => _a * _a * _a; +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Unary/TrigBenchmarks.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Unary/TrigBenchmarks.cs new file mode 100644 index 000000000..924b663a0 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Benchmarks/Unary/TrigBenchmarks.cs @@ -0,0 +1,49 @@ +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.Unary; + +/// +/// Benchmarks for trigonometric functions. +/// +[BenchmarkCategory("Unary", "Trig")] +public class TrigBenchmarks : TypedBenchmarkBase +{ + private NDArray _angles = null!; + + [Params(ArraySizeSource.Small, ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + [ParamsSource(nameof(Types))] + public new NPTypeCode DType { get; set; } + + public static IEnumerable Types => TypeParameterSource.TranscendentalTypes; + + [GlobalSetup] + public void Setup() + { + np.random.seed(Seed); + // Angles between -2π and 2π + _angles = ((np.random.rand(N) * 4 - 2) * Math.PI).astype(DType); + } + + [GlobalCleanup] + public void Cleanup() + { + _angles = null!; + GC.Collect(); + } + + [Benchmark(Description = "np.sin(a)")] + [BenchmarkCategory("Basic")] + public NDArray Sin() => np.sin(_angles); + + [Benchmark(Description = "np.cos(a)")] + [BenchmarkCategory("Basic")] + public NDArray Cos() => np.cos(_angles); + + [Benchmark(Description = "np.tan(a)")] + [BenchmarkCategory("Basic")] + public NDArray Tan() => np.tan(_angles); +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Infrastructure/ArraySizeSource.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Infrastructure/ArraySizeSource.cs new file mode 100644 index 000000000..ce2a2fac5 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Infrastructure/ArraySizeSource.cs @@ -0,0 +1,98 @@ +namespace NumSharp.Benchmark.GraphEngine.Infrastructure; + +/// +/// Provides standard array sizes for benchmarks. +/// +public static class ArraySizeSource +{ + /// + /// Scalar size - single element. + /// Critical for measuring pure dispatch/call overhead without any loop cost. + /// + public const int Scalar = 1; + + /// + /// Tiny array size - common small collection. + /// Good for evaluating performance on typical small datasets (configs, small batches). + /// + public const int Tiny = 100; + + /// + /// Small array size - fits in L1 cache. + /// Good for measuring per-element overhead with minimal memory effects. + /// + public const int Small = 1_000; + + /// + /// Medium array size - fits in L2/L3 cache. + /// Good for typical use cases. + /// + public const int Medium = 100_000; + + /// + /// Large array size - exceeds cache, memory-bound. + /// Good for measuring throughput. + /// + public const int Large = 10_000_000; + + /// + /// Standard array sizes for comprehensive benchmarks. + /// Includes scalar for overhead measurement, tiny for common collections, + /// and the three cache-tier sizes. + /// + public static IEnumerable StandardSizes => new[] { Scalar, Tiny, Small, Medium, Large }; + + /// + /// Quick test sizes - only large for throughput focus. + /// + public static IEnumerable QuickSizes => new[] { Large }; + + /// + /// Overhead-focused sizes - scalar and tiny for measuring dispatch cost. + /// + public static IEnumerable OverheadSizes => new[] { Scalar, Tiny }; + + /// + /// Cache-tier sizes - small, medium, large (excludes scalar/tiny). + /// + public static IEnumerable CacheTierSizes => new[] { Small, Medium, Large }; + + /// + /// All sizes including intermediate steps for detailed analysis. + /// + public static IEnumerable AllSizes => new[] { Scalar, Tiny, Small, 10_000, Medium, 1_000_000, Large }; + + /// + /// 2D array sizes as (rows, cols) tuples. + /// + public static IEnumerable<(int Rows, int Cols)> Matrix2DSizes => new[] + { + (100, 100), // 10K elements + (1000, 1000), // 1M elements + (3162, 3162) // ~10M elements (sqrt of 10M) + }; + + /// + /// 3D array sizes as (d1, d2, d3) tuples. + /// + public static IEnumerable<(int D1, int D2, int D3)> Tensor3DSizes => new[] + { + (100, 100, 100), // 1M elements + (215, 215, 215) // ~10M elements (cbrt of 10M) + }; + + /// + /// Get human-readable size description. + /// + public static string GetSizeDescription(int n) => n switch + { + Scalar => "Scalar (1)", + <= Tiny => $"Tiny ({Tiny})", + <= Small => $"Small ({Small:N0})", + <= 10_000 => "10K", + <= Medium => $"Medium ({Medium:N0})", + <= 1_000_000 => "1M", + <= Large => $"Large ({Large:N0})", + _ => $"Huge ({n:N0})" + }; +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Infrastructure/BenchmarkBase.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Infrastructure/BenchmarkBase.cs new file mode 100644 index 000000000..b46a38b25 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Infrastructure/BenchmarkBase.cs @@ -0,0 +1,131 @@ +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Order; +using NumSharp; + +namespace NumSharp.Benchmark.GraphEngine.Infrastructure; + +/// +/// Base class for NumSharp benchmarks with standard setup patterns. +/// Provides array creation and type parameterization. +/// +[MemoryDiagnoser] +[Orderer(SummaryOrderPolicy.FastestToSlowest)] +[RankColumn] +[CategoriesColumn] +public abstract class BenchmarkBase +{ + /// + /// Array size parameter. Override in derived class with [Params] or [ParamsSource]. + /// + public virtual int N { get; set; } = ArraySizeSource.Large; + + /// + /// Random seed for reproducibility. + /// + protected const int Seed = 42; + + /// + /// Create a random array of the specified type and size. + /// + protected static NDArray CreateRandomArray(int n, NPTypeCode dtype, int seed = Seed) + { + np.random.seed(seed); + + return dtype switch + { + NPTypeCode.Boolean => np.random.randint(0, 2, new Shape(n)).astype(np.@bool), + NPTypeCode.Byte => np.random.randint(0, 256, new Shape(n)).astype(np.uint8), + NPTypeCode.Int16 => np.random.randint(-1000, 1000, new Shape(n)).astype(np.int16), + NPTypeCode.UInt16 => np.random.randint(0, 2000, new Shape(n)).astype(np.uint16), + NPTypeCode.Int32 => np.random.randint(-1000, 1000, new Shape(n)), + NPTypeCode.UInt32 => np.random.randint(0, 2000, new Shape(n)).astype(np.uint32), + NPTypeCode.Int64 => np.random.randint(-1000, 1000, new Shape(n)).astype(np.int64), + NPTypeCode.UInt64 => np.random.randint(0, 2000, new Shape(n)).astype(np.uint64), + NPTypeCode.Char => np.random.randint(32, 127, new Shape(n)).astype(NPTypeCode.Char), + NPTypeCode.Single => (np.random.rand(n) * 100 - 50).astype(np.float32), + NPTypeCode.Double => np.random.rand(n) * 100 - 50, + NPTypeCode.Decimal => (np.random.rand(n) * 100 - 50).astype(NPTypeCode.Decimal), + _ => throw new ArgumentException($"Unsupported type: {dtype}") + }; + } + + /// + /// Create a random 2D array of the specified type and shape. + /// + protected static NDArray CreateRandomArray2D(int rows, int cols, NPTypeCode dtype, int seed = Seed) + { + np.random.seed(seed); + var flat = CreateRandomArray(rows * cols, dtype, seed); + return flat.reshape(rows, cols); + } + + /// + /// Create a random 3D array of the specified type and shape. + /// + protected static NDArray CreateRandomArray3D(int d1, int d2, int d3, NPTypeCode dtype, int seed = Seed) + { + np.random.seed(seed); + var flat = CreateRandomArray(d1 * d2 * d3, dtype, seed); + return flat.reshape(d1, d2, d3); + } + + /// + /// Create a positive random array (for operations like log, sqrt, division, modulo). + /// Returns values >= 1 to avoid divide-by-zero errors. + /// + protected static NDArray CreatePositiveArray(int n, NPTypeCode dtype, int seed = Seed) + { + np.random.seed(seed); + + return dtype switch + { + // Floating point: rand() * 100 + 1 gives [1, 101) + NPTypeCode.Single => (np.random.rand(n) * 100 + 1).astype(np.float32), + NPTypeCode.Double => np.random.rand(n) * 100 + 1, + NPTypeCode.Decimal => (np.random.rand(n) * 100 + 1).astype(NPTypeCode.Decimal), + // Integers: randint(1, N) gives [1, N) - never zero + NPTypeCode.Boolean => np.random.randint(1, 2, new Shape(n)).astype(np.@bool), + NPTypeCode.Byte => np.random.randint(1, 256, new Shape(n)).astype(np.uint8), + NPTypeCode.Int16 => np.random.randint(1, 1000, new Shape(n)).astype(np.int16), + NPTypeCode.UInt16 => np.random.randint(1, 2000, new Shape(n)).astype(np.uint16), + NPTypeCode.Int32 => np.random.randint(1, 1000, new Shape(n)), + NPTypeCode.UInt32 => np.random.randint(1, 2000, new Shape(n)).astype(np.uint32), + NPTypeCode.Int64 => np.random.randint(1, 1000, new Shape(n)).astype(np.int64), + NPTypeCode.UInt64 => np.random.randint(1, 2000, new Shape(n)).astype(np.uint64), + NPTypeCode.Char => np.random.randint(1, 127, new Shape(n)).astype(NPTypeCode.Char), + _ => throw new ArgumentException($"Unsupported type: {dtype}") + }; + } + + /// + /// Get a scalar value of the specified type. + /// + protected static object GetScalar(NPTypeCode dtype, double value = 42.0) => dtype switch + { + NPTypeCode.Boolean => value != 0, + NPTypeCode.Byte => (byte)Math.Abs(value), + NPTypeCode.Int16 => (short)value, + NPTypeCode.UInt16 => (ushort)Math.Abs(value), + NPTypeCode.Int32 => (int)value, + NPTypeCode.UInt32 => (uint)Math.Abs(value), + NPTypeCode.Int64 => (long)value, + NPTypeCode.UInt64 => (ulong)Math.Abs(value), + NPTypeCode.Char => (char)(int)Math.Abs(value), + NPTypeCode.Single => (float)value, + NPTypeCode.Double => value, + NPTypeCode.Decimal => (decimal)value, + _ => throw new ArgumentException($"Unsupported type: {dtype}") + }; +} + +/// +/// Base class for benchmarks parameterized by both size and type. +/// Derived classes must define their own Types property with [ParamsSource]. +/// +public abstract class TypedBenchmarkBase : BenchmarkBase +{ + /// + /// Type parameter. Derived class must provide [ParamsSource]. + /// + public NPTypeCode DType { get; set; } +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Infrastructure/BenchmarkConfig.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Infrastructure/BenchmarkConfig.cs new file mode 100644 index 000000000..543fbe3a3 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Infrastructure/BenchmarkConfig.cs @@ -0,0 +1,87 @@ +using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Exporters; +using BenchmarkDotNet.Exporters.Json; +using BenchmarkDotNet.Jobs; +using BenchmarkDotNet.Diagnosers; +using BenchmarkDotNet.Columns; +using BenchmarkDotNet.Reports; +using BenchmarkDotNet.Filters; +using BenchmarkDotNet.Validators; + +namespace NumSharp.Benchmark.GraphEngine.Infrastructure; + +/// +/// Custom BenchmarkDotNet configuration for NumSharp benchmarks. +/// Provides consistent settings across all benchmark classes. +/// +public class NumSharpBenchmarkConfig : ManualConfig +{ + public NumSharpBenchmarkConfig() + { + // Job configuration + AddJob(Job.Default + .WithWarmupCount(3) + .WithIterationCount(20) + .AsDefault()); + + // Diagnosers + AddDiagnoser(MemoryDiagnoser.Default); + + // Exporters - JSON for automated comparison + AddExporter(JsonExporter.FullCompressed); + AddExporter(MarkdownExporter.GitHub); + + // Columns + AddColumn(StatisticColumn.Mean); + AddColumn(StatisticColumn.StdDev); + AddColumn(StatisticColumn.Median); + AddColumn(StatisticColumn.Min); + AddColumn(StatisticColumn.Max); + AddColumn(BaselineRatioColumn.RatioMean); + AddColumn(RankColumn.Arabic); + + // Summary style + WithSummaryStyle(SummaryStyle.Default.WithMaxParameterColumnWidth(40)); + } +} + +/// +/// Quick benchmark configuration for fast iterations during development. +/// +public class QuickBenchmarkConfig : ManualConfig +{ + public QuickBenchmarkConfig() + { + AddJob(Job.Dry + .WithWarmupCount(1) + .WithIterationCount(3)); + + AddDiagnoser(MemoryDiagnoser.Default); + AddExporter(JsonExporter.Brief); + } +} + +/// +/// Full benchmark configuration for comprehensive analysis. +/// +public class FullBenchmarkConfig : ManualConfig +{ + public FullBenchmarkConfig() + { + AddJob(Job.Default + .WithWarmupCount(5) + .WithIterationCount(50)); + + AddDiagnoser(MemoryDiagnoser.Default); + AddExporter(JsonExporter.FullCompressed); + AddExporter(MarkdownExporter.GitHub); + AddExporter(HtmlExporter.Default); + + AddColumn(StatisticColumn.Mean); + AddColumn(StatisticColumn.StdDev); + AddColumn(StatisticColumn.Median); + AddColumn(StatisticColumn.P95); + AddColumn(BaselineRatioColumn.RatioMean); + AddColumn(RankColumn.Arabic); + } +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Infrastructure/TypeParameterSource.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Infrastructure/TypeParameterSource.cs new file mode 100644 index 000000000..26f69ad6d --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Infrastructure/TypeParameterSource.cs @@ -0,0 +1,145 @@ +using NumSharp; + +namespace NumSharp.Benchmark.GraphEngine.Infrastructure; + +/// +/// Provides type parameter sources for parameterized benchmarks. +/// Supports all 12 NumSharp NPTypeCodes. +/// +public static class TypeParameterSource +{ + /// + /// All 12 NumSharp supported types. + /// Boolean, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Char, Single, Double, Decimal + /// + public static IEnumerable AllNumericTypes => new[] + { + NPTypeCode.Boolean, + NPTypeCode.Byte, + NPTypeCode.Int16, + NPTypeCode.UInt16, + NPTypeCode.Int32, + NPTypeCode.UInt32, + NPTypeCode.Int64, + NPTypeCode.UInt64, + NPTypeCode.Char, + NPTypeCode.Single, + NPTypeCode.Double, + NPTypeCode.Decimal + }; + + /// + /// Integer types only: bool, byte, int16, uint16, int32, uint32, int64, uint64, char + /// + public static IEnumerable IntegerTypes => new[] + { + NPTypeCode.Boolean, + NPTypeCode.Byte, + NPTypeCode.Int16, + NPTypeCode.UInt16, + NPTypeCode.Int32, + NPTypeCode.UInt32, + NPTypeCode.Int64, + NPTypeCode.UInt64, + NPTypeCode.Char + }; + + /// + /// Floating-point types only: float, double, decimal + /// + public static IEnumerable FloatingTypes => new[] + { + NPTypeCode.Single, + NPTypeCode.Double, + NPTypeCode.Decimal + }; + + /// + /// Common types for fast benchmarks: int32, int64, float, double + /// These cover the most common use cases with minimal runtime. + /// + public static IEnumerable CommonTypes => new[] + { + NPTypeCode.Int32, + NPTypeCode.Int64, + NPTypeCode.Single, + NPTypeCode.Double + }; + + /// + /// Minimal types for smoke tests: int32, double + /// + public static IEnumerable MinimalTypes => new[] + { + NPTypeCode.Int32, + NPTypeCode.Double + }; + + /// + /// Types that support standard arithmetic: excludes bool and char + /// + public static IEnumerable ArithmeticTypes => new[] + { + NPTypeCode.Byte, + NPTypeCode.Int16, + NPTypeCode.UInt16, + NPTypeCode.Int32, + NPTypeCode.UInt32, + NPTypeCode.Int64, + NPTypeCode.UInt64, + NPTypeCode.Single, + NPTypeCode.Double, + NPTypeCode.Decimal + }; + + /// + /// Types that support transcendental functions (sqrt, exp, log, trig): float, double, decimal + /// + public static IEnumerable TranscendentalTypes => new[] + { + NPTypeCode.Single, + NPTypeCode.Double, + NPTypeCode.Decimal + }; + + /// + /// Get the NumPy dtype name for a given NPTypeCode. + /// Used for matching with Python benchmark results. + /// + public static string GetDtypeName(NPTypeCode code) => code switch + { + NPTypeCode.Boolean => "bool", + NPTypeCode.Byte => "uint8", + NPTypeCode.Int16 => "int16", + NPTypeCode.UInt16 => "uint16", + NPTypeCode.Int32 => "int32", + NPTypeCode.UInt32 => "uint32", + NPTypeCode.Int64 => "int64", + NPTypeCode.UInt64 => "uint64", + NPTypeCode.Char => "uint16", // char is 16-bit in C# + NPTypeCode.Single => "float32", + NPTypeCode.Double => "float64", + NPTypeCode.Decimal => "float128", // closest approximation + _ => throw new ArgumentException($"Unknown NPTypeCode: {code}") + }; + + /// + /// Get the short display name for a given NPTypeCode. + /// + public static string GetShortName(NPTypeCode code) => code switch + { + NPTypeCode.Boolean => "bool", + NPTypeCode.Byte => "u8", + NPTypeCode.Int16 => "i16", + NPTypeCode.UInt16 => "u16", + NPTypeCode.Int32 => "i32", + NPTypeCode.UInt32 => "u32", + NPTypeCode.Int64 => "i64", + NPTypeCode.UInt64 => "u64", + NPTypeCode.Char => "char", + NPTypeCode.Single => "f32", + NPTypeCode.Double => "f64", + NPTypeCode.Decimal => "dec", + _ => code.ToString() + }; +} diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/NumSharp.Benchmark.GraphEngine.csproj b/benchmark/NumSharp.Benchmark.GraphEngine/NumSharp.Benchmark.GraphEngine.csproj new file mode 100644 index 000000000..0ecf9b2ee --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/NumSharp.Benchmark.GraphEngine.csproj @@ -0,0 +1,23 @@ + + + + Exe + net8.0;net10.0 + enable + enable + true + x64 + true + NumSharp.Benchmark.GraphEngine + NumSharp.Benchmark.GraphEngine + + + + + + + + + + + diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/Program.cs b/benchmark/NumSharp.Benchmark.GraphEngine/Program.cs new file mode 100644 index 000000000..414be314b --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/Program.cs @@ -0,0 +1,63 @@ +using BenchmarkDotNet.Running; +using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Jobs; +using BenchmarkDotNet.Environments; +using BenchmarkDotNet.Columns; +using BenchmarkDotNet.Reports; +using NumSharp.Benchmark.GraphEngine; + +// Run all benchmarks or specific ones based on command line args +if (args.Length == 0) +{ + // Interactive menu + Console.WriteLine("NumSharp Performance Benchmarks"); + Console.WriteLine("================================"); + Console.WriteLine(); + Console.WriteLine("=== Original Benchmarks ==="); + Console.WriteLine("1. Dispatch Mechanism Comparison (DynamicMethod vs Static vs Struct)"); + Console.WriteLine("2. Fusion Pattern Benchmarks (fused vs multi-pass)"); + Console.WriteLine("3. NumSharp Current Performance"); + Console.WriteLine("4. DynamicMethod Emission (#544) - NumSharp vs DynMethod per-op"); + Console.WriteLine(); + Console.WriteLine("=== Comprehensive Benchmarks ==="); + Console.WriteLine("5. Arithmetic Operations (add, sub, mul, div, mod)"); + Console.WriteLine("6. Unary Operations (math, exp/log, trig, power)"); + Console.WriteLine("7. Reduction Operations (sum, mean, var/std, min/max)"); + Console.WriteLine("8. Broadcasting Operations"); + Console.WriteLine("9. Array Creation Operations"); + Console.WriteLine("10. Shape Manipulation (reshape, transpose, stack)"); + Console.WriteLine("11. Slicing Operations"); + Console.WriteLine("12. Multi-dimensional Arrays"); + Console.WriteLine(); + Console.WriteLine("=== Performance Analysis ==="); + Console.WriteLine("13. SIMD vs Scalar Comparison (binary ops, reductions)"); + Console.WriteLine(); + Console.WriteLine("=== Meta Options ==="); + Console.WriteLine("A. All Benchmarks"); + Console.WriteLine("Q. Quick smoke test (dry run)"); + Console.WriteLine(); + Console.Write("Select benchmark suite: "); + + var choice = Console.ReadLine()?.Trim().ToUpperInvariant(); + args = choice switch + { + "1" => ["--filter", "*Dispatch*"], + "2" => ["--filter", "*Fusion*"], + "3" => ["--filter", "*NumSharpBenchmarks*"], + "4" => ["--filter", "*DynamicEmission*"], + "5" => ["--filter", "*Arithmetic*"], + "6" => ["--filter", "*Unary*,*Math*,*ExpLog*,*Trig*,*Power*"], + "7" => ["--filter", "*Reduction*,*Sum*,*Mean*,*VarStd*,*MinMax*,*Prod*"], + "8" => ["--filter", "*Broadcast*"], + "9" => ["--filter", "*Creation*"], + "10" => ["--filter", "*Manipulation*,*Reshape*,*Stack*,*Dims*"], + "11" => ["--filter", "*Slice*"], + "12" => ["--filter", "*MultiDim*"], + "13" => ["--filter", "*SimdVsScalar*,*SimdReductionType*"], + "A" => [], + "Q" => ["--job", "Dry"], + _ => [] + }; +} + +BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); diff --git a/benchmark/NumSharp.Benchmark.GraphEngine/README.md b/benchmark/NumSharp.Benchmark.GraphEngine/README.md new file mode 100644 index 000000000..1f003887d --- /dev/null +++ b/benchmark/NumSharp.Benchmark.GraphEngine/README.md @@ -0,0 +1,326 @@ +# NumSharp Benchmark Suite + +[![BenchmarkDotNet](https://img.shields.io/badge/benchmark-BenchmarkDotNet%200.14-blue)](https://benchmarkdotnet.org/) +[![.NET](https://img.shields.io/badge/.NET-8.0%20%7C%2010.0-purple)](https://dotnet.microsoft.com/) +[![License](https://img.shields.io/badge/license-Apache%202.0-green)](../../LICENSE) + +Industry-standard performance benchmarks for [NumSharp](https://github.com/SciSharp/NumSharp) using [BenchmarkDotNet](https://benchmarkdotnet.org/). Compare NumSharp operations against NumPy baselines with reproducible, statistically rigorous measurements. + +## Key Metrics + +| Metric | Coverage | +|--------|----------| +| **Operations** | 130+ benchmarked operations | +| **Data Types** | All 12 NumSharp types | +| **Suites** | 12 benchmark categories | +| **Array Sizes** | Scalar, 100, 1K, 100K, 10M elements | + +## Quick Start + +```bash +# Navigate to benchmark directory +cd benchmark/NumSharp.Benchmark.GraphEngine + +# Build in Release mode (required for accurate benchmarks) +dotnet build -c Release + +# Run interactive benchmark menu +dotnet run -c Release -f net10.0 + +# Or run all benchmarks directly +dotnet run -c Release -f net10.0 -- --filter "*" +``` + +## Benchmark Suites + +### Core Operation Benchmarks + +| Suite | Operations | Description | +|-------|------------|-------------| +| **Arithmetic** | `+`, `-`, `*`, `/`, `%` | Binary arithmetic with element-wise and scalar variants | +| **Unary** | `sqrt`, `abs`, `exp`, `log`, `sin`, `cos`, `tan` | Single-input mathematical functions | +| **Reduction** | `sum`, `mean`, `var`, `std`, `min`, `max`, `prod` | Aggregation operations with axis support | +| **Broadcasting** | Scalar, row, column, 3D patterns | Shape broadcasting performance | + +### Memory & Layout Benchmarks + +| Suite | Operations | Description | +|-------|------------|-------------| +| **Creation** | `zeros`, `ones`, `empty`, `full`, `arange`, `copy` | Array allocation and initialization | +| **Manipulation** | `reshape`, `transpose`, `ravel`, `flatten` | Shape transformation (view vs copy) | +| **Stacking** | `concatenate`, `stack`, `hstack`, `vstack` | Combining multiple arrays | +| **Slicing** | Contiguous, strided, reversed slices | View creation and iteration | + +### Research Benchmarks + +| Suite | Operations | Description | +|-------|------------|-------------| +| **Dispatch** | Raw ptr, Static, Struct, DynamicMethod | Compares dispatch mechanisms for binary operations | +| **Fusion** | Multi-pass vs fused kernels | Evaluates kernel fusion optimization potential | +| **MultiDim** | 1D vs 2D vs 3D | Same operations across different dimensionalities | +| **DynamicEmission** | Per-operation IL emission | Proposed SIMD optimization via DynamicMethod | + +## Running Benchmarks + +### Interactive Menu + +```bash +dotnet run -c Release -f net10.0 +``` + +``` +NumSharp Performance Benchmarks +================================ + +=== Original Benchmarks === +1. Dispatch Mechanism Comparison +2. Fusion Pattern Benchmarks +3. NumSharp Current Performance +4. DynamicMethod Emission (#544) + +=== Comprehensive Benchmarks === +5. Arithmetic Operations +6. Unary Operations +7. Reduction Operations +8. Broadcasting Operations +9. Array Creation Operations +10. Shape Manipulation +11. Slicing Operations +12. Multi-dimensional Arrays + +=== Meta Options === +A. All Benchmarks +Q. Quick smoke test (dry run) +``` + +### Command-Line Options + +```bash +# Run specific suite by filter +dotnet run -c Release -- --filter "*Dispatch*" +dotnet run -c Release -- --filter "*Arithmetic*" +dotnet run -c Release -- --filter "*Reduction*,*Sum*" + +# Quick smoke test (single iteration) +dotnet run -c Release -- --job Dry + +# Short benchmarks (faster, less statistical rigor) +dotnet run -c Release -- --job Short + +# Filter by array size +dotnet run -c Release -- --filter "*10000000*" + +# Export results +dotnet run -c Release -- --exporters json html markdown + +# Compare .NET versions +dotnet run -c Release -f net10.0 -- --runtimes net8.0 net10.0 +``` + +### Common Filter Patterns + +| Pattern | Benchmarks | +|---------|------------| +| `*Add*` | All addition benchmarks | +| `*Sum*` | Sum reduction benchmarks | +| `*Arithmetic*` | Add, Subtract, Multiply, Divide, Modulo | +| `*Unary*,*Math*,*Trig*` | All unary operations | +| `*N: 1*` | Scalar benchmarks only (overhead analysis) | +| `*N: 100*` | Tiny array benchmarks only | +| `*10000000*` | Large array (10M elements) benchmarks only | + +## Interpreting Results + +### Output Columns + +| Column | Meaning | +|--------|---------| +| **Mean** | Average execution time | +| **Error** | Half of 99.9% confidence interval | +| **StdDev** | Standard deviation across iterations | +| **Ratio** | Time relative to baseline (1.00 = same speed) | +| **Rank** | Performance ranking (1 = fastest) | +| **Allocated** | Memory allocated per operation | + +### Performance Guidelines + +| Time Range | Interpretation | +|------------|----------------| +| < 1 μs | Pure metadata (view creation, shape queries) | +| 1 - 10 μs | Scalar operations, minimal dispatch overhead | +| 10 - 100 μs | Small array operations (100 elements) | +| 0.1 - 1 ms | Small overhead + minimal computation | +| 1 - 10 ms | Cache-efficient operations | +| 10 - 50 ms | Memory-bound operations | +| 50 - 200 ms | Complex operations (trig, var/std) | +| > 200 ms | Multi-pass or unoptimized | + +### Overhead Analysis (Scalar Benchmarks) + +Scalar (N=1) benchmarks isolate fixed costs: +- **Method dispatch**: Virtual calls, interface dispatch +- **Array allocation**: NDArray/Storage creation overhead +- **Safety checks**: Bounds checking, null checks +- **Type resolution**: NPTypeCode switching + +A well-optimized operation should show scalar overhead < 10 μs. + +### Memory Bandwidth Reference + +For 10M elements: +- **float32** (40 MB): ~5 ms theoretical minimum +- **float64** (80 MB): ~10 ms theoretical minimum +- Well-optimized operations should be within 2-5x of theoretical minimum + +## Architecture + +``` +NumSharp.Benchmark.GraphEngine/ +├── Program.cs # Entry point with interactive menu +├── Infrastructure/ +│ ├── BenchmarkBase.cs # Base class with array creation +│ ├── BenchmarkConfig.cs # BenchmarkDotNet configurations +│ ├── TypeParameterSource.cs # NPTypeCode collections +│ └── ArraySizeSource.cs # Standard array sizes +└── Benchmarks/ + ├── DispatchBenchmarks.cs # Dispatch mechanism comparison + ├── FusionBenchmarks.cs # Kernel fusion patterns + ├── NumSharpBenchmarks.cs # NumSharp baseline + ├── DynamicEmissionBenchmarks.cs # DynamicMethod per-op + ├── Arithmetic/ # +, -, *, /, % + ├── Unary/ # sqrt, exp, log, trig + ├── Reduction/ # sum, mean, var, min/max + ├── Broadcasting/ # Broadcast patterns + ├── Creation/ # zeros, ones, empty, full + ├── Manipulation/ # reshape, transpose, stack + ├── Slicing/ # View and slice operations + └── MultiDim/ # 1D vs 2D vs 3D +``` + +### Type Collections + +```csharp +TypeParameterSource.CommonTypes // int32, int64, float32, float64 (fast benchmarks) +TypeParameterSource.ArithmeticTypes // All types except bool, char +TypeParameterSource.TranscendentalTypes // float32, float64, decimal (for sqrt, log, trig) +TypeParameterSource.AllNumericTypes // All 12 NumSharp types +``` + +### Array Sizes + +```csharp +ArraySizeSource.Scalar = 1 // Pure overhead measurement (dispatch, allocation, no loop) +ArraySizeSource.Tiny = 100 // Common small collections (configs, batches, embeddings) +ArraySizeSource.Small = 1,000 // L1 cache, per-element overhead +ArraySizeSource.Medium = 100,000 // L2/L3 cache, typical use case +ArraySizeSource.Large = 10,000,000 // Memory-bound, throughput measurement +``` + +**Why these sizes matter:** +- **Scalar (1)**: Reveals fixed costs (method dispatch, array allocation, safety checks) with zero loop iterations +- **Tiny (100)**: Represents real-world small data (config arrays, feature vectors, small batches) +- **Small-Large**: Traditional cache-tier progression for throughput analysis + +## Adding New Benchmarks + +### 1. Create Benchmark Class + +```csharp +using BenchmarkDotNet.Attributes; +using NumSharp; +using NumSharp.Benchmark.GraphEngine.Infrastructure; + +namespace NumSharp.Benchmark.GraphEngine.Benchmarks.YourCategory; + +[BenchmarkCategory("YourCategory")] +public class YourBenchmarks : TypedBenchmarkBase +{ + private NDArray _a = null!; + + // Use StandardSizes for comprehensive coverage (scalar through large) + // Or pick specific sizes: Scalar, Tiny, Small, Medium, Large + [Params(ArraySizeSource.Scalar, ArraySizeSource.Tiny, ArraySizeSource.Small, + ArraySizeSource.Medium, ArraySizeSource.Large)] + public override int N { get; set; } + + [ParamsSource(nameof(Types))] + public new NPTypeCode DType { get; set; } + + public static IEnumerable Types => TypeParameterSource.CommonTypes; + + [GlobalSetup] + public void Setup() + { + _a = CreateRandomArray(N, DType); + } + + [GlobalCleanup] + public void Cleanup() + { + _a = null!; + GC.Collect(); + } + + [Benchmark(Description = "Your operation")] + public NDArray YourOperation() => np.your_operation(_a); +} +``` + +### 2. Add Menu Entry (Program.cs) + +```csharp +Console.WriteLine("13. Your New Benchmarks"); +// ... +"13" => ["--filter", "*YourBenchmarks*"], +``` + +### 3. Best Practices + +- Use `[GlobalSetup]` for array allocation (not measured) +- Use `[GlobalCleanup]` to release unmanaged memory +- Return results from benchmark methods (prevents dead code elimination) +- Use `CreateRandomArray()` with fixed seed for reproducibility +- Mark baseline with `[Benchmark(Baseline = true)]` for relative comparisons + +## Comparison with NumPy + +The companion Python benchmarks in `../numpy_benchmark.py` provide NumPy baselines using the same: +- Array sizes (1K, 100K, 10M) +- Random seeds (42) +- Operations + +```bash +# Run NumPy benchmarks +python ../NumSharp.Benchmark.Python/numpy_benchmark.py --output ../benchmark-report.json + +# Run full comparison suite +pwsh ../run-benchmarks.ps1 +``` + +See `../benchmark-report.md` for the generated comparison report. + +## Results Location + +After running benchmarks, results are saved to: + +``` +BenchmarkDotNet.Artifacts/ +└── results/ + ├── *-report.html # Interactive HTML report + ├── *-report.md # Markdown tables + └── *-report.json # Machine-readable JSON +``` + +## Contributing + +When adding benchmarks: + +1. Match existing code style and patterns +2. Use appropriate `TypeParameterSource` for your operation +3. Include both element-wise and scalar variants where applicable +4. Add corresponding Python benchmark in `numpy_benchmark.py` +5. Document any NumSharp API quirks (see `../CLAUDE.md`) + +## License + +This benchmark suite is part of NumSharp, licensed under [Apache 2.0](../../LICENSE). diff --git a/benchmark/NumSharp.Benchmark.Python/README.md b/benchmark/NumSharp.Benchmark.Python/README.md new file mode 100644 index 000000000..9cc881570 --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Python/README.md @@ -0,0 +1,75 @@ +# NumSharp Python Benchmarks + +NumPy baseline benchmarks for comparing against NumSharp performance. + +## Requirements + +```bash +pip install numpy tabulate +``` + +## Usage + +```bash +# Full benchmark suite +python numpy_benchmark.py + +# Quick run (fewer iterations) +python numpy_benchmark.py --quick + +# Specific suite +python numpy_benchmark.py --suite arithmetic +python numpy_benchmark.py --suite reduction + +# Specific type +python numpy_benchmark.py --type float64 + +# JSON output +python numpy_benchmark.py --output results.json + +# Combine options +python numpy_benchmark.py --quick --suite arithmetic --type int32 --output results.json +``` + +## Available Suites + +| Suite | Operations | +|-------|------------| +| `dispatch` | Basic add operations with different patterns | +| `fusion` | Multi-operation expressions (a*a+2*b, variance, etc.) | +| `arithmetic` | +, -, *, /, % with scalars and arrays | +| `unary` | sqrt, abs, exp, log, sin, cos, etc. | +| `reduction` | sum, mean, var, std, min, max, argmin, argmax | +| `broadcast` | Scalar, row, column broadcasting | +| `creation` | zeros, ones, empty, full, copy | +| `manipulation` | reshape, transpose, ravel, flatten, stack | +| `slicing` | Contiguous, strided, reversed slices | + +## Output Format + +Results are saved as JSON with the following structure: + +```json +{ + "name": "a + b (int32)", + "category": "Add", + "suite": "Arithmetic", + "dtype": "int32", + "n": 10000000, + "mean_ms": 10.5, + "stddev_ms": 0.5, + "min_ms": 9.8, + "max_ms": 11.2, + "iterations": 50, + "ops_per_sec": 95.2 +} +``` + +## Integration + +This script is typically run via the parent `run-benchmarks.ps1` script which: +1. Runs Python benchmarks +2. Runs C# benchmarks +3. Merges results into a comparison report + +See `../README.md` for the latest benchmark results. diff --git a/benchmark/NumSharp.Benchmark.Python/numpy_benchmark.py b/benchmark/NumSharp.Benchmark.Python/numpy_benchmark.py new file mode 100644 index 000000000..cf90ecdde --- /dev/null +++ b/benchmark/NumSharp.Benchmark.Python/numpy_benchmark.py @@ -0,0 +1,925 @@ +#!/usr/bin/env python3 +""" +NumPy Performance Benchmarks +============================ + +Comprehensive benchmarks matching the C# NumSharp.Benchmark.GraphEngine suite. +These provide the baseline for comparing NumSharp performance against NumPy. + +Usage: + python numpy_benchmark.py # Run all benchmarks + python numpy_benchmark.py --suite dispatch # Run specific suite + python numpy_benchmark.py --quick # Quick run (fewer reps) + python numpy_benchmark.py --json # Output JSON for parsing + python numpy_benchmark.py --type int32 # Run specific type + python numpy_benchmark.py --size 10000000 # Specific array size + +Requirements: + pip install numpy tabulate +""" + +import numpy as np +import time +import argparse +import json +import sys +from dataclasses import dataclass, asdict +from typing import Callable, List, Optional, Dict, Any +import statistics + +# ============================================================================= +# Configuration +# ============================================================================= + +ARRAY_SIZES = { + 'scalar': 1, # Pure overhead measurement (dispatch, allocation, no loop) + 'tiny': 100, # Common small collections (configs, batches, embeddings) + 'small': 1_000, # L1 cache, per-element overhead + 'medium': 100_000, # L2/L3 cache, typical use case + 'large': 10_000_000 # Memory-bound, throughput measurement +} + +# NumPy dtypes matching NumSharp's 12 supported types +DTYPES = { + 'bool': np.bool_, + 'uint8': np.uint8, + 'int16': np.int16, + 'uint16': np.uint16, + 'int32': np.int32, + 'uint32': np.uint32, + 'int64': np.int64, + 'uint64': np.uint64, + 'float32': np.float32, + 'float64': np.float64, +} + +# Common types for quick benchmarks +COMMON_DTYPES = ['int32', 'int64', 'float32', 'float64'] + +# Arithmetic types (excludes bool) +ARITHMETIC_DTYPES = ['uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', 'float32', 'float64'] + +# Transcendental types (for sqrt, exp, log, trig) +TRANSCENDENTAL_DTYPES = ['float32', 'float64'] + +# ============================================================================= +# Benchmark Infrastructure +# ============================================================================= + +@dataclass +class BenchmarkResult: + name: str + category: str + suite: str + dtype: str + n: int + mean_ms: float + stddev_ms: float + min_ms: float + max_ms: float + iterations: int + ops_per_sec: float + allocated_mb: float = 0.0 + +def benchmark(func: Callable, n: int, warmup: int = 10, iterations: int = 50) -> BenchmarkResult: + """Run a benchmark with proper warmup and statistical analysis.""" + # Warmup + for _ in range(warmup): + func() + + # Timed runs + times = [] + for _ in range(iterations): + start = time.perf_counter() + func() + elapsed = (time.perf_counter() - start) * 1000 # ms + times.append(elapsed) + + mean = statistics.mean(times) + stddev = statistics.stdev(times) if len(times) > 1 else 0 + + return BenchmarkResult( + name=func.__name__ if hasattr(func, '__name__') else str(func), + category="", + suite="", + dtype="", + n=n, + mean_ms=mean, + stddev_ms=stddev, + min_ms=min(times), + max_ms=max(times), + iterations=iterations, + ops_per_sec=1000.0 / mean if mean > 0 else 0 + ) + +def create_random_array(n: int, dtype_name: str, seed: int = 42) -> np.ndarray: + """Create a random array of the specified dtype.""" + np.random.seed(seed) + dtype = DTYPES[dtype_name] + + if dtype == np.bool_: + return np.random.randint(0, 2, n, dtype=dtype) + elif np.issubdtype(dtype, np.integer): + if np.issubdtype(dtype, np.unsignedinteger): + return np.random.randint(0, 100, n, dtype=dtype) + else: + return np.random.randint(-50, 50, n, dtype=dtype) + else: + return (np.random.random(n) * 100 - 50).astype(dtype) + +def create_positive_array(n: int, dtype_name: str, seed: int = 42) -> np.ndarray: + """Create a positive random array (for sqrt, log, etc.).""" + np.random.seed(seed) + dtype = DTYPES[dtype_name] + return (np.random.random(n) * 100 + 1).astype(dtype) + +# ============================================================================= +# Arithmetic Benchmarks +# ============================================================================= + +def run_arithmetic_benchmarks(n: int, dtype_name: str, iterations: int) -> List[BenchmarkResult]: + """Benchmark arithmetic operations for a specific dtype. + + Matches C# benchmark classes: + - AddBenchmarks: Add_Elementwise, NpAdd, Add_Scalar, Add_ScalarLiteral + - SubtractBenchmarks: Subtract_Elementwise, Subtract_Scalar, Subtract_ScalarLeft + - MultiplyBenchmarks: Multiply_Elementwise, Multiply_Square, Multiply_Scalar, Multiply_ScalarLiteral + - DivideBenchmarks: Divide_Elementwise, Divide_Scalar, Divide_ScalarLeft (CommonTypes only) + - ModuloBenchmarks: Modulo_Elementwise, Modulo_Scalar (CommonTypes only) + """ + results = [] + dtype = DTYPES[dtype_name] + + np.random.seed(42) + a = create_random_array(n, dtype_name, seed=42) + b = create_random_array(n, dtype_name, seed=43) + b_positive = create_positive_array(n, dtype_name, seed=43) # Avoid div by zero + scalar = dtype(5) + scalar2 = dtype(2) + + # ======================================================================== + # Add (matches AddBenchmarks.cs - ArithmeticTypes = 10 types) + # ======================================================================== + + # Add_Elementwise: a + b (element-wise) + def add_elementwise(): return a + b + r = benchmark(add_elementwise, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"a + b (element-wise) ({dtype_name})", "Add", "Arithmetic", dtype_name + results.append(r) + + # NpAdd: np.add(a, b) + def np_add(): return np.add(a, b) + r = benchmark(np_add, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.add(a, b) ({dtype_name})", "Add", "Arithmetic", dtype_name + results.append(r) + + # Add_Scalar: a + scalar + def add_scalar(): return a + scalar + r = benchmark(add_scalar, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"a + scalar ({dtype_name})", "Add", "Arithmetic", dtype_name + results.append(r) + + # Add_ScalarLiteral: a + 5 (literal) + def add_scalar_literal(): return a + 5 + r = benchmark(add_scalar_literal, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"a + 5 (literal) ({dtype_name})", "Add", "Arithmetic", dtype_name + results.append(r) + + # ======================================================================== + # Subtract (matches SubtractBenchmarks.cs - ArithmeticTypes = 10 types) + # ======================================================================== + + # Subtract_Elementwise: a - b (element-wise) + def sub_elementwise(): return a - b + r = benchmark(sub_elementwise, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"a - b (element-wise) ({dtype_name})", "Subtract", "Arithmetic", dtype_name + results.append(r) + + # Subtract_Scalar: a - scalar + def sub_scalar(): return a - scalar + r = benchmark(sub_scalar, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"a - scalar ({dtype_name})", "Subtract", "Arithmetic", dtype_name + results.append(r) + + # Subtract_ScalarLeft: scalar - a + def sub_scalar_left(): return scalar - a + r = benchmark(sub_scalar_left, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"scalar - a ({dtype_name})", "Subtract", "Arithmetic", dtype_name + results.append(r) + + # ======================================================================== + # Multiply (matches MultiplyBenchmarks.cs - ArithmeticTypes = 10 types) + # ======================================================================== + + # Multiply_Elementwise: a * b (element-wise) + def mul_elementwise(): return a * b + r = benchmark(mul_elementwise, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"a * b (element-wise) ({dtype_name})", "Multiply", "Arithmetic", dtype_name + results.append(r) + + # Multiply_Square: a * a (square) + def mul_square(): return a * a + r = benchmark(mul_square, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"a * a (square) ({dtype_name})", "Multiply", "Arithmetic", dtype_name + results.append(r) + + # Multiply_Scalar: a * scalar + def mul_scalar(): return a * scalar2 + r = benchmark(mul_scalar, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"a * scalar ({dtype_name})", "Multiply", "Arithmetic", dtype_name + results.append(r) + + # Multiply_ScalarLiteral: a * 2 (literal) + def mul_scalar_literal(): return a * 2 + r = benchmark(mul_scalar_literal, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"a * 2 (literal) ({dtype_name})", "Multiply", "Arithmetic", dtype_name + results.append(r) + + # ======================================================================== + # Divide (matches DivideBenchmarks.cs - CommonTypes = 4 types) + # ======================================================================== + if dtype_name in COMMON_DTYPES: + # Divide_Elementwise: a / b (element-wise) + def div_elementwise(): return a / b_positive + r = benchmark(div_elementwise, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"a / b (element-wise) ({dtype_name})", "Divide", "Arithmetic", dtype_name + results.append(r) + + # Divide_Scalar: a / scalar + def div_scalar(): return a / scalar2 + r = benchmark(div_scalar, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"a / scalar ({dtype_name})", "Divide", "Arithmetic", dtype_name + results.append(r) + + # Divide_ScalarLeft: scalar / a + def div_scalar_left(): return scalar2 / b_positive + r = benchmark(div_scalar_left, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"scalar / a ({dtype_name})", "Divide", "Arithmetic", dtype_name + results.append(r) + + # ======================================================================== + # Modulo (matches ModuloBenchmarks.cs - CommonTypes = 4 types) + # ======================================================================== + if dtype_name in COMMON_DTYPES: + # Modulo_Elementwise: a % b (element-wise) + def mod_elementwise(): return a % b_positive + r = benchmark(mod_elementwise, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"a % b (element-wise) ({dtype_name})", "Modulo", "Arithmetic", dtype_name + results.append(r) + + # Modulo_Scalar: a % 7 (literal) + def mod_scalar(): return a % 7 + r = benchmark(mod_scalar, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"a % 7 (literal) ({dtype_name})", "Modulo", "Arithmetic", dtype_name + results.append(r) + + return results + +# ============================================================================= +# Unary Benchmarks +# ============================================================================= + +def run_unary_benchmarks(n: int, dtype_name: str, iterations: int) -> List[BenchmarkResult]: + """Benchmark unary operations for a specific dtype.""" + results = [] + + a = create_random_array(n, dtype_name, seed=42) + a_positive = create_positive_array(n, dtype_name, seed=42) + a_small = (np.random.random(n) * 10).astype(DTYPES[dtype_name]) # For exp + + # Math functions + def np_sqrt(): return np.sqrt(a_positive) + r = benchmark(np_sqrt, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.sqrt ({dtype_name})", "Math", "Unary", dtype_name + results.append(r) + + def np_abs(): return np.abs(a) + r = benchmark(np_abs, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.abs ({dtype_name})", "Math", "Unary", dtype_name + results.append(r) + + def np_sign(): return np.sign(a) + r = benchmark(np_sign, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.sign ({dtype_name})", "Math", "Unary", dtype_name + results.append(r) + + # Rounding (float only) + if np.issubdtype(DTYPES[dtype_name], np.floating): + def np_floor(): return np.floor(a) + r = benchmark(np_floor, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.floor ({dtype_name})", "Rounding", "Unary", dtype_name + results.append(r) + + def np_ceil(): return np.ceil(a) + r = benchmark(np_ceil, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.ceil ({dtype_name})", "Rounding", "Unary", dtype_name + results.append(r) + + def np_round(): return np.round(a) + r = benchmark(np_round, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.round ({dtype_name})", "Rounding", "Unary", dtype_name + results.append(r) + + # Exp/Log (float only) + if np.issubdtype(DTYPES[dtype_name], np.floating): + def np_exp(): return np.exp(a_small) + r = benchmark(np_exp, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.exp ({dtype_name})", "ExpLog", "Unary", dtype_name + results.append(r) + + def np_log(): return np.log(a_positive) + r = benchmark(np_log, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.log ({dtype_name})", "ExpLog", "Unary", dtype_name + results.append(r) + + def np_log10(): return np.log10(a_positive) + r = benchmark(np_log10, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.log10 ({dtype_name})", "ExpLog", "Unary", dtype_name + results.append(r) + + # Trig (float only) + if np.issubdtype(DTYPES[dtype_name], np.floating): + angles = (np.random.random(n) * 4 - 2) * np.pi + + def np_sin(): return np.sin(angles) + r = benchmark(np_sin, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.sin ({dtype_name})", "Trig", "Unary", dtype_name + results.append(r) + + def np_cos(): return np.cos(angles) + r = benchmark(np_cos, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.cos ({dtype_name})", "Trig", "Unary", dtype_name + results.append(r) + + return results + +# ============================================================================= +# Reduction Benchmarks +# ============================================================================= + +def run_reduction_benchmarks(n: int, dtype_name: str, iterations: int) -> List[BenchmarkResult]: + """Benchmark reduction operations.""" + results = [] + + a = create_random_array(n, dtype_name, seed=42) + rows = int(np.sqrt(n)) + cols = n // rows + a_2d = create_random_array(rows * cols, dtype_name, seed=42).reshape(rows, cols) + + # Sum + def np_sum(): return np.sum(a) + r = benchmark(np_sum, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.sum ({dtype_name})", "Sum", "Reduction", dtype_name + results.append(r) + + def np_sum_axis0(): return np.sum(a_2d, axis=0) + r = benchmark(np_sum_axis0, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.sum axis=0 ({dtype_name})", "Sum", "Reduction", dtype_name + results.append(r) + + def np_sum_axis1(): return np.sum(a_2d, axis=1) + r = benchmark(np_sum_axis1, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.sum axis=1 ({dtype_name})", "Sum", "Reduction", dtype_name + results.append(r) + + # Mean + def np_mean(): return np.mean(a) + r = benchmark(np_mean, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.mean ({dtype_name})", "Mean", "Reduction", dtype_name + results.append(r) + + # Var/Std (float only for accuracy) + if np.issubdtype(DTYPES[dtype_name], np.floating): + def np_var(): return np.var(a) + r = benchmark(np_var, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.var ({dtype_name})", "VarStd", "Reduction", dtype_name + results.append(r) + + def np_std(): return np.std(a) + r = benchmark(np_std, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.std ({dtype_name})", "VarStd", "Reduction", dtype_name + results.append(r) + + # Min/Max + def np_amin(): return np.amin(a) + r = benchmark(np_amin, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.amin ({dtype_name})", "MinMax", "Reduction", dtype_name + results.append(r) + + def np_amax(): return np.amax(a) + r = benchmark(np_amax, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.amax ({dtype_name})", "MinMax", "Reduction", dtype_name + results.append(r) + + # ArgMin/ArgMax + def np_argmin(): return np.argmin(a) + r = benchmark(np_argmin, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.argmin ({dtype_name})", "ArgMinMax", "Reduction", dtype_name + results.append(r) + + def np_argmax(): return np.argmax(a) + r = benchmark(np_argmax, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.argmax ({dtype_name})", "ArgMinMax", "Reduction", dtype_name + results.append(r) + + return results + +# ============================================================================= +# Broadcasting Benchmarks +# ============================================================================= + +def run_broadcast_benchmarks(n: int, iterations: int) -> List[BenchmarkResult]: + """Benchmark broadcasting operations.""" + results = [] + dtype_name = 'float64' + + np.random.seed(42) + matrix_size = int(np.sqrt(n)) + matrix = np.random.random((matrix_size, matrix_size)) * 100 + row_vector = np.random.random(matrix_size) * 100 + col_vector = np.random.random((matrix_size, 1)) * 100 + scalar = np.array(42.0) + + # Scalar broadcast + def broadcast_scalar(): return matrix + scalar + r = benchmark(broadcast_scalar, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = "matrix + scalar", "Scalar", "Broadcasting", dtype_name + results.append(r) + + # Row broadcast + def broadcast_row(): return matrix + row_vector + r = benchmark(broadcast_row, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = "matrix + row_vector (N,M)+(M,)", "Row", "Broadcasting", dtype_name + results.append(r) + + # Column broadcast + def broadcast_col(): return matrix + col_vector + r = benchmark(broadcast_col, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = "matrix + col_vector (N,M)+(N,1)", "Column", "Broadcasting", dtype_name + results.append(r) + + # broadcast_to + def broadcast_to_row(): return np.broadcast_to(row_vector, (matrix_size, matrix_size)) + r = benchmark(broadcast_to_row, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = "np.broadcast_to(row, (N,M))", "BroadcastTo", "Broadcasting", dtype_name + results.append(r) + + return results + +# ============================================================================= +# Creation Benchmarks +# ============================================================================= + +def run_creation_benchmarks(n: int, dtype_name: str, iterations: int) -> List[BenchmarkResult]: + """Benchmark array creation functions.""" + results = [] + dtype = DTYPES[dtype_name] + source = create_random_array(n, dtype_name) + + # Initialized arrays + def np_zeros(): return np.zeros(n, dtype=dtype) + r = benchmark(np_zeros, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.zeros ({dtype_name})", "Initialized", "Creation", dtype_name + results.append(r) + + def np_ones(): return np.ones(n, dtype=dtype) + r = benchmark(np_ones, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.ones ({dtype_name})", "Initialized", "Creation", dtype_name + results.append(r) + + def np_full(): return np.full(n, 42, dtype=dtype) + r = benchmark(np_full, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.full ({dtype_name})", "Initialized", "Creation", dtype_name + results.append(r) + + def np_empty(): return np.empty(n, dtype=dtype) + r = benchmark(np_empty, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.empty ({dtype_name})", "Uninitialized", "Creation", dtype_name + results.append(r) + + # Copy + def np_copy(): return np.copy(source) + r = benchmark(np_copy, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.copy ({dtype_name})", "Copy", "Creation", dtype_name + results.append(r) + + # Like-based + def np_zeros_like(): return np.zeros_like(source) + r = benchmark(np_zeros_like, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = f"np.zeros_like ({dtype_name})", "Like", "Creation", dtype_name + results.append(r) + + return results + +# ============================================================================= +# Manipulation Benchmarks +# ============================================================================= + +def run_manipulation_benchmarks(n: int, iterations: int) -> List[BenchmarkResult]: + """Benchmark shape manipulation operations.""" + results = [] + dtype_name = 'float64' + + np.random.seed(42) + rows = int(np.sqrt(n)) + cols = n // rows + actual_n = rows * cols # May be slightly less than n due to integer division + arr_1d = np.random.random(actual_n) * 100 # Use actual_n to ensure reshape works + arr_2d = np.random.random((rows, cols)) * 100 + d = int(n ** (1/3)) + arr_3d = np.random.random((d, d, d)) * 100 + + # Reshape + def reshape_1d_2d(): return arr_1d.reshape(rows, cols) + r = benchmark(reshape_1d_2d, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = "reshape 1D->2D", "Reshape", "Manipulation", dtype_name + results.append(r) + + def reshape_2d_1d(): return arr_2d.reshape(-1) + r = benchmark(reshape_2d_1d, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = "reshape 2D->1D", "Reshape", "Manipulation", dtype_name + results.append(r) + + # Transpose + def transpose_2d(): return arr_2d.T + r = benchmark(transpose_2d, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = "a.T (2D)", "Transpose", "Manipulation", dtype_name + results.append(r) + + def np_transpose(): return np.transpose(arr_2d) + r = benchmark(np_transpose, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = "np.transpose (2D)", "Transpose", "Manipulation", dtype_name + results.append(r) + + # Ravel/Flatten + def np_ravel(): return np.ravel(arr_2d) + r = benchmark(np_ravel, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = "np.ravel", "Flatten", "Manipulation", dtype_name + results.append(r) + + def np_flatten(): return arr_2d.flatten() + r = benchmark(np_flatten, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = "a.flatten", "Flatten", "Manipulation", dtype_name + results.append(r) + + # Stack + arr_1d_b = np.random.random(actual_n) * 100 # Same size as arr_1d + + def np_concatenate(): return np.concatenate([arr_1d, arr_1d_b]) + r = benchmark(np_concatenate, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = "np.concatenate", "Stack", "Manipulation", dtype_name + results.append(r) + + def np_stack(): return np.stack([arr_1d, arr_1d_b]) + r = benchmark(np_stack, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = "np.stack", "Stack", "Manipulation", dtype_name + results.append(r) + + return results + +# ============================================================================= +# Slicing Benchmarks +# ============================================================================= + +def run_slicing_benchmarks(n: int, iterations: int) -> List[BenchmarkResult]: + """Benchmark slicing operations.""" + results = [] + dtype_name = 'float64' + + np.random.seed(42) + arr_1d = np.random.random(n) * 100 + rows = int(np.sqrt(n)) + cols = n // rows + arr_2d = np.random.random((rows, cols)) * 100 + + # Contiguous slice + contiguous_slice = arr_1d[100:1000] + strided_slice = arr_1d[::2] + + # Slice creation + def slice_contiguous(): return arr_1d[100:1000] + r = benchmark(slice_contiguous, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = "a[100:1000] (contiguous)", "Create", "Slicing", dtype_name + results.append(r) + + def slice_strided(): return arr_1d[::2] + r = benchmark(slice_strided, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = "a[::2] (strided)", "Create", "Slicing", dtype_name + results.append(r) + + def slice_reversed(): return arr_1d[::-1] + r = benchmark(slice_reversed, n, iterations=iterations) + r.name, r.category, r.suite, r.dtype = "a[::-1] (reversed)", "Create", "Slicing", dtype_name + results.append(r) + + # Operations on slices + def sum_contiguous(): return np.sum(contiguous_slice) + r = benchmark(sum_contiguous, len(contiguous_slice), iterations=iterations) + r.name, r.category, r.suite, r.dtype = "np.sum(contiguous_slice)", "SumSlice", "Slicing", dtype_name + results.append(r) + + def sum_strided(): return np.sum(strided_slice) + r = benchmark(sum_strided, len(strided_slice), iterations=iterations) + r.name, r.category, r.suite, r.dtype = "np.sum(strided_slice)", "SumSlice", "Slicing", dtype_name + results.append(r) + + return results + +# ============================================================================= +# Dispatch Benchmarks (matching DispatchBenchmarks.cs) +# ============================================================================= + +def run_dispatch_benchmarks(n: int, iterations: int) -> List[BenchmarkResult]: + """Compare different ways to perform c = a + b.""" + print(f"\n{'='*60}") + print(f" Dispatch Benchmarks (int32, N={n:,})") + print(f"{'='*60}\n") + + # Setup + np.random.seed(42) + a = np.random.randint(0, 100, n, dtype=np.int32) + b = np.random.randint(0, 100, n, dtype=np.int32) + c = np.empty(n, dtype=np.int32) + + results = [] + + # np.add with pre-allocated output + def numpy_add_out(): + np.add(a, b, out=c) + r = benchmark(numpy_add_out, n, iterations=iterations) + r.name = "np.add(a, b, out=c)" + r.category = "Dispatch" + r.suite = "Dispatch" + r.dtype = "int32" + results.append(r) + print(f" {r.name:<40} {r.mean_ms:>8.3f} ms (±{r.stddev_ms:.3f})") + + # Operator syntax (allocates new array) + def numpy_operator(): + return a + b + r = benchmark(numpy_operator, n, iterations=iterations) + r.name = "c = a + b (allocates)" + r.category = "Dispatch" + r.suite = "Dispatch" + r.dtype = "int32" + results.append(r) + print(f" {r.name:<40} {r.mean_ms:>8.3f} ms (±{r.stddev_ms:.3f})") + + # Scalar broadcast + scalar = b[0] + def numpy_broadcast(): + np.add(a, scalar, out=c) + r = benchmark(numpy_broadcast, n, iterations=iterations) + r.name = "np.add(a, scalar, out=c)" + r.category = "Dispatch" + r.suite = "Dispatch" + r.dtype = "int32" + results.append(r) + print(f" {r.name:<40} {r.mean_ms:>8.3f} ms (±{r.stddev_ms:.3f})") + + return results + +# ============================================================================= +# Fusion Benchmarks (matching FusionBenchmarks.cs) +# ============================================================================= + +def run_fusion_benchmarks(n: int, iterations: int) -> List[BenchmarkResult]: + """Compare compound expressions - NumPy cannot fuse these.""" + print(f"\n{'='*60}") + print(f" Fusion Benchmarks (float64, N={n:,})") + print(f"{'='*60}\n") + + # Setup + np.random.seed(42) + a = np.random.random(n) * 10 + b = np.random.random(n) * 10 + mean_val = np.mean(a) + + results = [] + + # Pattern 1: c = a * a + print(" --- Pattern 1: c = a * a ---") + def p1_numpy(): + return a * a + r = benchmark(p1_numpy, n, iterations=iterations) + r.name = "NumPy: a * a" + r.category = "Pattern1_Square" + r.suite = "Fusion" + r.dtype = "float64" + results.append(r) + print(f" {r.name:<40} {r.mean_ms:>8.3f} ms") + + # Pattern 2: c = a*a + 2*b + print("\n --- Pattern 2: c = a*a + 2*b ---") + def p2_numpy(): + return a*a + 2*b + r = benchmark(p2_numpy, n, iterations=iterations) + r.name = "NumPy: a*a + 2*b" + r.category = "Pattern2_AaBb" + r.suite = "Fusion" + r.dtype = "float64" + results.append(r) + print(f" {r.name:<40} {r.mean_ms:>8.3f} ms") + + # Pattern 3: variance + print("\n --- Pattern 3: variance ---") + def p3_manual(): + return np.sum((a - mean_val) ** 2) / n + r = benchmark(p3_manual, n, iterations=iterations) + r.name = "NumPy: sum((a-mean)**2)/N" + r.category = "Pattern3_Variance" + r.suite = "Fusion" + r.dtype = "float64" + results.append(r) + print(f" {r.name:<40} {r.mean_ms:>8.3f} ms") + + def p3_optimized(): + return np.var(a) + r = benchmark(p3_optimized, n, iterations=iterations) + r.name = "NumPy: np.var(a) [optimized]" + r.category = "Pattern3_Variance" + r.suite = "Fusion" + r.dtype = "float64" + results.append(r) + print(f" {r.name:<40} {r.mean_ms:>8.3f} ms") + + # Pattern 4: polynomial a³ + a² + a + print("\n --- Pattern 4: c = a³ + a² + a ---") + def p4_power(): + return a**3 + a**2 + a + r = benchmark(p4_power, n, iterations=iterations) + r.name = "NumPy: a**3 + a**2 + a" + r.category = "Pattern4_Polynomial" + r.suite = "Fusion" + r.dtype = "float64" + results.append(r) + print(f" {r.name:<40} {r.mean_ms:>8.3f} ms") + + def p4_multiply(): + return a*a*a + a*a + a + r = benchmark(p4_multiply, n, iterations=iterations) + r.name = "NumPy: a*a*a + a*a + a" + r.category = "Pattern4_Polynomial" + r.suite = "Fusion" + r.dtype = "float64" + results.append(r) + print(f" {r.name:<40} {r.mean_ms:>8.3f} ms") + + # Pattern 5: euclidean sqrt(a² + b²) + print("\n --- Pattern 5: c = sqrt(a² + b²) ---") + def p5_manual(): + return np.sqrt(a**2 + b**2) + r = benchmark(p5_manual, n, iterations=iterations) + r.name = "NumPy: sqrt(a**2 + b**2)" + r.category = "Pattern5_Euclidean" + r.suite = "Fusion" + r.dtype = "float64" + results.append(r) + print(f" {r.name:<40} {r.mean_ms:>8.3f} ms") + + def p5_hypot(): + return np.hypot(a, b) + r = benchmark(p5_hypot, n, iterations=iterations) + r.name = "NumPy: np.hypot(a, b) [optimized]" + r.category = "Pattern5_Euclidean" + r.suite = "Fusion" + r.dtype = "float64" + results.append(r) + print(f" {r.name:<40} {r.mean_ms:>8.3f} ms") + + return results + +# ============================================================================= +# Main +# ============================================================================= + +def print_summary(results: List[BenchmarkResult]): + """Print a summary table of all results.""" + try: + from tabulate import tabulate + headers = ["Name", "Suite", "DType", "N", "Mean (ms)", "StdDev"] + rows = [ + [r.name, r.suite, r.dtype, f"{r.n:,}", f"{r.mean_ms:.3f}", f"{r.stddev_ms:.3f}"] + for r in results + ] + print(f"\n{'='*80}") + print(" SUMMARY") + print(f"{'='*80}") + print(tabulate(rows, headers=headers, tablefmt="github")) + except ImportError: + print("\n(Install 'tabulate' for formatted table output: pip install tabulate)") + +def main(): + parser = argparse.ArgumentParser(description="NumPy Performance Benchmarks") + parser.add_argument("--suite", choices=["dispatch", "fusion", "arithmetic", "unary", "reduction", + "broadcast", "creation", "manipulation", "slicing", "all"], + default="all", help="Benchmark suite to run") + parser.add_argument("--n", type=int, default=10_000_000, help="Array size") + parser.add_argument("--size", choices=["small", "medium", "large"], default=None, help="Array size preset") + parser.add_argument("--type", type=str, default=None, help="Specific dtype (e.g., int32, float64)") + parser.add_argument("--iterations", type=int, default=50, help="Benchmark iterations") + parser.add_argument("--quick", action="store_true", help="Quick run (10 iterations, common types only)") + parser.add_argument("--json", action="store_true", help="Output JSON") + parser.add_argument("--output", type=str, default=None, help="Output JSON to file") + args = parser.parse_args() + + if args.quick: + args.iterations = 10 + + if args.size: + args.n = ARRAY_SIZES[args.size] + + # Determine which dtypes to run + dtypes_to_run = COMMON_DTYPES if args.quick else ARITHMETIC_DTYPES + if args.type: + dtypes_to_run = [args.type] + + print(f"\nNumPy {np.__version__}") + print(f"Python {sys.version.split()[0]}") + print(f"Array size: N = {args.n:,}") + print(f"Iterations: {args.iterations}") + print(f"Types: {dtypes_to_run}") + + all_results = [] + + # Dispatch and Fusion benchmarks (original) + if args.suite in ["dispatch", "all"]: + all_results.extend(run_dispatch_benchmarks(args.n, args.iterations)) + + if args.suite in ["fusion", "all"]: + all_results.extend(run_fusion_benchmarks(args.n, args.iterations)) + + # Comprehensive benchmarks with type iteration + if args.suite in ["arithmetic", "all"]: + print(f"\n{'='*60}") + print(f" Arithmetic Benchmarks (N={args.n:,})") + print(f"{'='*60}") + for dtype in dtypes_to_run: + if dtype in ARITHMETIC_DTYPES: + print(f"\n --- {dtype} ---") + results = run_arithmetic_benchmarks(args.n, dtype, args.iterations) + all_results.extend(results) + for r in results: + print(f" {r.name:<40} {r.mean_ms:>8.3f} ms") + + if args.suite in ["unary", "all"]: + print(f"\n{'='*60}") + print(f" Unary Benchmarks (N={args.n:,})") + print(f"{'='*60}") + for dtype in dtypes_to_run: + if dtype in TRANSCENDENTAL_DTYPES: + print(f"\n --- {dtype} ---") + results = run_unary_benchmarks(args.n, dtype, args.iterations) + all_results.extend(results) + for r in results: + print(f" {r.name:<40} {r.mean_ms:>8.3f} ms") + + if args.suite in ["reduction", "all"]: + print(f"\n{'='*60}") + print(f" Reduction Benchmarks (N={args.n:,})") + print(f"{'='*60}") + for dtype in dtypes_to_run: + print(f"\n --- {dtype} ---") + results = run_reduction_benchmarks(args.n, dtype, args.iterations) + all_results.extend(results) + for r in results: + print(f" {r.name:<40} {r.mean_ms:>8.3f} ms") + + if args.suite in ["broadcast", "all"]: + all_results.extend(run_broadcast_benchmarks(args.n, args.iterations)) + + if args.suite in ["creation", "all"]: + print(f"\n{'='*60}") + print(f" Creation Benchmarks (N={args.n:,})") + print(f"{'='*60}") + for dtype in COMMON_DTYPES: + print(f"\n --- {dtype} ---") + results = run_creation_benchmarks(args.n, dtype, args.iterations) + all_results.extend(results) + for r in results: + print(f" {r.name:<40} {r.mean_ms:>8.3f} ms") + + if args.suite in ["manipulation", "all"]: + all_results.extend(run_manipulation_benchmarks(args.n, args.iterations)) + + if args.suite in ["slicing", "all"]: + all_results.extend(run_slicing_benchmarks(args.n, args.iterations)) + + # Output + if args.json or args.output: + json_output = json.dumps([asdict(r) for r in all_results], indent=2) + if args.output: + with open(args.output, 'w') as f: + f.write(json_output) + print(f"\nJSON results written to: {args.output}") + if args.json: + print("\n" + json_output) + else: + print_summary(all_results) + + print(f"\n{'='*60}") + print(f" Benchmark complete ({len(all_results)} results)") + print(f"{'='*60}") + +if __name__ == "__main__": + main() diff --git a/benchmark/README.md b/benchmark/README.md new file mode 100644 index 000000000..ea2fa805e --- /dev/null +++ b/benchmark/README.md @@ -0,0 +1,128 @@ +# NumSharp vs NumPy Performance + +**Baseline:** NumPy (N=10M elements) + +**Ratio** = NumSharp ÷ NumPy → Lower is better for NumSharp + +| | Status | Ratio | Meaning | +|:-:|--------|:-----:|---------| +|✅| Faster | <1.0 | NumSharp beats NumPy | +|🟡| Close | 1-2x | Acceptable parity | +|🟠| Slower | 2-5x | Optimization target | +|🔴| Slow | >5x | Priority fix | +|⚪| Pending | - | C# benchmark not run | + +--- + +**Summary:** 64 ops | ✅ 61 | 🟡 3 | 🟠 0 | 🔴 0 | ⚪ 0 + +### 🏆 Top 15 Best (NumSharp closest to NumPy) + +| | Operation | Type | NumPy | NumSharp | Ratio | +|:-:|-----------|:----:|------:|---------:|------:| +|✅| a % 7 (literal) (float64) | float64 | 267.0 | 39.8 | 0.1x | +|✅| a % b (element-wise) (float64) | float64 | 188.5 | 45.7 | 0.2x | +|✅| a % 7 (literal) (int32) | int32 | 49.7 | 13.8 | 0.3x | +|✅| a % b (element-wise) (int32) | int32 | 46.9 | 13.9 | 0.3x | +|✅| a % 7 (literal) (int64) | int64 | 49.2 | 23.9 | 0.5x | +|✅| a % b (element-wise) (int64) | int64 | 48.1 | 24.2 | 0.5x | +|✅| a % b (element-wise) (float32) | float32 | 155.0 | 84.3 | 0.5x | +|✅| a % 7 (literal) (float32) | float32 | 174.6 | 96.7 | 0.6x | +|✅| scalar - a (int32) | int32 | 11.4 | 7.2 | 0.6x | +|✅| a / b (element-wise) (int32) | int32 | 21.7 | 14.1 | 0.7x | +|✅| a - b (element-wise) (int32) | int32 | 11.1 | 7.4 | 0.7x | +|✅| a * a (square) (int32) | int32 | 9.7 | 6.7 | 0.7x | +|✅| a * b (element-wise) (int32) | int32 | 10.3 | 7.4 | 0.7x | +|✅| a + b (element-wise) (int64) | int64 | 20.3 | 14.8 | 0.7x | +|✅| np.add(a, b) (float64) | float64 | 20.3 | 14.9 | 0.7x | + +### 🔻 Top 15 Worst (Optimization priorities) + +| | Operation | Type | NumPy | NumSharp | Ratio | +|:-:|-----------|:----:|------:|---------:|------:| +|🟡| a / scalar (int64) | int64 | 18.7 | 21.7 | 1.2x | +|🟡| a * scalar (float32) | float32 | 7.7 | 8.7 | 1.1x | +|🟡| a * 2 (literal) (float64) | float64 | 16.9 | 18.7 | 1.1x | +|✅| a * 2 (literal) (int32) | int32 | 9.0 | 8.9 | 1.0x | +|✅| scalar - a (int64) | int64 | 15.0 | 14.0 | 0.9x | +|✅| a * 2 (literal) (float32) | float32 | 7.7 | 6.9 | 0.9x | +|✅| a * b (element-wise) (int64) | int64 | 17.0 | 15.1 | 0.9x | +|✅| a + scalar (float32) | float32 | 7.8 | 6.9 | 0.9x | +|✅| a + b (element-wise) (float32) | float32 | 8.5 | 7.5 | 0.9x | +|✅| a * 2 (literal) (int64) | int64 | 15.0 | 13.2 | 0.9x | +|✅| a / b (element-wise) (float32) | float32 | 8.9 | 7.7 | 0.9x | +|✅| a - b (element-wise) (float32) | float32 | 8.6 | 7.5 | 0.9x | +|✅| a - scalar (int64) | int64 | 15.4 | 13.5 | 0.9x | +|✅| a * b (element-wise) (float32) | float32 | 8.6 | 7.4 | 0.9x | +|✅| a * a (square) (int64) | int64 | 15.8 | 13.6 | 0.9x | + +--- + +### Arithmetic + +| | Operation | Type | NumPy | NumSharp | Ratio | +|:-:|-----------|:----:|------:|---------:|------:| +|✅| a + b (element-wise) (int32) | int32 | 9.5 | 7.5 | 0.8x | +|✅| np.add(a, b) (int32) | int32 | 9.6 | 7.7 | 0.8x | +|✅| a + scalar (int32) | int32 | 8.7 | 6.9 | 0.8x | +|✅| a + 5 (literal) (int32) | int32 | 9.1 | 6.9 | 0.8x | +|✅| a - b (element-wise) (int32) | int32 | 11.1 | 7.4 | 0.7x | +|✅| a - scalar (int32) | int32 | 9.0 | 6.8 | 0.8x | +|✅| scalar - a (int32) | int32 | 11.4 | 7.2 | 0.6x | +|✅| a * b (element-wise) (int32) | int32 | 10.3 | 7.4 | 0.7x | +|✅| a * a (square) (int32) | int32 | 9.7 | 6.7 | 0.7x | +|✅| a * scalar (int32) | int32 | 8.7 | 7.3 | 0.8x | +|✅| a * 2 (literal) (int32) | int32 | 9.0 | 8.9 | 1.0x | +|✅| a / b (element-wise) (int32) | int32 | 21.7 | 14.1 | 0.7x | +|✅| a / scalar (int32) | int32 | 17.5 | 14.4 | 0.8x | +|✅| scalar / a (int32) | int32 | 18.1 | 13.7 | 0.8x | +|✅| a % b (element-wise) (int32) | int32 | 46.9 | 13.9 | 0.3x | +|✅| a % 7 (literal) (int32) | int32 | 49.7 | 13.8 | 0.3x | +|✅| a + b (element-wise) (int64) | int64 | 20.3 | 14.8 | 0.7x | +|✅| np.add(a, b) (int64) | int64 | 18.8 | 14.9 | 0.8x | +|✅| a + scalar (int64) | int64 | 16.1 | 13.7 | 0.8x | +|✅| a + 5 (literal) (int64) | int64 | 16.5 | 13.9 | 0.8x | +|✅| a - b (element-wise) (int64) | int64 | 17.5 | 14.8 | 0.8x | +|✅| a - scalar (int64) | int64 | 15.4 | 13.5 | 0.9x | +|✅| scalar - a (int64) | int64 | 15.0 | 14.0 | 0.9x | +|✅| a * b (element-wise) (int64) | int64 | 17.0 | 15.1 | 0.9x | +|✅| a * a (square) (int64) | int64 | 15.8 | 13.6 | 0.9x | +|✅| a * scalar (int64) | int64 | 15.9 | 13.0 | 0.8x | +|✅| a * 2 (literal) (int64) | int64 | 15.0 | 13.2 | 0.9x | +|✅| a / b (element-wise) (int64) | int64 | 24.0 | 19.2 | 0.8x | +|🟡| a / scalar (int64) | int64 | 18.7 | 21.7 | 1.2x | +|✅| scalar / a (int64) | int64 | 18.8 | 15.4 | 0.8x | +|✅| a % b (element-wise) (int64) | int64 | 48.1 | 24.2 | 0.5x | +|✅| a % 7 (literal) (int64) | int64 | 49.2 | 23.9 | 0.5x | +|✅| a + b (element-wise) (float32) | float32 | 8.5 | 7.5 | 0.9x | +|✅| np.add(a, b) (float32) | float32 | 8.9 | 7.6 | 0.8x | +|✅| a + scalar (float32) | float32 | 7.8 | 6.9 | 0.9x | +|✅| a + 5 (literal) (float32) | float32 | 8.2 | 6.9 | 0.8x | +|✅| a - b (element-wise) (float32) | float32 | 8.6 | 7.5 | 0.9x | +|✅| a - scalar (float32) | float32 | 8.1 | 6.8 | 0.8x | +|✅| scalar - a (float32) | float32 | 8.4 | 7.1 | 0.8x | +|✅| a * b (element-wise) (float32) | float32 | 8.6 | 7.4 | 0.9x | +|✅| a * a (square) (float32) | float32 | 8.4 | 6.5 | 0.8x | +|🟡| a * scalar (float32) | float32 | 7.7 | 8.7 | 1.1x | +|✅| a * 2 (literal) (float32) | float32 | 7.7 | 6.9 | 0.9x | +|✅| a / b (element-wise) (float32) | float32 | 8.9 | 7.7 | 0.9x | +|✅| a / scalar (float32) | float32 | 8.9 | 6.6 | 0.7x | +|✅| scalar / a (float32) | float32 | 8.3 | 6.8 | 0.8x | +|✅| a % b (element-wise) (float32) | float32 | 155.0 | 84.3 | 0.5x | +|✅| a % 7 (literal) (float32) | float32 | 174.6 | 96.7 | 0.6x | +|✅| a + b (element-wise) (float64) | float64 | 20.1 | 15.0 | 0.8x | +|✅| np.add(a, b) (float64) | float64 | 20.3 | 14.9 | 0.7x | +|✅| a + scalar (float64) | float64 | 17.9 | 13.7 | 0.8x | +|✅| a + 5 (literal) (float64) | float64 | 17.9 | 13.6 | 0.8x | +|✅| a - b (element-wise) (float64) | float64 | 18.3 | 15.2 | 0.8x | +|✅| a - scalar (float64) | float64 | 17.2 | 13.5 | 0.8x | +|✅| scalar - a (float64) | float64 | 16.7 | 14.1 | 0.8x | +|✅| a * b (element-wise) (float64) | float64 | 18.6 | 14.7 | 0.8x | +|✅| a * a (square) (float64) | float64 | 17.0 | 13.1 | 0.8x | +|✅| a * scalar (float64) | float64 | 17.3 | 13.8 | 0.8x | +|🟡| a * 2 (literal) (float64) | float64 | 16.9 | 18.7 | 1.1x | +|✅| a / b (element-wise) (float64) | float64 | 18.6 | 15.2 | 0.8x | +|✅| a / scalar (float64) | float64 | 17.0 | 13.7 | 0.8x | +|✅| scalar / a (float64) | float64 | 17.9 | 13.5 | 0.8x | +|✅| a % b (element-wise) (float64) | float64 | 188.5 | 45.7 | 0.2x | +|✅| a % 7 (literal) (float64) | float64 | 267.0 | 39.8 | 0.1x | diff --git a/benchmark/benchmark-report.md b/benchmark/benchmark-report.md new file mode 100644 index 000000000..ea2fa805e --- /dev/null +++ b/benchmark/benchmark-report.md @@ -0,0 +1,128 @@ +# NumSharp vs NumPy Performance + +**Baseline:** NumPy (N=10M elements) + +**Ratio** = NumSharp ÷ NumPy → Lower is better for NumSharp + +| | Status | Ratio | Meaning | +|:-:|--------|:-----:|---------| +|✅| Faster | <1.0 | NumSharp beats NumPy | +|🟡| Close | 1-2x | Acceptable parity | +|🟠| Slower | 2-5x | Optimization target | +|🔴| Slow | >5x | Priority fix | +|⚪| Pending | - | C# benchmark not run | + +--- + +**Summary:** 64 ops | ✅ 61 | 🟡 3 | 🟠 0 | 🔴 0 | ⚪ 0 + +### 🏆 Top 15 Best (NumSharp closest to NumPy) + +| | Operation | Type | NumPy | NumSharp | Ratio | +|:-:|-----------|:----:|------:|---------:|------:| +|✅| a % 7 (literal) (float64) | float64 | 267.0 | 39.8 | 0.1x | +|✅| a % b (element-wise) (float64) | float64 | 188.5 | 45.7 | 0.2x | +|✅| a % 7 (literal) (int32) | int32 | 49.7 | 13.8 | 0.3x | +|✅| a % b (element-wise) (int32) | int32 | 46.9 | 13.9 | 0.3x | +|✅| a % 7 (literal) (int64) | int64 | 49.2 | 23.9 | 0.5x | +|✅| a % b (element-wise) (int64) | int64 | 48.1 | 24.2 | 0.5x | +|✅| a % b (element-wise) (float32) | float32 | 155.0 | 84.3 | 0.5x | +|✅| a % 7 (literal) (float32) | float32 | 174.6 | 96.7 | 0.6x | +|✅| scalar - a (int32) | int32 | 11.4 | 7.2 | 0.6x | +|✅| a / b (element-wise) (int32) | int32 | 21.7 | 14.1 | 0.7x | +|✅| a - b (element-wise) (int32) | int32 | 11.1 | 7.4 | 0.7x | +|✅| a * a (square) (int32) | int32 | 9.7 | 6.7 | 0.7x | +|✅| a * b (element-wise) (int32) | int32 | 10.3 | 7.4 | 0.7x | +|✅| a + b (element-wise) (int64) | int64 | 20.3 | 14.8 | 0.7x | +|✅| np.add(a, b) (float64) | float64 | 20.3 | 14.9 | 0.7x | + +### 🔻 Top 15 Worst (Optimization priorities) + +| | Operation | Type | NumPy | NumSharp | Ratio | +|:-:|-----------|:----:|------:|---------:|------:| +|🟡| a / scalar (int64) | int64 | 18.7 | 21.7 | 1.2x | +|🟡| a * scalar (float32) | float32 | 7.7 | 8.7 | 1.1x | +|🟡| a * 2 (literal) (float64) | float64 | 16.9 | 18.7 | 1.1x | +|✅| a * 2 (literal) (int32) | int32 | 9.0 | 8.9 | 1.0x | +|✅| scalar - a (int64) | int64 | 15.0 | 14.0 | 0.9x | +|✅| a * 2 (literal) (float32) | float32 | 7.7 | 6.9 | 0.9x | +|✅| a * b (element-wise) (int64) | int64 | 17.0 | 15.1 | 0.9x | +|✅| a + scalar (float32) | float32 | 7.8 | 6.9 | 0.9x | +|✅| a + b (element-wise) (float32) | float32 | 8.5 | 7.5 | 0.9x | +|✅| a * 2 (literal) (int64) | int64 | 15.0 | 13.2 | 0.9x | +|✅| a / b (element-wise) (float32) | float32 | 8.9 | 7.7 | 0.9x | +|✅| a - b (element-wise) (float32) | float32 | 8.6 | 7.5 | 0.9x | +|✅| a - scalar (int64) | int64 | 15.4 | 13.5 | 0.9x | +|✅| a * b (element-wise) (float32) | float32 | 8.6 | 7.4 | 0.9x | +|✅| a * a (square) (int64) | int64 | 15.8 | 13.6 | 0.9x | + +--- + +### Arithmetic + +| | Operation | Type | NumPy | NumSharp | Ratio | +|:-:|-----------|:----:|------:|---------:|------:| +|✅| a + b (element-wise) (int32) | int32 | 9.5 | 7.5 | 0.8x | +|✅| np.add(a, b) (int32) | int32 | 9.6 | 7.7 | 0.8x | +|✅| a + scalar (int32) | int32 | 8.7 | 6.9 | 0.8x | +|✅| a + 5 (literal) (int32) | int32 | 9.1 | 6.9 | 0.8x | +|✅| a - b (element-wise) (int32) | int32 | 11.1 | 7.4 | 0.7x | +|✅| a - scalar (int32) | int32 | 9.0 | 6.8 | 0.8x | +|✅| scalar - a (int32) | int32 | 11.4 | 7.2 | 0.6x | +|✅| a * b (element-wise) (int32) | int32 | 10.3 | 7.4 | 0.7x | +|✅| a * a (square) (int32) | int32 | 9.7 | 6.7 | 0.7x | +|✅| a * scalar (int32) | int32 | 8.7 | 7.3 | 0.8x | +|✅| a * 2 (literal) (int32) | int32 | 9.0 | 8.9 | 1.0x | +|✅| a / b (element-wise) (int32) | int32 | 21.7 | 14.1 | 0.7x | +|✅| a / scalar (int32) | int32 | 17.5 | 14.4 | 0.8x | +|✅| scalar / a (int32) | int32 | 18.1 | 13.7 | 0.8x | +|✅| a % b (element-wise) (int32) | int32 | 46.9 | 13.9 | 0.3x | +|✅| a % 7 (literal) (int32) | int32 | 49.7 | 13.8 | 0.3x | +|✅| a + b (element-wise) (int64) | int64 | 20.3 | 14.8 | 0.7x | +|✅| np.add(a, b) (int64) | int64 | 18.8 | 14.9 | 0.8x | +|✅| a + scalar (int64) | int64 | 16.1 | 13.7 | 0.8x | +|✅| a + 5 (literal) (int64) | int64 | 16.5 | 13.9 | 0.8x | +|✅| a - b (element-wise) (int64) | int64 | 17.5 | 14.8 | 0.8x | +|✅| a - scalar (int64) | int64 | 15.4 | 13.5 | 0.9x | +|✅| scalar - a (int64) | int64 | 15.0 | 14.0 | 0.9x | +|✅| a * b (element-wise) (int64) | int64 | 17.0 | 15.1 | 0.9x | +|✅| a * a (square) (int64) | int64 | 15.8 | 13.6 | 0.9x | +|✅| a * scalar (int64) | int64 | 15.9 | 13.0 | 0.8x | +|✅| a * 2 (literal) (int64) | int64 | 15.0 | 13.2 | 0.9x | +|✅| a / b (element-wise) (int64) | int64 | 24.0 | 19.2 | 0.8x | +|🟡| a / scalar (int64) | int64 | 18.7 | 21.7 | 1.2x | +|✅| scalar / a (int64) | int64 | 18.8 | 15.4 | 0.8x | +|✅| a % b (element-wise) (int64) | int64 | 48.1 | 24.2 | 0.5x | +|✅| a % 7 (literal) (int64) | int64 | 49.2 | 23.9 | 0.5x | +|✅| a + b (element-wise) (float32) | float32 | 8.5 | 7.5 | 0.9x | +|✅| np.add(a, b) (float32) | float32 | 8.9 | 7.6 | 0.8x | +|✅| a + scalar (float32) | float32 | 7.8 | 6.9 | 0.9x | +|✅| a + 5 (literal) (float32) | float32 | 8.2 | 6.9 | 0.8x | +|✅| a - b (element-wise) (float32) | float32 | 8.6 | 7.5 | 0.9x | +|✅| a - scalar (float32) | float32 | 8.1 | 6.8 | 0.8x | +|✅| scalar - a (float32) | float32 | 8.4 | 7.1 | 0.8x | +|✅| a * b (element-wise) (float32) | float32 | 8.6 | 7.4 | 0.9x | +|✅| a * a (square) (float32) | float32 | 8.4 | 6.5 | 0.8x | +|🟡| a * scalar (float32) | float32 | 7.7 | 8.7 | 1.1x | +|✅| a * 2 (literal) (float32) | float32 | 7.7 | 6.9 | 0.9x | +|✅| a / b (element-wise) (float32) | float32 | 8.9 | 7.7 | 0.9x | +|✅| a / scalar (float32) | float32 | 8.9 | 6.6 | 0.7x | +|✅| scalar / a (float32) | float32 | 8.3 | 6.8 | 0.8x | +|✅| a % b (element-wise) (float32) | float32 | 155.0 | 84.3 | 0.5x | +|✅| a % 7 (literal) (float32) | float32 | 174.6 | 96.7 | 0.6x | +|✅| a + b (element-wise) (float64) | float64 | 20.1 | 15.0 | 0.8x | +|✅| np.add(a, b) (float64) | float64 | 20.3 | 14.9 | 0.7x | +|✅| a + scalar (float64) | float64 | 17.9 | 13.7 | 0.8x | +|✅| a + 5 (literal) (float64) | float64 | 17.9 | 13.6 | 0.8x | +|✅| a - b (element-wise) (float64) | float64 | 18.3 | 15.2 | 0.8x | +|✅| a - scalar (float64) | float64 | 17.2 | 13.5 | 0.8x | +|✅| scalar - a (float64) | float64 | 16.7 | 14.1 | 0.8x | +|✅| a * b (element-wise) (float64) | float64 | 18.6 | 14.7 | 0.8x | +|✅| a * a (square) (float64) | float64 | 17.0 | 13.1 | 0.8x | +|✅| a * scalar (float64) | float64 | 17.3 | 13.8 | 0.8x | +|🟡| a * 2 (literal) (float64) | float64 | 16.9 | 18.7 | 1.1x | +|✅| a / b (element-wise) (float64) | float64 | 18.6 | 15.2 | 0.8x | +|✅| a / scalar (float64) | float64 | 17.0 | 13.7 | 0.8x | +|✅| scalar / a (float64) | float64 | 17.9 | 13.5 | 0.8x | +|✅| a % b (element-wise) (float64) | float64 | 188.5 | 45.7 | 0.2x | +|✅| a % 7 (literal) (float64) | float64 | 267.0 | 39.8 | 0.1x | diff --git a/benchmark/run-benchmarks.ps1 b/benchmark/run-benchmarks.ps1 new file mode 100644 index 000000000..8d9609ebd --- /dev/null +++ b/benchmark/run-benchmarks.ps1 @@ -0,0 +1,578 @@ +<# +.SYNOPSIS + Runs NumSharp and NumPy benchmarks and generates a consolidated Markdown report. + +.DESCRIPTION + This script executes both C# (BenchmarkDotNet) and Python (NumPy) benchmarks, + collects the results, calculates performance ratios, and generates a comprehensive + Markdown report for comparison. + + Results are archived in timestamped folders under results/ for historical tracking. + +.PARAMETER Quick + Run quick benchmarks (fewer iterations, faster but less accurate) + +.PARAMETER Suite + Specific suite to run. Standard suites: 'all', 'arithmetic', 'unary', + 'reduction', 'broadcast', 'creation', 'manipulation', 'slicing' + Experimental suites (use -Experimental): 'dispatch', 'fusion' + +.PARAMETER Experimental + Run experimental/research benchmarks (dispatch, fusion) instead of NumPy comparison. + These are internal research benchmarks that don't merge with NumPy results. + +.PARAMETER OutputPath + Path for the output report (default: benchmark-report.md) + +.PARAMETER SkipCSharp + Skip C# benchmarks + +.PARAMETER SkipPython + Skip Python benchmarks + +.PARAMETER Type + Specific dtype to benchmark (e.g., int32, float64) + +.PARAMETER Size + Array size: small (1K), medium (100K), large (10M) + +.EXAMPLE + .\run-benchmarks.ps1 + .\run-benchmarks.ps1 -Quick + .\run-benchmarks.ps1 -Suite arithmetic -Type int32 + .\run-benchmarks.ps1 -Experimental -Suite dispatch -SkipPython +#> + +param( + [switch]$Quick, + [string]$Suite = 'all', + [switch]$Experimental, + [string]$OutputPath = 'benchmark-report.md', + [switch]$SkipCSharp, + [switch]$SkipPython, + [string]$Type = '', + [ValidateSet('', 'small', 'medium', 'large')] + [string]$Size = '' +) + +$ErrorActionPreference = 'Stop' +$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path +$Timestamp = Get-Date -Format "yyyyMMdd-HHmmss" +$ResultsDir = Join-Path $ScriptDir "results\$Timestamp" + +# Standard suites (for NumPy comparison) +$StandardSuites = @('all', 'arithmetic', 'unary', 'reduction', 'broadcast', 'creation', 'manipulation', 'slicing') +# Experimental suites (research benchmarks) +$ExperimentalSuites = @('dispatch', 'fusion') + +# Validate suite selection +if ($Experimental) { + if ($Suite -notin @('all') + $ExperimentalSuites) { + Write-Host "`n[ERROR] Invalid experimental suite: '$Suite'" -ForegroundColor Red + Write-Host "Valid experimental suites: $($ExperimentalSuites -join ', ')" -ForegroundColor Yellow + Write-Host "Use -Experimental -Suite dispatch|fusion" -ForegroundColor Yellow + exit 1 + } + if (-not $SkipPython) { + Write-Host "`n[WARNING] Experimental benchmarks don't merge with NumPy results. Consider using -SkipPython." -ForegroundColor Yellow + } +} else { + if ($Suite -in $ExperimentalSuites) { + Write-Host "`n[ERROR] Suite '$Suite' is an experimental suite." -ForegroundColor Red + Write-Host "Valid standard suites: $($StandardSuites -join ', ')" -ForegroundColor Yellow + Write-Host "Use -Experimental flag for experimental benchmarks: .\run-benchmarks.ps1 -Experimental -Suite $Suite" -ForegroundColor Cyan + exit 1 + } + if ($Suite -notin $StandardSuites) { + Write-Host "`n[ERROR] Invalid suite: '$Suite'" -ForegroundColor Red + Write-Host "Valid standard suites: $($StandardSuites -join ', ')" -ForegroundColor Yellow + exit 1 + } +} + +# Create results directory +New-Item -ItemType Directory -Path $ResultsDir -Force | Out-Null +$LogPath = Join-Path $ResultsDir "benchmark.log" + +# Logging function +function Write-Log { + param( + [string]$Message, + [string]$Prefix = "", + [string]$ForegroundColor = "White" + ) + $timestamp = Get-Date -Format "HH:mm:ss" + $logLine = "[$timestamp]" + if ($Prefix) { $logLine += " [$Prefix]" } + $logLine += " $Message" + + # Write to console + Write-Host $logLine -ForegroundColor $ForegroundColor + + # Append to log file + $logLine | Out-File -FilePath $LogPath -Append -Encoding UTF8 +} + +# Colors for console output +function Write-Status { param($msg) Write-Log $msg -Prefix "INFO" -ForegroundColor Cyan } +function Write-Success { param($msg) Write-Log $msg -Prefix "OK" -ForegroundColor Green } +function Write-Warning { param($msg) Write-Log $msg -Prefix "WARN" -ForegroundColor Yellow } +function Write-Error { param($msg) Write-Log $msg -Prefix "ERROR" -ForegroundColor Red } + +# Performance status icons +function Get-StatusIcon { + param([double]$Ratio) + if ($Ratio -le 1.0) { return "`u{2705}" } # Green check - faster + if ($Ratio -le 2.0) { return "`u{1F7E1}" } # Yellow circle - close + if ($Ratio -le 5.0) { return "`u{1F7E0}" } # Orange circle - slower + return "`u{1F534}" # Red circle - much slower +} + +function Get-StatusText { + param([double]$Ratio) + if ($Ratio -le 1.0) { return "faster" } + if ($Ratio -le 2.0) { return "~2x" } + if ($Ratio -le 5.0) { return "$([math]::Round($Ratio, 1))x slower" } + return "$([math]::Round($Ratio, 1))x slower" +} + +Write-Host "" +Write-Host "`u{2554}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2557}" -ForegroundColor Blue +if ($Experimental) { + Write-Host "`u{2551} NumSharp Experimental Benchmark Suite `u{2551}" -ForegroundColor Magenta +} else { + Write-Host "`u{2551} NumSharp vs NumPy Comprehensive Benchmark Suite `u{2551}" -ForegroundColor Blue +} +Write-Host "`u{255A}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{255D}" -ForegroundColor Blue +Write-Host "" + +Write-Status "Results will be saved to: $ResultsDir" +Write-Log "Benchmark started: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" +Write-Log "Mode: $(if ($Experimental) { 'Experimental' } else { 'Standard' }), Suite: $Suite, Quick: $Quick" + +# Initialize report +$reportTimestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" +$report = @" +# NumSharp Performance Benchmark Report + +**Generated:** $reportTimestamp +**Mode:** $(if ($Quick) { 'Quick (reduced iterations)' } else { 'Full' }) +**Suite:** $Suite $(if ($Experimental) { '(Experimental)' } else { '' }) + +--- + +## Environment + +| Component | Version | +|-----------|---------| +"@ + +# Get environment info +$dotnetVersion = & dotnet --version 2>$null +$pythonVersion = & python --version 2>$null +$numpyVersion = & python -c "import numpy; print(numpy.__version__)" 2>$null + +$report += "`n| .NET SDK | $dotnetVersion |" +$report += "`n| Python | $($pythonVersion -replace 'Python ', '') |" +$report += "`n| NumPy | $numpyVersion |" +$report += "`n| OS | $([System.Environment]::OSVersion.VersionString) |" + +try { + $cpuName = (Get-CimInstance Win32_Processor).Name + $report += "`n| CPU | $cpuName |" +} catch { + $report += "`n| CPU | Unknown |" +} + +$report += "`n" + +# ============================================================================= +# Run Python Benchmarks +# ============================================================================= + +$pythonResults = @() +$numpyJsonPath = Join-Path $ResultsDir "numpy-results.json" + +if (-not $SkipPython) { + Write-Status "Running Python/NumPy benchmarks..." + + $pythonScript = Join-Path $ScriptDir "NumSharp.Benchmark.Python\numpy_benchmark.py" + $pythonArgs = @($pythonScript, "--output", $numpyJsonPath) + if ($Quick) { $pythonArgs += "--quick" } + if ($Suite -ne 'all') { $pythonArgs += "--suite"; $pythonArgs += $Suite } + if ($Type) { $pythonArgs += "--type"; $pythonArgs += $Type } + if ($Size) { $pythonArgs += "--size"; $pythonArgs += $Size } + + $pythonCmd = "python " + ($pythonArgs -join " ") + Write-Log "Command: $pythonCmd" + + try { + & python @pythonArgs 2>&1 | ForEach-Object { + Write-Log $_ -Prefix "Python" + } + + if (Test-Path $numpyJsonPath) { + $pythonResults = Get-Content $numpyJsonPath | ConvertFrom-Json + Write-Success "Python benchmarks complete ($($pythonResults.Count) results)" + } + } catch { + Write-Warning "Python benchmarks failed: $_" + } +} else { + Write-Status "Skipping Python benchmarks (-SkipPython)" + Write-Log "Skipping Python benchmarks" +} + +# ============================================================================= +# Run C# Benchmarks +# ============================================================================= + +$csharpResults = @{} +$csharpJsonDir = $null +$numsharpJsonPath = Join-Path $ResultsDir "numsharp-results.json" + +if (-not $SkipCSharp) { + Write-Status "Building C# benchmarks..." + + $csharpDir = Join-Path $ScriptDir "NumSharp.Benchmark.GraphEngine" + Push-Location $csharpDir + + try { + & dotnet build -c Release -v q --nologo 2>$null | Out-Null + Write-Success "Build complete" + + Write-Status "Running C# benchmarks (this may take a few minutes)..." + + $jobType = if ($Quick) { "Short" } else { "Medium" } + + # Build filter based on suite and experimental flag + if ($Experimental) { + # Experimental benchmarks (dispatch, fusion) are research benchmarks + # that don't correspond to NumPy operations + $filter = switch ($Suite) { + 'dispatch' { "*DispatchBenchmarks*" } + 'fusion' { "*FusionBenchmarks*" } + default { "*DispatchBenchmarks*,*FusionBenchmarks*" } + } + } else { + $filter = switch ($Suite) { + 'arithmetic' { "*Arithmetic*" } + 'unary' { "*Unary*,*Math*,*ExpLog*,*Trig*,*Power*" } + 'reduction' { "*Reduction*,*Sum*,*Mean*,*VarStd*,*MinMax*,*Prod*" } + 'broadcast' { "*Broadcast*" } + 'creation' { "*Creation*" } + 'manipulation' { "*Manipulation*,*Reshape*,*Stack*,*Dims*" } + 'slicing' { "*Slice*" } + default { "*" } + } + } + + # Map -Type parameter to C# DType filter + # NumPy dtype names -> C# NPTypeCode names + # BDN filter format: namespace.class.method(N: 10000000, DType: Int32) + $dtypeFilter = "" + if ($Type) { + $dtypeMap = @{ + 'int32' = 'Int32' + 'int64' = 'Int64' + 'float32' = 'Single' + 'float64' = 'Double' + 'uint8' = 'Byte' + 'int16' = 'Int16' + 'uint16' = 'UInt16' + 'uint32' = 'UInt32' + 'uint64' = 'UInt64' + 'bool' = 'Boolean' + } + $csharpType = $dtypeMap[$Type.ToLower()] + if ($csharpType) { + $dtypeFilter = "*DType: $csharpType*" + Write-Log "Filtering C# benchmarks to DType=$csharpType" + } else { + Write-Warning "Unknown type '$Type' - running all types" + } + } + + # In Quick mode, only run N=10M (matches NumPy comparison) + # This dramatically reduces benchmark count + $sizeFilter = "" + if ($Quick) { + $sizeFilter = "*N: 10000000*" + Write-Log "Quick mode: filtering to N=10000000 only" + } + + # Combine filters: suite AND size AND dtype + # BDN parameter order is (N: value, DType: type) so size filter must come before dtype + # BDN uses glob patterns on full name: namespace.class.method(params) + # Multiple wildcards in same pattern act as AND + $filterParts = @() + foreach ($suitePart in $filter.Split(',')) { + $combined = $suitePart.Trim() + if ($sizeFilter) { $combined += $sizeFilter } # N: comes first in BDN output + if ($dtypeFilter) { $combined += $dtypeFilter } # DType: comes second + $filterParts += $combined + } + $filter = $filterParts -join "," + + $csharpCmd = "dotnet run -c Release --no-build -f net10.0 -- --job $jobType --filter $filter --exporters json" + Write-Log "Command: $csharpCmd" + + # Run and capture output + $output = & dotnet run -c Release --no-build -f net10.0 -- --job $jobType --filter $filter --exporters json 2>&1 + + # Log all output + foreach ($line in $output) { + Write-Log $line -Prefix "C#" + } + + # Parse the summary table from output + $inTable = $false + $tableLines = @() + foreach ($line in $output) { + if ($line -match '^\| Method') { $inTable = $true } + if ($inTable -and $line -match '^\|') { $tableLines += $line } + if ($inTable -and $line -notmatch '^\|' -and $line -match '\S') { $inTable = $false } + } + + if ($tableLines.Count -gt 0) { + $csharpResults['table'] = $tableLines -join "`n" + Write-Success "C# benchmarks complete" + } + + # Find JSON results directory and copy artifacts + $artifactsDir = Join-Path $csharpDir "BenchmarkDotNet.Artifacts\results" + if (Test-Path $artifactsDir) { + $csharpJsonDir = $artifactsDir + + # Copy BDN artifacts to results folder + $bdnFiles = Get-ChildItem $artifactsDir -Filter "*.json" -ErrorAction SilentlyContinue + foreach ($file in $bdnFiles) { + Copy-Item $file.FullName -Destination $ResultsDir -Force + Write-Log "Copied BDN artifact: $($file.Name)" + } + $mdFiles = Get-ChildItem $artifactsDir -Filter "*.md" -ErrorAction SilentlyContinue + foreach ($file in $mdFiles) { + Copy-Item $file.FullName -Destination $ResultsDir -Force + Write-Log "Copied BDN artifact: $($file.Name)" + } + + # Create consolidated numsharp-results.json from BDN results + # (merge-results.py will read from BDN artifacts dir) + } + + } catch { + Write-Warning "C# benchmarks failed: $_" + } finally { + Pop-Location + } +} else { + Write-Status "Skipping C# benchmarks (-SkipCSharp)" + Write-Log "Skipping C# benchmarks" +} + +# ============================================================================= +# Generate Executive Summary +# ============================================================================= + +Write-Status "Generating report..." + +$report += @" + +--- + +## Executive Summary + +"@ + +if ($pythonResults.Count -gt 0) { + # Calculate statistics + $totalOps = $pythonResults.Count + $faster = 0 + $within2x = 0 + $slower = 0 + $muchSlower = 0 + + # Group by suite for summary + $suiteStats = @{} + $pythonResults | Group-Object -Property suite | ForEach-Object { + $suiteStats[$_.Name] = @{ + Count = $_.Count + AvgMs = ($_.Group | Measure-Object -Property mean_ms -Average).Average + } + } + + $report += @" +| Metric | Value | +|--------|-------| +| Operations Tested | $totalOps | +| Suites | $($suiteStats.Keys -join ', ') | +| Array Size (N) | $(if ($pythonResults[0].n) { "{0:N0}" -f $pythonResults[0].n } else { "Varies" }) | + +"@ +} + +# ============================================================================= +# NumPy Baseline Performance +# ============================================================================= + +if ($pythonResults.Count -gt 0) { + $report += @" + +--- + +## NumPy Baseline Performance + +> These results represent NumPy's performance on the same operations. +> NumPy is the reference implementation NumSharp aims to match. + +"@ + + # Group results by suite + $suiteGroups = $pythonResults | Group-Object -Property suite + + foreach ($suiteGroup in $suiteGroups) { + $suiteName = if ($suiteGroup.Name) { $suiteGroup.Name } else { "General" } + $report += "`n### $suiteName`n`n" + $report += "| Operation | Type | Mean (ms) | StdDev |`n" + $report += "|-----------|------|----------:|-------:|`n" + + foreach ($r in $suiteGroup.Group) { + $report += "| $($r.name) | $($r.dtype) | $([math]::Round($r.mean_ms, 3)) | $([math]::Round($r.stddev_ms, 3)) |`n" + } + } +} + +# ============================================================================= +# C# Results Section +# ============================================================================= + +if ($csharpResults['table']) { + $report += @" + +--- + +## NumSharp (C#) Benchmark Results + +> BenchmarkDotNet results for NumSharp operations. + +### Summary Table + +$($csharpResults['table']) + +"@ +} + +$report += @" + +--- + +## Quick Reference + +Ratio = NumSharp / NumPy | `u{2705} ≤1x | `u{1F7E1} ≤2x | `u{1F7E0} ≤5x | `u{1F534} >5x + +**See benchmark-report.md for the full comparison matrix.** + +--- + +*Generated by run-benchmarks.ps1* +"@ + +# Write report to results folder +$reportPath = Join-Path $ResultsDir "benchmark-report.md" +$report | Out-File -FilePath $reportPath -Encoding UTF8 +Write-Log "Report written to: $reportPath" + +# ============================================================================= +# Generate Unified Comparison (if both results exist and not Experimental) +# ============================================================================= + +$mergeScript = Join-Path $ScriptDir "scripts\merge-results.py" +$mergedJsonPath = Join-Path $ResultsDir "benchmark-report.json" +$mergedCsvPath = Join-Path $ResultsDir "benchmark-report.csv" + +if (-not $Experimental -and (Test-Path $numpyJsonPath) -and (Test-Path $mergeScript) -and $csharpJsonDir) { + Write-Status "Generating unified comparison..." + Write-Log "Running merge script..." + + $outputBase = Join-Path $ResultsDir "benchmark-report" + $mergeCmd = "python $mergeScript --numpy $numpyJsonPath --csharp $csharpJsonDir --output $outputBase" + Write-Log "Command: $mergeCmd" + + try { + & python $mergeScript --numpy $numpyJsonPath --csharp $csharpJsonDir --output $outputBase 2>&1 | ForEach-Object { + Write-Log $_ -Prefix "Merge" + } + Write-Success "Unified results generated" + } catch { + Write-Warning "Failed to generate unified results: $_" + } +} elseif ($Experimental) { + Write-Log "Skipping merge (Experimental mode - no NumPy comparison)" +} elseif (-not (Test-Path $numpyJsonPath)) { + Write-Log "Skipping merge (no numpy-results.json)" +} + +# ============================================================================= +# Copy results to benchmark/ root +# ============================================================================= + +Write-Status "Copying results to benchmark root..." + +$filesToCopy = @( + "benchmark.log", + "benchmark-report.md", + "benchmark-report.json", + "benchmark-report.csv", + "numpy-results.json", + "numsharp-results.json" +) + +foreach ($fileName in $filesToCopy) { + $sourcePath = Join-Path $ResultsDir $fileName + if (Test-Path $sourcePath) { + $destPath = Join-Path $ScriptDir $fileName + Copy-Item $sourcePath -Destination $destPath -Force + Write-Log "Copied to root: $fileName" + } +} + +# ============================================================================= +# Copy report to README.md (only if README.md already exists) +# ============================================================================= + +$readmePath = Join-Path $ScriptDir "README.md" +$mergedReportPath = Join-Path $ResultsDir "benchmark-report.md" + +# Prefer merged report if available +if (Test-Path (Join-Path $ResultsDir "benchmark-report.md")) { + $reportToCopy = Join-Path $ResultsDir "benchmark-report.md" +} else { + $reportToCopy = $reportPath +} + +if (Test-Path $readmePath) { + Copy-Item -Path $reportToCopy -Destination $readmePath -Force + Write-Success "README.md updated with benchmark results" +} else { + Write-Warning "README.md not found - skipping auto-update (create it manually to enable)" +} + +Write-Host "" + +# Display summary +Write-Host "`u{2554}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2557}" -ForegroundColor Green +Write-Host "`u{2551} Benchmark Complete! `u{2551}" -ForegroundColor Green +Write-Host "`u{255A}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{2550}`u{255D}" -ForegroundColor Green +Write-Host "" +Write-Host " Results: " -NoNewline; Write-Host $ResultsDir -ForegroundColor Yellow +Write-Host " Report: " -NoNewline; Write-Host (Join-Path $ScriptDir "benchmark-report.md") -ForegroundColor Yellow +Write-Host " README: " -NoNewline; Write-Host $readmePath -ForegroundColor Yellow +Write-Host " Log: " -NoNewline; Write-Host $LogPath -ForegroundColor Yellow +if (Test-Path $numpyJsonPath) { + Write-Host " NumPy: " -NoNewline; Write-Host $numpyJsonPath -ForegroundColor Yellow +} +if (Test-Path $mergedJsonPath) { + Write-Host " Merged: " -NoNewline; Write-Host $mergedJsonPath -ForegroundColor Yellow +} +Write-Host " View: " -NoNewline; Write-Host "code $ResultsDir" -ForegroundColor Cyan +Write-Host "" diff --git a/benchmark/scripts/merge-results.py b/benchmark/scripts/merge-results.py new file mode 100644 index 000000000..41ff0db52 --- /dev/null +++ b/benchmark/scripts/merge-results.py @@ -0,0 +1,462 @@ +#!/usr/bin/env python3 +""" +Merge NumPy and NumSharp benchmark results into a unified comparison table. + +Outputs: + - benchmark-report.json: Machine-readable merged data with ratios + - benchmark-report.md: Markdown table for documentation + - benchmark-report.csv: CSV for spreadsheet analysis + +Usage: + python merge-results.py + python merge-results.py --numpy ../benchmark-report.json --csharp ../NumSharp.Benchmark.GraphEngine/BenchmarkDotNet.Artifacts/results/ + python merge-results.py --format csv + +Note: This script is typically invoked from run-benchmarks.ps1 with explicit paths. +""" + +import json +import os +import sys +import argparse +import glob +from pathlib import Path +from typing import Dict, List, Any, Optional +from dataclasses import dataclass, asdict + +@dataclass +class UnifiedResult: + """A single benchmark comparison result.""" + operation: str + suite: str + category: str + dtype: str + n: int + numpy_ms: float + numsharp_ms: Optional[float] + ratio: Optional[float] # NumSharp / NumPy + status: str # "faster", "close", "slower", "much_slower", "no_data" + + def to_dict(self) -> dict: + return asdict(self) + + +def load_numpy_results(path: str) -> List[dict]: + """Load NumPy benchmark results from JSON.""" + if not os.path.exists(path): + print(f"Warning: NumPy results not found at {path}") + return [] + with open(path, 'r') as f: + return json.load(f) + + +def load_csharp_results(artifacts_dir: str) -> List[dict]: + """Load BenchmarkDotNet results from artifacts directory.""" + results = [] + if not os.path.exists(artifacts_dir): + print(f"Warning: C# artifacts not found at {artifacts_dir}") + return [] + + # Find all *-report*.json files (including -full-compressed.json) + for pattern in ["*-report.json", "*-report-full-compressed.json"]: + full_pattern = os.path.join(artifacts_dir, pattern) + for json_file in glob.glob(full_pattern): + try: + with open(json_file, 'r') as f: + data = json.load(f) + if 'Benchmarks' in data: + for bench in data['Benchmarks']: + result = parse_bdn_benchmark(bench) + if result: + results.append(result) + except Exception as e: + print(f"Warning: Failed to parse {json_file}: {e}") + + return results + + +def parse_bdn_benchmark(bench: dict) -> Optional[dict]: + """Parse a single BenchmarkDotNet benchmark result.""" + try: + method = bench.get('Method', '') + method_title = bench.get('MethodTitle', method) + params = bench.get('Parameters', '') + stats = bench.get('Statistics', {}) + + # Extract N and DType from parameters (format: "N=1000&DType=UInt16" or "N=1000, DType=UInt16") + n = 10_000_000 + dtype = 'float64' + + if params: + # Handle both "&" and ", " separators + parts = params.replace('&', ', ').split(', ') + for part in parts: + part = part.strip() + if part.startswith('N='): + n = int(part[2:]) + elif part.startswith('DType='): + dtype = part[6:].lower() + + # Only use Large array size (10M) for comparison + if n != 10_000_000: + return None + + # Convert nanoseconds to milliseconds + mean_ns = stats.get('Mean', 0) + mean_ms = mean_ns / 1_000_000 + + stddev_ns = stats.get('StandardDeviation', stats.get('StdDev', 0)) + stddev_ms = stddev_ns / 1_000_000 + + # Map dtype to numpy names + dtype_map = { + 'int32': 'int32', 'int64': 'int64', 'single': 'float32', 'double': 'float64', + 'byte': 'uint8', 'uint16': 'uint16', 'uint32': 'uint32', 'uint64': 'uint64', + 'int16': 'int16', 'boolean': 'bool', 'decimal': 'decimal' + } + dtype = dtype_map.get(dtype.lower(), dtype.lower()) + + # Clean up method title + operation = method_title.strip("'") + + return { + 'name': operation, + 'method': method, + 'dtype': dtype, + 'n': n, + 'mean_ms': mean_ms, + 'stddev_ms': stddev_ms + } + except Exception as e: + print(f"Warning: Failed to parse benchmark: {e}") + return None + + +def method_to_operation(method: str) -> str: + """Convert C# method name to operation name matching NumPy results.""" + # Map common method names to NumPy-style names + mappings = { + 'Add_Elementwise': 'a + b', + 'Add_Scalar': 'a + scalar', + 'Subtract_Elementwise': 'a - b', + 'Multiply_Elementwise': 'a * b', + 'Multiply_Same': 'a * a', + 'Divide_Elementwise': 'a / b', + 'Sum_Full': 'np.sum', + 'Sum_Axis0': 'np.sum axis=0', + 'Sum_Axis1': 'np.sum axis=1', + 'Mean_Full': 'np.mean', + 'Var_Full': 'np.var', + 'Std_Full': 'np.std', + 'Min_Full': 'np.amin', + 'Max_Full': 'np.amax', + 'ArgMin_Full': 'np.argmin', + 'ArgMax_Full': 'np.argmax', + 'Sqrt': 'np.sqrt', + 'Abs': 'np.abs', + 'Sign': 'np.sign', + 'Floor': 'np.floor', + 'Ceil': 'np.ceil', + 'Round': 'np.round', + 'Exp': 'np.exp', + 'Log': 'np.log', + 'Log10': 'np.log10', + 'Sin': 'np.sin', + 'Cos': 'np.cos', + 'Zeros': 'np.zeros', + 'Ones': 'np.ones', + 'Full': 'np.full', + 'Empty': 'np.empty', + 'Copy': 'np.copy', + 'Zeros_Like': 'np.zeros_like', + } + + return mappings.get(method, method) + + +def get_status(ratio: Optional[float]) -> str: + """Get status string from ratio.""" + if ratio is None: + return "no_data" + if ratio <= 1.0: + return "faster" + if ratio <= 2.0: + return "close" + if ratio <= 5.0: + return "slower" + return "much_slower" + + +def get_status_icon(status: str) -> str: + """Get status icon for markdown.""" + icons = { + "faster": "✅", + "close": "🟡", + "slower": "🟠", + "much_slower": "🔴", + "no_data": "⚪" + } + return icons.get(status, "⚪") + + +def normalize_op_name(name: str) -> str: + """Normalize operation name for matching. + + Maps C# BDN method titles to Python benchmark names. + Both sides include dtype suffix like " (int32)" which is stripped. + """ + import re + # Remove dtype suffix like " (int32)" or " (float64)" + # Only remove parentheses that contain dtype names, not descriptive text like "(element-wise)" + dtype_pattern = r'\s*\((int32|int64|float32|float64|uint8|int16|uint16|uint32|uint64|bool|decimal)\)\s*$' + name = re.sub(dtype_pattern, '', name) + # Remove quotes + name = name.strip("'\"") + # Normalize whitespace + name = re.sub(r'\s+', ' ', name) + # Lowercase for comparison + name = name.lower() + + # Map C# BDN method titles to Python benchmark names + # C# uses titles like "a + b (element-wise)" while Python uses same format + mappings = { + # Arithmetic - Add + 'a + b (element-wise)': 'a + b (element-wise)', + 'np.add(a, b)': 'np.add(a, b)', + 'a + scalar': 'a + scalar', + 'a + 5 (literal)': 'a + 5 (literal)', + + # Arithmetic - Subtract + 'a - b (element-wise)': 'a - b (element-wise)', + 'a - scalar': 'a - scalar', + 'scalar - a': 'scalar - a', + + # Arithmetic - Multiply + 'a * b (element-wise)': 'a * b (element-wise)', + 'a * a (square)': 'a * a (square)', + 'a * scalar': 'a * scalar', + 'a * 2 (literal)': 'a * 2 (literal)', + + # Arithmetic - Divide + 'a / b (element-wise)': 'a / b (element-wise)', + 'a / scalar': 'a / scalar', + 'scalar / a': 'scalar / a', + + # Arithmetic - Modulo + 'a % b (element-wise)': 'a % b (element-wise)', + 'a % 7 (literal)': 'a % 7 (literal)', + + # Reduction + 'np.sum(a) [full]': 'np.sum', + 'np.sum(a, axis=0)': 'np.sum axis=0', + 'np.sum(a, axis=1)': 'np.sum axis=1', + } + return mappings.get(name, name) + + +def merge_results(numpy_results: List[dict], csharp_results: List[dict]) -> List[UnifiedResult]: + """Merge NumPy and C# results into unified comparison.""" + unified = [] + + # Index C# results by (normalized_operation, dtype) + csharp_index: Dict[tuple, dict] = {} + for r in csharp_results: + norm_name = normalize_op_name(r['name']) + key = (norm_name, r['dtype'].lower()) + csharp_index[key] = r + # Debug + # print(f"C# key: {key}") + + # Process each NumPy result + for np_result in numpy_results: + name = np_result.get('name', '') + dtype = np_result.get('dtype', 'float64') + n = np_result.get('n', 10_000_000) + suite = np_result.get('suite', 'General') + category = np_result.get('category', '') + numpy_ms = np_result.get('mean_ms', 0) + + # Look for matching C# result + norm_name = normalize_op_name(name) + key = (norm_name, dtype.lower()) + cs_result = csharp_index.get(key) + + numsharp_ms = cs_result['mean_ms'] if cs_result else None + ratio = numsharp_ms / numpy_ms if (numsharp_ms and numpy_ms > 0) else None + status = get_status(ratio) + + unified.append(UnifiedResult( + operation=name, + suite=suite, + category=category, + dtype=dtype, + n=n, + numpy_ms=round(numpy_ms, 3), + numsharp_ms=round(numsharp_ms, 3) if numsharp_ms else None, + ratio=round(ratio, 2) if ratio else None, + status=status + )) + + return unified + + +def generate_json(results: List[UnifiedResult], output_path: str): + """Generate JSON output.""" + data = [r.to_dict() for r in results] + with open(output_path, 'w') as f: + json.dump(data, f, indent=2) + print(f"JSON written to: {output_path}") + + +def generate_csv(results: List[UnifiedResult], output_path: str): + """Generate CSV output.""" + import csv + with open(output_path, 'w', newline='') as f: + writer = csv.writer(f) + writer.writerow(['Operation', 'Suite', 'Category', 'DType', 'N', + 'NumPy (ms)', 'NumSharp (ms)', 'Ratio', 'Status']) + for r in results: + writer.writerow([ + r.operation, r.suite, r.category, r.dtype, r.n, + r.numpy_ms, r.numsharp_ms or '', r.ratio or '', r.status + ]) + print(f"CSV written to: {output_path}") + + +def generate_markdown(results: List[UnifiedResult], output_path: str): + """Generate concise Markdown comparison matrix.""" + + # Count stats + faster = sum(1 for r in results if r.status == 'faster') + close = sum(1 for r in results if r.status == 'close') + slower = sum(1 for r in results if r.status == 'slower') + much_slower = sum(1 for r in results if r.status == 'much_slower') + no_data = sum(1 for r in results if r.status == 'no_data') + total = len(results) + + lines = [ + "# NumSharp vs NumPy Performance", + "", + "**Baseline:** NumPy (N=10M elements)", + "", + "**Ratio** = NumSharp ÷ NumPy → Lower is better for NumSharp", + "", + "| | Status | Ratio | Meaning |", + "|:-:|--------|:-----:|---------|", + "|✅| Faster | <1.0 | NumSharp beats NumPy |", + "|🟡| Close | 1-2x | Acceptable parity |", + "|🟠| Slower | 2-5x | Optimization target |", + "|🔴| Slow | >5x | Priority fix |", + "|⚪| Pending | - | C# benchmark not run |", + "", + "---", + "", + f"**Summary:** {total} ops | ✅ {faster} | 🟡 {close} | 🟠 {slower} | 🔴 {much_slower} | ⚪ {no_data}", + "", + ] + + # Get results with valid data (both sides, NumPy >= 0.001ms to avoid division issues) + with_data = [r for r in results if r.ratio is not None and r.numpy_ms >= 0.001] + + if with_data: + # Sort by ratio - best (lowest) first + sorted_by_ratio = sorted(with_data, key=lambda r: r.ratio) + + # Top 15 best (NumSharp faster or closest) + best_15 = sorted_by_ratio[:15] + lines.append("### 🏆 Top 15 Best (NumSharp closest to NumPy)") + lines.append("") + lines.append("| | Operation | Type | NumPy | NumSharp | Ratio |") + lines.append("|:-:|-----------|:----:|------:|---------:|------:|") + for r in best_15: + icon = get_status_icon(r.status) + lines.append(f"|{icon}| {r.operation} | {r.dtype} | {r.numpy_ms:.1f} | {r.numsharp_ms:.1f} | {r.ratio:.1f}x |") + lines.append("") + + # Top 15 worst (NumPy much faster) + worst_15 = sorted_by_ratio[-15:][::-1] # Reverse to show worst first + lines.append("### 🔻 Top 15 Worst (Optimization priorities)") + lines.append("") + lines.append("| | Operation | Type | NumPy | NumSharp | Ratio |") + lines.append("|:-:|-----------|:----:|------:|---------:|------:|") + for r in worst_15: + icon = get_status_icon(r.status) + lines.append(f"|{icon}| {r.operation} | {r.dtype} | {r.numpy_ms:.1f} | {r.numsharp_ms:.1f} | {r.ratio:.1f}x |") + lines.append("") + + lines.append("---") + lines.append("") + + # Group by suite + suites: Dict[str, List[UnifiedResult]] = {} + for r in results: + suite = r.suite or "General" + if suite not in suites: + suites[suite] = [] + suites[suite].append(r) + + # Generate compact table for each suite + for suite_name, suite_results in suites.items(): + lines.append(f"### {suite_name}") + lines.append("") + lines.append("| | Operation | Type | NumPy | NumSharp | Ratio |") + lines.append("|:-:|-----------|:----:|------:|---------:|------:|") + + for r in suite_results: + icon = get_status_icon(r.status) + numsharp_str = f"{r.numsharp_ms:.1f}" if r.numsharp_ms else "-" + ratio_str = f"{r.ratio:.1f}x" if r.ratio else "-" + lines.append(f"|{icon}| {r.operation} | {r.dtype} | {r.numpy_ms:.1f} | {numsharp_str} | {ratio_str} |") + + lines.append("") + + with open(output_path, 'w', encoding='utf-8') as f: + f.write('\n'.join(lines)) + print(f"Markdown written to: {output_path}") + + +def main(): + parser = argparse.ArgumentParser(description='Merge NumPy and NumSharp benchmark results') + parser.add_argument('--numpy', default='benchmark-report.json', help='Path to NumPy results JSON') + parser.add_argument('--csharp', default='NumSharp.Benchmark.GraphEngine/BenchmarkDotNet.Artifacts/results', + help='Path to BenchmarkDotNet artifacts directory') + parser.add_argument('--output', default='benchmark-report', help='Output file base name (without extension)') + parser.add_argument('--format', choices=['all', 'json', 'csv', 'md'], default='all', + help='Output format(s)') + args = parser.parse_args() + + # Load results + print("Loading NumPy results...") + numpy_results = load_numpy_results(args.numpy) + print(f" Found {len(numpy_results)} NumPy results") + + print("Loading C# results...") + csharp_results = load_csharp_results(args.csharp) + print(f" Found {len(csharp_results)} C# results") + + # Merge + print("Merging results...") + unified = merge_results(numpy_results, csharp_results) + print(f" Generated {len(unified)} unified results") + + # Generate outputs + if args.format in ('all', 'json'): + generate_json(unified, f"{args.output}.json") + if args.format in ('all', 'csv'): + generate_csv(unified, f"{args.output}.csv") + if args.format in ('all', 'md'): + generate_markdown(unified, f"{args.output}.md") + + # Print summary + print("\n" + "=" * 60) + print("Summary:") + print(f" ✅ Faster: {sum(1 for r in unified if r.status == 'faster')}") + print(f" 🟡 Close: {sum(1 for r in unified if r.status == 'close')}") + print(f" 🟠 Slower: {sum(1 for r in unified if r.status == 'slower')}") + print(f" 🔴 Much slower: {sum(1 for r in unified if r.status == 'much_slower')}") + print(f" ⚪ No data: {sum(1 for r in unified if r.status == 'no_data')}") + print("=" * 60) + + +if __name__ == '__main__': + main() diff --git a/docfx_project/api/.gitignore b/docfx_project/api/.gitignore deleted file mode 100644 index e8079a3be..000000000 --- a/docfx_project/api/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -############### -# temp file # -############### -*.yml -.manifest diff --git a/docfx_project/api/index.md b/docfx_project/api/index.md deleted file mode 100644 index 362837245..000000000 --- a/docfx_project/api/index.md +++ /dev/null @@ -1,3 +0,0 @@ -# NumSharp docfx documentation - -This is the autogenerated documentation of NumSharp \ No newline at end of file diff --git a/docfx_project/articles/NDArray.Creation.md b/docfx_project/articles/NDArray.Creation.md deleted file mode 100644 index 22da1c732..000000000 --- a/docfx_project/articles/NDArray.Creation.md +++ /dev/null @@ -1,104 +0,0 @@ - # Array creation - -Before we do some fancy numeric stuff or even machine learning we have to clear one thing. - -**How do we generate NDArrays?** - -Since NDArray is the key class in SciSharp stack there must be numerous possibilities how to generate this arrays. And yes that’s the case. - -Maybe first of all we should see the dump way – which can be always used but is not too user friendly. -In this example we access the Storage property directly - one more reason to avoid it. - -**Dump way** - -```CSHARP -// first constructor with data type and shape (here 3x3 matrix) -var nd = new NDArray(typeof(double),3,3); - -// set 9 elements into the storage of this array. -np.Storage.SetData(new double[] {1,2,3,4,5,6,7,8,9}); -``` - -Ok looks not too difficult. But also not too userfriendly. - -We create an empty NDArray with 3x3 shape, fill it with 9 elements. -We followed the row wise matrix layour by default. - -So with this 3x3 shaped NDArray we can do matrix multiplication, QR decomposition, SVD, ... - -But keep in mind - always be careful with your shape and be sure what you want to do with your elements in this shape. - -**Create by enumeration** - -The next example shows the numpy style creation. - -```CSHARP -using NumSharp.Core; - -// we take the Data / elements from an array -// we do not need to define the shape here - it is automaticly shaped to 1D -var np1 = np.array(new double[] {1,2,3,4,5,6} ); -``` - -Ok as we can see, this time the array was created without define the shape. - -This is possible since the method expect that the double[] array shall be transformed into a NDArray directly. - -**Create by implicit cast** - -Beside this numpy style C# offers its own flavour of creation. - -```CSHARP -using NumSharp.Core; - -// implicit cast double[] to NDArray - dtype & shape are deduced by array type and shape -NDArray nd = new double[]{1,2,3,4}; -``` - -And for matrix and n dim tensors also work the same. - -```CSHARP -using NumSharp.Core; - -NDArray nd = new double[,]{{1,2,3},{4,5,6}}; -``` - -Beside the .NET array to NDArray converting there exist different kinds of methods which also exist in numpy. - -**Create by given range** - -```CSHARP -using NumSharp.Core; - -// we simple say "create an array with 10 elements" -// start is expected to be 0 and step 1 -var np1 = np.arange(10); - -// this time start with 1, step 2 -// and do it as long as smaller than 10 -var np2 = np.arange(1,10,2); -``` - -**Create diagonal matrix** - -```CSHARP -using NumSharp.Core; - -// simple 5x5 eye matrix -var nd1 = np.eye(5); - -// 3x3 eye matrix but elements different diagonal -nd1 = np.eye(3,1); -``` - -**Create by linspace** - -```CSHARP -using NumSharp.Core; - -// create vector with 50 elements, from 4 to 10 -// include last element -// and convert them to double (float64) -var nd1 = np.linspace(4,10, 50, true, np.float64); -``` - diff --git a/docfx_project/articles/NDArray.LinAlg.md b/docfx_project/articles/NDArray.LinAlg.md deleted file mode 100644 index bd289865d..000000000 --- a/docfx_project/articles/NDArray.LinAlg.md +++ /dev/null @@ -1,17 +0,0 @@ - # Linear algebra - - Now we got some arrays so we should understand what we can do with it. - -## element wise operation - -## Matrix Transpose - -## Matrix and Vector multiplication - - ## Solve Linear Equation - - ## QR decomposition - - ## Inverse of Matrix - - ## SVD \ No newline at end of file diff --git a/docfx_project/articles/toc.yml b/docfx_project/articles/toc.yml deleted file mode 100644 index 3d97d6a03..000000000 --- a/docfx_project/articles/toc.yml +++ /dev/null @@ -1,8 +0,0 @@ -- name: Introduction - href: intro.md -- name: Array Creation - href: NDArray.Creation.md -- name: Linear Algebra - href: NDArray.LinAlg.md - - \ No newline at end of file diff --git a/docfx_project/docfx.json b/docfx_project/docfx.json deleted file mode 100644 index 5bfcf3d37..000000000 --- a/docfx_project/docfx.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "metadata": [ - { - "src": [ - { - "src": "../", - "files": [ - "src/NumSharp.Core/NumSharp.Core.csproj" - ] - } - ], - "dest": "api", - "disableGitFeatures": false, - "disableDefaultFilter": false - } - ], - "build": { - "content": [ - { - "files": [ - "api/**.yml", - "api/index.md" - ] - }, - { - "files": [ - "articles/**.md", - "articles/**/toc.yml", - "toc.yml", - "*.md" - ] - } - ], - "resource": [ - { - "files": [ - "images/**" - ] - } - ], - "overwrite": [ - { - "files": [ - "apidoc/**.md" - ], - "exclude": [ - "obj/**", - "_site/**" - ] - } - ], - "dest": ".", - "globalMetadataFiles": [], - "fileMetadataFiles": [], - "template": [ - "default" - ], - "postProcessors": [], - "markdownEngineName": "markdig", - "noLangKeyword": false, - "keepFileLink": false, - "cleanupCacheHistory": false, - "disableGitFeatures": false - } -} \ No newline at end of file diff --git a/docfx_project/images/python-csharp-comparision.png b/docfx_project/images/python-csharp-comparision.png deleted file mode 100644 index 1b8b3675d..000000000 Binary files a/docfx_project/images/python-csharp-comparision.png and /dev/null differ diff --git a/docfx_project/index.md b/docfx_project/index.md deleted file mode 100644 index 8d6a6e4b0..000000000 --- a/docfx_project/index.md +++ /dev/null @@ -1,31 +0,0 @@ -Welcome Seeker to NumSharp's documentation! -=========================================== - -Since you reached our documentation, you must be interested into .NET or into machine learning. - -No matter what you was searching, you will be satisfied. - -NumSharp is quite new open source project with one big goal: adapt the famous and well-known python library numpy and bring it into .NET world. -On top of this, we try to bring the whole Scipy Stack to .NET world. -Sounds crazy? -Yes maybe a little bit. As crazy as bring .NET on mobile phones (Xamarin) or into browser (Blazor). ;) - -Why we should do that? - -- Because in .NET we trust (everybody knows why ^^) -- Because we can do (hey we are .NET developer we can do cloud computing, do fancy web side stuff, are No. 1 for GUI programming in windows area, experiment with WASM – a.k.a. the Blazor project, do mobile things with Xamarin – yes, so how hard it can be to improve our numeric stack?) -- Because Microsoft also try to let .NET framework become an important framework for machine learning area. Therefore, it is time for us to support the F# developers who always were the leading experts in numeric area and machine learning. Let us help to shape .NET for numeric area. -- Because we can reach more languages than any other framework can do. It is not just a project for C#. We are not just C# developers – we are .NET developers and we are like a big family. Code one time and give it to all other languages. Because of this we are not just interested into C# - we also want to deliver packages special for F#, Powershell, VB, Ironpython, PHP, … we want to write the core in C# but we want to give each language the sugar it deserves. - -What does Numsharp make different than the other numeric frameworks? - -- We deliver a new class of array, which has a good performance in all different situations. The NDArray follows the idea of numpy and Quantstack, which store all elements of a multidimensional array (independent of the number of dimensions) into one large array. The indexing depends totally on the Shape of the NDArray, which determines if it is a matrix, a tensor, a vector or something else. -- We try to implement the numpy APIs as well as possible so that people who come from numpy feels like be at home. More over people can find easier tutorials if they are new to machine learning or numerical stuff in general. - -So I hope seeker you got a quite well impression of what this is all about. - -- Curious? → ```dotnet add package NumSharp``` -- Want new features? → https://github.com/SciSharp/NumSharp -- Want to chat in digital "Coffeeroom"? → https://gitter.im/numsharp/Lobby -- Want to support? → fork us on Github ;) - diff --git a/docfx_project/toc.yml b/docfx_project/toc.yml deleted file mode 100644 index f0d10cac4..000000000 --- a/docfx_project/toc.yml +++ /dev/null @@ -1,5 +0,0 @@ -- name: User Documentation - href: articles/ -- name: Api Documentation - href: api/ - homepage: api/index.md diff --git a/docs/api/NumSharp.Extensions.html b/docs/api/NumSharp.Extensions.html deleted file mode 100644 index 131d12789..000000000 --- a/docs/api/NumSharp.Extensions.html +++ /dev/null @@ -1,121 +0,0 @@ - - - - - - - - Namespace NumSharp.Extensions - - - - - - - - - - - - - - - - -
-
- - - - -
- - - -
- - - - - - diff --git a/docs/api/NumSharp.Generic.NDArray-1.html b/docs/api/NumSharp.Generic.NDArray-1.html deleted file mode 100644 index df43ee96e..000000000 --- a/docs/api/NumSharp.Generic.NDArray-1.html +++ /dev/null @@ -1,440 +0,0 @@ - - - - - - - - Class NDArray<T> - - - - - - - - - - - - - - - - -
-
- - - - -
- - - -
- - - - - - diff --git a/docs/api/NumSharp.Generic.html b/docs/api/NumSharp.Generic.html deleted file mode 100644 index 8d56944be..000000000 --- a/docs/api/NumSharp.Generic.html +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - Namespace NumSharp.Generic - - - - - - - - - - - - - - - - -
-
- - - - -
- - - -
- - - - - - diff --git a/docs/api/NumSharp.Shape.html b/docs/api/NumSharp.Shape.html deleted file mode 100644 index d6eefef46..000000000 --- a/docs/api/NumSharp.Shape.html +++ /dev/null @@ -1,691 +0,0 @@ - - - - - - - - Class Shape - - - - - - - - - - - - - - - - -
-
- - - - -
- - - -
- - - - - - diff --git a/docs/api/NumSharp.Slice.html b/docs/api/NumSharp.Slice.html deleted file mode 100644 index 65bf8fcff..000000000 --- a/docs/api/NumSharp.Slice.html +++ /dev/null @@ -1,313 +0,0 @@ - - - - - - - - Class Slice - - - - - - - - - - - - - - - - -
-
- - - - -
- - - -
- - - - - - diff --git a/docs/api/NumSharp.html b/docs/api/NumSharp.html deleted file mode 100644 index ba62f16d1..000000000 --- a/docs/api/NumSharp.html +++ /dev/null @@ -1,136 +0,0 @@ - - - - - - - - Namespace NumSharp - - - - - - - - - - - - - - - - -
-
- - - - -
- - - -
- - - - - - diff --git a/docs/api/index.html b/docs/api/index.html deleted file mode 100644 index f2746efc3..000000000 --- a/docs/api/index.html +++ /dev/null @@ -1,111 +0,0 @@ - - - - - - - - NumSharp docfx documentation - - - - - - - - - - - - - - - -
-
- - - - -
- - - -
- - - - - - diff --git a/docs/api/toc.html b/docs/api/toc.html deleted file mode 100644 index 0a79ac682..000000000 --- a/docs/api/toc.html +++ /dev/null @@ -1,95 +0,0 @@ - -
-
-
-
- - -
-
-
-
- - -
-
-
-
\ No newline at end of file diff --git a/docs/images/python-csharp-comparision.png b/docs/images/python-csharp-comparision.png deleted file mode 100644 index 1b8b3675d..000000000 Binary files a/docs/images/python-csharp-comparision.png and /dev/null differ diff --git a/docs/index.html b/docs/index.html deleted file mode 100644 index e320272fa..000000000 --- a/docs/index.html +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - - Welcome Seeker to NumSharp's documentation! - - - - - - - - - - - - - - - -
-
- - - - -
- - - -
- - - - - - diff --git a/docs/issues/categories.md b/docs/issues/categories.md new file mode 100644 index 000000000..56e88efa9 --- /dev/null +++ b/docs/issues/categories.md @@ -0,0 +1,332 @@ +# NumSharp Open Issues - Categorized + +**Total open issues: 142** + +| Category | Count | +|----------|-------| +| [np.* Bugs](#np-bugs) | 29 | +| [Other Bugs](#other-bugs) | 28 | +| [Missing np.* Functions](#missing-np-functions) | 34 | +| [Feature Requests](#feature-requests) | 21 | +| [Performance Issues](#performance-issues) | 4 | +| [Questions / How-To / Off-Topic](#questions--how-to--off-topic) | 27 | + +--- + +## np.* Bugs + +Bugs in existing `np.*` functions: wrong results, crashes, or API typos. + +| Issue | Title | Author | Labels | +|-------|-------|--------|--------| +| [#315](https://github.com/SciSharp/NumSharp/issues/315) | ToString should truncate its output | @thomasd3 | bug, enhancement | +| [#362](https://github.com/SciSharp/NumSharp/issues/362) | Implicit operators for >, >=, <, <= | @deepakkumar1984 | help wanted, missing feature/s | +| [#398](https://github.com/SciSharp/NumSharp/issues/398) | Typo in library np.random.stardard | @QadiymStewart | | +| [#405](https://github.com/SciSharp/NumSharp/issues/405) | np.argsort not sorting properly | @tk4218 | | +| [#407](https://github.com/SciSharp/NumSharp/issues/407) | np.negative is not working ? | @LordTrololo | | +| [#408](https://github.com/SciSharp/NumSharp/issues/408) | np.meshgrid() has a hidden error returning wrong results | @LordTrololo | | +| [#418](https://github.com/SciSharp/NumSharp/issues/418) | help me | @mak27arr | | +| [#419](https://github.com/SciSharp/NumSharp/issues/419) | np.meshgrid error | @mak27arr | | +| [#426](https://github.com/SciSharp/NumSharp/issues/426) | arctan2() returning incorrect value | @RoseberryPi | | +| [#428](https://github.com/SciSharp/NumSharp/issues/428) | Typo in NDArray.ToMuliArray method name | @jpmn | | +| [#436](https://github.com/SciSharp/NumSharp/issues/436) | np.searchsorted error! | @wangfeixing | | +| [#437](https://github.com/SciSharp/NumSharp/issues/437) | argmin is not the same with numpy | @tomachristian | | +| [#443](https://github.com/SciSharp/NumSharp/issues/443) | 0.3.0 from NuGet throwing NotSupportedException on negate function call | @gandalfh | | +| [#447](https://github.com/SciSharp/NumSharp/issues/447) | np.sum() Is supported on numsharp0.20.5, but not on NumSharp0.30.0 | @lijianxin520 | | +| [#452](https://github.com/SciSharp/NumSharp/issues/452) | [missing feature/s] NumSharp's np.around() method is missing decimals parameter which is available in NumPy | @shashi4u | | +| [#456](https://github.com/SciSharp/NumSharp/issues/456) | silent catastrophe in implicit casting singleton array to value type | @dmacd | | +| [#461](https://github.com/SciSharp/NumSharp/issues/461) | np.save incorrectly saves System.Byte arrays as signed | @rikkitook | | +| [#466](https://github.com/SciSharp/NumSharp/issues/466) | [Bug] np.random.choice raise Exception | @QingtaoLi1 | | +| [#468](https://github.com/SciSharp/NumSharp/issues/468) | np_array.convolve returning Null | @dklein9500 | | +| [#470](https://github.com/SciSharp/NumSharp/issues/470) | Numsharp0.30.0 np.random.choice() method missing cause Exception | @UCtreespring | | +| [#477](https://github.com/SciSharp/NumSharp/issues/477) | Different Result between NumPy and NumSharp with np.matmul Function | @Koyamin | | +| [#487](https://github.com/SciSharp/NumSharp/issues/487) | linspace to Array as type float, while other functions as type double | @changjian-github | | +| [#488](https://github.com/SciSharp/NumSharp/issues/488) | np.random.choice raised System.NotSupportedException | @alvinfebriando | | +| [#490](https://github.com/SciSharp/NumSharp/issues/490) | np.random.choice with replace: false produces duplicates | @GThibeault | | +| [#499](https://github.com/SciSharp/NumSharp/issues/499) | Possible typo "ToMuliDimArray()" | @sappho192 | | +| [#505](https://github.com/SciSharp/NumSharp/issues/505) | `np.convolve` return null exception | @behroozbc | | +| [#507](https://github.com/SciSharp/NumSharp/issues/507) | np.maximum error | @Thanatos0173 | | +| [#508](https://github.com/SciSharp/NumSharp/issues/508) | np.hstack has diffrent effect from python | @xdqa01 | | +| [#517](https://github.com/SciSharp/NumSharp/issues/517) | Error when loading a `.npy` file containing a scalar value | @thalesfm | | + +### Breakdown + +**Wrong/Unexpected Results:** +- [#398](https://github.com/SciSharp/NumSharp/issues/398) - Typo: np.random.stardard_normal (should be standard) +- [#405](https://github.com/SciSharp/NumSharp/issues/405) - np.argsort returns wrong order +- [#408](https://github.com/SciSharp/NumSharp/issues/408) - np.meshgrid returns wrong results (hidden memory bug) +- [#426](https://github.com/SciSharp/NumSharp/issues/426) - np.arctan2 returns incorrect value +- [#437](https://github.com/SciSharp/NumSharp/issues/437) - np.argmin behavior differs from NumPy +- [#456](https://github.com/SciSharp/NumSharp/issues/456) - Implicit cast of singleton NDArray silently produces wrong value (memory reinterpretation) +- [#466](https://github.com/SciSharp/NumSharp/issues/466) - np.random.choice raises NotSupportedException +- [#470](https://github.com/SciSharp/NumSharp/issues/470) - np.random.choice() throws NotSupportedException (0.30.0) +- [#477](https://github.com/SciSharp/NumSharp/issues/477) - np.matmul returns different results from NumPy for 3D arrays +- [#488](https://github.com/SciSharp/NumSharp/issues/488) - np.random.choice raises NotSupportedException +- [#490](https://github.com/SciSharp/NumSharp/issues/490) - np.random.choice with replace=false produces duplicates +- [#507](https://github.com/SciSharp/NumSharp/issues/507) - np.maximum throws random errors during repeated calls +- [#508](https://github.com/SciSharp/NumSharp/issues/508) - np.hstack produces different results from Python + +**Crashes / Exceptions:** +- [#362](https://github.com/SciSharp/NumSharp/issues/362) - Comparison operators >, >=, <, <= return null +- [#418](https://github.com/SciSharp/NumSharp/issues/418) - np.meshgrid second return value is always null +- [#419](https://github.com/SciSharp/NumSharp/issues/419) - np.meshgrid second return value crashes the program +- [#436](https://github.com/SciSharp/NumSharp/issues/436) - np.searchsorted throws error on double arrays +- [#443](https://github.com/SciSharp/NumSharp/issues/443) - np.negate throws NotSupportedException on 0.30.0 +- [#447](https://github.com/SciSharp/NumSharp/issues/447) - np.sum throws NotSupportedException on 0.30.0 +- [#466](https://github.com/SciSharp/NumSharp/issues/466) - np.random.choice raises NotSupportedException +- [#468](https://github.com/SciSharp/NumSharp/issues/468) - NDArray.convolve() returns null +- [#470](https://github.com/SciSharp/NumSharp/issues/470) - np.random.choice() throws NotSupportedException (0.30.0) +- [#488](https://github.com/SciSharp/NumSharp/issues/488) - np.random.choice raises NotSupportedException +- [#505](https://github.com/SciSharp/NumSharp/issues/505) - np.convolve returns null / NullReferenceException +- [#507](https://github.com/SciSharp/NumSharp/issues/507) - np.maximum throws random errors during repeated calls +- [#517](https://github.com/SciSharp/NumSharp/issues/517) - np.load fails on scalar .npy files (off-by-one in header parsing) + +**API Typos / Naming:** +- [#398](https://github.com/SciSharp/NumSharp/issues/398) - Typo: np.random.stardard_normal (should be standard) +- [#428](https://github.com/SciSharp/NumSharp/issues/428) - Typo: NDArray.ToMuliArray (should be ToMultiArray) +- [#452](https://github.com/SciSharp/NumSharp/issues/452) - np.around() missing decimals parameter +- [#499](https://github.com/SciSharp/NumSharp/issues/499) - Typo: ToMuliDimArray() should be ToMultiDimArray() + +**Version 0.30.0 Regressions:** +- [#443](https://github.com/SciSharp/NumSharp/issues/443) - np.negate throws NotSupportedException on 0.30.0 +- [#447](https://github.com/SciSharp/NumSharp/issues/447) - np.sum throws NotSupportedException on 0.30.0 +- [#466](https://github.com/SciSharp/NumSharp/issues/466) - np.random.choice raises NotSupportedException +- [#470](https://github.com/SciSharp/NumSharp/issues/470) - np.random.choice() throws NotSupportedException (0.30.0) +- [#488](https://github.com/SciSharp/NumSharp/issues/488) - np.random.choice raises NotSupportedException + +--- + +## Other Bugs + +Bugs in core infrastructure, indexing, memory management, platform compatibility. + +| Issue | Title | Author | Labels | +|-------|-------|--------|--------| +| [#366](https://github.com/SciSharp/NumSharp/issues/366) | Masking (ndarray[nd]) | @henon | | +| [#368](https://github.com/SciSharp/NumSharp/issues/368) | Masking a slice ("...") returns null | @ohjerm | | +| [#369](https://github.com/SciSharp/NumSharp/issues/369) | Slicing NotSupportedException | @Oceania2018 | missing feature/s | +| [#396](https://github.com/SciSharp/NumSharp/issues/396) | Bitmap.ToNDArray problem with odd bitmap width | @herrvonregen | | +| [#410](https://github.com/SciSharp/NumSharp/issues/410) | np.save fails with IndexOutOfRangeException for jagged arrays | @Jmerk523 | | +| [#412](https://github.com/SciSharp/NumSharp/issues/412) | The type 'NDArray' exists in both 'NumSharp.Core, Version=0.20.5.0, ' and 'NumSharp.Lite, Version=0.1.7.0, | @sportbilly21 | | +| [#422](https://github.com/SciSharp/NumSharp/issues/422) | Index of element with a condiction | @EnricoBeltramo | | +| [#423](https://github.com/SciSharp/NumSharp/issues/423) | "System.NotImplementedException: '' --> someArray = np.frombuffer(byteBuffer.ToArray(), np.uint32); | @mehmetcanbalci-Notrino | | +| [#430](https://github.com/SciSharp/NumSharp/issues/430) | NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock`1 fails on Mono on Linux | @kgoderis | | +| [#433](https://github.com/SciSharp/NumSharp/issues/433) | NDArray exists in both NumSharp.Core, Version=0.20.5.0 and NumSharp.Lite, Version=0.1.9.0 | @gscheck | | +| [#434](https://github.com/SciSharp/NumSharp/issues/434) | AccessViolationException when selecting indexes using ndarray[ndarray] and setting a scalar value | @lijianxin520 | bug | +| [#440](https://github.com/SciSharp/NumSharp/issues/440) | NDArray.ToBitmap() has critical issue with 24bpp VERTICAL images | @MiroslavKabat | bug | +| [#448](https://github.com/SciSharp/NumSharp/issues/448) | Debug.Assert(...) causes tests to stop the entire process | @Nucs | bug | +| [#455](https://github.com/SciSharp/NumSharp/issues/455) | NumSharp does not allow building with IL2CPP via Unity | @julia-koziel | | +| [#467](https://github.com/SciSharp/NumSharp/issues/467) | NumSharp and Tensorflow.NET works on Desktop but fails on Cloud Web Service (.NET 5) | @marsousi | | +| [#471](https://github.com/SciSharp/NumSharp/issues/471) | Unhandled Exception: System.NotSupportedException: Specified method is not supported. | @KonardAdams | | +| [#475](https://github.com/SciSharp/NumSharp/issues/475) | ToBitmap fails if not contiguous because of Broadcast mismatch | @ponzis | | +| [#476](https://github.com/SciSharp/NumSharp/issues/476) | Numsharp.Core contains many Debug.Assert() lines | @rtwalterson | | +| [#484](https://github.com/SciSharp/NumSharp/issues/484) | np.load System.Exception | @Kiord | | +| [#491](https://github.com/SciSharp/NumSharp/issues/491) | ToBitmap() - datatype mistmatch | @davidvct | | +| [#492](https://github.com/SciSharp/NumSharp/issues/492) | critical vulnerability in version 5.0.2 of system.drawing.common | @jkl-ds | | +| [#493](https://github.com/SciSharp/NumSharp/issues/493) | Numsharp array output in .net interactive notebooks is misleading | @oxygen-dioxide | | +| [#501](https://github.com/SciSharp/NumSharp/issues/501) | Memory leak? | @TakuNishiumi | | +| [#506](https://github.com/SciSharp/NumSharp/issues/506) | Cannot create an NDArray of shorts | @NickBotelho | | +| [#509](https://github.com/SciSharp/NumSharp/issues/509) | Extremely poor performance on sum reduce | @lucdem | | +| [#514](https://github.com/SciSharp/NumSharp/issues/514) | SetItem for multiple Ids not working | @MaxOmlor | | +| [#519](https://github.com/SciSharp/NumSharp/issues/519) | BUG: NDArray filted_array = ori_array[max_prob > conf_threshold]; | @1Zengy | | +| [#520](https://github.com/SciSharp/NumSharp/issues/520) | Can't convert to Vector3 | @xiaoshux | | + +### Breakdown + +**Indexing / Slicing / Masking:** +- [#366](https://github.com/SciSharp/NumSharp/issues/366) - Boolean masking ndarray[nd] throws NotSupportedException on setter +- [#368](https://github.com/SciSharp/NumSharp/issues/368) - Masking a slice ('...') returns null +- [#410](https://github.com/SciSharp/NumSharp/issues/410) - np.save fails with IndexOutOfRangeException for jagged arrays +- [#422](https://github.com/SciSharp/NumSharp/issues/422) - Boolean indexing / conditional filtering not working +- [#434](https://github.com/SciSharp/NumSharp/issues/434) - AccessViolationException on ndarray[ndarray] index + scalar set +- [#519](https://github.com/SciSharp/NumSharp/issues/519) - Boolean filtering randomly returns correct results or empty array + +**Memory / Crashes:** +- [#430](https://github.com/SciSharp/NumSharp/issues/430) - UnmanagedMemoryBlock fails on Mono/Linux +- [#434](https://github.com/SciSharp/NumSharp/issues/434) - AccessViolationException on ndarray[ndarray] index + scalar set +- [#501](https://github.com/SciSharp/NumSharp/issues/501) - Memory leak: repeated NDArray operations consume excessive memory + +**Platform / Compatibility:** +- [#430](https://github.com/SciSharp/NumSharp/issues/430) - UnmanagedMemoryBlock fails on Mono/Linux +- [#455](https://github.com/SciSharp/NumSharp/issues/455) - IL2CPP build fails in Unity (LAPACKProviderType) +- [#467](https://github.com/SciSharp/NumSharp/issues/467) - Fails on Azure Web Service / cloud (DllNotFoundException tensorflow) +- [#492](https://github.com/SciSharp/NumSharp/issues/492) - Critical vulnerability in System.Drawing.Common 5.0.2 +- [#520](https://github.com/SciSharp/NumSharp/issues/520) - Cannot cast NDArray values to Unity Vector3 (implicit cast bug) + +**Bitmap / Image:** +- [#396](https://github.com/SciSharp/NumSharp/issues/396) - Bitmap.ToNDArray fails with odd bitmap widths (stride alignment) +- [#440](https://github.com/SciSharp/NumSharp/issues/440) - NDArray.ToBitmap() incorrect for 24bpp vertical images +- [#475](https://github.com/SciSharp/NumSharp/issues/475) - ToBitmap fails on non-contiguous arrays (broadcast mismatch) +- [#491](https://github.com/SciSharp/NumSharp/issues/491) - ToBitmap() type mismatch (int arrays not supported) +- [#492](https://github.com/SciSharp/NumSharp/issues/492) - Critical vulnerability in System.Drawing.Common 5.0.2 + +--- + +## Missing np.* Functions + +Feature requests for specific NumPy API functions not yet implemented. + +| Issue | Function | Author | Labels | +|-------|----------|--------|--------| +| [#75](https://github.com/SciSharp/NumSharp/issues/75) | np.asarray | @Oceania2018 | enhancement | +| [#78](https://github.com/SciSharp/NumSharp/issues/78) | np.where | @Oceania2018 | enhancement | +| [#105](https://github.com/SciSharp/NumSharp/issues/105) | np.vdot | @Oceania2018 | enhancement | +| [#106](https://github.com/SciSharp/NumSharp/issues/106) | np.inner | @Oceania2018 | help wanted | +| [#108](https://github.com/SciSharp/NumSharp/issues/108) | np.tensordot | @Oceania2018 | help wanted | +| [#114](https://github.com/SciSharp/NumSharp/issues/114) | np.fft.fft | @Oceania2018 | enhancement | +| [#202](https://github.com/SciSharp/NumSharp/issues/202) | np.pad | @skywalkerisnull | enhancement | +| [#210](https://github.com/SciSharp/NumSharp/issues/210) | np.all (with axis support) | @Esther2013 | | +| [#220](https://github.com/SciSharp/NumSharp/issues/220) | np.flip | @pkingwsd | enhancement | +| [#221](https://github.com/SciSharp/NumSharp/issues/221) | np.rot90 | @pkingwsd | | +| [#239](https://github.com/SciSharp/NumSharp/issues/239) | np.linalg.norm (full implementation) | @henon | enhancement | +| [#298](https://github.com/SciSharp/NumSharp/issues/298) | np.random.choice (weighted sampling) | @Plankton555 | enhancement | +| [#360](https://github.com/SciSharp/NumSharp/issues/360) | np.any (with axis support) | @Oceania2018 | enhancement | +| [#365](https://github.com/SciSharp/NumSharp/issues/365) | np.nonzero | @Oceania2018 | enhancement | +| [#373](https://github.com/SciSharp/NumSharp/issues/373) | np.median | @turowicz | help wanted, missing feature/s | +| [#374](https://github.com/SciSharp/NumSharp/issues/374) | np.append | @solarflarefx | help wanted, missing feature/s | +| [#378](https://github.com/SciSharp/NumSharp/issues/378) | np.frombuffer | @Nucs | enhancement, missing feature/s | +| [#397](https://github.com/SciSharp/NumSharp/issues/397) | np.tile | @QadiymStewart | | +| [#413](https://github.com/SciSharp/NumSharp/issues/413) | np.split | @lqdev | | +| [#414](https://github.com/SciSharp/NumSharp/issues/414) | np.delete (currently returns null) | @simonbuehler | | +| [#415](https://github.com/SciSharp/NumSharp/issues/415) | Boolean indexing and np.where | @joshmyersdean | | +| [#439](https://github.com/SciSharp/NumSharp/issues/439) | np.where (re-requested) | @minhduc66532 | missing feature/s | +| [#441](https://github.com/SciSharp/NumSharp/issues/441) | np.linalg.norm | @minhduc66532 | missing feature/s | +| [#445](https://github.com/SciSharp/NumSharp/issues/445) | np.dot with preallocated output array | @bigdimboom | missing feature/s | +| [#449](https://github.com/SciSharp/NumSharp/issues/449) | np.isclose / np.allclose (currently dead code) | @koliyo | missing feature/s | +| [#450](https://github.com/SciSharp/NumSharp/issues/450) | np.diag | @syemhusa | missing feature/s | +| [#454](https://github.com/SciSharp/NumSharp/issues/454) | np.linalg.lstsq (currently returns null) | @yangjiandendi | | +| [#464](https://github.com/SciSharp/NumSharp/issues/464) | np.random.triangular | @ppsdatta | | +| [#473](https://github.com/SciSharp/NumSharp/issues/473) | Bitwise shift and OR operators on NDArray | @MichielMans | | +| [#480](https://github.com/SciSharp/NumSharp/issues/480) | np.unravel_index | @iainross | | +| [#485](https://github.com/SciSharp/NumSharp/issues/485) | np.linalg.norm (re-requested) | @williamlzw | | +| [#486](https://github.com/SciSharp/NumSharp/issues/486) | Slice assignment (e.g. preds[:,:,0] = ...) | @burungiu | | +| [#497](https://github.com/SciSharp/NumSharp/issues/497) | np.linalg.pinv | @gsgou | | +| [#515](https://github.com/SciSharp/NumSharp/issues/515) | np.tile (re-requested) | @MaxOmlor | | + +### By Area + +**Linear Algebra:** +- [#105](https://github.com/SciSharp/NumSharp/issues/105) - np.vdot +- [#106](https://github.com/SciSharp/NumSharp/issues/106) - np.inner +- [#108](https://github.com/SciSharp/NumSharp/issues/108) - np.tensordot +- [#239](https://github.com/SciSharp/NumSharp/issues/239) - np.linalg.norm (full implementation) +- [#441](https://github.com/SciSharp/NumSharp/issues/441) - np.linalg.norm +- [#445](https://github.com/SciSharp/NumSharp/issues/445) - np.dot with preallocated output array +- [#454](https://github.com/SciSharp/NumSharp/issues/454) - np.linalg.lstsq (currently returns null) +- [#485](https://github.com/SciSharp/NumSharp/issues/485) - np.linalg.norm (re-requested) +- [#497](https://github.com/SciSharp/NumSharp/issues/497) - np.linalg.pinv + +**Array Creation / Manipulation:** +- [#75](https://github.com/SciSharp/NumSharp/issues/75) - np.asarray +- [#202](https://github.com/SciSharp/NumSharp/issues/202) - np.pad +- [#220](https://github.com/SciSharp/NumSharp/issues/220) - np.flip +- [#221](https://github.com/SciSharp/NumSharp/issues/221) - np.rot90 +- [#374](https://github.com/SciSharp/NumSharp/issues/374) - np.append +- [#378](https://github.com/SciSharp/NumSharp/issues/378) - np.frombuffer +- [#397](https://github.com/SciSharp/NumSharp/issues/397) - np.tile +- [#413](https://github.com/SciSharp/NumSharp/issues/413) - np.split +- [#414](https://github.com/SciSharp/NumSharp/issues/414) - np.delete (currently returns null) +- [#450](https://github.com/SciSharp/NumSharp/issues/450) - np.diag +- [#480](https://github.com/SciSharp/NumSharp/issues/480) - np.unravel_index +- [#486](https://github.com/SciSharp/NumSharp/issues/486) - Slice assignment (e.g. preds[:,:,0] = ...) +- [#515](https://github.com/SciSharp/NumSharp/issues/515) - np.tile (re-requested) + +**Logic / Selection / Indexing:** +- [#78](https://github.com/SciSharp/NumSharp/issues/78) - np.where +- [#210](https://github.com/SciSharp/NumSharp/issues/210) - np.all (with axis support) +- [#360](https://github.com/SciSharp/NumSharp/issues/360) - np.any (with axis support) +- [#365](https://github.com/SciSharp/NumSharp/issues/365) - np.nonzero +- [#415](https://github.com/SciSharp/NumSharp/issues/415) - Boolean indexing and np.where +- [#439](https://github.com/SciSharp/NumSharp/issues/439) - np.where (re-requested) +- [#445](https://github.com/SciSharp/NumSharp/issues/445) - np.dot with preallocated output array +- [#449](https://github.com/SciSharp/NumSharp/issues/449) - np.isclose / np.allclose (currently dead code) + +**Statistics:** +- [#373](https://github.com/SciSharp/NumSharp/issues/373) - np.median + +**Random:** +- [#298](https://github.com/SciSharp/NumSharp/issues/298) - np.random.choice (weighted sampling) +- [#464](https://github.com/SciSharp/NumSharp/issues/464) - np.random.triangular + +**Other:** +- [#114](https://github.com/SciSharp/NumSharp/issues/114) - np.fft.fft +- [#473](https://github.com/SciSharp/NumSharp/issues/473) - Bitwise shift and OR operators on NDArray + +--- + +## Feature Requests + +Non-np.* enhancements: architecture, tooling, new capabilities, ecosystem. + +| Issue | Title | Author | Labels | +|-------|-------|--------|--------| +| [#95](https://github.com/SciSharp/NumSharp/issues/95) | Extend the guidelines | @dotChris90 | | +| [#111](https://github.com/SciSharp/NumSharp/issues/111) | NumSharp GPU acceleration | @Oceania2018 | enhancement, help wanted, further discuss | +| [#116](https://github.com/SciSharp/NumSharp/issues/116) | Intel Math Kernel Library (MKL) | @Oceania2018 | enhancement, help wanted | +| [#129](https://github.com/SciSharp/NumSharp/issues/129) | Doc : Better specification for all classes (What class has what task) | @dotChris90 | further discuss | +| [#190](https://github.com/SciSharp/NumSharp/issues/190) | Compressed Sparse Format | @Oceania2018 | enhancement | +| [#211](https://github.com/SciSharp/NumSharp/issues/211) | implement scipy interpolate? | @xinqipony | enhancement | +| [#284](https://github.com/SciSharp/NumSharp/issues/284) | [Discussion] Ground Rules and Library Structure/Architecture | @Nucs | further discuss | +| [#326](https://github.com/SciSharp/NumSharp/issues/326) | Lazy loading | @aidevnn | further discuss | +| [#340](https://github.com/SciSharp/NumSharp/issues/340) | Memory Limitations | @Nucs | enhancement | +| [#341](https://github.com/SciSharp/NumSharp/issues/341) | NDArray string problem | @lokinfey | missing feature/s | +| [#343](https://github.com/SciSharp/NumSharp/issues/343) | Built-in System.Drawing.Image and Bitmap methods | @Nucs | enhancement | +| [#349](https://github.com/SciSharp/NumSharp/issues/349) | Scipy.Signal | @natank1 | missing feature/s | +| [#351](https://github.com/SciSharp/NumSharp/issues/351) | Proper way to iterate using IEnumerable | @Nucs | enhancement | +| [#361](https://github.com/SciSharp/NumSharp/issues/361) | Mixing indices and slices in NDArray[...] | @Oceania2018 | enhancement | +| [#363](https://github.com/SciSharp/NumSharp/issues/363) | Add `NDIterator` overload with support for specific axis. | @Nucs | missing feature/s | +| [#372](https://github.com/SciSharp/NumSharp/issues/372) | Clustering Example | @turowicz | help wanted, missing feature/s | +| [#375](https://github.com/SciSharp/NumSharp/issues/375) | Slice assignment? | @solarflarefx | missing feature/s | +| [#435](https://github.com/SciSharp/NumSharp/issues/435) | Complex number support? | @cgranade | | +| [#479](https://github.com/SciSharp/NumSharp/issues/479) | Lacking/Outdated Documentation | @Tianmaru | | +| [#500](https://github.com/SciSharp/NumSharp/issues/500) | The fact that such an excellent project has many unimplemented APIs and is no longer being maintained is regrettable. | @HCareLou | | +| [#523](https://github.com/SciSharp/NumSharp/issues/523) | Multi-threading supported? | @sawyermade | | + +--- + +## Performance Issues + +Reports of NumSharp being significantly slower than expected. + +| Issue | Title | Author | Summary | +|-------|-------|--------|---------| +| [#421](https://github.com/SciSharp/NumSharp/issues/421) | Performance | @mishun | Overall performance far slower than expected vs naive C# | +| [#427](https://github.com/SciSharp/NumSharp/issues/427) | Performance on np.matmul | @Banyc | np.matmul 100x slower than NumPy (3-4s vs 0.03s) | +| [#451](https://github.com/SciSharp/NumSharp/issues/451) | np.argmax is slow | @feiyuhuahuo | np.argmax very slow on large arrays (~500ms) | +| [#509](https://github.com/SciSharp/NumSharp/issues/509) | Extremely poor performance on sum reduce | @lucdem | sum(axis:0) 150x slower than NumPy | + +--- + +## Questions / How-To / Off-Topic + +Usage questions, conversion help, off-topic requests. + +| Issue | Title | Author | +|-------|-------|--------| +| [#70](https://github.com/SciSharp/NumSharp/issues/70) | Let more people know about NumSharp | @Oceania2018 | +| [#238](https://github.com/SciSharp/NumSharp/issues/238) | How to mimic Python's nice column and row access (i.e matrix[:, 2])? | @henon | +| [#383](https://github.com/SciSharp/NumSharp/issues/383) | is there any way to convert NumSharp.NDArray to Numpy.NDarray? | @lelelemonade | +| [#384](https://github.com/SciSharp/NumSharp/issues/384) | Save NDArray as png image | @solarflarefx | +| [#386](https://github.com/SciSharp/NumSharp/issues/386) | how to read .csv file with Numsharp? | @guang7400613 | +| [#390](https://github.com/SciSharp/NumSharp/issues/390) | How to create an NDArray from pointer and NPTypeCode? | @LarryThermo | +| [#401](https://github.com/SciSharp/NumSharp/issues/401) | How to convert NDArray to list | @Sullivanecidi | +| [#406](https://github.com/SciSharp/NumSharp/issues/406) | C# --> convert image to NDarray | @R06921096Yen | +| [#411](https://github.com/SciSharp/NumSharp/issues/411) | PyObject to NDArray | @aaronavi | +| [#416](https://github.com/SciSharp/NumSharp/issues/416) | how to make NumSharp.NDArray from Numpy.NDarray? | @djagatiya | +| [#424](https://github.com/SciSharp/NumSharp/issues/424) | The type or namespace name 'NumSharp' could not be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp]csharp(CS0246) | @rcffc | +| [#438](https://github.com/SciSharp/NumSharp/issues/438) | How to get the inverse of a 2D matrix? | @Mingrui-Yu | +| [#446](https://github.com/SciSharp/NumSharp/issues/446) | Unable to use np.dot due to "Specified method unsupported" error | @moonlitlyra | +| [#462](https://github.com/SciSharp/NumSharp/issues/462) | How to use the repo to convert some Python code? | @zydjohnHotmail | +| [#465](https://github.com/SciSharp/NumSharp/issues/465) | how could I transform between NumSharp.NDArray with Tensorflow.Numpy.NDArray? | @cross-hello | +| [#472](https://github.com/SciSharp/NumSharp/issues/472) | How to calculate the rank of a matrix with NumSharp? | @drtujugkhjk | +| [#481](https://github.com/SciSharp/NumSharp/issues/481) | Normal disttribution in NumSharp | @rthota90 | +| [#482](https://github.com/SciSharp/NumSharp/issues/482) | 大佬,能否用C#还原 java 的一个求解器 optaplanner | @JavaScript-zt | +| [#483](https://github.com/SciSharp/NumSharp/issues/483) | How to convert List to NDArray | @williamlzw | +| [#494](https://github.com/SciSharp/NumSharp/issues/494) | Hello, has SciSharp/NumSharp stopped development and maintenance? | @sdyby2006 | +| [#495](https://github.com/SciSharp/NumSharp/issues/495) | What is the exposed method for percentiles & median using np? | @vikassingh281 | +| [#496](https://github.com/SciSharp/NumSharp/issues/496) | Can NumSharp fit polynomial surface equations? | @liyu3519 | +| [#498](https://github.com/SciSharp/NumSharp/issues/498) | Is there an example on how to use it with IronPython? | @william19941994 | +| [#510](https://github.com/SciSharp/NumSharp/issues/510) | How to save a nested dictionary with `save_npz` | @rqx110 | +| [#511](https://github.com/SciSharp/NumSharp/issues/511) | Does Numsharp work in Unity with the IL2CPP backend? | @jacob-jacob-jacob | +| [#512](https://github.com/SciSharp/NumSharp/issues/512) | how to change to Microsoft.ML.OnnxRuntime.Tensors.DenseTensor? | @BingGitCn | +| [#516](https://github.com/SciSharp/NumSharp/issues/516) | Very helpful work. Keep at it | @duxuan11 | diff --git a/docs/issues/issue-0070-let-more-people-know-about-numsharp.md b/docs/issues/issue-0070-let-more-people-know-about-numsharp.md new file mode 100644 index 000000000..ac7afaa29 --- /dev/null +++ b/docs/issues/issue-0070-let-more-people-know-about-numsharp.md @@ -0,0 +1,123 @@ +# #70: Let more people know about NumSharp + +- **URL:** https://github.com/SciSharp/NumSharp/issues/70 +- **State:** OPEN +- **Author:** @Oceania2018 +- **Created:** 2018-11-08T03:07:08Z +- **Updated:** 2019-08-06T13:03:10Z +- **Labels:** help wanted + +## Description + +I've written an article [here](https://medium.com/@haiping008/numsharp-numerical-net-7c6ab6edfe27) which introduce NumSharp. + +@dotChris90 Can you start with the [docs](https://numsharp.readthedocs.io). + +## Comments + +### Comment 1 by @dotChris90 (2018-11-08T06:24:14Z) + +Would start maybe at weekends. Next 2 days have little bit more work to do. :) + +### Comment 2 by @dotChris90 (2018-11-08T10:19:18Z) + +@Oceania2018 just one little thing. Sorry I mention it. + +Shouldn't it be: + +var a = np.arange(9).Reshape(3,3)? + +So with capital R instead of small r? +The output of arange is a NDArray object. So we call its Reshape method. + +What we are doing is method chaining. So we do not use the np.reshape method (if exist didn't look ^^') but the NDArray Reshape method. + +### Comment 3 by @dotChris90 (2018-11-08T10:46:38Z) + +@Oceania2018 and question : shall we start doc with python sphinx? Or maybe take docfx? https://dotnet.github.io/docfx/ + +Just idk if sphinx can parse c# for api documentations by doc comments. + +### Comment 4 by @Oceania2018 (2018-11-08T11:34:21Z) + +We should use both of them, docfx is for generating md files, Sphinx is for organizing them, and make docs readable on readthedocs.io. + + +I prefer arange().reshape(), keep same as numpy as much as possible. + +### Comment 5 by @dotChris90 (2018-11-17T18:19:34Z) + +@Oceania2018 at the moment I experiment with docfx - it does not look as bad as i though. Especially the API documentation and the style looks promising. Moreover docfx is the one which is used from Microsoft I though. The hosting we could do on Github Pages. + +Just feel annoyed at sphinx python doc, that it highlight my C# code but it thinks it is python lol so the code looks not good. And was investigating for C# docs at moment. + +How you think of docfx? i tried at https://dotchris90.github.io/NumSharp/ I will not merge it to Scisharp/NumSharp - so dont worry but I will see how well this can look like. + +### Comment 6 by @Oceania2018 (2018-11-17T18:30:20Z) + +Does docfx generate markdown file? I think docfx is used to generate developer's API reference, because it is generated from souce code directly. Sphinx is often used to make tutorial document, like quick start. Sphinx support markdown file, it's easy to use. + +### Comment 7 by @dotChris90 (2018-11-17T18:58:24Z) + +Yes they are now able to do it. I was also surprised. Seems they developed quite well. + +You can write so called articles which is equivalent sphinx tutorials. Using markdown. Very easy seems. So tutorials and api and swagger rest api and more seems (ok rest API is not important for us....). + +I can maybe experiment with it and upload to my repo. If we think it looks good we can go with it. If not we take sphinx. + +### Comment 8 by @dotChris90 (2018-11-18T17:01:07Z) + +@Oceania2018 an example for our api +https://dotchris90.github.io/NumSharp/api/NumSharp.NDArray-1.html + +And example for article : +https://dotchris90.github.io/NumSharp/articles/NDArray.Creation.html + +@Oceania2018 if u not too angry with me. I would like to go with docfx. They plan to support multiple languages besides c# in future and using 100% md for articles. Plus the generated docs folder can be hosted 100% on github for free. + +The only thing that I am not satisfied is... The style. I look now for better template... + + + + +### Comment 9 by @Oceania2018 (2018-11-19T02:29:48Z) + +@dotChris90 Docfx looks awesome. keep going. + +### Comment 10 by @dotChris90 (2018-11-19T02:48:29Z) + +@Oceania2018 thanks. Before thinking about pull requests. Is NumSharps github page active? If not, could you activate it? Not sure if I can since u the founder / constructor of SciSharp organizations. :) + +### Comment 11 by @Oceania2018 (2018-11-19T03:22:12Z) + +@dotChris90 It's active. https://scisharp.github.io/NumSharp/ + +### Comment 12 by @dotChris90 (2018-11-19T03:29:29Z) + +@Oceania2018 thanks a lot. Then today maybe write some more user tutorials. ;) +And push. + +### Comment 13 by @Oceania2018 (2018-11-19T03:32:43Z) + +Sounds great. NumSharp got 80+ stars now. Seems like people really need it. + +### Comment 14 by @dotChris90 (2018-11-19T03:42:26Z) + +Totally. Before c# was not the language of numeric. Since this year Microsoft push this AI and ML topics so hard... But Microsoft didn't give us a numerical stack. + +But people deserve and need a numerical stack like NumSharp. :) + +### Comment 15 by @dotChris90 (2018-11-19T11:52:18Z) + +Ok it worked. Just merged the docs which I already made. Nothing new. But will write some tutorials for user and also a small Readme how to use docfx best. + +It's time we dotnet developers go deeper to science, machine learning and numerics. + +### Comment 16 by @fdncred (2018-11-19T13:54:26Z) + +docfx is looking good. + +### Comment 17 by @Nucs (2019-08-06T13:03:10Z) + +@henon @Oceania2018, Should we implement a documentation page like discussed here? +https://dotnet.github.io/docfx/ diff --git a/docs/issues/issue-0075-implement-numpy.asarray.md b/docs/issues/issue-0075-implement-numpy.asarray.md new file mode 100644 index 000000000..cd42308a3 --- /dev/null +++ b/docs/issues/issue-0075-implement-numpy.asarray.md @@ -0,0 +1,19 @@ +# #75: Implement numpy.asarray + +- **URL:** https://github.com/SciSharp/NumSharp/issues/75 +- **State:** OPEN +- **Author:** @Oceania2018 +- **Created:** 2018-11-09T05:00:28Z +- **Updated:** 2018-11-14T22:04:06Z +- **Labels:** enhancement + +## Description + +Convert the input to an array. +https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.asarray.html + +## Comments + +### Comment 1 by @Obrain2016 (2018-11-14T22:04:06Z) + +adopt diff --git a/docs/issues/issue-0078-implement-numpy.where.md b/docs/issues/issue-0078-implement-numpy.where.md new file mode 100644 index 000000000..7b82c5b6b --- /dev/null +++ b/docs/issues/issue-0078-implement-numpy.where.md @@ -0,0 +1,19 @@ +# #78: Implement numpy.where + +- **URL:** https://github.com/SciSharp/NumSharp/issues/78 +- **State:** OPEN +- **Author:** @Oceania2018 +- **Created:** 2018-11-09T05:07:46Z +- **Updated:** 2019-12-05T02:00:14Z +- **Labels:** enhancement + +## Description + +Return elements, either from x or y, depending on condition. +https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.where.html + +## Comments + +### Comment 1 by @rakshithm (2019-12-05T02:00:14Z) + +When can we expect this to be implemented? diff --git a/docs/issues/issue-0095-extend-the-guidelines.md b/docs/issues/issue-0095-extend-the-guidelines.md new file mode 100644 index 000000000..8fb80a834 --- /dev/null +++ b/docs/issues/issue-0095-extend-the-guidelines.md @@ -0,0 +1,59 @@ +# #95: Extend the guidelines + +- **URL:** https://github.com/SciSharp/NumSharp/issues/95 +- **State:** OPEN +- **Author:** @dotChris90 +- **Created:** 2018-11-10T18:36:50Z +- **Updated:** 2019-08-06T13:05:05Z +- **Assignees:** @Nucs + +## Description + +@Oceania2018 @fdncred I started our Wiki (was not a lot but at least some lines ....) + +On https://github.com/Oceania2018/NumSharp/wiki/Design-guidelines I started a page with guidelines. +Because I found our discussions and investigations last weeks very interesting and want to write them down. Especially casting, performance, arange instead of ARange, ... such things. + +If you do not like some parts, or want to add something, feel free to change. ;) + +## Comments + +### Comment 1 by @Oceania2018 (2018-11-12T23:03:19Z) + +Looks great. Good job! + +### Comment 2 by @Oceania2018 (2018-11-14T23:28:39Z) + +@dotChris90 @fdncred I've wrote an article [here](https://medium.com/@haiping008/numsharp-works-with-matplotlib-213f1753480). + +### Comment 3 by @fdncred (2018-11-15T00:17:59Z) + +Awesome! Good job. Maybe you should put your c# demo app in the repo as an example. + +### Comment 4 by @dotChris90 (2018-11-15T03:44:36Z) + +Amazing. I really was impressed when saw it. 🤩 + +### Comment 5 by @dotChris90 (2018-11-15T03:58:07Z) + +By the way. Technically background question. + +You used a matplotlib adapter and in background also using matplotlib. Amazing. + +I was wondering how much work it would be to make a own matplotlib but html based. + +In my mind hat sth like +- tiny web sever in background +- plotly.js as drawing lib +- chromely project for rendering + +### Comment 6 by @Oceania2018 (2018-11-15T04:00:32Z) + +Our hard work is worth it. NumSharp is providing enough methods to support high level library. +@dotChris90 I don't want to implement a ploting library for now. Let's focus on NumSharp and Pandas.NET. + +### Comment 7 by @dotChris90 (2018-11-15T04:08:50Z) + +Sure and agree. + +OH seems the f# guys already have sth like this with their xplot project so maybe even later no reason for us to implement diff --git a/docs/issues/issue-0105-implement-numpy.vdot.md b/docs/issues/issue-0105-implement-numpy.vdot.md new file mode 100644 index 000000000..c25fe5ebd --- /dev/null +++ b/docs/issues/issue-0105-implement-numpy.vdot.md @@ -0,0 +1,22 @@ +# #105: Implement numpy.vdot + +- **URL:** https://github.com/SciSharp/NumSharp/issues/105 +- **State:** OPEN +- **Author:** @Oceania2018 +- **Created:** 2018-11-15T03:48:18Z +- **Updated:** 2018-11-15T16:48:44Z +- **Labels:** enhancement +- **Assignees:** @tatadyj + +## Description + +Return the dot product of two vectors. +https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.vdot.html#numpy.vdot + +`ndarray.vdot` should be put in `LinearAlgebra` folder. + +## Comments + +### Comment 1 by @tatadyj (2018-11-15T16:45:36Z) + +give a try vdot diff --git a/docs/issues/issue-0106-implement-numpy.inner.md b/docs/issues/issue-0106-implement-numpy.inner.md new file mode 100644 index 000000000..a808603c8 --- /dev/null +++ b/docs/issues/issue-0106-implement-numpy.inner.md @@ -0,0 +1,16 @@ +# #106: Implement numpy.inner + +- **URL:** https://github.com/SciSharp/NumSharp/issues/106 +- **State:** OPEN +- **Author:** @Oceania2018 +- **Created:** 2018-11-15T03:49:36Z +- **Updated:** 2018-12-28T07:03:26Z +- **Labels:** help wanted +- **Milestone:** v0.7 + +## Description + +Inner product of two arrays. +https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.inner.html#numpy.inner + +`ndarray.inner` should be put in `LinearAlgebra` folder. diff --git a/docs/issues/issue-0108-implement-numpy.tensordot.md b/docs/issues/issue-0108-implement-numpy.tensordot.md new file mode 100644 index 000000000..7780a0d58 --- /dev/null +++ b/docs/issues/issue-0108-implement-numpy.tensordot.md @@ -0,0 +1,16 @@ +# #108: Implement numpy.tensordot + +- **URL:** https://github.com/SciSharp/NumSharp/issues/108 +- **State:** OPEN +- **Author:** @Oceania2018 +- **Created:** 2018-11-15T03:51:17Z +- **Updated:** 2018-12-28T07:03:44Z +- **Labels:** help wanted +- **Milestone:** v0.7 + +## Description + +Compute tensor dot product along specified axes for arrays >= 1-D. +https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.tensordot.html#numpy.tensordot + +`ndarray.tensordot` should be put in `LinearAlgebra` folder. diff --git a/docs/issues/issue-0111-numsharp-gpu-acceleration.md b/docs/issues/issue-0111-numsharp-gpu-acceleration.md new file mode 100644 index 000000000..74c59aa86 --- /dev/null +++ b/docs/issues/issue-0111-numsharp-gpu-acceleration.md @@ -0,0 +1,26 @@ +# #111: NumSharp GPU acceleration + +- **URL:** https://github.com/SciSharp/NumSharp/issues/111 +- **State:** OPEN +- **Author:** @Oceania2018 +- **Created:** 2018-11-16T18:08:54Z +- **Updated:** 2022-02-26T16:16:26Z +- **Labels:** enhancement, help wanted, further discuss + +## Description + +We might use [Campy](https://github.com/kaby76/Campy) to accelerate NumSharp. + +## Comments + +### Comment 1 by @fdncred (2018-11-16T18:25:03Z) + +@Oceania2018, I was going to suggest the same thing. We don't want to be writing cuda .cu files. It's not easy. However, my first suggestion would be to parallelize the code where possible. i.e. on `IEnumerables` we could use `.AsParallel()`, on for loops we could use `Parallel.For` and `Parallel.Foreach`. BenchmarkDotNet will be helpful here. + +### Comment 2 by @ZhiZe-ZG (2022-02-26T15:11:37Z) + +This function is very important in some occasions where accelerated computing is required but neural networks (and torch) are not suitable. + +### Comment 3 by @Oceania2018 (2022-02-26T16:16:26Z) + +We switched to [Tensorflow.Numpy](https://github.com/SciSharp/TensorFlow.NET/tree/master/src/TensorFlowNET.Core/NumPy). diff --git a/docs/issues/issue-0114-implement-numpy.fft.fft.md b/docs/issues/issue-0114-implement-numpy.fft.fft.md new file mode 100644 index 000000000..7fcd1c9c4 --- /dev/null +++ b/docs/issues/issue-0114-implement-numpy.fft.fft.md @@ -0,0 +1,13 @@ +# #114: Implement numpy.fft.fft + +- **URL:** https://github.com/SciSharp/NumSharp/issues/114 +- **State:** OPEN +- **Author:** @Oceania2018 +- **Created:** 2018-11-17T04:35:25Z +- **Updated:** 2018-11-17T04:35:47Z +- **Labels:** enhancement + +## Description + +Compute the one-dimensional discrete Fourier Transform. +https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.fft.fft.html#numpy.fft.fft diff --git a/docs/issues/issue-0116-intel-math-kernel-library-mkl.md b/docs/issues/issue-0116-intel-math-kernel-library-mkl.md new file mode 100644 index 000000000..8eef99d75 --- /dev/null +++ b/docs/issues/issue-0116-intel-math-kernel-library-mkl.md @@ -0,0 +1,321 @@ +# #116: Intel Math Kernel Library (MKL) + +- **URL:** https://github.com/SciSharp/NumSharp/issues/116 +- **State:** OPEN +- **Author:** @Oceania2018 +- **Created:** 2018-11-17T15:12:25Z +- **Updated:** 2019-05-02T16:53:31Z +- **Labels:** enhancement, help wanted +- **Assignees:** @dotChris90 +- **Milestone:** v0.7 + +## Description + +Performance-sensitive algorithms can be swapped with alternative implementations by the concept of providers like Intel MKL. +https://software.intel.com/en-us/performance-libraries + +## Comments + +### Comment 1 by @dotChris90 (2018-12-12T20:01:13Z) + +Intels MKL library implement the LAPACK interfaces - so it would be logical to think about a layer with different LAPACK providers - in other words - a strategy pattern. Let users decide which LAPACK provider they want to use. + +It will be not much work since LAPACK usual means --> all interfaces are the same. So the PInvoke class would be the same - just the native lib is different. + +As fdncred already said. :) + +### Comment 2 by @Oceania2018 (2018-12-12T20:01:52Z) + +Sounds great. + +### Comment 3 by @fdncred (2018-12-12T20:05:26Z) + +This is exactly what I was saying in #145 when I mentioned and linked to Armadillo. + +### Comment 4 by @dotChris90 (2018-12-13T07:27:39Z) + +@fdncred sorry yes i know but I want to mention it here at this place ;) + +### Comment 5 by @Oceania2018 (2018-12-13T18:04:00Z) + +@dotChris90 Please add MKL as a new provider when you have a chance. + +### Comment 6 by @dotChris90 (2018-12-13T18:29:30Z) + +yes. but after seeing Intel website I think we go strategy that mkl provider expects the lib installed. on their site they said u have to registry etc..... So.... I don't wanna quarrel with them. in case we simple copy their DLLs and publish them with NumSharp.... think Intel will be not happy. + +so installation must be done manually by user. + +At moment not sure what is most comfortable way to change providers. + +My suggestion is that static numpy class has a static property lapack provider which is an enum. + +The static lapack class will check this enum and will call the specific static lapack provider classes. + +The user can change provider global. I think most comfortable. + +### Comment 7 by @fdncred (2018-12-13T19:04:47Z) + +@dotChris90, I'll research this a bit because other people, namely microsoft, point to dlls such as this https://docs.microsoft.com/en-us/cognitive-toolkit/setup-mkl-on-windows. + +Now that I look closer, this one ls mklml and is opensource by intel. Perhaps that is different. + +### Comment 8 by @fdncred (2018-12-13T19:12:12Z) + +Check this out. Intel allows one to redistribute MKL. It's in the license. +https://software.intel.com/en-us/mkl/license-faq + +And here is the full license. +https://software.intel.com/en-us/license/intel-simplified-software-license + + +### Comment 9 by @fdncred (2018-12-13T19:20:21Z) + +Here's a few Github projects that wrap MKL in C#. May be easier just to use something that already exists. +https://github.com/DNRY/CSIntelPerfLibs +https://github.com/Rafka86/SharpMKL +https://github.com/Proxem/BlasNet + + +### Comment 10 by @dotChris90 (2018-12-13T19:40:01Z) + +@fdncred much thanks for investigation. This makes the situation much better. 👍 + +### Comment 11 by @dotChris90 (2018-12-14T07:26:10Z) + +Hm - ok it will not be so easy as I though. + +The problem is that MKL implement just a subset of LAPACK and it implement LAPACKE - not LAPACK. They are little bit different from interfaces. + +The LAPACK we have at moment (Standard) has about 1500 Functions - MKL has 450. But is much bigger .... NetLib is about 8MB and their MKL 150MB -.- + +Sorry I say - this issue will be open little bit longer because Intel just implement what they want .... + +### Comment 12 by @dotChris90 (2018-12-14T07:36:25Z) + +But do not worry - the Provider strategy I still want to follow. ;) + +### Comment 13 by @dotChris90 (2019-01-05T08:36:59Z) + +ok some news from my side. + +MKL is installable on Linux via https://gist.github.com/pachamaltese/afc4faef2f191b533556f261a46b3aa8 +and on Windows via PIP with command"pip install mkl". + +With this Libs can check what functions **are really exported**. + +@Oceania2018 @fdncred just one question to you 2. What you think about "put providers in separate packages?" Like "NumSharp.MKLProvider" and so on. The benefit would be --> do unit Tests and maybe automatic benchmark Tests just when the provider project made some changes and not NumSharp. +Appveyor would be capable of this. + +@Oceania2018 this would be maybe also a solution for Tensorflow.NET --> package the Libs as Provider in new Nuget Package. + +### Comment 14 by @Oceania2018 (2019-01-05T11:21:41Z) + +Seems like if we separate NumSharp.MKLProvider, we need to separate an Interface project too, then we will have 3 separate NuGet packages, right? + +### Comment 15 by @fdncred (2019-01-05T13:36:58Z) + +I like the idea of separate packages because it gives users a choice. + +### Comment 16 by @dotChris90 (2019-01-05T14:40:46Z) + +@Oceania2018 I think so. at least easiest solution. also agree with @fdncred. people can free choose. maybe we even can pack mkl in nuget package like python do. since pip offers nuget also could do. and we could offer nuget package with tensorflow C Api. + + I think it could be best solution because people can use mkl if they like or not. or take standard lapack. + +by the way on Friday I checked the CI of the standard open source lapack. with appveyor was able to build the DLLs and shared objects myself. + +If appveyor offers mac OS images we also could support Mac OS. + + +### Comment 17 by @Oceania2018 (2019-01-05T14:53:49Z) + +@dotChris90 you can try to add a new project. + +### Comment 18 by @dotChris90 (2019-01-05T20:34:53Z) + +Ok before do the stuff just want to clear with you 2 (@Oceania2018 @fdncred ) the plan. + +Our NumSharp repo would consist of + +- NumSharp.Core => our main project with no provider just abstraction (like an interface ILAPACKProvider) +- NumSharp.NetLibLAPACK => it provides the default LAPACK implementation from https://github.com/Reference-LAPACK/lapack (we could fork it and build C# wrapper classes - already was able to set it up on appveyor and generate some *.dlls +- NumSharp.IntelMKL => it provides the MKL from Intel with LAPACK (just can deliver the binaries - no source code) +- Ironpython and Powershell projects but they are not relevant for our providers + +Beside This I suggest one more thing +- folder "NumSharp.Meta" with a nuget spec file +- the NumSharp.Meta folder with its nuget spec file shall be used to generate an metapackage called simple "NumSharp" (this NumSharp package should add multiple references to users project like NumSharp.Core + NumSharp.NetLibLAPACK - in future we can add more but for now this 2 references are enough) +- why we should do it? --> users just need to do "dotnet add package NumSharp" (so 1 instead of 2 add package commands) and can start! but! important! they can remove the reference to NetLibLAPACK by themselves and add the IntelMKL - and everybody is happy. ;) + +@Oceania2018 for Tensorflow.NET I also suggest this solution with meta-package - so we deliver Tensorflow C API as package for users. + +### Comment 19 by @dotChris90 (2019-01-05T20:45:28Z) + +But also the annoying news .... Since we take a provider strategy we must take an OOP strategy pattern and ... they do not work with static methods. This just means our providers must be implemented as non-static classes with constructor - or other said - they must implement an interface. + +This is no bad thing just brings more code. we need our static methods to adapt the native libraries and we need the non static methods to implement interface. + +### Comment 20 by @Oceania2018 (2019-01-05T22:08:17Z) + +@dotChris90 Where is the interface project? We should have another Interface project dll. + +### Comment 21 by @dotChris90 (2019-01-07T19:46:35Z) + +hm I am not sure at moment. + +We could make a separate project and package or keep it in NumSharp.Core. +At moment think about pros and cons. + +### Comment 22 by @Oceania2018 (2019-01-07T19:52:20Z) + +OK, do more research. + +### Comment 23 by @buybackoff (2019-01-07T19:59:49Z) + +Have you looked at Math.Net MKL provider? Or at Math.Net integration at all? As far as I remember Math.Net has its own native wrapper over which they interop, but it should be trivial to amend if all parties agree. I'm following this project/stack for a while and happy if Python stack is repeated 1-to-1 in .NET, but having several options that basically do the same stuff seems sad. Especially given the size of MKL dependency. + +Cc @cdrnet + +### Comment 24 by @Oceania2018 (2019-01-07T20:57:15Z) + +@dotChris90 Do you know how much size of the MKL dll? As my experience of TensorFlow.NET, tensorflow.dll is about 65M, luckly the NuGet compress it to about 16M. So I pack the dll directly into NuGet, It's acceptable. + +### Comment 25 by @pkingwsd (2019-01-08T02:46:16Z) + +as below from MathNet + + +Licensing Restrictions +Be aware that unlike the core of Math.NET Numerics including the native wrapper, which are both open source under the terms of the MIT/X11 license, the Intel MKL binaries themselves are closed source and non-free. + +The Math.NET Numerics project does own an Intel MKL license (for Windows, no longer for Linux) and thus does have the right to distribute it along Math.NET Numerics. You can therefore use the Math.NET Numerics MKL native provider for free for your own use. However, it does not give you any right to redistribute it again yourself to customers of your own product. If you need to redistribute, buy a license from Intel. If unsure, contact the Intel sales team to clarify. + +@Oceania2018 +MathNet.Numerics.MKL.Win-x64 nuget package, the size about 136 MB, mathnet.numerics.mkl.linux-x64 about 134m + + +### Comment 26 by @Oceania2018 (2019-01-08T02:50:27Z) + +@pkingwsd It means we can't pack MKL into NumSharp's package? @dotChris90 so we just have to place the download link for user? + +### Comment 27 by @pkingwsd (2019-01-08T02:57:28Z) + +@Oceania2018 i thank so that ,just make NumSharp's MKL for windows package. + +### Comment 28 by @dotChris90 (2019-01-08T07:00:00Z) + +@buybackoff thanks for mention it. Actually I was thinking about this **BUT** (there is always a but ... ) I am really unsure about Intel Licensing etc. Not sure if we can use their Math.NET Libs .... thats the only reason. +To be honest - we plan that at the end is just one meta-data package called **NumSharp** and this contains references to **NumSharp.Core** and **NetLibLAPACK** package. + +For NetLibLAPACK Standard - I already tried out their build system with my personal account https://github.com/dotChris90/lapack. I am sure if we mention them in our Readme its ok for them. + +MKL is tricky. For standard user who just want to learn and get things done I prefer the NetLibLAPACK Lib. which will be reference when using "dotnet add package NumSharp" in future. But .... when we cleared this discussion about MKL .... we want to give user the chance to remove this NetLibLAPACK reference from their project and use MKL intel. This will reduce the space in memory and hard disk space. + +### Comment 29 by @dotChris90 (2019-01-08T07:04:37Z) + +@Oceania2018 @pkingwsd damn ... this license stuff get more complex .... but yes he is right. **If you do not mind - I will write an email to intel sales team to clear things.** + +I am little confused at moment since the Linux MKL is a simple debian based package and can be downloaded any time. So I though there is no restriction for windows also. But I am not sure so far. Because I can not find official windows repo for MKL ..... + +### Comment 30 by @dotChris90 (2019-01-08T15:00:49Z) + +@Oceania2018 @pkingwsd what about this section https://software.intel.com/en-us/mkl/license-faq ? +In the FAQ stand Yes, redistribution is allowed per the terms of the ISSL. and also no payment etc. + +### Comment 31 by @Oceania2018 (2019-01-08T15:18:30Z) + +Great, so we don't need to worry about the license problem per the official statement. + +### Comment 32 by @dotChris90 (2019-01-08T15:41:53Z) + +still wrote to them. I want a statement of them.... BTW fdncred also mentioned it before lol the faq but as I said I wait for their response. + +### Comment 33 by @fdncred (2019-01-08T16:04:00Z) + +yeah! someone reads my comments. LOL! ;) + +### Comment 34 by @dotChris90 (2019-01-08T16:09:44Z) + +@fdncred definitely. I am just highly confused about the mkl libraries out there. + +is anaconda mkl the same like normal mkl and why there is no package for windows... the apt get installer also just download the file and put at specific locations... + +drives me crazy.... + +### Comment 35 by @fdncred (2019-01-08T16:47:58Z) + +@dotChris90 it appears to me that anaconda's MKL is just the regular MKL. It also looks to me like there is a windows package. See the links below. +https://anaconda.org/anaconda/mkl +https://docs.anaconda.com/accelerate/mkl-overview/ +https://repo.anaconda.com/pkgs/main/win-64/ +For my two cents, I think Proxem's BlasNet is the best wrapper for MKL. It looks pretty mature. +https://github.com/Proxem/BlasNet + +### Comment 36 by @dotChris90 (2019-01-08T21:13:48Z) + +@fdncred Thanks for the update. ;) + +From the URL I agree with you. 👍 +I already downloaded the package via pip and checked it but the package brings multiple MKL dlls. In anaconda location you will find binaries with mkl_corem mkl_xyz, …. about 6 or 7 files. But I though the mkl thing is one single DLL …. but anaconda shows multiple .... this is extrem strange behaviour... + +I agree Proxems BlasNet looks fine but it does not solve our main problem. Proxem just brings Wrapper code in C# - please do not misunderstand me but I am not very impressed by this …. because there are a lot of C# Code-Generators who do the same job - e.g. ClangSharp, T4, SWIG and if I check the Mono team I am 100% sure I can find more generators. xD Such automatic wrapper always simple take a C header file and generate Code …. I really do not see any benefit to use it BlasNet. I saw the Code and as far as I can see the main methods we can use could be also generated automaticly by ClangSharp (or T4) so not sure why add package for something we can auto generate xD. + +Our (at least what makes me feel uncomfortable) problem is : Proxem does not bring a native MKL Lib package. I have to install it manually. In Linux its easy - "sudo apt-get install" but on windows it is impossible to do this. This makes CI Testing impossible. How do we want to do unit testing or automatic benchmark testing on Appveyor? Unfortunately -.- we can not do this - except we package this MKL DLL into a nuget package. damn windows has no apt get.... + + +### Comment 37 by @fdncred (2019-01-08T22:08:23Z) + +Probably not impossible for CI. Have you looked at using chocolatey to install MKL? It looks like one of microsoft's packages includes it https://chocolatey.org/packages/microsoft-r-open. It may not be perfect but it may work. + +I've had a lot of experience with ClangSharp and NClang as well as other generators to take a C/C++ library to C# and I'm quite sure that they are not easy. I've found with one for months trying to get the library ported and it's very time consuming. You can get close pretty easily but you can't get complete easily. It'll take work for sure. + +### Comment 38 by @dotChris90 (2019-01-09T05:16:00Z) + +damn choco package management didn't think on it yes. can try. thanks. + +If u say it is hard maybe I was too easy thinking. the only complex thing we could have with code generation is.... lapack 100 % uses pointer. so generator can not know what's array and what pass by reference. + +hm...yes could be trickier. but as long as we just using some few functions from lapack.... writing own is easier. but yes maybe later need some more professional things. + +### Comment 39 by @fdncred (2019-01-09T13:56:05Z) + +Yes, IntPtr from C/C++ can be tricky and requires hand massaging for every call, from my experience. Marshalling arrays isn't too complex if you know the count of the array and the size of the array. Ref, In, Out params can be tricky, especially if you have an [In, Out] parameter in C/C++, where you pass in out value in a parameter and you return a different value out of the same parameter. If you get stuck on something reach out to me and I may be able to help. + +### Comment 40 by @Oceania2018 (2019-01-09T14:11:46Z) + +@fdncred can you help with +https://github.com/SciSharp/TensorFlow.NET/issues/86? + +### Comment 41 by @fdncred (2019-01-09T14:17:14Z) + +@Oceania2018, yes, i'll look at it. I'm not promising i can fix it but I'll try. ;) + +### Comment 42 by @Oceania2018 (2019-01-09T14:22:30Z) + +Anyway I’d appreciate. Try to make it work. Enjoy tensorflow.net. + +### Comment 43 by @dotChris90 (2019-01-10T06:06:45Z) + +for traceability. Intel just offer you help if u have customer service.. yeah every company need money I know.... + +But post in forum and got answer direct from Intel. + +https://software.intel.com/en-us/comment/1932183#comment-1932183 + +as we can read there. don't worry take the mkl lib. + +answers was (2019 Jan 10th, 7:09 Berlin time) + +please refer here : license FAQ + +you won't have a problem redistributing it. + +### Comment 44 by @mzhukova (2019-05-02T16:53:31Z) + +Hi folks, +I saw on the Intel forum that you were asking about distributing MKL via nuget. +It is available now in nuget channel as well. I was just wondering, if this may be useful to you: https://www.nuget.org/packages?q=intelmkl + +Best regards, +Maria diff --git a/docs/issues/issue-0129-doc-better-specification-for-all-classes-what-class-has-what-task.md b/docs/issues/issue-0129-doc-better-specification-for-all-classes-what-class-has-what-task.md new file mode 100644 index 000000000..1e8bdbca6 --- /dev/null +++ b/docs/issues/issue-0129-doc-better-specification-for-all-classes-what-class-has-what-task.md @@ -0,0 +1,92 @@ +# #129: Doc : Better specification for all classes (What class has what task) + +- **URL:** https://github.com/SciSharp/NumSharp/issues/129 +- **State:** OPEN +- **Author:** @dotChris90 +- **Created:** 2018-11-23T17:16:31Z +- **Updated:** 2018-12-14T12:25:49Z +- **Labels:** further discuss + +## Description + +Since now NumSharp offers a system for non generic, generic, dynamic and static we are in a good position for further dialog / discuss about classes tasks. +Moreover this issue can be used for the developer documentation. + +Let us call it "tidy up" and think about what we really need and most important need to think about the SW design. + +At the moment I see the following classes and their tasks + +- Storage (which could be a child of interface class IStorage) + - store the Data somehow (abstract said - concrete store in 1D System.Array) + - Get and Set Data in this Store (all at once or by indexing) + - convert Data to specific type +- Shape ( best practice would be child of IShape) + - store the dimensions of the array + - compute the index of a 1D array by multiple indexes if array is a multidimensional array + - compute the multiple indexes of multidimensional array from the index of 1D array +- Core.NDArray (non generic ) + - 1 NDArray has 1 Storage & 1 Shape + - delivers many methods for manipulate, processes, … 1 or N different Core.NDArrays. + - since its non generic elements are ValueTypes (must be cast to double etc.) +- Generic.NDArray + - children of Core.NDArray which offers possibility to direct indexing since elements are of generic parameter type + +@Oceania2018 @fdncred you 2 ;) please correct me if I wrote something wrong. + +@Oceania2018 Sorry for my stupid questions always - is there a reason that a Storage shall have a shape? Its really just a design question. I just think for Testability Classes shall be as independent as possible from each others. If they do not need a relationship then they should not have. From my point of view since NDArray has a shape, Storage does not need a shape. Storage shall not care about its Shape and just contain the elements. Just our best friend NDArray shall use Storage and Shape to bring elements in correct form. + +;) anyway guys have a good week and nice weekend. + + + + + +## Comments + +### Comment 1 by @Oceania2018 (2018-11-23T18:39:50Z) + +Excellent concept describing. For shape in storage, my idea is storage should be responsible for persisting and seeking data from any dimension and position, NDArray’s main responsibility is calculating, not seek data form storage. We are open for this topic. And NumPy is responsible for exposing interfaces to external invoking. + +### Comment 2 by @dotChris90 (2018-11-23T18:51:25Z) + +hm good point. + +from testability point of view storage should not have a shape. +from logic I am not sure. + +We keep issue open and I look again the code. what fits better. + +It's really just design question. user should not care this because they are not official Apis. + +### Comment 3 by @dotChris90 (2018-11-28T04:12:16Z) + +I come up with decision. + +I agree with you. the storage should be responsible for every data access and converting stuff. + +But then we must be careful. Ndarray shall have no own shape. if necessary it shall call methods from its storage object. dtype same. +ndarray must return the dtype of storage at e. g. it's property dtype. + +### Comment 4 by @dotChris90 (2018-12-14T12:24:42Z) + +@Oceania2018 @fdncred + +I added an interface for storage and one for shape. This is a future planning so the storage get easier and more clear to use. I come up with this because I noticed the storages methods sometimes not 100% well ..... most was my mistake -.- + +e.g. GetData() return the internal 1D array but! if dtype is corresponding to T its the reference array and if not its a copy .... the data types are correct but the underlying pointers are different ..... and since you all so interested in performance, memory, etc. such things can not be. + + +The interfaces are suggestions for next generation Storage lol https://github.com/SciSharp/NumSharp/blob/master/src/NumSharp.Core/Interfaces/IStorage.cs + +As you see I made up the following convensions : + +- new property TensorOrder (maybe should call it TensorLayout) +- Allocate will be used to choose Shape, data type and! TensorOrder +- GetData always return the reference of internal storage ALWAYS! +- if dtype is not equal to T in GetData< T > the internal storage is converted automaticly! +- New method CloneData which always will give you a copy of the internal storage and not storage itself +- so all in all GetData is copy by reference, CloneData is copy by value +- GetColumWiseStorage & GetRowWiseStorage methods return the instance itself but with column wise or row wise layout +- This layout stuff is extrem critical for LAPACK - including MKL! since they just accept rowwise and we at moment use columnwise ;) + + diff --git a/docs/issues/issue-0190-compressed-sparse-format.md b/docs/issues/issue-0190-compressed-sparse-format.md new file mode 100644 index 000000000..953ac8482 --- /dev/null +++ b/docs/issues/issue-0190-compressed-sparse-format.md @@ -0,0 +1,35 @@ +# #190: Compressed Sparse Format + +- **URL:** https://github.com/SciSharp/NumSharp/issues/190 +- **State:** OPEN +- **Author:** @Oceania2018 +- **Created:** 2019-01-09T21:45:32Z +- **Updated:** 2019-04-16T16:00:05Z +- **Labels:** enhancement +- **Assignees:** @dotChris90 +- **Milestone:** v0.7 + +## Description + +We should implement the compressed ndarray, it is used widely in scikit-learn. The csr_matrix is included in SciPy not NumPy, but I think we should move it into NumSharp. @dotChris90 What do you think of it? + +[Compressed Sparse Column Format (CSC)](https://www.scipy-lectures.org/advanced/scipy_sparse/csc_matrix.html) +[Compressed Sparse Row Format (CSR)](https://www.scipy-lectures.org/advanced/scipy_sparse/csr_matrix.html) + +https://www.scipy-lectures.org/advanced/scipy_sparse/storage_schemes.html + +## Comments + +### Comment 1 by @Deep-Blue-2013 (2019-01-09T21:47:51Z) + +CSC format saved memory a lot. Looking forward to see this feature. + +### Comment 2 by @sebhofer (2019-04-16T13:38:38Z) + +Would be great to have an sparse matrix implementation with good performance! Math.Net has some support for sparse matrices, but performance is not great. Also, would be useful to have support for different storage formats (as you already hinted at above). + +As an additional reference: [Here](https://github.com/wo80/mathnet-extensions) is an implementation improving on the performance of Math.Net. + +### Comment 3 by @Oceania2018 (2019-04-16T16:00:05Z) + +@sebhofer Thanks for the info, it's important to us. diff --git a/docs/issues/issue-0202-implement-np.pad.md b/docs/issues/issue-0202-implement-np.pad.md new file mode 100644 index 000000000..4d345a6df --- /dev/null +++ b/docs/issues/issue-0202-implement-np.pad.md @@ -0,0 +1,25 @@ +# #202: implement np.pad + +- **URL:** https://github.com/SciSharp/NumSharp/issues/202 +- **State:** OPEN +- **Author:** @skywalkerisnull +- **Created:** 2019-03-03T04:25:59Z +- **Updated:** 2019-03-10T01:06:49Z +- **Labels:** enhancement +- **Assignees:** @KevinMa0207 +- **Milestone:** v0.7.5 + +## Description + +Add a buffer or padding around a numpy array: +https://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html + +## Comments + +### Comment 1 by @Oceania2018 (2019-03-03T15:13:32Z) + +```python +a = [1, 2, 3, 4, 5] +np.pad(a, (2,3), 'constant', constant_values=(4, 6)) + +``` diff --git a/docs/issues/issue-0210-add-numpy.all.md b/docs/issues/issue-0210-add-numpy.all.md new file mode 100644 index 000000000..97fca549b --- /dev/null +++ b/docs/issues/issue-0210-add-numpy.all.md @@ -0,0 +1,20 @@ +# #210: Add numpy.all + +- **URL:** https://github.com/SciSharp/NumSharp/issues/210 +- **State:** OPEN +- **Author:** @Esther2013 +- **Created:** 2019-03-10T04:32:04Z +- **Updated:** 2019-04-05T07:56:30Z +- **Assignees:** @Oceania2018, @KevinMa0207 + +## Description + +Test whether all array elements along a given axis evaluate to True. +`np.all([[True,False],[True,True]])` +https://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html + +## Comments + +### Comment 1 by @henon (2019-04-05T07:56:30Z) + +I just implemented this, but without axis support at the moment. The overload with axis is still to be done diff --git a/docs/issues/issue-0211-implement-scipy-interpolate.md b/docs/issues/issue-0211-implement-scipy-interpolate.md new file mode 100644 index 000000000..ebbdbfb8a --- /dev/null +++ b/docs/issues/issue-0211-implement-scipy-interpolate.md @@ -0,0 +1,32 @@ +# #211: implement scipy interpolate? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/211 +- **State:** OPEN +- **Author:** @xinqipony +- **Created:** 2019-03-12T02:27:15Z +- **Updated:** 2019-03-26T05:14:11Z +- **Labels:** enhancement +- **Assignees:** @Oceania2018 + +## Description + +this is an amazing project and any plan to implement scipy interpolate? + +## Comments + +### Comment 1 by @Oceania2018 (2019-03-12T02:50:02Z) + +Will do `Interpolate a 1-D function.` and `2-D` + +### Comment 2 by @Oceania2018 (2019-03-26T04:37:13Z) + +@xinqipony Is https://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html you want? + +### Comment 3 by @xinqipony (2019-03-26T05:09:21Z) + +yes, this is what I used: +interpolate.interp1d(x, y, kind='cubic', axis=0), + +in the meantime, I use MathNet now, but its implementation is not so good and not easy to use, + +look forward to your new updates! diff --git a/docs/issues/issue-0220-numpy.flip.md b/docs/issues/issue-0220-numpy.flip.md new file mode 100644 index 000000000..cce182e25 --- /dev/null +++ b/docs/issues/issue-0220-numpy.flip.md @@ -0,0 +1,20 @@ +# #220: numpy.flip + +- **URL:** https://github.com/SciSharp/NumSharp/issues/220 +- **State:** OPEN +- **Author:** @pkingwsd +- **Created:** 2019-03-21T03:29:13Z +- **Updated:** 2019-06-15T04:49:17Z +- **Labels:** enhancement +- **Assignees:** @yanglr + +## Description + +numpy.flip + +## Comments + +### Comment 1 by @Oceania2018 (2019-03-21T03:31:07Z) + +https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html +Please also past the python link, thanks. diff --git a/docs/issues/issue-0221-numpy.rot90.md b/docs/issues/issue-0221-numpy.rot90.md new file mode 100644 index 000000000..70a070da3 --- /dev/null +++ b/docs/issues/issue-0221-numpy.rot90.md @@ -0,0 +1,22 @@ +# #221: numpy.rot90 + +- **URL:** https://github.com/SciSharp/NumSharp/issues/221 +- **State:** OPEN +- **Author:** @pkingwsd +- **Created:** 2019-03-21T03:30:00Z +- **Updated:** 2021-01-25T22:55:22Z +- **Assignees:** @emrahsungu + +## Description + +numpy.rot90 + +## Comments + +### Comment 1 by @Oceania2018 (2019-03-21T03:31:46Z) + +https://numpy.org/doc/stable/reference/generated/numpy.rot90.html + +### Comment 2 by @solarflarefx (2021-01-25T22:53:39Z) + +@Oceania2018 @emrahsungu Does this exist in the current version of NumSharp? diff --git a/docs/issues/issue-0238-how-to-mimic-pythons-nice-column-and-row-access-i.e-matrix-2.md b/docs/issues/issue-0238-how-to-mimic-pythons-nice-column-and-row-access-i.e-matrix-2.md new file mode 100644 index 000000000..bb8287fc7 --- /dev/null +++ b/docs/issues/issue-0238-how-to-mimic-pythons-nice-column-and-row-access-i.e-matrix-2.md @@ -0,0 +1,401 @@ +# #238: How to mimic Python's nice column and row access (i.e matrix[:, 2])? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/238 +- **State:** OPEN +- **Author:** @henon +- **Created:** 2019-04-05T08:08:30Z +- **Updated:** 2020-02-08T11:40:24Z +- **Labels:** help wanted +- **Assignees:** @henon +- **Milestone:** v0.9 Multiple Backends + +## Description + +Hey all, + +How would you say to do access to a column `matrix[:, i]` or access to a row `matrix[i, :]` in NumSharp? + + +## Comments + +### Comment 1 by @henon (2019-04-05T11:21:07Z) + +I need to be able to get a (n-1)-dimensional slice of a n-dimensional matrix, i.e. a 1d vector out of a 2d matrix. +First step would be to add appropriate accessors to IStorage right? +I am not yet sure how they should look like, please comment if you have ideas. + +### Comment 2 by @henon (2019-04-05T11:35:01Z) + +This is not as elegantly possible as in Python, but we can do something like this, given that matrix is an NDArray: + +* matrix[Range.All, 1] ... return the first column, Python: matrix[:, 1] +* matrix[new Range(0, 2), 1] ... return the first two entries of the first column, Python: matrix[:2, 1] +* matrix[new Range(1,3), new Range(1,3)] ... return a 2x2 submatrix of matrix starting at 1,1, Python: matrix[1:3, 1:3] + + +### Comment 3 by @Oceania2018 (2019-04-05T11:35:18Z) + +Check `indexing` to help. +![image](https://user-images.githubusercontent.com/1705364/55624849-c97ce200-576c-11e9-8b03-5b4cac0766b0.png) + +We can override in `Slice` +![image](https://user-images.githubusercontent.com/1705364/55624914-f03b1880-576c-11e9-9456-2b4e97c17077.png) + +Or we can pass string `":1"`. + +### Comment 4 by @henon (2019-04-05T11:40:45Z) + +Yeah, the string idea is great for porting code from Python. I am sure it will be popular. + +### Comment 5 by @Oceania2018 (2019-04-05T11:43:02Z) + +Seem's like another contributor already implemented the string index. I'll found out later. @PppBr is that true? + +### Comment 6 by @henon (2019-04-05T11:45:05Z) + +when you slice a matrix in numpy you essentially get a view of the original data. modifying it will modify the original matrix. Do we have a view concept or implementation already? + +### Comment 7 by @Oceania2018 (2019-04-05T11:50:46Z) + +Not yet, we havn't have the `view` class. I've an idea how to implement the new `view`. + +`view` inherit from `ndarray`, but keep a `filter` of data index. +and `view` will implement a `IEnumerate` interface. +when interating the `view`, it will return all the element in the `filter`. +and view don't need copy the memory. change data will reflect in the original memory. + +@henon What do you think of it? + +or we need a new `NDStorage`? + +### Comment 8 by @henon (2019-04-05T12:14:49Z) + +@Oceania2018: I think the projection from the view to the original data could be handled entirely by the storage. + +This is complicated, I had to think about it for a time to wrap my head around it. If I am correct, what you need is a function that projects a view index onto an index on the original data (which could be another view that does further projection - think about that). + +I am not yet sure how that function looks like if you i.e. for instance get a 1D slice out of a 17-dimensional matrix but once we have that generic formula we can easily project view_index to underlying data_index and view_index+1, view_index+2, ... etc. to enumerate it. + + + + + + + +### Comment 9 by @Oceania2018 (2019-04-05T12:17:40Z) + +Actually, we have the formula to convert n-d index to 1d index and wise-verse. +chech the function `Shape.GetDimIndexOutShape` +So don't worry about the dimension. the storage is persistent data in 1d array. + +I still think the `view` should inherit from `ndarray` with a `filters` in `view` instance, not in `ndstorage` level. Let's keep this talk open. + +### Comment 10 by @henon (2019-04-05T12:47:10Z) + +Nice we have the projection and the inverse projection already, so the difficult part is actually already solved. The rest is just software design. + +One thing I missed, that the view also needs to enumerate on the underlying data (or view), is a stride. If you take a row out of a matrix the stride is 1, but if you take a column, the stride is the width of the matrix. + +ok, you may be right about inheriting from ndarray. I have only limited knowledge about the design at this point, so I trust your judgement. + +### Comment 11 by @Oceania2018 (2019-04-05T13:01:13Z) + +I will write the first version of view, then we can discuss further. + +### Comment 12 by @henon (2019-04-05T13:25:41Z) + +Don't forget to make the design recursive, so that you can have a `view` of a `view` of a `view` of a 'storage'. + +### Comment 13 by @Oceania2018 (2019-04-05T14:00:16Z) + +Sure + +### Comment 14 by @henon (2019-04-08T09:51:45Z) + +Update: Python's slice notation for accessing slices of NDArray has been implemented. However, the implementation of a view that serves that slice of the original data still needs to be done. + +Here is a very simple test case that demonstrates the problem to be solved: +```[TestMethod] + public void GetAColumnOf2dMatrix() + { + var x = np.arange(9).reshape(3, 3); + var v = x[":, 1"]; + Assert.IsTrue(Enumerable.SequenceEqual( v.Data(), new double[]{ 1, 4, 7 })); + v[1] = 99; + Assert.AreEqual(99, x[1,1]); + } +``` + +### Comment 15 by @Oceania2018 (2019-04-27T16:46:05Z) + +Check the `Slice3x2x2` UnitTest. + +### Comment 16 by @Rikki-Tavi (2020-02-07T03:35:42Z) + + +I have been wrestling with the same (or similar) issue in the context of trying to generate randomized mini-batches using NumSharp. +The python code I am trying to emulate looks like this: + +def random_mini_batches(X, Y, mini_batch_size = 64): + """ + Creates a list of random minibatches from (X, Y) + + Arguments: + X -- input data, of shape (input size, number of examples) + Y -- true "label" vector of shape (1, number of examples) + mini_batch_size - size of the mini-batches, integer + + Returns: + mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y) + """ + + m = X.shape[1] # number of training examples + mini_batches = [] + + # Step 1: Shuffle (X, Y) + permutation = list(np.random.permutation(m)) + + shuffled_X = X[:, permutation] + shuffled_Y = Y[:, permutation].reshape((Y.shape[0],m)) + + # Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case. + num_complete_minibatches = math.floor(m/mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning + for k in range(0, num_complete_minibatches): + mini_batch_X = shuffled_X[:, k * mini_batch_size : k * mini_batch_size + mini_batch_size] + mini_batch_Y = shuffled_Y[:, k * mini_batch_size : k * mini_batch_size + mini_batch_size] + mini_batch = (mini_batch_X, mini_batch_Y) + mini_batches.append(mini_batch) + + # Handling the end case (last mini-batch < mini_batch_size) + if m % mini_batch_size != 0: + mini_batch_X = shuffled_X[:, num_complete_minibatches * mini_batch_size : m] + mini_batch_Y = shuffled_Y[:, num_complete_minibatches * mini_batch_size : m] + mini_batch = (mini_batch_X, mini_batch_Y) + mini_batches.append(mini_batch) + + return mini_batches + +The part I have trouble emulating with NumSharp is: + + shuffled_X = X[:, permutation] + shuffled_Y = Y[:, permutation].reshape((Y.shape[0],m)) + +The closest I have been able to get is: + + var shuffled_X = new NDArray(np.float32, X.shape); + for (int i = 0; i < X.shape[0]; i++) + { + shuffled_X[i] = X[i][permutation]; + } + + var shuffled_Y = new NDArray(np.float32, Y.shape); + for (int i = 0; i < Y.shape[0]; i++) + { + shuffled_Y[i] = Y[i][permutation]; + } + shuffled_Y = shuffled_Y.reshape((Y.shape[0], m)); + +Which works, but is much, much slower (also true when I implement the alternative in Python). + +The problem with NumSharp is that I cannot put the indexer ":, permutation" in quotes. I've tried converting 'permutation' to its string-expanded list equivalent (so that I can have a totally string-based indexer that NumSharp likes) but I don't seem to be able to arrive at a string-serialized encoding of 'permutation' inside the resulting indexer that doesn't make NumSharp crash. + +Am I overlooking an obvious solution here? + +### Comment 17 by @Oceania2018 (2020-02-07T04:20:06Z) + +@BillyDJr Try +```csharp +shuffled_X = X[Slice.All, new Slice(permutation)]; +``` + +### Comment 18 by @Rikki-Tavi (2020-02-07T05:50:40Z) + +Trying that yielded: +`NumSharp.IncorrectShapeException: 'This method does not work with this shape or was not already implemented.'` + + +### Comment 19 by @henon (2020-02-07T07:50:54Z) + +> @BillyDJr Try +> +> ```cs +> shuffled_X = X[Slice.All, new Slice(permutation)]; +> ``` + +No, he needs index access to get shuffled data. It should be + +```cs +shuffled_X = X[Slice.All, new NDArray(permutation)]; +``` + +### Comment 20 by @Rikki-Tavi (2020-02-07T21:11:11Z) + +I simplified my Python target test case, showing two ways to generate the shuffled Xs and Ys. +m = 4 +X = np.random.rand(3,m) +Y = np.random.rand(1,m) +permutation = list(np.random.permutation(m)) +print ("perm: " + str(permutation)) +print ("X: " + str(X)) +print ("Y: " + str(Y)) +shuffled_X1 = X[:, permutation] +shuffled_X2 = X.copy() +for i in range(0, X.shape[0]): + shuffled_X2[i] = X[i][permutation] + +print("shuffled_X1: " + str(shuffled_X1)) +print("shuffled_X2: " + str(shuffled_X2)) + +shuffled_Y1 = Y[:, permutation].reshape((Y.shape[0],m)) +shuffled_Y2 = Y.copy() +for i in range(0, Y.shape[0]): + shuffled_Y2[i] = Y[i][permutation] +shuffled_Y2 = shuffled_Y2.reshape((Y.shape[0], m)) + +print("shuffled_Y1 " + str(shuffled_Y1)) +print("shuffled_Y2 " + str(shuffled_Y2)) + +And the results: +perm: [2, 1, 3, 0] +X: [[0.14038694 0.19810149 0.80074457 0.96826158] + [0.31342418 0.69232262 0.87638915 0.89460666] + [0.08504421 0.03905478 0.16983042 0.8781425 ]] +Y: [[0.09834683 0.42110763 0.95788953 0.53316528]] +shuffled_X1: [[0.80074457 0.19810149 0.96826158 0.14038694] + [0.87638915 0.69232262 0.89460666 0.31342418] + [0.16983042 0.03905478 0.8781425 0.08504421]] +shuffled_X2: [[0.80074457 0.19810149 0.96826158 0.14038694] + [0.87638915 0.69232262 0.89460666 0.31342418] + [0.16983042 0.03905478 0.8781425 0.08504421]] +shuffled_Y1 [[0.95788953 0.42110763 0.53316528 0.09834683]] +shuffled_Y2 [[0.95788953 0.42110763 0.53316528 0.09834683]] + +Here is the C# code (just showing the Xs for the sake of brevity). Note the shuffled_X2 works (as I reported before, but it runs too slowly for large datasets). As you can see, I try various stabs at arriving at shuffled_X1, all failing: + + var m = 4; + var X = np.random.rand(3, m); + var permutation = np.random.permutation(m); + + print($"perm: {permutation}"); + print($"X: {X}"); + + // In Python: shuffled_X1 = X[:, permutation] + try + { + var shuffled_X1 = X[Slice.All, permutation]; + print($"shuffled_X1: {shuffled_X1}"); + } + catch (Exception ex) + { + print($"Param as: raw permutation - error: {ex.Message}"); + } + + try + { + var shuffled_X1 = X[Slice.All, new Slice(permutation)]; + print($"shuffled_X1: {shuffled_X1}"); + } + catch (Exception ex) + { + print($"Param as: new Slice(permutation) - error: {ex.Message}"); + } + + try + { + var shuffled_X1 = X[Slice.All, new NDArray(permutation.ToArray())]; + print($"shuffled_X1: {shuffled_X1}"); + } + catch (Exception ex) + { + print($"Param as: new NDArray(permutation.ToArray()) - error: {ex.Message}"); + } + + try + { + var shuffled_X1 = X[Slice.All, new NDArray(permutation.CloneData())]; + print($"shuffled_X1: {shuffled_X1}"); + } + catch (Exception ex) + { + print($"Param as: new NDArray(permutation.CloneData()) - error: {ex.Message}"); + } + + try + { + var shuffled_X1 = X[Slice.All, new NDArray(Binding.list(permutation.ToArray()))]; + print($"shuffled_X1: {shuffled_X1}"); + } + catch (Exception ex) + { + print($"Param as: new NDArray(Binding.list(permutation.ToArray())) - error: {ex.Message}"); + } + + var shuffled_X2 = new NDArray(np.float32, X.shape); + for (int i=0; i()) - error: shape mismatch: objects cannot be broadcast to a single shape +Param as: new NDArray(permutation.CloneData()) - error: shape mismatch: objects cannot be broadcast to a single shape +Param as: new NDArray(Binding.list(permutation.ToArray())) - error: shape mismatch: objects cannot be broadcast to a single shape +shuffled_X2: [[0.03434474, 0.8834703, 0.5201029, 0.55567724], +[0.6067407, 0.7806033, 0.3361534, 0.7949469], +[0.60182047, 0.11560028, 0.83518714, 0.2805164]] + +Are there any other variations I should try? + + + + +### Comment 21 by @Rikki-Tavi (2020-02-08T04:45:32Z) + +FWIW....It was easy to get working with Numpy.NET: + + [TestMethod] + public void mytest() { + var m = 4; + var X = np.random.rand(3, m); + var permutation = np.random.permutation(m); + + print($"perm: {permutation}"); + print($"X: {X}"); + + var shuffled_X = X[":", permutation]; + print($"shuffled_X: {shuffled_X}"); + } + + private void print (string output) + { + System.Diagnostics.Debug.WriteLine(output); + } + +Resulted in: + +``` +perm: [3 0 1 2] +X: [[0.58033439 0.99341353 0.77685615 0.1893294 ] + [0.81824309 0.7315536 0.64120989 0.97876454] + [0.15659539 0.9045345 0.83839889 0.43254176]] +shuffled_X: [[0.1893294 0.58033439 0.99341353 0.77685615] + [0.97876454 0.81824309 0.7315536 0.64120989] + [0.43254176 0.15659539 0.9045345 0.83839889]] +``` +Now I'm off to investigate if there is an efficient way that I can use Nump.NET NDArrays for my mini-batch randomization in TensorFlow.NET. (I'm admittedly just hacking away here....please stop me, anyone, if you think there is a better way.) + + +### Comment 22 by @henon (2020-02-08T09:41:39Z) + +Obviously, this should also work in NumSharp, but there seems to be a bug somewhere. + +### Comment 23 by @Rikki-Tavi (2020-02-08T11:40:24Z) + +Ok. Thanks. I will keep my eye out for the resolution, once it appears, so that i might switch over. diff --git a/docs/issues/issue-0239-np.linalg.norm.md b/docs/issues/issue-0239-np.linalg.norm.md new file mode 100644 index 000000000..49f9cb621 --- /dev/null +++ b/docs/issues/issue-0239-np.linalg.norm.md @@ -0,0 +1,49 @@ +# #239: np.linalg.norm + +- **URL:** https://github.com/SciSharp/NumSharp/issues/239 +- **State:** OPEN +- **Author:** @henon +- **Created:** 2019-04-05T10:52:03Z +- **Updated:** 2020-10-09T10:41:13Z +- **Labels:** enhancement + +## Description + +I am going to port np.linalg.norm(...) + +## Comments + +### Comment 1 by @Oceania2018 (2019-04-05T15:35:08Z) + +It's not same as ? +![image](https://user-images.githubusercontent.com/1705364/55639218-77e54f00-578e-11e9-8320-89364ddc6805.png) + + +### Comment 2 by @henon (2019-04-05T16:36:31Z) + +ok, you are right. that implements the L2 norm I need. I'll add the shortcut np.linalg.norm(...) just for Python compatibility + +### Comment 3 by @henon (2019-04-05T16:44:54Z) + +no, after checking the code against the numpy docs, actually, the 2-norm is not the same what has been implemented in normalize(). There is no squaring of coefficients. Is that a bug? + +https://het.as.utexas.edu/HET/Software/Numpy/reference/generated/numpy.linalg.norm.html + +### Comment 4 by @Oceania2018 (2019-04-05T18:02:55Z) + +Yes, they're different. + +### Comment 5 by @8 (2020-10-09T07:23:27Z) + +Hi, + +I also noticed that the function is missing in `0.20.5`. +I think one could add a shortcut from `np.linalg.norm(a)` => `np.sqrt(a.dot(a))` instead, which should be equivalent. +Not sure about the overloads though. + +Does this make sense to you? + +Take care, +Martin + + diff --git a/docs/issues/issue-0284-discussion-ground-rules-and-library-structure-architecture.md b/docs/issues/issue-0284-discussion-ground-rules-and-library-structure-architecture.md new file mode 100644 index 000000000..8e3825964 --- /dev/null +++ b/docs/issues/issue-0284-discussion-ground-rules-and-library-structure-architecture.md @@ -0,0 +1,96 @@ +# #284: [Discussion] Ground Rules and Library Structure/Architecture + +- **URL:** https://github.com/SciSharp/NumSharp/issues/284 +- **State:** OPEN +- **Author:** @Nucs +- **Created:** 2019-06-14T15:33:31Z +- **Updated:** 2021-06-29T07:16:05Z +- **Labels:** further discuss + +## Description + +I couldn't but notice the inconsistencies around the library, There are functions that returns copies while some don't while some are not even complete. +The strong-typing of C# does surely makes it harder to get stuff done so `.tt` generators does a nice job helping with that. + +I would like to discuss the following: +1. What are the supported C# primitive types compared to numpy? +Looking at the implicit conversions of `NDArray` and other math operations such as `np.sum`, +I found that the type support is inconsistent. +note: Numpy supports both signed and unsigned types. [see this](https://www.numpy.org/devdocs/user/basics.types.html). + + ![image](https://user-images.githubusercontent.com/649919/59519128-ddad3000-8ecf-11e9-9091-552d86184504.png) + +2. Do we support `Complex`? +because aside of the basic math operations, it is not supported anywhere. + +3. To what rank/ndim the algorithms in C# support? +I saw some functions that support 2-3 and some up to 6. +[Numpy limitation is 32 dimensions.](https://github.com/numpy/numpy/issues/5744) + +4. NDArray mutable vs immutable + I think it should be up to the user to decide via a bool parameter. + * Arithmetic operators should always return a copy + * Following numpy's lead is the priority ofcouse. + +5. Seperation between `np`, `NDArray` and `backend engine` +There is a lot of mixup between whats computed where. +The reality is that they all redirect calls to each other. +In a perfect scenario: +we would refer all operations low-level operations to backend engine to perform the wanted task. +Having a fallback to each method that will compute in C#. +`NDArray` is only responsible for casting, initialization, storing data and serialization +And `np` is the high-level zone that uses backend. + +6. The incomplete methods should be logged somewhere, preferably in Issues or project here. +Heres just a few examples from my findings: + * `np.transpose` supports only to rank 2 and theres a `//todo` in the unit test that fails + * `np.flatten` wasn't implemented completely but was shipped on release + * `np.sum` doesn't support all data types. +We should start by creating issues for those problems in code and we'll get on from there + +7. Means of communication between the developing team via instant messaging? +Edit: Did not see the gitter tag on readme.md + +Those issues are important to address, simply because this library is and will be the backend of many high-level applications. +That's about it, Best regards. + +## Comments + +### Comment 1 by @henon (2019-06-14T17:00:28Z) + +Hi Nucs, +you are right, there are many inconsistencies due to the fact that people just added what they needed and left the rest undone. We should define stricter rules and postulate them in the readme. + +I think the most important guidance principle must be compatibility with the original NumPy. Only that way we can guarantee that porting Python scripts using numpy will work in NumSharp also. In this regard there is a lot of work to be done because until now it wasn't enforced very strongly. + +I agree that some kind of management of what we have and what we are missing would be nice. Creating issues is of course a good idea. I have another one: create as many test cases as possible which will reflect what already works and what not. I have recently ported a lot of tests from the Numpy documentation for NumSharp's sister project [Numpy.NET](https://github.com/SciSharp/Numpy.NET) which is a auto-generated wrapper around numpy. While doing that I also generated over 600 test cases which could be repurposed for testing NumSharp. In addition to that, we can generate further test cases that test both Numpy.NET and NumSharp against all the things you mentioned: +* number of supported ranks +* supported data types +* support for all backend engines +etc. + +A complete test suite is the ultimate todo list and helps keeping NumSharp in sync with numpy. + +PS: I could help generating more test cases from the Numpy.NET project. + +### Comment 2 by @henon (2019-06-14T17:25:44Z) + +ad 7: you can reach us on Gitter for quick questions, small talk, etc, but of course important stuff that should be accessible to all (like this) is of course best discussed in issues. I am sure @Oceania2018 will have answers for the other questions. + +### Comment 3 by @Oceania2018 (2019-06-16T00:02:33Z) + +ad 1: Ideally, support all primitive data type. +ad 2: Not support, but can add easily. +ad 3: In theory, no limitation. +ad 4: Following numpy's lead. +ad 5: Should do the calculation in `engine`, move current code into `engine` gradually. +ad 6: Agree. +ad 7: https://gitter.im/sci-sharp/community + +### Comment 4 by @Nucs (2019-08-06T12:47:33Z) + +All of these suggestions were implemented in the [new release](https://github.com/SciSharp/NumSharp/pull/336) of NumSharp 0.11.0-alpha2 and available on [nuget](https://www.nuget.org/packages/NumSharp/0.11.0-alpha2). + +### Comment 5 by @dcuccia (2021-06-29T00:51:14Z) + +ad 2: Would love to have Complex support. Just got to the end of a port and realized this was a non-starter. diff --git a/docs/issues/issue-0298-implement-numpy.random.choice.md b/docs/issues/issue-0298-implement-numpy.random.choice.md new file mode 100644 index 000000000..021cb32ac --- /dev/null +++ b/docs/issues/issue-0298-implement-numpy.random.choice.md @@ -0,0 +1,96 @@ +# #298: Implement numpy.random.choice + +- **URL:** https://github.com/SciSharp/NumSharp/issues/298 +- **State:** OPEN +- **Author:** @Plankton555 +- **Created:** 2019-06-27T09:42:50Z +- **Updated:** 2019-10-05T16:12:40Z +- **Labels:** enhancement +- **Assignees:** @Nucs + +## Description + +Generates a random sample from a given (possible weighted) 1-D array. + +NumPy docs: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html + +## Comments + +### Comment 1 by @Plankton555 (2019-06-27T09:48:16Z) + +I needed this and implemented a subset of this functionality (random sampling based on weighted probabilities). I can clean up that code and upload here so that it maybe can work as a start for this functionality. + +I've never contributed to an open-source project before though, so I might need some help when it comes to what must be implemented, and where in the architecture it should be located, and so on. + +### Comment 2 by @henon (2019-06-27T10:15:05Z) + +One of us (maybe @Nucs ?) can provide the method stub for you to fill in the code. You can then look at that commit to learn which files needed to be touched to add a new function. + +### Comment 3 by @Plankton555 (2019-06-28T10:11:27Z) + +Please do! Let me know when that is done. + +### Comment 4 by @Nucs (2019-06-30T20:02:39Z) + +Sorry it took so long, it should be placed in `NumSharp.Core/Random/np.random.choice.cs` +```C# +/// +/// //todo +/// +/// If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a were np.arange(a) +/// +/// The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a. +/// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html +public NDArray choice(NDArray arr, Shape shape, double[] probabilities = null) { + throw new NotImplementedException(); +} + +/// +/// //todo +/// +/// If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a were np.arange(a) +/// +/// The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a. +/// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html +public NDArray choice(int a, Shape shape, double[] probabilities = null) { + throw new NotImplementedException(); +} +``` +Feel free to contact us via [gitter](https://gitter.im/sci-sharp/community) if you get stuck or have a question + +### Comment 5 by @Plankton555 (2019-07-02T14:16:04Z) + +Working on this in https://github.com/Plankton555/NumSharp/tree/feature/np_random_choice + +### Comment 6 by @Plankton555 (2019-07-04T13:52:33Z) + +One of the examples in the numpy docs looks like +``` +>>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher'] +>>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3]) +array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'], + dtype='|S11') +``` + +Since the numsharp method signature either takes an integer or an NDArray I tried implementing this string[] list with an NDArray. This gives an exception (which maybe should be reported as a bug or nonimplemented feature since numpy arrays can take strings). +``` +NDArray aa_milne_arr = new string[] { "pooh", "rabbit", "piglet", "Christopher" }; // throws System.NotImplementedException: implicit operator NDArray(Array array) +``` + +In this particular case I can solve it in some ways: +1. Let this error happen until the NDArray has support for strings. +2. Have another method signature which takes an array/enumerable of some sort. This could be reasonable since the numpy docs explicitly states that np.random.choice "Generates a random sample from a given 1-D array", which should be possible to represent as an enumerable? + +Any thoughts? + +### Comment 7 by @Oceania2018 (2019-07-04T13:55:59Z) + +@Nucs Do you have any plan on `String` support? + +### Comment 8 by @Plankton555 (2019-07-04T14:31:40Z) + +Pull request at https://github.com/SciSharp/NumSharp/pull/310 + +### Comment 9 by @Nucs (2019-10-05T16:12:40Z) + +This issue is still open because `np.random.choice` does not support multi-dimensions. diff --git a/docs/issues/issue-0315-tostring-should-truncate-its-output.md b/docs/issues/issue-0315-tostring-should-truncate-its-output.md new file mode 100644 index 000000000..a1a01684d --- /dev/null +++ b/docs/issues/issue-0315-tostring-should-truncate-its-output.md @@ -0,0 +1,40 @@ +# #315: ToString should truncate its output + +- **URL:** https://github.com/SciSharp/NumSharp/issues/315 +- **State:** OPEN +- **Author:** @thomasd3 +- **Created:** 2019-07-18T12:32:09Z +- **Updated:** 2019-07-18T13:56:23Z +- **Labels:** bug, enhancement +- **Assignees:** @Nucs + +## Description + +On very large arrays, NDArray.ToString() is never coming back (or maybe it would at some point in time). + +It would make sense to truncate the ToString() output. + +## Comments + +### Comment 1 by @Nucs (2019-07-18T12:49:04Z) + +I'll add a `DebuggerTypeProxy` that'll truncute beyond certain amount of characters. +After we finish the rework on the NumSharp's backend - It should be much faster. + +### Comment 2 by @henon (2019-07-18T13:30:42Z) + +I implemented the NDArray.ToString() but at the time I didn't know that Numpy has a way of not showing the middle elements of a huge array. if you create a 100x100 matrix it will show this on the console. the ToString method probably should do the same. See below. Also, current ToString() does not format the elements so that they are equally spaced with a monotype font. + +``` +>>> import numpy as np +>>> a=np.arange(10000).reshape(100,100) +>>> a +array([[ 0, 1, 2, ..., 97, 98, 99], + [ 100, 101, 102, ..., 197, 198, 199], + [ 200, 201, 202, ..., 297, 298, 299], + ..., + [9700, 9701, 9702, ..., 9797, 9798, 9799], + [9800, 9801, 9802, ..., 9897, 9898, 9899], + [9900, 9901, 9902, ..., 9997, 9998, 9999]]) +>>> +``` diff --git a/docs/issues/issue-0326-lazy-loading.md b/docs/issues/issue-0326-lazy-loading.md new file mode 100644 index 000000000..4604762eb --- /dev/null +++ b/docs/issues/issue-0326-lazy-loading.md @@ -0,0 +1,122 @@ +# #326: Lazy loading + +- **URL:** https://github.com/SciSharp/NumSharp/issues/326 +- **State:** OPEN +- **Author:** @aidevnn +- **Created:** 2019-08-01T13:30:31Z +- **Updated:** 2019-09-25T17:58:40Z +- **Labels:** further discuss +- **Assignees:** @Nucs + +## Description + +Hi +Your lib NumSharp was inspired me and i tried to write a other approach of NumPy more easy to use. +The big idea is the Lazy Loading for the front end and this is my repo. +https://github.com/aidevnn/DesertLand + +My lib isnt optimized for speed at this time, but i can improve it with ease by rewritting NDarray backend class and methods WITHOUT changing nothing from the NDview struct frontend which use the lazy loading. + +Actually your Backend is very very powerfull and maybe the frontend can be also improved with Lazy Loading. + +Best regards. + +## Comments + +### Comment 1 by @Oceania2018 (2019-08-01T13:46:01Z) + +@aidevnn Join us, build Deep Learning library based on current work. + +### Comment 2 by @aidevnn (2019-08-01T13:52:23Z) + +I started to fork your repo, it takes me some month to understand in deep your great work. +Best regards. + +### Comment 3 by @Nucs (2019-08-01T15:01:17Z) + +Hey @aidevnn, Thank you. +A. Are you aware we are rewriting our backend in a [separate branch](https://github.com/SciSharp/NumSharp/tree/unmanaged-bytes-storage)? +B. Can you elaborate more about what do you mean by a front-end lazy loading? +If I understand correctly, lazy-loading is something that numpy does not implement therefore if you wish to contribute a lazy-loading front-end when NumSharp is the backend - it'll have to be in a seperate project. + +### Comment 4 by @aidevnn (2019-08-01T19:23:20Z) + +Hello @Nucs + +A. Ok a devel branch is more collaborative than a fork + +B. Lazy Loading can separate the SharpNum library onto frontend with simple to write specification which will be used by the rest of SciSharp ML/AI framework and the pure SharpNum backend for fast and speed computation. The SciSharp ML/AI team can write their own unit test to integrate SharpNum progression. +Lazy Loading is a design pattern wich allow to build complex expressions and he acts sometime like -proxy-. It is also a possible abstraction for integrating multiple different backend but it isnt a good idea at this moment for the framework SciSharp. + +For example, the expression +NDproxy d = a+2*b+np.log(c); +NDarray e = d; +will only be evaluated during the implicit type conversion. +I am a self taugh and i discovered the lazy loading just now to reduce computation. I have some intuition about some other usage of the Lazy Loading, but i cannot explain it. + +### Comment 5 by @Oceania2018 (2019-08-01T19:35:35Z) + +@aidevnn Is `NDProxy` like a kind of Expression/ Func/ Delegate ? It can be executed after all operations have been decided ? + +### Comment 6 by @aidevnn (2019-08-01T19:56:43Z) + +@Oceania2018 Yes it is a struct that can be defined like this during internal computation of the backend +``` +NDproxy a = new NDproxy(()=>ndArray0) +``` + +Its contains only one field / property : +``` +Func fnc +``` +which can be called explicitly +``` +NDarray b = a.fnc() +``` +during internal computation of the backend +or implicitly during type conversion by the frontend. + +In my repo i used delegate + struct. +https://github.com/aidevnn/DesertLand/blob/master/NDarray/NDview.cs#L4 + +### Comment 7 by @Nucs (2019-08-01T20:04:54Z) + +@aidevnn +A. You can still use that branch from a fork +B. Thanks for laying it out for me, I am too a self taught. +Honestly - there is no fast way to stack lazy loading ops. Any basic implementation in C++ will surpass C#'s performance by far. +Your best luck is to put efforts in [Tensorflow.NET](https://github.com/SciSharp/TensorFlow.NET) since tensorflow holds a somewhat similar API to numpy and is capable of computation on a GPU and it provides a pretty impressive performance (both CPU and GPU). + +if you do insist on writing it on your own then you better get started with IL generation that will link the math ops together. +Mainly because every math-op method you delegate to the next math-op method is adding more overhead than you would think. + +`NumSharp` itself is not the fastest it can be. Any library that utilizes the performance of a low-level languages will be faster than our unmanaged algorithms. + +### Comment 8 by @aidevnn (2019-08-01T20:11:27Z) + +@Nucs you are right! Lazy Loading adds some stacks operations because its a kind of managing expression pattern. +Managing code have advantage for simplifying coding and maintenance, but with loss of speed and performance. Its a tradeoff. + +### Comment 9 by @aidevnn (2019-08-02T19:38:38Z) + +@Nucs The idea behind the lazy loading is to introduce step by step some symbolic neural network algorithms with the numerical algorithms. +For beginning, a precompilation (or may be caching) of all requirement like shape / strides / slices can be done without recreating them each time and its my first objectif. I will let you being informed on my progress + +### Comment 10 by @aidevnn (2019-08-03T02:50:11Z) + +I forget to comment an important thing about some counters. +``` +var a = ND.Uniform(1, 10, 4, 4); // Counters. DataAccess:16 / MethCall:16 +var b = 3 * ND.Sq(a - 1) - 4; // Counters. DataAccess:16 / MethCall:80 +var c = 3 * ND.Sq(a - 1) - 4 * ND.Sqrt(a + 5); // Counters. DataAccess:32 / MethCall:144 +``` +In the above expression, my actual code and symbolic approch reduce rawdata access only to one time for expression b. Also in a more complexe expression, the lazy loading reduce the data access to the minimum effort for expression c. But i am trying to solve some performances problems. + +We can say that a lazy loading pattern can improve the performance in theory but it introduces some other execution stack problems. I will continue to search how to take advantage of it. + +### Comment 11 by @aidevnn (2019-09-25T17:58:40Z) + +I discovered in this article +https://techdecoded.intel.io/resources/parallelism-in-python-directing-vectorization-with-numexpr/#gs.63gvwl + +Numexpr : it is very usefull and it already use lazy-loading and a lot of symbolics optimisations to enhance performance. diff --git a/docs/issues/issue-0340-memory-limitations.md b/docs/issues/issue-0340-memory-limitations.md new file mode 100644 index 000000000..3290d5ee7 --- /dev/null +++ b/docs/issues/issue-0340-memory-limitations.md @@ -0,0 +1,31 @@ +# #340: Memory Limitations + +- **URL:** https://github.com/SciSharp/NumSharp/issues/340 +- **State:** OPEN +- **Author:** @Nucs +- **Created:** 2019-08-08T15:39:23Z +- **Updated:** 2019-08-12T13:39:23Z +- **Labels:** enhancement +- **Assignees:** @Nucs + +## Description + +Allocation currently supports up to 2^32 bytes due to using int and not IntPtr and long. + +## Comments + +### Comment 1 by @Nucs (2019-08-08T15:52:05Z) + +Unit test +```C# +[TestMethod] +public void MyTestMethod() +{ + NDArray x = np.zeros(new Shape(600, 1000, 1000), np.float32); +} +``` + +### Comment 2 by @Nucs (2019-08-12T13:38:48Z) + +Ported UnmanagedMemoryBlock and ArraySlice to use long in commit https://github.com/SciSharp/NumSharp/commit/539683f23af53a8b1e31023f8472880cbcc69517 . +Next is to port Shape to use long and all the algorithms with it. Mainly refactoring job diff --git a/docs/issues/issue-0341-ndarray-string-problem.md b/docs/issues/issue-0341-ndarray-string-problem.md new file mode 100644 index 000000000..41ca50483 --- /dev/null +++ b/docs/issues/issue-0341-ndarray-string-problem.md @@ -0,0 +1,30 @@ +# #341: NDArray string problem + +- **URL:** https://github.com/SciSharp/NumSharp/issues/341 +- **State:** OPEN +- **Author:** @lokinfey +- **Created:** 2019-08-26T02:39:33Z +- **Updated:** 2019-08-28T21:45:29Z +- **Labels:** missing feature/s +- **Assignees:** @Nucs + +## Description + +I try to use + var bb8List = new NDArray(typeof(string) , new Shape(bb8Num)); + +but it show error like this + +Exception has occurred: CLR/System.NotSupportedException +An unhandled exception of type 'System.NotSupportedException' occurred in NumSharp.Core.dll: 'Specified method is not supported.' + at NumSharp.Backends.Unmanaged.ArraySlice.Allocate(Type elementType, Int32 count, Boolean fillDefault) + at NumSharp.Backends.UnmanagedStorage.Allocate(Shape shape, Type dtype, Boolean fillZeros) + at NumSharp.NDArray..ctor(Type dtype, Shape shape) + at TFDemo.Program.Main(String[] args) in /Users/lokinfey/Desktop/File/Proj/AI/tensorflownet/code/TFDemo/Program.cs:line 61 + +## Comments + +### Comment 1 by @Nucs (2019-08-26T13:02:40Z) + +We currently do not support NDArray of string because `System.String` is not an unmanaged object which causes multiple problems with our current backend architecture since strings can have different sizes. +We do plan to implement it ASAP. diff --git a/docs/issues/issue-0343-built-in-system.drawing.image-and-bitmap-methods.md b/docs/issues/issue-0343-built-in-system.drawing.image-and-bitmap-methods.md new file mode 100644 index 000000000..0f70b93b8 --- /dev/null +++ b/docs/issues/issue-0343-built-in-system.drawing.image-and-bitmap-methods.md @@ -0,0 +1,44 @@ +# #343: Built-in System.Drawing.Image and Bitmap methods + +- **URL:** https://github.com/SciSharp/NumSharp/issues/343 +- **State:** OPEN +- **Author:** @Nucs +- **Created:** 2019-09-01T13:01:21Z +- **Updated:** 2019-11-05T17:00:36Z +- **Labels:** enhancement +- **Assignees:** @Nucs + +## Description + +Theres a repeating need for methods to load Image to bitmap, we should provide performant builtin API for that. + +EDIT 1: +System.Drawing.Bitmap are now supported by a separate package, [read more](https://github.com/SciSharp/NumSharp/wiki/Bitmap-Extensions). + +## Comments + +### Comment 1 by @Oceania2018 (2019-09-01T13:06:07Z) + +Yes, many people need it. It helps. But that will make NumSharp introduce extra dependency. Or we just add file.read to bytes interface ? + +### Comment 2 by @Nucs (2019-09-01T13:09:39Z) + +Yes, `System.Drawing.Image` package. +I'm thinking about `new NDArray(System.Drawing.Image)` and `np.array(System.Drawing.Image)` or something of that sort. + +### Comment 3 by @sdg002 (2019-09-10T09:02:37Z) + +Thanks for all the hard work. +My 2 cents. It might be worth considering the pros and cons of keeping `System.Drawing.Image` outside of the core `NDArray` through a factory approach. At some later date you might consider introducing a factory class for images loaded using `ImageSharp` or some other imaging library. + +This approach will not cut down your code, however it might spare end developers from having to add too many NUGET references. Gives them the opportunity to progressively encompass more packages as the needs grow. E.g. In my company, `System.Drawing` is not really favored because it does not work on Azure functions due to GDI+ restrictions of Azure function sandbox. + + +### Comment 4 by @Nucs (2019-09-11T20:30:52Z) + +@sdg002 Thanks for the note, +I've decided to create separate projects and nuget packages for `NumSharp.Bitmap` (published) and `NumSharp.ImageSharp` (WIP). + +### Comment 5 by @Oceania2018 (2019-10-04T11:11:03Z) + +Is it possible to integrate OpenCvSharp into NumSharp.ImageSharp? diff --git a/docs/issues/issue-0349-scipy.signal.md b/docs/issues/issue-0349-scipy.signal.md new file mode 100644 index 000000000..11bfcab50 --- /dev/null +++ b/docs/issues/issue-0349-scipy.signal.md @@ -0,0 +1,90 @@ +# #349: Scipy.Signal + +- **URL:** https://github.com/SciSharp/NumSharp/issues/349 +- **State:** OPEN +- **Author:** @natank1 +- **Created:** 2019-09-21T07:53:55Z +- **Updated:** 2019-09-22T15:17:25Z +- **Labels:** missing feature/s + +## Description + +Hi + +Is there a way to run spectogram with scipy.signal in Using this library? + +## Comments + +### Comment 1 by @Nucs (2019-09-21T09:38:28Z) + +No, Unfortunately we do not have implementations of [scipy.signal](https://docs.scipy.org/doc/scipy/reference/signal.html). +I would suggest you to use [Numpy.NET](https://github.com/SciSharp/Numpy.NET) as it wraps numpy directly and provides all its features. + +### Comment 2 by @natank1 (2019-09-21T09:48:29Z) + +Including SciPy ? + +### Comment 3 by @Nucs (2019-09-21T10:43:05Z) + +Scipy is the name of the company that developed numpy... +אנחנו תומכים בעיקר באלגברה לינארית שזה בערך השימוש הכי נפוץ בסיפריה והכרחי בכדי להפעיל את הסיפריה טנסורפלוו +הספריה [נמפיינט ](https://github.com/SciSharp/Numpy.NET) תומכת בכל הפיצ'רים של נמפיי + +### Comment 4 by @natank1 (2019-09-21T13:03:15Z) + +Sorry again + +When you say the Scipy exists you mean we have an API for it under +Numpy.Net (I can find such ), +or we can take the python code of scipy and arrange it in away that +Numpy.net will handle this? +Sorry again fro bothering + +On Sat, Sep 21, 2019 at 12:38 PM Eli Belash +wrote: + +> No, Unfortunately we do not have implementations of scipy.signal +> . +> I would suggest you to use Numpy.NET +> as it wraps numpy directly and +> provides all its features. +> +> — +> You are receiving this because you authored the thread. +> Reply to this email directly, view it on GitHub +> , +> or mute the thread +> +> . +> + + +### Comment 5 by @Nucs (2019-09-21T14:06:35Z) + +Scipy is the name of the company that published Numpy. When you say Scipy it makes no sense. +When I comment I add URLs, just click on my mentions in the comments above of numpy.net or scipy.signal. +Numpy.NET is a different library from NumSharp which uses Pythonnet to call numpy. +Numpy.NET implements ALL numpy's functions but might be sometimes slower because you transfer data from C# to python. + +### Comment 6 by @natank1 (2019-09-21T14:36:13Z) + +So function /class that is written in python sipy.signal , how should be called inumpy.net? + +> Scipy is the name of the company that published Numpy. When you say Scipy it makes no sense. +> When I comment I add URLs, just click on my mentions of numpy.net. +> Numpy.NET is a different library from NumSharp which uses Pythonnet to call numpy. +> Numpy.NET implements ALL numpy's functions but might be sometimes slower because you transfer data from C# to python. +> +> — +> You are receiving this because you authored the thread. +> Reply to this email directly, view it on GitHub, or mute the thread. + + +### Comment 7 by @Nucs (2019-09-21T15:57:10Z) + +I have no clue, This is NumSharp repository. +Read Numpy.NET's readme.md. + +### Comment 8 by @natank1 (2019-09-21T16:06:56Z) + +Thanks! diff --git a/docs/issues/issue-0351-proper-way-to-iterate-using-ienumerable-t.md b/docs/issues/issue-0351-proper-way-to-iterate-using-ienumerable-t.md new file mode 100644 index 000000000..6d0c14454 --- /dev/null +++ b/docs/issues/issue-0351-proper-way-to-iterate-using-ienumerable-t.md @@ -0,0 +1,15 @@ +# #351: Proper way to iterate using IEnumerable + +- **URL:** https://github.com/SciSharp/NumSharp/issues/351 +- **State:** OPEN +- **Author:** @Nucs +- **Created:** 2019-09-28T15:42:47Z +- **Updated:** 2019-09-28T15:42:47Z +- **Labels:** enhancement +- **Assignees:** @Nucs + +## Description + +There should be an approachable way to perform fast `foreach` on a `NDArray`. +Currently `NDArray` implements non-generic `IEnumerable` which returns a boxed value that can be either the `NDArray.dtype` or an `NDArray`. +Boxing causes `O(n)` operations to be significantly slower on large datasets. diff --git a/docs/issues/issue-0360-np.any.md b/docs/issues/issue-0360-np.any.md new file mode 100644 index 000000000..6c85a66ab --- /dev/null +++ b/docs/issues/issue-0360-np.any.md @@ -0,0 +1,21 @@ +# #360: np.any + +- **URL:** https://github.com/SciSharp/NumSharp/issues/360 +- **State:** OPEN +- **Author:** @Oceania2018 +- **Created:** 2019-10-05T23:50:58Z +- **Updated:** 2019-10-12T11:16:22Z +- **Labels:** enhancement +- **Assignees:** @Nucs + +## Description + +Test whether any array element along a given axis evaluates to True. +https://docs.scipy.org/doc/numpy/reference/generated/numpy.any.html + +## Comments + +### Comment 1 by @Nucs (2019-10-12T11:16:22Z) + +Added in https://github.com/SciSharp/NumSharp/commit/f4ee1353e1d159a9e9334dcb38ee4f005160808c , +Remaining open because specific axis support is not implemented yet. diff --git a/docs/issues/issue-0361-mixing-indices-and-slices-in-ndarray.md b/docs/issues/issue-0361-mixing-indices-and-slices-in-ndarray.md new file mode 100644 index 000000000..f6892c4b0 --- /dev/null +++ b/docs/issues/issue-0361-mixing-indices-and-slices-in-ndarray.md @@ -0,0 +1,101 @@ +# #361: Mixing indices and slices in NDArray[...] + +- **URL:** https://github.com/SciSharp/NumSharp/issues/361 +- **State:** OPEN +- **Author:** @Oceania2018 +- **Created:** 2019-10-06T03:22:07Z +- **Updated:** 2019-10-12T11:35:37Z +- **Labels:** enhancement +- **Assignees:** @henon, @Nucs + +## Description + +Is it possible to suppor mixed index/ slice? This is what numpy doing: + +![image](https://user-images.githubusercontent.com/1705364/66263777-49d4dc00-e7be-11e9-8fba-fd1014cbd922.png) + +Currently, it doesn't support: + +![image](https://user-images.githubusercontent.com/1705364/66263800-7688f380-e7be-11e9-933a-2dfeb71f98f3.png) + + +## Comments + +### Comment 1 by @Nucs (2019-10-06T06:31:04Z) + +```C# +label[i][Slice.Index(yind), Slice.Index(xind), Slice.Index(iou_mast), new Slice(0, 4)] = bbox_xywh; +``` + +### Comment 2 by @henon (2019-10-06T11:48:20Z) + +or + +```C# +label[i][$"{yind}, {xind}, {iou_mast}, 0:4"] = bbox_xywh; +``` + +Btw: we could try implicitly convert from int to Slice.Index(int) + + +### Comment 3 by @Nucs (2019-10-06T12:30:22Z) + +Worth mentioning that using a string inside a loop or O(n) will affect performance. +Regex parsing is not lightning fast. + +### Comment 4 by @Oceania2018 (2019-10-06T13:51:40Z) + +The `iou_mask` is `NDArray`. +![image](https://user-images.githubusercontent.com/1705364/66269842-048ec980-e813-11e9-8e33-fa624271ace2.png) + +It means we use different ways in different dimension to select elements. + +One approach my idea is: +Define a `IIndex` interface, `NDArray` and `Slice` implement `IIndex`. +update +```csharp +NDArray this[params IIndex[] selectors] +{ + get; set; +} +``` + + +### Comment 5 by @Nucs (2019-10-06T14:40:04Z) + +Too messy, plus it won't solve your problem.. you can't implement implicit cast from `int` to `IIndex`. +Having index `nd[int, int, NDArray, Slice]` doesn't make sense. Our algorithm accepts either only slices or only ints. +`nd[NDArray[]]` is not for Indexing, it is for Masking. +Right now use `Slice.Index`, in the future I'll implement implicit castings to `Slice`. + +### Comment 6 by @henon (2019-10-06T15:04:49Z) + +We might have to extend the slicing algorithm to accept a mask (i.e. Slice.Mask(boolean_array)). He is porting Python code so it seems Python allows mixing of indices and masks. + +### Comment 7 by @Nucs (2019-10-06T15:06:57Z) + +Masking has a complete separate algorithm from slicing. In fact they don't have anything in common (function-wise). + +### Comment 8 by @Oceania2018 (2019-10-06T16:36:44Z) + +Not only for masking, but also for any 1d array. We don’t have to have int to IIndex implicitly, we can use np.array(1) as alternative. + +The goal is having people can use 1d or Slice, Scalar to select and mask elements in appropriate dimensions. + +### Comment 9 by @Oceania2018 (2019-10-12T00:13:21Z) + +@henon This situation doesn't work: + +`iou_mask` is `NDArray`, `yind` and `xind` are `int`: +![image](https://user-images.githubusercontent.com/1705364/66691314-0addd500-ec5b-11e9-816f-be0dd63f9d0a.png) + +![image](https://user-images.githubusercontent.com/1705364/66691447-0fef5400-ec5c-11e9-8368-d9f01b5ea440.png) + + +### Comment 10 by @henon (2019-10-12T08:32:57Z) + +I know, @Nucs is removing the int[] indexer in favor of an object[] indexer so that implicit conversion operators don't get in the way and we can reliably forward the different use cases into the right implementatons ( slicing if no NDarrays are part of the params and index extraction/masking otherwise) + +### Comment 11 by @Nucs (2019-10-12T11:35:37Z) + +@Oceania2018 Please verify if it works on master branch. diff --git a/docs/issues/issue-0362-implicit-operators-for.md b/docs/issues/issue-0362-implicit-operators-for.md new file mode 100644 index 000000000..f4ab47b99 --- /dev/null +++ b/docs/issues/issue-0362-implicit-operators-for.md @@ -0,0 +1,43 @@ +# #362: Implicit operators for >, >=, <, <= + +- **URL:** https://github.com/SciSharp/NumSharp/issues/362 +- **State:** OPEN +- **Author:** @deepakkumar1984 +- **Created:** 2019-10-06T07:49:57Z +- **Updated:** 2019-10-12T00:33:30Z +- **Labels:** help wanted, missing feature/s + +## Description + +x == 1 gives a result which is NDArray as expected + +x>1 and other operators like >=, <, <= give null result + +## Comments + +### Comment 1 by @Nucs (2019-10-06T07:51:06Z) + +`np.where` is yet to be implemented. + +### Comment 2 by @deepakkumar1984 (2019-10-06T08:55:19Z) + +I have done some work with np.where in this commit https://github.com/deepakkumar1984/NumSharp/commit/8bfa4f2484fc974e10e250f6b7ef5da0f381b683 +the first parameter is a condition for which we need to finish the implementation under https://github.com/SciSharp/NumSharp/tree/master/src/NumSharp.Core/Operations/Elementwise + +Most of the code in commented and return as null + +### Comment 3 by @Nucs (2019-10-06T09:03:06Z) + +I misunderstood [np.where](https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html), I was sure that the first argument is something of a sort of Expression>. +I'll need to implement each (comparing) operator separately and np.where will work then. +I'll open up a separate issue for that. This might take a while as I'm unavailable (sunday is not a day off in my country 😅) + +### Comment 4 by @Oceania2018 (2019-10-12T00:03:42Z) + +Same thing happened for me, shouldn't return null: +![image](https://user-images.githubusercontent.com/1705364/66691132-c6056e80-ec59-11e9-890e-29e516a00a1f.png) + + +### Comment 5 by @Nucs (2019-10-12T00:33:30Z) + +Null because it is not implemented. diff --git a/docs/issues/issue-0363-add-nditerator-t-overload-with-support-for-specific-axis.md b/docs/issues/issue-0363-add-nditerator-t-overload-with-support-for-specific-axis.md new file mode 100644 index 000000000..e6dc03bb2 --- /dev/null +++ b/docs/issues/issue-0363-add-nditerator-t-overload-with-support-for-specific-axis.md @@ -0,0 +1,18 @@ +# #363: Add `NDIterator` overload with support for specific axis. + +- **URL:** https://github.com/SciSharp/NumSharp/issues/363 +- **State:** OPEN +- **Author:** @Nucs +- **Created:** 2019-10-12T11:11:32Z +- **Updated:** 2019-10-12T11:11:32Z +- **Labels:** missing feature/s + +## Description + +NDIterator is useful, we should add an overload that handles specific axis iterator: +usage: +```C# +new NDIterator(ndarray, axis: 1); +``` + +Also add an overload to extension `ndarray.AsIterator(axis: 1);` diff --git a/docs/issues/issue-0365-np.nonzero.md b/docs/issues/issue-0365-np.nonzero.md new file mode 100644 index 000000000..65ae16934 --- /dev/null +++ b/docs/issues/issue-0365-np.nonzero.md @@ -0,0 +1,14 @@ +# #365: np.nonzero + +- **URL:** https://github.com/SciSharp/NumSharp/issues/365 +- **State:** OPEN +- **Author:** @Oceania2018 +- **Created:** 2019-10-12T19:49:12Z +- **Updated:** 2019-10-12T19:49:12Z +- **Labels:** enhancement +- **Assignees:** @Nucs + +## Description + +Return the indices of the elements that are non-zero. +https://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html diff --git a/docs/issues/issue-0366-masking-ndarray-nd.md b/docs/issues/issue-0366-masking-ndarray-nd.md new file mode 100644 index 000000000..37375c010 --- /dev/null +++ b/docs/issues/issue-0366-masking-ndarray-nd.md @@ -0,0 +1,26 @@ +# #366: Masking (ndarray[nd]) + +- **URL:** https://github.com/SciSharp/NumSharp/issues/366 +- **State:** OPEN +- **Author:** @henon +- **Created:** 2019-10-12T19:49:33Z +- **Updated:** 2019-10-12T19:51:59Z + +## Description + +Doesn't work in ndarray[nd]? + +![image](https://user-images.githubusercontent.com/1705364/66706800-4335ef80-ecfd-11e9-9a4d-4631255241d8.png) + +```shell +System.NotSupportedException: Specified method is not supported. + at NumSharp.NDArray.set_Item(Object[] indices_or_slices, NDArray value) in D:\SciSharp\NumSharp\src\NumSharp.Core\Selection\NDArray.Indexing.cs:line 202 +``` + +_Originally posted by @Oceania2018 in https://github.com/SciSharp/NumSharp/issues/359#issuecomment-541355337_ + +## Comments + +### Comment 1 by @henon (2019-10-12T19:51:59Z) + +we need this for it: #365 diff --git a/docs/issues/issue-0368-masking-a-slice-...-returns-null.md b/docs/issues/issue-0368-masking-a-slice-...-returns-null.md new file mode 100644 index 000000000..b4dbc44be --- /dev/null +++ b/docs/issues/issue-0368-masking-a-slice-...-returns-null.md @@ -0,0 +1,45 @@ +# #368: Masking a slice ("...") returns null + +- **URL:** https://github.com/SciSharp/NumSharp/issues/368 +- **State:** OPEN +- **Author:** @ohjerm +- **Created:** 2019-11-12T09:48:54Z +- **Updated:** 2019-11-12T14:56:29Z +- **Assignees:** @henon, @Nucs + +## Description + +``` +NDArray positive_boxes = batch_item["...,0"] != 0; +Debug.Log(positive_boxes); +``` +The output is Null. In numpy I would expect an boolean mask NDArray of shape (...,1) here, right? Is masking implemented another way? + +I'm on the latest nuget release (0.20.4) if that helps. + +## Comments + +### Comment 1 by @henon (2019-11-12T14:16:57Z) + +@ChaiKnight: I can not work with the example you have given here to reproduce the problem. Can you please write me a piece of code that is complete and reproduces the bug? + +Like this: + +```C# +var x=np.arange(10).reshape(2,5); +var y=x["...,0"]; +// what does it give and what do you expect instead? +``` +I don't know your setup, the above is just an example. Thanks. + +### Comment 2 by @ohjerm (2019-11-12T14:42:55Z) + +I don't know how much more I can give you without just dumping my entire codebase on you. My batch_item is an NDArray of size (7160,6). When I test I currently just feed it zeroes, so it basically looks like np.zero((7160,6)) to me when I print it. + +Your example seems to work just fine, I am able to print out [0,5], but I am also able to print out a long array of zeroes when I do `Debug.Log(batch_item["...,0"]);`, so somewhere in the masking process is where it goes wrong. I figured the masking should return an empty array like numpy does, of size (0,6). Is that at all possible? + + + +### Comment 3 by @henon (2019-11-12T14:55:51Z) + +Alright, I understand. This is a known problem then. Masking is currently under construction. @Nucs is working on it. diff --git a/docs/issues/issue-0369-slicing-notsupportedexception.md b/docs/issues/issue-0369-slicing-notsupportedexception.md new file mode 100644 index 000000000..19ec472cc --- /dev/null +++ b/docs/issues/issue-0369-slicing-notsupportedexception.md @@ -0,0 +1,15 @@ +# #369: Slicing NotSupportedException + +- **URL:** https://github.com/SciSharp/NumSharp/issues/369 +- **State:** OPEN +- **Author:** @Oceania2018 +- **Created:** 2019-11-23T18:48:33Z +- **Updated:** 2019-11-23T18:48:33Z +- **Labels:** missing feature/s +- **Assignees:** @Nucs + +## Description + +Runing YOLO with `ndarray-indexing` branch. +![image](https://user-images.githubusercontent.com/1705364/69483632-54d7e000-0def-11ea-99b4-3b2863490b39.png) + diff --git a/docs/issues/issue-0372-clustering-example.md b/docs/issues/issue-0372-clustering-example.md new file mode 100644 index 000000000..064248808 --- /dev/null +++ b/docs/issues/issue-0372-clustering-example.md @@ -0,0 +1,24 @@ +# #372: Clustering Example + +- **URL:** https://github.com/SciSharp/NumSharp/issues/372 +- **State:** OPEN +- **Author:** @turowicz +- **Created:** 2019-12-05T13:32:43Z +- **Updated:** 2019-12-07T17:51:04Z +- **Labels:** help wanted, missing feature/s + +## Description + +Do we have a C# version of something like this? +https://github.com/lars76/kmeans-anchor-boxes + + +## Comments + +### Comment 1 by @turowicz (2019-12-05T13:48:45Z) + +cc @Nucs @Oceania2018 + +### Comment 2 by @turowicz (2019-12-05T14:13:32Z) + +It seems that C# `np.random.choice` has different arguments than the original one. diff --git a/docs/issues/issue-0373-np.median.md b/docs/issues/issue-0373-np.median.md new file mode 100644 index 000000000..75583bced --- /dev/null +++ b/docs/issues/issue-0373-np.median.md @@ -0,0 +1,18 @@ +# #373: np.median + +- **URL:** https://github.com/SciSharp/NumSharp/issues/373 +- **State:** OPEN +- **Author:** @turowicz +- **Created:** 2019-12-05T13:42:11Z +- **Updated:** 2019-12-07T17:49:43Z +- **Labels:** help wanted, missing feature/s + +## Description + +What is the np.median equivalent? + +## Comments + +### Comment 1 by @turowicz (2019-12-05T13:48:32Z) + +cc @Nucs @Oceania2018 diff --git a/docs/issues/issue-0374-np.append.md b/docs/issues/issue-0374-np.append.md new file mode 100644 index 000000000..a4d135db6 --- /dev/null +++ b/docs/issues/issue-0374-np.append.md @@ -0,0 +1,19 @@ +# #374: np.append + +- **URL:** https://github.com/SciSharp/NumSharp/issues/374 +- **State:** OPEN +- **Author:** @solarflarefx +- **Created:** 2019-12-05T20:29:23Z +- **Updated:** 2019-12-07T17:49:30Z +- **Labels:** help wanted, missing feature/s + +## Description + +Is there an equivalent method to np.append? If not, what is the best workaround? + +## Comments + +### Comment 1 by @Nucs (2019-12-07T17:49:22Z) + +Maybe np.concatenate, np.vstack or np.stack will help you. They might require reshaping to emulate np.append. + diff --git a/docs/issues/issue-0375-slice-assignment.md b/docs/issues/issue-0375-slice-assignment.md new file mode 100644 index 000000000..591b7e203 --- /dev/null +++ b/docs/issues/issue-0375-slice-assignment.md @@ -0,0 +1,25 @@ +# #375: Slice assignment? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/375 +- **State:** OPEN +- **Author:** @solarflarefx +- **Created:** 2019-12-07T17:40:06Z +- **Updated:** 2019-12-07T17:48:07Z +- **Labels:** missing feature/s +- **Assignees:** @Nucs + +## Description + +If you declare an array of a specific size, is there a way to assign slices of arrays? + +For example, if x is an NDArray of size (5,2,3,4), is there a way to do something like the following? + +NDArray a = some NDArray of size (1,2,3,4) + +x[0,:,:,:] = a + +## Comments + +### Comment 1 by @Nucs (2019-12-07T17:47:58Z) + +Related to https://github.com/SciSharp/NumSharp/issues/369 https://github.com/SciSharp/NumSharp/issues/368 https://github.com/SciSharp/NumSharp/issues/366 and is work in progress. diff --git a/docs/issues/issue-0378-add-np.frombuffer.md b/docs/issues/issue-0378-add-np.frombuffer.md new file mode 100644 index 000000000..bf9990b23 --- /dev/null +++ b/docs/issues/issue-0378-add-np.frombuffer.md @@ -0,0 +1,14 @@ +# #378: Add np.frombuffer + +- **URL:** https://github.com/SciSharp/NumSharp/issues/378 +- **State:** OPEN +- **Author:** @Nucs +- **Created:** 2019-12-15T19:39:07Z +- **Updated:** 2019-12-15T19:39:07Z +- **Labels:** enhancement, missing feature/s +- **Assignees:** @Nucs + +## Description + +This is how we should wrap a pointer to a certain memory block. +https://docs.scipy.org/doc/numpy/reference/generated/numpy.frombuffer.html diff --git a/docs/issues/issue-0383-is-there-any-way-to-convert-numsharp.ndarray-to-numpy.ndarray.md b/docs/issues/issue-0383-is-there-any-way-to-convert-numsharp.ndarray-to-numpy.ndarray.md new file mode 100644 index 000000000..d8efaf077 --- /dev/null +++ b/docs/issues/issue-0383-is-there-any-way-to-convert-numsharp.ndarray-to-numpy.ndarray.md @@ -0,0 +1,94 @@ +# #383: is there any way to convert NumSharp.NDArray to Numpy.NDarray? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/383 +- **State:** OPEN +- **Author:** @lelelemonade +- **Created:** 2020-01-06T10:31:01Z +- **Updated:** 2023-02-24T10:15:20Z + +## Description + +_No description provided._ + +## Comments + +### Comment 1 by @Nucs (2020-01-06T11:15:15Z) + +Me and @henon have collaborated just two days ago on a solution for that, +The trick is to create a python scope, load a script that takes in a pointer-length and returns an np.ndarray +Remember! you have to keep reference to the original NDArray, otherwise the NDArray will be disposed and will release the memory. (@henon is there a tag field we can use in NDarray?) + +Note: the code below is psuedo, the rest of the code can be found here: [ConsoleApp9.zip](https://github.com/SciSharp/NumSharp/files/4025804/ConsoleApp9.zip) + + +*numpy_interop.py* as embedded resource +```python +import numpy as np +import ctypes + +def to_numpy(ptr, bytes, dtype, shape): + return np.frombuffer((ctypes.c_uint8*(bytes)).from_address(ptr), dtype).reshape(shape) + +``` + +*PythonExtensions.cs* +```C# +public static class PythonExtensions { + + ... + private static PyScope NumpyInteropScope; + private static PyObject NumpyConverter; + + public static unsafe NDarray ToNumpyNET(this NDArray nd) { + using (Py.GIL()) { + if (NumpyInteropScope == null) { + NumpyInteropScope = Py.CreateScope(); + NumpyInteropScope.ExecResource("numpy_interop.py"); + NumpyConverter = NumpyInteropScope.GetFunction("to_numpy"); + } + + return new NDarray(NumpyConverter.Invoke(new PyLong((long) nd.Unsafe.Address), + new PyLong(nd.size * nd.dtypesize), + new PyString(nd.dtype.Name.ToLowerInvariant()), + new PyTuple(nd.shape.Select(dim => (PyObject) new PyLong(dim)).ToArray()))); + } + } +} +``` + +*main.cs* +```C# +using numsharp_np = NumSharp.np; +using numpy_np = Numpy.np; +static void Main(string[] args) { + var numsharp_nd = numsharp_np.arange(10); + var numpy_nd = numsharp_nd.ToNumpyNET(); + numpy_nd[1] = (NDarray) 5; + Debug.Assert(numsharp_nd[1].array_equal(5)); + Console.WriteLine("numsharp_nd[1].array_equal(5) is indeed true!"); +} +``` + +### Comment 2 by @Nucs (2020-01-06T11:35:04Z) + +Added some changes that will make sure the NDarray will hold reference to the NDArray as long as the PyObject doesnt change internally. + +[ConsoleApp9.zip](https://github.com/SciSharp/NumSharp/files/4025864/ConsoleApp9.zip) + + + +### Comment 3 by @henon (2020-01-06T15:13:53Z) + +> Remember! you have to keep reference to the original NDArray, otherwise the NDArray will be disposed and will release the memory. (@henon is there a tag field we can use in NDarray?) +> + +Not yet, but I will add one in Numpy.NET and support this. + + +### Comment 4 by @davidvct (2023-02-24T04:14:22Z) + +Hi, could you provide instruction on how to use the ConsoleApp9.zip? And does it able to convert Numpy array back to NumSharp array? + +### Comment 5 by @henon (2023-02-24T10:15:20Z) + +@davidvct, if I remember correctly I have added support for copying data to and from Numpy.NET like @Nucs did in this solution. Read this to see how: https://github.com/SciSharp/Numpy.NET#create-a-numpy-array-from-a-c-array-and-vice-versa diff --git a/docs/issues/issue-0384-save-ndarray-as-png-image.md b/docs/issues/issue-0384-save-ndarray-as-png-image.md new file mode 100644 index 000000000..7de212eef --- /dev/null +++ b/docs/issues/issue-0384-save-ndarray-as-png-image.md @@ -0,0 +1,43 @@ +# #384: Save NDArray as png image + +- **URL:** https://github.com/SciSharp/NumSharp/issues/384 +- **State:** OPEN +- **Author:** @solarflarefx +- **Created:** 2020-01-12T23:54:22Z +- **Updated:** 2020-01-13T00:30:55Z + +## Description + +I am looking to save an NDArray to an image. + +In Python code, I used the io.imsave() method from skimage.io. + +I tried using the approach shown here: https://stackoverflow.com/questions/5113919/how-to-convert-2-d-array-into-image-in-c-sharp + +Basically it uses the the Bitmap method in System.Drawing.Bitmap + +Is this the correct way to do this? + +I tried converting the NDArray to a C# multidimensional array and then using the following type of code: + +`Bitmap bitmap; +unsafe +{ + fixed (int* intPtr = &integers[0,0]) + { + bitmap = new Bitmap(width, height, stride, PixelFormat.Format32bppRgb, new IntPtr(intPtr)); + } +}` + +However, I get this error on the "bitmap =" line: System.ArgumentException: 'Parameter is not valid.' + +Ultimately I would like to compare the output from my python code to the output from my C# code to ensure that they are doing the same thing. As I stated, in Python I saved a multidimensional array to png. My thought was to do the same in C# using NumSharp, and then comparing the output images. + +Thanks in advance. + +## Comments + +### Comment 1 by @Nucs (2020-01-13T00:30:00Z) + +Take a look at our [wiki](https://github.com/SciSharp/NumSharp/wiki/Bitmap-Extensions). We provide support for converting/wrapping NDArray to System.Drawing.Bitmap. +If it is for the purpose of only saving then specify argument `copy: false` diff --git a/docs/issues/issue-0386-how-to-read-.csv-file-with-numsharp.md b/docs/issues/issue-0386-how-to-read-.csv-file-with-numsharp.md new file mode 100644 index 000000000..b0e0d4355 --- /dev/null +++ b/docs/issues/issue-0386-how-to-read-.csv-file-with-numsharp.md @@ -0,0 +1,18 @@ +# #386: how to read .csv file with Numsharp? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/386 +- **State:** OPEN +- **Author:** @guang7400613 +- **Created:** 2020-01-15T13:56:28Z +- **Updated:** 2020-01-15T14:09:27Z + +## Description + +how to read .csv file or .txt file wiht Numsharp(np) in C#? +is it np.load(string filename)? + +## Comments + +### Comment 1 by @Oceania2018 (2020-01-15T14:09:27Z) + +Should use Pandas.NET diff --git a/docs/issues/issue-0390-how-to-create-an-ndarray-from-pointer-and-nptypecode.md b/docs/issues/issue-0390-how-to-create-an-ndarray-from-pointer-and-nptypecode.md new file mode 100644 index 000000000..2dfc38e4b --- /dev/null +++ b/docs/issues/issue-0390-how-to-create-an-ndarray-from-pointer-and-nptypecode.md @@ -0,0 +1,52 @@ +# #390: How to create an NDArray from pointer and NPTypeCode? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/390 +- **State:** OPEN +- **Author:** @LarryThermo +- **Created:** 2020-01-24T19:52:51Z +- **Updated:** 2020-01-27T17:13:48Z + +## Description + +First of all thanks for this project. + +My code calls into lower level C++ code and I wish to represent the returned array as an NDArray in C#. I have a pointer to the data, the length of the data in bytes, as well as type code. How would I go about creating an NDArray for this case? Something like: + +NDArray CreateNDArray(void* data,int dataLengthBytes,NPTypeCode typeCode) +{ +var storage = new UnmanagedStorage( "something here" ); +var nda = new NDArray(storage); +return nda; +} + +Thanks, + +Lars + +## Comments + +### Comment 1 by @Oceania2018 (2020-01-24T23:19:00Z) + +@LarryThermo This [snippet of code](https://github.com/SciSharp/SharpCV/blob/792c8744856cff69f06ddfb17c2866d4d18a05db/src/SharpCV/Core/Mat.cs#L128) will help you. + +### Comment 2 by @LarryThermo (2020-01-27T17:13:48Z) + +Thank you. It was helpful. + +Although this works for me I was hoping to find a solution that did not involve maintaining a case statement for all possible types, and instead took in a void* pointer and an NPTypeCode. + +From: Haiping [mailto:notifications@github.com] +Sent: Friday, January 24, 2020 3:19 PM +To: SciSharp/NumSharp +Cc: Rystrom, Larry ; Mention +Subject: Re: [SciSharp/NumSharp] How to create an NDArray from pointer and NPTypeCode? (#390) + +CAUTION: This email originated from outside of Thermo Fisher Scientific. If you believe it to be suspicious, report using the Report Phish button in Outlook or send to SOC@thermofisher.com. + + +@LarryThermo This snippet of code will help you. + +— +You are receiving this because you were mentioned. +Reply to this email directly, view it on GitHub, or unsubscribe. + diff --git a/docs/issues/issue-0396-bitmap.tondarray-problem-with-odd-bitmap-width.md b/docs/issues/issue-0396-bitmap.tondarray-problem-with-odd-bitmap-width.md new file mode 100644 index 000000000..6f6536116 --- /dev/null +++ b/docs/issues/issue-0396-bitmap.tondarray-problem-with-odd-bitmap-width.md @@ -0,0 +1,40 @@ +# #396: Bitmap.ToNDArray problem with odd bitmap width + +- **URL:** https://github.com/SciSharp/NumSharp/issues/396 +- **State:** OPEN +- **Author:** @herrvonregen +- **Created:** 2020-02-06T12:04:28Z +- **Updated:** 2020-02-06T16:44:23Z + +## Description + +Hi everyone. +The official micorsoft documenation for Bitmap.Stride says: + +> The stride is the width of a single row of pixels (a scan line), rounded up to a four-byte boundary. + +This could cause an exception here if the loaded bitmap is RGB with an odd width. +` Buffer.MemoryCopy(src, dst, bmpData.Stride * image.Height, nd.size);` +`var ret = nd.reshape(1, image.Height, image.Width, bmpData.Stride / bmpData.Width);` + +Example: +An RGB image with the size of 227x227 pixels +Stride will be 684. 227*3 = 681 rounded up to four-byte boundary. +Copied data are 155268 bytes. +Reshaped into 277 * 277 * floor(684/227) = 154587 bytes +This will cause an IncorrectShapeException + + + +## Comments + +### Comment 1 by @Nucs (2020-02-06T15:44:37Z) + +You shouldn't work hard, we provide extensions to Bitmap, see [this wiki article](https://github.com/SciSharp/NumSharp/wiki/Bitmap-Extensions). + +### Comment 2 by @herrvonregen (2020-02-06T16:44:23Z) + +Yes, I know but the implementation has the described behavior. +Try it with the picture provided below. +![00001](https://user-images.githubusercontent.com/33056845/73958447-39697500-4908-11ea-8628-33dce6582f17.jpg) + diff --git a/docs/issues/issue-0397-missing-np.tile.md b/docs/issues/issue-0397-missing-np.tile.md new file mode 100644 index 000000000..ed10ed3da --- /dev/null +++ b/docs/issues/issue-0397-missing-np.tile.md @@ -0,0 +1,64 @@ +# #397: Missing np.tile? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/397 +- **State:** OPEN +- **Author:** @QadiymStewart +- **Created:** 2020-02-12T15:55:12Z +- **Updated:** 2020-06-03T13:42:46Z +- **Assignees:** @Nucs + +## Description + +Is np.tile implemented in this library as of yet? + +## Comments + +### Comment 1 by @simonbuehler (2020-05-25T10:25:11Z) + +hi, + +bumped into the same issue, is there a workaround for something like `np.tile(center, (1, 1, 2 * num_anchors));` or maybe even better a working tile implementation? + +### Comment 2 by @QadiymStewart (2020-05-25T14:41:50Z) + +> hi, +> +> bumped into the same issue, is there a workaround for something like `np.tile(center, (1, 1, 2 * num_anchors));` or maybe even better a working tile implementation? + +Switched to https://github.com/Quansight-Labs/numpy.net + +### Comment 3 by @simonbuehler (2020-05-25T14:56:20Z) + +@QadiymStewart thanks for your reply, a pity that tensorflow.net depends on NumSharp so i can't switch :/ +@Oceania2018 are there plans to implement this like in[NumpyDotNet/shape_base.cs](https://github.com/Quansight-Labs/numpy.net/blob/b6ac4af87e21bd561a022ebe067d322b88273157/src/NumpyDotNet/NumpyDotNet/shape_base.cs#L1623) ? + +### Comment 4 by @Oceania2018 (2020-05-25T15:23:08Z) + +@simonbuehler Try to use the built-in functions of tensorflow. https://www.tensorflow.org/api_docs/python/tf/tile + +### Comment 5 by @simonbuehler (2020-05-25T17:54:25Z) + +is there already a nuget with a Tensor -> NDarray method? + +### Comment 6 by @Oceania2018 (2020-05-26T03:38:36Z) + +@simonbuehler You can create tensor directly from Tensor -> NDArray and vice verse. + +### Comment 7 by @simonbuehler (2020-05-26T08:54:41Z) + +just for info, unfortunatly `var center_tiled = tf.tile(temp , temp2);` throws a `NullReferenceException` guess this is a TensorFlow.NET issue, nevertheless a numsharp implementation would be awesome! + +``` + TensorFlow.NET.dll!Tensorflow.Tensor._as_tf_output() Unbekannt + TensorFlow.NET.dll!Tensorflow.ops._create_c_op(Tensorflow.Graph graph, Tensorflow.NodeDef node_def, object[] inputs, Tensorflow.Operation[] control_inputs) Unbekannt + TensorFlow.NET.dll!Tensorflow.Operation.Operation(Tensorflow.NodeDef node_def, Tensorflow.Graph g, Tensorflow.Tensor[] inputs, Tensorflow.TF_DataType[] output_types, Tensorflow.ITensorOrOperation[] control_inputs, Tensorflow.TF_DataType[] input_types, string original_op, Tensorflow.OpDef op_def) Unbekannt + TensorFlow.NET.dll!Tensorflow.Graph.create_op(string op_type, Tensorflow.Tensor[] inputs, Tensorflow.TF_DataType[] dtypes, Tensorflow.TF_DataType[] input_types, string name, System.Collections.Generic.Dictionary attrs, Tensorflow.OpDef op_def) Unbekannt + TensorFlow.NET.dll!Tensorflow.OpDefLibrary._apply_op_helper.AnonymousMethod__0(Tensorflow.ops.NameScope scope) Unbekannt + TensorFlow.NET.dll!Tensorflow.Binding.tf_with(System.__Canon py, System.Func action) Unbekannt + TensorFlow.NET.dll!Tensorflow.gen_array_ops.tile(Tensorflow.Tensor input, Tensorflow.Tensor multiples, string name) Unbekannt + +``` + +### Comment 8 by @simonbuehler (2020-06-03T13:42:46Z) + +@Oceania2018 hi, are there any chances that np.tile could be implemented? diff --git a/docs/issues/issue-0398-typo-in-library-np.random.stardard.md b/docs/issues/issue-0398-typo-in-library-np.random.stardard.md new file mode 100644 index 000000000..866bc5689 --- /dev/null +++ b/docs/issues/issue-0398-typo-in-library-np.random.stardard.md @@ -0,0 +1,18 @@ +# #398: Typo in library np.random.stardard + +- **URL:** https://github.com/SciSharp/NumSharp/issues/398 +- **State:** OPEN +- **Author:** @QadiymStewart +- **Created:** 2020-02-12T16:29:28Z +- **Updated:** 2020-02-12T16:29:28Z + +## Description + +Found a typo + np.random.stardard_normal(Batch_Size, X_Res * Y_Res, 1); + +should be + np.random.standard_normal(Batch_Size, X_Res * Y_Res, 1); + +Spelling Error "standard" + diff --git a/docs/issues/issue-0401-how-to-convert-ndarray-to-list.md b/docs/issues/issue-0401-how-to-convert-ndarray-to-list.md new file mode 100644 index 000000000..63e6b9d7a --- /dev/null +++ b/docs/issues/issue-0401-how-to-convert-ndarray-to-list.md @@ -0,0 +1,90 @@ +# #401: How to convert NDArray to list + +- **URL:** https://github.com/SciSharp/NumSharp/issues/401 +- **State:** OPEN +- **Author:** @Sullivanecidi +- **Created:** 2020-03-18T00:26:17Z +- **Updated:** 2020-03-30T02:57:02Z + +## Description + +It is really a big surprise for me to find the Numsharp. +Here is little question with using the NumSharp: How to convert the NDArray data to list ? since in VB.net, list is the frequently used. +For example: +dim x_data, y_data as NDArray +dim y() as double +x_data = np.linspace(0,100,500) +y_data = x_data * 2 + np.random.randn(500) + +how to convert y_data to y() ? + +Thanks! + +## Comments + +### Comment 1 by @Oceania2018 (2020-03-18T02:35:02Z) + +`x_data.ToArray()` + +### Comment 2 by @Sullivanecidi (2020-03-18T03:05:49Z) + +> `x_data.ToArray()` + +Do you mean y = y_data.ToArray(of double)() +it doesn't work at all...... + +### Comment 3 by @Jiuyong (2020-03-18T05:45:07Z) + +VB.Net don't support Of **unmanaged** +目前看到的情况是,VB.Net 不支持 C# 7.3 新的 **unmanaged** 泛型约束。 +如果想要使用,可能需要变通一下了。 + +### Comment 4 by @pepure (2020-03-18T06:57:27Z) + +> > `x_data.ToArray()` +> +> Do you mean y = y_data.ToArray(of double)() +> it doesn't work at all...... + +I offer a lower level solution:) +-------------------------------------------------------- +Dim x_data, y_data As NDArray +x_data = np.linspace(0, 100, 500) +y_data = x_data * 2 + np.random.randn(500) + +Dim y(y_data.size - 1) As Double +For i = 0 To y_data.size - 1 + y(i) = y_data(i) +Next i +-------------------------------------------------------- +Debugging results: +![image](https://user-images.githubusercontent.com/53322892/76933706-b1c04e80-6928-11ea-9825-aa453c80421b.png) +Please confirm if it can solve your problem。 + + +### Comment 5 by @Sullivanecidi (2020-03-18T07:23:03Z) + +> VB.Net don't support Of **unmanaged** +> 目前看到的情况是,VB.Net 不支持 C# 7.3 新的 **unmanaged** 泛型约束。 +> 如果想要使用,可能需要变通一下了。 + +那就可能是按照楼上这位了,一个一个取出来。谢谢你了~ + +### Comment 6 by @Sullivanecidi (2020-03-18T07:25:10Z) + +Thanks very much! this is the alternative way, since VB.net don't support the unmanaged constraint. + + +### Comment 7 by @Sullivanecidi (2020-03-18T08:38:54Z) + +> VB.Net don't support Of **unmanaged** +> 目前看到的情况是,VB.Net 不支持 C# 7.3 新的 **unmanaged** 泛型约束。 +> 如果想要使用,可能需要变通一下了。 + +我刚试了下c#,是可以用toArray()实现的。 + +### Comment 8 by @Jiuyong (2020-03-30T02:57:02Z) + +是的,C#肯定没问题啊。 +还有个稍微好一点的解决方案。 +就是用C#弄一个缝合项目,然后VB项目引用。 diff --git a/docs/issues/issue-0405-np.argsort-not-sorting-properly.md b/docs/issues/issue-0405-np.argsort-not-sorting-properly.md new file mode 100644 index 000000000..43fcaef17 --- /dev/null +++ b/docs/issues/issue-0405-np.argsort-not-sorting-properly.md @@ -0,0 +1,38 @@ +# #405: np.argsort not sorting properly + +- **URL:** https://github.com/SciSharp/NumSharp/issues/405 +- **State:** OPEN +- **Author:** @tk4218 +- **Created:** 2020-04-09T18:35:33Z +- **Updated:** 2020-04-09T21:18:51Z + +## Description + +I am attempting to call np.argsort() on the following array: +[0.700656592845917, 0.651415288448334, 0.719015657901764] dtype = Double + +The expected result should be: +[1, 0, 2] + +However, the actual result I'm getting is: +[0, 2, 1] + +This doesn't to produce a result that is sorted in any direction. I pulled in ndarray.argsort locally and changed line 31 - +from: `var data = Array;` +to: `var data = ToArray()` +(Also changing the declaration of the function to include `where T : unmanaged `) + +And this seemed to work for me. + + +## Comments + +### Comment 1 by @tk4218 (2020-04-09T21:18:51Z) + +After trying things out for awhile, it seems I can get np.argsort to work if I pass a copy of the NDArray to it. It seems like the NDArray is being manipulated while sorting, causing the sort to misbehave. + +It seems like np.argsort should be: +`nd.copy().argsort(axis)` + +rather than: +`nd.argsort(axis)` diff --git a/docs/issues/issue-0406-c-convert-image-to-ndarray.md b/docs/issues/issue-0406-c-convert-image-to-ndarray.md new file mode 100644 index 000000000..07332e59f --- /dev/null +++ b/docs/issues/issue-0406-c-convert-image-to-ndarray.md @@ -0,0 +1,20 @@ +# #406: C# --> convert image to NDarray + +- **URL:** https://github.com/SciSharp/NumSharp/issues/406 +- **State:** OPEN +- **Author:** @R06921096Yen +- **Created:** 2020-04-20T11:39:16Z +- **Updated:** 2020-05-22T09:06:36Z + +## Description + +Does anyone know how to convert "System.Drawing.Image" to "NDarray" in C#? +Any suggestions would be greatly appreciated. + +## Comments + +### Comment 1 by @chriss2401 (2020-05-22T09:06:35Z) + +Could this extension class help ? + +https://github.com/SciSharp/NumSharp/blob/master/src/NumSharp.Bitmap/np_.extensions.cs diff --git a/docs/issues/issue-0407-np.negative-is-not-working.md b/docs/issues/issue-0407-np.negative-is-not-working.md new file mode 100644 index 000000000..6f7644e64 --- /dev/null +++ b/docs/issues/issue-0407-np.negative-is-not-working.md @@ -0,0 +1,35 @@ +# #407: np.negative is not working ? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/407 +- **State:** OPEN +- **Author:** @LordTrololo +- **Created:** 2020-04-21T07:52:19Z +- **Updated:** 2020-04-21T13:56:16Z +- **Assignees:** @Nucs + +## Description + +Hi, + +I have a NDArray of Floats with dimensions {(1, 13, 13, 3, 2)} and size 1014. + +`np.negative(myArray)` + +works by converting all values to negative. However I think that [official Numpy behaviour](https://numpy.org/doc/stable/reference/generated/numpy.negative.html?highlight=negative#numpy.negative) is to convert positives to negatives and negatives to positives. + +Like so: +``` +np.negative([1.,-1.]) +array([-1., 1.]) + +``` + +What I get is: +``` +np.negative([1.,-1.]) +array([-1., -1.]) +``` +Did someone experience similar problem ? + +BTW, the solution I use to solve the problem is trivial - +`var negativeArray = myarray*(-1);` diff --git a/docs/issues/issue-0408-np.meshgrid-has-a-hidden-error-returning-wrong-results.md b/docs/issues/issue-0408-np.meshgrid-has-a-hidden-error-returning-wrong-results.md new file mode 100644 index 000000000..23111b02c --- /dev/null +++ b/docs/issues/issue-0408-np.meshgrid-has-a-hidden-error-returning-wrong-results.md @@ -0,0 +1,55 @@ +# #408: np.meshgrid() has a hidden error returning wrong results + +- **URL:** https://github.com/SciSharp/NumSharp/issues/408 +- **State:** OPEN +- **Author:** @LordTrololo +- **Created:** 2020-04-23T10:38:03Z +- **Updated:** 2021-07-15T12:26:10Z + +## Description + +There seems to be a bug in the `np.meshgrid()` function. It has something to do with the way the unmanaged memory is handeld but I havent tried to understand the details. + +Why hidden ? Well, lets say we have the following code: +``` +var meshAB = np.meshgrid(np.arange(3), np.arange(3)); +``` + +`meshAB.Item1` seems to be ok, but `meshAB.Item2` hides a nasty problem. +Strangely enough, when one makes a clone of Item2, the cloned values are OK! This is also my quick fix for now. + +So to summary, the code below: +``` +var meshAB = np.meshgrid(np.arange(3), np.arange(3)); +Console.WriteLine("meshAB.Item1.flatten(): " + meshAB.Item1.flatten().ToString()); +Console.WriteLine("meshAB.Item2.flatten(): " + meshAB.Item2.flatten().ToString()); + +NDArray a = meshAB.Item1.Clone(); +NDArray b = meshAB.Item2.Clone(); + +Console.WriteLine("a.flatten(): " +a.flatten().ToString()); +Console.WriteLine("b.flatten(): " +b.flatten().ToString()); +``` + +Will output: +``` +meshAB.Item1.flatten(): [0, 1, 2, 0, 1, 2, 0, 1, 2] +meshAB.Item2.flatten(): [0, 1, 2, 0, 1, 2, 0, 1, 2] <-------WRONG +a.flatten(): [0, 1, 2, 0, 1, 2, 0, 1, 2] +b.flatten(): [0, 0, 0, 1, 1, 1, 2, 2, 2] <------ CORRECT +``` +The bug is nasty because in inspector we also see ok values which is not true. Here is an image: +![image](https://user-images.githubusercontent.com/61494668/80100219-f6ff1e00-856f-11ea-8da8-91caf7e164af.png) + + +## Comments + +### Comment 1 by @ArthHil (2021-07-15T10:48:05Z) + +Same problem, but clone didnt resolve the problem + +### Comment 2 by @Oceania2018 (2021-07-15T12:24:32Z) + +I tested it in [tf.net preview](https://github.com/SciSharp/TensorFlow.NET/blob/16ff7a3dafd283b07d91f61a88e0743a3c47c9fc/test/TensorFlowNET.UnitTest/Numpy/Array.Creation.Test.cs#L69). It's working good. +![image](https://user-images.githubusercontent.com/1705364/125787200-59813f3a-616e-4b44-9f1a-435fc17fe3b2.png) +New version implemented the NumPy API in [TensorFlow NumPy](https://www.tensorflow.org/guide/tf_numpy) diff --git a/docs/issues/issue-0410-np.save-fails-with-indexoutofrangeexception-for-jagged-arrays.md b/docs/issues/issue-0410-np.save-fails-with-indexoutofrangeexception-for-jagged-arrays.md new file mode 100644 index 000000000..9deefa945 --- /dev/null +++ b/docs/issues/issue-0410-np.save-fails-with-indexoutofrangeexception-for-jagged-arrays.md @@ -0,0 +1,40 @@ +# #410: np.save fails with IndexOutOfRangeException for jagged arrays + +- **URL:** https://github.com/SciSharp/NumSharp/issues/410 +- **State:** OPEN +- **Author:** @Jmerk523 +- **Created:** 2020-05-08T01:00:52Z +- **Updated:** 2020-05-08T01:00:52Z + +## Description + +Hi, +I am seeing this exception when trying to save a jagged array to a stream: + +Index was outside the bounds of the array. + at NumSharp.np.d__109`1.MoveNext() + at NumSharp.np.writeValueJagged(BinaryWriter reader, Array matrix, Int32 bytes, Int32[] shape) + at NumSharp.np.Save(Array array, Stream stream) + +I haven't pinpointed the root cause specifically, but it seems that there is some issue with jagged arrays when the outer array has rank 1: + +``` + static IEnumerable Enumerate(Array a, int[] dimensions, int pos) + { + if (pos == dimensions.Length - 1) + { + for (int i = 0; i < dimensions[pos]; i++) + yield return (T)a.GetValue(i); + } + else + { + for (int i = 0; i < dimensions[pos]; i++) + foreach (var subArray in Enumerate(a.GetValue(i) as Array, dimensions, pos + 1)) + yield return subArray; + } + } +``` +When pos == 0 and dimensions[] has length 0, the else will execute and pos(0) will be out of bounds. +dimensions[] has length 0 from the caller, which passes: +` int[] first = shape.Take(shape.Length - 1).ToArray();` +so first[] will be an empty array when shape has length 1 (as in, the single dimension of the 1 dimensional outer jagged array). diff --git a/docs/issues/issue-0411-pyobject-to-ndarray.md b/docs/issues/issue-0411-pyobject-to-ndarray.md new file mode 100644 index 000000000..3c77343c8 --- /dev/null +++ b/docs/issues/issue-0411-pyobject-to-ndarray.md @@ -0,0 +1,16 @@ +# #411: PyObject to NDArray + +- **URL:** https://github.com/SciSharp/NumSharp/issues/411 +- **State:** OPEN +- **Author:** @aaronavi +- **Created:** 2020-05-20T11:24:41Z +- **Updated:** 2020-05-20T11:24:41Z + +## Description + +Hi +I have a PyObject which is of a PyDict type, It contains an NDArray, i need to convert it to actual NDArray. + +How can i do that? + +Thanks diff --git a/docs/issues/issue-0412-the-type-ndarray-exists-in-both-numsharp.core-version-0.20.5.0-and-numsh.md b/docs/issues/issue-0412-the-type-ndarray-exists-in-both-numsharp.core-version-0.20.5.0-and-numsh.md new file mode 100644 index 000000000..1877583b3 --- /dev/null +++ b/docs/issues/issue-0412-the-type-ndarray-exists-in-both-numsharp.core-version-0.20.5.0-and-numsh.md @@ -0,0 +1,18 @@ +# #412: The type 'NDArray' exists in both 'NumSharp.Core, Version=0.20.5.0, ' and 'NumSharp.Lite, Version=0.1.7.0, + +- **URL:** https://github.com/SciSharp/NumSharp/issues/412 +- **State:** OPEN +- **Author:** @sportbilly21 +- **Created:** 2020-05-27T11:43:26Z +- **Updated:** 2020-05-27T11:43:26Z + +## Description + +Hi +I am trying to use +Tensorflow.NET= 0.15.1 +Numsharp = 0.20.5 +SharpCV = 0.5.0 +and I getting the error +The type 'NDArray' exists in both 'NumSharp.Core, Version=0.20.5.0, ' and 'NumSharp.Lite, Version=0.1.7.0, +Any thoughts? diff --git a/docs/issues/issue-0413-ndarray-split.md b/docs/issues/issue-0413-ndarray-split.md new file mode 100644 index 000000000..f51e5a531 --- /dev/null +++ b/docs/issues/issue-0413-ndarray-split.md @@ -0,0 +1,34 @@ +# #413: NDArray Split + +- **URL:** https://github.com/SciSharp/NumSharp/issues/413 +- **State:** OPEN +- **Author:** @lqdev +- **Created:** 2020-06-01T15:09:12Z +- **Updated:** 2020-06-01T15:09:12Z + +## Description + +Given the following Python code: + +```python +a = [1, 2, 3, 99, 99, 3, 2, 1] +a1, a2, a3 = np.split(a, [3, 5]) +print(a1, a2, a3) +``` + +Translated to F#: + +```fsharp +let a = [|1;2;3;99;99;3;2;1|] +let a1,a2,a3 = np.split(a,[|3,5|]) +``` + +When trying to call `split`, I get the following error + +```text +typecheck error The field, constructor or member 'split' is not defined +``` + +Calling `split` on its own without any input arguments, also returns the same error. + +Is `split` implemented in NumSharp? diff --git a/docs/issues/issue-0414-implementation-of-np.delete-working.md b/docs/issues/issue-0414-implementation-of-np.delete-working.md new file mode 100644 index 000000000..d90f4eb08 --- /dev/null +++ b/docs/issues/issue-0414-implementation-of-np.delete-working.md @@ -0,0 +1,16 @@ +# #414: Implementation of np.delete working? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/414 +- **State:** OPEN +- **Author:** @simonbuehler +- **Created:** 2020-06-16T21:50:47Z +- **Updated:** 2020-06-16T21:50:47Z + +## Description + +hi, + +currently the sourcode just returns null, shouldn't the commented code work? + + +https://github.com/SciSharp/NumSharp/blob/843309e7e873bfb0bec2d6e56b3dcba4b9e723e0/src/NumSharp.Core/Manipulation/NdArray.delete.cs#L9 diff --git a/docs/issues/issue-0415-boolean-indexing-and-np.where.md b/docs/issues/issue-0415-boolean-indexing-and-np.where.md new file mode 100644 index 000000000..51e74df5d --- /dev/null +++ b/docs/issues/issue-0415-boolean-indexing-and-np.where.md @@ -0,0 +1,18 @@ +# #415: Boolean indexing and np.where + +- **URL:** https://github.com/SciSharp/NumSharp/issues/415 +- **State:** OPEN +- **Author:** @joshmyersdean +- **Created:** 2020-06-22T15:48:40Z +- **Updated:** 2020-07-08T17:42:28Z + +## Description + +Are there any plans to implement these? Or are they already in place and I am just not getting the syntax right? Thank you! + +## Comments + +### Comment 1 by @SanftMonster (2020-07-08T17:42:28Z) + +I am also finding this...I found that nd[true] works,however not for a variable value,for example nd[nd>0]. +Could you please tell me if you have found a solution?thank you very much! diff --git a/docs/issues/issue-0416-how-to-make-numsharp.ndarray-from-numpy.ndarray.md b/docs/issues/issue-0416-how-to-make-numsharp.ndarray-from-numpy.ndarray.md new file mode 100644 index 000000000..824baffa2 --- /dev/null +++ b/docs/issues/issue-0416-how-to-make-numsharp.ndarray-from-numpy.ndarray.md @@ -0,0 +1,28 @@ +# #416: how to make NumSharp.NDArray from Numpy.NDarray? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/416 +- **State:** OPEN +- **Author:** @djagatiya +- **Created:** 2020-07-06T13:45:49Z +- **Updated:** 2020-07-07T05:43:56Z + +## Description + +_No description provided._ + +## Comments + +### Comment 1 by @djagatiya (2020-07-07T05:43:56Z) + +I found a solution, but is this the right way to do it? + +``` +Numpy.NDarray numpyArray = Numpy.np.random.randn(224,224,3); +byte[] v = numpyArray.GetData(); +fixed (byte* packet = v) +{ + var block = new UnmanagedMemoryBlock(packet, v.Length); + var storage = new UnmanagedStorage(new ArraySlice(block), numpyArray.shape.Dimensions); + NumSharp.NDArray numSharpArray = new NumSharp.NDArray(storage); +} +``` diff --git a/docs/issues/issue-0418-help-me.md b/docs/issues/issue-0418-help-me.md new file mode 100644 index 000000000..36ac8a946 --- /dev/null +++ b/docs/issues/issue-0418-help-me.md @@ -0,0 +1,26 @@ +# #418: help me + +- **URL:** https://github.com/SciSharp/NumSharp/issues/418 +- **State:** OPEN +- **Author:** @mak27arr +- **Created:** 2020-08-01T17:11:03Z +- **Updated:** 2020-08-02T00:52:38Z +- **Assignees:** @Nucs + +## Description + +what im do wrong np.meshgrid return only one NDArray, second always null + +(scales, ratios) = np.meshgrid(np.array(scales), np.array(ratios)); + scales = scales.flatten(); + ratios = ratios.flatten(); + // Enumerate heights and widths from scales and ratios + var heights = scales / np.sqrt(ratios); + var widths = scales * np.sqrt(ratios); + //Enumerate shifts in feature space + var shifts_y = np.arange(0, shape[0], anchor_stride) * feature_stride; + var shifts_x = np.arange(0, shape[1], anchor_stride) * feature_stride; + (shifts_x, shifts_y) = np.meshgrid(shifts_x, shifts_y); + // Enumerate combinations of shifts, widths, and heights + var (box_widths, box_centers_x) = np.meshgrid(widths, shifts_x); + var (box_heights, box_centers_y) = np.meshgrid(heights, shifts_y); diff --git a/docs/issues/issue-0419-np.meshgrid-error.md b/docs/issues/issue-0419-np.meshgrid-error.md new file mode 100644 index 000000000..06a4abc30 --- /dev/null +++ b/docs/issues/issue-0419-np.meshgrid-error.md @@ -0,0 +1,11 @@ +# #419: np.meshgrid error + +- **URL:** https://github.com/SciSharp/NumSharp/issues/419 +- **State:** OPEN +- **Author:** @mak27arr +- **Created:** 2020-08-04T09:50:23Z +- **Updated:** 2020-08-04T09:50:23Z + +## Description + +np.meshgrid return only first item second item break program with code 3221225477 diff --git a/docs/issues/issue-0421-performance.md b/docs/issues/issue-0421-performance.md new file mode 100644 index 000000000..1b8af5ebe --- /dev/null +++ b/docs/issues/issue-0421-performance.md @@ -0,0 +1,86 @@ +# #421: Performance + +- **URL:** https://github.com/SciSharp/NumSharp/issues/421 +- **State:** OPEN +- **Author:** @mishun +- **Created:** 2020-08-16T01:11:02Z +- **Updated:** 2020-08-17T03:15:52Z + +## Description + +Hi! +I just tried to do some basic computational geometry with NumSharp and compare it with naive implementation like that: +```F# +open System +open System.Diagnostics +open System.Numerics +open NumSharp + +[] +type Line2f = { + Normal : Vector2 + Offset : single +} + +let residualsNaive (points : ReadOnlySpan, line : Line2f) = + let residuals = Array.create points.Length 0.0f + for i in 0 .. points.Length - 1 do + residuals.[i] <- abs (Vector2.Dot(line.Normal, points.[i]) + line.Offset) + residuals + + +let residuals (points : NDArray, line : Line2f) = + let l = np.array(line.Normal.X, line.Normal.Y) + let signed = np.dot(&points, &l) + line.Offset + np.abs &signed + + +[] +let main argv = + let n = 10000000 + + let rand = Random () + let points = Array.init n (fun _ -> Vector2 (single (rand.NextDouble ()), single (rand.NextDouble ()))) + let line = + let a = Math.PI * rand.NextDouble () + { Normal = Vector2 (single (cos a), single (sin a)) + Offset = single (rand.NextDouble ()) + } + + let swNaive = Stopwatch.StartNew () + let res1 = residualsNaive (ReadOnlySpan points, line) + swNaive.Stop () + + let pointsArray = np.array([| for p in points do yield p.X ; yield p.Y |]).reshape(n, 2) + + let swNumSharp = Stopwatch.StartNew () + let res2 = residuals (pointsArray, line) + swNumSharp.Stop () + + printfn "Naive: %A\nNumSharp: %A\n\n" swNaive.Elapsed swNumSharp.Elapsed + printfn "Result:\n%A vs %A" (Array.sum res1) (np.sum (&res2)) + + 0 +``` +and got: +``` +$ dotnet run -c release +Naive: 00:00:00.0762210 +NumSharp: 00:00:09.7929785 +``` +Maybe I'm doing something very-very wrong, but 2-something orders of magnitude difference looks a bit too much even if there are just managed loops inside NumSharp's functions. + +Tested with +``` +) +``` + +## Comments + +### Comment 1 by @Oceania2018 (2020-08-16T12:49:32Z) + +Can you try in Tensorflow.net preview3? + +### Comment 2 by @mishun (2020-08-17T03:15:52Z) + +You mean use NumSharp that is installed with Tensorflow.NET 0.20.0-preview3 nuget package? Runtime looks roughly the same except np.sum is now throwing an exception. diff --git a/docs/issues/issue-0422-index-of-element-with-a-condiction.md b/docs/issues/issue-0422-index-of-element-with-a-condiction.md new file mode 100644 index 000000000..d37d86180 --- /dev/null +++ b/docs/issues/issue-0422-index-of-element-with-a-condiction.md @@ -0,0 +1,19 @@ +# #422: Index of element with a condiction + +- **URL:** https://github.com/SciSharp/NumSharp/issues/422 +- **State:** OPEN +- **Author:** @EnricoBeltramo +- **Created:** 2020-09-11T05:45:48Z +- **Updated:** 2020-09-11T05:45:48Z + +## Description + +I'm implementing a filter on array. In python it works well, but if I try to replicate in numsharp, doesn't: + +var threshold = 0.01 +var filter1 = XYZ1[2, Slice.All] < -threshold; +var XYZ_1_filter = XYZ1[Slice.All, filter1]; +var XYZ_2_filter = XYZ2[Slice.All, filter1]; + +In particular way, filter1 return null. +How can I do? In general, how i can find indexes that respect a particular condiction (i.e. greater than, minor than) in numsharp? diff --git a/docs/issues/issue-0423-system.notimplementedexception-somearray-np.frombuffer-bytebuffer.toa.md b/docs/issues/issue-0423-system.notimplementedexception-somearray-np.frombuffer-bytebuffer.toa.md new file mode 100644 index 000000000..4b1a3b801 --- /dev/null +++ b/docs/issues/issue-0423-system.notimplementedexception-somearray-np.frombuffer-bytebuffer.toa.md @@ -0,0 +1,50 @@ +# #423: "System.NotImplementedException: '' --> someArray = np.frombuffer(byteBuffer.ToArray(), np.uint32); + +- **URL:** https://github.com/SciSharp/NumSharp/issues/423 +- **State:** OPEN +- **Author:** @mehmetcanbalci-Notrino +- **Created:** 2020-10-09T16:10:25Z +- **Updated:** 2020-10-18T22:51:51Z + +## Description + +Hello, +i got this execption "System.NotImplementedException: ''" when i use this code ; +someArray = np.frombuffer(byteBuffer.ToArray(), np.uint32); + +if I will use np.int32, it is working as expected. + +## Comments + +### Comment 1 by @ (2020-10-18T22:51:51Z) + +Hello @mehmetcanbalci-Notrino , + +You got an exception because data type "uint32" is not yet being implemented, only "int32" and "byte". + + ```c# + public static NDArray frombuffer(byte[] bytes, Type dtype) + { + + //TODO! all types + if (dtype.Name == "Int32") + { + var size = bytes.Length / InfoOf.Size; + var ints = new int[size]; + for (var index = 0; index < size; index++) + { + ints[index] = BitConverter.ToInt32(bytes, index * InfoOf.Size); + } + + return new NDArray(ints); + } + else if (dtype.Name == "Byte") + { + var size = bytes.Length / InfoOf.Size; + var ints = bytes; + return new NDArray(bytes); + } + + throw new NotImplementedException(""); + } +``` diff --git a/docs/issues/issue-0424-the-type-or-namespace-name-numsharp-could-not-be-found-are-you-missing-a-usin.md b/docs/issues/issue-0424-the-type-or-namespace-name-numsharp-could-not-be-found-are-you-missing-a-usin.md new file mode 100644 index 000000000..b2312eea9 --- /dev/null +++ b/docs/issues/issue-0424-the-type-or-namespace-name-numsharp-could-not-be-found-are-you-missing-a-usin.md @@ -0,0 +1,36 @@ +# #424: The type or namespace name 'NumSharp' could not be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp]csharp(CS0246) + +- **URL:** https://github.com/SciSharp/NumSharp/issues/424 +- **State:** OPEN +- **Author:** @rcffc +- **Created:** 2020-10-15T15:47:16Z +- **Updated:** 2020-10-19T21:52:32Z + +## Description + +I am using VSCode and have tried installing Numsharp using NuGet Gallery and Nuget Package Manager. + +But still I am getting this error in my Unity project: +`The type or namespace name 'NumSharp' could not be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp]csharp(CS0246)` + +Any cues? + +## Comments + +### Comment 1 by @rcffc (2020-10-15T15:48:24Z) + +It is also included in Assembly-CSharp.csproj: + `` + +### Comment 2 by @ (2020-10-19T21:52:31Z) + +Hello @rcffc, + +1) Have you tried to restart VSCode? + +2) If your project is using .NET Core, the CLI tool allows you to easily install NuGet packages from VSCode. + + `dotnet add package NumSharp` + + After the command completes, look at the project file (*.csproj) to make sure the package was installed. + diff --git a/docs/issues/issue-0426-arctan2-returning-incorrect-value.md b/docs/issues/issue-0426-arctan2-returning-incorrect-value.md new file mode 100644 index 000000000..c94cdb4c4 --- /dev/null +++ b/docs/issues/issue-0426-arctan2-returning-incorrect-value.md @@ -0,0 +1,48 @@ +# #426: arctan2() returning incorrect value + +- **URL:** https://github.com/SciSharp/NumSharp/issues/426 +- **State:** OPEN +- **Author:** @RoseberryPi +- **Created:** 2020-10-25T17:14:27Z +- **Updated:** 2020-10-29T22:22:09Z + +## Description + +So I'm using numsharp +`np.arctan2(np.array(-0.0012562886517319706), np.array(-0.7499033624114052))` + +I get the wrong value, approximately, `-4.33e-5` + +using numpy.net and C#'s Math library +`np.arctan2(np.array(-0.0012562886517319706), np.array(-0.7499033624114052))` +`Math.Atan2(-0.0012562886517319706, -0.7499033624114052)` + +I get `-3.1399`, which is the correct value.. Am I just being dumb and doing something wrong or is NumSharp not actually calculating the correct value? + +furthmore, `np.arctan2(1,1)` is 90deg according to numsharp. Should be 45. +`np.arctan2(1,-1)` is also 90deg.... + +I'm using version v0.20.5 + +## Comments + +### Comment 1 by @ (2020-10-29T22:22:09Z) + +Hello @RoseberryPi, + +You are right, looking at code I don't understand the type casting done to (byte*) instead of (double*). +There must be an explanation. + +```csharp +case NPTypeCode.Double: +{ + var out_addr = (double*)out_y.Address; + var out_addr_x = (byte*)out_x.Address; + Parallel.For(0, len, i => *(out_addr) = Converts.ToDouble(Math.Atan2(*(out_addr) + i, *(out_addr_x) + i))); + return out_y; +} +``` +I tried casting to (double*) and it returns the expected value, 3.13991738776297 + + + diff --git a/docs/issues/issue-0427-performance-on-np.matmul.md b/docs/issues/issue-0427-performance-on-np.matmul.md new file mode 100644 index 000000000..0ea6b7e38 --- /dev/null +++ b/docs/issues/issue-0427-performance-on-np.matmul.md @@ -0,0 +1,44 @@ +# #427: Performance on np.matmul + +- **URL:** https://github.com/SciSharp/NumSharp/issues/427 +- **State:** OPEN +- **Author:** @Banyc +- **Created:** 2020-10-31T12:26:03Z +- **Updated:** 2020-10-31T14:10:34Z + +## Description + +The shape of `x` is [200, 1000], of `w` is [1000, 500], and of `b` is [500] + +`b` is filled with zeros, `x` and `w` are random float64/double. + +Example code of NumSharp: + +```csharp +var out = np.matmul(x, w) + b; +``` + +... takes 3-4 seconds. + +Example code of numpy: + +```python +out = x @ w + b +``` + +... finishes immediately. + + +## Comments + +### Comment 1 by @Oceania2018 (2020-10-31T13:53:38Z) + +@Banyc Can you test it in `TensorFlow.NET` eager mode? + +### Comment 2 by @Banyc (2020-10-31T14:07:13Z) + +I use only this package to implement neural network layers from the stretch, without using other packages like `Tensorflow.NET`. + +### Comment 3 by @Oceania2018 (2020-10-31T14:10:34Z) + +It will have performance issue. Should use other more mature package. diff --git a/docs/issues/issue-0428-typo-in-ndarray.tomuliarray-method-name.md b/docs/issues/issue-0428-typo-in-ndarray.tomuliarray-method-name.md new file mode 100644 index 000000000..6e6d21639 --- /dev/null +++ b/docs/issues/issue-0428-typo-in-ndarray.tomuliarray-method-name.md @@ -0,0 +1,13 @@ +# #428: Typo in NDArray.ToMuliArray method name + +- **URL:** https://github.com/SciSharp/NumSharp/issues/428 +- **State:** OPEN +- **Author:** @jpmn +- **Created:** 2020-11-11T20:09:52Z +- **Updated:** 2020-11-11T20:09:52Z + +## Description + +According to the filename `NumSharp.Core/Casting/NdArrayToMultiDimArray.cs`, I think it should be `NDArray.ToMultiArray` + +https://github.com/SciSharp/NumSharp/blob/843309e7e873bfb0bec2d6e56b3dcba4b9e723e0/src/NumSharp.Core/Casting/NdArrayToMultiDimArray.cs#L31 diff --git a/docs/issues/issue-0430-numsharp.backends.unmanaged.unmanagedmemoryblock1-fails-on-mono-on-linux.md b/docs/issues/issue-0430-numsharp.backends.unmanaged.unmanagedmemoryblock1-fails-on-mono-on-linux.md new file mode 100644 index 000000000..3266398b8 --- /dev/null +++ b/docs/issues/issue-0430-numsharp.backends.unmanaged.unmanagedmemoryblock1-fails-on-mono-on-linux.md @@ -0,0 +1,33 @@ +# #430: NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock`1 fails on Mono on Linux + +- **URL:** https://github.com/SciSharp/NumSharp/issues/430 +- **State:** OPEN +- **Author:** @kgoderis +- **Created:** 2020-11-15T18:22:46Z +- **Updated:** 2020-11-15T18:22:46Z + +## Description + +Mono 5.12.0.301 +Linux 4.19.76 + +Attempting the "Hello World" Tensortflow.NET example in a docker environment running Mono yields the following error. Exactly the same code on Mono 6.12.0.93 on Mac OS X however does run flawlessly + +2020-11-15 17:53:41.843832: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU instructions in performance-critical operations: AVX2 FMA +To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. +2020-11-15 17:53:41.873442: I tensorflow/core/platform/profile_utils/cpu_utils.cc:104] CPU Frequency: 2712000000 Hz +2020-11-15 17:53:41.874170: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x7fc874d557a0 initialized for platform Host (this does not guarantee that XLA will be used). Devices: +2020-11-15 17:53:41.874230: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version +Stacktrace: + + at <0xffffffff> +* Assertion at method-to-ir.c:7352, condition `!sig->has_type_parameters' not met + + at NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock`1.FromArray (byte[],bool) [0x00037] in <6d1fbec37f814ff9b52dec21dc0ebd1a>:0 + at NumSharp.Backends.Unmanaged.ArraySlice.FromArray (byte[],bool) [0x00000] in <6d1fbec37f814ff9b52dec21dc0ebd1a>:0 + at NumSharp.np.array (byte[]) [0x00000] in <6d1fbec37f814ff9b52dec21dc0ebd1a>:0 + at Tensorflow.Tensor.GetNDArray (Tensorflow.TF_DataType) [0x00041] in :0 + at Tensorflow.Tensor.numpy () [0x00007] in :0 + at Tensorflow.tensor_util.to_numpy_string (Tensorflow.Tensor) [0x00034] in :0 + at Tensorflow.Eager.EagerTensor.ToString () [0x00016] in :0 + diff --git a/docs/issues/issue-0433-ndarray-exists-in-both-numsharp.core-version-0.20.5.0-and-numsharp.lite-versio.md b/docs/issues/issue-0433-ndarray-exists-in-both-numsharp.core-version-0.20.5.0-and-numsharp.lite-versio.md new file mode 100644 index 000000000..c7054db8d --- /dev/null +++ b/docs/issues/issue-0433-ndarray-exists-in-both-numsharp.core-version-0.20.5.0-and-numsharp.lite-versio.md @@ -0,0 +1,58 @@ +# #433: NDArray exists in both NumSharp.Core, Version=0.20.5.0 and NumSharp.Lite, Version=0.1.9.0 + +- **URL:** https://github.com/SciSharp/NumSharp/issues/433 +- **State:** OPEN +- **Author:** @gscheck +- **Created:** 2020-12-09T16:50:56Z +- **Updated:** 2020-12-09T20:14:45Z + +## Description + +I get the following error when trying to compile an example: + +Severity Code Description Project File Line Suppression State +Error CS0433 The type 'NDArray' exists in both 'NumSharp.Core, Version=0.20.5.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' and 'NumSharp.Lite, Version=0.1.9.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' Tensorflow1 I:\Operations\Test Engineering\Test Eng\Software Development\AOI\Tensorflow1\Tensorflow1\Form1.cs 47 Active + + +I am only using TensorFlow.NET and NumSharp libraries. + +See screen shots below: + +![image](https://user-images.githubusercontent.com/32424716/101659915-6c363b00-39fb-11eb-8c40-e86669bd195c.png) + +![image](https://user-images.githubusercontent.com/32424716/101659977-7eb07480-39fb-11eb-8586-8ffa642f1059.png) + + + +## Comments + +### Comment 1 by @Oceania2018 (2020-12-09T17:59:09Z) + +Remove NumSharp reference, just reference TensorFlow.NET project. It will include NumSharp automatically. + +### Comment 2 by @gscheck (2020-12-09T18:29:12Z) + +If I remove the NumSharp reference, I get the following error. + +Severity Code Description Project File Line Suppression State +Error CS0246 The type or namespace name 'NDArray' could not be found (are you missing a using directive or an assembly reference?) Tensorflow1 I:\Operations\Test Engineering\Test Eng\Software Development\AOI\Tensorflow1\Tensorflow1\Form1.cs 46 Active + + +![image](https://user-images.githubusercontent.com/32424716/101671436-5891d100-3a09-11eb-8217-918b6444a1e0.png) + +![image](https://user-images.githubusercontent.com/32424716/101671376-431ca700-3a09-11eb-930c-5fb6c5e4dfa7.png) + + + + +### Comment 3 by @Oceania2018 (2020-12-09T20:14:35Z) + +Remove project reference means remove it from package. +![image](https://user-images.githubusercontent.com/1705364/101682026-ae29a600-3a28-11eb-8fad-6b9496827314.png) + +You still need: +```csharp +using Numsharp; +``` + +The easiest step is just follow this [sample project](https://github.com/SciSharp/SciSharp-Stack-Examples). diff --git a/docs/issues/issue-0434-accessviolationexception-when-selecting-indexes-using-ndarray-ndarray-and-setti.md b/docs/issues/issue-0434-accessviolationexception-when-selecting-indexes-using-ndarray-ndarray-and-setti.md new file mode 100644 index 000000000..869ca7fd2 --- /dev/null +++ b/docs/issues/issue-0434-accessviolationexception-when-selecting-indexes-using-ndarray-ndarray-and-setti.md @@ -0,0 +1,39 @@ +# #434: AccessViolationException when selecting indexes using ndarray[ndarray] and setting a scalar value + +- **URL:** https://github.com/SciSharp/NumSharp/issues/434 +- **State:** OPEN +- **Author:** @lijianxin520 +- **Created:** 2020-12-31T02:30:16Z +- **Updated:** 2021-04-21T04:50:55Z +- **Labels:** bug + +## Description + +Attempted to read or write protected memory. This is often an indication that other memory is corrupt. +![2020-12-30_230218](https://user-images.githubusercontent.com/47262889/103391183-013bd800-4b53-11eb-9f76-0ad77b978ae2.png) + + +## Comments + +### Comment 1 by @rikkitook (2021-04-01T12:43:13Z) + +To my experience, problems like these can be avoided if you do not access an instance of ndarray from different threads or tasks. If it is still necessary, try copying ndarray to float[], pass it to your method and then copy to new ndarray. +Cheers! + +### Comment 2 by @lijianxin520 (2021-04-13T06:43:06Z) + +I'm single-threaded, so I shouldn't have any problems with multithreading + +### Comment 3 by @Nucs (2021-04-13T11:19:50Z) + +To my understanding - `AccessViolationException` usually occurs if you somehow lost reference to your `NDArray`. +`NDArray` only frees allocated memory when `IDisposable` is triggered by the garbage collector when there are no longer any references to it. +In addition, zero-copied `NDArray`s from any operation still hold a reference to base memory which should prevent deallocation. + +Please provide here a reproducing unit test/piece of code and I'll gladly investigate. + +### Comment 4 by @lijianxin520 (2021-04-15T06:40:57Z) + +这个是我测试的时候异常的内容, +![image](https://user-images.githubusercontent.com/47262889/114825071-521cc700-9df8-11eb-9125-08b91b5971fd.png) +当我对一个数组执行批处理操作时,我看到的结果是这个问题. diff --git a/docs/issues/issue-0435-complex-number-support.md b/docs/issues/issue-0435-complex-number-support.md new file mode 100644 index 000000000..ae436af3f --- /dev/null +++ b/docs/issues/issue-0435-complex-number-support.md @@ -0,0 +1,43 @@ +# #435: Complex number support? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/435 +- **State:** OPEN +- **Author:** @cgranade +- **Created:** 2021-01-07T22:43:31Z +- **Updated:** 2023-08-19T14:29:33Z + +## Description + +When attempting to create a new `NDArray` of complex numbers, I get an exception in the `Allocate` method at https://github.com/SciSharp/NumSharp/blob/00d8700b00e815f321238536e0d6b4dbc9af8d6a/src/NumSharp.Core/Backends/Unmanaged/ArraySlice.cs#L387: + +![image](https://user-images.githubusercontent.com/31516/103953204-89435400-50f6-11eb-9ec7-13e522da1445.png) + +Are complex numbers supported as the dtype of `NDArray` objects, and if so, how do I allocate them? Thanks for the help, and for the awesome project! + +## Comments + +### Comment 1 by @dcuccia (2021-06-29T00:48:34Z) + ++1. Just got to the end of a port, and realized Complex is not supported. Are there plans for this? + +### Comment 2 by @LetGo (2022-03-10T06:33:07Z) + ++1. Just got to the end of a port, and realized Complex is not supported. Are there plans for this? + +### Comment 3 by @gsgou (2023-08-19T14:26:53Z) + +Any way to workaround this one? +UnmanagedStorage also doesnt support Complex. + +``` +System.NotSupportedException: Specified method is not supported. + at NumSharp.NPTypeCodeExtensions.AsType (NumSharp.NPTypeCode typeCode) [0x00097] in D:\SciSharp\NumSharp\src\NumSharp.Core\Backends\NPTypeCode.cs:144 + at NumSharp.Backends.UnmanagedStorage..ctor (NumSharp.NPTypeCode typeCode) [0x00014] in D:\SciSharp\NumSharp\src\NumSharp.Core\Backends\Unmanaged\UnmanagedStorage.cs:181 + at NumSharp.Backends.DefaultEngine.GetStorage (NumSharp.NPTypeCode typeCode) [0x00000] in D:\SciSharp\NumSharp\src\NumSharp.Core\Backends\Default\Allocation\Default.Allocation.cs:14 + at NumSharp.NDArray..ctor (NumSharp.NPTypeCode typeCode, NumSharp.TensorEngine engine) [0x0000d] in D:\SciSharp\NumSharp\src\NumSharp.Core\Backends\NDArray.cs:102 + at NumSharp.NDArray..ctor (NumSharp.NPTypeCode typeCode) [0x00000] in D:\SciSharp\NumSharp\src\NumSharp.Core\Backends\NDArray.cs:119 + at NumSharp.NDArray..ctor (NumSharp.NPTypeCode dtype, NumSharp.Shape shape, System.Boolean fillZeros) [0x00000] in D:\SciSharp\NumSharp\src\NumSharp.Core\Backends\NDArray.cs:234 + at NumSharp.np.zeros (NumSharp.Shape shape, NumSharp.NPTypeCode typeCode) [0x0000e] in D:\SciSharp\NumSharp\src\NumSharp.Core\Creation\np.zeros.cs:54 +``` + + diff --git a/docs/issues/issue-0436-np.searchsorted-error.md b/docs/issues/issue-0436-np.searchsorted-error.md new file mode 100644 index 000000000..be9c5c742 --- /dev/null +++ b/docs/issues/issue-0436-np.searchsorted-error.md @@ -0,0 +1,19 @@ +# #436: np.searchsorted error! + +- **URL:** https://github.com/SciSharp/NumSharp/issues/436 +- **State:** OPEN +- **Author:** @wangfeixing +- **Created:** 2021-01-12T09:20:40Z +- **Updated:** 2021-01-12T09:20:40Z + +## Description + +i use "np.searchsorted" function like the code below: + List list1 = new List() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + List list2 = new List() { 1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 8.1, 9.1, 10.1 }; + NDArray array1 = np.array(list1.ToArray()); + NDArray array2 = np.array(list2.ToArray()); + + int kk = np.searchsorted(array2, 3.0); + +but it reports the error "System.IndexOutOfRangeException",is this a bug? diff --git a/docs/issues/issue-0437-argmin-is-not-the-same-with-numpy.md b/docs/issues/issue-0437-argmin-is-not-the-same-with-numpy.md new file mode 100644 index 000000000..da3861434 --- /dev/null +++ b/docs/issues/issue-0437-argmin-is-not-the-same-with-numpy.md @@ -0,0 +1,13 @@ +# #437: argmin is not the same with numpy + +- **URL:** https://github.com/SciSharp/NumSharp/issues/437 +- **State:** OPEN +- **Author:** @tomachristian +- **Created:** 2021-01-30T09:08:48Z +- **Updated:** 2021-01-30T09:08:48Z + +## Description + +https://github.com/SciSharp/NumSharp/blob/00d8700b00e815f321238536e0d6b4dbc9af8d6a/src/NumSharp.Core/Statistics/NDArray.argmin.cs#L20 + +this does not look right because it returns int, also np.argmin does not seem to behave correctly (like its numpy counterpart) diff --git a/docs/issues/issue-0438-how-to-get-the-inverse-of-a-2d-matrix.md b/docs/issues/issue-0438-how-to-get-the-inverse-of-a-2d-matrix.md new file mode 100644 index 000000000..4a4aad089 --- /dev/null +++ b/docs/issues/issue-0438-how-to-get-the-inverse-of-a-2d-matrix.md @@ -0,0 +1,13 @@ +# #438: How to get the inverse of a 2D matrix? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/438 +- **State:** OPEN +- **Author:** @Mingrui-Yu +- **Created:** 2021-02-03T16:50:22Z +- **Updated:** 2021-02-03T16:50:22Z + +## Description + +How to get the inverse of a 2D matrix ?I find NumSharp/src/NumSharp.Core/LinearAlgebra/NdArray.Inv.cs just returns null. + +Thanks for your help! diff --git a/docs/issues/issue-0439-where-is-np.where-function.md b/docs/issues/issue-0439-where-is-np.where-function.md new file mode 100644 index 000000000..be042e069 --- /dev/null +++ b/docs/issues/issue-0439-where-is-np.where-function.md @@ -0,0 +1,14 @@ +# #439: Where is np.where() function ? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/439 +- **State:** OPEN +- **Author:** @minhduc66532 +- **Created:** 2021-02-07T05:02:40Z +- **Updated:** 2021-04-14T11:22:27Z +- **Labels:** missing feature/s + +## Description + +The title says it all: +![image](https://user-images.githubusercontent.com/66398066/107137154-30a4e800-693c-11eb-8720-d67acfd9eead.png) + diff --git a/docs/issues/issue-0440-ndarray.tobitmap-has-critical-issue-with-24bpp-vertical-images.md b/docs/issues/issue-0440-ndarray.tobitmap-has-critical-issue-with-24bpp-vertical-images.md new file mode 100644 index 000000000..6997a0e55 --- /dev/null +++ b/docs/issues/issue-0440-ndarray.tobitmap-has-critical-issue-with-24bpp-vertical-images.md @@ -0,0 +1,30 @@ +# #440: NDArray.ToBitmap() has critical issue with 24bpp VERTICAL images + +- **URL:** https://github.com/SciSharp/NumSharp/issues/440 +- **State:** OPEN +- **Author:** @MiroslavKabat +- **Created:** 2021-02-09T00:57:34Z +- **Updated:** 2021-04-14T11:21:57Z +- **Labels:** bug + +## Description + + var arr = np.ones(1, 2, 1, 3).astype(NPTypeCode.Byte); + var bmp = arr.ToBitmap(); + + for (int c = 0; c < bmp.Width; c++) + { + for (int r = 0; r < bmp.Height; r++) + { + var p = bmp.GetPixel(c, r); + Console.WriteLine($"r:{r} c:{c} => ({p.R};{p.G};{p.B})"); + } + } + + // return + // r: 0 c: 0 => (1; 1; 1) + // r: 1 c: 0 => (0; 1; 1) !!! + + // instead of + // r: 0 c: 0 => (1; 1; 1) + // r: 1 c: 0 => (1; 1; 1) diff --git a/docs/issues/issue-0441-no-numpy.linalg.norm.md b/docs/issues/issue-0441-no-numpy.linalg.norm.md new file mode 100644 index 000000000..e48782887 --- /dev/null +++ b/docs/issues/issue-0441-no-numpy.linalg.norm.md @@ -0,0 +1,12 @@ +# #441: No numpy.linalg.norm() ? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/441 +- **State:** OPEN +- **Author:** @minhduc66532 +- **Created:** 2021-02-22T15:49:06Z +- **Updated:** 2021-04-14T11:20:43Z +- **Labels:** missing feature/s + +## Description + +There is no [np.linalg.norm()](https://numpy.org/doc/stable/reference/generated/numpy.linalg.norm.html) function diff --git a/docs/issues/issue-0443-0.3.0-from-nuget-throwing-notsupportedexception-on-negate-function-call.md b/docs/issues/issue-0443-0.3.0-from-nuget-throwing-notsupportedexception-on-negate-function-call.md new file mode 100644 index 000000000..a1f2e4a8d --- /dev/null +++ b/docs/issues/issue-0443-0.3.0-from-nuget-throwing-notsupportedexception-on-negate-function-call.md @@ -0,0 +1,26 @@ +# #443: 0.3.0 from NuGet throwing NotSupportedException on negate function call + +- **URL:** https://github.com/SciSharp/NumSharp/issues/443 +- **State:** OPEN +- **Author:** @gandalfh +- **Created:** 2021-03-09T03:25:55Z +- **Updated:** 2021-04-14T11:18:02Z + +## Description + +This code behaves as expected on version 0.20.5 from NuGet (https://www.nuget.org/packages/NumSharp/) + +`var ones = np.ones((10, 1));` +`ones.negate();` + +But after upgrading to 0.3.0 a NotSupportedException is thrown: + + at NumSharp.Backends.DefaultEngine.Negate(NDArray& nd) + at NumSharp.NDArray.negate() + + +## Comments + +### Comment 1 by @Nucs (2021-04-14T11:18:01Z) + +Related to #447 diff --git a/docs/issues/issue-0445-how-can-provide-output-for-np.dot.md b/docs/issues/issue-0445-how-can-provide-output-for-np.dot.md new file mode 100644 index 000000000..e732ab9a3 --- /dev/null +++ b/docs/issues/issue-0445-how-can-provide-output-for-np.dot.md @@ -0,0 +1,14 @@ +# #445: How can provide output for np.dot? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/445 +- **State:** OPEN +- **Author:** @bigdimboom +- **Created:** 2021-03-24T02:49:34Z +- **Updated:** 2021-04-23T11:58:36Z +- **Labels:** missing feature/s + +## Description + +I can't find the impl. of np.dot(inputA, inutB, out preallocatedArray). + +Currently I am using np.dot(.....).copyTo(....). But I think it still allocates a tmp memory. diff --git a/docs/issues/issue-0446-unable-to-use-np.dot-due-to-specified-method-unsupported-error.md b/docs/issues/issue-0446-unable-to-use-np.dot-due-to-specified-method-unsupported-error.md new file mode 100644 index 000000000..c50eda11d --- /dev/null +++ b/docs/issues/issue-0446-unable-to-use-np.dot-due-to-specified-method-unsupported-error.md @@ -0,0 +1,69 @@ +# #446: Unable to use np.dot due to "Specified method unsupported" error + +- **URL:** https://github.com/SciSharp/NumSharp/issues/446 +- **State:** OPEN +- **Author:** @moonlitlyra +- **Created:** 2021-03-27T17:01:11Z +- **Updated:** 2021-06-30T18:55:04Z + +## Description + +I have recently been working on a unity project involving the genetic algorithm, but have run into an error while trying to use the function np.dot(). NumSharp has been installed using the NuGet client [NuGetForUnity](https://github.com/GlitchEnzo/NuGetForUnity) + +The error message is as follows: + +NotSupportedException: Specified method is not supported. +NumSharp.NPTypeCodeExtensions.GetAccumulatingType (NumSharp.NPTypeCode typeCode) (at <7807b007e09c46aca587061f8867e538>:0) +NumSharp.Backends.DefaultEngine.ReduceAdd (NumSharp.NDArray& arr, System.Nullable`1[T] axis_, System.Boolean keepdims, System.Nullable`1[T] typeCode, NumSharp.NDArray out) (at <7807b007e09c46aca587061f8867e538>:0) +NumSharp.Backends.DefaultEngine.Sum (NumSharp.NDArray& nd, System.Nullable`1[T] axis, System.Nullable`1[T] typeCode, System.Boolean keepdims) (at <7807b007e09c46aca587061f8867e538>:0) +NumSharp.np.sum (NumSharp.NDArray& a, System.Int32 axis) (at <7807b007e09c46aca587061f8867e538>:0) +NumSharp.Backends.DefaultEngine.Dot (NumSharp.NDArray& left, NumSharp.NDArray& right) (at <7807b007e09c46aca587061f8867e538>:0) +NumSharp.np.dot (NumSharp.NDArray& a, NumSharp.NDArray& b) (at <7807b007e09c46aca587061f8867e538>:0) +NN.FeedForward () (at Assets/scripts/NeuralNetwork.cs:73) +Bot.FixedUpdate () (at Assets/scripts/Bot.cs:70) + +Line 73 of the FeedForward script: + +73. `NDArray activations = np.dot(layers[i].weights, layers[i].activations);` + +Other sections of relevant code: + +47. `layer.weights = np.random.rand(3, 2);` +48. `layer.activations = np.zeros(2);` + +## Comments + +### Comment 1 by @Nucs (2021-04-14T11:16:39Z) + +Related to #447 + + +### Comment 2 by @BlackholeGH (2021-06-27T10:07:04Z) + +I seem to have this same issue, in a similar context attempting to use np.dot to do a dot-product for two 1-D numpy arrays containing double values. Assuming we're not both doing something wrong, any workarounds beside calculating the dot product manually? + +> System.NotSupportedException + HResult=0x80131515 + Message=Specified method is not supported. + Source=NumSharp + StackTrace: + at NumSharp.NPTypeCodeExtensions.GetAccumulatingType(NPTypeCode typeCode) + at NumSharp.Backends.DefaultEngine.sum_elementwise(NDArray arr, Nullable`1 typeCode) + at NumSharp.Backends.DefaultEngine.ReduceAdd(NDArray& arr, Nullable`1 axis_, Boolean keepdims, Nullable`1 typeCode, NDArray out) + at NumSharp.Backends.DefaultEngine.Dot(NDArray& left, NDArray& right) + + +### Comment 3 by @moonlitlyra (2021-06-30T18:55:04Z) + +> I seem to have this same issue, in a similar context attempting to use np.dot to do a dot-product for two 1-D numpy arrays containing double values. Assuming we're not both doing something wrong, any workarounds beside calculating the dot product manually? +> +> > System.NotSupportedException +> > HResult=0x80131515 +> > Message=Specified method is not supported. +> > Source=NumSharp +> > StackTrace: +> > at NumSharp.NPTypeCodeExtensions.GetAccumulatingType(NPTypeCode typeCode) +> > at NumSharp.Backends.DefaultEngine.sum_elementwise(NDArray arr, Nullable`1 typeCode) at NumSharp.Backends.DefaultEngine.ReduceAdd(NDArray& arr, Nullable`1 axis_, Boolean keepdims, Nullable`1 typeCode, NDArray out) +> > at NumSharp.Backends.DefaultEngine.Dot(NDArray& left, NDArray& right) + +Hello, thankyou for commenting on this issue. No workarounds as far as I am aware, I ended up having to scrap part of my project sadly. Thanks anyway. diff --git a/docs/issues/issue-0447-np.sum-is-supported-on-numsharp0.20.5-but-not-on-numsharp0.30.0.md b/docs/issues/issue-0447-np.sum-is-supported-on-numsharp0.20.5-but-not-on-numsharp0.30.0.md new file mode 100644 index 000000000..f1a66063e --- /dev/null +++ b/docs/issues/issue-0447-np.sum-is-supported-on-numsharp0.20.5-but-not-on-numsharp0.30.0.md @@ -0,0 +1,88 @@ +# #447: np.sum() Is supported on numsharp0.20.5, but not on NumSharp0.30.0 + +- **URL:** https://github.com/SciSharp/NumSharp/issues/447 +- **State:** OPEN +- **Author:** @lijianxin520 +- **Created:** 2021-04-13T06:35:26Z +- **Updated:** 2024-02-26T22:17:28Z + +## Description + +np.sum() Is supported on numsharp0.20.5, but not on NumSharp0.30.0 +the exception message :"Specified method is not supported." + +## Comments + +### Comment 1 by @Nucs (2021-04-13T11:24:36Z) + +What datatype are you trying to use? + +### Comment 2 by @lijianxin520 (2021-04-14T00:57:05Z) + + double s = np.sum(w * w); +w data type is NDArray; + +### Comment 3 by @lijianxin520 (2021-04-14T01:16:44Z) + +![image](https://user-images.githubusercontent.com/47262889/114640175-1b648500-9d02-11eb-8ef5-c75dcc150941.png) + + +### Comment 4 by @Nucs (2021-04-14T11:13:10Z) + +I mean what will this output on NumSharp 20.5? +``` C# +Console.WriteLine(w.dtype); +Console.WriteLine(s.dtype); +``` + +At version 30.x+ @Oceania2018 has removed many supported DTypes which might cause `NotSupportedException` or `NotImplementedException`. Some even return null. + +### Comment 5 by @lijianxin520 (2021-04-15T01:07:57Z) + +Thank you very much for your attention, the following is the supplementary content. +![image](https://user-images.githubusercontent.com/47262889/114799357-07845600-9dca-11eb-9374-e26c77e0e102.png) + + +### Comment 6 by @bigdimboom (2021-04-18T17:14:47Z) + +same problem. Is there a walkaround for now? + + +### Comment 7 by @Nucs (2021-04-21T04:46:24Z) + +@lijianxin520 I was not able to reproduce this locally, can you or @bigdimboom provide with a simple unit test that reproduces this and I'll take a deeper look. + +### Comment 8 by @ppsdatta (2021-04-23T10:14:54Z) + +Hello, +I encountered this problem as well and here's some data to help investigate: +1. A sample code which reproduces the problem on my Mac - Visual Studio. https://github.com/ppsdatta/NpSumIssue +2. With version 0.30.0 the code fails with the not supported error. +![Error screen shot](https://user-images.githubusercontent.com/18713580/115856850-9e948200-a44a-11eb-8a6a-4a0665002cad.png) +3. With version 0.20.5 the code works without runtime exception. +![No error screen shot](https://user-images.githubusercontent.com/18713580/115856971-c4ba2200-a44a-11eb-9e65-f97dbe509dbd.png) + + + +### Comment 9 by @badjano (2021-08-19T22:31:21Z) + +having exact same error, numsharp 0.30.0 +any workaround besides you know... for? + +### Comment 10 by @gv-collibris (2021-08-25T13:23:42Z) + +same error with NumSharp 0.30.0, with `np.sum(NDArray[])` + +### Comment 11 by @yuta0306 (2021-11-10T00:23:30Z) + +I also encountered the same error. +When the value of elements of NDArray is `double`, this error certainly occur. +To change the type `double` to `float` works well in my case. + +### Comment 12 by @guozifeng91 (2024-01-10T17:34:38Z) + +same error here, sum() works for int but not for double, using version 0.30.0 + +### Comment 13 by @PavanSuta (2024-02-26T22:17:27Z) + +I am using v4.0.30319 Numsharp. Getting the same error after calling the sum function. I am passing NDArray Double datatype. diff --git a/docs/issues/issue-0448-debug.assert-...-causes-tests-to-stop-the-entire-process.md b/docs/issues/issue-0448-debug.assert-...-causes-tests-to-stop-the-entire-process.md new file mode 100644 index 000000000..19bbb545d --- /dev/null +++ b/docs/issues/issue-0448-debug.assert-...-causes-tests-to-stop-the-entire-process.md @@ -0,0 +1,21 @@ +# #448: Debug.Assert(...) causes tests to stop the entire process + +- **URL:** https://github.com/SciSharp/NumSharp/issues/448 +- **State:** OPEN +- **Author:** @Nucs +- **Created:** 2021-04-23T12:03:33Z +- **Updated:** 2023-02-27T19:47:40Z +- **Labels:** bug +- **Assignees:** @Nucs + +## Description + +_No description provided._ + +## Comments + +### Comment 1 by @bojake (2023-02-27T19:47:40Z) + +The problem with this test is that the values array is not being broadcast/broadened properly. The assert expects the values array to match the size of the indices array. In this test case, though, the selector ("np < 3") is choosing 2 elements out of the 6 and the result is applying "-2" (which is another bug, btw). Changing the result value to "-2.0" gets past another bug but then you see where the actual bug in the SetIndiceND method resides. Before SetIndicesND can be called the "values" must be made to match the expected buffer size through implicit broadening. + +If you give "-2" as the value then the framework thinks you are setting the "size" of the NDArray for values instead of setting an actual value array of INTs. Oops. diff --git a/docs/issues/issue-0449-isclose-is-not-implemented-and-allclose-test-is-ignored.md b/docs/issues/issue-0449-isclose-is-not-implemented-and-allclose-test-is-ignored.md new file mode 100644 index 000000000..9b20e6cb4 --- /dev/null +++ b/docs/issues/issue-0449-isclose-is-not-implemented-and-allclose-test-is-ignored.md @@ -0,0 +1,26 @@ +# #449: IsClose is not implemented and allclose test is ignored + +- **URL:** https://github.com/SciSharp/NumSharp/issues/449 +- **State:** OPEN +- **Author:** @koliyo +- **Created:** 2021-04-28T17:23:19Z +- **Updated:** 2021-04-29T09:56:42Z +- **Labels:** missing feature/s + +## Description + +These should probably be removed from the API if they are not properly implemented? + +```cs + [Ignore("TODO: fix this test")] + [TestMethod] + public void np_allclose_1D() +``` + +```cs + public override NDArray IsClose(NDArray a, NDArray b, double rtol = 1.0E-5, double atol = 1.0E-8, bool equal_nan = false) + { + // ... lots of commeted out code + return null; + } +``` diff --git a/docs/issues/issue-0450-is-it-possible-to-add-numpy.diag.md b/docs/issues/issue-0450-is-it-possible-to-add-numpy.diag.md new file mode 100644 index 000000000..07c1e4ad1 --- /dev/null +++ b/docs/issues/issue-0450-is-it-possible-to-add-numpy.diag.md @@ -0,0 +1,12 @@ +# #450: Is it possible to add [numpy.diag]? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/450 +- **State:** OPEN +- **Author:** @syemhusa +- **Created:** 2021-05-05T20:29:13Z +- **Updated:** 2021-05-07T17:13:12Z +- **Labels:** missing feature/s + +## Description + +_No description provided._ diff --git a/docs/issues/issue-0451-np.argmax-is-slow.md b/docs/issues/issue-0451-np.argmax-is-slow.md new file mode 100644 index 000000000..7c70bdab7 --- /dev/null +++ b/docs/issues/issue-0451-np.argmax-is-slow.md @@ -0,0 +1,12 @@ +# #451: np.argmax is slow + +- **URL:** https://github.com/SciSharp/NumSharp/issues/451 +- **State:** OPEN +- **Author:** @feiyuhuahuo +- **Created:** 2021-06-18T01:46:57Z +- **Updated:** 2021-06-18T01:46:57Z + +## Description + +![image](https://user-images.githubusercontent.com/32631344/122493133-bb4bd100-d019-11eb-9a89-728c4465d4e0.png) +`nd` is an array with shape of (1, 13, 512, 512), the time consumption of doing argmax on it is about 500ms. That's really slow. Any way to improve it? diff --git a/docs/issues/issue-0452-missing-feature-s-numsharps-np.around-method-is-missing-decimals-parameter.md b/docs/issues/issue-0452-missing-feature-s-numsharps-np.around-method-is-missing-decimals-parameter.md new file mode 100644 index 000000000..4088cf486 --- /dev/null +++ b/docs/issues/issue-0452-missing-feature-s-numsharps-np.around-method-is-missing-decimals-parameter.md @@ -0,0 +1,15 @@ +# #452: [missing feature/s] NumSharp's np.around() method is missing decimals parameter which is available in NumPy + +- **URL:** https://github.com/SciSharp/NumSharp/issues/452 +- **State:** OPEN +- **Author:** @shashi4u +- **Created:** 2021-07-19T03:40:26Z +- **Updated:** 2021-07-19T03:59:32Z + +## Description + +In NumPy user has control over on how many decimal places the floating point number can be rounded to by setting **decimal** argument in **[numpy.around()](https://numpy.org/doc/stable/reference/generated/numpy.around.html)** method. + +However, NumSharp is missing this functionality. + +It would be better if this feature is added to NumSharp's np.around() method. diff --git a/docs/issues/issue-0454-ndarray.lstqr-doesnt-work.md b/docs/issues/issue-0454-ndarray.lstqr-doesnt-work.md new file mode 100644 index 000000000..91e817016 --- /dev/null +++ b/docs/issues/issue-0454-ndarray.lstqr-doesnt-work.md @@ -0,0 +1,15 @@ +# #454: NDArray.lstqr() doesn't work + +- **URL:** https://github.com/SciSharp/NumSharp/issues/454 +- **State:** OPEN +- **Author:** @yangjiandendi +- **Created:** 2021-07-24T18:39:31Z +- **Updated:** 2021-07-24T18:39:31Z + +## Description + +can you check why `NDArray.lstqr()` doesn't work? + +I wanna finish this part, in python it like `a = np.linalg.lstsq(x,y)` + +how does it work in Numsharp? diff --git a/docs/issues/issue-0455-numsharp-does-not-allow-building-with-il2cpp-via-unity.md b/docs/issues/issue-0455-numsharp-does-not-allow-building-with-il2cpp-via-unity.md new file mode 100644 index 000000000..906e1df5d --- /dev/null +++ b/docs/issues/issue-0455-numsharp-does-not-allow-building-with-il2cpp-via-unity.md @@ -0,0 +1,23 @@ +# #455: NumSharp does not allow building with IL2CPP via Unity + +- **URL:** https://github.com/SciSharp/NumSharp/issues/455 +- **State:** OPEN +- **Author:** @julia-koziel +- **Created:** 2021-07-27T09:14:17Z +- **Updated:** 2024-03-27T15:52:40Z + +## Description + +Hi, I am having trouble with building an Android app that is using a NumSharp package in Unity. + +This is the error that I keep receiving: +IL2CPP error for type 'NumSharp.LAPACKProviderType' in assembly '/UnityProject/Temp/StagingArea/assets/bin/Data/Managed/NumSharp.Core.dll' +Additional information: Value of type 'int' is too large to convert to short. + +Any help would be much appreciated! Thanks + +## Comments + +### Comment 1 by @jacob-jacob-jacob (2024-03-27T15:52:31Z) + +Were you ever able to solve this? diff --git a/docs/issues/issue-0456-silent-catastrophe-in-implicit-casting-singleton-array-to-value-type.md b/docs/issues/issue-0456-silent-catastrophe-in-implicit-casting-singleton-array-to-value-type.md new file mode 100644 index 000000000..18174e907 --- /dev/null +++ b/docs/issues/issue-0456-silent-catastrophe-in-implicit-casting-singleton-array-to-value-type.md @@ -0,0 +1,41 @@ +# #456: silent catastrophe in implicit casting singleton array to value type + +- **URL:** https://github.com/SciSharp/NumSharp/issues/456 +- **State:** OPEN +- **Author:** @dmacd +- **Created:** 2021-07-29T22:27:25Z +- **Updated:** 2021-07-29T22:28:14Z + +## Description + +Hi there! + +I love NumSharp and its been a key enabler of my current project (a neurofeedback platform built in Unity3d). +However I ran across some odd behavior I feel compelled to surface. Example: + +``` +var reactor_temp = +{-6.62420108914375} + +(float)reactor_temp +-4.03896783E-28 + +(int)reactor_temp +-1845493760 + +(double)reactor_temp +-6.6242010891437531 +``` + +In this example, the actual dtype of the singleton array was double, yet I'm freely (and _implicitly_) able to cast the object to other numeric types with no warning or error. This is....counterintuitive...to say the least, has cost me several hours of debugging time, and I'm frankly lucky to have even caught it at all. Fortunately, I'm only using numsharp to manipulate people's brainwaves and not fissile material just yet :) + + +(As an aside: The issue surfaced for me when I changed an operation np.sum to np.mean, which changed the output type on me, contrary to expectation) + +If the implicit conversions cant be type-guarded or converted in a sane manner, would it make more sense to just remove them? + +Once again, grateful for all hard work that went in to this library! +Daniel + + + diff --git a/docs/issues/issue-0461-np.save-incorrectly-saves-system.byte-arrays-as-signed.md b/docs/issues/issue-0461-np.save-incorrectly-saves-system.byte-arrays-as-signed.md new file mode 100644 index 000000000..88219a1c3 --- /dev/null +++ b/docs/issues/issue-0461-np.save-incorrectly-saves-system.byte-arrays-as-signed.md @@ -0,0 +1,27 @@ +# #461: np.save incorrectly saves System.Byte arrays as signed + +- **URL:** https://github.com/SciSharp/NumSharp/issues/461 +- **State:** OPEN +- **Author:** @rikkitook +- **Created:** 2021-08-04T12:06:31Z +- **Updated:** 2023-01-23T09:04:19Z + +## Description + +in function GetDtypeFromType +... +if (type == typeof(Byte)) + return "|i1"; +... +i1 gets translated to signed integer +https://numpy.org/doc/stable/user/basics.types.html + +## Comments + +### Comment 1 by @Cle-O (2023-01-23T09:03:24Z) + +Bump. This issue is still existing. +I am saving a numpy array (an image) with positive values only using _np.save()_. +Positive values only are verified calling _amin()_ on the array. +After reading the file again, the array contains negative values. +Is there a workaround for this? diff --git a/docs/issues/issue-0462-how-to-use-the-repo-to-convert-some-python-code.md b/docs/issues/issue-0462-how-to-use-the-repo-to-convert-some-python-code.md new file mode 100644 index 000000000..840419cef --- /dev/null +++ b/docs/issues/issue-0462-how-to-use-the-repo-to-convert-some-python-code.md @@ -0,0 +1,65 @@ +# #462: How to use the repo to convert some Python code? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/462 +- **State:** OPEN +- **Author:** @zydjohnHotmail +- **Created:** 2021-09-21T07:57:34Z +- **Updated:** 2021-12-01T05:58:40Z + +## Description + +Hello: +I have the following Python code to convert one RGB image to one YUV image, and use numpy to calculate an average of one column. + +`import cv2 +import numpy as np + +img_rgb = cv2.imread('C:/Images/1.PNG') +img_yuv = cv2.cvtColor(img_rgb,cv2.COLOR_BGR2YUV) +averageV = np.average(img_yuv[:,:,2]) +print(averageV); +` + +The Python code works well. Now, I want to change it to use C# code, as I have many other C# programs will need this averageV value. + +I have done the following: +1) I created one C# console project with Visual Studio 2019 (target .NET 5.0) +2) I installed necessary NUGET packages: +PM> Install-Package OpenCvSharp4 -Version 4.5.3.20210817 +PM> Install-Package NumSharp -Version 0.30.0 +3) I have the following C# code: +`using NumSharp; +using OpenCvSharp; +using System; + +namespace ConvertRGB2YUV +{ + class Program + { + public const string Image1_File = @"C:\Images\1.PNG"; + + static void Main(string[] args) + { + Mat img_rgb = Cv2.ImRead(Image1_File); + Mat img_yuv = img_rgb.CvtColor(ColorConversionCodes.RGB2YUV); + //var averageV = (img_yuv[:,:,2]); + //averageV = np.average(img_yuv[:,:, 2]) + } + } +}` + +I can run my code, and I can see the image: img_rgb and img_yuv. +But I have no idea on how to write the python corresponding statement: +averageV = np.average(img_yuv[:,:,2]) +In NumSharp, the img_yuv[…] simply doesn’t exist. +In Python, the img_yuv is treated like an array of float numbers. +How I can do this in NumSharp? +Please advise, +Thanks, + + +## Comments + +### Comment 1 by @QingtaoLi1 (2021-12-01T05:58:40Z) + +C# doesn't support this kind of indices or slices. I guess you can explore the `NumSharp.Slice` class to reach your target. diff --git a/docs/issues/issue-0464-new-api-request-to-port-np.random.triangular.md b/docs/issues/issue-0464-new-api-request-to-port-np.random.triangular.md new file mode 100644 index 000000000..305729216 --- /dev/null +++ b/docs/issues/issue-0464-new-api-request-to-port-np.random.triangular.md @@ -0,0 +1,14 @@ +# #464: New API request to port np.random.triangular + +- **URL:** https://github.com/SciSharp/NumSharp/issues/464 +- **State:** OPEN +- **Author:** @ppsdatta +- **Created:** 2021-11-23T11:50:37Z +- **Updated:** 2021-11-23T11:50:37Z + +## Description + +While porting a Python code to .NET using NumSharp as replacement for numpy - I found that there is no alternative version for `np.random.triangular` api present in NumSharp. I tried to search in the documents and didn't find any reference to it. Here is the link to the documentation for the API in numpy https://numpy.org/doc/stable/reference/random/generated/numpy.random.triangular.html + +NumSharp version I am using: `0.30.0`. + diff --git a/docs/issues/issue-0465-how-could-i-transform-between-numsharp.ndarray-with-tensorflow.numpy.ndarray.md b/docs/issues/issue-0465-how-could-i-transform-between-numsharp.ndarray-with-tensorflow.numpy.ndarray.md new file mode 100644 index 000000000..b27789656 --- /dev/null +++ b/docs/issues/issue-0465-how-could-i-transform-between-numsharp.ndarray-with-tensorflow.numpy.ndarray.md @@ -0,0 +1,18 @@ +# #465: how could I transform between NumSharp.NDArray with Tensorflow.Numpy.NDArray? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/465 +- **State:** OPEN +- **Author:** @cross-hello +- **Created:** 2021-11-24T06:38:01Z +- **Updated:** 2021-11-27T13:45:04Z + +## Description + +Both library complement the functionality of **Numpy** library. There are some lack for methods between. So I want to know the converting method. +Give me a hand~ + +## Comments + +### Comment 1 by @Oceania2018 (2021-11-27T13:45:04Z) + +What are the missing methods? diff --git a/docs/issues/issue-0466-bug-np.random.choice-raise-exception.md b/docs/issues/issue-0466-bug-np.random.choice-raise-exception.md new file mode 100644 index 000000000..60181c18c --- /dev/null +++ b/docs/issues/issue-0466-bug-np.random.choice-raise-exception.md @@ -0,0 +1,52 @@ +# #466: [Bug] np.random.choice raise Exception + +- **URL:** https://github.com/SciSharp/NumSharp/issues/466 +- **State:** OPEN +- **Author:** @QingtaoLi1 +- **Created:** 2021-11-30T07:54:33Z +- **Updated:** 2021-12-15T05:29:47Z + +## Description + +Hi, when using `np.random.choice`, I got an Exception with message "Specified method is not supported.", and the stack trace is: + +> at NumSharp.NPTypeCodeExtensions.GetAccumulatingType(NPTypeCode typeCode) +> at NumSharp.Backends.DefaultEngine.cumsum_elementwise(NDArray& arr, Nullable`1 typeCode) +> at NumSharp.Backends.DefaultEngine.ReduceCumAdd(NDArray& arr, Nullable`1 axis_, Nullable`1 typeCode) +> at NumSharp.np.cumsum(NDArray arr, Nullable`1 axis, Nullable`1 typeCode) + +## Comments + +### Comment 1 by @QingtaoLi1 (2021-11-30T07:57:42Z) + +It seems there is no UT for this function in this repo. + +### Comment 2 by @QingtaoLi1 (2021-11-30T08:00:22Z) + +Besides, another argument `replace` is not used at all in both overrides. + +### Comment 3 by @QingtaoLi1 (2021-11-30T08:28:09Z) + +I do a simple test on `np.cumsum` since it is in the stack trace: +> public static void RandomChoice() +> { +> var array = np.arange(1, 50265); +> var arrayDouble = 1.0 / array.astype(np.@double); +> var cumsum = np.cumsum(arrayDouble, typeCode: arrayDouble.typecode); // OK +> var cumsum2 = np.cumsum(arrayDouble); // raise Exception mentioned above +> } +> + +It looks like there's something wrong in the default typeCode. BTW, I'm using the latest NumSharp 0.30.0 version. + +### Comment 4 by @UCtreespring (2021-12-14T16:25:46Z) + +相同的问题,你解决了吗? + +### Comment 5 by @QingtaoLi1 (2021-12-15T02:55:05Z) + +目前发现的解决方案就是上面那样自己copy一个,加上typeCode就能跑了 + +### Comment 6 by @UCtreespring (2021-12-15T05:29:47Z) + +是我没有留意到那个“Ok”的注释,按照你的方案,我复制了官方Numsharp-master中的相关方法,添加了相关的typeCode参数,问题解决。非常感谢! diff --git a/docs/issues/issue-0467-numsharp-and-tensorflow.net-works-on-desktop-but-fails-on-cloud-web-service-.ne.md b/docs/issues/issue-0467-numsharp-and-tensorflow.net-works-on-desktop-but-fails-on-cloud-web-service-.ne.md new file mode 100644 index 000000000..df357174b --- /dev/null +++ b/docs/issues/issue-0467-numsharp-and-tensorflow.net-works-on-desktop-but-fails-on-cloud-web-service-.ne.md @@ -0,0 +1,39 @@ +# #467: NumSharp and Tensorflow.NET works on Desktop but fails on Cloud Web Service (.NET 5) + +- **URL:** https://github.com/SciSharp/NumSharp/issues/467 +- **State:** OPEN +- **Author:** @marsousi +- **Created:** 2021-12-06T04:56:23Z +- **Updated:** 2021-12-06T04:56:23Z + +## Description + +NumSharp and Tensorflow.NET work fine on my desktop computer. But once I publish it on the cloud service (Azure Web Service using ASP.NET Core - .NET 5), even running a simple code to define an NDArray gives the following error: + +_DllNotFoundException: Unable to load DLL 'tensorflow' or one of its dependencies: The specified module could not be found. (0x8007007E) +Tensorflow.c_api.TF_NewStatus() + +TypeInitializationException: The type initializer for 'Tensorflow.Binding' threw an exception. +Tensorflow.Binding.get_tf()_ + +The following packages are installed in Visual Studio Solution: + + +SciSharp.TensorFlow.Redist (2.3.1)
+NumSharp (0.30.0)
+NumSharp.Bitmap (0.30.0)
+SharpCV (0.10.1)
+Rensorflow.Net (0.60.5)
+Tensorflow.Keras (0.6.5)
+Google.Protobuf (3.19.1)
+Protobuf.Text (0.5.0)
+Serilog.Sinks.Console (4.0.1)
+ +and some more but I don't think they would interfere with the above packages +
+ +Besides, I tried to change the Release CPU from AnyCPU to x64, but then the cloud service fails running. + +Am I missing something? + + diff --git a/docs/issues/issue-0468-np-array.convolve-returning-null.md b/docs/issues/issue-0468-np-array.convolve-returning-null.md new file mode 100644 index 000000000..5bbabbf38 --- /dev/null +++ b/docs/issues/issue-0468-np-array.convolve-returning-null.md @@ -0,0 +1,202 @@ +# #468: np_array.convolve returning Null + +- **URL:** https://github.com/SciSharp/NumSharp/issues/468 +- **State:** OPEN +- **Author:** @dklein9500 +- **Created:** 2021-12-06T10:57:13Z +- **Updated:** 2022-06-26T22:42:49Z + +## Description + +Hi, +I am using this function to smooth some measurement data, sadly it returns null for some reason. +Here is the example code that produced the same result: + +``` +int filter_length = 5; +List data = new List() {1, 34, 3, 4, 22, 4, 24, 42, 24, 22, 4 }; // Just some random numbers for testing +var array = data.ToArray(); +NDArray np_array = new NDArray(array); +var filter = np.ones(filterLength); +NDArray filtered_array = np_array.convolve(filter, "same"); // Here null is returned +``` +There is probably a better way to construct the NDArray, but I think the code should still work. +What am I doing wrong? +Thanks in advance! + +## Comments + +### Comment 1 by @abbefus (2022-04-28T18:02:26Z) + +This is because someone put "return null" a few lines down in the code: + +``` +public NDArray convolve(NDArray rhs, string mode = "full") +{ + var lhs = this; + int nf = lhs.shape[0]; + int ng = rhs.shape[0]; + + if (ndim > 1 || rhs.ndim > 1) + throw new IncorrectShapeException(); + var retType = np._FindCommonType(lhs, rhs); + return null; +``` + +That's enough to guarantee you get null every time. Who knows if the rest of the code ever worked. + + +### Comment 2 by @guillermoe7 (2022-06-24T18:01:36Z) + +Also facing this problem. +Have any idea if this function was in working condition before? + +### Comment 3 by @abbefus (2022-06-24T19:14:29Z) + +This function works when it is rewritten, leading me to believe it did work before. Here is the function as I rewrote it -- verified against the python version. Sorry for my comments. + +``` +public static class NumpyExtensions +{ + + // NOTE: lhs must always be bigger than rhs -- + public static NDArray LinearConvolution(this NDArray lhs, NDArray rhs, ConvolveModes mode = ConvolveModes.Full) + { + if (lhs.ndim > 1 || rhs.ndim > 1) + throw new IncorrectShapeException("Both arrays must be 1-dimensional"); + + if (lhs.Shape.Size < rhs.Shape.Size) + throw new IncorrectShapeException("Right-hand side array must be smaller than left-hand side."); + + + // NOTE: + // NDArray.GetData just runs NDArray.Storage.GetData + // which returns NDArray.Storage.InternalArray == NDArray.Array + // so all three methods are practically interchangeable so why they had to make things complicated is beyond me + + ArraySlice lhsarr = lhs.GetData(); + ArraySlice rhsarr = rhs.GetData(); + + int nf = lhs.shape[0]; + int ng = rhs.shape[0]; + + + switch (mode) + { + case ConvolveModes.Full: + { + int n = nf + ng - 1; + + NDArray ret = new NDArray(Shape.Vector(n), true); + ArraySlice outArray = ret.GetData(); + + for (int idx = 0; idx < n; ++idx) + { + int jmn = (idx >= ng - 1) ? (idx - (ng - 1)) : 0; + int jmx = (idx < nf - 1) ? idx : nf - 1; + + for (int jdx = jmn; jdx <= jmx; ++jdx) + { + outArray[idx] += lhsarr[jdx] * rhsarr[idx - jdx]; + } + } + + return ret; + } + + case ConvolveModes.Valid: + { + var min_v = (nf < ng) ? lhsarr : rhsarr; + var max_v = (nf < ng) ? rhsarr : lhsarr; + + int n = Math.Max(nf, ng) - Math.Min(nf, ng) + 1; + + var ret = new NDArray(typeof(double), Shape.Vector(n), true); + ArraySlice outArray = ret.GetData(); + + for (int idx = 0; idx < n; ++idx) + { + int kdx = idx; + + for (int jdx = (min_v.Count - 1); jdx >= 0; --jdx) + { + outArray[idx] += min_v[jdx] * max_v[kdx]; + ++kdx; + } + } + + return ret; + } + + case ConvolveModes.Same: + { + // https://stackoverflow.com/questions/38194270/matlab-convolution-same-to-numpy-convolve + var npad = rhs.shape[0] - 1; + + if (npad % 2 == 1) + { + unsafe + { + npad = (int)Math.Floor(((double)npad) / 2.0); + + ArraySlice arr = ArraySlice.Allocate(npad + lhsarr.Count); + Span span = new Span(arr.VoidAddress, arr.Count); + lhsarr.CopyTo(span, npad); + var retnd = new NDArray(new UnmanagedStorage(arr, Shape.Vector(lhsarr.Count))); + return retnd.LinearConvolution(rhs, ConvolveModes.Valid); + } + } + else + { + throw new NotImplementedException("Cannot implement because NDArray.Address is protected."); + // I suppose we could extend NDArray and create a getter for Address + //{ + // unsafe + // { + // npad = npad / 2; + + // NPTypeCode retType = NPTypeCode.Double; + // NDArray puffer = new NDArray(retType, Shape.Vector(npad + lhsarr.Count), true); + // ArraySlice puffslice = puffer.Data(); // not sure this is equal to storage + // Span span = new Span(puffslice.VoidAddress, puffslice.Count); + // //lhsarr.CopyTo(puffer.Storage.AsSpan <#202>(), npad); + // lhsarr.CopyTo(span, npad); + // NDArray np1New = puffer; + + // puffer = new NDArray(retType, Shape.Vector(npad + np1New.size), true); + // int cpylen = np1New.size * sizeof(double); + // Buffer.MemoryCopy(np1New.Address, (double)puffer.Address) + npad, cpylen, cpylen); + // return puffer.convolve(rhs, "valid"); + // } + //} + } + } + default: + return lhs.LinearConvolution(rhs); + } + } +} +``` + +``` +public enum ConvolveModes +{ + Full, + Same, + Valid +} +``` + +### Comment 4 by @guillermoe7 (2022-06-26T22:42:49Z) + +Hello abbefus, + +Thanks a lot. That's quite a good code example. +Just one more bit of help. Seems my files are not up to date as there are some resources not available in my SliceAndDice install: +ArraySlice.Allocate() +ArraySlice.CopyTo() +Shape.Vector() + +Can you please show me where to get the proper version where these methods may be found? + +Thank you very much. diff --git a/docs/issues/issue-0470-numsharp0.30.0-np.random.choice-method-missing-cause-exception.md b/docs/issues/issue-0470-numsharp0.30.0-np.random.choice-method-missing-cause-exception.md new file mode 100644 index 000000000..4c94101ca --- /dev/null +++ b/docs/issues/issue-0470-numsharp0.30.0-np.random.choice-method-missing-cause-exception.md @@ -0,0 +1,25 @@ +# #470: Numsharp0.30.0 np.random.choice() method missing cause Exception + +- **URL:** https://github.com/SciSharp/NumSharp/issues/470 +- **State:** OPEN +- **Author:** @UCtreespring +- **Created:** 2021-12-14T10:52:50Z +- **Updated:** 2021-12-14T10:52:50Z + +## Description + +System.NotSupportedException + HResult=0x80131515 + Source=NumSharp + StackTrace: + at NumSharp.NPTypeCodeExtensions.GetAccumulatingType(NPTypeCode typeCode) + at NumSharp.Backends.DefaultEngine.cumsum_elementwise(NDArray& arr, Nullable`1 typeCode) + at NumSharp.Backends.DefaultEngine.ReduceCumAdd(NDArray& arr, Nullable`1 axis_, Nullable`1 typeCode) + at NumSharp.NumPyRandom.choice(Int32 a, Shape shape, Boolean replace, Double[] probabilities) + at NumSharp.NumPyRandom.choice(NDArray arr, Shape shape, Boolean replace, Double[] probabilities) + at PolicyGradient_TF050.PolicyGradient.ChooseAction(NDArray observation, NDArray actions, NDArray actionmask) + +I‘m new to this , + +Thanks for help. + diff --git a/docs/issues/issue-0471-unhandled-exception-system.notsupportedexception-specified-method-is-not-suppo.md b/docs/issues/issue-0471-unhandled-exception-system.notsupportedexception-specified-method-is-not-suppo.md new file mode 100644 index 000000000..c7fb89652 --- /dev/null +++ b/docs/issues/issue-0471-unhandled-exception-system.notsupportedexception-specified-method-is-not-suppo.md @@ -0,0 +1,17 @@ +# #471: Unhandled Exception: System.NotSupportedException: Specified method is not supported. + +- **URL:** https://github.com/SciSharp/NumSharp/issues/471 +- **State:** OPEN +- **Author:** @KonardAdams +- **Created:** 2021-12-15T16:57:20Z +- **Updated:** 2021-12-15T16:57:20Z + +## Description + +**I am getting an error at this line of code:** + `double theta3_2 = Math.Atan2(a3, d4) - Math.Atan2(K / p3, -np.sqrt(np.power(1 - (K / p3), 2)));` + +Unhandled Exception: System.NotSupportedException: Specified method is not supported. + at NumSharp.Backends.DefaultEngine.Negate(NDArray& nd) in D:\SciSharp\NumSharp\src\NumSharp.Core\Backends\Default\Math\Default.Negate.cs:line 119 + at NumSharp.NDArray.op_UnaryNegation(NDArray x) in D:\SciSharp\NumSharp\src\NumSharp.Core\Operations\Elementwise\NDArray.Primitive.cs:line 10 + at Robotics.InverseNP.Main(String[] args) in C:\Users\.......................... diff --git a/docs/issues/issue-0472-how-to-calculate-the-rank-of-a-matrix-with-numsharp.md b/docs/issues/issue-0472-how-to-calculate-the-rank-of-a-matrix-with-numsharp.md new file mode 100644 index 000000000..d85de8af7 --- /dev/null +++ b/docs/issues/issue-0472-how-to-calculate-the-rank-of-a-matrix-with-numsharp.md @@ -0,0 +1,15 @@ +# #472: How to calculate the rank of a matrix with NumSharp? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/472 +- **State:** OPEN +- **Author:** @drtujugkhjk +- **Created:** 2021-12-20T10:42:27Z +- **Updated:** 2021-12-20T10:42:27Z + +## Description + +I have a question,but I'm new to this. +I want to compute the rank of a matrix, but could not do it when I tried the following. + np.linalg.matrix_rank(A) ; + A:NDArray +What is wrong with it? How do I calculate the rank of a matrix? diff --git a/docs/issues/issue-0473-bit-shift-and-bit-or.md b/docs/issues/issue-0473-bit-shift-and-bit-or.md new file mode 100644 index 000000000..70825bb43 --- /dev/null +++ b/docs/issues/issue-0473-bit-shift-and-bit-or.md @@ -0,0 +1,16 @@ +# #473: Bit shift and bit or + +- **URL:** https://github.com/SciSharp/NumSharp/issues/473 +- **State:** OPEN +- **Author:** @MichielMans +- **Created:** 2021-12-28T13:21:27Z +- **Updated:** 2021-12-28T13:21:27Z + +## Description + +Is it possible to bit-shift and bit-or all values in a NDArray with NumSharp, whiteout a for loop? With Numpy (python) is works as follows: + +r_shift = r<<8 +g_shift = g<<0 +rg_concat = r_shift|g_shift + diff --git a/docs/issues/issue-0475-tobitmap-fails-if-not-contiguous-because-of-broadcast-mismatch.md b/docs/issues/issue-0475-tobitmap-fails-if-not-contiguous-because-of-broadcast-mismatch.md new file mode 100644 index 000000000..adf1c52ca --- /dev/null +++ b/docs/issues/issue-0475-tobitmap-fails-if-not-contiguous-because-of-broadcast-mismatch.md @@ -0,0 +1,12 @@ +# #475: ToBitmap fails if not contiguous because of Broadcast mismatch + +- **URL:** https://github.com/SciSharp/NumSharp/issues/475 +- **State:** OPEN +- **Author:** @ponzis +- **Created:** 2022-02-09T15:51:52Z +- **Updated:** 2022-02-09T15:54:08Z + +## Description + +When using the `public static unsafe Bitmap ToBitmap(this NDArray nd, int width, int height, PixelFormat format = PixelFormat.DontCare)` passing a NDArray of shape (1, x, y, 3) fails due to broadcast mismatch at `(LeftShape, RightShape) = DefaultEngine.Broadcast(lhs.Shape, rhs.Shape);` due to broadcasting with `(x*y*3)` and `(1, x, y, 3)` the work around is to clone the NDArray so that it is continues or change the shape of the function so that it has a correct shape. + diff --git a/docs/issues/issue-0476-numsharp.core-contains-many-debug.assert-lines.md b/docs/issues/issue-0476-numsharp.core-contains-many-debug.assert-lines.md new file mode 100644 index 000000000..7b0ba1687 --- /dev/null +++ b/docs/issues/issue-0476-numsharp.core-contains-many-debug.assert-lines.md @@ -0,0 +1,14 @@ +# #476: Numsharp.Core contains many Debug.Assert() lines + +- **URL:** https://github.com/SciSharp/NumSharp/issues/476 +- **State:** OPEN +- **Author:** @rtwalterson +- **Created:** 2022-03-30T20:56:02Z +- **Updated:** 2022-03-30T20:56:02Z + +## Description + +great work at your side. +simply don't understand the reason why. +example: file Default.NonZero.cs + diff --git a/docs/issues/issue-0477-different-result-between-numpy-and-numsharp-with-np.matmul-function.md b/docs/issues/issue-0477-different-result-between-numpy-and-numsharp-with-np.matmul-function.md new file mode 100644 index 000000000..fe7838800 --- /dev/null +++ b/docs/issues/issue-0477-different-result-between-numpy-and-numsharp-with-np.matmul-function.md @@ -0,0 +1,43 @@ +# #477: Different Result between NumPy and NumSharp with np.matmul Function + +- **URL:** https://github.com/SciSharp/NumSharp/issues/477 +- **State:** OPEN +- **Author:** @Koyamin +- **Created:** 2022-04-05T15:29:06Z +- **Updated:** 2022-09-09T18:42:50Z + +## Description + +I am a new learner of NumSharp and now I want to calculate the matmul product of two NDArrays by using `np.matmul` function: +```Csharp +using NumSharp; + +var a = np.arange(2 * 2 * 3).reshape((2, 2, 3)); +var b = np.array(new double[] { 1, 2, 3 }); +var res = np.matmul(a, b); +``` +The value of `res` is as follow: +``` +[[6], [24]] +``` +However I have tried the same code in Python: +```Python +import numpy as np + +a = np.arange(2*2*3).reshape((2,2,3)) +b = np.array([1,2,3]) +res = np.matmul(a, b) +``` +Now the value of `res` is +``` +[[ 8 26] + [44 62]] +``` +I have no idea about it. I want to get the result in Python, what should I do? + +## Comments + +### Comment 1 by @ChengYen-Tang (2022-09-09T18:42:50Z) + +這個專案好像已經沒有在維護了,我有發現一個更完善的專案 +https://github.com/Quansight-Labs/numpy.net diff --git a/docs/issues/issue-0479-lacking-outdated-documentation.md b/docs/issues/issue-0479-lacking-outdated-documentation.md new file mode 100644 index 000000000..5eaf98568 --- /dev/null +++ b/docs/issues/issue-0479-lacking-outdated-documentation.md @@ -0,0 +1,19 @@ +# #479: Lacking/Outdated Documentation + +- **URL:** https://github.com/SciSharp/NumSharp/issues/479 +- **State:** OPEN +- **Author:** @Tianmaru +- **Created:** 2022-08-16T00:19:13Z +- **Updated:** 2022-09-09T18:40:32Z + +## Description + +Many methods don't seem to be documented at all, or did I just fail to find the right place to look for? +Also, is this project still maintained or is it discontinued? Seems like not much happened since the release of Numpy.NET, which is a pity. + +## Comments + +### Comment 1 by @ChengYen-Tang (2022-09-09T18:40:32Z) + +I found a more complete package, maybe you can try it. +https://github.com/Quansight-Labs/numpy.net diff --git a/docs/issues/issue-0480-numsharp-equivalent-for-unravel-index.md b/docs/issues/issue-0480-numsharp-equivalent-for-unravel-index.md new file mode 100644 index 000000000..dd66e857d --- /dev/null +++ b/docs/issues/issue-0480-numsharp-equivalent-for-unravel-index.md @@ -0,0 +1,18 @@ +# #480: Numsharp equivalent for unravel_index + +- **URL:** https://github.com/SciSharp/NumSharp/issues/480 +- **State:** OPEN +- **Author:** @iainross +- **Created:** 2022-08-30T15:49:50Z +- **Updated:** 2022-09-09T18:40:19Z + +## Description + +I can't find anything that maps onto `numpy.unravel_index` - is it missing from the `NumSharp` API or am I missing something? + +## Comments + +### Comment 1 by @ChengYen-Tang (2022-09-09T18:40:19Z) + +I found a more complete package, maybe you can try it. +https://github.com/Quansight-Labs/numpy.net diff --git a/docs/issues/issue-0481-normal-disttribution-in-numsharp.md b/docs/issues/issue-0481-normal-disttribution-in-numsharp.md new file mode 100644 index 000000000..51a0de4f1 --- /dev/null +++ b/docs/issues/issue-0481-normal-disttribution-in-numsharp.md @@ -0,0 +1,14 @@ +# #481: Normal disttribution in NumSharp + +- **URL:** https://github.com/SciSharp/NumSharp/issues/481 +- **State:** OPEN +- **Author:** @rthota90 +- **Created:** 2022-10-11T17:19:38Z +- **Updated:** 2022-10-11T17:19:38Z + +## Description + +Hi, + +I am looking for a solution to do normal distributions NORM.S.INV, NORM.S.DIST in C# .NET. +Is it possible to achieve using NumSharp? If so How? diff --git a/docs/issues/issue-0482-c-java-optaplanner.md b/docs/issues/issue-0482-c-java-optaplanner.md new file mode 100644 index 000000000..ad3ad2269 --- /dev/null +++ b/docs/issues/issue-0482-c-java-optaplanner.md @@ -0,0 +1,11 @@ +# #482: 大佬,能否用C#还原 java 的一个求解器 optaplanner + +- **URL:** https://github.com/SciSharp/NumSharp/issues/482 +- **State:** OPEN +- **Author:** @JavaScript-zt +- **Created:** 2022-12-07T08:33:17Z +- **Updated:** 2022-12-07T08:33:17Z + +## Description + +optaplanner 用于复杂的APS,目前C#生态却没有一个类似这样的工具,建议大佬用C#实现一下。谢谢 diff --git a/docs/issues/issue-0483-how-to-convert-list-ndarray-to-ndarray.md b/docs/issues/issue-0483-how-to-convert-list-ndarray-to-ndarray.md new file mode 100644 index 000000000..fab5b619e --- /dev/null +++ b/docs/issues/issue-0483-how-to-convert-list-ndarray-to-ndarray.md @@ -0,0 +1,22 @@ +# #483: How to convert List to NDArray + +- **URL:** https://github.com/SciSharp/NumSharp/issues/483 +- **State:** OPEN +- **Author:** @williamlzw +- **Created:** 2022-12-13T14:12:14Z +- **Updated:** 2022-12-13T14:13:02Z + +## Description + +str = '00000.jpg 130,83,205,108,0 130,137,154,161,1 255,137,279,160,2 125,186,177,208,3 210,186,236,208,4 285,186,311,208,5 130,237,400,292,6 230,328,555,354,7' +line = str.split() +box = np.array([np.array(list(map(int, box.split(','))))for box in line[1:]]) +print(box) + +string str = "00000.jpg 130,83,205,108,0 130,137,154,161,1 255,137,279,160,2 125,186,177,208,3 210,186,236,208,4 285,186,311,208,5 130,237,400,292,6 230,328,555,354,7"; +var line = str.Split(); +List> allList = new List>(); +var boxarr = line.Skip(1).Select(box => np.array(box.Split(',').Select(int.Parse))).ToList(); +var aa = boxarr.ToArray();//How to convert List\ to NDArray + + diff --git a/docs/issues/issue-0484-np.load-system.exception.md b/docs/issues/issue-0484-np.load-system.exception.md new file mode 100644 index 000000000..30a690981 --- /dev/null +++ b/docs/issues/issue-0484-np.load-system.exception.md @@ -0,0 +1,21 @@ +# #484: np.load System.Exception + +- **URL:** https://github.com/SciSharp/NumSharp/issues/484 +- **State:** OPEN +- **Author:** @Kiord +- **Created:** 2022-12-20T13:31:58Z +- **Updated:** 2022-12-20T13:31:58Z + +## Description + +I am loading several arrays in Unity using NumSharp's `np.load`. It works well for most of them but one throws an exception : + +![image](https://user-images.githubusercontent.com/79104227/208677853-547fae45-ffaa-4106-8670-6876fd810665.png) + +In NumPy `np.load` works fine for this this array. + +[here is a link to download this specific array](https://github.com/SciSharp/NumSharp/files/10268745/array.zip). + +What is the reason behind this exception ? + +Thank you diff --git a/docs/issues/issue-0485-np.linalg.norm-not-support.md b/docs/issues/issue-0485-np.linalg.norm-not-support.md new file mode 100644 index 000000000..63887eaaa --- /dev/null +++ b/docs/issues/issue-0485-np.linalg.norm-not-support.md @@ -0,0 +1,11 @@ +# #485: np.linalg.norm not support + +- **URL:** https://github.com/SciSharp/NumSharp/issues/485 +- **State:** OPEN +- **Author:** @williamlzw +- **Created:** 2022-12-22T03:35:00Z +- **Updated:** 2022-12-22T03:35:00Z + +## Description + +np.linalg.norm not support diff --git a/docs/issues/issue-0486-slice-assign.md b/docs/issues/issue-0486-slice-assign.md new file mode 100644 index 000000000..3cd0d26db --- /dev/null +++ b/docs/issues/issue-0486-slice-assign.md @@ -0,0 +1,29 @@ +# #486: Slice assign + +- **URL:** https://github.com/SciSharp/NumSharp/issues/486 +- **State:** OPEN +- **Author:** @burungiu +- **Created:** 2023-01-30T10:42:54Z +- **Updated:** 2023-02-28T17:38:50Z + +## Description + +Hello everyone, there is a way to do assigment as in python? +Example: +`preds[:, :, 0] = preds[:, :, 0] % heatmapWidth` + +Thank you + +## Comments + +### Comment 1 by @bojake (2023-02-28T17:38:50Z) + +There is an issue with auto-broadening of scalar operands in the framework. + +For instance: + +var foo = (array > 12f); // fails +var foo = np.full(12f, array.shape); +var result = (array > foo); // successful + +In your "heatmapWidth" operand just create an "np.full(heatmapWidth, preds.shape)" NDArray and use that as the operand. I bet that will work for you. diff --git a/docs/issues/issue-0487-linspace-to-array-as-type-float-while-other-functions-as-type-double.md b/docs/issues/issue-0487-linspace-to-array-as-type-float-while-other-functions-as-type-double.md new file mode 100644 index 000000000..1816c4379 --- /dev/null +++ b/docs/issues/issue-0487-linspace-to-array-as-type-float-while-other-functions-as-type-double.md @@ -0,0 +1,25 @@ +# #487: linspace to Array as type float, while other functions as type double + +- **URL:** https://github.com/SciSharp/NumSharp/issues/487 +- **State:** OPEN +- **Author:** @changjian-github +- **Created:** 2023-02-13T12:51:52Z +- **Updated:** 2023-02-13T12:52:41Z + +## Description + +``` +using NumSharp; + +class Program +{ + static void Main(string[] args) + { + double[] x = np.arange(-1, 1.1, 0.1).ToArray(); + float[] y = np.linspace(-1, 1, 21).ToArray(); + double[] z = np.random.rand(21).ToArray(); + Console.WriteLine("compile passed"); + } +} +``` +Changing float to double will result in an error. diff --git a/docs/issues/issue-0488-np.random.choice-raised-system.notsupportedexception.md b/docs/issues/issue-0488-np.random.choice-raised-system.notsupportedexception.md new file mode 100644 index 000000000..d504c7c30 --- /dev/null +++ b/docs/issues/issue-0488-np.random.choice-raised-system.notsupportedexception.md @@ -0,0 +1,35 @@ +# #488: np.random.choice raised System.NotSupportedException + +- **URL:** https://github.com/SciSharp/NumSharp/issues/488 +- **State:** OPEN +- **Author:** @alvinfebriando +- **Created:** 2023-02-15T06:20:28Z +- **Updated:** 2023-02-27T22:57:51Z + +## Description + +error on np.random.choice, it said "Specified method isn not supported". Is my usage wrong? + +```csharp +var score = np.arange(1,6); +var p = new[] { 0.2, 0.2, 0.2, 0.2, 0.2 }; +var result = np.random.choice(score, probabilities: p); +``` + +Stack trace +``` +Unhandled exception. System.NotSupportedException: Specified method is not supported. + at NumSharp.NPTypeCodeExtensions.GetAccumulatingType(NPTypeCode typeCode) + at NumSharp.Backends.DefaultEngine.cumsum_elementwise(NDArray& arr, Nullable`1 typeCode) + at NumSharp.Backends.DefaultEngine.ReduceCumAdd(NDArray& arr, Nullable`1 axis_, Nullable`1 typeCode) + at NumSharp.np.cumsum(NDArray arr, Nullable`1 axis, Nullable`1 typeCode) + at NumSharp.NumPyRandom.choice(Int32 a, Shape shape, Boolean replace, Double[] probabilities) + at NumSharp.NumPyRandom.choice(NDArray arr, Shape shape, Boolean replace, Double[] probabilities) + at Program.
$(String[] args) +``` + +## Comments + +### Comment 1 by @bojake (2023-02-27T22:57:51Z) + +I created a test case with your exact code and ran it using my dev fork of NumSharp. No errors were produced. Are you using an out dated NumSharp? diff --git a/docs/issues/issue-0490-np.random.choice-with-replace-false-produces-duplicates.md b/docs/issues/issue-0490-np.random.choice-with-replace-false-produces-duplicates.md new file mode 100644 index 000000000..873a43ece --- /dev/null +++ b/docs/issues/issue-0490-np.random.choice-with-replace-false-produces-duplicates.md @@ -0,0 +1,13 @@ +# #490: np.random.choice with replace: false produces duplicates + +- **URL:** https://github.com/SciSharp/NumSharp/issues/490 +- **State:** OPEN +- **Author:** @GThibeault +- **Created:** 2023-03-06T00:04:52Z +- **Updated:** 2023-03-06T00:04:52Z + +## Description + +e.g. np.random.choice(71, new Shape(40), **replace: false**) is producing duplicates. + +I've tried setting the seed to provide a reproducible example, but that doesn't seem to work either. diff --git a/docs/issues/issue-0491-tobitmap-datatype-mistmatch.md b/docs/issues/issue-0491-tobitmap-datatype-mistmatch.md new file mode 100644 index 000000000..4d6d0c575 --- /dev/null +++ b/docs/issues/issue-0491-tobitmap-datatype-mistmatch.md @@ -0,0 +1,21 @@ +# #491: ToBitmap() - datatype mistmatch + +- **URL:** https://github.com/SciSharp/NumSharp/issues/491 +- **State:** OPEN +- **Author:** @davidvct +- **Created:** 2023-03-08T09:12:45Z +- **Updated:** 2023-03-08T09:12:45Z + +## Description + +I tried to convert a numsharp array with integers to bitmap. + +``` +array_rgb_numsharp = array_rgb_numsharp.reshape(1, 300, 300, 3); +Bitmap image = array_rgb_numsharp.ToBitmap(); +``` +and encounter this error: +System.InvalidCastException: 'Unable to perform CopyTo when T does not match dtype, use non-generic overload instead.' + +How can I fix it? + diff --git a/docs/issues/issue-0492-critical-vulnerability-in-version-5.0.2-of-system.drawing.common.md b/docs/issues/issue-0492-critical-vulnerability-in-version-5.0.2-of-system.drawing.common.md new file mode 100644 index 000000000..7287b9fe5 --- /dev/null +++ b/docs/issues/issue-0492-critical-vulnerability-in-version-5.0.2-of-system.drawing.common.md @@ -0,0 +1,17 @@ +# #492: critical vulnerability in version 5.0.2 of system.drawing.common + +- **URL:** https://github.com/SciSharp/NumSharp/issues/492 +- **State:** OPEN +- **Author:** @jkl-ds +- **Created:** 2023-03-17T15:26:36Z +- **Updated:** 2023-03-17T15:27:51Z + +## Description + +"When a .NET application utilizing libgdiplus on a non-Windows system accepts input, an attacker could send a specially crafted request that could result in remote code execution." + +https://github.com/dotnet/announcements/issues/176 + +Please upgrade to version 5.0.3 or higher. + +https://github.com/SciSharp/NumSharp/blob/master/src/NumSharp.Bitmap/NumSharp.Bitmap.csproj#L78 diff --git a/docs/issues/issue-0493-numsharp-array-output-in-.net-interactive-notebooks-is-misleading.md b/docs/issues/issue-0493-numsharp-array-output-in-.net-interactive-notebooks-is-misleading.md new file mode 100644 index 000000000..6f31e8ba8 --- /dev/null +++ b/docs/issues/issue-0493-numsharp-array-output-in-.net-interactive-notebooks-is-misleading.md @@ -0,0 +1,13 @@ +# #493: Numsharp array output in .net interactive notebooks is misleading + +- **URL:** https://github.com/SciSharp/NumSharp/issues/493 +- **State:** OPEN +- **Author:** @oxygen-dioxide +- **Created:** 2023-03-23T06:47:54Z +- **Updated:** 2023-03-23T06:47:54Z + +## Description + +image + +In [.net interactive notebooks](https://github.com/dotnet/interactive), no matter how many dimensions an array has, it will be output as an 1d array. diff --git a/docs/issues/issue-0494-hello-has-scisharp-numsharp-stopped-development-and-maintenance.md b/docs/issues/issue-0494-hello-has-scisharp-numsharp-stopped-development-and-maintenance.md new file mode 100644 index 000000000..118547a0f --- /dev/null +++ b/docs/issues/issue-0494-hello-has-scisharp-numsharp-stopped-development-and-maintenance.md @@ -0,0 +1,22 @@ +# #494: Hello, has SciSharp/NumSharp stopped development and maintenance? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/494 +- **State:** OPEN +- **Author:** @sdyby2006 +- **Created:** 2023-07-03T01:24:46Z +- **Updated:** 2024-03-31T17:58:17Z + +## Description + +Hello, has SciSharp/NumSharp stopped development and maintenance? + +## Comments + +### Comment 1 by @HCareLou (2023-09-11T16:39:49Z) + +I think so,it's so sad. + +### Comment 2 by @tingspain (2024-03-31T17:58:16Z) + +Any news about this topic? + diff --git a/docs/issues/issue-0495-what-is-the-exposed-method-for-percentiles-median-using-np.md b/docs/issues/issue-0495-what-is-the-exposed-method-for-percentiles-median-using-np.md new file mode 100644 index 000000000..b7ca0f7b8 --- /dev/null +++ b/docs/issues/issue-0495-what-is-the-exposed-method-for-percentiles-median-using-np.md @@ -0,0 +1,11 @@ +# #495: What is the exposed method for percentiles & median using np? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/495 +- **State:** OPEN +- **Author:** @vikassingh281 +- **Created:** 2023-07-19T09:40:57Z +- **Updated:** 2023-07-19T09:40:57Z + +## Description + +_No description provided._ diff --git a/docs/issues/issue-0496-can-numsharp-fit-polynomial-surface-equations.md b/docs/issues/issue-0496-can-numsharp-fit-polynomial-surface-equations.md new file mode 100644 index 000000000..dc6feab57 --- /dev/null +++ b/docs/issues/issue-0496-can-numsharp-fit-polynomial-surface-equations.md @@ -0,0 +1,11 @@ +# #496: Can NumSharp fit polynomial surface equations? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/496 +- **State:** OPEN +- **Author:** @liyu3519 +- **Created:** 2023-08-10T05:59:24Z +- **Updated:** 2023-08-10T05:59:24Z + +## Description + +Can NumSharp fit polynomial surface equations? diff --git a/docs/issues/issue-0497-np.linalg.pinv-not-supported.md b/docs/issues/issue-0497-np.linalg.pinv-not-supported.md new file mode 100644 index 000000000..ecf198cb2 --- /dev/null +++ b/docs/issues/issue-0497-np.linalg.pinv-not-supported.md @@ -0,0 +1,23 @@ +# #497: np.linalg.pinv not supported + +- **URL:** https://github.com/SciSharp/NumSharp/issues/497 +- **State:** OPEN +- **Author:** @gsgou +- **Created:** 2023-08-12T12:35:37Z +- **Updated:** 2023-10-20T17:05:22Z + +## Description + +Here is a link to what I think is the python sources for np.linalg: +https://github.com/numpy/numpy/blob/master/numpy/linalg/linalg.py + +Other implementations: +https://github.com/TheAlgorithms/C-Sharp/blob/master/Algorithms/Numeric/Pseudoinverse/PseudoInverse.cs +https://github.com/accord-net/framework/blob/master/Sources/Accord.Math/Matrix/Matrix.Linear.Generated.cs#L298 + + +## Comments + +### Comment 1 by @YariLAN (2023-10-20T17:05:22Z) + +It’s very necessary, by the way - I have a lab on it(( diff --git a/docs/issues/issue-0498-is-there-an-example-on-how-to-use-it-with-ironpython.md b/docs/issues/issue-0498-is-there-an-example-on-how-to-use-it-with-ironpython.md new file mode 100644 index 000000000..32181ce27 --- /dev/null +++ b/docs/issues/issue-0498-is-there-an-example-on-how-to-use-it-with-ironpython.md @@ -0,0 +1,27 @@ +# #498: Is there an example on how to use it with IronPython? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/498 +- **State:** OPEN +- **Author:** @william19941994 +- **Created:** 2023-08-22T01:52:28Z +- **Updated:** 2023-08-22T01:52:28Z + +## Description + +I have a big project using c# + wpf +.net framework 4. and I can upgrade to 4.8 or 4.7.2 +and a supplier send some python examples to me. +I have to add some python script to the old project. I don't want to rewrite. + +I added IronPython yesterday, but it uses hardware communication lib, I replaced with a c# object. +and then, I found that it uses numpy. +I added another small c# class. +and then, I found that it uses lots of numpy functions. +I download this project and added a wrapper class to redirect the result. +and then, this project need System.Memory.dll 4.0.1.1, while my project has 4.5.5 .... +and I changed the prj.exe.config to lower dll version. +my exe can't run now. + +I'm re-compiling this csprj now. + +Does anyone have done this before? and where can I find a whole example or blog? + diff --git a/docs/issues/issue-0499-possible-typo-tomulidimarray.md b/docs/issues/issue-0499-possible-typo-tomulidimarray.md new file mode 100644 index 000000000..f11f9f061 --- /dev/null +++ b/docs/issues/issue-0499-possible-typo-tomulidimarray.md @@ -0,0 +1,21 @@ +# #499: Possible typo "ToMuliDimArray()" + +- **URL:** https://github.com/SciSharp/NumSharp/issues/499 +- **State:** OPEN +- **Author:** @sappho192 +- **Created:** 2023-08-30T11:52:05Z +- **Updated:** 2024-06-12T04:11:55Z + +## Description + +Hi, recently I've been using this library and stumbled upon this method. + +https://github.com/SciSharp/NumSharp/blob/1fed94d2e556a7fdfc815775db68f9c8f195298a/src/NumSharp.Core/Casting/NdArrayToMultiDimArray.cs#L31 + +Is `ToMuliDimArray()` typo of `ToMultiDimArray()`? + +## Comments + +### Comment 1 by @sappho192 (2024-06-12T04:11:55Z) + +I've found that there'd been the pull request related to this #474 by @Karthick47v2 but don't know why it has been closed. diff --git a/docs/issues/issue-0500-the-fact-that-such-an-excellent-project-has-many-unimplemented-apis-and-is-no-lo.md b/docs/issues/issue-0500-the-fact-that-such-an-excellent-project-has-many-unimplemented-apis-and-is-no-lo.md new file mode 100644 index 000000000..210dfa878 --- /dev/null +++ b/docs/issues/issue-0500-the-fact-that-such-an-excellent-project-has-many-unimplemented-apis-and-is-no-lo.md @@ -0,0 +1,11 @@ +# #500: The fact that such an excellent project has many unimplemented APIs and is no longer being maintained is regrettable. + +- **URL:** https://github.com/SciSharp/NumSharp/issues/500 +- **State:** OPEN +- **Author:** @HCareLou +- **Created:** 2023-09-11T16:41:52Z +- **Updated:** 2023-09-11T16:41:52Z + +## Description + +The fact that such an excellent project has many unimplemented APIs and is no longer being maintained is regrettable. diff --git a/docs/issues/issue-0501-memory-leak.md b/docs/issues/issue-0501-memory-leak.md new file mode 100644 index 000000000..f3869d6de --- /dev/null +++ b/docs/issues/issue-0501-memory-leak.md @@ -0,0 +1,65 @@ +# #501: Memory leak? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/501 +- **State:** OPEN +- **Author:** @TakuNishiumi +- **Created:** 2023-12-13T07:32:29Z +- **Updated:** 2023-12-13T07:32:29Z + +## Description + +Hi, +I tried below code and usage rate of my memory increased up to around 10GB. + +```C# +// 配列を宣言する +double[] array = new double[110]; + +// 乱数を生成する +Random rnd = new Random(); + +// 配列に乱数を代入する +// make random double array +for (int i = 0; i < array.Length; i++) +{ + array[i] = rnd.NextDouble(); +} + +// make new NDarray in loop +for (int i = 0; i < 1000000; i++) +{ + NDArray array2 = np.array(array); + // NDArray array2 = np.argmin(array); also cause same trouble +} +``` +This is also caused when this is used as function. +I modified this and add GC.Collect(). +This make the code usage rate of my memory, but the calculation time increased. + +```C# +// 配列を宣言する +double[] array = new double[110]; + +// 乱数を生成する +Random rnd = new Random(); + +// 配列に乱数を代入する +// make random double array +for (int i = 0; i < array.Length; i++) +{ + array[i] = rnd.NextDouble(); +} + +// make new NDarray in loop +for (int i = 0; i < 1000000; i++) +{ + NDArray array2 = np.array(array); + if (i % 10000 == 0) + { + GC.Collect(); + } +} +``` + +What should I do next? +Do you have any ideas? diff --git a/docs/issues/issue-0505-np.convolve-return-null-exception.md b/docs/issues/issue-0505-np.convolve-return-null-exception.md new file mode 100644 index 000000000..09639c357 --- /dev/null +++ b/docs/issues/issue-0505-np.convolve-return-null-exception.md @@ -0,0 +1,23 @@ +# #505: `np.convolve` return null exception + +- **URL:** https://github.com/SciSharp/NumSharp/issues/505 +- **State:** OPEN +- **Author:** @behroozbc +- **Created:** 2023-12-25T14:42:33Z +- **Updated:** 2023-12-25T14:42:33Z + +## Description + +I am new to this repository, and I want to test a convolve funcation but I got `System.NullReferenceException: Object reference not set to an instance of an object.`. I am using the NumSharp version: 0.30.0 and .net sdk version: 8.0.100 my code is simple, which I wrote in a console app. +``` +using NumSharp; +var f = np.array(new int[] { 3, 3, 2, 1, 2 }); +var g = np.array(new int[] { -1, 2, 1 }); +var outp=np.convolve(f,g, "valid"); +Console.WriteLine(outp.ToString()); +``` +the full error message +``` +Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object. + at Program.
$(String[] args) in E:\repos\ConsoleApp7\ConsoleApp7\Program.cs:line 7 +``` diff --git a/docs/issues/issue-0506-cannot-create-an-ndarray-of-shorts.md b/docs/issues/issue-0506-cannot-create-an-ndarray-of-shorts.md new file mode 100644 index 000000000..dfb3f7e7b --- /dev/null +++ b/docs/issues/issue-0506-cannot-create-an-ndarray-of-shorts.md @@ -0,0 +1,13 @@ +# #506: Cannot create an NDArray of shorts + +- **URL:** https://github.com/SciSharp/NumSharp/issues/506 +- **State:** OPEN +- **Author:** @NickBotelho +- **Created:** 2024-01-24T14:19:58Z +- **Updated:** 2024-01-24T14:19:58Z + +## Description + +When I try to initialize an NDArray with the short type, it throws a System.NotSupportedException. It seems like it only does this with shorts, every other type works fine. Heres a line of code to run to reproduce + +`var nd = new NDArray(dtype: np.int16, shape: new Shape(new []{1, 2}));` diff --git a/docs/issues/issue-0507-np.maximum-error.md b/docs/issues/issue-0507-np.maximum-error.md new file mode 100644 index 000000000..c8cf39fe5 --- /dev/null +++ b/docs/issues/issue-0507-np.maximum-error.md @@ -0,0 +1,188 @@ +# #507: np.maximum error + +- **URL:** https://github.com/SciSharp/NumSharp/issues/507 +- **State:** OPEN +- **Author:** @Thanatos0173 +- **Created:** 2024-02-16T18:29:17Z +- **Updated:** 2024-02-17T14:43:40Z + +## Description + +Hello, +I'm working on a Neural Network for the video game Celeste, and I'm using Numsharp to convert a code that a friend made, but he used python. +Currently, I'm calling a train function a huge number of time, and randomly, this error pops out : +``` +One or more errors occurred. +-> at System.Threading.Tasks.Task.ThrowIfExceptional() +-> at System.Threading.Tasks.Task.Wait() +-> at System.Threading.Tasks.Task.Wait() +-> at System.Threading.Tasks.Parallel.ForWorker[TLocal]() +-> at System. Threading.Tasks. Parallel.For() +-> at NumSharp. Backends. DefaultEngine.ClipNDArray() +-> at NumSharp.np.maximum() +``` +I've googled it but found nothing relevant. +I don't really know if I can do a proper reproductible exemple, but if you need more informations about this error, i would be pleased to send them. + +Here is some of the code : + +```csharp + public static void TrainCommand() + { + NeuralNetwork.NeuralNetwork.Open(); + + for (int i = 0; i < Directory.GetFiles("Mia/Saves","*",SearchOption.AllDirectories).Length/2; i++) + { + var tdimarray = np.load($"Mia/Saves/ArraySaved_{i}.npy"); // 20x20 array + var tdiminput = np.load($"Mia/Saves/InputSaved_{i}.npy"); // 56x1 array + for(int j = 0; j < 10_000; j++) + { + double[] input = (double[])(Array)tdiminput[j]; + NeuralNetwork.NeuralNetwork.Train(lr, tdimarray[j], Utils.AllArrayFromOld(input )); + } + } + } +``` + +```csharp + public class FirstLayers + { + public NDArray weights; + public NDArray biases; + public NDArray inputs; + public NDArray outputNotActivated; + public NDArray output; + public NDArray outputGradient; + public FirstLayers(NDArray weights, NDArray biases) + { + this.weights = weights; + this.biases = biases; + } + + public void Forward(NDArray inputs) + { + this.inputs = inputs; + this.outputNotActivated = np.dot(inputs, this.weights) + this.biases; //np.dot + this.output = np.maximum(0, this.outputNotActivated); + } + + public void FirstLayerBackward(NDArray inputGradient, double learningRate) + { + bool one = DerivRelu(this.outputNotActivated) == null; + inputGradient = inputGradient * DerivRelu(this.outputNotActivated); + this.outputGradient = np.dot(inputGradient, this.weights.T); + this.weights -= np.dot(this.inputs.T, inputGradient) * learningRate / inputGradient.shape[0]; + this.biases -= np.mean(inputGradient, axis: 0) * learningRate; + } + + public NDArray DerivRelu(NDArray x) + { + NDArray result = np.zeros(x.Shape); + for (int i = 0; i < x.Shape[0]; i++) + { + for (int j = 0; j < x.Shape[1]; j++) + { + result[i, j] = (x[i, j].Data()[0] > 0 ? 1 : 0); + } + } + return result; + } + + } + + public class LastLayer + { + public NDArray weights; + public NDArray biases; + public NDArray inputs; + public NDArray outputGradient; + public NDArray output; + + public LastLayer(NDArray weights, NDArray biases) + { + this.weights = weights; + this.biases = biases; + } + + public void Forward(NDArray inputs) + { + this.inputs = inputs; + NDArray outputNotActivated = np.dot(inputs, this.weights) + this.biases; + NDArray expValues = np.exp(outputNotActivated - np.max(outputNotActivated, axis: 1, keepdims: true)); + this.output = expValues / np.sum(expValues.astype(NPTypeCode.Float), axis: 1, keepdims: true); + } + + public void LastLayerBackward(NDArray yPred, NDArray yTrue, double learningRate) + { + NDArray inputGradient = yPred - yTrue; + this.outputGradient = np.dot(inputGradient, this.weights.T); + this.weights -= np.dot(this.inputs.T, inputGradient) * learningRate / inputGradient.shape[0]; + this.biases -= np.mean(inputGradient, axis: 0) * learningRate; + } + } + + private static Tuple, LastLayer> nn; + + public static void Open() + { + var weights = new List (); + var biases = new List (); + foreach(string file in Directory.GetFiles("Mia/weights")) + { + weights.Add(np.load (file)); + } + foreach (string file in Directory.GetFiles("Mia/biases")) + { + biases.Add(np.load(file)); + } + + int n = weights.Count; + + nn = new Tuple, LastLayer>( + new List(), + new LastLayer(weights[n - 1], biases[n - 1])); // I gave it a new value... We'll see. + for (int j = 0; j < n - 1; j++) + { + nn.Item1.Add(new FirstLayers(weights[j], biases[j])); + } + } + + public static void Train(double lr, NDArray allTiles, int[] keypress) + { + NDArray trueInputs = allTiles.reshape(1, 400); + NDArray labels = new NDArray(keypress); + + NDArray output = ForPropagation(trueInputs); + + + BackPropagation(output, labels, lr); + + + } + public static NDArray ForPropagation(NDArray input) + { + nn.Item1[0].Forward(input); + for (int i = 1; i < nn.Item1.Count; i++) // Adding all the values inside of FirstLayer + { + nn.Item1[i].Forward(nn.Item1[i - 1].output); + } + + nn.Item2.Forward(nn.Item1[nn.Item1.Count - 1].output); + + return nn.Item2.output; + } + + public static void BackPropagation(NDArray yPred, NDArray yTrue, double lr) + { + // Your implementation for the BackPropagation function + nn.Item2.LastLayerBackward(yPred, yTrue, lr); + nn.Item1[nn.Item1.Count - 1].FirstLayerBackward(nn.Item2.outputGradient, lr); + for (int i = nn.Item1.Count - 3; i >= 0; i--) + { + nn.Item1[i].FirstLayerBackward(nn.Item1[i + 1].outputGradient, lr); + } + } + } +} + +``` diff --git a/docs/issues/issue-0508-np.hstack-has-diffrent-effect-from-python.md b/docs/issues/issue-0508-np.hstack-has-diffrent-effect-from-python.md new file mode 100644 index 000000000..45831d041 --- /dev/null +++ b/docs/issues/issue-0508-np.hstack-has-diffrent-effect-from-python.md @@ -0,0 +1,54 @@ +# #508: np.hstack has diffrent effect from python + +- **URL:** https://github.com/SciSharp/NumSharp/issues/508 +- **State:** OPEN +- **Author:** @xdqa01 +- **Created:** 2024-02-17T08:19:50Z +- **Updated:** 2024-02-18T00:28:53Z + +## Description + +Windows 10@19044.2364 +Dotnet@net8.0-windows,wpf +NumSharp@0.30.0 +OpenCvSharp4@4.9.0.20240103 +Python@3.12 + + +NumSharp np.hstack(img1,img2,img3) +```csharp + var image1 = Cv2.ImRead(FirstImagePath).NotNull().ResizeToStandardSize(); + var image2 = Cv2.ImRead(SecondImagePath).NotNull().ResizeToStandardSize(); + var image3 = Cv2.ImRead(ThirdImagePath).NotNull().ResizeToStandardSize(); + var imageArray = np.hstack(image1.ToNDArray(), image2.ToNDArray(), image3.ToNDArray()); + var image = imageArray.ToMat(); + Cv2.ImShow(WindowName, image); + FourthImageSource = image.ToBitmapSource(); +``` + +print +- img1 +- img2 +- img3 + +python np.hstack(img1,img2,img3) +```python + img1 = cv.imread("./static/fllower.jpg") + img2 = cv.imread("./static/lake.jpg") + img3 = cv.imread("./static/mountain.jpg") + img1 = cv.resize(img1, (200, 200)) + img2 = cv.resize(img2, (200, 200)) + img3 = cv.resize(img3, (200, 200)) + imgs = np.hstack([img1, img2, img3]) + cv.imshow("multi_pic", imgs) +``` + +print +img1 img2 img3 + + +And,if i use code below,it print like python np.hstack +```csharp +var imageArray = np.dstack(image1.ToNDArray(), image2.ToNDArray(), image3.ToNDArray()); +``` + diff --git a/docs/issues/issue-0509-extremely-poor-performance-on-sum-reduce.md b/docs/issues/issue-0509-extremely-poor-performance-on-sum-reduce.md new file mode 100644 index 000000000..6fafa8f88 --- /dev/null +++ b/docs/issues/issue-0509-extremely-poor-performance-on-sum-reduce.md @@ -0,0 +1,92 @@ +# #509: Extremely poor performance on sum reduce + +- **URL:** https://github.com/SciSharp/NumSharp/issues/509 +- **State:** OPEN +- **Author:** @lucdem +- **Created:** 2024-02-19T23:32:37Z +- **Updated:** 2024-03-27T04:09:12Z + +## Description + +Creating a large 3 dimensional array and calling sum(axis: 0) takes an enormous amount of time on my machine (11s), far more than Numpy (around 75ms) or even just a simple C# naive implementation (around 200ms). + +C# Code: + +``` +using NumSharp; +using System.Diagnostics; +using System.Linq; + +namespace NumSharpTest; + +internal class Program +{ + static void Main(string[] args) + { + Console.WriteLine("NumSharp"); + NumSharp(); + Console.WriteLine("#######################"); + Console.WriteLine("Naive"); + Naive(); + } + + static void NumSharp() + { + var randArr = np.random.uniform(0, 1, [500, 500, 500]).astype(np.float32); + + var stopwatch = new Stopwatch(); + stopwatch.Start(); + var linesSum = randArr.sum(axis: 0); + stopwatch.Stop(); + Console.WriteLine($"Elapsed: {stopwatch.ElapsedMilliseconds} ms"); + } + + static void Naive() + { + var random = new Random(); + var shape = new int[] { 500, 500, 500 }; + var randArr = new float[shape[0] * shape[1] * shape[2]]; + for (int i = 0; i < randArr.Length; i++) { randArr[i] = (float)random.NextDouble(); } + + var stopwatch = new Stopwatch(); + stopwatch.Start(); + var sum = new float[shape[1] * shape[2]]; + for (int i = 0; i < shape[0]; i++) + { + for (int j = 0; j < shape[1]; j++) + { + for (int k = 0; k < shape[2]; k++) + { + sum[shape[2] * j + k] += randArr[shape[1] * shape[2] * i + shape[2] * j + k]; + } + } + } + stopwatch.Stop(); + Console.WriteLine($"Elapsed: {stopwatch.ElapsedMilliseconds} ms"); + } +} + + +``` + +Python Code: + +``` +import numpy as np +from time import time + +randArr = np.random.normal(1, 0.5, (500, 500, 500)) + +start = time() +sum = randArr.sum(axis=0) +end = time() + +print(f'Elapsed: {(end - start) * 1000} ms') +``` + +## Comments + +### Comment 1 by @vkribo (2024-03-27T04:09:11Z) + +I profiled it and the problem seems to be in the method GetOffset in the Shape class. In the method there is a list called coords being created milions of times. I tried reimplementing it using a stackalloced array instead and it went from 6287 ms to 2315 ms. +Maybe someone more familliar with the code could look into it. diff --git a/docs/issues/issue-0510-how-to-save-a-nested-dictionary-with-save-npz.md b/docs/issues/issue-0510-how-to-save-a-nested-dictionary-with-save-npz.md new file mode 100644 index 000000000..bd42a4b40 --- /dev/null +++ b/docs/issues/issue-0510-how-to-save-a-nested-dictionary-with-save-npz.md @@ -0,0 +1,25 @@ +# #510: How to save a nested dictionary with `save_npz` + +- **URL:** https://github.com/SciSharp/NumSharp/issues/510 +- **State:** OPEN +- **Author:** @rqx110 +- **Created:** 2024-03-07T01:20:45Z +- **Updated:** 2024-03-07T01:20:45Z + +## Description + +If i have a data struct like: +```json +{ + "port1": { + "time": ["xxxx", "yyyy"], + "data": [0.0, 0.0] + }, + "port2": { + "time": ["xxxx", "yyyy"], + "data": [0.0, 0.0] + }, +} +``` +how to save it with `save_npz`? +can you give same sample codes? Thanks! diff --git a/docs/issues/issue-0511-does-numsharp-work-in-unity-with-the-il2cpp-backend.md b/docs/issues/issue-0511-does-numsharp-work-in-unity-with-the-il2cpp-backend.md new file mode 100644 index 000000000..4e4ea7e06 --- /dev/null +++ b/docs/issues/issue-0511-does-numsharp-work-in-unity-with-the-il2cpp-backend.md @@ -0,0 +1,13 @@ +# #511: Does Numsharp work in Unity with the IL2CPP backend? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/511 +- **State:** OPEN +- **Author:** @jacob-jacob-jacob +- **Created:** 2024-03-27T15:28:35Z +- **Updated:** 2024-03-27T15:28:35Z + +## Description + +In the following thread there is some nice advice on how to set up Numsharp in unity: +https://github.com/SciSharp/NumSharp/issues/353 +However, I've been asking myself if people have tested its performance. I reccon that it should work well with the Unitys Mono backend, but will it also have relatively good performance if choosing the IL2CPP backend? diff --git a/docs/issues/issue-0512-how-to-change-to-microsoft.ml.onnxruntime.tensors.densetensor-float.md b/docs/issues/issue-0512-how-to-change-to-microsoft.ml.onnxruntime.tensors.densetensor-float.md new file mode 100644 index 000000000..07034a74c --- /dev/null +++ b/docs/issues/issue-0512-how-to-change-to-microsoft.ml.onnxruntime.tensors.densetensor-float.md @@ -0,0 +1,26 @@ +# #512: how to change to Microsoft.ML.OnnxRuntime.Tensors.DenseTensor? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/512 +- **State:** OPEN +- **Author:** @BingGitCn +- **Created:** 2024-04-01T09:13:01Z +- **Updated:** 2024-04-01T09:13:01Z + +## Description + + public static void ExtractPixelsArgb(DenseTensor tensor, Span data, int pixelCount) + { + Span spanR = tensor.Buffer.Span; + Span spanG = spanR[pixelCount..]; + Span spanB = spanG[pixelCount..]; + + int sidx = 0; + for (int i = 0; i < pixelCount; i++) + { + spanR[i] = data[sidx + 2] * 0.0039215686274509803921568627451f; + spanG[i] = data[sidx + 1] * 0.0039215686274509803921568627451f; + spanB[i] = data[sidx] * 0.0039215686274509803921568627451f; + sidx += 4; + } + } +Is there a faster way than this? diff --git a/docs/issues/issue-0514-setitem-for-multiple-ids-not-working.md b/docs/issues/issue-0514-setitem-for-multiple-ids-not-working.md new file mode 100644 index 000000000..ee7c2030b --- /dev/null +++ b/docs/issues/issue-0514-setitem-for-multiple-ids-not-working.md @@ -0,0 +1,41 @@ +# #514: SetItem for multiple Ids not working + +- **URL:** https://github.com/SciSharp/NumSharp/issues/514 +- **State:** OPEN +- **Author:** @MaxOmlor +- **Created:** 2024-06-03T07:57:24Z +- **Updated:** 2024-06-03T07:57:24Z + +## Description + +```C# +[Test] + public void MultiIdSetItem() + { + var a = np.arange(5); + Debug.Log($"a = {a}"); + var ids = np.array(new int[] { 1, 3 }); + Debug.Log($"ids = {ids}"); + var newValues = np.array(new int[] { 10, 20 }); + Debug.Log($"newValues = {newValues}"); + + a[ids] = newValues; + Debug.Log($"after set item: a = {a}"); + + var expected = np.array(new[] { 0, 10, 2, 20, 4 }); + Assert.AreEqual(expected, a); + } +``` +Output: +``` +Expected and actual are both + Values differ at index [1] + Expected: 10 + But was: 1 +--- +a = [0, 1, 2, 3, 4] +ids = [1, 3] +newValues = [10, 20] +after set item: a = [0, 1, 2, 3, 4] +``` + diff --git a/docs/issues/issue-0515-np.tile-not-implemented.md b/docs/issues/issue-0515-np.tile-not-implemented.md new file mode 100644 index 000000000..3607cc5bf --- /dev/null +++ b/docs/issues/issue-0515-np.tile-not-implemented.md @@ -0,0 +1,11 @@ +# #515: np.tile not implemented + +- **URL:** https://github.com/SciSharp/NumSharp/issues/515 +- **State:** OPEN +- **Author:** @MaxOmlor +- **Created:** 2024-06-03T10:08:23Z +- **Updated:** 2024-06-03T10:08:23Z + +## Description + +getting message 'Cannot resolve symbol 'tile'' when i try to use np.tile diff --git a/docs/issues/issue-0516-very-helpful-work.-keep-at-it.md b/docs/issues/issue-0516-very-helpful-work.-keep-at-it.md new file mode 100644 index 000000000..4dc2e33a2 --- /dev/null +++ b/docs/issues/issue-0516-very-helpful-work.-keep-at-it.md @@ -0,0 +1,11 @@ +# #516: Very helpful work. Keep at it + +- **URL:** https://github.com/SciSharp/NumSharp/issues/516 +- **State:** OPEN +- **Author:** @duxuan11 +- **Created:** 2024-08-13T08:13:55Z +- **Updated:** 2024-08-13T08:13:55Z + +## Description + +Such a great job, hope to continue to deal with issues, come on. diff --git a/docs/issues/issue-0517-error-when-loading-a-.npy-file-containing-a-scalar-value.md b/docs/issues/issue-0517-error-when-loading-a-.npy-file-containing-a-scalar-value.md new file mode 100644 index 000000000..30c121b84 --- /dev/null +++ b/docs/issues/issue-0517-error-when-loading-a-.npy-file-containing-a-scalar-value.md @@ -0,0 +1,12 @@ +# #517: Error when loading a `.npy` file containing a scalar value + +- **URL:** https://github.com/SciSharp/NumSharp/issues/517 +- **State:** OPEN +- **Author:** @thalesfm +- **Created:** 2024-09-24T17:56:29Z +- **Updated:** 2024-09-24T17:56:29Z + +## Description + +Due to an off-by-one error, `np.load` fails to parse the file's header when `shape = ()` and triggers an `ArgumentOutOfRangeException` +(Also, the function doesn't consider this possibility when calculating the size of the underlying buffer). diff --git a/docs/issues/issue-0519-bug-ndarray-filted-array-ori-array-max-prob-conf-threshold.md b/docs/issues/issue-0519-bug-ndarray-filted-array-ori-array-max-prob-conf-threshold.md new file mode 100644 index 000000000..a2f5bc964 --- /dev/null +++ b/docs/issues/issue-0519-bug-ndarray-filted-array-ori-array-max-prob-conf-threshold.md @@ -0,0 +1,18 @@ +# #519: BUG: NDArray filted_array = ori_array[max_prob > conf_threshold]; + +- **URL:** https://github.com/SciSharp/NumSharp/issues/519 +- **State:** OPEN +- **Author:** @1Zengy +- **Created:** 2024-11-11T09:09:51Z +- **Updated:** 2024-11-11T09:09:51Z + +## Description + +In the C# code, NDArray filted_array = ori_array[max_prob > conf_threshold]; +Here, `ori_array` is an `NDArray` with a shape of [1, 8400, 5], where 5 represents the five probabilities of 5 classes. `max_prob` is an `NDArray` with a shape of [1, 8400], indicating the maximum probability among the 5 classes. `conf_threshold` is a float value which represents the threshold of probability. + +I would like to delete the objects in the 8400 dimension where the maximum probability is lower than the `conf_threshold`. However, even though I have ensured that `ori_array` and `max_prob` have the same values, the code will randomly return either an exact value with a shape of [n, 5] or a null value with a shape of [0, 5]. Here is my data saved using "np.save()". +[ori_array.json](https://github.com/user-attachments/files/17699927/ori_array.json) +[max_prob.json](https://github.com/user-attachments/files/17699931/max_prob.json) + + diff --git a/docs/issues/issue-0520-cant-convert-to-vector3.md b/docs/issues/issue-0520-cant-convert-to-vector3.md new file mode 100644 index 000000000..d18e090ed --- /dev/null +++ b/docs/issues/issue-0520-cant-convert-to-vector3.md @@ -0,0 +1,21 @@ +# #520: Can't convert to Vector3 + +- **URL:** https://github.com/SciSharp/NumSharp/issues/520 +- **State:** OPEN +- **Author:** @xiaoshux +- **Created:** 2025-03-12T06:09:51Z +- **Updated:** 2025-12-16T13:45:12Z + +## Description + +In Unity, this bug trapped me for 5 days—I couldn't pass values into Vector3. I don't recommend using NumSharp! + +![Image](https://github.com/user-attachments/assets/1e1ee948-510f-4373-b02d-a8b7bc0bef4f) + +![Image](https://github.com/user-attachments/assets/35dfd893-3a91-4496-abda-9ce46aa10268) + +## Comments + +### Comment 1 by @zhuoshui-AI (2025-12-16T13:45:12Z) + +Bcausse in this a[1,1,1] return tpye is NDarray of one element.Not a scalar. try to use .getInt32() np.asscalar()to get a pure number diff --git a/docs/issues/issue-0523-multi-threading-supported.md b/docs/issues/issue-0523-multi-threading-supported.md new file mode 100644 index 000000000..82bc2baa2 --- /dev/null +++ b/docs/issues/issue-0523-multi-threading-supported.md @@ -0,0 +1,11 @@ +# #523: Multi-threading supported? + +- **URL:** https://github.com/SciSharp/NumSharp/issues/523 +- **State:** OPEN +- **Author:** @sawyermade +- **Created:** 2025-09-09T19:10:24Z +- **Updated:** 2025-09-09T19:10:24Z + +## Description + +I was wondering how multi-threading works with this, Numpy.NET doesnt allow it and you have to lock the GIL, since this is all in native C#, is "no real multi-threading" like in Numpy.NET a problem with this library? Thanks for your time and have a great day. diff --git a/docs/manifest.json b/docs/manifest.json deleted file mode 100644 index 6994f5187..000000000 --- a/docs/manifest.json +++ /dev/null @@ -1,395 +0,0 @@ -{ - "homepages": [], - "source_base_path": "C:/Users/KAC2ST/GitHub/NumSharp/docfx_project", - "xrefmap": "xrefmap.yml", - "files": [ - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Core.Extensions.NDArrayExtensions.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Core.Extensions.NDArrayExtensions.html", - "hash": "sRQzNU8b8C1bQ02hzMTfwQ==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Core.Extensions.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Core.Extensions.html", - "hash": "hG2v/Fulj3Khfz/gQ3fdpg==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Core.Interfaces.IShape.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Core.Interfaces.IShape.html", - "hash": "LIzW4Lsr8qydT5CWlOnGNg==" - } - }, - "is_incremental": true, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Core.Interfaces.IStorage.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Core.Interfaces.IStorage.html", - "hash": "9YgCDj9Y/Nrn9wPsI62CLg==" - } - }, - "is_incremental": true, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Core.Interfaces.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Core.Interfaces.html", - "hash": "tMq88azXIF+BU7SPkCaqCw==" - } - }, - "is_incremental": true, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Core.LAPACK.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Core.LAPACK.html", - "hash": "3EGFB6QDoQmSZbQE0oNmkw==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Core.Manipulation.NumPy.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Core.Manipulation.NumPy.html", - "hash": "bMtwBAC/Psyy6xrwHzJf0Q==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Core.Manipulation.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Core.Manipulation.html", - "hash": "k2+Q5hrJCh0X4tRdi4WYHQ==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Core.NDArray.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Core.NDArray.html", - "hash": "VVX028sHaxDdD9sWXFERDA==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Core.NDArrayRandomExtensions.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Core.NDArrayRandomExtensions.html", - "hash": "q4E8BgWQdPR6H62oNIoWRA==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Core.NDStorage.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Core.NDStorage.html", - "hash": "qPcqIx4EudcOtS9CZd5FvA==" - } - }, - "is_incremental": true, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Core.NumPyRandom.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Core.NumPyRandom.html", - "hash": "cRiiHr+b0LayXcXF44onDw==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Core.Shape.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Core.Shape.html", - "hash": "m95I3Nf85USD6SS2BZcUmA==" - } - }, - "is_incremental": true, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Core.Slice.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Core.Slice.html", - "hash": "PtWnURvKOsry+uJwZ1Mk8Q==" - } - }, - "is_incremental": true, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Core.matrix.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Core.matrix.html", - "hash": "6LYGpdDvx+WFIpDCVv9Njg==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Core.np.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Core.np.html", - "hash": "ZJLc76nk0kLCEm/mfu1rJQ==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Core.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Core.html", - "hash": "VdUKDFoOn0biV4RV3zNMag==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Generic.NDArray-1.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Generic.NDArray-1.html", - "hash": "3715+Gmi8ATgWJjsz+KjWQ==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "ManagedReference", - "source_relative_path": "api/NumSharp.Generic.yml", - "output": { - ".html": { - "relative_path": "api/NumSharp.Generic.html", - "hash": "yOTxlJr2dlBw0Vg8Yz3PEA==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "Conceptual", - "source_relative_path": "api/index.md", - "output": { - ".html": { - "relative_path": "api/index.html", - "hash": "SQeko4I7ApfRdkE5XoQ8CA==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "Toc", - "source_relative_path": "api/toc.yml", - "output": { - ".html": { - "relative_path": "api/toc.html", - "hash": "/OB9zMJCNLVqeUFkNsVmOw==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "Conceptual", - "source_relative_path": "articles/NDArray.Creation.md", - "output": { - ".html": { - "relative_path": "articles/NDArray.Creation.html", - "hash": "Kl9EJo7ocCkdMbsxATnrIw==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "Conceptual", - "source_relative_path": "articles/NDArray.LinAlg.md", - "output": { - ".html": { - "relative_path": "articles/NDArray.LinAlg.html", - "hash": "Vhf+qXU/g/4GZXFGuRgfpA==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "Conceptual", - "source_relative_path": "articles/intro.md", - "output": { - ".html": { - "relative_path": "articles/intro.html", - "hash": "y5iN4VEFDtycfsCI73EKAQ==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "Toc", - "source_relative_path": "articles/toc.yml", - "output": { - ".html": { - "relative_path": "articles/toc.html", - "hash": "Ao4weLW79Kg/nkMBj7lT+Q==" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "Resource", - "source_relative_path": "images/python-csharp-comparision.png", - "output": { - "resource": { - "relative_path": "images/python-csharp-comparision.png" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "Resource", - "source_relative_path": "images/rowWise_ColumnWise.png", - "output": { - "resource": { - "relative_path": "images/rowWise_ColumnWise.png" - } - }, - "is_incremental": false, - "version": "" - }, - { - "type": "Conceptual", - "source_relative_path": "index.md", - "output": { - ".html": { - "relative_path": "index.html", - "hash": "oxT/YIdDuKMxSX9nXEp5VQ==" - } - }, - "is_incremental": true, - "version": "" - }, - { - "type": "Toc", - "source_relative_path": "toc.yml", - "output": { - ".html": { - "relative_path": "toc.html", - "hash": "sg3p87VbBWcK30qmego3TQ==" - } - }, - "is_incremental": false, - "version": "" - } - ], - "incremental_info": [ - { - "status": { - "can_incremental": true, - "incrementalPhase": "build" - }, - "processors": { - "TocDocumentProcessor": { - "can_incremental": false, - "details": "Processor TocDocumentProcessor cannot support incremental build because the processor doesn't implement ISupportIncrementalDocumentProcessor interface.", - "incrementalPhase": "build" - }, - "ResourceDocumentProcessor": { - "can_incremental": false, - "details": "Processor ResourceDocumentProcessor cannot support incremental build because the processor doesn't implement ISupportIncrementalDocumentProcessor interface.", - "incrementalPhase": "build" - }, - "ConceptualDocumentProcessor": { - "can_incremental": true, - "incrementalPhase": "build" - }, - "ManagedReferenceDocumentProcessor": { - "can_incremental": true, - "incrementalPhase": "build" - } - } - }, - { - "status": { - "can_incremental": true, - "details": "Can support incremental post processing.", - "incrementalPhase": "postProcessing" - }, - "processors": {} - } - ], - "version_info": {}, - "groups": [ - { - "xrefmap": "xrefmap.yml" - } - ] -} \ No newline at end of file diff --git a/docs/numpy/NUMPY_FUNCTIONS.md b/docs/numpy/NUMPY_FUNCTIONS.md new file mode 100644 index 000000000..e10a39e13 --- /dev/null +++ b/docs/numpy/NUMPY_FUNCTIONS.md @@ -0,0 +1,383 @@ +# NumPy 2.4.2 vs NumSharp: Function Comparison + +This document provides a comprehensive comparison of `np.*` functions between NumPy 2.4.2 and NumSharp, identifying missing functions and prioritizing them by popularity. + +## Summary + +| Category | NumPy 2.4.2 | NumSharp | Missing | +|----------|-------------|----------|---------| +| Callable np.* functions | 404 | 177 | 239 | +| Coverage | 100% | 44% | 56% | + +**Note:** NumPy count excludes type aliases, constants, modules, and dtype classes. NumSharp count includes static `np.*` functions only (instance methods listed separately below). + +--- + +## NumSharp Supported Functions (177 static functions) + +### Array Creation (31) +`arange`, `array`, `asanyarray`, `asarray`, `broadcast`, `broadcast_arrays`, `broadcast_to`, `concatenate`, `copy`, `dstack`, `empty`, `empty_like`, `eye`, `frombuffer`, `FromMultiDimArray`, `FromString`, `full`, `full_like`, `hstack`, `identity`, `linspace`, `meshgrid`, `mgrid`, `ndarray`, `ones`, `ones_like`, `Scalar`, `stack`, `vstack`, `zeros`, `zeros_like` + +### Math - Arithmetic (55) +`abs`, `absolute`, `add`, `arccos`, `arcsin`, `arctan`, `arctan2`, `around`, `cbrt`, `ceil`, `clip`, `convolve`, `cos`, `cosh`, `deg2rad`, `degrees`, `divide`, `exp`, `exp2`, `expm1`, `floor`, `floor_divide`, `fmax`, `fmin`, `invert`, `bitwise_not`, `left_shift`, `log`, `log10`, `log1p`, `log2`, `maximum`, `minimum`, `mod`, `modf`, `multiply`, `negative`, `positive`, `power`, `rad2deg`, `radians`, `reciprocal`, `right_shift`, `round`, `round_`, `sign`, `sin`, `sinh`, `sqrt`, `square`, `subtract`, `tan`, `tanh`, `true_divide`, `trunc` + +### Reductions (25) +`all`, `amax`, `amin`, `any`, `argmax`, `argmin`, `count_nonzero`, `cumprod`, `cumsum`, `max`, `mean`, `min`, `nanmax`, `nanmean`, `nanmin`, `nanprod`, `nanstd`, `nansum`, `nanvar`, `prod`, `size`, `std`, `sum`, `var` + +### Logic & Comparison (27) +`allclose`, `are_broadcastable`, `array_equal`, `can_cast`, `equal`, `greater`, `greater_equal`, `isclose`, `iscomplex`, `iscomplexobj`, `isfinite`, `isinf`, `isnan`, `isreal`, `isrealobj`, `isscalar`, `issctype`, `isdtype`, `issubdtype`, `issubsctype`, `less`, `less_equal`, `logical_and`, `logical_not`, `logical_or`, `logical_xor`, `not_equal` + +### Shape Manipulation (17) +`asscalar`, `atleast_1d`, `atleast_2d`, `atleast_3d`, `copyto`, `expand_dims`, `moveaxis`, `ravel`, `repeat`, `reshape`, `roll`, `rollaxis`, `squeeze`, `swapaxes`, `transpose`, `unique` + +### Sorting & Searching (6) +`argmax`, `argmin`, `argsort`, `nonzero`, `searchsorted` + +### Splitting (5) +`array_split`, `dsplit`, `hsplit`, `split`, `vsplit` + +### Linear Algebra (3) +`dot`, `matmul`, `outer` + +### Random (np.random.*) (46) +`bernoulli`, `beta`, `binomial`, `chisquare`, `choice`, `dirichlet`, `exponential`, `f`, `gamma`, `geometric`, `gumbel`, `hypergeometric`, `laplace`, `logistic`, `lognormal`, `logseries`, `multinomial`, `multivariate_normal`, `negative_binomial`, `noncentral_chisquare`, `noncentral_f`, `normal`, `pareto`, `permutation`, `poisson`, `power`, `rand`, `randint`, `randn`, `random`, `random_sample`, `rayleigh`, `seed`, `shuffle`, `standard_cauchy`, `standard_exponential`, `standard_gamma`, `standard_normal`, `standard_t`, `triangular`, `uniform`, `vonmises`, `wald`, `weibull`, `zipf` + +### File I/O (4) +`fromfile`, `load`, `save`, `tofile` + +### Type Info (13) +`can_cast`, `common_type`, `common_type_code`, `dtype`, `finfo`, `find_common_type`, `iinfo`, `maximum_sctype`, `min_scalar_type`, `mintypecode`, `promote_types`, `result_type`, `sctype2char` + +--- + +## NDArray Instance Methods + +These methods are available on NDArray objects (equivalent to `ndarray.method()` in NumPy): + +| Method | Description | +|--------|-------------| +| `amax()` / `max()` | Maximum value | +| `amin()` / `min()` | Minimum value | +| `argmax(axis)` | Indices of maximum | +| `argmin(axis)` | Indices of minimum | +| `argsort(axis)` | Indices that would sort | +| `astype(dtype)` | Cast to specified type | +| `Clone()` | Deep copy | +| `convolve(v)` | 1D convolution | +| `copy()` | Return a copy | +| `cumsum(axis)` | Cumulative sum | +| `delete(indices)` | Delete elements | +| `dot(b)` | Dot product | +| `flatten(order)` | Return flattened copy | +| `inv()` | Matrix inverse | +| `item(*args)` | Copy element to Python scalar | +| `itemset(*args)` | Set a single item | +| `lstqr(b)` | Least-squares solution | +| `matrix_power(n)` | Raise matrix to power n | +| `mean(axis)` | Mean value | +| `multi_dot(*arrays)` | Chained dot products | +| `negative()` / `negate()` | Numerical negative | +| `positive()` | Numerical positive | +| `prod(axis)` | Product of elements | +| `ravel()` | Return flattened view | +| `reshape(shape)` | Return reshaped array | +| `roll(shift)` | Roll elements | +| `std(axis)` | Standard deviation | +| `sum(axis)` | Sum of elements | +| `swapaxes(a1, a2)` | Swap two axes | +| `tofile(path)` | Write to file | +| `tolist()` | Return as nested Python list | +| `transpose()` | Transpose | +| `unique()` | Unique elements | +| `var(axis)` | Variance | +| `view(dtype)` | New view with different dtype | + +### NDArray Properties + +| Property | Description | +|----------|-------------| +| `T` | Transpose | +| `base` | Base object if view | +| `dtype` | Data type | +| `dtypesize` | Size of dtype in bytes | +| `flat` | 1D iterator | +| `ndim` | Number of dimensions | +| `shape` | Tuple of dimensions | +| `size` | Number of elements | +| `strides` | Strides of data | +| `typecode` | NPTypeCode of dtype | + +--- + +## Missing Functions (239 total) + +### Complete Alphabetical List + +``` +acos acosh angle append +apply_along_axis apply_over_axes arccosh arcsinh +arctanh argpartition argwhere array2string +array_equiv array_repr array_str asarray_chkfinite +ascontiguousarray asfortranarray asin asinh +asmatrix astype atan atan2 +atanh average bartlett base_repr +binary_repr bincount bitwise_and bitwise_count +bitwise_invert bitwise_left_shift bitwise_or bitwise_right_shift +bitwise_xor blackman block bmat +broadcast_shapes busday_count busday_offset c_ +choose column_stack compress concat +conj conjugate copysign corrcoef +correlate cov cross cumulative_prod +cumulative_sum datetime_as_string datetime_data delete +diag diag_indices diag_indices_from diagflat +diagonal diff digitize divmod +ediff1d einsum einsum_path emath +errstate extract fabs fill_diagonal +fix flatnonzero flip fliplr +flipud float_power fmod format_float_positional +format_float_scientific frexp from_dlpack fromfunction +fromiter frompyfunc fromregex fromstring +gcd genfromtxt geomspace get_include +get_printoptions getbufsize geterr geterrcall +gradient hamming hanning heaviside +histogram histogram2d histogram_bin_edges histogramdd +hypot i0 imag index_exp +indices info inner insert +interp intersect1d is_busday isfortran +isin isnat isneginf isposinf +iterable ix_ kaiser kron +lcm ldexp lexsort loadtxt +logaddexp logaddexp2 logspace mask_indices +matrix matrix_transpose matvec may_share_memory +median nan_to_num nanargmax nanargmin +nancumprod nancumsum nanmedian nanpercentile +nanquantile ndenumerate ndim ndindex +nextafter ogrid packbits pad +partition percentile permute_dims piecewise +place poly poly1d polyadd +polyder polydiv polyfit polyint +polymul polysub polyval pow +printoptions ptp put put_along_axis +putmask quantile r_ ravel_multi_index +real real_if_close remainder require +resize rint roots rot90 +row_stack s_ savetxt savez +savez_compressed select set_printoptions setbufsize +setdiff1d seterr seterrcall setxor1d +shape shares_memory show_config show_runtime +signbit sinc sort sort_complex +spacing take take_along_axis tensordot +tile trace trapezoid tri +tril tril_indices tril_indices_from trim_zeros +triu triu_indices triu_indices_from typename +union1d unique_all unique_counts unique_inverse +unique_values unpackbits unravel_index unstack +unwrap vander vdot vecdot +vecmat vectorize where +``` + +--- + +## Missing Functions by Priority + +### Tier 1: Critical (Most Popular) - 25 functions + +| # | Function | Category | Why Popular | +|---|----------|----------|-------------| +| 1 | `where` | Selection | Conditional element selection - used constantly | +| 2 | `sort` | Sorting | In-place/out-of-place sorting | +| 3 | `flip` | Manipulation | Reverse arrays along axis | +| 4 | `diag` | Linear Algebra | Extract/create diagonals | +| 5 | `diagonal` | Linear Algebra | Return specified diagonals | +| 6 | `trace` | Linear Algebra | Sum of diagonal elements | +| 7 | `diff` | Math | Discrete difference (derivatives) | +| 8 | `histogram` | Statistics | Compute histogram | +| 9 | `percentile` | Statistics | Percentile computation | +| 10 | `median` | Statistics | Median value | +| 11 | `pad` | Manipulation | Array padding (CNNs, signal processing) | +| 12 | `tile` | Manipulation | Repeat array (data augmentation) | +| 13 | `bitwise_and` | Bitwise | Bitwise AND | +| 14 | `bitwise_or` | Bitwise | Bitwise OR | +| 15 | `bitwise_xor` | Bitwise | Bitwise XOR | +| 16 | `argwhere` | Indexing | Find indices where True | +| 17 | `flatnonzero` | Indexing | Flat indices of non-zero | +| 18 | `nan_to_num` | NaN handling | Replace NaN/inf with numbers | +| 19 | `rot90` | Manipulation | Rotate 90 degrees | +| 20 | `average` | Statistics | Weighted average | +| 21 | `take` | Indexing | Take elements along axis | +| 22 | `put` | Indexing | Put values at indices | +| 23 | `insert` | Manipulation | Insert elements | +| 24 | `append` | Manipulation | Append to array | +| 25 | `delete` | Manipulation | Delete elements (static version) | + +### Tier 2: High Priority - 30 functions + +| # | Function | Category | Description | +|---|----------|----------|-------------| +| 26 | `quantile` | Statistics | Quantile values | +| 27 | `cov` | Statistics | Covariance matrix | +| 28 | `corrcoef` | Statistics | Correlation coefficients | +| 29 | `inner` | Linear Algebra | Inner product | +| 30 | `vdot` | Linear Algebra | Vector dot product | +| 31 | `cross` | Linear Algebra | Cross product | +| 32 | `tensordot` | Linear Algebra | Tensor contraction | +| 33 | `kron` | Linear Algebra | Kronecker product | +| 34 | `nanargmax` | NaN-aware | Argmax ignoring NaN | +| 35 | `nanargmin` | NaN-aware | Argmin ignoring NaN | +| 36 | `nanmedian` | NaN-aware | Median ignoring NaN | +| 37 | `nancumsum` | NaN-aware | Cumsum ignoring NaN | +| 38 | `nancumprod` | NaN-aware | Cumprod ignoring NaN | +| 39 | `nanpercentile` | NaN-aware | Percentile ignoring NaN | +| 40 | `nanquantile` | NaN-aware | Quantile ignoring NaN | +| 41 | `fliplr` | Manipulation | Flip left-right | +| 42 | `flipud` | Manipulation | Flip up-down | +| 43 | `histogram2d` | Statistics | 2D histogram | +| 44 | `histogramdd` | Statistics | N-D histogram | +| 45 | `gradient` | Math | Numerical gradient | +| 46 | `arccosh` | Trig | Inverse hyperbolic cosine | +| 47 | `arcsinh` | Trig | Inverse hyperbolic sine | +| 48 | `arctanh` | Trig | Inverse hyperbolic tangent | +| 49 | `correlate` | Signal | Cross-correlation | +| 50 | `lexsort` | Sorting | Indirect lexicographic sort | +| 51 | `partition` | Sorting | Partial sort | +| 52 | `argpartition` | Sorting | Indices for partial sort | +| 53 | `logspace` | Creation | Log-spaced array | +| 54 | `geomspace` | Creation | Geometrically spaced | +| 55 | `resize` | Manipulation | Resize array | + +### Tier 3: Medium Priority - 40 functions + +| Function | Category | +|----------|----------| +| `take_along_axis` | Indexing | +| `put_along_axis` | Indexing | +| `putmask` | Indexing | +| `compress` | Indexing | +| `choose` | Indexing | +| `select` | Indexing | +| `extract` | Indexing | +| `place` | Indexing | +| `ptp` | Statistics | +| `hypot` | Math | +| `sinc` | Math | +| `rint` | Math | +| `fix` | Math | +| `real` | Complex | +| `imag` | Complex | +| `conj` / `conjugate` | Complex | +| `angle` | Complex | +| `triu` | Matrix | +| `tril` | Matrix | +| `tri` | Matrix | +| `diagflat` | Matrix | +| `vander` | Matrix | +| `piecewise` | Math | +| `ediff1d` | Math | +| `heaviside` | Math | +| `unwrap` | Signal | +| `indices` | Creation | +| `ogrid` | Creation | +| `fromfunction` | Creation | +| `fromiter` | Creation | +| `fromstring` | Creation | +| `block` | Creation | +| `column_stack` | Manipulation | +| `row_stack` | Manipulation | +| `unstack` | Manipulation | +| `mask_indices` | Indexing | +| `fill_diagonal` | Indexing | +| `ravel_multi_index` | Indexing | +| `unravel_index` | Indexing | +| `ix_` | Indexing | + +### Tier 4: Lower Priority - 50 functions + +| Category | Functions | +|----------|-----------| +| Triangle indices | `triu_indices`, `triu_indices_from`, `tril_indices`, `tril_indices_from`, `diag_indices`, `diag_indices_from` | +| Iteration | `ndenumerate`, `ndindex` | +| Functional | `apply_along_axis`, `apply_over_axes`, `vectorize`, `frompyfunc` | +| Interpolation | `interp` | +| Discretization | `digitize`, `bincount` | +| Set operations | `intersect1d`, `union1d`, `setdiff1d`, `setxor1d`, `isin`, `unique_all`, `unique_counts`, `unique_inverse`, `unique_values` | +| Bit manipulation | `packbits`, `unpackbits`, `bitwise_count` | +| Memory | `shares_memory`, `may_share_memory`, `ascontiguousarray`, `asfortranarray`, `require` | +| Special functions | `i0`, `frexp`, `ldexp`, `fmod`, `copysign`, `signbit`, `nextafter`, `spacing`, `logaddexp`, `logaddexp2`, `gcd`, `lcm`, `fabs`, `float_power`, `divmod`, `remainder` | +| Window functions | `hamming`, `hanning`, `bartlett`, `blackman`, `kaiser` | +| Integration | `trapezoid` | + +### Tier 5: Specialized/Rarely Used - 94 functions + +| Category | Functions | +|----------|-----------| +| Polynomial | `poly`, `roots`, `polyfit`, `polyval`, `polyadd`, `polysub`, `polymul`, `polydiv`, `polyint`, `polyder`, `poly1d` | +| I/O | `loadtxt`, `savetxt`, `genfromtxt`, `fromregex`, `savez`, `savez_compressed` | +| Error handling | `seterr`, `geterr`, `errstate`, `seterrcall`, `geterrcall` | +| Print options | `set_printoptions`, `get_printoptions`, `printoptions`, `array2string`, `format_float_scientific`, `format_float_positional`, `array_repr`, `array_str` | +| NumPy 2.x additions | `cumulative_sum`, `cumulative_prod`, `matrix_transpose`, `vecdot`, `vecmat`, `matvec`, `permute_dims`, `concat` | +| Date/time | `busday_count`, `busday_offset`, `is_busday`, `datetime_as_string`, `datetime_data`, `isnat` | +| Index expressions | `r_`, `c_`, `s_`, `index_exp` | +| Matrix class (legacy) | `matrix`, `asmatrix`, `bmat` | +| Misc | `typename`, `iterable`, `info`, `get_include`, `show_config`, `show_runtime`, `from_dlpack`, `broadcast_shapes`, `setbufsize`, `getbufsize`, `array_equiv`, `asarray_chkfinite`, `isfortran`, `isneginf`, `isposinf`, `acos`, `acosh`, `asin`, `asinh`, `atan`, `atan2`, `atanh`, `astype`, `base_repr`, `binary_repr`, `emath`, `ndim`, `shape`, `sort_complex`, `trim_zeros`, `real_if_close`, `pow` | + +--- + +## Implementation Recommendations + +### Quick Wins (Low effort, high impact) + +| Function | Implementation Approach | +|----------|------------------------| +| `flip` | Index manipulation with `[::-1]` slicing | +| `fliplr` | `flip(a, axis=1)` | +| `flipud` | `flip(a, axis=0)` | +| `rot90` | Transpose + flip combination | +| `diag` | Index extraction/creation | +| `diagonal` | Stride-based view | +| `trace` | `sum(diagonal(a))` | +| `bitwise_and/or/xor` | ILKernel already has infrastructure | +| `arccosh/arcsinh/arctanh` | Follow existing trig pattern | +| `nan_to_num` | Simple masking operation | +| `ptp` | `max(a) - min(a)` | +| `flatnonzero` | `nonzero(ravel(a))[0]` | +| `triu/tril` | Index masking | +| `correlate` | `convolve(a, v[::-1])` | +| `logspace` | `power(base, linspace(...))` | +| `geomspace` | `exp(linspace(log(start), log(stop)))` | + +### Medium Effort + +| Function | Implementation Approach | +|----------|------------------------| +| `where` | Conditional indexing with broadcasting | +| `sort` | Sorting algorithm with dtype support | +| `histogram` | Bin counting with edge handling | +| `median` | Sort + middle element(s) | +| `percentile/quantile` | Sort + interpolation | +| `pad` | Memory allocation + copy patterns | +| `tile` | Repeat + reshape | +| `diff` | Subtraction with slicing | +| `average` | Weighted sum / weight sum | +| `argwhere` | Coordinate extraction from mask | +| `take/put` | Fancy indexing generalization | + +### Higher Effort + +| Function | Implementation Approach | +|----------|------------------------| +| `einsum` | Einstein summation parser + optimizer | +| `tensordot` | Generalized tensor contraction | +| `kron` | Kronecker product expansion | +| `cov/corrcoef` | Covariance calculation | +| `gradient` | Finite difference schemes | +| `histogram2d/histogramdd` | N-D binning | + +--- + +## Reference + +- NumPy 2.4.2 source: `src/numpy/` +- NumPy API reference: https://numpy.org/doc/stable/reference/ +- NumSharp source: `src/NumSharp.Core/` + +Last updated: 2026-04-12 diff --git a/docs/numpy/NUMPY_NPZ_SAVE_LOAD.md b/docs/numpy/NUMPY_NPZ_SAVE_LOAD.md new file mode 100644 index 000000000..352c9dd2c --- /dev/null +++ b/docs/numpy/NUMPY_NPZ_SAVE_LOAD.md @@ -0,0 +1,1615 @@ +# NumPy .npy/.npz Format Implementation + +This document describes how NumPy implements `np.save`, `np.load`, and the underlying `.npy`/`.npz` binary formats. Based on analysis of `numpy/lib/_format_impl.py` (NumPy 2.x). + +## Table of Contents + +1. [Binary File Structure](#binary-file-structure) +2. [Format Versions](#format-versions) +3. [Header Format](#header-format) +4. [Data Layout](#data-layout) +5. [Write Implementation](#write-implementation) +6. [Read Implementation](#read-implementation) +7. [NPZ Archive Format](#npz-archive-format) +8. [Memory Mapping](#memory-mapping) +9. [Edge Cases](#edge-cases) +10. [Security Considerations](#security-considerations) +11. [Constants Reference](#constants-reference) +12. [Implicit Behaviors and Gotchas](#implicit-behaviors-and-gotchas) +13. [Limitations and Warnings](#limitations-and-warnings) +14. [Error Messages](#error-messages) +15. [Public API Reference](#public-api-reference) + +--- + +## Binary File Structure + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ MAGIC STRING (6 bytes) │ +│ Fixed value: \x93NUMPY │ +├─────────────────────────────────────────────────────────────────┤ +│ VERSION (2 bytes) │ +│ major (1 byte), minor (1 byte) │ +├─────────────────────────────────────────────────────────────────┤ +│ HEADER LENGTH (2 or 4 bytes, little-endian) │ +│ v1.0: uint16 ( 65,535 bytes | +| (3, 0) | 4 bytes (`` + +| Endian | Meaning | +|--------|---------| +| `<` | Little-endian | +| `>` | Big-endian | +| `\|` | Not applicable (single-byte or opaque) | +| `=` | Native byte order | + +| Type Code | C Type | Examples | +|-----------|--------|----------| +| `b` | bool | `\|b1` | +| `i` | signed int | `\|i1`, ` 2x3 array of float64 + dt = descr_to_dtype(descr[0]) + return numpy.dtype((dt, descr[1])) + + else: + # Record array: list of field tuples + # Each field: (name, descr) or (name, descr, shape) + # Name can be string or (title, name) tuple + names, formats, titles, offsets = [], [], [], [] + offset = 0 + + for field in descr: + if len(field) == 2: + name, descr_str = field + dt = descr_to_dtype(descr_str) + else: + name, descr_str, shape = field + dt = numpy.dtype((descr_to_dtype(descr_str), shape)) + + # Skip padding bytes (aligned dtypes insert void padding) + # Condition: empty name AND void type AND no subfields + is_pad = (name == '' and dt.type is numpy.void and dt.names is None) + + if not is_pad: + # Handle titled fields: name can be (title, actual_name) + title, name = name if isinstance(name, tuple) else (None, name) + titles.append(title) + names.append(name) + formats.append(dt) + offsets.append(offset) + + # Always advance offset (padding consumes space) + offset += dt.itemsize + + return numpy.dtype({ + 'names': names, + 'formats': formats, + 'titles': titles, + 'offsets': offsets, + 'itemsize': offset # Total size including padding + }) +``` + +**Field tuple formats:** +- `(name, dtype_str)` - Simple field +- `(name, dtype_str, shape)` - Subarray field +- `((title, name), dtype_str)` - Titled field +- `('', 'V8')` - Padding (8 bytes of void, skipped) + +### Header Alignment + +The total header (magic + version + length field + header string) is padded to a multiple of `ARRAY_ALIGN` (64 bytes) for memory-mapping compatibility. + +```python +ARRAY_ALIGN = 64 + +def _wrap_header(header, version): + header_bytes = header.encode(encoding) # latin1 or utf8 + hlen = len(header_bytes) + 1 # +1 for trailing newline + + # Calculate padding needed + padlen = ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize(fmt) + hlen) % ARRAY_ALIGN) + + # Build: magic + length + header + padding + newline + return magic(*version) + struct.pack(fmt, hlen + padlen) + header_bytes + b' ' * padlen + b'\n' +``` + +### Growth Axis Padding + +Extra spaces are added after the dictionary to allow in-place header modification when appending data: + +```python +GROWTH_AXIS_MAX_DIGITS = 21 # len(str(8 * 2**64 - 1)) + +# Add padding for the axis that can grow +# C-order: first axis; F-order: last axis +growth_axis = -1 if fortran_order else 0 +current_digits = len(repr(shape[growth_axis])) if shape else 0 +padding = GROWTH_AXIS_MAX_DIGITS - current_digits +header += " " * padding +``` + +--- + +## Data Layout + +### C-Order (Row-Major) + +Default layout. Elements are contiguous along the last axis. + +``` +Array: [[1, 2, 3], + [4, 5, 6]] + +Memory: [1, 2, 3, 4, 5, 6] +``` + +### Fortran-Order (Column-Major) + +Elements are contiguous along the first axis. + +``` +Array: [[1, 2, 3], + [4, 5, 6]] + +Memory: [1, 4, 2, 5, 3, 6] +``` + +### Contiguity Detection + +```python +def header_data_from_array_1_0(array): + d = {'shape': array.shape} + + if array.flags.c_contiguous: + d['fortran_order'] = False + elif array.flags.f_contiguous: + d['fortran_order'] = True + else: + # Non-contiguous: will be copied as C-order + d['fortran_order'] = False + + d['descr'] = dtype_to_descr(array.dtype) + return d +``` + +**Important**: 1-D arrays are both C-contiguous and F-contiguous. The check order (C first) ensures 1-D arrays use C-order. + +### Contiguity Decision Table + +| Array Type | C-contiguous | F-contiguous | fortran_order | +|------------|--------------|--------------|---------------| +| 1D array | True | True | False | +| 2D C-order | True | False | False | +| 2D transposed | False | True | True | +| 2D F-order | False | True | True | +| 1D strided | False | False | False | +| 2D strided | False | False | False | +| Scalar | True | True | False | +| Empty | True | True | False | + +**Key insight**: Both C and F are true for 1D/scalar/empty arrays. The check order matters! + +**Contiguity edge cases:** +| Array Type | C_CONTIGUOUS | F_CONTIGUOUS | fortran_order | +|------------|--------------|--------------|---------------| +| 1D array | True | True | False | +| Scalar | True | True | False | +| Empty (0,) | True | True | False | +| Empty (0,0,0) | True | True | False | +| 2D C-order | True | False | False | +| 2D F-order | False | True | True | +| Transposed | False | True | True | +| Strided slice | False | False | False | + +--- + +## Write Implementation + +### write_array Function + +```python +def write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None): + _check_version(version) + _write_array_header(fp, header_data_from_array_1_0(array), version) + + # Calculate buffer size (16 MiB worth of elements) + if array.itemsize == 0: + buffersize = 0 + else: + buffersize = max(16 * 1024**2 // array.itemsize, 1) + + # Write data based on dtype and contiguity + if array.dtype.hasobject or not type(array.dtype)._legacy: + # Object arrays or custom dtypes: use pickle + if not allow_pickle: + raise ValueError("Object arrays cannot be saved when allow_pickle=False") + pickle.dump(array, fp, protocol=4, **pickle_kwargs or {}) + + elif array.flags.f_contiguous and not array.flags.c_contiguous: + # F-contiguous: write in Fortran order + if isfileobj(fp): + array.T.tofile(fp) + else: + for chunk in numpy.nditer(array, + flags=['external_loop', 'buffered', 'zerosize_ok'], + buffersize=buffersize, order='F'): + fp.write(chunk.tobytes('C')) + + elif isfileobj(fp): + # C-contiguous with real file: direct write + array.tofile(fp) + + else: + # C-contiguous with stream: chunked write + for chunk in numpy.nditer(array, + flags=['external_loop', 'buffered', 'zerosize_ok'], + buffersize=buffersize, order='C'): + fp.write(chunk.tobytes('C')) +``` + +### Write Buffer Size Calculation + +```python +if array.itemsize == 0: + buffersize = 0 +else: + # 16 MiB worth of elements, minimum 1 + buffersize = max(16 * 1024**2 // array.itemsize, 1) +``` + +**Buffer size examples:** +| dtype | itemsize | buffersize (elements) | +|-------|----------|----------------------| +| int8 | 1 | 16,777,216 | +| int32 | 4 | 4,194,304 | +| float64 | 8 | 2,097,152 | +| complex128 | 16 | 1,048,576 | + +### isfileobj Detection + +```python +def isfileobj(f): + if not isinstance(f, (io.FileIO, io.BufferedReader, io.BufferedWriter)): + return False + try: + f.fileno() # May raise for wrapped BytesIO + return True + except OSError: + return False +``` + +**Why it matters**: +- `True`: Use fast `tofile()`/`fromfile()` methods (kernel-level I/O) +- `False`: Use chunked `tobytes()`/`frombuffer()` for streams (Python-level) + +**Accepted types:** +- `io.FileIO` - raw file I/O +- `io.BufferedReader` - buffered read (from `open(file, 'rb')`) +- `io.BufferedWriter` - buffered write (from `open(file, 'wb')`) + +**Rejected types:** +- `io.BytesIO` - in-memory stream +- `gzip.GzipFile` - compressed stream +- `zipfile.ZipExtFile` - file within ZIP + +--- + +## Read Implementation + +### read_array Function + +```python +def read_array(fp, allow_pickle=False, pickle_kwargs=None, *, max_header_size=10000): + if allow_pickle: + max_header_size = 2**64 # Trusted file, no limit + + # 1. Read and validate magic/version + version = read_magic(fp) + _check_version(version) + + # 2. Parse header + shape, fortran_order, dtype = _read_array_header(fp, version, max_header_size) + + # 3. Calculate element count + if len(shape) == 0: + count = 1 # Scalar + else: + count = numpy.multiply.reduce(shape, dtype=numpy.int64) + + # 4. Read data + if dtype.hasobject: + if not allow_pickle: + raise ValueError("Object arrays cannot be loaded when allow_pickle=False") + array = pickle.load(fp, **pickle_kwargs or {}) + + elif isfileobj(fp): + # Real file: fast path + array = numpy.fromfile(fp, dtype=dtype, count=count) + + else: + # Stream: chunked read + array = numpy.ndarray(count, dtype=dtype) + if dtype.itemsize > 0: + max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize) + for i in range(0, count, max_read_count): + read_count = min(max_read_count, count - i) + read_size = int(read_count * dtype.itemsize) + data = _read_bytes(fp, read_size, "array data") + array[i:i+read_count] = numpy.frombuffer(data, dtype=dtype, count=read_count) + + # 5. Validate and reshape + if array.size != count: + raise ValueError(f"Failed to read all data. Expected {count}, got {array.size}") + + if fortran_order: + array = array.reshape(shape[::-1]).transpose() + else: + array = array.reshape(shape) + + return array +``` + +### Read Buffer Size (BUFFER_SIZE) + +```python +BUFFER_SIZE = 2**18 # 262,144 bytes (256 KB) + +# Max elements per chunk +max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize) +``` + +**Read chunk examples:** +| dtype | itemsize | max_read_count | +|-------|----------|----------------| +| int8 | 1 | 262,144 | +| int32 | 4 | 65,536 | +| float64 | 8 | 32,768 | +| S1000 | 1000 | 262 | + +The `min(BUFFER_SIZE, dtype.itemsize)` prevents division by zero when itemsize > BUFFER_SIZE. + +### _read_bytes - Robust Stream Reading + +```python +def _read_bytes(fp, size, error_template="ran out of data"): + """Read exactly `size` bytes, handling partial reads.""" + data = b"" + while True: + try: + r = fp.read(size - len(data)) + data += r + if len(r) == 0 or len(data) == size: + break + except BlockingIOError: + pass + + if len(data) != size: + raise ValueError(f"EOF: reading {error_template}, expected {size} bytes got {len(data)}") + return data +``` + +**Why needed**: +- ZipExtFile may return fewer bytes than requested +- Network streams may have partial reads +- Non-blocking I/O may return early +- gzip streams have crc32 limitations at 2**32 bytes + +### _read_array_header + +```python +def _read_array_header(fp, version, max_header_size=10000): + # Get format info for version + hlength_type, encoding = { + (1, 0): (' max_header_size: + raise ValueError(f"Header info length ({len(header)}) is large and may not be safe") + + # Parse Python literal + try: + d = ast.literal_eval(header) + except SyntaxError: + if version <= (2, 0): + # Try filtering Python 2 'L' suffixes + header = _filter_header(header) + d = ast.literal_eval(header) + else: + raise + + # Validate structure + if not isinstance(d, dict): + raise ValueError("Header is not a dictionary") + if {'descr', 'fortran_order', 'shape'} != d.keys(): + raise ValueError("Header does not contain correct keys") + + # Validate values + if not isinstance(d['shape'], tuple) or not all(isinstance(x, int) for x in d['shape']): + raise ValueError(f"shape is not valid: {d['shape']}") + if not isinstance(d['fortran_order'], bool): + raise ValueError(f"fortran_order is not valid: {d['fortran_order']}") + + dtype = descr_to_dtype(d['descr']) + return d['shape'], d['fortran_order'], dtype +``` + +### Python 2 Compatibility Filter + +```python +def _filter_header(s): + """Remove 'L' suffix from integers (Python 2 legacy).""" + import tokenize + from io import StringIO + + tokens = [] + last_token_was_number = False + for token in tokenize.generate_tokens(StringIO(s).readline): + token_type, token_string = token[0], token[1] + if last_token_was_number and token_type == tokenize.NAME and token_string == "L": + continue # Skip the 'L' + tokens.append(token) + last_token_was_number = (token_type == tokenize.NUMBER) + + return tokenize.untokenize(tokens) +``` + +--- + +## NPZ Archive Format + +NPZ is a ZIP archive containing multiple `.npy` files. + +### Structure + +``` +archive.npz (ZIP file) +├── arr_0.npy # Positional array 0 +├── arr_1.npy # Positional array 1 +├── weights.npy # Named array "weights" +└── biases.npy # Named array "biases" +``` + +### _savez Implementation (Internal) + +```python +def _savez(file, args, kwds, compress, allow_pickle=True, pickle_kwargs=None): + import zipfile + + if not hasattr(file, 'write'): + file = os.fspath(file) + if not file.endswith('.npz'): + file = file + '.npz' + + # Merge positional args as arr_0, arr_1, ... + namedict = kwds + for i, val in enumerate(args): + key = 'arr_%d' % i + if key in namedict.keys(): + raise ValueError(f"Cannot use un-named variables and keyword {key}") + namedict[key] = val + + compression = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED + + # Always enable Zip64 for large files (gh-10776) + zipf = zipfile_factory(file, mode="w", compression=compression) + try: + for key, val in namedict.items(): + fname = key + '.npy' + val = np.asanyarray(val) + # force_zip64=True always, even for small files + with zipf.open(fname, 'w', force_zip64=True) as fid: + format.write_array(fid, val, allow_pickle=allow_pickle, + pickle_kwargs=pickle_kwargs) + finally: + zipf.close() +``` + +### zipfile_factory + +```python +def zipfile_factory(file, *args, **kwargs): + """Create ZipFile with Zip64 support and path-like handling.""" + if not hasattr(file, 'read'): + file = os.fspath(file) # Handle pathlib.Path + kwargs['allowZip64'] = True # Always enable Zip64 + return zipfile.ZipFile(file, *args, **kwargs) +``` + +### savez_compressed + +Same as `savez` but uses `compression=zipfile.ZIP_DEFLATED`. + +### NpzFile Class (Lazy Loading) + +```python +class NpzFile(Mapping): + """Lazy-loading NPZ archive with dict-like interface.""" + + zip = None + fid = None + _MAX_REPR_ARRAY_COUNT = 5 + + def __init__(self, fid, own_fid=False, allow_pickle=False, + pickle_kwargs=None, *, max_header_size=10000): + _zip = zipfile_factory(fid) + _files = _zip.namelist() + + # Strip .npy extension for user-facing keys + self.files = [name.removesuffix(".npy") for name in _files] + + # Map both stripped and unstripped names + self._files = dict(zip(self.files, _files)) + self._files.update(zip(_files, _files)) + + self.allow_pickle = allow_pickle + self.max_header_size = max_header_size + self.pickle_kwargs = pickle_kwargs + self.zip = _zip + self.f = BagObj(self) # Attribute access: npz.f.array_name + + if own_fid: + self.fid = fid + + def __getitem__(self, key): + try: + key = self._files[key] + except KeyError: + raise KeyError(f"{key} is not a file in the archive") from None + + with self.zip.open(key) as bytes: + # Check magic to distinguish .npy from other files + magic = bytes.read(len(format.MAGIC_PREFIX)) + bytes.seek(0) + if magic == format.MAGIC_PREFIX: + return format.read_array(bytes, + allow_pickle=self.allow_pickle, + pickle_kwargs=self.pickle_kwargs, + max_header_size=self.max_header_size) + else: + # Non-.npy files returned as raw bytes + return bytes.read() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + def __del__(self): + self.close() + + def close(self): + if self.zip is not None: + self.zip.close() + self.zip = None + if self.fid is not None: + self.fid.close() + self.fid = None + self.f = None # Break reference cycle +``` + +### BagObj - Attribute Access Helper + +```python +class BagObj: + """Convert attribute lookups to getitem on wrapped object.""" + + def __init__(self, obj): + # Use weakref to make NpzFile collectable by refcount + self._obj = weakref.proxy(obj) + + def __getattribute__(self, key): + try: + return object.__getattribute__(self, '_obj')[key] + except KeyError: + raise AttributeError(key) from None + + def __dir__(self): + # Enable tab-completion in IPython + return list(object.__getattribute__(self, '_obj').keys()) +``` + +### NPZ Key Naming Rules + +- Positional arrays: `arr_0`, `arr_1`, `arr_2`, ... +- Keyword arrays: use the keyword name directly +- Collision check: cannot use both positional and keyword with same name +- Keys should be valid filenames: avoid `/` or `.` characters +- Cannot use `file` as keyword (conflicts with function parameter) + +### NPZ Key Access + +Both stripped and unstripped names work: + +```python +with np.load('data.npz') as npz: + npz['arr_0'] # Works + npz['arr_0.npy'] # Also works (maps to same file) + npz.files # Returns ['arr_0'] (stripped) +``` + +### Non-.npy Files in NPZ + +NpzFile can contain non-numpy files. They're returned as raw bytes: + +```python +with np.load('mixed.npz') as npz: + arr = npz['data'] # Returns ndarray (was data.npy) + txt = npz['readme.txt'] # Returns bytes + raw = npz['config.bin'] # Returns bytes +``` + +Magic check in `__getitem__`: +```python +magic = bytes.read(len(format.MAGIC_PREFIX)) +bytes.seek(0) +if magic == format.MAGIC_PREFIX: + return format.read_array(bytes, ...) +else: + return bytes.read() # Raw bytes for non-.npy +``` + +--- + +## Memory Mapping + +### open_memmap Function + +```python +def open_memmap(filename, mode='r+', dtype=None, shape=None, + fortran_order=False, version=None, *, max_header_size=10000): + + if isfileobj(filename): + raise ValueError("Memmap requires file path, not file object") + + if 'w' in mode: + # Create new file + dtype = numpy.dtype(dtype) + if dtype.hasobject: + raise ValueError("Cannot memmap object arrays") + + d = {'descr': dtype_to_descr(dtype), 'fortran_order': fortran_order, 'shape': shape} + + with open(filename, mode + 'b') as fp: + _write_array_header(fp, d, version) + offset = fp.tell() + else: + # Read existing file + with open(filename, 'rb') as fp: + version = read_magic(fp) + shape, fortran_order, dtype = _read_array_header(fp, version, max_header_size) + if dtype.hasobject: + raise ValueError("Cannot memmap object arrays") + offset = fp.tell() + + order = 'F' if fortran_order else 'C' + if mode == 'w+': + mode = 'r+' # Already wrote header + + return numpy.memmap(filename, dtype=dtype, shape=shape, order=order, mode=mode, offset=offset) +``` + +--- + +## Edge Cases + +### Scalar Arrays (0-dimensional) + +```python +arr = np.array(42) +# shape: () +# count: 1 (special case) +# Data: single element +``` + +### Empty Arrays + +```python +arr = np.array([], dtype=' 0 but no actual data +# buffersize = 0 for writes +# Skip data read loop +``` + +### Truncated Files + +```python +# If file ends before expected data: +raise ValueError( + f"Failed to read all data for array. " + f"Expected {shape} = {count} elements, " + f"could only read {array.size} elements. " + f"(file seems not fully written?)" +) +``` + +--- + +## Security Considerations + +### max_header_size + +Default: 10,000 bytes + +`ast.literal_eval()` can be slow or crash on very large inputs. This limit prevents DoS attacks with malicious headers. + +```python +# Bypass for trusted files +np.load(file, allow_pickle=True) # Sets max_header_size = 2**64 +np.load(file, max_header_size=200000) # Explicit override +``` + +### allow_pickle + +Default: `False` (since NumPy 1.16.3) + +Object arrays use Python pickle, which can execute arbitrary code. Never load untrusted `.npy` files with `allow_pickle=True`. + +```python +# This is DANGEROUS with untrusted files: +np.load(untrusted_file, allow_pickle=True) +``` + +### Validation + +Headers are strictly validated: +- Exactly 3 keys required +- `shape` must be tuple of ints +- `fortran_order` must be bool +- `descr` must produce valid dtype + +### Error Messages + +| Error | Message | +|-------|---------| +| Invalid version | `we only support format version (1,0), (2,0), and (3,0), not {version}` | +| Bad magic | `the magic string is not correct; expected b'\x93NUMPY', got {actual}` | +| Object w/o pickle (write) | `Object arrays cannot be saved when allow_pickle=False` | +| Object w/o pickle (read) | `Object arrays cannot be loaded when allow_pickle=False` | +| Header too large | `Header info length ({len}) is large and may not be safe to load securely` | +| Truncated header | `EOF: reading array header length, expected {n} bytes got {m}` | +| Non-dict header | `Header is not a dictionary: {value}` | +| Wrong keys | `Header does not contain the correct keys: {keys}` | +| Invalid shape | `shape is not valid: {value}` | +| Invalid fortran_order | `fortran_order is not a valid bool: {value}` | +| Invalid dtype | `descr is not a valid dtype descriptor: {value}` | +| Truncated data | `Failed to read all data for array. Expected {shape} = {count} elements, could only read {actual}` | +| No data (np.load) | `EOFError: No data left in file` | +| Pickle file w/o allow | `This file contains pickled data. Use allow_pickle=True if you trust the file.` | +| User dtype w/o pickle | `User-defined dtypes cannot be saved when allow_pickle=False` | +| Memmap w/ file obj | `Filename must be a string or a path-like object. Memmap cannot use existing file handles.` | +| Memmap w/ object dtype | `Array can't be memory-mapped: Python objects in dtype.` | + +--- + +## Constants Reference + +### File Type Detection (np.load) + +```python +_ZIP_PREFIX = b'PK\x03\x04' # Standard ZIP files +_ZIP_SUFFIX = b'PK\x05\x06' # Empty ZIP files + +# Detection order: +# 1. magic.startswith(_ZIP_PREFIX) or magic.startswith(_ZIP_SUFFIX) -> NPZ +# 2. magic == MAGIC_PREFIX -> NPY +# 3. Otherwise -> Pickle file +``` + +### Format Constants + +```python +# Magic string +MAGIC_PREFIX = b'\x93NUMPY' +MAGIC_LEN = 8 # len(MAGIC_PREFIX) + 2 version bytes + +# Alignment +ARRAY_ALIGN = 64 # Header aligned to this boundary (for mmap) + +# Buffer sizes +BUFFER_SIZE = 2**18 # 262,144 bytes (256 KB) for chunked I/O + +# Header growth +GROWTH_AXIS_MAX_DIGITS = 21 # len(str(8 * 2**64 - 1)) + +# Security +_MAX_HEADER_SIZE = 10000 # Default limit for ast.literal_eval + +# Version info +_header_size_info = { + (1, 0): (' BUFFER_SIZE: + +```python +max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize) +``` + +### crc32 Limitation + +Comment in source: "crc32 module fails on reads greater than 2**32 bytes, breaking large reads from gzip streams." + +This is why chunked reading is used even for non-file streams. + +### Python 2 Header Filtering + +Only applied for versions (1, 0) and (2, 0), not (3, 0): + +```python +if version <= (2, 0): + header = _filter_header(header) # Remove 'L' suffixes +``` + +### Header Key Sorting + +Keys are sorted alphabetically in output ("Writer SHOULD implement"), but readers "MUST NOT depend on this": + +```python +for key, value in sorted(d.items()): + header.append(f"'{key}': {repr(value)}, ") +``` + +### Path-like Object Handling + +`os.fspath()` used throughout for pathlib.Path support: + +```python +file = os.fspath(file) +``` + +### UnicodeError in Pickle Load + +Special handling with helpful message: + +```python +except UnicodeError as err: + raise UnicodeError("Unpickling a python object failed: %r\n" + "You may need to pass the encoding= option " + "to numpy.load" % (err,)) from err +``` + +### open_memmap Mode Conversion + +After writing header, `w+` mode becomes `r+`: + +```python +if mode == 'w+': + mode = 'r+' # Already wrote header +``` + +### Structured dtype Padding Detection + +Specific condition for identifying padding bytes: + +```python +is_pad = (name == '' and dt.type is numpy.void and dt.names is None) +``` + +### Titled Fields in Structured dtypes + +Field names can be tuples of `(title, name)`: + +```python +title, name = name if isinstance(name, tuple) else (None, name) +``` + +### Non-legacy dtype Check + +User-defined dtypes detected via internal `_legacy` attribute: + +```python +if not type(dtype)._legacy: + # Use pickle, emit warning + return "|O" +``` + +### drop_metadata Behavior + +```python +dt_meta = np.dtype('i4', metadata={'key': 'value'}) +dropped = format.drop_metadata(dt_meta) +# dropped is a NEW dtype without metadata +# Original dtype unchanged +# Returns same object if no metadata present +``` + +### File Position After Header Read + +After `read_array_header_*()`, file position is exactly at data start: + +```python +shape, fort, dt = format.read_array_header_1_0(fp) +data_offset = fp.tell() # This is the mmap offset! +# data_offset is always 64-byte aligned +``` + +### Header Dictionary repr() Usage + +All values use Python `repr()` for serialization: + +```python +header.append(f"'{key}': {repr(value)}, ") +``` + +This ensures: +- Tuples have trailing comma: `(3,)` not `(3)` +- Strings are properly quoted +- Numbers are exact + +### Trailing Comma in Header + +Header dict always has trailing comma before closing brace: + +```python +"{'descr': ' "a file with little-endian numbers will yield a little-endian array on any machine reading the file" + +### Object Array Memory Mapping + +Cannot memory-map object arrays: + +```python +if dtype.hasobject: + raise ValueError("Array can't be memory-mapped: Python objects in dtype.") +``` + +### Size Validation After Read + +The size check happens OUTSIDE the itemsize > 0 block, so it always validates: + +```python +# After chunked read loop +if array.size != count: + raise ValueError("Failed to read all data for array...") +``` + +### Warning Messages + +Version 2.0 warning has a typo in original source: "It can only beread" (missing space). + +--- + +## Public API Reference + +### numpy.lib.format Module + +| Function | Description | +|----------|-------------| +| `magic(major, minor)` | Create magic bytes for version | +| `read_magic(fp)` | Read version from file, returns (major, minor) | +| `write_array(fp, array, version, allow_pickle, pickle_kwargs)` | Write array to file | +| `read_array(fp, allow_pickle, pickle_kwargs, max_header_size)` | Read array from file | +| `write_array_header_1_0(fp, d)` | Write v1.0 header | +| `write_array_header_2_0(fp, d)` | Write v2.0 header | +| `read_array_header_1_0(fp, max_header_size)` | Read v1.0 header | +| `read_array_header_2_0(fp, max_header_size)` | Read v2.0 header | +| `header_data_from_array_1_0(array)` | Extract header dict from array | +| `dtype_to_descr(dtype)` | Convert dtype to serializable descr | +| `descr_to_dtype(descr)` | Convert descr back to dtype | +| `open_memmap(filename, mode, dtype, shape, fortran_order, version, max_header_size)` | Memory-map a .npy file | +| `isfileobj(f)` | Check if f is a real file object | +| `drop_metadata(dtype)` | Strip metadata from dtype | + +### numpy Module (High-Level) + +| Function | Description | +|----------|-------------| +| `np.save(file, arr, allow_pickle)` | Save single array | +| `np.load(file, mmap_mode, allow_pickle, fix_imports, encoding, max_header_size)` | Load .npy/.npz/pickle | +| `np.savez(file, *args, allow_pickle, **kwds)` | Save multiple arrays (uncompressed) | +| `np.savez_compressed(file, *args, allow_pickle, **kwds)` | Save multiple arrays (compressed) | + +--- + +--- + +## Error Messages + +### Format Errors + +| Error | Message Pattern | +|-------|-----------------| +| Bad magic | `the magic string is not correct; expected b'\x93NUMPY', got {got!r}` | +| Bad version | `we only support format version (1,0), (2,0), and (3,0), not {version}` | +| Invalid version | `Invalid version {version!r}` | +| Header too large | `Header length {hlen} too big for version={version}` | +| Header security | `Header info length ({len}) is large and may not be safe to load securely` | +| Truncated header | `EOF: reading array header, expected {size} bytes got {len}` | +| Truncated data | `EOF: reading array data, expected {size} bytes got {len}` | +| Invalid header | `Cannot parse header: {header!r}` | +| Not dict | `Header is not a dictionary: {d!r}` | +| Wrong keys | `Header does not contain the correct keys: {keys!r}` | +| Invalid shape | `shape is not valid: {shape!r}` | +| Invalid fortran | `fortran_order is not a valid bool: {value!r}` | +| Invalid descr | `descr is not a valid dtype descriptor: {descr!r}` | +| Data mismatch | `Failed to read all data for array. Expected {shape} = {count} elements, could only read {size} elements.` | +| Object no pickle | `Object arrays cannot be saved/loaded when allow_pickle=False` | +| Custom dtype | `User-defined dtypes cannot be saved when allow_pickle=False` | + +### np.load Errors + +| Error | Condition | +|-------|-----------| +| `EOFError("No data left in file")` | Empty file or past end | +| `ValueError("encoding must be 'ASCII', 'latin1', or 'bytes'")` | Bad encoding value | +| `pickle.UnpicklingError(f"Failed to interpret file {file!r}")` | Not npy/npz/pickle | +| `KeyError(f"{key} is not a file in the archive")` | NPZ key not found | + +### open_memmap Errors + +| Error | Condition | +|-------|-----------| +| `ValueError("Filename must be a string or path-like object...")` | File object passed | +| `ValueError("Array can't be memory-mapped: Python objects in dtype.")` | Object dtype | + +--- + +## Public API Reference + +### numpy.lib.format Functions + +| Function | Description | +|----------|-------------| +| `magic(major, minor)` | Create magic bytes for version | +| `read_magic(fp)` | Read magic, return (major, minor) | +| `dtype_to_descr(dtype)` | Convert dtype to serializable descriptor | +| `descr_to_dtype(descr)` | Convert descriptor back to dtype | +| `header_data_from_array_1_0(array)` | Get header dict from array | +| `write_array_header_1_0(fp, d)` | Write v1.0 header | +| `write_array_header_2_0(fp, d)` | Write v2.0 header | +| `read_array_header_1_0(fp, max_header_size)` | Read v1.0 header | +| `read_array_header_2_0(fp, max_header_size)` | Read v2.0 header | +| `write_array(fp, array, version, allow_pickle)` | Write array with header | +| `read_array(fp, allow_pickle, max_header_size)` | Read array from file | +| `open_memmap(filename, mode, dtype, shape, ...)` | Open as memory-mapped | +| `isfileobj(f)` | Check if real file (vs stream) | +| `drop_metadata(dtype)` | Remove metadata from dtype | + +### numpy.lib.format Constants + +| Constant | Value | Description | +|----------|-------|-------------| +| `MAGIC_PREFIX` | `b'\x93NUMPY'` | File magic (6 bytes) | +| `MAGIC_LEN` | `8` | Magic + version bytes | +| `ARRAY_ALIGN` | `64` | Header alignment | +| `BUFFER_SIZE` | `262144` | Chunk size (256KB) | +| `GROWTH_AXIS_MAX_DIGITS` | `21` | Space for axis growth | +| `EXPECTED_KEYS` | `{'descr', 'fortran_order', 'shape'}` | Required header keys | + +### numpy Functions + +| Function | Description | +|----------|-------------| +| `np.save(file, arr, allow_pickle=True)` | Save to .npy | +| `np.load(file, mmap_mode, allow_pickle, ...)` | Load .npy/.npz/pickle | +| `np.savez(file, *args, **kwds)` | Save to uncompressed .npz | +| `np.savez_compressed(file, *args, **kwds)` | Save to compressed .npz | + +### File Type Detection Order + +np.load detects file type by magic bytes: + +| Magic Bytes | File Type | Action | +|-------------|-----------|--------| +| `b'PK\x03\x04'` | ZIP (NPZ) | Return NpzFile | +| `b'PK\x05\x06'` | Empty ZIP | Return NpzFile | +| `b'\x93NUMPY'` | NPY | read_array or open_memmap | +| Other | Pickle | pickle.load | + +--- + +## References + +- Source: `numpy/lib/_format_impl.py` (NumPy 2.x) +- Source: `numpy/lib/_npyio_impl.py` (np.save/load wrappers) +- NEP 1: [A Simple File Format for NumPy Arrays](https://numpy.org/neps/nep-0001-npy-format.html) +- NumPy Documentation: [numpy.save](https://numpy.org/doc/stable/reference/generated/numpy.save.html) diff --git a/docs/numpy/NUMPY_RANDOM.md b/docs/numpy/NUMPY_RANDOM.md new file mode 100644 index 000000000..107ebfa8f --- /dev/null +++ b/docs/numpy/NUMPY_RANDOM.md @@ -0,0 +1,1938 @@ +# NumPy Random Module - Complete Reference + +> **NumPy Version:** 2.4.2 +> **Purpose:** Authoritative reference for implementing NumSharp's `np.random` module with 100% NumPy compatibility. + +--- + +## Table of Contents + +1. [Overview](#overview) +2. [Quick Reference](#quick-reference) +3. [Architecture](#architecture) +4. [Legacy API (np.random.*)](#legacy-api) +5. [Modern Generator API](#modern-generator-api) +6. [BitGenerators](#bitgenerators) +7. [SeedSequence](#seedsequence) +8. [Distribution Reference](#distribution-reference) +9. [Seeded Reference Values](#seeded-reference-values) +10. [Validation Rules](#validation-rules) +11. [Edge Cases](#edge-cases) +12. [Implicit Behaviors](#implicit-behaviors) +13. [NumSharp Implementation Status](#numsharp-implementation-status) +14. [MT19937 Implementation Details](#mt19937-implementation-details) + +--- + +## Overview + +NumPy's random module provides two APIs: + +| API | Introduced | Default RNG | Recommended | +|-----|------------|-------------|-------------| +| **Legacy** (`np.random.*`) | NumPy 1.0 | MT19937 | No (deprecated patterns) | +| **Modern** (`np.random.Generator`) | NumPy 1.17 | PCG64 | Yes (SPEC 7 compliant) | + +### Key Differences + +| Feature | Legacy | Modern | +|---------|--------|--------| +| Global state | Yes (`np.random.seed()`) | No (explicit Generator) | +| Default algorithm | MT19937 | PCG64 | +| Thread safety | No | Yes (per-Generator) | +| Reproducibility | Global seed | Explicit seeding | +| Parallel streams | Manual | `spawn()` / `SeedSequence` | +| `axis` parameter | No | Yes (shuffle, permutation, choice) | + +--- + +## Quick Reference + +### All Functions by Category + +#### Uniform Distributions +| Function | Legacy | Generator | NumSharp | Description | +|----------|--------|-----------|----------|-------------| +| `random()` | `random(size)` | `random(size, dtype, out)` | ✅ | Uniform [0, 1) | +| `rand()` | `rand(*shape)` | — | ✅ | Uniform [0, 1), shape as args | +| `random_sample()` | `random_sample(size)` | — | ✅ | Alias for `random()` | +| `ranf()` | `ranf(size)` | — | ❌ | Alias for `random()` | +| `sample()` | `sample(size)` | — | ❌ | Alias for `random()` | +| `uniform()` | `uniform(low, high, size)` | `uniform(low, high, size)` | ✅ | Uniform [low, high) | + +#### Normal Distributions +| Function | Legacy | Generator | NumSharp | Description | +|----------|--------|-----------|----------|-------------| +| `randn()` | `randn(*shape)` | — | ✅ | Standard normal, shape as args | +| `standard_normal()` | `standard_normal(size)` | `standard_normal(size, dtype, out)` | ✅ | Standard normal N(0,1) | +| `normal()` | `normal(loc, scale, size)` | `normal(loc, scale, size)` | ✅ | Normal N(loc, scale²) | +| `lognormal()` | `lognormal(mean, sigma, size)` | `lognormal(mean, sigma, size)` | ✅ | Log-normal | + +#### Integer Distributions +| Function | Legacy | Generator | NumSharp | Description | +|----------|--------|-----------|----------|-------------| +| `randint()` | `randint(low, high, size, dtype)` | — | ✅ | Random integers [low, high) | +| `integers()` | — | `integers(low, high, size, dtype, endpoint)` | ❌ | Random integers with endpoint option | +| `random_integers()` | `random_integers(low, high, size)` | — | ❌ | **DEPRECATED** - integers [low, high] | + +#### Sequences +| Function | Legacy | Generator | NumSharp | Description | +|----------|--------|-----------|----------|-------------| +| `choice()` | `choice(a, size, replace, p)` | `choice(a, size, replace, p, axis, shuffle)` | ✅ | Random selection | +| `permutation()` | `permutation(x)` | `permutation(x, axis)` | ✅ | Random permutation | +| `permuted()` | — | `permuted(x, axis, out)` | ❌ | Independent axis permutation | +| `shuffle()` | `shuffle(x)` | `shuffle(x, axis)` | ✅ | In-place shuffle | + +#### Continuous Distributions +| Function | Parameters | NumSharp | Description | +|----------|------------|----------|-------------| +| `beta()` | `a, b, size` | ✅ | Beta distribution | +| `chisquare()` | `df, size` | ✅ | Chi-square distribution | +| `exponential()` | `scale, size` | ✅ | Exponential distribution | +| `f()` | `dfnum, dfden, size` | ✅ | F distribution | +| `gamma()` | `shape, scale, size` | ✅ | Gamma distribution | +| `gumbel()` | `loc, scale, size` | ✅ | Gumbel (extreme value type I) | +| `laplace()` | `loc, scale, size` | ✅ | Laplace (double exponential) | +| `logistic()` | `loc, scale, size` | ✅ | Logistic distribution | +| `noncentral_chisquare()` | `df, nonc, size` | ✅ | Non-central chi-square | +| `noncentral_f()` | `dfnum, dfden, nonc, size` | ✅ | Non-central F | +| `pareto()` | `a, size` | ✅ | Pareto (Lomax) | +| `power()` | `a, size` | ✅ | Power distribution | +| `rayleigh()` | `scale, size` | ✅ | Rayleigh distribution | +| `standard_cauchy()` | `size` | ✅ | Standard Cauchy | +| `standard_exponential()` | `size` | ✅ | Standard exponential | +| `standard_gamma()` | `shape, size` | ✅ | Standard gamma | +| `standard_t()` | `df, size` | ✅ | Student's t | +| `triangular()` | `left, mode, right, size` | ✅ | Triangular distribution | +| `vonmises()` | `mu, kappa, size` | ✅ | Von Mises (circular) | +| `wald()` | `mean, scale, size` | ✅ | Wald (inverse Gaussian) | +| `weibull()` | `a, size` | ✅ | Weibull distribution | + +#### Discrete Distributions +| Function | Parameters | NumSharp | Description | +|----------|------------|----------|-------------| +| `bernoulli()` | `p, size` | ✅* | Bernoulli (NumSharp extra) | +| `binomial()` | `n, p, size` | ✅ | Binomial distribution | +| `geometric()` | `p, size` | ✅ | Geometric distribution | +| `hypergeometric()` | `ngood, nbad, nsample, size` | ✅ | Hypergeometric | +| `logseries()` | `p, size` | ✅ | Logarithmic series | +| `negative_binomial()` | `n, p, size` | ✅ | Negative binomial | +| `poisson()` | `lam, size` | ✅ | Poisson distribution | +| `zipf()` | `a, size` | ✅ | Zipf distribution | + +#### Multivariate Distributions +| Function | Parameters | NumSharp | Description | +|----------|------------|----------|-------------| +| `dirichlet()` | `alpha, size` | ✅ | Dirichlet distribution | +| `multinomial()` | `n, pvals, size` | ✅ | Multinomial distribution | +| `multivariate_normal()` | `mean, cov, size, check_valid, tol` | ✅ | Multivariate normal | +| `multivariate_hypergeometric()` | `colors, nsample, size, method` | ❌ | Multivariate hypergeometric | + +#### State Management +| Function | Legacy | Generator | NumSharp | Description | +|----------|--------|-----------|----------|-------------| +| `seed()` | `seed(seed)` | — | ✅ | Set global seed | +| `get_state()` | `get_state(legacy)` | — | ✅ | Get RNG state | +| `set_state()` | `set_state(state)` | — | ✅ | Set RNG state | +| `get_bit_generator()` | `get_bit_generator()` | — | ❌ | Get underlying BitGenerator | +| `set_bit_generator()` | `set_bit_generator(bg)` | — | ❌ | Set underlying BitGenerator | + +#### Utilities +| Function | Legacy | Generator | NumSharp | Description | +|----------|--------|-----------|----------|-------------| +| `bytes()` | `bytes(length)` | `bytes(length)` | ❌ | Random bytes | +| `spawn()` | — | `spawn(n)` | ❌ | Create child generators | + +--- + +## Architecture + +``` +np.random (module) +├── Module-level functions (legacy API) +│ ├── seed(), get_state(), set_state() +│ ├── rand(), randn(), randint(), random() +│ └── All distribution functions +│ +├── default_rng(seed) → Generator +│ +├── RandomState(seed) → Legacy container +│ └── Same methods as module-level +│ +├── Generator(bit_generator) → Modern container +│ ├── All distribution methods +│ ├── integers() (replaces randint) +│ ├── permuted() (axis-aware) +│ └── spawn() (parallel streams) +│ +├── BitGenerators (abstract base) +│ ├── MT19937 (Mersenne Twister) +│ ├── PCG64 (default, recommended) +│ ├── PCG64DXSM (PCG variant) +│ ├── Philox (counter-based) +│ └── SFC64 (Small Fast Chaotic) +│ +└── SeedSequence + ├── Proper seed mixing + ├── spawn() for parallel streams + └── generate_state() +``` + +--- + +## Legacy API + +### Module-Level Functions + +The legacy API uses global state. All functions operate on a shared `RandomState` instance. + +```python +import numpy as np + +# Set global seed +np.random.seed(42) + +# Generate random values +x = np.random.rand(5) # Uniform [0, 1) +y = np.random.randn(5) # Standard normal +z = np.random.randint(0, 100, 5) # Integers [0, 100) +``` + +### RandomState Class + +Encapsulates MT19937 state for reproducible sequences: + +```python +rs = np.random.RandomState(42) +x = rs.rand(5) +y = rs.randn(5) +``` + +### RandomState Methods (Complete List) + +``` +beta(a, b, size=None) +binomial(n, p, size=None) +bytes(length) +chisquare(df, size=None) +choice(a, size=None, replace=True, p=None) +dirichlet(alpha, size=None) +exponential(scale=1.0, size=None) +f(dfnum, dfden, size=None) +gamma(shape, scale=1.0, size=None) +geometric(p, size=None) +get_state(legacy=True) +gumbel(loc=0.0, scale=1.0, size=None) +hypergeometric(ngood, nbad, nsample, size=None) +laplace(loc=0.0, scale=1.0, size=None) +logistic(loc=0.0, scale=1.0, size=None) +lognormal(mean=0.0, sigma=1.0, size=None) +logseries(p, size=None) +multinomial(n, pvals, size=None) +multivariate_normal(mean, cov, size=None, check_valid='warn', tol=1e-08) +negative_binomial(n, p, size=None) +noncentral_chisquare(df, nonc, size=None) +noncentral_f(dfnum, dfden, nonc, size=None) +normal(loc=0.0, scale=1.0, size=None) +pareto(a, size=None) +permutation(x) +poisson(lam=1.0, size=None) +power(a, size=None) +rand(*args) +randint(low, high=None, size=None, dtype=int) +randn(*args) +random(size=None) +random_integers(low, high=None, size=None) # DEPRECATED +random_sample(size=None) +rayleigh(scale=1.0, size=None) +seed(seed=None) +set_state(state) +shuffle(x) +standard_cauchy(size=None) +standard_exponential(size=None) +standard_gamma(shape, size=None) +standard_normal(size=None) +standard_t(df, size=None) +tomaxint(size=None) +triangular(left, mode, right, size=None) +uniform(low=0.0, high=1.0, size=None) +vonmises(mu, kappa, size=None) +wald(mean, scale, size=None) +weibull(a, size=None) +zipf(a, size=None) +``` + +### State Format + +```python +state = np.random.get_state() +# Returns tuple: +# ('MT19937', +# array([624 uint32 values], dtype=uint32), # key array +# 624, # position (0-624) +# 0, # has_gauss (0 or 1) +# 0.0) # cached_gaussian +``` + +--- + +## Modern Generator API + +### Creating Generators + +```python +# Recommended: use default_rng() +rng = np.random.default_rng(42) + +# Or construct with specific BitGenerator +rng = np.random.Generator(np.random.PCG64(42)) +rng = np.random.Generator(np.random.MT19937(42)) +``` + +### Generator Methods (Complete List) + +``` +beta(a, b, size=None) +binomial(n, p, size=None) +bytes(length) +chisquare(df, size=None) +choice(a, size=None, replace=True, p=None, axis=0, shuffle=True) +dirichlet(alpha, size=None) +exponential(scale=1.0, size=None) +f(dfnum, dfden, size=None) +gamma(shape, scale=1.0, size=None) +geometric(p, size=None) +gumbel(loc=0.0, scale=1.0, size=None) +hypergeometric(ngood, nbad, nsample, size=None) +integers(low, high=None, size=None, dtype=np.int64, endpoint=False) +laplace(loc=0.0, scale=1.0, size=None) +logistic(loc=0.0, scale=1.0, size=None) +lognormal(mean=0.0, sigma=1.0, size=None) +logseries(p, size=None) +multinomial(n, pvals, size=None) +multivariate_hypergeometric(colors, nsample, size=None, method='marginals') +multivariate_normal(mean, cov, size=None, check_valid='warn', tol=1e-08, *, method='svd') +negative_binomial(n, p, size=None) +noncentral_chisquare(df, nonc, size=None) +noncentral_f(dfnum, dfden, nonc, size=None) +normal(loc=0.0, scale=1.0, size=None) +pareto(a, size=None) +permutation(x, axis=0) +permuted(x, *, axis=None, out=None) +poisson(lam=1.0, size=None) +power(a, size=None) +random(size=None, dtype=np.float64, out=None) +rayleigh(scale=1.0, size=None) +shuffle(x, axis=0) +spawn(n_children) +standard_cauchy(size=None) +standard_exponential(size=None, dtype=np.float64, method='zig', out=None) +standard_gamma(shape, size=None, dtype=np.float64, out=None) +standard_normal(size=None, dtype=np.float64, out=None) +standard_t(df, size=None) +triangular(left, mode, right, size=None) +uniform(low=0.0, high=1.0, size=None) +vonmises(mu, kappa, size=None) +wald(mean, scale, size=None) +weibull(a, size=None) +zipf(a, size=None) +``` + +### Generator Properties + +| Property | Description | +|----------|-------------| +| `bit_generator` | The underlying BitGenerator instance | + +### Generator-Specific Features + +#### `integers()` vs `randint()` + +```python +rng = np.random.default_rng(42) + +# endpoint=False (default): [low, high) +rng.integers(10, size=5) # [0, 7, 6, 4, 4] + +# endpoint=True: [low, high] +rng.integers(10, size=5, endpoint=True) # [0, 8, 7, 4, 4] +``` + +#### `permuted()` - Independent Axis Shuffle + +Unlike `shuffle()`, `permuted()` shuffles each slice independently: + +```python +rng = np.random.default_rng(42) +arr = np.arange(12).reshape(3, 4) +# [[ 0, 1, 2, 3], +# [ 4, 5, 6, 7], +# [ 8, 9, 10, 11]] + +# Shuffle along axis=1 (each row shuffled independently) +rng.permuted(arr, axis=1) +# [[ 3, 2, 1, 0], +# [ 7, 6, 4, 5], +# [ 8, 11, 10, 9]] +``` + +#### `shuffle()` with Axis + +```python +rng = np.random.default_rng(42) +arr = np.arange(12).reshape(3, 4) + +# Shuffle along axis=1 (columns reordered, same for all rows) +rng.shuffle(arr, axis=1) +# [[ 3, 2, 1, 0], +# [ 7, 6, 5, 4], +# [11, 10, 9, 8]] +``` + +#### `choice()` with Axis + +```python +rng = np.random.default_rng(42) +arr = np.arange(12).reshape(3, 4) + +# Select 2 items along axis=0 (rows) +rng.choice(arr, 2, axis=0) +# [[ 0, 1, 2, 3], +# [ 8, 9, 10, 11]] + +# Select 2 items along axis=1 (columns) +rng.choice(arr, 2, axis=1) +# [[ 0, 3], +# [ 4, 7], +# [ 8, 11]] +``` + +#### `spawn()` for Parallel Streams + +```python +rng = np.random.default_rng(42) +children = rng.spawn(3) + +# Each child is independent +for i, child in enumerate(children): + print(f"child[{i}]: {child.random()}") +# child[0]: 0.9167441575549085 +# child[1]: 0.4674907799518424 +# child[2]: 0.07123920291270869 +``` + +--- + +## BitGenerators + +### Overview + +| BitGenerator | Period | Speed | Use Case | +|--------------|--------|-------|----------| +| `PCG64` | 2^128 | Fast | **Default** - general use | +| `PCG64DXSM` | 2^128 | Fast | Better statistical properties | +| `MT19937` | 2^19937-1 | Medium | Legacy compatibility | +| `Philox` | 2^256 | Medium | Parallelization, reproducibility | +| `SFC64` | ~2^256 | Fastest | Speed-critical applications | + +### PCG64 (Default) + +Permuted Congruential Generator - NumPy's recommended default. + +```python +bg = np.random.PCG64(42) +rng = np.random.Generator(bg) + +# State +bg.state +# {'bit_generator': 'PCG64', +# 'state': {'state': 229482374823..., 'inc': 283847592...}, +# 'has_uint32': 0, +# 'uinteger': 0} + +# Advance state by n steps +bg.advance(1000) + +# Jump ahead by 2^64 steps +bg.jumped() +``` + +### MT19937 (Mersenne Twister) + +Classic algorithm, used by legacy API. + +```python +bg = np.random.MT19937(42) +rng = np.random.Generator(bg) + +# State +bg.state +# {'bit_generator': 'MT19937', +# 'state': {'key': array([...624 uint32...]), 'pos': 624}} + +# Jump ahead by 2^128 steps +bg.jumped() +``` + +### Philox (Counter-Based) + +Deterministic, parallelizable, cryptographically-derived. + +```python +bg = np.random.Philox(42) +rng = np.random.Generator(bg) + +# Key feature: advance to any position +bg.advance(1000000) # Skip 1M values instantly +``` + +### SFC64 (Small Fast Chaotic) + +Fastest option for non-cryptographic use. + +```python +bg = np.random.SFC64(42) +rng = np.random.Generator(bg) +``` + +### BitGenerator Common Methods + +| Method | Description | +|--------|-------------| +| `random_raw(size, output)` | Raw uint64 values | +| `spawn(n)` | Create n child BitGenerators | +| `jumped(jumps)` | Return jumped copy | +| `state` | Get/set state dict | +| `seed_seq` | Associated SeedSequence | +| `lock` | Threading lock (property) | +| `capsule` | PyCapsule for C API (property) | +| `cffi` | CFFI interface (property) | +| `ctypes` | ctypes interface (property) | + +### Seeded Output Comparison (seed=42) + +| BitGenerator | First 5 `random()` values | +|--------------|---------------------------| +| MT19937 | 0.5420, 0.6197, 0.0574, 0.8119, 0.8601 | +| PCG64 | 0.7740, 0.4389, 0.8586, 0.6974, 0.0942 | +| PCG64DXSM | 0.6684, 0.0068, 0.6580, 0.3713, 0.2067 | +| Philox | 0.0861, 0.1416, 0.2701, 0.8740, 0.1702 | +| SFC64 | 0.5299, 0.3782, 0.9454, 0.4211, 0.6412 | + +--- + +## SeedSequence + +Proper seed mixing for parallel streams. Avoids correlation issues with naive seeding. + +### Basic Usage + +```python +ss = np.random.SeedSequence(42) + +# Properties +ss.entropy # 42 +ss.pool_size # 4 +ss.pool # Mixed seed array +ss.spawn_key # () +ss.state # Internal state dict +ss.n_children_spawned # Number of children spawned +``` + +### Methods + +| Method | Signature | Description | +|--------|-----------|-------------| +| `spawn` | `spawn(n_children)` | Create n child SeedSequences | +| `generate_state` | `generate_state(n_words, dtype=np.uint32)` | Generate seed material | + +### Spawning Independent Streams + +```python +# BAD: Sequential seeds can be correlated +rng1 = np.random.default_rng(0) +rng2 = np.random.default_rng(1) # Potentially correlated! + +# GOOD: Use SeedSequence.spawn() +ss = np.random.SeedSequence(42) +children = ss.spawn(10) +rngs = [np.random.default_rng(child) for child in children] +# All statistically independent +``` + +### Generate State Material + +```python +ss = np.random.SeedSequence(42) +state = ss.generate_state(4) # [3444837047, 2669555309, 2046530742, 3581440988] +``` + +### Hierarchical Spawning + +```python +ss = np.random.SeedSequence(42) +level1 = ss.spawn(3) + +# Each child can spawn further +level2 = level1[0].spawn(5) +``` + +--- + +## Distribution Reference + +### Uniform Distributions + +#### `random(size=None)` / `rand(*shape)` + +Uniform distribution over [0, 1). + +```python +np.random.seed(42) +np.random.random(5) # [0.37454012, 0.95071431, 0.73199394, 0.59865848, 0.15601864] +np.random.rand(2, 3) # Shape as separate args +``` + +**Returns:** float64 + +#### `uniform(low=0.0, high=1.0, size=None)` + +Uniform distribution over [low, high). + +```python +np.random.seed(42) +np.random.uniform(0, 10, 5) # [3.74540119, 9.50714306, 7.31993942, 5.98658484, 1.5601864] +``` + +**Validation:** +- `low` and `high` must be finite +- `OverflowError` if range exceeds float64 bounds + +#### `randint(low, high=None, size=None, dtype=int)` + +Random integers from [low, high). + +```python +np.random.seed(42) +np.random.randint(100, size=5) # [51, 92, 14, 71, 60] +np.random.randint(0, 100, size=5) # Same as above +``` + +**Default dtype:** `int32` (NOT int64!) + +**Validation:** +- `ValueError: high <= 0` if only low provided and low <= 0 +- `ValueError: low >= high` if low >= high + +#### `integers(low, high=None, size=None, dtype=np.int64, endpoint=False)` [Generator only] + +Modern replacement for `randint()`. + +```python +rng = np.random.default_rng(42) +rng.integers(10, size=5) # [0, 7, 6, 4, 4] - exclusive +rng.integers(10, size=5, endpoint=True) # [0, 8, 7, 4, 4] - inclusive +``` + +--- + +### Normal Distributions + +#### `randn(*shape)` / `standard_normal(size=None)` + +Standard normal distribution N(0, 1). + +```python +np.random.seed(42) +np.random.randn(5) # [0.49671415, -0.1382643, 0.64768854, 1.52302986, -0.23415337] +``` + +**Returns:** float64 + +#### `normal(loc=0.0, scale=1.0, size=None)` + +Normal distribution N(loc, scale²). + +```python +np.random.seed(42) +np.random.normal(0, 1, 5) # Same as randn(5) +np.random.normal(100, 15, 5) # Mean=100, std=15 +``` + +**Edge cases:** +- `normal(nan, 1)` → array of nan +- `normal(0, inf)` → array of inf +- `normal(0, 0)` → array of loc (constant) + +#### `lognormal(mean=0.0, sigma=1.0, size=None)` + +Log-normal distribution. + +```python +np.random.seed(42) +np.random.lognormal(0, 1, 5) # [1.64331272, 0.87086849, 1.91111824, 4.58609939, 0.79124045] +``` + +**Note:** `mean` and `sigma` are of the underlying normal distribution, not the log-normal. + +--- + +### Discrete Distributions + +#### `binomial(n, p, size=None)` + +Binomial distribution. + +```python +np.random.seed(42) +np.random.binomial(10, 0.5, 5) # [4, 8, 6, 5, 3] +``` + +**Returns:** int32 + +**Validation:** +- `ValueError: n < 0` +- `ValueError: p < 0, p > 1 or p is NaN` + +#### `poisson(lam=1.0, size=None)` + +Poisson distribution. + +```python +np.random.seed(42) +np.random.poisson(5, 5) # [5, 4, 4, 5, 5] +``` + +**Returns:** int32 + +**Validation:** +- `ValueError: lam < 0 or lam is NaN` +- `ValueError: lam value too large` (lam >= ~1e10) + +#### `geometric(p, size=None)` + +Geometric distribution (number of trials until first success). + +```python +np.random.seed(42) +np.random.geometric(0.5, 5) # [1, 5, 2, 2, 1] +``` + +**Returns:** int32 + +**Validation:** +- `ValueError: p <= 0, p > 1 or p contains NaNs` + +#### `negative_binomial(n, p, size=None)` + +Negative binomial distribution. + +```python +np.random.seed(42) +np.random.negative_binomial(5, 0.5, 5) # [3, 2, 3, 2, 5] +``` + +**Validation:** +- `ValueError: n <= 0` +- `ValueError: p < 0, p > 1 or p is NaN` + +**Edge cases:** +- `negative_binomial(1, 0)` → large integers (no error!) +- `negative_binomial(1, 1)` → array of 0 + +#### `hypergeometric(ngood, nbad, nsample, size=None)` + +Hypergeometric distribution. + +```python +np.random.seed(42) +np.random.hypergeometric(10, 5, 7, 5) # [5, 3, 6, 6, 5] +``` + +**Validation:** +- `ValueError: nsample < 1 or nsample is NaN` + +#### `logseries(p, size=None)` + +Logarithmic series distribution. + +```python +np.random.seed(42) +np.random.logseries(0.9, 5) # [9, 2, 2, 20, 3] +``` + +**Validation:** +- `ValueError: p < 0, p >= 1 or p is NaN` + +**Edge case:** `logseries(0)` → array of 1 (no error!) + +#### `zipf(a, size=None)` + +Zipf distribution. + +```python +np.random.seed(42) +np.random.zipf(2, 5) # [1, 3, 1, 1, 2] +``` + +**Validation:** +- `ValueError: a <= 1 or a is NaN` + +--- + +### Continuous Distributions + +#### `beta(a, b, size=None)` + +Beta distribution. + +```python +np.random.seed(42) +np.random.beta(2, 5, 5) # [0.35367666, 0.24855807, 0.41595909, 0.15996758, 0.55028308] +``` + +**Validation:** +- `ValueError: a <= 0` +- `ValueError: b <= 0` + +#### `gamma(shape, scale=1.0, size=None)` + +Gamma distribution. + +```python +np.random.seed(42) +np.random.gamma(2, 1, 5) # [2.39367939, 1.49446473, 1.38228358, 1.38230229, 4.64971441] +``` + +**Validation:** +- `ValueError: shape < 0` +- `ValueError: scale < 0` + +**Edge cases:** +- `gamma(0, 1)` → array of 0.0 (no error!) +- `gamma(nan, 1)` → array of nan +- `gamma(inf, 1)` → array of inf + +#### `exponential(scale=1.0, size=None)` + +Exponential distribution. + +```python +np.random.seed(42) +np.random.exponential(1, 5) # [0.46926809, 3.01012143, 1.31674569, 0.91294255, 0.16962487] +``` + +**Validation:** +- `ValueError: scale < 0` + +**Edge cases:** +- `exponential(0)` → array of 0.0 +- `exponential(nan)` → array of nan +- `exponential(inf)` → array of inf + +#### `chisquare(df, size=None)` + +Chi-square distribution. + +```python +np.random.seed(42) +np.random.chisquare(5, 5) # [5.96627073, 3.93890591, 3.67991027, 3.67995362, 10.84321348] +``` + +**Validation:** +- `ValueError: df <= 0` + +**Edge case:** `chisquare(nan)` → array of nan + +#### `f(dfnum, dfden, size=None)` + +F distribution. + +```python +np.random.seed(42) +np.random.f(5, 10, 5) # [1.36393455, 0.88058749, 1.66088313, 0.52073749, 3.11291601] +``` + +#### `standard_t(df, size=None)` + +Student's t distribution. + +```python +np.random.seed(42) +np.random.standard_t(5, 5) # [0.55963354, -1.07574122, 1.33391804, -0.75446925, 0.60920065] +``` + +**Edge case:** `standard_t(nan)` → array of nan + +#### `vonmises(mu, kappa, size=None)` + +Von Mises distribution (circular normal). + +```python +np.random.seed(42) +np.random.vonmises(0, 1, 5) # [0.62690657, -1.17478453, 0.08884717, 1.55489819, -2.1288983] +``` + +**Validation:** +- `ValueError: kappa < 0` + +#### `wald(mean, scale, size=None)` + +Wald (inverse Gaussian) distribution. + +```python +np.random.seed(42) +np.random.wald(1, 1, 5) # [1.63516639, 1.14815282, 0.79166122, 1.26314598, 0.23479012] +``` + +**Validation:** +- `ValueError: mean <= 0` +- `ValueError: scale <= 0` + +#### `weibull(a, size=None)` + +Weibull distribution. + +```python +np.random.seed(42) +np.random.weibull(2, 5) # [0.68503145, 1.73497015, 1.1474954, 0.95548027, 0.4118554] +``` + +**Edge case:** `weibull(0)` → no error (returns values) + +#### `pareto(a, size=None)` + +Pareto distribution. + +```python +np.random.seed(42) +np.random.pareto(2, 5) # [0.26444595, 3.50442711, 0.93164669, 0.57849408, 0.08851288] +``` + +**Validation:** +- `ValueError: a <= 0` + +#### `power(a, size=None)` + +Power distribution. + +```python +np.random.seed(42) +np.random.power(2, 5) # [0.61199683, 0.9750458, 0.85556645, 0.77373024, 0.39499195] +``` + +**Validation:** +- `ValueError: a <= 0` + +#### `rayleigh(scale=1.0, size=None)` + +Rayleigh distribution. + +```python +np.random.seed(42) +np.random.rayleigh(1, 5) # [0.96878077, 2.45361832, 1.62280356, 1.35125316, 0.58245149] +``` + +**Validation:** +- `ValueError: scale < 0` + +**Edge case:** `rayleigh(0)` → array of 0.0 + +#### `laplace(loc=0.0, scale=1.0, size=None)` + +Laplace (double exponential) distribution. + +```python +np.random.seed(42) +np.random.laplace(0, 1, 5) # [-0.28890917, 2.31697425, 0.62359851, 0.21979537, -1.16463261] +``` + +**Edge cases:** +- `laplace(0, 0)` → array of 0.0 +- `laplace(nan, 1)` → array of nan + +#### `logistic(loc=0.0, scale=1.0, size=None)` + +Logistic distribution. + +```python +np.random.seed(42) +np.random.logistic(0, 1, 5) # [-0.51278827, 2.95957976, 1.00476265, 0.39987857, -1.68815492] +``` + +**Edge case:** `logistic(0, 0)` → array of 0.0 + +#### `gumbel(loc=0.0, scale=1.0, size=None)` + +Gumbel (extreme value type I) distribution. + +```python +np.random.seed(42) +np.random.gumbel(0, 1, 5) # [0.75658105, -1.10198042, -0.27516331, 0.09108232, 1.77416592] +``` + +**Edge case:** `gumbel(0, 0)` → array of 0.0 + +#### `triangular(left, mode, right, size=None)` + +Triangular distribution. + +```python +np.random.seed(42) +np.random.triangular(0, 0.5, 1, 5) # [0.43274711, 0.8430196, 0.63393576, 0.5520371, 0.27930149] +``` + +**Validation:** +- `ValueError: left > mode` +- `ValueError: mode > right` +- `ValueError: left == right` (when left == mode == right) + +#### `standard_cauchy(size=None)` + +Standard Cauchy distribution. + +```python +np.random.seed(42) +np.random.standard_cauchy(5) # [-3.59249748, 0.42526319, 1.00007012, 2.05778128, -0.8652948] +``` + +#### `standard_exponential(size=None)` + +Standard exponential distribution (scale=1). + +```python +np.random.seed(42) +np.random.standard_exponential(5) # [0.46926809, 3.01012143, 1.31674569, 0.91294255, 0.16962487] +``` + +#### `standard_gamma(shape, size=None)` + +Standard gamma distribution (scale=1). + +```python +np.random.seed(42) +np.random.standard_gamma(2, 5) # [2.39367939, 1.49446473, 1.38228358, 1.38230229, 4.64971441] +``` + +#### `noncentral_chisquare(df, nonc, size=None)` + +Non-central chi-square distribution. + +```python +np.random.seed(42) +np.random.noncentral_chisquare(5, 1, 5) # [5.52994719, 2.94728841, 12.42325435, 2.27267645, 4.83200133] +``` + +#### `noncentral_f(dfnum, dfden, nonc, size=None)` + +Non-central F distribution. + +```python +np.random.seed(42) +np.random.noncentral_f(5, 10, 1, 5) # [2.08421137, 0.81334421, 1.3119517, 2.28476301, 0.48492134] +``` + +--- + +### Multivariate Distributions + +#### `dirichlet(alpha, size=None)` + +Dirichlet distribution. + +```python +np.random.seed(42) +np.random.dirichlet([1, 1, 1], 3) +# [[0.09784297, 0.62761396, 0.27454307], +# [0.72909200, 0.13546541, 0.13544259], +# [0.02001195, 0.67261832, 0.30736973]] +``` + +**Validation:** +- `ValueError: alpha <= 0` + +#### `multinomial(n, pvals, size=None)` + +Multinomial distribution. + +```python +np.random.seed(42) +np.random.multinomial(10, [0.2, 0.3, 0.5], 3) +# [[1, 6, 3], +# [3, 3, 4], +# [1, 2, 7]] +``` + +**Note:** `pvals` should sum to 1, but NumPy doesn't strictly enforce this. + +#### `multivariate_normal(mean, cov, size=None, check_valid='warn', tol=1e-08)` + +Multivariate normal distribution. + +```python +np.random.seed(42) +np.random.multivariate_normal([0, 0], [[1, 0], [0, 1]], 3) +# [[ 0.49671415, -0.1382643 ], +# [ 0.64768854, 1.52302986], +# [-0.23415337, -0.23413696]] +``` + +**Parameters:** +- `check_valid`: 'warn', 'raise', or 'ignore' for covariance matrix validity +- `tol`: Tolerance for covariance matrix symmetry check + +#### `multivariate_hypergeometric(colors, nsample, size=None, method='marginals')` [Generator only] + +Multivariate hypergeometric distribution. + +```python +rng = np.random.default_rng(42) +rng.multivariate_hypergeometric([10, 5, 3], 8) # [5, 2, 1] +``` + +**Parameters:** +- `colors`: Number of items of each type +- `nsample`: Number of items to sample +- `method`: 'marginals' or 'count' + +--- + +### Sequence Operations + +#### `choice(a, size=None, replace=True, p=None)` + +Random selection from array or range. + +```python +np.random.seed(42) +np.random.choice(10, 5) # [6, 3, 7, 4, 6] +np.random.choice([1,2,3,4,5], 3) # Selection from array +np.random.choice(10, 5, replace=False) # Without replacement +np.random.choice(10, 5, p=[0.1]*10) # With probabilities +``` + +**Generator version** adds `axis` and `shuffle` parameters: +```python +rng = np.random.default_rng(42) +arr = np.arange(12).reshape(3, 4) +rng.choice(arr, 2, axis=0) # Select rows +rng.choice(arr, 2, axis=1) # Select columns +``` + +**Validation:** +- `ValueError: 'a' cannot be empty unless no samples are taken` + +#### `permutation(x)` + +Return a randomly permuted copy. + +```python +np.random.seed(42) +np.random.permutation(10) # [8, 1, 5, 0, 7, 2, 9, 4, 3, 6] +np.random.permutation([1, 2, 3, 4, 5]) # Permute array +``` + +**Generator version** adds `axis` parameter: +```python +rng = np.random.default_rng(42) +rng.permutation(arr, axis=1) # Permute along axis +``` + +#### `shuffle(x)` + +Shuffle array in-place. + +```python +arr = np.arange(10) +np.random.seed(42) +np.random.shuffle(arr) # arr is now [8, 1, 5, 0, 7, 2, 9, 4, 3, 6] +``` + +**Note:** For multi-dimensional arrays, only shuffles along first axis. + +**Generator version** adds `axis` parameter: +```python +rng = np.random.default_rng(42) +rng.shuffle(arr, axis=1) # Shuffle along specific axis +``` + +#### `permuted(x, axis=None, out=None)` [Generator only] + +Shuffle along axis with independent permutations per slice. + +```python +rng = np.random.default_rng(42) +arr = np.arange(12).reshape(3, 4) + +# Each row is shuffled independently +rng.permuted(arr, axis=1) +# [[ 3, 2, 1, 0], +# [ 7, 6, 4, 5], +# [ 8, 11, 10, 9]] +``` + +**Key difference from `shuffle(axis=...)`:** +- `shuffle(axis=1)`: Reorders columns, same order for all rows +- `permuted(axis=1)`: Each row gets its own independent shuffle + +#### `bytes(length)` + +Generate random bytes. + +```python +np.random.seed(42) +np.random.bytes(10) # b'\xc9\xa5...' +``` + +--- + +## Seeded Reference Values + +All values generated with `seed(42)`, `size=5` unless noted. + +### Core Functions + +| Function | Output | +|----------|--------| +| `rand(5)` | `[0.37454012, 0.95071431, 0.73199394, 0.59865848, 0.15601864]` | +| `randn(5)` | `[0.49671415, -0.1382643, 0.64768854, 1.52302986, -0.23415337]` | +| `randint(100, size=5)` | `[51, 92, 14, 71, 60]` | +| `random(5)` | `[0.37454012, 0.95071431, 0.73199394, 0.59865848, 0.15601864]` | +| `uniform(0, 10, 5)` | `[3.74540119, 9.50714306, 7.31993942, 5.98658484, 1.5601864]` | +| `normal(0, 1, 5)` | `[0.49671415, -0.1382643, 0.64768854, 1.52302986, -0.23415337]` | +| `choice(10, 5)` | `[6, 3, 7, 4, 6]` | +| `permutation(10)` | `[8, 1, 5, 0, 7, 2, 9, 4, 3, 6]` | + +### Distributions + +| Distribution | Output | +|--------------|--------| +| `beta(2, 5, 5)` | `[0.35367666, 0.24855807, 0.41595909, 0.15996758, 0.55028308]` | +| `binomial(10, 0.5, 5)` | `[4, 8, 6, 5, 3]` | +| `chisquare(5, 5)` | `[5.96627073, 3.93890591, 3.67991027, 3.67995362, 10.84321348]` | +| `exponential(1, 5)` | `[0.46926809, 3.01012143, 1.31674569, 0.91294255, 0.16962487]` | +| `f(5, 10, 5)` | `[1.36393455, 0.88058749, 1.66088313, 0.52073749, 3.11291601]` | +| `gamma(2, 1, 5)` | `[2.39367939, 1.49446473, 1.38228358, 1.38230229, 4.64971441]` | +| `geometric(0.5, 5)` | `[1, 5, 2, 2, 1]` | +| `gumbel(0, 1, 5)` | `[0.75658105, -1.10198042, -0.27516331, 0.09108232, 1.77416592]` | +| `hypergeometric(10, 5, 7, 5)` | `[5, 3, 6, 6, 5]` | +| `laplace(0, 1, 5)` | `[-0.28890917, 2.31697425, 0.62359851, 0.21979537, -1.16463261]` | +| `logistic(0, 1, 5)` | `[-0.51278827, 2.95957976, 1.00476265, 0.39987857, -1.68815492]` | +| `lognormal(0, 1, 5)` | `[1.64331272, 0.87086849, 1.91111824, 4.58609939, 0.79124045]` | +| `logseries(0.9, 5)` | `[9, 2, 2, 20, 3]` | +| `negative_binomial(5, 0.5, 5)` | `[3, 2, 3, 2, 5]` | +| `noncentral_chisquare(5, 1, 5)` | `[5.52994719, 2.94728841, 12.42325435, 2.27267645, 4.83200133]` | +| `noncentral_f(5, 10, 1, 5)` | `[2.08421137, 0.81334421, 1.3119517, 2.28476301, 0.48492134]` | +| `pareto(2, 5)` | `[0.26444595, 3.50442711, 0.93164669, 0.57849408, 0.08851288]` | +| `poisson(5, 5)` | `[5, 4, 4, 5, 5]` | +| `power(2, 5)` | `[0.61199683, 0.9750458, 0.85556645, 0.77373024, 0.39499195]` | +| `rayleigh(1, 5)` | `[0.96878077, 2.45361832, 1.62280356, 1.35125316, 0.58245149]` | +| `standard_cauchy(5)` | `[-3.59249748, 0.42526319, 1.00007012, 2.05778128, -0.8652948]` | +| `standard_exponential(5)` | `[0.46926809, 3.01012143, 1.31674569, 0.91294255, 0.16962487]` | +| `standard_gamma(2, 5)` | `[2.39367939, 1.49446473, 1.38228358, 1.38230229, 4.64971441]` | +| `standard_t(5, 5)` | `[0.55963354, -1.07574122, 1.33391804, -0.75446925, 0.60920065]` | +| `triangular(0, 0.5, 1, 5)` | `[0.43274711, 0.8430196, 0.63393576, 0.5520371, 0.27930149]` | +| `vonmises(0, 1, 5)` | `[0.62690657, -1.17478453, 0.08884717, 1.55489819, -2.1288983]` | +| `wald(1, 1, 5)` | `[1.63516639, 1.14815282, 0.79166122, 1.26314598, 0.23479012]` | +| `weibull(2, 5)` | `[0.68503145, 1.73497015, 1.1474954, 0.95548027, 0.4118554]` | +| `zipf(2, 5)` | `[1, 3, 1, 1, 2]` | + +### Multivariate (size=3) + +| Distribution | Output | +|--------------|--------| +| `dirichlet([1,1,1], 3)` | `[[0.098, 0.628, 0.275], [0.729, 0.135, 0.135], [0.020, 0.673, 0.307]]` | +| `multinomial(10, [.2,.3,.5], 3)` | `[[1, 6, 3], [3, 3, 4], [1, 2, 7]]` | +| `multivariate_normal([0,0], [[1,0],[0,1]], 3)` | `[[0.497, -0.138], [0.648, 1.523], [-0.234, -0.234]]` | + +--- + +## Validation Rules + +### Seed Validation + +| Input | Result | +|-------|--------| +| `seed(0)` to `seed(2**32-1)` | Valid | +| `seed(-1)` | `ValueError: Seed must be between 0 and 2**32 - 1` | +| `seed(2**32)` | `ValueError: Seed must be between 0 and 2**32 - 1` | +| `seed(42.0)` | `TypeError: Cannot cast scalar from dtype('float64') to dtype('int64')` | +| `seed(None)` | Valid - uses system entropy | +| `seed([])` | `ValueError: Seed must be non-empty` | +| `seed([1,2,3,4])` | Valid - array seeding | +| `seed([[1,2],[3,4]])` | `ValueError: Seed array must be 1-d` | + +### Size Parameter + +| Input | Result | +|-------|--------| +| `size=None` | Returns Python scalar (float/int) | +| `size=()` | Returns 0-d ndarray (shape=(), ndim=0) | +| `size=5` | Returns 1-d ndarray (shape=(5,)) | +| `size=(2,3)` | Returns 2-d ndarray (shape=(2,3)) | +| `size=0` | Returns empty 1-d ndarray (shape=(0,)) | +| `size=(5,0)` | Returns empty 2-d ndarray (shape=(5,0)) | +| `size=-1` | `ValueError: negative dimensions are not allowed` | + +### Distribution Validation Summary + +| Distribution | Parameter | Constraint | Error | +|--------------|-----------|------------|-------| +| `beta` | `a`, `b` | > 0 | `ValueError: a <= 0` / `b <= 0` | +| `binomial` | `n` | >= 0 | `ValueError: n < 0` | +| `binomial` | `p` | [0, 1] | `ValueError: p < 0, p > 1 or p is NaN` | +| `chisquare` | `df` | > 0 | `ValueError: df <= 0` | +| `exponential` | `scale` | >= 0 | `ValueError: scale < 0` | +| `gamma` | `shape` | >= 0 | `ValueError: shape < 0` | +| `gamma` | `scale` | >= 0 | `ValueError: scale < 0` | +| `geometric` | `p` | (0, 1] | `ValueError: p <= 0, p > 1 or p contains NaNs` | +| `hypergeometric` | `nsample` | >= 1 | `ValueError: nsample < 1 or nsample is NaN` | +| `hypergeometric` | `nsample` | <= ngood + nbad | `ValueError: ngood + nbad < nsample` | +| `logseries` | `p` | [0, 1) | `ValueError: p < 0, p >= 1 or p is NaN` | +| `negative_binomial` | `n` | > 0 | `ValueError: n <= 0` | +| `pareto` | `a` | > 0 | `ValueError: a <= 0` | +| `poisson` | `lam` | >= 0, < ~1e10 | `ValueError: lam < 0 or lam is NaN` | +| `power` | `a` | > 0 | `ValueError: a <= 0` | +| `randint` | `low`, `high` | low < high | `ValueError: low >= high` | +| `rayleigh` | `scale` | >= 0 | `ValueError: scale < 0` | +| `triangular` | `left`, `mode`, `right` | left <= mode <= right | `ValueError: left > mode` | +| `uniform` | `low`, `high` | finite | `OverflowError: Range exceeds valid bounds` | +| `vonmises` | `kappa` | >= 0 | `ValueError: kappa < 0` | +| `wald` | `mean`, `scale` | > 0 | `ValueError: mean <= 0` / `scale <= 0` | +| `zipf` | `a` | > 1 | `ValueError: a <= 1 or a is NaN` | +| `dirichlet` | `alpha` | all > 0 | `ValueError: alpha <= 0` | +| `multinomial` | `n` | >= 0 | `ValueError: n < 0` | +| `choice` | `a` | non-empty | `ValueError: 'a' cannot be empty unless no samples are taken` | + +--- + +## Edge Cases + +### No-Error Edge Cases + +These inputs do NOT throw errors in NumPy - they produce nan/inf or degenerate outputs: + +| Function | Input | Output | +|----------|-------|--------| +| `normal(nan, 1)` | nan loc | Array of nan | +| `normal(0, inf)` | inf scale | Array of inf | +| `normal(0, 0)` | zero scale | Array of loc (constant) | +| `gamma(0, 1)` | zero shape | Array of 0.0 | +| `gamma(nan, 1)` | nan shape | Array of nan | +| `gamma(inf, 1)` | inf shape | Array of inf | +| `exponential(0)` | zero scale | Array of 0.0 | +| `exponential(nan)` | nan scale | Array of nan | +| `exponential(inf)` | inf scale | Array of inf | +| `beta(nan, 1)` | nan a | Array of nan | +| `beta(inf, 1)` | inf a | Array of nan (inf/inf) | +| `standard_gamma(0)` | zero shape | Array of 0.0 | +| `standard_gamma(nan)` | nan shape | Array of nan | +| `chisquare(nan)` | nan df | Array of nan | +| `standard_t(nan)` | nan df | Array of nan | +| `laplace(0, 0)` | zero scale | Array of 0.0 | +| `laplace(nan, 1)` | nan loc | Array of nan | +| `logistic(0, 0)` | zero scale | Array of 0.0 | +| `gumbel(0, 0)` | zero scale | Array of 0.0 | +| `lognormal(0, 0)` | zero sigma | Array of 1.0 | +| `logseries(0)` | zero p | Array of 1 | +| `rayleigh(0)` | zero scale | Array of 0.0 | +| `negative_binomial(1, 0)` | zero p | Large integers | +| `negative_binomial(1, 1)` | one p | Array of 0 | +| `weibull(0)` | zero a | Values (no error) | +| `multinomial(10, [0.5, 0.6])` | pvals > 1 | Works (no validation!) | + +--- + +## Implicit Behaviors + +### Return Type: Scalar vs Array + +The `size` parameter controls whether a scalar or array is returned: + +| `size` value | Return type | Shape | Notes | +|--------------|-------------|-------|-------| +| `None` (default) | Python scalar (`float`/`int`) | N/A | NOT an ndarray | +| `()` | 0-d ndarray | `()` | `ndim=0`, `size=1` | +| `5` | 1-d ndarray | `(5,)` | | +| `(2, 3)` | 2-d ndarray | `(2, 3)` | | +| `0` | Empty 1-d ndarray | `(0,)` | | +| `(5, 0)` | Empty 2-d ndarray | `(5, 0)` | | + +**0-d array properties:** +```python +arr0d = np.random.random(size=()) +arr0d.shape # () +arr0d.ndim # 0 +arr0d.size # 1 +arr0d.item() # Extract as Python scalar +arr0d[()] # Also extracts scalar +``` + +### Default Return Dtypes + +| Category | Functions | Default dtype | +|----------|-----------|---------------| +| Floating | `rand`, `randn`, `random`, `uniform`, `normal`, `standard_normal`, `beta`, `gamma`, `exponential`, `chisquare`, `f`, `standard_t`, `vonmises`, `wald`, `weibull`, `pareto`, `power`, `rayleigh`, `laplace`, `logistic`, `gumbel`, `triangular`, `lognormal`, `standard_cauchy`, `standard_exponential`, `standard_gamma`, `noncentral_chisquare`, `noncentral_f`, `dirichlet` | `float64` | +| Integer | `randint`, `choice`, `permutation`, `binomial`, `poisson`, `geometric`, `negative_binomial`, `hypergeometric`, `zipf`, `logseries`, `multinomial` | `int32` | + +**Note:** `randint` default is `int32`, not `int64`! + +### Broadcasting in Distribution Parameters + +Most distribution parameters accept arrays and broadcast: + +```python +# Array parameters broadcast with size +np.random.seed(42) +np.random.uniform(low=[0, 1, 2], high=10, size=3) +# [3.74540119, 9.55642876, 7.85595153] + +np.random.normal(loc=[0, 10, 100], scale=1, size=3) +# [0.49671415, 9.8617357, 100.64768854] + +np.random.poisson(lam=[1, 5, 10], size=3) +# [1, 4, 14] +``` + +**Shape inference when `size=None`:** + +When `size` is not provided, output shape is inferred from parameter broadcasting: + +```python +np.random.uniform([0, 1], [10, 20]) # shape=(2,) +np.random.normal([[0], [1]], [[1, 2], [3, 4]]) # shape=(2, 2) +``` + +### Multivariate Distribution Shapes + +Multivariate distributions append their output dimension to the size: + +| Distribution | Parameters | size=None | size=3 | size=(2,3) | +|--------------|------------|-----------|--------|------------| +| `multivariate_normal` | mean=(k,) | (k,) | (3, k) | (2, 3, k) | +| `dirichlet` | alpha=(k,) | (k,) | (3, k) | (2, 3, k) | +| `multinomial` | pvals=(k,) | (k,) | (3, k) | (2, 3, k) | +| `multivariate_hypergeometric` | colors=(k,) | (k,) | (3, k) | (2, 3, k) | + +### Sequence Operation Details + +#### `shuffle(x)` Behavior + +- **Returns:** `None` (in-place modification) +- **Multi-dimensional:** Only shuffles along axis 0 (rows) +- **Generator version:** Accepts `axis` parameter + +```python +arr = np.arange(10) +result = np.random.shuffle(arr) # result is None +# arr is modified in-place + +arr2d = np.arange(12).reshape(3, 4) +np.random.shuffle(arr2d) # Only shuffles rows, not elements +``` + +#### `permutation(x)` Behavior + +- **Returns:** New array (copy, original unchanged) +- **Multi-dimensional:** Only permutes along axis 0 (rows) +- **Generator version:** Accepts `axis` parameter + +```python +arr = np.arange(10) +result = np.random.permutation(arr) # New array +# arr is unchanged +``` + +#### `choice()` Validation + +| Condition | Error | +|-----------|-------| +| Empty `a` with size > 0 | `ValueError: 'a' cannot be empty unless no samples are taken` | +| `replace=False` and size > len(a) | `ValueError: Cannot take a larger sample than population when 'replace=False'` | +| Negative probability | `ValueError: probabilities are not non-negative` | +| Probabilities don't sum to 1 | `ValueError: probabilities do not sum to 1` | + +### Generator-Specific Parameters + +#### `out` Parameter + +Many Generator methods accept an `out` parameter for in-place output: + +```python +rng = np.random.default_rng(42) +out = np.zeros(5) +result = rng.random(size=5, out=out) +# result is out (same object) +# out is filled with random values +``` + +**Validation:** +- Wrong shape: `ValueError` +- Wrong dtype: `TypeError` + +#### `dtype` Parameter + +Generator methods support `dtype` for output type: + +```python +rng = np.random.default_rng(42) +rng.random(5, dtype=np.float32) # Returns float32 array +rng.standard_normal(5, dtype=np.float32) # Returns float32 array +``` + +**Supported:** `np.float32`, `np.float64` (default) + +#### `method` Parameter + +Some Generator methods have algorithm selection: + +```python +# standard_exponential: 'zig' (default, Ziggurat) or 'inv' (inverse transform) +rng.standard_exponential(3, method='zig') # Faster +rng.standard_exponential(3, method='inv') # Different values + +# multivariate_normal: 'svd' (default), 'cholesky', 'eigh' +rng.multivariate_normal(mean, cov, method='cholesky') +``` + +### `default_rng()` Input Types + +| Input | Behavior | +|-------|----------| +| `None` | Create new Generator with system entropy | +| `int` | Create Generator seeded with integer | +| `SeedSequence` | Create Generator from SeedSequence | +| `BitGenerator` | Wrap in Generator | +| `Generator` | **Return same object** (no copy) | + +```python +rng1 = np.random.default_rng(42) +rng2 = np.random.default_rng(rng1) +rng1 is rng2 # True! Same object +``` + +### State Format Details + +#### Legacy Format (`get_state(legacy=True)`) + +Returns a tuple: + +```python +('MT19937', # [0] Algorithm name + array([...624...]), # [1] uint32[624] state array + 624, # [2] Position (0-624) + 0, # [3] has_gauss (0 or 1) + 0.0) # [4] cached_gaussian +``` + +**Gaussian caching:** After calling `randn()`, the state includes the cached second Gaussian value from Box-Muller: + +```python +np.random.seed(42) +np.random.randn() +state = np.random.get_state() +state[3] # 1 (has_gauss = True) +state[4] # -0.138264... (cached value) +``` + +#### Dict Format (`get_state(legacy=False)`) + +Returns a dict: + +```python +{ + 'bit_generator': 'MT19937', + 'state': {'key': array([...624...]), 'pos': 624}, + 'has_gauss': 0, + 'gauss': 0.0 +} +``` + +### BitGenerator Properties and Methods + +| Property/Method | Description | +|-----------------|-------------| +| `state` | Get/set state dict | +| `seed_seq` | Associated SeedSequence | +| `lock` | Threading `RLock` for thread safety | +| `capsule` | PyCapsule for C API | +| `cffi` | CFFI interface | +| `ctypes` | ctypes interface | +| `random_raw(size, output)` | Raw uint64 values | +| `spawn(n)` | Create n child BitGenerators | +| `jumped(jumps)` | Return jumped copy (advance by 2^128 steps) | +| `advance(delta)` | Advance state by delta steps (PCG64/Philox only) | + +### `randint` Dtype Bounds Checking + +When specifying dtype, values must fit in the dtype range: + +```python +# Valid +np.random.randint(0, 127, dtype=np.int8) + +# Invalid - high out of bounds +np.random.randint(0, 256, dtype=np.int8) +# ValueError: high is out of bounds for int8 + +# Invalid - low out of bounds for unsigned +np.random.randint(-1, 10, dtype=np.uint8) +# ValueError: low is out of bounds for uint8 +``` + +### Negative Axis Support (Generator) + +Generator methods with `axis` parameter support negative indices: + +```python +rng = np.random.default_rng(42) +arr = np.arange(12).reshape(3, 4) + +rng.permuted(arr, axis=-1) # Same as axis=1 +rng.permuted(arr, axis=-2) # Same as axis=0 +``` + +### Special Float Value Behavior + +| Distribution | nan input | inf input | +|--------------|-----------|-----------| +| `normal(loc, scale)` | nan → array of nan | inf → array of inf | +| `gamma(shape, scale)` | nan → array of nan | inf → array of inf | +| `exponential(scale)` | nan → array of nan | inf → array of inf | +| `uniform(low, high)` | — | `OverflowError` | +| `beta(a, b)` | nan → array of nan | inf → array of nan | + +### Validation Error Messages + +NumPy uses specific error message formats. Key patterns: + +| Pattern | Example | +|---------|---------| +| `X <= 0` | `ValueError: a <= 0` | +| `X < 0` | `ValueError: scale < 0` | +| `X < 0, X > 1 or X is NaN` | `ValueError: p < 0, p > 1 or p is NaN` | +| `low >= high` | `ValueError: low >= high` | +| `high is out of bounds for X` | `ValueError: high is out of bounds for int8` | + +--- + +## NumSharp Implementation Status + +### Fully Implemented (40) + +| Category | Functions | +|----------|-----------| +| Uniform | `rand`, `random`, `random_sample`, `uniform` | +| Normal | `randn`, `standard_normal`, `normal`, `lognormal` | +| Integer | `randint` | +| Sequence | `choice`, `permutation`, `shuffle` | +| Discrete | `bernoulli`*, `binomial`, `geometric`, `hypergeometric`, `logseries`, `negative_binomial`, `poisson`, `zipf` | +| Continuous | `beta`, `chisquare`, `exponential`, `f`, `gamma`, `gumbel`, `laplace`, `logistic`, `noncentral_chisquare`, `noncentral_f`, `pareto`, `power`, `rayleigh`, `standard_cauchy`, `standard_exponential`, `standard_gamma`, `standard_t`, `triangular`, `vonmises`, `wald`, `weibull` | +| Multivariate | `dirichlet`, `multinomial`, `multivariate_normal` | +| State | `seed`, `get_state`, `set_state` | + +\* `bernoulli` is NumSharp extra, not in NumPy + +### Missing - Legacy API (4) + +| Function | Priority | Notes | +|----------|----------|-------| +| `bytes(length)` | Low | Generate random bytes | +| `ranf(size)` | Low | Alias for `random_sample` | +| `sample(size)` | Low | Alias for `random_sample` | +| `random_integers` | Skip | Deprecated in NumPy | + +### Missing - Generator API (7) + +| Function | Priority | Notes | +|----------|----------|-------| +| `Generator` class | High | Modern RNG container | +| `default_rng(seed)` | High | Factory for Generator | +| `integers(low, high, endpoint)` | High | Modern randint replacement | +| `permuted(x, axis)` | High | Independent axis shuffle | +| `shuffle(x, axis)` | Medium | Axis-aware in-place shuffle | +| `multivariate_hypergeometric` | Medium | Multivariate hypergeometric | +| `spawn(n)` | High | Create child generators | + +### Missing - BitGenerators (5) + +| Class | Priority | Notes | +|-------|----------|-------| +| `PCG64` | High | NumPy's new default | +| `PCG64DXSM` | Medium | PCG variant | +| `Philox` | Medium | Counter-based, parallelizable | +| `SFC64` | Low | Fastest option | +| `SeedSequence` | High | Proper parallel seeding | + +### Implementation Roadmap + +#### Phase 1: Complete Legacy API (Low effort) +- Add `ranf()` and `sample()` aliases +- Add `bytes()` function + +#### Phase 2: Generator Infrastructure (High effort) +- Implement `Generator` class +- Implement `default_rng()` factory +- Port all distribution methods with `out` parameter support + +#### Phase 3: BitGenerators (Medium effort) +- Implement `PCG64` (highest priority) +- Implement `SeedSequence` +- Add `Philox`, `SFC64`, `PCG64DXSM` + +#### Phase 4: Generator-Only Features (Medium effort) +- Add `integers()` with endpoint +- Add `permuted()` with axis +- Add `shuffle()` / `permutation()` axis support +- Add `multivariate_hypergeometric()` +- Add `spawn()` for parallel streams + +--- + +## MT19937 Implementation Details + +This section provides the exact algorithm details needed to implement NumPy-compatible MT19937. + +### Constants + +```c +#define RK_STATE_LEN 624 // State array length (N) +#define _MT19937_N 624 // Period parameter N +#define _MT19937_M 397 // Period parameter M +#define MATRIX_A 0x9908b0dfUL // Constant vector A +#define UPPER_MASK 0x80000000UL // Most significant w-r bits +#define LOWER_MASK 0x7fffffffUL // Least significant r bits +``` + +### State Structure + +```c +typedef struct { + uint32_t key[624]; // State array + int pos; // Current position in state array +} mt19937_state; +``` + +### Seeding (Single Integer) + +NumPy uses Knuth's PRNG for seeding (different from the generator itself): + +```c +void mt19937_seed(mt19937_state *state, uint32_t seed) { + seed &= 0xffffffffUL; + for (int pos = 0; pos < 624; pos++) { + state->key[pos] = seed; + seed = (1812433253UL * (seed ^ (seed >> 30)) + pos + 1) & 0xffffffffUL; + } + state->pos = 624; // Force regeneration on first use +} +``` + +**Key constant:** `1812433253` (Knuth's multiplier) + +### Array Seeding + +For seeding with an array of integers: + +```c +void mt19937_init_by_array(mt19937_state *state, uint32_t *init_key, int key_length) { + // First, initialize with fixed seed + init_genrand(state, 19650218UL); + + // Then mix in the key array + int i = 1, j = 0; + int k = (624 > key_length) ? 624 : key_length; + + for (; k; k--) { + state->key[i] = (state->key[i] ^ + ((state->key[i-1] ^ (state->key[i-1] >> 30)) * 1664525UL)) + + init_key[j] + j; + state->key[i] &= 0xffffffffUL; + i++; j++; + if (i >= 624) { state->key[0] = state->key[623]; i = 1; } + if (j >= key_length) { j = 0; } + } + + for (k = 623; k; k--) { + state->key[i] = (state->key[i] ^ + ((state->key[i-1] ^ (state->key[i-1] >> 30)) * 1566083941UL)) - i; + state->key[i] &= 0xffffffffUL; + i++; + if (i >= 624) { state->key[0] = state->key[623]; i = 1; } + } + + state->key[0] = 0x80000000UL; // MSB=1 ensures non-zero initial state +} +``` + +**Key constants:** +- `19650218` - Initial seed for array seeding +- `1664525` - First mixing multiplier +- `1566083941` - Second mixing multiplier + +### State Generation (Twist) + +When all 624 values have been used, generate 624 new ones: + +```c +void mt19937_gen(mt19937_state *state) { + uint32_t y; + + // First 227 values (N - M = 624 - 397 = 227) + for (int i = 0; i < 227; i++) { + y = (state->key[i] & UPPER_MASK) | (state->key[i+1] & LOWER_MASK); + state->key[i] = state->key[i + 397] ^ (y >> 1) ^ (-(y & 1) & MATRIX_A); + } + + // Next 396 values (up to N - 1) + for (int i = 227; i < 623; i++) { + y = (state->key[i] & UPPER_MASK) | (state->key[i+1] & LOWER_MASK); + state->key[i] = state->key[i - 227] ^ (y >> 1) ^ (-(y & 1) & MATRIX_A); + } + + // Last value wraps around + y = (state->key[623] & UPPER_MASK) | (state->key[0] & LOWER_MASK); + state->key[623] = state->key[396] ^ (y >> 1) ^ (-(y & 1) & MATRIX_A); + + state->pos = 0; +} +``` + +### Extracting Random Values + +Raw 32-bit integer with tempering: + +```c +uint32_t mt19937_next(mt19937_state *state) { + if (state->pos == 624) { + mt19937_gen(state); // Generate new batch + } + + uint32_t y = state->key[state->pos++]; + + // Tempering transformation + y ^= (y >> 11); + y ^= (y << 7) & 0x9d2c5680UL; + y ^= (y << 15) & 0xefc60000UL; + y ^= (y >> 18); + + return y; +} +``` + +**Tempering constants:** +- `0x9d2c5680` - Tempering mask B +- `0xefc60000` - Tempering mask C + +### Converting to Double [0, 1) + +NumPy uses a 53-bit precision method: + +```c +double mt19937_next_double(mt19937_state *state) { + // Use 27 bits from one call, 26 bits from another + int32_t a = mt19937_next(state) >> 5; // 27 bits + int32_t b = mt19937_next(state) >> 6; // 26 bits + + // Combine for 53-bit mantissa (IEEE 754 double precision) + return (a * 67108864.0 + b) / 9007199254740992.0; +} +``` + +**Key values:** +- `67108864 = 2^26` (shift factor for combining) +- `9007199254740992 = 2^53` (normalization factor) + +### Gaussian Caching + +The legacy `RandomState` caches one Gaussian value for Box-Muller: + +```c +typedef struct { + int has_gauss; // 0 or 1 + double gauss; // Cached value +} augmented_state; +``` + +This means `get_state()` / `set_state()` must save/restore this cached value for reproducibility. + +### C# Implementation Template + +```csharp +public sealed class MT19937 +{ + private const int N = 624; + private const int M = 397; + private const uint MATRIX_A = 0x9908b0dfU; + private const uint UPPER_MASK = 0x80000000U; + private const uint LOWER_MASK = 0x7fffffffU; + + private uint[] key = new uint[N]; + private int pos; + + public void Seed(uint seed) + { + seed &= 0xffffffffU; + for (int i = 0; i < N; i++) + { + key[i] = seed; + seed = (1812433253U * (seed ^ (seed >> 30)) + (uint)(i + 1)) & 0xffffffffU; + } + pos = N; + } + + private void Generate() + { + uint y; + for (int i = 0; i < N - M; i++) + { + y = (key[i] & UPPER_MASK) | (key[i + 1] & LOWER_MASK); + key[i] = key[i + M] ^ (y >> 1) ^ ((y & 1) == 0 ? 0 : MATRIX_A); + } + for (int i = N - M; i < N - 1; i++) + { + y = (key[i] & UPPER_MASK) | (key[i + 1] & LOWER_MASK); + key[i] = key[i + (M - N)] ^ (y >> 1) ^ ((y & 1) == 0 ? 0 : MATRIX_A); + } + y = (key[N - 1] & UPPER_MASK) | (key[0] & LOWER_MASK); + key[N - 1] = key[M - 1] ^ (y >> 1) ^ ((y & 1) == 0 ? 0 : MATRIX_A); + + pos = 0; + } + + public uint NextUInt32() + { + if (pos == N) Generate(); + uint y = key[pos++]; + + y ^= (y >> 11); + y ^= (y << 7) & 0x9d2c5680U; + y ^= (y << 15) & 0xefc60000U; + y ^= (y >> 18); + + return y; + } + + public double NextDouble() + { + int a = (int)(NextUInt32() >> 5); // 27 bits + int b = (int)(NextUInt32() >> 6); // 26 bits + return (a * 67108864.0 + b) / 9007199254740992.0; + } +} +``` + +--- + +## Related Documentation + +- [NumPy Random Sampling](https://numpy.org/doc/stable/reference/random/index.html) +- [SPEC 7: Seeding Pseudo-Random Number Generation](https://scientific-python.org/specs/spec-0007/) +- [NEP 19: Random Number Generator Policy](https://numpy.org/neps/nep-0019-rng-policy.html) +- [Mersenne Twister Home Page](http://www.math.sci.hiroshima-u.ac.jp/m-mat/MT/emt.html) +- [MT19937 Paper](http://www.math.sci.hiroshima-u.ac.jp/m-mat/MT/ARTICLES/mt.pdf) +- NumPy Source: `numpy/random/src/mt19937/mt19937.c` +- NumPy Source: `numpy/random/_mt19937.pyx` +- NumPy Source: `numpy/random/mtrand.pyx` +- NumSharp Issue #559: [SPEC7] Seeding Pseudo-Random Number Generation +- NumSharp Issue #553: [NEP01 NEP19] File Format and RNG Interoperability diff --git a/docs/numpy/NUMPY_STRING_TYPES.md b/docs/numpy/NUMPY_STRING_TYPES.md new file mode 100644 index 000000000..ec72c9176 --- /dev/null +++ b/docs/numpy/NUMPY_STRING_TYPES.md @@ -0,0 +1,1958 @@ +# NumPy String Types - Complete Reference + +> **Source**: NumPy v2.4.2 (`src/numpy/`) +> **Purpose**: Reference for implementing string support in NumSharp + +--- + +## Table of Contents + +1. [Overview: Three String Representations](#overview-three-string-representations) +2. [Fixed-Width Byte Strings (bytes_ / 'S')](#1-fixed-width-byte-strings-bytes_--s) +3. [Fixed-Width Unicode Strings (str_ / 'U')](#2-fixed-width-unicode-strings-str_--u) +4. [Variable-Length Strings (StringDType / 'T')](#3-variable-length-strings-stringdtype--t---numpy-20) +5. [Deprecated char Type ('c')](#4-deprecated-char-type-c) +6. [Object dtype with Strings](#5-object-dtype-with-strings) +7. [Type Codes and Constants](#6-type-codes-and-constants) +8. [Memory Layout Details](#7-memory-layout-details) +9. [String Operations API](#8-string-operations-api) +10. [Splitting and Joining (Object Array Results)](#9-splitting-and-joining-object-array-results) +11. [Type Conversion and Casting](#10-type-conversion-and-casting) +12. [Structured Arrays with String Fields](#11-structured-arrays-with-string-fields) +13. [File I/O with Strings](#12-file-io-with-strings) +14. [Sorting and Searching](#13-sorting-and-searching) +15. [Boolean Conversion and Truthiness](#14-boolean-conversion-and-truthiness) +16. [chararray Legacy Class](#15-chararray-legacy-class) +17. [Implementation Internals](#16-implementation-internals) +18. [Edge Cases and Behavior](#17-edge-cases-and-behavior) +19. [Best Practices](#18-best-practices) + +--- + +## Overview: Three String Representations + +NumPy provides **three distinct string types** with fundamentally different memory layouts and use cases: + +| Type | DType Code | Type Char | C Enum | Description | +|------|------------|-----------|--------|-------------| +| **bytes_** | `NPY_STRING` | `'S'` | 18 | Fixed-width byte strings (ASCII/binary) | +| **str_** | `NPY_UNICODE` | `'U'` | 19 | Fixed-width Unicode strings (UTF-32/UCS-4) | +| **StringDType** | `NPY_VSTRING` | `'T'` | 2056 | Variable-length UTF-8 strings (NumPy 2.0+) | + +### Quick Comparison + +| Feature | bytes_ ('S') | str_ ('U') | StringDType ('T') | +|---------|-------------|------------|-------------------| +| **Storage per char** | 1 byte | 4 bytes | 1-4 bytes (UTF-8) | +| **Width** | Fixed | Fixed | Variable | +| **Unicode support** | No (ASCII/binary) | Full (UTF-32) | Full (UTF-8) | +| **NA/missing support** | No | No | Yes | +| **Memory efficiency** | Best for ASCII | Worst | Best overall | +| **Min element size** | 1 byte | 4 bytes | 16 bytes (header) | +| **NumPy version** | All | All | 2.0+ | +| **Recommended for** | Binary data, ASCII | Fixed-width Unicode | General text | + +--- + +## 1. Fixed-Width Byte Strings (`bytes_` / `'S'`) + +### Overview + +The `bytes_` dtype stores fixed-width sequences of bytes. Each element occupies exactly `itemsize` bytes, regardless of actual content length. Shorter strings are null-padded. + +### Memory Layout + +``` +Structure: [byte0][byte1][byte2]...[byteN-1] + |<-------- itemsize bytes ------->| + +Example: dtype='S5' holding "abc" +Memory: [0x61][0x62][0x63][0x00][0x00] + 'a' 'b' 'c' null null + |<------ 5 bytes total ------>| +``` + +### Dtype Specification + +```python +# All equivalent ways to specify bytes dtype +np.dtype('S') # Zero-length bytes (itemsize=0) +np.dtype('S5') # 5-byte fixed string +np.dtype('S10') # 10-byte fixed string +np.dtype('|S10') # Explicit byte order (| = not-applicable for bytes) +np.dtype(np.bytes_) # Using scalar type +np.dtype((np.bytes_, 5)) # Tuple form with size + +# Byte order markers (all equivalent for bytes, no byte swapping needed) +np.dtype('|S5') # Native/not-applicable +np.dtype('=S5') # Native +np.dtype('S5') # Big-endian (same as native for single bytes) +``` + +### Creating Arrays + +```python +# From Python bytes +arr = np.array([b'hello', b'world'], dtype='S') +# dtype='|S5' (auto-sized to longest) + +# From Python strings (encoded as ASCII) +arr = np.array(['hello', 'world'], dtype='S') +# dtype='|S5' + +# Fixed size (truncates if too long) +arr = np.array([b'hello', b'world'], dtype='S3') +# array([b'hel', b'wor'], dtype='|S3') + +# Explicit size +arr = np.array([b'hi'], dtype='S10') +# array([b'hi'], dtype='|S10') # Null-padded to 10 bytes +``` + +### Key Properties + +```python +arr = np.array([b'hello'], dtype='S10') + +arr.dtype # dtype('|S10') +arr.dtype.char # 'S' +arr.dtype.kind # 'S' +arr.dtype.type # +arr.dtype.itemsize # 10 (bytes per element) +arr.dtype.name # 'bytes80' (bits = itemsize * 8) +arr.dtype.str # '|S10' + +# Scalar access +arr[0] # np.bytes_(b'hello') +type(arr[0]) # +bytes(arr[0]) # b'hello' (Python bytes, null-stripped) +``` + +### Characteristics + +- **Encoding**: None assumed - raw bytes. Content interpreted as ASCII when displayed. +- **Character range**: 0x00-0xFF (full byte range) +- **Safe content**: ASCII (0x00-0x7F) for text; any bytes for binary data +- **Null handling**: Stored but may be stripped on scalar access +- **Itemsize**: Exactly equals byte count per element +- **Use cases**: Binary data, ASCII text, fixed-record file formats, C struct compatibility + +### Limitations + +```python +# Cannot store non-ASCII Unicode directly +arr = np.array(['hello'], dtype='S') # Works (ASCII) +arr = np.array(['caf\xe9'], dtype='S') # Works (Latin-1 byte) + +# But emoji/CJK require explicit encoding +text = 'hello \U0001F60A' # Contains emoji +encoded = text.encode('utf-8') # b'hello \xf0\x9f\x98\x8a' +arr = np.array([encoded], dtype='S') # Store as raw bytes +``` + +--- + +## 2. Fixed-Width Unicode Strings (`str_` / `'U'`) + +### Overview + +The `str_` dtype stores fixed-width Unicode strings using **UTF-32/UCS-4 encoding**. Each character occupies exactly 4 bytes (one `npy_ucs4` code point), providing O(1) character access but with significant memory overhead. + +### Memory Layout + +``` +Structure: [codepoint0][codepoint1][codepoint2]...[codepointN-1] + |<------------- itemsize bytes (N * 4) ------------>| + +Each codepoint: 4 bytes (32-bit unsigned integer) + +Example: dtype='| + +Note: Emoji U+1F60A stored as 0x0001F60A in 4 bytes +``` + +### Dtype Specification + +```python +# All ways to specify unicode dtype +np.dtype('U') # Zero-length unicode (itemsize=0) +np.dtype('U5') # 5 characters = 20 bytes +np.dtype('U10') # 10 characters = 40 bytes +np.dtype('U5') # Big-endian +np.dtype('=U5') # Native byte order +np.dtype(np.str_) # Using scalar type +np.dtype((np.str_, 5)) # Tuple form with character count + +# Platform-dependent native order +import sys +if sys.byteorder == 'little': + np.dtype('U5').str # 'U5' +``` + +### Creating Arrays + +```python +# From Python strings +arr = np.array(['hello', 'world'], dtype='U') +# dtype=' +arr.dtype.itemsize # 40 (bytes = chars * 4) +arr.dtype.name # 'str320' (bits = itemsize * 8) +arr.dtype.str # 'U10' + +# Character count (not byte count!) +num_chars = arr.dtype.itemsize // 4 # 10 + +# Scalar access +arr[0] # np.str_('hello \U0001F60A') +type(arr[0]) # +str(arr[0]) # 'hello \U0001F60A' (Python str) +``` + +### The `npy_ucs4` Type + +Internally, each character is stored as `npy_ucs4`: + +```c +// From npy_common.h - platform-dependent definition +typedef unsigned int npy_ucs4; // Most common (32-bit int) +typedef unsigned long npy_ucs4; // Some platforms +typedef unsigned short npy_ucs4; // Rare (16-bit) + +// Valid range: 0x00000000 to 0x0010FFFF (Unicode code points) +``` + +### Byte Order + +Unlike bytes, Unicode strings have meaningful byte order: + +```python +# Little-endian: 'A' (U+0041) stored as 41 00 00 00 +# Big-endian: 'A' (U+0041) stored as 00 00 00 41 + +arr_le = np.array(['A'], dtype='') # Returns view with swapped interpretation +``` + +### Characteristics + +- **Encoding**: UTF-32/UCS-4 (fixed 4 bytes per code point) +- **Character range**: U+0000 to U+10FFFF (full Unicode) +- **Itemsize**: 4 * character_count +- **Memory**: 4x overhead for ASCII content +- **Access**: O(1) character indexing (unlike UTF-8) +- **Use cases**: Fixed-width text fields, guaranteed character alignment + +### Helper Functions + +```python +def get_num_chars(arr): + """Get number of characters per element in string array.""" + if issubclass(arr.dtype.type, np.str_): + return arr.dtype.itemsize // 4 # Unicode: 4 bytes/char + return arr.dtype.itemsize # Bytes: 1 byte/char + +def unicode_itemsize(num_chars): + """Calculate itemsize for given character count.""" + return num_chars * 4 +``` + +--- + +## 3. Variable-Length Strings (`StringDType` / `'T'`) - NumPy 2.0+ + +### Overview + +`StringDType` is NumPy 2.0's modern string type featuring: +- **Variable-length storage** (no fixed itemsize) +- **UTF-8 encoding** (memory-efficient for ASCII) +- **NA/missing data support** (configurable sentinel) +- **Arena allocation** with small-string optimization + +### Dtype Specification + +```python +from numpy.dtypes import StringDType + +# Basic creation +np.dtype('T') # Default StringDType +np.dtypes.StringDType() # Constructor form + +# With NA support +np.dtypes.StringDType(na_object=None) # None as NA +np.dtypes.StringDType(na_object=np.nan) # NaN as NA +np.dtypes.StringDType(na_object=pd.NA) # pandas NA + +# Coercion control +np.dtypes.StringDType(coerce=True) # Convert non-strings (default) +np.dtypes.StringDType(coerce=False) # Reject non-strings + +# Combined +np.dtypes.StringDType(na_object=np.nan, coerce=False) +``` + +### Creating Arrays + +```python +# Basic creation +arr = np.array(['hello', 'world'], dtype='T') +arr = np.array(['hello', 'world'], dtype=StringDType()) + +# With NA values +dt = StringDType(na_object=np.nan) +arr = np.array(['hello', np.nan, 'world'], dtype=dt) +arr[1] is np.nan # True + +# From other types (with coerce=True) +arr = np.array([1, 2, 3], dtype=StringDType()) # ['1', '2', '3'] +arr = np.array([b'hello'], dtype=StringDType()) # ['hello'] + +# Without coercion (strict) +dt = StringDType(coerce=False) +np.array([1, 2], dtype=dt) # Raises ValueError +``` + +### Key Properties + +```python +arr = np.array(['hello'], dtype='T') + +arr.dtype # StringDType() +arr.dtype.char # 'T' +arr.dtype.kind # 'T' +arr.dtype.itemsize # 16 (header size, not string length!) +arr.dtype.name # 'StringDType128' +arr.dtype.str # '|T16' + +# NA-related properties +dt = StringDType(na_object=np.nan) +dt.na_object # nan +dt.coerce # True +hasattr(dt, 'na_object') # True (False if no NA configured) +``` + +### Memory Layout (Internal) + +The StringDType uses a sophisticated packed structure: + +```c +// Per-element: 16 bytes on 64-bit, 8 bytes on 32-bit +union _npy_static_string_u { + // For long strings (>15 bytes on 64-bit) + struct _npy_static_vstring_t { + size_t offset; // Arena offset or heap pointer + size_t size_and_flags; // Size + flag byte in MSB + } vstring; + + // For short strings (<=15 bytes on 64-bit) - Small String Optimization + struct _short_string_buffer { + char buf[15]; // Inline string data (7 on 32-bit) + unsigned char size_and_flags; // Size in low 4 bits + } direct_buffer; +}; +``` + +### Storage Modes + +| Mode | Condition | Storage Location | Description | +|------|-----------|------------------|-------------| +| **Short String** | <= 15 bytes (64-bit) | Inline | Data stored directly in array buffer | +| **Short String** | <= 7 bytes (32-bit) | Inline | Data stored directly in array buffer | +| **Medium Arena** | <= 255 bytes, initial | Arena buffer | Contiguous allocation, 1-byte size | +| **Long Arena** | > 255 bytes, initial | Arena buffer | Contiguous allocation, size_t size | +| **Heap** | Mutation exceeds arena | malloc | Independent allocation | + +### Flag Bits + +```c +#define NPY_STRING_MISSING 0x80 // 1000 0000 - Null/NA value +#define NPY_STRING_INITIALIZED 0x40 // 0100 0000 - Element has been set +#define NPY_STRING_OUTSIDE_ARENA 0x20 // 0010 0000 - Heap-allocated +#define NPY_STRING_LONG 0x10 // 0001 0000 - Arena string >255 bytes + +#define NPY_SHORT_STRING_MAX_SIZE (sizeof(npy_static_string) - 1) // 15 or 7 +#define NPY_MEDIUM_STRING_MAX_SIZE 0xFF // 255 +#define NPY_MAX_STRING_SIZE ((1 << 8*(sizeof(size_t)-1)) - 1) // Very large +``` + +### Arena Allocator + +The arena is a contiguous buffer that grows as needed: + +```c +struct npy_string_arena { + size_t cursor; // Current write position + size_t size; // Total buffer size + char *buffer; // The buffer itself +}; + +struct npy_string_allocator { + npy_string_malloc_func malloc; + npy_string_free_func free; + npy_string_realloc_func realloc; + npy_string_arena arena; + PyMutex allocator_lock; // Thread safety +}; +``` + +### NA/Missing Data Handling + +```python +# Different NA sentinels +dt_none = StringDType(na_object=None) +dt_nan = StringDType(na_object=np.nan) +dt_custom = StringDType(na_object="__NA__") + +# Creating with NA +arr = np.array(['hello', np.nan, 'world'], dtype=dt_nan) + +# Checking for NA +np.isnan(arr) # [False, True, False] (only for NaN-like NA) +arr[1] is np.nan # True (identity check) + +# NA in operations +# Sorting: NA values sorted to end +# Comparisons: May raise for non-NaN NA (e.g., None) +``` + +### Null Byte Handling + +Unlike legacy strings, StringDType preserves embedded nulls: + +```python +arr = np.array(["hello\x00world"], dtype='T') +arr[0] # 'hello\x00world' (preserved) +len(arr[0]) # 11 + +# Legacy types strip at first null on access +arr_u = np.array(["hello\x00world"], dtype='U') +# Stored fully, but may behave differently in operations +``` + +### Thread Safety + +StringDType uses mutex locks for thread-safe allocator access: + +```c +// Acquiring allocator (locks mutex) +npy_string_allocator *alloc = NpyString_acquire_allocator(descr); + +// ... use allocator ... + +// Releasing (unlocks mutex) +NpyString_release_allocator(alloc); +``` + +--- + +## 4. Deprecated char Type (`'c'`) + +### Overview + +The `'c'` (NPY_CHAR) type is **deprecated** and will raise an error if used. It was historically used for single-character access but is no longer supported. + +```python +# This will raise an error +np.dtype('c') # DeprecationWarning or error + +# NPY_CHAR = 24 in the enum, but deprecated +``` + +### Historical Usage + +```python +# Legacy code that no longer works: +# arr = np.array('abcd', dtype='c') # Would create array of 4 chars + +# Modern equivalent using bytes_: +arr = np.array(list(b'abcd'), dtype='S1') # Array of 4 single-byte strings + +# Or view bytes as individual characters: +arr = np.frombuffer(b'abcd', dtype='S1') +``` + +### In chararray (Legacy) + +```python +# The 'c' dtype can still appear when viewing bytes: +A = np.array('abc1', dtype='c').view(np.char.chararray) +A.shape # (4,) - one element per character +A.dtype # dtype('S1') +``` + +--- + +## 5. Object dtype with Strings + +### Overview + +The `object` dtype (`'O'`) stores Python object references, including strings. This provides unlimited flexibility but loses NumPy's memory efficiency and vectorized operations. + +### When to Use + +| Scenario | Use Object dtype? | +|----------|-------------------| +| Variable-length strings (pre-NumPy 2.0) | Yes | +| Mixed types in array | Yes | +| Need Python string methods directly | Yes | +| Performance-critical operations | No (use 'U' or 'T') | +| Large arrays | No (memory overhead) | + +### Creating Object Arrays with Strings + +```python +# Automatic object dtype for mixed content +arr = np.array(['hello', 123, None]) +arr.dtype # dtype('O') + +# Explicit object dtype +arr = np.array(['hello', 'world'], dtype=object) +arr.dtype # dtype('O') + +# Each element is a Python str object +type(arr[0]) # +``` + +### Memory Layout + +```python +# Object arrays store pointers, not string data +arr = np.array(['hello', 'world'], dtype=object) + +# Each element is 8 bytes (pointer on 64-bit) +# Actual string data is in Python heap +arr.itemsize # 8 (pointer size) + +# Compare to fixed-width: +arr_u = np.array(['hello', 'world'], dtype='U') +arr_u.itemsize # 20 (5 chars * 4 bytes) +``` + +### String Operations on Object Arrays + +```python +# numpy.strings functions work with object arrays +arr = np.array(['hello', 'world'], dtype=object) + +np.strings.upper(arr) # array(['HELLO', 'WORLD'], dtype=object) +np.strings.str_len(arr) # array([5, 5]) +np.strings.find(arr, 'o') # array([4, 1]) + +# But some return object arrays for split operations +np.char.split(arr, 'l') # Returns object array of lists +``` + +### Interoperability + +```python +# Object dtype works in type promotion with StringDType +arr_obj = np.array(['hello'], dtype=object) +arr_t = np.array(['world'], dtype='T') + +# Comparison works (promotes to common type) +arr_obj == arr_t # Works + +# Concatenation requires explicit conversion +np.concatenate([arr_obj.astype('T'), arr_t]) +``` + +--- + +## 6. Type Codes and Constants + +### NPY_TYPES Enum + +```c +enum NPY_TYPES { + NPY_BOOL = 0, + NPY_BYTE, NPY_UBYTE, // 1, 2 + NPY_SHORT, NPY_USHORT, // 3, 4 + NPY_INT, NPY_UINT, // 5, 6 + NPY_LONG, NPY_ULONG, // 7, 8 + NPY_LONGLONG, NPY_ULONGLONG, // 9, 10 + NPY_FLOAT, NPY_DOUBLE, NPY_LONGDOUBLE, // 11, 12, 13 + NPY_CFLOAT, NPY_CDOUBLE, NPY_CLONGDOUBLE, // 14, 15, 16 + NPY_OBJECT = 17, + NPY_STRING, // 18 - bytes_ + NPY_UNICODE, // 19 - str_ + NPY_VOID, // 20 + NPY_DATETIME, NPY_TIMEDELTA, NPY_HALF, // 21, 22, 23 + NPY_CHAR, // 24 - Deprecated + NPY_NTYPES_LEGACY = 24, + NPY_NOTYPE = 25, + NPY_USERDEF = 256, + NPY_VSTRING = 2056, // StringDType (NumPy 2.0+) +}; +``` + +### NPY_TYPECHAR Enum + +```c +enum NPY_TYPECHAR { + // Numeric types... + NPY_STRINGLTR = 'S', // bytes_ + NPY_DEPRECATED_STRINGLTR2 = 'a', // Legacy alias for 'S' + NPY_UNICODELTR = 'U', // str_ + NPY_VSTRINGLTR = 'T', // StringDType + NPY_CHARLTR = 'c', // Deprecated + // ... +}; +``` + +### Type Check Macros + +```c +// Check if type is string-like +#define PyTypeNum_ISSTRING(type) \ + (((type) == NPY_STRING) || ((type) == NPY_UNICODE)) + +// Check if type is flexible (string, unicode, or void) +#define PyTypeNum_ISFLEXIBLE(type) \ + (((type) >= NPY_STRING) && ((type) <= NPY_VOID)) + +// Python checks +np.issubdtype(arr.dtype, np.bytes_) # True for 'S' +np.issubdtype(arr.dtype, np.str_) # True for 'U' +np.issubdtype(arr.dtype, np.character) # True for 'S' or 'U' +np.issubdtype(arr.dtype, np.flexible) # True for 'S', 'U', 'V' +``` + +### Type Hierarchy + +``` +numpy.generic + numpy.flexible + numpy.character + numpy.bytes_ (S) + numpy.str_ (U) + numpy.void (V) + numpy.number + ... +``` + +--- + +## 7. Memory Layout Details + +### Itemsize Calculation + +```python +# bytes_ (S): itemsize = byte count +np.dtype('S10').itemsize # 10 + +# str_ (U): itemsize = character count * 4 +np.dtype('U10').itemsize # 40 + +# StringDType (T): itemsize = header size (fixed) +np.dtype('T').itemsize # 16 (64-bit) or 8 (32-bit) +``` + +### Array Memory Layout + +```python +# Contiguous bytes array +arr = np.array([b'abc', b'de', b'fghi'], dtype='S4') +# Memory: [a][b][c][0] [d][e][0][0] [f][g][h][i] +# |-- 4 -----| |-- 4 ----| |-- 4 ---| +# Total: 12 bytes, strides=(4,) + +# Contiguous unicode array +arr = np.array(['ab', 'cd'], dtype='U2') +# Memory: [a...][b...] [c...][d...] (each [...] = 4 bytes) +# |--- 8 ----| |--- 8 ---| +# Total: 16 bytes, strides=(8,) + +# StringDType array +arr = np.array(['hello', 'world'], dtype='T') +# Array buffer: [header1][header2] (each header = 16 bytes) +# Arena buffer: [h][e][l][l][o][w][o][r][l][d] (separate allocation) +``` + +### Stride Considerations + +```python +# All string types support standard striding +arr = np.array([['a', 'b'], ['c', 'd']], dtype='U1') +arr.strides # (8, 4) - row stride, column stride in bytes + +# Slicing creates views (shared memory) +view = arr[::2, :] +view.strides # (16, 4) - doubled row stride + +# StringDType slicing +arr_t = np.array(['hello', 'world', 'test'], dtype='T') +view = arr_t[::2] # ['hello', 'test'] +# Headers are views, but string data is shared via arena +``` + +--- + +## 8. String Operations API + +### Module Organization + +```python +numpy.strings # Modern API (NumPy 2.0+, preferred) +numpy.char # Legacy API (backwards compatibility, wraps numpy.strings) +``` + +### Comparison Operations + +All comparisons work with `S`, `U`, and `T` dtypes: + +```python +# Element-wise comparison (return bool array) +np.equal(arr1, arr2) # arr1 == arr2 +np.not_equal(arr1, arr2) # arr1 != arr2 +np.less(arr1, arr2) # arr1 < arr2 (lexicographic) +np.less_equal(arr1, arr2) # arr1 <= arr2 +np.greater(arr1, arr2) # arr1 > arr2 +np.greater_equal(arr1, arr2) # arr1 >= arr2 + +# Direct operators also work +arr1 == arr2 +arr1 < arr2 + +# compare_chararrays (low-level) +np.char.compare_chararrays(arr1, arr2, '==', rstrip=True) +# rstrip=True strips trailing whitespace before comparing +``` + +### Concatenation and Repetition + +```python +# String concatenation +np.strings.add(a, b) +# 'hello' + 'world' = 'helloworld' +# Broadcasts: ['a', 'b'] + 'x' = ['ax', 'bx'] + +# String repetition +np.strings.multiply(a, n) +# 'ab' * 3 = 'ababab' +# ['a', 'b'] * [2, 3] = ['aa', 'bbb'] + +# Negative/zero repeat = empty string +np.strings.multiply('abc', 0) # '' +np.strings.multiply('abc', -1) # '' + +# Overflow protection +np.strings.multiply('abc', sys.maxsize) # Raises OverflowError +``` + +### Length + +```python +np.strings.str_len(arr) +# Returns array of int64 with string lengths + +np.strings.str_len(['hello', '', 'ab']) # [5, 0, 2] +np.strings.str_len(['caf\xe9']) # [4] (4 chars, not bytes) +np.strings.str_len(['\U0001F60A']) # [1] (1 emoji = 1 char) +``` + +### Searching + +```python +# Find first occurrence (returns -1 if not found) +np.strings.find(a, sub, start=0, end=None) +np.strings.find('hello world', 'o') # 4 +np.strings.find('hello world', 'o', 5) # 7 +np.strings.find('hello world', 'x') # -1 + +# Find last occurrence +np.strings.rfind(a, sub, start=0, end=None) +np.strings.rfind('hello world', 'o') # 7 + +# Like find but raises ValueError if not found +np.strings.index(a, sub, start=0, end=None) +np.strings.rindex(a, sub, start=0, end=None) + +# Count occurrences +np.strings.count(a, sub, start=0, end=None) +np.strings.count('banana', 'a') # 3 +np.strings.count('banana', 'na') # 2 + +# Prefix/suffix check +np.strings.startswith(a, prefix, start=0, end=None) +np.strings.endswith(a, suffix, start=0, end=None) +np.strings.startswith('hello', 'he') # True +np.strings.endswith('hello', 'lo') # True +``` + +### Case Operations + +```python +np.strings.upper(arr) # HELLO +np.strings.lower(arr) # hello +np.strings.capitalize(arr) # Hello (first char upper, rest lower) +np.strings.title(arr) # Hello World (each word capitalized) +np.strings.swapcase(arr) # hELLO wORLD (swap case) +``` + +### Character Classification + +```python +# All return bool arrays +np.strings.isalpha(arr) # All alphabetic? +np.strings.isdigit(arr) # All digits? +np.strings.isalnum(arr) # All alphanumeric? +np.strings.isspace(arr) # All whitespace? +np.strings.islower(arr) # All lowercase (cased chars)? +np.strings.isupper(arr) # All uppercase (cased chars)? +np.strings.istitle(arr) # Titlecase format? +np.strings.isnumeric(arr) # Numeric (Unicode-aware)? +np.strings.isdecimal(arr) # Decimal digits (Unicode-aware)? + +# Empty strings return False for all +np.strings.isalpha('') # False +np.strings.isspace('') # False +``` + +### Whitespace Operations + +```python +# Strip whitespace +np.strings.strip(arr, chars=None) # Both ends +np.strings.lstrip(arr, chars=None) # Left only +np.strings.rstrip(arr, chars=None) # Right only + +# Custom characters to strip +np.strings.strip('xxhelloxx', 'x') # 'hello' + +# Padding/alignment +np.strings.center(arr, width, fillchar=' ') +np.strings.ljust(arr, width, fillchar=' ') +np.strings.rjust(arr, width, fillchar=' ') +np.strings.zfill(arr, width) # Numeric zero-fill: '42' -> '0042' + +# Tab expansion +np.strings.expandtabs(arr, tabsize=8) +``` + +### Splitting and Partitioning + +```python +# Partition at separator (returns 3 parts) +np.strings.partition(arr, sep) +np.strings.partition('hello-world', '-') +# ('hello', '-', 'world') + +np.strings.rpartition(arr, sep) # From right +np.strings.rpartition('a-b-c', '-') +# ('a-b', '-', 'c') + +# Replacement +np.strings.replace(arr, old, new, count=-1) +np.strings.replace('hello', 'l', 'L') # 'heLLo' +np.strings.replace('hello', 'l', 'L', 1) # 'heLlo' + +# Slicing (substring extraction) +np.strings.slice(arr, start=0, stop=None, step=1) +np.strings.slice('hello', 1, 4) # 'ell' +np.strings.slice('hello', None, None, -1) # 'olleh' +``` + +### Encoding/Decoding (bytes_ only) + +```python +# Encode str -> bytes +np.strings.encode(arr, encoding='utf-8', errors='strict') + +# Decode bytes -> str +np.strings.decode(arr, encoding='utf-8', errors='strict') + +# Error handling modes: 'strict', 'ignore', 'replace', etc. +``` + +### Printf-style Formatting + +```python +np.strings.mod(format_arr, values) +# Like Python's % formatting + +np.strings.mod(['%s is %d'], [('answer', 42)]) +# ['answer is 42'] + +np.strings.mod(['Value: %05.2f'], [3.14159]) +# ['Value: 03.14'] +``` + +### Character Translation + +```python +np.strings.translate(arr, table, deletechars=None) +# Apply character mapping table + +# table: str.maketrans result or 256-char string +table = str.maketrans('abc', 'xyz') +np.strings.translate('abcdef', table) # 'xyzdef' +``` + +--- + +## 9. Splitting and Joining (Object Array Results) + +### Overview + +Split operations (`split`, `rsplit`, `splitlines`) return **object arrays** containing Python lists, not string arrays. This is because the number of splits varies per element. + +### split and rsplit + +```python +# split - split at separator, returns object array of lists +arr = np.array(['a,b,c', 'd,e'], dtype='U') +result = np.char.split(arr, ',') +# result.dtype = object +# result[0] = ['a', 'b', 'c'] +# result[1] = ['d', 'e'] + +# With maxsplit +result = np.char.split(arr, ',', maxsplit=1) +# result[0] = ['a', 'b,c'] + +# rsplit - split from right +result = np.char.rsplit(arr, ',', maxsplit=1) +# result[0] = ['a,b', 'c'] + +# Works with all string dtypes +arr_t = np.array(['a,b,c'], dtype='T') +np.char.split(arr_t, ',') # Same behavior +``` + +### splitlines + +```python +# Split on line boundaries +arr = np.array(['line1\nline2\nline3']) +result = np.char.splitlines(arr) +# result[0] = ['line1', 'line2', 'line3'] + +# Keep line endings +result = np.char.splitlines(arr, keepends=True) +# result[0] = ['line1\n', 'line2\n', 'line3'] +``` + +### join + +```python +# Join sequences with separator +sep = np.array(['-', '.']) +seq = np.array([['a', 'b', 'c'], ['x', 'y', 'z']], dtype=object) + +# Join each sequence with corresponding separator +result = np.char.join(sep, seq) # Not directly available in np.strings + +# For simple cases, use Python: +arr = np.array(['abc', 'def']) +joined = np.char.join(',', arr) # 'a,b,c' and 'd,e,f' +``` + +### partition and rpartition + +Unlike split, `partition` returns **fixed-size tuple arrays**: + +```python +# partition returns 3 parts: (before, sep, after) +arr = np.array(['hello-world', 'foo-bar-baz']) +result = np.strings.partition(arr, '-') +# Returns tuple of 3 arrays: +# (['hello', 'foo'], ['-', '-'], ['world', 'bar-baz']) + +# rpartition splits at last occurrence +result = np.strings.rpartition(arr, '-') +# (['hello', 'foo-bar'], ['-', '-'], ['world', 'baz']) +``` + +### Internal _vec_string Function + +Many operations use the internal `_vec_string` function: + +```python +from numpy._core.multiarray import _vec_string + +# Signature: _vec_string(arr, output_dtype, method_name, args_tuple) +# Calls Python string method element-wise + +# Example (internal use only): +_vec_string(['hello', 'world'], np.object_, 'split', (',',)) +``` + +--- + +## 10. Type Conversion and Casting + +### Between String Types + +```python +# bytes_ <-> str_ +arr_s = np.array([b'hello'], dtype='S') +arr_u = arr_s.astype('U') # Decode as ASCII + +arr_u = np.array(['hello'], dtype='U') +arr_s = arr_u.astype('S') # Encode as ASCII (fails for non-ASCII) + +# str_ <-> StringDType +arr_u = np.array(['hello'], dtype='U') +arr_t = arr_u.astype('T') # Full Unicode preserved + +arr_t = np.array(['hello'], dtype='T') +arr_u = arr_t.astype('U10') # May truncate to width + +# StringDType -> bytes_ (ASCII only) +arr_t = np.array(['hello'], dtype='T') +arr_s = arr_t.astype('S') # Works for ASCII +``` + +### Width Truncation + +```python +# Truncation when target is smaller +arr = np.array(['hello world'], dtype='U') +arr.astype('U5') # ['hello'] - truncated + +arr.astype('S3') # [b'hel'] - truncated +``` + +### Numeric Conversions + +```python +# Numbers to strings +np.array([1, 2, 3]).astype('U') # ['1', '2', '3'] +np.array([1.5, 2.5]).astype('U') # ['1.5', '2.5'] +np.array([1+2j]).astype('U') # ['(1+2j)'] + +# Special values +np.array([np.nan, np.inf, -np.inf]).astype('U') +# ['nan', 'inf', '-inf'] + +# Strings to numbers +np.array(['1.5', '2.5']).astype(float) # [1.5, 2.5] +np.array(['1', '2']).astype(int) # [1, 2] +``` + +### Void (V) Conversions + +```python +# StringDType <-> Void (raw bytes) +arr_t = np.array(['hello'], dtype='T') +arr_v = arr_t.astype('V5') # Raw UTF-8 bytes + +arr_v = np.array([b'hello'], dtype='V5') +arr_t = arr_v.astype('T') # Interpret as UTF-8 +``` + +### Casting Safety + +```python +# Safe casts (no data loss possible) +arr_s = np.array([b'hi'], dtype='S') +arr_s.astype('U', casting='safe') # OK + +# Unsafe casts (may lose data) +arr_u = np.array(['\u00e9'], dtype='U') # 'e' with acute +arr_u.astype('S', casting='safe') # Raises TypeError +arr_u.astype('S', casting='unsafe') # May corrupt + +# StringDType NA casting +dt_na = StringDType(na_object=np.nan) +dt_no_na = StringDType() +arr_na = np.array(['hi', np.nan], dtype=dt_na) +arr_na.astype(dt_no_na, casting='safe') # Raises (NA -> string unsafe) +``` + +### Datetime/Timedelta Conversions + +```python +# datetime64 -> StringDType +dt_arr = np.array(['2023-01-15T10:30:00'], dtype='datetime64[s]') +str_arr = dt_arr.astype('T') +# ['2023-01-15T10:30:00'] + +# StringDType -> datetime64 +str_arr = np.array(['2023-01-15'], dtype='T') +dt_arr = str_arr.astype('datetime64[D]') + +# NaT handling +dt = StringDType(na_object=np.nan) +arr = np.array(['2023-01-15', np.nan], dtype=dt) +dt_arr = arr.astype('datetime64[D]') +# arr[1] becomes NaT + +# 'nat', 'NAT', 'NaT', etc. all parse as NaT +arr = np.array(['NaT', 'nat', 'NAT', ''], dtype='T') +arr.astype('datetime64[s]') # All become NaT + +# timedelta64 similar behavior +td_arr = np.array([12358], dtype='timedelta64[s]') +str_arr = td_arr.astype('T') # ['12358'] (seconds as string) +``` + +--- + +## 11. Structured Arrays with String Fields + +### Creating Structured Arrays + +```python +# Structured dtype with string fields +dt = np.dtype([('name', 'U20'), ('id', 'i4'), ('code', 'S5')]) +arr = np.array([('Alice', 1, b'ABC'), ('Bob', 2, b'DEF')], dtype=dt) + +# Access fields +arr['name'] # array(['Alice', 'Bob'], dtype=' +inline npy_ucs4 getchar(const unsigned char *buf, int *bytes); + +// ASCII: 1 byte +template <> +inline npy_ucs4 getchar(const unsigned char *buf, int *bytes) { + *bytes = 1; + return (npy_ucs4) *buf; +} + +// UTF-32: 4 bytes +template <> +inline npy_ucs4 getchar(const unsigned char *buf, int *bytes) { + *bytes = 4; + return *(npy_ucs4 *)buf; +} + +// UTF-8: 1-4 bytes +template <> +inline npy_ucs4 getchar(const unsigned char *buf, int *bytes) { + Py_UCS4 codepoint; + *bytes = utf8_char_to_ucs4_code(buf, &codepoint); + return (npy_ucs4)codepoint; +} +``` + +### Character Classification (Templates) + +```cpp +// Platform-specific implementations +template +inline bool codepoint_isalpha(npy_ucs4 code); + +template<> +inline bool codepoint_isalpha(npy_ucs4 code) { + return NumPyOS_ascii_isalpha(code); // ASCII-only check +} + +template<> +inline bool codepoint_isalpha(npy_ucs4 code) { + return Py_UNICODE_ISALPHA(code); // Full Unicode via Python +} + +template<> +inline bool codepoint_isalpha(npy_ucs4 code) { + return Py_UNICODE_ISALPHA(code); // Same as UTF32 after decoding +} + +// Similar templates for: isdigit, isspace, isalnum, islower, isupper, istitle +``` + +### StringDType API Functions + +```c +// Allocator management +npy_string_allocator *NpyString_new_allocator(malloc, free, realloc); +void NpyString_free_allocator(npy_string_allocator *allocator); + +// Thread-safe allocator access +npy_string_allocator *NpyString_acquire_allocator(descr); +void NpyString_release_allocator(allocator); + +// String operations +int NpyString_pack(allocator, packed_string, buf, size); +int NpyString_load(allocator, packed_string, unpacked_string); +int NpyString_free(packed_string, allocator); + +// Queries +int NpyString_isnull(packed_string); +size_t NpyString_size(packed_string); +int NpyString_cmp(s1, s2); + +// Special values +int NpyString_pack_null(allocator, packed_string); +int NpyString_pack_empty(packed_string); +``` + +### Buffer Class (C++) + +```cpp +template +struct Buffer { + char *buf; // Start of string data + char *after; // One past end + + // Get number of codepoints (not bytes!) + size_t num_codepoints(); + + // Character-by-character operations + // (implementation varies by encoding) +}; +``` + +### UTF-8 Utilities API + +```c +// From utf8_utils.h + +// Convert UTF-8 byte sequence to code point +// Returns number of bytes consumed +size_t utf8_char_to_ucs4_code(const unsigned char *c, Py_UCS4 *code); + +// Get number of bytes for UTF-8 character from first byte +// Uses lookup table based on high bits of first byte +static inline int num_bytes_for_utf8_character(const unsigned char *c) { + static const char LENGTHS_LUT[] = { + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x00-0x7F: ASCII + 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 // continuation/multibyte + }; + return LENGTHS_LUT[c[0] >> 3]; +} + +// Find previous UTF-8 character in buffer +const unsigned char* find_previous_utf8_character(const unsigned char *c, size_t nchar); + +// How many UTF-8 bytes needed for a code point +int num_utf8_bytes_for_codepoint(uint32_t code); + +// Count codepoints in UTF-8 byte sequence +int num_codepoints_for_utf8_bytes(const unsigned char *s, size_t *num_codepoints, + size_t max_bytes); + +// Calculate UTF-8 byte length from UCS-4 codepoints +int utf8_size(const Py_UCS4 *codepoints, long max_length, + size_t *num_codepoints, size_t *utf8_bytes); + +// Convert code point to UTF-8 bytes +// Returns number of bytes written +size_t ucs4_code_to_utf8_char(Py_UCS4 code, char *c); + +// Get buffer size needed for UTF-8 string +Py_ssize_t utf8_buffer_size(const uint8_t *s, size_t max_bytes); + +// Find byte positions for character indices +void find_start_end_locs(char* buf, size_t buffer_size, + npy_int64 start_index, npy_int64 end_index, + char **start_loc, char **end_loc); + +// Get character index from byte offset +size_t utf8_character_index(const char* start_loc, size_t start_byte_offset, + size_t start_index, size_t search_byte_offset, + size_t buffer_size); +``` + +### UTF-8 Byte Length by Code Point + +| Code Point Range | UTF-8 Bytes | Example | +|------------------|-------------|---------| +| U+0000 - U+007F | 1 | ASCII 'A' | +| U+0080 - U+07FF | 2 | Latin 'e' | +| U+0800 - U+FFFF | 3 | CJK, Euro | +| U+10000 - U+10FFFF | 4 | Emoji | + +--- + +## 17. Edge Cases and Behavior + +### Empty Strings + +```python +# Empty string is valid +np.array([''], dtype='S') # dtype='|S0' or '|S1' depending on context +np.array([''], dtype='U') # dtype='U` | str_ | `>U10` | Big-endian unicode | +| `T` | StringDType | `T` | Variable-length UTF-8 | + +### Common Operations Matrix + +| Operation | Function | bytes_ | str_ | StringDType | +|-----------|----------|--------|------|-------------| +| Length | `str_len` | Y | Y | Y | +| Concat | `add` | Y | Y | Y | +| Repeat | `multiply` | Y | Y | Y | +| Find | `find/rfind` | Y | Y | Y | +| Count | `count` | Y | Y | Y | +| Upper | `upper` | Y | Y | Y | +| Lower | `lower` | Y | Y | Y | +| Strip | `strip/lstrip/rstrip` | Y | Y | Y | +| Replace | `replace` | Y | Y | Y | +| Compare | `equal/less/etc` | Y | Y | Y | +| Encode | `encode` | - | Y | Y | +| Decode | `decode` | Y | - | - | +| isalpha | `isalpha` | Y (ASCII) | Y (Unicode) | Y (Unicode) | +| isnan | `isnan` | N | N | Y (with NA) | + +### Memory Sizes + +| Content | bytes_ | str_ | StringDType | +|---------|--------|------|-------------| +| "" (empty) | 0-1 bytes | 0-4 bytes | 16 bytes | +| "hello" (5 ASCII) | 5 bytes | 20 bytes | 16 bytes (inline) | +| "hello world" (11) | 11 bytes | 44 bytes | 16 + 11 bytes | +| Single emoji | N/A | 4 bytes | 16 + 4 bytes | +| 100 ASCII chars | 100 bytes | 400 bytes | 16 + 100 bytes | + +### Array Functions with String Support + +| Function | bytes_ | str_ | StringDType | Notes | +|----------|--------|------|-------------|-------| +| `np.sort` | Y | Y | Y | Lexicographic | +| `np.argsort` | Y | Y | Y | | +| `np.argmax` | Y | Y | Y | | +| `np.argmin` | Y | Y | Y | | +| `np.searchsorted` | Y | Y | Y | | +| `np.unique` | Y | Y | Y | | +| `np.concatenate` | Y | Y | Y | | +| `np.stack/vstack/hstack` | Y | Y | Y | | +| `np.where` | Y | Y | Y | | +| `np.take` | Y | Y | Y | | +| `np.nonzero` | Y | Y | Y | Empty string = False | +| `np.any` | Y | Y | Y | Empty string = False | +| `np.all` | Y | Y | Y | Empty string = False | +| `np.copy` | Y | Y | Y | | +| `np.resize` | Y | Y | Y | | +| `np.save/load` | Y | Y | Y | .npy format | + +### Type Hierarchy + +``` +numpy.generic + numpy.number + ... (numeric types) + numpy.flexible + numpy.void (V) + numpy.character + numpy.bytes_ (S) + numpy.str_ (U) + numpy.object_ (O) + +# StringDType is a new-style dtype, not in scalar hierarchy +numpy.dtypes.StringDType (T) +``` + +### String UFuncs + +| UFunc | Signature | Notes | +|-------|-----------|-------| +| `np.add` | `(T,T)->T` | String concatenation | +| `np.multiply` | `(T,i)->T` | String repetition | +| `np.equal` | `(T,T)->?` | Element-wise == | +| `np.not_equal` | `(T,T)->?` | Element-wise != | +| `np.less` | `(T,T)->?` | Lexicographic < | +| `np.less_equal` | `(T,T)->?` | Lexicographic <= | +| `np.greater` | `(T,T)->?` | Lexicographic > | +| `np.greater_equal` | `(T,T)->?` | Lexicographic >= | +| `np.maximum` | `(T,T)->T` | Lexicographic max | +| `np.minimum` | `(T,T)->T` | Lexicographic min | + +### isnumeric vs isdecimal vs isdigit + +| Function | '123' | '\u00b2' (superscript 2) | '\u2460' (circled 1) | Arabic-Indic | +|----------|-------|--------------------------|---------------------|--------------| +| `isdigit` | True | True | True | True | +| `isdecimal` | True | False | False | True | +| `isnumeric` | True | True | True | True | + +- `isdecimal`: Characters forming decimal numbers in base 10 (0-9) +- `isdigit`: Includes superscript/subscript digits +- `isnumeric`: Includes fractions, Roman numerals, etc. + +**Note**: `isdecimal` and `isnumeric` are Unicode-only, will raise TypeError on bytes_ + +### StringDType Flag Summary + +| Flag | Value | Meaning | +|------|-------|---------| +| `NPY_STRING_MISSING` | 0x80 | NA/null value | +| `NPY_STRING_INITIALIZED` | 0x40 | Element has been set | +| `NPY_STRING_OUTSIDE_ARENA` | 0x20 | Heap-allocated | +| `NPY_STRING_LONG` | 0x10 | Arena string >255 bytes | + +### Short String Optimization Thresholds + +| Architecture | Max Inline Size | Struct Size | +|--------------|-----------------|-------------| +| 64-bit | 15 bytes | 16 bytes | +| 32-bit | 7 bytes | 8 bytes | + +--- + +*Document generated from NumPy v2.4.2 source analysis* diff --git a/docs/numpy/PERFORMANCE_EXECUTION_PATHS.md b/docs/numpy/PERFORMANCE_EXECUTION_PATHS.md new file mode 100644 index 000000000..5ccaa8917 --- /dev/null +++ b/docs/numpy/PERFORMANCE_EXECUTION_PATHS.md @@ -0,0 +1,764 @@ +# NumPy Execution Paths + +This document details the different execution paths NumPy operations can take, when each path is selected, and what optimizations apply to each. + +## Overview: Path Selection + +Every NumPy operation selects from multiple execution paths based on input characteristics: + +``` + Input Analysis + │ + ┌───────────────────────┼───────────────────────┐ + ▼ ▼ ▼ + Contiguous? Scalar operand? Overlap? + │ │ │ + ▼ ▼ ▼ + ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ + │ SIMD Fast Path│ │ Scalar Broad- │ │ Copy-Operate │ + │ (4x unrolled) │ │ cast Path │ │ Path │ + └───────────────┘ └───────────────┘ └───────────────┘ +``` + +--- + +## 1. Binary Elementwise Operations (add, sub, mul, div) + +### Path Decision Tree + +``` +np.add(a, b): +│ +├─ IS_BINARY_REDUCE? (accumulator: a += b) +│ └─ YES: Pairwise summation path +│ ├─ 8 accumulators +│ ├─ Prefetch 512B ahead +│ └─ O(log n) rounding error +│ +├─ Memory overlap with output? +│ └─ YES: Allocate temp, operate, copy back +│ +├─ SIMD eligible? (NPY_SIMD && len > 2*vwidth) +│ │ +│ ├─ Both contiguous? (IS_BINARY_CONT) +│ │ └─ **Path A: SIMD Contiguous** +│ │ ├─ 2x unrolled vector loop +│ │ ├─ Masked tail handling +│ │ └─ ~8x faster than scalar +│ │ +│ ├─ First operand scalar? (IS_BINARY_CONT_S1) +│ │ └─ **Path B: SIMD Scalar+Array** +│ │ ├─ Broadcast scalar to vector once +│ │ ├─ 2x unrolled vector loop +│ │ └─ ~6x faster than scalar +│ │ +│ ├─ Second operand scalar? (IS_BINARY_CONT_S2) +│ │ └─ **Path C: SIMD Array+Scalar** +│ │ └─ Same as Path B +│ │ +│ └─ None of above +│ └─ **Path D: Scalar Strided** +│ +└─ SIMD not available + └─ **Path D: Scalar Strided** + ├─ Generic loop with arbitrary strides + └─ No vectorization +``` + +### Path Characteristics + +| Path | Conditions | Unroll | SIMD | Speed | +|------|------------|--------|------|-------| +| A: SIMD Contiguous | `steps == sizeof(type)` | 2x | Yes | 1.0x (baseline) | +| B: SIMD Scalar+Array | `steps[0]==0`, others contiguous | 2x | Yes | 1.1x | +| C: SIMD Array+Scalar | `steps[1]==0`, others contiguous | 2x | Yes | 1.1x | +| D: Scalar Strided | Any other case | None | No | 4-8x slower | +| Reduce | Accumulator pattern | 8 accum | Partial | Varies | + +--- + +## 2. Unary Elementwise Operations (sqrt, sin, abs) + +### Path Decision Tree + +``` +np.sqrt(a): +│ +├─ Memory overlap (in-place)? +│ └─ YES: **Path E: No-Unroll** +│ └─ Single-element SIMD for FP consistency +│ +├─ Loadable stride? (stride fits in gather) +│ └─ NO: **Path E: No-Unroll** +│ +├─ SIMD eligible? +│ │ +│ ├─ Input contiguous, output contiguous? +│ │ └─ **Path F: CONTIG_CONTIG** +│ │ ├─ 4x unrolled vector loop +│ │ ├─ npyv_load_till for tail +│ │ └─ Maximum throughput +│ │ +│ ├─ Input strided, output contiguous? +│ │ └─ **Path G: NCONTIG_CONTIG** +│ │ ├─ 4x unrolled with gather loads +│ │ └─ Slower due to gather +│ │ +│ ├─ Input contiguous, output strided? +│ │ └─ **Path H: CONTIG_NCONTIG** +│ │ ├─ 2x unrolled with scatter stores +│ │ └─ Scatter is expensive +│ │ +│ └─ Both strided? +│ └─ **Path I: NCONTIG_NCONTIG** +│ ├─ 2x unrolled gather/scatter +│ └─ Slowest SIMD path +│ +└─ SIMD not available + └─ **Path J: Scalar** + └─ c_sqrt() or npy_sqrt() +``` + +### Path Characteristics + +| Path | In Stride | Out Stride | Unroll | Notes | +|------|-----------|------------|--------|-------| +| F: CONTIG_CONTIG | 1 | 1 | 4x | Best path | +| G: NCONTIG_CONTIG | N | 1 | 4x | Gather loads | +| H: CONTIG_NCONTIG | 1 | N | 2x | Scatter stores | +| I: NCONTIG_NCONTIG | N | N | 2x | Both gather/scatter | +| E: No-Unroll | Any | Any | None | Overlap safety | +| J: Scalar | Any | Any | None | Fallback | + +**Note**: NumPy forces SSE128 even on AVX512 for some unary ops because gather/scatter instructions are too expensive at wider widths. + +--- + +## 3. Reduction Operations (sum, prod, min, max) + +### Path Decision Tree + +``` +np.sum(a, axis=1): +│ +├─ axis=None? (full array reduction) +│ │ +│ └─ IS_BINARY_REDUCE && contiguous? +│ └─ **Path K: Pairwise Summation** +│ ├─ Recursive divide-and-conquer +│ ├─ Block size 128 +│ ├─ 8 independent accumulators +│ ├─ Prefetch 512B ahead +│ └─ O(log n) rounding error +│ +├─ Axis reduction (axis=0, 1, ...)? +│ │ +│ ├─ Contiguous along reduction axis? +│ │ └─ **Path L: Contiguous Axis Reduce** +│ │ ├─ May use SIMD for inner reduction +│ │ └─ Iterator handles outer dims +│ │ +│ └─ Non-contiguous reduction axis? +│ └─ **Path M: Iterator Reduce** +│ ├─ NpyIter with EXTERNAL_LOOP +│ ├─ Axis reordering for cache +│ └─ Axis coalescing when possible +│ +└─ Has identity? (0 for sum, 1 for prod) + ├─ YES: Initialize result to identity + └─ NO: Copy first element, skip in loop +``` + +### Pairwise Summation Detail + +``` +n < 8: Scalar loop (r = -0.0 init for sign preservation) +n <= 128: 8-way unrolled, tree reduction at end +n > 128: Recursive split at n/2 (aligned to 8) + + pairwise_sum(0..n) + │ + ┌────────────┴────────────┐ + ▼ ▼ + pairwise_sum(0..n/2) pairwise_sum(n/2..n) + │ │ + [8 accum] [8 accum] + │ │ + ((r0+r1)+(r2+r3)) ((r0+r1)+(r2+r3)) + +((r4+r5)+(r6+r7)) +((r4+r5)+(r6+r7)) +``` + +--- + +## 4. Comparison Operations (<, >, ==, !=) + +### Path Decision Tree + +``` +np.greater(a, b): +│ +└─ Implemented as: np.less(b, a) // Swap arguments! + +np.less(a, b): +│ +├─ Memory overlap? +│ └─ YES: Scalar fallback +│ +├─ SIMD eligible? +│ │ +│ ├─ Scalar + Array? (IS_BINARY_CONT_S1) +│ │ └─ **Path N: Scalar Broadcast Compare** +│ │ +│ ├─ Array + Scalar? (IS_BINARY_CONT_S2) +│ │ └─ **Path O: Array Scalar Compare** +│ │ +│ └─ Both contiguous? (IS_BINARY_CONT) +│ └─ **Path P: SIMD Compare** +│ ├─ Vector comparison → boolean vector +│ ├─ Pack to u8 (see below) +│ └─ Unroll factor depends on type width +│ +└─ Fallback + └─ **Path Q: Scalar Compare** +``` + +### Pack-to-Bool Pattern + +Comparisons produce wide boolean vectors that must be packed to u8: + +```c +// 64-bit types: 8x unroll to fill one u8 vector +npyv_b64 c0 = npyv_cmplt_f64(a0, b0); // 4 bools in 256 bits +npyv_b64 c1 = npyv_cmplt_f64(a1, b1); +// ... c2..c7 +npyv_u8 packed = npyv_pack_b8_b64(c0, c1, c2, c3, c4, c5, c6, c7); + +// 32-bit types: 4x unroll +npyv_u8 packed = npyv_pack_b8_b32(c0, c1, c2, c3); + +// 16-bit types: 2x unroll +npyv_u8 packed = npyv_pack_b8_b16(c0, c1); + +// 8-bit types: 1x (already u8 width) +npyv_u8 packed = npyv_cvt_u8_b8(c0); +``` + +| Input Type | Unroll Factor | Why | +|------------|---------------|-----| +| int8/uint8 | 1x | Already byte-width booleans | +| int16/uint16 | 2x | Pack 2 comparisons → 1 u8 vector | +| int32/uint32/float32 | 4x | Pack 4 comparisons → 1 u8 vector | +| int64/uint64/float64 | 8x | Pack 8 comparisons → 1 u8 vector | + +--- + +## 5. Matrix Multiplication (matmul, dot) + +### Path Decision Tree + +``` +np.matmul(a, b): +│ +├─ BLAS available && (float32|float64|complex)? +│ │ +│ ├─ Too big or zero dimension? +│ │ └─ **Path R: No-BLAS Triple Loop** +│ │ +│ ├─ Special shapes? +│ │ │ +│ │ ├─ Scalar output (1xN @ Nx1)? +│ │ │ └─ **Path S: BLAS Dot** +│ │ │ └─ cblas_ddot / cblas_sdot +│ │ │ +│ │ ├─ Matrix @ Vector? +│ │ │ └─ **Path T: BLAS GEMV** +│ │ │ └─ cblas_dgemv / cblas_sgemv +│ │ │ +│ │ └─ Vector @ Matrix? +│ │ └─ **Path T: BLAS GEMV** (transposed) +│ │ +│ ├─ A @ A.T detected? (same array, transposed) +│ │ └─ **Path U: BLAS SYRK** +│ │ ├─ Only compute upper triangle +│ │ ├─ Mirror to lower +│ │ └─ ~50% fewer operations +│ │ +│ ├─ Both BLAS-able layout? +│ │ └─ **Path V: BLAS GEMM** +│ │ └─ cblas_dgemm / cblas_sgemm +│ │ +│ └─ Need to copy for BLAS? +│ └─ **Path W: Copy + GEMM** +│ ├─ Copy non-contiguous to temp +│ └─ Then GEMM +│ +└─ No BLAS (integer, half, object) + └─ **Path R: Triple Loop** +``` + +### BLAS-Ability Check + +```c +bool is_blasable2d(array) { + // Inner (fast) dimension must be contiguous + if (strides[1] != itemsize) return false; + + // Outer stride must be >= inner size + if (strides[0] < shape[1] * itemsize) return false; + + // Stride must fit in BLAS integer + if (strides[0] > BLAS_MAXSIZE) return false; + + return true; +} +``` + +--- + +## 6. Edge Case Paths + +### Memory Overlap Path + +When output overlaps input: + +``` +1. Detect overlap (Diophantine solver, max_work=1) +2. If overlap: + a. Allocate temporary array + b. Operate into temporary + c. Copy temporary to output (WRITEBACKIFCOPY) +3. Cost: +100% memory, +50% time +``` + +### Type Casting Path + +When dtypes don't match: + +``` +1. Allocate buffer (size = min(8192, array_size)) +2. For each buffer chunk: + a. Cast input chunk to buffer + b. Operate on buffer + c. Cast buffer to output +3. Cost: +copy overhead per buffer +``` + +### Empty Array Path + +When `size == 0`: + +``` +1. Check NPY_ITER_ZEROSIZE_OK flag +2. If reduction without identity: + → Raise ValueError +3. Else: + → Return empty array (no computation) +``` + +### Division Edge Cases + +```c +// Division by zero +if (divisor == 0) { + npy_set_floatstatus_divbyzero(); + return 0; // Don't crash +} + +// Overflow case (MIN_INT / -1) +if (dividend == MIN_INT && divisor == -1) { + npy_set_floatstatus_overflow(); + return MIN_INT; // Avoid x86 SIGFPE +} +``` + +### NaN Handling Paths + +| Function | NaN Behavior | Implementation | +|----------|--------------|----------------| +| `max/min` | Propagate | `(a >= b \|\| isnan(a)) ? a : b` | +| `fmax/fmin` | Ignore | Use `fmax()/fmin()` C functions | +| `nanmax/nanmin` | Skip | Filter NaN before reduction | + +--- + +## Path Selection Summary Table + +| Operation | # Paths | Fast Path Condition | Slowest Path | +|-----------|---------|---------------------|--------------| +| Binary (add) | 5 | Both contiguous | Strided (4-8x slower) | +| Unary (sqrt) | 6 | Both contiguous | Gather+scatter (3x slower) | +| Reduction (sum) | 4 | Contiguous, axis=None | Iterator (2x slower) | +| Comparison | 4 | Both contiguous | Strided (4x slower) | +| Matmul | 7 | BLAS-able layout | Triple loop (10-100x slower) | + +--- + +## Critical Clarification: Runtime Branches, Not Separate Kernels + +**The paths described above are NOT separate compiled kernels.** They are **runtime branches within ONE kernel per dtype**. + +### NumPy's Actual Structure + +```c +// ONE function with if/else branches - NOT multiple functions +void DOUBLE_add(char **args, npy_intp *dimensions, npy_intp *steps, void *func) +{ + // Path selection happens HERE at RUNTIME via stride checks + if (IS_BINARY_REDUCE) { + // Branch 1: Pairwise reduction + } + else if (IS_BLOCKABLE_BINARY(sizeof(double), NPY_SIMD_WIDTH)) { + // Branch 2: SIMD contiguous + } + else if (IS_BINARY_CONT_S1(double, double)) { + // Branch 3: Scalar + array + } + else if (IS_BINARY_CONT_S2(double, double)) { + // Branch 4: Array + scalar + } + else { + // Branch 5: General strided + } +} +``` + +### Implications for NumSharp + +NumSharp's ILKernelGenerator should generate **ONE method per operation+dtype** with runtime branches: + +```csharp +// Generated IL method - ONE method with branches +void Generated_Add_Float64(double* lhs, double* rhs, double* result, + int lhsStride, int rhsStride, int resultStride, int length) +{ + // Runtime branch selection (mirrors NumPy's if/else) + if (lhsStride == 0 && lhs == result) { + // Pairwise reduction branch + } + else if (lhsStride == 1 && rhsStride == 1 && resultStride == 1) { + // SIMD contiguous branch + } + else if (lhsStride == 0 && rhsStride == 1) { + // Scalar + array branch + } + else if (rhsStride == 0 && lhsStride == 1) { + // Array + scalar branch + } + else { + // General strided branch + } +} +``` + +--- + +## 7. Sorting (sort, argsort) + +### Path Decision Tree + +``` +np.sort(a): +│ +├─ SIMD dispatch available? +│ │ +│ ├─ x86 platform? +│ │ ├─ sizeof(T) == 2 (16-bit)? +│ │ │ └─ **Path: x86_simd_qsort_16bit** +│ │ └─ sizeof(T) == 4 or 8 (32/64-bit)? +│ │ └─ **Path: x86_simd_qsort** (AVX512) +│ │ +│ └─ ARM/other platform? +│ └─ **Path: highway_qsort** (portable SIMD) +│ +├─ SIMD dispatch returns false → Introsort +│ │ +│ ├─ Recursion depth exceeded (cdepth < 0)? +│ │ └─ **Path: Heapsort** (O(n log n) guaranteed) +│ │ +│ ├─ Partition size > SMALL_QUICKSORT (15)? +│ │ └─ **Path: Quicksort partition** +│ │ ├─ (pi - pl) < (pr - pi) → push right, recurse left +│ │ └─ (pi - pl) >= (pr - pi) → push left, recurse right +│ │ +│ └─ Partition size <= 15? +│ └─ **Path: Insertion sort** +│ +├─ String type? +│ └─ **Path: string_quicksort_** (length-aware) +│ +└─ Generic type (custom comparator)? + └─ **Path: npy_quicksort_impl** with PyArray_CompareFunc +``` + +### Branch Count: 9 + +| Branch | Condition | Algorithm | +|--------|-----------|-----------| +| 1 | x86 + 16-bit | SIMD quicksort (16-bit) | +| 2 | x86 + 32/64-bit | SIMD quicksort (AVX512) | +| 3 | ARM/other | Highway SIMD quicksort | +| 4 | Depth exceeded | Heapsort fallback | +| 5 | Large partition | Quicksort partition | +| 6 | Small partition (≤15) | Insertion sort | +| 7 | String type | String-aware quicksort | +| 8 | Generic type | Comparator-based sort | +| 9 | Cygwin | SIMD disabled entirely | + +--- + +## 8. Searching (searchsorted, nonzero) + +### Path Decision Tree + +``` +np.searchsorted(sorted_arr, values, side='left'): +│ +├─ side == 'left'? +│ └─ **Path: Binary search with < comparator** +│ +├─ side == 'right'? +│ └─ **Path: Binary search with <= comparator** +│ +├─ Empty key array (key_len == 0)? +│ └─ **Path: Early return** (nothing to search) +│ +├─ Sorted key optimization? +│ ├─ last_key < current_key? +│ │ └─ Adjust min_idx based on previous result +│ └─ Skip binary search portion +│ +├─ Has sorter array (indirect search)? +│ └─ **Path: argbinsearch** +│ ├─ Validate index bounds +│ └─ Indirect array access +│ +└─ Generic type? + └─ **Path: npy_binsearch** with PyArray_CompareFunc +``` + +### np.nonzero(a) + +``` +np.nonzero(a): +│ +├─ Count nonzero elements (first pass) +│ └─ Iterate, count where a[i] != 0 +│ +├─ Allocate output arrays (one per dimension) +│ └─ Shape: (count,) × ndim +│ +└─ Fill indices (second pass) + └─ Iterate, store coordinates where a[i] != 0 +``` + +### Branch Count: 7 + +| Branch | Condition | Operation | +|--------|-----------|-----------| +| 1 | side='left' | Use `<` comparator | +| 2 | side='right' | Use `<=` comparator | +| 3 | Empty keys | Early return | +| 4 | Sorted keys | Skip redundant search | +| 5 | Has sorter | Indirect search | +| 6 | Invalid index | Return -1 (error) | +| 7 | Generic type | Custom comparator | + +--- + +## 9. Indexing (boolean, fancy, take/put) + +### Path Decision Tree + +``` +a[index]: +│ +├─ Structured array field access? +│ └─ **Path: _get_field_view** +│ +├─ Full integer index (all dims specified)? +│ └─ **Path: Scalar return** +│ └─ get_item_pointer + PyArray_Scalar +│ +├─ Boolean array index? +│ └─ **Path: Boolean subscript** +│ ├─ count_boolean_trues (first pass) +│ ├─ Allocate 1D result +│ └─ Copy matching elements (second pass) +│ +├─ Single ellipsis (...)? +│ └─ **Path: View return** (PyArray_View) +│ +├─ Slices/newaxis/ellipsis/integer combo? +│ └─ **Path: get_view_from_index** +│ ├─ HAS_SCALAR_ARRAY → PyArray_NewCopy +│ └─ !HAS_FANCY → return view +│ +├─ Simple 1D fancy (single index array)? +│ └─ Check trivial conditions: +│ ├─ TRIVIALLY_ITERABLE? +│ ├─ ITEMSIZE == sizeof(intp)? +│ ├─ Integer kind + aligned? +│ └─ → **Path: mapiter_trivial_get** (optimized) +│ +├─ Complex fancy indexing? +│ └─ **Path: PyArray_MapIterNew** +│ ├─ Multiple index arrays → MapIterCheckIndices +│ ├─ subspace_iter != NULL → subspace iteration +│ └─ subspace_iter == NULL → direct copy +│ +└─ Assignment (a[index] = value)? + ├─ Integer → get_item_pointer + PyArray_Pack + ├─ Boolean → array_assign_boolean_subscript + ├─ Ellipsis → self==op check, PyArray_CopyObject + ├─ Subclass → PyObject_GetItem + └─ Fancy → mapiter_set +``` + +### Branch Count: 15 + +| Branch | Condition | Operation | +|--------|-----------|-----------| +| 1 | Field access | Structured array field | +| 2 | Full integer | Return scalar | +| 3 | Boolean array | Count + gather | +| 4 | Single ellipsis | Return view | +| 5 | Slice combo | Strided view | +| 6 | Scalar array | Copy required | +| 7 | Simple 1D fancy | Trivial mapiter | +| 8 | Complex fancy | Full MapIterNew | +| 9 | Subspace iter | Subspace iteration | +| 10 | Direct copy | No subspace | +| 11 | Assign integer | Pack scalar | +| 12 | Assign boolean | Boolean scatter | +| 13 | Assign ellipsis | Full copy | +| 14 | Assign subclass | Python protocol | +| 15 | Assign fancy | mapiter_set | + +--- + +## 10. Histogram/Bincount + +### Path Decision Tree + +``` +np.bincount(x, weights=None, minlength=0): +│ +├─ Empty input (len == 0)? +│ └─ **Path: Return zeros(minlength)** +│ +├─ Negative values in x? +│ └─ **Path: Raise ValueError** +│ +├─ minlength handling +│ ├─ minlength == None → Error (use 0) +│ ├─ minlength specified → ans_size = max(max(x)+1, minlength) +│ └─ minlength not specified → ans_size = max(x) + 1 +│ +├─ weights == None (unweighted)? +│ └─ **Path: Integer accumulation** +│ └─ for (i=0; i /* implementation */; +} + +public static NDArray Add(NDArray a, NDArray b) +{ + // Check if 'a' can be reused + if (a.IsTemporary && + a.HasSingleReference && + a.IsContiguous && + a.dtype == ResultDtype(a, b) && + a.Shape.Equals(ResultShape(a, b))) + { + AddInPlace(a, b); + return a; + } + + // Check if 'b' can be reused (commutative) + if (b.IsTemporary && + b.HasSingleReference && + b.IsContiguous && + b.dtype == ResultDtype(a, b) && + b.Shape.Equals(ResultShape(a, b))) + { + AddInPlace(b, a); + return b; + } + + // Allocate new array + var result = new NDArray(ResultDtype(a, b), ResultShape(a, b)); + result.IsTemporary = true; + AddInto(result, a, b); + return result; +} +``` + +**Elision conditions** (from NumPy): +- Array is temporary (created by operation, not user) +- Single reference (no other code holds it) +- Owns data (not a view) +- Writeable +- Size >= 256KB (overhead worth it) +- Same dtype or safe cast +- Shape matches result + +### P0.2: Implement Pairwise Summation + +**Impact**: 3-5x speedup for reductions (closes 5.5x gap) + +**Problem**: Current implementation uses linear accumulation with 4 accumulators. NumPy uses pairwise with 8 accumulators and recursive splitting. + +**Implementation**: + +```csharp +public static class PairwiseSum +{ + private const int BlockSize = 128; + + public static double Sum(double* data, int n, int stride = 1) + { + if (n < 8) + { + // Small array: direct accumulation + double r = 0.0; // Use -0.0 to preserve sign + for (int i = 0; i < n; i++) + r += data[i * stride]; + return r; + } + else if (n <= BlockSize) + { + // Medium array: 8 accumulators, unrolled + double r0 = data[0 * stride], r1 = data[1 * stride]; + double r2 = data[2 * stride], r3 = data[3 * stride]; + double r4 = data[4 * stride], r5 = data[5 * stride]; + double r6 = data[6 * stride], r7 = data[7 * stride]; + + for (int i = 8; i < n - (n % 8); i += 8) + { + // Prefetch 512 bytes ahead + Sse.Prefetch0(data + (i + 64) * stride); + + r0 += data[(i + 0) * stride]; + r1 += data[(i + 1) * stride]; + r2 += data[(i + 2) * stride]; + r3 += data[(i + 3) * stride]; + r4 += data[(i + 4) * stride]; + r5 += data[(i + 5) * stride]; + r6 += data[(i + 6) * stride]; + r7 += data[(i + 7) * stride]; + } + + // Handle remainder + for (int i = n - (n % 8); i < n; i++) + r0 += data[i * stride]; + + // Tree reduction preserves pairing + return ((r0 + r1) + (r2 + r3)) + ((r4 + r5) + (r6 + r7)); + } + else + { + // Large array: recursive split + int n2 = (n / 2) - ((n / 2) % 8); // Align to 8 + return Sum(data, n2, stride) + + Sum(data + n2 * stride, n - n2, stride); + } + } +} +``` + +### P0.3: Fix SIMD for Type-Promoted Reductions + +**Impact**: 4-8x speedup for int32 sum (currently falls back to scalar) + +**Problem**: When summing int32 to int64 accumulator, NumSharp disables SIMD because vector widening is complex. + +**Solution**: Accumulate in same type, periodically drain to wider accumulator: + +```csharp +public static long SumInt32ToInt64(int* data, int n) +{ + const int DrainInterval = 1000000; // Drain before overflow risk + long total = 0; + int remaining = n; + + while (remaining > 0) + { + int chunk = Math.Min(remaining, DrainInterval); + int partialSum = SumInt32Simd(data, chunk); // SIMD sum in int32 + total += partialSum; + data += chunk; + remaining -= chunk; + } + + return total; +} +``` + +Or use widening SIMD instructions: +```csharp +// AVX2: widen int32 to int64 +Vector256 sum = Vector256.Zero; +for (int i = 0; i < n; i += 4) +{ + Vector128 v = Sse2.LoadVector128(data + i); + Vector256 wide = Avx2.ConvertToVector256Int64(v); + sum = Avx2.Add(sum, wide); +} +``` + +--- + +## Priority 1: High Impact Optimizations + +### P1.1: Fast Path for Same-Type Contiguous Arrays + +**Impact**: 1.5x speedup for binary operations + +**Problem**: NumSharp goes through full path classification even for the most common case. + +**Implementation**: + +```csharp +public static NDArray Add(NDArray a, NDArray b) +{ + // Fast path: same type, same shape, both contiguous + if (a.typecode == b.typecode && + a.Shape.IsContiguous && + b.Shape.IsContiguous && + a.Shape.Equals(b.Shape)) + { + var result = new NDArray(a.typecode, a.Shape); + SimdBinaryContiguous(a.Address, b.Address, result.Address, + a.size, a.typecode, BinaryOp.Add); + return result; + } + + // Full path with broadcasting, type promotion, etc. + return AddGeneral(a, b); +} +``` + +### P1.2: Axis Reordering for Reductions + +**Impact**: 2-3x speedup for axis reductions + +**Problem**: `sum(axis=0)` on a C-order array iterates non-contiguously. + +**Implementation**: + +```csharp +public static int[] OptimalAxisOrder(Shape shape, int[] reduceAxes) +{ + // Sort axes by stride (smallest first = most contiguous) + var axisInfo = Enumerable.Range(0, shape.NDim) + .Select(i => (axis: i, stride: Math.Abs(shape.strides[i]))) + .OrderBy(x => x.stride) + .ToArray(); + + // Inner loop should be on smallest stride + return axisInfo.Select(x => x.axis).ToArray(); +} +``` + +### P1.3: Axis Coalescing + +**Impact**: 2x speedup for multi-dimensional reductions + +**Problem**: Nested loops have overhead. Adjacent compatible dimensions can be merged. + +```csharp +public static Shape CoalesceAxes(Shape shape) +{ + var newDims = new List(); + var newStrides = new List(); + + int currentDim = shape.dimensions[0]; + int currentStride = shape.strides[0]; + + for (int i = 1; i < shape.NDim; i++) + { + // Can coalesce if strides are compatible + if (shape.strides[i] == currentStride * currentDim) + { + currentDim *= shape.dimensions[i]; + } + else + { + newDims.Add(currentDim); + newStrides.Add(currentStride); + currentDim = shape.dimensions[i]; + currentStride = shape.strides[i]; + } + } + + newDims.Add(currentDim); + newStrides.Add(currentStride); + + return new Shape(newDims.ToArray(), newStrides.ToArray()); +} +``` + +### P1.4: Use 8 Accumulators Instead of 4 + +**Impact**: 1.3x speedup for reductions + +Current ILKernelGenerator uses 4 vector accumulators. NumPy uses 8. + +--- + +## Priority 2: Medium Impact Optimizations + +### P2.1: Small Array Cache + +**Impact**: Faster small array operations (< 1KB) + +```csharp +public class SmallArrayCache +{ + private const int MaxSize = 1024; + private const int MaxCached = 7; + + private readonly ConcurrentStack[] _buckets = + new ConcurrentStack[MaxSize]; + + public byte[] Rent(int size) + { + if (size < MaxSize && _buckets[size]?.TryPop(out var arr) == true) + return arr; + return new byte[size]; + } + + public void Return(byte[] arr) + { + if (arr.Length < MaxSize) + { + var bucket = _buckets[arr.Length] ??= new ConcurrentStack(); + if (bucket.Count < MaxCached) + bucket.Push(arr); + } + } +} +``` + +Or use `System.Buffers.ArrayPool.Shared`. + +### P2.2: Partial Load/Store for Remainder Handling + +**Impact**: Cleaner, potentially faster tail handling + +```csharp +// Current: scalar loop for remainder +for (int i = vectorEnd; i < n; i++) + dst[i] = src[i] + scalar; + +// Better: masked vector operation +if (remaining > 0) +{ + var mask = CreateMask(remaining); // e.g., [1,1,1,0,0,0,0,0] + var v = MaskedLoad(src + vectorEnd, mask); + var r = Vector256.Add(v, scalarVec); + MaskedStore(dst + vectorEnd, mask, r); +} +``` + +### P2.3: Memory Overlap Detection + +**Impact**: Safe in-place operations + +```csharp +public static bool MayShareMemory(NDArray a, NDArray b) +{ + // Fast path: different storage + if (!ReferenceEquals(a.Storage, b.Storage)) + return false; + + // Calculate memory extents + var (aStart, aEnd) = GetMemoryExtent(a); + var (bStart, bEnd) = GetMemoryExtent(b); + + // Check if extents overlap + return aStart < bEnd && bStart < aEnd; +} + +private static (long start, long end) GetMemoryExtent(NDArray arr) +{ + long start = arr.Address.ToInt64(); + long end = start; + + for (int i = 0; i < arr.ndim; i++) + { + if (arr.strides[i] > 0) + end += (arr.shape[i] - 1) * arr.strides[i]; + else + start += (arr.shape[i] - 1) * arr.strides[i]; + } + + return (start, end + arr.itemsize); +} +``` + +### P2.4: Support `out=` Parameter + +**Impact**: User-controlled buffer reuse + +```csharp +public static NDArray Add(NDArray a, NDArray b, NDArray? @out = null) +{ + var resultShape = BroadcastShape(a.Shape, b.Shape); + var resultDtype = PromoteTypes(a.typecode, b.typecode); + + NDArray result; + if (@out != null) + { + ValidateOutput(@out, resultShape, resultDtype); + if (MayShareMemory(@out, a) || MayShareMemory(@out, b)) + { + // Operate into temp, then copy + var temp = new NDArray(resultDtype, resultShape); + AddInto(temp, a, b); + temp.CopyTo(@out); + return @out; + } + result = @out; + } + else + { + result = new NDArray(resultDtype, resultShape); + } + + AddInto(result, a, b); + return result; +} +``` + +--- + +## Priority 3: Lower Impact Optimizations + +### P3.1: Division by Invariant + +For `a / scalar`, precompute magic multiplier: + +```csharp +// Instead of: result[i] = a[i] / scalar +// Use: result[i] = MultiplyHigh(a[i], magic) >> shift +``` + +### P3.2: Prefetch Hints + +```csharp +// In hot loops: +Sse.Prefetch0(ptr + 64); // Prefetch 512 bytes ahead to L1 +``` + +### P3.3: BLAS Integration + +For `np.matmul` with large matrices, integrate with: +- Math.NET Numerics +- Intel MKL via P/Invoke +- OpenBLAS + +--- + +## Architecture Recommendation + +### Shared Infrastructure Design + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ NumSharp Shared Infrastructure │ +├─────────────────────────────────────────────────────────────────────┤ +│ PathClassifier │ +│ ├─ IsContiguous(a, b) → bool │ +│ ├─ IsScalarBroadcast(a, b) → (bool isFirst, bool isSecond) │ +│ ├─ IsSIMDEligible(a, b) → bool │ +│ └─ ClassifyPath(a, b) → ExecutionPath enum │ +├─────────────────────────────────────────────────────────────────────┤ +│ LoopDispatcher where TOp : IBinaryOp │ +│ ├─ SimdContiguous(a, b, result) │ +│ ├─ SimdScalarFirst(scalar, b, result) │ +│ ├─ SimdScalarSecond(a, scalar, result) │ +│ └─ ScalarStrided(a, b, result) │ +├─────────────────────────────────────────────────────────────────────┤ +│ SimdKernel │ +│ ├─ PeelToAlignment() │ +│ ├─ MainLoop4xUnrolled() │ +│ └─ TailWithMask() │ +├─────────────────────────────────────────────────────────────────────┤ +│ ReductionKernel │ +│ ├─ PairwiseSum() │ +│ ├─ AxisReduce() │ +│ └─ TreeHorizontalReduce() │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +### Operation Definition (5% of code) + +```csharp +// Each operation is just an interface implementation +public readonly struct AddOp : IBinaryOp +{ + public float ScalarOp(float a, float b) => a + b; + public Vector256 VectorOp(Vector256 a, Vector256 b) + => Avx.Add(a, b); +} + +public readonly struct SqrtOp : IUnaryOp +{ + public float ScalarOp(float a) => MathF.Sqrt(a); + public Vector256 VectorOp(Vector256 a) + => Avx.Sqrt(a); +} +``` + +### Usage + +```csharp +public static NDArray Add(NDArray a, NDArray b) +{ + return BinaryDispatcher.Execute(a, b); +} + +public static NDArray Sqrt(NDArray a) +{ + return UnaryDispatcher.Execute(a); +} +``` + +--- + +## Implementation Roadmap + +### Phase 1: Quick Wins (1-2 weeks) +- [ ] P0.2: Pairwise summation (biggest impact on reduction gap) +- [ ] P1.1: Fast path for contiguous same-type arrays +- [ ] P1.4: 8 accumulators instead of 4 + +### Phase 2: Allocation Optimization (2-3 weeks) +- [ ] P0.1: Temporary elision infrastructure +- [ ] P2.4: `out=` parameter support +- [ ] P2.1: Small array cache + +### Phase 3: Advanced Paths (3-4 weeks) +- [ ] P0.3: SIMD for type-promoted reductions +- [ ] P1.2: Axis reordering +- [ ] P1.3: Axis coalescing +- [ ] P2.2: Partial load/store + +### Phase 4: Infrastructure Refactor (ongoing) +- [ ] Shared LoopDispatcher +- [ ] Shared SimdKernel +- [ ] Operation interfaces + +--- + +## Measurement + +Benchmark after each phase: + +```csharp +// Standard benchmark array +var a = np.random.rand(10_000_000); +var b = np.random.rand(10_000_000); + +// Binary operations +Measure(() => a + b); +Measure(() => a + b + a + b); // Chained - tests temp elision + +// Reductions +Measure(() => np.sum(a)); +Measure(() => np.sum(a.reshape(1000, 10000), axis: 1)); + +// Target: within 2x of NumPy for all operations +``` + +--- + +## IL Generator Architecture (Matching NumPy) + +### Critical Insight: How NumPy Actually Works + +**NumPy does NOT generate separate functions for each "path".** Instead: + +1. **ONE function per operation per dtype** (e.g., `DOUBLE_add`) +2. That function contains **RUNTIME if/else branches** that check stride patterns +3. **Multiple CPU-target variants** are compiled (AVX512, AVX2, SSE) but with identical internal structure +4. CPU variant is selected **once at module load**, then the function pointer is cached + +```c +// NumPy's ACTUAL structure (from loops_arithm_fp.dispatch.c.src) +NPY_NO_EXPORT void DOUBLE_add(char **args, npy_intp const *dimensions, + npy_intp const *steps, void *func) +{ + npy_intp ssrc0 = steps[0], ssrc1 = steps[1], sdst = steps[2]; + char *src0 = args[0], *src1 = args[1], *dst = args[2]; + + // RUNTIME BRANCH 1: Reduce pattern (a += b) + if (ssrc0 == 0 && ssrc0 == sdst && src0 == dst) { + // Pairwise summation with 8 accumulators + ... + } + // RUNTIME BRANCH 2: All contiguous + else if (ssrc0 == sizeof(double) && ssrc0 == ssrc1 && ssrc0 == sdst) { + // SIMD contiguous loop (4x unrolled) + for (; len >= vstep*4; len -= vstep*4, ...) { + v0 = npyv_load_f64(src0); v1 = npyv_load_f64(src0 + vstep); ... + r0 = npyv_add_f64(v0, v1); ... + npyv_store_f64(dst, r0); ... + } + // Tail handling + ... + } + // RUNTIME BRANCH 3: Scalar + contiguous array + else if (ssrc0 == 0 && ssrc1 == sizeof(double) && sdst == ssrc1) { + npyv_f64 scalar_vec = npyv_setall_f64(*(double*)src0); + // SIMD loop with broadcast scalar + ... + } + // RUNTIME BRANCH 4: Contiguous array + scalar + else if (ssrc1 == 0 && ssrc0 == sizeof(double) && sdst == ssrc0) { + npyv_f64 scalar_vec = npyv_setall_f64(*(double*)src1); + // SIMD loop with broadcast scalar + ... + } + // RUNTIME BRANCH 5: General fallback + else { + // Scalar strided loop + for (i = 0; i < n; i++, src0 += ssrc0, src1 += ssrc1, dst += sdst) { + *(double*)dst = *(double*)src0 + *(double*)src1; + } + } +} +``` + +### NumSharp ILKernelGenerator Should Match This + +**Generate ONE method per operation+dtype with runtime branches:** + +```csharp +// What ILKernelGenerator should emit (pseudocode of generated IL) +void Generated_Add_Float64( + double* lhs, double* rhs, double* result, + int lhsStride, int rhsStride, int resultStride, + int length) +{ + // RUNTIME BRANCH 1: Reduce pattern + if (lhsStride == 0 && lhs == result) { + // Emit: Pairwise summation + } + // RUNTIME BRANCH 2: All contiguous + else if (lhsStride == 1 && rhsStride == 1 && resultStride == 1) { + // Emit: SIMD contiguous (4x unrolled) + int i = 0; + for (; i <= length - Vector256.Count * 4; i += Vector256.Count * 4) { + var v0 = Vector256.Load(lhs + i); + var v1 = Vector256.Load(lhs + i + Vector256.Count); + // ... 4x unrolled + var r0 = Vector256.Add(v0, Vector256.Load(rhs + i)); + // ... + Vector256.Store(result + i, r0); + // ... + } + // Tail + for (; i < length; i++) result[i] = lhs[i] + rhs[i]; + } + // RUNTIME BRANCH 3: Scalar + array + else if (lhsStride == 0 && rhsStride == 1 && resultStride == 1) { + var scalarVec = Vector256.Create(*lhs); + // SIMD loop + } + // RUNTIME BRANCH 4: Array + scalar + else if (rhsStride == 0 && lhsStride == 1 && resultStride == 1) { + var scalarVec = Vector256.Create(*rhs); + // SIMD loop + } + // RUNTIME BRANCH 5: General + else { + // Coordinate-based or strided scalar loop + } +} +``` + +### Kernel Count (Corrected) + +**Per ufunc, NumPy generates:** + +| Level | What | Count | +|-------|------|-------| +| C functions | Per dtype | 1 function × 12 dtypes = **12 functions** | +| CPU variants | Per function | ×3 (AVX512, AVX2, SSE baseline) | +| Runtime branches | Inside each function | 5 branches (not separate functions) | + +**NumSharp should generate:** + +| Level | What | Count | +|-------|------|-------| +| IL methods | Per operation × dtype | 1 method × 12 dtypes = **12 methods** | +| Runtime branches | Inside each method | 5 branches (matching NumPy) | + +### The 5 Runtime Branches (Binary Operations) + +These are **NOT separate kernels** - they are **if/else branches within ONE kernel**: + +``` +┌─────────────────────────────────────────────────────────────────────────────┐ +│ RUNTIME BRANCHES WITHIN ONE BINARY KERNEL │ +├─────────────────────────────────────────────────────────────────────────────┤ +│ │ +│ Branch 1: REDUCE │ +│ ├─ Condition: lhsStride==0 && lhs==result (accumulator pattern) │ +│ ├─ Algorithm: Pairwise summation, 8 accumulators, recursive split │ +│ └─ Used by: np.add.reduce(), a += b │ +│ │ +│ Branch 2: SIMD_CONTIGUOUS │ +│ ├─ Condition: All strides == sizeof(element) │ +│ ├─ Algorithm: 4x unrolled vector loop + scalar tail │ +│ └─ Used by: Most common case (contiguous arrays) │ +│ │ +│ Branch 3: SIMD_SCALAR_FIRST │ +│ ├─ Condition: lhsStride==0, others contiguous │ +│ ├─ Algorithm: Broadcast scalar to vector, then SIMD loop │ +│ └─ Used by: scalar + array, e.g., 5 + a │ +│ │ +│ Branch 4: SIMD_SCALAR_SECOND │ +│ ├─ Condition: rhsStride==0, others contiguous │ +│ ├─ Algorithm: Broadcast scalar to vector, then SIMD loop │ +│ └─ Used by: array + scalar, e.g., a + 5 │ +│ │ +│ Branch 5: GENERAL_FALLBACK │ +│ ├─ Condition: All other cases (strided, misaligned, overlap) │ +│ ├─ Algorithm: Scalar loop with arbitrary strides │ +│ └─ Used by: Sliced arrays, transposed views, etc. │ +│ │ +└─────────────────────────────────────────────────────────────────────────────┘ +``` + +### Branch Patterns by Operation Category + +| Category | Branch 1 | Branch 2 | Branch 3 | Branch 4 | Branch 5 | +|----------|----------|----------|----------|----------|----------| +| **Binary** | Reduce | Contiguous | Scalar+Array | Array+Scalar | General | +| **Unary** | - | Contig→Contig | Strided→Contig | Contig→Strided | General | +| **Reduce** | Pairwise | AxisContig | AxisStrided | - | Iterator | +| **Compare** | - | Contiguous | Scalar+Array | Array+Scalar | General | +| **Scan** | - | Contiguous | AxisContig | - | AxisGeneral | + +### What Needs Implementation (Corrected) + +**Not "26 separate paths" but rather "missing branches within existing kernels":** + +| Kernel Type | Current Branches | Missing Branches | Priority | +|-------------|------------------|------------------|----------| +| Binary | Contiguous, General | **Reduce (pairwise)**, Scalar+Array, Array+Scalar | Critical | +| Unary | Contig→Contig, General | Strided→Contig, Contig→Strided | Medium | +| Reduce | AxisBasic | **Pairwise**, AxisReorder | Critical | +| Compare | Contiguous, General | Scalar+Array, Array+Scalar | Medium | +| Scan | Contiguous, AxisBasic | - | Low | + +### Implementation Priority (Corrected) + +#### Critical: Add Missing Branches + +| Missing Branch | In Kernel | Gap Impact | Effort | +|----------------|-----------|------------|--------| +| **Reduce/Pairwise** | Binary reduce, Sum | 5.5x → 2x | Add ~200 lines to existing | +| **Scalar+Array** | Binary | 1.5x → 1.1x | Add ~50 lines branch | +| **Array+Scalar** | Binary | 1.5x → 1.1x | Add ~50 lines branch | +| **AxisReorder** | Reduce | 3x → 1.5x | Add ~100 lines branch | + +#### Medium: Strided SIMD Branches + +| Missing Branch | In Kernel | Benefit | Effort | +|----------------|-----------|---------|--------| +| Strided→Contig | Unary | Transposed input | Add ~100 lines | +| Contig→Strided | Unary | Transposed output | Add ~100 lines | +| Scalar+Array | Compare | Scalar comparison | Add ~50 lines | + +### Summary (Corrected) + +| Metric | Previous (Wrong) | Corrected | +|--------|------------------|-----------| +| Architecture | 26 separate kernel functions | 1 kernel with 5 runtime branches | +| What to generate | Separate IL methods per path | One IL method with if/else branches | +| Total IL methods | 26 × 12 dtypes = 312 | 1 × 12 dtypes = 12 per operation | +| Code to add | ~4,000 lines (new paths) | ~500 lines (new branches in existing) | +| Path selection | At dispatch time | At runtime via stride checks | + +### NumPy's Stride-Check Macros (for reference) + +```c +// From fast_loop_macros.h - these are RUNTIME checks + +// Check if all arrays are contiguous +#define IS_BINARY_CONT(tin, tout) \ + (steps[0] == sizeof(tin) && steps[1] == sizeof(tin) && steps[2] == sizeof(tout)) + +// Check if first operand is scalar +#define IS_BINARY_CONT_S1(tin, tout) \ + (steps[0] == 0 && steps[1] == sizeof(tin) && steps[2] == sizeof(tout)) + +// Check if second operand is scalar +#define IS_BINARY_CONT_S2(tin, tout) \ + (steps[0] == sizeof(tin) && steps[1] == 0 && steps[2] == sizeof(tout)) + +// Check if this is a reduction (accumulator pattern) +#define IS_BINARY_REDUCE \ + (args[0] == args[2] && steps[0] == steps[2] && steps[0] == 0) + +// Check if SIMD-safe (alignment + no problematic overlap) +#define IS_BLOCKABLE_BINARY(esize, vsize) \ + (IS_BINARY_CONT(esize, esize) && \ + npy_is_aligned(args[0], esize) && \ + npy_is_aligned(args[1], esize) && \ + npy_is_aligned(args[2], esize) && \ + (abs_ptrdiff(args[2], args[0]) >= vsize || args[2] == args[0])) +``` + +### Additional Multi-Output Operations + +These require **separate kernel signatures** (not just branches): + +| Operation | Signature | NumPy Macro | +|-----------|-----------|-------------| +| `modf` | (in) → (frac, int) | `UNARY_LOOP_TWO_OUT` | +| `frexp` | (in) → (mantissa, exp) | `UNARY_LOOP_TWO_OUT` | +| `divmod` | (a, b) → (quot, rem) | `BINARY_LOOP_TWO_OUT` | + +These are genuinely different kernel types, not branches. + +--- + +## Final Verified: Complete NumPy Computation Systems + +After exhaustive verification of NumPy source code, here are ALL computation systems: + +### 10 Core Computation Systems + +``` +┌─────────────────────────────────────────────────────────────────────────────────┐ +│ VERIFIED COMPLETE: 10 COMPUTATION SYSTEMS │ +│ 78+ Total Runtime Branches │ +├─────────────────────────────────────────────────────────────────────────────────┤ +│ │ +│ SYSTEM 1: UFUNC BINARY ELEMENTWISE [10 branches] │ +│ ├─ Source: loops_arithmetic.dispatch.c.src, loops.c.src │ +│ ├─ Operations: add, sub, mul, div, power, mod, floor_div, bitwise_* │ +│ ├─ Branches: SIMD contiguous, SIMD scalar1, SIMD scalar2, reduce, │ +│ │ aliasing variants (×3), VSX4 path, general fallback │ +│ └─ NumSharp: DONE (ILKernelGenerator) │ +│ │ +│ SYSTEM 2: UFUNC UNARY ELEMENTWISE [8 branches] │ +│ ├─ Source: loops_unary.dispatch.c.src, loops_unary_fp.dispatch.c.src │ +│ ├─ Operations: neg, abs, sqrt, sin, cos, exp, log, floor, ceil, etc. │ +│ ├─ Branches: CONTIG_CONTIG, NCONTIG_CONTIG, CONTIG_NCONTIG, NCONTIG_NCONTIG, │ +│ │ overlap check, loadable stride check, no_unroll, scalar │ +│ └─ NumSharp: DONE (ILKernelGenerator) │ +│ │ +│ SYSTEM 3: UFUNC REDUCTIONS [9 branches] │ +│ ├─ Source: reduction.c, loops_utils.h.src │ +│ ├─ Operations: sum, prod, min, max, any, all, mean, std, var │ +│ ├─ Branches: masked/unmasked, identity/no-identity, skip-first, │ +│ │ pairwise (n<8 / n≤128 / recursive), wheremask │ +│ └─ NumSharp: DONE (ILKernelGenerator) - pairwise needs improvement │ +│ │ +│ SYSTEM 4: UFUNC COMPARISONS [4+ branches] │ +│ ├─ Source: loops_comparison.dispatch.c.src │ +│ ├─ Operations: eq, ne, lt, gt, le, ge │ +│ ├─ Branches: contiguous, scalar1, scalar2, general + pack-to-bool │ +│ │ (pack varies by type: 1x/2x/4x/8x unroll) │ +│ └─ NumSharp: DONE (ILKernelGenerator) │ +│ │ +│ SYSTEM 5: LINEAR ALGEBRA [12 branches] │ +│ ├─ Source: cblasfuncs.c, matmul.c.src, vdot.c, einsum.cpp │ +│ ├─ Operations: dot, matmul, vdot, inner, tensordot, einsum │ +│ ├─ Branches: noblas fallback, scalar_out (dot), scalar_vec, gemv (×2), │ +│ │ gemm, syrk (A@A.T), buffer allocation, layout transpose │ +│ ├─ BLAS levels: L1 (dot), L2 (gemv), L3 (gemm, syrk) │ +│ └─ NumSharp: DONE (basic matmul) - einsum NOT IMPLEMENTED │ +│ │ +│ SYSTEM 6: SORTING [9 branches] │ +│ ├─ Source: npysort/quicksort.cpp, heapsort.cpp, timsort.cpp │ +│ ├─ Operations: sort, argsort, lexsort │ +│ ├─ Branches: SIMD dispatch (x86/ARM), introsort, heapsort (depth limit), │ +│ │ insertion sort (n≤15), string sort, generic comparator │ +│ ├─ SIMD: x86-simd-sort (AVX512), highway (ARM/other) │ +│ └─ NumSharp: **NOT IMPLEMENTED** ◄── HIGH PRIORITY │ +│ │ +│ SYSTEM 7: SEARCHING [7 branches] │ +│ ├─ Source: npysort/binsearch.cpp, item_selection.c │ +│ ├─ Operations: searchsorted, nonzero, argmax, argmin │ +│ ├─ Branches: left/right side, arg variant, sorted key optimization, │ +│ │ generic comparator, empty input │ +│ └─ NumSharp: DONE (searchsorted, argmax, argmin, nonzero) │ +│ │ +│ SYSTEM 8: INDEXING [15 branches] │ +│ ├─ Source: mapping.c, item_selection.c │ +│ ├─ Operations: a[i], a[mask], a[indices], take, put, compress, choose │ +│ ├─ Branches: field access, integer index, boolean array, ellipsis, │ +│ │ slice/newaxis combo, simple 1D fancy, complex fancy, │ +│ │ trivial mapiter, subspace iteration, assignment variants │ +│ └─ NumSharp: DONE (boolean masking, fancy indexing, take) │ +│ │ +│ SYSTEM 9: HISTOGRAM/BINCOUNT [8 branches] │ +│ ├─ Source: compiled_base.c (arr_bincount) │ +│ ├─ Operations: bincount, histogram, digitize │ +│ ├─ Branches: empty input, negative check, minlength handling, │ +│ │ weighted/unweighted, type checking, monotonic check │ +│ └─ NumSharp: **NOT IMPLEMENTED** ◄── MEDIUM PRIORITY │ +│ │ +│ SYSTEM 10: PARTITION/SELECTION [separate] │ +│ ├─ Source: npysort/selection.cpp │ +│ ├─ Operations: partition, argpartition │ +│ ├─ Algorithm: Introselect (quickselect + heapselect fallback) │ +│ └─ NumSharp: **NOT IMPLEMENTED** ◄── MEDIUM PRIORITY │ +│ │ +└─────────────────────────────────────────────────────────────────────────────────┘ +``` + +### Special Cases (Within Existing Systems) + +These are NOT separate systems - they use branches within existing systems: + +| Operation | System | Implementation | +|-----------|--------|----------------| +| `clip` | Ufunc Binary (#1) | Ternary ufunc with min/max bounds | +| `where` (3-arg) | Indexing (#8) | Conditional selection in mapping.c | +| `divmod` | Ufunc Binary (#1) | `BINARY_LOOP_TWO_OUT` macro | +| `modf`, `frexp` | Ufunc Unary (#2) | `UNARY_LOOP_TWO_OUT` macro | +| `cumsum`, `cumprod` | Ufunc Reductions (#3) | Accumulate mode of add/multiply | +| `unique` | Sorting (#6) + Searching (#7) | Sort-based or hash-based | +| `correlate`, `convolve` | Linear Algebra (#5) | 1D signal processing | + +### Dtype-Specific Paths (Within Existing Systems) + +These are NOT separate systems - they are dtype branches within ufuncs: + +| Dtype | Location | Notes | +|-------|----------|-------| +| String/Unicode | `string_ufuncs.cpp` | Registered as ufuncs | +| DateTime | `datetime.c` | Business day calculations | +| Object | `loops.c.src` | Python protocol fallback | +| Complex | `loops_unary_complex.dispatch.c.src` | Via ufuncs | + +### Composed Operations (No Unique Kernels) + +These are Python-level and use existing primitives: + +| Operation | Composition | +|-----------|-------------| +| `diff` | slicing + subtraction | +| `gradient` | slicing + division | +| `mean`, `std`, `var` | sum + division | +| `outer` | multiply.outer | +| `tensordot` | transpose + reshape + dot | +| `cross`, `kron` | multiply + subtract/reshape | +| `tril`, `triu` | where + indices | +| Set ops (`unique`, `union1d`, etc.) | sort + comparison | + +### NumSharp Implementation Status + +| System | Status | Missing | +|--------|--------|---------| +| 1. Ufunc Binary | DONE | Pairwise reduce branch | +| 2. Ufunc Unary | DONE | Strided SIMD branches | +| 3. Ufunc Reductions | DONE | Pairwise algorithm | +| 4. Ufunc Comparisons | DONE | Scalar broadcast branches | +| 5. Linear Algebra | Partial | Einsum, advanced LAPACK | +| 6. Sorting | **MISSING** | All of it | +| 7. Searching | DONE | - | +| 8. Indexing | DONE | put, choose | +| 9. Histogram | **MISSING** | All of it | +| 10. Partition | **MISSING** | All of it | + +### Final Summary + +| Metric | Value | +|--------|-------| +| **Total computation systems** | 10 | +| **Total runtime branches** | 78+ | +| **Systems fully implemented** | 7/10 | +| **Systems missing** | 3 (Sorting, Histogram, Partition) | +| **Branches needing improvement** | ~10 (pairwise, scalar broadcast, strided SIMD) | + +**This is the COMPLETE and VERIFIED list of all NumPy computation systems.** diff --git a/docs/numpy/PERFORMANCE_OPTIMIZATION_STRATEGIES.md b/docs/numpy/PERFORMANCE_OPTIMIZATION_STRATEGIES.md new file mode 100644 index 000000000..4cbf6f793 --- /dev/null +++ b/docs/numpy/PERFORMANCE_OPTIMIZATION_STRATEGIES.md @@ -0,0 +1,423 @@ +# NumPy Optimization Strategies + +This document analyzes how NumPy achieves high performance through various optimization strategies. Understanding these patterns is essential for improving NumSharp's performance. + +## Overview + +NumPy's performance comes from a combination of strategies working together: + +| Strategy | Impact | Where Applied | +|----------|--------|---------------| +| SIMD Vectorization | 4-16x speedup | All elementwise ops | +| Memory Layout Optimization | 2-5x speedup | Iteration, reductions | +| Temporary Elision | 4-6x speedup | Chained operations | +| Pairwise Summation | 3-5x speedup | Reductions | +| BLAS Integration | 10-100x speedup | Linear algebra | +| Small Array Cache | Reduced allocation | Arrays < 1KB | + +--- + +## 1. SIMD Vectorization + +### Universal Intrinsics (npyv_*) + +NumPy abstracts SIMD across platforms with a unified API: + +```c +// Same code compiles to SSE, AVX2, AVX-512, NEON, VSX +npyv_f32 v = npyv_load_f32(ptr); // Load vector +npyv_f32 r = npyv_add_f32(v1, v2); // Vector operation +npyv_store_f32(dst, r); // Store vector +``` + +**Platform Support**: +| Platform | Width | Lanes (f32) | +|----------|-------|-------------| +| SSE2 | 128-bit | 4 | +| AVX2 | 256-bit | 8 | +| AVX-512 | 512-bit | 16 | +| ARM NEON | 128-bit | 4 | +| PowerPC VSX | 128-bit | 4 | + +### Multi-Target Compilation + +NumPy compiles the same source multiple times for different CPU targets: + +```c +// Generated at build time: +void add_AVX512_SKX(const float *src, float *dst, size_t n); +void add_AVX2(const float *src, float *dst, size_t n); +void add_SSE2(const float *src, float *dst, size_t n); // baseline + +// Runtime dispatch: +if (NPY_CPU_HAVE(AVX512_SKX)) return add_AVX512_SKX; +if (NPY_CPU_HAVE(AVX2)) return add_AVX2; +return add_SSE2; +``` + +### Standard SIMD Loop Pattern + +All SIMD operations follow a 3-phase pattern: + +```c +// Phase 1: Peel to alignment +for (i = 0; i < peel; i++) { + dst[i] = scalar_op(src[i]); +} + +// Phase 2: Main SIMD loop (4x unrolled) +for (; i < end - 4*vstep; i += 4*vstep) { + npyv_f32 v0 = npyv_load_f32(src + i + 0*vstep); + npyv_f32 v1 = npyv_load_f32(src + i + 1*vstep); + npyv_f32 v2 = npyv_load_f32(src + i + 2*vstep); + npyv_f32 v3 = npyv_load_f32(src + i + 3*vstep); + + npyv_f32 r0 = npyv_sqrt_f32(v0); + npyv_f32 r1 = npyv_sqrt_f32(v1); + npyv_f32 r2 = npyv_sqrt_f32(v2); + npyv_f32 r3 = npyv_sqrt_f32(v3); + + npyv_store_f32(dst + i + 0*vstep, r0); + npyv_store_f32(dst + i + 1*vstep, r1); + npyv_store_f32(dst + i + 2*vstep, r2); + npyv_store_f32(dst + i + 3*vstep, r3); +} + +// Phase 3: Tail with partial vector operations +if (remaining > 0) { + npyv_f32 v = npyv_load_till_f32(src + i, remaining, 0); + npyv_store_till_f32(dst + i, remaining, npyv_sqrt_f32(v)); +} +``` + +**Key aspects**: +- 4x unrolling maximizes instruction-level parallelism +- `npyv_load_till` / `npyv_store_till` handle remainders without scalar fallback +- Cleanup call (`npyv_cleanup()`) required for AVX→SSE transitions + +--- + +## 2. Memory Management + +### Small Array Cache + +NumPy caches small allocations to avoid malloc overhead: + +```c +#define NBUCKETS 1024 // Arrays up to 1KB +#define NCACHE 7 // 7 cached pointers per bucket + +// Allocation: check cache first +if (size < NBUCKETS && cache[size].available > 0) { + return cache[size].ptrs[--cache[size].available]; +} +return malloc(size); + +// Deallocation: cache if bucket not full +if (size < NBUCKETS && cache[size].available < NCACHE) { + cache[size].ptrs[cache[size].available++] = ptr; +} else { + free(ptr); +} +``` + +### Temporary Elision + +For chained operations like `a + b + c`, NumPy detects when intermediate results can be reused: + +**Conditions for elision**: +| Condition | Check | +|-----------|-------| +| Unique reference | `refcount == 1` | +| Large enough | `size >= 256KB` | +| Owns data | `OWNDATA` flag set | +| Writeable | `WRITEABLE` flag set | +| Same/safe dtype | Safe casting allowed | +| From interpreter | Backtrace validates caller | + +**Result**: `a + b + c + d` allocates once instead of three times (4-6x speedup). + +### Huge Pages + +For arrays >= 4MB, NumPy advises the kernel to use huge pages: + +```c +if (size >= (1u << 22u)) { // 4MB + madvise(ptr, size, MADV_HUGEPAGE); +} +``` + +This reduces TLB misses for large array traversals. + +--- + +## 3. Pairwise Summation + +For floating-point reductions, NumPy uses pairwise summation for numerical stability: + +```c +#define PW_BLOCKSIZE 128 + +double pairwise_sum(double *a, size_t n, size_t stride) { + if (n < 8) { + // Direct accumulation + double r = -0.0; // Preserves -0 semantics + for (i = 0; i < n; i++) r += a[i * stride]; + return r; + } + else if (n <= PW_BLOCKSIZE) { + // 8 independent accumulators + double r[8]; + // Initialize r[0..7] from first 8 elements + + for (i = 8; i < n - (n % 8); i += 8) { + NPY_PREFETCH(a + (i + 64) * stride, 0, 3); // L1 prefetch + r[0] += a[(i+0) * stride]; + r[1] += a[(i+1) * stride]; + // ... r[2..7] + } + + // Tree reduction preserves pairing + return ((r[0]+r[1]) + (r[2]+r[3])) + ((r[4]+r[5]) + (r[6]+r[7])); + } + else { + // Recursive split + size_t n2 = (n / 2) - ((n / 2) % 8); // Keep aligned to 8 + return pairwise_sum(a, n2, stride) + + pairwise_sum(a + n2*stride, n - n2, stride); + } +} +``` + +**Benefits**: +- O(log n) rounding error instead of O(n) +- 8 accumulators enable superscalar execution +- Prefetch hints improve cache behavior +- Block size (128) fits in L1 cache + +--- + +## 4. BLAS Integration + +For linear algebra, NumPy dispatches to optimized BLAS libraries: + +### Tiered Dispatch + +| Operation | BLAS Level | Function | +|-----------|------------|----------| +| Inner product | Level 1 | `cblas_ddot` | +| Matrix-vector | Level 2 | `cblas_dgemv` | +| Matrix-matrix | Level 3 | `cblas_dgemm` | +| Symmetric A@A.T | Level 3 | `cblas_dsyrk` | + +### Blasable Detection + +```c +bool is_blasable2d(PyArrayObject *arr) { + // Inner dimension must be contiguous + if (strides[1] != itemsize) return false; + + // Outer stride must be reasonable + if (strides[0] < shape[1] * itemsize) return false; + if (strides[0] > BLAS_MAXSIZE) return false; + + return true; +} +``` + +### Symmetric Optimization + +When computing `A @ A.T`, NumPy detects this pattern and uses `syrk`: + +```c +if (ip1 == ip2 && same_shape && opposite_transpose) { + // Only compute upper triangle, then mirror + cblas_dsyrk(CblasRowMajor, CblasUpper, trans, n, k, + alpha, A, lda, beta, C, ldc); + // Mirror upper to lower +} +``` + +This halves the computation for symmetric results. + +--- + +## 5. Division Optimization + +### Division by Constant + +Integer division by a constant uses multiply-high trick: + +```c +// Precompute magic numbers once +npyv_s32x3 divisor = npyv_divisor_s32(scalar); + +// In loop: multiply-high instead of divide +for (; len >= vstep; len -= vstep) { + npyv_s32 a = npyv_load_s32(src); + npyv_s32 q = npyv_divc_s32(a, divisor); // No actual division! + npyv_store_s32(dst, q); +} +``` + +The `npyv_divc_s32` uses the magic multiplier + shifts instead of hardware division. + +### Edge Case Handling + +```c +// Avoid hardware exceptions +if (divisor == 0) { + npy_set_floatstatus_divbyzero(); + return 0; // Don't crash +} +if (dividend == MIN_INT && divisor == -1) { + npy_set_floatstatus_overflow(); + return MIN_INT; // Avoid x86 SIGFPE +} +``` + +--- + +## 6. Compiler Hints + +NumPy uses various compiler hints to enable better optimization: + +### Loop Optimization + +```c +// Tell compiler no loop-carried dependencies +#if __GNUC__ >= 6 +#define IVDEP_LOOP _Pragma("GCC ivdep") +#endif + +IVDEP_LOOP +for (i = 0; i < n; i++) { + dst[i] = src1[i] + src2[i]; +} +``` + +### Branch Prediction + +```c +#define NPY_LIKELY(x) __builtin_expect(!!(x), 1) +#define NPY_UNLIKELY(x) __builtin_expect(!!(x), 0) + +if (NPY_UNLIKELY(divisor == 0)) { + handle_error(); +} +``` + +### Force Optimization + +```c +// Force O3 for hot functions +#define NPY_GCC_OPT_3 __attribute__((optimize("O3"))) + +NPY_GCC_OPT_3 +static void hot_inner_loop(...) { ... } +``` + +### Prefetch + +```c +// Prefetch 512 bytes ahead into L1 cache +NPY_PREFETCH(ptr + 64, 0, 3); // 0=read, 3=L1 locality +``` + +--- + +## 7. Axis Reduction Optimization + +### Axis Reordering + +NumPy sorts axes by stride for better cache locality: + +```c +// Before: sum along axis 0 of C-order array +// shape=[1000, 1000], strides=[8000, 8] (row-major) +// Naive: 1000 cache misses per column + +// After reordering: inner loop on contiguous axis +// Process rows (stride=8) in inner loop +// 1000x fewer cache misses +``` + +### Axis Coalescing + +Adjacent axes with compatible strides are merged: + +```c +// shape=[100, 100, 100], strides=[80000, 800, 8] +// All contiguous: coalesce to shape=[1000000], strides=[8] +// Single large SIMD reduction instead of nested loops +``` + +--- + +## Summary: Optimization Checklist + +When implementing NumSharp operations, verify: + +1. **SIMD**: Is the hot path vectorized with 4x unrolling? +2. **Contiguity**: Is there a fast path for contiguous arrays? +3. **Scalar broadcast**: Is scalar+array optimized (broadcast once)? +4. **Reductions**: Using pairwise summation with 8 accumulators? +5. **Allocation**: Can temporaries be elided? Small array cache? +6. **Edge cases**: Division by zero, overflow handled without crash? +7. **Cache**: Axes reordered for locality? Prefetch for large arrays? + +--- + +## Key Files in NumPy Source + +| Area | File | +|------|------| +| SIMD abstraction | `numpy/_core/src/common/simd/` | +| Loop macros | `numpy/_core/src/umath/fast_loop_macros.h` | +| Pairwise sum | `numpy/_core/src/umath/loops_utils.h.src` | +| BLAS dispatch | `numpy/_core/src/common/cblasfuncs.c` | +| Memory alloc | `numpy/_core/src/multiarray/alloc.c` | +| Temp elision | `numpy/_core/src/multiarray/temp_elide.c` | + +--- + +## Optimization Strategy by Computation System + +NumPy has **10 core computation systems**. Here's which optimizations apply to each: + +| System | SIMD | Pairwise | BLAS | Cache Reorder | Temp Elision | +|--------|------|----------|------|---------------|--------------| +| 1. Ufunc Binary | Yes (4x unroll) | Reduce only | - | - | Yes | +| 2. Ufunc Unary | Yes (4x unroll) | - | - | - | Yes | +| 3. Ufunc Reductions | Yes | **Yes** | - | **Yes** | - | +| 4. Ufunc Comparisons | Yes + pack-to-bool | - | - | - | Yes | +| 5. Linear Algebra | - | - | **Yes** | - | - | +| 6. Sorting | Yes (x86-simd-sort) | - | - | - | - | +| 7. Searching | - | - | - | - | - | +| 8. Indexing | Partial | - | - | - | - | +| 9. Histogram | - | - | - | - | - | +| 10. Partition | - | - | - | - | - | + +### Key Insight: ONE Kernel with Runtime Branches + +Each system generates **ONE kernel per dtype** with **runtime branches** for different memory layouts: + +``` +Binary kernel (e.g., DOUBLE_add): +├─ Branch 1: IS_REDUCE → pairwise accumulator +├─ Branch 2: IS_CONTIGUOUS → SIMD 4x unrolled loop +├─ Branch 3: IS_SCALAR1 → broadcast first operand +├─ Branch 4: IS_SCALAR2 → broadcast second operand +└─ Branch 5: GENERAL → scalar strided loop +``` + +**This is NOT multiple separate kernels - it's ONE function with if/else branches.** + +### NumSharp Alignment + +NumSharp's ILKernelGenerator should: +1. Generate ONE method per operation+dtype +2. Include runtime branches matching NumPy's patterns +3. Apply appropriate optimizations per branch + +See `PERFORMANCE_NUMSHARP_RECOMMENDATIONS.md` for the complete 10-system architecture. diff --git a/docs/numpy/PERFORMANCE_SHARED_INFRASTRUCTURE.md b/docs/numpy/PERFORMANCE_SHARED_INFRASTRUCTURE.md new file mode 100644 index 000000000..c3c70b40d --- /dev/null +++ b/docs/numpy/PERFORMANCE_SHARED_INFRASTRUCTURE.md @@ -0,0 +1,564 @@ +# NumPy Shared Infrastructure + +This document describes the common infrastructure that NumPy operations share. Understanding this architecture enables building similarly reusable infrastructure in NumSharp. + +## Overview: Code Reuse Statistics + +| Component | Lines | Shared % | Used By | +|-----------|-------|----------|---------| +| NpyIter | 8,425 | 100% | All multi-dim ops | +| ufunc_object.c | 6,805 | 90% | All ufuncs | +| fast_loop_macros.h | 380 | 100% | All inner loops | +| type_resolution.c | 2,258 | 100% | All type dispatch | +| mem_overlap.c | 923 | 100% | All write ops | +| SIMD infrastructure | 818 | 100% | All vectorized ops | + +**Effective reuse**: ~70% of code is shared infrastructure used by 100+ operations. + +--- + +## 1. Ufunc Execution Skeleton + +All ufuncs flow through a common execution pipeline: + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ UFUNC EXECUTION PIPELINE │ +├─────────────────────────────────────────────────────────────────────┤ +│ 1. PyUFunc_GenericFunction() ← Entry point for all ufuncs │ +│ 2. convert_ufunc_arguments() ← Parse Python arguments │ +│ 3. promote_and_get_info() ← Type resolution (shared table) │ +│ └─ Cache lookup (O(1) identity hash) │ +│ 4. try_trivial_single_output_loop() ← Fast path for simple cases │ +│ └─ If contiguous: skip iterator, direct loop call │ +│ 5. execute_ufunc_loop() ← Full NpyIter path │ +│ ├─ NpyIter_AdvancedNew() ← Iterator construction │ +│ ├─ Broadcasting resolution ← Automatic shape matching │ +│ ├─ Memory overlap check ← Automatic safety │ +│ └─ Buffered iteration ← If casting needed │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +**Key insight**: Operations only implement the inner loop. Everything else is shared. + +--- + +## 2. Fast Loop Macros + +Location: `numpy/_core/src/umath/fast_loop_macros.h` + +### Basic Loop Skeletons + +These macros provide the iteration structure that operations plug into: + +```c +// Unary loop skeleton +#define UNARY_LOOP \ + char *ip1 = args[0], *op1 = args[1]; \ + npy_intp is1 = steps[0], os1 = steps[1]; \ + npy_intp n = dimensions[0]; \ + npy_intp i; \ + for(i = 0; i < n; i++, ip1 += is1, op1 += os1) + +// Binary loop skeleton +#define BINARY_LOOP \ + char *ip1 = args[0], *ip2 = args[1], *op1 = args[2]; \ + npy_intp is1 = steps[0], is2 = steps[1], os1 = steps[2]; \ + npy_intp n = dimensions[0]; \ + npy_intp i; \ + for(i = 0; i < n; i++, ip1 += is1, ip2 += is2, op1 += os1) + +// Reduction loop skeleton +#define BINARY_REDUCE_LOOP(TYPE) \ + char *iop1 = args[0]; \ + TYPE io1 = *(TYPE *)iop1; \ + npy_intp is2 = steps[1]; \ + char *ip2 = args[1]; \ + npy_intp n = dimensions[0]; \ + npy_intp i; \ + for(i = 0; i < n; i++, ip2 += is2) +``` + +### Contiguity Detection Macros + +```c +// Check if unary operation has contiguous input/output +#define IS_UNARY_CONT(tin, tout) \ + (steps[0] == sizeof(tin) && steps[1] == sizeof(tout)) + +// Check if binary operation has contiguous operands +#define IS_BINARY_CONT(tin, tout) \ + (steps[0] == sizeof(tin) && steps[1] == sizeof(tin) && steps[2] == sizeof(tout)) + +// Scalar operand detection +#define IS_BINARY_CONT_S1(tin, tout) // First operand is scalar (step=0) +#define IS_BINARY_CONT_S2(tin, tout) // Second operand is scalar + +// SIMD eligibility (alignment + separation) +#define IS_BLOCKABLE_BINARY(esize, vsize) \ + (IS_BINARY_CONT(esize, esize) && \ + npy_is_aligned(args[0], esize) && \ + npy_is_aligned(args[1], esize) && \ + npy_is_aligned(args[2], esize) && \ + (abs_ptrdiff(args[2], args[0]) >= vsize || args[2] == args[0])) +``` + +### Fast Loop Variants + +The `*_FAST` macros automatically dispatch to the best path: + +```c +#define BINARY_LOOP_FAST(tin, tout, op) \ + do { \ + if (IS_BINARY_CONT(tin, tout)) { \ + /* Contiguous path - SIMD friendly */ \ + BINARY_LOOP { op; } \ + } \ + else if (IS_BINARY_CONT_S1(tin, tout)) { \ + /* Scalar + array path */ \ + BINARY_LOOP_S1 { op; } \ + } \ + else if (IS_BINARY_CONT_S2(tin, tout)) { \ + /* Array + scalar path */ \ + BINARY_LOOP_S2 { op; } \ + } \ + else { \ + /* Generic strided path */ \ + BINARY_LOOP { op; } \ + } \ + } while (0) +``` + +--- + +## 3. NpyIter Infrastructure + +Location: `numpy/_core/src/multiarray/nditer_*.c` (~8,425 lines) + +### Core Structure + +```c +struct NpyIter_InternalOnly { + npy_uint32 itflags; // NPY_ITFLAG_* flags + npy_uint8 ndim; // Number of dimensions + int nop; // Number of operands + npy_intp itersize; // Total iteration count + npy_intp iterindex; // Current position + char iter_flexdata[]; // Variable-length: perm, dtypes, axisdata +}; +``` + +### Common Iterator Setup + +```c +NpyIter *iter = NpyIter_AdvancedNew( + nop, op_arrays, + NPY_ITER_EXTERNAL_LOOP | // We handle inner loop + NPY_ITER_BUFFERED | // Enable type casting buffers + NPY_ITER_ZEROSIZE_OK | // Allow empty arrays + NPY_ITER_GROWINNER | // Maximize inner loop size + NPY_ITER_REDUCE_OK, // Allow reduction operands + order, casting, + op_flags, op_dtypes, + -1, NULL, NULL, buffersize +); + +// Get iteration pointers +NpyIter_IterNextFunc *iternext = NpyIter_GetIterNext(iter, NULL); +char **dataptr = NpyIter_GetDataPtrArray(iter); +npy_intp *strideptr = NpyIter_GetInnerStrideArray(iter); +npy_intp *countptr = NpyIter_GetInnerLoopSizePtr(iter); + +// Main iteration +do { + inner_loop(dataptr, *countptr, strideptr); +} while (iternext(iter)); +``` + +### Key Iterator Features + +| Feature | Flag | Purpose | +|---------|------|---------| +| External loop | `NPY_ITER_EXTERNAL_LOOP` | We control inner loop | +| Buffering | `NPY_ITER_BUFFERED` | Type casting support | +| Grow inner | `NPY_ITER_GROWINNER` | Maximize SIMD runs | +| Reduce OK | `NPY_ITER_REDUCE_OK` | Allow stride=0 writes | +| Copy if overlap | `NPY_ITER_COPY_IF_OVERLAP` | Safety for in-place | + +### Axis Optimization + +The iterator automatically: +1. **Reorders axes** by stride for cache locality +2. **Coalesces axes** with compatible strides into larger dimensions +3. **Tracks first-visit** for no-identity reductions + +--- + +## 4. Type Resolution + +Location: `numpy/_core/src/umath/ufunc_type_resolution.c` + +### Dispatch Cache + +O(1) lookup using identity hash on dtype tuple: + +```c +PyObject *info = PyArrayIdentityHash_GetItem( + ufunc->_dispatch_cache, + (PyObject **)op_dtypes +); +if (info != NULL) { + return info; // Cache hit +} +// Cache miss: resolve and cache +``` + +### Common Type Resolvers + +| Resolver | Pattern | Used By | +|----------|---------|---------| +| `SimpleUniform` | XX -> X | add, sub, mul | +| `SimpleBinaryComparison` | XX -> bool | <, >, ==, != | +| `Default` | Linear search | Complex ops | + +### Casting Validation + +```c +// Compile-time table: can type A safely cast to type B? +static const bool _npy_can_cast_safely_table[NPY_NTYPES][NPY_NTYPES] = { + // bool < int8 < int16 < int32 < int64 < float32 < float64 + ... +}; +``` + +--- + +## 5. Template System (.c.src) + +Location: `numpy/_core/src/umath/loops*.c.src` + +### Template Syntax + +```c +/**begin repeat + * #TYPE = FLOAT, DOUBLE# + * #type = npy_float, npy_double# + * #sfx = f32, f64# + */ +NPY_NO_EXPORT void @TYPE@_sqrt(char **args, ...) { + UNARY_LOOP_FAST(@type@, @type@, *out = npy_sqrt@sfx@(in)); +} +/**end repeat**/ +``` + +Generates: +```c +NPY_NO_EXPORT void FLOAT_sqrt(char **args, ...) { + UNARY_LOOP_FAST(npy_float, npy_float, *out = npy_sqrtf32(in)); +} +NPY_NO_EXPORT void DOUBLE_sqrt(char **args, ...) { + UNARY_LOOP_FAST(npy_double, npy_double, *out = npy_sqrtf64(in)); +} +``` + +### Nested Templates + +```c +/**begin repeat + * #sfx = s8, u8, s16, u16, s32, u32, s64, u64, f32, f64# + */ +/**begin repeat1 + * #kind = add, subtract, multiply# + * #OP = +, -, *# + */ +void @sfx@_@kind@(...) { + BINARY_LOOP_FAST(..., *out = in1 @OP@ in2); +} +/**end repeat1**/ +/**end repeat**/ +``` + +Generates 10 types x 3 operations = 30 functions from ~5 lines. + +--- + +## 6. SIMD Kernel Templates + +### Unary Operation Template + +From `loops_unary_fp.dispatch.c.src`: + +```c +/**begin repeat1 + * #kind = sqrt, abs, square, reciprocal, floor, ceil, trunc, rint# + * #intr = sqrt, abs, square, recip, floor, ceil, trunc, rint# + */ +/**begin repeat2 + * #STYPE = CONTIG, NCONTIG# + * #DTYPE = CONTIG, NCONTIG# + * #unroll = 4, 2# + */ +static void simd_@TYPE@_@kind@_@STYPE@_@DTYPE@(...) +{ + const int vstep = npyv_nlanes_@sfx@; + + // Unrolled SIMD loop (structure is IDENTICAL for all operations) + for (; len >= @unroll@*vstep; len -= @unroll@*vstep) { + npyv_@sfx@ v0 = LOAD_@STYPE@(src, 0); + #if @unroll@ > 1 + npyv_@sfx@ v1 = LOAD_@STYPE@(src, 1); + #endif + // ... more loads if unroll > 2 + + // THE ONLY PART THAT DIFFERS: + npyv_@sfx@ r0 = npyv_@intr@_@sfx@(v0); + #if @unroll@ > 1 + npyv_@sfx@ r1 = npyv_@intr@_@sfx@(v1); + #endif + + STORE_@DTYPE@(dst, 0, r0); + #if @unroll@ > 1 + STORE_@DTYPE@(dst, 1, r1); + #endif + } + // Tail handling (shared) +} +/**end repeat2**/ +/**end repeat1**/ +``` + +This generates **8 operations x 4 layouts x 2 types = 64 functions** from one template. + +### Binary Operation Template + +```c +/**begin repeat1 + * #kind = add, subtract, multiply, divide# + * #VOP = add, sub, mul, div# + */ +static void simd_binary_@kind@_@sfx@(char **args, npy_intp len) +{ + // Load (shared) + npyv_@sfx@ a = npyv_load_@sfx@(src1); + npyv_@sfx@ b = npyv_load_@sfx@(src2); + + // Operation (ONLY DIFFERENCE) + npyv_@sfx@ r = npyv_@VOP@_@sfx@(a, b); + + // Store (shared) + npyv_store_@sfx@(dst, r); +} +/**end repeat1**/ +``` + +### Comparison Template (with pack-to-bool) + +```c +/**begin repeat1 + * #kind = equal, not_equal, less, less_equal, greater, greater_equal# + * #VOP = cmpeq, cmpneq, cmplt, cmple, cmpgt, cmpge# + */ +static void simd_compare_@kind@_@sfx@(...) +{ + // Compare (generates boolean vector) + npyv_b@width@ c = npyv_@VOP@_@sfx@(a, b); + + // Pack to u8 (shared across all comparisons) + #if @width@ == 32 + npyv_u8 r = npyv_pack_b8_b32(c0, c1, c2, c3); + #elif @width@ == 64 + npyv_u8 r = npyv_pack_b8_b64(c0, c1, c2, c3, c4, c5, c6, c7); + #endif + + npyv_store_u8(dst, npyv_and_u8(r, truemask)); +} +/**end repeat1**/ +``` + +--- + +## 7. Memory Overlap Detection + +Location: `numpy/_core/src/common/mem_overlap.c` + +### Algorithm + +NumPy solves a bounded Diophantine equation: + +``` +sum(stride_a[i] * x_a[i]) - sum(stride_b[i] * x_b[i]) == offset + +where: 0 <= x_a[i] < shape_a[i] + 0 <= x_b[i] < shape_b[i] +``` + +### Fast Paths + +1. **Different base pointers**: Check if memory extents overlap +2. **Same array**: Check internal overlap via stride patterns +3. **Simple cases**: Direct bounds comparison + +### Usage + +```c +// Check before in-place operations +if (solve_may_share_memory(output, input, 1) != MEM_OVERLAP_NO) { + // Allocate temporary, copy, operate, copy back + temp = PyArray_Copy(input); + operate(temp, output); + PyArray_CopyInto(output, temp); +} +``` + +--- + +## 8. How to Add a New Operation + +To add a new ufunc leveraging shared infrastructure: + +### Step 1: Define Inner Loop + +```c +// In loops_custom.c.src +/**begin repeat + * #TYPE = FLOAT, DOUBLE# + * #type = float, double# + */ +NPY_NO_EXPORT void @TYPE@_myop( + char **args, npy_intp const *dimensions, + npy_intp const *steps, void *func) +{ + // Use shared macro - only provide the operation + BINARY_LOOP_FAST(@type@, @type@, *out = custom_op(in1, in2)); +} +/**end repeat**/ +``` + +### Step 2: Optional SIMD Optimization + +```c +#if NPY_SIMD +static void simd_myop_@sfx@(char **args, npy_intp len) +{ + // Use shared SIMD skeleton + const int vstep = npyv_nlanes_@sfx@; + for (; len >= vstep; len -= vstep, ...) { + npyv_@sfx@ a = npyv_load_@sfx@(src1); + npyv_@sfx@ b = npyv_load_@sfx@(src2); + npyv_@sfx@ r = /* your SIMD operation */; + npyv_store_@sfx@(dst, r); + } +} +#endif + +NPY_NO_EXPORT void @TYPE@_myop(...) { +#if NPY_SIMD + if (IS_BLOCKABLE_BINARY(sizeof(@type@), NPY_SIMD_WIDTH)) { + simd_myop_@sfx@(args, dimensions[0]); + return; + } +#endif + BINARY_LOOP_FAST(@type@, @type@, *out = custom_op(in1, in2)); +} +``` + +### What You Get for Free + +- Broadcasting (via NpyIter) +- Type casting (via buffered iteration) +- Memory safety (via overlap detection) +- `out=` parameter support +- Reduction support (`ufunc.reduce()`) +- Accumulate support (`ufunc.accumulate()`) +- Multi-threading coordination + +--- + +## Summary: Infrastructure Layers + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ Layer 1: Python Interface │ +│ - Argument parsing, output allocation │ +├─────────────────────────────────────────────────────────────────────┤ +│ Layer 2: Type Dispatch (shared) │ +│ - Cache lookup, type resolution, casting decisions │ +├─────────────────────────────────────────────────────────────────────┤ +│ Layer 3: Iterator (shared) │ +│ - Broadcasting, axis reordering, buffering │ +├─────────────────────────────────────────────────────────────────────┤ +│ Layer 4: Loop Selection (shared macros) │ +│ - IS_BLOCKABLE_*, contiguity detection │ +├─────────────────────────────────────────────────────────────────────┤ +│ Layer 5: SIMD Kernel (shared skeleton) │ +│ - Peel/main/tail, unrolling, partial loads │ +├─────────────────────────────────────────────────────────────────────┤ +│ Layer 6: Operation (5% unique code) │ +│ - One intrinsic or operator per operation │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +--- + +## Scope: Which Systems Use This Infrastructure + +**This shared infrastructure applies to ufuncs (Systems 1-4).** NumPy has 10 total computation systems: + +### Systems Using Ufunc Infrastructure (This Document) + +| System | Uses NpyIter | Uses Loop Macros | Uses SIMD Templates | +|--------|--------------|------------------|---------------------| +| 1. Ufunc Binary | Yes | Yes | Yes | +| 2. Ufunc Unary | Yes | Yes | Yes | +| 3. Ufunc Reductions | Yes | Yes | Partial (pairwise) | +| 4. Ufunc Comparisons | Yes | Yes | Yes + pack-to-bool | + +### Systems with SEPARATE Infrastructure + +| System | Infrastructure | Location | +|--------|----------------|----------| +| 5. Linear Algebra | BLAS dispatch | `cblasfuncs.c`, `matmul.c.src` | +| 6. Sorting | SIMD quicksort | `npysort/quicksort.cpp` | +| 7. Searching | Binary search templates | `npysort/binsearch.cpp` | +| 8. Indexing | MapIterator | `mapping.c`, `item_selection.c` | +| 9. Histogram | Direct accumulation | `compiled_base.c` | +| 10. Partition | Introselect | `npysort/selection.cpp` | + +### Key Insight: ONE Kernel per Dtype with Runtime Branches + +The shared infrastructure produces **ONE function per operation per dtype** with **runtime branches**: + +```c +// Generated from template: ONE function, multiple branches +void DOUBLE_add(char **args, npy_intp *dimensions, npy_intp *steps, void *func) +{ + // Branch selection happens at RUNTIME based on steps[] values + if (IS_BINARY_REDUCE) { + // Pairwise reduction branch + } + else if (IS_BLOCKABLE_BINARY(sizeof(double), NPY_SIMD_WIDTH)) { + // SIMD contiguous branch + } + else if (IS_BINARY_CONT_S1(double, double)) { + // Scalar + array branch + } + else if (IS_BINARY_CONT_S2(double, double)) { + // Array + scalar branch + } + else { + // General strided branch + } +} +``` + +**This is NOT multiple separate kernels - it's runtime dispatch within ONE kernel.** + +### NumSharp Alignment + +NumSharp's ILKernelGenerator should mirror this architecture: +- Generate ONE method per operation+dtype +- Include runtime branches for contiguity/scalar/overlap checks +- Share loop skeleton code across operations +- Only the actual operation differs (one intrinsic or operator) + +See `PERFORMANCE_NUMSHARP_RECOMMENDATIONS.md` for the complete 10-system architecture and implementation priorities. diff --git a/docs/numpy/README.md b/docs/numpy/README.md new file mode 100644 index 000000000..4775ce34d --- /dev/null +++ b/docs/numpy/README.md @@ -0,0 +1,13 @@ +# NumPy Reference Documentation + +This directory contains documentation about **NumPy behavior** based on **NumPy 2.4.2**. + +These documents serve as reference material for understanding NumPy's APIs, semantics, and implementation details. They are used to ensure NumSharp maintains 1-to-1 behavioral compatibility with NumPy. + +## Contents + +- `neps/` - NumPy Enhancement Proposals (NEPs) relevant to NumSharp + +## Source + +The authoritative NumPy source is available at `src/numpy/` (checked out to v2.4.2). diff --git a/docs/numpy/neps/NEP01.md b/docs/numpy/neps/NEP01.md new file mode 100644 index 000000000..a70956d7d --- /dev/null +++ b/docs/numpy/neps/NEP01.md @@ -0,0 +1,65 @@ +# NEP 01 - A Simple File Format for NumPy Arrays (.npy) + +**Status:** Final +**NumSharp Impact:** HIGH - NumSharp implements `np.save`/`np.load` + +## Summary + +Defines the `.npy` binary file format for persisting single NumPy arrays to disk, preserving shape and dtype information. + +## NumSharp Relevance + +NumSharp implements this format in `np.save.cs` and `np.load.cs`. Must match the specification exactly for interoperability. + +## File Format Specification + +### Magic Number and Version +``` +Bytes 0-5: Magic string "\x93NUMPY" (6 bytes) +Byte 6: Major version (0x01 or 0x02) +Byte 7: Minor version (0x00) +``` + +### Header Length +- **Version 1.0:** Bytes 8-9 = little-endian unsigned short (max 65535) +- **Version 2.0:** Bytes 8-11 = little-endian unsigned int (max 4 GiB) + +### Header Format +ASCII string containing a Python dictionary literal, padded with spaces to make total header divisible by 16, terminated with newline. + +```python +{ + "descr": "` = big) +- [ ] Support all NumSharp dtypes +- [ ] Handle Fortran-order arrays (convert to C-order or preserve) + +## Related Files + +- `src/NumSharp.Core/APIs/np.save.cs` +- `src/NumSharp.Core/APIs/np.load.cs` + +## References + +- [NEP 1 Full Text](https://numpy.org/neps/nep-0001-npy-format.html) +- [NumPy format.py](https://github.com/numpy/numpy/blob/main/numpy/lib/format.py) diff --git a/docs/numpy/neps/NEP05.md b/docs/numpy/neps/NEP05.md new file mode 100644 index 000000000..adcd89ba9 --- /dev/null +++ b/docs/numpy/neps/NEP05.md @@ -0,0 +1,62 @@ +# NEP 05 - Generalized Universal Functions (gufuncs) + +**Status:** Final +**NumSharp Impact:** MEDIUM - Affects operation signatures like matmul, dot + +## Summary + +Extends ufuncs to operate on sub-arrays instead of just scalars. Enables "sub-array by sub-array" operations with defined core dimensions. + +## Key Concept + +Regular ufuncs operate element-by-element. Generalized ufuncs operate on sub-arrays with a defined **signature** specifying core dimensions. + +## Signature Syntax + +``` + ::= "->" + ::= "(" ")" +``` + +### Examples + +| Function | Signature | Description | +|----------|-----------|-------------| +| `add` | `(),()->()` | Two scalars → scalar | +| `inner1d` | `(i),(i)->()` | Two 1-D arrays → scalar | +| `matmul` | `(m,n),(n,p)->(m,p)` | Matrix multiplication | +| `sum1d` | `(i)->()` | 1-D array → scalar | + +## Broadcasting with gufuncs + +1. Core dimensions are mapped to the **last dimensions** of arrays +2. Remaining dimensions are "loop dimensions" and are broadcast +3. Same dimension name = same size (or broadcastable) + +### Example: `inner1d` with signature `(i),(i)->()` + +``` +Input a: (3, 5, N) → Core dim i=N, loop dims (3, 5) +Input b: (5, N) → Core dim i=N, loop dims (5,) → broadcast to (3, 5) +Output: (3, 5) → No core dims, just loop dims +``` + +## NumSharp Relevance + +NumSharp operations that follow gufunc semantics: +- `np.dot` / `np.matmul` - matrix multiplication +- `np.tensordot` - tensor contraction +- `np.inner` - inner product +- `np.outer` - outer product + +### Implementation Pattern + +When implementing gufunc-like operations: +1. Extract core dimensions from last axes +2. Broadcast remaining "loop" dimensions +3. Apply operation over core dimensions +4. Output shape = loop dims + output core dims + +## References + +- [NEP 5 Full Text](https://numpy.org/neps/nep-0005-generalized-ufuncs.html) diff --git a/docs/numpy/neps/NEP07.md b/docs/numpy/neps/NEP07.md new file mode 100644 index 000000000..cd7a399d8 --- /dev/null +++ b/docs/numpy/neps/NEP07.md @@ -0,0 +1,95 @@ +# NEP 07 - DateTime and Timedelta Types + +**Status:** Final +**NumSharp Impact:** HIGH - NumSharp does NOT currently support datetime64/timedelta64 + +## Summary + +Defines `datetime64` (absolute time) and `timedelta64` (relative time) types for NumPy arrays. + +## Type Definitions + +### datetime64 +- 64-bit signed integer +- Measures units from POSIX epoch (January 1, 1970, 12:00 AM) +- NaT (Not a Time) = `-2^63` + +### timedelta64 +- 64-bit signed integer +- Represents duration/interval +- NaT = `-2^63` + +## Time Units + +| Code | Meaning | Range | +|------|---------|-------| +| Y | year | ± 9.2e18 years | +| M | month | ± 7.6e17 years | +| W | week | ± 1.7e17 years | +| D | day | ± 2.5e16 years | +| h | hour | ± 1.0e15 years | +| m | minute | ± 1.7e13 years | +| s | second | ± 2.9e12 years | +| ms | millisecond | ± 2.9e9 years | +| us | microsecond (default) | ± 2.9e6 years | +| ns | nanosecond | ± 292 years | +| ps | picosecond | ± 106 days | +| fs | femtosecond | ± 2.6 hours | +| as | attosecond | ± 9.2 seconds | + +## Operations + +### datetime64 vs datetime64 +- **Subtraction:** Returns timedelta64 +- **Comparison:** ==, !=, <, >, <=, >= +- **NOT allowed:** Addition, multiplication, division + +### datetime64 vs timedelta64 +- **Addition/Subtraction:** Returns datetime64 +- **NOT allowed:** Multiplication, division + +### timedelta64 vs timedelta64 +- **All arithmetic:** +, -, *, / +- **Result unit:** Shorter (more precise) of the two units + +## String Notation + +```python +dtype('datetime64[us]') # Long form +dtype('M8[us]') # Short form (M8 = datetime64) +dtype('timedelta64[ms]') # Long form +dtype('m8[ms]') # Short form (m8 = timedelta64) + +# Multiples +dtype('M8[100ns]') # 100 nanoseconds +dtype('M8[3M]') # 3 months +``` + +## NumSharp Implementation Status + +**NOT IMPLEMENTED** - datetime64 and timedelta64 are not supported. + +### Implementation Requirements + +1. Add `NPTypeCode.DateTime64` and `NPTypeCode.TimeDelta64` +2. Store as Int64 internally with unit metadata +3. Implement unit conversion +4. Support ISO 8601 string parsing +5. Handle NaT values +6. Implement arithmetic operations with unit rules + +### Potential C# Mapping + +```csharp +// datetime64 could map to: +DateTimeOffset // for absolute time with timezone +DateTime // for naive datetime + +// timedelta64 could map to: +TimeSpan // for durations +``` + +## References + +- [NEP 7 Full Text](https://numpy.org/neps/nep-0007-datetime-proposal.html) +- [NumPy datetime64 docs](https://numpy.org/doc/stable/reference/arrays.datetime.html) diff --git a/docs/numpy/neps/NEP10.md b/docs/numpy/neps/NEP10.md new file mode 100644 index 000000000..2f34bbe4e --- /dev/null +++ b/docs/numpy/neps/NEP10.md @@ -0,0 +1,154 @@ +# NEP 10 - Optimizing Iterator/UFunc Performance + +**Status:** Final +**NumSharp Impact:** HIGH - Core optimization patterns for array iteration + +## Summary + +Introduces advanced iterator optimizations that significantly improve ufunc performance, especially for non-contiguous arrays. + +## Key Optimizations + +### 1. Cache-Coherency (order='K') + +New memory layout option that preserves input layout instead of forcing C-contiguous: + +```python +# Memory layout options +NPY_ANYORDER = -1 # F if all inputs F, else C +NPY_CORDER = 0 # C-contiguous (row-major) +NPY_FORTRANORDER = 1 # Fortran-contiguous (column-major) +NPY_KEEPORDER = 2 # Match input layout (NEW) +``` + +**Performance impact:** +```python +a = np.arange(1000000).reshape(10,10,10,10,10,10) +timeit a + a.copy() # 28.5 ms (C-contiguous) +timeit a.T + a.T.copy() # 237 ms (8.3x slower without order='K') +``` + +### 2. Dimension Coalescing + +Merge adjacent dimensions when memory is contiguous: +``` +If strides[i+1] * shape[i+1] == strides[i]: + Merge dimensions i and i+1 +``` + +Enables single-loop iteration instead of nested loops. + +### 3. Inner Loop Specialization + +- Load constants once instead of repeatedly +- SSE/SIMD for aligned data +- Reduction operation optimizations + +## Casting Modes + +```c +typedef enum { + NPY_NO_CASTING = 0, // Identical types only + NPY_EQUIV_CASTING = 1, // + byte-swapped + NPY_SAFE_CASTING = 2, // Safe casts only + NPY_SAME_KIND_CASTING = 3, // + same-kind casts + NPY_UNSAFE_CASTING = 4 // Any casts +} NPY_CASTING; +``` + +## Performance Examples + +### Image Compositing (19x speedup) +```python +# Poor memory layout: 3.51s +# With buffered iterator: 180ms +``` + +### Python-Level UFunc (2.3x speedup) +```python +# Standard: 138ms +timeit 3*a + b - (a/c) + +# Lambda UFunc with iterator: 60.9ms +timeit luf(lambda a,b,c: 3*a + b - (a/c), a, b, c) +``` + +## NumSharp Implementation Patterns + +### 1. Layout Detection + +```csharp +public enum ArrayOrder { + C, // Row-major (default) + Fortran, // Column-major + Any, // F if all F, else C + Keep // Match input layout +} + +public bool IsContiguous(ArrayOrder order) { + // Check if strides match expected layout +} +``` + +### 2. Dimension Coalescing + +```csharp +public (int[] shape, int[] strides) CoalesceDimensions() { + var newShape = new List(); + var newStrides = new List(); + + for (int i = 0; i < NDim; i++) { + if (i > 0 && CanCoalesce(i-1, i)) { + // Merge with previous dimension + newShape[^1] *= Dimensions[i]; + } else { + newShape.Add(Dimensions[i]); + newStrides.Add(Strides[i]); + } + } + return (newShape.ToArray(), newStrides.ToArray()); +} + +bool CanCoalesce(int i, int j) { + return Strides[i] == Strides[j] * Dimensions[j]; +} +``` + +### 3. Iterator with Buffering + +```csharp +public class BufferedIterator { + private readonly T[] _buffer; + private readonly int _bufferSize; + + public void Iterate(NDArray arr, Action> process) { + // Copy chunks to buffer for cache-friendly access + // Process buffer + // Copy back if needed + } +} +``` + +### 4. Keep-Order Output Allocation + +```csharp +public NDArray AllocateOutput(params NDArray[] inputs) { + // Determine best output layout from inputs + var order = DetermineOptimalOrder(inputs); + return np.empty(shape, dtype, order); +} +``` + +## Key Takeaways + +| Optimization | When to Use | Speedup | +|--------------|-------------|---------| +| order='K' | Non-contiguous inputs | Up to 8x | +| Dimension coalescing | Many small dimensions | 2-4x | +| Buffering | Poor memory layout | Up to 20x | +| Inner specialization | Repeated operations | 2-3x | + +## References + +- [NEP 10 Full Text](https://numpy.org/neps/nep-0010-new-iterator-ufunc.html) +- `src/NumSharp.Core/Backends/Iterators/NDIterator.cs` diff --git a/docs/numpy/neps/NEP13.md b/docs/numpy/neps/NEP13.md new file mode 100644 index 000000000..320aa12ca --- /dev/null +++ b/docs/numpy/neps/NEP13.md @@ -0,0 +1,65 @@ +# NEP 13 - A Mechanism for Overriding Ufuncs + +**Status:** Final +**NumSharp Impact:** LOW (Python-specific) - Informational only + +## Summary + +Defines `__array_ufunc__`, a special method allowing classes to override NumPy ufunc behavior. This is Python's duck-typing mechanism. + +## What is `__array_ufunc__`? + +A Python protocol enabling custom array types to intercept and customize ufunc operations. + +```python +def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): + """ + ufunc: The ufunc object (e.g., np.add) + method: How called: "__call__", "reduce", "accumulate", etc. + inputs: Positional arguments + kwargs: Keyword arguments + """ +``` + +## Why This Matters for NumSharp (Informational) + +### Python Duck Typing + +This protocol enables: +- CuPy arrays to work with NumPy operations +- Dask arrays to work with NumPy operations +- Custom array types in the NumPy ecosystem + +### C# Equivalent + +C# doesn't have this dynamic dispatch. Instead, NumSharp uses: +1. **Interface-based polymorphism** +2. **Generic methods with type constraints** +3. **Runtime type checking** + +```csharp +// NumSharp pattern +public static NDArray Add(NDArray a, NDArray b) { + // Type-check and dispatch + return a.TensorEngine.Add(a, b); +} +``` + +### No Direct Implementation Needed + +NumSharp doesn't need to implement `__array_ufunc__` because: +1. It's a Python-specific protocol +2. C# has different extensibility mechanisms +3. NumSharp is the primary array type (not integrating with others) + +## Understanding NumPy's Design + +This NEP helps understand why NumPy: +- Has a `TensorEngine` abstraction +- Separates operation dispatch from implementation +- Supports multiple backend implementations + +## References + +- [NEP 13 Full Text](https://numpy.org/neps/nep-0013-ufunc-overrides.html) +- Related: NEP 18 (array function protocol) diff --git a/docs/numpy/neps/NEP18.md b/docs/numpy/neps/NEP18.md new file mode 100644 index 000000000..8fcd3675e --- /dev/null +++ b/docs/numpy/neps/NEP18.md @@ -0,0 +1,83 @@ +# NEP 18 - A Dispatch Mechanism for NumPy's High Level Array Functions + +**Status:** Final +**NumSharp Impact:** LOW (Python-specific) - Informational only + +## Summary + +Defines `__array_function__`, a protocol enabling arguments of NumPy functions to define how those functions operate. Complements NEP 13 for non-ufunc functions. + +## What is `__array_function__`? + +A dispatch mechanism for NumPy's general-purpose functions (not ufuncs): + +```python +def __array_function__(self, func, types, args, kwargs): + """ + func: NumPy function being called + types: Collection of argument types + args: Original positional arguments + kwargs: Original keyword arguments + """ +``` + +## Functions Affected + +### Dispatched via `__array_function__` +- `np.concatenate`, `np.stack`, `np.broadcast_to` +- `np.mean`, `np.sum`, `np.prod` +- `np.tensordot`, matrix operations +- Most array-processing functions + +### NOT Dispatched (use other protocols) +- **Ufuncs:** Use `__array_ufunc__` (NEP 13) +- **`np.array()`, `np.asarray()`:** Explicit coercion +- **Methods:** On RandomState, etc. + +## Why This Matters for NumSharp (Informational) + +### Python Ecosystem Integration + +This enables: +```python +# Generic code works with any compliant array +def f(x): + y = np.tensordot(x, x.T) # Dispatches via __array_function__ + return np.mean(np.exp(y)) # Mixed protocols +``` + +### NumSharp Architecture Insight + +NumSharp's `TensorEngine` abstraction serves similar purpose: + +```csharp +public abstract class TensorEngine { + public abstract NDArray Sum(NDArray a, int? axis); + public abstract NDArray Mean(NDArray a, int? axis); + public abstract NDArray Concatenate(NDArray[] arrays, int axis); +} +``` + +The difference: +- Python: Runtime dispatch via special methods +- C#: Compile-time dispatch via abstract methods + +## Supported Array Implementations + +Libraries using this protocol: +- **CuPy** - GPU arrays +- **Dask** - Parallel/distributed arrays +- **scipy.sparse** - Sparse arrays +- **XArray** - Labeled arrays + +## No Direct Implementation Needed + +NumSharp doesn't implement `__array_function__` because: +1. Python-specific protocol +2. NumSharp IS the primary array implementation +3. C# uses different extensibility patterns + +## References + +- [NEP 18 Full Text](https://numpy.org/neps/nep-0018-array-function-protocol.html) +- Related: NEP 13 (ufunc overrides) diff --git a/docs/numpy/neps/NEP19.md b/docs/numpy/neps/NEP19.md new file mode 100644 index 000000000..35020e017 --- /dev/null +++ b/docs/numpy/neps/NEP19.md @@ -0,0 +1,93 @@ +# NEP 19 - Random Number Generator Policy + +**Status:** Final +**NumSharp Impact:** HIGH - NumSharp claims 1-to-1 seed/state matching with NumPy + +## Summary + +Defines the new `Generator` API and establishes policy for RNG stream compatibility. + +## Key Policy Change + +**NumPy no longer guarantees stream compatibility across versions.** + +> "The standard practice now for bit-for-bit reproducible research is to pin all of the versions of code of your software stack." + +## Two RNG APIs + +### Legacy: `RandomState` +```python +np.random.seed(42) +np.random.random() +np.random.normal() +``` +- Fixed behavior for backwards compatibility +- Stream compatibility maintained within major versions +- Use for: unit testing, legacy code + +### New: `Generator` +```python +from numpy.random import Generator, MT19937 +rng = Generator(MT19937(42)) +rng.random() +rng.standard_normal() +``` +- No stream compatibility guarantee +- Allows algorithm improvements +- Use for: new code, best practices + +## BitGenerator Infrastructure + +BitGenerators are the core PRNG algorithms. Examples: +- `MT19937` - Mersenne Twister (legacy default) +- `PCG64` - Permuted Congruential Generator (new default) +- `Philox` - Counter-based RNG +- `SFC64` - Small Fast Chaotic + +### Stream-Compatibility Guarantees (within version) + +Only these methods are guaranteed stable: +```python +bg.bytes() # Raw byte output +bg.integers() # Integer generation +bg.random() # Uniform [0,1) floats +``` + +## NumSharp Implementation Notes + +NumSharp's `np.random` module in `RandomSampling/` claims 1-to-1 matching. + +### What This Means + +1. **Match legacy `RandomState` behavior** - for compatibility with existing NumPy code +2. **Same seed → same sequence** - critical for reproducibility +3. **Algorithm-specific** - must use same PRNG algorithm (likely MT19937) + +### Verification Approach + +```python +# Python +np.random.seed(42) +expected = [np.random.random() for _ in range(10)] +``` + +```csharp +// C# +np.random.seed(42); +var actual = Enumerable.Range(0, 10).Select(_ => np.random.random()).ToArray(); +// actual should match expected exactly +``` + +### Implemented Distributions + +- `rand`, `randn` - uniform, normal +- `randint` - integers +- `uniform`, `choice`, `shuffle`, `permutation` +- `beta`, `binomial`, `gamma`, `poisson` +- `exponential`, `geometric`, `lognormal` +- `chisquare`, `bernoulli` + +## References + +- [NEP 19 Full Text](https://numpy.org/neps/nep-0019-rng-policy.html) +- `src/NumSharp.Core/RandomSampling/` diff --git a/docs/numpy/neps/NEP20.md b/docs/numpy/neps/NEP20.md new file mode 100644 index 000000000..318ef345c --- /dev/null +++ b/docs/numpy/neps/NEP20.md @@ -0,0 +1,144 @@ +# NEP 20 - Expansion of Generalized Universal Function Signatures + +**Status:** Final +**NumSharp Impact:** MEDIUM - Extends NEP 5 gufunc signatures + +## Summary + +Adds two signature enhancements to generalized ufuncs: +1. **Frozen dimensions** - Fixed size requirements (e.g., size-3 for cross product) +2. **Flexible dimensions** - Optional dimensions that can be absent + +## Signature Syntax + +``` + ::= + ::= variable_name | integer + ::= "" | "?" +``` + +## Frozen (Fixed-Size) Dimensions + +Use integer instead of variable name to require specific size. + +### Examples + +| Signature | Description | +|-----------|-------------| +| `()->(2)` | Polar angle → 2D cartesian unit vector | +| `(3),(3)->(3)` | Cross product of two 3-vectors | +| `(),()->(3)` | Two angles → 3D unit vector | + +### Implementation + +```csharp +// Validate frozen dimensions +public void ValidateFrozenDimension(int axis, int requiredSize) { + if (Shape[axis] != requiredSize) { + throw new ArgumentException( + $"Axis {axis} must have size {requiredSize}, got {Shape[axis]}"); + } +} + +// Cross product requires size 3 +public static NDArray Cross(NDArray a, NDArray b) { + a.ValidateFrozenDimension(-1, 3); + b.ValidateFrozenDimension(-1, 3); + // ... implementation +} +``` + +## Flexible (Optional) Dimensions + +Suffix with `?` to make dimension optional. + +### Matrix Multiplication Example + +**Signature:** `(m?,n),(n,p?)->(m?,p?)` + +This single signature covers four cases: + +| Case | Input Shapes | Output Shape | +|------|--------------|--------------| +| matrix × matrix | `(m,n),(n,p)` | `(m,p)` | +| vector × matrix | `(n),(n,p)` | `(p)` | +| matrix × vector | `(m,n),(n)` | `(m)` | +| vector × vector | `(n),(n)` | `()` (scalar) | + +### Implementation + +```csharp +// Handle optional dimensions in matmul +public static NDArray Matmul(NDArray a, NDArray b) { + bool aIsVector = a.NDim == 1; + bool bIsVector = b.NDim == 1; + + // Expand vectors to 2D for computation + var a2d = aIsVector ? a.reshape(1, -1) : a; + var b2d = bIsVector ? b.reshape(-1, 1) : b; + + // Compute matrix product + var result = MatrixProduct(a2d, b2d); + + // Squeeze output based on input shapes + if (aIsVector && bIsVector) return result.squeeze(); // scalar + if (aIsVector) return result.squeeze(axis: 0); // (p,) + if (bIsVector) return result.squeeze(axis: -1); // (m,) + return result; // (m,p) +} +``` + +## NumSharp Functions Affected + +| Function | Signature | Frozen | Flexible | +|----------|-----------|--------|----------| +| `np.cross` | `(3),(3)->(3)` | Yes (size 3) | No | +| `np.dot` | `(n),(n)->()` | No | No | +| `np.matmul` | `(m?,n),(n,p?)->(m?,p?)` | No | Yes | +| `np.inner` | `(n),(n)->()` | No | No | +| `np.outer` | `(m),(n)->(m,n)` | No | No | + +## Validation Patterns + +### Frozen Dimension Check + +```csharp +public static void ValidateSignature( + string signature, + params NDArray[] arrays) +{ + // Parse signature for frozen dimensions + // e.g., "(3),(3)->(3)" requires size 3 + + var frozenDims = ParseFrozenDimensions(signature); + foreach (var (arrayIdx, axis, size) in frozenDims) { + if (arrays[arrayIdx].Shape[axis] != size) { + throw new ValueError( + $"Input {arrayIdx} axis {axis} must be {size}"); + } + } +} +``` + +### Flexible Dimension Handling + +```csharp +public static (NDArray[], int[]) PrepareFlexibleInputs( + string signature, + params NDArray[] arrays) +{ + var squeezedAxes = new List(); + var prepared = new List(); + + // Identify which flexible dims are missing + // Expand missing dims to size 1 + // Track which to squeeze in output + + return (prepared.ToArray(), squeezedAxes.ToArray()); +} +``` + +## References + +- [NEP 20 Full Text](https://numpy.org/neps/nep-0020-gufunc-signature-enhancement.html) +- [NEP 5 - Basic gufuncs](NEP05.md) diff --git a/docs/numpy/neps/NEP21.md b/docs/numpy/neps/NEP21.md new file mode 100644 index 000000000..2813b759d --- /dev/null +++ b/docs/numpy/neps/NEP21.md @@ -0,0 +1,153 @@ +# NEP 21 - Simplified and Explicit Advanced Indexing + +**Status:** Deferred +**NumSharp Impact:** MEDIUM - Documents indexing semantics issues + +## Summary + +Proposes explicit `oindex` (outer) and `vindex` (vectorized) indexing to resolve confusing advanced indexing behavior. Though deferred, it documents important edge cases NumSharp should handle correctly. + +## The Three Problems + +### 1. Outer vs. Vectorized Ambiguity + +For `x[[0, 1], [0, 1]]` on a 2D array: + +| Mode | Result | Shape | +|------|--------|-------| +| **Outer** (intuitive) | All combinations | `(2, 2)` | +| **Vectorized** (NumPy) | Diagonal elements | `(2,)` | + +```python +x = np.arange(9).reshape(3, 3) +# [[0, 1, 2], +# [3, 4, 5], +# [6, 7, 8]] + +# What users often expect (outer): +# [[x[0,0], x[0,1]], +# [x[1,0], x[1,1]]] +# = [[0, 1], [3, 4]] + +# What NumPy does (vectorized): +x[[0, 1], [0, 1]] # = [x[0,0], x[1,1]] = [0, 4] +``` + +### 2. Confusing Mixed Indexing Transpose + +```python +arr = np.zeros((X, Y, Z)) # 3D array + +arr[:, [0,1], 0].shape # (X, 2) - intuitive +arr[[0,1], 0, :].shape # (2, Z) - intuitive +arr[0, :, [0,1]].shape # (2, Y) NOT (Y, 2) - surprising! +``` + +### 3. Difficulty for Other Libraries + +Dask, h5py, xarray struggle to implement NumPy indexing consistently. + +## Proposed Solution (Deferred) + +### `arr.oindex[...]` - Outer/Orthogonal Indexing + +Array indices behave like slices - result axes where indices appear: + +```python +arr.oindex[:, [0], [0, 1], :].shape # (5, 1, 2, 8) +arr.oindex[:, [0], :, [0, 1]].shape # (5, 1, 7, 2) +``` + +### `arr.vindex[...]` - Vectorized Indexing (Explicit) + +Array indices broadcast together, **result always at front**: + +```python +arr.vindex[:, [0], [0, 1], :].shape # (2, 5, 8) +arr.vindex[:, [0], :, [0, 1]].shape # (2, 5, 7) +``` + +## NumSharp Current Behavior + +NumSharp should match NumPy's current (vectorized) behavior: + +```csharp +var arr = np.arange(9).reshape(3, 3); +var idx = np.array(new[] { 0, 1 }); + +// This should return diagonal: [0, 4] +var result = arr[idx, idx]; // Vectorized indexing +``` + +### Implementation Considerations + +```csharp +public NDArray this[params NDArray[] indices] { + get { + if (HasMultipleArrayIndices(indices)) { + // Vectorized indexing: broadcast and zip + return VectorizedIndex(indices); + } else { + // Simple indexing + return SimpleIndex(indices); + } + } +} + +private NDArray VectorizedIndex(NDArray[] indices) { + // 1. Broadcast all array indices to common shape + var broadcastedIndices = np.broadcast_arrays(indices); + + // 2. Iterate through broadcast shape + // 3. Gather elements at (idx0[i], idx1[i], ...) + + // Result shape: broadcast shape (placed where array indices are) +} +``` + +### Edge Case: Mixed Slices and Arrays + +The confusing transpose behavior: + +```csharp +// arr[0, :, [0,1]] should have shape (2, Y) not (Y, 2) +// This is because array index results go to front when separated by slice +``` + +Rule: When array indices are **separated** by slices, their result dimensions are transposed to the front. + +## Behavior Reference Table + +| Expression | Shape | Explanation | +|------------|-------|-------------| +| `arr[0, 1, 2]` | `()` | Scalar | +| `arr[0, :, 2]` | `(Y,)` | Slice in middle | +| `arr[[0,1], 0, 0]` | `(2,)` | Array index first | +| `arr[0, [0,1], 0]` | `(2,)` | Array index middle | +| `arr[0, 0, [0,1]]` | `(2,)` | Array index last | +| `arr[[0,1], :, 0]` | `(2, Y)` | Array, slice, int | +| `arr[0, :, [0,1]]` | `(2, Y)` | **Confusing!** Array at end, but result at front | +| `arr[:, [0,1], :]` | `(X, 2, Z)` | Array in middle, stays there | + +## Workaround for Outer Indexing + +Until `oindex` is implemented, use `np.ix_`: + +```python +# Outer indexing workaround +rows = [0, 1] +cols = [0, 1] +result = arr[np.ix_(rows, cols)] # Shape (2, 2) +``` + +```csharp +// NumSharp equivalent +var rows = np.array(new[] { 0, 1 }); +var cols = np.array(new[] { 0, 1 }); +var result = arr[np.ix_(rows, cols)]; // Shape (2, 2) +``` + +## References + +- [NEP 21 Full Text](https://numpy.org/neps/nep-0021-advanced-indexing.html) +- `src/NumSharp.Core/Selection/NDArray.Indexing.Selection.cs` diff --git a/docs/numpy/neps/NEP27.md b/docs/numpy/neps/NEP27.md new file mode 100644 index 000000000..d4be48279 --- /dev/null +++ b/docs/numpy/neps/NEP27.md @@ -0,0 +1,99 @@ +# NEP 27 - Zero Rank Arrays + +**Status:** Final (Informational) +**NumSharp Impact:** HIGH - Affects scalar handling throughout the library + +## Summary + +Documents the behavior and rationale of zero-rank arrays (`shape=()`), which represent scalar quantities as arrays. + +## What are Zero-Rank Arrays? + +Arrays with no dimensions: +```python +>>> x = np.array(1) +>>> x.shape +() +>>> x.ndim +0 +``` + +## Zero-Rank vs Array Scalars vs Python Scalars + +| Feature | Zero-Rank Array | Array Scalar | Python Scalar | +|---------|-----------------|--------------|---------------| +| Type | `ndarray` | e.g., `np.int64` | `int`, `float` | +| Mutable | Yes | No | N/A | +| Has `.shape` | Yes `()` | Yes `()` | No | +| Can be output buffer | Yes | No | No | +| Shares memory | Can | Cannot | N/A | + +## Indexing Zero-Rank Arrays + +```python +>>> x = np.array(1) +>>> x[...] # Returns scalar, not array +1 +>>> x[()] # Same as above +1 +>>> x[np.newaxis] # Adds dimension +array([1]) +``` + +## Critical Use Cases + +### 1. Output Arguments +Zero-rank arrays can be used as output buffers (scalars cannot): +```python +>>> y = np.int_(5) +>>> np.add(5, 5, y) # TypeError - scalar can't be output + +>>> x = np.array(10) +>>> np.add(5, 5, x) # Works - zero-rank array is valid output +array(10) +``` + +### 2. Shared Memory Views +```python +>>> x = np.array([1, 2]) +>>> y = x[1:2] +>>> y.shape = () # Reshape to zero-rank +>>> y +array(2) +>>> x[1] = 20 +>>> y # Reflects change +array(20) +``` + +### 3. Generic Code +Zero-rank arrays allow writing code that works uniformly across all array ranks. + +## NumSharp Implementation Notes + +### Current Behavior +NumSharp's `Shape` class supports zero-rank: +```csharp +var shape = new Shape(); // shape.NDim == 0, shape.Size == 1 +var scalar = np.array(5); // Creates zero-rank array +``` + +### Key Considerations + +1. **Indexing:** `arr[...]` and `arr[()]` should return scalar value, not array +2. **Operations:** All operations must handle zero-rank input gracefully +3. **Broadcasting:** Zero-rank arrays broadcast to any shape +4. **Type preservation:** Zero-rank arrays maintain dtype + +### Related Shape Properties + +```csharp +shape.IsScalar // True for shape () +shape.IsEmpty // False for scalars (size > 0) +shape.NDim // 0 for scalars +shape.Size // 1 for scalars +``` + +## References + +- [NEP 27 Full Text](https://numpy.org/neps/nep-0027-zero-rank-arrarys.html) +- `src/NumSharp.Core/View/Shape.cs` diff --git a/docs/numpy/neps/NEP32.md b/docs/numpy/neps/NEP32.md new file mode 100644 index 000000000..ff895be7e --- /dev/null +++ b/docs/numpy/neps/NEP32.md @@ -0,0 +1,62 @@ +# NEP 32 - Remove Financial Functions + +**Status:** Final +**NumSharp Impact:** LOW - NumSharp should NOT implement these functions + +## Summary + +Removed 10 financial functions from NumPy as they were too specialized and not part of NumPy's core mission. + +## Removed Functions + +| Function | Description | +|----------|-------------| +| `fv` | Future value | +| `ipmt` | Interest payment | +| `irr` | Internal rate of return | +| `mirr` | Modified internal rate of return | +| `nper` | Number of periods | +| `npv` | Net present value | +| `pmt` | Payment | +| `ppmt` | Principal payment | +| `pv` | Present value | +| `rate` | Rate of return | + +## Timeline + +- **NumPy 1.18:** Functions deprecated with warnings +- **NumPy 1.20:** Functions removed from NumPy + +## Replacement + +Functions moved to separate package: **`numpy-financial`** + +```bash +pip install numpy-financial +``` + +```python +# Old +from numpy import npv, irr, pmt + +# New +from numpy_financial import npv, irr, pmt +``` + +## NumSharp Implications + +**DO NOT IMPLEMENT** these functions in NumSharp. + +If users need financial functions, they should use a dedicated C# financial library instead of expecting NumSharp to provide them. + +### Rationale + +1. Outside NumSharp's scope (array operations, not domain-specific calculations) +2. Real financial calculations need proper date/calendar handling +3. Low usage in Python NumPy (only 8 GitHub repos found using them) +4. Maintenance burden without core team interest + +## References + +- [NEP 32 Full Text](https://numpy.org/neps/nep-0032-remove-financial-functions.html) +- [numpy-financial package](https://pypi.org/project/numpy-financial/) diff --git a/docs/numpy/neps/NEP34.md b/docs/numpy/neps/NEP34.md new file mode 100644 index 000000000..eb1326485 --- /dev/null +++ b/docs/numpy/neps/NEP34.md @@ -0,0 +1,83 @@ +# NEP 34 - Disallow Inferring dtype=object from Sequences + +**Status:** Final +**NumSharp Impact:** MEDIUM - Affects array creation from ragged sequences + +## Summary + +NumPy no longer silently creates `dtype=object` arrays from ragged nested sequences. Instead, it raises `ValueError`. + +## Behavior Change + +### Old Behavior (Pre-NEP 34) +```python +>>> np.array([[1, 2], [1]]) +array([[1, 2], [1]], dtype=object) # Silent object dtype +``` + +### New Behavior (Post-NEP 34) +```python +>>> np.array([[1, 2], [1]]) +ValueError: cannot guess the desired dtype from the input +``` + +## When ValueError is Raised + +1. **Ragged nested sequences:** + ```python + np.array([[1, 2], [1]]) # Different lengths + ``` + +2. **Mixed sequences and non-sequences:** + ```python + np.array([np.arange(10), [10]]) + ``` + +3. **Mixed sequence types within sequences:** + ```python + np.array([[range(3), range(3)], [range(3), 0]]) + ``` + +## Explicit Object Dtype + +Users who intentionally want object arrays must explicitly request them: + +```python +# Explicit dtype=object works +np.array([[1, 2], [1]], dtype=object) + +# For structured object arrays +arr = np.empty(correct_shape, dtype=object) +arr[...] = values +``` + +## NumSharp Implementation + +### Current Behavior Check + +Verify NumSharp's `np.array()` behavior with ragged sequences: +```csharp +// Should this throw or create object array? +var arr = np.array(new object[] { + new int[] { 1, 2 }, + new int[] { 1 } +}); +``` + +### Recommended Approach + +1. **Detect ragged sequences** during array creation +2. **Throw `ArgumentException`** if shapes don't match +3. **Allow explicit `dtype: NPTypeCode.Object`** to override + +### Why This Matters + +Prevents silent errors where users accidentally: +- Pass mismatched sequence lengths +- Get unexpected object dtype instead of numeric +- Experience poor performance (object arrays are slow) + +## References + +- [NEP 34 Full Text](https://numpy.org/neps/nep-0034-infer-dtype-is-object.html) +- `src/NumSharp.Core/Creation/np.array.cs` diff --git a/docs/numpy/neps/NEP38.md b/docs/numpy/neps/NEP38.md new file mode 100644 index 000000000..f387d3370 --- /dev/null +++ b/docs/numpy/neps/NEP38.md @@ -0,0 +1,156 @@ +# NEP 38 - Using SIMD Optimization Instructions for Performance + +**Status:** Final +**NumSharp Impact:** HIGH - Relevant to issues #544, #545 (SIMD optimization) + +## Summary + +Defines NumPy's SIMD infrastructure using "universal intrinsics" that abstract SIMD operations across CPU architectures, with runtime dispatch to select optimal implementations. + +## Three-Stage Mechanism + +1. **Infrastructure:** Abstract intrinsics in code, extending ufunc machinery +2. **Compile-time:** Compiler macros convert abstract intrinsics to concrete calls +3. **Runtime:** CPU detection selects optimal loop for each ufunc + +## Universal Intrinsics Concept + +Abstract SIMD operations that map to platform-specific implementations: + +| Universal Intrinsic | ARM NEON | x86 AVX2 | x86 AVX-512 | +|---------------------|----------|----------|-------------| +| `npyv_load_u32` | `vld1q_u32` | `_mm256_loadu_si256` | `_mm512_loadu_si512` | +| `npyv_add_f32` | `vaddq_f32` | `_mm256_add_ps` | `_mm512_add_ps` | +| `npyv_mul_f64` | `vmulq_f64` | `_mm256_mul_pd` | `_mm512_mul_pd` | + +## Supported Instruction Sets + +### x86_64 (Default baseline: SSE3) +``` +SSE3, SSSE3, SSE41, SSE42, POPCNT, AVX, F16C, XOP, FMA4, FMA3, +AVX2, AVX512F, AVX512CD, AVX512_KNL, AVX512_KNM, AVX512_SKX, +AVX512_CLX, AVX512_CNL, AVX512_ICL +``` + +### Other Architectures +- **ARM:** NEON +- **PowerPC:** VSX +- **s390x:** VX/VXE/VXE2 + +## Runtime Dispatch + +### CPU Feature Detection +```c +// C-level boolean array +extern bool npy__cpu_have[NPY_CPU_FEATURE_MAX]; + +// Query function +bool npy_cpu_have(int feature_id); +``` + +### Python API +```python +import numpy as np +np.__cpu_features__ # Dict of feature → bool +# {'SSE': True, 'SSE2': True, 'AVX2': True, 'AVX512F': False, ...} +``` + +### Loop Selection +At import time, NumPy selects the best available loop for each ufunc based on runtime CPU capabilities. + +## Build Configuration + +### `--cpu-baseline` +Minimum required features (default x86_64: SSE3) + +### `--cpu-dispatch` +Additional features to compile dispatch variants for + +```bash +# Build with specific dispatch targets +python setup.py build --cpu-dispatch="AVX2 AVX512F" +``` + +## NumSharp Relevance + +### Current State +NumSharp uses scalar loops. SIMD would significantly improve: +- Element-wise operations (+, -, *, /) +- Reductions (sum, mean, min, max) +- Comparisons +- Mathematical functions + +### Implementation Options for C# + +#### Option 1: System.Numerics.Vector +```csharp +// .NET's portable SIMD +using System.Numerics; + +public static void Add(float[] a, float[] b, float[] result) { + int simdLength = Vector.Count; + int i = 0; + for (; i <= a.Length - simdLength; i += simdLength) { + var va = new Vector(a, i); + var vb = new Vector(b, i); + (va + vb).CopyTo(result, i); + } + // Scalar remainder + for (; i < a.Length; i++) { + result[i] = a[i] + b[i]; + } +} +``` + +#### Option 2: System.Runtime.Intrinsics (.NET Core 3.0+) +```csharp +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; + +public static unsafe void AddAvx(float* a, float* b, float* result, int length) { + if (Avx.IsSupported) { + int i = 0; + for (; i <= length - 8; i += 8) { + var va = Avx.LoadVector256(a + i); + var vb = Avx.LoadVector256(b + i); + Avx.Store(result + i, Avx.Add(va, vb)); + } + // Scalar remainder + } +} +``` + +#### Option 3: Native Libraries +- Intel MKL via P/Invoke +- OpenBLAS +- Custom C/C++ with SIMD + +### Priority Operations for SIMD + +| Operation | Potential Speedup | Complexity | +|-----------|-------------------|------------| +| Element-wise arithmetic | 4-8x | Low | +| Reductions (sum, mean) | 2-4x | Medium | +| Dot product / matmul | 4-16x | High | +| Transcendentals (exp, log) | 2-4x | High | + +## Design Principles (from NumPy) + +| Aspect | NumPy Approach | +|--------|----------------| +| **Correctness** | Max 1-3 ULP accuracy loss | +| **Code Bloat** | Minimize source and binary size | +| **Maintainability** | Prefer universal intrinsics | +| **Performance** | Require benchmarks showing significant boost | + +## References + +- [NEP 38 Full Text](https://numpy.org/neps/nep-0038-SIMD-optimizations.html) +- [NumPy SIMD docs](https://numpy.org/doc/stable/reference/simd/index.html) +- [.NET Vector docs](https://docs.microsoft.com/dotnet/api/system.numerics.vector-1) +- [.NET Intrinsics docs](https://docs.microsoft.com/dotnet/api/system.runtime.intrinsics) + +## Related Issues + +- #544 - SIMD optimization tracking +- #545 - SIMD implementation diff --git a/docs/numpy/neps/NEP42.md b/docs/numpy/neps/NEP42.md new file mode 100644 index 000000000..a19dfaafe --- /dev/null +++ b/docs/numpy/neps/NEP42.md @@ -0,0 +1,107 @@ +# NEP 42 - New and Extensible DTypes + +**Status:** Accepted (Implementation in Progress) +**NumSharp Impact:** INFORMATIONAL - Informs future dtype architecture + +## Summary + +Proposes a modular, class-based architecture for NumPy dtypes, enabling user-defined custom dtypes with full functionality. + +## Key Changes + +### From Monolithic to Modular +- Each dtype becomes an instance of a DType subclass +- `np.dtype("float64")` returns instance of `Float64` class +- User-extensible through subclassing + +### DType Hierarchy + +``` +numpy.dtype (base) +├── Abstract dtypes (cannot be instantiated) +│ ├── Integer +│ ├── Floating +│ ├── Complex +│ └── User abstract (e.g., Unit, Categorical) +│ +└── Concrete dtypes (can be instantiated, cannot be subclassed) + ├── Float64 + ├── Int32 + ├── String + └── User concrete (e.g., Float64Unit) +``` + +### Class Getter Syntax +```python +np.dtype[np.int64] # Get DType class for int64 +np.dtype[UserScalar] # Works with user-defined scalars +``` + +## User-Defined DType API + +### Basic Structure +```python +class DType(np.dtype): + type : type # Python scalar type + parametric : bool # Whether dtype has parameters + + @property + def canonical(self) -> bool: ... + + def ensure_canonical(self) -> DType: ... +``` + +### Casting Methods +```python +@classmethod +def common_dtype(cls, other) -> DTypeMeta: ... + +def common_instance(self, other) -> DType: ... +``` + +## NumSharp Relevance + +### Current Architecture +NumSharp uses `NPTypeCode` enum for dtype identification: +```csharp +enum NPTypeCode { + Boolean, Byte, Int16, UInt16, Int32, UInt32, + Int64, UInt64, Char, Single, Double, Decimal +} +``` + +### Potential Future Alignment + +If NumSharp wanted to match NumPy's new dtype system: + +1. **DType Classes:** Create class hierarchy for dtypes + ```csharp + abstract class DType { } + class Float64 : DType { } + class Int32 : DType { } + ``` + +2. **Type Resolution:** Implement `common_dtype` for type promotion + ```csharp + DType CommonDType(DType other); + ``` + +3. **Extensibility:** Allow user-defined dtypes + ```csharp + class QuantityDType : DType { + public Unit Unit { get; } + } + ``` + +### Practical Implications + +For now, NumSharp can continue with `NPTypeCode` enum. The NEP 42 architecture is primarily useful for: +- Understanding NumPy's internal evolution +- Planning future extensibility (e.g., custom dtypes for units, categoricals) +- Ensuring type promotion logic matches NumPy + +## References + +- [NEP 42 Full Text](https://numpy.org/neps/nep-0042-new-dtypes.html) +- [NEP 40 - Legacy dtypes](https://numpy.org/neps/nep-0040-legacy-datatype-impl.html) +- [NEP 41 - First step towards new dtypes](https://numpy.org/neps/nep-0041-improved-dtype-support.html) diff --git a/docs/numpy/neps/NEP43.md b/docs/numpy/neps/NEP43.md new file mode 100644 index 000000000..ab583fdbe --- /dev/null +++ b/docs/numpy/neps/NEP43.md @@ -0,0 +1,154 @@ +# NEP 43 - Enhancing the Extensibility of UFuncs + +**Status:** Draft +**NumSharp Impact:** LOW - Future extensibility patterns + +## Summary + +Proposes `ArrayMethod` objects that encapsulate dtype-specific ufunc implementations, enabling user-defined dtypes to have custom ufunc behavior. + +## Relationship to Other NEPs + +Part of the dtype modernization series: +- **NEP 40:** Documents current dtype shortcomings +- **NEP 41:** Overview of replacement proposal +- **NEP 42:** New dtype APIs (see [NEP42.md](NEP42.md)) +- **NEP 43:** Ufunc APIs for new dtypes (this NEP) + +## Key Concept: ArrayMethod + +Encapsulates dtype-specific ufunc functionality: + +```python +class ArrayMethod: + name: str + casting: str = "no" + + def resolve_descriptors(self, DTypes, given_descrs): + """Determine output dtype parameters""" + # For parametric types like strings: S5 + S4 -> S9 + return (resolved_descrs, casting_safety) + + def strided_inner_loop(context, data, dims, strides): + """The actual computation kernel""" + pass +``` + +## Why This Matters + +### Parametric Types Need Runtime Resolution + +```python +# String concatenation: output length = input1 + input2 +np.add(np.array(["abc"], dtype="S3"), + np.array(["xy"], dtype="S2")) +# Result dtype must be S5, determined at runtime +``` + +### Custom DTypes Need Custom UFuncs + +```python +# Unit type example +class UnitDType: + def __init__(self, unit): + self.unit = unit + +# Adding meters + kilometers requires unit conversion +np.add(UnitDType("m")(1.0), UnitDType("km")(1.0)) +``` + +## NumSharp Relevance + +### Current Architecture + +NumSharp's `TensorEngine` serves a similar purpose: + +```csharp +public abstract class TensorEngine { + public abstract NDArray Add(NDArray a, NDArray b); + public abstract NDArray Multiply(NDArray a, NDArray b); +} +``` + +### Future Considerations + +If NumSharp adds custom dtypes: + +```csharp +// Similar to ArrayMethod concept +public interface ITypeOperation { + NPTypeCode ResolveOutputType(NPTypeCode[] inputs); + void Execute(Span a, Span b, Span output); +} + +// Registration +TensorEngine.RegisterOperation( + OperationType.Add, + new FloatAddOperation() +); +``` + +### Registration Pattern + +```csharp +// Register custom operation for custom dtype +public static void RegisterUFunc( + string ufuncName, + NPTypeCode[] inputTypes, + NPTypeCode outputType, + Delegate implementation) +{ + _ufuncRegistry[(ufuncName, inputTypes)] = (outputType, implementation); +} +``` + +## Key Design Elements + +### 1. Context Object + +Passes dtype metadata to inner loops: + +```csharp +public class UFuncContext { + public NPTypeCode[] InputTypes { get; } + public NPTypeCode OutputType { get; } + public object[] DTypeMetadata { get; } // e.g., string lengths, units +} +``` + +### 2. Promoter Functions + +Handle type promotion when exact match not found: + +```csharp +// Promote int32 to int64 for timedelta operations +public static NPTypeCode PromoteTimedeltaInteger(NPTypeCode[] inputs) { + if (inputs[0] == NPTypeCode.TimeDelta && IsInteger(inputs[1])) { + return NPTypeCode.Int64; + } + return NPTypeCode.NotDefined; +} +``` + +### 3. Existing Loop Wrapping + +Reuse implementations with type adapters: + +```csharp +// Wrap existing float64 implementation for unit types +public class UnitAddOperation : ITypeOperation { + private readonly FloatAddOperation _inner = new(); + + public void Execute(Span a, Span b, Span output) { + // Convert units, call inner, wrap result + var normalized = ConvertUnits(a, b); + _inner.Execute(normalized.a, normalized.b, output.AsFloats()); + ApplyOutputUnit(output); + } +} +``` + +## References + +- [NEP 43 Full Text](https://numpy.org/neps/nep-0043-extensible-ufuncs.html) +- [NEP 42 - New DTypes](NEP42.md) diff --git a/docs/numpy/neps/NEP49.md b/docs/numpy/neps/NEP49.md new file mode 100644 index 000000000..0b7594894 --- /dev/null +++ b/docs/numpy/neps/NEP49.md @@ -0,0 +1,92 @@ +# NEP 49 - Data Allocation Strategies + +**Status:** Final +**NumSharp Impact:** LOW - NumSharp uses unmanaged memory with custom patterns + +## Summary + +Provides mechanism to override memory management strategy for `ndarray.data` with user-provided alternatives. + +## Custom Allocator API + +### C Structure +```c +typedef struct { + void *ctx; + void* (*malloc) (void *ctx, size_t size); + void* (*calloc) (void *ctx, size_t nelem, size_t elsize); + void* (*realloc) (void *ctx, void *ptr, size_t new_size); + void (*free) (void *ctx, void *ptr, size_t size); +} PyDataMemAllocator; +``` + +### Python API +```python +# Set/get allocation handler +np.core.multiarray.set_handler(handler) +np.core.multiarray.get_handler_name(arr) +``` + +## Use Cases + +1. **Data Alignment:** 64-byte alignment for SIMD (40x performance gain) +2. **NUMA Pinning:** Pin to specific cores on multi-socket systems +3. **Memory Profiling:** Integration with tracing tools +4. **Specialized Hardware:** FPGA DMA operations +5. **Huge Pages:** Linux `madvise` for huge page allocation + +## NumSharp Relevance + +### Current Architecture + +NumSharp already uses custom memory management: + +```csharp +// UnmanagedMemoryBlock allocates via Marshal.AllocHGlobal +public unsafe class UnmanagedMemoryBlock { + private T* _address; + + public UnmanagedMemoryBlock(int length) { + _address = (T*)Marshal.AllocHGlobal(length * sizeof(T)); + } +} +``` + +### Potential Enhancements + +If NumSharp wanted similar flexibility: + +```csharp +public interface IMemoryAllocator { + IntPtr Allocate(int size); + IntPtr Reallocate(IntPtr ptr, int newSize); + void Free(IntPtr ptr); +} + +public class AlignedAllocator : IMemoryAllocator { + private readonly int _alignment; // e.g., 64 bytes for AVX-512 + + public IntPtr Allocate(int size) { + // Use NativeMemory.AlignedAlloc in .NET 6+ + return (IntPtr)NativeMemory.AlignedAlloc((nuint)size, (nuint)_alignment); + } +} +``` + +### Current Priority + +**LOW** - NumSharp's current allocation works. Custom allocators would be useful for: +- SIMD-optimized operations (future) +- GPU memory (if CUDA support added) +- Memory-mapped files + +## Key Design Decisions + +- **Handler Lifetime:** Each array carries its allocator +- **Context Variables:** Thread-safe per-coroutine configuration +- **Backward Compatible:** Doesn't break existing code + +## References + +- [NEP 49 Full Text](https://numpy.org/neps/nep-0049-data-allocation-strategies.html) +- `src/NumSharp.Core/Backends/Unmanaged/UnmanagedMemoryBlock.cs` diff --git a/docs/numpy/neps/NEP50.md b/docs/numpy/neps/NEP50.md new file mode 100644 index 000000000..b66958e7f --- /dev/null +++ b/docs/numpy/neps/NEP50.md @@ -0,0 +1,136 @@ +# NEP 50 - Promotion Rules for Python Scalars + +**Status:** Final +**NumSharp Impact:** CRITICAL - Major behavioral change in NumPy 2.0 + +## Summary + +NumPy 2.0 changes how Python scalars (int, float, complex) interact with NumPy arrays in type promotion. Values no longer influence result types. + +## The Two Key Problems Solved + +### Problem 1: Value-Based Promotion (ELIMINATED) + +**Old behavior inspected values:** +```python +np.result_type(np.int8, 1) == np.int8 # 1 fits in int8 +np.result_type(np.int8, 255) == np.int16 # 255 doesn't fit - UPCASTED! +``` + +**New behavior ignores values:** +```python +np.result_type(np.int8, 1) == np.int8 # int8, regardless of value +np.result_type(np.int8, 255) == np.int8 # Still int8! +``` + +### Problem 2: Inconsistent 0-D vs N-D Arrays (FIXED) + +**Old inconsistency:** +```python +np.result_type(np.array(1, dtype=np.uint8), 1) == np.int64 # 0-D +np.result_type(np.array([1], dtype=np.uint8), 1) == np.uint8 # 1-D different! +``` + +**New consistency:** +```python +# Both now return uint8 +np.result_type(np.array(1, dtype=np.uint8), 1) == np.uint8 +np.result_type(np.array([1], dtype=np.uint8), 1) == np.uint8 +``` + +## New "Weak" Scalar Promotion Rules + +Python `int`, `float`, `complex` are treated as "weakly typed": + +```python +np.uint8(1) + 1 == np.uint8(2) # Result is uint8 +np.int16(2) + 2 == np.int16(4) # Result is int16 +np.uint16(3) + 3.0 == np.float64(6.0) # Float promotes to default +np.float32(5) + 5j == np.complex64(5+5j) # Same precision preserved +``` + +### Kind Hierarchy + +**boolean < integral < inexact** + +Cross-kind promotion uses default precision: +- `boolean` + `integral` → `int64` +- `integral` + `inexact` → `float64` or `complex128` +- `float32` + `complex` → `complex64` + +## Breaking Changes Table + +| Expression | NumPy 1.x | NumPy 2.x | Note | +|---|---|---|---| +| `uint8(1) + 2` | `int64(3)` | `uint8(3)` | Honors uint8 | +| `array([1], uint8) + int64(1)` | `uint8` | `int64` | Respects int64 | +| `array([1.], float32) + float64(1.)` | `float32` | `float64` | Respects float64 | +| `uint8(1) + 300` | `int64(301)` | **Exception** | 300 > uint8 max | +| `uint8(100) + 200` | `int64(300)` | `uint8(44)` | Overflow warning | + +## NumSharp Implementation Requirements + +### Current Behavior Audit + +Check NumSharp's `np._FindCommonType` and arithmetic operators: + +```csharp +var a = np.array(new byte[] { 1 }); // uint8 +var b = 300; // C# int +var c = a + b; // What happens? +``` + +### Required Changes + +1. **Value-Independent Promotion:** + ```csharp + // Don't inspect scalar value, only type + NPTypeCode Promote(NPTypeCode arrayType, Type scalarType) { + // scalarType is int/long/float/double, not the actual value + } + ``` + +2. **Weak Scalar Treatment:** + - C# `int` → weakly typed (defers to array dtype if same kind) + - C# `double` → weakly typed for floating arrays + - NumPy scalar types → strongly typed + +3. **Overflow Handling:** + ```csharp + // When Python scalar doesn't fit in target dtype: + // Option A: Throw (matches NumPy for literals) + // Option B: Overflow with warning (matches NumPy for operations) + ``` + +4. **Consistent 0-D and N-D:** + - Zero-rank arrays should behave same as N-D arrays in promotion + +### Type Promotion Matrix + +```csharp +// Weak scalar (C# int) + NumPy array +uint8 + int → uint8 // int defers to array +int16 + int → int16 +float32 + int → float32 + +// NumPy scalar + NumPy array +uint8 + int64 → int64 // int64 is strong +float32 + float64 → float64 + +// Cross-kind (weak scalar) +uint8 + float → float64 // Default float +int32 + complex → complex128 // Default complex +``` + +## Migration Detection + +Test with environment variable (NumPy 1.24+): +```bash +NPY_PROMOTION_STATE=weak_and_warn +``` + +## References + +- [NEP 50 Full Text](https://numpy.org/neps/nep-0050-scalar-promotion.html) +- `src/NumSharp.Core/Utilities/np.find_common_type.cs` +- `src/NumSharp.Core/Operations/Elementwise/` diff --git a/docs/numpy/neps/NEP51.md b/docs/numpy/neps/NEP51.md new file mode 100644 index 000000000..0f73be018 --- /dev/null +++ b/docs/numpy/neps/NEP51.md @@ -0,0 +1,81 @@ +# NEP 51 - Changing the Representation of NumPy Scalars + +**Status:** Accepted +**NumSharp Impact:** LOW - Affects ToString() output only + +## Summary + +Changes how NumPy scalars are displayed in `repr()` to make types explicit. + +## Representation Changes + +### Before (NumPy 1.x) +```python +>>> np.float32(3.0) +3.0 + +>>> np.int64(34) +34 + +>>> np.True_ +True +``` + +### After (NumPy 2.x) +```python +>>> np.float32(3.0) +np.float32(3.0) + +>>> np.int64(34) +np.int64(34) + +>>> np.True_ +np.True_ +``` + +## Affected Types + +| Type | Old repr | New repr | +|------|----------|----------| +| `np.bool_` | `True` | `np.True_` | +| `np.int64` | `34` | `np.int64(34)` | +| `np.float32` | `3.0` | `np.float32(3.0)` | +| `np.complex128` | `(3+4j)` | `np.complex128(3.0+4.0j)` | +| `np.str_` | `'text'` | `np.str_('text')` | + +## Rationale + +1. **Type Awareness:** Makes type distinctions clearer +2. **Behavior Differences:** NumPy scalars differ from Python builtins: + - NumPy integers can overflow (Python cannot) + - Lower precision types need caution + - Division by zero behavior differs +3. **Debugging:** Easier to identify type-related bugs + +## NumSharp Implications + +### Current Behavior + +NumSharp's `ToString()` for scalars likely returns just the value: +```csharp +var x = np.array(3.0f).GetSingle(); // Returns float +Console.WriteLine(x); // "3" +``` + +### Potential Alignment + +If matching NumPy 2.x representation: +```csharp +public override string ToString() { + // For scalar NDArray or typed scalar + return $"np.{TypeName}({Value})"; +} +``` + +### Priority + +**LOW** - This is cosmetic output formatting. Focus on behavioral compatibility first. + +## References + +- [NEP 51 Full Text](https://numpy.org/neps/nep-0051-scalar-representation.html) diff --git a/docs/numpy/neps/NEP52.md b/docs/numpy/neps/NEP52.md new file mode 100644 index 000000000..9666d2d13 --- /dev/null +++ b/docs/numpy/neps/NEP52.md @@ -0,0 +1,142 @@ +# NEP 52 - Python API Cleanup for NumPy 2.0 + +**Status:** Final +**NumSharp Impact:** HIGH - Many functions removed/renamed in NumPy 2.0 + +## Summary + +NumPy 2.0 cleaned up the main namespace, removing ~100 entries including deprecated aliases, redundant functions, and legacy code. + +## Removed/Deprecated Functions + +### Removed Aliases + +| Removed | Use Instead | +|---------|-------------| +| `np.round_` | `np.round` | +| `np.product` | `np.prod` | +| `np.cumproduct` | `np.cumprod` | +| `np.sometrue` | `np.any` | +| `np.alltrue` | `np.all` | +| `np.inf` (8 aliases) | `np.inf` (single) | +| `np.nan` (8 aliases) | `np.nan` (single) | + +### Removed Functions + +| Removed | Replacement | +|---------|-------------| +| `byte_bounds` | (internal use only) | +| `disp` | `print()` | +| `safe_eval` | `ast.literal_eval` | +| `who` | (debugging tool) | +| `maximum_sctype` | Use dtype directly | + +### Removed Namespaces + +| Namespace | Status | +|-----------|--------| +| `np.compat` | Removed (Python 2-3 transition) | +| `numpy.core` | Renamed to `numpy._core` (private) | +| `numpy.version` | Renamed to `numpy._version` | + +## Namespace Reorganization + +### Regular Namespaces (Recommended) +```python +numpy +numpy.exceptions +numpy.fft +numpy.linalg +numpy.polynomial +numpy.random +numpy.testing +numpy.typing +``` + +### Special-Purpose +```python +numpy.array_api +numpy.ctypeslib +numpy.dtypes +numpy.lib.stride_tricks +numpy.rec +``` + +### Legacy (De-emphasized) +```python +numpy.char # Use np.strings instead (NEP 55) +numpy.distutils # Use meson/setuptools +numpy.ma # Masked arrays +numpy.matlib # Matrix library +``` + +## DType Alias Simplification + +### Removed Redundant Aliases + +```python +# These were all equivalent but confusing: +np.float_ # Removed, use np.float64 +np.int_ # Changed meaning +np.complex_ # Removed, use np.complex128 + +# Platform-specific cleanup: +np.float96 # May not exist on all platforms +np.float128 # May not exist on all platforms +``` + +## NumSharp Implementation Checklist + +### Functions to Verify + +Check if NumSharp implements any removed functions: + +- [ ] `np.round_` → should be `np.round` only +- [ ] `np.product` → should be `np.prod` only +- [ ] `np.cumproduct` → should be `np.cumprod` only +- [ ] `np.sometrue` → should be `np.any` only +- [ ] `np.alltrue` → should be `np.all` only + +### NDArray Method Cleanup + +Removed/deprecated methods: +- [ ] `.itemset()` - discouraged +- [ ] `.newbyteorder()` - too niche +- [ ] `.ptp()` - use `np.ptp()` function + +### Namespace Organization + +NumSharp's namespace structure in `APIs/np.cs`: +```csharp +public static partial class np { + // Core functions + public static NDArray array(...) { } + + // Submodules + public static class random { } + public static class linalg { } + public static class fft { } // Does NumSharp have this? +} +``` + +### Dead Code Audit + +Per CLAUDE.md, NumSharp has dead code that should NOT be exposed: +- `np.linalg.norm` - private static (not accessible) +- `nd.inv()` - returns null +- `nd.qr()` - returns default +- `nd.svd()` - returns default +- `nd.lstsq()` - returns null +- `nd.multi_dot()` - returns null +- `np.isnan`, `np.isfinite`, `np.isclose` - return null +- `operator &`, `operator |` - return null + +These should either be: +1. Properly implemented +2. Removed entirely +3. Throw `NotImplementedException` + +## References + +- [NEP 52 Full Text](https://numpy.org/neps/nep-0052-python-api-cleanup.html) +- [NumPy 2.0 Migration Guide](https://numpy.org/doc/stable/numpy_2_0_migration_guide.html) diff --git a/docs/numpy/neps/NEP53.md b/docs/numpy/neps/NEP53.md new file mode 100644 index 000000000..a89d16448 --- /dev/null +++ b/docs/numpy/neps/NEP53.md @@ -0,0 +1,92 @@ +# NEP 53 - Evolving the NumPy C-API for NumPy 2.0 + +**Status:** Draft (Open) +**NumSharp Impact:** LOW - C-API specific, but informs API evolution patterns + +## Summary + +Defines strategy for evolving NumPy's C-API while maintaining backwards compatibility. Introduces API versioning and compatibility packages. + +## Key Changes in NumPy 2.0 + +### Removed Functions +| Function | Replacement | +|----------|-------------| +| `PyArray_Mean` | Use `arr.mean()` method | +| `PyArray_Std` | Use `arr.std()` method | +| `MapIter` API | N/A (advanced indexing internals) | + +### Struct Layout Changes + +**`PyArray_Descr` (dtype struct):** +- Larger maximum itemsize +- New flags for custom user dtypes +- Direct field access → macro access + +```c +// OLD +npy_intp size = descr->elsize; + +// NEW +npy_intp size = PyDataType_ITEMSIZE(descr); +``` + +**`NPY_MAXDIMS`:** Increased from 32 to 64 dimensions + +## Backwards Compatibility Strategy + +### Step 1: NumPy 1.25+ +```c +#define NPY_TARGET_VERSION NPY_1_22_API_VERSION +``` +- Default exports older API for compatibility +- New API requires explicit opt-in + +### Step 2: NumPy 2.0 +- Requires recompilation against NumPy 2.0 +- `numpy2_compat` package for dual 1.x/2.0 support + +## NumSharp Relevance + +### Why This Matters (Informational) + +1. **API Evolution Pattern:** Shows how NumPy handles breaking changes +2. **Versioning Strategy:** Informs NumSharp's own API versioning decisions +3. **Compatibility Layer:** Concept of compatibility packages + +### NumSharp Considerations + +NumSharp doesn't use NumPy's C-API directly, but similar patterns apply: + +```csharp +// Similar pattern: accessor methods instead of direct field access +public class Shape { + // BAD: public fields that can't evolve + public int[] Dimensions; + + // GOOD: properties/methods that can change implementation + public int NDim => _dimensions.Length; + public int GetDimension(int axis) => _dimensions[axis]; +} +``` + +### Breaking Changes in NumSharp + +If NumSharp follows similar patterns: + +1. **Deprecation Period:** Warn before removing APIs +2. **Accessor Methods:** Use methods/properties instead of fields +3. **Versioning:** Consider major version bumps for breaking changes + +## Impact on Downstream Packages + +| Package Type | Impact | Migration | +|--------------|--------|-----------| +| C-API Users | Must adapt code | Minor changes | +| Cython Users | Less impact with Cython 3 | Use macros | +| End Users | Transparent | None | + +## References + +- [NEP 53 Full Text](https://numpy.org/neps/nep-0053-c-abi-evolution.html) +- [NumPy 2.0 Migration Guide](https://numpy.org/doc/stable/numpy_2_0_migration_guide.html) diff --git a/docs/numpy/neps/NEP54.md b/docs/numpy/neps/NEP54.md new file mode 100644 index 000000000..775e54574 --- /dev/null +++ b/docs/numpy/neps/NEP54.md @@ -0,0 +1,142 @@ +# NEP 54 - SIMD Infrastructure Evolution: Google Highway + +**Status:** Accepted +**NumSharp Impact:** INFORMATIONAL - Shows modern SIMD library design patterns + +## Summary + +NumPy is adopting Google Highway as its SIMD framework, replacing the C-based Universal Intrinsics with a C++ solution supporting sizeless SIMD (ARM SVE, RISC-V RVV). + +## What is Google Highway? + +Google Highway is a modern C++ SIMD library providing: +- Portable intrinsics across CPU architectures +- Sizeless SIMD support (SVE, RVV) +- Clean, readable API +- Apache 2.0 / BSD-3 dual license +- Used by Chromium, JPEG XL + +## Why Move from Universal Intrinsics to Highway? + +### Code Readability Improvement + +**Old C code (Universal Intrinsics):** +```c +npyv_@sfx@ a5 = npyv_load_@sfx@(src1 + npyv_nlanes_@sfx@ * 4); +``` + +**New C++ (Highway):** +```cpp +auto a5 = Load(src1 + nlanes * 4); +``` + +### Key Motivations + +1. **Sizeless SIMD:** ARM SVE and RISC-V RVV not possible with C intrinsics +2. **Better Documentation:** Highway has extensive docs +3. **Wider Testing:** Used by other projects, more bug detection +4. **Maintainability:** Clearer C++ code reduces regressions + +## Comparison: Highway vs Universal Intrinsics + +| Aspect | Highway | Universal Intrinsics | +|--------|---------|----------------------| +| **Language** | C++ | C | +| **Compilation** | Single unit, preprocessing | Multiple units per feature | +| **Runtime Dispatch** | One-time dynamic | Multiple linked functions | +| **SVE/RVV Support** | Yes | No | +| **Z-system Support** | Limited | Full (VX/VXE/VXE2) | + +## Supported Platforms + +### Highway Supports: +- x86/x86-64: SSE4.2, AVX, AVX2, AVX-512 +- ARM: NEON, SVE, SVE2 +- PowerPC +- RISC-V RVV +- s390x (limited) + +### NumPy Already Implemented: +Sorting functions (sort, argsort, partition, argpartition) use: +- Intel x86-simd-sort +- Google Highway +- Large speedups reported + +## NumSharp Relevance + +### Learning from Highway's Design + +Highway's API patterns are applicable to .NET SIMD: + +**Highway (C++):** +```cpp +HWY_API Vec128 Add(Vec128 a, Vec128 b) { + return Vec128{_mm_add_ps(a.raw, b.raw)}; +} +``` + +**Equivalent .NET pattern:** +```csharp +public static Vector128 Add(Vector128 a, Vector128 b) { + if (Sse.IsSupported) + return Sse.Add(a, b); + // Fallback + return SoftwareFallback(a, b); +} +``` + +### .NET SIMD Options + +| Option | Pros | Cons | +|--------|------|------| +| `Vector` | Portable, simple | Limited operations | +| `Vector128/256` | Full control, all intrinsics | More code, manual dispatch | +| `Span` + vectorization | Compiler may vectorize | Unpredictable | + +### Potential NumSharp Architecture + +```csharp +public interface ISimdBackend { + void Add(ReadOnlySpan a, ReadOnlySpan b, Span result); + void Multiply(ReadOnlySpan a, ReadOnlySpan b, Span result); + float Sum(ReadOnlySpan a); +} + +public class AvxBackend : ISimdBackend { + public void Add(ReadOnlySpan a, ReadOnlySpan b, Span result) { + // AVX implementation + } +} + +public class ScalarBackend : ISimdBackend { + // Fallback implementation +} + +// Runtime selection +ISimdBackend backend = Avx2.IsSupported ? new Avx2Backend() + : Avx.IsSupported ? new AvxBackend() + : new ScalarBackend(); +``` + +## Performance in NumPy 2.0 + +### Sorting Speedups (VQSort via Highway) +- `np.sort`, `np.argsort` +- `np.partition`, `np.argpartition` +- Hardware-specific large speedups + +### Math Routines +- Highway has limited, low-precision math +- NumPy keeps existing routines, may use Highway primitives internally + +## References + +- [NEP 54 Full Text](https://numpy.org/neps/nep-0054-simd-cpp-highway.html) +- [Google Highway GitHub](https://github.com/google/highway) +- [NumPy Roadmap](https://numpy.org/neps/roadmap.html) +- [.NET Hardware Intrinsics](https://docs.microsoft.com/dotnet/standard/simd) + +## Related Issues + +- #544 - SIMD optimization tracking +- #545 - SIMD implementation diff --git a/docs/numpy/neps/NEP55.md b/docs/numpy/neps/NEP55.md new file mode 100644 index 000000000..2e4a4295e --- /dev/null +++ b/docs/numpy/neps/NEP55.md @@ -0,0 +1,127 @@ +# NEP 55 - UTF-8 Variable-Width String DType + +**Status:** Final +**NumSharp Impact:** MEDIUM - New string handling in NumPy 2.0 + +## Summary + +Adds `StringDType`, a variable-length UTF-8 encoded string dtype for NumPy 2.0, replacing object arrays for string data. + +## The Problem with Fixed-Width Strings + +| Aspect | `bytes_` (S) | `unicode` (U) | New `StringDType` (T) | +|--------|--------------|---------------|----------------------| +| Encoding | Null-terminated | UCS-4 (32-bit) | UTF-8 | +| Width | Fixed | Fixed | **Variable** | +| Memory | Wastes space | 4x overhead for ASCII | Optimized | +| Max length | Pre-determined | Pre-determined | **Unlimited** | + +### Fixed-Width Problems + +1. Must determine max string length before array creation +2. Short strings padded to match longest element +3. Memory waste with mixed-length strings + +## New StringDType Usage + +### Basic Creation +```python +from numpy.dtypes import StringDType +import numpy as np + +data = ["short", "this is a very long string"] +arr = np.array(data, dtype=StringDType()) + +# Or using character code +arr = np.array(data, dtype="T") +``` + +### Missing Data Support +```python +dt = StringDType(na_object=np.nan) +arr = np.array(["hello", np.nan, "world"], dtype=dt) +np.isnan(arr) # array([False, True, False]) +``` + +### String Coercion Control +```python +# Default: coerce non-strings +np.array([1, 3.4], dtype=StringDType()) +# array(['1', '3.4'], dtype=StringDType()) + +# Strict: reject non-strings +np.array([1, 3.4], dtype=StringDType(coerce=False)) +# ValueError +``` + +## String Operations: `np.strings` Namespace + +New namespace replaces `np.char`: + +```python +np.strings.upper(arr) # Uppercase +np.strings.lower(arr) # Lowercase +np.strings.str_len(arr) # String length +np.strings.isalpha(arr) # Check alphabetic +np.strings.find(arr, sub) # Find substring +np.strings.replace(arr, old, new) +np.strings.strip(arr) # Strip whitespace +``` + +### String Arithmetic +```python +arr + "!" # Concatenation +arr * 2 # Repetition +arr == "test" # Comparison +``` + +## NumSharp Implications + +### Current String Support + +NumSharp's string handling is limited. Check current status: +- `NPTypeCode.Char` - single characters only +- No `NPTypeCode.String` or variable-length string dtype + +### Implementation Options + +**Option 1: Object Array Pattern** +```csharp +// Store strings as object references +var arr = np.array(new string[] { "hello", "world" }, dtype: NPTypeCode.Object); +``` + +**Option 2: New StringDType** +```csharp +// Add new NPTypeCode +enum NPTypeCode { + // ... existing ... + String, // Variable-length UTF-8 +} + +// Or dedicated class +class StringDType : DType { + public NullObject NaObject { get; } + public bool Coerce { get; } +} +``` + +### Storage Considerations + +NumPy's StringDType uses: +- **Small string optimization:** ≤15 bytes stored inline +- **Arena allocation:** Longer strings in heap arena +- **Thread-safe allocator:** Mutex-protected access + +For NumSharp, consider: +- Using `string[]` for simplicity +- Or `Span` with UTF-8 encoding for performance + +### Priority + +**MEDIUM** - String handling is important but not as critical as numeric operations. Current workaround: use object arrays with strings. + +## References + +- [NEP 55 Full Text](https://numpy.org/neps/nep-0055-string_dtype.html) +- [NumPy StringDType docs](https://numpy.org/doc/stable/reference/routines.strings.html) diff --git a/docs/numpy/neps/NEP56.md b/docs/numpy/neps/NEP56.md new file mode 100644 index 000000000..cf8246221 --- /dev/null +++ b/docs/numpy/neps/NEP56.md @@ -0,0 +1,151 @@ +# NEP 56 - Array API Standard Support + +**Status:** Final +**NumSharp Impact:** HIGH - Defines cross-library compatibility standard + +## Summary + +NumPy 2.0 adds support for the **Array API standard (2022.12)**, enabling code portability across NumPy, CuPy, JAX, PyTorch, and Dask. + +## What is the Array API Standard? + +A specification for array library APIs designed for cross-library compatibility. Code written to the standard works with any compliant library. + +```python +def vq_py(obs, code_book): + xp = array_namespace(obs, code_book) # Get namespace (numpy, cupy, etc.) + dist = xp.asarray(cdist(obs, code_book)) + return xp.argmin(dist, axis=1) +``` + +## Major Changes in NumPy 2.0 + +### A. New Strict Behaviors + +| Function | Change | +|----------|--------| +| `.T` | Errors for ndim > 2 | +| `cross()` | Errors on size-2 vectors (only size-3) | +| `solve()` | Strict validation of inputs | +| `outer()` | Raises on >1-D inputs (was: flatten) | + +### B. DType Changes + +| Function | Change | +|----------|--------| +| `ceil()` | Returns integer dtype (was: float) | +| `floor()` | Returns integer dtype (was: float) | +| `trunc()` | Returns integer dtype (was: float) | + +### C. Numerical Behavior Changes + +| Function | Change | +|----------|--------| +| `pinv()` | `rtol` default now dtype-dependent | +| `matrix_rank()` | `tol` renamed to `rtol` | + +### D. `copy` Keyword Semantics + +```python +np.asarray(obj, copy=True) # Always copy +np.asarray(obj, copy=False) # Never copy (raise if needed) +np.asarray(obj, copy=None) # Copy if necessary (old default) +``` + +### E. FFT Precision + +All `numpy.fft` functions now preserve 32-bit precision (was: upcast to float64). + +## New Functions and Aliases + +### New Aliases (Trigonometry) +| New Name | Alias For | +|----------|-----------| +| `acos` | `arccos` | +| `acosh` | `arccosh` | +| `asin` | `arcsin` | +| `asinh` | `arcsinh` | +| `atan` | `arctan` | +| `atanh` | `arctanh` | +| `atan2` | `arctan2` | + +### New Aliases (Other) +| New Name | Alias For | +|----------|-----------| +| `concat` | `concatenate` | +| `permute_dims` | `transpose` | +| `pow` | `power` | +| `bitwise_left_shift` | `left_shift` | +| `bitwise_right_shift` | `right_shift` | +| `bitwise_invert` | `invert` | + +### New Functions + +| Function | Description | +|----------|-------------| +| `isdtype(dtype, kind)` | Check dtype kind | +| `unique_all()` | All unique info | +| `unique_counts()` | Unique values + counts | +| `unique_inverse()` | Unique values + inverse indices | +| `unique_values()` | Just unique values | +| `matrix_transpose()` | Transpose last two axes | +| `vecdot()` | Vector dot product | +| `matrix_norm()` | Matrix norm (gufunc) | +| `vector_norm()` | Vector norm (gufunc) | + +### New Properties + +| Property | Description | +|----------|-------------| +| `ndarray.mT` | Matrix transpose (last 2 axes) | +| `ndarray.device` | Returns CPU device object | + +### New Keywords + +| Function | New Keyword | Description | +|----------|-------------|-------------| +| `std()`, `var()` | `correction` | Clearer than `ddof` | +| `sort()`, `argsort()` | `stable` | Complement to `kind` | + +## NumSharp Implementation Checklist + +### Required for Array API Compliance + +**High Priority:** +- [ ] `copy` keyword with three-way semantics +- [ ] `.T` error for ndim > 2 +- [ ] `ceil/floor/trunc` return integer dtypes +- [ ] `isdtype()` function + +**Medium Priority:** +- [ ] Add trig aliases: `acos`, `asin`, `atan`, etc. +- [ ] Add `concat`, `permute_dims`, `pow` aliases +- [ ] Implement `unique_*` family of functions +- [ ] Add `matrix_transpose()` and `.mT` property + +**Lower Priority:** +- [ ] `vecdot()`, `matrix_norm()`, `vector_norm()` +- [ ] `correction` keyword for `std/var` +- [ ] `stable` keyword for `sort/argsort` +- [ ] `.device` property (always returns CPU) + +### Breaking Changes to Consider + +NumSharp should decide whether to: +1. Match NumPy 2.0 exactly (breaking from 1.x) +2. Provide compatibility layer +3. Target specific NumPy version + +## `np.bool` Reintroduced + +```python +np.bool # Now points to numpy.bool_ (was removed in NumPy 1.20) +``` + +NumSharp note: `np.bool` should map to `NPTypeCode.Boolean`. + +## References + +- [NEP 56 Full Text](https://numpy.org/neps/nep-0056-array-api-main-namespace.html) +- [Array API Standard](https://data-apis.org/array-api/latest/) +- [NumPy 2.0 Migration Guide](https://numpy.org/doc/stable/numpy_2_0_migration_guide.html) diff --git a/docs/numpy/neps/README.md b/docs/numpy/neps/README.md new file mode 100644 index 000000000..4dc9bd2a5 --- /dev/null +++ b/docs/numpy/neps/README.md @@ -0,0 +1,169 @@ +# NumPy Enhancement Proposals (NEPs) - NumSharp Reference + +This directory contains documentation for NEPs relevant to NumSharp's goal of 1-to-1 NumPy compatibility. + +## What are NEPs? + +NEPs (NumPy Enhancement Proposals) are design documents describing new features, processes, or environments for NumPy. Similar to Python's PEPs. + +## NEP Index by Impact + +### CRITICAL - Breaking Changes in NumPy 2.0 + +| NEP | Title | Impact | +|-----|-------|--------| +| [NEP 50](NEP50.md) | Promotion Rules for Python Scalars | Type promotion completely changed | +| [NEP 52](NEP52.md) | Python API Cleanup for NumPy 2.0 | ~100 functions removed/renamed | +| [NEP 56](NEP56.md) | Array API Standard Support | New functions, changed behaviors | + +### HIGH - Significant Implementation Requirements + +| NEP | Title | Impact | +|-----|-------|--------| +| [NEP 01](NEP01.md) | .npy File Format | Must match exactly for interop | +| [NEP 07](NEP07.md) | DateTime Types | NOT IMPLEMENTED in NumSharp | +| [NEP 19](NEP19.md) | Random Number Generator Policy | NumSharp claims 1-to-1 seed matching | +| [NEP 27](NEP27.md) | Zero Rank Arrays | Affects scalar handling | +| [NEP 38](NEP38.md) | SIMD Optimization Instructions | Performance via SIMD (#544, #545) | +| [NEP 54](NEP54.md) | SIMD Infrastructure (Highway) | Modern SIMD patterns | +| [NEP 55](NEP55.md) | UTF-8 Variable-Width String DType | New string handling | + +### MEDIUM - Behavioral Considerations + +| NEP | Title | Impact | +|-----|-------|--------| +| [NEP 05](NEP05.md) | Generalized Ufuncs | Affects operation signatures | +| [NEP 10](NEP10.md) | Iterator/UFunc Optimization | Cache-coherency, dimension coalescing | +| [NEP 20](NEP20.md) | Gufunc Signature Enhancement | Frozen/flexible dimensions | +| [NEP 21](NEP21.md) | Advanced Indexing Semantics | oindex vs vindex (deferred but informative) | +| [NEP 34](NEP34.md) | Disallow dtype=object Inference | Ragged array creation | +| [NEP 42](NEP42.md) | New and Extensible DTypes | Future dtype architecture | +| [NEP 43](NEP43.md) | Extensible UFuncs | Custom dtype ufuncs | +| [NEP 51](NEP51.md) | Scalar Representation | ToString() output | + +### LOW - Informational / Python-Specific + +| NEP | Title | Impact | +|-----|-------|--------| +| [NEP 13](NEP13.md) | Ufunc Override Mechanism | Python duck-typing | +| [NEP 18](NEP18.md) | Array Function Dispatch | Python duck-typing | +| [NEP 32](NEP32.md) | Remove Financial Functions | DO NOT IMPLEMENT | +| [NEP 49](NEP49.md) | Data Allocation Strategies | Custom allocator patterns | +| [NEP 53](NEP53.md) | C-API Evolution for NumPy 2.0 | API versioning patterns | + +## NEPs NOT Documented (Not Relevant to NumSharp) + +| NEP | Title | Reason | +|-----|-------|--------| +| 0 | Purpose and Process | Meta | +| 14 | Dropping Python 2.7 | Python-specific | +| 15 | Merging multiarray/umath | Internal restructuring | +| 22 | Duck Typing Overview | Python-specific | +| 23 | Backwards Compatibility Policy | Meta | +| 28 | Website Redesign | Meta | +| 29 | Version Support Policy | Meta | +| 36 | Fair Play | Meta | +| 40 | Legacy Datatype Docs | Informational only | +| 41 | First Step Toward New Dtypes | Covered by NEP 42 | +| 44 | Documentation Restructuring | Meta | +| 45 | C Style Guide | Meta | +| 46-48 | Sponsorship/Spending | Meta | +| 57 | Platform Support | Meta | + +## Quick Reference: NumPy 1.x vs 2.x Changes + +### Type Promotion (NEP 50) +```python +# NumPy 1.x: Value-based promotion +uint8(1) + 2 → int64(3) + +# NumPy 2.x: Weak scalar promotion +uint8(1) + 2 → uint8(3) +``` + +### Removed Functions (NEP 52) +```python +# Use instead: +np.round_ → np.round +np.product → np.prod +np.sometrue → np.any +np.alltrue → np.all +``` + +### New Functions (NEP 56) +```python +# Aliases +np.acos, np.asin, np.atan # for arccos, arcsin, arctan +np.concat # for concatenate +np.permute_dims # for transpose + +# New +np.isdtype(dtype, kind) +np.unique_values(), np.unique_counts() +ndarray.mT # Matrix transpose +``` + +### copy Keyword (NEP 56) +```python +np.asarray(x, copy=True) # Always copy +np.asarray(x, copy=False) # Never copy (error if needed) +np.asarray(x, copy=None) # Copy if necessary +``` + +## Implementation Priority for NumSharp + +### Phase 1: Core Compatibility +1. NEP 50 - Fix type promotion +2. NEP 52 - API cleanup audit +3. NEP 56 - Add new functions/aliases + +### Phase 2: Feature Completeness +4. NEP 07 - Add datetime64/timedelta64 +5. NEP 55 - Improve string handling +6. NEP 27 - Verify zero-rank behavior + +### Phase 3: Interoperability +7. NEP 01 - Verify .npy format compliance +8. NEP 19 - Verify RNG seed matching + +### Phase 4: Performance (SIMD) +9. NEP 38/54 - SIMD optimization (#544, #545) + +## SIMD Implementation for NumSharp + +Related GitHub issues: **#544**, **#545** + +### .NET SIMD Options + +| API | .NET Version | Portability | Control | +|-----|--------------|-------------|---------| +| `Vector` | .NET Core 2.0+ | High | Low | +| `Vector128/256/512` | .NET Core 3.0+ | Medium | High | +| Native P/Invoke | Any | Low | Full | + +### Priority Operations + +| Operation | Speedup | Complexity | +|-----------|---------|------------| +| Element-wise (+, -, *, /) | 4-8x | Low | +| Reductions (sum, mean) | 2-4x | Medium | +| Comparisons | 4-8x | Low | +| Dot/matmul | 4-16x | High | + +### Example Pattern + +```csharp +// Runtime dispatch like NumPy +ISimdBackend backend = Avx2.IsSupported ? new Avx2Backend() + : Avx.IsSupported ? new AvxBackend() + : Sse2.IsSupported ? new Sse2Backend() + : new ScalarBackend(); +``` + +See [NEP38.md](NEP38.md) and [NEP54.md](NEP54.md) for detailed patterns. + +## References + +- [NumPy NEPs Index](https://numpy.org/neps/) +- [NumPy 2.0 Migration Guide](https://numpy.org/doc/stable/numpy_2_0_migration_guide.html) +- [Array API Standard](https://data-apis.org/array-api/latest/) diff --git a/docs/plans/AUTOCOVERAGE_TESTFRAMEWORK.md b/docs/plans/AUTOCOVERAGE_TESTFRAMEWORK.md new file mode 100644 index 000000000..5ec2fe98a --- /dev/null +++ b/docs/plans/AUTOCOVERAGE_TESTFRAMEWORK.md @@ -0,0 +1,920 @@ +# NumSharp-NumPy Hybrid Test Framework Design + +**Status**: FINAL DESIGN +**Goal**: 100% behavioral consistency between NumSharp and NumPy 2.x + +## Overview + +A C#-driven test framework that: +1. **Defines test cases** via `yield return np.function(...)` expressions (semantic, not execution) +2. **Expands markers** into combinatorial grid variations automatically +3. **Python executes first** — creates arrays, runs operations, saves artifacts to disk +4. **NumSharp executes second** — loads artifacts, runs same operations, compares results +5. **Reports alignment** with statistics and detailed mismatches + +### Key Principles + +- **Yield is semantic** — `yield return np.sum(...)` is a *description*, not execution +- **Python-first** — Python is the source of truth; NumSharp validates against it +- **Grid expansion** — `np.dot(arrays, arrays)` = N² combinations (full cross product) +- **Every step verified** — Chained operations store and compare each intermediate result +- **Executor manages state** — Re-seeding, sequencing, parallelization handled outside contracts + +--- + +## Core Idea + +One line generates thousands of test cases: + +```csharp +yield return np.sum(arrays, axis: axes, keepdims: bools); +``` + +Expands to: +```python +np.sum(np.arange(6), axis=None, keepdims=False) +np.sum(np.arange(6), axis=None, keepdims=True) +np.sum(np.arange(6), axis=0, keepdims=False) +np.sum(np.zeros((3,4)), axis=0, keepdims=False) +np.sum(np.zeros((3,4)), axis=1, keepdims=True) +np.sum(np.zeros((3,4)), axis=2, keepdims=False) # Invalid - should throw +... (hundreds more) +``` + +--- + +## Architecture + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ NumSharp.Tests.Battletesting │ +├─────────────────────────────────────────────────────────────────┤ +│ │ +│ ┌─────────────────┐ ┌─────────────────┐ │ +│ │ Contracts │ │ Expander │ │ +│ │ (semantic) │────▶│ │ │ +│ │ │ │ Marker → Values │ │ +│ │ yield return │ │ Grid expansion │ │ +│ │ np.sum(arrays, │ │ Context-aware │ │ +│ │ axis: axes) │ │ │ │ +│ └─────────────────┘ └────────┬────────┘ │ +│ │ │ +│ ▼ │ +│ ┌─────────────────────────────────────────────────────────┐ │ +│ │ Expanded Calls │ │ +│ │ np.sum(arange(6), axis=None, keepdims=False) │ │ +│ │ np.sum(arange(6), axis=0, keepdims=True) │ │ +│ │ np.dot(arange(6), zeros(3,4)) ← grid: arrays × arrays │ │ +│ │ ... │ │ +│ └─────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌─────────────────────────────────────────────────────────┐ │ +│ │ PHASE 1: Python Executor (first) │ │ +│ │ │ │ +│ │ For each expanded call: │ │ +│ │ 1. Execute array builders → save intermediates │ │ +│ │ 2. Execute operation → save result │ │ +│ │ 3. Catch exceptions → save error info │ │ +│ │ │ │ +│ │ Artifacts: inputs/*.npy, outputs/*.npy, results.json │ │ +│ └─────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌─────────────────────────────────────────────────────────┐ │ +│ │ PHASE 2: NumSharp Executor (second) │ │ +│ │ │ │ +│ │ For each expanded call: │ │ +│ │ 1. Execute array builders → compare with saved │ │ +│ │ 2. Execute operation → compare with saved │ │ +│ │ 3. Catch exceptions → compare error messages │ │ +│ │ │ │ +│ │ Every intermediate step is verified against Python │ │ +│ └─────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌─────────────────────────────────────────────────────────┐ │ +│ │ Report Generator │ │ +│ │ - Alignment % per function │ │ +│ │ - Mismatch details (values, shapes, dtypes, errors) │ │ +│ │ - Intermediate step failures │ │ +│ └─────────────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────────┘ +``` + +--- + +## Execution Model + +### Yield is Semantic + +The `yield return` statement is a **description**, not execution: + +```csharp +yield return np.sum(arange(24).reshape(2,3,4), axis: 1); +``` + +This describes: "Test `np.sum` on a reshaped arange array with axis=1." + +No code runs during yield. The executor interprets this description later. + +### Python-First Execution + +Python is the source of truth. The executor: + +1. **Python Phase**: Execute operation, save all artifacts to disk +2. **NumSharp Phase**: Load artifacts, execute same operation, compare + +``` +Contract Python Executor NumSharp Executor + │ │ │ + │ np.sum(arange(24) │ │ + │ .reshape(2,3,4), │ │ + │ axis=1) │ │ + │────────────────────────────▶ │ + │ │ │ + │ Execute & Save: │ + │ step1 = np.arange(24) │ + │ save("step1.npy") │ + │ step2 = step1.reshape(2,3,4) │ + │ save("step2.npy") │ + │ result = np.sum(step2, axis=1) │ + │ save("result.npy") │ + │ │ │ + │ │────────────────────────────▶│ + │ │ │ + │ │ Execute & Compare: + │ │ step1 = np.arange(24) + │ │ compare(step1, "step1.npy") + │ │ step2 = step1.reshape(2,3,4) + │ │ compare(step2, "step2.npy") + │ │ result = np.sum(step2, axis: 1) + │ │ compare(result, "result.npy") +``` + +### Chained Operations + +Every intermediate step is stored and compared: + +```csharp +yield return np.sum(arange(24).reshape(2,3,4), axis: 1); +``` + +Becomes 3 verification points: +1. `arange(24)` — NumSharp's arange must match NumPy's +2. `.reshape(2,3,4)` — NumSharp's reshape must match NumPy's +3. `np.sum(..., axis=1)` — Final result must match + +If `reshape` differs, we catch it before `sum` runs — pinpointing the actual bug. + +### Grid Expansion + +When the same marker appears multiple times, it's a **full cross product**: + +```csharp +yield return np.dot(arrays, arrays); +``` + +If `arrays` = `[arange(6), zeros(3,4), ones(2,3)]`, this generates 9 test cases: + +| Left | Right | Expected | +|------|-------|----------| +| arange(6) | arange(6) | Inner product (works) | +| arange(6) | zeros(3,4) | Error: shapes not aligned | +| arange(6) | ones(2,3) | Error: shapes not aligned | +| zeros(3,4) | arange(6) | Error: shapes not aligned | +| zeros(3,4) | zeros(3,4) | Error: (3,4)·(3,4) not aligned | +| ... | ... | ... | + +Most combinations are errors — and that's valid testing. NumSharp must throw the same errors as NumPy. + +### Tuple Returns + +Functions returning tuples use ITuple-compliant C# tuples: + +```csharp +// NumPy returns: (unique_values, indices, inverse_indices) +// NumSharp returns: (NDArray, NDArray, NDArray) + +yield return np.unique(arrays, return_index: true, return_inverse: true); +``` + +The framework compares tuple element-by-element. No special declaration needed. + +--- + +## Contract Definition + +### The Contract Base Class + +```csharp +public abstract class Contract +{ + // Dynamic np proxy - captures calls instead of executing + protected static dynamic np => new NpCapture(); + + // ===== Array Builders ===== + protected static ArraySpec arange(int stop) => new("arange", stop) { Ndim = 1 }; + protected static ArraySpec arange(int start, int stop, int step = 1) => new("arange", start, stop, step) { Ndim = 1 }; + protected static ArraySpec zeros(params int[] shape) => new("zeros", shape) { Ndim = shape.Length }; + protected static ArraySpec ones(params int[] shape) => new("ones", shape) { Ndim = shape.Length }; + protected static ArraySpec eye(int n) => new("eye", n) { Ndim = 2 }; + protected static ArraySpec array(params object[] values) => new("array", values) { Ndim = 1 }; + protected static ArraySpec linspace(double start, double stop, int num) => new("linspace", start, stop, num) { Ndim = 1 }; + protected static ArraySpec empty(params int[] shape) => new("empty", shape) { Ndim = shape.Length }; + protected static ArraySpec full(int[] shape, object fill) => new("full", shape, fill) { Ndim = shape.Length }; + + // ===== Standard Markers (expand to predefined variations) ===== + protected static Marker arrays => new("arrays"); // Standard array variations + protected static Marker arrays_float => new("arrays_float"); // Float arrays only (for sqrt, log, etc.) + protected static Marker arrays_sorted => new("sorted_arrays"); // Pre-sorted arrays + protected static Marker matrices => new("matrices"); // 2D arrays only + protected static Marker scalars => new("scalars"); // Numeric scalars + protected static Marker axes => new("axes"); // Context-aware axis values + protected static Marker bools => new("bools"); // true, false + protected static Marker dtypes => new("dtypes"); // All NPTypeCodes + protected static Marker dtypes_float => new("dtypes_float"); // Float dtypes + protected static Marker dtypes_int => new("dtypes_int"); // Integer dtypes + protected static Marker shapes => new("shapes"); // Output shapes + protected static Marker sides => new("sides"); // "left", "right" + protected static Marker orders => new("orders"); // "C", "F" + + // ===== Inline Variation (custom values) ===== + protected static Vary Vary(params object[] values) => new(values); + + // ===== Special Values ===== + protected static double nan => double.NaN; + protected static double inf => double.PositiveInfinity; + protected static double neginf => double.NegativeInfinity; + + // ===== The test case generator - override this ===== + public abstract IEnumerable TestCases(); +} +``` + +### Writing Contracts + +```csharp +public class NpMathContracts : Contract +{ + public override IEnumerable TestCases() + { + // ===== Unary operations ===== + yield return np.abs(arrays); + yield return np.negative(arrays); + yield return np.sqrt(arrays_float); // Float only (negative ints would fail) + yield return np.exp(arrays); + yield return np.log(arrays_float); + yield return np.sin(arrays); + yield return np.cos(arrays); + yield return np.floor(arrays); + yield return np.ceil(arrays); + yield return np.sign(arrays); + + // ===== Reductions ===== + yield return np.sum(arrays, axis: axes, keepdims: bools); + yield return np.prod(arrays, axis: axes, keepdims: bools); + yield return np.mean(arrays, axis: axes, keepdims: bools); + yield return np.std(arrays, axis: axes, keepdims: bools); + yield return np.var(arrays, axis: axes, keepdims: bools); + yield return np.min(arrays, axis: axes, keepdims: bools); + yield return np.max(arrays, axis: axes, keepdims: bools); + yield return np.argmin(arrays, axis: axes); + yield return np.argmax(arrays, axis: axes); + yield return np.all(arrays, axis: axes); + yield return np.any(arrays, axis: axes); + + // ===== Binary operations ===== + yield return np.add(arrays, arrays); + yield return np.subtract(arrays, arrays); + yield return np.multiply(arrays, arrays); + yield return np.divide(arrays, arrays); + yield return np.power(arrays, Vary(0, 1, 2, 3, -1)); + yield return np.dot(arrays, arrays); + yield return np.matmul(matrices, matrices); + + // ===== Edge cases - explicit ===== + yield return np.sum(array(nan, 1.0, 2.0), axis: 0); + yield return np.sum(array(inf, neginf, 0.0)); + yield return np.divide(array(1.0, 2.0), array(0.0, 0.0)); // Division by zero + } +} + +public class NpCreationContracts : Contract +{ + public override IEnumerable TestCases() + { + yield return np.zeros(shapes, dtype: dtypes); + yield return np.ones(shapes, dtype: dtypes); + yield return np.empty(shapes, dtype: dtypes); + yield return np.full(shapes, scalars, dtype: dtypes); + yield return np.arange(Vary(0, 1, 10), Vary(10, 100), Vary(1, 2, 5)); + yield return np.linspace(scalars, scalars, Vary(0, 1, 10, 50)); + yield return np.eye(Vary(1, 3, 5, 10), dtype: dtypes_float); + } +} + +public class NpManipulationContracts : Contract +{ + public override IEnumerable TestCases() + { + yield return np.reshape(arrays, Vary(new[]{-1}, new[]{2,-1}, new[]{3,4})); + yield return np.transpose(matrices); + yield return np.squeeze(arrays); + yield return np.expand_dims(arrays, axis: axes); + yield return np.concatenate(array_tuples, axis: Vary(0, 1, -1)); + yield return np.stack(array_tuples, axis: Vary(0, 1, -1)); + yield return np.broadcast_to(arrays, broadcast_shapes); + yield return np.unique(arrays, return_index: bools, return_inverse: bools, return_counts: bools); + yield return np.nonzero(arrays); + } + + // Custom markers for this contract + Marker array_tuples => new("array_tuples"); + Marker broadcast_shapes => new("broadcast_shapes"); +} + +[Sequential("np.random")] // All cases run sequentially in this group +public class NpRandomContracts : Contract +{ + public override IEnumerable TestCases() + { + // Seed first for reproducibility + yield return np.random.seed(42); + + yield return np.random.rand(shapes); + yield return np.random.randn(shapes); + yield return np.random.randint(Vary(0, 1, 10), Vary(10, 100, 256), size: shapes); + yield return np.random.uniform(scalars, scalars, size: shapes); + yield return np.random.normal(Vary(0.0, 1.0), Vary(1.0, 0.5), size: shapes); + yield return np.random.choice(Vary(5, 10), size: shapes, replace: bools, p: probs); + yield return np.random.permutation(Vary(5, 10)); + yield return np.random.shuffle(arange(10)); + } + + Marker probs => new("probs"); // Context-aware probability arrays +} +``` + +### Mixing Markers with Concrete Values + +You have full control over test coverage: + +```csharp +public class NpSumDetailedContracts : Contract +{ + public override IEnumerable TestCases() + { + // 1. Full combinatorial (broad coverage) + yield return np.sum(arrays, axis: axes, keepdims: bools); + + // 2. Custom axis values with fixed keepdims (edge cases) + yield return np.sum(arrays, axis: Vary(-1, -2, 100, -100), keepdims: true); + + // 3. Specific array with varied params + yield return np.sum(arange(24).reshape(2,3,4), axis: Vary(0, 1, 2, null)); + + // 4. Explicit edge cases + yield return np.sum(array(nan, 1.0, 2.0), axis: 0); + yield return np.sum(array(inf, neginf, 1.0), axis: null); + yield return np.sum(array(), axis: null); // Empty array + + // 5. Dtype-specific tests + yield return np.sum(arrays, dtype: Vary(NPTypeCode.Float32, NPTypeCode.Float64, NPTypeCode.Int64)); + } +} +``` + +| Pattern | Example | Effect | +|---------|---------|--------| +| Standard marker | `arrays` | Expands to all predefined array variations | +| Inline Vary() | `Vary(-1, -2, 100)` | Expands to exactly those values | +| Concrete value | `keepdims: true` | Fixed, no expansion | +| Explicit array | `array(nan, 1.0, 2.0)` | One specific test case | +| Named custom marker | `edge_axes` | Reusable custom variations | + +--- + +## Markers and Expansion + +### Standard Markers + +| Marker | Expands To | Context-Aware | +|--------|------------|---------------| +| `arrays` | arange(6), zeros(3,4), ones(2,3,4), eye(3), ... | No | +| `arrays_float` | Arrays with float dtypes only | No | +| `arrays_sorted` | Pre-sorted arrays | No | +| `matrices` | 2D arrays only | No | +| `scalars` | 0, 1, -1, 0.5, 1e10, nan, inf, ... | No | +| `bools` | false, true | No | +| `dtypes` | All NPTypeCodes | No | +| `dtypes_float` | Float32, Float64 | No | +| `dtypes_int` | Int8...Int64, UInt8...UInt64 | No | +| `shapes` | (), (1,), (5,), (3,4), (2,3,4), ... | No | +| `axes` | null, 0, 1, ..., ndim-1, ndim (invalid) | **Yes** - adapts to input array | +| `probs` | null, uniform, skewed, invalid | **Yes** - adapts to size param | +| `broadcast_shapes` | Valid broadcast targets | **Yes** - adapts to input shape | + +### Context-Aware Expansion + +The `axes` marker generates different values based on the input array's ndim: + +```csharp +yield return np.sum(arrays, axis: axes); + +// For arange(6) [1D]: axis = null, 0, 1(invalid) +// For zeros(3,4) [2D]: axis = null, 0, 1, 2(invalid) +// For ones(2,3,4) [3D]: axis = null, 0, 1, 2, 3(invalid) +``` + +The `probs` marker generates probability arrays that match the `a` parameter: + +```csharp +yield return np.random.choice(Vary(5, 10), p: probs); + +// For a=5: p = null, [0.2,0.2,0.2,0.2,0.2], [0.9,0.025,...] +// For a=10: p = null, [0.1,0.1,...], [0.9,0.01,...] +``` + +### Inline Vary() + +For custom values that don't need a named marker: + +```csharp +// Test specific axis values +yield return np.sum(arrays, axis: Vary(-1, -2, 100)); + +// Test specific dtype conversions +yield return np.sum(arrays, dtype: Vary(null, NPTypeCode.Float32, NPTypeCode.Int64)); + +// Test specific shapes (array literals) +yield return np.zeros(Vary(new[]{0}, new[]{1}, new[]{3,4}, new[]{2,3,4})); + +// Array values in Vary +yield return np.concatenate( + Vary(arange(6), zeros(3,4)), // First array options + Vary(new[]{1,2,3}, new[]{3,2,1}), // Second array options (literals) + axis: Vary(0, 1) +); +``` + +### Expansion Combinations + +Multiple `Vary()` or markers expand as a **grid** (cross product): + +```csharp +yield return np.foo(Vary(a1, a2), Vary(b1, b2), axis: Vary(0, 1)); +// Generates: 2 × 2 × 2 = 8 test cases +// (a1, b1, 0), (a1, b1, 1), (a1, b2, 0), (a1, b2, 1), +// (a2, b1, 0), (a2, b1, 1), (a2, b2, 0), (a2, b2, 1) +``` + +### Testing Error Cases + +For functions with many error cases, use explicit yields or loops: + +```csharp +public override IEnumerable TestCases() +{ + // Happy paths with markers + yield return np.sum(arrays, axis: axes); + + // Explicit error cases + yield return np.sum(arange(6), axis: 5); // Out of bounds + yield return np.sum(arange(6), axis: -10); // Out of bounds negative + + // Loop for systematic edge case coverage + foreach (var invalidAxis in new[] { 5, -5, 100, -100 }) + { + yield return np.sum(zeros(3, 4), axis: invalidAxis); + } + + // Or use Vary for invalid values + yield return np.sum(arrays, axis: Vary(10, -10, 50, -50)); +} +``` + +The framework doesn't distinguish "expected error" from "expected success" — it just compares behavior. If both NumPy and NumSharp throw, that's a passing test. + +--- + +## The Call Object + +When you write `np.sum(arrays, axis: axes)`, it returns a `Call` object: + +```csharp +public class Call +{ + public string Path { get; } // "np.sum" + public object[] Args { get; } // [ArraySpec, Marker, ...] + public string[] ArgNames { get; } // ["axis", "keepdims"] + + // Generate Python code + public string ToPython(); + // "np.sum(np.arange(6), axis=0, keepdims=False)" + + // Generate NumSharp invocation + public object ExecuteNumSharp(); + // Calls np.sum(ndarray, axis: 0, keepdims: false) + + // Auto-generated case ID + public string CaseId { get; } + // "np.sum.case042:arange6_axis0_keepdimsF" +} +``` + +--- + +## Python Runner + +### Single Process, File-Based Communication + +``` +C# Test Runner Python Runner + │ │ + │ 1. Write manifest.json │ + │─────────────────────────────────────▶│ + │ │ + │ 2. Write input arrays (.npy) │ + │─────────────────────────────────────▶│ + │ │ + │ 3. Launch: python runner.py │ + │─────────────────────────────────────▶│ + │ │ Execute all cases + │ │ Save outputs (.npy) + │ 4. Wait for exit code 0 │ + │◀─────────────────────────────────────│ + │ │ + │ 5. Read results.json │ + │◀─────────────────────────────────────│ + │ │ + │ 6. Load output arrays (.npy) │ + │◀─────────────────────────────────────│ +``` + +### Work Directory Structure + +``` +./testresults// +├── manifest.json # All test cases to execute +├── inputs/ # Input arrays +│ ├── np.sum.case001_a.npy +│ └── ... +├── outputs/ # NumPy outputs +│ ├── np.sum.case001.npy +│ └── ... +├── results.json # Execution results + metadata +└── report.md # Final alignment report +``` + +### Manifest Format + +```json +{ + "version": "1.0", + "cases": [ + { + "case_id": "np.sum.case001:arange6_axis0_keepdimsF", + "python_code": "np.sum(np.arange(6), axis=0, keepdims=False)", + "inputs": { + "a": "inputs/np.sum.case001_a.npy" + }, + "output_path": "outputs/np.sum.case001.npy", + "sequential_group": null + }, + { + "case_id": "np.random.rand.case001:shape3x4", + "python_code": "np.random.rand(3, 4)", + "inputs": {}, + "output_path": "outputs/np.random.rand.case001.npy", + "sequential_group": "np.random" + } + ] +} +``` + +### Results Format + +```json +{ + "version": "1.0", + "numpy_version": "2.4.2", + "results": { + "np.sum.case001:arange6_axis0_keepdimsF": { + "success": true, + "return_type": "scalar", + "dtype": "int64", + "shape": [], + "output_path": "outputs/np.sum.case001.npy" + }, + "np.sum.case099:arange6_axis5_keepdimsF": { + "success": false, + "error_type": "AxisError", + "error_message": "axis 5 is out of bounds for array of dimension 1" + } + } +} +``` + +--- + +## Result Comparison + +### Comparison Rules + +1. **Both succeeded** → Compare return type, dtype, shape, values +2. **Both failed** → Compare exception behavior (see below) +3. **One succeeded, one failed** → **MISMATCH** + +### Exception Comparison + +When both sides throw, the framework checks: + +1. **Both threw** — This is already valuable (behavior matches) +2. **Exception type similarity** — Optional, logged for review +3. **Message comparison** — Configurable per test + +The default is lenient: if both threw, it's a **PASS** (same behavior). + +For stricter matching, use explicit assertions: + +```csharp +// Explicit error message validation +yield return np.sum(arange(6), axis: 5) + .ExpectError(msg => msg.Contains("out of bounds")); + +// Or just let both sides throw and compare (default behavior) +yield return np.sum(arange(6), axis: 5); +``` + +**Why lenient by default?** + +NumPy: `"axis 5 is out of bounds for array of dimension 1"` +NumSharp: `"Axis must be in range [-1, 1) for 1-dimensional array"` + +These are semantically equivalent but textually different. Both correctly reject axis=5. Requiring exact message containment would flag false negatives. + +The report still shows both messages for manual review. + +### Type Matching + +Return types must match exactly: + +| NumPy Returns | NumSharp Must Return | +|---------------|---------------------| +| Python scalar (float, int) | C# scalar (double, int) | +| 0-d ndarray (shape=()) | NDArray with shape=() | +| tuple of arrays | ValueTuple or array of NDArray | + +**A scalar is NOT the same as a 0-d array.** + +### Value Comparison + +```csharp +public class ResultComparator +{ + public ComparisonResult Compare(NumpyResult numpy, NumSharpResult numsharp, ToleranceConfig tol) + { + // Both succeeded + if (numpy.Success && numsharp.Success) + { + if (numpy.ReturnType != numsharp.ReturnType) + return Mismatch("Return type differs"); + + if (!numpy.Shape.SequenceEqual(numsharp.Shape)) + return Mismatch("Shape differs"); + + if (numpy.Dtype != numsharp.Dtype) + return Mismatch("Dtype differs"); + + // Value comparison with tolerance + if (!np.allclose(numpy.Data, numsharp.Data, tol.Rtol, tol.Atol, equal_nan: true)) + return Mismatch("Values differ"); + + return Match(); + } + + // Both failed - check exception message + if (!numpy.Success && !numsharp.Success) + { + if (!numsharp.ErrorMessage.Contains(numpy.ErrorMessage)) + return Mismatch($"Exception message mismatch: NumPy='{numpy.ErrorMessage}', NumSharp='{numsharp.ErrorMessage}'"); + + return Match(); + } + + // One succeeded, one failed + return Mismatch($"Behavior mismatch: NumPy {(numpy.Success ? "succeeded" : "failed")}, NumSharp {(numsharp.Success ? "succeeded" : "failed")}"); + } +} +``` + +### Tolerance Configuration + +```csharp +[Tolerance(Rtol = 1e-7, Atol = 1e-8)] // Default for most +[Tolerance(Rtol = 1e-5, Atol = 1e-6)] // For linalg operations +[Tolerance(ExactMatch = true)] // For RNG (seeded) +[Tolerance(EqualNaN = true, EqualInf = true)] // Default: NaN==NaN, Inf==Inf +``` + +--- + +## Report Format + +### Console Output + +``` +================================================================================ + NumSharp Alignment Report + NumPy 2.4.2 | NumSharp 0.41.0 +================================================================================ + +SUMMARY +-------------------------------------------------------------------------------- +Total Functions: 127 +Total Test Cases: 45,320 +Passed: 44,120 (97.4%) +Failed: 1,200 (2.6%) + +PER-FUNCTION RESULTS +-------------------------------------------------------------------------------- +Function Cases Pass Fail Alignment +-------------------------------------------------------------------------------- +np.abs 156 156 0 100.0% +np.sum 1560 1554 6 99.6% +np.mean 1560 1560 0 100.0% +np.dot 324 320 4 98.8% +np.random.choice 240 228 12 95.0% +... + +FAILURES (first 10) +-------------------------------------------------------------------------------- +[FAIL] np.sum.case042:zeros3x4_axis5_keepdimsF + NumPy: AxisError: axis 5 is out of bounds for array of dimension 2 + NumSharp: ArgumentOutOfRangeException: Axis must be within array dimensions + Issue: Exception message mismatch + +[FAIL] np.dot.case089:arange6_zeros3x4 + NumPy: ValueError: shapes (6,) and (3,4) not aligned + NumSharp: IncorrectShapeException: Shapes are not aligned for dot product + Issue: Exception message mismatch +``` + +--- + +## Sequential Execution + +For functions with shared state (like `np.random.*`), use `[Sequential]`: + +```csharp +[Sequential("np.random")] // Group name +public class NpRandomContracts : Contract +{ + public override IEnumerable TestCases() + { + yield return np.random.seed(42); + yield return np.random.rand(Vary((3,4), (5,), (2,3,4))); + yield return np.random.randn(Vary((2,3), (4,))); + } +} +``` + +### Executor Handles Re-seeding + +The contract is declarative — it doesn't manage state. The **executor** handles re-seeding: + +``` +For np.random.rand with shapes [(3,4), (5,), (2,3,4)]: + + seed(42) → rand(3,4) → compare with Python + seed(42) → rand(5,) → compare with Python ← re-seeded! + seed(42) → rand(2,3,4) → compare with Python ← re-seeded! +``` + +Each expanded test case starts fresh from the seed. The executor: +1. Detects `seed()` calls in sequential groups +2. Re-runs the seed before each subsequent expanded case +3. Ensures deterministic, independent test cases + +### Execution Order + +- Cases **within same group** run sequentially (in yield order) +- **Different groups** run in parallel with each other +- **Non-sequential contracts** run fully in parallel + +### Why This Matters + +Without re-seeding: +``` +seed(42) → rand(3,4) → rand(5,) → rand(2,3,4) + ↑ ↑ ↑ + state A state B state C +``` + +The `rand(5,)` result depends on `rand(3,4)` running first — fragile. + +With re-seeding: +``` +seed(42) → rand(3,4) # Independent +seed(42) → rand(5,) # Independent +seed(42) → rand(2,3,4) # Independent +``` + +Each test is self-contained and reproducible. + +--- + +## Project Structure + +``` +test/NumSharp.Tests.Battletesting/ +├── NumSharp.Tests.Battletesting.csproj +│ +├── Core/ +│ ├── Contract.cs # Base class with np, markers, Vary() +│ ├── Call.cs # Captured call object +│ ├── NpCapture.cs # DynamicObject for np proxy +│ ├── ArraySpec.cs # Array builder specs +│ ├── Marker.cs # Variation markers +│ ├── Vary.cs # Inline variations +│ └── Expander.cs # Marker → concrete values +│ +├── Contracts/ +│ ├── NpMathContracts.cs # abs, sum, mean, dot, ... +│ ├── NpCreationContracts.cs # zeros, ones, arange, ... +│ ├── NpManipulationContracts.cs # reshape, transpose, ... +│ ├── NpRandomContracts.cs # rand, randn, choice, ... +│ └── NpLinalgContracts.cs # dot, matmul, svd, ... +│ +├── Runners/ +│ ├── PythonRunner.cs # Launches Python, reads results +│ ├── NumSharpRunner.cs # Executes C# calls +│ └── runner.py # Embedded Python script +│ +├── Comparison/ +│ ├── ResultComparator.cs # Compare NumPy vs NumSharp +│ └── ToleranceConfig.cs # Rtol, Atol, ExactMatch +│ +├── Reports/ +│ ├── ConsoleReporter.cs +│ ├── MarkdownReporter.cs +│ └── JsonReporter.cs +│ +└── Program.cs # CLI entry point +``` + +--- + +## CLI Usage + +```bash +# Run all tests +dotnet run --project test/NumSharp.Tests.Battletesting + +# Run specific contract +dotnet run -- --contract NpMathContracts + +# Run specific function pattern +dotnet run -- --filter "np.sum*" + +# Limit cases per function +dotnet run -- --max-cases 100 + +# Output formats +dotnet run -- --output console +dotnet run -- --output markdown --output-file report.md + +# Show only failures +dotnet run -- --failures-only +``` + +--- + +## Summary + +### The Framework is Minimal + +| Step | What Happens | +|------|--------------| +| 1. **Write contracts** | `yield return np.function(markers)` — semantic, not execution | +| 2. **Markers expand** | Grid expansion (cross product), context-aware | +| 3. **Python runs first** | Creates arrays, executes operations, saves artifacts | +| 4. **NumSharp runs second** | Loads artifacts, executes same operations, compares | +| 5. **Every step verified** | Chained operations compare each intermediate | +| 6. **Report alignment** | Per-function statistics, mismatch details | + +### Key Design Principles + +| Principle | Meaning | +|-----------|---------| +| **Semantic yield** | `yield return` describes what to test, doesn't execute | +| **Python-first** | Python is source of truth; NumSharp validates against it | +| **Grid expansion** | `np.dot(arrays, arrays)` = N² combinations | +| **Chained verification** | `arange(24).reshape(2,3,4)` verifies both steps | +| **Executor manages state** | Re-seeding, sequencing, parallelization outside contracts | +| **Errors are valid tests** | Both throwing = PASS (same behavior) | + +### Coverage + +~100 lines of contract definitions → thousands of test cases covering the entire NumPy API. diff --git a/docs/plans/DESIGN_CHALLENGE_10_FUNCTIONS.md b/docs/plans/DESIGN_CHALLENGE_10_FUNCTIONS.md new file mode 100644 index 000000000..55233d4ad --- /dev/null +++ b/docs/plans/DESIGN_CHALLENGE_10_FUNCTIONS.md @@ -0,0 +1,182 @@ +# Design Challenge: 10 Diverse NumSharp Functions + +Testing the dynamic `yield return` approach against 10 challenging functions. + +--- + +## The 10 Functions + +| # | Function | Challenge | How Dynamic Approach Handles It | +|---|----------|-----------|--------------------------------| +| 1 | `np.unique` | Variable return count (1-4) based on flags | Just works - compare whatever comes back | +| 2 | `np.modf` | Fixed tuple return (2 arrays) | Just works - tuples compare element-wise | +| 3 | `np.linspace` | Multiple params, edge cases | `Vary()` for custom values | +| 4 | `np.meshgrid` | String param (`indexing`) | `Vary("xy", "ij")` | +| 5 | `np.concatenate` | Array tuple input | Custom `array_tuples` marker | +| 6 | `np.dot` | Behavior varies by ndim | Test all combos, errors are valid results | +| 7 | `np.searchsorted` | String param (`side`) | `Vary("left", "right")` | +| 8 | `np.nonzero` | Returns ndim-tuple | Just works - compare tuple lengths | +| 9 | `np.random.choice` | Probability array param | Context-aware `probs` marker | +| 10 | `np.broadcast_to` | Shape compatibility | Context-aware `broadcast_shapes` marker | + +--- + +## Contract Definitions + +```csharp +public class ChallengeContracts : Contract +{ + public override IEnumerable TestCases() + { + // 1. np.unique - variable return count based on flags + // No special handling needed - framework compares whatever NumPy returns + yield return np.unique(arrays); + yield return np.unique(arrays, return_index: bools); + yield return np.unique(arrays, return_index: bools, return_inverse: bools); + yield return np.unique(arrays, return_index: bools, return_inverse: bools, return_counts: bools); + + // 2. np.modf - always returns (fractional, integral) tuple + yield return np.modf(arrays); + yield return np.modf(arrays_float); + + // 3. np.linspace - scalar params with edge cases + yield return np.linspace(scalars, scalars, Vary(0, 1, 2, 50, 100)); + yield return np.linspace(Vary(0, -10, 1e10), Vary(1, 10, -1e10), 50); + + // 4. np.meshgrid - string indexing parameter + yield return np.meshgrid(arange(3), arange(4), indexing: Vary("xy", "ij")); + yield return np.meshgrid(arange(5), arange(3), indexing: Vary("xy", "ij"), sparse: bools); + + // 5. np.concatenate - tuple of arrays + yield return np.concatenate(array_tuples, axis: Vary(0, 1, -1)); + yield return np.concatenate(array_tuples_3, axis: 0); // 3 arrays + + // 6. np.dot - behavior varies by ndim, incompatible shapes should error + yield return np.dot(arrays, arrays); // All combos, errors are valid + yield return np.dot(arange(6), arange(6)); // 1D inner product + yield return np.dot(zeros(3, 4), zeros(4, 5)); // 2D matmul + yield return np.dot(arange(6), zeros(3, 4)); // Should error + + // 7. np.searchsorted - side parameter + yield return np.searchsorted(sorted_arrays, scalars, side: Vary("left", "right")); + yield return np.searchsorted(arange(10), Vary(0, 5, 9, 10, -1, 100), side: Vary("left", "right")); + + // 8. np.nonzero - returns tuple with length = ndim + yield return np.nonzero(arrays); + yield return np.nonzero(eye(5)); + yield return np.nonzero(zeros(3, 4, 5)); // Returns 3-tuple of empty arrays + + // 9. np.random.choice - probability array must match size + yield return np.random.choice(Vary(5, 10), size: shapes, replace: bools, p: probs); + yield return np.random.choice(5, p: Vary(null, array(0.1, 0.2, 0.3, 0.2, 0.2))); + yield return np.random.choice(3, p: array(0.5, 0.5, 0.5)); // Invalid - should error + + // 10. np.broadcast_to - shape must be compatible + yield return np.broadcast_to(arrays, broadcast_shapes); + yield return np.broadcast_to(arange(4), Vary(new[]{3,4}, new[]{2,3,4})); + yield return np.broadcast_to(zeros(3, 1), Vary(new[]{3,4}, new[]{2,3,4})); + yield return np.broadcast_to(arange(4), new[]{3,3}); // Should error + } + + // Custom markers + Marker array_tuples => new("array_tuples"); // Pairs of compatible arrays + Marker array_tuples_3 => new("array_tuples_3"); // Triples of compatible arrays + Marker sorted_arrays => new("sorted_arrays"); + Marker probs => new("probs"); // Context-aware probabilities + Marker broadcast_shapes => new("broadcast_shapes"); +} +``` + +--- + +## Why This Works + +### No Special Attributes Needed + +The old design required: +- `[ConditionalReturns]` for np.unique +- `[NdimMatchingReturns]` for np.nonzero +- `[ArraySequenceParameter]` for np.concatenate +- `[VariadicInput]` for np.meshgrid +- etc. + +The dynamic approach needs **none of these**. The framework simply: +1. Runs the Python code +2. Runs the C# code +3. Compares whatever comes back + +### Variable Returns Just Work + +```csharp +// np.unique with all flags = returns 4 arrays +yield return np.unique(arrays, return_index: true, return_inverse: true, return_counts: true); + +// NumPy returns: (unique, indices, inverse, counts) +// NumSharp returns: (NDArray, NDArray, NDArray, NDArray) +// Comparison: Element-wise on each tuple position +``` + +No need to declare the return structure - just compare what you get. + +### Errors Are Valid Test Results + +```csharp +yield return np.dot(arange(6), zeros(3, 4)); // Incompatible shapes +``` + +- NumPy throws: `ValueError: shapes (6,) and (3,4) not aligned` +- NumSharp throws: `IncorrectShapeException: Shapes not aligned for dot product` +- **Both threw = PASS** (same behavior, lenient by default) + +The report shows both messages for review, but doesn't fail on text differences. + +### Context-Aware Markers Handle Dependencies + +```csharp +yield return np.random.choice(Vary(5, 10), p: probs); +``` + +The `probs` marker sees that `a=5` or `a=10` and generates: +- For a=5: `null`, `[0.2, 0.2, 0.2, 0.2, 0.2]`, `[0.9, 0.025, ...]` +- For a=10: `null`, `[0.1, 0.1, ...]`, etc. + +### Inline Vary() for Edge Cases + +```csharp +yield return np.searchsorted(arange(10), Vary(0, 5, 9, 10, -1, 100), side: Vary("left", "right")); +``` + +Generates 12 test cases (6 values × 2 sides) with one line. + +--- + +## Generated Test Counts + +| Function | Contract Lines | Expanded Cases | +|----------|---------------|----------------| +| np.unique | 4 | 16+ (2 arrays × 2³ flag combos) | +| np.modf | 2 | 4+ | +| np.linspace | 2 | 50+ | +| np.meshgrid | 2 | 8+ | +| np.concatenate | 2 | 6+ | +| np.dot | 4 | 20+ | +| np.searchsorted | 2 | 24+ | +| np.nonzero | 3 | 6+ | +| np.random.choice | 3 | 36+ | +| np.broadcast_to | 4 | 12+ | +| **Total** | **~28** | **~180+** | + +--- + +## Conclusion + +The dynamic `yield return` approach handles all 10 challenges with: +- **No special attributes** — Just yield what you want to test +- **No complex type system** — Compare whatever comes back +- **Semantic yields** — Descriptions, not execution +- **Python-first execution** — Python creates artifacts, NumSharp validates +- **Chained verification** — Every intermediate step is compared +- **Grid expansion** — `np.dot(arrays, arrays)` = N² combinations +- **Errors are valid** — Both throwing = PASS + +The framework's job is simple: run Python, save artifacts, run NumSharp, compare. diff --git a/docs/plans/EXCEPTION_REDESIGN.md b/docs/plans/EXCEPTION_REDESIGN.md new file mode 100644 index 000000000..2aff49882 --- /dev/null +++ b/docs/plans/EXCEPTION_REDESIGN.md @@ -0,0 +1,681 @@ +# NumSharp Exception Redesign + +## Goals + +1. **NumPy message compatibility**: First line matches NumPy exactly +2. **Rich context**: Second line provides NumSharp-specific debugging info +3. **Catchable hierarchy**: Exceptions grouped by category +4. **Replace blank throws**: 158+ throws with no message get proper context + +--- + +## Document Status + +| Section | Status | +|---------|--------| +| Current exceptions inventory | COMPLETE | +| NumPy message verification | COMPLETE (10/10 verified from source) | +| New hierarchy design | COMPLETE | +| Migration mapping | COMPLETE (382 throws categorized) | +| Throw helper design | COMPLETE | +| Implementation | NOT STARTED | + +**Last Updated:** Based on NumPy v2.4.2 source at `src/numpy/` + +--- + +## Part 1: Current NumSharp Exceptions + +### Existing Exception Classes + +| Class | File | Inherits | Current Usage | +|-------|------|----------|---------------| +| `NumSharpException` | `Exceptions/NumSharpException.cs` | `Exception` | Base class, has `ThrowIfNotWriteable` helper | +| `IncorrectShapeException` | `Exceptions/IncorrectShapeException.cs` | `NumSharpException` | ~40 throws | +| `IncorrectTypeException` | `Exceptions/IncorrectTypeException.cs` | `NumSharpException` | ~5 throws | +| `IncorrectSizeException` | `Exceptions/IncorrectSizeException.cs` | `NumSharpException` | ~19 throws | +| `AxisOutOfRangeException` | `Exceptions/AxisOutOfRangeException.cs` | `ArgumentOutOfRangeException` | ~2 throws | + +### Current Throw Patterns (501 total) + +| Pattern | Count | Quality | Target Exception | +|---------|-------|---------|------------------| +| `NotSupportedException()` | 156 | BAD - no message | `UnsupportedDTypeException` | +| `NotSupportedException("...")` | 74 | MIXED | various | +| `ArgumentNullException(nameof(...))` | 79 | OK | keep | +| `ArgumentException("...")` | 56 | OK | keep or migrate | +| `ArgumentOutOfRangeException()` | 33 | BAD - no message | `AxisOutOfRangeException` | +| `ArgumentOutOfRangeException("...")` | 14 | OK | review | +| `IncorrectShapeException()` | 18 | BAD - no message | `BroadcastException`/`ReshapeException` | +| `IncorrectShapeException("...")` | 22 | MIXED | review | +| `IncorrectSizeException("...")` | 19 | OK | keep or `ScalarConversionException` | +| `IncorrectTypeException()` | 3 | BAD - no message | `UnsupportedDTypeException` | +| `Exception("...")` | 13 | BAD - generic | `InternalException` or specific | +| `IndexOutOfRangeException("...")` | 7 | OK | `IndexException` | +| `InvalidOperationException("...")` | 5 | MIXED | various | +| `ReadOnlyException()` | 3 | BAD - System.Data | `ReadOnlyArrayException` | + +--- + +## Part 2: NumPy Error Messages (Source Verified) + +### Shape Errors + +| Error Type | NumPy Message | NumPy Source Location | Verified | +|------------|---------------|----------------------|----------| +| Broadcast failure (simple) | `operands could not be broadcast together with shapes (2,3) (4,)` | `_core/src/multiarray/nditer_constr.c:1740` | YES | +| Broadcast failure (with requested) | `operands could not be broadcast together with shapes (2,3) and requested shape (5,)` | `_core/src/multiarray/nditer_constr.c:1752` | YES | +| Reshape size mismatch | `cannot reshape array of size 24 into shape (3,6)` | `_core/src/multiarray/shape.c:467` | YES | +| Dimension mismatch | *(varies by context - no single standard message)* | various | NO | + +### Axis Errors + +| Error Type | NumPy Message | NumPy Source Location | Verified | +|------------|---------------|----------------------|----------| +| Axis out of range | `axis {axis} is out of bounds for array of dimension {ndim}` | `numpy/exceptions.py:193` | YES | +| With prefix | `{prefix}: axis {axis} is out of bounds for array of dimension {ndim}` | `numpy/exceptions.py:195` | YES | + +**Note:** NumPy's `AxisError` inherits from BOTH `ValueError` AND `IndexError` for backwards compatibility. + +### Index Errors + +| Error Type | NumPy Message | NumPy Source Location | Verified | +|------------|---------------|----------------------|----------| +| Index out of bounds | `index {obj} is out of bounds for axis {axis} with size {size}` | `lib/_function_base_impl.py:5354` | YES | + +### Type/DType Errors + +| Error Type | NumPy Message | NumPy Source Location | Verified | +|------------|---------------|----------------------|----------| +| Ufunc not supported | `ufunc '{name}' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule '{rule}'` | `_core/src/umath/ufunc_type_resolution.c:1997` | YES | +| Loop not supported | `loop of ufunc does not support argument {i} of type {type} which has no callable {method} method` | `_core/src/umath/loops.c.src:233` | YES | +| Type promotion failure | `The DType could not be promoted by ...` | `numpy/exceptions.py:227` (DTypePromotionError) | YES | + +**Note:** NumPy's `DTypePromotionError` inherits from `TypeError`. + +### Size/Empty Errors + +| Error Type | NumPy Message | NumPy Source Location | Verified | +|------------|---------------|----------------------|----------| +| Empty array reduction | `zero-size array to reduction operation {funcname} which has no identity` | `_core/src/umath/reduction.c:101` | YES | +| Empty argmax/argmin | `attempt to get {func_name} of an empty sequence` | `_core/src/multiarray/calculation.c:142` | YES | + +### Read-Only Errors + +| Error Type | NumPy Message | NumPy Source Location | Verified | +|------------|---------------|----------------------|----------| +| Assignment to read-only | `{name} is read-only` | `_core/src/multiarray/arrayobject.c:560` | YES | + +**Note:** The `{name}` parameter is typically "assignment destination", "output array", or "array". + +--- + +## Part 3: New Exception Hierarchy + +``` +NumSharpException (base) +| ++-- ShapeException +| +-- BroadcastException +| +-- ReshapeException +| +-- DimensionMismatchException +| ++-- DTypeException +| +-- UnsupportedDTypeException +| +-- TypeMismatchException +| ++-- AxisOutOfRangeException (existing, enhanced) +| ++-- IndexException +| ++-- SizeException +| +-- EmptyArrayException +| +-- ScalarConversionException +| ++-- MemoryLayoutException +| +-- NonContiguousException +| +-- ReadOnlyArrayException +| ++-- InternalException +``` + +--- + +## Part 4: Detailed Migration Mapping + +### 4.1 NotSupportedException() - 156 cases + +**By File (top contributors):** + +| File | Count | Context | New Exception | +|------|-------|---------|---------------| +| `Backends/Unmanaged/UnmanagedMemoryBlock.Casting.cs` | 34 | Type switch default | `UnsupportedDTypeException` | +| `Utilities/Converts.cs` | 30 | Type switch default | `UnsupportedDTypeException` | +| `Backends/Unmanaged/ArraySlice.cs` | 20 | Type switch default | `UnsupportedDTypeException` | +| `Backends/NPTypeCode.cs` | 18 | Type switch default | `UnsupportedDTypeException` | +| `Backends/Iterators/NDIteratorExtensions.cs` | 10 | Type switch default | `UnsupportedDTypeException` | +| `Backends/Iterators/MultiIterator.cs` | 10 | Type switch default | `UnsupportedDTypeException` | +| `Backends/Unmanaged/UnmanagedStorage.cs` | 8 | Type switch default | `UnsupportedDTypeException` | +| `Casting/Implicit/NdArray.Implicit.Array.cs` | 6 | Type switch default | `UnsupportedDTypeException` | +| `Backends/Unmanaged/UnmanagedMemoryBlock.cs` | 6 | Type switch default | `UnsupportedDTypeException` | +| Other files | 14 | Various | Review individually | + +**Pattern:** Most are `default:` cases in `switch (typeCode)` statements. All should become: +```csharp +default: throw new UnsupportedDTypeException(typeCode, "OperationName"); +// or using helper: +default: Throw.UnsupportedDType(typeCode); // auto-captures method name +``` + +**Sample migration:** +```csharp +// BEFORE (no context): +default: + throw new NotSupportedException(); + +// AFTER (NumPy-style + context): +default: + throw new UnsupportedDTypeException(typeCode, "FromMultiDimArray"); + // Message: "FromMultiDimArray() does not support dtype 'complex64'" +``` + +### 4.2 ArgumentOutOfRangeException() - 72 blank cases + +**IMPORTANT:** These are NOT axis errors! They are type switch defaults. + +**By File (top contributors):** + +| File | Count | Context | New Exception | +|------|-------|---------|---------------| +| `Backends/Iterators/NDIterator.Cast.*.cs` | 48 | Type switch default | `UnsupportedDTypeException` | +| `Utilities/ArrayConvert.cs` | 15 | Type switch default | `UnsupportedDTypeException` | +| `Backends/Iterators/NDIterator.cs` | 4 | Type switch default | `UnsupportedDTypeException` | +| `Backends/Iterators/NDIterator.template.cs` | 4 | Template file | `UnsupportedDTypeException` | +| `Backends/Unmanaged/UnmanagedMemoryBlock.cs` | 1 | Type switch default | `UnsupportedDTypeException` | + +### 4.2b ArgumentOutOfRangeException(nameof(axis)) - 25 cases + +**These ARE axis errors and should use `AxisOutOfRangeException`:** + +| File | Line | Current | New Message | +|------|------|---------|-------------| +| `np.any.cs` | 74 | `nameof(axis)` only | `axis {axis} is out of bounds for array of dimension {ndim}` | +| `np.all.cs` | 73 | `nameof(axis)` only | `axis {axis} is out of bounds for array of dimension {ndim}` | +| `NDArray.cs` | 557 | `nameof(axis)` only | `axis {axis} is out of bounds for array of dimension {ndim}` | +| `np.squeeze.cs` | 35 | `nameof(axis)` only | `axis {axis} is out of bounds for array of dimension {ndim}` | +| `np.nansum.cs` | 154 | `nameof(axis)` only | `axis {axis} is out of bounds for array of dimension {ndim}` | +| `np.nanvar.cs` | 164 | Has message already | KEEP (already NumPy format) | +| `np.nanstd.cs` | 164 | Has message already | KEEP (already NumPy format) | +| `np.nanmean.cs` | 111 | Has message already | KEEP (already NumPy format) | +| `np.count_nonzero.cs` | 39 | `nameof(axis)` only | `axis {axis} is out of bounds for array of dimension {ndim}` | +| Various reduction files | ~15 | `nameof(axis)` or `nameof(axis_)` | `axis {axis} is out of bounds for array of dimension {ndim}` | + +**Migration:** Replace with `throw new AxisOutOfRangeException(ndim, axis);` + +### 4.3 IncorrectShapeException() - 18 cases + +**By context:** + +| File | Count | Context | New Exception | New Message | +|------|-------|---------|---------------|-------------| +| `Casting/Implicit/NdArray.Implicit.ValueTypes.cs` | 13 | `if (nd.ndim != 0)` - scalar conversion | `ScalarConversionException` | `cannot convert {ndim}D array to scalar` | +| `RandomSampling/np.random.uniform.cs` | 1 | Shape validation | `BroadcastException` | Review context | +| `Creation/np.mgrid.cs` | 1 | Invalid input | `ShapeException` | Review context | +| `Operations/Elementwise/NdArray.DetermineEmptyResult.cs` | 1 | Shape mismatch | `BroadcastException` | NumPy msg | +| `LinearAlgebra/NdArray.multi_dot.cs` | 2 | Commented out | N/A | Dead code | + +**Note:** The scalar conversion cases (13 of 18) should use a new `ScalarConversionException`: +```csharp +// BEFORE: +if (nd.ndim != 0) + throw new IncorrectShapeException(); + +// AFTER: +if (nd.ndim != 0) + throw new ScalarConversionException(nd.ndim); + // Message: "cannot convert 2D array to scalar (must be 0D)" +``` + +### 4.4 Exception("...") - 13 cases + +| File | Line | Current Message | New Exception | New Message | +|------|------|-----------------|---------------|-------------| +| `np.save.cs` | 185 | `""` | `InternalException` | TBD | +| `np.vstack.cs` | 14 | `"Input arrays can not be empty"` | `EmptyArrayException` | NumPy msg TBD | +| `np.vstack.cs` | 20 | `"Arrays mush have same shapes"` | `BroadcastException` | NumPy msg TBD | +| `NDArray.Indexing.Selection.Setter.cs` | 194 | `"if (nd.typecode == NPTypeCode.Boolean)"` | `InternalException` | internal error | +| `np.load.cs` | 314, 322, 383 | `""` | `InternalException` | TBD | +| `NdArrayFromJaggedArr.cs` | 33 | `"Multi dim arrays are not allowed here!"` | `ArgumentException` | TBD | +| `NDArray.matrix_power.cs` | 10 | `"matrix_power just work with int >= 0"` | `ArgumentOutOfRangeException` | TBD | +| `Default.Transpose.cs` | 72 | `"source and destination arguments must have..."` | `IncorrectShapeException` | TBD | +| `Default.Transpose.cs` | 106 | `"start arg requires start <= n + 1..."` | `ArgumentOutOfRangeException` | TBD | +| `Default.Transpose.cs` | 141 | `"axes don't match array"` | `AxisOutOfRangeException` | TBD | +| `Default.Transpose.cs` | 150 | `"repeated axis in transpose"` | `ArgumentException` | TBD | + +### 4.5 ReadOnlyException() - 3 cases + +**Source:** `System.Data.ReadOnlyException` - wrong namespace for a math library! + +| File | Line | Context | New Exception | New Message | +|------|------|---------|---------------|-------------| +| `Utilities/NpzDictionary.cs` | 143 | `Add()` method | `NotSupportedException` | `NpzDictionary is read-only` | +| `Utilities/NpzDictionary.cs` | 148 | `Clear()` method | `NotSupportedException` | `NpzDictionary is read-only` | +| `Utilities/NpzDictionary.cs` | 161 | `Remove()` method | `NotSupportedException` | `NpzDictionary is read-only` | + +**Note:** These are collection operations, not array operations. Use standard `NotSupportedException` with message. + +### 4.6 NumSharpException.ThrowReadOnly() - existing helper + +Already exists in `NumSharpException.cs:50` with NumPy-compatible format: +```csharp +throw new NumSharpException($"{name} is read-only"); +// Default name: "assignment destination" +``` + +**Decision:** Move this to `Throw.ReadOnly()` helper and create `ReadOnlyArrayException` for array-specific cases. + +--- + +## Part 5: New Exception Class Specifications + +### 5.1 BroadcastException + +```csharp +/// Shapes cannot be broadcast together. +public class BroadcastException : ShapeException +{ + public int[] ShapeA { get; } + public int[] ShapeB { get; } + + // NumPy message (verified): "operands could not be broadcast together with shapes (2,3) (4,)" + public BroadcastException(int[] a, int[] b) + : base($"operands could not be broadcast together with shapes {Fmt(a)} {Fmt(b)}") { ... } + + // NumPy message with requested shape + public BroadcastException(int[] a, int[] b, int[] requested) + : base($"operands could not be broadcast together with shapes {Fmt(a)} and requested shape {Fmt(requested)}") { ... } +} +``` + +### 5.2 ReshapeException + +```csharp +/// Array cannot be reshaped to target shape. +public class ReshapeException : ShapeException +{ + public int SourceSize { get; } + public int[] TargetShape { get; } + + // NumPy message (verified): "cannot reshape array of size 24 into shape (3,6)" + public ReshapeException(int sourceSize, int[] targetShape) + : base($"cannot reshape array of size {sourceSize} into shape {Fmt(targetShape)}") { ... } +} +``` + +### 5.3 AxisOutOfRangeException (existing - enhanced) + +```csharp +/// Axis is out of bounds. +/// Inherits from both ValueError and IndexError like NumPy's AxisError. +public class AxisOutOfRangeException : ArgumentOutOfRangeException, INumSharpException +{ + public int Axis { get; } + public int NDim { get; } + public int[]? Shape { get; } // NEW: optional shape context + + // NumPy message (verified): "axis {axis} is out of bounds for array of dimension {ndim}" + public AxisOutOfRangeException(int ndim, int axis) + : base("axis", $"axis {axis} is out of bounds for array of dimension {ndim}") { ... } + + // With shape context (NumSharp enhancement) + public AxisOutOfRangeException(int ndim, int axis, int[] shape) + : base("axis", $"axis {axis} is out of bounds for array of dimension {ndim}\n -> array.shape={Fmt(shape)}") { ... } +} +``` + +### 5.4 IndexException + +```csharp +/// Index is out of bounds. +public class IndexException : NumSharpException +{ + public int Index { get; } + public int Axis { get; } + public int Size { get; } + + // NumPy message (verified): "index {obj} is out of bounds for axis {axis} with size {size}" + public IndexException(int index, int axis, int size) + : base($"index {index} is out of bounds for axis {axis} with size {size}") { ... } +} +``` + +### 5.5 UnsupportedDTypeException + +```csharp +/// Operation does not support the given dtype. +public class UnsupportedDTypeException : DTypeException +{ + public NPTypeCode TypeCode { get; } + public string? Operation { get; } + + // NumPy message (verified): "ufunc '{name}' not supported for the input types..." + // Simplified for NumSharp: "{operation}() does not support dtype '{dtype}'" + public UnsupportedDTypeException(NPTypeCode typeCode, string operation) + : base($"{operation}() does not support dtype '{typeCode}'") { ... } + + // For switch default (auto-captures caller) + public static UnsupportedDTypeException ForSwitch( + NPTypeCode typeCode, + [CallerMemberName] string? operation = null) + => new(typeCode, operation ?? "unknown"); +} +``` + +### 5.6 EmptyArrayException + +```csharp +/// Operation cannot be performed on an empty array. +public class EmptyArrayException : SizeException +{ + public string? Operation { get; } + + // NumPy message (verified): "zero-size array to reduction operation {funcname} which has no identity" + public static EmptyArrayException NoIdentity(string operation) + => new($"zero-size array to reduction operation {operation} which has no identity"); + + // NumPy message (verified): "attempt to get {func_name} of an empty sequence" + public static EmptyArrayException EmptySequence(string operation) + => new($"attempt to get {operation} of an empty sequence"); +} +``` + +### 5.7 ScalarConversionException + +```csharp +/// Array cannot be converted to scalar (not 0-dimensional). +public class ScalarConversionException : SizeException +{ + public int NDim { get; } + + // NumSharp-specific (NumPy uses different mechanism via .item()) + public ScalarConversionException(int ndim) + : base($"cannot convert {ndim}D array to scalar (must be 0D)") { ... } +} +``` + +### 5.8 ReadOnlyArrayException + +```csharp +/// Array is read-only and cannot be modified. +public class ReadOnlyArrayException : MemoryLayoutException +{ + // NumPy message (verified): "{name} is read-only" + public ReadOnlyArrayException(string name = "assignment destination") + : base($"{name} is read-only") { } + + // With context (NumSharp enhancement) + public static ReadOnlyArrayException BroadcastView() + => new("assignment destination is read-only\n -> array is a broadcast view (stride=0 dimension)"); +} +``` + +### 5.9 NonContiguousException + +```csharp +/// Operation requires contiguous memory layout. +public class NonContiguousException : MemoryLayoutException +{ + // NumSharp-specific (NumPy handles this differently) + public static NonContiguousException CannotPin() + => new("cannot pin reference when array is sliced or broadcasted"); + + public static NonContiguousException CannotSpan() + => new("cannot create Span over non-contiguous storage"); +} +``` + +### 5.10 InternalException + +```csharp +/// Internal error that should not occur in normal operation. +public class InternalException : NumSharpException +{ + // For "this shouldn't happen" cases - replaces generic Exception throws + public InternalException(string message) + : base($"internal error: {message} (please report this bug)") { } +} +``` + +--- + +## Part 6: Throw Helper Specifications + +```csharp +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace NumSharp; + +/// +/// Centralized throw helpers with context capture. +/// All methods are [DoesNotReturn] to help flow analysis. +/// +public static class Throw +{ + // ===== Shape Errors ===== + + [DoesNotReturn] + public static void CannotBroadcast(int[] a, int[] b) + => throw new BroadcastException(a, b); + + [DoesNotReturn] + public static void CannotBroadcast(Shape a, Shape b) + => throw new BroadcastException(a.Dimensions, b.Dimensions); + + [DoesNotReturn] + public static void CannotReshape(int size, int[] target) + => throw new ReshapeException(size, target); + + // ===== DType Errors ===== + + /// + /// For type switch default cases. Auto-captures method name. + /// + [DoesNotReturn] + public static void UnsupportedDType(NPTypeCode typeCode, [CallerMemberName] string? op = null) + => throw UnsupportedDTypeException.ForSwitch(typeCode, op); + + // ===== Axis Errors ===== + + [DoesNotReturn] + public static void AxisOutOfRange(int axis, int ndim) + => throw new AxisOutOfRangeException(ndim, axis); + + [DoesNotReturn] + public static void AxisOutOfRange(int axis, int ndim, int[] shape) + => throw new AxisOutOfRangeException(ndim, axis, shape); + + /// + /// Normalize axis (handle negative) and throw if out of range. + /// + public static int NormalizeAxis(int axis, int ndim) + { + if (axis < -ndim || axis >= ndim) + throw new AxisOutOfRangeException(ndim, axis); + return axis < 0 ? ndim + axis : axis; + } + + // ===== Index Errors ===== + + [DoesNotReturn] + public static void IndexOutOfBounds(int index, int axis, int size) + => throw new IndexException(index, axis, size); + + // ===== Size Errors ===== + + [DoesNotReturn] + public static void EmptyArray([CallerMemberName] string? op = null) + => throw EmptyArrayException.NoIdentity(op ?? "unknown"); + + [DoesNotReturn] + public static void EmptySequence([CallerMemberName] string? op = null) + => throw EmptyArrayException.EmptySequence(op ?? "unknown"); + + [DoesNotReturn] + public static void CannotConvertToScalar(int ndim) + => throw new ScalarConversionException(ndim); + + // ===== Memory Layout Errors ===== + + [DoesNotReturn] + public static void CannotPin() + => throw NonContiguousException.CannotPin(); + + [DoesNotReturn] + public static void ReadOnly(string name = "assignment destination") + => throw new ReadOnlyArrayException(name); + + /// + /// Check if array is writeable, throw if not. + /// Equivalent to NumPy's PyArray_FailUnlessWriteable. + /// + public static void IfNotWriteable(in Shape shape, string name = "assignment destination") + { + if (!shape.IsWriteable) + throw new ReadOnlyArrayException(name); + } + + // ===== Null Checks ===== + + public static void IfNull([NotNull] T? value, [CallerArgumentExpression(nameof(value))] string? name = null) + where T : class + { + if (value is null) + throw new ArgumentNullException(name); + } + + // ===== Internal Errors ===== + + [DoesNotReturn] + public static void Internal(string message) + => throw new InternalException(message); +} +``` + +### Usage Examples + +```csharp +// BEFORE (no context): +default: + throw new NotSupportedException(); + +// AFTER (auto-captures method name): +default: + Throw.UnsupportedDType(typeCode); // -> "MethodName() does not support dtype 'int8'" + +// BEFORE: +if (axis < 0 || axis >= ndim) + throw new ArgumentOutOfRangeException(nameof(axis)); + +// AFTER: +axis = Throw.NormalizeAxis(axis, ndim); // handles negative, throws with NumPy message + +// BEFORE: +if (!shape.IsWriteable) + throw new ReadOnlyException(); + +// AFTER: +Throw.IfNotWriteable(shape); // -> "assignment destination is read-only" +``` + +--- + +## Part 7: Files to Create/Modify + +### New Files + +| File | Purpose | +|------|---------| +| `Exceptions/ShapeException.cs` | Base + BroadcastException + ReshapeException + DimensionMismatchException | +| `Exceptions/DTypeException.cs` | Base + UnsupportedDTypeException + TypeMismatchException | +| `Exceptions/IndexException.cs` | Index out of bounds | +| `Exceptions/SizeException.cs` | Base + EmptyArrayException + ScalarConversionException | +| `Exceptions/MemoryLayoutException.cs` | Base + NonContiguousException + ReadOnlyArrayException | +| `Exceptions/InternalException.cs` | For "should not happen" cases | +| `Exceptions/Throw.cs` | Static throw helpers | + +### Modified Files + +| File | Changes | +|------|---------| +| `Exceptions/NumSharpException.cs` | Keep as base, remove `ThrowIfNotWriteable` (moved to `Throw`) | +| `Exceptions/IncorrectShapeException.cs` | DEPRECATE - redirect to ShapeException | +| `Exceptions/IncorrectTypeException.cs` | DEPRECATE - redirect to DTypeException | +| `Exceptions/IncorrectSizeException.cs` | DEPRECATE - redirect to SizeException | +| `Exceptions/AxisOutOfRangeException.cs` | ENHANCE - add optional shape context | + +--- + +## Appendix A: Throw Count Summary + +| Pattern | Count | Target | +|---------|-------|--------| +| `NotSupportedException()` blank | 156 | `UnsupportedDTypeException` | +| `NotSupportedException("...")` with message | 74 | Review - keep good ones | +| `ArgumentOutOfRangeException()` blank | 72 | `UnsupportedDTypeException` (type switches) | +| `ArgumentOutOfRangeException(nameof(axis))` | 25 | `AxisOutOfRangeException` | +| `IncorrectShapeException()` blank | 18 | Various (13 are `ScalarConversionException`) | +| `IncorrectShapeException("...")` with message | 22 | Review - align with NumPy messages | +| `IncorrectSizeException("...")` | 19 | Keep or `ScalarConversionException` | +| `Exception("...")` generic | 13 | `InternalException` or specific type | +| `ReadOnlyException()` (System.Data!) | 3 | `NotSupportedException` (collection) | +| **Total throws to migrate** | ~382 | | + +## Appendix B: NumPy Source References (v2.4.2) + +All paths relative to `src/numpy/numpy/`: + +| Error Type | Source File | Line | Verified Message | +|------------|-------------|------|------------------| +| Broadcast | `_core/src/multiarray/nditer_constr.c` | 1740 | `operands could not be broadcast together with shapes %S` | +| Broadcast+requested | `_core/src/multiarray/nditer_constr.c` | 1752 | `...with shapes %S and requested shape %S` | +| Reshape | `_core/src/multiarray/shape.c` | 467 | `cannot reshape array of size %zd into shape %S` | +| AxisError | `exceptions.py` | 193 | `axis {axis} is out of bounds for array of dimension {ndim}` | +| AxisError (class) | `exceptions.py` | 108-196 | Inherits from `ValueError, IndexError` | +| IndexError | `lib/_function_base_impl.py` | 5354 | `index {obj} is out of bounds for axis {axis} with size {size}` | +| Empty reduction | `_core/src/umath/reduction.c` | 101 | `zero-size array to reduction operation %s which has no identity` | +| Empty argmax | `_core/src/multiarray/calculation.c` | 142 | `attempt to get %s of an empty sequence` | +| Read-only | `_core/src/multiarray/arrayobject.c` | 560 | `%s is read-only` | +| Ufunc not supported | `_core/src/umath/ufunc_type_resolution.c` | 1997 | `ufunc '%s' not supported for the input types...` | +| DTypePromotionError | `exceptions.py` | 199-246 | Inherits from `TypeError` | + +## Appendix C: Files to Modify (Migration Plan) + +### Phase 1: Create New Exception Classes (0 breaking changes) + +| File | Action | +|------|--------| +| `Exceptions/ShapeException.cs` | CREATE: Base + BroadcastException + ReshapeException | +| `Exceptions/DTypeException.cs` | CREATE: Base + UnsupportedDTypeException + TypeMismatchException | +| `Exceptions/IndexException.cs` | CREATE | +| `Exceptions/SizeException.cs` | CREATE: Base + EmptyArrayException + ScalarConversionException | +| `Exceptions/MemoryLayoutException.cs` | CREATE: Base + NonContiguousException + ReadOnlyArrayException | +| `Exceptions/InternalException.cs` | CREATE | +| `Exceptions/Throw.cs` | CREATE: Static helpers | +| `Exceptions/AxisOutOfRangeException.cs` | MODIFY: Add Shape property | + +### Phase 2: Migrate High-Impact Throws + +| File Pattern | Count | Change | +|--------------|-------|--------| +| `*/default: throw new NotSupportedException();` | 156 | `Throw.UnsupportedDType(typeCode)` | +| `*/default: throw new ArgumentOutOfRangeException();` | 72 | `Throw.UnsupportedDType(typeCode)` | +| `throw new ArgumentOutOfRangeException(nameof(axis))` | 25 | `throw new AxisOutOfRangeException(ndim, axis)` | + +### Phase 3: Deprecate Old Exceptions + +| Old Class | New Class | Migration | +|-----------|-----------|-----------| +| `IncorrectShapeException` | `ShapeException` / `BroadcastException` / `ReshapeException` | Add `[Obsolete]`, inherit from new base | +| `IncorrectTypeException` | `DTypeException` / `UnsupportedDTypeException` | Add `[Obsolete]`, inherit from new base | +| `IncorrectSizeException` | `SizeException` / `ScalarConversionException` | Add `[Obsolete]`, inherit from new base | diff --git a/docs/plans/UNIFIED_ITERATOR_DESIGN.md b/docs/plans/UNIFIED_ITERATOR_DESIGN.md new file mode 100644 index 000000000..c229819ed --- /dev/null +++ b/docs/plans/UNIFIED_ITERATOR_DESIGN.md @@ -0,0 +1,536 @@ +# Unified Iterator Design (v5 — current state) + +> **Status:** implemented. The plan in v1-v4 (build a new `NDIterator` class with +> three tiers of kernels) was superseded by porting NumPy's `nditer` directly — +> now `NpyIterRef`. The three "tiers" morphed into seven layered integration +> points, all sharing one IL-emitted-kernel cache. This document captures the +> final shape and how we got here. +> +> **Production docs:** `docs/website-src/docs/NDIter.md` has the full user-facing +> reference (~1900 lines). This file is the design rationale and migration +> crib-sheet for contributors porting old patterns. + +--- + +## Design principles (unchanged from v4) + +1. **No backwards compatibility** — old iterators/incrementors deleted (done; see Migration below) +2. **Direct IL control** — users can inject their own IL at every layer +3. **Zero allocation** — struct-based state, unmanaged memory, no closures on hot paths +4. **Layered, not flat** — seven entry points on an ergonomics-vs-control axis + +## What changed since v4 + +| v4 plan | v5 reality | Why | +|---------|-----------|-----| +| Build new `NDIterator` class from scratch | Port NumPy's `nditer` as `NpyIterRef` | Every ufunc, reduction, and broadcast in NumPy already goes through it; reinventing the scheduler would re-discover the same design choices (coalescing, buffered reduction, op_axes). Porting preserves 1-to-1 behavioral parity. | +| 3 tiers (interface / IL / Func) | 7 entry points (Layer 1/2/3 + Tier 3A/3B/3C + Call) | Three layers conflated "how does the kernel dispatch?" with "what kernel shape am I authoring?". Splitting gives us baked ufuncs *and* custom-op escape hatches without mode-switching. | +| `IUnaryKernel` static abstracts | `NpyInnerLoopFunc` delegate + struct-generic `INpyInnerLoop` | Static-abstract generics don't inline reliably across assemblies on net8; struct-generic dispatch is cleaner and the `NpyInnerLoopFunc` delegate matches NumPy's C-API loop signature 1-to-1. | +| `IKernelEmitter` interface for IL injection | `Action` per-element + factory-wrapped shell | A full `IKernelEmitter` interface was overkill for the common "I just want SIMD with a custom op" case. The factory handles the unroll shell; users write only the per-element body. Raw-IL power-users use `ExecuteRawIL(Action)`. | +| `Func` delegates as Tier 3 | `ForEach(NpyInnerLoopFunc)` + `NpyExpr.Call(Delegate)` | The `Func<>` path morphed into two: Layer 1 `ForEach` for whole-loop delegates, and `NpyExpr.Call` for per-element managed methods embedded inside a DSL tree. | + +## The seven techniques + +``` + ergonomics control + ▲ ▲ + │ │ + Layer 3 │ ExecuteBinary / Unary / Reduction / Comparison / Scan │ 90% case + │ "one call, NumPy-style — one line per op" │ + ────────── │ ───────────────────────────────────────────────────────── │ ────────── + Tier 3C │ ExecuteExpression(NpyExpr) │ compose + │ "build a tree with operators; no IL in caller" │ with DSL + ────────── │ ───────────────────────────────────────────────────────── │ ────────── + Tier 3C │ NpyExpr.Call(Math.X / Func / MethodInfo, args) │ inject any + + Call │ "invoke arbitrary managed method per element" │ BCL / user op + ────────── │ ───────────────────────────────────────────────────────── │ ────────── + Tier 3B │ ExecuteElementWiseBinary(scalarBody, vectorBody) │ hand-tune + │ "write per-element IL; factory wraps the unroll shell" │ the vector body + ────────── │ ───────────────────────────────────────────────────────── │ ────────── + Tier 3A │ ExecuteRawIL(emit, key, aux) │ emit + │ "emit the whole inner-loop body including ret" │ everything + ────────── │ ───────────────────────────────────────────────────────── │ ────────── + Layer 2 │ ExecuteGeneric / ExecuteReducing │ struct- + │ "zero-alloc; JIT specializes per struct; early-exit reduce" │ generic + ────────── │ ───────────────────────────────────────────────────────── │ ────────── + Layer 1 │ ForEach(NpyInnerLoopFunc kernel, void* aux) │ delegate, + │ "closest to NumPy's C API; closures welcome" │ anything goes + │ │ + ▼ ▼ + NpyIter state (Shape, Strides, DataPtrs, Buffers, ...) + │ + ▼ + ILKernelGenerator (DynamicMethod + V128/V256/V512) +``` + +All seven share: +- one `ConcurrentDictionary` inner-loop cache +- one `ForEach` driver at the bottom (`do { kernel(dataptrs, strides, count, aux); } while (iternext);`) +- the same SIMD machinery in `ILKernelGenerator` (V128 / V256 / V512 selection at startup) + +--- + +## Layer 3 — Baked ufuncs (the 90% case) + +```csharp +using var iter = NpyIterRef.MultiNew(3, new[] { a, b, c }, + NpyIterGlobalFlags.EXTERNAL_LOOP, NPY_ORDER.NPY_KEEPORDER, + NPY_CASTING.NPY_NO_CASTING, + new[] { NpyIterPerOpFlags.READONLY, + NpyIterPerOpFlags.READONLY, + NpyIterPerOpFlags.WRITEONLY }); +iter.ExecuteBinary(BinaryOp.Add); +``` + +`ExecuteBinary / Unary / Reduction / Comparison / Scan / Copy` resolve to a cached `MixedTypeKernelKey` lookup in `ILKernelGenerator`. First call JIT-compiles; every subsequent call with matching types/path returns the cached delegate. + +Benchmark: 1M float32 `a + b` = **0.58 ms/run** (4×-unrolled V256, post-warmup). + +--- + +## Tier 3C — Expression DSL (`NpyExpr`) + +45+ node types compose with operators: + +```csharp +var x = NpyExpr.Input(0); +var pos = NpyExpr.Const(1.0) / (NpyExpr.Const(1.0) + NpyExpr.Exp(-x)); +var neg = NpyExpr.Exp(x) / (NpyExpr.Const(1.0) + NpyExpr.Exp(x)); +var stable = NpyExpr.Where( + NpyExpr.GreaterEqual(x, NpyExpr.Const(0.0)), pos, neg); + +iter.ExecuteExpression(stable, + new[] { NPTypeCode.Double }, NPTypeCode.Double); +``` + +Covers arithmetic, bitwise, rounding, transcendentals (exp/log/trig/hyperbolic/inverse-trig), predicates, comparisons, Min/Max/Clamp/Where. Auto-derives a cache key from the tree's structural signature (e.g. `NpyExpr:Sqrt(Add(Square(In[0]),Square(In[1]))):in=Single,Single:out=Single`). + +Benchmark: stable sigmoid on 1M f64 = **13.6 ms/run** (3 × `Math.Exp` per element dominates). + +## Tier 3C + Call — Inject any .NET method + +```csharp +// Typed Func overloads — method groups bind without cast +NpyExpr.Call(Math.Sqrt, NpyExpr.Input(0)); +NpyExpr.Call(Math.Pow, NpyExpr.Input(0), NpyExpr.Input(1)); + +// Cast to disambiguate overloaded methods +NpyExpr.Call((Func)Math.Abs, NpyExpr.Input(0)); + +// Pre-constructed delegate with captures +static readonly Func GELU = x => + 0.5 * x * (1.0 + Math.Tanh(Math.Sqrt(2.0 / Math.PI) * + (x + 0.044715 * x * x * x))); +NpyExpr.Call(GELU, NpyExpr.Input(0)); + +// MethodInfo — static +var mi = typeof(Math).GetMethod("BitIncrement", new[] { typeof(double) }); +NpyExpr.Call(mi, NpyExpr.Input(0)); + +// MethodInfo + instance target +NpyExpr.Call(instanceMethod, targetObject, NpyExpr.Input(0)); +``` + +Three dispatch paths, selected automatically at node construction: + +| Condition | Emitted IL | Per-element cost | +|-----------|------------|------------------| +| Static method, no captures | `call ` | Direct call; JIT may inline | +| Instance `MethodInfo` with explicit `target` | `ldc.i4 slotId` → `DelegateSlots.LookupTarget` → `castclass T` → `callvirt ` | ~5 ns + virtual call | +| Any other Delegate | `ldc.i4 slotId` → `DelegateSlots.LookupDelegate` → `castclass Func<...>` → `callvirt Invoke` | ~5-10 ns + `Delegate.Invoke` | + +Strong-ref `DelegateSlots` registry keeps captured delegates alive for the process lifetime — user must register once at startup (static field) to avoid unbounded growth. + +Benchmark: GELU via captured lambda on 1M f64 = **8.08 ms/run**. + +--- + +## Tier 3B — Templated element-wise, hand-written vector body + +Factory emits the 4×-unrolled SIMD + 1-vec remainder + scalar-tail + scalar-strided fallback shell. User provides only the per-element scalar and (optional) vector body: + +```csharp +iter.ExecuteElementWiseBinary( + NPTypeCode.Single, NPTypeCode.Single, NPTypeCode.Single, + scalarBody: il => + { + // Stack: [a, b] → [2a + 3b] + il.Emit(OpCodes.Ldc_R4, 2f); il.Emit(OpCodes.Mul); + var tmp = il.DeclareLocal(typeof(float)); il.Emit(OpCodes.Stloc, tmp); + il.Emit(OpCodes.Ldc_R4, 3f); il.Emit(OpCodes.Mul); + il.Emit(OpCodes.Ldloc, tmp); il.Emit(OpCodes.Add); + }, + vectorBody: il => + { + // Vector256 ops — all via ILKernelGenerator primitives + il.Emit(OpCodes.Ldc_R4, 2f); + ILKernelGenerator.EmitVectorCreate(il, NPTypeCode.Single); + ILKernelGenerator.EmitVectorOperation(il, BinaryOp.Multiply, NPTypeCode.Single); + // … symmetric for 3b, then add … + }, + cacheKey: "linear_2a_3b_f32"); +``` + +**When SIMD is skipped.** Vector body is emitted only when `CanSimdAllOperands(operandTypes)` is true (all operand dtypes identical *and* SIMD-capable). Mixed-type ufuncs (int32 + float32 → float32) run the scalar body with `EmitConvertTo` inside. + +**Runtime contig check.** Factory emits a stride-vs-elemSize comparison at kernel entry. Any stride mismatch falls into the scalar-strided loop — one kernel handles both contiguous and sliced inputs without recompile. + +Benchmark: `2a + 3b` on 1M f32 = **0.61 ms/run** — within ~7% of baked Layer 3 Add. + +--- + +## Tier 3A — Raw IL escape hatch + +User emits the entire inner-loop body against the NumPy ufunc signature +`void(void** dataptrs, long* byteStrides, long count, void* aux)`: + +```csharp +iter.ExecuteRawIL(il => +{ + // c[i] = |a[i] - b[i]| for int32 operands, fused in one kernel. + var p0 = il.DeclareLocal(typeof(byte*)); + var p1 = il.DeclareLocal(typeof(byte*)); + var p2 = il.DeclareLocal(typeof(byte*)); + var s0 = il.DeclareLocal(typeof(long)); + // ... 60 lines of il.Emit(OpCodes.*) ... + il.Emit(OpCodes.Ret); +}, cacheKey: "abs_diff_i32"); +``` + +Use when the loop shape is non-rectangular (gather/scatter, cross-element dependencies, branch-on-auxdata). Otherwise prefer Tier 3B which gets you the SIMD shell for free. + +Benchmark: `abs(a - b)` on 1M i32 = **1.27 ms/run** (scalar loop, JIT autovectorizes post tier-1). + +--- + +## Layer 2 — Struct-generic dispatch (zero-alloc) + +The JIT specializes `ExecuteGeneric` per struct type at codegen time. No delegate indirection, no boxing. **Only path with early-exit reductions.** + +```csharp +readonly unsafe struct HypotKernel : INpyInnerLoop +{ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Execute(void** p, long* s, long n) + { + if (s[0] == 4 && s[1] == 4 && s[2] == 4) + { + float* pa = (float*)p[0], pb = (float*)p[1], pc = (float*)p[2]; + for (long i = 0; i < n; i++) + pc[i] = MathF.Sqrt(pa[i] * pa[i] + pb[i] * pb[i]); + } + // … strided fallback … + } +} + +readonly unsafe struct AnyNonZero : INpyReducingInnerLoop +{ + public bool Execute(void** p, long* s, long n, ref bool acc) + { + byte* pt = (byte*)p[0]; long st = s[0]; + for (long i = 0; i < n; i++) + if (*(int*)(pt + i * st) != 0) { acc = true; return false; } // STOP + return true; + } +} + +iter.ExecuteGeneric(default(HypotKernel)); +bool found = iter.ExecuteReducing(default, false); +``` + +Benchmark: `AnyNonZero` early-exit over 1M int32 with hit at idx 500 = **0.001 ms/run** — the kernel returns `false`, the bridge bails out of the do/while after one call. + +--- + +## Layer 1 — ForEach delegate (NumPy-C-API parity) + +```csharp +iter.ForEach((ptrs, strides, count, aux) => { + if (strides[0] == 4 && strides[1] == 4 && strides[2] == 4) { + float* pa = (float*)ptrs[0], pb = (float*)ptrs[1], pc = (float*)ptrs[2]; + for (long i = 0; i < count; i++) + pc[i] = MathF.Sqrt(pa[i] * pa[i] + pb[i] * pb[i]); + } else { + // … strided scalar fallback … + } +}); +``` + +Classic NumPy-C-API shape. One delegate closure per call. Most flexible for one-offs, fused kernels with captures, or mid-execution experimentation. + +--- + +## Decision tree + +``` +Is the op a standard NumPy ufunc already in ExecuteBinary/Unary/Reduction? + yes → Layer 3. Fastest, zero work. Done. + no ↓ + +Can I express it as a tree of DSL nodes (Add, Sqrt, Where, Exp, …)? + yes → Tier 3C. Fused, SIMD-or-scalar automatic, no IL. + no ↓ + +Is the missing piece a BCL method (Math.X, user activation, reflected plugin)? + yes → Tier 3C + Call. Scalar-only but fused. Done. + no ↓ + +Do I need V256/V512 intrinsics the DSL doesn't wrap (Fma, Shuffle, Gather, …)? + yes → Tier 3B. Hand-write the vector body; factory wraps the shell. + no ↓ + +Is the loop shape non-rectangular (gather/scatter, cross-element deps)? + yes → Tier 3A. Emit the whole inner-loop IL yourself. + no ↓ + +Do I need an early-exit reduction (Any / All / find-first)? + yes → Layer 2 ExecuteReducing. Returns false from the kernel to bail out. + no ↓ + +Just exploring or writing a one-off? + → Layer 1 ForEach. Delegate per call; flexible. +``` + +--- + +## Performance summary (1M elements, post-warmup) + +| Technique | Operation | Time / run | Notes | +|-----------|-----------|-----------:|-------| +| Layer 3 | `a + b` (f32) | 0.58 ms | baked, 4×-unrolled V256, cache hit | +| Tier 3B | `2a + 3b` hand V256 (f32) | 0.61 ms | within ~7% of baked | +| Layer 2 reduction | `AnyNonZero` early-exit (hit @ 500) | 0.001 ms | returns `false` from kernel | +| Tier 3A | `abs(a - b)` raw IL (i32) | 1.27 ms | scalar, JIT autovectorizes | +| Tier 3C + Call | `GELU` via captured lambda (f64) | 8.08 ms | `Math.Tanh` dominates | +| Tier 3C | stable sigmoid via `Where` (f64) | 13.6 ms | 3 × `Math.Exp` per element | + +Tier-0 JIT caveat applies to Layer 1/2 element-wise kernels in ephemeral hosts (dotnet_run, cold-start scripts) — they can look 30-50× slower than production until tier-1 promotion kicks in (~100 hot-loop iterations). + +--- + +## NpyIter state (unified, post-port) + +Replaces the v4 `IteratorState` struct. Heap-allocated via `NativeMemory.AllocZeroed` (not stack-allocated with `fixed int[16]`) because NumSharp drops NumPy's `NPY_MAXDIMS=64` ceiling — state is sized to the actual `(ndim, nop)`. + +```csharp +public unsafe struct NpyIterState +{ + // Scalars + public int NDim, NOp; + public long IterSize, IterIndex; + public NpyIterFlags ItFlags; + + // Dim arrays (size = NDim) + public long* Shape; + public long* Coords; + public long* Strides; // element strides per (op, axis) + public sbyte* Perm; // negative = axis was flipped + + // Op arrays (size = NOp) + public long* DataPtrs, ResetDataPtrs, BufStrides, InnerStrides, BaseOffsets; + public NPTypeCode* OpDTypes; + + // Reduction arrays + public long* ReduceOuterStrides, ReduceOuterPtrs, ArrayWritebackPtrs; + public long CoreSize, CorePos, ReduceOuterSize, ReducePos; + + // Buffer + public long BufferSize, BufIterEnd; + public long* Buffers; +} +``` + +See `src/NumSharp.Core/Backends/Iterators/NpyIter.State.cs` for the full definition and `NDIter.md` for the field-by-field walkthrough. + +--- + +## Migration: old patterns → NpyIter + +### Pattern 1: element-wise loop via `NDIterator` + +**Old:** +```csharp +var iter = new NDIterator(source, false); +while (iter.HasNext()) +{ + var val = iter.MoveNext(); + sum += val * val; +} +``` + +**New (Layer 2 struct-generic):** +```csharp +readonly unsafe struct SumOfSquares : INpyReducingInnerLoop +{ + public bool Execute(void** p, long* s, long n, ref double acc) + { + byte* pt = (byte*)p[0]; long st = s[0]; + for (long i = 0; i < n; i++) + { + double v = *(double*)(pt + i * st); + acc += v * v; + } + return true; + } +} + +using var iter = NpyIterRef.MultiNew(1, new[] { source }, + NpyIterGlobalFlags.EXTERNAL_LOOP, NPY_ORDER.NPY_KEEPORDER, + NPY_CASTING.NPY_NO_CASTING, new[] { NpyIterPerOpFlags.READONLY }); +double sum = iter.ExecuteReducing(default, 0.0); +``` + +**New (Tier 3C DSL):** +```csharp +// If you also want the *array* of x² (not just the reduction): +var expr = NpyExpr.Square(NpyExpr.Input(0)); +iter.ExecuteExpression(expr, new[] { NPTypeCode.Double }, NPTypeCode.Double); +``` + +### Pattern 2: axis-wise iteration via `NDCoordinatesAxisIncrementor` + +**Old:** +```csharp +var iterAxis = new NDCoordinatesAxisIncrementor(ref shape, axis); +var slices = iterAxis.Slices; +do +{ + var slice = arr[slices]; + ret[slices] = ProcessSlice(slice); +} while (iterAxis.Next() != null); +``` + +**New (axis-reducing iterator with op_axes):** +```csharp +// Use the axis-reduction construction path; NpyIter handles the double-loop +// buffered reduction internally via REDUCE_OK + ExecuteReduction. +using var iter = NpyIterRef.AdvancedNew(2, new[] { input, output }, + NpyIterGlobalFlags.EXTERNAL_LOOP | NpyIterGlobalFlags.REDUCE_OK + | NpyIterGlobalFlags.BUFFERED, + NPY_ORDER.NPY_KEEPORDER, NPY_CASTING.NPY_SAFE_CASTING, + new[] { NpyIterPerOpFlags.READONLY, + NpyIterPerOpFlags.WRITEONLY | NpyIterPerOpFlags.ALLOCATE }, + opAxes: new[][] { null, outputAxes }); +iter.ExecuteReduction(ReductionOp.Sum); +``` + +### Pattern 3: broadcast paired iteration via `MultiIterator` + +**Old:** +```csharp +var (lIter, rIter) = MultiIterator.GetIterators(lhs, rhs, broadcast: true); +while (lIter.HasNext()) + lIter.MoveNextReference() = rIter.MoveNext(); +``` + +**New (Layer 3 Copy):** +```csharp +using var iter = NpyIterRef.MultiNew(2, new[] { rhs, lhs }, + NpyIterGlobalFlags.EXTERNAL_LOOP, NPY_ORDER.NPY_KEEPORDER, + NPY_CASTING.NPY_SAFE_CASTING, + new[] { NpyIterPerOpFlags.READONLY, NpyIterPerOpFlags.WRITEONLY }); +iter.ExecuteCopy(); +``` + +### Pattern 4: coordinate access via `ValueCoordinatesIncrementor` + +**Old:** +```csharp +var incr = new ValueCoordinatesIncrementor(ref shape); +int[] coords = incr.Index; +do +{ + var offset = shape.GetOffset(coords); + Process(data + offset); +} while (incr.Next() != null); +``` + +**New (Layer 1):** +```csharp +using var iter = NpyIterRef.MultiNew(1, new[] { arr }, + NpyIterGlobalFlags.None, NPY_ORDER.NPY_KEEPORDER, + NPY_CASTING.NPY_NO_CASTING, new[] { NpyIterPerOpFlags.READONLY }); +iter.ForEach((ptrs, strides, count, aux) => { + byte* p = (byte*)ptrs[0]; long s = strides[0]; + for (long i = 0; i < count; i++) + Process((double*)(p + i * s)); +}); +``` + +--- + +## Files — current state + +**Core (production):** + +``` +src/NumSharp.Core/Backends/Iterators/ +├── NpyIter.cs construction wrappers, MultiNew/AdvancedNew +├── NpyIter.State.cs NpyIterState struct, Advance/Reset/GotoIterIndex +├── NpyIter.Execution.cs Layer 1/2/3 — ForEach, ExecuteGeneric, Execute* +├── NpyIter.Execution.Custom.cs Tier 3A/3B/3C — ExecuteRawIL, ExecuteElementWise, ExecuteExpression +├── NpyExpr.cs Tier 3C DSL — 45+ nodes + Call factory + DelegateSlots +├── NpyIterFlags.cs flag enums (Global / PerOp / internal) +├── NpyIterCoalescing.cs CoalesceAxes, ReorderAxesForCoalescing, FlipNegativeStrides +├── NpyIterCasting.cs safe/same-kind/unsafe cast rules +├── NpyIterBufferManager.cs aligned buffer alloc, copy-in/copy-out +├── NpyIterKernels.cs INpyInnerLoop, INpyReducingInnerLoop interfaces +├── NpyAxisIter.cs, NpyAxisIter.State.cs axis-reduction iterator +└── NpyLogicalReductionKernels.cs generic boolean/numeric axis reduction structs + +src/NumSharp.Core/Backends/Kernels/ +└── ILKernelGenerator.InnerLoop.cs CompileRawInnerLoop, CompileInnerLoop, factory shell +``` + +**Deleted (v4 → v5 migration, completed):** + +``` +src/NumSharp.Core/Backends/Iterators/ +├── INDIterator.cs [deleted] +├── IteratorType.cs [deleted] +├── MultiIterator.cs [deleted] +├── NDIterator.cs [deleted] +├── NDIterator.template.cs [deleted] +├── NDIteratorExtensions.cs [deleted] +└── NDIteratorCasts/NDIterator.Cast.*.cs (×12) [deleted] + +src/NumSharp.Core/Utilities/Incrementors/ +├── NDCoordinatesAxisIncrementor.cs [deleted] +├── NDCoordinatesIncrementor.cs [deleted] +├── ValueCoordinatesIncrementor.cs [deleted] +└── ValueOffsetIncrementor.cs [deleted] +``` + +--- + +## Scope limitations (unchanged) + +1. **Multi-output operations** (e.g., `modf` returning two arrays) — use `ILKernelGenerator.Modf` directly, not via the seven-tier bridge +2. **Type promotion** — caller's responsibility via `np._FindCommonType` / NPTypeCode utilities +3. **Memory allocation** — caller provides output NDArray (or uses `NpyIterPerOpFlags.ALLOCATE`) + +Broadcasting is **not** a scope limitation anymore — NpyIter handles it inherently via stride=0 dimensions. + +--- + +## Known bugs (post-port) + +The bridge works around two bugs in the ported `NpyIter` that should be fixed in-place eventually: + +- **Bug A:** `NpyIterRef.Iternext()` unconditionally calls `state.Advance()`, ignoring `EXLOOP`. Bridge sidesteps by calling `GetIterNext()` directly. +- **Bug B:** Buffered + Cast path computes wrong byte deltas because `state.Strides[op]` holds element strides but `ElementSizes[op]` is buffer-dtype size. Bridge routes buffered paths through `RunBuffered*` methods using `BufStrides` instead. + +Eight additional bugs surfaced during development (C through H, covering Where, Decimal size, predicate I4 leak, LogicalNot type mismatch, Vector256.Round availability, MinMax NaN propagation) were **fixed**. See `NDIter.md § Known Bugs and Workarounds` for full writeups. + +--- + +## References + +- **Production reference docs:** `docs/website-src/docs/NDIter.md` — complete user-facing documentation (~1900 lines) +- **NumPy port source:** NumPy's `numpy/_core/src/multiarray/nditer_*.c` +- **Test coverage:** 264 tests across + `NpyIterCustomOpTests.cs` (14 basic), + `NpyIterCustomOpEdgeCaseTests.cs` (76 edge cases), + `NpyExprExtensiveTests.cs` (136 DSL ops), + `NpyExprCallTests.cs` (38 Call variants) — + all passing on net8.0 and net10.0. diff --git a/docs/plans/gh-issue-npy-npz-rewrite.md b/docs/plans/gh-issue-npy-npz-rewrite.md new file mode 100644 index 000000000..d4be1e50c --- /dev/null +++ b/docs/plans/gh-issue-npy-npz-rewrite.md @@ -0,0 +1,144 @@ +# [Rewrite] np.save/load - NPY/NPZ Format (NEP-01) + +## Overview + +NumSharp's implementation of `.npy` and `.npz` file I/O needs a complete rewrite. The current code was written as a quick solution years ago and has accumulated significant technical debt. It diverges from NumPy's behavior in ways that break interoperability, throws exceptions on valid files that NumPy handles gracefully, and exposes an API that doesn't match NumPy's signatures. This issue proposes bringing the implementation into full compliance with NEP-01 (the NumPy Enhancement Proposal that defines the binary format) and achieving API parity with NumPy 2.x. + +## The Problem + +### We Only Support a Fraction of the Format + +The NPY format has evolved through three versions since its introduction in NumPy 1.0.5. Version 1.0 uses a 2-byte header length field, limiting headers to 65KB - plenty for simple arrays but insufficient for structured arrays with many fields. Version 2.0, introduced in NumPy 1.9, extended this to a 4-byte field supporting headers up to 4GB. Version 3.0, added in NumPy 1.17, switched the header encoding from Latin-1 to UTF-8 to support Unicode field names in structured dtypes. + +NumSharp currently only recognizes version 1.0 and throws `NotSupportedException` when encountering version 2.0 or 3.0 files. This means any `.npy` file saved by modern NumPy with a large structured dtype or Unicode field names simply cannot be loaded. Users hitting this wall have no workaround other than re-saving their data in NumPy with simpler dtypes. + +### Header Alignment is Wrong + +One of the cleverest aspects of the NPY format is that the header is padded so the data section begins at a 64-byte aligned offset. This alignment enables memory-mapped access to the array data without copying - the operating system can map the file directly into virtual memory and the CPU can access the data with aligned SIMD instructions. + +NumSharp's implementation uses 16-byte alignment instead of 64. Files written by NumSharp technically conform to the format specification (alignment is not strictly required), but they lose the performance benefits of memory mapping. More importantly, this signals a fundamental misunderstanding of the format that likely indicates other subtle bugs. + +### We Reject Valid Data Layouts + +NumPy arrays can be stored in either C-order (row-major) or Fortran-order (column-major) layout. The format captures this in the `fortran_order` header field. When NumPy encounters a Fortran-order file, it reads the data, reshapes with reversed dimensions, then transposes to produce the correct array. + +NumSharp throws an exception when `fortran_order` is `True`. This is particularly frustrating because Fortran-order arrays are common in scientific computing - they're the native layout for MATLAB, R, and many numerical libraries. A user trying to load data exported from these tools will simply get an error with no path forward. + +The same issue applies to byte order. NumPy files can contain big-endian data (indicated by `>` in the dtype descriptor). NumPy handles this transparently by byte-swapping on read when the host system uses a different byte order. NumSharp throws an exception. While big-endian systems are rare today, big-endian files still exist - especially in legacy scientific datasets and network protocols. + +### The API Doesn't Match NumPy + +When users learn NumPy, they learn to call `np.save()`, `np.load()`, `np.savez()`, and `np.savez_compressed()`. These function signatures have specific parameters with specific defaults that users come to expect. + +NumSharp's API diverges in several ways. The methods are named `Save_Npz` and `Load_Npz` instead of `savez` - mixing PascalCase with underscores in a way that matches neither .NET conventions nor NumPy conventions. The `load` function is missing critical parameters like `allow_pickle` (which controls whether object arrays can be loaded), `mmap_mode` (for memory-mapped access), and `max_header_size` (a security feature that limits header parsing to prevent denial-of-service attacks from malicious files). + +The `Load_Npz` method requires a generic type parameter with a complex constraint (`where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable`). This constraint exists because the implementation returns .NET arrays rather than NDArrays, but it creates an awkward API that doesn't exist in NumPy. Users shouldn't need to specify type parameters to load a file - the type information is in the file itself. + +### NPZ Handling Has Subtle Bugs + +The `.npz` format is simply a ZIP archive containing multiple `.npy` files. NumPy's `NpzFile` class provides lazy loading - arrays aren't actually read from disk until accessed. It also provides a convenient interface where both `npz['arr_0']` and `npz['arr_0.npy']` work as keys, with the `.files` property returning the stripped names. + +NumSharp's `NpzDictionary` class doesn't strip the `.npy` extension, so code written for NumPy that accesses arrays by their logical names will fail. The class also doesn't implement the context manager protocol properly for deterministic cleanup, potentially leaking file handles. + +### Security Features Are Missing + +NumPy added the `max_header_size` parameter after discovering that `ast.literal_eval()` (used to parse the header dictionary) can be slow or even crash on extremely large inputs. A malicious actor could craft a `.npy` file with a header designed to cause denial of service. The default limit of 10,000 bytes is sufficient for any legitimate array while protecting against attacks. + +NumPy also changed `allow_pickle` to default to `False` in version 1.16.3 after security researchers demonstrated that pickle deserialization could execute arbitrary code. Object arrays in `.npy` files are serialized using pickle, so loading an untrusted file with `allow_pickle=True` is equivalent to running untrusted code. + +NumSharp has neither protection. There's no header size limit, and there's no pickle support at all (which means object arrays simply can't be loaded, but also means there's no parameter to control this behavior). + +### Dtype Coverage is Incomplete + +The dtype descriptor in an NPY header maps directly to NumPy's dtype system. NumSharp's parser handles the common cases but has gaps and bugs. + +The unsigned byte type `|u1` is mapped to signed byte, which is simply wrong. Complex number types (`` with an `NpzFile` class that matches NumPy's interface. This class should: + +- Provide lazy loading with internal caching (arrays loaded on first access, then cached) +- Accept both `"arr_0"` and `"arr_0.npy"` as valid keys +- Expose a `files` property with stripped names +- Implement `IDisposable` properly for the underlying ZIP archive +- Support the `f` attribute for dot-notation access (`npz.f.weights` instead of `npz["weights"]`) + +The `savez` and `savez_compressed` functions should accept both positional arrays (named `arr_0`, `arr_1`, etc.) and keyword arguments. They should always enable Zip64 extensions to support archives larger than 4GB. + +### Match the NumPy API + +The public API should match NumPy's signatures: + +```python +np.save(file, arr, allow_pickle=True) +np.load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, + encoding='ASCII', *, max_header_size=10000) +np.savez(file, *args, allow_pickle=True, **kwds) +np.savez_compressed(file, *args, allow_pickle=True, **kwds) +``` + +The `allow_pickle` parameter should be implemented even though we don't support pickle - it should raise a clear error when `allow_pickle=False` and an object array is encountered, matching NumPy's behavior. + +The `mmap_mode` parameter enables memory-mapped access. While full implementation is complex, at minimum we should accept the parameter and either implement basic read-only mapping or raise `NotImplementedException` with a clear message. + +### Add Security Protections + +Implement the `max_header_size` check. Before parsing the header with any string operations, verify its length is within the limit. If `allow_pickle=True`, the limit can be bypassed (the user has already indicated they trust the file). + +Validate the header dictionary strictly: exactly three keys (`descr`, `fortran_order`, `shape`), `shape` must be a tuple of non-negative integers, `fortran_order` must be a boolean, `descr` must produce a valid dtype. + +### Improve Error Messages + +Replace generic exceptions with descriptive messages that help users understand what went wrong. NumPy's error messages are a good template: + +- `"the magic string is not correct; expected b'\\x93NUMPY', got {actual!r}"` +- `"we only support format version (1,0), (2,0), and (3,0), not {version}"` +- `"Header does not contain the correct keys: {keys!r}"` +- `"Object arrays cannot be loaded when allow_pickle=False"` + +## Breaking Changes + +This rewrite will change the public API. The `Save_Npz` and `Load_Npz` methods will be deprecated in favor of `savez` and `load`. The `NpzDictionary` class will be replaced by `NpzFile`. Code that depends on these will need to be updated. + +The default value of `allow_pickle` on `load` will be `False` to match NumPy's security-conscious default. Code that loads object arrays will need to explicitly pass `allow_pickle=True`. + +Files written by the old implementation with 16-byte alignment will still be readable, but memory mapping performance characteristics may differ. + +## What We're Not Doing (Yet) + +Some features are out of scope for this rewrite: + +**Object arrays** require implementing Python's pickle protocol, which is a substantial undertaking with security implications. For now, we'll raise a clear error when object arrays are encountered. + +**Structured dtypes** (record arrays) are complex to map to .NET types. A future enhancement could support them via dynamically generated types or a generic record class. + +**datetime64 and timedelta64** need design decisions about how to map to .NET types (`DateTime`, `DateTimeOffset`, `TimeSpan`, or custom structs). + +**Memory-mapped write mode** is complex because it requires pre-allocating the file to the correct size and carefully managing the mapping lifetime. + +## References + +The authoritative source for the NPY format is NEP-01, available at https://numpy.org/neps/nep-0001-npy-format.html. The implementation lives in `numpy/lib/_format_impl.py` (low-level format handling) and `numpy/lib/_npyio_impl.py` (high-level `save`/`load` functions). + +I've prepared comprehensive documentation of the format in `docs/numpy/NUMPY_NPZ_SAVE_LOAD.md` based on reading the NumPy source code. This covers every constant, every function, every edge case, and every error message. It should serve as the specification for our implementation. diff --git a/docs/plans/numpy-1x-deprecation-audit.md b/docs/plans/numpy-1x-deprecation-audit.md new file mode 100644 index 000000000..6cdffe57b --- /dev/null +++ b/docs/plans/numpy-1x-deprecation-audit.md @@ -0,0 +1,400 @@ +# Plan: NumPy 1.x Deprecated Feature Audit in NumSharp + +## Status: Investigation Complete — See `numpy-1x-deprecation-findings.md` for results + +NumSharp was originally built targeting NumPy 1.x APIs. NumPy 2.0 (June 2024) introduced ~100 API removals, behavioral changes, and type promotion overhauls. This plan documents a systematic investigation to identify every NumSharp feature that corresponds to deprecated, removed, or behaviorally-changed NumPy 1.x functionality, using the NumPy v2.4.2 source tree at `src/numpy/` as the authoritative reference. + +## Objectives + +1. **Identify deprecated/removed APIs** present in NumSharp that no longer exist in NumPy 2.x +2. **Identify behavioral differences** where NumSharp follows NumPy 1.x semantics that changed in 2.x +3. **Identify type aliases and constants** that were removed or renamed in NumPy 2.0 +4. **Categorize findings** by severity: breaking (must fix), warning (should fix), cosmetic (can defer) +5. **Produce actionable tickets** for each finding with migration path + +## Reference Sources + +| Source | Location | Contents | +|--------|----------|----------| +| NumPy 2.0 Migration Guide | `src/numpy/doc/source/numpy_2_0_migration_guide.rst` | Comprehensive migration instructions, ~100 removed members table | +| NumPy 2.0.0 Release Notes | `src/numpy/doc/source/release/2.0.0-notes.rst` | All removals, deprecations, expired deprecations, behavioral changes | +| NumPy 2.1.0 Release Notes | `src/numpy/doc/source/release/2.1.0-notes.rst` | Post-2.0 deprecations | +| NumPy 2.2.0 Release Notes | `src/numpy/doc/source/release/2.2.0-notes.rst` | Further deprecations | +| NumPy _methods.py | `src/numpy/numpy/_core/_methods.py` | Canonical reduction implementations (mean, var, std) | +| NumPy fromnumeric.py | `src/numpy/numpy/_core/fromnumeric.py` | Function signatures and delegation patterns | +| NumPy numeric.py | `src/numpy/numpy/_core/numeric.py` | Creation functions, element-wise ops | +| NumPy _type_aliases.py | `src/numpy/numpy/_core/_type_aliases.py` | Type hierarchy and promotion | +| **NUMPY_NUMSHARP_MAP.md** | `src/numpy/NUMPY_NUMSHARP_MAP.md` | Complete 1-to-1 API map (394 functions, ~40% coverage) — **must be cross-checked by this audit** | + +--- + +## Phase 1: Removed APIs Still Present in NumSharp + +### 1.1 Functions Removed in NumPy 2.0 + +Cross-reference every function listed in the NumPy 2.0 migration guide removal table against NumSharp's public API. + +#### Already Identified + +| NumSharp API | NumPy Status | File | Action Required | +|-------------|-------------|------|-----------------| +| `np.asscalar()` | **Removed in NumPy 1.23** (deprecated 1.16) | `Manipulation/np.asscalar.cs` | Replace with `ndarray.item()`. Note: NumSharp references `numpy-1.16.0` docs in remarks. | +| `np.find_common_type()` | **Removed in NumPy 2.0** | `Logic/np.find_common_type.cs` | Replace public API with `np.result_type()` or `np.promote_types()`. Internal `_FindCommonType` can stay but must match NumPy 2.x `result_type` semantics. | +| `np.NaN` (capitalized) | **Removed in NumPy 2.0** | `APIs/np.cs:67` | Keep as alias but mark `[Obsolete]`. NumPy 2.0 only has `np.nan`. | +| `np.Inf` (capitalized) | **Removed in NumPy 2.0** | `APIs/np.cs:73` | Keep as alias but mark `[Obsolete]`. NumPy 2.0 only has `np.inf`. | +| `np.Infinity` | **Removed in NumPy 2.0** | `APIs/np.cs:76` | Mark `[Obsolete]`, use `np.inf`. | +| `np.infty` | **Removed in NumPy 2.0** | `APIs/np.cs:72` | Mark `[Obsolete]`, use `np.inf`. | +| `np.NINF` | **Removed in NumPy 2.0** | `APIs/np.cs:74` | Remove or mark `[Obsolete]`, use `-np.inf`. | +| `np.PINF` | **Removed in NumPy 2.0** | `APIs/np.cs:75` | Remove or mark `[Obsolete]`, use `np.inf`. | +| `np.float_` | **Removed in NumPy 2.0** (use `np.float64`) | `APIs/np.cs:50` | Mark `[Obsolete]`. | +| `np.complex_` | **Removed in NumPy 2.0** (use `np.complex128`) | `APIs/np.cs:54` | Mark `[Obsolete]`. | +| `np.bool8` | **Removed in NumPy 2.0** (dtype alias `bool8` removed) | `APIs/np.cs:22` | Remove. | +| `np.int0` | **Removed in NumPy 2.0** (dtype alias `int0` removed) | `APIs/np.cs:42` | Remove. | +| `np.uint0` | **Removed in NumPy 2.0** (dtype alias `uint0` removed) | `APIs/np.cs:45` | Remove. | + +#### Investigation Needed + +Search NumSharp for any usage of these NumPy 1.x functions that were removed in 2.0: + +| Removed in NumPy 2.0 | Search Pattern | Expected in NumSharp? | +|----------------------|----------------|----------------------| +| `np.alltrue` | `alltrue` | Unlikely (NumSharp uses `np.all`) | +| `np.sometrue` | `sometrue` | Unlikely (NumSharp uses `np.any`) | +| `np.cumproduct` | `cumproduct` | Unlikely (NumSharp uses `np.cumsum` but check for `cumprod`) | +| `np.product` | `product` | Unlikely (NumSharp uses `np.prod`) | +| `np.asfarray` | `asfarray` | Unlikely | +| `np.round_` | `round_` | Check if alias exists alongside `np.round` | +| `np.msort` | `msort` | Unlikely | +| `np.cast` | `np.cast` | Unlikely | +| `np.row_stack` | `row_stack` | Unlikely (deprecated alias for vstack) | +| `np.in1d` | `in1d` | Unlikely (deprecated, use `np.isin`) | +| `np.trapz` | `trapz` | Unlikely | + +**Task**: Run grep across `src/NumSharp.Core/` for each pattern above to confirm presence/absence. + +### 1.2 ndarray/scalar Methods Removed in NumPy 2.0 + +| Removed Method | Replacement | Check in NumSharp | +|---------------|-------------|-------------------| +| `ndarray.newbyteorder()` | `arr.view(arr.dtype.newbyteorder(order))` | Search for `newbyteorder` | +| `ndarray.ptp()` | `np.ptp(arr)` | Search for `ptp` | +| `ndarray.setitem()` | `arr[index] = value` | Search for `setitem` | + +**Task**: Grep for these method names in NDArray class files. + +--- + +## Phase 2: Type Promotion Changes (NEP 50) + +This is the most impactful behavioral change. NumPy 2.0 overhauled type promotion via NEP 50. + +### 2.1 Key Changes + +| Behavior | NumPy 1.x | NumPy 2.x | NumSharp Current | +|----------|----------|----------|-----------------| +| `float32(3) + 3.0` | float64 | **float32** | Investigate | +| `array([3], dtype=float32) + float64(3)` | float32 | **float64** | Investigate | +| Scalar precision preserved | No (data-dependent) | **Yes** (dtype-dependent) | Investigate | +| Windows default int | int32 | **int64** | NumSharp uses int64 (may already match) | + +### 2.2 Investigation Steps + +1. **Read NumSharp's type promotion tables** in `np.find_common_type.cs` — the `_typemap_arr_arr` and `_typemap_arr_scalar` dictionaries encode NumPy 1.x promotion rules. +2. **Compare each entry** against NumPy 2.x `result_type` behavior by running Python scripts: + ```python + import numpy as np + # For each combination: + print(np.result_type(np.float32, np.float64)) + print(np.result_type(np.array([1], dtype=np.float32), np.float64(1.0))) + ``` +3. **Document all differences** between NumSharp's tables and NumPy 2.x `result_type`. +4. **Decide migration strategy**: update tables to match 2.x, or provide both modes. + +### 2.3 Specific Promotion Rules to Verify + +The `_typemap_arr_scalar` dictionary (lines 242-425 in `np.find_common_type.cs`) encodes the old `find_common_type` behavior with separate array/scalar semantics. NumPy 2.0 replaced this with unified `result_type`. Key entries to verify: + +- `(float32, float64_scalar)` → NumSharp says float32; NumPy 2.x says float64 (scalar precision preserved) +- `(int32, int64_scalar)` → NumSharp says int32; NumPy 2.x says int64 +- All `(array_type, scalar_type)` combinations where scalar has higher precision + +**Task**: Write a Python script that generates the full NumPy 2.x promotion table for all dtype pairs, then compare against NumSharp's hardcoded tables. + +--- + +## Phase 3: Behavioral Changes + +### 3.1 Sorting Algorithm Changes + +NumPy 2.0 uses SIMD-accelerated sorting (Intel x86-simd-sort, Google Highway). Unstable sorts may return different orderings for equal elements. + +**Task**: Check if NumSharp's `argsort` tests assume specific ordering for equal elements. + +### 3.2 `np.unique` Return Shape Changes + +NumPy 2.0 changed `return_inverse` shape for multi-dimensional inputs. + +**Task**: Compare NumSharp's `np.unique` behavior with NumPy 2.x for multi-dim arrays. + +### 3.3 `floor`, `ceil`, `trunc` Integer Input Behavior + +NumPy 2.1: `floor`, `ceil`, `trunc` no longer cast integer input to float. + +**Task**: Check if NumSharp's `np.floor`/`np.ceil` cast integer arrays to float. + +### 3.4 `np.any`/`np.all` Object Array Returns + +NumPy 2.0: `any`/`all` now return booleans for object arrays (previously returned objects). + +**Task**: Not directly applicable to NumSharp (no object dtype), but verify bool return type consistency. + +### 3.5 Copy Keyword Behavior + +NumPy 2.0 changed `np.array(..., copy=False)` and `np.asarray(...)` copy semantics. + +**Task**: Check if NumSharp's `np.array` and `np.asarray` have `copy` parameter and if behavior matches. + +### 3.6 Empty Array Truthiness + +NumPy 2.0: `bool(np.array([]))` now raises an error (previously returned False). + +**Task**: Check NumSharp's behavior for `bool` conversion of empty arrays. + +--- + +## Phase 4: Dead Code Tied to NumPy 1.x + +From CLAUDE.md, these are known dead code items. Verify if any correspond to APIs that were restructured in NumPy 2.x: + +| Dead Code | Status | NumPy 2.x Status | +|-----------|--------|-------------------| +| `np.linalg.norm` (private) | Dead — declared `private static` | Still exists in NumPy 2.x as `np.linalg.norm` | +| `nd.inv()` → returns null | Dead | `np.linalg.inv` still exists | +| `nd.qr()` → returns default | Dead | `np.linalg.qr` still exists | +| `nd.svd()` → returns default | Dead | `np.linalg.svd` still exists | +| `nd.lstsq()` → named `lstqr`, returns null | Dead | `np.linalg.lstsq` still exists | +| `nd.multi_dot()` → returns null | Dead | `np.linalg.multi_dot` still exists | +| `np.isnan` → engine returns null | Dead | Still exists in NumPy 2.x | +| `np.isfinite` → engine returns null | Dead | Still exists in NumPy 2.x | +| `np.isclose` → engine returns null | Dead | Still exists in NumPy 2.x | +| `np.allclose` → depends on isclose | Dead | Still exists in NumPy 2.x | +| `NDArray & (AND)` → returns null | Dead | Still exists in NumPy 2.x | +| `NDArray \| (OR)` → returns null | Dead | Still exists in NumPy 2.x | +| `nd.delete()` → returns null | Dead | Still exists in NumPy 2.x | +| `nd.roll()` → partial | Partial | Still exists, no API change | + +**Conclusion**: These are not NumPy 1.x deprecations — they're unfinished implementations. They should be fixed (implemented properly) or removed, but that's a separate concern from the deprecation audit. + +--- + +## Phase 5: Documentation Link Audit + +Many NumSharp files contain XML doc `` links pointing to NumPy 1.x documentation URLs. + +### Examples Found + +- `np.asscalar.cs`: References `numpy-1.16.0` docs +- `np.cs`: References `numpy-1.17.0` and `numpy-1.16.0` docs +- Various other files likely reference `scipy.org/doc/numpy-1.xx.x/` + +**Task**: Grep for `numpy-1.` across the codebase to find all 1.x doc references and update to NumPy 2.x URLs (which use `numpy.org/doc/stable/`). + +--- + +## Phase 6: Automated Investigation Scripts + +### 6.1 Python Script: Generate NumPy 2.x Type Promotion Table + +```python +# Run with NumPy 2.x installed +import numpy as np +import itertools + +dtypes = [np.bool_, np.uint8, np.int16, np.uint16, np.int32, np.uint32, + np.int64, np.uint64, np.float32, np.float64] + +print("# Array-Array promotion (np.result_type)") +for d1, d2 in itertools.product(dtypes, repeat=2): + result = np.result_type(d1, d2) + print(f"({np.dtype(d1).name}, {np.dtype(d2).name}) -> {result}") + +print("\n# Array-Scalar promotion") +for d1 in dtypes: + for scalar in [True, 0, 0.0]: + arr = np.array([1], dtype=d1) + result = np.result_type(arr, type(scalar)) + print(f"array({np.dtype(d1).name}) + {type(scalar).__name__} -> {result}") +``` + +### 6.2 Grep Commands for Phase 1 Audit + +```bash +# Removed function names +rg -i "asscalar|find_common_type|alltrue|sometrue|cumproduct|asfarray" src/NumSharp.Core/ --type cs +rg -i "msort|row_stack|in1d|trapz" src/NumSharp.Core/ --type cs +rg -i "newbyteorder|\.ptp\b|\.setitem\b" src/NumSharp.Core/ --type cs + +# Old doc URLs +rg "numpy-1\." src/NumSharp.Core/ --type cs + +# Deprecated constant/alias usage in test code +rg "np\.NaN|np\.Inf\b|np\.Infinity|np\.infty|np\.NINF|np\.PINF|np\.float_|np\.complex_|np\.bool8|np\.int0|np\.uint0" src/ --type cs +``` + +### 6.3 C# Script: Compare NumSharp Promotion Tables Against NumPy 2.x + +Write a `dotnet run` script that: +1. Loads NumSharp's `_nptypemap_arr_arr` and `_nptypemap_arr_scalar` tables +2. Compares against expected NumPy 2.x `result_type` values (hardcoded from Python output) +3. Reports all mismatches + +--- + +## Phase 7: Cross-Check NUMPY_NUMSHARP_MAP.md + +The file `src/numpy/NUMPY_NUMSHARP_MAP.md` is a comprehensive 394-function API map with status codes (`Y`/`~`/`-`), file locations, and notes. This audit should validate and correct that map. + +### 7.1 Deprecation-Related Corrections + +Items in the map that are NumPy 1.x-only and need annotation: + +| Map Entry | Section | Current Status | Correction Needed | +|-----------|---------|----------------|-------------------| +| `np.asscalar` | §23 Other | `Y` | Should be marked `Y (deprecated)` — removed in NumPy 1.23, replace with `ndarray.item()` | +| `np.find_common_type` | §11 Logic | `Y` | Should be marked `Y (deprecated)` — removed in NumPy 2.0, replace with `np.result_type` | +| `np.row_stack` | §2 Stacking | `-` | Correctly absent. Was deprecated alias for `vstack`, removed in NumPy 2.0. Should note "Removed in NumPy 2.0, was alias for vstack" | +| `np.trapezoid` | §21 Advanced | `-` | Correctly listed as NumPy 2.0 name. Note: old name `np.trapz` also not in NumSharp (clean) | + +### 7.2 Map Accuracy Verification — Status Claims + +For each `Y` (implemented) entry in the map, verify the claim by checking: +1. The file exists at the stated path +2. The function is public and callable (not dead code) +3. The function signature matches NumPy 2.x (not just NumPy 1.x) + +Priority spot-checks (items that may have NumPy 1.x → 2.x signature changes): + +| Function | Map Claim | What to Verify | +|----------|-----------|---------------| +| `np.round` / `np.around` | `Y` | Does NumSharp also expose `np.round_`? (Yes — 4 overloads, deprecated in NumPy 2.0) | +| `np.convolve` | `-` (dead) | Map says "Dead code: Regen not generated, returns null". Verify this is accurate. | +| `np.any(axis)` | `~` | Map says "with-axis always throws". Verify against CLAUDE.md dead code list. | +| `np.savez` | `~` | Map says "As `Save_Npz`". Verify this matches NumPy 2.x `savez` signature. | +| `np.roll` | `~` | Map says "static returns int (bug)". Verify. | + +### 7.3 Missing Deprecation Annotations + +The map should flag these NumPy 2.0 items that NumSharp should NOT implement (since they were removed): + +| Should NOT Be Added | Reason | +|---------------------|--------| +| `np.alltrue` | Removed in 2.0, use `np.all` | +| `np.sometrue` | Removed in 2.0, use `np.any` | +| `np.cumproduct` | Removed in 2.0, use `np.cumprod` | +| `np.product` | Removed in 2.0, use `np.prod` | +| `np.asfarray` | Removed in 2.0 | +| `np.msort` | Removed in 2.0 | +| `np.in1d` | Deprecated in 2.0, use `np.isin` | + +These are already absent from the map, which is correct. + +### 7.4 New NumPy 2.x Functions to Track + +The map already identifies some NumPy 2.0+ additions. Verify completeness: + +| New in NumPy 2.x | In Map? | Notes | +|-------------------|---------|-------| +| `np.cumulative_sum` | Yes (§9) | New in 2.0 | +| `np.cumulative_prod` | Yes (§9) | New in 2.0 | +| `np.matrix_transpose` | Yes (§5) | New in 2.0 | +| `np.unstack` | Yes (§2) | New in 2.1 | +| `np.unique_all` | Yes (§18) | New in 2.0 | +| `np.unique_counts` | Yes (§18) | New in 2.0 | +| `np.unique_inverse` | Yes (§18) | New in 2.0 | +| `np.unique_values` | Yes (§18) | New in 2.0 | +| `np.linalg.matrix_norm` | Yes (§13) | New in 2.0 | +| `np.linalg.vector_norm` | Yes (§13) | New in 2.0 | +| `np.vecdot` | Yes (§13) | New in 2.0 | +| `np.matvec` | No | New in 2.2 — add to map | +| `np.vecmat` | No | New in 2.2 — add to map | +| `np.bitwise_count` | No | New in 2.0 — add to map | +| `np.astype` (top-level) | Yes (§23) | New in 2.0 | +| `np.from_dlpack` | Yes (§1) | New in 2.0 | +| `np.isdtype` | No | New in 2.0 — add to map | +| `np.trapezoid` | Yes (§21) | Renamed from `trapz` in 2.0 | + +### 7.5 Summary Statistics Validation + +The map claims **152 implemented, 5 partial, 237 missing** out of **394 total (~40% coverage)**. This audit should: +1. Subtract deprecated functions from the "implemented" count (asscalar, find_common_type → these still count as implemented but need annotation) +2. Verify the dead code items are correctly marked `-` (not `Y`) +3. Add missing NumPy 2.0+ functions to the total + +--- + +## Execution Order + +| Phase | Description | Effort | Priority | +|-------|-------------|--------|----------| +| 1.1 | Grep for removed APIs | Low | High | +| 1.2 | Check removed ndarray methods | Low | High | +| 2.1-2.3 | Type promotion comparison | Medium | **Critical** | +| 3.1-3.6 | Behavioral change audit | Medium | High | +| 4 | Dead code review (already known) | Low | Low | +| 5 | Doc URL audit | Low | Low | +| 6 | Write and run automated scripts | Medium | High | +| 7.1-7.2 | Cross-check NUMPY_NUMSHARP_MAP.md deprecations & accuracy | Medium | High | +| 7.3-7.5 | Update map with 2.0 annotations & new functions | Low | Medium | + +## Output Artifacts + +Each phase produces: +1. A findings table (present/absent, matches/differs) +2. Migration recommendations (fix, deprecate, remove) +3. Test cases to verify corrections + +Final deliverables: +- `docs/plans/numpy-1x-deprecation-findings.md` — all results consolidated +- Updated `src/numpy/NUMPY_NUMSHARP_MAP.md` — corrected with deprecation annotations, new 2.x functions, verified status claims + +--- + +## Summary of Known Issues (Pre-Investigation) + +### Confirmed Deprecated APIs in NumSharp + +| # | Item | Severity | Migration | +|---|------|----------|-----------| +| 1 | `np.asscalar()` | Breaking | Replace with `ndarray.item()` method | +| 2 | `np.find_common_type()` public API | Breaking | Replace with `np.result_type()` / `np.promote_types()` | +| 3 | `np.NaN`, `np.Inf`, `np.Infinity`, `np.infty`, `np.NINF`, `np.PINF` | Warning | Mark `[Obsolete]`, keep for compat | +| 4 | `np.float_`, `np.complex_` | Warning | Mark `[Obsolete]` | +| 5 | `np.bool8`, `np.int0`, `np.uint0` | Warning | Remove aliases | +| 6 | `np.round_()` (4 public overloads) | Warning | Mark `[Obsolete]`, keep `np.round()` as primary. `np.round_` was removed in NumPy 2.0 (use `np.round`). | +| 7 | `DType.newbyteorder()` | Warning | Throws `NotSupportedException` already. `ndarray.newbyteorder()` was removed in NumPy 2.0. Consider removing. | +| 8 | Type promotion tables | **Critical** | Must update to match NEP 50 / `result_type` semantics | +| 9 | Old documentation URLs (54 occurrences across 22 files) | Cosmetic | Bulk find-replace `numpy-1.xx.x` → `numpy.org/doc/stable/` | + +### Grep Results Summary (Phase 1 Bootstrap) + +**Deprecated functions found in NumSharp:** +- `np.asscalar()` — `Manipulation/np.asscalar.cs` (6 overloads, references numpy-1.16.0 docs) +- `np.round_()` — `Math/np.round.cs` (4 public overloads alongside `np.round`) +- `np.find_common_type()` — `Logic/np.find_common_type.cs` (public API + internal) +- `DType.newbyteorder()` — `Creation/np.dtype.cs:114` (throws NotSupportedException) + +**Deprecated functions NOT found in NumSharp (clean):** +- `alltrue`, `sometrue`, `cumproduct`, `product`, `asfarray`, `msort`, `row_stack`, `in1d`, `trapz`, `cast`, `ptp`, `setitem` + +**Old documentation URLs:** 54 references to `numpy-1.x` docs across 22 .cs files + +**Deprecated aliases/constants used in test code:** No test files use the deprecated aliases (clean) + +### Requires Python Verification + +| # | Area | Method | +|---|------|--------| +| 1 | Full type promotion table comparison | Run Python script with NumPy 2.x | +| 2 | `floor`/`ceil` integer behavior | Run `np.floor(np.array([1,2,3]))` in NumPy 2.x | +| 3 | `np.unique` return_inverse shape | Run multi-dim unique in NumPy 2.x | +| 4 | Copy semantics of `np.array`/`np.asarray` | Compare `copy=` parameter behavior | diff --git a/docs/plans/numpy-1x-deprecation-findings.md b/docs/plans/numpy-1x-deprecation-findings.md new file mode 100644 index 000000000..faab95f74 --- /dev/null +++ b/docs/plans/numpy-1x-deprecation-findings.md @@ -0,0 +1,246 @@ +# NumPy 1.x Deprecation Audit — Findings + +## Status: Phase 1-7 Complete + +This document contains the consolidated results of the systematic audit comparing NumSharp against NumPy 2.x (v2.4.2). See `numpy-1x-deprecation-audit.md` for the investigation plan. + +--- + +## Executive Summary + +| Category | Count | Severity | +|----------|-------|----------| +| Deprecated/removed APIs present in NumSharp | 5 functions | High | +| Deprecated aliases/constants | 13 symbols | Medium | +| Type promotion table mismatches (arr-arr) | 0 of 100 | None | +| Type promotion table mismatches (arr-scalar) | 12 of 80 | **Critical** | +| Behavioral divergences from NumPy 2.x | 6 areas | High | +| Bugs discovered during audit | 8 bugs | Mixed | +| NUMPY_NUMSHARP_MAP.md corrections needed | 5 entries | Medium | +| Outdated documentation URLs | 385 across 121 files | Low | + +--- + +## 1. Deprecated/Removed APIs Still Present + +### 1.1 Functions + +| # | Function | File | NumPy Status | Severity | Migration | +|---|----------|------|-------------|----------|-----------| +| 1 | `np.asscalar()` (6 overloads) | `Manipulation/np.asscalar.cs` | Removed in 1.23 | **High** | Replace with `ndarray.item()`. Used internally by `NDArray.amin()` and `NDArray.amax()`. | +| 2 | `np.find_common_type()` (7+ overloads) | `Logic/np.find_common_type.cs` | Removed in 2.0 | **High** | Replace public API with `np.result_type()` / `np.promote_types()`. Internal `_FindCommonType` stays but needs NEP 50 update. Has ~25 dedicated test cases. | +| 3 | `np.round_()` (4 overloads) | `Math/np.round.cs` | Removed in 2.0 | **Medium** | Mark `[Obsolete]`. `np.round()` already exists alongside. No tests call `round_` directly. | +| 4 | `DType.newbyteorder()` | `Creation/np.dtype.cs:114` | Removed in 2.0 | **Low** | Already throws `NotSupportedException`. Consider removing entirely. | +| 5 | `np.asscalar` reference in comments | `LinearAlgebra/np.linalg.norm.cs` | — | **Low** | Commented-out Python code references `asfarray` (removed in 2.0). Clean up comments. | + +### 1.2 Aliases & Constants + +All defined in `APIs/np.cs`: + +| # | Symbol | Line | NumPy 2.0 Status | Action | +|---|--------|------|-----------------|--------| +| 1 | `np.NaN` | 67 | Removed (use `np.nan`) | Mark `[Obsolete]` | +| 2 | `np.NAN` | 66 | Removed | Mark `[Obsolete]` | +| 3 | `np.Inf` | 73 | Removed (use `np.inf`) | Mark `[Obsolete]` | +| 4 | `np.Infinity` | 76 | Removed (use `np.inf`) | Mark `[Obsolete]` | +| 5 | `np.infinity` | 77 | Removed | Mark `[Obsolete]` | +| 6 | `np.infty` | 72 | Removed (use `np.inf`) | Mark `[Obsolete]` | +| 7 | `np.NINF` | 74 | Removed (use `-np.inf`) | Mark `[Obsolete]` | +| 8 | `np.PINF` | 75 | Removed (use `np.inf`) | Mark `[Obsolete]` | +| 9 | `np.float_` | 50 | Removed (use `np.float64`) | Mark `[Obsolete]` | +| 10 | `np.complex_` | 54 | Removed (use `np.complex128`) | Mark `[Obsolete]` | +| 11 | `np.bool8` | 22 | Removed | Remove | +| 12 | `np.int0` | 42 | Removed | Remove | +| 13 | `np.uint0` | 45 | Removed | Remove | + +### 1.3 Confirmed Absent (Clean) + +These NumPy 1.x deprecated functions are NOT present in NumSharp: +`alltrue`, `sometrue`, `cumproduct`, `product`, `asfarray`, `msort`, `row_stack`, `in1d`, `trapz`, `cast`, `ptp` (method), `setitem` (method), `issubsctype`, `issubclass_`, `maximum_sctype`, `set_string_function`, `set_numeric_ops`, `fastCopyAndTranspose`, `get_array_wrap`, `safe_eval`, `nbytes` (function), `AxisError`, `ComplexWarning`, `VisibleDeprecationWarning`. + +--- + +## 2. Type Promotion Table Analysis + +### 2.1 Array-Array Promotion (`_typemap_arr_arr`) + +**Result: 100/100 entries match NumPy 2.x — perfect correspondence.** + +NumSharp's `_typemap_arr_arr` dictionary in `Logic/np.find_common_type.cs` was compared against `np.result_type(dtype1, dtype2)` for all 100 comparable pairs (10 types x 10 types, excluding complex64/decimal/char which are NumSharp-specific). Every entry matches. + +### 2.2 Array-Scalar Promotion (`_typemap_arr_scalar`) — 12 MISMATCHES + +**Result: 68/80 entries match NEP 50, 12 diverge.** + +All 12 divergences follow one pattern: **unsigned integer array + signed integer scalar**. Under NumPy 1.x, the result widens to accommodate both ranges. Under NEP 50 (NumPy 2.x), the array dtype wins because the scalar is a "weak" integer of the same kind. + +| Line | NumSharp (1.x) | NumPy 2.x (NEP 50) | Array Type | Scalar Type | +|------|---------------|---------------------|------------|-------------| +| 258 | (uint8, int16) → int16 | → **uint8** | uint8 | int16 | +| 260 | (uint8, int32) → int32 | → **uint8** | uint8 | int32 | +| 262 | (uint8, int64) → int64 | → **uint8** | uint8 | int64 | +| 297 | (uint16, int16) → int32 | → **uint16** | uint16 | int16 | +| 299 | (uint16, int32) → int32 | → **uint16** | uint16 | int32 | +| 301 | (uint16, int64) → int64 | → **uint16** | uint16 | int64 | +| 323 | (uint32, int16) → int64 | → **uint32** | uint32 | int16 | +| 325 | (uint32, int32) → int64 | → **uint32** | uint32 | int32 | +| 327 | (uint32, int64) → int64 | → **uint32** | uint32 | int64 | +| 349 | (uint64, int16) → float64 | → **uint64** | uint64 | int16 | +| 351 | (uint64, int32) → float64 | → **uint64** | uint64 | int32 | +| 353 | (uint64, int64) → float64 | → **uint64** | uint64 | int64 | + +**Fix**: Update these 12 entries so the result equals the array's unsigned type (the "array wins" rule). + +### 2.3 Key NEP 50 Behavioral Changes (from Python verification) + +Verified against NumPy 2.4.2: + +| Expression | NumPy 1.x | NumPy 2.x | NumSharp | +|-----------|----------|----------|----------| +| `float32(3) + 3.0` | float64 | **float32** | Needs testing | +| `float32_arr + float64_scalar` | float32 | **float64** | Needs testing | +| `int8_arr + python_int` | int16+ | **int8** | Needs testing | +| `uint8_arr + python_int` | int16+ | **uint8** | Needs testing | +| `bool_arr + bool_arr` | int (value=2) | **bool** | bool (OR semantics — see Bug #5) | + +--- + +## 3. Behavioral Divergences + +### 3.1 floor/ceil on integer arrays — BREAKING + +**NumPy 2.1+**: `np.floor(int_array)` returns the array with the same integer dtype (no-op). +**NumSharp**: Always casts to `Double`. The chain: `ResolveUnaryReturnType` → `GetComputingType()` → any integer → `NPTypeCode.Double`. The `Default.Floor.cs` switch only handles Double/Single/Decimal and throws for integer types. + +**Location**: `Backends/Default/Math/Default.Floor.cs`, `Default.Ceil.cs`, `NPTypeCode.cs:577` +**Impact**: Any `np.floor` or `np.ceil` call on integer arrays produces float64 output instead of preserving dtype. + +### 3.2 np.unique return_inverse — MISSING FEATURE + +**NumPy 2.x**: `return_inverse` shape matches input array shape (was 1D in 1.x). +**NumSharp**: `np.unique` accepts only `(NDArray a)` — no `return_index`, `return_inverse`, or `return_counts` parameters exist at all. + +### 3.3 np.asarray — MISSING copy PARAMETER + +**NumPy 2.x**: `np.asarray(existing_array)` returns a view; `copy=False` raises if copy needed. +**NumSharp**: `np.asarray` only accepts scalars and managed arrays (`T[]`), never an existing `NDArray`. Always creates a new `NDArray` and copies data. No `copy` parameter. + +### 3.4 bool + bool semantics — WRONG + +**NumPy 2.x**: `np.array([True]) + np.array([True])` returns `int` value `2`. +**NumSharp**: Uses `Operator.Add(bool, bool)` which is `lhs || rhs` (OR), so `True + True = True`. Loses information: `True + True` should be `2`, not `True`. + +**Location**: `Utilities/Maths/Operator.cs:32` + +### 3.5 np.any(axis) — COMPLETELY BROKEN + +Two bugs make `np.any(nd, axis)` always throw `InvalidOperationException`: + +1. **Bug**: `ComputeAnyPerAxis` returns `false` (line 162 of `np.any.cs`), causing the caller to always throw. +2. **Bug**: The inner logic implements `all()` instead of `any()` — initializes `currentResult = true` and detects zero values, which is the inverse of correct `any()` behavior. + +### 3.6 np.random — LEGACY API ONLY + +**NumPy 2.x**: Recommends `np.random.default_rng()` Generator API with PCG64/Philox/SFC64 bit generators. Legacy `RandomState` is deprecated. +**NumSharp**: Uses exclusively the legacy `RandomState` API. The `NumPyRandom` class docs explicitly say "serves as numpy.random.RandomState". No Generator API, no `default_rng()`, no modern bit generators. The underlying `Randomizer` class is a serializable clone of `System.Random`. + +--- + +## 4. Bugs Discovered During Audit + +| # | Bug | Location | Severity | Category | +|---|-----|----------|----------|----------| +| 1 | `np.roll` static returns `int` instead of `NDArray` | `APIs/np.array_manipulation.cs:16` | **High** | Implementation bug | +| 2 | `np.fmax`/`np.fmin` have identical implementation to `np.maximum`/`np.minimum` — NaN-ignoring behavior not implemented | `Math/np.maximum.cs:57-89`, `Math/np.minimum.cs:57-89` | **Medium** | Missing behavior | +| 3 | `np.fmin` docstrings say "Element-wise maximum" and "NaNs are propagated" — should say "minimum" and "NaNs are ignored" | `Math/np.minimum.cs:57-89` | **Low** | Wrong docs | +| 4 | `stardard_normal` method name is misspelled (missing 'd') | `RandomSampling/np.random.randn.cs` | **Low** | Typo | +| 5 | `bool + bool` uses OR (`||`) instead of integer addition | `Utilities/Maths/Operator.cs:32` | **Medium** | Wrong semantics | +| 6 | `np.any(axis)` always throws — `ComputeAnyPerAxis` returns false + has inverted logic | `Logic/np.any.cs:130-162` | **High** | Two bugs | +| 7 | `np.convolve` always returns null — Regen template never generated | `Math/NdArray.Convolve.cs` | **Medium** | Dead code | +| 8 | `floor`/`ceil` cast integer inputs to Double | `Backends/Default/Math/Default.Floor.cs`, `NPTypeCode.cs:577` | **Medium** | NumPy 1.x behavior | + +--- + +## 5. NUMPY_NUMSHARP_MAP.md Corrections + +### 5.1 Status Corrections + +| Function | Current Status | Correct Status | Reason | +|----------|---------------|----------------|--------| +| `np.asscalar` (§23) | `Y` | `Y` **(deprecated)** | Removed in NumPy 1.23 | +| `np.find_common_type` (§11) | `Y` | `Y` **(deprecated)** | Removed in NumPy 2.0 | +| `np.fmax`/`np.fmin` (§6) | `Y` | `~` | NaN-ignoring behavior not actually different from `maximum`/`minimum` | +| `nd.tofile()` (§16) | `Y` at `APIs/np.save.cs` | `Y` at `APIs/np.tofile.cs` | Wrong file path | +| `np.random.normal`/`standard_normal` (§15) | "Part of randn" | Independent impl + typo | `normal()` is standalone; `stardard_normal` is misspelled | + +### 5.2 Missing NumPy 2.x Functions (add to map) + +| Function | NumPy Version | Section | +|----------|--------------|---------| +| `np.matvec` | New in 2.2 | §13 Linear Algebra | +| `np.vecmat` | New in 2.2 | §13 Linear Algebra | +| `np.bitwise_count` | New in 2.0 | §6 Math | +| `np.isdtype` | New in 2.0 | §11 Logic | + +### 5.3 Deprecation Notes (add to map) + +These entries in the map should note they correspond to deprecated NumPy APIs: +- `np.row_stack` (§2): "Deprecated alias for vstack, removed in NumPy 2.0" +- `np.trapezoid` (§21): "Renamed from np.trapz in NumPy 2.0" + +--- + +## 6. Documentation URL Audit + +### 6.1 Old scipy-hosted URLs + +**385 occurrences across 121 files** of `https://numpy.org/doc/stable/...` in XML doc `` tags. + +**Fix**: Bulk replace `https://numpy.org/doc/stable/` → `https://numpy.org/doc/stable/` + +### 6.2 Version-pinned NumPy 1.x URLs + +**54 occurrences across 22 files** referencing specific 1.x versions: + +| Version | Files | Count | +|---------|-------|-------| +| `numpy-1.14.0` | np.random.binomial.cs | 2 | +| `numpy-1.15.0` | np.random.gamma.cs, np.random.exponential.cs, np.random.chisquare.cs, np.clip.cs, np.linspace.cs, np.exp.cs | 16 | +| `numpy-1.16.0` | np.asscalar.cs, np.array_equal.cs, np.dtype.cs, np.reshape.cs, NDArray.Equals.cs, np.cs | 16 | +| `numpy-1.16.1` | Default.Broadcasting.cs, np.random.cs, np.dtype.cs | 11 | +| `numpy-1.17.0` | NDArray.Indexing*.cs, np.cs | 5 | + +**Fix**: Replace all with `https://numpy.org/doc/stable/` (unversioned stable docs). + +--- + +## 7. Priority Action Items + +### Critical (must fix for NumPy 2.x compatibility) + +1. **Update 12 entries in `_typemap_arr_scalar`** — unsigned int array + signed int scalar should return the array's type under NEP 50. +2. **Implement `np.result_type()` and `np.promote_types()`** — replacements for the removed `np.find_common_type()`. +3. **Fix `np.any(axis)`** — two bugs: return value and inverted logic. + +### High Priority + +4. **Mark `np.asscalar` as `[Obsolete]`** — add `NDArray.item()` method as replacement. +5. **Fix `np.roll` static return type** — should return `NDArray`, not `int`. +6. **Fix `bool + bool` semantics** — should be integer addition, not OR. +7. **Fix `floor`/`ceil` on integer arrays** — should return same dtype, not cast to Double. + +### Medium Priority + +8. **Mark deprecated aliases `[Obsolete]`** — 13 symbols in `np.cs`. +9. **Mark `np.round_()` as `[Obsolete]`** — 4 overloads. +10. **Fix `np.fmax`/`np.fmin` NaN handling** — should ignore NaN unlike `maximum`/`minimum`. +11. **Fix `np.fmin` docstrings** — says "maximum" instead of "minimum". +12. **Fix `stardard_normal` typo** — rename to `standard_normal`. +13. **Update NUMPY_NUMSHARP_MAP.md** — 5 corrections + 4 new functions. + +### Low Priority + +14. **Update 385 doc URLs** — bulk replace `docs.scipy.org` → `numpy.org/doc/stable/`. +15. **Remove `DType.newbyteorder()`** — already throws, just dead weight. +16. **Clean up `asfarray` reference in `np.linalg.norm.cs` comments**. +17. **Remove `np.bool8`, `np.int0`, `np.uint0` aliases**. diff --git a/docs/plans/offset-model-rewrite.md b/docs/plans/offset-model-rewrite.md new file mode 100644 index 000000000..2a523a0a5 --- /dev/null +++ b/docs/plans/offset-model-rewrite.md @@ -0,0 +1,210 @@ +# Plan: Rewrite Offset Model to Match NumPy's `base_offset + strides` Architecture + +## Status: Investigation Required + +This document is the entry point for planning the rewrite of NumSharp's view/offset resolution system to match NumPy's architecture exactly. It identifies what needs to change, what needs to be investigated first, and the risks involved. + +## Problem Statement + +NumSharp uses a chain-based offset model (ViewInfo + BroadcastInfo) to resolve memory offsets for sliced and broadcast arrays. NumPy uses a flat model: `base_offset + sum(stride[i] * coord[i])`. NumSharp's model is the root cause of most broadcast/slice bugs and creates O(chain_depth) overhead per element access. + +### NumPy's Model (target) + +Every ndarray view stores exactly: +``` +data → pointer to first element of THIS view (not the allocation base) +shape → int[ndim] dimensions +strides → int[ndim] bytes per step (0 for broadcast, negative for reversed) +base → reference to parent array (for memory management / refcounting only) +``` + +Offset computation: `byte_offset = sum(strides[i] * coords[i])` — one loop, no branching, no chain resolution. + +When creating a slice `a[2:8:2, ::-1]`: +```python +new.data = a.data + 2*a.strides[0] + (a.shape[1]-1)*a.strides[1] +new.shape = [3, original_cols] +new.strides = [a.strides[0]*2, -a.strides[1]] +new.base = a.base or a +``` + +When broadcasting `broadcast_to(a, target_shape)`: +```python +new.data = a.data +new.shape = target_shape +new.strides = [0 if dim was stretched, else a.strides[i]] +new.base = a +``` + +Both operations compose naturally: slicing a broadcast produces correct strides via arithmetic on the existing strides. No special cases. + +### NumSharp's Current Model (to be replaced) + +``` +Shape +├── dimensions[] +├── strides[] ← may be broadcast strides (0) OR original strides +├── ViewInfo ← chain of slice history +│ ├── OriginalShape ← the unsliced root shape +│ ├── ParentShape ← intermediate sliced shape (for recursive slicing) +│ ├── Slices[] ← SliceDef per dimension (start, stop, step) +│ └── UnreducedShape ← shape before dimension reduction +└── BroadcastInfo ← broadcast history + ├── OriginalShape ← shape before broadcasting + └── UnreducedBroadcastedShape ← lazy-loaded resolved shape +``` + +Offset computation: 6+ code paths in `GetOffset`, `GetOffset_1D`, `GetOffset_broadcasted`, `GetOffset_broadcasted_1D`, `GetOffset_IgnoreViewInfo`, `resolveUnreducedBroadcastedShape`, plus recursive calls through `ParentShape.GetOffset`. + +## Target Architecture + +### Shape (after rewrite) + +```csharp +public struct Shape +{ + internal int[] dimensions; + internal int[] strides; // fully resolved — absorbs slicing, broadcasting + internal int base_offset; // offset to first element within InternalArray + internal int size; // product of dimensions + // ViewInfo and BroadcastInfo: REMOVED + // IsSliced, IsBroadcasted: derived from strides (stride=0 → broadcast) +} +``` + +### GetOffset (after rewrite) + +```csharp +public int GetOffset(params int[] coords) +{ + int offset = base_offset; + for (int i = 0; i < coords.Length; i++) + offset += strides[i] * coords[i]; + return offset; +} +``` + +### View Creation (after rewrite) + +```csharp +// Slicing: a[start:stop:step] along axis +new_base_offset = old_base_offset + start * old_strides[axis]; +new_strides[axis] = old_strides[axis] * step; +new_dimensions[axis] = (stop - start + step - 1) / step; // ceiling division + +// Negative step (reversal): a[::-1] along axis +new_base_offset = old_base_offset + (old_dimensions[axis] - 1) * old_strides[axis]; +new_strides[axis] = -old_strides[axis]; + +// Broadcasting: stretch dim from 1 to N +new_strides[axis] = 0; // that's it +new_dimensions[axis] = N; + +// Index reduction: a[3] along axis — removes dimension, adjusts base_offset +new_base_offset = old_base_offset + 3 * old_strides[axis]; +// remove axis from dimensions[] and strides[] +``` + +## Investigation Checklist + +Before writing a full implementation plan, the following must be investigated: + +### 1. Catalog all Shape consumers + +Every place that reads `ViewInfo`, `BroadcastInfo`, `IsSliced`, `IsBroadcasted`, `IsRecursive` needs to be identified and mapped to the new model. + +- [ ] `Shape.cs` — GetOffset variants, Slice(), TransformOffset, GetCoordinates, Clean, Clone +- [ ] `Shape.Unmanaged.cs` — unmanaged pointer access paths +- [ ] `Shape.Reshaping.cs` — reshape on sliced/broadcast views +- [ ] `NDIterator.cs` — iteration with AutoReset for broadcasting +- [ ] `MultiIterator.cs` — paired/broadcast iteration +- [ ] `UnmanagedStorage.Slicing.cs` — GetViewInternal, the Bug 17 materializing fix +- [ ] `UnmanagedStorage.Getters.cs` — element access +- [ ] `Default.Broadcasting.cs` — Broadcast() creates ViewInfo/BroadcastInfo +- [ ] Generated math templates (`Default.Add.*.cs`, `Default.Subtract.*.cs`, etc.) — ~24 files, ~200K lines that reference ViewInfo/BroadcastInfo for fast-path decisions +- [ ] `NDArray.Indexing.cs` — indexing dispatch +- [ ] Selection/masking code +- [ ] `np.reshape.cs` — reshape interacts with views + +### 2. Understand IArraySlice bounds checking + +NumPy adjusts the `data` pointer to point at the first view element. NumSharp uses `IArraySlice` with bounds-checked access via `Count`. Questions: + +- [ ] Can `base_offset` be negative? (yes, for reversed views the first logical element may precede the parent's first element in memory — NumPy handles this with pointer arithmetic, NumSharp would need signed offset) +- [ ] Does `IArraySlice` support negative indexing or must we use raw pointers? +- [ ] Should we keep `IArraySlice` bounds checking (safety) or move to unchecked pointer access (performance)? +- [ ] How does `InternalArray.Address` interact with offset-based access? + +### 3. Understand NDIterator's relationship to strides + +NDIterator has fast paths for contiguous arrays and slow paths for sliced/broadcast. Questions: + +- [ ] With the new model, is NDIterator still needed or can it be simplified to `pointer + stride` walking? +- [ ] Does AutoReset (for broadcast smaller-into-larger iteration) still work with flat strides? +- [ ] What is the performance impact of removing the contiguous fast path (since all arrays now use the same stride-based access)? + +### 4. Understand reshape-after-slice interactions + +`np.reshape(sliced_view)` in NumPy either returns a view (if the slice is contiguous) or copies. NumSharp's `IsRecursive` flag and `ParentShape` chain handle this. Questions: + +- [ ] Can reshape on a non-contiguous view be handled with just `base_offset + strides`? +- [ ] When must reshape force a copy? (NumPy: when the data is not contiguous in the requested order) +- [ ] How to detect contiguity from strides alone? (check: `strides[i] == strides[i+1] * dimensions[i+1]` for all i) + +### 5. Understand generated template code + +The `Regen` templates generate type-specific math code that checks `IsBroadcasted` / `IsSliced` for fast-path branching. + +- [ ] What does the template source look like? (`Default.Op.General.template.cs`) +- [ ] Can the fast-path decisions be made from strides alone? (e.g., contiguous = strides match row-major; broadcast = any stride is 0) +- [ ] How to regenerate after changes? + +### 6. Map `IsSliced` / `IsBroadcasted` to stride-based checks + +Current flags: +- `IsSliced` → `ViewInfo != null` +- `IsBroadcasted` → `BroadcastInfo != null` +- `IsContiguous` → complex check involving ViewInfo + +New derivations: +- `IsBroadcasted` → `any(strides[i] == 0 && dimensions[i] > 1)` +- `IsContiguous` → `strides == row_major_strides(dimensions)` (can precompute) +- `IsSliced` → no longer a meaningful concept; all views are just `base_offset + strides` + +### 7. Memory management / aliasing + +- [ ] How does NumSharp track that a view shares memory with a parent? (`InternalArray` reference) +- [ ] Does `base_offset` change anything about GC pinning or unmanaged memory lifetime? +- [ ] The `Alias()` method creates views — confirm it can work with `base_offset` + +## Risk Assessment + +| Risk | Severity | Mitigation | +|------|----------|------------| +| Breaking the 1601 passing tests | High | Incremental approach — keep old model behind a flag initially | +| Generated template code (~200K lines) | High | Must understand Regen before touching templates | +| NDIterator redesign cascade | Medium | May need to rewrite iteration entirely | +| Performance regression | Medium | Benchmark before/after; the new model should be faster (fewer branches) | +| Reshape-after-slice edge cases | Medium | Port NumPy's contiguity check exactly | +| Negative base_offset for reversed views | Medium | Verify IArraySlice can handle it or use pointer arithmetic | + +## Suggested Investigation Approach + +1. Start with investigation items 1-3 above — catalog every consumer and understand the constraints +2. Build a prototype `Shape2` struct with `base_offset + strides` alongside the existing `Shape` +3. Add a `ToShape2()` conversion and verify offset parity on all test cases +4. Once parity is confirmed, plan the incremental migration file by file + +## NumPy Reference Files + +These files in `src/numpy/` contain the authoritative implementation: + +| File | What to study | +|------|---------------| +| `numpy/_core/include/numpy/ndarraytypes.h` | `PyArrayObject` struct — `data`, `dimensions`, `strides`, `base` | +| `numpy/_core/src/multiarray/getitem.c` | Element access via strides | +| `numpy/_core/src/multiarray/mapping.c` | Slice/index view creation, stride computation | +| `numpy/_core/src/multiarray/ctors.c` | Array construction, contiguity checks | +| `numpy/_core/src/multiarray/shape.c` | Reshape — when to copy vs view | +| `numpy/_core/src/multiarray/nditer_constr.c` | Iterator setup, stride=0 for broadcast | +| `numpy/lib/_stride_tricks_impl.py` | `as_strided`, `broadcast_to`, `broadcast_arrays` | diff --git a/docs/releases/RELEASE_0.41.0-prerelease.md b/docs/releases/RELEASE_0.41.0-prerelease.md new file mode 100644 index 000000000..250228705 --- /dev/null +++ b/docs/releases/RELEASE_0.41.0-prerelease.md @@ -0,0 +1,479 @@ +# NumSharp 0.41.0-prerelease + +This prerelease introduces the **IL Kernel Generator** - a complete architectural overhaul that replaces ~600K lines of Regen-generated template code with ~19K lines of runtime IL generation. This delivers massive performance improvements, comprehensive NumPy 2.x alignment, and significantly cleaner maintainable code. + +--- + +## TL;DR + +- **IL Kernel Generator**: Runtime IL emission replaces 600K lines of Regen templates with 19K lines +- **SIMD everywhere**: Vector128/256/512 with runtime detection across all operations +- **35 new functions**: nansum/prod/min/max/mean/var/std, cbrt, floor_divide, left/right_shift, deg2rad, rad2deg, cumprod, count_nonzero, isnan, isfinite, isinf, isclose, invert, reciprocal, square, trunc, plus comparison and logical modules +- **Operators fixed**: `==`, `!=`, `<`, `>`, `<=`, `>=`, `&`, `|`, `^` +- **np.comparison module**: `np.equal()`, `np.not_equal()`, `np.less()`, `np.greater()`, `np.less_equal()`, `np.greater_equal()` +- **np.logical module**: `np.logical_and()`, `np.logical_or()`, `np.logical_not()`, `np.logical_xor()` +- **NDArray\ operators**: Typed `&`, `|`, `^` for generic arrays (resolves `NDArray` ambiguity) +- **Math functions rewritten**: sin, cos, tan, exp, log, sqrt, abs, sign, floor, ceil, etc. +- **60+ bug fixes**: np.negative, np.positive, np.unique, np.dot, np.matmul, np.abs, np.argmax/min, np.mean, np.std/var, np.cumsum, np.nonzero, np.all/any, np.clip, and more +- **MatMul 35-100x faster**: Cache-blocked SIMD achieving 20+ GFLOPS +- **Boolean indexing rewrite**: SIMD fast path with CountTrue/CopyMasked +- **Axis reductions rewrite**: AVX2 gather, NaN-aware, proper keepdims and empty array handling +- **Single-threaded execution**: Deterministic, non-blocking (SIMD compensates for parallelism), Removed use of `Parallel.*` +- **Architecture cleanup**: Broadcasting in Shape struct, TensorEngine routing, static ILKernelGenerator +- **np.random aligned** (#582): Parameter names match NumPy, Shape overloads added +- **DecimalMath internalized** (#588): Removed embedded third-party code +- **NEP50 compliant**: NumPy 2.x type promotion rules +- **Benchmark infrastructure**: SIMD vs scalar comparison suite +- **DefaultEngine dispatch layer**: BinaryOp, BitwiseOp, CompareOp, ReductionOp, UnaryOp +- +4,200 unit tests, our own and migrated from python/numpy to C#. + +--- + +## Contents + +| Section | Highlights | +|---------|------------| +| [Summary](#summary) | 106 commits, -533K lines, 3,907 tests | +| [IL Kernel Generator](#il-kernel-generator) | 27 files, SIMD V128/256/512 | +| [Architecture](#architecture) | Static ILKernelGenerator, TensorEngine routing | +| [New NumPy Functions (35)](#new-numpy-functions-25) | nansum, isnan, cumprod, etc. | +| [Critical Bug Fixes](#critical-bug-fixes) | negative, unique, dot, linspace, intp | +| [Operator Rewrites](#operator-rewrites) | ==, !=, <, >, &, \| now work | +| [Boolean Indexing Rewrite](#boolean-indexing-rewrite) | SIMD fast path, 76 battle tests | +| [Slicing Improvements](#slicing-improvements) | Broadcast stride=0 preserved | +| [Performance Improvements](#performance-improvements) | MatMul 35-100x, 20+ GFLOPS | +| [Code Reduction](#code-reduction) | 99% binary, 98% MatMul, 97% Dot | +| [Infrastructure Changes](#infrastructure-changes) | NativeMemory, static kernels | +| [API Alignment](#api-alignment) | random() params aligned with NumPy | +| [New Test Files (68)](#new-test-files-68) | 34 kernel, 8 NumPy, 4 linalg, 76 boolean | +| [Breaking Changes](#breaking-changes) | None | +| [Known Issues](#known-issues-openbugs) | 52 OpenBugs excluded | +| [Installation](#installation) | `dotnet add package NumSharp` | + +--- + +## Summary + +| Metric | Value | +|--------|-------| +| Commits | 106 | +| Files Changed | 558 | +| Lines Added | +72,635 | +| Lines Deleted | -605,976 | +| **Net Change** | **-533K lines** | +| Test Results | 3,907 passed, 52 OpenBugs, 11 skipped | + +--- + +## IL Kernel Generator + +Runtime IL generation via `System.Reflection.Emit.DynamicMethod` replaces static Regen templates. + +### Kernel Files (27 new files) +- `ILKernelGenerator.cs` - Core infrastructure, SIMD detection (Vector128/256/512) +- `ILKernelGenerator.Binary.cs` - Add, Sub, Mul, Div, BitwiseAnd/Or/Xor +- `ILKernelGenerator.MixedType.cs` - Mixed-type ops with type promotion +- `ILKernelGenerator.Unary.cs` - Negate, Abs, Sqrt, Sin, Cos, Exp, Log, Sign +- `ILKernelGenerator.Comparison.cs` - ==, !=, <, >, <=, >= returning bool arrays +- `ILKernelGenerator.Reduction.cs` - Sum, Prod, Min, Max, Mean, ArgMax, ArgMin, All, Any +- `ILKernelGenerator.Reduction.Axis.Simd.cs` - AVX2 gather for axis reductions +- `ILKernelGenerator.Scan.cs` - CumSum, CumProd with SIMD +- `ILKernelGenerator.Shift.cs` - LeftShift, RightShift +- `ILKernelGenerator.MatMul.cs` - Cache-blocked SIMD matrix multiply +- `ILKernelGenerator.Clip.cs`, `.Modf.cs`, `.Masking.cs` - Specialized ops + +### Execution Paths +1. **SimdFull** - Contiguous + SIMD-capable dtype → Vector loop + scalar tail +2. **ScalarFull** - Contiguous + non-SIMD dtype (Decimal) → Scalar loop +3. **General** - Strided/broadcast → Coordinate-based iteration + +### Infrastructure +- `KernelKey.cs`, `KernelOp.cs`, `KernelSignatures.cs` - Kernel dispatch +- `SimdMatMul.cs` - SIMD matrix multiplication helpers +- `TypeRules.cs` - NEP50 type promotion rules + +--- + +## Architecture + +Clean separation of concerns: + +| Component | Design | +|-----------|--------| +| `ILKernelGenerator` | Static class (27 partial files), internal to `DefaultEngine` | +| `TensorEngine` | All `np.*` ops route through abstract methods | +| `Shape.Broadcasting` | Pure shape math in `Shape` struct (456 lines) | +| `ArgMin/ArgMax` | Unified IL kernel with NaN-aware + Boolean semantics | +| `DecimalMath` | Internal utility (~403 lines) for Sqrt, Pow, ATan2, Exp, Log | + +### Single-Threaded Execution +All computation is single-threaded with no `Parallel.For` usage. This provides: +- **Deterministic behavior** - Same inputs always produce same outputs in same order +- **Non-blocking execution** - No thread synchronization overhead +- **Simplified debugging** - Stack traces are straightforward +- **SIMD compensation** - Vector128/256/512 intrinsics provide parallelism at the CPU level + +### Broadcasting External to Engine +Broadcasting logic (`Shape.Broadcasting.cs`) is pure shape math with no engine dependencies: +- `Shape.AreBroadcastable()` - Check if shapes can broadcast +- `Shape.Broadcast()` - Compute broadcast result shape and strides +- `Shape.ResolveReturnShape()` - Determine output shape for operations +- `DefaultEngine` delegates all broadcasting to `Shape.*` methods + +### DecimalMath (#588) +Replaced embedded third-party `DecimalEx.cs` (~1061 lines) with minimal internal `DecimalMath.cs` (~403 lines) containing only the functions NumSharp actually uses: Sqrt, Pow, ATan2, Exp, Log, Log10, ATan. + +### TensorEngine Abstract Methods +`Compare`, `NotEqual`, `Less`, `LessEqual`, `Greater`, `GreaterEqual`, `BitwiseAnd`, `BitwiseOr`, `BitwiseXor`, `LeftShift`, `RightShift`, `Power(NDArray, NDArray)`, `FloorDivide`, `Truncate`, `Reciprocal`, `Square`, `Cbrt`, `Invert`, `Deg2Rad`, `Rad2Deg`, `IsInf`, `ReduceCumMul`, `Any`, `NanSum`, `NanProd`, `NanMin`, `NanMax`, `BooleanMask` + +### DefaultEngine Dispatch Files (IL kernel integration) +| File | Functions | +|------|-----------| +| `DefaultEngine.BinaryOp.cs` | `np.add`, `np.subtract`, `np.multiply`, `np.divide`, `np.mod`, `np.power` | +| `DefaultEngine.BitwiseOp.cs` | `np.bitwise_and`, `np.bitwise_or`, `np.bitwise_xor`, `&`, `\|`, `^` | +| `DefaultEngine.CompareOp.cs` | `np.equal`, `np.not_equal`, `np.less`, `np.greater`, `np.less_equal`, `np.greater_equal` | +| `DefaultEngine.ReductionOp.cs` | `np.sum`, `np.prod`, `np.min`, `np.max`, `np.mean`, `np.std`, `np.var`, `np.argmax`, `np.argmin` | +| `DefaultEngine.UnaryOp.cs` | `np.abs`, `np.negative`, `np.sqrt`, `np.sin`, `np.cos`, `np.exp`, `np.log`, `np.sign`, etc. | + +### Implementation Files +`Default.Any.cs`, `Default.BooleanMask.cs`, `Default.Reduction.Nan.cs`, `Shape.Broadcasting.cs` + +--- + +## New NumPy Functions (35) + +### NaN-Aware Reductions (7) +| Function | Description | +|----------|-------------| +| `np.nansum` | Sum ignoring NaN | +| `np.nanprod` | Product ignoring NaN | +| `np.nanmin` | Minimum ignoring NaN | +| `np.nanmax` | Maximum ignoring NaN | +| `np.nanmean` | Mean ignoring NaN | +| `np.nanvar` | Variance ignoring NaN | +| `np.nanstd` | Standard deviation ignoring NaN | + +### Math Operations (8) +| Function | Description | +|----------|-------------| +| `np.cbrt` | Cube root | +| `np.floor_divide` | Integer division | +| `np.reciprocal` | Element-wise 1/x | +| `np.trunc` | Truncate to integer | +| `np.invert` | Bitwise NOT | +| `np.square` | Element-wise square | +| `np.cumprod` | Cumulative product | +| `np.count_nonzero` | Count non-zero elements | + +### Bitwise & Trigonometric (4) +| Function | Description | +|----------|-------------| +| `np.left_shift` | Bitwise left shift | +| `np.right_shift` | Bitwise right shift | +| `np.deg2rad` | Degrees to radians | +| `np.rad2deg` | Radians to degrees | + +### Logic & Validation (4) - Previously returned `null` +| Function | Description | +|----------|-------------| +| `np.isnan` | Test element-wise for NaN | +| `np.isfinite` | Test element-wise for finiteness | +| `np.isinf` | Test element-wise for infinity | +| `np.isclose` | Element-wise comparison within tolerance | + +### Operators (2) - Previously returned `null` +| Operator | Description | +|----------|-------------| +| `operator &` | Bitwise/logical AND with broadcasting | +| `operator \|` | Bitwise/logical OR with broadcasting | + +### Comparison Functions (6) - New named API +| Function | Description | +|----------|-------------| +| `np.equal` | Element-wise equality (wraps `==`) | +| `np.not_equal` | Element-wise inequality (wraps `!=`) | +| `np.less` | Element-wise less than (wraps `<`) | +| `np.greater` | Element-wise greater than (wraps `>`) | +| `np.less_equal` | Element-wise less or equal (wraps `<=`) | +| `np.greater_equal` | Element-wise greater or equal (wraps `>=`) | + +### Logical Functions (4) - New named API +| Function | Description | +|----------|-------------| +| `np.logical_and` | Element-wise logical AND | +| `np.logical_or` | Element-wise logical OR | +| `np.logical_not` | Element-wise logical NOT | +| `np.logical_xor` | Element-wise logical XOR | + +### New Overloads +| Function | New Capability | +|----------|----------------| +| `np.power(array, array)` | Array exponents (was scalar only) | +| `np.repeat(array, NDArray)` | Per-element repeat counts | +| `np.argmax/argmin(axis, keepdims)` | keepdims parameter | +| `np.convolve` | Complete rewrite (was throwing NRE) | + +--- + +## Critical Bug Fixes + +### Behavioral Fixes +| Bug | Before | After | +|-----|--------|-------| +| `np.negative()` | Only negated positive values (`if val > 0`) | Negates ALL values (`val = -val`) | +| `np.positive()` | Applied `abs()` | Identity operation (returns input unchanged) | +| `np.unique()` | Returned unsorted | Sorts output, NaN at end | +| `np.dot(1D, 2D)` | Threw `NotSupportedException` | Treats 1D as row vector | +| `np.dot()` non-contiguous | Failed on strided arrays | Works with all memory layouts | +| `np.matmul()` broadcast | Crashed with >2D arrays | Full broadcasting support | +| `np.linspace()` | Returned `float32` for float inputs | Always `float64` default | +| `np.arange()` | Threw on `start >= stop` | Returns empty array | +| `np.searchsorted()` | No scalar support | Added scalar overloads returning `int` | +| `np.shuffle()` | Non-standard `passes` parameter | NumPy legacy API (axis-0 only) | +| `np.moveaxis()` | Broken | Verified working | +| `np.argsort()` | NaN handling incorrect | NaN-aware sorting | +| `np.intp` | Mapped to `int` (always 32-bit) | Uses `nint` (native-sized integer) | +| `np.uintp` | Not defined | Added as `nuint` (native unsigned) | +| `np.LogicalNot()` | Changed dtype | Preserves Boolean type | +| Float-to-int conversion | Used rounding | Uses truncation toward zero | + +### Return Type Fixes +| Function | Before | After | +|----------|--------|-------| +| `np.argmax()` / `np.argmin()` | Returned `int` | Returns `long` (large array support) | +| `np.abs()` | Converted to Double | Preserves input dtype | + +### Empty Array Handling +| Function | Before | After | +|----------|--------|-------| +| `np.mean([])` | Threw or returned 0 | Returns `NaN` | +| `np.mean(zeros((0,3)), axis=0)` | Incorrect | `[NaN, NaN, NaN]` | +| `np.mean(zeros((0,3)), axis=1)` | Incorrect | Empty array `[]` | +| `np.std/var` single element | Returned 0 | Returns `NaN` with `ddof >= size` | + +### keepdims Fixes +All reduction functions now properly preserve dimensions when `keepdims=True`: +- `np.sum`, `np.prod`, `np.mean`, `np.std`, `np.var` +- `np.min`, `np.max`, `np.argmin`, `np.argmax` + +### Rewritten Functions (IL kernel migration) +| Function | Fix | +|----------|-----| +| `np.all()` | SIMD, all 12 dtypes (was boolean-only) | +| `np.any()` | SIMD with early-exit; axis parameter fixed (was always throwing) | +| `np.sum()` | Axis reduction for broadcast arrays | +| `np.cumsum()` | Axis support with SIMD, 4K lines Regen removed | +| `np.cumprod()` | Axis support with SIMD | +| `np.nonzero()` | Unified IL approach | +| `np.clip()` | IL kernel rewrite | + +### Math Functions (IL migration) +All migrated from Regen templates to IL kernels with SIMD: +- **Trig**: `sin`, `cos`, `tan`, `sinh`, `cosh`, `tanh`, `arcsin`, `arccos`, `arctan`, `arctan2` +- **Exp/Log**: `exp`, `exp2`, `expm1`, `log`, `log2`, `log10`, `log1p` +- **Other**: `sqrt`, `abs`, `sign`, `floor`, `ceil`, `round` + +--- + +## Operator Rewrites + +### Comparison Operators (==, !=, <, >, <=, >=) +- **Before**: Manual type switch per dtype +- **After**: Uses `TensorEngine` with IL kernels +- Proper null handling (returns `false` scalar) +- Empty array handling (returns empty bool array) +- Added reverse operators (`object op NDArray`) +- Full broadcasting support + +### Bitwise Operators (&, |, ^) +- **Before**: Returned `null` +- **After**: Full implementation via IL kernels +- Added `NDArray` typed operators +- Scalar overloads for all integer types + +### Implicit Scalar Conversion +- **Before**: `(int)ndarray_float64` would fail +- **After**: Uses `Converts.ChangeType` for cross-dtype conversion + +--- + +## Boolean Indexing Rewrite + +Complete rewrite with NumPy-aligned behavior: + +### Two Cases Supported +1. `arr[mask]` where `mask.shape == arr.shape` → element-wise selection +2. `arr[mask]` where `mask` is 1D and `mask.shape[0] == arr.shape[0]` → axis-0 selection + +### SIMD Fast Path +- New `BooleanMaskFastPath` for contiguous arrays +- `CountTrue(bool*, int)` - SIMD count of true values +- `CopyMasked(src, mask, dest, size)` - SIMD masked copy + +--- + +## Slicing Improvements + +### Broadcast Array Handling +- **Before**: Slicing broadcast arrays would materialize data (losing stride=0) +- **After**: Preserves stride=0 information (NumPy behavior) +- Critical for `cumsum` and axis reductions on broadcast arrays + +### Empty Slice Handling +- `a[100:200]` on 10-element array now returns proper empty array + +### Contiguous Optimization +- Contiguous slices get fresh shape with `offset=0` +- `IsSliced=false` for contiguous slices + +--- + +## Performance Improvements + +| Operation | Improvement | Details | +|-----------|-------------|---------| +| MatMul (2D) | 35-100x | Cache-blocked SIMD, 20+ GFLOPS | +| Axis Reductions | Major | AVX2 gather + parallel outer loop | +| All/Any | Major | SIMD with early-exit | +| CumSum/CumProd | Major | Element-wise SIMD | +| Boolean Masking | Major | SIMD CountTrue + CopyMasked | +| Integer Abs/Sign | Minor | Bitwise (branchless) | +| Vector512 | New | Runtime detection and utilization | +| Loop Unrolling | 4x | All SIMD kernels | + +--- + +## Code Reduction + +### Massive File Deletions +| Component | Before | After | Reduction | +|-----------|--------|-------|-----------| +| Binary ops (Add/Sub/Mul/Div/Mod) | 60 files, ~500K lines | 2 IL files | **99%** | +| `Default.MatMul.2D2D.cs` | ~20K lines | 325 lines | **98.4%** | +| `Default.Dot.NDMD.cs` | ~16K lines | 422 lines | **97.4%** | +| Comparison ops (Equals) | 13 files | 1 IL file | **92%** | +| Std/Var reductions | ~20K lines | ~500 lines | **97%** | + +### Deleted Files (76) +- 60 binary op files (`Default.Add.{Type}.cs`, etc.) +- 13 comparison files (`Default.Equals.{Type}.cs`, etc.) +- 3 template files + +--- + +## Infrastructure Changes + +### Memory Allocation +- `Marshal.AllocHGlobal` → `NativeMemory.Alloc` +- `Marshal.FreeHGlobal` → `NativeMemory.Free` +- `AllocationType.AllocHGlobal` → `AllocationType.Native` +- `StackedMemoryPool` migrated to NativeMemory + +### DefaultEngine +- `ILKernelGenerator` is a static class (internal to DefaultEngine) +- Single-threaded execution (no `Parallel.For`) + +### Math Functions +All migrated from Regen templates to `ExecuteUnaryOp`: +- Sin, Cos, Tan, ASin, ACos, ATan, ATan2 +- Exp, Exp2, Expm1, Log, Log2, Log10, Log1p +- Sqrt, Cbrt, Abs, Sign, Floor, Ceil, Truncate +- Removed `DecimalMath` dependency for most operations + +### TensorEngine Extensions +New abstract methods (28 total): +- **Comparison**: `Compare`, `NotEqual`, `Less`, `LessEqual`, `Greater`, `GreaterEqual` +- **Bitwise**: `BitwiseAnd`, `BitwiseOr`, `BitwiseXor`, `LeftShift`, `RightShift` +- **Math**: `Power(NDArray, NDArray)`, `FloorDivide`, `Truncate`, `Reciprocal`, `Square`, `Cbrt`, `Invert`, `Deg2Rad`, `Rad2Deg`, `IsInf` +- **Reduction**: `ReduceCumMul`, `Any`, `NanSum`, `NanProd`, `NanMin`, `NanMax` +- **Indexing**: `BooleanMask` + +### IKernelProvider Methods +- `CountTrue(bool*, int)` - SIMD true count +- `CopyMasked` - SIMD masked copy +- `Variance`, `StandardDeviation` - SIMD two-pass +- `NanSum/Prod/Min/Max` for float/double +- `FindNonZeroStrided` - Strided nonzero detection + +--- + +## API Alignment + +| API | NumPy-Aligned Behavior | +|-----|------------------------| +| `np.random.random()` | Alias for `random_sample()` | +| `np.random.standard_normal()` | Correct spelling (matches NumPy) | +| `np.random.*` params | `size`, `a`, `b`, `p`, `d0` (NumPy names) | +| `np.random.randn/rand/normal` | Accept `Shape` parameter | +| `np.minimum/maximum` | `dtype` parameter (not `outType`) | +| `np.modf()` | Validates floating-point input | + +--- + +## New Test Files (68) + +### Kernel Tests (34) +`BinaryOpTests`, `UnaryOpTests`, `ComparisonOpTests`, `ReductionOpTests`, `AxisReductionSimdTests`, `NonContiguousTests`, `SlicedArrayOpTests`, `NanReductionTests`, `VarStdComprehensiveTests`, `ArgMaxArgMinComprehensiveTests`, `CumSumComprehensiveTests`, `BitwiseOpTests`, `ShiftOpTests`, `DtypeCoverageTests`, `DtypePromotionTests`, `EdgeCaseTests`, `BattleProofTests`, `SimdOptimizationTests`, and more. + +### NumPy Ported Tests (8) +`ArgMaxArgMinEdgeCaseTests`, `ClipEdgeCaseTests`, `ClipNDArrayTests`, `CumSumEdgeCaseTests`, `ModfEdgeCaseTests`, `NonzeroEdgeCaseTests`, `PowerEdgeCaseTests`, `VarStdEdgeCaseTests` + +### Linear Algebra Battle Tests (4) +`np.dot.BattleTest` (195 tests), `np.matmul.BattleTest` (106 tests), `np.outer.BattleTest` (88 tests) + +### Boolean Indexing Battle Tests (76 tests) +`BooleanIndexing.BattleTests.cs` - Comprehensive NumPy 2.4.2 alignment covering same-shape masks, axis-0 selection, partial shape match, 0-D indexing, mask assignment, empty masks, shape mismatch errors, non-contiguous arrays, all dtypes, NaN/Infinity, logical operations. + +### Random Sampling Tests +`np.random.shuffle.NumPyAligned.Test.cs` (133 tests) + +--- + +## Breaking Changes + +**None.** This is a drop-in replacement with improved performance and NumPy compatibility. + +--- + +## Known Issues (OpenBugs) + +52 tests marked as `[OpenBugs]` are excluded from CI: +- sbyte (int8) type not supported +- Some bitmap operations require GDI+ (Windows only) +- Various edge cases documented in test files + +--- + +## Installation + +```bash +dotnet add package NumSharp --version 0.41.0-prerelease +``` + +Or via Package Manager: +```powershell +Install-Package NumSharp -Version 0.41.0-prerelease +``` + +## Testing + +```bash +cd test/NumSharp.UnitTest + +# Run tests excluding known issues +dotnet test -- "--treenode-filter=/*/*/*/*[Category!=OpenBugs]" + +# Run all tests +dotnet test +``` + +--- + +## Feedback + +This is a prerelease. Please report any issues at: +https://github.com/SciSharp/NumSharp/issues + +--- + +**Full Changelog**: See [CHANGES.md](./CHANGES.md) for complete documentation of all 106 commits. diff --git a/docs/releases/RELEASE_0.50.0-prerelease.md b/docs/releases/RELEASE_0.50.0-prerelease.md new file mode 100644 index 000000000..e06773d32 --- /dev/null +++ b/docs/releases/RELEASE_0.50.0-prerelease.md @@ -0,0 +1,467 @@ +# NumSharp 0.50.0 - Long Indexing Release + +This release introduces **Int64/Long Indexing** - a complete architectural migration enabling arrays larger than 2.1 billion elements (>2GB), along with comprehensive **NumPy 2.x type system alignment**, new type introspection APIs, and the Python container protocol. + +## TL;DR + +- **Int64/Long Indexing**: Full migration from `int` to `long` across Shape, NDArray, Storage, Iterators, and ILKernelGenerator - ndarrays >2GB now supported +- **12 New Type APIs**: `np.can_cast`, `np.promote_types`, `np.result_type`, `np.min_scalar_type`, `np.common_type`, `np.issubdtype`, `np.finfo`, `np.iinfo`, `np.isreal`, `np.iscomplex`, `np.isrealobj`, `np.iscomplexobj` +- **6 Comparison Functions**: `np.equal`, `np.not_equal`, `np.less`, `np.greater`, `np.less_equal`, `np.greater_equal` +- **4 Logical Functions**: `np.logical_and`, `np.logical_or`, `np.logical_not`, `np.logical_xor` +- **Container Protocol**: `__contains__`, `__len__`, `__iter__`, `__getitem__`, `__setitem__` - NumPy-compatible iteration +- **New NDArray Methods**: `tolist()`, `item()` for NumPy parity +- **NumPy 2.x Type System**: `np.arange()` returns Int64, `NPTypeHierarchy` encoding NumPy's exact type tree, Bool NOT under Number +- **`np.frombuffer()` Rewrite**: Full NumPy signature with `count`, `offset`, big-endian support, `IntPtr`/`void*` overloads, view semantics +- **0D Scalar Arrays**: `np.array(5)` now creates 0D arrays (matching NumPy) +- **`np.arange()` Fixes**: Negative step, integer arithmetic, inlined type-specific loops, full NumPy parity. +- **`np.any/np.all`**: 0D array support with axis parameter +- **Random API Alignment** (#582): Parameter names match NumPy, `np.shuffle` fixed +- **Empty Array Handling**: Proper NaN returns for mean/std/var on empty arrays +- **NaN Sorting**: `np.unique` now sorts NaN to end (matches NumPy) +- **ValueType to Object Migration**: All scalar returns now `object` (NumPy alignment), discarded usages of ValueType +- **UnmanagedSpan**: Ported from dotnet/runtime for Span-like semantics with `long` length +- **Operator Cleanup**: 74% reduction in NDArray.Primitive.cs (150 → 40 overloads) +- **600+ Battle Tests**: All validated against actual NumPy 2.x output +- **145 Test Fixes**: 71 for Int64 alignment + 74 previously failing tests now passing + + +## Contents + +- [Int64/Long Indexing](#int64long-indexing-support) +- [NumPy 2.x Type System](#numpy-2x-type-system) +- [Container Protocol](#container-protocol) +- [New APIs](#new-apis) +- [Bug Fixes](#bug-fixes) +- [Performance](#performance-improvements) +- [Refactoring](#refactoring) +- [Test Improvements](#test-improvements) +- [Breaking Changes](#breaking-changes) +- [Known Issues](#known-issues) +- [Documentation](#documentation) +- [Installation](#installation) + + + +## Int64/Long Indexing Support + +Complete migration from `int` to `long` indexing across the entire codebase, enabling arrays larger than 2.1 billion elements (~2GB for byte arrays, ~16GB for doubles). + +### Core Type Changes + +- `Shape.dimensions`: `int[]` -> `long[]` +- `Shape.strides`: `int[]` -> `long[]` +- `Shape.size`: `int` -> `long` +- `Shape.offset`: `int` -> `long` +- `NDArray.size`: `int` -> `long` +- `NDArray.len`: `int` -> `long` +- All NDArray indexers: `int` -> `long` +- `ArraySlice`: `int` indexing -> `long` indexing +- `UnmanagedMemoryBlock`: `int` indexing -> `long` indexing +- `UnmanagedStorage`: `int` indexing -> `long` indexing +- `NDIterator` coordinates: `int[]` -> `long[]` +- `MultiIterator`: `int` offsets -> `long` offsets +- `np.nonzero()`: Returns `NDArray[]` instead of `NDArray[]` +- `np.argmax/argmin`: Returns `long` indices + +### ILKernelGenerator Migration (20+ files) + +All ILKernelGenerator partial classes updated for `long` loop counters and offsets: + +- `ILKernelGenerator.Binary.cs` - Loop counters to `long` +- `ILKernelGenerator.Reduction.cs` - Index variables to `long` +- `ILKernelGenerator.Reduction.Axis.cs` - Axis iteration with `long` +- `ILKernelGenerator.Reduction.Axis.Simd.cs` - SIMD paths with `long` +- `ILKernelGenerator.Reduction.Axis.NaN.cs` - NaN handling with `long` +- `ILKernelGenerator.Reduction.Axis.Arg.cs` - ArgMax/ArgMin with `long` +- `ILKernelGenerator.Reduction.Axis.VarStd.cs` - Variance/StdDev with `long` +- `ILKernelGenerator.Reduction.NaN.cs` - **NEW** NaN reductions IL generation +- `ILKernelGenerator.Scan.cs` - CumSum/CumProd with `long` indices +- `ILKernelGenerator.MatMul.cs` - Matrix dimensions to `long` +- `ILKernelGenerator.Clip.cs` - TransformOffset calculations +- `ILKernelGenerator.Masking.cs` - Boolean masking with `long` +- `ILKernelGenerator.Masking.Boolean.cs` - Boolean operations with `long` +- `ILKernelGenerator.Masking.NaN.cs` - NaN masking with `long` +- `ILKernelGenerator.Masking.VarStd.cs` - Variance masking with `long` + +### New Infrastructure + +- `UnmanagedSpan` - Ported from dotnet/runtime Span - Span-like with `long` length +- `ReadOnlyUnmanagedSpan` - Read-only variant +- `UnmanagedSpanExtensions` - Extension methods for Span parity +- `UnmanagedSpanHelpers` - SIMD-optimized value type methods +- `UnmanagedSpanHelpers.T.cs` - Generic type helpers +- `UnmanagedBuffer` - Buffer management for long arrays +- `LongIntroSort` - Sorting algorithm for large arrays (port of .NET IntroSort) +- `LongIndexBuffer` - Unmanaged index collection (replaces List for >2B indices) +- `BitHelperLong` - Long-indexed bit marking (for >2B bits) +- `IndexCollector.cs` - **NEW** Index collection for masking operations +- `Hashset` - Upgraded to long-based indexing with 33% growth + +### New API Overloads + +- `NDArray.GetInt32(long[])` - Long coordinate access +- `NDArray.GetInt64(long[])` - Long coordinate access +- `NDArray.GetSingle(long[])` - Long coordinate access +- `NDArray.GetDouble(long[])` - Long coordinate access +- `NDArray.GetBoolean(long[])` - Long coordinate access +- `NDArray.GetByte(long[])` - Long coordinate access +- All 9 typed setters with `long[]` coordinates +- All other typed getters with `long[]` coordinates +- `np.random.choice` - `long` population size support +- `np.repeat` - `long` repeat counts +- `np.linspace` - `long` num parameter +- `np.roll` - `long` shift parameter +- All random sampling functions - `long[]` size parameters + + + +## NumPy 2.x Type System + +### `np.arange()` Returns Int64 + +- `np.arange(10)` - Before: `Int32`, After: `Int64` +- `np.arange(10.0)` - Unchanged: `Float64` +- Integer arithmetic now performed in target dtype (matches NumPy's template approach) +- Inlined type-specific loops matching NumPy's `arraytypes.c.src` implementation + +### NPTypeHierarchy + +New `NPTypeHierarchy.cs` (294 lines) encoding NumPy's exact type tree structure from `multiarraymodule.c`: + +- Bool is NOT under Number (NumPy 2.x critical behavior) +- `NPTypeHierarchy.IsSubType(Bool, Number)` returns `false` +- `issubdtype(int32, int64)` returns `false` (concrete types are siblings) +- `isdtype(bool, 'numeric')` returns `false` (bool excluded from numeric) + +### New Type Introspection APIs (12) + +- `np.can_cast(from, to, casting)` - Full NumPy-compatible type casting checks with 'no', 'equiv', 'safe', 'same_kind', 'unsafe' modes +- `np.promote_types(type1, type2)` - Type promotion following NumPy rules +- `np.result_type(*args)` - Result type inference for arrays and dtypes +- `np.min_scalar_type(value)` - Minimum scalar type for a value +- `np.common_type(*arrays)` - Common type for multiple arrays +- `np.issubdtype(arg1, arg2)` - Type hierarchy checking +- `np.finfo(dtype)` - Machine limits for floating-point types (eps, min, max, resolution) +- `np.iinfo(dtype)` - Machine limits for integer types (min, max, bits) +- `np.isreal(x)` - Check if array has no imaginary part +- `np.iscomplex(x)` - Check if array has imaginary part +- `np.isrealobj(x)` - Check if object is real type +- `np.iscomplexobj(x)` - Check if object is complex type + +### C#-Friendly Overloads + +- `iinfo()`, `finfo()` - Generic overloads +- `can_cast()` - Generic type checking +- `promote_types()` - Generic promotion +- NDArray and string dtype overloads for all functions + +### can_cast Refactoring + +Replaced 80+ lines of switch cases with single-line derivation: +```csharp +CanCastSafe(A, B) = (A == B) || (_FindCommonType_Array(A, B) == B) +``` +Verified against NumPy for all 121 type pairs (11x11 matrix). + + + +## Container Protocol + +New `NDArray.Container.cs` implementing Python's container protocol for NumPy compatibility. + +### Implemented Methods + +- `__contains__` / `Contains()` - Membership testing via element-wise comparison +- `__hash__` / `GetHashCode()` - Throws `NotSupportedException` (NDArray is mutable/unhashable) +- `__len__` - Returns first dimension length, throws `TypeError` for 0-d scalars +- `__iter__` / `GetEnumerator()` - NumPy-compatible iteration over first axis +- `__getitem__` - Indexing with int/long/string slice notation +- `__setitem__` - Assignment with int/long/string slice notation + +### Iteration Behavior (BREAKING) + +- **0-D arrays (scalars)**: Throws `TypeError` (not iterable) +- **1-D arrays**: Yields scalar elements +- **N-D arrays (N > 1)**: Yields (N-1)-D NDArray slices along first axis + +This matches NumPy: +```python +>>> for x in np.array([[1,2],[3,4]]): print(x) +[1 2] +[3 4] +``` + +### New Exception + +- `TypeError.cs` - For NumPy-compatible error messages + + + +## New APIs + +### Comparison Functions (6 new) + +- `np.equal(x1, x2)` - Element-wise equality (wraps `==`) +- `np.not_equal(x1, x2)` - Element-wise inequality (wraps `!=`) +- `np.less(x1, x2)` - Element-wise less than (wraps `<`) +- `np.greater(x1, x2)` - Element-wise greater than (wraps `>`) +- `np.less_equal(x1, x2)` - Element-wise less or equal (wraps `<=`) +- `np.greater_equal(x1, x2)` - Element-wise greater or equal (wraps `>=`) + +### Logical Functions (4 new) + +- `np.logical_and(x1, x2)` - Element-wise logical AND +- `np.logical_or(x1, x2)` - Element-wise logical OR +- `np.logical_not(x)` - Element-wise logical NOT +- `np.logical_xor(x1, x2)` - Element-wise logical XOR + +### NDArray Methods + +**`NDArray.tolist()`** - Convert NDArray to nested lists (NumPy parity): +```csharp +var arr = np.array(new int[,] {{1,2}, {3,4}}); +var list = arr.tolist(); // List containing nested lists +``` + +**`NDArray.item(*args)`** - Copy element to standard scalar: +- `item()` - Extract scalar from size-1 arrays +- `item(index)` - Flat indexing with negative index support +- `item(i, j)` / `item(i, j, k)` - Multi-dimensional indexing +- `item()` - Type-converting variant +- `np.asscalar()` marked as `[Obsolete]` (removed in NumPy 2.0) + +### Operator Files + +- `NDArray.BitwiseNot.cs` - `~` operator implementation +- `NDArray.XOR.cs` - `^` operator with object pattern + +### `np.frombuffer()` Complete Rewrite + +**NumPy-compatible signature:** +- `np.frombuffer(buffer, dtype=float64, count=-1, offset=0)` + +**Features:** +- `count` parameter - Number of items to read (-1 = all available) +- `offset` parameter - Byte offset into buffer +- Big-endian support via dtype strings (`">u4"`, `">i4"`, `"` overload - Uses built-in Offset/Count +- `Memory` overload - View if array-backed, otherwise copies +- `IntPtr` + dispose overload - Native interop with optional ownership +- `void*` overload - Unsafe pointer convenience +- `frombuffer(TSource[], dtype)` - Reinterpret typed arrays +- View semantics - Pinned buffer, modifications affect original + +### Scalar Array Creation + +- `np.array(5)` now correctly creates 0D arrays (matching NumPy) +- Previously created 1D single-element arrays + +### keepdims Parameter + +- `np.argmax(axis, keepdims)` - Added keepdims parameter +- `np.argmin(axis, keepdims)` - Added keepdims parameter + +### Parameter Rename + +- `outType` renamed to `dtype` in 19 np.*.cs files to match NumPy + + + +## Changes and Fixes + +- **`np.arange(10, 0, -2)`**: Before returned `[9, 7, 5, 3, 1]`, now correctly returns `[10, 8, 6, 4, 2]` +- **`np.arange(0, 5, 0.5, int32)`**: Before returned `[0,0,1,1,2,2,3,3,4,4]`, now correctly returns `[0,0,0,0,0,0,0,0,0,0]` (NumPy behavior) +- **`np.any(0D_array, axis=0)`**: Before threw `ArgumentException`, now returns 0D bool scalar +- **`np.all(0D_array, axis=-1)`**: Before threw `ArgumentException`, now returns 0D bool scalar +- **`Contains([1,2], array([1,2,3]))`**: Before returned `False`, now throws `IncorrectShapeException` (matches NumPy) +- **`np.shuffle` axis parameter**: Removed non-existent `axis` param, now matches NumPy legacy API +- **`np.random.standard_normal`**: Fixed typo (`stardard_normal` → `standard_normal`) +- **Scalar broadcast assignment**: Fixed cross-dtype conversion failure + - Root cause: `AsOrMakeGeneric()` called `new NDArray(astype(...))` which triggered implicit scalar → size constructor + - Fix: Use `.Storage` to pass storage directly, avoiding implicit conversion +- **Fancy indexing dtypes**: Now supports all integer dtypes (Int16, Int32, Int64), not just Int32 + - Added `NormalizeIndexArray()` helper that keeps Int32/Int64 as-is, converts smaller types to Int64 + - Throws `IndexOutOfRangeException` for non-integer types (float, decimal) +- NDArray.ToString() now formats 100% identical to numpy. +- **`np.mean([])`**: Returns `NaN` (was throwing or returning 0) +- **`np.mean(zeros((0,3)), axis=0)`**: Returns `[NaN, NaN, NaN]` +- **`np.mean(zeros((0,3)), axis=1)`**: Returns empty array `[]` +- **`np.std/var` single element**: Returns `NaN` with `ddof >= size` +- **Empty comparison**: All 6 comparison operators now return empty boolean arrays (was returning scalar) +- **`np.unique` NaN sorting**: NaN now sorts to end (matches NumPy: `[-inf, 1, 2, inf, nan]`) +- **`ArgMax/ArgMin` NaN**: First NaN always wins (NaN takes precedence over any value) +- **Single-element axis reduction**: Changed `Storage.Alias()` and `squeeze_fast()` to return copies (was sharing memory) +- **Clip mixed-dtype**: Fixed bug where int32 min/max arrays were read as int64 +- **`np.invert(bool)`**: Now uses logical NOT (`!x`) instead of bitwise NOT (`~x`) +- **`np.square(int)`**: Preserves integer dtype instead of promoting to double +- **`np.negate(bool)`**: Removed buggy linear-indexing path, now routes through `ExecuteUnaryOp` +- Fixed ATan2 non-contiguous array handling by adding `np.broadcast_arrays()` and `.copy()` materialization +- Fixed ATan2 wrong pointer type (byte*) for x operand in all non-byte cases +- **finfo**: Use `MathF.BitIncrement` for float eps (was using `Math.BitIncrement` which only works on double) +- **issctype**: Properly reject string type (was returning true for `typeof(string)`) +- **`NDArray.unique()`**: Fixed for long indexing support +- **`np.repeat`**: Fixed dtype handling and long count support +- **`np.random.choice`**: Fixed for long population sizes +- **`np.argmax/argmin` IL fix**: Removed `Conv_I4` instruction that truncated long indices to int32 +- **ILKernel loop counters**: Fixed numerous int32 overflow issues +- **`TransformOffset` calculations**: Fixed for >2GB arrays +- **SIMD helper functions**: Fixed for long indexing +- **AVX2 gather**: Added stride check (falls back to scalar for stride > int.MaxValue) +- Parameter names now match NumPy (`size`, `a`, `b`, `p`, `d0`) +- `np.random()` added as alias for uniform distribution +- `np.shuffle` removed non-existent axis parameter +- ValueType to Object Migration + - All scalar return types migrated from `ValueType` to `object` + - `NPTypeCode.GetDefaultValue()` now returns `object` + - All operators migrated to NumPy-aligned object pattern + - NDArray null checks converted from `== null` to `is null` pattern +- Operator Overload Cleanup + - `NDArray.Primitive.cs`: 159 → 42 lines (74% reduction) + - ~150 explicit scalar overloads → ~40 object-based overloads + - Added missing `implicit operator NDArray(byte)` + - Changed `ushort` from explicit to implicit +- Implicit Scalar Conversion + - `(int)ndarray_float64` now works via `Converts.ChangeType` + - `scalar → NDArray`: implicit (safe, creates 0-d array) + - `NDArray → scalar`: explicit (requires 0-d, throws `IncorrectShapeException`) + - Matches NumPy's `int(arr)`, `float(arr)`, `bool(arr)` pattern +- All `== null` changed to `is null` (because `==` now returns `NDArray` as does numpy) +- All `!= null` changed to `is not null` +- Type System Consolidation + - `can_cast` derived from promotion tables (replaced 80+ lines of switch cases) + - Single source of truth: `NPTypeHierarchy` + - Removed duplicate `TypeKind` enum and category helper methods + +## Performance Improvements + +### SIMD NaN Statistics + +New `ILKernelGenerator.Reduction.NaN.cs` (1,097 lines) providing SIMD optimization for: + +- `np.nansum` - Sum ignoring NaN +- `np.nanprod` - Product ignoring NaN +- `np.nanmin` - Minimum ignoring NaN +- `np.nanmax` - Maximum ignoring NaN +- `np.nanmean` - Mean ignoring NaN +- `np.nanvar` - Variance ignoring NaN +- `np.nanstd` - Standard deviation ignoring NaN + +SIMD Algorithm (NaN masking via self-comparison): +``` +nanMask = Equals(vec, vec) // True for non-NaN +cleaned = BitwiseAnd(vec, nanMask) // Zero out NaN values +``` + +### SIMD Helper Functions (IKernelProvider) + +- `AllSimdHelper()` - SIMD-accelerated boolean all() with early-exit +- `AnySimdHelper()` - SIMD-accelerated boolean any() with early-exit +- `ArgMaxSimdHelper()` - Two-pass SIMD: find max value, then find index +- `ArgMinSimdHelper()` - Two-pass SIMD: find min value, then find index +- `NonZeroSimdHelper()` - Collects indices where elements != 0 +- `CountTrueSimdHelper()` - Counts true values in bool array +- `CopyMaskedElementsHelper()` - Copies elements where mask is true +- `ConvertFlatIndicesToCoordinates()` - Converts flat indices to arrays + +### np.arange() Optimization + +- Inlined type-specific loops (no delegate overhead per element) +- Direct pointer casts: `addr[i] = (int)(start + i * step)` +- Matches NumPy's `arraytypes.c.src` fill pattern + +### MatMul Long Indexing + +- SIMD MatMul updated for `long` indices +- V128/V256/V512 support preserved +- Matrices >2GB now supported + +### Code Reduction + +- `Default.Clip.cs`: 914 → 240 lines (76% reduction) +- `Default.MatMul.2D2D.cs`: 19,862 → 284 lines (98.6% reduction) + + + +## Test Improvements + +### New Test Infrastructure + +- `[LargeMemoryTest]` attribute - Inherits from OpenBugs for CI exclusion +- `TestMemoryTracker` - Diagnose CI OOM failures +- TUnit category exclusion - Proper CI filtering with `--treenode-filter` + +### New Test Files (30+) + +**Type API Tests:** +- `np.can_cast.BattleTest.cs` +- `np.promote_types.BattleTest.cs` +- `np.result_type.BattleTest.cs` +- `np.min_scalar_type.BattleTest.cs` +- `np.common_type.BattleTest.cs` +- `np.issubdtype.BattleTest.cs` +- `np.finfo.BattleTest.cs` +- `np.iinfo.BattleTest.cs` +- `np.isreal_iscomplex.BattleTest.cs` +- `np.type_checks.BattleTest.cs` +- `np.typing.Test.cs` +- `NPTypeHierarchy.BattleTest.cs` (74 tests) + +**Long Indexing Tests:** +- `LongIndexingSmokeTest.cs` - 96 np.* functions with 1M elements +- `LongIndexingBroadcastTest.cs` - 2.36 billion element iterations +- `LongIndexingMasterTest.cs` - Full 2.4GB array allocations +- `ArgsortInt64Tests.cs` +- `HashsetLongIndexingTests.cs` +- `MatMulInt64Tests.cs` +- `NonzeroInt64Tests.cs` + +**Container Protocol Tests:** +- `ContainerProtocolTests.cs` - 69 basic tests +- `ContainerProtocolBattleTests.cs` - Round 1 battle tests +- `ContainerProtocolBattleTests2.cs` - 51 tests (round 2) +- `ContainsNumPyAlignmentTests.cs` + +**Comprehensive Tests:** +- `ArgMaxArgMinComprehensiveTests.cs` - 480 lines covering all dtypes, shapes, axes +- `VarStdComprehensiveTests.cs` - 462 lines covering ddof, empty arrays, edge cases +- `CumSumComprehensiveTests.cs` - 381 lines covering accumulation, overflow, dtypes +- `np_nonzero_strided_tests.cs` - 221 lines for strided/transposed arrays +- `NonContiguousTests.cs` - 35+ tests for strided/broadcast arrays +- `DtypeCoverageTests.cs` - 26 parameterized tests for all 12 dtypes +- `np.comparison.Test.cs` - Comparison function tests + +**Array Creation Tests:** +- `np.arange.BattleTests.cs` (50+ cases) +- `np.array.BattleTests.cs` +- `np.ToString.BattleTests.cs` + +**Other Tests:** +- `TolistTests.cs` +- `ViewTests.cs` + +### Test Counts + +- Type introspection battle tests: 200+ +- Container protocol tests: 120 (69 + 51) +- np.arange battle tests: 50+ +- Type hierarchy tests: 74 +- Contains battle tests: 50 +- Long indexing smoke tests: 96 functions +- Linear algebra tests: 389 (dot: 195, matmul: 106, outer: 88) +- Fancy indexing tests: 20 +- Scalar broadcast tests: 13 +- **Total new battle tests: 600+** +- NumPy 2.x Int64 alignment: 71 tests fixed +- OpenBugs now passing: 74 tests enabled +- **Total fixes: 145** +- 5,020 tests in CI (+74 tests from fixed OpenBugs) + +## Platform Limitations (Cannot Fix) + +These are .NET platform limitations, not NumSharp bugs: + +- `Span` limited to `int.MaxValue` elements by .NET runtime. We introduced UnmanagedSpan that has identical API to Span with long support. +- `List.Count` returns `int` (use `LongCount()` extension) but still the internal array can't exceed int.MaxValue. +- `Hashset.Count` returns `int` (NumSharp adds `LongCount` property) +- .NET managed arrays limited to `int.MaxValue` elements +- .NET string length limited to `int.MaxValue` characters diff --git a/docs/releases/RELEASE_0.51.0-prerelease.md b/docs/releases/RELEASE_0.51.0-prerelease.md new file mode 100644 index 000000000..3d862bec8 --- /dev/null +++ b/docs/releases/RELEASE_0.51.0-prerelease.md @@ -0,0 +1,228 @@ +# Release Notes + +## TL;DR + +This release adds full NumPy-parity support for **three new dtypes** — `SByte` (int8), `Half` (float16), and `Complex` (complex128) — across every `np.*` API, operator, IL kernel, and reduction. A new **`DateTime64` helper type** closes a 64-case conversion gap vs NumPy's `datetime64`. The **`np.*` class-level type aliases are now fully aligned with NumPy 2.4.2** (breaking changes: `np.byte = int8`, `np.complex64` throws, `np.uint = uintp`, `np.intp` is platform-detected), and `np.dtype(string)` is rewritten as a `FrozenDictionary` lookup covering every NumPy 2.x type code. Over the course of **55 commits (+30k / −5.0k lines, 165 files)**, **34 NumPy-parity bugs** were fixed, the entire casting subsystem was rewritten for NumPy 2.x wrapping semantics, the bitshift operators `<<` / `>>` were added to `NDArray`, and rejection sites (shift on non-integer dtypes, invalid indexing types, non-safe `repeat` counts, complex→int scalar cast) now throw NumPy-canonical `TypeError` / `IndexError`. Full test suite grew to **~7,000+ tests / 0 failures / 11 skipped** per framework (net8.0 + net10.0), with ~2,400 new test LoC across 23 new test files. Three systematic coverage sweeps (Creation, Arithmetic, Reductions) probed the new dtypes against NumPy 2.4.2 and landed at 100% parity on the functional surface, with 4 well-documented BCL-imposed divergences. + +--- + +## Major Features + +### New dtypes: SByte (int8), Half (float16), Complex (complex128) +Complete first-class support matching NumPy 2.x: +- `NPTypeCode` enum extended (`SByte=5`, `Half=16`, `Complex=128`) with every extension method (`GetGroup`, `GetPriority`, `AsNumpyDtypeName`, `IsFloatingPoint`, `IsSimdCapable`, `GetComputingType`, …). +- Type aliases on `np.*`: `np.int8`, `np.sbyte`, `np.float16`, `np.half`. +- Storage/memory plumbing: `UnmanagedMemoryBlock`, `ArraySlice`, `UnmanagedStorage` (Allocate / FromArray / Scalar / typed Getters + Setters). +- `np.find_common_type` — ~80 new type-promotion entries across both `arr_arr` and `arr_scalar` tables following NEP50. +- NDArray integer/float/complex indexing (`Get*`/`Set*` methods for the three dtypes). +- Full iterator casts added: `NDIterator.Cast.Half.cs`, `NDIterator.Cast.Complex.cs`, `NDIterator.Cast.SByte.cs`. + +### DateTime64 helper type (`src/NumSharp.Core/DateTime64.cs`) +New `readonly struct` modeled on `System.DateTime` but with NumPy `datetime64` semantics: +- Full `long.MinValue..long.MaxValue` tick range (no `DateTimeKind` bits). +- `NaT == long.MinValue` sentinel that propagates through arithmetic and compares like IEEE NaN. +- Implicit widenings from `DateTime` / `DateTimeOffset` / `long`; explicit narrowings with NaT/out-of-range guards. +- Closes **64 datetime-related fuzz diffs** that previously forced `DateTime.MinValue` fallbacks (Groups A + B). +- Bundled with reference `DateTime.cs` / `DateTimeOffset.cs` copies under `src/dotnet/` as source-of-truth. +- `Converts.DateTime64.cs` — NumPy-exact conversion to/from every primitive dtype. +- Quality pass (commit `7b14a41a`) trimmed the surface to helper scope and fixed the `Equals`/`==` contract split (mirrors `double`'s NaN handling so the type can be a `Dictionary` key while `==` follows NumPy). + +### NumPy 2.x type alias alignment (`src/NumSharp.Core/APIs/np.cs`) +Full overhaul of the class-level `Type` aliases on `np` to match NumPy 2.4.2 exactly. + +**Breaking changes:** + +| Alias | Before | After | Reason | +|-------|--------|-------|--------| +| `np.byte` | `byte` (uint8) | `sbyte` (int8) | NumPy C-char convention | +| `np.complex64` | alias → complex128 | throws `NotSupportedException` | no silent widening — user intent preserved | +| `np.csingle` | alias → complex128 | throws `NotSupportedException` | same rationale | +| `np.uint` | `uint64` | `uintp` (pointer-sized) | NumPy 2.x | +| `np.intp` | `nint` | `long` on 64-bit / `int` on 32-bit | `nint` resolves to `NPTypeCode.Empty`, breaking dispatch | +| `np.uintp` | `nuint` | `ulong` on 64-bit / `uint` on 32-bit | same | +| `np.int_` | `long` | `intp` | NumPy 2.x: `int_ == intp` | + +**New aliases:** `np.short`, `np.ushort`, `np.intc`, `np.uintc`, `np.longlong`, `np.ulonglong`, `np.single`, `np.cdouble`, `np.clongdouble`. + +**Platform-detected** (C-long convention: 32-bit MSVC / 64-bit \*nix LP64): `np.@long`, `np.@ulong`. + +### `np.dtype(string)` parser rewrite (`src/NumSharp.Core/Creation/np.dtype.cs`) +Regex-based parser replaced with a `FrozenDictionary` built once at static init. + +**Covers every NumPy 2.x dtype code:** +- Single-char: `?`, `b`/`B`, `h`/`H`, `i`/`I`, `l`/`L`, `q`/`Q`, `p`/`P`, `e`, `f`, `d`, `g`, `D`, `G`. +- Sized forms: `b1`, `i1`/`u1`, `i2`/`u2`, `i4`/`u4`, `i8`/`u8`, `f2`, `f4`, `f8`, `c16`. +- Lowercase names: `bool`, `int8..int64`, `uint8..uint64`, `float16..float64`, `complex`, `complex128`, `half`, `single`, `double`, `byte`, `ubyte`, `short`, `ushort`, `intc`, `uintc`, `int_`, `intp`, `uintp`, `bool_`, `int`, `uint`, `long`, `ulong`, `longlong`, `ulonglong`, `longdouble`, `clongdouble`. +- NumSharp-friendly: `SByte`, `Byte`, `UByte`, `Int16..UInt64`, `Half`, `Single`, `Float`, `Double`, `Complex`, `Bool`, `Boolean`, `boolean`, `Char`, `char`, `decimal`. + +**Unsupported codes throw `NotSupportedException`** with an explanatory message: +- Bytestring (`S`/`a`), Unicode (`U`), datetime (`M`), timedelta (`m`), object (`O`), void (`V`) — NumSharp has no equivalents. +- `complex64` / `F` / `c8` — NumSharp only has complex128; refusing to silently widen preserves user intent. + +**Platform-detection helpers** (`_cLongType`, `_cULongType`, `_intpType`, `_uintpType`) are declared before the dictionary since static initializers run top-down. + +### `np.finfo` + `np.iinfo` extended to new dtypes +- **`np.finfo(Half)`** — IEEE binary16: `bits=16`, `eps=2^-10`, `smallest_subnormal=2^-24`, `maxexp=16`, `minexp=-14`, `precision=3`, `resolution=1e-3`. +- **`np.finfo(Complex)`** — NumPy parity: reports underlying float64 values with `dtype=float64` (`finfo(complex128).dtype == float64`). +- **`np.iinfo(SByte)`** — int8 with signed min/max and `'i'` kind. +- `IsSupportedType` on both extended to accept the new dtypes. + +### Complex-source → non-complex scalar cast = `TypeError` +All explicit `NDArray → scalar` conversions (`(int)arr`, `(double)arr`, etc) now validate via a common `EnsureCastableToScalar(nd, targetType, targetIsComplex)` helper: +- `ndim != 0` → `IncorrectShapeException`. +- Non-complex target + complex source → `TypeError` ("can't convert complex to int/float/…"). + +This matches Python's `int(complex(1, 2))` behavior. NumPy's silent `ComplexWarning` is treated as a hard error since NumSharp has no warning mechanism — users must `np.real(arr)` explicitly to drop imaginary. + +Also added: implicit `sbyte → NDArray`, implicit `Half → NDArray`, explicit `NDArray → sbyte`. + +### NumPy-canonical exception types at rejection sites +| Site | Before | After | NumPy message | +|------|--------|-------|---------------| +| `Default.Shift.ValidateIntegerType` | `NotSupportedException` | `TypeError` | "ufunc 'left_shift' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule 'safe'" | +| `NDArray.Indexing.Selection.{Getter,Setter}` validation | `ArgumentException` | `IndexError` | "only integers, slices (':'), ellipsis ('...'), numpy.newaxis ('None') and integer or boolean arrays are valid indices" | +| `np.repeat` on non-integer repeats | permissive truncation | `TypeError` | "Cannot cast array data from dtype('float16') to dtype('int64') according to the rule 'safe'" | + +**New exception:** `NumSharp.IndexError : NumSharpException` mirroring Python's `IndexError`. + +### Operator overloads +- **`<<` and `>>`** added to `NDArray` (file `NDArray.Shift.cs`). Two overloads per direction (NDArray↔NDArray, NDArray↔object) mirroring `NDArray.OR/AND/XOR.cs`. C# compiler synthesizes `<<=` / `>>=` (reassign, not in-place — locked in by test). + +### NumPy-parity casting overhaul +Entire `Converts.cs` / `Converts.Native.cs` / `Converts.DateTime64.cs` rewritten across Rounds 1-5E: +- Modular wrapping for integer overflow matching NumPy (no more `OverflowException`). +- NaN / Inf → 0 consistently across all float → int targets. +- `Char` (16-bit) follows `uint16` semantics for every source type. +- `IConvertible` constraint removed from generic converter surface (`Converts`) to admit `Half` / `Complex`. +- Six precision-boundary bugs in `double → int` converters fixed (Round 5F). +- `ToUInt32(double)` overflow now returns 0. +- `ToInt64` / `ToTimeSpan` / `ToDateTime` precision fixes at 2^63 boundary. +- `ArraySlice.Allocate` + `np.searchsorted` patched for `Half` / `Complex`. +- `UnmanagedMemoryBlock.Allocate(Type, long, object)` — direct boxing casts (`(Half)fill`, `(Complex)fill`, …) replaced with `Converts.ToXxx(fill)` dispatchers, so cross-type fills (e.g. `fill = 1` on a Half array, `fill = 3.14` on a Complex array) work with full NumPy-parity wrapping. + +### Complex matmul preserves imaginary +`Default.MatMul.2D2D.cs::MatMulMixedType` short-circuits to a dedicated `MatMulComplexAccumulator` when `TResult` is `Complex`. The double-precision accumulator was dropping imaginary parts for Complex-typed result buffers; the new path accumulates in `Complex` across the inner `K` dimension. + +--- + +## Bug fixes (34 closed) + +| ID | Round | Area | Summary | +|----|-------|------|---------| +| B1 | 14 | Reduction | `Half` min/max elementwise returned ±inf — IL `Bgt/Blt` don't work on `Half` | +| B2 | 14 | Reduction | Complex `mean(axis)` returned `Double`, dropping imaginary | +| B3/B38 | 13 | Arithmetic | Complex `1/0` returned `(NaN,NaN)` vs NumPy `(inf,NaN)` — .NET Smith's algorithm | +| B4 | 14 | Reduction | `np.prod(Half/Complex)` threw `NotSupportedException` | +| B5 | 14 | Reduction | `SByte` axis reduction threw (no identity/combiner) | +| B6 | 14 | Reduction | `Half/Complex cumsum(axis)` threw mid-execution | +| B7 | 14 | Reduction | `argmax/argmin(axis)` threw for Half/Complex/SByte | +| B8 | 14 | Reduction | Complex `min/max` elementwise threw | +| B9 | 15 | Manipulation | `np.unique(Complex)` threw — generic `IComparable` constraint | +| B10/B17 | 6 | Arithmetic | Half/Complex `maximum`/`minimum`/`clip` + axis variant | +| B11 | 6 | Unary Math | Half+Complex `log10`/`log2`/`cbrt`/`exp2`/`log1p`/`expm1` missing | +| B12 | 14 | Reduction | Complex `argmax` tiebreak wrong (non-lex compare) | +| B13 | 15 | Reduction | Complex `argmax/argmin` with NaN returned wrong index | +| B14 | 6 | Statistics | Half+Complex `nanmean`/`nanstd`/`nanvar` returned NaN | +| B15 | 14 | Reduction | Complex `nansum` propagated NaN instead of skipping | +| B16 | 14 | Reduction | Half `std/var(axis)` returned `Double` instead of preserving | +| B18 | 7 | Reduction | `cumprod(Complex, axis)` dropped imaginary | +| B19 | 7 | Reduction | `max/min(Complex, axis)` returned all zeros | +| B20 | 7 | Reduction | `std/var(Complex, axis)` computed real-only variance | +| B21 | 9 | Unary Math | Half `log1p/expm1` lost subnormal precision — promote to `double` | +| B22 | 9 | Unary Math | Complex `exp2(±inf+0j)` returned NaN — use `Math.Pow(2,r)` branch | +| B23 | 9 | Reduction | Complex `var/std` single-element axis returned Complex dtype | +| B24 | 9 | Reduction | `var/std` with `ddof > n` returned negative variance — clamp `max(n-ddof, 0)` | +| B25 | 10 | Comparison | Complex ordered compare with NaN returned True — NaN short-circuit | +| B26 | 10 | Unary Math | Complex `sign(inf+0j)` returned `NaN+NaNj` — unit-vector branch | +| B27 | 11 | Creation | `np.eye(N,M,k)` wrong diagonal stride for non-square/k≠0 (all dtypes) | +| B28 | 11 | Creation | `np.asanyarray(NDArray, dtype)` ignored dtype override | +| B29 | 11 | Creation | `np.asarray(NDArray, dtype)` overload missing | +| B30 | 12 | Creation | `np.frombuffer` dtype-string parser incomplete + `i1/b` wrong (uint8 vs int8) | +| B31 | 12 | Creation | `ByteSwapInPlace` missing Half/Complex branches — big-endian reads corrupted | +| B32 | 12 | Creation | `np.eye` didn't validate negative N/M | +| B33 | 13 | Arithmetic | `floor_divide(inf, x)` returned `inf` vs NumPy `NaN` for all float dtypes | +| B35 | 13 | Arithmetic | Integer `power` overflow wrong — routed through `Math.Pow(double)` | +| B36 | 13 | Arithmetic | `np.reciprocal(int)` promoted to float64 instead of C-truncated int | +| B37 | 13 | Arithmetic | `np.floor/ceil/trunc(int)` promoted to float64 instead of no-op | + +Plus the pre-existing fixes landed before the tracked-bug table: +- `np.abs(complex)` now returns `float64` matching NumPy. +- Complex `ArgMax`/`ArgMin`, `IsInf`/`IsNan`/`IsFinite`, Half NaN reductions. +- 1-D `dot` preserves dtype. +- `Half + int16/uint16` promotes to `float32` (was `float16`). +- `float → byte` uses int32 intermediate. +- `UnmanagedMemoryBlock.Allocate` cross-type fills now use `Converts.ToXxx(fill)` — `fill = 1` on a `Half` array no longer throws `InvalidCastException`. +- `np.asanyarray(Half)` / `np.asanyarray(Complex)` — scalar detection now includes `Half` and `System.Numerics.Complex`. +- `Default.MatMul.2D2D` — Complex result type preserves imaginary via dedicated accumulator. + +### Accepted divergences (documented) +1. **Complex `(inf+0j)^(1+1j)`** — BCL `Complex.Pow` via `exp(b*log(a))` fails; would require rewriting `Complex.Pow` manually. +2. **SByte integer `// 0`, `% 0`** — returns garbage via double-cast path; seterr-dependent. +3. **`exp2(complex(inf, inf))`** — .NET `Complex.Pow` BCL quirk in dual-infinity regime. +4. **`frombuffer(">f2"/">c16")`** — byte values correct after swap, but dtype string loses byte-order prefix (NumSharp dtypes carry no byte-order info). + +--- + +## Infrastructure / IL Kernel + +- `ILKernelGenerator` gained Half/Complex/SByte across `.Binary`, `.Unary`, `.Unary.Math`, `.Unary.Decimal`, `.Comparison`, `.Reduction`, `.Reduction.Arg`, `.Reduction.Axis`, `.Reduction.Axis.Simd`, `.Reduction.Axis.VarStd`, `.Masking.NaN`, `.Scan`, `.Scalar`. +- **Six Complex IL helpers inlined** (`IsNaN`, `IsInfinity`, `IsFinite`, `Log2`, `Sign`, `Less/LessEqual/Greater/GreaterEqual`) — eliminates reflection lookup and method-call hops in hot loops. Factored into `EmitComplexComponentPredicate` and `EmitComplexLexCompare`. +- `ComplexExp2Helper` inlined as direct IL emit. +- `ComplexDivideNumPy` helper replaces BCL `Complex.op_Division` (Smith's algorithm) to match NumPy's component-wise IEEE semantics at `z/0`. +- `PowerInteger` fast-path for all 8 integer dtypes (repeated squaring with unchecked multiplication). +- `ReciprocalInteger` fast-path with C-truncated division. +- Sign-of-zero preservation for Half `log1p`/`expm1` (Math.CopySign) and Complex `exp2` pure-real branch. + +--- + +## Tests + +- **14 new test files** under `test/NumSharp.UnitTest/NewDtypes/` covering Basic, Arithmetic, Unary, Comparison, Reduction, Cumulative, EdgeCase, TypePromotion, Round 6/7/8 battletests, and three 100%-coverage sweep files (Creation / Arithmetic / Reductions). +- **9 new test files** for the NumPy 2.x alignment commit (~1,912 LoC): + + | File | LoC | Scope | + |------|-----|-------| + | `NpTypeAliasParityTests` | 174 | Every `np.*` alias vs NumPy 2.4.2 (Windows 64-bit + platform-gated) | + | `np.finfo.NewDtypesTests` | 262 | Half + Complex finfo | + | `np.iinfo.NewDtypesTests` | 95 | SByte iinfo | + | `UnmanagedMemoryBlockAllocateTests` | 226 | Cross-type fill matrix | + | `ComplexToRealTypeErrorTests` | 170 | Complex → int/float scalar cast TypeError | + | `NDArrayScalarCastTests` | 384 | 0-d cast matrix (implicit + explicit, 15 × 15) | + | `Complex64RefusalTests` | 116 | `np.complex64` / `np.csingle` throw | + | `DTypePlatformDivergenceTests` | 166 | `'l'` / `'L'` / `'int'` platform-dependent behavior | + | `DTypeStringParityTests` | 319 | Every dtype string vs NumPy 2.4.2 | + +- **Casting suite** grew by ~4,800 lines: `ConvertsBattleTests.cs` (1,586 LoC), `DtypeConversionMatrixTests.cs` (1,456 LoC), `DtypeConversionParityTests.cs` (526 LoC), `ConvertsDateTimeParityTests.cs` (615 LoC), `ConvertsDateTime64ParityTests.cs` (631 LoC). +- Test count: **~6,400 → 7,000+** / 0 failed / 11 skipped on both net8.0 and net10.0. +- Probe matrices (330 cases Creation, 109 Arithmetic, 80 Reductions) re-run against NumPy 2.4.2 at 100% / 96.3% / 100% post-fix parity. + +--- + +## Breaking changes / behavioral alignment + +- `Convert.ChangeType`-style paths for `decimal` / `float` / `Half` → integer now **wrap modularly** instead of throwing `OverflowException`. +- `ToDecimal(float/double)` for NaN/Inf/out-of-range now returns `0m` (was: throw). +- `np.reciprocal(int)` / `np.floor/ceil/trunc(int)` now **preserve integer dtype** (was: promoted to `float64`). +- `InfoOf.Size` switched from `Marshal.SizeOf()` to `Unsafe.SizeOf()` — `Marshal.SizeOf` rejects `System.DateTime` and other managed-only structs. +- `NPTypeCode` for `typeof(DateTime)` now returns `Empty` instead of accidentally resolving to `Half` (`TypeCode.DateTime (16) == NPTypeCode.Half (16)` collision fixed). +- `Shape.IsWriteable` enforces read-only broadcast views (NumPy-aligned). +- **`np.byte` is now `sbyte` (int8)** — was `byte` (uint8). For .NET-style `uint8`, use `np.uint8` / `np.ubyte`. +- **`np.complex64` / `np.csingle` throw `NotSupportedException`** — previously silently aliased to complex128. Use `np.complex128` / `np.complex_` / `np.cdouble` explicitly. +- **`np.uint` is now `uintp` (pointer-sized)** — was `uint64`. For explicit 64-bit unsigned, use `np.uint64` / `np.ulonglong`. +- **`np.intp` is now platform-detected `long`/`int`** — was `nint`. `nint` has `NPTypeCode.Empty` which broke dispatch through `np.zeros(typeof(nint))`. +- **`np.int_` is now `intp` (pointer-sized)** — was always `long`. Matches NumPy 2.x where `int_ == intp`. +- **Shift ops on non-integer dtypes throw `TypeError`** — was `NotSupportedException`. Message matches NumPy: `"ufunc '...' not supported for the input types, ... safe casting"`. +- **Invalid index types throw `IndexError`** — was `ArgumentException`. New `NumSharp.IndexError` mirrors Python. +- **`np.repeat` on non-integer repeats throws `TypeError`** — was permissive truncation. Matches NumPy 2.4.2 exactly. +- **Explicit cast `NDArray → non-complex scalar` on Complex source throws `TypeError`** — was silent imaginary drop via `Convert.ChangeType`. Use `np.real(arr)` explicitly to drop imaginary. +- **`np.find_common_type` table entries** — all `np.complex64` references replaced with `np.complex128` to avoid relying on the now-throwing alias. No behavioral change for callers (the alias pointed at `Complex` anyway). + +--- + +## Docs + +- `docs/NEW_DTYPES_IMPLEMENTATION.md`, `docs/NEW_DTYPES_HANDOFF.md` — implementation design + handoff notes. +- `docs/plans/LEFTOVER.md`, `docs/plans/LEFTOVER_CONVERTS.md`, `docs/plans/REVIEW_FINDINGS.md` — round-by-round tracking with post-mortem audit. +- `docs/website-src/docs/NDArray.md` (663 LoC) — user-facing NDArray guide. +- `docs/website-src/docs/dtypes.md` (610 LoC) — complete dtype reference (aliases, string forms, type promotion, platform notes). +- `docs/website-src/docs/toc.yml` — NDArray + Dtypes pages added to the navigation. diff --git a/docs/toc.html b/docs/toc.html deleted file mode 100644 index 635ae27e0..000000000 --- a/docs/toc.html +++ /dev/null @@ -1,24 +0,0 @@ - -
-
-
-
- - -
-
-
- -
-
-
\ No newline at end of file diff --git a/docfx_project/.gitignore b/docs/website-src/.gitignore similarity index 100% rename from docfx_project/.gitignore rename to docs/website-src/.gitignore diff --git a/docs/website-src/api/.gitignore b/docs/website-src/api/.gitignore new file mode 100644 index 000000000..85cf0fe3f --- /dev/null +++ b/docs/website-src/api/.gitignore @@ -0,0 +1,7 @@ +############### +# temp file # +############### +# Generated API YAML files (except toc.yml which we customize) +*.yml +!toc.yml +.manifest diff --git a/docs/website-src/api/index.md b/docs/website-src/api/index.md new file mode 100644 index 000000000..f74cca9c7 --- /dev/null +++ b/docs/website-src/api/index.md @@ -0,0 +1,385 @@ +--- +uid: api-index +--- + +# NumSharp API Reference + +NumSharp is a .NET port of Python's NumPy library. This API reference is organized by functionality, matching NumPy's documentation structure. + +--- + +## Core Types + +The essential types for working with NumSharp. + +| Type | Description | +|------|-------------| +| @NumSharp.NDArray | The main n-dimensional array type | +| @NumSharp.np | Static API class (like `import numpy as np` in Python) | +| @NumSharp.Shape | Array dimensions and strides | +| @NumSharp.Slice | Slice specification for array indexing | +| @NumSharp.Generic.NDArray`1 | Generic typed wrapper for type-safe access | + +### Quick Example + +```csharp +using NumSharp; + +// Create arrays +var a = np.array(new[] { 1, 2, 3, 4, 5 }); +var b = np.zeros((3, 4)); +var c = np.arange(10); + +// Operations +var sum = np.sum(a); +var reshaped = a.reshape(5, 1); +var sliced = a["1:4"]; // Elements 1, 2, 3 +``` + +--- + +## Array Creation + +Functions for creating new arrays. + +| Function | Description | +|----------|-------------| +| `np.array(data)` | Create array from existing data | +| `np.zeros(shape)` | Array filled with zeros | +| `np.zeros_like(a)` | Array of zeros with same shape as `a` | +| `np.ones(shape)` | Array filled with ones | +| `np.ones_like(a)` | Array of ones with same shape as `a` | +| `np.empty(shape)` | Uninitialized array | +| `np.full(shape, value)` | Array filled with a constant value | +| `np.eye(N)` | Identity matrix | +| `np.arange(start, stop, step)` | Evenly spaced values within interval | +| `np.linspace(start, stop, num)` | Evenly spaced values (specify count) | +| `np.meshgrid(x, y)` | Coordinate matrices from vectors | +| `np.copy(a)` | Return a copy of the array | +| `np.asarray(a)` | Convert input to array | +| `np.frombuffer(buffer)` | Create array from buffer | + +--- + +## Stacking & Joining + +Functions for combining multiple arrays. + +| Function | Description | +|----------|-------------| +| `np.concatenate(arrays, axis)` | Join arrays along an existing axis | +| `np.stack(arrays, axis)` | Join arrays along a new axis | +| `np.vstack(arrays)` | Stack arrays vertically (row-wise) | +| `np.hstack(arrays)` | Stack arrays horizontally (column-wise) | +| `np.dstack(arrays)` | Stack arrays depth-wise (along 3rd axis) | + +--- + +## Math Operations + +Arithmetic and mathematical functions. + +### Arithmetic Operators + +| Operator | Description | +|----------|-------------| +| `a + b` | Element-wise addition | +| `a - b` | Element-wise subtraction | +| `a * b` | Element-wise multiplication | +| `a / b` | Element-wise division | +| `a % b` | Element-wise modulo | +| `-a` | Element-wise negation | + +### Math Functions + +| Function | Description | +|----------|-------------| +| `np.sum(a, axis)` | Sum of array elements | +| `np.prod(a)` | Product of array elements | +| `np.cumsum(a)` | Cumulative sum | +| `np.sqrt(a)` | Element-wise square root | +| `np.power(a, n)` | Element-wise power | +| `np.abs(a)` | Element-wise absolute value | +| `np.sign(a)` | Element-wise sign | +| `np.floor(a)` | Element-wise floor | +| `np.ceil(a)` | Element-wise ceiling | +| `np.round(a)` | Element-wise rounding | +| `np.clip(a, min, max)` | Clip values to range | +| `np.maximum(a, b)` | Element-wise maximum | +| `np.minimum(a, b)` | Element-wise minimum | + +### Exponentials & Logarithms + +| Function | Description | +|----------|-------------| +| `np.exp(a)` | Element-wise exponential | +| `np.exp2(a)` | Element-wise 2^x | +| `np.expm1(a)` | exp(x) - 1 | +| `np.log(a)` | Natural logarithm | +| `np.log2(a)` | Base-2 logarithm | +| `np.log10(a)` | Base-10 logarithm | +| `np.log1p(a)` | log(1 + x) | + +### Trigonometric Functions + +| Function | Description | +|----------|-------------| +| `np.sin(a)` | Element-wise sine | +| `np.cos(a)` | Element-wise cosine | +| `np.tan(a)` | Element-wise tangent | + +--- + +## Statistics + +Statistical functions. + +| Function | Description | +|----------|-------------| +| `np.mean(a, axis)` | Arithmetic mean | +| `np.std(a, axis)` | Standard deviation | +| `np.var(a, axis)` | Variance | +| `np.amax(a, axis)` | Maximum value | +| `np.amin(a, axis)` | Minimum value | + +--- + +## Sorting & Searching + +Functions for sorting arrays and finding elements. + +| Function | Description | +|----------|-------------| +| `np.argsort(a)` | Indices that would sort an array | +| `np.argmax(a, axis)` | Index of maximum value | +| `np.argmin(a, axis)` | Index of minimum value | +| `np.searchsorted(a, v)` | Find indices for inserting values | +| `np.nonzero(a)` | Indices of non-zero elements | + +--- + +## Linear Algebra + +Matrix and vector operations. + +| Function | Description | +|----------|-------------| +| `np.dot(a, b)` | Dot product / matrix multiplication | +| `np.matmul(a, b)` | Matrix product (@ operator) | +| `np.outer(a, b)` | Outer product of two vectors | + +--- + +## Shape Manipulation + +Functions for changing array shape and dimensions. + +| Function | Description | +|----------|-------------| +| `np.reshape(a, shape)` | Reshape without changing data | +| `a.reshape(shape)` | Instance method for reshape | +| `np.transpose(a)` | Permute array dimensions | +| `a.T` | Transpose property | +| `np.ravel(a)` | Flatten to 1-D array (returns view) | +| `a.flatten()` | Flatten to 1-D array (returns copy) | +| `np.squeeze(a)` | Remove axes of length 1 | +| `np.expand_dims(a, axis)` | Insert a new axis | +| `np.swapaxes(a, ax1, ax2)` | Swap two axes | +| `np.moveaxis(a, src, dst)` | Move axes to new positions | +| `np.rollaxis(a, axis)` | Roll axis backwards | +| `np.atleast_1d(a)` | Convert to at least 1-D | +| `np.atleast_2d(a)` | Convert to at least 2-D | +| `np.atleast_3d(a)` | Convert to at least 3-D | + +--- + +## Indexing & Slicing + +NumSharp supports Python-style array indexing and slicing. + +### Slice Syntax + +```csharp +a[":"] // All elements +a["1:5"] // Elements 1-4 (stop exclusive) +a["::2"] // Every 2nd element +a["-1"] // Last element (reduces dimension) +a["::-1"] // Reversed +a[":, 0"] // All rows, first column +a["..., -1"] // Ellipsis fills dimensions +``` + +### Special Slice Constants + +| Constant | Description | +|----------|-------------| +| `Slice.All` | All elements (`:`) | +| `Slice.Ellipsis` | Fill remaining dimensions (`...`) | +| `Slice.NewAxis` | Insert new dimension | +| `Slice.Index(n)` | Single element selection | + +### Boolean Masking + +```csharp +var a = np.array(new[] { 1, 2, 3, 4, 5 }); +var mask = a > 2; // [false, false, true, true, true] +var filtered = a[mask]; // [3, 4, 5] +``` + +--- + +## Logic Functions + +Boolean operations and comparisons. + +### Comparison Operators + +| Operator | Description | +|----------|-------------| +| `a == b` | Element-wise equality | +| `a != b` | Element-wise inequality | +| `a > b` | Element-wise greater than | +| `a >= b` | Element-wise greater or equal | +| `a < b` | Element-wise less than | +| `a <= b` | Element-wise less or equal | +| `!a` | Element-wise NOT (boolean arrays) | + +### Logic Functions + +| Function | Description | +|----------|-------------| +| `np.all(a, axis)` | Test if all elements are true | +| `np.any(a, axis)` | Test if any element is true | +| `np.array_equal(a, b)` | Test if arrays are equal | +| `np.isscalar(a)` | Test if input is scalar | + +--- + +## Random Sampling + +Random number generation. Access via @NumSharp.NumPyRandom. + +| Function | Description | +|----------|-------------| +| `np.random.rand(d0, d1, ...)` | Random values in [0, 1) | +| `np.random.randn(d0, d1, ...)` | Standard normal distribution | +| `np.random.randint(low, high, size)` | Random integers | +| `np.random.uniform(low, high, size)` | Uniform distribution | +| `np.random.choice(a, size, replace)` | Random sample from array | +| `np.random.shuffle(a)` | Shuffle array in-place | +| `np.random.permutation(a)` | Random permutation | + +### Distributions + +| Function | Description | +|----------|-------------| +| `np.random.beta(a, b, size)` | Beta distribution | +| `np.random.binomial(n, p, size)` | Binomial distribution | +| `np.random.gamma(shape, scale, size)` | Gamma distribution | +| `np.random.poisson(lam, size)` | Poisson distribution | +| `np.random.exponential(scale, size)` | Exponential distribution | +| `np.random.geometric(p, size)` | Geometric distribution | +| `np.random.lognormal(mean, sigma, size)` | Log-normal distribution | +| `np.random.chisquare(df, size)` | Chi-square distribution | +| `np.random.bernoulli(p, size)` | Bernoulli distribution | + +--- + +## Broadcasting + +Functions for array broadcasting. + +| Function | Description | +|----------|-------------| +| `np.broadcast_to(a, shape)` | Broadcast array to new shape | +| `np.broadcast_arrays(a, b, ...)` | Broadcast arrays against each other | + +Broadcasting automatically aligns array shapes for operations: +- Shapes align from the right +- Dimensions must be equal OR one must be 1 +- Dimension of 1 "stretches" to match + +--- + +## File I/O + +Functions for saving and loading arrays. + +| Function | Description | +|----------|-------------| +| `np.save(file, arr)` | Save array to `.npy` file | +| `np.load(file)` | Load `.npy` or `.npz` file | +| `np.fromfile(file, dtype)` | Load array from binary file | +| `arr.tofile(file)` | Write array to binary file | + +--- + +## Unique & Set Operations + +| Function | Description | +|----------|-------------| +| `np.unique(a)` | Find unique elements | +| `np.repeat(a, repeats)` | Repeat elements of array | + +--- + +## Internals & Advanced + +These types are for advanced users extending NumSharp or understanding its internals. + +### Storage & Backends + +| Type | Description | +|------|-------------| +| @NumSharp.Backends.UnmanagedStorage | Raw unmanaged memory management | +| @NumSharp.TensorEngine | Abstract computation backend interface | +| @NumSharp.Backends.DefaultEngine | Pure C# implementation of TensorEngine | + +### Iteration + +| Type | Description | +|------|-------------| +| @NumSharp.NDIterator | Traverses arrays with different memory layouts | +| @NumSharp.MultiIterator | Paired iteration for broadcasting | + +### Memory Management + +| Type | Description | +|------|-------------| +| @NumSharp.Backends.Unmanaged.ArraySlice`1 | Typed memory slice | +| @NumSharp.Backends.Unmanaged.IMemoryBlock | Memory block interface | + +### Utilities + +| Type | Description | +|------|-------------| +| @NumSharp.Utilities.InfoOf`1 | Static type information cache | +| @NumSharp.NPTypeCode | Enum of supported data types | + +--- + +## Supported Data Types + +NumSharp supports 12 numeric data types: + +| NPTypeCode | C# Type | NumPy Equivalent | +|------------|---------|------------------| +| Boolean | `bool` | `np.bool_` | +| Byte | `byte` | `np.uint8` | +| Int16 | `short` | `np.int16` | +| UInt16 | `ushort` | `np.uint16` | +| Int32 | `int` | `np.int32` | +| UInt32 | `uint` | `np.uint32` | +| Int64 | `long` | `np.int64` | +| UInt64 | `ulong` | `np.uint64` | +| Char | `char` | (no equivalent) | +| Single | `float` | `np.float32` | +| Double | `double` | `np.float64` | +| Decimal | `decimal` | (no equivalent) | + +--- + +## See Also + +- [User Documentation](../docs/intro.md) - Tutorials and guides +- [GitHub Repository](https://github.com/SciSharp/NumSharp) - Source code and issues diff --git a/docs/website-src/api/toc.yml b/docs/website-src/api/toc.yml new file mode 100644 index 000000000..8140a26d2 --- /dev/null +++ b/docs/website-src/api/toc.yml @@ -0,0 +1,240 @@ +### YamlMime:TableOfContent +items: +- name: API Reference + href: index.md + +# Core Types - the essentials +- name: Core Types + items: + - uid: NumSharp.NDArray + name: NDArray + - uid: NumSharp.np + name: np (Static API) + - uid: NumSharp.Shape + name: Shape + - uid: NumSharp.Slice + name: Slice + - uid: NumSharp.SliceDef + name: SliceDef + - uid: NumSharp.Generic.NDArray`1 + name: NDArray + +# Random sampling via np.random +- name: Random Sampling + items: + - uid: NumSharp.NumPyRandom + name: NumPyRandom (np.random) + - uid: NumSharp.Randomizer + name: Randomizer + - uid: NumSharp.NativeRandomState + name: NativeRandomState + +# Linear algebra via np.linalg +- name: Linear Algebra + items: + - uid: NumSharp.np.linalg + name: np.linalg + +# Broadcasting +- name: Broadcasting + items: + - uid: NumSharp.np.Broadcast + name: np.Broadcast + - uid: NumSharp.BroadcastInfo + name: BroadcastInfo + - uid: NumSharp.ViewInfo + name: ViewInfo + +# Type Information +- name: Type System + items: + - uid: NumSharp.NPTypeCode + name: NPTypeCode + - uid: NumSharp.NPTypeCodeExtensions + name: NPTypeCodeExtensions + - uid: NumSharp.DType + name: DType + +# File I/O +- name: File I/O + items: + - uid: NumSharp.NpzDictionary + name: NpzDictionary + - uid: NumSharp.NpzDictionary`1 + name: NpzDictionary + +# Iteration +- name: Iterators + items: + - uid: NumSharp.NDIterator + name: NDIterator + - uid: NumSharp.NDIterator`1 + name: NDIterator + - uid: NumSharp.NDIteratorExtensions + name: NDIteratorExtensions + - uid: NumSharp.MultiIterator + name: MultiIterator + - uid: NumSharp.IteratorType + name: IteratorType + - uid: NumSharp.MoveNextReferencedDelegate`1 + name: MoveNextReferencedDelegate + +# Exceptions +- name: Exceptions + items: + - uid: NumSharp.INumSharpException + name: INumSharpException + - uid: NumSharp.NumSharpException + name: NumSharpException + - uid: NumSharp.AxisOutOfRangeException + name: AxisOutOfRangeException + - uid: NumSharp.IncorrectShapeException + name: IncorrectShapeException + - uid: NumSharp.IncorrectSizeException + name: IncorrectSizeException + - uid: NumSharp.IncorrectTypeException + name: IncorrectTypeException + +# Internals section - Storage & Backends +- name: Internals + items: + - name: Backends + items: + - uid: NumSharp.TensorEngine + name: TensorEngine + - uid: NumSharp.Backends.DefaultEngine + name: DefaultEngine + - uid: NumSharp.Backends.UnmanagedStorage + name: UnmanagedStorage + - uid: NumSharp.Backends.BackendFactory + name: BackendFactory + - uid: NumSharp.BackendType + name: BackendType + - uid: NumSharp.StorageType + name: StorageType + - name: Unmanaged Memory + items: + - uid: NumSharp.Backends.Unmanaged.ArraySlice + name: ArraySlice + - uid: NumSharp.Backends.Unmanaged.ArraySlice`1 + name: ArraySlice + - uid: NumSharp.Backends.Unmanaged.IArraySlice + name: IArraySlice + - uid: NumSharp.Backends.Unmanaged.IMemoryBlock + name: IMemoryBlock + - uid: NumSharp.Backends.Unmanaged.IMemoryBlock`1 + name: IMemoryBlock + - uid: NumSharp.Backends.Unmanaged.IUnmanagedMemoryBlock + name: IUnmanagedMemoryBlock + - uid: NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock + name: UnmanagedMemoryBlock + - uid: NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock`1 + name: UnmanagedMemoryBlock + - uid: NumSharp.Backends.Unmanaged.UnmanagedHelper + name: UnmanagedHelper + - name: Memory Pools + items: + - uid: NumSharp.Unmanaged.Memory.ScalarMemoryPool + name: ScalarMemoryPool + - uid: NumSharp.Unmanaged.Memory.StackedMemoryPool + name: StackedMemoryPool + - name: NDArray Internals + items: + - uid: NumSharp.NDArray._Unsafe + name: NDArray._Unsafe + - uid: NumSharp.NDArray._Unsafe._Pinning + name: NDArray._Unsafe._Pinning + - uid: NumSharp.IIndex + name: IIndex + - uid: NumSharp.Kwargs + name: Kwargs + +# Utilities +- name: Utilities + items: + - name: Type Conversion + items: + - uid: NumSharp.Utilities.Converts + name: Converts + - uid: NumSharp.Utilities.Converts`1 + name: Converts + - uid: NumSharp.Utilities.NonGenericConvert + name: NonGenericConvert + - uid: NumSharp.Utilities.TypelessConvert + name: TypelessConvert + - uid: NumSharp.Utilities.TypelessConvertDelegate + name: TypelessConvertDelegate + - uid: NumSharp.Utilities.ArrayConvert + name: ArrayConvert + - name: Type Info + items: + - uid: NumSharp.Utilities.InfoOf`1 + name: InfoOf + - uid: NumSharp.Utilities.NumberInfo + name: NumberInfo + - name: Arrays + items: + - uid: NumSharp.Utilities.Arrays + name: Arrays + - uid: NumSharp.Utilities.ArraysExtensions + name: ArraysExtensions + - name: Coordinate Incrementors + items: + - uid: NumSharp.Utilities.NDCoordinatesIncrementor + name: NDCoordinatesIncrementor + - uid: NumSharp.Utilities.NDCoordinatesIncrementorAutoResetting + name: NDCoordinatesIncrementorAutoResetting + - uid: NumSharp.Utilities.NDCoordinatesAxisIncrementor + name: NDCoordinatesAxisIncrementor + - uid: NumSharp.Utilities.NDCoordinatesLeftToAxisIncrementor + name: NDCoordinatesLeftToAxisIncrementor + - uid: NumSharp.Utilities.NDExtendedCoordinatesIncrementor + name: NDExtendedCoordinatesIncrementor + - uid: NumSharp.Utilities.NDOffsetIncrementor + name: NDOffsetIncrementor + - uid: NumSharp.Utilities.NDOffsetIncrementorAutoresetting + name: NDOffsetIncrementorAutoresetting + - uid: NumSharp.Utilities.ValueCoordinatesIncrementor + name: ValueCoordinatesIncrementor + - uid: NumSharp.Utilities.ValueCoordinatesIncrementor.EndCallbackHandler + name: ValueCoordinatesIncrementor.EndCallbackHandler + - uid: NumSharp.Utilities.ValueCoordinatesIncrementorAutoResetting + name: ValueCoordinatesIncrementorAutoResetting + - uid: NumSharp.Utilities.ValueOffsetIncrementor + name: ValueOffsetIncrementor + - uid: NumSharp.Utilities.ValueOffsetIncrementorAutoresetting + name: ValueOffsetIncrementorAutoresetting + - name: Collections + items: + - uid: NumSharp.Utilities.Hashset`1 + name: Hashset + - uid: NumSharp.Utilities.Hashset`1.Enumerator + name: Hashset.Enumerator + - uid: NumSharp.Utilities.ConcurrentHashset`1 + name: ConcurrentHashset + - name: LINQ Extensions + items: + - uid: NumSharp.Utilities.Linq.IEnumeratorExtensions + name: IEnumeratorExtensions + - uid: NumSharp.Utilities.Linq.IExtremaEnumerable`1 + name: IExtremaEnumerable + - name: Other + items: + - uid: NumSharp.Utilities.SteppingExtension + name: SteppingExtension + - uid: NumSharp.Utilities.py + name: py + +# Extensions +- name: Extensions + items: + - uid: NumSharp.Extensions.LinqExtensions + name: LinqExtensions + +# External Dependencies +- name: External + items: + - uid: DecimalMath.DecimalEx + name: DecimalEx (DecimalMath) + +memberLayout: SamePage diff --git a/docs/website-src/docfx.json b/docs/website-src/docfx.json new file mode 100644 index 000000000..5266ee471 --- /dev/null +++ b/docs/website-src/docfx.json @@ -0,0 +1,61 @@ +{ + "$schema": "https://raw.githubusercontent.com/dotnet/docfx/main/schemas/docfx.schema.json", + "metadata": [ + { + "src": [ + { + "src": "../../src", + "files": ["NumSharp.Core/NumSharp.Core.csproj"] + } + ], + "dest": "api", + "includePrivateMembers": false, + "disableGitFeatures": false, + "disableDefaultFilter": false, + "noRestore": false, + "namespaceLayout": "flattened", + "memberLayout": "samePage", + "enumSortOrder": "declaringOrder", + "allowCompilationErrors": false + } + ], + "build": { + "content": [ + { + "files": ["**/*.{md,yml}"], + "exclude": ["_site/**", "obj/**", "scripts/**", "filterConfig.yml", "templates/**"] + } + ], + "resource": [ + { + "files": ["images/**"] + } + ], + "output": "../website", + "template": ["default", "modern", "templates/numsharp"], + "globalMetadata": { + "_appName": "NumSharp", + "_appTitle": "NumSharp Documentation", + "_appLogoPath": "images/numsharp.icon.svg", + "_appFaviconPath": "images/numsharp.icon128.png", + "_appFooter": "Copyright © 2025 SciSharp STACK. Built with DocFX.", + "_enableSearch": true, + "_enableNewTab": true, + "_disableContribution": false, + "_disableNextArticle": false, + "_lang": "en", + "_gitContribute": { + "repo": "https://github.com/SciSharp/NumSharp", + "branch": "master" + } + }, + "sitemap": { + "baseUrl": "https://scisharp.github.io/NumSharp", + "changefreq": "weekly", + "priority": 0.5 + }, + "xref": [], + "xrefService": ["https://xref.docs.microsoft.com/query?uid={uid}"], + "postProcessors": ["ExtractSearchIndex"] + } +} diff --git a/docs/website-src/docs/NDArray.md b/docs/website-src/docs/NDArray.md new file mode 100644 index 000000000..625562d1b --- /dev/null +++ b/docs/website-src/docs/NDArray.md @@ -0,0 +1,663 @@ +# NumSharp's ndarray is NDArray! + +NumPy's central type is `numpy.ndarray`. NumSharp's is `NDArray`. If you know one, you know the other — same concept, same memory model, same semantics, same operator behavior, ported to .NET idioms. This page is the quick tour: what `NDArray` is, how to make one, how to read and modify it, how it compares to `numpy.ndarray`, and where the two diverge because C# is not Python. + +--- + +## Anatomy + +An `NDArray` is three things glued together: + +``` +NDArray ← user-facing handle (the type you work with) +├── Storage ← UnmanagedStorage: raw pointer to native memory +├── Shape ← dimensions, strides, offset, flags +└── TensorEngine ← dispatches operations (DefaultEngine by default) +``` + +- **Storage** holds the actual bytes in unmanaged memory (not GC-allocated). This beat every managed alternative in benchmarking and is what makes SIMD and zero-copy interop practical. +- **Shape** is a `readonly struct` describing how the 1-D byte block is viewed as N-D. It knows dimensions, strides, offset, and precomputed `ArrayFlags` (contiguous, broadcasted, writeable, owns-data). +- **TensorEngine** is where `+`, `-`, `sum`, `matmul`, etc. actually run. Different engines can plug in (GPU/SIMD/BLAS); the default is pure C# with IL-generated kernels. + +You rarely touch Storage or TensorEngine directly — `NDArray` exposes everything. + +--- + +## Creating an NDArray + +The usual ways, with their `numpy` counterparts: + +```csharp +np.array(new[] {1, 2, 3}); // np.array([1, 2, 3]) +np.array(new int[,] {{1, 2}, {3, 4}}); // np.array([[1, 2], [3, 4]]) + +np.zeros((3, 4)); // np.zeros((3, 4)) +np.ones(5); // np.ones(5) +np.full((2, 2), 7); // np.full((2, 2), 7) +np.full(new Shape(2, 2), 7); // same thing, explicit Shape form +np.empty((3, 3)); // np.empty((3, 3)) +np.eye(4); // np.eye(4) +np.identity(4); // np.identity(4) + +np.arange(10); // np.arange(10) +np.arange(0, 1, 0.1); // np.arange(0, 1, 0.1) +np.linspace(0, 1, 11); // np.linspace(0, 1, 11) + +np.random.rand(3, 4); // np.random.rand(3, 4) +np.random.randn(100); // np.random.randn(100) +``` + +> **Where `(3, 4)` comes from.** NumSharp's `Shape` struct has implicit conversions from `int`, `long`, `int[]`, `long[]`, and value tuples of 2–6 dimensions. So these four calls all produce the same (3, 4) array: +> +> ```csharp +> np.zeros((3, 4)); // tuple → Shape +> np.zeros(new[] {3, 4}); // int[] → Shape +> np.zeros(new Shape(3, 4)); // explicit Shape +> np.zeros(new Shape(new[] {3L, 4L})); +> ``` +> +> A bare `np.zeros(5)` creates a 1-D length-5 array — it hits the `int shape` overload, not a tuple. + +Scalars (0-d arrays) flow in implicitly: + +```csharp +NDArray a = 42; // 0-d int32 +NDArray b = 3.14; // 0-d double +NDArray c = Half.One; // 0-d float16 +NDArray d = NDArray.Scalar(100.123m); // 0-d decimal +NDArray e = NDArray.Scalar(1); // 0-d with explicit dtype +``` + +Implicit scalar → NDArray exists for all 15 dtypes (`bool, sbyte, byte, short, ushort, int, uint, long, ulong, char, Half, float, double, decimal, Complex`). Use `NDArray.Scalar(value)` to force a specific dtype the C# literal wouldn't pick — e.g. `NDArray.Scalar(1)` instead of `NDArray x = 1;` (which would be int32). + +See also: [Dtypes](dtypes.md) for how to pick element types, [Broadcasting](broadcasting.md) for shape rules. + +--- + +## Wrapping Existing Buffers — `np.frombuffer` + +When you already have memory — a `byte[]` read from a file, a network packet, a pointer from a native library, or even a typed `T[]` you want to reinterpret — `np.frombuffer` wraps it as an NDArray **without copying** whenever possible. Same contract as NumPy's `numpy.frombuffer`. + +```csharp +// From a byte[] — creates a view (pins the array) +byte[] buffer = File.ReadAllBytes("sensor_data.bin"); +var readings = np.frombuffer(buffer, typeof(float)); + +// Skip a header +var data = np.frombuffer(buffer, typeof(float), offset: 16); + +// Read only part of the buffer +var subset = np.frombuffer(buffer, typeof(float), count: 1000, offset: 16); + +// Reinterpret a typed array as a different dtype (view) +int[] ints = { 1, 2, 3, 4 }; +var bytes = np.frombuffer(ints, typeof(byte)); // 16 bytes: [1,0,0,0, 2,0,0,0, ...] + +// From .NET buffer types +var fromSegment = np.frombuffer(new ArraySegment(buffer, 0, 128), typeof(int)); +var fromMemory = np.frombuffer((Memory)buffer, typeof(float)); +// ReadOnlySpan always copies (spans can't be pinned) +ReadOnlySpan span = stackalloc byte[16]; +var fromSpan = np.frombuffer(span, typeof(int)); + +// From native memory — NumSharp takes ownership and frees on GC +IntPtr owned = Marshal.AllocHGlobal(1024); +var arr1 = np.frombuffer(owned, 1024, typeof(float), + dispose: () => Marshal.FreeHGlobal(owned)); + +// Or just borrow — caller must keep it alive and free it later +IntPtr borrowed = NativeLib.GetData(out int size); +var arr2 = np.frombuffer(borrowed, size, typeof(float)); +// ... use arr2 ... +NativeLib.FreeData(borrowed); // after arr2 is done + +// Endianness via dtype strings (big-endian triggers a copy) +byte[] networkData = ReceivePacket(); +var be = np.frombuffer(networkData, ">i4"); // big-endian int32 (copy) +var le = np.frombuffer(networkData, "`, array-backed `Memory` | view (array is pinned) | +| `T[]` via `frombuffer(T[], …)` | view (reinterpret bytes) | +| `IntPtr` | view (optionally with `dispose` callback for ownership transfer) | +| `ReadOnlySpan` | copy (spans can't be pinned) | +| `Memory` not backed by an array | copy | +| Big-endian dtype string on a little-endian CPU | copy (must swap bytes) | + +### Key rules (same as NumPy) + +- **`offset` is in bytes, `count` is in elements.** A `float` buffer with `offset: 4, count: 10` reads 40 bytes starting at byte 4. +- **Buffer length (minus offset) must be a multiple of the element size**, or NumSharp throws. +- **Views couple lifetimes.** If you return an NDArray wrapping a local `byte[]`, the array can be GC'd out from under the view. Either `.copy()` before returning, or allocate through NumSharp (`np.zeros`, `np.empty`). +- **Native memory without `dispose` is borrowed** — the caller must keep the memory alive and free it after all viewing NDArrays are gone. + +See the [Buffering & Memory](buffering.md) page for the full story: memory architecture, ownership patterns (ArrayPool, COM, P/Invoke), endianness, and troubleshooting. + +--- + +## Core Properties + +| Property | Type | NumPy equivalent | Description | +|----------|------|------------------|-------------| +| `shape` | `long[]` | `ndarray.shape` | Dimensions | +| `ndim` | `int` | `ndarray.ndim` | Number of dimensions | +| `size` | `long` | `ndarray.size` | Total element count | +| `dtype` | `Type` | `ndarray.dtype` | C# element type | +| `typecode` | `NPTypeCode` | — | Compact enum form of dtype | +| `strides` | `long[]` | `ndarray.strides` | Byte stride per dimension | +| `T` | `NDArray` | `ndarray.T` | Transpose (view) | +| `flat` | `NDArray` | `ndarray.flat` | 1-D iterator view | +| `Shape` | `Shape` | — | Full shape object (dimensions + strides + flags) | +| `@base` | `NDArray?` | `ndarray.base` | Owner array if this is a view, else `null` | + +```csharp +var a = np.arange(12).reshape(3, 4); +a.shape; // [3, 4] +a.ndim; // 2 +a.size; // 12 +a.dtype; // typeof(int) +a.typecode; // NPTypeCode.Int32 +a.T.shape; // [4, 3] +a.@base; // null (arange owns its data) +var b = a["1:, :2"]; +b.@base; // wraps a's Storage (b is a view) +``` + +--- + +## Indexing & Slicing + +Python's slice notation is accepted as a string: + +```csharp +var a = np.arange(20).reshape(4, 5); + +a[0]; // first row — reduces dim, returns (5,) +a[-1]; // last row +a[1, 2]; // single element at row 1, col 2 +a["1:3"]; // rows 1-2 — keeps dim, returns (2, 5) +a["1:3, :2"]; // rows 1-2, first two cols → (2, 2) +a["::2"]; // every other row +a["::-1"]; // reversed first axis +a["..., -1"]; // ellipsis + last column +``` + +Boolean and fancy indexing work like NumPy: + +```csharp +var arr = np.array(new[] {10, 20, 30, 40, 50}); + +var mask = arr > 20; // NDArray +arr[mask]; // [30, 40, 50] + +var idx = np.array(new[] {0, 2, 4}); +arr[idx]; // [10, 30, 50] — fancy indexing +``` + +Assignment follows the same rules: + +```csharp +a[1, 2] = 99; // scalar write +a[0] = np.zeros(5); // row write (assign a full row) +a[a > 10] = -1; // masked write +``` + +> **View / copy summary for indexing:** +> - Plain slices (`a["1:3"]`, `a[0]`, `a[..., -1]`): **writeable view** — shares memory with the parent. +> - Fancy indexing (`a[indexArray]`): **writeable copy** — independent memory (matches NumPy). +> - Boolean masking (`a[mask]`): **read-only copy** — independent memory; mutation via `a[mask] = value` still works as an *assignment* because it goes through the setter, not by writing into the returned array. + +--- + +## Views vs Copies — Most Important Rule + +**Slicing returns a view, not a copy.** The view shares memory with the parent. This matches NumPy and is the source of most "why did my array change?" questions. + +```csharp +var a = np.arange(10); +var v = a["2:5"]; // view — shares memory with a +v[0] = 999; // mutates a[2] as well! +a[2]; // 999 + +var c = a["2:5"].copy(); // explicit copy — independent memory +c[0] = 0; +a[2]; // still 999 +``` + +Detect views with `arr.@base != null`. Force a copy with `.copy()` or `np.copy(arr)`. + +Broadcasted arrays are a special case: they're views with stride=0 dimensions, and they're **read-only** (`Shape.IsWriteable == false`) to prevent cross-row corruption. See [Broadcasting](broadcasting.md#memory-behavior). + +--- + +## Operators + +Every NumPy operator that C# can express is defined on `NDArray` with matching semantics. + +### Arithmetic + +| NumPy | NumSharp | Broadcasts? | +|-------|----------|-------------| +| `a + b` | `a + b` | yes | +| `a - b` | `a - b` | yes | +| `a * b` | `a * b` | yes | +| `a / b` | `a / b` | yes — returns float dtype for int inputs | +| `a % b` | `a % b` | yes — result sign follows divisor (Python/NumPy convention) | +| `-a` | `-a` | — | +| `+a` | `+a` | returns a copy | + +Each takes `NDArray × NDArray`, `NDArray × object`, and `object × NDArray` — so `10 - arr` works just like `arr - 10`. + +### Bitwise & shift + +| NumPy | NumSharp | Notes | +|-------|----------|-------| +| `a & b` | `a & b` | bool arrays: logical AND | +| `a \| b` | `a \| b` | bool arrays: logical OR | +| `a ^ b` | `a ^ b` | — | +| `~a` | `~a` | — | +| `a << b` | `a << b` | integer dtypes only | +| `a >> b` | `a >> b` | integer dtypes only | + +### Comparison + +| NumPy | NumSharp | Returns | +|-------|----------|---------| +| `a == b` | `a == b` | `NDArray` | +| `a != b` | `a != b` | `NDArray` | +| `a < b` | `a < b` | `NDArray` | +| `a <= b` | `a <= b` | `NDArray` | +| `a > b` | `a > b` | `NDArray` | +| `a >= b` | `a >= b` | `NDArray` | + +Comparisons with `NaN` return `False` (IEEE 754), just like NumPy. + +### Logical + +| NumPy | NumSharp | Notes | +|-------|----------|-------| +| `np.logical_not(a)` | `!a` | `NDArray` only | + +### Operators NumPy has that C# doesn't + +C# has no `**`, `//`, `@` operators, and no `__abs__`/`__divmod__` protocol. Use the functions: + +| NumPy | NumSharp | +|-------|----------| +| `a ** b` | `np.power(a, b)` | +| `a // b` | `np.floor_divide(a, b)` | +| `a @ b` | `np.matmul(a, b)` or `np.dot(a, b)` | +| `abs(a)` | `np.abs(a)` | +| `divmod(a, b)` | `(np.floor_divide(a, b), a % b)` | + +### C# shift-operator quirk + +C# requires the declaring type on the left of `<<` / `>>`, so `object << NDArray` is a compile error. Use the named form: + +```csharp +object rhs = 2; +arr << 2; // OK — int RHS +arr << rhs; // OK — object RHS supported +2 << arr; // compile error +np.left_shift(2, arr); // use the function instead +``` + +### Compound assignment + +`+=`, `-=`, `*=`, `/=`, `%=`, `&=`, `|=`, `^=`, `<<=`, `>>=` all work. **But**: C# synthesizes them as `a = a op b` — they produce a new array and reassign the variable. They are **not in-place** like NumPy's compound operators. Other references to the original array do not see the change: + +```csharp +var x = np.array(new[] {1, 2, 3}); +var alias = x; +x += 10; // x → new array [11, 12, 13] +// alias // still [1, 2, 3] — different from NumPy! +``` + +This is a C# language constraint — compound operators on reference types cannot be defined independently of the binary operator — not a NumSharp choice. + +--- + +## Dtype Conversion + +Three ways to change an array's type: + +```csharp +var a = np.array(new[] {1, 2, 3}); + +// astype — allocates a new array (default) or rewrites in place (copy: false) +var b = a.astype(np.float64); +var c = a.astype(NPTypeCode.Int64); + +// explicit cast on 0-d arrays — matches NumPy's int(arr), float(arr), complex(arr) +NDArray scalar = NDArray.Scalar(42); // 0-d +int i = (int)scalar; // 42 +double d = (double)scalar; // 42.0 +Half h = (Half)scalar; // (Half)42 +Complex cx = (Complex)scalar; // 42 + 0i +``` + +Rules (match NumPy 2.x): + +- 0-d required. Casting an N-d array to a scalar throws `ScalarConversionException`. +- Complex → non-complex throws `TypeError` (mirroring Python's `int(1+2j)` error). Use `np.real(arr)` first. +- Numeric → numeric follows NEP 50 promotion: `int32 + float64 → float64`, `int32 * 1.0 → float64`, etc. + +See [Dtypes](dtypes.md) for the full type table and conversion rules. + +--- + +## Scalars (0-d Arrays) + +A 0-d array has no dimensions — `ndim == 0`, `shape == []`, `size == 1`. Create one with `NDArray.Scalar(value)` or implicit scalar conversion: + +```csharp +var s1 = NDArray.Scalar(42); // explicit +NDArray s2 = 42; // implicit (same result) + +s1.ndim; // 0 +s1.size; // 1 +(int)s1; // 42 — explicit cast out +``` + +Integer indexing always reduces one dimension: + +- 1-D `a[i]` → 0-d NDArray (single element, still wrapped as an array — matches NumPy 2.x) +- 2-D `a[i]` → 1-D NDArray (a row view) +- 3-D `a[i]` → 2-D NDArray (a slab view) + +To unwrap a 0-d result to a raw C# scalar, cast: `(int)a[i]` or `a.item(i)`. + +--- + +## Reading & Writing Elements + +Four ways to touch individual elements, picked based on how many indices you have and whether you already know the dtype: + +```csharp +var a = np.arange(12).reshape(3, 4); + +// 1. Indexer — returns NDArray (0-d for a single element) +NDArray elem = a[1, 2]; +int v = (int)elem; // explicit cast to scalar + +// 2. .item() — direct scalar extraction (NumPy parity) +int v2 = a.item(6); // flat index 6 → row 1, col 2 +object box = a.item(6); // untyped form returns object + +// 3. GetValue — N-D coordinates, typed +int v3 = a.GetValue(1, 2); + +// 4. GetAtIndex — flat index, typed, no Shape math (fastest) +int v4 = a.GetAtIndex(6); + +// Writes mirror the reads: +a[1, 2] = 99; // indexer assignment +a.SetValue(99, 1, 2); // N-D coordinates +a.SetAtIndex(99, 6); // flat index +``` + +**Rule of thumb:** use `.item()` when porting NumPy code, `GetAtIndex` in a hot loop, and the indexer (`a[i, j]`) when you want NumPy-like ergonomics and don't mind the 0-d NDArray detour. + +> `.item()` without arguments works on any size-1 array (0-d, 1-element 1-d, 1×1 2-d) and throws `IncorrectSizeException` otherwise — the NumPy 2.x replacement for the removed `np.asscalar()`. + +--- + +## Iterating (foreach) + +`NDArray` implements `IEnumerable`, so `foreach` works — and it iterates along **axis 0**, matching NumPy: + +```csharp +var m = np.arange(6).reshape(2, 3); +foreach (NDArray row in m) +{ + Console.WriteLine(row); // each `row` is shape (3,), a view of m +} +``` + +For a 1-D array, `foreach` yields individual elements (boxed). For higher-D arrays, each iteration yields a view of the subarray at that axis-0 index. + +To iterate all elements flat, use `.flat` or index into `.ravel()`: + +```csharp +foreach (var x in m.flat) { ... } +``` + +--- + +## Common Patterns + +### Flatten to 1-D (view if possible) + +```csharp +a.ravel(); // view if contiguous, copy if not +a.flatten(); // always a copy +``` + +### Reshape + +```csharp +a.reshape(3, 4); // explicit dims +a.reshape(-1); // auto-size one dim → 1-D flatten +a.reshape(-1, 4); // infer first dim, second is 4 +``` + +All three return a view when the source is contiguous and a copy otherwise. + +### Transpose / axis shuffle + +```csharp +a.T; // full transpose (view) +a.transpose(new[] {1, 0, 2}); // permute axes +np.swapaxes(a, 0, 1); +np.moveaxis(a, 0, -1); +``` + +### Copy semantics at a glance + +| Operation | Result | +|-----------|--------| +| `a["1:3"]` | view | +| `a.T` | view | +| `a.reshape(...)` | view if possible, else copy | +| `a.ravel()` | view if contiguous, else copy | +| `a.flatten()` | always copy | +| `a.copy()` | always copy | +| `a + b` | always new array | +| `a[mask]` with bool mask | copy | +| `a[idx]` with int indices | copy | + +--- + +## Generic `NDArray` + +For type-safe element access, use `NDArray`: + +```csharp +NDArray a = np.zeros(10).MakeGeneric(); +double first = a[0]; // T, not NDArray +a[0] = 3.14; +``` + +Three ways to get a typed wrapper: + +| Method | Allocates? | When to use | +|--------|------------|-------------| +| `MakeGeneric()` | never (same storage) | You know the dtype matches | +| `AsGeneric()` | never; throws if dtype mismatch | Defensive typing | +| `AsOrMakeGeneric()` | only if dtype differs (then `astype`) | Accept any dtype, convert if needed | + +`NDArray` wraps the same storage; use the untyped `NDArray` when dtype is dynamic. + +--- + +## Saving, Loading, and Interop + +NumSharp reads and writes NumPy's `.npy` / `.npz` formats and raw binary — files saved in Python open in NumSharp, and vice versa. To wrap an existing in-memory byte buffer (file bytes, a network packet, a native pointer) see [`np.frombuffer`](#wrapping-existing-buffers--npfrombuffer) above. + +```csharp +// .npy round-trip +np.save("arr.npy", arr); +var loaded = np.load("arr.npy"); // also handles .npz archives + +// Raw binary +arr.tofile("data.bin"); +var raw = np.fromfile("data.bin", np.float64); +``` + +Interop with standard .NET arrays: + +```csharp +var arr = np.array(new[,] {{1, 2}, {3, 4}}); + +// To multi-dim array (preserves shape). Note the method name is "Muli", not "Multi" — +// a longstanding API typo preserved for backwards compatibility. +int[,] md = (int[,])arr.ToMuliDimArray(); + +// To jagged array +int[][] jag = (int[][])arr.ToJaggedArray(); + +// From .NET array back (np.array accepts any rank) +NDArray fromMd = np.array(md); +``` + +For unsafe interop with native code, use `arr.Data()` (gets the `ArraySlice` handle) or the underlying `arr.Storage.Address` pointer. Contiguous-only; check `arr.Shape.IsContiguous` first or copy with `arr.copy()`. + +--- + +## Memory Layout + +NumSharp is **C-contiguous only** — row-major storage, like NumPy's default. The `order` parameter on `reshape`, `ravel`, `flatten`, and `copy` is accepted for API compatibility but ignored (there is no F-order path). + +This means: + +- `arr.shape = [3, 4]` → element `[i, j]` is at flat offset `i * 4 + j`. +- `arr.strides` reports byte strides, not element strides. +- For higher dimensions, the last axis varies fastest (element `[i, j, k]` is at `i * stride[0] + j * stride[1] + k * stride[2]` bytes from `Storage.Address`). + +Views can be non-contiguous (sliced, transposed, broadcasted). Use `arr.Shape.IsContiguous` to detect; use `arr.copy()` to materialize contiguous memory when a kernel needs it. + +--- + +## When Two Arrays Are "The Same" + +| Comparison | Returns | Meaning | +|------------|---------|---------| +| `a == b` | `NDArray` | element-wise equality (broadcasts) | +| `np.array_equal(a, b)` | `bool` | same shape AND all elements equal | +| `np.allclose(a, b)` | `bool` | same shape AND all elements within tolerance (good for floats) | +| `ReferenceEquals(a, b)` | `bool` | same C# object (rarely what you want) | +| `a.@base != null` | `bool` | `a` is a view (shares memory with some owner) | + +> Caveat: NumSharp does not expose a direct "do these two arrays share memory?" check from user code. `a.@base` returns a fresh wrapper on every call and the underlying `Storage` is `protected internal`, so strict memory-identity testing is only available inside the assembly. + +--- + +## Troubleshooting + +### "My array changed when I modified a slice!" + +That's views. `a["1:3"]` shares memory with `a`. Force a copy: `a["1:3"].copy()`. + +### "ReadOnlyArrayException writing to my slice" + +You're writing to a broadcasted view (stride=0 dimension). Copy first: `b.copy()[...] = value`. + +### "ScalarConversionException on `(int)arr`" + +The array isn't 0-d. `(int)` casts only work on scalars. Use `arr.GetAtIndex(0)` or index first: `(int)arr[0]`. + +### "10 << arr doesn't compile" + +C# requires the declaring type on the left of shift operators. Use `np.left_shift(10, arr)`. + +### "a += 1 didn't update another reference" + +C# compound assignment reassigns the variable; it doesn't mutate. See [Compound assignment](#compound-assignment) above. For in-place modification, write directly: `a[...] = a + 1`. + +--- + +## API Reference + +### Properties + +| Member | Type | Description | +|--------|------|-------------| +| `shape` | `long[]` | Dimensions | +| `ndim` | `int` | Rank | +| `size` | `long` | Total elements | +| `dtype` | `Type` | Element `Type` | +| `typecode` | `NPTypeCode` | Element type enum | +| `strides` | `long[]` | Byte strides | +| `T` | `NDArray` | Transpose (view) | +| `flat` | `NDArray` | 1-D view | +| `Shape` | `Shape` | Full shape struct | +| `@base` | `NDArray?` | Owning array if view, else `null` | +| `Storage` | `UnmanagedStorage` | Raw memory handle (internal) | +| `TensorEngine` | `TensorEngine` | Operation dispatcher | + +### Instance Methods + +| Method | Description | +|--------|-------------| +| `astype(type, copy)` | Cast to different dtype (copy by default) | +| `copy()` | Deep copy | +| `Clone()` | Same as `copy()` (ICloneable) | +| `reshape(...)` | Reshape (view if possible) | +| `ravel()` | Flatten to 1-D (view if contiguous) | +| `flatten()` | Flatten to 1-D (always copy) | +| `transpose(...)` | Permute axes | +| `view(dtype)` | Reinterpret bytes as a different dtype (no copy) | +| `item()` / `item()` | Extract size-1 array as scalar | +| `item(index)` / `item(index)` | Extract element at flat index as scalar | +| `GetAtIndex(i)` | Read element at flat index (typed, fastest) | +| `SetAtIndex(value, i)` | Write element at flat index | +| `GetValue(indices)` | Read at N-D coordinates | +| `SetValue(value, indices)` | Write at N-D coordinates | +| `MakeGeneric()` | Wrap as `NDArray` (same storage) | +| `AsGeneric()` | Wrap as `NDArray`; throws if dtype mismatch | +| `AsOrMakeGeneric()` | Wrap as `NDArray`; `astype` if dtype differs | +| `Data()` | Get the underlying `ArraySlice` handle | +| `ToMuliDimArray()` | Copy to a rank-N .NET array | +| `ToJaggedArray()` | Copy to a jagged .NET array | +| `tofile(path)` | Write raw bytes to file | + +### Operators + +| Operator | Overloads | +|----------|-----------| +| `+`, `-`, `*`, `/`, `%` | `(NDArray, NDArray)`, `(NDArray, object)`, `(object, NDArray)` | +| unary `-`, unary `+` | `(NDArray)` | +| `&`, `\|`, `^` | `(NDArray, NDArray)`, `(NDArray, object)`, `(object, NDArray)` | +| `~`, `!` | `(NDArray)`, `(NDArray)` | +| `<<`, `>>` | `(NDArray, NDArray)`, `(NDArray, object)` — RHS only | +| `==`, `!=`, `<`, `<=`, `>`, `>=` | `(NDArray, NDArray)`, `(NDArray, object)`, `(object, NDArray)` | + +### Conversions + +| Direction | Kind | Notes | +|-----------|------|-------| +| scalar → `NDArray` | implicit | `bool, sbyte, byte, short, ushort, int, uint, long, ulong, char, Half, float, double, decimal, Complex` | +| `NDArray` → scalar | explicit | same 15 types + `string` — 0-d required; complex → non-complex throws `TypeError` | + +### Persistence & Buffers + +| Call | Format | View / copy | Notes | +|------|--------|-------------|-------| +| `np.save(path, arr)` | `.npy` | — | NumPy-compatible; writes header + data | +| `np.load(path)` | `.npy` / `.npz` | — | Also accepts a `Stream` | +| `arr.tofile(path)` | raw | — | Element bytes only, no header | +| `np.fromfile(path, dtype)` | raw | copy | Pair with `tofile` | +| `np.frombuffer(byte[], …)` | in-memory | view (pins array) | Endian-prefix dtype strings trigger a copy | +| `np.frombuffer(ArraySegment, …)` | in-memory | view | Uses segment's offset | +| `np.frombuffer(Memory, …)` | in-memory | view if array-backed, else copy | | +| `np.frombuffer(ReadOnlySpan, …)` | in-memory | copy | Spans can't be pinned | +| `np.frombuffer(IntPtr, byteLength, …, dispose)` | native | view (optional ownership) | Pass `dispose` to transfer ownership | +| `np.frombuffer(T[], …)` | in-memory | view | Reinterpret typed array as different dtype | + +--- + +See also: [Dtypes](dtypes.md), [Broadcasting](broadcasting.md), [Exceptions](exceptions.md), [NumPy Compliance](compliance.md). diff --git a/docs/website-src/docs/array-api-standard.md b/docs/website-src/docs/array-api-standard.md new file mode 100644 index 000000000..a5e3383ec --- /dev/null +++ b/docs/website-src/docs/array-api-standard.md @@ -0,0 +1,501 @@ +# Python Array API Standard + +If you've ever tried to write code that works with NumPy, PyTorch, JAX, and CuPy, you know the pain. They all do similar things, but the APIs are just different enough that your code breaks when you switch libraries. The **Python Array API Standard** exists to fix this. + +NumSharp is working toward Array API compliance because it means your code can be more portable—not just between Python libraries, but between Python and C#. + +--- + +## What Is the Array API Standard? + +The Array API Standard is a specification developed by the [Consortium for Python Data API Standards](https://data-apis.org/). It defines a common interface for array operations that any library can implement. + +Think of it like USB for arrays. Before USB, every device had its own connector. Now they all use the same port. The Array API does the same thing for array libraries. + +### The Problem It Solves + +By 2020, Python had accumulated a zoo of array libraries: + +- **NumPy** — The original, CPU-only +- **PyTorch** — Deep learning, GPU support +- **TensorFlow** — Deep learning, different API +- **JAX** — Functional, JIT compilation +- **CuPy** — NumPy clone for NVIDIA GPUs +- **Dask** — Distributed/parallel arrays +- **MXNet**, **PaddlePaddle**, and more... + +Each library evolved independently. They all have `reshape()`, but the parameters are slightly different. They all have `sum()`, but the axis handling varies. Code written for NumPy rarely works on PyTorch without modification. + +The Array API Standard says: "Here's exactly what `reshape()` should look like. Here's exactly how `sum()` should behave. Implement these, and code becomes portable." + +### Who's Adopting It? + +As of 2024, these libraries have adopted or are adopting the Array API: + +| Library | Status | +|---------|--------| +| NumPy 2.0+ | Full support in main namespace | +| PyTorch 2.0+ | `torch` namespace is mostly compliant | +| JAX | Compliant (with some extras) | +| CuPy | Compliant | +| Dask | Compliant | +| ndonnx | Compliant | + +NumSharp aims to join this list. + +--- + +## Why Should You Care? + +### For NumPy Users Moving to C# + +If you're porting Python ML code to C#, Array API compliance means fewer surprises. When NumSharp follows the same specification as NumPy 2.x, the behavior matches. + +### For Library Authors + +If you're building a C# library that consumes arrays, coding against the Array API subset means your library works with any compliant array type—not just NumSharp. + +### For Cross-Platform Development + +Write once, run anywhere. The same algorithms can work on NumPy in Python and NumSharp in C#, producing identical results. + +--- + +## The Specification: What's Required? + +The Array API Standard (version 2024.12) specifies: + +- **14 data types** +- **5 constants** +- **133 core functions** +- **7 array attributes** +- **Full set of operators** +- **2 optional extensions** (linear algebra, FFT) + +Let's break these down. + +--- + +## Data Types: 14 Required + +The standard mandates support for exactly these types: + +### Integer Types + +| Type | Bits | Range | C# Equivalent | +|------|------|-------|---------------| +| `int8` | 8 | -128 to 127 | `sbyte` | +| `int16` | 16 | -32,768 to 32,767 | `short` | +| `int32` | 32 | -2B to 2B | `int` | +| `int64` | 64 | -9Q to 9Q | `long` | +| `uint8` | 8 | 0 to 255 | `byte` | +| `uint16` | 16 | 0 to 65,535 | `ushort` | +| `uint32` | 32 | 0 to 4B | `uint` | +| `uint64` | 64 | 0 to 18Q | `ulong` | + +### Floating-Point Types + +| Type | Bits | Precision | C# Equivalent | +|------|------|-----------|---------------| +| `float32` | 32 | ~7 digits | `float` | +| `float64` | 64 | ~16 digits | `double` | + +### Complex Types + +| Type | Bits | Components | C# Equivalent | +|------|------|------------|---------------| +| `complex64` | 64 | Two float32 | Custom struct needed | +| `complex128` | 128 | Two float64 | `System.Numerics.Complex` | + +### Boolean + +| Type | Bits | C# Equivalent | +|------|------|---------------| +| `bool` | 1 | `bool` | + +### NumSharp Status + +We support 12 of 14 types. **Missing:** `complex64` and `complex128`. + +Complex numbers are our biggest gap. C# has `System.Numerics.Complex`, but it's always 128-bit. For `complex64`, we'd need to implement our own struct with two `float` components. + +--- + +## Constants: 5 Required + +| Constant | Value | NumSharp | +|----------|-------|----------| +| `e` | 2.71828... | ✅ | +| `inf` | Positive infinity | ✅ | +| `nan` | Not a Number | ✅ | +| `newaxis` | None (for dimension expansion) | ✅ | +| `pi` | 3.14159... | ✅ | + +Full compliance here. + +--- + +## Array Attributes: 7 Required + +Every array object must have these properties: + +| Attribute | Description | NumSharp | +|-----------|-------------|----------| +| `dtype` | Data type of elements | ✅ | +| `device` | Hardware location (CPU/GPU) | ❌ | +| `mT` | Matrix transpose (last 2 axes) | ❌ | +| `ndim` | Number of dimensions | ✅ | +| `shape` | Tuple of dimension sizes | ✅ | +| `size` | Total number of elements | ✅ | +| `T` | Full transpose | ✅ | + +### What's `device`? + +The `device` attribute tells you where the array lives—CPU, GPU, TPU, etc. For NumSharp (CPU-only), this would always return a CPU device object. We need to implement this for compliance, even though we only support one device. + +### What's `mT`? + +The `mT` property is "matrix transpose"—it only transposes the last two dimensions. This matters for batched matrix operations: + +```python +# x has shape (batch, rows, cols) +x.T # Transposes ALL dimensions → (cols, rows, batch) — usually wrong! +x.mT # Transposes last two only → (batch, cols, rows) — what you want +``` + +NumPy 2.0 added `mT` for Array API compliance. NumSharp needs it too. + +--- + +## Operators: Complete Set Required + +Arrays must support these operators with proper semantics: + +### Arithmetic +`+`, `-`, `*`, `/`, `//` (floor division), `%`, `**` (power), unary `-`, unary `+` + +### Comparison +`<`, `<=`, `>`, `>=`, `==`, `!=` + +### Bitwise +`~` (NOT), `&` (AND), `|` (OR), `^` (XOR), `<<`, `>>` + +### Matrix +`@` (matrix multiplication) + +### In-place +`+=`, `-=`, `*=`, `/=`, `//=`, `%=`, `**=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, `@=` + +NumSharp implements most of these. We're missing the bitwise operators as named functions (though the operators themselves work) and `@` (we have `np.matmul()` instead). + +--- + +## Core Functions: 133 Required + +The specification groups functions into categories. Here's where NumSharp stands: + +### Creation Functions (16) + +These create new arrays from scratch or from existing data. + +| Function | Description | NumSharp | +|----------|-------------|----------| +| `arange` | Evenly spaced values in interval | ✅ | +| `asarray` | Convert to array | ✅ | +| `empty` | Uninitialized array | ✅ | +| `empty_like` | Same shape, uninitialized | ✅ | +| `eye` | Identity matrix | ✅ | +| `from_dlpack` | From DLPack capsule | ❌ | +| `full` | Filled with constant | ✅ | +| `full_like` | Same shape, filled | ✅ | +| `linspace` | Evenly spaced (by count) | ✅ | +| `meshgrid` | Coordinate matrices | ✅ | +| `ones` | Filled with ones | ✅ | +| `ones_like` | Same shape, ones | ✅ | +| `tril` | Lower triangle | ❌ | +| `triu` | Upper triangle | ❌ | +| `zeros` | Filled with zeros | ✅ | +| `zeros_like` | Same shape, zeros | ✅ | + +**Coverage: 81%** — Missing `tril`, `triu`, `from_dlpack` + +### Element-wise Functions (67) + +The largest category. Mathematical operations applied to each element. + +**Arithmetic:** `add`, `subtract`, `multiply`, `divide`, `floor_divide`, `remainder`, `pow`, `negative`, `positive`, `abs`, `sign` + +**Rounding:** `ceil`, `floor`, `trunc`, `round` + +**Exponential/Log:** `exp`, `expm1`, `log`, `log1p`, `log2`, `log10` + +**Trigonometric:** `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`, `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh` + +**Comparison:** `equal`, `not_equal`, `less`, `less_equal`, `greater`, `greater_equal`, `maximum`, `minimum` + +**Logical:** `logical_and`, `logical_or`, `logical_xor`, `logical_not` + +**Bitwise:** `bitwise_and`, `bitwise_or`, `bitwise_xor`, `bitwise_invert`, `bitwise_left_shift`, `bitwise_right_shift` + +**Type checking:** `isfinite`, `isinf`, `isnan` + +**Other:** `sqrt`, `square`, `clip`, `copysign`, `hypot`, `logaddexp`, `nextafter`, `signbit`, `conj`, `imag`, `real` + +**NumSharp Coverage: ~75%** + +We're missing: +- `copysign`, `hypot`, `logaddexp` (math functions) +- `nextafter`, `signbit` (floating-point utilities) +- `conj`, `imag`, `real` (complex number functions—blocked on complex type support) +- Named bitwise functions (we have the operators, not the functions) + +### Statistical Functions (9) + +| Function | Description | NumSharp | +|----------|-------------|----------| +| `max` | Maximum value | ✅ (`amax`) | +| `mean` | Arithmetic mean | ✅ | +| `min` | Minimum value | ✅ (`amin`) | +| `prod` | Product of elements | ✅ | +| `std` | Standard deviation | ✅ | +| `sum` | Sum of elements | ✅ | +| `var` | Variance | ✅ | +| `cumulative_sum` | Cumulative sum | ✅ (`cumsum`) | +| `cumulative_prod` | Cumulative product | ❌ | + +**Coverage: 89%** — Missing `cumulative_prod` + +**Note:** The Array API uses a `correction` parameter for `std`/`var`: +```python +# Array API +std(x, correction=1) # Sample standard deviation + +# NumPy (and NumSharp) +np.std(x, ddof=1) # Same thing, different name +``` + +### Manipulation Functions (14) + +| Function | Description | NumSharp | +|----------|-------------|----------| +| `broadcast_arrays` | Broadcast shapes | ✅ | +| `broadcast_to` | Broadcast to shape | ✅ | +| `concat` | Join along axis | ✅ (`concatenate`) | +| `expand_dims` | Add dimension | ✅ | +| `flip` | Reverse along axis | ✅ | +| `moveaxis` | Move axis position | ✅ | +| `permute_dims` | Permute dimensions | ✅ (`transpose`) | +| `repeat` | Repeat elements | ✅ | +| `reshape` | Change shape | ✅ | +| `roll` | Shift elements | Partial | +| `squeeze` | Remove size-1 dimensions | ✅ | +| `stack` | Join along new axis | ✅ | +| `tile` | Repeat whole array | ❌ | +| `unstack` | Split along axis | ❌ | + +**Coverage: ~79%** — Missing `tile`, `unstack`; `roll` is partial + +### Set Functions (4) + +This is our weakest area. + +| Function | Description | NumSharp | +|----------|-------------|----------| +| `unique_all` | Values + indices + inverse + counts | ❌ | +| `unique_counts` | Values + counts | ❌ | +| `unique_inverse` | Values + inverse indices | ❌ | +| `unique_values` | Just unique values | ✅ (`np.unique`) | + +**Coverage: 25%** + +The Array API split NumPy's `np.unique(return_counts=True, return_inverse=True)` into four focused functions. We only have the basic version. + +### Other Categories + +| Category | Required | NumSharp | Coverage | +|----------|----------|----------|----------| +| Searching | 6 | ~4 | ~67% | +| Sorting | 2 | 2 | 100% | +| Linear Algebra (core) | 4 | 4 | 100% | +| Indexing | 2 | 0 | 0% | +| Data Types | 6 | ~3 | ~50% | +| Utility | 3 | 2 | ~67% | + +--- + +## Type Promotion Rules + +The Array API specifies strict rules for what happens when you combine different types. + +### Same-Kind Promotion + +Within a type category, smaller types promote to larger: + +``` +int8 + int16 → int16 +int16 + int32 → int32 +float32 + float64 → float64 +``` + +### Cross-Kind: Undefined! + +Here's the crucial difference from NumPy 1.x: **mixing integers and floats is undefined** in the Array API. + +```python +# Array API says: DON'T DO THIS +int32_array + float32_array # Undefined behavior! +``` + +NumPy 2.x still allows it (promoting to float), but the Array API deliberately leaves this unspecified so libraries can make their own choices. + +### Scalar Promotion + +When you mix a Python scalar with an array, the scalar is "weak"—it adopts the array's type: + +```python +uint8_array + 2 → uint8_array # Scalar becomes uint8 +float32_array + 1.5 → float32_array # Scalar becomes float32 +``` + +This is consistent with NEP 50 in NumPy 2.x. + +--- + +## Extensions: Optional but Defined + +The Array API defines two optional extensions. If a library implements an extension, it must implement all functions in that extension. + +### Linear Algebra Extension (23 functions) + +Accessible via `linalg` namespace. + +| Function | Description | +|----------|-------------| +| `cholesky` | Cholesky decomposition | +| `cross` | Cross product | +| `det` | Determinant | +| `diagonal` | Extract diagonal | +| `eigh` | Eigenvalues/vectors (Hermitian) | +| `eigvalsh` | Eigenvalues only (Hermitian) | +| `inv` | Matrix inverse | +| `matmul` | Matrix multiplication | +| `matrix_norm` | Matrix norm | +| `matrix_power` | Matrix to integer power | +| `matrix_rank` | Numerical rank | +| `matrix_transpose` | Transpose last 2 dims | +| `outer` | Outer product | +| `pinv` | Pseudo-inverse | +| `qr` | QR decomposition | +| `slogdet` | Sign and log-determinant | +| `solve` | Solve linear system | +| `svd` | Singular value decomposition | +| `svdvals` | Singular values only | +| `tensordot` | Tensor contraction | +| `trace` | Sum of diagonal | +| `vecdot` | Vector dot product | +| `vector_norm` | Vector norm | + +**NumSharp Status:** We have `matmul`, `outer`, `trace`, and basic operations. The decompositions (`qr`, `svd`, `eigh`, `cholesky`, `inv`) are stubs that return null. + +### FFT Extension (14 functions) + +Accessible via `fft` namespace. + +| Function | Description | +|----------|-------------| +| `fft` | 1-D discrete Fourier transform | +| `ifft` | Inverse of fft | +| `fftn` | N-D DFT | +| `ifftn` | Inverse of fftn | +| `rfft` | 1-D DFT for real input | +| `irfft` | Inverse of rfft | +| `rfftn` | N-D DFT for real input | +| `irfftn` | Inverse of rfftn | +| `hfft` | 1-D DFT for Hermitian input | +| `ihfft` | Inverse of hfft | +| `fftfreq` | DFT sample frequencies | +| `rfftfreq` | Sample frequencies for rfft | +| `fftshift` | Shift zero-frequency to center | +| `ifftshift` | Inverse of fftshift | + +**NumSharp Status:** Not implemented. FFT requires complex number support. + +--- + +## What's NOT in the Standard + +The Array API deliberately excludes some things to remain implementable across diverse libraries: + +### Out of Scope + +- **I/O operations** — No `save`, `load`, `fromfile` +- **String dtypes** — No `StringDType` or fixed-width strings +- **Datetime dtypes** — No `datetime64`, `timedelta64` +- **Object dtype** — No arrays of arbitrary Python objects +- **Specific error types** — Error handling is implementation-defined +- **C API** — Only Python-level interface specified +- **Execution semantics** — Eager vs. lazy, parallelization, etc. + +This means NumSharp can have these features (and we do—`np.save`, `np.load` work), they're just outside the Array API specification. + +--- + +## Real-World Use Cases + +The specification documents several motivating use cases: + +### SciPy Without Dependencies + +SciPy's signal processing functions are pure Python but tied to NumPy. With Array API compliance, `scipy.signal.welch(x)` could work on GPU arrays (CuPy), distributed arrays (Dask), or NumSharp arrays—without SciPy depending on any of them. + +### einops Without Backend Code + +The [einops](https://github.com/arogozhnikov/einops) library maintains ~550 lines of glue code to support multiple backends. Array API compliance would eliminate this entirely. + +### JIT Compilation + +Numba and other JIT compilers struggle with NumPy's value-dependent type rules. The Array API's strict type-based promotion makes JIT compilation predictable. + +--- + +## NumSharp's Path to Compliance + +### Current Coverage + +| Category | Functions | NumSharp | % | +|----------|-----------|----------|---| +| Creation | 16 | 13 | 81% | +| Element-wise | 67 | ~50 | 75% | +| Statistical | 9 | 8 | 89% | +| Manipulation | 14 | 11 | 79% | +| Set | 4 | 1 | 25% | +| Searching | 6 | 4 | 67% | +| Sorting | 2 | 2 | 100% | +| Linear Algebra | 4 | 4 | 100% | +| Indexing | 2 | 0 | 0% | +| Data Types | 6 | 3 | 50% | +| Utility | 3 | 2 | 67% | +| **Total Core** | **133** | **~98** | **~74%** | + +### Priority Items + +1. **Complex number types** — Blocks FFT extension and many math functions +2. **`device` and `mT` properties** — Simple to add +3. **Set functions** (`unique_*` family) — Moderate effort +4. **Missing element-wise functions** — Incremental work +5. **Indexing functions** (`take`, `take_along_axis`) — Moderate effort + +### Tracking + +See [Array API Standard Milestone](https://github.com/SciSharp/NumSharp/milestone/6) for detailed issue tracking. + +--- + +## References + +- [Array API Standard Specification](https://data-apis.org/array-api/latest/) — The full specification +- [Type Promotion Rules](https://data-apis.org/array-api/latest/API_specification/type_promotion.html) — How types combine +- [Linear Algebra Extension](https://data-apis.org/array-api/latest/extensions/linear_algebra_functions.html) — All linalg functions +- [FFT Extension](https://data-apis.org/array-api/latest/extensions/fourier_transform_functions.html) — All FFT functions +- [Consortium for Python Data API Standards](https://data-apis.org/) — The organization behind the standard +- [NumPy Array API Support](https://numpy.org/doc/stable/reference/array_api.html) — NumPy's implementation notes diff --git a/docs/website-src/docs/broadcasting.md b/docs/website-src/docs/broadcasting.md new file mode 100644 index 000000000..083ce843c --- /dev/null +++ b/docs/website-src/docs/broadcasting.md @@ -0,0 +1,242 @@ +# Broadcasting + +Broadcasting allows arithmetic operations between arrays of different shapes. When you add a `(3, 4)` matrix to a `(4,)` vector, NumSharp automatically "broadcasts" the vector across each row—no explicit loops or copying required. + +--- + +## How Broadcasting Works + +NumSharp follows NumPy's broadcasting rules exactly: + +1. **Shapes align from the right.** If arrays have different numbers of dimensions, prepend 1s to the shorter shape. + +2. **Dimensions must be equal or 1.** For each dimension, sizes must match OR one must be 1. + +3. **Size-1 dimensions stretch.** A dimension of size 1 expands to match the other array's size in that dimension. + +```csharp +// (3, 4) + (4,) → (3, 4) + (1, 4) → (3, 4) +var matrix = np.ones((3, 4)); +var row = np.array(new[] {1, 2, 3, 4}); +var result = matrix + row; // Shape: (3, 4) +``` + +Broadcasting creates **views, not copies**. The stretched array doesn't allocate new memory—it uses stride tricks to repeat values virtually. + +--- + +## Shape Compatibility + +### Compatible Shapes + +| Shape A | Shape B | Result | Notes | +|---------|---------|--------|-------| +| `(5,)` | `(5,)` | `(5,)` | Same shape | +| `(5,)` | `()` | `(5,)` | Scalar broadcasts to any shape | +| `(3, 4)` | `(4,)` | `(3, 4)` | Row vector broadcasts across rows | +| `(3, 4)` | `(3, 1)` | `(3, 4)` | Column vector broadcasts across columns | +| `(3, 1)` | `(1, 4)` | `(3, 4)` | Both arrays stretch | +| `(2, 3, 4)` | `(3, 4)` | `(2, 3, 4)` | Lower-dimensional array broadcasts | +| `(8, 1, 6, 1)` | `(7, 1, 5)` | `(8, 7, 6, 5)` | Complex case with multiple stretch dimensions | + +### Incompatible Shapes + +| Shape A | Shape B | Error | +|---------|---------|-------| +| `(3,)` | `(4,)` | 3 ≠ 4, neither is 1 | +| `(3, 4)` | `(3,)` | Trailing dimensions 4 ≠ 3 | +| `(2, 3)` | `(3, 2)` | No valid alignment | + +Incompatible shapes throw `IncorrectShapeException`. + +--- + +## Broadcasting Functions + +### `np.broadcast_to(array, shape)` + +Broadcasts an array to a specific shape. Returns a read-only view. + +```csharp +var a = np.array(new[] {1, 2, 3}); +var b = np.broadcast_to(a, (4, 3)); +// b.shape: (4, 3) +// b[0]: [1, 2, 3] +// b[1]: [1, 2, 3] (same data, not copied) +``` + +**Constraints:** The source shape must be unilaterally broadcastable to the target. You can only stretch dimensions that are size 1: + +```csharp +np.broadcast_to(np.ones((2,)), (3, 3)); // Error: can't stretch 2 to 3 +np.broadcast_to(np.ones((1, 3)), (4, 3)); // OK: stretches 1 to 4 +``` + +### `np.broadcast_arrays(array1, array2, ...)` + +Broadcasts multiple arrays against each other, returning views with a common shape. + +```csharp +var a = np.array(new[] {1, 2, 3}); // (3,) +var b = np.array(new[,] {{1}, {2}}); // (2, 1) + +var (a_bc, b_bc) = np.broadcast_arrays(a, b); +// Both now (2, 3) +``` + +Also available as: +```csharp +NDArray[] results = np.broadcast_arrays(arr1, arr2, arr3); +``` + +### Implicit Broadcasting + +All arithmetic operators broadcast automatically: + +```csharp +var a = np.ones((3, 4)); +var b = np.array(new[] {1, 2, 3, 4}); + +a + b; // (3, 4) +a - b; // (3, 4) +a * b; // (3, 4) +a / b; // (3, 4) +``` + +--- + +## Memory Behavior + +Broadcasted arrays are **views** that share memory with the original: + +```csharp +var small = np.array(new[] {1, 2, 3}); // 3 elements +var big = np.broadcast_to(small, (1000000, 3)); // Appears as 3M elements + +// big.size == 3_000_000 +// Actual memory: still just 3 elements +// big.Shape.IsBroadcasted == true +``` + +**Important:** Broadcasted arrays should be treated as read-only. Writing to a broadcasted position affects all positions that share that memory. If you need to modify a broadcasted array, copy it first: + +```csharp +var writable = big.copy(); // Allocates full 3M elements +``` + +--- + +## Implementation Details + +NumSharp implements broadcasting through stride manipulation. When a dimension is broadcast: + +- The **shape** shows the expanded size +- The **stride** for that dimension is set to 0 + +A stride of 0 means the index doesn't advance in memory—the same element is read repeatedly. + +```csharp +var a = np.array(new[] {1, 2, 3}); +var b = np.broadcast_to(a, (4, 3)); + +// b's internal representation: +// Shape: (4, 3) +// Strides: (0, 1) ← stride 0 in first dimension +``` + +This is tracked via `Shape.IsBroadcasted` and `BroadcastInfo`. + +--- + +## Common Patterns + +### Centering Data (subtract mean) + +```csharp +var data = np.random.rand(100, 5); // 100 samples, 5 features +var mean = np.mean(data, axis: 0); // (5,) +var centered = data - mean; // (100, 5) - broadcasts +``` + +### Normalizing (divide by std) + +```csharp +var std = np.std(data, axis: 0); // (5,) +var normalized = centered / std; // (100, 5) +``` + +### Outer Product + +```csharp +var row = np.array(new[] {1, 2, 3}); // (3,) +var col = np.array(new[,] {{10}, {20}}); // (2, 1) +var outer = row * col; // (2, 3) +``` + +### Batch Operations + +```csharp +var batch = np.random.rand(32, 28, 28); // 32 images +var mean_image = np.mean(batch, axis: 0); // (28, 28) +var normalized = batch - mean_image; // (32, 28, 28) +``` + +--- + +## Troubleshooting + +### "shape mismatch: objects cannot be broadcast" + +Shapes don't follow broadcasting rules. Check alignment: + +```csharp +// Wrong +var a = np.ones((3, 4)); +var b = np.ones((3,)); // Trailing dim 4 ≠ 3 +var c = a + b; // Error + +// Fix: reshape to column vector +var c = a + b.reshape(3, 1); // Now (3, 4) + (3, 1) works +``` + +### Unexpected Output Shape + +If you get a larger shape than expected, you may have accidentally broadcast: + +```csharp +var a = np.ones((10, 1)); +var b = np.ones((1, 10)); +var c = a + b; // (10, 10) — both stretched! +``` + +### Row vs Column Vector + +A 1-D array `(n,)` broadcasts as a **row** `(1, n)`, not a column: + +```csharp +var vec = np.array(new[] {1, 2, 3}); // (3,) — not (1, 3) or (3, 1) + +// To broadcast as column: +var col = vec.reshape(3, 1); // (3, 1) +// or +var col = vec[np.newaxis].T; // (3, 1) +``` + +--- + +## API Reference + +| Function | Description | +|----------|-------------| +| `np.broadcast_to(arr, shape)` | Broadcast array to specific shape (returns view) | +| `np.broadcast_arrays(a, b)` | Broadcast two arrays to common shape (returns tuple) | +| `np.broadcast_arrays(params NDArray[])` | Broadcast multiple arrays (returns array) | + +| Property | Description | +|----------|-------------| +| `Shape.IsBroadcasted` | True if shape has broadcast strides (stride 0) | +| `BroadcastInfo` | Internal metadata for broadcast tracking | + +| Exception | When | +|-----------|------| +| `IncorrectShapeException` | Shapes cannot be broadcast together | diff --git a/docs/website-src/docs/buffering.md b/docs/website-src/docs/buffering.md new file mode 100644 index 000000000..0a07d86ed --- /dev/null +++ b/docs/website-src/docs/buffering.md @@ -0,0 +1,621 @@ +# Buffering, Arrays and Unmanaged Memory + +NumSharp stores all array data in unmanaged memory for maximum performance. This design choice—borrowed from NumPy's architecture—enables zero-copy interop with native libraries, efficient memory-mapped file access, and predictable memory layout for SIMD operations. + +This page explains how to create arrays from existing buffers without copying, how to control who owns and frees the memory, and how memory flows through NumSharp. + +--- + +## Why Unmanaged Memory? + +.NET's managed heap is excellent for general-purpose programming, but scientific computing has different requirements: + +**Predictable Layout.** Managed arrays can be moved by the garbage collector at any time. Unmanaged memory stays put, which is essential when passing pointers to native libraries or GPU drivers. + +**Reduced GC Overhead.** Large managed arrays cause GC pressure and can trigger expensive collections. Unmanaged memory avoids this—though NumSharp still informs the GC about allocation sizes so it can schedule collections appropriately. + +**Interop Efficiency.** When calling into native code (BLAS, CUDA, image processing libraries), unmanaged memory can be passed directly without marshaling. + +**Memory Mapping.** Memory-mapped files work naturally with unmanaged memory, enabling datasets larger than RAM. + +The tradeoff is complexity: you need to understand when memory is shared, who owns it, and when it gets freed. + +--- + +## Memory Architecture + +NumSharp uses a layered architecture for memory management. Understanding these layers helps you reason about what happens under the hood. + +``` +User Code + │ + ▼ +┌─────────────────────────────────────────────┐ +│ External APIs (user-facing) │ +│ np.frombuffer(), np.array(), NDArray() │ +└─────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────┐ +│ Internal Infrastructure │ +│ ArraySlice, UnmanagedMemoryBlock, │ +│ UnmanagedStorage │ +└─────────────────────────────────────────────┘ + │ + ▼ + Native Memory (pinned arrays, allocated blocks, external pointers) +``` + +**External APIs** are what you interact with: `np.frombuffer()`, `np.array()`, and the `NDArray` constructors. These APIs hide the complexity of memory management behind sensible defaults. + +**Internal Infrastructure** handles the low-level details: pinning managed arrays so the GC won't move them, tracking ownership so memory gets freed at the right time, and managing the raw pointers. You don't need to interact with these directly—the external APIs handle it for you. + +### GC Pressure Tracking + +Although NumSharp uses unmanaged memory, the .NET garbage collector still needs to know about it. Otherwise, the GC sees only the small managed wrappers (~100 bytes each) and doesn't realize there's megabytes of unmanaged data attached. This can cause memory to grow unbounded before the GC kicks in. + +NumSharp solves this by calling `GC.AddMemoryPressure()` when allocating native memory and `GC.RemoveMemoryPressure()` when freeing it. This applies to arrays created with `np.array()`, `np.zeros()`, `np.empty()`, and similar functions. + +For external memory (via `np.frombuffer()` with a dispose callback), the caller is responsible for pressure tracking since NumSharp doesn't know how the memory was allocated. + +--- + +## Creating Arrays from Buffers + +The most common scenario is interpreting an existing buffer as a NumSharp array. Maybe you've read a binary file, received a network packet, or have data from a native library. You want to work with it as an NDArray without copying gigabytes of data. + +### From byte[] + +`np.frombuffer()` is the primary tool for this. Given a byte array, it interprets the bytes as a typed array: + +```csharp +byte[] buffer = File.ReadAllBytes("sensor_data.bin"); + +// Interpret the bytes as 32-bit floats +var readings = np.frombuffer(buffer, typeof(float)); + +Console.WriteLine($"Read {readings.size} float values"); +Console.WriteLine($"First reading: {readings.GetSingle(0)}"); +Console.WriteLine($"Last reading: {readings.GetSingle(readings.size - 1)}"); +``` + +This creates a **view** of the buffer, not a copy. The `readings` array points directly into `buffer`'s memory. This is fast (no allocation, no copying) but has implications: if you modify `readings`, you're modifying `buffer`, and vice versa. + +Often binary files have a header followed by data. Use the `offset` parameter to skip the header: + +```csharp +// File format: 16-byte header, then float data +var data = np.frombuffer(buffer, typeof(float), offset: 16); +``` + +If you only want part of the data, use `count`: + +```csharp +// Read only the first 1000 floats, starting at byte 16 +var subset = np.frombuffer(buffer, typeof(float), count: 1000, offset: 16); +``` + +The `count` parameter specifies the number of *elements* (floats, in this case), not bytes. If you ask for more elements than are available after the offset, NumSharp throws an exception. + +### From Typed Arrays + +Sometimes you have a .NET array and want to use it with NumSharp. There are two approaches with different tradeoffs. + +**Copying (safe, independent):** + +```csharp +int[] scores = { 85, 92, 78, 95, 88 }; +var arr = np.array(scores); // Copies the data + +scores[0] = 0; // Original changed +Console.WriteLine(arr[0]); // Still 85 - arr has its own copy +``` + +`np.array()` copies by default. This is safe: you can modify the original array or the NDArray independently. But for large arrays, copying is expensive. + +**Viewing (fast, shared memory):** + +```csharp +int[] scores = { 85, 92, 78, 95, 88 }; +var arr = new NDArray(scores); // Creates a view + +scores[0] = 0; // Original changed +Console.WriteLine(arr[0]); // 0 - they share memory! +``` + +The `NDArray` constructor creates a view. This is fast but couples their lifetimes: modifications to one affect the other. + +**Reinterpreting types:** + +A powerful technique is viewing an array as a different type. This lets you inspect the raw bytes of any data: + +```csharp +int[] values = { 1, 2, 3, 4 }; + +// View the same memory as bytes (16 bytes total for 4 ints) +var asBytes = np.frombuffer(values, typeof(byte)); +Console.WriteLine($"First int as bytes: {asBytes[":4"]}"); +// Output: [1, 0, 0, 0] on little-endian systems + +// View as floats (same bits, different interpretation) +var asFloats = np.frombuffer(values, typeof(float)); +``` + +This is useful for binary serialization, network protocols, or understanding how data is represented in memory. + +### From Native Pointers + +When working with native code, you often have a pointer to memory that was allocated outside .NET. NumSharp can wrap this memory without copying. + +The critical question is: **who frees the memory?** + +**View only (caller manages lifetime):** + +```csharp +// Native library allocated this memory +IntPtr nativeBuffer = NativeLib.GetData(out int byteSize); + +// Create a view - NumSharp does NOT own this memory +var arr = np.frombuffer(nativeBuffer, byteSize, typeof(float)); + +// Use the array... +ProcessData(arr); + +// Caller must free when done +NativeLib.FreeData(nativeBuffer); +``` + +This is appropriate when you're borrowing memory temporarily. You must ensure the native buffer outlives the NDArray—if the native code frees the memory while NumSharp is using it, you'll get crashes or corruption. + +**Transfer ownership (NumSharp frees):** + +```csharp +// We allocate native memory +int bytes = 1024 * sizeof(float); +IntPtr ptr = Marshal.AllocHGlobal(bytes); +GC.AddMemoryPressure(bytes); // Tell GC about this allocation + +// Transfer ownership to NumSharp +var arr = np.frombuffer(ptr, bytes, typeof(float), + dispose: () => { + Marshal.FreeHGlobal(ptr); + GC.RemoveMemoryPressure(bytes); + }); + +// When arr is garbage collected, the dispose action runs +``` + +The `dispose` parameter takes an action that NumSharp calls when the array is no longer needed. For large allocations, pair `GC.AddMemoryPressure()` with `GC.RemoveMemoryPressure()` so the GC knows about your memory. Be careful: if you free the memory yourself AND provide a dispose action, you'll double-free. + +### From .NET Buffer Types + +Modern .NET code often uses `ArraySegment`, `Memory`, or `Span` instead of raw arrays. NumSharp supports these too. + +**ArraySegment** is common in network code where you're working with a slice of a larger buffer: + +```csharp +byte[] networkBuffer = new byte[65536]; +int bytesReceived = socket.Receive(networkBuffer); + +// Work with just the received portion +var segment = new ArraySegment(networkBuffer, 0, bytesReceived); +var packet = np.frombuffer(segment, typeof(byte)); +``` + +ArraySegment already carries offset and count, so NumSharp uses them automatically. + +**Memory** is the modern way to represent a contiguous region of memory: + +```csharp +Memory memory = GetDataFromSomewhere(); +var arr = np.frombuffer(memory, typeof(float)); +``` + +If the Memory is backed by an array (the common case), NumSharp creates a view. If it's backed by something else, NumSharp copies. + +**ReadOnlySpan** always requires a copy because spans can't be pinned—they might be stack-allocated: + +```csharp +ReadOnlySpan span = stackalloc byte[16]; +var arr = np.frombuffer(span, typeof(int)); // Must copy +``` + +--- + +## View vs Copy: When Memory is Shared + +Understanding when NumSharp shares memory versus copying is crucial for correctness and performance. + +### The Rule of Thumb + +- **Mutable, pinnable sources → View.** `byte[]`, `T[]`, `ArraySegment`, array-backed `Memory` +- **Immutable or unpinnable sources → Copy.** `ReadOnlySpan`, non-array `Memory`, big-endian conversion + +### Why Views Matter + +Views are fast but create hidden coupling. Consider this bug: + +```csharp +byte[] buffer = new byte[1024]; +var arr = np.frombuffer(buffer, typeof(float)); + +// Later, somewhere else in the code... +Array.Clear(buffer, 0, buffer.Length); + +// arr now contains all zeros! +// If you expected arr to preserve the original data, this is a bug. +``` + +Views also mean modifications propagate both ways: + +```csharp +var buffer = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; +var shorts = np.frombuffer(buffer, typeof(short)); + +// Modify through NumSharp +shorts.SetInt16(9999, 0); + +// buffer changed too +Console.WriteLine(buffer[0]); // 15 (low byte of 9999) +Console.WriteLine(buffer[1]); // 39 (high byte of 9999) +``` + +### When to Force a Copy + +If you need independent data, call `.copy()`: + +```csharp +var buffer = new byte[] { 1, 2, 3, 4 }; +var view = np.frombuffer(buffer, typeof(byte)); +var independent = view.copy(); + +buffer[0] = 99; +Console.WriteLine(view[0]); // 99 - shared +Console.WriteLine(independent[0]); // 1 - independent copy +``` + +### Memory Lifetime + +When you create a view, you're responsible for keeping the source alive: + +```csharp +NDArray GetData() +{ + byte[] localBuffer = new byte[1024]; + FillWithData(localBuffer); + return np.frombuffer(localBuffer, typeof(float)); + // BUG: localBuffer can be GC'd after this returns! +} +``` + +The returned NDArray points into `localBuffer`, but once `GetData()` returns, nothing holds a reference to `localBuffer`. The GC might collect it, and the NDArray becomes a dangling pointer. + +The fix is either to copy: + +```csharp +return np.frombuffer(localBuffer, typeof(float)).copy(); +``` + +Or to let NumSharp own the memory by using a different approach: + +```csharp +var arr = np.zeros(256); // NumSharp owns this memory +FillWithData(arr); +return arr; +``` + +--- + +## Ownership: Who Frees the Memory? + +Memory ownership is the most subtle aspect of NumSharp's memory model. Getting it wrong causes either memory leaks (memory never freed) or crashes (memory freed while still in use). + +### Managed Arrays (byte[], T[]) + +When you view a managed array, NumSharp "pins" it internally. This prevents the GC from moving the array. When the NDArray is garbage collected, NumSharp unpins the array, and normal GC takes over. + +```csharp +var buffer = new byte[1024]; +var arr = np.frombuffer(buffer, typeof(float)); +// buffer is now pinned internally + +arr = null; +GC.Collect(); +// Eventually: buffer is unpinned, can be GC'd normally +``` + +You don't need to do anything special—the .NET garbage collector handles it. But be aware that pinned memory can cause heap fragmentation if you have many long-lived pinned arrays. + +### Native Memory Without Ownership + +When you wrap native memory without a dispose action, NumSharp creates a "borrowed" view: + +```csharp +IntPtr ptr = GetNativePointer(); +var arr = np.frombuffer(ptr, 1024, typeof(float)); +// NumSharp does NOT own this memory +``` + +The NDArray will use this memory, but when the NDArray is garbage collected, nothing happens to the native memory. It's your responsibility to free it at the appropriate time—which must be after all NDArrays viewing it are gone. + +### Native Memory With Ownership Transfer + +The `dispose` parameter lets you transfer ownership to NumSharp: + +```csharp +IntPtr ptr = Marshal.AllocHGlobal(1024); +var arr = np.frombuffer(ptr, 1024, typeof(float), + dispose: () => Marshal.FreeHGlobal(ptr)); +``` + +Now when `arr` is garbage collected, NumSharp calls your dispose action. This happens during finalization, which means: + +1. It's non-deterministic—you don't know exactly when +2. It will eventually happen (unless the process exits first) +3. Don't rely on order between multiple finalizers + +### Common Ownership Patterns + +**ArrayPool integration:** + +```csharp +var rental = ArrayPool.Shared.Rent(4096); +var arr = np.frombuffer(rental, typeof(float), + dispose: () => ArrayPool.Shared.Return(rental)); +// When arr is GC'd, the array returns to the pool +``` + +**P/Invoke with native allocator:** + +```csharp +[DllImport("mylib")] +static extern IntPtr alloc_buffer(int size); + +[DllImport("mylib")] +static extern void free_buffer(IntPtr ptr); + +IntPtr ptr = alloc_buffer(1024); +var arr = np.frombuffer(ptr, 1024, typeof(float), + dispose: () => free_buffer(ptr)); +``` + +**COM memory:** + +```csharp +IntPtr ptr = Marshal.AllocCoTaskMem(1024); +var arr = np.frombuffer(ptr, 1024, typeof(int), + dispose: () => Marshal.FreeCoTaskMem(ptr)); +``` + +--- + +## Endianness + +Binary data from files or networks may be in a different byte order than your CPU expects. x86/x64 processors are little-endian, but network protocols and some file formats use big-endian. + +NumSharp handles this through dtype strings: + +```csharp +byte[] networkData = ReceivePacket(); + +// Big-endian int32 (network byte order) +var values = np.frombuffer(networkData, ">i4"); + +// Little-endian int32 (native on x86/x64) +var values = np.frombuffer(networkData, "` or `!` — Big-endian (most significant byte first) +- `<` — Little-endian (least significant byte first) +- `=` — Native endian (whatever the CPU uses) +- `|` — Not applicable (single-byte types) + +**Important:** Big-endian conversion requires a copy because NumSharp must swap the bytes. Little-endian on a little-endian system creates a view. + +Common dtype strings: + +| String | Type | Bytes | +|--------|------|-------| +| `i1`, `b` | int8 | 1 | +| `u1`, `B` | uint8 | 1 | +| `i2`, `h` | int16 | 2 | +| `u2`, `H` | uint16 | 2 | +| `i4`, `i`, `l` | int32 | 4 | +| `u4`, `I`, `L` | uint32 | 4 | +| `i8`, `q` | int64 | 8 | +| `u8`, `Q` | uint64 | 8 | +| `f4`, `f` | float32 | 4 | +| `f8`, `d` | float64 | 8 | + +--- + +## Common Patterns + +### Reading Binary Files + +```csharp +// Simple case: entire file as one type +byte[] data = File.ReadAllBytes("measurements.bin"); +var readings = np.frombuffer(data, typeof(double)); + +// With header +// File format: 4-byte int (count), then float data +int count = BitConverter.ToInt32(data, 0); +var values = np.frombuffer(data, typeof(float), count: count, offset: 4); +``` + +### Memory-Mapped Large Files + +For files larger than RAM, memory-map them: + +```csharp +using var mmf = MemoryMappedFile.CreateFromFile( + "huge_dataset.bin", FileMode.Open); +using var accessor = mmf.CreateViewAccessor(); + +// Read chunks as needed +byte[] chunk = new byte[1_000_000]; +accessor.ReadArray(offset, chunk, 0, chunk.Length); +var arr = np.frombuffer(chunk, typeof(float)); +``` + +### Network Protocol Parsing + +```csharp +// Packet format: +// - 4 bytes: message type (int32) +// - 4 bytes: payload length (int32) +// - N bytes: payload (float32[]) + +byte[] packet = socket.Receive(); + +int messageType = BitConverter.ToInt32(packet, 0); +int payloadLength = BitConverter.ToInt32(packet, 4); +int floatCount = payloadLength / sizeof(float); + +var payload = np.frombuffer(packet, typeof(float), + count: floatCount, offset: 8); +``` + +### Interop with Native Libraries + +```csharp +[DllImport("imagelib")] +static extern IntPtr process_image( + IntPtr input, int width, int height, out IntPtr output); + +[DllImport("imagelib")] +static extern void free_image(IntPtr ptr); + +// Process an image +var inputArr = np.array(imageBytes).reshape(height, width, 3); +IntPtr outputPtr = process_image( + inputArr.data, width, height, out IntPtr resultPtr); + +// Wrap output with ownership transfer +var result = np.frombuffer(resultPtr, width * height * 3, typeof(byte), + dispose: () => free_image(resultPtr)); +var outputImage = result.reshape(height, width, 3); +``` + +### Sharing Data with GPU Libraries + +```csharp +// Create data on CPU +var cpuData = np.random.rand(1000, 1000).astype(np.float32); + +// Get pointer for GPU transfer +IntPtr dataPtr = cpuData.data; + +// Transfer to GPU (CUDA example) +cudaMemcpy(devicePtr, dataPtr, + cpuData.size * sizeof(float), cudaMemcpyHostToDevice); + +// ... GPU computation ... + +// Transfer back +cudaMemcpy(dataPtr, devicePtr, + cpuData.size * sizeof(float), cudaMemcpyDeviceToHost); +``` + +--- + +## Troubleshooting + +### "buffer size must be a multiple of element size" + +The byte buffer's length (after offset) must be divisible by the element size: + +```csharp +byte[] buf = new byte[7]; +var arr = np.frombuffer(buf, typeof(int)); // Error: 7 not divisible by 4 + +// Fix: use count to read only complete elements +var arr = np.frombuffer(buf, typeof(int), count: 1); // Reads 4 bytes +``` + +### "offset must be non-negative and no greater than buffer length" + +The offset is in bytes and must be within the buffer: + +```csharp +byte[] buf = new byte[100]; +var arr = np.frombuffer(buf, typeof(int), offset: 200); // Error + +// Fix: check your offset calculation +var arr = np.frombuffer(buf, typeof(int), offset: 96); // OK, reads 1 int +``` + +### Access Violation / Segmentation Fault + +Usually means you're accessing freed memory: + +```csharp +NDArray arr; +{ + byte[] localBuffer = new byte[1024]; + arr = np.frombuffer(localBuffer, typeof(float)); +} +// localBuffer may be GC'd here + +arr[0] = 1.0f; // CRASH: accessing freed memory +``` + +Fix: either copy the data or ensure the buffer outlives the NDArray. + +### Memory Leak + +If you transfer ownership but the NDArray never gets garbage collected: + +```csharp +static List cache = new List(); + +void ProcessData() +{ + IntPtr ptr = Marshal.AllocHGlobal(1024); + var arr = np.frombuffer(ptr, 1024, typeof(float), + dispose: () => Marshal.FreeHGlobal(ptr)); + + cache.Add(arr); // arr never gets GC'd! +} +``` + +The dispose action only runs on GC. If you hold references forever, the memory leaks. Clear your caches or use weak references if needed. + +--- + +## API Reference + +### np.frombuffer Overloads + +| Signature | View/Copy | Notes | +|-----------|-----------|-------| +| `frombuffer(byte[], dtype, count, offset)` | View | Pins array | +| `frombuffer(byte[], string dtype, count, offset)` | Copy if big-endian | Handles endianness | +| `frombuffer(ReadOnlySpan, dtype, count, offset)` | Copy | Spans can't be pinned | +| `frombuffer(ArraySegment, dtype, count)` | View | Uses segment's offset | +| `frombuffer(Memory, dtype, count, offset)` | View if array-backed | Fallback to copy | +| `frombuffer(IntPtr, byteLength, dtype, count, offset, dispose)` | View | Optional ownership | +| `frombuffer(TSource[], dtype, count, offset)` | View | Reinterpret typed array | + +### np.array vs NDArray Constructor + +| API | Default Behavior | Use When | +|-----|------------------|----------| +| `np.array(T[])` | Copy | You want independent data | +| `new NDArray(Array)` | View | You want shared memory, better performance | + +--- + +## Summary + +NumSharp's memory system is designed for performance and interoperability. The key concepts are: + +1. **Views share memory** with the source. Fast but coupled. +2. **Copies are independent** but require allocation. +3. **Ownership determines who frees.** Managed arrays are GC'd; native memory needs explicit handling. +4. **The dispose callback** transfers ownership to NumSharp for native memory. +5. **Use `.copy()` when in doubt** to avoid lifetime bugs. + +For most code, `np.frombuffer()` with default settings does the right thing. When you need more control, the parameters are there. diff --git a/docs/website-src/docs/compliance.md b/docs/website-src/docs/compliance.md new file mode 100644 index 000000000..8ddebb0a5 --- /dev/null +++ b/docs/website-src/docs/compliance.md @@ -0,0 +1,350 @@ +# NumPy Compliance & Compatibility + +NumSharp exists for one reason: to let you write NumPy-style code in C#. But "NumPy-style" isn't just about having similar function names—it's about behaving the same way. When you add a scalar to an array, when you slice with negative indices, when you broadcast two arrays together, NumSharp should do exactly what NumPy does. + +This page explains where we are on that journey, what challenges we face, and how you can help. + +--- + +## Why Compatibility Matters + +If you're porting Python ML code to C#, the last thing you want is subtle behavioral differences causing bugs. Consider this Python code: + +```python +import numpy as np +a = np.array([1, 2, 3], dtype=np.uint8) +b = a + 255 +print(b) # [0, 1, 2] - overflow wraps around +``` + +What should NumSharp do here? In NumPy 1.x, this would silently upcast to int16 to avoid overflow. In NumPy 2.x, it wraps with a warning. These differences matter when you're debugging why your neural network produces different results in C#. + +Our goal is **1-to-1 behavioral compatibility with NumPy 2.x** (currently targeting 2.4.2). We also aim to comply with the **Python Array API Standard**, which defines portable array operations across NumPy, PyTorch, JAX, and other libraries. + +--- + +## The Big Picture: Three Compliance Tracks + +We're tracking compliance across three related but distinct standards: + +### 1. NumPy 2.x Compatibility + +NumPy 2.0 (released April 2024) was a major breaking release. It changed how types are promoted, removed deprecated functions, and added new APIs. If you learned NumPy before 2024, some of your intuitions might be wrong now. + +**Tracking:** [NumPy 2.x Compliance Milestone](https://github.com/SciSharp/NumSharp/milestone/9) + +### 2. Array API Standard + +The Python Array API Standard is an industry consortium effort to define a common API that works across array libraries. Write code against the Array API, and it runs on NumPy, PyTorch, JAX, CuPy, or Dask without changes. NumPy adopted it in version 2.0. + +**Deep Dive:** [Array API Standard](array-api-standard.md) — Our dedicated page with full specification details + +**Tracking:** [Array API Standard Milestone](https://github.com/SciSharp/NumSharp/milestone/6) + +### 3. NumPy Enhancement Proposals (NEPs) + +NEPs are the design documents that define NumPy's behavior. When we say "NumPy does X," there's usually a NEP that specifies exactly what X means. We track the NEPs most relevant to NumSharp. + +**Tracking:** [NEP Compliance Milestone](https://github.com/SciSharp/NumSharp/milestone/7) + +--- + +## Type Promotion: The Biggest Change in NumPy 2.0 + +If there's one thing you need to understand about NumPy 2.x compatibility, it's **NEP 50: Promotion Rules for Python Scalars**. + +### The Old Way (NumPy 1.x) + +NumPy 1.x used "value-based" promotion. It would inspect the actual value of a scalar to decide the output type: + +```python +# NumPy 1.x behavior +np.result_type(np.int8, 1) # → int8 (1 fits in int8) +np.result_type(np.int8, 255) # → int16 (255 doesn't fit, upcast!) +``` + +This was convenient—you rarely got overflow errors. But it was also unpredictable. The same code could produce different types depending on the runtime values, making optimization and type inference nearly impossible. + +### The New Way (NumPy 2.x) + +NumPy 2.x uses "weak scalar" promotion. Python scalars defer to the array's dtype: + +```python +# NumPy 2.x behavior +np.uint8(1) + 2 # → uint8(3) +np.uint8(1) + 255 # → uint8(0) with overflow warning! +``` + +The scalar `2` is "weak"—it takes on whatever type the array has. This is more predictable and enables better optimization, but it can cause overflow where NumPy 1.x would have silently upcasted. + +### Where NumSharp Stands + +NumSharp currently has mixed behavior. Some operations follow the old value-based rules, others follow NEP 50. We're working on consistent NEP 50 compliance. + +**Key Issue:** [#529 - Type promotion diverges from NumPy 2.x](https://github.com/SciSharp/NumSharp/issues/529) + +**What you might see:** If you're porting NumPy code and get unexpected results with mixed types (especially unsigned + signed), this is likely why. + +--- + +## API Changes: What Got Removed and Added + +### Removed in NumPy 2.0 (NEP 52) + +NumPy 2.0 cleaned house, removing ~100 deprecated functions and aliases. If you're porting old NumPy code, you might need to update these: + +| Don't Use | Use Instead | Why It Changed | +|-----------|-------------|----------------| +| `np.round_` | `np.round` | Underscore was to avoid Python keyword conflict (no longer needed) | +| `np.product` | `np.prod` | Consistency with `sum` → `prod` | +| `np.sometrue` | `np.any` | Clearer naming | +| `np.alltrue` | `np.all` | Clearer naming | +| `np.rank` | `np.ndim` | `rank` was confusing (matrix rank vs array rank) | + +NumSharp supports the canonical names. We never implemented most deprecated aliases, so this is actually an advantage—less legacy baggage. + +### Added in NumPy 2.0 (NEP 56) + +NumPy 2.0 added Array API Standard functions. These are mostly aliases for existing functions, but some are genuinely new: + +**New Aliases** (for Array API compatibility): +- `np.acos`, `np.asin`, `np.atan` → aliases for `arccos`, `arcsin`, `arctan` +- `np.concat` → alias for `concatenate` +- `np.permute_dims` → alias for `transpose` +- `np.pow` → alias for `power` + +**Genuinely New:** +- `np.isdtype(dtype, kind)` — Check if dtype belongs to a category +- `np.unique_values()`, `np.unique_counts()`, `np.unique_inverse()`, `np.unique_all()` — Split the overloaded `np.unique()` into focused functions +- `ndarray.mT` — Matrix transpose (transposes last two dimensions only) +- `ndarray.device` — Returns the device (CPU for NumSharp) + +**NumSharp Status:** We have most aliases but are missing `isdtype()`, the `unique_*` family, `.mT`, and `.device`. + +--- + +## Data Types: What We Support (and Don't) + +NumSharp supports 12 numeric types—more than most users need, but not everything NumPy offers. + +### Fully Supported + +| NumSharp Type | C# Type | NumPy Type | Notes | +|---------------|---------|------------|-------| +| Boolean | `bool` | `bool_` | | +| Byte | `byte` | `uint8` | | +| Int16 | `short` | `int16` | | +| UInt16 | `ushort` | `uint16` | | +| Int32 | `int` | `int32` | Default integer type | +| UInt32 | `uint` | `uint32` | | +| Int64 | `long` | `int64` | | +| UInt64 | `ulong` | `uint64` | | +| Single | `float` | `float32` | | +| Double | `double` | `float64` | Default float type | +| Char | `char` | — | C#-specific, no NumPy equivalent | +| Decimal | `decimal` | — | C#-specific, 128-bit decimal | + +### Not Yet Supported + +**Complex Numbers** (`complex64`, `complex128`) + +This is our biggest gap. Complex numbers are required by the Array API Standard and essential for signal processing, FFT, and many scientific applications. They're also tricky to implement efficiently in C#. + +**Why it's hard:** C# has `System.Numerics.Complex`, but it's always 128-bit (complex128). There's no native complex64. We'd need to implement our own struct for float-based complex numbers. + +**DateTime Types** (`datetime64`, `timedelta64`) + +NumPy's datetime types (NEP 7) are powerful for time series analysis. We haven't implemented them. + +**Why it's hard:** NumPy datetime64 has multiple resolutions (nanoseconds to years) stored in the dtype. C# has `DateTime` and `TimeSpan`, but they don't map cleanly to NumPy's model. + +**Variable-Width Strings** (`StringDType`) + +NumPy 2.0 added a new UTF-8 variable-width string type (NEP 55). The old fixed-width strings (`S10`, `U10`) wasted memory. We don't support either. + +--- + +## Memory Layout: C-Order Only + +Here's a limitation that might surprise NumPy users: **NumSharp only supports C-order (row-major) memory layout.** + +### What This Means + +NumPy arrays can be stored in two layouts: +- **C-order (row-major):** Last index varies fastest. Default in NumPy. +- **F-order (column-major):** First index varies fastest. Default in Fortran, MATLAB. + +```python +# NumPy can do both +c_array = np.zeros((3, 4), order='C') # Row-major +f_array = np.zeros((3, 4), order='F') # Column-major +``` + +NumSharp always uses C-order. The `order` parameter exists on functions like `reshape`, `ravel`, and `flatten`, but it's ignored—we always use C-order. + +### When This Matters + +Most of the time, you won't notice. But if you're: +- Interfacing with Fortran libraries (LAPACK, BLAS) +- Reading data written by MATLAB +- Optimizing cache access patterns for column-wise operations + +...you might hit issues. See [#546](https://github.com/SciSharp/NumSharp/issues/546) for F-order support tracking. + +--- + +## Array API Standard + +The Array API Standard specifies 133 core functions, 14 data types, and strict type promotion rules. NumSharp currently implements about **74%** of the core specification. + +| Category | Required | NumSharp | Coverage | +|----------|----------|----------|----------| +| Creation | 16 | 13 | 81% | +| Element-wise | 67 | ~50 | 75% | +| Statistical | 9 | 8 | 89% | +| Manipulation | 14 | 11 | 79% | +| Set | 4 | 1 | 25% | +| Other | 23 | ~15 | ~65% | + +**Biggest Gaps:** +- Complex number types (`complex64`, `complex128`) — blocks FFT and many math functions +- Set functions (`unique_all`, `unique_counts`, `unique_inverse`) +- Array properties (`.device`, `.mT`) + +For the complete specification details, function lists, type promotion rules, and extension coverage, see our dedicated **[Array API Standard](array-api-standard.md)** page. + +--- + +## Random Number Generation + +Good news: NumSharp's `np.random` module provides **1-to-1 seed matching** with NumPy. + +```csharp +// NumSharp +np.random.seed(42); +var a = np.random.rand(5); +// Produces: [0.37454012, 0.95071431, 0.73199394, 0.59865848, 0.15601864] + +// Equivalent Python +np.random.seed(42) +a = np.random.rand(5) +# Produces: [0.37454012, 0.95071431, 0.73199394, 0.59865848, 0.15601864] +``` + +This is critical for reproducibility. If you're porting ML code that depends on specific random sequences (for testing, debugging, or reproducible experiments), you'll get identical results. + +### Supported Distributions + +- **Uniform:** `rand`, `uniform`, `randint` +- **Normal:** `randn`, `normal` +- **Other:** `beta`, `binomial`, `gamma`, `poisson`, `exponential`, `geometric`, `lognormal`, `chisquare`, `bernoulli` +- **Utilities:** `seed`, `shuffle`, `permutation`, `choice` + +--- + +## File Format Interoperability + +NumSharp can read and write NumPy's `.npy` file format. This means you can: + +1. Create arrays in Python, save with `np.save()`, load in NumSharp +2. Create arrays in NumSharp, save with `np.save()`, load in Python +3. Share data files between Python and C# applications + +```csharp +// Save +var arr = np.arange(100).reshape(10, 10); +np.save("mydata.npy", arr); + +// Load +var loaded = np.load("mydata.npy"); +``` + +### .npz Archives + +NumPy's `.npz` format stores multiple arrays in a ZIP archive. NumSharp can **read** `.npz` files but not write them yet. + +```csharp +// Load multiple arrays from .npz +var archive = np.load("data.npz") as NpzDictionary; +var weights = archive["weights"]; +var biases = archive["biases"]; +``` + +--- + +## Linear Algebra: Partial Support + +NumSharp has basic linear algebra operations, but advanced decompositions are incomplete. + +### Working + +| Function | Notes | +|----------|-------| +| `np.dot` | Matrix multiplication | +| `np.matmul` | Matrix multiplication (equivalent to `@` in Python) | +| `np.outer` | Outer product | +| `ndarray.T` | Transpose | + +### Stubs (Return null/default) + +These functions exist but don't work: +- `np.linalg.inv` — Matrix inverse +- `np.linalg.qr` — QR decomposition +- `np.linalg.svd` — Singular value decomposition +- `np.linalg.lstsq` — Least squares + +**Why?** These originally used native LAPACK bindings that have been removed. Implementing them in pure C# is possible but significant work. + +--- + +## What's Next: Implementation Roadmap + +### Phase 1: Core Compatibility (Current Focus) + +- Fix type promotion to match NEP 50 +- Add Array API function aliases +- Implement `isdtype()`, `unique_*` family +- Add `.mT` and `.device` properties + +### Phase 2: Feature Completeness + +- Complex number support (`complex64`, `complex128`) +- `datetime64` / `timedelta64` types +- Complete missing Array API functions + +### Phase 3: Linear Algebra + +- Implement matrix decompositions (QR, SVD, etc.) +- Either pure C# or via Math.NET Numerics integration + +### Phase 4: Performance + +- SIMD optimization for element-wise operations +- Iterator optimization for non-contiguous arrays + +--- + +## How You Can Help + +NumSharp is open source. Here's how to contribute: + +1. **Report incompatibilities.** If NumSharp behaves differently from NumPy, file an issue with both code snippets. + +2. **Add tests.** Write tests that verify NumPy behavior, then make them pass in NumSharp. + +3. **Implement missing functions.** Check the milestones for prioritized work. + +### GitHub Milestones + +- [NumPy 2.x Compliance](https://github.com/SciSharp/NumSharp/milestone/9) — 7 open issues +- [Array API Standard](https://github.com/SciSharp/NumSharp/milestone/6) — 1 open issue +- [NEP Compliance](https://github.com/SciSharp/NumSharp/milestone/7) — 9 open issues + +--- + +## References + +- [NumPy 2.0 Migration Guide](https://numpy.org/doc/stable/numpy_2_0_migration_guide.html) — What changed in NumPy 2.0 +- [Python Array API Standard](https://data-apis.org/array-api/latest/) — The specification we're implementing +- [NumPy Enhancement Proposals](https://numpy.org/neps/) — Design documents for NumPy behavior +- [NumPy Source (v2.4.2)](https://github.com/numpy/numpy/tree/v2.4.2) — Reference implementation (also at `src/numpy/` in our repo) diff --git a/docs/website-src/docs/dtypes.md b/docs/website-src/docs/dtypes.md new file mode 100644 index 000000000..9a3c5198d --- /dev/null +++ b/docs/website-src/docs/dtypes.md @@ -0,0 +1,610 @@ +# Dtypes in NumSharp + +Every array in NumSharp has a **dtype**—a data type that determines what kind of values the array stores, how many bytes each element takes, and which operations are valid. When you write `np.zeros(10, np.int32)`, the `np.int32` is the dtype. When you call `arr.astype(np.float64)`, you're converting to a different dtype. + +This page covers the 15 dtypes NumSharp supports, how they map to NumPy's types, how to refer to them in code, and the places where NumSharp's behavior diverges from NumPy (and why). + +--- + +## The 15 Supported Dtypes + +NumSharp supports every numeric dtype NumPy defines, plus a few .NET-specific ones: + +| NPTypeCode | C# Type | NumPy Equivalent | Bytes | Kind | SIMD | +|------------|---------|------------------|-------|------|------| +| `Boolean` | `bool` | `bool` | 1 | `?` † | Limited | +| `SByte` | `sbyte` | `int8` | 1 | `i` | Yes | +| `Byte` | `byte` | `uint8` | 1 | `u` | Yes | +| `Int16` | `short` | `int16` | 2 | `i` | Yes | +| `UInt16` | `ushort` | `uint16` | 2 | `u` | Yes | +| `Int32` | `int` | `int32` | 4 | `i` | Yes | +| `UInt32` | `uint` | `uint32` | 4 | `u` | Yes | +| `Int64` | `long` | `int64` | 8 | `i` | Yes | +| `UInt64` | `ulong` | `uint64` | 8 | `u` | Yes | +| `Half` | `System.Half` | `float16` | 2 | `f` | None | +| `Single` | `float` | `float32` | 4 | `f` | Yes | +| `Double` | `double` | `float64` | 8 | `f` | Yes | +| `Decimal` | `decimal` | *no equiv* | 32 ‡ | `f` | None | +| `Complex` | `System.Numerics.Complex` | `complex128` | 16 | `c` | None | +| `Char` | `char` | *no equiv* | 1 ‡ | `S` | None | + +**Bytes column reports `NPTypeCode.SizeOf()` / `DType.itemsize`** — what NumSharp actually returns to your code. Two of these diverge from both NumPy and the underlying .NET type: +- † `Boolean.kind` is `'?'` in NumSharp; NumPy uses `'b'`. (NumSharp stores the type-char in the `kind` slot for bool.) +- ‡ **`Decimal.itemsize == 32` and `Char.itemsize == 1`** are NumSharp reporting bugs. The actual .NET memory footprint is 16 bytes for `decimal` and 2 bytes for `char`. `InfoOf.Size == 16` and `InfoOf.Size == 2` give you the correct values. Storage allocation uses the correct .NET size; only the `DType.itemsize` property is wrong. + +**Half**, **SByte**, and **Complex** are the newest additions—see [Breaking Changes](#breaking-changes) below. + +**Decimal** and **Char** are NumSharp-specific types with no NumPy counterpart—see [NumSharp-Specific Types](#numsharp-specific-types-decimal-and-char) for how they behave and when to use them. + +--- + +## Referring to Dtypes in Code + +There are three ways to name a dtype: + +### 1. `NPTypeCode` enum (fastest, internal-style) + +```csharp +var arr = np.zeros(new Shape(10), NPTypeCode.Int32); +var cplx = np.zeros(new Shape(2, 3), NPTypeCode.Complex); +``` + +Use this when you want zero overhead and the type is known at compile time. `NPTypeCode` values are stable enum constants. + +### 2. `np.*` class-level aliases (idiomatic) + +```csharp +var arr = np.zeros(new Shape(10), np.int32); +var half = np.ones(new Shape(5), np.float16); +var cplx = np.zeros(new Shape(2, 3), np.complex128); +``` + +These match NumPy's Python API (`np.int32`, `np.float16`, `np.complex128`). Most NumSharp code uses this form. + +### 3. Dtype strings (NumPy-compatible parsing) + +```csharp +var a = np.dtype("int32"); +var b = np.dtype("float16"); +var c = np.dtype("complex128"); +var d = np.dtype("i4"); // NumPy shorthand +var e = np.dtype("`, `=`, `|`) are accepted and ignored: `np.dtype("(new Complex(3, 4)); +var x = (int)c; // throws TypeError +var r = (int)np.real(c); // 3 — explicit, unambiguous +``` + +--- + +## NumPy Types NumSharp Doesn't Support + +NumPy has several dtype families that NumSharp deliberately does not implement. Attempting to construct or parse any of these throws `NotSupportedException` (never silent misbehavior): + +| NumPy dtype | NumPy character | Why not in NumSharp | +|-------------|-----------------|---------------------| +| `complex64` | `F`, `c8` | NumSharp has only one complex type (`complex128`). Silently widening would double memory without asking. See [Complex: Only 128-bit Is Supported](#complex-only-128-bit-is-supported). | +| `bytes_` / `S` / `a` | `S`, `a`, `c` (=S1) | NumPy bytestrings are a variable-length null-terminated byte sequence type. Not a natural fit for .NET where `string` is UTF-16 and `byte[]` is a separate concept. Use .NET strings directly. | +| `str_` / `U` | `U` | NumPy unicode strings (UCS-4 fixed-width). Same reason—use `string` / `string[]`. | +| `void` / `V` | `V` | NumPy "raw bytes" scalar. No .NET equivalent; use `byte[]` or `Memory`. | +| `object` / `O` | `O` | NumPy boxed-Python-object arrays. Use `object[]` or `NDArray` conceptually. | +| `datetime64` | `M`, `M8[ns]` etc. | Needs nanosecond-epoch semantics and unit metadata that NumSharp doesn't model. Use `DateTime[]` directly, or `long[]` with epoch seconds. | +| `timedelta64` | `m`, `m8[us]` etc. | Same reason as `datetime64`. Use `TimeSpan[]` or `long[]`. | +| Structured / record dtypes | `(...)` in dtype string | NumPy allows composite dtypes like `np.dtype([('x', 'f4'), ('y', 'i4')])` for heterogeneous records. NumSharp throws on any dtype string containing `(`. Use a struct array or multiple parallel `NDArray`s. | +| Sub-array dtypes | `('f4', (3,))` | NumPy dtype-with-subshape. Not supported. | + +Every row above is tested in `test/NumSharp.UnitTest/Creation/DTypeStringParityTests.cs` with an `ExpectThrow` assertion. If you run into one of these in ported NumPy code, the exception message tells you which NumSharp alternative to use. + +### Why Throw Instead of Silent Approximation? + +A recurring temptation is to "do the nearest thing"—e.g., widen `complex64` to `complex128` or map `S10` to `string`. NumSharp refuses this because: + +1. **Memory surprise**: doubling precision doubles allocation; a user loading a gigabyte of `complex64` data would unexpectedly use two gigabytes. +2. **Precision surprise**: downstream computations on the "wrong" type produce results the user didn't request. +3. **Signal clarity**: a `NotSupportedException` with a clear message ("use np.complex128 instead") is actionable. Silent widening is a ticking bug. + +--- + +## NumSharp-Specific Types (Decimal and Char) + +Two types in NumSharp have no NumPy equivalent. They exist for .NET-idiomatic use cases where NumPy's dtype set is too narrow. + +### `Decimal` — 128-bit fixed-point + +.NET's `System.Decimal` is a 16-byte fixed-point number with 28-29 significant digits. It's the right type for **money and financial computation** where binary floating-point's representation errors are unacceptable (`0.1 + 0.2 != 0.3` is a non-starter for an accounting ledger). + +```csharp +var prices = np.array(new[] { 19.99m, 29.99m, 5.00m }); +prices.typecode; // NPTypeCode.Decimal +InfoOf.Size; // 16 (actual memory footprint) +var total = np.sum(prices); // exact decimal sum, no float drift +``` + +**Characteristics:** +- `kind == 'f'` (float-like—it's a fractional type even though internally integer-based) +- No SIMD acceleration (decimal arithmetic is scalar-only; much slower than `double`) +- No IEEE special values: no NaN, no Infinity, no subnormals +- `np.finfo(NPTypeCode.Decimal)` works and returns limited info (bits=128, precision=28, no subnormals) +- Boundary values: `Decimal.MinValue` / `Decimal.MaxValue` (±79228162514264337593543950335) +- **Known quirk:** `NPTypeCode.Decimal.SizeOf()` and `DType.itemsize` both report `32` instead of the correct `16`. Use `InfoOf.Size` for the true byte count. + +**When to use:** +- Financial calculations (currency, tax, interest) +- Any scenario where exact decimal representation matters more than speed + +**When NOT to use:** +- Scientific computing (`double` is faster and has wider range) +- SIMD-critical paths (no vectorization) +- Interop with NumPy/Python (no round-trip—NumPy has no decimal type) + +### `Char` — 16-bit UTF-16 code unit + +`System.Char` is a 2-byte Unicode UTF-16 code unit. NumSharp preserves it as a dtype mostly for arrays of characters where the type system benefits from knowing "these are characters, not shorts." + +```csharp +var letters = np.array(new[] { 'a', 'b', 'c' }); +letters.typecode; // NPTypeCode.Char +InfoOf.Size; // 2 (actual memory footprint) +``` + +**Important:** NumSharp's `Char` is **not** the same as NumPy's `'c'` / `S1` (which is a 1-byte bytestring). They have different sizes, different encodings, different semantics. Porting NumPy bytestring code to NumSharp `Char` will almost always be wrong—use `byte` arrays for bytestring data and `string` for actual text. + +**Characteristics:** +- `kind == 'S'` (bytestring-like category, chosen for NumPy roundtrip ergonomics despite the semantic difference) +- Treated as `ushort` for many operations (same byte width) +- Boundary values: `'\0'` (0) to `char.MaxValue` (65535) +- **Known quirk:** `NPTypeCode.Char.SizeOf()` and `DType.itemsize` both report `1` instead of the correct `2`. Use `InfoOf.Size` for the true byte count. Storage allocation uses the correct 2-byte size. + +**When to use:** +- Arrays of individual characters where type annotation matters +- Interop with APIs that treat char specifically + +**When NOT to use:** +- Text data—use `string` or `string[]` +- Porting NumPy bytestring arrays—use `byte[]` with explicit encoding + +--- + +## Platform-Dependent Types + +Some dtype names follow C's native `long` convention, which differs between compilers: + +- **Windows (MSVC, LLP64 model):** C `long` is 32 bits +- **64-bit Linux/Mac (gcc, LP64 model):** C `long` is 64 bits + +NumPy inherits this from its C compiler, so `np.dtype("long")` gives **`int32`** on Windows and **`int64`** on Linux. This is a well-known NumPy quirk, tracked in [numpy/numpy#9464](https://github.com/numpy/numpy/issues/9464). NumSharp matches NumPy's platform convention exactly by detecting the OS at runtime. + +### What's platform-dependent + +| Spelling | Windows 64-bit | Linux/Mac 64-bit | +|----------|----------------|------------------| +| `np.@long`, `np.dtype("long")`, `"l"` | `Int32` | `Int64` | +| `np.@ulong`, `np.dtype("ulong")`, `"L"` | `UInt32` | `UInt64` | + +### What's *not* platform-dependent + +Everything else is fixed across platforms: + +| Spelling | Always | +|----------|--------| +| `np.int_`, `np.intp`, `"int"`, `"int_"`, `"intp"`, `"p"` | pointer-sized (int64 on 64-bit platforms) | +| `np.longlong`, `"longlong"`, `"q"`, `"i8"` | `Int64` | +| `np.int32`, `"int32"`, `"i"`, `"i4"` | `Int32` | +| `np.int16`, `"int16"`, `"h"`, `"i2"` | `Int16` | + +### Recommendation + +If you want **portable** code across Windows and Linux, avoid `long`/`ulong`/`l`/`L`. Use explicit sized names: + +```csharp +// Portable — same result on every platform: +var a = np.zeros(shape, np.int32); +var b = np.zeros(shape, np.int64); +var c = np.dtype("int64"); + +// Platform-dependent — different result on Win vs Linux: +var d = np.zeros(shape, np.@long); +var e = np.dtype("long"); +``` + +This is the same guidance NumPy itself gives—see the [NumPy data types page](https://numpy.org/doc/stable/user/basics.types.html). + +--- + +## Creating Arrays with a Specific Dtype + +### Explicit dtype + +```csharp +var a = np.zeros(new Shape(3, 4), NPTypeCode.Single); // float32 zeros +var b = np.ones(new Shape(5), np.float16); // Half ones +var c = np.full(new Shape(2), (Half)3.14); // Half filled with 3.14 +var d = np.arange(0, 10, dtype: np.int8); // int8 range +var e = np.empty(new Shape(100), np.complex128); // uninitialized complex +``` + +### Inferred from the source array + +`np.array(T[])` infers the dtype from the .NET array type: + +```csharp +np.array(new[] { 1, 2, 3 }); // dtype=int32 (from int[]) +np.array(new[] { 1.0, 2.0 }); // dtype=float64 (from double[]) +np.array(new[] { (Half)1, (Half)2 }); // dtype=float16 +np.array(new[] { new Complex(1,2), new Complex(3,4) }); // dtype=complex128 +np.array(new sbyte[] { -1, 0, 1 }); // dtype=int8 +``` + +### Converting between dtypes + +Use `.astype()` for array-level conversions: + +```csharp +var doubles = np.array(new[] { 1.5, 2.7, 3.9 }); +var ints = doubles.astype(NPTypeCode.Int32); // [1, 2, 3] (truncated) +var halfs = doubles.astype(NPTypeCode.Half); // [1.5, 2.7, 3.9] (float16) +var cplxs = doubles.astype(NPTypeCode.Complex); // [1.5+0j, 2.7+0j, 3.9+0j] +``` + +### Scalar ↔ NDArray casts + +Every numeric C# type can be implicitly converted to a 0-d `NDArray`: + +```csharp +NDArray s1 = (sbyte)42; // 0-d int8 scalar +NDArray s2 = (Half)3.14; // 0-d float16 scalar +NDArray s3 = new Complex(1, 2); // 0-d complex128 scalar +``` + +Explicit casts back to .NET scalars require a 0-dimensional array (`ndim == 0`): + +```csharp +var scalar = np.array(new[] { 42 })[0]; // 0-d view +int x = (int)scalar; // works + +var oneD = np.array(new[] { 42 }); +int y = (int)oneD; // throws IncorrectShapeException (ndim == 1) +``` + +This matches NumPy 2.x's strict behavior: `int(np.array([42]))` raises `TypeError: only 0-dimensional arrays can be converted to Python scalars`. + +--- + +## Special Values + +### NaN, Infinity (floating-point types) + +`Half`, `Single`, and `Double` have IEEE 754 special values. NumSharp preserves them exactly through array storage and scalar round-trips: + +```csharp +var h = NDArray.Scalar(Half.NaN); +Half.IsNaN((Half)h); // true + +var d = NDArray.Scalar(double.PositiveInfinity); +double.IsPositiveInfinity((double)d); // true +``` + +`Decimal` and `Complex` have no NaN/Inf equivalents (Complex's real/imag components individually can be `double.NaN`, but there's no single `Complex.NaN`). + +### Boundary values + +`np.iinfo` and `np.finfo` give you the machine limits: + +```csharp +np.iinfo(np.int8).min; // -128 +np.iinfo(np.int8).max; // 127 +np.iinfo(np.uint64).max; // long.MaxValue (clamped to long) +np.iinfo(np.uint64).maxUnsigned; // 18446744073709551615 (true ulong.MaxValue) + +np.finfo(np.float16).eps; // 2^-10 = 0.0009765625 +np.finfo(np.float16).smallest_normal; // 2^-14 +np.finfo(np.float64).max; // double.MaxValue +``` + +`iinfo.max` is declared as `long`—for `uint64` its value is clamped to `long.MaxValue`. Use `maxUnsigned` (a `ulong`) to get the true 64-bit-unsigned max. + +`np.finfo(np.complex128)` reports the **underlying float64 precision**, matching NumPy—its `dtype` property is `Double`, `bits == 64`, `precision == 15`. This is NumPy's convention: a complex number's precision is the precision of its real and imaginary components. + +--- + +## Type Promotion + +When you combine two dtypes (e.g., `int32 + float32`), NumSharp picks a result dtype following NumPy 2.x rules (NEP 50). The result type is the smallest type that can hold both inputs' values: + +```csharp +var a = np.array(new int[] { 1, 2, 3 }); +var b = np.array(new[] { 1.5, 2.5, 3.5 }); +var c = a + b; +c.dtype; // Double — int32 + float64 promotes to float64 +``` + +Quick reference for common pairs: + +| Left | Right | Result | Why | +|------|-------|--------|-----| +| `int8` | `uint8` | `int16` | both widen to fit signed range | +| `int32` | `uint32` | `int64` | can't fit uint32 in int32 | +| `int32` | `uint64` | `float64` | no common integer type | +| `float16` | `int16` | `float32` | precision of float16 insufficient | +| `float16` | `float32` | `float32` | higher precision wins | +| any | `complex128` | `complex128` | complex absorbs | + +For full 15×15 promotion rules see `np.find_common_type` (`src/NumSharp.Core/Logic/np.find_common_type.cs`). Tests in `test/NumSharp.UnitTest/Casting/DtypeConversionMatrixTests.cs` verify every pair against NumPy 2.4.2. + +For the deeper story on how NumPy 2.x promotion differs from NumPy 1.x, see [NumPy Compliance](compliance.md). + +--- + +## Breaking Changes + +If you're upgrading from an earlier NumSharp, be aware of these dtype-related changes: + +### `np.byte` now returns `sbyte` (int8), not `byte` (uint8) + +NumPy convention: `np.byte = int8` (signed, C `char`-style). NumSharp now follows NumPy. + +```csharp +// Before: +Type t = np.@byte; // typeof(byte) — uint8 + +// After: +Type t = np.@byte; // typeof(sbyte) — int8 +// If you meant uint8, use: +Type t = np.uint8; // or np.ubyte +``` + +### `np.complex64` now throws + +Previously it was a silent alias for `np.complex128`. It now raises `NotSupportedException` with a message pointing users to `np.complex128`. Same for `np.dtype("complex64")` / `"F"` / `"c8"`. + +### `np.intp` / `np.uintp` now return `long` / `ulong` (not `IntPtr` / `UIntPtr`) + +Previously these were `typeof(nint)` / `typeof(nuint)`—which have `NPTypeCode.Empty` and broke `np.zeros(shape, np.intp.GetTypeCode())`. They now match `np.int64` / `np.uint64` on 64-bit platforms (and `np.int32` / `np.uint32` on 32-bit). + +### Complex → real scalar casts now throw `TypeError` + +Previously they silently dropped the imaginary part. Now they throw, matching Python's `int(complex)` / `float(complex)` semantics. Use `np.real(arr)` explicitly if that's what you want. + +### `np.dtype("int")` now returns `Int64` (pointer-sized), not `Int32` + +NumPy 2.x made `int` an alias for `intp` (pointer-sized). NumSharp now follows. If you want fixed 32-bit, use `np.int32` / `np.dtype("int32")` / `"i4"`. + +--- + +## Invalid Dtype Strings + +`np.dtype(s)` throws `NotSupportedException` (with a descriptive message) for any string that isn't a valid NumPy dtype: + +```csharp +np.dtype("xyz"); // throws — not a dtype +np.dtype("f16"); // throws — f is 2/4/8 bytes only +np.dtype("i3"); // throws — i is 1/2/4/8 bytes only +np.dtype("?1"); // throws — ? is not sized +np.dtype(" i4"); // throws — no whitespace trimming +``` + +It also throws for NumPy dtypes NumSharp doesn't implement: + +```csharp +np.dtype("S10"); // throws — bytestring +np.dtype("U32"); // throws — unicode string +np.dtype("M8"); // throws — datetime64 +np.dtype("object"); // throws — object dtype +``` + +This is strict on purpose: silently accepting "close enough" dtype strings produces hard-to-debug corruption downstream. + +--- + +## Common Patterns + +### Loading binary data with a known dtype + +```csharp +byte[] raw = File.ReadAllBytes("sensor.bin"); +var readings = np.frombuffer(raw, np.float16); // interpret as float16 +``` + +### Making arrays with matching dtype + +```csharp +var template = np.zeros(shape, np.int8); +var sameType = np.ones(template.shape, template.typecode); // template.typecode, not template.dtype.typecode +// or more concisely: +var sameType = np.ones_like(template); +``` + +### Force-cast vs safe-cast + +```csharp +// Force: silently wraps/truncates — fastest +var forced = np.array(new[] { 300.0 }).astype(NPTypeCode.Byte); +// forced[0] == 44 (300 wrapped modulo 256) + +// Safe: raise on overflow (if NumSharp had this; currently matches NumPy's behavior +// which wraps by default and requires explicit casting='safe' for stricter modes). +``` + +--- + +## API Reference + +### Dtype specification (three forms, all equivalent) + +| Form | Example | When to use | +|------|---------|-------------| +| `NPTypeCode` enum | `NPTypeCode.Int32` | Internal code, compile-time known | +| `Type` via `np.*` | `np.int32`, `np.complex128` | Idiomatic user code | +| String via `np.dtype()` | `np.dtype("i4")`, `np.dtype("complex128")` | Runtime / config-driven | + +### Introspection + +On `NDArray` itself the key properties are `.dtype` (a `System.Type`) and `.typecode` (an `NPTypeCode`). The `DType` class (with itemsize, kind, char, name, byteorder) is only returned by `np.dtype(string)`; construct it explicitly with `new DType(arr.dtype)` if you need those fields from an array. + +| Expression | Returns | Notes | +|------------|---------|-------| +| `arr.dtype` | `System.Type` | The .NET type (e.g. `typeof(int)`)—NOT a `DType` object | +| `arr.typecode` | `NPTypeCode` | Enum value (`NPTypeCode.Int32`, etc.) | +| `arr.typecode.SizeOf()` | `int` | Bytes per element (see quirks table for Decimal/Char) | +| `arr.typecode.AsNumpyDtypeName()` | `string` | e.g. `"int32"`, `"float16"`, `"complex128"` | +| `np.dtype("int32")` | `DType` | Full descriptor object | +| `np.dtype("int32").type` | `System.Type` | Same as `arr.dtype` would be | +| `np.dtype("int32").typecode` | `NPTypeCode` | Same as `arr.typecode` would be | +| `np.dtype("int32").itemsize` | `int` | Bytes (via `typecode.SizeOf()`) | +| `np.dtype("int32").kind` | `char` | `'?'`/`'i'`/`'u'`/`'f'`/`'c'`/`'S'` (see ‡ below) | +| `np.dtype("int32").@char` | `char` | NumPy type char (e.g. `'i'`, `'b'`, `'e'`) | +| `np.dtype("int32").name` | `string` | .NET `Type.Name` (e.g. `"Int32"`)—NOT the NumPy dtype name | +| `np.dtype("int32").byteorder` | `char` | Always `'='` (native) in NumSharp | +| `new DType(arr.dtype)` | `DType` | Construct `DType` from an `NDArray`'s `.dtype` | +| `InfoOf.Size` | `int` | Byte size of CLR type `T` (correct for all 15 types, including Decimal/Char) | +| `InfoOf.NPTypeCode` | `NPTypeCode` | `NPTypeCode` for CLR type `T` | + +‡ `kind` for `NPTypeCode.Boolean` returns `'?'` rather than NumPy's `'b'`; for Complex it's `'c'` (matches NumPy). + +### Machine limits + +| Function | Returns | Works for | +|----------|---------|-----------| +| `np.iinfo(dtype)` | `iinfo` with `bits`, `min`, `max`, `kind` | integer dtypes + Boolean + Char | +| `np.finfo(dtype)` | `finfo` with `bits`, `eps`, `min`, `max`, `precision`, `resolution`, `maxexp`, `minexp`, `smallest_normal`, `smallest_subnormal` | `Half`, `Single`, `Double`, `Decimal`, `Complex` | + +### Exceptions + +| Exception | When | +|-----------|------| +| `NotSupportedException` | dtype string unrecognized, or NumPy dtype NumSharp doesn't implement (`S`/`U`/`M`/`complex64`/…); access to `np.complex64` / `np.csingle` class-level aliases | +| `TypeError` | Complex → non-complex scalar cast (`(int)complexScalar`, etc.) | +| `IncorrectShapeException` | NDArray → scalar cast on non-0-d array (matches NumPy 2.x's strict 0-d requirement) | +| `ArgumentNullException` | `np.dtype(null)` | + +--- + +## Related Reading + +- [NumPy Compliance & Compatibility](compliance.md) — Type promotion, NEP 50, broader NumPy 2.x parity +- [Broadcasting](broadcasting.md) — How shapes combine across operations (dtype-independent) +- [Buffering, Arrays and Unmanaged Memory](buffering.md) — How dtype affects memory layout +- [IL Kernel Generation in NumSharp](il-generation.md) — Which dtypes get SIMD acceleration and why +- [NumPy data types user guide](https://numpy.org/doc/stable/user/basics.types.html) — NumPy's own dtype reference diff --git a/docs/website-src/docs/exceptions.md b/docs/website-src/docs/exceptions.md new file mode 100644 index 000000000..3046d8992 --- /dev/null +++ b/docs/website-src/docs/exceptions.md @@ -0,0 +1,405 @@ +# NumSharp Exceptions + +NumSharp provides a structured exception hierarchy designed for NumPy compatibility and clear error messages. All exceptions inherit from `NumSharpException` and follow NumPy's error message format. + +## Design Principles + +1. **NumPy message compatibility** - The first line of each error message matches NumPy exactly +2. **Rich context** - Additional lines provide NumSharp-specific debugging information +3. **Catchable hierarchy** - Exceptions are grouped by category for flexible error handling +4. **Self-documenting** - Exception properties expose the values that caused the error + +--- + +## Exception Hierarchy + +``` +NumSharpException (base) +| ++-- ShapeException +| +-- BroadcastException +| +-- ReshapeException +| ++-- DTypeException +| +-- UnsupportedDTypeException +| ++-- AxisOutOfRangeException +| ++-- IndexException +| ++-- SizeException +| +-- EmptyArrayException +| +-- ScalarConversionException +| ++-- MemoryLayoutException +| +-- NonContiguousException +| +-- ReadOnlyArrayException +| ++-- InternalException +``` + +--- + +## Shape Exceptions + +Shape exceptions occur when array dimensions are incompatible with the requested operation. + +### BroadcastException + +Raised when shapes cannot be broadcast together. + +```csharp +var a = np.ones(3, 4); +var b = np.ones(5); +var c = a + b; // BroadcastException +``` + +**Message format:** +``` +operands could not be broadcast together with shapes (3, 4) (5,) +``` + +**Properties:** +- `ShapeA` - First operand's dimensions +- `ShapeB` - Second operand's dimensions + +### ReshapeException + +Raised when an array cannot be reshaped to the target shape. + +```csharp +var a = np.arange(12); +var b = a.reshape(3, 5); // ReshapeException: 12 elements cannot fit in 3x5=15 +``` + +**Message format:** +``` +cannot reshape array of size 12 into shape (3, 5) +``` + +**Properties:** +- `SourceSize` - Original array size +- `TargetShape` - Requested shape dimensions + +--- + +## DType Exceptions + +DType exceptions occur when an operation doesn't support the array's data type. + +### UnsupportedDTypeException + +Raised when an operation cannot handle the given dtype. + +```csharp +var a = np.array(new[] { 1m, 2m, 3m }); // decimal +var b = np.sin(a); // UnsupportedDTypeException: sin() doesn't support decimal +``` + +**Message format:** +``` +sin() does not support dtype 'decimal' +``` + +**Properties:** +- `TypeCode` - The unsupported `NPTypeCode` +- `Operation` - Name of the operation that failed + +**Usage in switch statements:** + +```csharp +switch (arr.typecode) +{ + case NPTypeCode.Double: return ProcessDouble(arr); + case NPTypeCode.Single: return ProcessSingle(arr); + // ... other types + default: + throw new UnsupportedDTypeException(arr.typecode, nameof(MyOperation)); +} +``` + +--- + +## Axis Exceptions + +### AxisOutOfRangeException + +Raised when an axis parameter is outside the valid range for the array's dimensions. + +```csharp +var a = np.zeros(3, 4); // 2D array +var b = np.sum(a, axis: 5); // AxisOutOfRangeException +``` + +**Message format:** +``` +axis 5 is out of bounds for array of dimension 2 +``` + +With shape context: +``` +axis 5 is out of bounds for array of dimension 2 + -> array.shape=(3, 4) +``` + +**Properties:** +- `Axis` - The invalid axis value +- `NDim` - Number of dimensions in the array +- `Shape` - Optional array dimensions for context + +**Negative axis handling:** + +NumSharp normalizes negative axes like NumPy. Use `Throw.NormalizeAxis()`: + +```csharp +// axis=-1 on a 3D array becomes axis=2 +int normalizedAxis = Throw.NormalizeAxis(axis, arr.ndim); +``` + +--- + +## Index Exceptions + +### IndexException + +Raised when an index is out of bounds for a dimension. + +```csharp +var a = np.arange(5); +var b = a[10]; // IndexException +``` + +**Message format:** +``` +index 10 is out of bounds for axis 0 with size 5 +``` + +**Properties:** +- `Index` - The invalid index value +- `Axis` - Which axis the index applies to +- `Size` - Size of that axis + +--- + +## Size Exceptions + +Size exceptions occur when array size is incompatible with the operation. + +### EmptyArrayException + +Raised when an operation cannot be performed on an empty array. + +```csharp +var a = np.array(new double[0]); +var b = np.argmax(a); // EmptyArrayException +``` + +**Message formats:** + +For reductions without identity: +``` +zero-size array to reduction operation add which has no identity +``` + +For argmax/argmin: +``` +attempt to get argmax of an empty sequence +``` + +**Properties:** +- `Operation` - Name of the operation that failed + +### ScalarConversionException + +Raised when converting a non-scalar array to a scalar value. + +```csharp +var a = np.array(new[] { 1, 2, 3 }); +int x = (int)a; // ScalarConversionException +``` + +**Message format:** +``` +cannot convert 1D array to scalar (must be 0D) +``` + +**Properties:** +- `NDim` - Actual number of dimensions + +--- + +## Memory Layout Exceptions + +Memory layout exceptions occur when an operation requires a specific memory layout. + +### NonContiguousException + +Raised when an operation requires contiguous memory but the array is sliced or strided. + +```csharp +var a = np.arange(20).reshape(4, 5); +var view = a["::2"]; // Non-contiguous view +var ptr = view.GetPinnableReference(); // NonContiguousException +``` + +**Message formats:** +``` +cannot pin reference when array is sliced or broadcasted +``` + +``` +cannot create Span over non-contiguous storage +``` + +### ReadOnlyArrayException + +Raised when attempting to modify a read-only array (such as a broadcast view). + +```csharp +var a = np.array(new[] { 1, 2, 3 }); +var b = np.broadcast_to(a, new Shape(3, 3)); // b is read-only +b[0, 0] = 999; // ReadOnlyArrayException +``` + +**Message format:** +``` +assignment destination is read-only + -> array is a broadcast view (stride=0 dimension) +``` + +--- + +## Internal Exceptions + +### InternalException + +Raised for errors that should not occur during normal operation. These indicate bugs in NumSharp. + +**Message format:** +``` +internal error: {description} (please report this bug) +``` + +If you encounter an `InternalException`, please report it at https://github.com/SciSharp/NumSharp/issues + +--- + +## Throw Helpers + +NumSharp provides static helpers in the `Throw` class for common validation patterns. + +### Shape Validation + +```csharp +// Throws BroadcastException if shapes are incompatible +Throw.CannotBroadcast(a.Shape, b.Shape); + +// Throws ReshapeException if sizes don't match +Throw.CannotReshape(arr.size, targetShape); +``` + +### Axis Validation + +```csharp +// Throws AxisOutOfRangeException if invalid +Throw.AxisOutOfRange(axis, arr.ndim); + +// Normalize negative axis and validate (returns normalized value) +int normalizedAxis = Throw.NormalizeAxis(axis, arr.ndim); +``` + +### DType Validation + +```csharp +// For switch statement defaults - auto-captures method name +default: + Throw.UnsupportedDType(arr.typecode); + // Message: "MethodName() does not support dtype 'complex64'" +``` + +### Size Validation + +```csharp +// Throws EmptyArrayException with appropriate message +if (arr.size == 0) + Throw.EmptyArray(); // For reductions + +if (arr.size == 0) + Throw.EmptySequence(); // For argmax/argmin + +// Throws ScalarConversionException +if (arr.ndim != 0) + Throw.CannotConvertToScalar(arr.ndim); +``` + +### Memory Layout Validation + +```csharp +// Throws NonContiguousException if array cannot be pinned +if (!arr.Shape.IsContiguous) + Throw.CannotPin(); + +// Throws ReadOnlyArrayException if array is not writeable +Throw.IfNotWriteable(arr.Shape); +``` + +### Null Validation + +```csharp +// Throws ArgumentNullException with parameter name +Throw.IfNull(array); // Auto-captures "array" as parameter name +``` + +--- + +## Catching Exceptions + +The hierarchy allows catching at different granularities: + +```csharp +try +{ + var result = np.sum(a, axis: 5); +} +catch (AxisOutOfRangeException ex) +{ + // Handle specifically axis errors + Console.WriteLine($"Invalid axis {ex.Axis} for {ex.NDim}D array"); +} +catch (ShapeException ex) +{ + // Handle any shape-related error (broadcast, reshape, etc.) +} +catch (NumSharpException ex) +{ + // Handle any NumSharp error +} +``` + +--- + +## NumPy Compatibility Reference + +| NumSharp Exception | NumPy Equivalent | NumPy Message Format | +|--------------------|------------------|----------------------| +| `BroadcastException` | `ValueError` | `operands could not be broadcast together with shapes {shapes}` | +| `ReshapeException` | `ValueError` | `cannot reshape array of size {n} into shape {shape}` | +| `AxisOutOfRangeException` | `AxisError` | `axis {axis} is out of bounds for array of dimension {ndim}` | +| `IndexException` | `IndexError` | `index {i} is out of bounds for axis {ax} with size {sz}` | +| `EmptyArrayException` | `ValueError` | `zero-size array to reduction operation {op} which has no identity` | +| `ReadOnlyArrayException` | `ValueError` | `{name} is read-only` | +| `UnsupportedDTypeException` | `TypeError` | `ufunc '{name}' not supported for the input types...` | + +--- + +## Migration from Legacy Exceptions + +The following legacy exceptions are deprecated: + +| Deprecated | Replacement | +|------------|-------------| +| `IncorrectShapeException` | `ShapeException`, `BroadcastException`, or `ReshapeException` | +| `IncorrectTypeException` | `DTypeException` or `UnsupportedDTypeException` | +| `IncorrectSizeException` | `SizeException`, `EmptyArrayException`, or `ScalarConversionException` | + +The deprecated exceptions still work but will be removed in a future version. diff --git a/docs/website-src/docs/extensions/bitmap.md b/docs/website-src/docs/extensions/bitmap.md new file mode 100644 index 000000000..3ec2e70ab --- /dev/null +++ b/docs/website-src/docs/extensions/bitmap.md @@ -0,0 +1,337 @@ +# NumSharp.Bitmap + +The **NumSharp.Bitmap** package provides seamless conversion between `System.Drawing.Bitmap` and `NDArray`. If you're working with images in .NET—loading them, processing pixels, applying filters, or feeding them to ML models—this extension makes it easy to move data between the image world and the array world. + +--- + +## Installation + +NumSharp.Bitmap is a separate NuGet package: + +```bash +dotnet add package NumSharp.Bitmap +``` + +> **Platform Note:** This extension uses `System.Drawing.Common`, which is only fully supported on Windows. On Linux/macOS, you'll need additional setup (libgdiplus) or consider alternatives like ImageSharp. + +--- + +## Quick Start + +```csharp +using System.Drawing; +using NumSharp; + +// Load an image and convert to NDArray +var bitmap = new Bitmap("photo.jpg"); +var pixels = bitmap.ToNDArray(); +// Shape: (1, height, width, channels) +// e.g., (1, 480, 640, 3) for a 640x480 RGB image + +// Manipulate the pixel data +var brightened = (pixels.astype(NPTypeCode.Int32) + 50).clip(0, 255).astype(NPTypeCode.Byte); + +// Convert back to Bitmap +var result = brightened.ToBitmap(); +result.Save("brightened.jpg"); +``` + +--- + +## Converting Bitmaps to NDArrays + +### `Bitmap.ToNDArray()` + +The primary method for converting images to arrays. + +```csharp +public static NDArray ToNDArray( + this Bitmap image, + bool flat = false, + bool copy = true, + bool discardAlpha = false +) +``` + +**Parameters:** + +| Parameter | Default | Description | +|-----------|---------|-------------| +| `flat` | `false` | If `true`, returns 1-D array of pixels: `R1G1B1R2G2B2...` | +| `copy` | `true` | If `true`, copies pixel data. If `false`, wraps bitmap memory directly. | +| `discardAlpha` | `false` | If `true`, strips the alpha channel (4th channel) from 32bpp images. | + +**Return Shape:** + +- `flat=false`: `(1, height, width, channels)` — 4-D tensor suitable for ML models +- `flat=true`: `(height * width * channels,)` — 1-D array of raw pixel bytes + +### Examples + +**Standard conversion (recommended for most uses):** + +```csharp +var bitmap = new Bitmap("image.png"); +var nd = bitmap.ToNDArray(); + +Console.WriteLine(nd.shape); // e.g., (1, 480, 640, 4) for 32bpp ARGB +Console.WriteLine(nd.dtype); // Byte +``` + +**Discard alpha channel:** + +```csharp +// 32bpp ARGB → 3 channels (RGB only) +var rgb = bitmap.ToNDArray(discardAlpha: true); +Console.WriteLine(rgb.shape); // (1, 480, 640, 3) +``` + +**Flat pixel array:** + +```csharp +// For algorithms that expect 1-D input +var flat = bitmap.ToNDArray(flat: true); +Console.WriteLine(flat.ndim); // 1 +``` + +**Zero-copy mode (advanced):** + +```csharp +// Wraps bitmap memory directly — faster but risky +var wrapped = bitmap.ToNDArray(copy: false); +// WARNING: The NDArray becomes invalid if the bitmap is disposed +// or modified. The bitmap remains locked until the NDArray is GC'd. +``` + +### Memory Layout + +The pixel data is in **BGR/BGRA order** (Windows GDI convention), not RGB: + +```csharp +var nd = bitmap.ToNDArray(); +// nd[0, y, x, 0] = Blue +// nd[0, y, x, 1] = Green +// nd[0, y, x, 2] = Red +// nd[0, y, x, 3] = Alpha (if 32bpp) +``` + +If you need RGB order for ML models, swap the channels: + +```csharp +// BGRA → RGBA +var rgba = nd[Slice.All, Slice.All, Slice.All, new int[] {2, 1, 0, 3}]; +``` + +--- + +## Converting NDArrays to Bitmaps + +### `NDArray.ToBitmap()` + +Converts an NDArray back to a Bitmap. + +```csharp +public static Bitmap ToBitmap( + this NDArray nd, + int width, + int height, + PixelFormat format = PixelFormat.DontCare +) + +// Overload that infers dimensions from shape +public static Bitmap ToBitmap( + this NDArray nd, + PixelFormat format = PixelFormat.DontCare +) +``` + +**Requirements:** + +- NDArray must be 4-D: `(1, height, width, channels)` +- First dimension must be 1 (single image) +- dtype should be `Byte` +- Channels must match the pixel format (3 for 24bpp, 4 for 32bpp) + +### Examples + +**Basic conversion:** + +```csharp +var nd = np.zeros(1, 100, 200, 3).astype(NPTypeCode.Byte); +var bitmap = nd.ToBitmap(); +// Infers: 200x100 image, 24bpp RGB +``` + +**Explicit format:** + +```csharp +var nd = np.zeros(1, 100, 200, 4).astype(NPTypeCode.Byte); +var bitmap = nd.ToBitmap(200, 100, PixelFormat.Format32bppArgb); +``` + +**From flat array:** + +```csharp +// If you have a 1-D array, provide dimensions and format +var flat = np.arange(0, 200 * 100 * 3).astype(NPTypeCode.Byte); +var bitmap = flat.ToBitmap(200, 100, PixelFormat.Format24bppRgb); +``` + +### Supported Pixel Formats + +| Format | Channels | Bytes/Pixel | +|--------|----------|-------------| +| `Format24bppRgb` | 3 | 3 | +| `Format32bppArgb` | 4 | 4 | +| `Format32bppPArgb` | 4 | 4 | +| `Format32bppRgb` | 4 | 4 | +| `Format48bppRgb` | 3 | 6 | +| `Format64bppArgb` | 4 | 8 | +| `Format64bppPArgb` | 4 | 8 | + +--- + +## Working with BitmapData Directly + +For performance-critical code, you can work with `BitmapData` directly. + +### `BitmapData.AsNDArray()` + +Wraps locked bitmap data as an NDArray without copying. + +```csharp +var bitmap = new Bitmap("image.png"); +var bmpData = bitmap.LockBits( + new Rectangle(0, 0, bitmap.Width, bitmap.Height), + ImageLockMode.ReadOnly, + bitmap.PixelFormat +); + +try +{ + var nd = bmpData.AsNDArray(flat: false, discardAlpha: false); + // Process pixels... + // WARNING: nd is only valid while bits are locked! +} +finally +{ + bitmap.UnlockBits(bmpData); +} +``` + +> **Warning:** The NDArray points directly to bitmap memory. If you call `UnlockBits()`, the NDArray becomes invalid and accessing it causes undefined behavior. + +--- + +## Common Patterns + +### Image Preprocessing for ML + +```csharp +// Load and normalize for neural network input +var bitmap = new Bitmap("input.jpg"); +var nd = bitmap.ToNDArray(discardAlpha: true); // (1, H, W, 3) + +// Normalize to [0, 1] range +var normalized = nd.astype(NPTypeCode.Single) / 255.0f; + +// Resize would require additional libraries (not built into NumSharp) +``` + +### Grayscale Conversion + +```csharp +var bitmap = new Bitmap("color.jpg"); +var rgb = bitmap.ToNDArray(discardAlpha: true); // (1, H, W, 3) + +// Luminance formula: 0.299*R + 0.587*G + 0.114*B +// Note: GDI uses BGR order, so channels are [B, G, R] +var b = rgb[Slice.All, Slice.All, Slice.All, 0].astype(NPTypeCode.Single); +var g = rgb[Slice.All, Slice.All, Slice.All, 1].astype(NPTypeCode.Single); +var r = rgb[Slice.All, Slice.All, Slice.All, 2].astype(NPTypeCode.Single); + +var gray = (0.114f * b + 0.587f * g + 0.299f * r).astype(NPTypeCode.Byte); +// Shape: (1, H, W) - single channel +``` + +### Batch Processing + +```csharp +// Process multiple images +var files = Directory.GetFiles("images/", "*.jpg"); +var batch = new List(); + +foreach (var file in files) +{ + using var bitmap = new Bitmap(file); + var nd = bitmap.ToNDArray(discardAlpha: true); + batch.Add(nd); +} + +// Stack into batch: (N, H, W, 3) +// Note: All images must have same dimensions +var batchArray = np.concatenate(batch.ToArray(), axis: 0); +``` + +### Round-Trip (Load, Process, Save) + +```csharp +// Load +var original = new Bitmap("photo.jpg"); +var nd = original.ToNDArray(); + +// Process: invert colors +var inverted = (255 - nd.astype(NPTypeCode.Int32)).clip(0, 255).astype(NPTypeCode.Byte); + +// Save +var result = inverted.ToBitmap(); +result.Save("inverted.jpg", ImageFormat.Jpeg); +``` + +--- + +## Known Limitations + +### Platform Support + +`System.Drawing.Common` is Windows-only in .NET 6+. On other platforms: + +```csharp +// This throws PlatformNotSupportedException on Linux/macOS +var bitmap = new Bitmap("image.png"); +``` + +**Workarounds:** +- Use `libgdiplus` on Linux (limited compatibility) +- Use ImageSharp or SkiaSharp (different API, not covered by this extension) + +### Stride Padding + +Bitmaps may have stride padding (row alignment to 4-byte boundaries). The extension handles this in most cases, but odd-width 24bpp images may have issues with `copy: true`. Use `copy: false` for odd-width images. + +### Color Order + +Windows bitmaps use BGR/BGRA byte order, not RGB. If your ML model expects RGB, you need to swap channels manually. + +### No Resize + +NumSharp doesn't include image resizing. You'll need to resize in `System.Drawing` before converting, or use a library like ImageSharp. + +--- + +## API Reference + +### Extension Methods + +| Method | Description | +|--------|-------------| +| `Bitmap.ToNDArray(...)` | Convert Bitmap to NDArray | +| `Image.ToNDArray(...)` | Convert Image to NDArray (creates Bitmap internally) | +| `BitmapData.AsNDArray(...)` | Wrap locked BitmapData as NDArray (no copy) | +| `NDArray.ToBitmap(...)` | Convert NDArray to Bitmap | + +### Helper Methods + +| Method | Description | +|--------|-------------| +| `PixelFormat.ToBytesPerPixel()` | Get bytes per pixel for a format | diff --git a/docs/website-src/docs/extensions/index.md b/docs/website-src/docs/extensions/index.md new file mode 100644 index 000000000..bd07193d6 --- /dev/null +++ b/docs/website-src/docs/extensions/index.md @@ -0,0 +1,25 @@ +# Extending Libraries + +NumSharp is designed to integrate with the broader .NET ecosystem. Extension packages bridge NumSharp arrays with platform-specific features and external libraries. + +## Official Extensions + +| Package | Purpose | +|---------|---------| +| [NumSharp.Bitmap](bitmap.md) | Image ↔ NDArray conversion via `System.Drawing` | + +## Build Your Own + +NumSharp exposes low-level memory access for integration with native libraries, GPU frameworks, or domain-specific formats: + +```csharp +// Access raw memory for interop +byte* ptr = (byte*)ndarray.Unsafe.Address; + +// Wrap external memory as NDArray +var nd = new NDArray(new ArraySlice( + new UnmanagedMemoryBlock(ptr, length, onDispose) +)); +``` + +Have an extension to share? [Open a PR](https://github.com/SciSharp/NumSharp) to add it to this list. diff --git a/docs/website-src/docs/il-generation.md b/docs/website-src/docs/il-generation.md new file mode 100644 index 000000000..ddcb67227 --- /dev/null +++ b/docs/website-src/docs/il-generation.md @@ -0,0 +1,1123 @@ +# IL Kernel Generation in NumSharp + +NumSharp achieves near-native performance through runtime IL (Intermediate Language) generation using `System.Reflection.Emit.DynamicMethod`. This document provides a comprehensive guide to the IL kernel system architecture, techniques, and coverage. + +This guide walks through the entire IL kernel system—useful for working on NumSharp internals, understanding its performance characteristics, debugging issues, adding new operations, or simply learning about the implementation. Detailed explanations and practical examples are provided throughout. + +## Table of Contents + +- [Overview](#overview) +- [Architecture](#architecture) +- [File Organization](#file-organization) +- [Execution Paths](#execution-paths) +- [SIMD Optimization Techniques](#simd-optimization-techniques) +- [Operation Coverage](#operation-coverage) +- [Type Support](#type-support) +- [Cache System](#cache-system) +- [Adding New Operations](#adding-new-operations) +- [Performance Considerations](#performance-considerations) +- [Debugging IL Generation](#debugging-il-generation) + +--- + +## Overview + +### Why IL Generation? + +Why go through the complexity of generating IL at runtime rather than using straightforward C# loops? The answer lies in the dramatic performance gains this approach enables. + +When an operation like `np.add(a, b)` executes, NumSharp doesn't simply iterate through elements with generic code. Instead, it generates specialized machine code tailored to the exact types and array layouts involved. This eliminates the overhead that would otherwise kill performance in a numerical computing library. + +NumSharp generates optimized machine code at runtime rather than relying on interpreted loops or generic abstractions. This provides: + +1. **Type Specialization** - Eliminates boxing/unboxing and virtual dispatch +2. **SIMD Vectorization** - Leverages Vector128/Vector256/Vector512 intrinsics +3. **Loop Fusion** - Combines operations to reduce memory traffic +4. **Stride Optimization** - Generates path-specific code for contiguous vs strided arrays + +### Performance Impact + +To give you a sense of the gains, here's what you can expect when IL kernels kick in compared to naive scalar implementations: + +| Scenario | Speedup vs Naive | +|----------|------------------| +| Contiguous SIMD (float/double) | 8-16x | +| Contiguous SIMD (int32/int64) | 4-8x | +| Strided arrays | 2-4x | +| Type promotion (int32 + float64) | 3-6x | + +These aren't theoretical numbers—they reflect real-world benchmarks on modern CPUs with AVX2 support. If you're processing millions of elements, you'll see the difference immediately. + +--- + +## Architecture + +Understanding the architecture will help you navigate the codebase and know where to look when debugging or extending the system. If you've ever wondered how NumSharp achieves its performance, this section reveals the magic behind the curtain. + +### Why a Static Partial Class? + +The `ILKernelGenerator` is structured as a static partial class split across many files for practical reasons: IL generation code tends to be verbose—emitting individual opcodes line by line adds up quickly. By splitting responsibilities across 28 files, each file remains focused and manageable. Fixing a bug in matrix multiplication? Go straight to `ILKernelGenerator.MatMul.cs`. Adding a new unary operation? The path is clear. + +The static nature ensures zero allocation overhead when requesting kernels. There's no object instantiation, no virtual dispatch—just direct method calls to retrieve cached delegates. + +### Core Components + +The `ILKernelGenerator` is a static partial class split across 28 files. Each file owns a specific category of operations, making it easier for you to find and modify the code you need. Here's the overall structure: + +``` +ILKernelGenerator (static partial class) +├── Core Infrastructure (.cs) +│ ├── Enabled flag, VectorBits detection +│ ├── Type mapping (NPTypeCode ↔ CLR Type ↔ Vector type) +│ └── Shared IL emission primitives +│ +├── Operation Partials +│ ├── Binary operations (.Binary.cs, .MixedType.cs) +│ ├── Unary operations (.Unary.*.cs) +│ ├── Comparisons (.Comparison.cs) +│ ├── Reductions (.Reduction.*.cs) +│ ├── Scans (.Scan.cs) +│ ├── Shifts (.Shift.cs) +│ ├── MatMul (.MatMul.cs) +│ └── Masking (.Masking.*.cs) +│ +└── Supporting Classes + ├── StrideDetector - Execution path classification + ├── TypeRules - Type size, SIMD capability checks + ├── SimdThresholds - Minimum sizes for SIMD benefit + ├── SimdMatMul - Cache-blocked matrix multiplication + └── SimdReductionOptimized - Unrolled reduction kernels +``` + +### Flow: Request to Execution + +When you perform an operation like `a + b` on two NDArrays, here's what happens under the hood. Understanding this flow will help you debug issues and trace where performance bottlenecks might occur: + +``` +1. Caller (DefaultEngine, np.*, NDArray operator) + ↓ +2. ILKernelGenerator.Get*Kernel() or TryGet*Kernel() + ↓ +3. Cache lookup by operation key + ↓ (cache miss) +4. IL generation via DynamicMethod + ↓ +5. JIT compilation to native code + ↓ +6. Delegate cached and returned + ↓ +7. Caller invokes delegate with array pointers +``` + +The first execution of a particular operation (say, adding two `float` arrays) incurs a one-time cost to generate and JIT-compile the kernel. All subsequent calls with the same type and operation hit the cache, returning the optimized delegate immediately. This is why the second iteration of a loop often runs noticeably faster than the first. + +### Understanding the JIT Partnership + +An important point: NumSharp's IL generation works *with* the .NET JIT compiler, not as a replacement for it. Calling `dm.CreateDelegate()` hands a sequence of IL instructions to the JIT. The JIT then applies its own optimizations—register allocation, instruction scheduling, constant folding—before producing native machine code. + +This partnership is powerful. The IL generation code focuses on correct memory access patterns and SIMD intrinsic calls. The JIT handles low-level details of mapping that IL to the specific CPU. On a machine with AVX-512, the JIT uses those wider registers. On older hardware, it falls back gracefully. + +This is why debugging IL generation can be tricky: the emitted code isn't the code that runs. The JIT may transform IL significantly. Tools like WinDbg's `!dumpil` command or Disassembly view in Visual Studio help reveal what actually executes. + +--- + +## File Organization + +When you need to modify or debug the IL generation code, knowing where to look is half the battle. The system is organized by operation category, so you can quickly navigate to the relevant file. + +### Partial Class Files (28 files, ~21K lines) + +Don't be intimidated by the file count—each file has a focused responsibility. Here's your roadmap to finding what you need: + +| File | Responsibility | +|------|----------------| +| `ILKernelGenerator.cs` | Core infrastructure, type mapping, shared IL primitives | +| `ILKernelGenerator.Binary.cs` | Same-type contiguous binary ops (Add, Sub, Mul, Div) | +| `ILKernelGenerator.MixedType.cs` | Type-promoting binary ops, ClearAll() | +| `ILKernelGenerator.Unary.cs` | Unary kernel cache, loop emission | +| `ILKernelGenerator.Unary.Math.cs` | Math function IL emission (Sin, Cos, Exp, Log, etc.) | +| `ILKernelGenerator.Unary.Vector.cs` | SIMD vector operations for unary ops | +| `ILKernelGenerator.Unary.Decimal.cs` | Decimal-specific unary operations | +| `ILKernelGenerator.Unary.Predicate.cs` | IsNaN, IsFinite, IsInf predicates | +| `ILKernelGenerator.Scalar.cs` | Func and Func delegates | +| `ILKernelGenerator.Comparison.cs` | Comparison ops (==, !=, <, >, <=, >=) | +| `ILKernelGenerator.Reduction.cs` | Element-wise reductions (Sum, Prod, Min, Max, Mean) | +| `ILKernelGenerator.Reduction.Boolean.cs` | All/Any with early-exit optimization | +| `ILKernelGenerator.Reduction.Arg.cs` | ArgMax/ArgMin (value + index tracking) | +| `ILKernelGenerator.Reduction.NaN.cs` | NaN-aware reductions (NanSum, NanMax, etc.) | +| `ILKernelGenerator.Reduction.Axis.cs` | Axis reduction dispatcher and general kernels | +| `ILKernelGenerator.Reduction.Axis.Simd.cs` | Typed SIMD axis reduction kernels | +| `ILKernelGenerator.Reduction.Axis.Arg.cs` | Axis ArgMax/ArgMin | +| `ILKernelGenerator.Reduction.Axis.VarStd.cs` | Axis Variance/Std (two-pass algorithm) | +| `ILKernelGenerator.Reduction.Axis.NaN.cs` | NaN-aware axis reductions | +| `ILKernelGenerator.Scan.cs` | CumSum, CumProd (prefix operations) | +| `ILKernelGenerator.Shift.cs` | LeftShift, RightShift (SIMD for scalar shift) | +| `ILKernelGenerator.MatMul.cs` | 2D matrix multiplication with SIMD | +| `ILKernelGenerator.Clip.cs` | Value clamping | +| `ILKernelGenerator.Modf.cs` | Fractional/integer split | +| `ILKernelGenerator.Masking.cs` | NonZero index collection | +| `ILKernelGenerator.Masking.Boolean.cs` | CountTrue, CopyMasked | +| `ILKernelGenerator.Masking.VarStd.cs` | Variance/Std SIMD helpers | +| `ILKernelGenerator.Masking.NaN.cs` | NaN-aware masking helpers | + +### Supporting Files + +Beyond the main partial class files, you'll find these supporting files that define the types and utilities the IL generation system depends on: + +| File | Purpose | +|------|---------| +| `KernelOp.cs` | Enums: BinaryOp, UnaryOp, ReductionOp, ComparisonOp, ExecutionPath | +| `KernelKey.cs` | Cache key structs (ContiguousKernelKey, UnaryScalarKey, etc.) | +| `KernelSignatures.cs` | Delegate type definitions | +| `BinaryKernel.cs` | MixedTypeKernelKey, BinaryKernel, UnaryKernel, ComparisonKernel | +| `ReductionKernel.cs` | Reduction keys, delegates, extension methods | +| `ScalarKernel.cs` | UnaryScalarKernelKey, BinaryScalarKernelKey | +| `TypeRules.cs` | Type size, accumulating type, SIMD capability | +| `StrideDetector.cs` | Execution path classification | +| `IndexCollector.cs` | Growable long index buffer for NonZero | +| `SimdThresholds.cs` | Minimum element counts for SIMD benefit | +| `SimdReductionOptimized.cs` | Unrolled reduction kernels (4x/8x) | +| `SimdMatMul.cs` | GEBP algorithm with cache blocking | + +--- + +## Execution Paths + +One of the most important concepts is how NumSharp selects the right execution path for arrays. Not all arrays are created equal—a contiguous array can use blazing-fast SIMD loops, while a transposed or sliced array may need coordinate-based iteration. + +### StrideDetector Classification + +Before executing any operation, NumSharp analyzes the arrays' memory layout using `StrideDetector.Classify()`. This determines which code path will be most efficient: + +```csharp +public enum ExecutionPath +{ + SimdFull, // Both operands contiguous - flat SIMD loop + SimdScalarRight, // RHS is scalar (all strides = 0) + SimdScalarLeft, // LHS is scalar (all strides = 0) + SimdChunk, // Inner dimension contiguous - chunked SIMD + General // Arbitrary strides - coordinate iteration +} +``` + +### Path Selection Logic + +Understanding this priority order helps predict which path code will take. Slower-than-expected performance often means arrays are hitting the General path instead of SimdFull: + +```csharp +// Priority order (first match wins): +1. Both contiguous → SimdFull (fastest) +2. RHS all strides = 0 → SimdScalarRight (broadcast) +3. LHS all strides = 0 → SimdScalarLeft (broadcast) +4. Inner stride = 1 or 0 for both → SimdChunk +5. Otherwise → General (coordinate-based) +``` + +**Tip:** For maximum performance, ensure arrays are contiguous. Check with `ndarray.IsContiguous` or force contiguity with `np.ascontiguousarray()`. + +### Practical Implications + +Code like `result = a + b` abstracts away memory layout concerns. But understanding execution paths helps write faster NumSharp code: + +1. **Prefer contiguous arrays**: Operations on freshly-allocated arrays (from `np.zeros`, `np.arange`, etc.) hit the SimdFull path. Sliced or transposed arrays may fall to slower paths. + +2. **Scalar broadcast is nearly free**: With `a + 5`, the scalar `5` is broadcast. This hits SimdScalarRight, which broadcasts the scalar to a SIMD vector once and reuses it—nearly as fast as SimdFull. + +3. **Transposed views are slow**: A transposed array (`a.T`) has non-contiguous memory access. Operations use coordinate-based iteration, which is significantly slower. For multiple operations on a transposed array, calling `np.ascontiguousarray()` once upfront often pays off. + +4. **Inner-dimension slicing is cheap**: Slicing like `a[:, 0:100]` takes chunks of the inner dimension. These chunks may still be contiguous enough for SimdChunk optimization. + +### Path-Specific Code Generation + +**SimdFull Path:** +``` +for i = 0 to count step vectorCount: + result[i:i+vc] = op(lhs[i:i+vc], rhs[i:i+vc]) // SIMD +for i = vectorEnd to count: + result[i] = op(lhs[i], rhs[i]) // scalar tail +``` + +**SimdScalarRight Path:** +``` +rhsVec = Vector256.Create(rhs[0]) // broadcast scalar +for i = 0 to count step vectorCount: + result[i:i+vc] = op(lhs[i:i+vc], rhsVec) +``` + +**General Path:** +``` +for linearIdx = 0 to totalSize: + coords = IndexToCoordinates(linearIdx, shape) + lhsOffset = dot(coords, lhsStrides) + rhsOffset = dot(coords, rhsStrides) + result[linearIdx] = op(lhs[lhsOffset], rhs[rhsOffset]) +``` + +--- + +## SIMD Optimization Techniques + +This section covers the optimization techniques used throughout the IL kernel system. These patterns form the toolkit for implementing new operations or squeezing out more performance. These aren't theoretical—they're the actual techniques implemented in the ILKernelGenerator code. + +Understanding these patterns serves two purposes: appreciating why NumSharp performs the way it does, and knowing what techniques to apply when adding new operations. + +### The Three-Level Loop Structure + +Before diving into specific techniques, understand the standard loop structure used throughout the IL kernels: + +``` +┌─────────────────────────────────────────────────────────────┐ +│ 4x Unrolled SIMD Loop (processes 4 vectors per iteration) │ +│ - Maximum throughput, minimum loop overhead │ +│ - Continues while: i <= totalSize - vectorCount * 4 │ +└─────────────────────────────────────────────────────────────┘ + ↓ +┌─────────────────────────────────────────────────────────────┐ +│ Remainder SIMD Loop (0-3 vectors) │ +│ - Handles leftover full vectors │ +│ - Continues while: i <= totalSize - vectorCount │ +└─────────────────────────────────────────────────────────────┘ + ↓ +┌─────────────────────────────────────────────────────────────┐ +│ Scalar Tail Loop (0 to vectorCount-1 elements) │ +│ - Processes remaining individual elements │ +│ - Continues while: i < totalSize │ +└─────────────────────────────────────────────────────────────┘ +``` + +This structure appears everywhere: binary operations, unary operations, reductions, comparisons. Once you recognize it, you'll see it throughout the codebase. + +### 1. Loop Unrolling (4x) + +Processing one vector at a time might seem efficient enough, but modern CPUs can execute multiple independent instructions simultaneously. By unrolling the loop 4x, the CPU gets more work to parallelize. + +Processing 4 vectors per iteration reduces loop overhead and enables instruction-level parallelism: + +```csharp +// 4x unrolled SIMD loop +for (; i <= unrollEnd; i += vectorCount * 4) +{ + var v0 = Vector256.Load(data + i); + var v1 = Vector256.Load(data + i + vectorCount); + var v2 = Vector256.Load(data + i + vectorCount * 2); + var v3 = Vector256.Load(data + i + vectorCount * 3); + + acc0 += v0; // Independent - can execute in parallel + acc1 += v1; + acc2 += v2; + acc3 += v3; +} + +// Remainder loop (0-3 vectors) +for (; i <= vectorEnd; i += vectorCount) + acc0 += Vector256.Load(data + i); + +// Scalar tail +for (; i < size; i++) + result += data[i]; +``` + +### 2. Tree Reduction + +With 4 accumulator vectors that need combining into a single result, the naive approach creates a serial dependency chain where each addition must wait for the previous one. Tree reduction solves this by allowing parallel execution: + +```csharp +// Instead of: result = acc0 + acc1 + acc2 + acc3 (serial - each add waits for previous) +// Use tree pattern: +var sum01 = acc0 + acc1; // Can execute in parallel +var sum23 = acc2 + acc3; // Can execute in parallel +var sumAll = sum01 + sum23; +double result = Vector256.Sum(sumAll); +``` + +This might seem like a minor detail, but it can make a significant difference on modern out-of-order CPUs. + +### 3. Multiple Accumulator Vectors + +Using independent accumulators maximizes instruction-level parallelism (ILP): + +```csharp +// 4 independent accumulators - no dependency between updates +var acc0 = Vector256.Zero; +var acc1 = Vector256.Zero; +var acc2 = Vector256.Zero; +var acc3 = Vector256.Zero; +``` + +### 4. FMA (Fused Multiply-Add) + +On CPUs with FMA support (Intel Haswell and newer, AMD Piledriver and newer), a significant boost is available. FMA performs `a * b + c` in a single instruction with only one rounding step, which is both faster and more accurate: + +```csharp +if (Fma.IsSupported) + c = Fma.MultiplyAdd(a, b, c); // c = a * b + c in one instruction +else + c = Vector256.Add(c, Vector256.Multiply(a, b)); +``` + +The IL kernel system automatically detects FMA availability at runtime and uses it when possible. No special configuration needed—just capable hardware. + +### 5. Cache Blocking (MatMul) + +Matrix multiplication is where cache blocking becomes critical. Without it, constant fetching from main memory destroys performance. The GEBP (General Block Panel) algorithm ensures the working set fits in cache: + +```csharp +// Block sizes tuned for L1=32KB, L2=256KB +const int MC = 64; // A panel rows +const int KC = 256; // K depth +const int MR = 8; // Micro-kernel rows +const int NR = 16; // Micro-kernel cols (2 vectors) + +// Panel packing: A[kc][MR], B[kc][NR] for sequential access +``` + +These constants were tuned empirically for typical modern CPUs. If you're targeting specialized hardware, you might benefit from different values. + +### Why These Numbers? + +The specific values like 4x unrolling or 64-element block sizes aren't arbitrary: + +- **4x unrolling**: Modern CPUs have 4-8 execution units that can run SIMD operations in parallel. Unrolling 4x saturates these units without excessive code bloat. Going to 8x provides diminishing returns and increases instruction cache pressure. + +- **Block sizes (MC=64, KC=256, MR=8, NR=16)**: These are tuned for typical L1/L2 cache sizes. MC×KC should fit in L2 (~256KB), while MR×KC should fit in L1 (~32KB). The micro-kernel dimensions (MR×NR) are chosen to maximize register usage—on x86-64, you have 16 YMM registers, and an 8×16 micro-kernel needs 8 accumulators plus 2 for A and B panels. + +If you're running on a system with different cache sizes (e.g., ARM with larger L1, or a server with huge L3), these values could be retuned. For most desktop/laptop CPUs made in the last decade, they work well. + +### 6. Early Exit (Boolean Reductions) + +For `np.all()` and `np.any()`, scanning the entire array isn't always necessary. When checking whether all elements are true, finding a single false allows immediate termination. The IL kernels exploit this with SIMD-accelerated early exit: + +```csharp +// All: exit when first zero found +for (; i <= vectorEnd; i += vectorCount) +{ + var vec = Vector256.Load(data + i); + if (Vector256.EqualsAny(vec, zero)) + return false; // Early exit! +} + +// Any: exit when first non-zero found +for (; i <= vectorEnd; i += vectorCount) +{ + var vec = Vector256.Load(data + i); + if (!Vector256.EqualsAll(vec, zero)) + return true; // Early exit! +} +``` + +--- + +## Operation Coverage + +This section provides a comprehensive reference of every operation the IL kernel system supports. When you're implementing a new feature or debugging existing code, use these tables to understand what's available and how each operation is implemented. + +### How to Read These Tables + +Each table shows: +- **Operation**: The NumPy-equivalent operation name +- **SIMD**: The Vector256/Vector128 method or intrinsic used for SIMD acceleration +- **Scalar**: The IL opcode or .NET method used for the scalar fallback path +- **Types/Notes**: Which types are supported or special considerations + +If you see "-" in the SIMD column, that operation doesn't have SIMD acceleration—it falls back to scalar loops. This doesn't necessarily mean it's slow; operations like `Sin` and `Cos` call highly optimized `MathF`/`Math` methods that the JIT may vectorize internally on modern .NET versions. + +### Binary Operations + +| Operation | SIMD | Scalar | Types | +|-----------|------|--------|-------| +| Add | Vector256 op_Addition | OpCodes.Add | All numeric | +| Subtract | Vector256 op_Subtraction | OpCodes.Sub | All numeric | +| Multiply | Vector256 op_Multiply | OpCodes.Mul | All numeric | +| Divide | Vector256 op_Division | OpCodes.Div/Div_Un | All numeric | +| Power | - | Math.Pow | All numeric | +| FloorDivide | - | Div + Math.Floor | All numeric | +| BitwiseAnd | Vector256.BitwiseAnd | OpCodes.And | Integers | +| BitwiseOr | Vector256.BitwiseOr | OpCodes.Or | Integers | +| BitwiseXor | Vector256.Xor | OpCodes.Xor | Integers | +| LeftShift | Vector256.ShiftLeft | OpCodes.Shl | Integers | +| RightShift | Vector256.ShiftRight* | OpCodes.Shr/Shr_Un | Integers | +| ATan2 | - | Math.Atan2 | float, double | + +### Unary Operations + +| Operation | SIMD | Scalar | Notes | +|-----------|------|--------|-------| +| Negate | op_UnaryNegation | OpCodes.Neg | Two's complement for unsigned | +| Abs | Vector.Abs | Bitwise for int, Math.Abs for float | +| Sqrt | Vector.Sqrt | Math.Sqrt/MathF.Sqrt | +| Square | Multiply(dup) | OpCodes.Dup + Mul | +| Reciprocal | Divide(One, x) | 1.0 / x | +| Floor | Vector.Floor | Math.Floor | +| Ceiling | Vector.Ceiling | Math.Ceiling | +| Round | Vector.Round | Math.Round | +| Truncate | Vector.Truncate | Math.Truncate | +| Sign | - | Bitwise comparison | NaN → NaN | +| Exp | - | Math.Exp | +| Exp2 | - | Math.Pow(2, x) | +| Expm1 | - | Math.Exp(x) - 1 | +| Log | - | Math.Log | +| Log2 | - | Math.Log2 | +| Log10 | - | Math.Log10 | +| Log1p | - | Math.Log(1 + x) | +| Sin/Cos/Tan | - | Math.Sin/Cos/Tan | +| ASin/ACos/ATan | - | Math.Asin/Acos/Atan | +| Sinh/Cosh/Tanh | - | Math.Sinh/Cosh/Tanh | +| Cbrt | - | Math.Cbrt | +| Deg2Rad | Multiply(factor) | x * (π/180) | +| Rad2Deg | Multiply(factor) | x * (180/π) | +| BitwiseNot | OnesComplement | OpCodes.Not | +| LogicalNot | - | x == 0 | +| IsFinite | - | float.IsFinite/double.IsFinite | +| IsNaN | - | float.IsNaN/double.IsNaN | +| IsInf | - | float.IsInfinity/double.IsInfinity | + +### Comparison Operations + +| Operation | IL Opcode | Result | +|-----------|-----------|--------| +| Equal | Ceq | bool | +| NotEqual | Ceq + Ldc_I4_0 + Ceq | bool | +| Less | Clt / Clt_Un | bool | +| Greater | Cgt / Cgt_Un | bool | +| LessEqual | Cgt + Ldc_I4_0 + Ceq | bool | +| GreaterEqual | Clt + Ldc_I4_0 + Ceq | bool | + +### Reduction Operations + +| Operation | Element-wise | Axis | Identity | +|-----------|--------------|------|----------| +| Sum | SIMD + horizontal | SIMD per slice | 0 | +| Prod | SIMD + horizontal | SIMD per slice | 1 | +| Min | SIMD Min + horizontal | SIMD per slice | +∞ | +| Max | SIMD Max + horizontal | SIMD per slice | -∞ | +| Mean | Sum / count | Sum / axisSize | 0 | +| Var | Two-pass | Two-pass | - | +| Std | sqrt(Var) | sqrt(Var) | - | +| All | SIMD compare + early exit | Per slice | true | +| Any | SIMD compare + early exit | Per slice | false | +| ArgMax | Track value + index | Per slice | 0 | +| ArgMin | Track value + index | Per slice | 0 | +| NanSum | Skip NaN | Skip NaN | 0 | +| NanProd | Skip NaN | Skip NaN | 1 | +| NanMin | Skip NaN | Skip NaN | NaN if all NaN | +| NanMax | Skip NaN | Skip NaN | NaN if all NaN | +| NanMean | Skip NaN | Skip NaN | NaN if all NaN | +| NanVar | Skip NaN | Skip NaN | NaN if all NaN | +| NanStd | Skip NaN | Skip NaN | NaN if all NaN | + +### Scan Operations + +| Operation | Contiguous | Strided | +|-----------|------------|---------| +| CumSum | Sequential accumulation | Coordinate iteration | +| CumProd | Sequential accumulation | Coordinate iteration | + +--- + +## Type Support + +Understanding how different types are handled will help you predict performance and avoid surprises. Not all types are created equal when it comes to SIMD optimization. + +### The Type Hierarchy + +NumSharp supports 12 types, but they fall into natural categories with different performance characteristics: + +**SIMD-Friendly Types** (4-8 elements per Vector256): +- `float`, `double`: Full SIMD support including transcendental functions via Vector256 methods +- `int`, `uint`, `long`, `ulong`: Full SIMD for arithmetic and bitwise operations +- `short`, `ushort`, `byte`: SIMD works but with more elements per vector (16-32) + +**Limited SIMD Types**: +- `bool`: Used only for comparison results and masking; limited SIMD via byte representation +- `char`: Treated as `ushort` internally; SIMD works but rarely used + +**No SIMD Types**: +- `decimal`: 128-bit type with no hardware SIMD support; always uses scalar loops + +When you're working with decimal arrays, expect performance roughly 8-16x slower than float/double equivalents. This isn't a NumSharp limitation—it's inherent to the decimal type's complexity. + +### All 12 NumSharp Types + +| NPTypeCode | CLR Type | Size | SIMD Support | +|------------|----------|------|--------------| +| Boolean | bool | 1 | Limited (comparison) | +| Byte | byte | 1 | Vector256 (32 elements) | +| Int16 | short | 2 | Vector256 (16 elements) | +| UInt16 | ushort | 2 | Vector256 (16 elements) | +| Int32 | int | 4 | Vector256 (8 elements) | +| UInt32 | uint | 4 | Vector256 (8 elements) | +| Int64 | long | 8 | Vector256 (4 elements) | +| UInt64 | ulong | 8 | Vector256 (4 elements) | +| Single | float | 4 | Vector256 (8 elements) | +| Double | double | 8 | Vector256 (4 elements) | +| Char | char | 2 | Limited | +| Decimal | decimal | 16 | None (scalar only) | + +### Type Promotion (NEP50 Alignment) + +```csharp +// Accumulating types for reductions +GetAccumulatingType(int32) → int64 // Prevent overflow +GetAccumulatingType(uint16) → uint64 +GetAccumulatingType(float) → float // Preserve precision +GetAccumulatingType(double) → double +``` + +### SIMD Thresholds + +Minimum element counts where SIMD overhead is worthwhile: + +| Type | Threshold | +|------|-----------| +| byte | 64 | +| short/ushort | 64 | +| int/uint/float | 96 | +| long/ulong | 256 | +| double | 512 | + +--- + +## Cache System + +The cache system is what makes IL generation practical. Without caching, every operation would incur the overhead of IL emission and JIT compilation—potentially tens of milliseconds. With caching, you pay this cost once per unique operation type, then get sub-microsecond delegate lookups forever after. + +### How Caching Works + +When you call `GetContiguousKernel(BinaryOp.Add)`, here's what happens: + +1. **Key construction**: A cache key is created: `(BinaryOp.Add, typeof(float))` +2. **Cache lookup**: The `ConcurrentDictionary` checks if this key exists +3. **Cache hit**: If found, return the cached delegate immediately (~50ns) +4. **Cache miss**: Generate IL, JIT-compile, cache, and return (~5-50ms first time) + +The cache is global and lives for the application lifetime. Once a kernel is generated, it's never regenerated. This is why warm-up loops are common in benchmarking code—the first iteration pays the JIT tax. + +### Cache Key Design Philosophy + +Each operation category has its own key structure because different operations need different parameters to fully specify the generated code: + +- **Contiguous binary**: Just need `(Type, Operation)` since both arrays are contiguous +- **Mixed-type binary**: Need `(LhsType, RhsType, ResultType, Operation, ExecutionPath)` +- **Axis reductions**: Need `(InputType, AccumulatorType, Operation, InnerAxisContiguous)` + +The key principle: the cache key must capture everything that affects the generated IL. If two operations would generate identical IL, they should share a cache entry. If they would generate different IL, they need different keys. + +### Cache Key Structures + +Each operation category has a unique key structure: + +```csharp +// Binary operations +record struct ContiguousKernelKey(NPTypeCode Type, BinaryOp Op); +record struct MixedTypeKernelKey(NPTypeCode Lhs, NPTypeCode Rhs, + NPTypeCode Result, BinaryOp Op, ExecutionPath Path); + +// Unary operations +record struct UnaryKernelKey(NPTypeCode Input, NPTypeCode Output, + UnaryOp Op, bool IsContiguous); +record struct UnaryScalarKernelKey(NPTypeCode Input, NPTypeCode Output, UnaryOp Op); + +// Reductions +record struct ElementReductionKernelKey(NPTypeCode Input, + NPTypeCode Accumulator, ReductionOp Op, bool IsContiguous); +record struct AxisReductionKernelKey(NPTypeCode Input, + NPTypeCode Accumulator, ReductionOp Op, bool InnerAxisContiguous); + +// Comparisons +record struct ComparisonKernelKey(NPTypeCode Lhs, NPTypeCode Rhs, + ComparisonOp Op, ExecutionPath Path); +``` + +### Cache Implementation + +```csharp +// ConcurrentDictionary for thread-safe access +private static readonly ConcurrentDictionary + _contiguousKernelCache = new(); + +// GetOrAdd pattern for atomic cache population +public static ContiguousKernel? GetContiguousKernel(BinaryOp op) +{ + var key = (op, typeof(T)); + if (_contiguousKernelCache.TryGetValue(key, out var cached)) + return (ContiguousKernel)cached; + + var kernel = TryGenerateContiguousKernel(op); + if (kernel == null) return null; + + if (_contiguousKernelCache.TryAdd(key, kernel)) + return kernel; + return (ContiguousKernel)_contiguousKernelCache[key]; +} +``` + +### Cache Statistics + +```csharp +public static int CachedCount => _contiguousKernelCache.Count; +public static int UnaryCachedCount => _unaryCache.Count; +public static int ElementReductionCachedCount => _elementReductionCache.Count; +// ... etc +``` + +--- + +## Delegate Signatures + +### Binary Operations + +```csharp +// Same-type contiguous +public unsafe delegate void ContiguousKernel( + T* lhs, T* rhs, T* result, long count) where T : unmanaged; + +// Mixed-type with strides +public unsafe delegate void MixedTypeKernel( + void* lhs, void* rhs, void* result, + long* lhsStrides, long* rhsStrides, long* shape, + int ndim, long totalSize); +``` + +### Unary Operations + +```csharp +public unsafe delegate void UnaryKernel( + void* input, void* output, + long* strides, long* shape, + int ndim, long totalSize); +``` + +### Reductions + +```csharp +// Element-wise (full array → scalar) +public unsafe delegate TResult TypedElementReductionKernel( + void* input, long* strides, long* shape, + int ndim, long totalSize) where TResult : unmanaged; + +// Axis reduction +public unsafe delegate void AxisReductionKernel( + void* input, void* output, + long* inputStrides, long* inputShape, long* outputStrides, + int axis, long axisSize, int ndim, long outputSize); +``` + +### Comparisons + +```csharp +public unsafe delegate void ComparisonKernel( + void* lhs, void* rhs, bool* result, + long* lhsStrides, long* rhsStrides, long* shape, + int ndim, long totalSize); +``` + +--- + +## Adding New Operations + +Adding a new operation to the IL kernel system might seem daunting at first, but it follows a well-established pattern. This section walks you through the process step by step, with practical guidance at each stage. + +### Before You Start + +Ask yourself these questions: + +1. **Does NumPy have this operation?** If so, study NumPy's behavior carefully—edge cases, type handling, NaN behavior. NumSharp aims for NumPy compatibility. + +2. **Does SIMD acceleration make sense?** Operations like `np.sin` don't have direct SIMD intrinsics, so they call `Math.Sin` in a scalar loop. That's fine—don't force SIMD where it doesn't fit. + +3. **What types need support?** Most operations should support all 12 NumSharp types. Some (bitwise operations) only make sense for integers. + +4. **Are there existing similar operations?** Copy-paste-modify is encouraged. If you're adding `Sinh`, look at how `Sin` is implemented. + +### Step 1: Define the Operation + +Add to the appropriate enum in `KernelOp.cs`: + +```csharp +public enum UnaryOp +{ + // ... existing ops ... + MyNewOp, +} +``` + +### Step 2: Add Cache Key (if needed) + +If using a new key structure, add to `KernelKey.cs` or the appropriate file. + +### Step 3: Implement IL Emission + +Add the IL emission logic to the appropriate partial file: + +```csharp +// In ILKernelGenerator.Unary.Math.cs +case UnaryOp.MyNewOp: + EmitMyNewOpCall(il, type); + break; + +private static void EmitMyNewOpCall(ILGenerator il, NPTypeCode type) +{ + if (type == NPTypeCode.Single) + { + // Call MathF.MyNewOp(float) + var method = typeof(MathF).GetMethod("MyNewOp", new[] { typeof(float) }); + il.EmitCall(OpCodes.Call, method!, null); + } + else if (type == NPTypeCode.Double) + { + // Call Math.MyNewOp(double) + var method = typeof(Math).GetMethod("MyNewOp", new[] { typeof(double) }); + il.EmitCall(OpCodes.Call, method!, null); + } + else + { + // Convert to double, call, convert back + EmitConvertToDouble(il, type); + var method = typeof(Math).GetMethod("MyNewOp", new[] { typeof(double) }); + il.EmitCall(OpCodes.Call, method!, null); + EmitConvertFromDouble(il, type); + } +} +``` + +### Step 4: Add SIMD Path (if applicable) + +If the operation has SIMD support, add to `ILKernelGenerator.Unary.Vector.cs`: + +```csharp +case UnaryOp.MyNewOp: + EmitVectorMyNewOp(il, containerType, clrType, vectorType); + break; +``` + +### Step 5: Update CanUseSimd Check + +```csharp +private static bool CanUseUnarySimd(UnaryKernelKey key) +{ + // Add MyNewOp to SIMD-capable operations + return key.Op == UnaryOp.Negate || key.Op == UnaryOp.Abs || + key.Op == UnaryOp.MyNewOp || // Add here + // ... +} +``` + +### Step 6: Test Thoroughly + +This is where most bugs are caught. Write comprehensive tests covering: + +**Type Coverage:** +- All 12 NumSharp types (Boolean, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Char, Single, Double, Decimal) +- Pay special attention to signed/unsigned differences + +**Array Layout Coverage:** +- Contiguous arrays (the fast SIMD path) +- Strided arrays (sliced, transposed) +- Broadcast arrays (scalar × array) + +**Edge Cases:** +- Empty arrays (`np.array([])`) +- Single-element arrays +- NaN and Inf values (for float/double) +- Boundary values (min/max of each type) +- Very large arrays (tests SIMD loop correctness) + +**NumPy Verification:** +```python +# Run actual NumPy and record the expected output +import numpy as np +arr = np.array([1.0, 2.0, 3.0]) +result = np.my_new_op(arr) +print(result) # Use this as your expected value +``` + +### Step 7: Benchmark (Optional but Recommended) + +If you're adding a performance-critical operation, verify that your IL kernel actually provides speedup: + +```csharp +// Simple benchmark pattern +var arr = np.random.rand(10_000_000); + +// Warm up (JIT compile) +_ = np.my_new_op(arr); + +// Measure +var sw = Stopwatch.StartNew(); +for (int i = 0; i < 100; i++) + _ = np.my_new_op(arr); +Console.WriteLine($"{sw.ElapsedMilliseconds / 100.0} ms per call"); +``` + +Compare against a naive scalar implementation to quantify the speedup. If you're not seeing expected gains, check that your arrays are hitting the SIMD path (contiguous, supported type). + +--- + +## Performance Considerations + +This section helps you understand when you'll see the best performance from NumSharp and when to expect limitations. Use this knowledge to write faster code and to set appropriate expectations. + +### The Performance Hierarchy + +Not all operations achieve the same speedups. Here's a rough hierarchy from fastest to slowest: + +1. **Contiguous SIMD operations** (8-16x faster than scalar): `np.add`, `np.multiply`, etc. on contiguous float/double arrays +2. **Scalar broadcast operations** (6-12x faster): `array + 5`, `array * 2.0` +3. **Type-promoting operations** (3-6x faster): `int32_array + float64_array` +4. **Strided operations** (2-3x faster): Operations on sliced/transposed arrays +5. **Reductions** (4-8x faster): `np.sum`, `np.mean`, `np.max` with horizontal SIMD +6. **Scalar-only operations** (1-2x faster): `np.sin`, `np.power` where SIMD isn't available + +The "faster than scalar" comparisons are against naive C# loops. Actual speedup depends on CPU, memory bandwidth, and array sizes. + +### When IL Kernels Are Used + +1. **Contiguous arrays** - SimdFull path with SIMD vectorization +2. **Broadcast operations** - SimdScalarRight/Left with scalar splatting +3. **Type promotion** - MixedType kernels with conversion +4. **Reductions** - Horizontal SIMD with tree reduction + +### When IL Kernels Fall Back + +1. **Decimal type** - No SIMD support, scalar loop +2. **Complex strides** - General path with coordinate iteration +3. **Very small arrays** - Below SimdThresholds, overhead not worthwhile +4. **Unsupported operations** - Returns null, caller uses fallback + +### Memory Bandwidth vs Compute + +For very large arrays (>10M elements), performance becomes memory-bound rather than compute-bound. SIMD still helps by: +- Reducing instruction count +- Improving prefetching +- Better cache utilization + +### Alignment + +All NumSharp allocations are naturally aligned (managed memory). For optimal SIMD performance: +- Vector256 prefers 32-byte alignment +- Vector512 prefers 64-byte alignment +- Unaligned loads/stores work but may be slower + +--- + +## Debugging IL Generation + +IL generation bugs are notoriously difficult to debug. Unlike regular C# code where you get helpful compiler errors, IL generation failures often manifest as cryptic runtime exceptions or—worse—silently wrong results. This section arms you with the tools and techniques to track down these issues. + +### The Nature of IL Bugs + +Before diving into specific techniques, here are the kinds of bugs commonly encountered: + +1. **Stack imbalance**: You pushed more values than you popped (or vice versa). The JIT catches this and throws `InvalidProgramException`. + +2. **Type mismatch**: You tried to store a value of the wrong type. For example, you have a `double` on the stack but emit `Stind_I4`. This causes `VerificationException` or corrupted data. + +3. **Missing conversions**: You forgot to convert between types. For example, loading a `byte` and comparing with an `int` without `Conv_I4` first. + +4. **Wrong opcode**: Using `Shr` when you needed `Shr_Un` for unsigned right shift, or `Div` when you needed `Div_Un`. + +5. **Off-by-one in loops**: Your loop bounds are wrong, causing buffer overruns or missed elements. + +The catch-all exception handlers in `TryGet*Kernel()` methods are intentional—they let NumSharp gracefully fall back to scalar implementations when IL generation fails. During development, disabling these catches temporarily reveals the actual exceptions. + +### Enable Diagnostics + +IL generation failures are logged to Debug output: + +```csharp +System.Diagnostics.Debug.WriteLine( + $"[ILKernel] TryGenerateContiguousKernel<{typeof(T).Name}>({op}): " + + $"{ex.GetType().Name}: {ex.Message}"); +``` + +### Common IL Errors + +| Error | Cause | Fix | +|-------|-------|-----| +| InvalidProgramException | Stack imbalance | Check push/pop count | +| VerificationException | Type mismatch | Add Conv_* instruction | +| NullReferenceException | Missing method | Check reflection lookup | + +### Verifying Generated IL + +Use a decompiler (ILSpy, dnSpy) to inspect generated methods: + +```csharp +var dm = new DynamicMethod(...); +var il = dm.GetILGenerator(); +// ... emit IL ... +var del = dm.CreateDelegate<...>(); + +// Inspect with: +// - ILSpy: Load assembly, find dynamic method +// - WinDbg: !dumpil +``` + +### Stack Tracking + +Track stack depth mentally or with comments: + +```csharp +il.Emit(OpCodes.Ldarg_0); // Stack: [ptr] +il.Emit(OpCodes.Ldloc, idx); // Stack: [ptr, idx(long)] +il.Emit(OpCodes.Ldc_I8, 4L); // Stack: [ptr, idx, 4] +il.Emit(OpCodes.Mul); // Stack: [ptr, offset(long)] +il.Emit(OpCodes.Conv_I); // Stack: [ptr, offset(native)] +il.Emit(OpCodes.Add); // Stack: [addr] +il.Emit(OpCodes.Ldind_R4); // Stack: [value] +``` + +--- + +## Int64 Indexing + +All loop counters and indices use `long` to support arrays >2GB: + +```csharp +// Loop counter declaration +var locI = il.DeclareLocal(typeof(long)); + +// Load long constant +il.Emit(OpCodes.Ldc_I8, 0L); + +// Increment +il.Emit(OpCodes.Ldloc, locI); +il.Emit(OpCodes.Ldc_I8, 1L); +il.Emit(OpCodes.Add); +il.Emit(OpCodes.Stloc, locI); + +// Delegate signatures use long +public unsafe delegate void ContiguousKernel( + T* lhs, T* rhs, T* result, long count); +``` + +--- + +## Common Pitfalls and How to Avoid Them + +Over time, contributors have encountered the same IL generation pitfalls repeatedly. Learning from these mistakes will save you debugging time. + +### Pitfall 1: Forgetting Conv_I for Pointer Arithmetic + +When computing pointer offsets, the result must be a native int for the `Add` to pointer. NumSharp uses `long` indices throughout, so you must convert after multiplication: + +```csharp +// WRONG: Multiplying long by int is invalid in IL +il.Emit(OpCodes.Ldloc, locI); // long index +il.Emit(OpCodes.Ldc_I4, elementSize); // int size +il.Emit(OpCodes.Mul); // IL verification error! long * int is not valid + +// CORRECT: Use long * long, then convert result to native int for pointer add +il.Emit(OpCodes.Ldloc, locI); // long index +il.Emit(OpCodes.Ldc_I8, (long)elementSize); // long size (cast int to long) +il.Emit(OpCodes.Mul); // long * long = long (preserves precision) +il.Emit(OpCodes.Conv_I); // Convert to native int for pointer arithmetic +il.Emit(OpCodes.Add); // Add to base pointer +``` + +The key insight: keep full 64-bit precision during the multiplication, only convert to native int right before adding to the pointer. + +### Pitfall 2: Stack Imbalance in Branches + +When you have conditional branches, both paths must leave the stack in the same state: + +```csharp +// WRONG: Different stack states +il.Emit(OpCodes.Ldloc, locValue); +il.Emit(OpCodes.Brfalse, lblElse); +il.Emit(OpCodes.Ldc_I4_1); +il.Emit(OpCodes.Ldc_I4_2); // Extra value on stack! +il.Emit(OpCodes.Br, lblEnd); +il.MarkLabel(lblElse); +il.Emit(OpCodes.Ldc_I4_0); +il.MarkLabel(lblEnd); + +// CORRECT: Both paths leave one value on stack +il.Emit(OpCodes.Ldloc, locValue); +il.Emit(OpCodes.Brfalse, lblElse); +il.Emit(OpCodes.Ldc_I4_1); +il.Emit(OpCodes.Br, lblEnd); +il.MarkLabel(lblElse); +il.Emit(OpCodes.Ldc_I4_0); +il.MarkLabel(lblEnd); +``` + +### Pitfall 3: Using Wrong Indirect Load/Store + +Each type has specific load/store opcodes. Using the wrong one causes subtle corruption: + +```csharp +// For uint: use Ldind_U4, not Ldind_I4 +// For ulong: use Ldind_I8 (same as long) +// For float: use Ldind_R4 +// For double: use Ldind_R8 +``` + +The helpers `EmitLoadIndirect()` and `EmitStoreIndirect()` handle this correctly—use them instead of emitting opcodes directly. + +### Pitfall 4: Forgetting Unsigned Operations + +Division and right shift have signed and unsigned variants: + +```csharp +// For signed types: Div, Shr +// For unsigned types: Div_Un, Shr_Un + +// WRONG: Using Div for uint gives signed semantics +il.Emit(OpCodes.Div); + +// CORRECT: Check type and use appropriate opcode +if (IsUnsignedType(type)) + il.Emit(OpCodes.Div_Un); +else + il.Emit(OpCodes.Div); +``` + +### Pitfall 5: Not Handling Empty Arrays + +Always check for empty arrays at the start of your kernel. Many SIMD operations will fail or produce undefined behavior on zero-length data: + +```csharp +// At kernel start, check totalSize and return early +il.Emit(OpCodes.Ldarg, totalSizeArgIndex); +il.Emit(OpCodes.Ldc_I8, 0L); +il.Emit(OpCodes.Ble, lblReturn); // If totalSize <= 0, return immediately +``` + +--- + +## Summary + +You've now explored the ILKernelGenerator system, NumSharp's performance backbone. Let's recap what you've learned: + +**Core Architecture:** +- The system uses `System.Reflection.Emit.DynamicMethod` to generate specialized kernels at runtime +- 28 partial class files organize the code by operation category +- Kernels are cached by operation key for instant reuse after first generation +- The JIT compiler further optimizes the emitted IL to native machine code + +**Optimization Techniques:** +- **SIMD vectorization** with Vector128/256/512 processes 4-32 elements per instruction +- **4x loop unrolling** maximizes instruction-level parallelism +- **Tree reduction** combines accumulator vectors efficiently +- **Cache blocking** (GEBP algorithm) optimizes matrix multiplication +- **Early exit** accelerates boolean reductions like `np.all()` and `np.any()` + +**Execution Paths:** +- **SimdFull**: Both arrays contiguous—maximum performance +- **SimdScalarRight/Left**: Broadcast operations—nearly as fast +- **SimdChunk**: Inner dimension contiguous—partial SIMD benefit +- **General**: Arbitrary strides—coordinate-based iteration (slowest) + +**Type Support:** +- All 12 NumSharp types are supported (with varying SIMD capabilities) +- Float/double have the best SIMD support +- Decimal requires scalar-only loops + +**Practical Guidance:** +- Keep arrays contiguous for best performance +- Watch for common IL pitfalls (stack balance, type conversions, signed/unsigned) +- Test thoroughly across types, layouts, and edge cases +- Benchmark to verify expected speedups + +This enables NumSharp to achieve performance competitive with native NumPy while maintaining the safety and productivity of managed .NET code. A call like `np.add(a, b)` invokes machine code specifically optimized for the exact types and array layouts involved—generated in milliseconds, cached forever, and executed in microseconds. diff --git a/docfx_project/articles/intro.md b/docs/website-src/docs/intro.md similarity index 100% rename from docfx_project/articles/intro.md rename to docs/website-src/docs/intro.md diff --git a/docs/website-src/docs/toc.yml b/docs/website-src/docs/toc.yml new file mode 100644 index 000000000..e3dd64def --- /dev/null +++ b/docs/website-src/docs/toc.yml @@ -0,0 +1,24 @@ +- name: Home + href: ../index.md +- name: Introduction + href: intro.md +- name: NDArray + href: NDArray.md +- name: Dtypes + href: dtypes.md +- name: Broadcasting + href: broadcasting.md +- name: Buffering & Memory + href: buffering.md +- name: NumPy Compliance & Compatibility + href: compliance.md +- name: Array API Standard + href: array-api-standard.md +- name: IL Generation + href: il-generation.md +- name: Extending Libraries + href: extensions/index.md + expanded: false + items: + - name: NumSharp.Bitmap + href: extensions/bitmap.md diff --git a/docs/website-src/filterConfig.yml b/docs/website-src/filterConfig.yml new file mode 100644 index 000000000..f57c15c4a --- /dev/null +++ b/docs/website-src/filterConfig.yml @@ -0,0 +1,40 @@ +# DocFX API Filter Configuration +# https://dotnet.github.io/docfx/docs/dotnet-api-docs.html#filter-apis +# +# Uncomment rules below to hide internal/utility types from API documentation. +# To enable: add "filter": "filterConfig.yml" to metadata section in docfx.json + +apiRules: + # Include all public APIs by default + - include: + hasAttribute: + uid: System.Runtime.CompilerServices.CompilerGeneratedAttribute + type: Member + exclude: true + + # Uncomment to hide utility namespaces from public docs: + # - exclude: + # uidRegex: ^NumSharp\.Utilities + # type: Namespace + + # - exclude: + # uidRegex: ^NumSharp\.Backends\.Unmanaged\.Pooling + # type: Namespace + + # Uncomment to hide internal helper classes: + # - exclude: + # uidRegex: Helper$ + # type: Class + + # - exclude: + # uidRegex: Extensions$ + # type: Class + + # Uncomment to hide specific types: + # - exclude: + # uidRegex: ^NumSharp\.Utilities\.InfoOf + # type: Class + + # - exclude: + # uidRegex: ^NumSharp\.Utilities\.Converts + # type: Class diff --git a/docs/website-src/images/numsharp.icon.svg b/docs/website-src/images/numsharp.icon.svg new file mode 100644 index 000000000..2be77864c --- /dev/null +++ b/docs/website-src/images/numsharp.icon.svg @@ -0,0 +1,238 @@ + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/website-src/images/numsharp.icon128.png b/docs/website-src/images/numsharp.icon128.png new file mode 100644 index 000000000..b8b689e00 Binary files /dev/null and b/docs/website-src/images/numsharp.icon128.png differ diff --git a/docs/website-src/images/python-csharp-comparision.png b/docs/website-src/images/python-csharp-comparision.png new file mode 100644 index 000000000..87d04283e Binary files /dev/null and b/docs/website-src/images/python-csharp-comparision.png differ diff --git a/docfx_project/images/rowWise_ColumnWise.png b/docs/website-src/images/rowWise_ColumnWise.png similarity index 100% rename from docfx_project/images/rowWise_ColumnWise.png rename to docs/website-src/images/rowWise_ColumnWise.png diff --git a/docs/website-src/index.md b/docs/website-src/index.md new file mode 100644 index 000000000..e387be570 --- /dev/null +++ b/docs/website-src/index.md @@ -0,0 +1,45 @@ +# Welcome to NumSharp + +NumSharp is a .NET port of Python's NumPy library, bringing powerful numerical computing to the .NET ecosystem. + +## Why NumSharp? + +- **NumPy API compatibility** - Feel right at home if you're coming from Python +- **High-performance NDArray** - Multi-dimensional arrays stored efficiently in unmanaged memory +- **Full .NET integration** - Works seamlessly with C#, F#, VB.NET, and other .NET languages +- **Part of the SciSharp ecosystem** - Works alongside TensorFlow.NET, ML.NET, and other ML libraries + +## Quick Start + +```bash +dotnet add package NumSharp +``` + +```csharp +using NumSharp; + +var a = np.array(new int[] { 1, 2, 3, 4, 5 }); +var b = np.arange(5); +var c = a + b; +Console.WriteLine(c); // [1, 3, 5, 7, 9] +``` + +## Features + +- **Array Creation** - `np.zeros`, `np.ones`, `np.arange`, `np.linspace`, and more +- **Array Manipulation** - Reshape, transpose, concatenate, stack operations +- **Math Operations** - Element-wise arithmetic, broadcasting, linear algebra +- **Slicing & Indexing** - NumPy-style slicing with views, not copies +- **Random Sampling** - Full numpy.random compatibility with seed/state matching +- **File I/O** - Load and save `.npy` and `.npz` files + +## Get Started + +- [Introduction](docs/intro.md) - Learn about NDArray, Shape, and Storage +- [NumPy Compliance](docs/compliance.md) - Compatibility status and roadmap +- [API Reference](api/index.md) - Full API documentation + +## Community + +- [GitHub Repository](https://github.com/SciSharp/NumSharp) - Star us, report issues, contribute +- [NuGet Package](https://www.nuget.org/packages/NumSharp) - Latest stable release diff --git a/docs/website-src/scripts/generate-llms-txt.sh b/docs/website-src/scripts/generate-llms-txt.sh new file mode 100644 index 000000000..a903a7b67 --- /dev/null +++ b/docs/website-src/scripts/generate-llms-txt.sh @@ -0,0 +1,402 @@ +#!/bin/bash +# Auto-generate llms.txt and llms-full.txt from actual documentation +# Parses toc.yml, markdown files, and API metadata - no hardcoded content + +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SRC_DIR="$(dirname "$SCRIPT_DIR")" +OUTPUT_DIR="${1:-$SRC_DIR/../website}" +SITE_URL="${2:-https://scisharp.github.io/NumSharp}" + +echo "Generating AI-friendly documentation files..." +echo "Source: $SRC_DIR" +echo "Output: $OUTPUT_DIR" + +# ============================================================================ +# Helper: Extract first paragraph from markdown (description) +# ============================================================================ +extract_description() { + local file="$1" + # Skip YAML frontmatter, get first non-empty paragraph + awk ' + BEGIN { in_frontmatter=0; found=0 } + /^---$/ { + if (NR==1) { in_frontmatter=1; next } + else { in_frontmatter=0; next } + } + in_frontmatter { next } + /^[ \t]*#/ { next } # Skip headers (with optional leading whitespace) + /^[ \t]*$/ { if (found) exit; next } # Empty line after content = done + /^[^-\*\|>]/ { + gsub(/\*\*/, ""); gsub(/\*/, ""); gsub(/`/, "") # Remove markdown formatting + gsub(/^[ \t]+/, "") # Trim leading whitespace + print; found=1 + } + ' "$file" | head -2 | tr '\n' ' ' | sed 's/ */ /g' | head -c 200 +} + +# ============================================================================ +# Helper: Extract title from markdown (first H1) +# ============================================================================ +extract_title() { + local file="$1" + # Handle optional leading whitespace before # + grep -m1 "^[ \t]*# " "$file" 2>/dev/null | sed 's/^[ \t]*# //' | sed 's/[ \t]*$//' || basename "$file" .md +} + +# ============================================================================ +# Helper: Parse toc.yml and generate links +# ============================================================================ +parse_toc() { + local toc_file="$1" + local base_url="$2" + local base_path="$3" + + if [ ! -f "$toc_file" ]; then + return + fi + + # Simple YAML parser for toc.yml format + awk -v base_url="$base_url" -v base_path="$base_path" ' + /^- name:/ { + name = $0 + gsub(/^- name: */, "", name) + gsub(/["'\'']/, "", name) + } + /^ href:/ { + href = $0 + gsub(/^ href: */, "", href) + gsub(/["'\'']/, "", href) + # Convert .md to .html + gsub(/\.md$/, ".html", href) + if (href !~ /^http/) { + href = base_url "/" base_path "/" href + } + print "- [" name "](" href ")" + } + ' "$toc_file" +} + +# ============================================================================ +# Generate llms.txt +# ============================================================================ +generate_llms_txt() { + local output="$OUTPUT_DIR/llms.txt" + + # Header from index.md or default + echo "# NumSharp" > "$output" + echo "" >> "$output" + + # Extract description from index.md + if [ -f "$SRC_DIR/index.md" ]; then + echo "> $(extract_description "$SRC_DIR/index.md")" >> "$output" + else + echo "> NumSharp is a .NET port of Python's NumPy library for numerical computing." >> "$output" + fi + echo "" >> "$output" + + # Quick start section + cat >> "$output" << 'QUICKSTART' +## Installation + +```bash +dotnet add package NumSharp +``` + +## Quick Start + +```csharp +using NumSharp; + +var a = np.array(new[] { 1, 2, 3, 4, 5 }); +var b = np.zeros((3, 4)); +var result = np.sum(a); +var slice = a["1:4"]; // Slicing returns views +``` + +QUICKSTART + + # Documentation section - parse docs/toc.yml + echo "## Documentation" >> "$output" + echo "" >> "$output" + + if [ -d "$SRC_DIR/docs" ]; then + for md_file in "$SRC_DIR/docs/"*.md; do + if [ -f "$md_file" ]; then + filename=$(basename "$md_file" .md) + title=$(extract_title "$md_file") + desc=$(extract_description "$md_file") + echo "- [$title](${SITE_URL}/docs/${filename}.html): $desc" >> "$output" + fi + done + elif [ -d "$SRC_DIR/articles" ]; then + for md_file in "$SRC_DIR/articles/"*.md; do + if [ -f "$md_file" ]; then + filename=$(basename "$md_file" .md) + title=$(extract_title "$md_file") + desc=$(extract_description "$md_file") + echo "- [$title](${SITE_URL}/articles/${filename}.html): $desc" >> "$output" + fi + done + fi + echo "" >> "$output" + + # API Reference section - parse generated API yml files + echo "## API Reference" >> "$output" + echo "" >> "$output" + + # Find key API types from generated yml or fallback + if [ -d "$SRC_DIR/api" ]; then + # Look for key types in yml files + for yml_file in "$SRC_DIR/api/"*.yml; do + if [ -f "$yml_file" ]; then + # Extract uid and summary from yml + uid=$(grep -m1 "^uid:" "$yml_file" 2>/dev/null | sed 's/uid: *//' || true) + summary=$(grep -m1 "summary:" "$yml_file" 2>/dev/null | sed 's/summary: *//' | sed 's/^"//' | sed 's/"$//' | head -c 100 || true) + + if [ -n "$uid" ] && [[ "$uid" == NumSharp* ]]; then + # Only include top-level types, not nested + if [[ "$uid" =~ ^NumSharp\.[A-Z][a-zA-Z0-9]*$ ]] || [[ "$uid" == "NumSharp" ]]; then + html_name=$(echo "$uid" | sed 's/\./\./g') + if [ -n "$summary" ]; then + echo "- [@$uid](${SITE_URL}/api/${uid}.html): $summary" >> "$output" + else + echo "- [@$uid](${SITE_URL}/api/${uid}.html)" >> "$output" + fi + fi + fi + fi + done 2>/dev/null | head -20 + fi + + # If no API yml found, add placeholder links + if ! grep -q "api/NumSharp" "$output" 2>/dev/null; then + cat >> "$output" << 'API_FALLBACK' +- [NumSharp.NDArray](https://scisharp.github.io/NumSharp/api/NumSharp.NDArray.html): Main n-dimensional array type +- [NumSharp.np](https://scisharp.github.io/NumSharp/api/NumSharp.np.html): Static NumPy-style API +- [NumSharp.Shape](https://scisharp.github.io/NumSharp/api/NumSharp.Shape.html): Array dimensions and strides +API_FALLBACK + fi + echo "" >> "$output" + + # Data types section - extract from codebase or use known types + cat >> "$output" << 'TYPES' +## Supported Data Types + +bool, byte, short, ushort, int, uint, long, ulong, float, double, decimal, char + +## Key Concepts + +- **NDArray**: Multi-dimensional array in unmanaged memory +- **Shape**: Dimensions and strides for offset calculation +- **Broadcasting**: Arrays with different shapes operate element-wise +- **Views**: Slicing returns views (shared memory), use `.copy()` for copies + +TYPES + + # Optional section + echo "## Optional" >> "$output" + echo "" >> "$output" + echo "- [Full API Reference](${SITE_URL}/api/): Complete class and method documentation" >> "$output" + echo "- [GitHub Repository](https://github.com/SciSharp/NumSharp): Source code and issues" >> "$output" + echo "- [NuGet Package](https://www.nuget.org/packages/NumSharp): Latest releases" >> "$output" + + echo "Generated: $output ($(wc -l < "$output") lines)" +} + +# ============================================================================ +# Generate llms-full.txt +# ============================================================================ +generate_llms_full_txt() { + local output="$OUTPUT_DIR/llms-full.txt" + + echo "# NumSharp - Complete Documentation" > "$output" + echo "" >> "$output" + echo "> This file contains the complete NumSharp documentation for AI/LLM ingestion." >> "$output" + echo "> Auto-generated from source markdown files." >> "$output" + echo "" >> "$output" + echo "---" >> "$output" + echo "" >> "$output" + + # Table of contents + echo "## Table of Contents" >> "$output" + echo "" >> "$output" + + local toc_num=1 + local docs_dir="$SRC_DIR/docs" + [ ! -d "$docs_dir" ] && docs_dir="$SRC_DIR/articles" + + if [ -d "$docs_dir" ]; then + for md_file in "$docs_dir/"*.md; do + if [ -f "$md_file" ] && [[ "$(basename "$md_file")" != "toc.yml" ]]; then + title=$(extract_title "$md_file") + echo "$toc_num. $title" >> "$output" + ((toc_num++)) + fi + done + fi + echo "" >> "$output" + echo "---" >> "$output" + + # Concatenate all documentation files + if [ -d "$docs_dir" ]; then + for md_file in "$docs_dir/"*.md; do + if [ -f "$md_file" ] && [[ "$(basename "$md_file")" != "toc.yml" ]]; then + echo "" >> "$output" + # Strip YAML frontmatter and include content + awk ' + BEGIN { in_frontmatter=0; skip_first=1 } + /^---$/ { + if (NR==1) { in_frontmatter=1; next } + else { in_frontmatter=0; next } + } + in_frontmatter { next } + { print } + ' "$md_file" >> "$output" + echo "" >> "$output" + echo "---" >> "$output" + fi + done + fi + + # Add API summary from yml files if available + echo "" >> "$output" + echo "# API Quick Reference" >> "$output" + echo "" >> "$output" + + if [ -d "$SRC_DIR/api" ] && ls "$SRC_DIR/api/"*.yml >/dev/null 2>&1; then + echo "## Namespaces and Types" >> "$output" + echo "" >> "$output" + + # Parse yml files for type information + for yml_file in "$SRC_DIR/api/"*.yml; do + if [ -f "$yml_file" ]; then + # Extract namespace/class info + awk ' + /^uid:/ { uid = $2 } + /^type:/ { type = $2 } + /^summary:/ { + summary = $0 + gsub(/^summary: *["'\'']?/, "", summary) + gsub(/["'\'']$/, "", summary) + } + END { + if (uid && type) { + if (type == "Namespace" || type == "Class" || type == "Struct") { + printf "- **%s** (%s): %s\n", uid, type, summary + } + } + } + ' "$yml_file" 2>/dev/null + fi + done | sort | uniq | head -50 >> "$output" + else + # Fallback: Include common API patterns + cat >> "$output" << 'API_PATTERNS' +## Common API Patterns + +### Array Creation (np.*) +- `np.array(data)` - Create from existing data +- `np.zeros(shape)`, `np.ones(shape)`, `np.empty(shape)` - Initialize arrays +- `np.arange(start, stop, step)` - Range of values +- `np.linspace(start, stop, num)` - Evenly spaced values +- `np.eye(n)` - Identity matrix +- `np.random.rand(shape)`, `np.random.randn(shape)` - Random arrays + +### Math Operations +- `np.sum(a)`, `np.mean(a)`, `np.std(a)` - Statistics +- `np.dot(a, b)`, `np.matmul(a, b)` - Linear algebra +- `np.sqrt(a)`, `np.exp(a)`, `np.log(a)` - Element-wise math +- `+`, `-`, `*`, `/`, `%` - Arithmetic operators (with broadcasting) + +### Array Manipulation +- `np.reshape(a, shape)`, `a.reshape(shape)` - Change shape +- `np.transpose(a)`, `a.T` - Transpose +- `np.concatenate([a, b])`, `np.stack([a, b])` - Join arrays +- `np.squeeze(a)`, `np.expand_dims(a, axis)` - Dimension changes + +### Indexing +- `a[i]`, `a[i, j]` - Element access +- `a["start:stop"]`, `a["::step"]` - Slicing (returns view) +- `a[boolArray]` - Boolean mask +- `a[intArray]` - Fancy indexing +API_PATTERNS + fi + + echo "" >> "$output" + echo "---" >> "$output" + echo "" >> "$output" + echo "*Auto-generated from NumSharp documentation source files*" >> "$output" + + echo "Generated: $output ($(wc -l < "$output") lines)" +} + +# ============================================================================ +# Generate robots.txt +# ============================================================================ +generate_robots_txt() { + local output="$OUTPUT_DIR/robots.txt" + + cat > "$output" << ROBOTS +# NumSharp Documentation - robots.txt +# Auto-generated - Allow all crawlers including AI + +User-agent: * +Allow: / + +# AI Crawlers - explicitly allowed +User-agent: GPTBot +Allow: / + +User-agent: ChatGPT-User +Allow: / + +User-agent: Claude-Web +Allow: / + +User-agent: ClaudeBot +Allow: / + +User-agent: Anthropic-AI +Allow: / + +User-agent: Google-Extended +Allow: / + +User-agent: PerplexityBot +Allow: / + +User-agent: Amazonbot +Allow: / + +User-agent: Bytespider +Allow: / + +User-agent: CCBot +Allow: / + +# AI-friendly documentation files +# ${SITE_URL}/llms.txt - Curated summary +# ${SITE_URL}/llms-full.txt - Complete documentation + +Sitemap: ${SITE_URL}/sitemap.xml +ROBOTS + + echo "Generated: $output" +} + +# ============================================================================ +# Main +# ============================================================================ + +mkdir -p "$OUTPUT_DIR" + +generate_llms_txt +generate_llms_full_txt +generate_robots_txt + +echo "" +echo "AI-friendly documentation generation complete!" +echo "Files created in $OUTPUT_DIR:" +ls -la "$OUTPUT_DIR/llms.txt" "$OUTPUT_DIR/llms-full.txt" "$OUTPUT_DIR/robots.txt" 2>/dev/null | awk '{print " " $NF " (" $5 " bytes)"}' diff --git a/docs/website-src/templates/numsharp/public/main.css b/docs/website-src/templates/numsharp/public/main.css new file mode 100644 index 000000000..49498b8cc --- /dev/null +++ b/docs/website-src/templates/numsharp/public/main.css @@ -0,0 +1,85 @@ +/* NumSharp DocFX Custom Styles + * https://dotnet.github.io/docfx/docs/template.html + * + * The modern template uses Bootstrap 5.3 CSS variables. + * Override variables here to customize the theme. + */ + +:root { + /* Primary brand color (NumSharp blue) */ + --bs-primary: #0d6efd; + --bs-primary-rgb: 13, 110, 253; + + /* Link colors */ + --bs-link-color: #0d6efd; + --bs-link-hover-color: #0a58ca; +} + +/* Dark mode overrides */ +[data-bs-theme="dark"] { + --bs-link-color: #6ea8fe; + --bs-link-hover-color: #8bb9fe; +} + +/* Logo sizing */ +#logo { + height: 32px; + width: auto; +} + +/* Footer styling */ +.footer { + border-top: 1px solid var(--bs-border-color); + padding: 1rem 0; + font-size: 0.875rem; +} + +.footer a { + color: var(--bs-link-color); + text-decoration: none; +} + +.footer a:hover { + text-decoration: underline; +} + +/* Code block enhancements */ +pre code { + font-size: 0.875em; +} + +/* Table of contents sticky positioning */ +@media (min-width: 992px) { + .sticky-top { + top: 80px; + } +} + +/* API documentation improvements */ +.api-member { + margin-bottom: 1.5rem; +} + +.api-member h4 { + border-bottom: 1px solid var(--bs-border-color); + padding-bottom: 0.5rem; +} + +/* Syntax highlighting improvements for C# */ +.hljs-keyword { + font-weight: 600; +} + +/* Print styles */ +@media print { + .navbar, + .toc, + .affix, + .footer { + display: none !important; + } + + .article { + max-width: 100% !important; + } +} diff --git a/docs/website-src/templates/numsharp/public/main.js b/docs/website-src/templates/numsharp/public/main.js new file mode 100644 index 000000000..6b5cc3869 --- /dev/null +++ b/docs/website-src/templates/numsharp/public/main.js @@ -0,0 +1,32 @@ +// NumSharp DocFX Template Customization +// https://dotnet.github.io/docfx/docs/template.html + +export default { + // Icon links displayed in the navbar (top-right) + iconLinks: [ + { + icon: 'github', + href: 'https://github.com/SciSharp/NumSharp', + title: 'GitHub' + }, + { + icon: 'box-seam', + href: 'https://www.nuget.org/packages/NumSharp', + title: 'NuGet' + } + ], + + // Default theme: 'light', 'dark', or 'auto' (system preference) + // defaultTheme: 'auto', + + // Startup script (runs when page loads) + start: () => { + // Add any custom initialization here + // console.log('NumSharp docs loaded'); + }, + + // Customize syntax highlighting (highlight.js) + // configureHljs: (hljs) => { + // // Register additional languages or customize + // } +} diff --git a/docs/website-src/toc.yml b/docs/website-src/toc.yml new file mode 100644 index 000000000..dd59c9426 --- /dev/null +++ b/docs/website-src/toc.yml @@ -0,0 +1,5 @@ +- name: Docs + href: docs/ + homepage: docs/intro.md +- name: API + href: api/ diff --git a/docs/_config.yml b/docs/website/_config.yml similarity index 100% rename from docs/_config.yml rename to docs/website/_config.yml diff --git a/docs/api/.manifest b/docs/website/api/.manifest similarity index 100% rename from docs/api/.manifest rename to docs/website/api/.manifest diff --git a/docs/website/api/DecimalMath.DecimalEx.html b/docs/website/api/DecimalMath.DecimalEx.html new file mode 100644 index 000000000..6dbbeedff --- /dev/null +++ b/docs/website/api/DecimalMath.DecimalEx.html @@ -0,0 +1,1684 @@ + + + + + Class DecimalEx | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class DecimalEx +

+ +
+
Namespace
DecimalMath
+
Assembly
NumSharp.dll
+
+ +

Contains mathematical operations performed in Decimal precision.

+
+
+ +
+
public static class DecimalEx
+
+ + + + +
+
Inheritance
+
+ +
DecimalEx
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Fields +

+ + + +

+ E + +

+ +

The e constant, also known as "Euler's number" or "Napier's constant"

+
+
+ +
+
public const decimal E = 2.7182818284590452353602874714
+
+ + + + +

Field Value

+
+
decimal
+
+
+ + + + + +

Remarks

+

Full value is 2.718281828459045235360287471352662497757, +see http://mathworld.wolfram.com/e.html

+
+ + + + + +

+ Ln10 + +

+ +

The value of the natural logarithm of 10.

+
+
+ +
+
public const decimal Ln10 = 2.3025850929940456840179914547
+
+ + + + +

Field Value

+
+
decimal
+
+
+ + + + + +

Remarks

+

Full value is: 2.30258509299404568401799145468436420760110148862877297603332790096757 +From: http://oeis.org/A002392/constant

+
+ + + + + +

+ Ln2 + +

+ +

The value of the natural logarithm of 2.

+
+
+ +
+
public const decimal Ln2 = 0.6931471805599453094172321215
+
+ + + + +

Field Value

+
+
decimal
+
+
+ + + + + +

Remarks

+

Full value is: .693147180559945309417232121458176568075500134360255254120680009493393621969694715605863326996418687 +From: http://oeis.org/A002162/constant

+
+ + + + + +

+ Pi + +

+ +

The pi (π) constant. Pi radians is equivalent to 180 degrees.

+
+
+ +
+
public const decimal Pi = 3.1415926535897932384626433833
+
+ + + + +

Field Value

+
+
decimal
+
+
+ + + + + +

Remarks

+ + + + + + +

+ PiHalf + +

+ +

π/2 - in radians is equivalent to 90 degrees.

+
+
+ +
+
public const decimal PiHalf = 1.5707963267948966192313216916
+
+ + + + +

Field Value

+
+
decimal
+
+
+ + + + + + + + + + +

+ PiQuarter + +

+ +

π/4 - in radians is equivalent to 45 degrees.

+
+
+ +
+
public const decimal PiQuarter = 0.7853981633974483096156608458
+
+ + + + +

Field Value

+
+
decimal
+
+
+ + + + + + + + + + +

+ PiTwelfth + +

+ +

π/12 - in radians is equivalent to 15 degrees.

+
+
+ +
+
public const decimal PiTwelfth = 0.2617993877991494365385536153
+
+ + + + +

Field Value

+
+
decimal
+
+
+ + + + + + + + + + +

+ SmallestNonZeroDec + +

+ +

Smallest non-zero decimal value.

+
+
+ +
+
public const decimal SmallestNonZeroDec = 0.0000000000000000000000000001
+
+ + + + +

Field Value

+
+
decimal
+
+
+ + + + + + + + + + +

+ TwoPi + +

+ +

2π - in radians is equivalent to 360 degrees.

+
+
+ +
+
public const decimal TwoPi = 6.2831853071795864769252867666
+
+ + + + +

Field Value

+
+
decimal
+
+
+ + + + + + + + + +

Methods +

+ + + + +

+ ACos(decimal) + +

+ +

Returns the angle whose cosine is the specified number.

+
+
+ +
+
public static decimal ACos(decimal z)
+
+ +

Parameters

+
+
z decimal
+

A number representing a cosine, where -1 ≤d≤ 1.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ AGMean(decimal, decimal) + +

+ +

Computes arithmetic-geometric mean which is the convergence of the +series of the arithmetic and geometric means and their mean values.

+
+
+ +
+
public static decimal AGMean(decimal x, decimal y)
+
+ +

Parameters

+
+
x decimal
+

A number.

+
+
y decimal
+

A number.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + +

Remarks

+

See http://en.wikipedia.org/wiki/Arithmetic-geometric_mean +Originally implemented to try to get a fast approximation of the +natural logarithm: http://en.wikipedia.org/wiki/Natural_logarithm#High_precision +But it didn't yield a precise enough answer.

+
+ + + + + + +

+ ASin(decimal) + +

+ +

Returns the angle whose sine is the specified number.

+
+
+ +
+
public static decimal ASin(decimal z)
+
+ +

Parameters

+
+
z decimal
+

A number representing a sine, where -1 ≤d≤ 1.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + +

Remarks

+

See http://en.wikipedia.org/wiki/Inverse_trigonometric_function +and http://mathworld.wolfram.com/InverseSine.html +I originally used the Taylor series for ASin, but it was extremely slow +around -1 and 1 (millions of iterations) and still ends up being less +accurate than deriving from the ATan function.

+
+ + + + + + +

+ ATan(decimal) + +

+ +

Returns the angle whose tangent is the quotient of two specified numbers.

+
+
+ +
+
public static decimal ATan(decimal x)
+
+ +

Parameters

+
+
x decimal
+

A number representing a tangent.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + +

Remarks

+

See http://mathworld.wolfram.com/InverseTangent.html for faster converging +series from Euler that was used here.

+
+ + + + + + +

+ ATan2(decimal, decimal) + +

+ +

Returns the angle whose tangent is the quotient of two specified numbers.

+
+
+ +
+
public static decimal ATan2(decimal y, decimal x)
+
+ +

Parameters

+
+
y decimal
+

The y coordinate of a point.

+
+
x decimal
+

The x coordinate of a point.

+
+
+ +

Returns

+
+
decimal
+

An angle, θ, measured in radians, such that -π≤θ≤π, and tan(θ) = y / x, +where (x, y) is a point in the Cartesian plane. Observe the following: +For (x, y) in quadrant 1, 0 < θ < π/2. +For (x, y) in quadrant 2, π/2 < θ ≤ π. +For (x, y) in quadrant 3, -π < θ < -π/2. +For (x, y) in quadrant 4, -π/2 < θ < 0.

+
+
+ + + + + + + + + + + + + +

+ Abs(decimal) + +

+ +
+
+ +
+
public static decimal Abs(decimal a)
+
+ +

Parameters

+
+
a decimal
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ Average(params decimal[]) + +

+ +

Calculates the average of the supplied numbers.

+
+
+ +
+
public static decimal Average(params decimal[] values)
+
+ +

Parameters

+
+
values decimal[]
+

The numbers to average.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + +

Remarks

+

Simply uses LINQ's Average function, but switches to a potentially less +accurate method of summing each value divided by the number of values.

+
+ + + + + + +

+ Ceiling(decimal, int) + +

+ +

Returns the ceiling of a Decimal value at the given number of digits.

+
+
+ +
+
public static decimal Ceiling(decimal value, int places = 0)
+
+ +

Parameters

+
+
value decimal
+

A decimal value.

+
+
places int
+

An integer representing the maximum number of digits +after the decimal point to end up with.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ Cos(decimal) + +

+ +

Returns the cosine of the specified angle.

+
+
+ +
+
public static decimal Cos(decimal x)
+
+ +

Parameters

+
+
x decimal
+

An angle, measured in radians.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + +

Remarks

+

Uses a Taylor series to calculate sine. See +http://en.wikipedia.org/wiki/Trigonometric_functions for details.

+
+ + + + + + +

+ Exp(decimal) + +

+ +

Returns e raised to the specified power.

+
+
+ +
+
public static decimal Exp(decimal d)
+
+ +

Parameters

+
+
d decimal
+

A number specifying a power.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ Factorial(decimal) + +

+ +

Returns the factorial of a number n expressed as n!. Factorial is +calculated as follows: n * (n - 1) * (n - 2) * ... * 1

+
+
+ +
+
public static decimal Factorial(decimal n)
+
+ +

Parameters

+
+
n decimal
+

An integer.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + +

Remarks

+

Only supports non-negative integers.

+
+ + + + + + +

+ Floor(decimal, int) + +

+ +

Returns the floor of a Decimal value at the given number of digits.

+
+
+ +
+
public static decimal Floor(decimal value, int places = 0)
+
+ +

Parameters

+
+
value decimal
+

A decimal value.

+
+
places int
+

An integer representing the maximum number of digits +after the decimal point to end up with.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ GCF(decimal, decimal) + +

+ +

Calculates the greatest common factor of a and b to the highest level of +precision represented by either number.

+
+
+ +
+
public static decimal GCF(decimal a, decimal b)
+
+ +

Parameters

+
+
a decimal
+
+
b decimal
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + +

Remarks

+

If either number is not an integer, the factor sought will be at the +same precision as the most precise value. +For example, 1.2 and 0.42 will yield 0.06.

+
+ + + + + + +

+ GCF(decimal, decimal, params decimal[]) + +

+ +

Gets the greatest common factor of three or more numbers.

+
+
+ +
+
public static decimal GCF(decimal a, decimal b, params decimal[] values)
+
+ +

Parameters

+
+
a decimal
+
+
b decimal
+
+
values decimal[]
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ GetDecimalPlaces(decimal, bool) + +

+ +

Gets the number of decimal places in a decimal value.

+
+
+ +
+
public static int GetDecimalPlaces(decimal dec, bool countTrailingZeros)
+
+ +

Parameters

+
+
dec decimal
+
+
countTrailingZeros bool
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + +

Remarks

+

Started with something found here: http://stackoverflow.com/a/6092298/856595

+
+ + + + + + +

+ Log(decimal) + +

+ +

Returns the natural (base e) logarithm of a specified number.

+
+
+ +
+
public static decimal Log(decimal d)
+
+ +

Parameters

+
+
d decimal
+

A number whose logarithm is to be found.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + +

Remarks

+

I'm still not satisfied with the speed. I tried several different +algorithms that you can find in a historical version of this +source file. The one I settled on was the best of mediocrity.

+
+ + + + + + +

+ Log(decimal, decimal) + +

+ +

Returns the logarithm of a specified number in a specified base.

+
+
+ +
+
public static decimal Log(decimal d, decimal newBase)
+
+ +

Parameters

+
+
d decimal
+

A number whose logarithm is to be found.

+
+
newBase decimal
+

The base of the logarithm.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + +

Remarks

+

This is a relatively naive implementation that simply divides the +natural log of d by the natural log of the base.

+
+ + + + + + +

+ Log10(decimal) + +

+ +

Returns the base 10 logarithm of a specified number.

+
+
+ +
+
public static decimal Log10(decimal d)
+
+ +

Parameters

+
+
d decimal
+

A number whose logarithm is to be found.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ Log2(decimal) + +

+ +

Returns the base 2 logarithm of a specified number.

+
+
+ +
+
public static decimal Log2(decimal d)
+
+ +

Parameters

+
+
d decimal
+

A number whose logarithm is to be found.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ NormalizeAngle(decimal) + +

+ +

Normalizes an angle in radians to the 0 to 2Pi interval.

+
+
+ +
+
public static decimal NormalizeAngle(decimal radians)
+
+ +

Parameters

+
+
radians decimal
+

Angle in radians.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ NormalizeAngleDeg(decimal) + +

+ +

Normalizes an angle in degrees to the 0 to 360 degree interval.

+
+
+ +
+
public static decimal NormalizeAngleDeg(decimal degrees)
+
+ +

Parameters

+
+
degrees decimal
+

Angle in degrees.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ Pow(decimal, decimal) + +

+ +

Returns a specified number raised to the specified power.

+
+
+ +
+
public static decimal Pow(decimal x, decimal y)
+
+ +

Parameters

+
+
x decimal
+

A number to be raised to a power.

+
+
y decimal
+

A number that specifies a power.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ Remainder(decimal, decimal) + +

+ +

Gets the remainder of one number divided by another number in such a way as to retain maximum precision.

+
+
+ +
+
public static decimal Remainder(decimal d1, decimal d2)
+
+ +

Parameters

+
+
d1 decimal
+
+
d2 decimal
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ Sin(decimal) + +

+ +

Returns the sine of the specified angle.

+
+
+ +
+
public static decimal Sin(decimal x)
+
+ +

Parameters

+
+
x decimal
+

An angle, measured in radians.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + +

Remarks

+

Uses a Taylor series to calculate sine. See +http://en.wikipedia.org/wiki/Trigonometric_functions for details.

+
+ + + + + + +

+ SolveQuadratic(decimal, decimal, decimal) + +

+ +

Uses the quadratic formula to factor and solve the equation ax^2 + bx + c = 0

+
+
+ +
+
public static decimal[] SolveQuadratic(decimal a, decimal b, decimal c)
+
+ +

Parameters

+
+
a decimal
+

The coefficient of x^2.

+
+
b decimal
+

The coefficient of x.

+
+
c decimal
+

The constant.

+
+
+ +

Returns

+
+
decimal[]
+
+
+ + + + + + + +

Remarks

+

Will return empty results where there is no solution and for complex solutions. +See http://www.wikihow.com/Factor-Second-Degree-Polynomials-%28Quadratic-Equations%29

+
+ + + + + + +

+ Sqrt(decimal) + +

+ +

Returns the square root of a given number.

+
+
+ +
+
public static decimal Sqrt(decimal s)
+
+ +

Parameters

+
+
s decimal
+

A non-negative number.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + +

Remarks

+

Uses an implementation of the "Babylonian Method". +See http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method

+
+ + + + + + +

+ Tan(decimal) + +

+ +

Returns the tangent of the specified angle.

+
+
+ +
+
public static decimal Tan(decimal radians)
+
+ +

Parameters

+
+
radians decimal
+

An angle, measured in radians.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + +

Remarks

+

Uses a Taylor series to calculate sine. See +http://en.wikipedia.org/wiki/Trigonometric_functions for details.

+
+ + + + + + +

+ ToDeg(decimal) + +

+ +

Converts radians to degrees. (π radians = 180 degrees)

+
+
+ +
+
public static decimal ToDeg(decimal radians)
+
+ +

Parameters

+
+
radians decimal
+

The radians to convert.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToRad(decimal) + +

+ +

Converts degrees to radians. (π radians = 180 degrees)

+
+
+ +
+
public static decimal ToRad(decimal degrees)
+
+ +

Parameters

+
+
degrees decimal
+

The degrees to convert.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/DecimalMath.html b/docs/website/api/DecimalMath.html new file mode 100644 index 000000000..4ec48aecb --- /dev/null +++ b/docs/website/api/DecimalMath.html @@ -0,0 +1,127 @@ + + + + + Namespace DecimalMath | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ +

Namespace DecimalMath

+
+
+
+ +

+Classes +

+
+
DecimalEx
+

Contains mathematical operations performed in Decimal precision.

+
+
+ + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.AxisOutOfRangeException.html b/docs/website/api/NumSharp.AxisOutOfRangeException.html new file mode 100644 index 000000000..1ffa7f84c --- /dev/null +++ b/docs/website/api/NumSharp.AxisOutOfRangeException.html @@ -0,0 +1,356 @@ + + + + + Class AxisOutOfRangeException | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class AxisOutOfRangeException +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class AxisOutOfRangeException : ArgumentOutOfRangeException, ISerializable, INumSharpException
+
+ + + + +
+
Inheritance
+
+ + + + + +
AxisOutOfRangeException
+
+
+ +
+
Implements
+
+ + +
+
+ + +
+
Inherited Members
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ AxisOutOfRangeException() + +

+ +
+
+ +
+
public AxisOutOfRangeException()
+
+ + + + + + + + + + + + + + + +

+ AxisOutOfRangeException(int, int) + +

+ +
+
+ +
+
public AxisOutOfRangeException(int ndim, int axis)
+
+ +

Parameters

+
+
ndim int
+
+
axis int
+
+
+ + + + + + + + + + + + + + +

+ AxisOutOfRangeException(string) + +

+ +
+
+ +
+
public AxisOutOfRangeException(string message)
+
+ +

Parameters

+
+
message string
+
+
+ + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.BackendType.html b/docs/website/api/NumSharp.BackendType.html new file mode 100644 index 000000000..f548a6ea4 --- /dev/null +++ b/docs/website/api/NumSharp.BackendType.html @@ -0,0 +1,157 @@ + + + + + Enum BackendType | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + + +

+Enum BackendType +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public enum BackendType
+
+ + + + + + + + +
+
Extension Methods
+
+ +
+ +

Fields +

+
+
Default = 0
+ +

Pure micro-optimized C# implementation.

+
+
+ + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Backends.BackendFactory.html b/docs/website/api/NumSharp.Backends.BackendFactory.html new file mode 100644 index 000000000..bbc7ac022 --- /dev/null +++ b/docs/website/api/NumSharp.Backends.BackendFactory.html @@ -0,0 +1,258 @@ + + + + + Class BackendFactory | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class BackendFactory +

+ +
+
Namespace
NumSharp.Backends
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class BackendFactory
+
+ + + + +
+
Inheritance
+
+ +
BackendFactory
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Methods +

+ + + + +

+ GetEngine(BackendType) + +

+ +
+
+ +
+
public static TensorEngine GetEngine(BackendType backendType = BackendType.Default)
+
+ +

Parameters

+
+
backendType BackendType
+
+
+ +

Returns

+
+
TensorEngine
+
+
+ + + + + + + + + + + + + +

+ GetEngine<T>() + +

+ +
+
+ +
+
public static TensorEngine GetEngine<T>() where T : TensorEngine, new()
+
+ + +

Returns

+
+
TensorEngine
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Backends.DefaultEngine.html b/docs/website/api/NumSharp.Backends.DefaultEngine.html new file mode 100644 index 000000000..ea847f04a --- /dev/null +++ b/docs/website/api/NumSharp.Backends.DefaultEngine.html @@ -0,0 +1,8696 @@ + + + + + Class DefaultEngine | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class DefaultEngine +

+ +
+
Namespace
NumSharp.Backends
+
Assembly
NumSharp.dll
+
+ +

Default Tensor Engine implemented in pure micro-optimized C#.

+
+
+ +
+
public class DefaultEngine : TensorEngine
+
+ + + + +
+
Inheritance
+
+ + +
DefaultEngine
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Fields +

+ + + +

+ ParallelAbove + +

+ +

The threshold atwhich after n-items in an array, computation will use Parallel.For

+
+
+ +
+
public const int ParallelAbove = 84999
+
+ + + + +

Field Value

+
+
int
+
+
+ + + + + + + + + +

Methods +

+ + + + +

+ ACos(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray ACos(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ACos(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray ACos(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AMax(in NDArray, int, Type, bool) + +

+ +
+
+ +
+
public override NDArray AMax(in NDArray nd, int axis, Type dtype, bool keepdims = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int
+
+
dtype Type
+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AMax(in NDArray, int?, NPTypeCode?, bool) + +

+ +
+
+ +
+
public override NDArray AMax(in NDArray nd, int? axis = null, NPTypeCode? typeCode = null, bool keepdims = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int?
+
+
typeCode NPTypeCode?
+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AMaxElementwise<T>(NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public T AMaxElementwise<T>(NDArray arr, NPTypeCode? typeCode) where T : unmanaged
+
+ +

Parameters

+
+
arr NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ AMin(in NDArray, int, Type, bool) + +

+ +
+
+ +
+
public override NDArray AMin(in NDArray nd, int axis, Type dtype, bool keepdims = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int
+
+
dtype Type
+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AMin(in NDArray, int?, NPTypeCode?, bool) + +

+ +
+
+ +
+
public override NDArray AMin(in NDArray nd, int? axis = null, NPTypeCode? typeCode = null, bool keepdims = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int?
+
+
typeCode NPTypeCode?
+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AMinElementwise<T>(NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public T AMinElementwise<T>(NDArray arr, NPTypeCode? typeCode) where T : unmanaged
+
+ +

Parameters

+
+
arr NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ ASin(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray ASin(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ASin(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray ASin(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ATan(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray ATan(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ATan(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray ATan(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ATan2(in NDArray, in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray ATan2(in NDArray y, in NDArray x, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
y NDArray
+
+
x NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ATan2(in NDArray, in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray ATan2(in NDArray y, in NDArray x, Type dtype)
+
+ +

Parameters

+
+
y NDArray
+
+
x NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Abs(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Abs(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Abs(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Abs(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Add(in NDArray, in NDArray) + +

+ +
+
+ +
+
public override NDArray Add(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AddBoolean(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray AddBoolean(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AddByte(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray AddByte(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AddChar(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray AddChar(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AddDecimal(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray AddDecimal(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AddDouble(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray AddDouble(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AddInt16(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray AddInt16(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AddInt32(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray AddInt32(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AddInt64(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray AddInt64(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AddSingle(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray AddSingle(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AddUInt16(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray AddUInt16(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AddUInt32(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray AddUInt32(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AddUInt64(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray AddUInt64(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ All(NDArray) + +

+ +

Test whether all array elements evaluate to True.

+
+
+ +
+
public override bool All(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ All(NDArray, int) + +

+ +

Test whether all array elements along a given axis evaluate to True.

+
+
+ +
+
public override NDArray<bool> All(NDArray nd, int axis)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int
+
+
+ +

Returns

+
+
NDArray<bool>
+

Returns an array of bools

+
+
+ + + + + + + + + + + + + +

+ AllClose(NDArray, NDArray, double, double, bool) + +

+ +

Returns True if two arrays are element-wise equal within a tolerance. +The tolerance values are positive, typically very small numbers.The

+

relative difference (rtol * abs(b)) and the absolute difference +atol are added together to compare against the absolute difference +between a and b. +If either array contains one or more NaNs, False is returned. +Infs are treated as equal if they are in the same place and of the same +sign in both arrays.

+
+
+ +
+
public override bool AllClose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false)
+
+ +

Parameters

+
+
a NDArray
+
+
b NDArray
+

Input array to compare with a.

+
+
rtol double
+

The relative tolerance parameter(see Notes)

+
+
atol double
+

The absolute tolerance parameter(see Notes)

+
+
equal_nan bool
+

Whether to compare NaN's as equal. If True, NaN's in a will be +considered equal to NaN's in b in the output array.

+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ AreBroadcastable(params NDArray[]) + +

+ +
+
+ +
+
public static bool AreBroadcastable(params NDArray[] arrays)
+
+ +

Parameters

+
+
arrays NDArray[]
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ AreBroadcastable(params Shape[]) + +

+ +
+
+ +
+
public static bool AreBroadcastable(params Shape[] shapes)
+
+ +

Parameters

+
+
shapes Shape[]
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ AreBroadcastable(params int[][]) + +

+ +
+
+ +
+
public static bool AreBroadcastable(params int[][] shapes)
+
+ +

Parameters

+
+
shapes int[][]
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ ArgMax(in NDArray) + +

+ +
+
+ +
+
public override NDArray ArgMax(in NDArray a)
+
+ +

Parameters

+
+
a NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ArgMax(in NDArray, int) + +

+ +
+
+ +
+
public override NDArray ArgMax(in NDArray a, int axis)
+
+ +

Parameters

+
+
a NDArray
+
+
axis int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ArgMaxElementwise(NDArray) + +

+ +
+
+ +
+
public int ArgMaxElementwise(NDArray arr)
+
+ +

Parameters

+
+
arr NDArray
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ArgMin(in NDArray) + +

+ +
+
+ +
+
public override NDArray ArgMin(in NDArray a)
+
+ +

Parameters

+
+
a NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ArgMin(in NDArray, int) + +

+ +
+
+ +
+
public override NDArray ArgMin(in NDArray a, int axis)
+
+ +

Parameters

+
+
a NDArray
+
+
axis int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ArgMinElementwise(NDArray) + +

+ +
+
+ +
+
public int ArgMinElementwise(NDArray arr)
+
+ +

Parameters

+
+
arr NDArray
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ Broadcast(params NDArray[]) + +

+ +
+
+ +
+
public static NDArray[] Broadcast(params NDArray[] arrays)
+
+ +

Parameters

+
+
arrays NDArray[]
+
+
+ +

Returns

+
+
NDArray[]
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ Broadcast(Shape, Shape) + +

+ +
+
+ +
+
public static (Shape LeftShape, Shape RightShape) Broadcast(Shape leftShape, Shape rightShape)
+
+ +

Parameters

+
+
leftShape Shape
+
+
rightShape Shape
+
+
+ +

Returns

+
+
(Shape LeftShape, Shape RightShape)
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ Broadcast(params Shape[]) + +

+ +
+
+ +
+
public static Shape[] Broadcast(params Shape[] shapes)
+
+ +

Parameters

+
+
shapes Shape[]
+
+
+ +

Returns

+
+
Shape[]
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ Cast(NDArray, NPTypeCode, bool) + +

+ +
+
+ +
+
public override NDArray Cast(NDArray nd, NPTypeCode dtype, bool copy)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype NPTypeCode
+
+
copy bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Cast(NDArray, Type, bool) + +

+ +
+
+ +
+
public override NDArray Cast(NDArray nd, Type dtype, bool copy)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
copy bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Ceil(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Ceil(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Ceil(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Ceil(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Clip(in NDArray, in ValueType, in ValueType, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Clip(in NDArray lhs, in ValueType min, in ValueType max, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
lhs NDArray
+
+
min ValueType
+
+
max ValueType
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Clip(in NDArray, in ValueType, in ValueType, Type) + +

+ +
+
+ +
+
public override NDArray Clip(in NDArray lhs, in ValueType min, in ValueType max, Type dtype)
+
+ +

Parameters

+
+
lhs NDArray
+
+
min ValueType
+
+
max ValueType
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ClipNDArray(in NDArray, in NDArray, in NDArray, NPTypeCode?, NDArray) + +

+ +
+
+ +
+
public override NDArray ClipNDArray(in NDArray lhs, in NDArray min, in NDArray max, NPTypeCode? typeCode = null, NDArray @out = null)
+
+ +

Parameters

+
+
lhs NDArray
+
+
min NDArray
+
+
max NDArray
+
+
typeCode NPTypeCode?
+
+
out NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ClipNDArray(in NDArray, in NDArray, in NDArray, Type, NDArray) + +

+ +
+
+ +
+
public override NDArray ClipNDArray(in NDArray lhs, in NDArray min, in NDArray max, Type dtype, NDArray @out = null)
+
+ +

Parameters

+
+
lhs NDArray
+
+
min NDArray
+
+
max NDArray
+
+
dtype Type
+
+
out NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Compare(in NDArray, in NDArray) + +

+ +
+
+ +
+
public override NDArray<bool> Compare(in NDArray x, in NDArray y)
+
+ +

Parameters

+
+
x NDArray
+
+
y NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ Cos(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Cos(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Cos(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Cos(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Cosh(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Cosh(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Cosh(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Cosh(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ CreateNDArray(Shape, Type, IArraySlice, char) + +

+ +
+
+ +
+
public override NDArray CreateNDArray(Shape shape, Type dtype = null, IArraySlice buffer = null, char order = 'C')
+
+ +

Parameters

+
+
shape Shape
+
+
dtype Type
+
+
buffer IArraySlice
+
+
order char
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ CreateNDArray(Shape, Type, Array, char) + +

+ +
+
+ +
+
public override NDArray CreateNDArray(Shape shape, Type dtype = null, Array buffer = null, char order = 'C')
+
+ +

Parameters

+
+
shape Shape
+
+
dtype Type
+
+
buffer Array
+
+
order char
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ CumSumElementwise<T>(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public NDArray CumSumElementwise<T>(in NDArray arr, NPTypeCode? typeCode) where T : unmanaged
+
+ +

Parameters

+
+
arr NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Divide(in NDArray, in NDArray) + +

+ +
+
+ +
+
public override NDArray Divide(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ DivideBoolean(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray DivideBoolean(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ DivideByte(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray DivideByte(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ DivideChar(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray DivideChar(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ DivideDecimal(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray DivideDecimal(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ DivideDouble(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray DivideDouble(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ DivideInt16(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray DivideInt16(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ DivideInt32(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray DivideInt32(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ DivideInt64(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray DivideInt64(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ DivideSingle(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray DivideSingle(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ DivideUInt16(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray DivideUInt16(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ DivideUInt32(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray DivideUInt32(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ DivideUInt64(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray DivideUInt64(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Dot(in NDArray, in NDArray) + +

+ +
+
+ +
+
public override NDArray Dot(in NDArray left, in NDArray right)
+
+ +

Parameters

+
+
left NDArray
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ DotNDMD(in NDArray, in NDArray) + +

+ +
+
+ +
+
public static NDArray DotNDMD(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ EqualsBoolean(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray<bool> EqualsBoolean(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ EqualsByte(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray<bool> EqualsByte(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ EqualsChar(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray<bool> EqualsChar(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ EqualsDecimal(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray<bool> EqualsDecimal(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ EqualsDouble(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray<bool> EqualsDouble(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ EqualsInt16(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray<bool> EqualsInt16(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ EqualsInt32(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray<bool> EqualsInt32(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ EqualsInt64(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray<bool> EqualsInt64(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ EqualsSingle(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray<bool> EqualsSingle(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ EqualsUInt16(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray<bool> EqualsUInt16(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ EqualsUInt32(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray<bool> EqualsUInt32(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ EqualsUInt64(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray<bool> EqualsUInt64(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ Exp(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Exp(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Exp(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Exp(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Exp2(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Exp2(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Exp2(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Exp2(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Expm1(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Expm1(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Expm1(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Expm1(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Floor(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Floor(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Floor(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Floor(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ GetStorage(NPTypeCode) + +

+ +

Get storage for given typeCode.

+
+
+ +
+
public override UnmanagedStorage GetStorage(NPTypeCode typeCode)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+
+
+ +

Returns

+
+
UnmanagedStorage
+
+
+ + + + + + + + + + + + + +

+ GetStorage(Type) + +

+ +

Get storage for given dtype.

+
+
+ +
+
public override UnmanagedStorage GetStorage(Type dtype)
+
+ +

Parameters

+
+
dtype Type
+
+
+ +

Returns

+
+
UnmanagedStorage
+
+
+ + + + + + + + + + + + + +

+ IsClose(NDArray, NDArray, double, double, bool) + +

+ +

Returns a boolean array where two arrays are element-wise equal within a +tolerance. +The tolerance values are positive, typically very small numbers.The
+relative difference (rtol * abs(b)) and the absolute difference +atol are added together to compare against the absolute difference +between a and b. +Warning: The default atol is not appropriate for comparing numbers +that are much smaller than one(see Notes).

+

See also allclose

+

Notes: +For finite values, isclose uses the following equation to test whether +two floating point values are equivalent.

+
absolute(`a` - `b`) less than or equal to (`atol` + `rtol` * absolute(`b`))
+

Unlike the built-in math.isclose, the above equation is not symmetric +in a and b -- it assumes b is the reference value -- so that +isclose(a, b) might be different from isclose(b, a). Furthermore, +the default value of atol is not zero, and is used to determine what +small values should be considered close to zero.The default value is +appropriate for expected values of order unity: if the expected values +are significantly smaller than one, it can result in false positives. +atol should be carefully selected for the use case at hand. A zero value +for atol will result in False if either a or b is zero.

+
+
+ +
+
public override NDArray<bool> IsClose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false)
+
+ +

Parameters

+
+
a NDArray
+

Input array to compare with b

+
+
b NDArray
+

Input array to compare with a.

+
+
rtol double
+

The relative tolerance parameter(see Notes)

+
+
atol double
+

The absolute tolerance parameter(see Notes)

+
+
equal_nan bool
+

Whether to compare NaN's as equal. If True, NaN's in a will be +considered equal to NaN's in b in the output array.

+
+
+ +

Returns

+
+
NDArray<bool>
+

Returns a boolean array of where a and b are equal within the +given tolerance.If both a and b are scalars, returns a single +boolean value.

+
+
+ + + + + + + + + + + + + +

+ IsFinite(NDArray) + +

+ +

Test element-wise for finiteness (not infinity or not Not a Number).

+
+
+ +
+
public override NDArray<bool> IsFinite(NDArray a)
+
+ +

Parameters

+
+
a NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+

The result is returned as a boolean array.

+
+
+ + + + + + + + + + + + + +

+ IsNan(NDArray) + +

+ +

Test element-wise for Not a Number.

+
+
+ +
+
public override NDArray<bool> IsNan(NDArray a)
+
+ +

Parameters

+
+
a NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+

The result is returned as a boolean array.

+
+
+ + + + + + + + + + + + + +

+ Log(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Log(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Log(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Log(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Log10(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Log10(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Log10(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Log10(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Log1p(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Log1p(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Log1p(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Log1p(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Log2(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Log2(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Log2(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Log2(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Matmul(NDArray, NDArray) + +

+ +
+
+ +
+
public override NDArray Matmul(NDArray lhs, NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ Mean(in NDArray, int, Type, bool) + +

+ +
+
+ +
+
public override NDArray Mean(in NDArray nd, int axis, Type dtype, bool keepdims = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int
+
+
dtype Type
+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Mean(in NDArray, int?, NPTypeCode?, bool) + +

+ +
+
+ +
+
public override NDArray Mean(in NDArray nd, int? axis = null, NPTypeCode? typeCode = null, bool keepdims = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int?
+
+
typeCode NPTypeCode?
+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ MeanElementwise<T>(NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public T MeanElementwise<T>(NDArray arr, NPTypeCode? typeCode) where T : unmanaged
+
+ +

Parameters

+
+
arr NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Mod(in NDArray, in NDArray) + +

+ +
+
+ +
+
public override NDArray Mod(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ModBoolean(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray ModBoolean(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ModByte(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray ModByte(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ModChar(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray ModChar(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ModDecimal(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray ModDecimal(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ModDouble(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray ModDouble(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ModF(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override (NDArray Fractional, NDArray Intergral) ModF(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
(NDArray Lhs, NDArray Rhs)
+
+
+ + + + + + + + + + + + + +

+ ModF(in NDArray, Type) + +

+ +
+
+ +
+
public override (NDArray Fractional, NDArray Intergral) ModF(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
(NDArray Lhs, NDArray Rhs)
+
+
+ + + + + + + + + + + + + +

+ ModInt16(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray ModInt16(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ModInt32(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray ModInt32(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ModInt64(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray ModInt64(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ModSingle(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray ModSingle(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ModUInt16(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray ModUInt16(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ModUInt32(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray ModUInt32(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ModUInt64(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray ModUInt64(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ MoveAxis(in NDArray, int[], int[]) + +

+ +
+
+ +
+
public override NDArray MoveAxis(in NDArray nd, int[] source, int[] destinition)
+
+ +

Parameters

+
+
nd NDArray
+
+
source int[]
+
+
destinition int[]
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Multiply(NDArray, NDArray) + +

+ +
+
+ +
+
public override NDArray Multiply(NDArray lhs, NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ MultiplyBoolean(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray MultiplyBoolean(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ MultiplyByte(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray MultiplyByte(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ MultiplyChar(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray MultiplyChar(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ MultiplyDecimal(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray MultiplyDecimal(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ MultiplyDouble(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray MultiplyDouble(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ MultiplyInt16(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray MultiplyInt16(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ MultiplyInt32(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray MultiplyInt32(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ MultiplyInt64(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray MultiplyInt64(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ MultiplyMatrix(NDArray, NDArray, NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+protected static NDArray MultiplyMatrix(NDArray left, NDArray right, NDArray @out = null)
+
+ +

Parameters

+
+
left NDArray
+
+
right NDArray
+
+
out NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ MultiplySingle(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray MultiplySingle(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ MultiplyUInt16(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray MultiplyUInt16(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ MultiplyUInt32(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray MultiplyUInt32(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ MultiplyUInt64(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray MultiplyUInt64(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Negate(in NDArray) + +

+ +
+
+ +
+
public override NDArray Negate(in NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ NonZero(in NDArray) + +

+ +

Test whether all array elements evaluate to True.

+
+
+ +
+
public override NDArray<int>[] NonZero(in NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
NDArray<int>[]
+
+
+ + + + + + + + + + + + + +

+ Power(in NDArray, in ValueType, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Power(in NDArray lhs, in ValueType rhs, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs ValueType
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Power(in NDArray, in ValueType, Type) + +

+ +
+
+ +
+
public override NDArray Power(in NDArray lhs, in ValueType rhs, Type dtype)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs ValueType
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ProductElementwise<T>(NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public T ProductElementwise<T>(NDArray arr, NPTypeCode? typeCode) where T : unmanaged
+
+ +

Parameters

+
+
arr NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ ReduceAMax(NDArray, int?, bool, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray ReduceAMax(NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
keepdims bool
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceAMin(NDArray, int?, bool, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray ReduceAMin(NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
keepdims bool
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceAdd(in NDArray, int?, bool, NPTypeCode?, NDArray) + +

+ +
+
+ +
+
public override NDArray ReduceAdd(in NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null, NDArray @out = null)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
keepdims bool
+
+
typeCode NPTypeCode?
+
+
out NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceArgMax(NDArray, int?) + +

+ +
+
+ +
+
public override NDArray ReduceArgMax(NDArray arr, int? axis_)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceArgMin(NDArray, int?) + +

+ +
+
+ +
+
public override NDArray ReduceArgMin(NDArray arr, int? axis_)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceCumAdd(in NDArray, int?, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray ReduceCumAdd(in NDArray arr, int? axis_, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceMean(in NDArray, int?, bool, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray ReduceMean(in NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
keepdims bool
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceProduct(NDArray, int?, bool, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray ReduceProduct(NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
keepdims bool
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceStd(NDArray, int?, bool, int?, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray ReduceStd(NDArray arr, int? axis_, bool keepdims = false, int? ddof = null, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
keepdims bool
+
+
ddof int?
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceVar(NDArray, int?, bool, int?, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray ReduceVar(NDArray arr, int? axis_, bool keepdims = false, int? ddof = null, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
keepdims bool
+
+
ddof int?
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ResolveReturnShape(params NDArray[]) + +

+ +
+
+ +
+
public static Shape ResolveReturnShape(params NDArray[] shapes)
+
+ +

Parameters

+
+
shapes NDArray[]
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ ResolveReturnShape(Shape, Shape) + +

+ +
+
+ +
+
public static Shape ResolveReturnShape(Shape leftShape, Shape rightShape)
+
+ +

Parameters

+
+
leftShape Shape
+
+
rightShape Shape
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ ResolveReturnShape(params Shape[]) + +

+ +
+
+ +
+
public static Shape ResolveReturnShape(params Shape[] shapes)
+
+ +

Parameters

+
+
shapes Shape[]
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ ResolveUnaryReturnType(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public NPTypeCode ResolveUnaryReturnType(in NDArray nd, NPTypeCode? @override)
+
+ +

Parameters

+
+
nd NDArray
+
+
override NPTypeCode?
+
+
+ +

Returns

+
+
NPTypeCode
+
+
+ + + + + + + + + + + + + +

+ ResolveUnaryReturnType(in NDArray, Type) + +

+ +
+
+ +
+
public NPTypeCode ResolveUnaryReturnType(in NDArray nd, Type @override)
+
+ +

Parameters

+
+
nd NDArray
+
+
override Type
+
+
+ +

Returns

+
+
NPTypeCode
+
+
+ + + + + + + + + + + + + +

+ RollAxis(in NDArray, int, int) + +

+ +
+
+ +
+
public override NDArray RollAxis(in NDArray nd, int axis, int start = 0)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int
+
+
start int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Round(in NDArray, int, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Round(in NDArray nd, int decimals, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
decimals int
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Round(in NDArray, int, Type) + +

+ +
+
+ +
+
public override NDArray Round(in NDArray nd, int decimals, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
decimals int
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Round(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Round(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Round(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Round(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sign(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Sign(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sign(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Sign(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sin(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Sin(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sin(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Sin(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sinh(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Sinh(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sinh(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Sinh(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sqrt(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Sqrt(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sqrt(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Sqrt(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ StdElementwise<T>(NDArray, NPTypeCode?, int?) + +

+ +
+
+ +
+
public T StdElementwise<T>(NDArray arr, NPTypeCode? typeCode, int? ddof) where T : unmanaged
+
+ +

Parameters

+
+
arr NDArray
+
+
typeCode NPTypeCode?
+
+
ddof int?
+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Subtract(in NDArray, in NDArray) + +

+ +
+
+ +
+
public override NDArray Subtract(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ SubtractBoolean(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray SubtractBoolean(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ SubtractByte(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray SubtractByte(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ SubtractChar(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray SubtractChar(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ SubtractDecimal(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray SubtractDecimal(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ SubtractDouble(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray SubtractDouble(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ SubtractInt16(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray SubtractInt16(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ SubtractInt32(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray SubtractInt32(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ SubtractInt64(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray SubtractInt64(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ SubtractSingle(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray SubtractSingle(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ SubtractUInt16(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray SubtractUInt16(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ SubtractUInt32(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray SubtractUInt32(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ SubtractUInt64(in NDArray, in NDArray) + +

+ +
+
+ +
+
[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
+public NDArray SubtractUInt64(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sum(in NDArray, int, Type, bool) + +

+ +
+
+ +
+
public override NDArray Sum(in NDArray nd, int axis, Type dtype, bool keepdims = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int
+
+
dtype Type
+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sum(in NDArray, int?, NPTypeCode?, bool) + +

+ +
+
+ +
+
public override NDArray Sum(in NDArray nd, int? axis = null, NPTypeCode? typeCode = null, bool keepdims = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int?
+
+
typeCode NPTypeCode?
+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ SumElementwise<T>(NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public T SumElementwise<T>(NDArray arr, NPTypeCode? typeCode) where T : unmanaged
+
+ +

Parameters

+
+
arr NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ SwapAxes(in NDArray, int, int) + +

+ +
+
+ +
+
public override NDArray SwapAxes(in NDArray nd, int axis1, int axis2)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis1 int
+
+
axis2 int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Tan(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Tan(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Tan(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Tan(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Tanh(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public override NDArray Tanh(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Tanh(in NDArray, Type) + +

+ +
+
+ +
+
public override NDArray Tanh(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Transpose(in NDArray, int[]) + +

+ +
+
+ +
+
public override NDArray Transpose(in NDArray nd, int[] premute = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
premute int[]
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ VarElementwise<T>(NDArray, NPTypeCode?, int?) + +

+ +
+
+ +
+
public T VarElementwise<T>(NDArray arr, NPTypeCode? typeCode, int? ddof) where T : unmanaged
+
+ +

Parameters

+
+
arr NDArray
+
+
typeCode NPTypeCode?
+
+
ddof int?
+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ amax_elementwise(NDArray, NPTypeCode?) + +

+ +
+
+ +
+
protected object amax_elementwise(NDArray arr, NPTypeCode? typeCode)
+
+ +

Parameters

+
+
arr NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
object
+
+
+ + + + + + + + + + + + + +

+ amin_elementwise(NDArray, NPTypeCode?) + +

+ +
+
+ +
+
protected object amin_elementwise(NDArray arr, NPTypeCode? typeCode)
+
+ +

Parameters

+
+
arr NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
object
+
+
+ + + + + + + + + + + + + +

+ argmax_elementwise(NDArray) + +

+ +
+
+ +
+
protected object argmax_elementwise(NDArray arr)
+
+ +

Parameters

+
+
arr NDArray
+
+
+ +

Returns

+
+
object
+
+
+ + + + + + + + + + + + + +

+ argmin_elementwise(NDArray) + +

+ +
+
+ +
+
protected object argmin_elementwise(NDArray arr)
+
+ +

Parameters

+
+
arr NDArray
+
+
+ +

Returns

+
+
object
+
+
+ + + + + + + + + + + + + +

+ check_and_adjust_axis(NDArray, int) + +

+ +
+
+ +
+
public static int check_and_adjust_axis(NDArray nd, int axis)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ check_and_adjust_axis(int, int) + +

+ +
+
+ +
+
public static int check_and_adjust_axis(int ndims, int axis)
+
+ +

Parameters

+
+
ndims int
+
+
axis int
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ cumsum_elementwise(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
protected NDArray cumsum_elementwise(in NDArray arr, NPTypeCode? typeCode)
+
+ +

Parameters

+
+
arr NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ mean_elementwise(NDArray, NPTypeCode?) + +

+ +
+
+ +
+
protected object mean_elementwise(NDArray arr, NPTypeCode? typeCode)
+
+ +

Parameters

+
+
arr NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
object
+
+
+ + + + + + + + + + + + + +

+ normalize_axis_tuple(int, object, bool) + +

+ +
+
+ +
+
public static int[] normalize_axis_tuple(int axis, object argname = null, bool allow_duplicate = false)
+
+ +

Parameters

+
+
axis int
+
+
argname object
+
+
allow_duplicate bool
+
+
+ +

Returns

+
+
int[]
+
+
+ + + + + + + + + + + + + +

+ normalize_axis_tuple(int[], object, bool) + +

+ +
+
+ +
+
public static int[] normalize_axis_tuple(int[] axis, object argname = null, bool allow_duplicate = false)
+
+ +

Parameters

+
+
axis int[]
+
+
argname object
+
+
allow_duplicate bool
+
+
+ +

Returns

+
+
int[]
+
+
+ + + + + + + + + + + + + +

+ product_elementwise(NDArray, NPTypeCode?) + +

+ +
+
+ +
+
protected object product_elementwise(NDArray arr, NPTypeCode? typeCode)
+
+ +

Parameters

+
+
arr NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
object
+
+
+ + + + + + + + + + + + + +

+ std_elementwise(NDArray, NPTypeCode?, int?) + +

+ +
+
+ +
+
protected object std_elementwise(NDArray arr, NPTypeCode? typeCode, int? ddof)
+
+ +

Parameters

+
+
arr NDArray
+
+
typeCode NPTypeCode?
+
+
ddof int?
+
+
+ +

Returns

+
+
object
+
+
+ + + + + + + + + + + + + +

+ sum_elementwise(NDArray, NPTypeCode?) + +

+ +
+
+ +
+
protected object sum_elementwise(NDArray arr, NPTypeCode? typeCode)
+
+ +

Parameters

+
+
arr NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
object
+
+
+ + + + + + + + + + + + + +

+ var_elementwise(NDArray, NPTypeCode?, int?) + +

+ +
+
+ +
+
protected object var_elementwise(NDArray arr, NPTypeCode? typeCode, int? ddof)
+
+ +

Parameters

+
+
arr NDArray
+
+
typeCode NPTypeCode?
+
+
ddof int?
+
+
+ +

Returns

+
+
object
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Backends.Unmanaged.ArraySlice-1.html b/docs/website/api/NumSharp.Backends.Unmanaged.ArraySlice-1.html new file mode 100644 index 000000000..f112c3eb1 --- /dev/null +++ b/docs/website/api/NumSharp.Backends.Unmanaged.ArraySlice-1.html @@ -0,0 +1,1347 @@ + + + + + Struct ArraySlice<T> | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Struct ArraySlice<T> +

+ +
+
Namespace
NumSharp.Backends.Unmanaged
+
Assembly
NumSharp.dll
+
+ +

ArraySlice<T> is similar to Span<T> but it can be moved around without having to follow ref struct rules.

+
+
+ +
+
public readonly struct ArraySlice<T> : IArraySlice, ICloneable, IMemoryBlock<T>, IMemoryBlock, IEnumerable<T>, IEnumerable where T : unmanaged
+
+ + + +

Type Parameters

+
+
T
+

The type that the MemoryBlock implements.

+
+
+ + +
+
Implements
+
+ + + + + + +
+
+ + +
+
Inherited Members
+
+ + + + + + +
+ +
+
Extension Methods
+
+ + + + + + + + + + + + + +
+ + + + + +

Constructors +

+ + + + +

+ ArraySlice(UnmanagedMemoryBlock<T>) + +

+ +
+
+ +
+
public ArraySlice(UnmanagedMemoryBlock<T> memoryBlock)
+
+ +

Parameters

+
+
memoryBlock UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + + +

+ ArraySlice(UnmanagedMemoryBlock<T>, Span<T>) + +

+ +
+
+ +
+
public ArraySlice(UnmanagedMemoryBlock<T> memoryBlock, Span<T> slice)
+
+ +

Parameters

+
+
memoryBlock UnmanagedMemoryBlock<T>
+
+
slice Span<T>
+
+
+ + + + + + + + + + + + + + +

+ ArraySlice(UnmanagedMemoryBlock<T>, T*, int) + +

+ +

Creates a sliced ArraySlice<T>.

+
+
+ +
+
public ArraySlice(UnmanagedMemoryBlock<T> memoryBlock, T* address, int count)
+
+ +

Parameters

+
+
memoryBlock UnmanagedMemoryBlock<T>
+
+
address T*
+
+
count int
+

The number of T this slice should contain - relative to the memoryBlock

+
+
+ + + + + + + + + + + + + + +

+ ArraySlice(UnmanagedMemoryBlock<T>, T*, long) + +

+ +

Creates a sliced ArraySlice<T>.

+
+
+ +
+
public ArraySlice(UnmanagedMemoryBlock<T> memoryBlock, T* address, long count)
+
+ +

Parameters

+
+
memoryBlock UnmanagedMemoryBlock<T>
+
+
address T*
+
+
count long
+

The number of T this slice should contain - relative to the memoryBlock

+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ Address + +

+ +
+
+ +
+
public readonly T* Address
+
+ + + + +

Field Value

+
+
T*
+
+
+ + + + + + + + + + +

+ Count + +

+ +
+
+ +
+
public readonly int Count
+
+ + + + +

Field Value

+
+
int
+
+
+ + + + + + + + + + +

+ IsSlice + +

+ +

Is this ArraySlice<T> a smaller part/slice of an unmanaged allocation?

+
+
+ +
+
public readonly bool IsSlice
+
+ + + + +

Field Value

+
+
bool
+
+
+ + + + + + + + + + +

+ MemoryBlock + +

+ +

The memory block this ArraySlice<T> is stored in.

+
+
+ +
+
public readonly UnmanagedMemoryBlock<T> MemoryBlock
+
+ + + + +

Field Value

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + +

Remarks

+

If IsSlice is false then this slice represents the entire MemoryBlock.

+
+ + + + + +

+ VoidAddress + +

+ +
+
+ +
+
public readonly void* VoidAddress
+
+ + + + +

Field Value

+
+
void*
+
+
+ + + + + + + + + +

Properties +

+ + + + +

+ this[int] + +

+ +
+
+ +
+
public T this[int index] { get; set; }
+
+ +

Parameters

+
+
index int
+
+
+ + + + +

Property Value

+
+
T
+
+
+ + + + + + + + + + +

+ ItemLength + +

+ +

The size of a single item stored in Address.

+
+
+ +
+
public int ItemLength { get; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + +

Remarks

+

Equivalent to NPTypeCode.SizeOf extension.

+
+ + + + + + +

+ TypeCode + +

+ +
+
+ +
+
public static NPTypeCode TypeCode { get; }
+
+ + + + + +

Property Value

+
+
NPTypeCode
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ Allocate(int) + +

+ +

Allocate an array filled with noisy memory.

+
+
+ +
+
public static ArraySlice<T> Allocate(int count)
+
+ +

Parameters

+
+
count int
+

How many items this array will have (aka Count).

+
+
+ +

Returns

+
+
ArraySlice<T>
+

A newly allocated array.

+
+
+ + + + + + + + + + + + + +

+ Allocate(int, bool) + +

+ +

Allocate an array filled with default value of T.

+
+
+ +
+
public static ArraySlice<T> Allocate(int count, bool fillDefault)
+
+ +

Parameters

+
+
count int
+

How many items this array will have (aka Count).

+
+
fillDefault bool
+

Should the newly allocated memory be filled with the default of T

+
+
+ +

Returns

+
+
ArraySlice<T>
+

A newly allocated array.

+
+
+ + + + + + + + + + + + + +

+ Allocate(int, T) + +

+ +

Allocate an array filled filled with fill.

+
+
+ +
+
public static ArraySlice<T> Allocate(int count, T fill)
+
+ +

Parameters

+
+
count int
+

How many items this array will have (aka Count).

+
+
fill T
+

The item to fill the newly allocated memory with.

+
+
+ +

Returns

+
+
ArraySlice<T>
+

A newly allocated array.

+
+
+ + + + + + + + + + + + + +

+ Clone() + +

+ +
+
+ +
+
public ArraySlice<T> Clone()
+
+ + +

Returns

+
+
ArraySlice<T>
+
+
+ + + + + + + + + + + + + +

+ Contains(T) + +

+ +
+
+ +
+
public bool Contains(T item)
+
+ +

Parameters

+
+
item T
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ CopyTo(nint) + +

+ +

Copies the entire array to address.

+
+
+ +
+
public void CopyTo(nint dst)
+
+ +

Parameters

+
+
dst nint
+

The address to copy to

+
+
+ + + + + + + + +

Remarks

+

The destiniton has to be atleast the size of this array, otherwise memory corruption is likely to occur.

+
+ + + + + + +

+ CopyTo(nint, int, int) + +

+ +

Copies the entire array to address.

+
+
+ +
+
public void CopyTo(nint dst, int sourceOffset, int sourceCount)
+
+ +

Parameters

+
+
dst nint
+

The address to copy to

+
+
sourceOffset int
+
+
sourceCount int
+
+
+ + + + + + + + +

Remarks

+

The destiniton has to be atleast the size of this array, otherwise memory corruption is likely to occur.

+
+ + + + + + +

+ CopyTo(Span<T>) + +

+ +
+
+ +
+
public void CopyTo(Span<T> destination)
+
+ +

Parameters

+
+
destination Span<T>
+
+
+ + + + + + + + + + + + + + +

+ CopyTo(Span<T>, int) + +

+ +
+
+ +
+
public void CopyTo(Span<T> destination, int sourceOffset)
+
+ +

Parameters

+
+
destination Span<T>
+
+
sourceOffset int
+

offset of source via count (not bytes)

+
+
+ + + + + + + + + + + + + + +

+ CopyTo(Span<T>, int, int) + +

+ +
+
+ +
+
public void CopyTo(Span<T> destination, int sourceOffset, int sourceLength)
+
+ +

Parameters

+
+
destination Span<T>
+
+
sourceOffset int
+

offset of source via count (not bytes)

+
+
sourceLength int
+

How many items to copy

+
+
+ + + + + + + + + + + + + + +

+ DangerousFree() + +

+ +

Performs dispose on the internal unmanaged memory block.

+
+
+ +
+
public void DangerousFree()
+
+ + + + + + + + + +

Remarks

+

Dangerous because this ArraySlice might be a IsSlice therefore there might be other slices that point to current MemoryBlock.
+So releasing the MemoryBlock might cause memory corruption elsewhere.
+It is best to leave MemoryBlock to GC.

+
+ + + + + + +

+ Fill(T) + +

+ +
+
+ +
+
public void Fill(T value)
+
+ +

Parameters

+
+
value T
+
+
+ + + + + + + + + + + + + + +

+ GetEnumerator() + +

+ +

Returns an enumerator that iterates through the collection.

+
+
+ +
+
public IEnumerator<T> GetEnumerator()
+
+ + +

Returns

+
+
IEnumerator<T>
+

An enumerator that can be used to iterate through the collection.

+
+
+ + + + + + + + + + + + + +

+ GetIndex(int) + +

+ +
+
+ +
+
public T GetIndex(int index)
+
+ +

Parameters

+
+
index int
+
+
+ +

Returns

+
+
T
+
+
+ + + + + + + + + + + + + +

+ SetIndex(int, object) + +

+ +
+
+ +
+
public void SetIndex(int index, object value)
+
+ +

Parameters

+
+
index int
+
+
value object
+
+
+ + + + + + + + + + + + + + +

+ SetIndex(int, T) + +

+ +
+
+ +
+
public void SetIndex(int index, T value)
+
+ +

Parameters

+
+
index int
+
+
value T
+
+
+ + + + + + + + + + + + + + +

+ Slice(int) + +

+ +
+
+ +
+
public ArraySlice<T> Slice(int start)
+
+ +

Parameters

+
+
start int
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ + + + + + + + + + + + + +

+ Slice(int, int) + +

+ +
+
+ +
+
public ArraySlice<T> Slice(int start, int length)
+
+ +

Parameters

+
+
start int
+
+
length int
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ + + + + + + + + + + + + +

+ ToArray() + +

+ +

Copies the contents of this span into a new array. This heap +allocates, so should generally be avoided, however it is sometimes +necessary to bridge the gap with APIs written in terms of arrays.

+
+
+ +
+
public T[] ToArray()
+
+ + +

Returns

+
+
T[]
+
+
+ + + + + + + + + + + + + +

+ TryCopyTo(Span<T>) + +

+ +
+
+ +
+
public bool TryCopyTo(Span<T> destination)
+
+ +

Parameters

+
+
destination Span<T>
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Backends.Unmanaged.ArraySlice.html b/docs/website/api/NumSharp.Backends.Unmanaged.ArraySlice.html new file mode 100644 index 000000000..f87e0900f --- /dev/null +++ b/docs/website/api/NumSharp.Backends.Unmanaged.ArraySlice.html @@ -0,0 +1,2072 @@ + + + + + Class ArraySlice | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class ArraySlice +

+ +
+
Namespace
NumSharp.Backends.Unmanaged
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public static class ArraySlice
+
+ + + + +
+
Inheritance
+
+ +
ArraySlice
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Methods +

+ + + + +

+ Allocate(NPTypeCode, int) + +

+ +
+
+ +
+
public static IArraySlice Allocate(NPTypeCode typeCode, int count)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+
+
count int
+
+
+ +

Returns

+
+
IArraySlice
+
+
+ + + + + + + + + + + + + +

+ Allocate(NPTypeCode, int, bool) + +

+ +
+
+ +
+
public static IArraySlice Allocate(NPTypeCode typeCode, int count, bool fillDefault)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+
+
count int
+
+
fillDefault bool
+
+
+ +

Returns

+
+
IArraySlice
+
+
+ + + + + + + + + + + + + +

+ Allocate(NPTypeCode, int, object) + +

+ +
+
+ +
+
public static IArraySlice Allocate(NPTypeCode typeCode, int count, object fill)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+
+
count int
+
+
fill object
+
+
+ +

Returns

+
+
IArraySlice
+
+
+ + + + + + + + + + + + + +

+ Allocate(Type, int) + +

+ +
+
+ +
+
public static IArraySlice Allocate(Type elementType, int count)
+
+ +

Parameters

+
+
elementType Type
+
+
count int
+
+
+ +

Returns

+
+
IArraySlice
+
+
+ + + + + + + + + + + + + +

+ Allocate(Type, int, bool) + +

+ +
+
+ +
+
public static IArraySlice Allocate(Type elementType, int count, bool fillDefault)
+
+ +

Parameters

+
+
elementType Type
+
+
count int
+
+
fillDefault bool
+
+
+ +

Returns

+
+
IArraySlice
+
+
+ + + + + + + + + + + + + +

+ Allocate(Type, int, object) + +

+ +
+
+ +
+
public static IArraySlice Allocate(Type elementType, int count, object fill)
+
+ +

Parameters

+
+
elementType Type
+
+
count int
+
+
fill object
+
+
+ +

Returns

+
+
IArraySlice
+
+
+ + + + + + + + + + + + + +

+ Allocate<T>(int) + +

+ +

Allocate an array filled with noisy memory.

+
+
+ +
+
public static ArraySlice<T> Allocate<T>(int count) where T : unmanaged
+
+ +

Parameters

+
+
count int
+

How many items this array will have (aka Count).

+
+
+ +

Returns

+
+
ArraySlice<T>
+

A newly allocated array.

+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Allocate<T>(int, bool) + +

+ +

Allocate an array filled with default value of T.

+
+
+ +
+
public static ArraySlice<T> Allocate<T>(int count, bool fillDefault) where T : unmanaged
+
+ +

Parameters

+
+
count int
+

How many items this array will have (aka Count).

+
+
fillDefault bool
+

Should the newly allocated memory be filled with the default of T

+
+
+ +

Returns

+
+
ArraySlice<T>
+

A newly allocated array.

+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Allocate<T>(int, T) + +

+ +

Allocate an array filled filled with fill.

+
+
+ +
+
public static ArraySlice<T> Allocate<T>(int count, T fill) where T : unmanaged
+
+ +

Parameters

+
+
count int
+

How many items this array will have (aka Count).

+
+
fill T
+

The item to fill the newly allocated memory with.

+
+
+ +

Returns

+
+
ArraySlice<T>
+

A newly allocated array.

+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromArray(Array, bool) + +

+ +
+
+ +
+
public static IArraySlice FromArray(Array arr, bool copy = false)
+
+ +

Parameters

+
+
arr Array
+
+
copy bool
+
+
+ +

Returns

+
+
IArraySlice
+
+
+ + + + + + + + + + + + + +

+ FromArray(bool[], bool) + +

+ +
+
+ +
+
public static ArraySlice<bool> FromArray(bool[] bools, bool copy = false)
+
+ +

Parameters

+
+
bools bool[]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<bool>
+
+
+ + + + + + + + + + + + + +

+ FromArray(byte[], bool) + +

+ +
+
+ +
+
public static ArraySlice<byte> FromArray(byte[] bytes, bool copy = false)
+
+ +

Parameters

+
+
bytes byte[]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<byte>
+
+
+ + + + + + + + + + + + + +

+ FromArray(char[], bool) + +

+ +
+
+ +
+
public static ArraySlice<char> FromArray(char[] chars, bool copy = false)
+
+ +

Parameters

+
+
chars char[]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<char>
+
+
+ + + + + + + + + + + + + +

+ FromArray(decimal[], bool) + +

+ +
+
+ +
+
public static ArraySlice<decimal> FromArray(decimal[] decimals, bool copy = false)
+
+ +

Parameters

+
+
decimals decimal[]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<decimal>
+
+
+ + + + + + + + + + + + + +

+ FromArray(double[], bool) + +

+ +
+
+ +
+
public static ArraySlice<double> FromArray(double[] doubles, bool copy = false)
+
+ +

Parameters

+
+
doubles double[]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<double>
+
+
+ + + + + + + + + + + + + +

+ FromArray(short[], bool) + +

+ +
+
+ +
+
public static ArraySlice<short> FromArray(short[] shorts, bool copy = false)
+
+ +

Parameters

+
+
shorts short[]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<short>
+
+
+ + + + + + + + + + + + + +

+ FromArray(int[], bool) + +

+ +
+
+ +
+
public static ArraySlice<int> FromArray(int[] ints, bool copy = false)
+
+ +

Parameters

+
+
ints int[]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<int>
+
+
+ + + + + + + + + + + + + +

+ FromArray(long[], bool) + +

+ +
+
+ +
+
public static ArraySlice<long> FromArray(long[] longs, bool copy = false)
+
+ +

Parameters

+
+
longs long[]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<long>
+
+
+ + + + + + + + + + + + + +

+ FromArray(float[], bool) + +

+ +
+
+ +
+
public static ArraySlice<float> FromArray(float[] floats, bool copy = false)
+
+ +

Parameters

+
+
floats float[]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<float>
+
+
+ + + + + + + + + + + + + +

+ FromArray(ushort[], bool) + +

+ +
+
+ +
+
public static ArraySlice<ushort> FromArray(ushort[] ushorts, bool copy = false)
+
+ +

Parameters

+
+
ushorts ushort[]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<ushort>
+
+
+ + + + + + + + + + + + + +

+ FromArray(uint[], bool) + +

+ +
+
+ +
+
public static ArraySlice<uint> FromArray(uint[] uints, bool copy = false)
+
+ +

Parameters

+
+
uints uint[]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<uint>
+
+
+ + + + + + + + + + + + + +

+ FromArray(ulong[], bool) + +

+ +
+
+ +
+
public static ArraySlice<ulong> FromArray(ulong[] ulongs, bool copy = false)
+
+ +

Parameters

+
+
ulongs ulong[]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<ulong>
+
+
+ + + + + + + + + + + + + +

+ FromArray<T>(T[,,,,,,,,,,,,,,,], bool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromArray<T>(T[,,,,,,,,,,,,,,,] array, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
array T[,,,,,,,,,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromArray<T>(T[,,,,,,,,,,,,,,], bool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromArray<T>(T[,,,,,,,,,,,,,,] array, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
array T[,,,,,,,,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromArray<T>(T[,,,,,,,,,,,,,], bool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromArray<T>(T[,,,,,,,,,,,,,] array, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
array T[,,,,,,,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromArray<T>(T[,,,,,,,,,,,,], bool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromArray<T>(T[,,,,,,,,,,,,] array, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
array T[,,,,,,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromArray<T>(T[,,,,,,,,,,,], bool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromArray<T>(T[,,,,,,,,,,,] array, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
array T[,,,,,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromArray<T>(T[,,,,,,,,,,], bool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromArray<T>(T[,,,,,,,,,,] array, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
array T[,,,,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromArray<T>(T[,,,,,,,,,], bool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromArray<T>(T[,,,,,,,,,] array, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
array T[,,,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromArray<T>(T[,,,,,,,,], bool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromArray<T>(T[,,,,,,,,] array, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
array T[,,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromArray<T>(T[,,,,,,,], bool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromArray<T>(T[,,,,,,,] array, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
array T[,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromArray<T>(T[,,,,,,], bool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromArray<T>(T[,,,,,,] array, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
array T[,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromArray<T>(T[,,,,,], bool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromArray<T>(T[,,,,,] array, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
array T[,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromArray<T>(T[,,,,], bool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromArray<T>(T[,,,,] array, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
array T[,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromArray<T>(T[,,,], bool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromArray<T>(T[,,,] array, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
array T[,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromArray<T>(T[,,], bool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromArray<T>(T[,,] array, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
array T[,,]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromArray<T>(T[,], bool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromArray<T>(T[,] array, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
array T[,]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromArray<T>(T[], bool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromArray<T>(T[] array, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
array T[]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromBuffer<T>(byte[], bool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromBuffer<T>(byte[] arr, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
arr byte[]
+
+
copy bool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromMemoryBlock(IMemoryBlock, bool) + +

+ +
+
+ +
+
public static IArraySlice FromMemoryBlock(IMemoryBlock block, bool copy = false)
+
+ +

Parameters

+
+
block IMemoryBlock
+
+
copy bool
+
+
+ +

Returns

+
+
IArraySlice
+
+
+ + + + + + + + + + + + + +

+ FromPool<T>(StackedMemoryPool) + +

+ +
+
+ +
+
public static ArraySlice<T> FromPool<T>(StackedMemoryPool pool) where T : unmanaged
+
+ +

Parameters

+
+
pool StackedMemoryPool
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Scalar(object) + +

+ +

Wrap a val inside ArraySlice<T>.

+
+
+ +
+
public static IArraySlice Scalar(object val)
+
+ +

Parameters

+
+
val object
+

The value to wrap into an arrayslice.

+
+
+ +

Returns

+
+
IArraySlice
+
+
+ + + + + + + + + + + + + +

+ Scalar(object, NPTypeCode) + +

+ +

Wrap a T inside ArraySlice<T>.

+
+
+ +
+
public static IArraySlice Scalar(object val, NPTypeCode typeCode)
+
+ +

Parameters

+
+
val object
+

The value to wrap into an arrayslice.

+
+
typeCode NPTypeCode
+

The type expected to be returned

+
+
+ +

Returns

+
+
IArraySlice
+
+
+ + + + + + + + + + + + + +

+ Scalar<T>(T) + +

+ +

Wrap a T inside ArraySlice<T>.

+
+
+ +
+
public static ArraySlice<T> Scalar<T>(T val) where T : unmanaged
+
+ +

Parameters

+
+
val T
+
+
+ +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Wrap<T>(void*, int) + +

+ +

Wrap around a address with given count without claiming ownership of the address.

+
+
+ +
+
public static ArraySlice<T> Wrap<T>(void* address, int count) where T : unmanaged
+
+ +

Parameters

+
+
address void*
+

The address at which the memory block starts

+
+
count int
+

The count of items of type T (not bytes count)

+
+
+ +

Returns

+
+
ArraySlice<T>
+

A wrapped memory block as ArraySlice<T>

+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Wrap<T>(T*, int) + +

+ +

Wrap around a address with given count without claiming ownership of the address.

+
+
+ +
+
public static ArraySlice<T> Wrap<T>(T* address, int count) where T : unmanaged
+
+ +

Parameters

+
+
address T*
+

The address at which the memory block starts

+
+
count int
+

The count of items of type T (not bytes count)

+
+
+ +

Returns

+
+
ArraySlice<T>
+

A wrapped memory block as ArraySlice<T>

+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Backends.Unmanaged.IArraySlice.html b/docs/website/api/NumSharp.Backends.Unmanaged.IArraySlice.html new file mode 100644 index 000000000..2508d5188 --- /dev/null +++ b/docs/website/api/NumSharp.Backends.Unmanaged.IArraySlice.html @@ -0,0 +1,788 @@ + + + + + Interface IArraySlice | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Interface IArraySlice +

+ +
+
Namespace
NumSharp.Backends.Unmanaged
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public interface IArraySlice : IMemoryBlock, ICloneable, IEnumerable
+
+ + + + + + + +
+
Inherited Members
+
+ + + + + + +
+ +
+
Extension Methods
+
+ + + + + + + + + + + + +
+ + + + + +

Properties +

+ + + + +

+ this[int] + +

+ +
+
+ +
+
object this[int index] { get; set; }
+
+ +

Parameters

+
+
index int
+
+
+ + + + +

Property Value

+
+
object
+
+
+ + + + + + + + + + +

+ MemoryBlock + +

+ +
+
+ +
+
IMemoryBlock MemoryBlock { get; }
+
+ + + + + +

Property Value

+
+
IMemoryBlock
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ AsSpan<T>() + +

+ +
+
+ +
+
Span<T> AsSpan<T>()
+
+ + +

Returns

+
+
Span<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+

Does not perform copy.

+
+ + + + + + +

+ Clone() + +

+ +
+
+ +
+
IArraySlice Clone()
+
+ + +

Returns

+
+
IArraySlice
+
+
+ + + + + + + + + + + + + +

+ Clone<T>() + +

+ +
+
+ +
+
ArraySlice<T> Clone<T>() where T : unmanaged
+
+ + +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ CopyTo<T>(Span<T>) + +

+ +
+
+ +
+
void CopyTo<T>(Span<T> destination)
+
+ +

Parameters

+
+
destination Span<T>
+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ DangerousFree() + +

+ +

Performs dispose on the internal unmanaged memory block.

+
+
+ +
+
void DangerousFree()
+
+ + + + + + + + + +

Remarks

+

Dangerous because this ArraySlice might be a IsSlice therefore there might be other slices that point to current MemoryBlock.
+So releasing the MemoryBlock might cause memory corruption elsewhere.
+It is best to leave MemoryBlock to GC.

+
+ + + + + + +

+ Fill(object) + +

+ +

Fills all indexes with value.

+
+
+ +
+
void Fill(object value)
+
+ +

Parameters

+
+
value object
+
+
+ + + + + + + + + + + + + + +

+ GetIndex(int) + +

+ +
+
+ +
+
object GetIndex(int index)
+
+ +

Parameters

+
+
index int
+
+
+ +

Returns

+
+
object
+
+
+ + + + + + + + + + + + + +

+ GetIndex<T>(int) + +

+ +
+
+ +
+
T GetIndex<T>(int index) where T : unmanaged
+
+ +

Parameters

+
+
index int
+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ GetPinnableReference<T>() + +

+ +

Gets pinnable reference of the first item in the memory block storage.

+
+
+ +
+
ref T GetPinnableReference<T>() where T : unmanaged
+
+ + +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ SetIndex(int, object) + +

+ +
+
+ +
+
void SetIndex(int index, object value)
+
+ +

Parameters

+
+
index int
+
+
value object
+
+
+ + + + + + + + + + + + + + +

+ SetIndex<T>(int, T) + +

+ +
+
+ +
+
void SetIndex<T>(int index, T value) where T : unmanaged
+
+ +

Parameters

+
+
index int
+
+
value T
+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Slice(int) + +

+ +

Perform a slicing on this IMemoryBlock without copying data.

+
+
+ +
+
IArraySlice Slice(int start)
+
+ +

Parameters

+
+
start int
+

The index to start from

+
+
+ +

Returns

+
+
IArraySlice
+
+
+ + + + + + + +

Remarks

+

Creates a slice without copying.

+
+ + + + + + +

+ Slice(int, int) + +

+ +

Perform a slicing on this IMemoryBlock without copying data.

+
+
+ +
+
IArraySlice Slice(int start, int count)
+
+ +

Parameters

+
+
start int
+

The index to start from

+
+
count int
+

The number of items to slice (not bytes)

+
+
+ +

Returns

+
+
IArraySlice
+
+
+ + + + + + + +

Remarks

+

Creates a slice without copying.

+
+ + + + + + +

+ ToArray() + +

+ +

Copies this IArraySlice contents into a new array.

+
+
+ +
+
Array ToArray()
+
+ + +

Returns

+
+
Array
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Backends.Unmanaged.IMemoryBlock-1.html b/docs/website/api/NumSharp.Backends.Unmanaged.IMemoryBlock-1.html new file mode 100644 index 000000000..0b108543f --- /dev/null +++ b/docs/website/api/NumSharp.Backends.Unmanaged.IMemoryBlock-1.html @@ -0,0 +1,234 @@ + + + + + Interface IMemoryBlock<T> | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Interface IMemoryBlock<T> +

+ +
+
Namespace
NumSharp.Backends.Unmanaged
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public interface IMemoryBlock<T> : IMemoryBlock where T : unmanaged
+
+ + + +

Type Parameters

+
+
T
+
+
+ + + + +
+
Inherited Members
+
+ + + + +
+ +
+
Extension Methods
+
+ + + + + + + + + + +
+ + + + + +

Properties +

+ + + + +

+ Address + +

+ +

The start address of this memory block.

+
+
+ +
+
T* Address { get; }
+
+ + + + + +

Property Value

+
+
T*
+
+
+ + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Backends.Unmanaged.IMemoryBlock.html b/docs/website/api/NumSharp.Backends.Unmanaged.IMemoryBlock.html new file mode 100644 index 000000000..6f4acba83 --- /dev/null +++ b/docs/website/api/NumSharp.Backends.Unmanaged.IMemoryBlock.html @@ -0,0 +1,347 @@ + + + + + Interface IMemoryBlock | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Interface IMemoryBlock +

+ +
+
Namespace
NumSharp.Backends.Unmanaged
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public interface IMemoryBlock
+
+ + + + + + + + +
+
Extension Methods
+
+ + + + + + + + + +
+ + + + + +

Properties +

+ + + + +

+ Address + +

+ +

The start address of this memory block.

+
+
+ +
+
void* Address { get; }
+
+ + + + + +

Property Value

+
+
void*
+
+
+ + + + + + + + + + +

+ BytesLength + +

+ +

How many bytes are stored in this memory block.

+
+
+ +
+
long BytesLength { get; }
+
+ + + + + +

Property Value

+
+
long
+
+
+ + + + +

Remarks

+

Calculated by Count*ItemLength

+
+ + + + + + +

+ Count + +

+ +

How many items are stored in Address.

+
+
+ +
+
long Count { get; }
+
+ + + + + +

Property Value

+
+
long
+
+
+ + + + +

Remarks

+

Not to confuse with BytesLength

+
+ + + + + + +

+ ItemLength + +

+ +

The size of a single item stored in Address.

+
+
+ +
+
int ItemLength { get; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + +

Remarks

+

Equivalent to NPTypeCode.SizeOf extension.

+
+ + + + + + +

+ TypeCode + +

+ +

The NPTypeCode of the type stored inside this memory block.

+
+
+ +
+
NPTypeCode TypeCode { get; }
+
+ + + + + +

Property Value

+
+
NPTypeCode
+
+
+ + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Backends.Unmanaged.IUnmanagedMemoryBlock.html b/docs/website/api/NumSharp.Backends.Unmanaged.IUnmanagedMemoryBlock.html new file mode 100644 index 000000000..845a8595e --- /dev/null +++ b/docs/website/api/NumSharp.Backends.Unmanaged.IUnmanagedMemoryBlock.html @@ -0,0 +1,262 @@ + + + + + Interface IUnmanagedMemoryBlock | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Interface IUnmanagedMemoryBlock +

+ +
+
Namespace
NumSharp.Backends.Unmanaged
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public interface IUnmanagedMemoryBlock : IEnumerable, IMemoryBlock, ICloneable
+
+ + + + + + + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ + + + + + + + + +
+ + + + + +

Methods +

+ + + + +

+ Free() + +

+ +
+
+ +
+
void Free()
+
+ + + + + + + + + + + + + + + +

+ Reallocate(long, bool) + +

+ +
+
+ +
+
void Reallocate(long length, bool copyOldValues = false)
+
+ +

Parameters

+
+
length long
+
+
copyOldValues bool
+
+
+ + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Backends.Unmanaged.UnmanagedHelper.html b/docs/website/api/NumSharp.Backends.Unmanaged.UnmanagedHelper.html new file mode 100644 index 000000000..d0e0969a8 --- /dev/null +++ b/docs/website/api/NumSharp.Backends.Unmanaged.UnmanagedHelper.html @@ -0,0 +1,363 @@ + + + + + Class UnmanagedHelper | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class UnmanagedHelper +

+ +
+
Namespace
NumSharp.Backends.Unmanaged
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public static class UnmanagedHelper
+
+ + + + +
+
Inheritance
+
+ +
UnmanagedHelper
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Methods +

+ + + + +

+ CopyTo(IMemoryBlock, IMemoryBlock) + +

+ +

Copies the entire contents of this storage to given address (using Count).

+
+
+ +
+
public static void CopyTo(this IMemoryBlock src, IMemoryBlock dst)
+
+ +

Parameters

+
+
src IMemoryBlock
+
+
dst IMemoryBlock
+

The block to copy to.

+
+
+ + + + + + + + + + + + + + +

+ CopyTo(IMemoryBlock, IMemoryBlock, int) + +

+ +

Copies the entire contents of this storage to given address (using Count).

+
+
+ +
+
public static void CopyTo(this IMemoryBlock src, IMemoryBlock dst, int countOffsetDesitinion)
+
+ +

Parameters

+
+
src IMemoryBlock
+
+
dst IMemoryBlock
+

The block to copy to.

+
+
countOffsetDesitinion int
+
+
+ + + + + + + + + + + + + + +

+ CopyTo(IMemoryBlock, void*) + +

+ +

Copies the entire contents of this storage to given address.

+
+
+ +
+
public static void CopyTo(this IMemoryBlock src, void* dstAddress)
+
+ +

Parameters

+
+
src IMemoryBlock
+

The source of the copying

+
+
dstAddress void*
+

The address to copy to.

+
+
+ + + + + + + + + + + + + + +

+ CopyTo(IMemoryBlock, void*, int) + +

+ +

Copies the entire contents of this storage to given address (using Count).

+
+
+ +
+
public static void CopyTo(this IMemoryBlock src, void* dstAddress, int countOffsetDesitinion)
+
+ +

Parameters

+
+
src IMemoryBlock
+
+
dstAddress void*
+
+
countOffsetDesitinion int
+
+
+ + + + + + + + + + + + + + +

+ CopyTo<T>(UnmanagedMemoryBlock<T>, UnmanagedMemoryBlock<T>) + +

+ +

Copies the entire contents of this storage to given address (using Count).

+
+
+ +
+
public static void CopyTo<T>(this UnmanagedMemoryBlock<T> src, UnmanagedMemoryBlock<T> dst) where T : unmanaged
+
+ +

Parameters

+
+
src UnmanagedMemoryBlock<T>
+
+
dst UnmanagedMemoryBlock<T>
+

The block to copy to.

+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock-1.html b/docs/website/api/NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock-1.html new file mode 100644 index 000000000..c164cf37a --- /dev/null +++ b/docs/website/api/NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock-1.html @@ -0,0 +1,2916 @@ + + + + + Struct UnmanagedMemoryBlock<T> | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Struct UnmanagedMemoryBlock<T> +

+ +
+
Namespace
NumSharp.Backends.Unmanaged
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public struct UnmanagedMemoryBlock<T> : IUnmanagedMemoryBlock, IMemoryBlock<T>, IMemoryBlock, IEnumerable<T>, IEnumerable, IEquatable<UnmanagedMemoryBlock<T>>, ICloneable where T : unmanaged
+
+ + + +

Type Parameters

+
+
T
+
+
+ + +
+
Implements
+
+ + + + + + + +
+
+ + +
+
Inherited Members
+
+ + + + +
+ +
+
Extension Methods
+
+ + + + + + + + + + + +
+ + + + + +

Constructors +

+ + + + +

+ UnmanagedMemoryBlock(long) + +

+ +
+
+ +
+
public UnmanagedMemoryBlock(long count)
+
+ +

Parameters

+
+
count long
+

The length in objects of T and not in bytes.

+
+
+ + + + + + + + +

Remarks

+

Does claim ownership since allocation is publicly.

+
+ + + + + + +

+ UnmanagedMemoryBlock(long, T) + +

+ +
+
+ +
+
public UnmanagedMemoryBlock(long count, T fill)
+
+ +

Parameters

+
+
count long
+

The length in objects of T and not in bytes.

+
+
fill T
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedMemoryBlock(GCHandle, long) + +

+ +

Construct with externally allocated memory settings this memory block as owner.

+
+
+ +
+
public UnmanagedMemoryBlock(GCHandle handle, long count)
+
+ +

Parameters

+
+
handle GCHandle
+
+
count long
+

The length in objects of T and not in bytes.

+
+
+ + + + + + + + +

Remarks

+

Does claim ownership.

+
+ + + + + + +

+ UnmanagedMemoryBlock(GCHandle, long, Action) + +

+ +

Construct with externally allocated memory and a custom dispose function.

+
+
+ +
+
public UnmanagedMemoryBlock(GCHandle handle, long count, Action dispose)
+
+ +

Parameters

+
+
handle GCHandle
+
+
count long
+

The length in objects of T and not in bytes.

+
+
dispose Action
+
+
+ + + + + + + + +

Remarks

+

Does claim ownership.

+
+ + + + + + +

+ UnmanagedMemoryBlock(T*, long) + +

+ +

Construct as a wrapper around pointer and given length without claiming ownership.

+
+
+ +
+
public UnmanagedMemoryBlock(T* ptr, long count)
+
+ +

Parameters

+
+
ptr T*
+
+
count long
+

The length in objects of T and not in bytes.

+
+
+ + + + + + + + +

Remarks

+

Does claim ownership.

+
+ + + + + + +

+ UnmanagedMemoryBlock(T*, long, Action) + +

+ +

Construct with externally allocated memory and a custom dispose function.

+
+
+ +
+
public UnmanagedMemoryBlock(T* start, long count, Action dispose)
+
+ +

Parameters

+
+
start T*
+
+
count long
+

The length in objects of T and not in bytes.

+
+
dispose Action
+
+
+ + + + + + + + +

Remarks

+

Does claim ownership.

+
+ + + + +

Fields +

+ + + +

+ Address + +

+ +
+
+ +
+
public readonly T* Address
+
+ + + + +

Field Value

+
+
T*
+
+
+ + + + + + + + + + +

+ BytesCount + +

+ +
+
+ +
+
public readonly long BytesCount
+
+ + + + +

Field Value

+
+
long
+
+
+ + + + + + + + + + +

+ Count + +

+ +
+
+ +
+
public readonly long Count
+
+ + + + +

Field Value

+
+
long
+
+
+ + + + + + + + + +

Properties +

+ + + + +

+ this[int] + +

+ +
+
+ +
+
public T this[int index] { get; set; }
+
+ +

Parameters

+
+
index int
+
+
+ + + + +

Property Value

+
+
T
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ Clone() + +

+ +

Performs a copy to this memory block.

+
+
+ +
+
public UnmanagedMemoryBlock<T> Clone()
+
+ + +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ Contains(T) + +

+ +
+
+ +
+
public bool Contains(T item)
+
+ +

Parameters

+
+
item T
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ Copy(UnmanagedMemoryBlock<T>) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> Copy(UnmanagedMemoryBlock<T> source)
+
+ +

Parameters

+
+
source UnmanagedMemoryBlock<T>
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ Copy(nint, int) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> Copy(nint address, int count)
+
+ +

Parameters

+
+
address nint
+
+
count int
+

How many T to copy, not how many bytes.

+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ Copy(void*, int) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> Copy(void* address, int count)
+
+ +

Parameters

+
+
address void*
+

The address of the first T

+
+
count int
+

How many T to copy, not how many bytes.

+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ Copy(T*, int) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> Copy(T* address, int count)
+
+ +

Parameters

+
+
address T*
+

The address of the first T

+
+
count int
+

How many T to copy, not how many bytes.

+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ CopyTo(UnmanagedMemoryBlock<T>, long) + +

+ +
+
+ +
+
public void CopyTo(UnmanagedMemoryBlock<T> memoryBlock, long arrayIndex)
+
+ +

Parameters

+
+
memoryBlock UnmanagedMemoryBlock<T>
+
+
arrayIndex long
+
+
+ + + + + + + + + + + + + + +

+ CopyTo(Array, int) + +

+ +

Copies the elements of the ICollection to an Array, starting at a particular Array index.

+
+
+ +
+
public void CopyTo(Array array, int arrayIndex)
+
+ +

Parameters

+
+
array Array
+

The one-dimensional Array that is the destination of the elements copied from ICollection. The Array must have zero-based indexing.

+
+
arrayIndex int
+

The zero-based index in array at which copying begins.

+
+
+ + + + + + + + + +

Exceptions

+
+
ArgumentNullException
+

array is null.

+
+
ArgumentOutOfRangeException
+

arrayIndex is less than zero.

+
+
ArgumentException
+

array is multidimensional.-or- The number of elements in the source ICollection is greater than the available space from arrayIndex to the end of the destination array.-or-The type of the source ICollection cannot be cast automatically to the type of the destination array.

+
+
+ + + + + +

+ CopyTo(T*, long, long) + +

+ +
+
+ +
+
public void CopyTo(T* array, long arrayIndex, long lengthToCopy)
+
+ +

Parameters

+
+
array T*
+
+
arrayIndex long
+
+
lengthToCopy long
+
+
+ + + + + + + + + + + + + + +

+ CopyTo(T[], int) + +

+ +
+
+ +
+
public void CopyTo(T[] array, int arrayIndex)
+
+ +

Parameters

+
+
array T[]
+
+
arrayIndex int
+
+
+ + + + + + + + + + + + + + +

+ Equals(UnmanagedMemoryBlock<T>) + +

+ +

Indicates whether the current object is equal to another object of the same type.

+
+
+ +
+
public bool Equals(UnmanagedMemoryBlock<T> other)
+
+ +

Parameters

+
+
other UnmanagedMemoryBlock<T>
+

An object to compare with this object.

+
+
+ +

Returns

+
+
bool
+

true if the current object is equal to the other parameter; otherwise, false.

+
+
+ + + + + + + + + + + + + +

+ Equals(object) + +

+ +

Indicates whether this instance and a specified object are equal.

+
+
+ +
+
public override bool Equals(object obj)
+
+ +

Parameters

+
+
obj object
+

The object to compare with the current instance.

+
+
+ +

Returns

+
+
bool
+

true if obj and this instance are the same type and represent the same value; otherwise, false.

+
+
+ + + + + + + + + + + + + +

+ Fill(T) + +

+ +

Fills the contents of this span with the given value.

+
+
+ +
+
public void Fill(T value)
+
+ +

Parameters

+
+
value T
+
+
+ + + + + + + + + + + + + + +

+ Fill(T, long, long) + +

+ +

Fills the contents of this span with the given value.

+
+
+ +
+
public void Fill(T value, long offset, long count)
+
+ +

Parameters

+
+
value T
+
+
offset long
+
+
count long
+
+
+ + + + + + + + + + + + + + +

+ Free() + +

+ +
+
+ +
+
public void Free()
+
+ + + + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,,,,,,,,,]) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,,,,,] arr)
+
+ +

Parameters

+
+
arr T[,,,,,,,,,,,,,,,]
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,,,,,,,,,], bool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,,,,,] arr, bool copy)
+
+ +

Parameters

+
+
arr T[,,,,,,,,,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,,,,,,,,]) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,,,,] arr)
+
+ +

Parameters

+
+
arr T[,,,,,,,,,,,,,,]
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,,,,,,,,], bool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,,,,] arr, bool copy)
+
+ +

Parameters

+
+
arr T[,,,,,,,,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,,,,,,,]) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,,,] arr)
+
+ +

Parameters

+
+
arr T[,,,,,,,,,,,,,]
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,,,,,,,], bool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,,,] arr, bool copy)
+
+ +

Parameters

+
+
arr T[,,,,,,,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,,,,,,]) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,,] arr)
+
+ +

Parameters

+
+
arr T[,,,,,,,,,,,,]
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,,,,,,], bool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,,] arr, bool copy)
+
+ +

Parameters

+
+
arr T[,,,,,,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,,,,,]) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,] arr)
+
+ +

Parameters

+
+
arr T[,,,,,,,,,,,]
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,,,,,], bool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,] arr, bool copy)
+
+ +

Parameters

+
+
arr T[,,,,,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,,,,]) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,] arr)
+
+ +

Parameters

+
+
arr T[,,,,,,,,,,]
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,,,,], bool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,] arr, bool copy)
+
+ +

Parameters

+
+
arr T[,,,,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,,,]) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,] arr)
+
+ +

Parameters

+
+
arr T[,,,,,,,,,]
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,,,], bool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,] arr, bool copy)
+
+ +

Parameters

+
+
arr T[,,,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,,]) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,] arr)
+
+ +

Parameters

+
+
arr T[,,,,,,,,]
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,,], bool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,] arr, bool copy)
+
+ +

Parameters

+
+
arr T[,,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,]) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,] arr)
+
+ +

Parameters

+
+
arr T[,,,,,,,]
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,,], bool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,] arr, bool copy)
+
+ +

Parameters

+
+
arr T[,,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,]) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,] arr)
+
+ +

Parameters

+
+
arr T[,,,,,,]
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,,], bool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,] arr, bool copy)
+
+ +

Parameters

+
+
arr T[,,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,]) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,] arr)
+
+ +

Parameters

+
+
arr T[,,,,,]
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,,], bool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,] arr, bool copy)
+
+ +

Parameters

+
+
arr T[,,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,]) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,] arr)
+
+ +

Parameters

+
+
arr T[,,,,]
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,,], bool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,] arr, bool copy)
+
+ +

Parameters

+
+
arr T[,,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,]) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,] arr)
+
+ +

Parameters

+
+
arr T[,,,]
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,,], bool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,,] arr, bool copy)
+
+ +

Parameters

+
+
arr T[,,,]
+
+
copy bool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,]) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,] arr)
+
+ +

Parameters

+
+
arr T[,,]
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,,], bool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,,] arr, bool copy)
+
+ +

Parameters

+
+
arr T[,,]
+
+
copy bool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,]) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,] arr)
+
+ +

Parameters

+
+
arr T[,]
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[,], bool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[,] arr, bool copy)
+
+ +

Parameters

+
+
arr T[,]
+
+
copy bool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[]) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[] arr)
+
+ +

Parameters

+
+
arr T[]
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromArray(T[], bool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromArray(T[] arr, bool copy)
+
+ +

Parameters

+
+
arr T[]
+
+
copy bool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromBuffer(byte[]) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromBuffer(byte[] arr)
+
+ +

Parameters

+
+
arr byte[]
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromBuffer(byte[], bool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromBuffer(byte[] arr, bool copy)
+
+ +

Parameters

+
+
arr byte[]
+
+
copy bool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ FromPool(StackedMemoryPool) + +

+ +
+
+ +
+
public static UnmanagedMemoryBlock<T> FromPool(StackedMemoryPool manager)
+
+ +

Parameters

+
+
manager StackedMemoryPool
+
+
+ +

Returns

+
+
UnmanagedMemoryBlock<T>
+
+
+ + + + + + + + + + + + + +

+ GetEnumerator() + +

+ +

Returns an enumerator that iterates through the collection.

+
+
+ +
+
public IEnumerator<T> GetEnumerator()
+
+ + +

Returns

+
+
IEnumerator<T>
+

An enumerator that can be used to iterate through the collection.

+
+
+ + + + + + + + + + + + + +

+ GetHashCode() + +

+ +

Returns the hash code for this instance.

+
+
+ +
+
public override int GetHashCode()
+
+ + +

Returns

+
+
int
+

A 32-bit signed integer that is the hash code for this instance.

+
+
+ + + + + + + + + + + + + +

+ GetIndex(int) + +

+ +
+
+ +
+
public T GetIndex(int index)
+
+ +

Parameters

+
+
index int
+
+
+ +

Returns

+
+
T
+
+
+ + + + + + + + + + + + + +

+ GetIndex(long) + +

+ +
+
+ +
+
public T GetIndex(long index)
+
+ +

Parameters

+
+
index long
+
+
+ +

Returns

+
+
T
+
+
+ + + + + + + + + + + + + +

+ GetRefTo(int) + +

+ +
+
+ +
+
public ref T GetRefTo(int index)
+
+ +

Parameters

+
+
index int
+
+
+ +

Returns

+
+
T
+
+
+ + + + + + + + + + + + + +

+ GetRefTo(long) + +

+ +
+
+ +
+
public ref T GetRefTo(long index)
+
+ +

Parameters

+
+
index long
+
+
+ +

Returns

+
+
T
+
+
+ + + + + + + + + + + + + +

+ Reallocate(long, bool) + +

+ +
+
+ +
+
public void Reallocate(long length, bool copyOldValues = false)
+
+ +

Parameters

+
+
length long
+
+
copyOldValues bool
+
+
+ + + + + + + + + + + + + + +

+ Reallocate(long, T, bool) + +

+ +
+
+ +
+
public void Reallocate(long length, T fill, bool copyOldValues = false)
+
+ +

Parameters

+
+
length long
+
+
fill T
+
+
copyOldValues bool
+
+
+ + + + + + + + + + + + + + +

+ SetIndex(int, T) + +

+ +
+
+ +
+
public void SetIndex(int index, T value)
+
+ +

Parameters

+
+
index int
+
+
value T
+
+
+ + + + + + + + + + + + + + +

+ SetIndex(int, ref T) + +

+ +
+
+ +
+
public void SetIndex(int index, ref T value)
+
+ +

Parameters

+
+
index int
+
+
value T
+
+
+ + + + + + + + + + + + + + +

+ SetIndex(long, T) + +

+ +
+
+ +
+
public void SetIndex(long index, T value)
+
+ +

Parameters

+
+
index long
+
+
value T
+
+
+ + + + + + + + + + + + + + +

+ SetIndex(long, ref T) + +

+ +
+
+ +
+
public void SetIndex(long index, ref T value)
+
+ +

Parameters

+
+
index long
+
+
value T
+
+
+ + + + + + + + + + + + +

Operators +

+ + + + +

+ operator ==(UnmanagedMemoryBlock<T>, UnmanagedMemoryBlock<T>) + +

+ +

Returns a value that indicates whether the values of two NumSharp.Backends.Unmanaged.UnmanagedArray`1 objects are equal.

+
+
+ +
+
public static bool operator ==(UnmanagedMemoryBlock<T> left, UnmanagedMemoryBlock<T> right)
+
+ +

Parameters

+
+
left UnmanagedMemoryBlock<T>
+

The first value to compare.

+
+
right UnmanagedMemoryBlock<T>
+

The second value to compare.

+
+
+ +

Returns

+
+
bool
+

true if the left and right parameters have the same value; otherwise, false.

+
+
+ + + + + + + + + + + + + +

+ operator !=(UnmanagedMemoryBlock<T>, UnmanagedMemoryBlock<T>) + +

+ +

Returns a value that indicates whether two NumSharp.Backends.Unmanaged.UnmanagedArray`1 objects have different values.

+
+
+ +
+
public static bool operator !=(UnmanagedMemoryBlock<T> left, UnmanagedMemoryBlock<T> right)
+
+ +

Parameters

+
+
left UnmanagedMemoryBlock<T>
+

The first value to compare.

+
+
right UnmanagedMemoryBlock<T>
+

The second value to compare.

+
+
+ +

Returns

+
+
bool
+

true if left and right are not equal; otherwise, false.

+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock.html b/docs/website/api/NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock.html new file mode 100644 index 000000000..fca68307e --- /dev/null +++ b/docs/website/api/NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock.html @@ -0,0 +1,515 @@ + + + + + Class UnmanagedMemoryBlock | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class UnmanagedMemoryBlock +

+ +
+
Namespace
NumSharp.Backends.Unmanaged
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public static class UnmanagedMemoryBlock
+
+ + + + +
+
Inheritance
+
+ +
UnmanagedMemoryBlock
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Methods +

+ + + + +

+ Allocate(Type, int) + +

+ +
+
+ +
+
public static IMemoryBlock Allocate(Type elementType, int count)
+
+ +

Parameters

+
+
elementType Type
+
+
count int
+
+
+ +

Returns

+
+
IMemoryBlock
+
+
+ + + + + + + + + + + + + +

+ Allocate(Type, int, object) + +

+ +
+
+ +
+
public static IMemoryBlock Allocate(Type elementType, int count, object fill)
+
+ +

Parameters

+
+
elementType Type
+
+
count int
+
+
fill object
+
+
+ +

Returns

+
+
IMemoryBlock
+
+
+ + + + + + + + + + + + + +

+ CastTo(IMemoryBlock, IMemoryBlock, int?, int?) + +

+ +
+
+ +
+
public static void CastTo(this IMemoryBlock source, IMemoryBlock @out, int? bytesOffset = null, int? countOffset = null)
+
+ +

Parameters

+
+
source IMemoryBlock
+
+
out IMemoryBlock
+
+
bytesOffset int?
+
+
countOffset int?
+
+
+ + + + + + + + +

Remarks

+

Returns a copy.

+
+ + + + + + +

+ CastTo(IMemoryBlock, NPTypeCode) + +

+ +
+
+ +
+
public static IMemoryBlock CastTo(this IMemoryBlock source, NPTypeCode to)
+
+ +

Parameters

+
+
source IMemoryBlock
+
+
to NPTypeCode
+

The type to cast this memory block to.

+
+
+ +

Returns

+
+
IMemoryBlock
+
+
+ + + + + + + +

Remarks

+

Returns a copy.

+
+ + + + + + +

+ CastTo<TOut>(IMemoryBlock) + +

+ +
+
+ +
+
public static IMemoryBlock<TOut> CastTo<TOut>(this IMemoryBlock source) where TOut : unmanaged
+
+ +

Parameters

+
+
source IMemoryBlock
+
+
+ +

Returns

+
+
IMemoryBlock<TOut>
+
+
+ +

Type Parameters

+
+
TOut
+
+
+ + + + + + +

Remarks

+

Returns a copy.

+
+ + + + + + +

+ CastTo<TIn, TOut>(IMemoryBlock) + +

+ +
+
+ +
+
public static IMemoryBlock<TOut> CastTo<TIn, TOut>(this IMemoryBlock source) where TIn : unmanaged where TOut : unmanaged
+
+ +

Parameters

+
+
source IMemoryBlock
+
+
+ +

Returns

+
+
IMemoryBlock<TOut>
+
+
+ +

Type Parameters

+
+
TIn
+
+
TOut
+
+
+ + + + + + +

Remarks

+

Returns a copy.

+
+ + + + + + +

+ CastTo<TIn, TOut>(IMemoryBlock<TIn>) + +

+ +
+
+ +
+
public static IMemoryBlock<TOut> CastTo<TIn, TOut>(this IMemoryBlock<TIn> source) where TIn : unmanaged where TOut : unmanaged
+
+ +

Parameters

+
+
source IMemoryBlock<TIn>
+
+
+ +

Returns

+
+
IMemoryBlock<TOut>
+
+
+ +

Type Parameters

+
+
TIn
+
+
TOut
+
+
+ + + + + + +

Remarks

+

Returns a copy.

+
+ + + + + + +

+ FromArray(Array, bool, Type) + +

+ +
+
+ +
+
public static IMemoryBlock FromArray(Array arr, bool copy, Type elementType = null)
+
+ +

Parameters

+
+
arr Array
+
+
copy bool
+
+
elementType Type
+
+
+ +

Returns

+
+
IMemoryBlock
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Backends.Unmanaged.html b/docs/website/api/NumSharp.Backends.Unmanaged.html new file mode 100644 index 000000000..77208d5b9 --- /dev/null +++ b/docs/website/api/NumSharp.Backends.Unmanaged.html @@ -0,0 +1,165 @@ + + + + + Namespace NumSharp.Backends.Unmanaged | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ + + +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Backends.UnmanagedStorage.html b/docs/website/api/NumSharp.Backends.UnmanagedStorage.html new file mode 100644 index 000000000..d7ff8dff6 --- /dev/null +++ b/docs/website/api/NumSharp.Backends.UnmanagedStorage.html @@ -0,0 +1,5729 @@ + + + + + Class UnmanagedStorage | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class UnmanagedStorage +

+ +
+
Namespace
NumSharp.Backends
+
Assembly
NumSharp.dll
+
+ +

Serves as a typed storage for an array.

+
+
+ +
+
public class UnmanagedStorage : ICloneable
+
+ + + + +
+
Inheritance
+
+ +
UnmanagedStorage
+
+
+ +
+
Implements
+
+ +
+
+ + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ + +
+ + + +

Remarks

+

Responsible for :

+
    +
  • store data type, elements, Shape
  • +
  • offers methods for accessing elements depending on shape
  • +
  • offers methods for casting elements
  • +
  • offers methods for change tensor order
  • +
  • GetData always return reference object to the true storage
  • +
  • GetData{T} and SetData{T} change dtype and cast storage
  • +
  • CloneData always create a clone of storage and return this as reference object
  • +
  • CloneData{T} clone storage and cast this clone
  • +
+
+ + +

Constructors +

+ + + + +

+ UnmanagedStorage(IArraySlice, Shape) + +

+ +

Wraps given arraySlice in UnmanagedStorage.

+
+
+ +
+
public UnmanagedStorage(IArraySlice arraySlice, Shape shape)
+
+ +

Parameters

+
+
arraySlice IArraySlice
+

The slice to wrap

+
+
shape Shape
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(NPTypeCode) + +

+ +

Creates an empty storage of type typeCode.

+
+
+ +
+
public UnmanagedStorage(NPTypeCode typeCode)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+

The type of this storage

+
+
+ + + + + + + + +

Remarks

+

Usually Allocate(Shape, Type) is called after this constructor.

+
+ + + + + + +

+ UnmanagedStorage(bool) + +

+ +
+
+ +
+
public UnmanagedStorage(bool scalar)
+
+ +

Parameters

+
+
scalar bool
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(bool[]) + +

+ +
+
+ +
+
public UnmanagedStorage(bool[] values)
+
+ +

Parameters

+
+
values bool[]
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(byte) + +

+ +
+
+ +
+
public UnmanagedStorage(byte scalar)
+
+ +

Parameters

+
+
scalar byte
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(byte[]) + +

+ +
+
+ +
+
public UnmanagedStorage(byte[] values)
+
+ +

Parameters

+
+
values byte[]
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(char) + +

+ +
+
+ +
+
public UnmanagedStorage(char scalar)
+
+ +

Parameters

+
+
scalar char
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(char[]) + +

+ +
+
+ +
+
public UnmanagedStorage(char[] values)
+
+ +

Parameters

+
+
values char[]
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(decimal) + +

+ +
+
+ +
+
public UnmanagedStorage(decimal scalar)
+
+ +

Parameters

+
+
scalar decimal
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(decimal[]) + +

+ +
+
+ +
+
public UnmanagedStorage(decimal[] values)
+
+ +

Parameters

+
+
values decimal[]
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(double) + +

+ +
+
+ +
+
public UnmanagedStorage(double scalar)
+
+ +

Parameters

+
+
scalar double
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(double[]) + +

+ +
+
+ +
+
public UnmanagedStorage(double[] values)
+
+ +

Parameters

+
+
values double[]
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(short) + +

+ +
+
+ +
+
public UnmanagedStorage(short scalar)
+
+ +

Parameters

+
+
scalar short
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(short[]) + +

+ +
+
+ +
+
public UnmanagedStorage(short[] values)
+
+ +

Parameters

+
+
values short[]
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(int) + +

+ +
+
+ +
+
public UnmanagedStorage(int scalar)
+
+ +

Parameters

+
+
scalar int
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(int[]) + +

+ +
+
+ +
+
public UnmanagedStorage(int[] values)
+
+ +

Parameters

+
+
values int[]
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(long) + +

+ +
+
+ +
+
public UnmanagedStorage(long scalar)
+
+ +

Parameters

+
+
scalar long
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(long[]) + +

+ +
+
+ +
+
public UnmanagedStorage(long[] values)
+
+ +

Parameters

+
+
values long[]
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(float) + +

+ +
+
+ +
+
public UnmanagedStorage(float scalar)
+
+ +

Parameters

+
+
scalar float
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(float[]) + +

+ +
+
+ +
+
public UnmanagedStorage(float[] values)
+
+ +

Parameters

+
+
values float[]
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(Type) + +

+ +

Creates an empty storage of type dtype.

+
+
+ +
+
public UnmanagedStorage(Type dtype)
+
+ +

Parameters

+
+
dtype Type
+

The type of this storage

+
+
+ + + + + + + + +

Remarks

+

Usually Allocate(Shape, Type) is called after this constructor.

+
+ + + + + + +

+ UnmanagedStorage(ushort) + +

+ +
+
+ +
+
public UnmanagedStorage(ushort scalar)
+
+ +

Parameters

+
+
scalar ushort
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(ushort[]) + +

+ +
+
+ +
+
public UnmanagedStorage(ushort[] values)
+
+ +

Parameters

+
+
values ushort[]
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(uint) + +

+ +
+
+ +
+
public UnmanagedStorage(uint scalar)
+
+ +

Parameters

+
+
scalar uint
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(uint[]) + +

+ +
+
+ +
+
public UnmanagedStorage(uint[] values)
+
+ +

Parameters

+
+
values uint[]
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(ulong) + +

+ +
+
+ +
+
public UnmanagedStorage(ulong scalar)
+
+ +

Parameters

+
+
scalar ulong
+
+
+ + + + + + + + + + + + + + +

+ UnmanagedStorage(ulong[]) + +

+ +
+
+ +
+
public UnmanagedStorage(ulong[] values)
+
+ +

Parameters

+
+
values ulong[]
+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ Address + +

+ +
+
+ +
+
public byte* Address
+
+ + + + +

Field Value

+
+
byte*
+
+
+ + + + + + + + + + +

+ Count + +

+ +
+
+ +
+
public int Count
+
+ + + + +

Field Value

+
+
int
+
+
+ + + + + + + + + + +

+ InternalArray + +

+ +
+
+ +
+
public IArraySlice InternalArray
+
+ + + + +

Field Value

+
+
IArraySlice
+
+
+ + + + + + + + + + +

+ _arrayBoolean + +

+ +
+
+ +
+
protected ArraySlice<bool> _arrayBoolean
+
+ + + + +

Field Value

+
+
ArraySlice<bool>
+
+
+ + + + + + + + + + +

+ _arrayByte + +

+ +
+
+ +
+
protected ArraySlice<byte> _arrayByte
+
+ + + + +

Field Value

+
+
ArraySlice<byte>
+
+
+ + + + + + + + + + +

+ _arrayChar + +

+ +
+
+ +
+
protected ArraySlice<char> _arrayChar
+
+ + + + +

Field Value

+
+
ArraySlice<char>
+
+
+ + + + + + + + + + +

+ _arrayDecimal + +

+ +
+
+ +
+
protected ArraySlice<decimal> _arrayDecimal
+
+ + + + +

Field Value

+
+
ArraySlice<decimal>
+
+
+ + + + + + + + + + +

+ _arrayDouble + +

+ +
+
+ +
+
protected ArraySlice<double> _arrayDouble
+
+ + + + +

Field Value

+
+
ArraySlice<double>
+
+
+ + + + + + + + + + +

+ _arrayInt16 + +

+ +
+
+ +
+
protected ArraySlice<short> _arrayInt16
+
+ + + + +

Field Value

+
+
ArraySlice<short>
+
+
+ + + + + + + + + + +

+ _arrayInt32 + +

+ +
+
+ +
+
protected ArraySlice<int> _arrayInt32
+
+ + + + +

Field Value

+
+
ArraySlice<int>
+
+
+ + + + + + + + + + +

+ _arrayInt64 + +

+ +
+
+ +
+
protected ArraySlice<long> _arrayInt64
+
+ + + + +

Field Value

+
+
ArraySlice<long>
+
+
+ + + + + + + + + + +

+ _arraySingle + +

+ +
+
+ +
+
protected ArraySlice<float> _arraySingle
+
+ + + + +

Field Value

+
+
ArraySlice<float>
+
+
+ + + + + + + + + + +

+ _arrayUInt16 + +

+ +
+
+ +
+
protected ArraySlice<ushort> _arrayUInt16
+
+ + + + +

Field Value

+
+
ArraySlice<ushort>
+
+
+ + + + + + + + + + +

+ _arrayUInt32 + +

+ +
+
+ +
+
protected ArraySlice<uint> _arrayUInt32
+
+ + + + +

Field Value

+
+
ArraySlice<uint>
+
+
+ + + + + + + + + + +

+ _arrayUInt64 + +

+ +
+
+ +
+
protected ArraySlice<ulong> _arrayUInt64
+
+ + + + +

Field Value

+
+
ArraySlice<ulong>
+
+
+ + + + + + + + + + +

+ _dtype + +

+ +
+
+ +
+
protected Type _dtype
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ _shape + +

+ +
+
+ +
+
protected Shape _shape
+
+ + + + +

Field Value

+
+
Shape
+
+
+ + + + + + + + + + +

+ _typecode + +

+ +
+
+ +
+
protected NPTypeCode _typecode
+
+ + + + +

Field Value

+
+
NPTypeCode
+
+
+ + + + + + + + + +

Properties +

+ + + + +

+ DType + +

+ +

The data type of internal storage array.

+
+
+ +
+
public Type DType { get; }
+
+ + + + + +

Property Value

+
+
Type
+

numpys equal dtype

+
+
+ + + + +

Remarks

+

Has to be compliant with NPTypeCode.

+
+ + + + + + +

+ DTypeSize + +

+ +

The size in bytes of a single value of DType

+
+
+ +
+
public int DTypeSize { get; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + +

Remarks

+

Computed by SizeOf(object)

+
+ + + + + + +

+ Engine + +

+ +

The engine that was used to create this IStorage.

+
+
+ +
+
public TensorEngine Engine { get; protected set; }
+
+ + + + + +

Property Value

+
+
TensorEngine
+
+
+ + + + + + + + + + +

+ Shape + +

+ +

The shape representing the data in this storage.

+
+
+ +
+
public Shape Shape { get; set; }
+
+ + + + + +

Property Value

+
+
Shape
+
+
+ + + + + + + + + + +

+ ShapeReference + +

+ +

The shape representing the data in this storage.

+
+
+ +
+
public ref Shape ShapeReference { get; }
+
+ + + + + +

Property Value

+
+
Shape
+
+
+ + + + +

Remarks

+

It is dangerous to set Shape by reference. use Reshape(Shape) instead.

+
+ + + + + + +

+ TypeCode + +

+ +

The NPTypeCode of IStorage.DType.

+
+
+ +
+
public NPTypeCode TypeCode { get; }
+
+ + + + + +

Property Value

+
+
NPTypeCode
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ Alias() + +

+ +

Creates an alias to this UnmanagedStorage.

+
+
+ +
+
public UnmanagedStorage Alias()
+
+ + +

Returns

+
+
UnmanagedStorage
+
+
+ + + + + + + + + + + + + +

+ Alias(Shape) + +

+ +

Creates an alias to this UnmanagedStorage with a specific shape.

+
+
+ +
+
public UnmanagedStorage Alias(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ +

Returns

+
+
UnmanagedStorage
+
+
+ + + + + + + +

Remarks

+

Doesn't check if Shape matches the internal storage.

+
+ + + + + + +

+ Alias(ref Shape) + +

+ +

Creates an alias to this UnmanagedStorage with a specific shape.

+
+
+ +
+
public UnmanagedStorage Alias(ref Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ +

Returns

+
+
UnmanagedStorage
+
+
+ + + + + + + +

Remarks

+

Doesn't check if Shape matches the internal storage.

+
+ + + + + + +

+ Allocate(IArraySlice, Shape, bool) + +

+ +

Allocate values into memory.

+
+
+ +
+
public void Allocate(IArraySlice values, Shape shape, bool copy = false)
+
+ +

Parameters

+
+
values IArraySlice
+

The array to set as internal data storage

+
+
shape Shape
+

The shape of the array.

+
+
copy bool
+

Should perform a copy of values

+
+
+ + + + + + + + +

Remarks

+

Does not copy values

+
+ + + + + + +

+ Allocate(Shape, NPTypeCode, bool) + +

+ +

Allocates a new Array into memory.

+
+
+ +
+
public void Allocate(Shape shape, NPTypeCode dtype, bool fillZeros)
+
+ +

Parameters

+
+
shape Shape
+

The shape of the array.

+
+
dtype NPTypeCode
+

The type of the Array, if null DType is used.

+
+
fillZeros bool
+
+
+ + + + + + + + + + + + + + +

+ Allocate(Shape, Type) + +

+ +

Allocates a new Array into memory.

+
+
+ +
+
public void Allocate(Shape shape, Type dtype = null)
+
+ +

Parameters

+
+
shape Shape
+

The shape of the array.

+
+
dtype Type
+

The type of the Array, if null DType is used.

+
+
+ + + + + + + + + + + + + + +

+ Allocate(Shape, Type, bool) + +

+ +

Allocates a new Array into memory.

+
+
+ +
+
public void Allocate(Shape shape, Type dtype, bool fillZeros)
+
+ +

Parameters

+
+
shape Shape
+

The shape of the array.

+
+
dtype Type
+

The type of the Array, if null DType is used.

+
+
fillZeros bool
+
+
+ + + + + + + + + + + + + + +

+ Allocate(Array) + +

+ +

Allocate array into memory.

+
+
+ +
+
public void Allocate(Array array)
+
+ +

Parameters

+
+
array Array
+

The array to set as internal data storage

+
+
+ + + + + + + + +

Remarks

+

Does not copy array

+
+ + + + + + +

+ Allocate(Array, Shape) + +

+ +

Allocate values into memory.

+
+
+ +
+
public void Allocate(Array values, Shape shape)
+
+ +

Parameters

+
+
values Array
+

The array to set as internal data storage

+
+
shape Shape
+

The shape of given array

+
+
+ + + + + + + + +

Remarks

+

Does not copy values

+
+ + + + + + +

+ Allocate<T>(ArraySlice<T>, Shape, bool) + +

+ +

Assign this ArraySlice<T> as the internal array storage and assign shape to it.

+
+
+ +
+
public void Allocate<T>(ArraySlice<T> values, Shape shape, bool copy = false) where T : unmanaged
+
+ +

Parameters

+
+
values ArraySlice<T>
+

The array to set as internal data storage

+
+
shape Shape
+

The shape of the array.

+
+
copy bool
+

Should perform a copy of values

+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+

Does not copy values

+
+ + + + + + +

+ Allocate<T>(T[]) + +

+ +

Allocate values into memory.

+
+
+ +
+
public void Allocate<T>(T[] values) where T : unmanaged
+
+ +

Parameters

+
+
values T[]
+

The array to set as internal data storage

+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+

Does not copy values

+
+ + + + + + +

+ AsSpan<T>() + +

+ +

Spans Address <-> Count

+
+
+ +
+
public Span<T> AsSpan<T>()
+
+ + +

Returns

+
+
Span<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+

This ignores completely slicing.

+
+ + + + + + +

+ Cast(NPTypeCode) + +

+ +

Return a casted UnmanagedStorage to a specific dtype.

+
+
+ +
+
public UnmanagedStorage Cast(NPTypeCode typeCode)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+

The dtype to convert to

+
+
+ +

Returns

+
+
UnmanagedStorage
+

A copy of this UnmanagedStorage casted to a specific dtype.

+
+
+ + + + + + + +

Remarks

+

Always copies, If dtype==typeof(T) then a Clone() is returned.

+
+ + + + + + +

+ Cast(Type) + +

+ +

Return a casted UnmanagedStorage to a specific dtype.

+
+
+ +
+
public UnmanagedStorage Cast(Type dtype)
+
+ +

Parameters

+
+
dtype Type
+

The dtype to convert to

+
+
+ +

Returns

+
+
UnmanagedStorage
+

A copy of this UnmanagedStorage casted to a specific dtype.

+
+
+ + + + + + + +

Remarks

+

Always copies, If dtype==typeof(T) then a Clone() is returned.

+
+ + + + + + +

+ CastIfNecessary(NPTypeCode) + +

+ +

Return a casted UnmanagedStorage to a specific dtype only if necessary

+
+
+ +
+
public UnmanagedStorage CastIfNecessary(NPTypeCode typeCode)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+

The dtype to convert to

+
+
+ +

Returns

+
+
UnmanagedStorage
+

A copy of this UnmanagedStorage casted to a specific dtype.

+
+
+ + + + + + + +

Remarks

+

Copies only if dtypes does not match typeCode

+
+ + + + + + +

+ CastIfNecessary(Type) + +

+ +

Return a casted UnmanagedStorage to a specific dtype.

+
+
+ +
+
public UnmanagedStorage CastIfNecessary(Type dtype)
+
+ +

Parameters

+
+
dtype Type
+

The dtype to convert to

+
+
+ +

Returns

+
+
UnmanagedStorage
+

A copy of this UnmanagedStorage casted to a specific dtype.

+
+
+ + + + + + + +

Remarks

+

Copies only if dtypes does not match typeCode

+
+ + + + + + +

+ CastIfNecessary<T>() + +

+ +

Return a casted UnmanagedStorage to a specific dtype only if necessary.

+
+
+ +
+
public UnmanagedStorage CastIfNecessary<T>() where T : unmanaged
+
+ + +

Returns

+
+
UnmanagedStorage
+

A copy of this UnmanagedStorage casted to a specific dtype.

+
+
+ +

Type Parameters

+
+
T
+

The dtype to convert to

+
+
+ + + + + + +

Remarks

+

Copies only if dtypes does not match T

+
+ + + + + + +

+ Cast<T>() + +

+ +

Return a casted UnmanagedStorage to a specific dtype.

+
+
+ +
+
public UnmanagedStorage Cast<T>() where T : unmanaged
+
+ + +

Returns

+
+
UnmanagedStorage
+

A copy of this UnmanagedStorage casted to a specific dtype.

+
+
+ +

Type Parameters

+
+
T
+

The dtype to convert to

+
+
+ + + + + + +

Remarks

+

Always copies, If dtype==typeof(T) then a Clone() is returned.

+
+ + + + + + +

+ Clone() + +

+ +

Perform a complete copy of this UnmanagedStorage and InternalArray.

+
+
+ +
+
public UnmanagedStorage Clone()
+
+ + +

Returns

+
+
UnmanagedStorage
+
+
+ + + + + + + +

Remarks

+

If shape is sliced, discards any slicing properties but copies only the sliced data

+
+ + + + + + +

+ CloneData() + +

+ +

Clone internal storage and get reference to it

+
+
+ +
+
public IArraySlice CloneData()
+
+ + +

Returns

+
+
IArraySlice
+

reference to cloned storage as System.Array

+
+
+ + + + + + + + + + + + + +

+ CloneData<T>() + +

+ +

Get all elements from cloned storage as ArraySlice<T> and cast if necessary.

+
+
+ +
+
public ArraySlice<T> CloneData<T>() where T : unmanaged
+
+ + +

Returns

+
+
ArraySlice<T>
+

reference to cloned storage and casted (if necessary) as ArraySlice<T>

+
+
+ +

Type Parameters

+
+
T
+

cloned storgae dtype

+
+
+ + + + + + + + + + + + +

+ CopyTo(IMemoryBlock) + +

+ +

Copies the entire contents of this storage to given address (using Count).

+
+
+ +
+
public void CopyTo(IMemoryBlock block)
+
+ +

Parameters

+
+
block IMemoryBlock
+

The block to copy to.

+
+
+ + + + + + + + + + + + + + +

+ CopyTo(nint) + +

+ +

Copies the entire contents of this storage to given address.

+
+
+ +
+
public void CopyTo(nint ptr)
+
+ +

Parameters

+
+
ptr nint
+
+
+ + + + + + + + + + + + + + +

+ CopyTo(void*) + +

+ +

Copies the entire contents of this storage to given address.

+
+
+ +
+
public void CopyTo(void* address)
+
+ +

Parameters

+
+
address void*
+

The address to copy to.

+
+
+ + + + + + + + + + + + + + +

+ CopyTo<T>(IMemoryBlock<T>) + +

+ +

Copies the entire contents of this storage to given address (using Count).

+
+
+ +
+
public void CopyTo<T>(IMemoryBlock<T> block) where T : unmanaged
+
+ +

Parameters

+
+
block IMemoryBlock<T>
+

The block to copy to.

+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ CopyTo<T>(T*) + +

+ +

Copies the entire contents of this storage to given address.

+
+
+ +
+
public void CopyTo<T>(T* address) where T : unmanaged
+
+ +

Parameters

+
+
address T*
+

The address to copy to.

+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ CopyTo<T>(T[]) + +

+ +

Copies the entire contents of this storage to given array.

+
+
+ +
+
public void CopyTo<T>(T[] array) where T : unmanaged
+
+ +

Parameters

+
+
array T[]
+

The array to copy to.

+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ CreateBroadcastedUnsafe(IArraySlice, Shape) + +

+ +

Wraps given arraySlice in UnmanagedStorage with a broadcasted shape.

+
+
+ +
+
public static UnmanagedStorage CreateBroadcastedUnsafe(IArraySlice arraySlice, Shape shape)
+
+ +

Parameters

+
+
arraySlice IArraySlice
+

The slice to wrap

+
+
shape Shape
+

The shape to represent this storage, can be a broadcast.

+
+
+ +

Returns

+
+
UnmanagedStorage
+
+
+ + + + + + + +

Remarks

+

Named unsafe because there it does not perform a check if the shape is valid for this storage size.

+
+ + + + + + +

+ CreateBroadcastedUnsafe(UnmanagedStorage, Shape) + +

+ +

Wraps given storage in UnmanagedStorage with a broadcasted shape.

+
+
+ +
+
public static UnmanagedStorage CreateBroadcastedUnsafe(UnmanagedStorage storage, Shape shape)
+
+ +

Parameters

+
+
storage UnmanagedStorage
+

The storage to take InternalArray from.

+
+
shape Shape
+

The shape to represent this storage, can be a broadcast.

+
+
+ +

Returns

+
+
UnmanagedStorage
+
+
+ + + + + + + +

Remarks

+

Named unsafe because there it does not perform a check if the shape is valid for this storage size.

+
+ + + + + + +

+ ExpandDimension(int) + +

+ +
+
+ +
+
protected void ExpandDimension(int axis)
+
+ +

Parameters

+
+
axis int
+
+
+ + + + + + + + + + + + + + +

+ GetAtIndex(int) + +

+ +
+
+ +
+
public ValueType GetAtIndex(int index)
+
+ +

Parameters

+
+
index int
+
+
+ +

Returns

+
+
ValueType
+
+
+ + + + + + + + + + + + + +

+ GetAtIndex<T>(int) + +

+ +
+
+ +
+
public T GetAtIndex<T>(int index) where T : unmanaged
+
+ +

Parameters

+
+
index int
+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ GetBoolean(params int[]) + +

+ +

Retrieves value of type bool from internal storage.

+
+
+ +
+
public bool GetBoolean(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not bool

+
+
+ + + + + +

+ GetByte(params int[]) + +

+ +

Retrieves value of type byte from internal storage.

+
+
+ +
+
public byte GetByte(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not byte

+
+
+ + + + + +

+ GetChar(params int[]) + +

+ +

Retrieves value of type char from internal storage.

+
+
+ +
+
public char GetChar(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not char

+
+
+ + + + + +

+ GetData() + +

+ +

Get reference to internal data storage

+
+
+ +
+
public IArraySlice GetData()
+
+ + +

Returns

+
+
IArraySlice
+

reference to internal storage as System.Array

+
+
+ + + + + + + + + + + + + +

+ GetData(int*, int) + +

+ +

Gets a subshape based on given indices.

+
+
+ +
+
public UnmanagedStorage GetData(int* dims, int ndims)
+
+ +

Parameters

+
+
dims int*
+
+
ndims int
+
+
+ +

Returns

+
+
UnmanagedStorage
+
+
+ + + + + + + +

Remarks

+

Does not copy, returns a Slice or a memory slice

+
+ + + + + + +

+ GetData(params int[]) + +

+ +

Gets a subshape based on given indices.

+
+
+ +
+
public UnmanagedStorage GetData(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+
+
+ +

Returns

+
+
UnmanagedStorage
+
+
+ + + + + + + +

Remarks

+

Does not copy, returns a Slice or a memory slice

+
+ + + + + + +

+ GetData<T>() + +

+ +

Get reference to internal data storage and cast (also copies) elements to new dtype if necessary

+
+
+ +
+
public ArraySlice<T> GetData<T>() where T : unmanaged
+
+ + +

Returns

+
+
ArraySlice<T>
+

reference to internal (casted) storage as T[]

+
+
+ +

Type Parameters

+
+
T
+

new storage data type

+
+
+ + + + + + +

Remarks

+

Copies if T does not equal to DType or if Shape is sliced.

+
+ + + + + + +

+ GetDecimal(params int[]) + +

+ +

Retrieves value of type decimal from internal storage.

+
+
+ +
+
public decimal GetDecimal(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not decimal

+
+
+ + + + + +

+ GetDouble(params int[]) + +

+ +

Retrieves value of type double from internal storage.

+
+
+ +
+
public double GetDouble(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not double

+
+
+ + + + + +

+ GetInt16(params int[]) + +

+ +

Retrieves value of type short from internal storage.

+
+
+ +
+
public short GetInt16(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not short

+
+
+ + + + + +

+ GetInt32(params int[]) + +

+ +

Retrieves value of type int from internal storage.

+
+
+ +
+
public int GetInt32(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not int

+
+
+ + + + + +

+ GetInt64(params int[]) + +

+ +

Retrieves value of type long from internal storage.

+
+
+ +
+
public long GetInt64(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not long

+
+
+ + + + + +

+ GetSingle(params int[]) + +

+ +

Retrieves value of type float from internal storage.

+
+
+ +
+
public float GetSingle(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not float

+
+
+ + + + + +

+ GetUInt16(params int[]) + +

+ +

Retrieves value of type ushort from internal storage.

+
+
+ +
+
public ushort GetUInt16(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not ushort

+
+
+ + + + + +

+ GetUInt32(params int[]) + +

+ +

Retrieves value of type uint from internal storage.

+
+
+ +
+
public uint GetUInt32(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not uint

+
+
+ + + + + +

+ GetUInt64(params int[]) + +

+ +

Retrieves value of type ulong from internal storage.

+
+
+ +
+
public ulong GetUInt64(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not ulong

+
+
+ + + + + +

+ GetValue(params int[]) + +

+ +

Retrieves value of unspecified type (will figure using IStorage.DType).

+
+
+ +
+
public ValueType GetValue(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
ValueType
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When IStorage.DType is not object

+
+
+ + + + + +

+ GetValue<T>(params int[]) + +

+ +

Get single value from internal storage as type T and cast dtype to T

+
+
+ +
+
public T GetValue<T>(params int[] indices) where T : unmanaged
+
+ +

Parameters

+
+
indices int[]
+

indices

+
+
+ +

Returns

+
+
T
+

element from internal storage

+
+
+ +

Type Parameters

+
+
T
+

new storage data type

+
+
+ + + + + + +

Remarks

+

If you provide less indices than there are dimensions, the rest are filled with 0.

+
+ +

Exceptions

+
+
NullReferenceException
+

When T does not equal to DType

+
+
+ + + + + +

+ GetView(params Slice[]) + +

+ +
+
+ +
+
public UnmanagedStorage GetView(params Slice[] slices)
+
+ +

Parameters

+
+
slices Slice[]
+
+
+ +

Returns

+
+
UnmanagedStorage
+
+
+ + + + + + + + + + + + + +

+ GetView(string) + +

+ +
+
+ +
+
public UnmanagedStorage GetView(string slicing_notation)
+
+ +

Parameters

+
+
slicing_notation string
+
+
+ +

Returns

+
+
UnmanagedStorage
+
+
+ + + + + + + + + + + + + +

+ ReplaceData(IArraySlice) + +

+ +

Sets values as the internal data source and changes the internal storage data type to values type.

+
+
+ +
+
public void ReplaceData(IArraySlice values)
+
+ +

Parameters

+
+
values IArraySlice
+
+
+ + + + + + + + +

Remarks

+

Does not copy values and doesn't change shape.

+
+ + + + + + +

+ ReplaceData(IArraySlice, Shape) + +

+ +

Sets values as the internal data source and changes the internal storage data type to values type.

+
+
+ +
+
public void ReplaceData(IArraySlice values, Shape shape)
+
+ +

Parameters

+
+
values IArraySlice
+
+
shape Shape
+

The shape to set in this storage. (without checking if shape matches storage)

+
+
+ + + + + + + + +

Remarks

+

Does not copy values and doesn't change shape. Doesn't check if shape size matches.

+
+ + + + + + +

+ ReplaceData(IArraySlice, Type) + +

+ +

Sets values as the internal data source and changes the internal storage data type to values type.

+
+
+ +
+
public void ReplaceData(IArraySlice values, Type dtype)
+
+ +

Parameters

+
+
values IArraySlice
+
+
dtype Type
+
+
+ + + + + + + + +

Remarks

+

Does not copy values and doesn't change shape.

+
+ + + + + + +

+ ReplaceData(IArraySlice, Type, Shape) + +

+ +

Sets values as the internal data source and changes the internal storage data type to values type.

+
+
+ +
+
public void ReplaceData(IArraySlice values, Type dtype, Shape shape)
+
+ +

Parameters

+
+
values IArraySlice
+
+
dtype Type
+
+
shape Shape
+

The shape to set in this storage. (without checking if shape matches storage)

+
+
+ + + + + + + + +

Remarks

+

Does not copy values and doesn't change shape. Doesn't check if shape size matches.

+
+ + + + + + +

+ ReplaceData(NDArray) + +

+ +

Sets nd as the internal data storage and changes the internal storage data type to nd type.

+
+
+ +
+
public void ReplaceData(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ + + + + + + + +

Remarks

+

Does not copy values and does change shape and dtype.

+
+ + + + + + +

+ ReplaceData(NDArray, Shape) + +

+ +

Sets nd as the internal data storage and changes the internal storage data type to nd type.

+
+
+ +
+
public void ReplaceData(NDArray nd, Shape shape)
+
+ +

Parameters

+
+
nd NDArray
+
+
shape Shape
+

The shape to set in this storage. (without checking if shape matches storage)

+
+
+ + + + + + + + +

Remarks

+

Does not copy values and does change shape and dtype. Doesn't check if shape size matches.

+
+ + + + + + +

+ ReplaceData(Array) + +

+ +

Sets values as the internal data source and changes the internal storage data type to values type.

+
+
+ +
+
public void ReplaceData(Array values)
+
+ +

Parameters

+
+
values Array
+
+
+ + + + + + + + +

Remarks

+

Copies values only if values type does not match DType and doesn't change shape.

+
+ + + + + + +

+ ReplaceData(Array, NPTypeCode) + +

+ +

Set an Array to internal storage, cast it to new dtype and if necessary change dtype

+
+
+ +
+
public void ReplaceData(Array values, NPTypeCode typeCode)
+
+ +

Parameters

+
+
values Array
+
+
typeCode NPTypeCode
+
+
+ + + + + + + + +

Remarks

+

Does not copy values unless cast is necessary and doesn't change shape.

+
+ + + + + + +

+ ReplaceData(Array, NPTypeCode, Shape) + +

+ +

Set an Array to internal storage, cast it to new dtype and if necessary change dtype

+
+
+ +
+
public void ReplaceData(Array values, NPTypeCode typeCode, Shape shape)
+
+ +

Parameters

+
+
values Array
+
+
typeCode NPTypeCode
+
+
shape Shape
+

The shape to set in this storage. (without checking if shape matches storage)

+
+
+ + + + + + + + +

Remarks

+

Does not copy values unless cast is necessary and doesn't change shape. Doesn't check if shape size matches.

+
+ + + + + + +

+ ReplaceData(Array, Shape) + +

+ +

Sets values as the internal data source and changes the internal storage data type to values type.

+
+
+ +
+
public void ReplaceData(Array values, Shape shape)
+
+ +

Parameters

+
+
values Array
+
+
shape Shape
+

The shape to set in this storage. (without checking if shape matches storage)

+
+
+ + + + + + + + +

Remarks

+

Copies values only if values type does not match DType and doesn't change shape. Doesn't check if shape size matches.

+
+ + + + + + +

+ ReplaceData(Array, Type) + +

+ +

Set an Array to internal storage, cast it to new dtype and change dtype

+
+
+ +
+
public void ReplaceData(Array values, Type dtype)
+
+ +

Parameters

+
+
values Array
+
+
dtype Type
+
+
+ + + + + + + + +

Remarks

+

Does not copy values unless cast in necessary and doesn't change shape.

+
+ + + + + + +

+ ReplaceData(Array, Type, Shape) + +

+ +

Set an Array to internal storage, cast it to new dtype and change dtype

+
+
+ +
+
public void ReplaceData(Array values, Type dtype, Shape shape)
+
+ +

Parameters

+
+
values Array
+
+
dtype Type
+
+
shape Shape
+

The shape to set in this storage. (without checking if shape matches storage)

+
+
+ + + + + + + + +

Remarks

+

Does not copy values unless cast in necessary and doesn't change shape. Doesn't check if shape size matches.

+
+ + + + + + +

+ Reshape(Shape, bool) + +

+ +

Changes the shape representing this storage.

+
+
+ +
+
public void Reshape(Shape newShape, bool @unsafe = false)
+
+ +

Parameters

+
+
newShape Shape
+
+
unsafe bool
+
+
+ + + + + + + + + +

Exceptions

+
+
IncorrectShapeException
+

If shape's size mismatches current shape size.

+
+
ArgumentException
+

If newShape's size == 0

+
+
+ + + + + +

+ Reshape(ref Shape, bool) + +

+ +

Changes the shape representing this storage.

+
+
+ +
+
public void Reshape(ref Shape newShape, bool @unsafe = false)
+
+ +

Parameters

+
+
newShape Shape
+
+
unsafe bool
+
+
+ + + + + + + + + +

Exceptions

+
+
IncorrectShapeException
+

If shape's size mismatches current shape size.

+
+
ArgumentException
+

If newShape's size == 0

+
+
+ + + + + +

+ Reshape(params int[]) + +

+ +

Changes the shape representing this storage.

+
+
+ +
+
public void Reshape(params int[] dimensions)
+
+ +

Parameters

+
+
dimensions int[]
+
+
+ + + + + + + + + +

Exceptions

+
+
IncorrectShapeException
+

If shape's size mismatches current shape size.

+
+
+ + + + + +

+ Reshape(int[], bool) + +

+ +

Changes the shape representing this storage.

+
+
+ +
+
public void Reshape(int[] dimensions, bool @unsafe)
+
+ +

Parameters

+
+
dimensions int[]
+
+
unsafe bool
+
+
+ + + + + + + + + +

Exceptions

+
+
IncorrectShapeException
+

If shape's size mismatches current shape size.

+
+
ArgumentException
+

If dimensions's size == 0

+
+
+ + + + + +

+ Scalar(object) + +

+ +
+
+ +
+
public static UnmanagedStorage Scalar(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
UnmanagedStorage
+
+
+ + + + + + + + + + + + + +

+ Scalar(object, NPTypeCode) + +

+ +
+
+ +
+
public static UnmanagedStorage Scalar(object value, NPTypeCode typeCode)
+
+ +

Parameters

+
+
value object
+
+
typeCode NPTypeCode
+
+
+ +

Returns

+
+
UnmanagedStorage
+
+
+ + + + + + + + + + + + + +

+ Scalar<T>(T) + +

+ +
+
+ +
+
public static UnmanagedStorage Scalar<T>(T value) where T : unmanaged
+
+ +

Parameters

+
+
value T
+
+
+ +

Returns

+
+
UnmanagedStorage
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ SetAtIndex(object, int) + +

+ +
+
+ +
+
public void SetAtIndex(object value, int index)
+
+ +

Parameters

+
+
value object
+
+
index int
+
+
+ + + + + + + + + + + + + + +

+ SetAtIndexUnsafe(ValueType, int) + +

+ +

Performs a set of index without calling TransformOffset(int).

+
+
+ +
+
public void SetAtIndexUnsafe(ValueType value, int index)
+
+ +

Parameters

+
+
value ValueType
+
+
index int
+
+
+ + + + + + + + + + + + + + +

+ SetAtIndexUnsafe<T>(T, int) + +

+ +

Performs a set of index without calling TransformOffset(int).

+
+
+ +
+
public void SetAtIndexUnsafe<T>(T value, int index) where T : unmanaged
+
+ +

Parameters

+
+
value T
+
+
index int
+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ SetAtIndex<T>(T, int) + +

+ +
+
+ +
+
public void SetAtIndex<T>(T value, int index) where T : unmanaged
+
+ +

Parameters

+
+
value T
+
+
index int
+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ SetBoolean(bool, params int[]) + +

+ +

Sets a bool at specific coordinates.

+
+
+ +
+
public void SetBoolean(bool value, params int[] indices)
+
+ +

Parameters

+
+
value bool
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetByte(byte, params int[]) + +

+ +

Sets a byte at specific coordinates.

+
+
+ +
+
public void SetByte(byte value, params int[] indices)
+
+ +

Parameters

+
+
value byte
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetChar(char, params int[]) + +

+ +

Sets a char at specific coordinates.

+
+
+ +
+
public void SetChar(char value, params int[] indices)
+
+ +

Parameters

+
+
value char
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetData(IArraySlice, params int[]) + +

+ +

Set a IArraySlice at given indices.

+
+
+ +
+
public void SetData(IArraySlice value, params int[] indices)
+
+ +

Parameters

+
+
value IArraySlice
+

The value to set

+
+
indices int[]
+

The

+
+
+ + + + + + + + +

Remarks

+

Does not change internal storage data type.
+If value does not match DType, value will be converted.

+
+ + + + + + +

+ SetData(NDArray, params int[]) + +

+ +

Set a NDArray at given indices.

+
+
+ +
+
public void SetData(NDArray value, params int[] indices)
+
+ +

Parameters

+
+
value NDArray
+

The value to set

+
+
indices int[]
+

The

+
+
+ + + + + + + + +

Remarks

+

Does not change internal storage data type.
+If value does not match DType, value will be converted.

+
+ + + + + + +

+ SetData(object, params int[]) + +

+ +

Set a single value at given indices.

+
+
+ +
+
public void SetData(object value, params int[] indices)
+
+ +

Parameters

+
+
value object
+

The value to set

+
+
indices int[]
+

The

+
+
+ + + + + + + + +

Remarks

+

Does not change internal storage data type.
+If value does not match DType, value will be converted.

+
+ + + + + + +

+ SetDecimal(decimal, params int[]) + +

+ +

Sets a decimal at specific coordinates.

+
+
+ +
+
public void SetDecimal(decimal value, params int[] indices)
+
+ +

Parameters

+
+
value decimal
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetDouble(double, params int[]) + +

+ +

Sets a double at specific coordinates.

+
+
+ +
+
public void SetDouble(double value, params int[] indices)
+
+ +

Parameters

+
+
value double
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetInt16(short, params int[]) + +

+ +

Sets a short at specific coordinates.

+
+
+ +
+
public void SetInt16(short value, params int[] indices)
+
+ +

Parameters

+
+
value short
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetInt32(int, params int[]) + +

+ +

Sets a int at specific coordinates.

+
+
+ +
+
public void SetInt32(int value, params int[] indices)
+
+ +

Parameters

+
+
value int
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetInt64(long, params int[]) + +

+ +

Sets a long at specific coordinates.

+
+
+ +
+
public void SetInt64(long value, params int[] indices)
+
+ +

Parameters

+
+
value long
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetInternalArray(IArraySlice) + +

+ +

Replace internal storage array with given array.

+
+
+ +
+
protected void SetInternalArray(IArraySlice array)
+
+ +

Parameters

+
+
array IArraySlice
+

The array to set as internal storage

+
+
+ + + + + + + + + +

Exceptions

+
+
InvalidCastException
+

When type of array does not match DType of this storage

+
+
+ + + + + +

+ SetInternalArray(Array) + +

+ +

Replace internal storage array with given array.

+
+
+ +
+
protected void SetInternalArray(Array array)
+
+ +

Parameters

+
+
array Array
+

The array to set as internal storage

+
+
+ + + + + + + + + +

Exceptions

+
+
InvalidCastException
+

When type of array does not match DType of this storage

+
+
+ + + + + +

+ SetShapeUnsafe(Shape) + +

+ +

Set the shape of this storage without checking if sizes match.

+
+
+ +
+
protected void SetShapeUnsafe(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ + + + + + + + +

Remarks

+

Used during broadcasting

+
+ + + + + + +

+ SetShapeUnsafe(ref Shape) + +

+ +

Set the shape of this storage without checking if sizes match.

+
+
+ +
+
protected void SetShapeUnsafe(ref Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ + + + + + + + +

Remarks

+

Used during broadcasting

+
+ + + + + + +

+ SetSingle(float, params int[]) + +

+ +

Sets a float at specific coordinates.

+
+
+ +
+
public void SetSingle(float value, params int[] indices)
+
+ +

Parameters

+
+
value float
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetUInt16(ushort, params int[]) + +

+ +

Sets a ushort at specific coordinates.

+
+
+ +
+
public void SetUInt16(ushort value, params int[] indices)
+
+ +

Parameters

+
+
value ushort
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetUInt32(uint, params int[]) + +

+ +

Sets a uint at specific coordinates.

+
+
+ +
+
public void SetUInt32(uint value, params int[] indices)
+
+ +

Parameters

+
+
value uint
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetUInt64(ulong, params int[]) + +

+ +

Sets a ulong at specific coordinates.

+
+
+ +
+
public void SetUInt64(ulong value, params int[] indices)
+
+ +

Parameters

+
+
value ulong
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetValue(object, params int[]) + +

+ +

Set a single value at given indices.

+
+
+ +
+
public void SetValue(object value, params int[] indices)
+
+ +

Parameters

+
+
value object
+

The value to set

+
+
indices int[]
+

The

+
+
+ + + + + + + + +

Remarks

+

Does not change internal storage data type.
+If value does not match DType, value will be converted.

+
+ + + + + + +

+ SetValue<T>(T, params int[]) + +

+ +

Set a single value at given indices.

+
+
+ +
+
public void SetValue<T>(T value, params int[] indices) where T : unmanaged
+
+ +

Parameters

+
+
value T
+

The value to set

+
+
indices int[]
+

The

+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+

Does not change internal storage data type.
+If value does not match DType, value will be converted.

+
+ + + + + + +

+ ToArray<T>() + +

+ +
+
+ +
+
public T[] ToArray<T>() where T : unmanaged
+
+ + +

Returns

+
+
T[]
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ _Allocate(Shape, IArraySlice) + +

+ +
+
+ +
+
protected void _Allocate(Shape shape, IArraySlice values)
+
+ +

Parameters

+
+
shape Shape
+
+
values IArraySlice
+
+
+ + + + + + + + + + + + + + +

+ _ChangeTypeOfArray(Array, Type) + +

+ +

Changes the type of sourceArray to to_dtype if necessary.

+
+
+ +
+
[SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")]
+protected static Array _ChangeTypeOfArray(Array sourceArray, Type to_dtype)
+
+ +

Parameters

+
+
sourceArray Array
+

The array to change his type

+
+
to_dtype Type
+

The type to change to.

+
+
+ +

Returns

+
+
Array
+

Returns sourceArray or new array with changed type to to_dtype

+
+
+ + + + + + + +

Remarks

+

If the return type is equal to source type, this method does not return a copy.

+
+ + + + + + +

+ _ChangeTypeOfArray<TOut>(IArraySlice) + +

+ +

Changes the type of sourceArray to to_dtype if necessary.

+
+
+ +
+
[SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")]
+protected static ArraySlice<TOut> _ChangeTypeOfArray<TOut>(IArraySlice sourceArray) where TOut : unmanaged
+
+ +

Parameters

+
+
sourceArray IArraySlice
+

The array to change his type

+
+
+ +

Returns

+
+
ArraySlice<TOut>
+

Returns sourceArray or new array with changed type to to_dtype

+
+
+ +

Type Parameters

+
+
TOut
+
+
+ + + + + + +

Remarks

+

If the return type is equal to source type, this method does not return a copy.

+
+ + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Backends.html b/docs/website/api/NumSharp.Backends.html new file mode 100644 index 000000000..ee6225b82 --- /dev/null +++ b/docs/website/api/NumSharp.Backends.html @@ -0,0 +1,136 @@ + + + + + Namespace NumSharp.Backends | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ +

Namespace NumSharp.Backends

+
+
+
+ +

+Classes +

+
+
BackendFactory
+
+
+
+
DefaultEngine
+

Default Tensor Engine implemented in pure micro-optimized C#.

+
+
+
+
UnmanagedStorage
+

Serves as a typed storage for an array.

+
+
+ + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.BroadcastInfo.html b/docs/website/api/NumSharp.BroadcastInfo.html new file mode 100644 index 000000000..e9e498b45 --- /dev/null +++ b/docs/website/api/NumSharp.BroadcastInfo.html @@ -0,0 +1,353 @@ + + + + + Class BroadcastInfo | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class BroadcastInfo +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class BroadcastInfo : ICloneable
+
+ + + + +
+
Inheritance
+
+ +
BroadcastInfo
+
+
+ +
+
Implements
+
+ +
+
+ + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ BroadcastInfo() + +

+ +
+
+ +
+
public BroadcastInfo()
+
+ + + + + + + + + + + + + + + +

+ BroadcastInfo(Shape) + +

+ +
+
+ +
+
public BroadcastInfo(Shape originalShape)
+
+ +

Parameters

+
+
originalShape Shape
+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ OriginalShape + +

+ +

The original shape prior to broadcasting.

+
+
+ +
+
public Shape OriginalShape
+
+ + + + +

Field Value

+
+
Shape
+
+
+ + + + + + + + + + +

+ UnreducedBroadcastedShape + +

+ +

Represents a shape with the same number of dimensions that the broadcasted ones are set to dim of 1.

+
+
+ +
+
public Shape? UnreducedBroadcastedShape
+
+ + + + +

Field Value

+
+
Shape?
+
+
+ + + + + +

Remarks

+

This shape is lazyloaded during runtime when calling Shape.GetOffset and other methods.

+
+ + + + +

Methods +

+ + + + +

+ Clone() + +

+ +
+
+ +
+
public BroadcastInfo Clone()
+
+ + +

Returns

+
+
BroadcastInfo
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/api/NumSharp.Core.Extensions.NDArrayExtensions.html b/docs/website/api/NumSharp.Core.Extensions.NDArrayExtensions.html similarity index 100% rename from docs/api/NumSharp.Core.Extensions.NDArrayExtensions.html rename to docs/website/api/NumSharp.Core.Extensions.NDArrayExtensions.html diff --git a/docs/api/NumSharp.Core.Extensions.html b/docs/website/api/NumSharp.Core.Extensions.html similarity index 100% rename from docs/api/NumSharp.Core.Extensions.html rename to docs/website/api/NumSharp.Core.Extensions.html diff --git a/docs/api/NumSharp.Core.Interfaces.IShape.html b/docs/website/api/NumSharp.Core.Interfaces.IShape.html similarity index 100% rename from docs/api/NumSharp.Core.Interfaces.IShape.html rename to docs/website/api/NumSharp.Core.Interfaces.IShape.html diff --git a/docs/api/NumSharp.Core.Interfaces.IStorage.html b/docs/website/api/NumSharp.Core.Interfaces.IStorage.html similarity index 100% rename from docs/api/NumSharp.Core.Interfaces.IStorage.html rename to docs/website/api/NumSharp.Core.Interfaces.IStorage.html diff --git a/docs/api/NumSharp.Core.Interfaces.html b/docs/website/api/NumSharp.Core.Interfaces.html similarity index 100% rename from docs/api/NumSharp.Core.Interfaces.html rename to docs/website/api/NumSharp.Core.Interfaces.html diff --git a/docs/api/NumSharp.Core.LAPACK.html b/docs/website/api/NumSharp.Core.LAPACK.html similarity index 100% rename from docs/api/NumSharp.Core.LAPACK.html rename to docs/website/api/NumSharp.Core.LAPACK.html diff --git a/docs/api/NumSharp.Core.Manipulation.NumPy.html b/docs/website/api/NumSharp.Core.Manipulation.NumPy.html similarity index 100% rename from docs/api/NumSharp.Core.Manipulation.NumPy.html rename to docs/website/api/NumSharp.Core.Manipulation.NumPy.html diff --git a/docs/api/NumSharp.Core.Manipulation.html b/docs/website/api/NumSharp.Core.Manipulation.html similarity index 100% rename from docs/api/NumSharp.Core.Manipulation.html rename to docs/website/api/NumSharp.Core.Manipulation.html diff --git a/docs/api/NumSharp.Core.NDArray.html b/docs/website/api/NumSharp.Core.NDArray.html similarity index 100% rename from docs/api/NumSharp.Core.NDArray.html rename to docs/website/api/NumSharp.Core.NDArray.html diff --git a/docs/api/NumSharp.Core.NDArrayRandomExtensions.html b/docs/website/api/NumSharp.Core.NDArrayRandomExtensions.html similarity index 100% rename from docs/api/NumSharp.Core.NDArrayRandomExtensions.html rename to docs/website/api/NumSharp.Core.NDArrayRandomExtensions.html diff --git a/docs/api/NumSharp.Core.NDArray_Legacy-1.html b/docs/website/api/NumSharp.Core.NDArray_Legacy-1.html similarity index 100% rename from docs/api/NumSharp.Core.NDArray_Legacy-1.html rename to docs/website/api/NumSharp.Core.NDArray_Legacy-1.html diff --git a/docs/api/NumSharp.Core.NDStorage.html b/docs/website/api/NumSharp.Core.NDStorage.html similarity index 100% rename from docs/api/NumSharp.Core.NDStorage.html rename to docs/website/api/NumSharp.Core.NDStorage.html diff --git a/docs/api/NumSharp.Core.NumPyRandom.html b/docs/website/api/NumSharp.Core.NumPyRandom.html similarity index 100% rename from docs/api/NumSharp.Core.NumPyRandom.html rename to docs/website/api/NumSharp.Core.NumPyRandom.html diff --git a/docs/api/NumSharp.Core.Shape.html b/docs/website/api/NumSharp.Core.Shape.html similarity index 100% rename from docs/api/NumSharp.Core.Shape.html rename to docs/website/api/NumSharp.Core.Shape.html diff --git a/docs/api/NumSharp.Core.Slice.html b/docs/website/api/NumSharp.Core.Slice.html similarity index 100% rename from docs/api/NumSharp.Core.Slice.html rename to docs/website/api/NumSharp.Core.Slice.html diff --git a/docs/api/NumSharp.Core.html b/docs/website/api/NumSharp.Core.html similarity index 100% rename from docs/api/NumSharp.Core.html rename to docs/website/api/NumSharp.Core.html diff --git a/docs/api/NumSharp.Core.matrix.html b/docs/website/api/NumSharp.Core.matrix.html similarity index 100% rename from docs/api/NumSharp.Core.matrix.html rename to docs/website/api/NumSharp.Core.matrix.html diff --git a/docs/api/NumSharp.Core.np.html b/docs/website/api/NumSharp.Core.np.html similarity index 100% rename from docs/api/NumSharp.Core.np.html rename to docs/website/api/NumSharp.Core.np.html diff --git a/docs/website/api/NumSharp.DType.html b/docs/website/api/NumSharp.DType.html new file mode 100644 index 000000000..c28b03f35 --- /dev/null +++ b/docs/website/api/NumSharp.DType.html @@ -0,0 +1,543 @@ + + + + + Class DType | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class DType +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class DType
+
+ + + + +
+
Inheritance
+
+ +
DType
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + +

Remarks

+ + + +

Constructors +

+ + + + +

+ DType(Type) + +

+ +

Initializes a new instance of the object class.

+
+
+ +
+
public DType(Type type)
+
+ +

Parameters

+
+
type Type
+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ _kind_list_map + +

+ +
+
+ +
+
protected static readonly FrozenDictionary<NPTypeCode, char> _kind_list_map
+
+ + + + +

Field Value

+
+
FrozenDictionary<NPTypeCode, char>
+
+
+ + + + + + + + + + +

+ byteorder + +

+ +

A character indicating the byte-order of this data-type object.
+One of:

+

'=' native
+'&lt;' little-endian
+'>' big-endian
+'|' not applicable

+
+
+ +
+
public char byteorder
+
+ + + + +

Field Value

+
+
char
+
+
+ + + + + + + + + + +

+ itemsize + +

+ +

The size of the dtype in bytes.

+
+
+ +
+
public int itemsize
+
+ + + + +

Field Value

+
+
int
+
+
+ + + + + + + + + + +

+ kind + +

+ +

A character code (one of ‘biufcmMOSUV’) identifying the general kind of data.

+b boolean
+i signed integer
+u unsigned integer
+f floating-point
+c complex floating-point
+m timedelta
+M datetime
+O object
+S(byte-)string
+U Unicode
+V void

+
+
+ +
+
public char kind
+
+ + + + +

Field Value

+
+
char
+
+
+ + + + + + + + + + +

+ name + +

+ +

The name of this dtype.

+
+
+ +
+
public string name
+
+ + + + +

Field Value

+
+
string
+
+
+ + + + + + + + + + +

+ type + +

+ +

The actual type this dtype represents.

+
+
+ +
+
public Type type
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ typecode + +

+ +

The NumSharp type code.

+
+
+ +
+
public NPTypeCode typecode
+
+ + + + +

Field Value

+
+
NPTypeCode
+
+
+ + + + + + + + + +

Properties +

+ + + + +

+ char + +

+ +

A unique character code for each of the 21 different built-in types.

+
+
+ +
+
public char @char { get; }
+
+ + + + + +

Property Value

+
+
char
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ newbyteorder(char) + +

+ +

Return a new dtype with a different byte order. +Changes are also made in all fields and sub-arrays of the data type.

+
+
+ +
+
public DType newbyteorder(char new_order = 'S')
+
+ +

Parameters

+
+
new_order char
+

Byte order to force; a value from the byte order specifications below.
The default value (‘S’) results in swapping the current byte order.
new_order codes can be any of:
+‘S’ - swap dtype from current to opposite endian
+'=' - native order
+'&lt;' - little-endian
+'>' - big-endian
+'|' - ignore(no change to byte order)
+The code does a case-insensitive check on the first letter of new_order for these alternatives.
For example, any of ‘>’ or ‘B’ or ‘b’ or ‘brian’ are valid to specify big-endian.

+
+
+ +

Returns

+
+
DType
+

New dtype object with the given change to the byte order.

+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Extensions.LinqExtensions.html b/docs/website/api/NumSharp.Extensions.LinqExtensions.html new file mode 100644 index 000000000..f321e0ce7 --- /dev/null +++ b/docs/website/api/NumSharp.Extensions.LinqExtensions.html @@ -0,0 +1,220 @@ + + + + + Class LinqExtensions | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class LinqExtensions +

+ +
+
Namespace
NumSharp.Extensions
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public static class LinqExtensions
+
+ + + + +
+
Inheritance
+
+ +
LinqExtensions
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Methods +

+ + + + +

+ Yield<T>(T) + +

+ +
+
+ +
+
public static IEnumerable<T> Yield<T>(this T item)
+
+ +

Parameters

+
+
item T
+
+
+ +

Returns

+
+
IEnumerable<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/api/NumSharp.Extensions.NDArrayExtensions.html b/docs/website/api/NumSharp.Extensions.NDArrayExtensions.html similarity index 100% rename from docs/api/NumSharp.Extensions.NDArrayExtensions.html rename to docs/website/api/NumSharp.Extensions.NDArrayExtensions.html diff --git a/docs/api/NumSharp.Extensions.NDArrayExtensions.yml b/docs/website/api/NumSharp.Extensions.NDArrayExtensions.yml similarity index 100% rename from docs/api/NumSharp.Extensions.NDArrayExtensions.yml rename to docs/website/api/NumSharp.Extensions.NDArrayExtensions.yml diff --git a/docs/api/NumSharp.Extensions.NDArrayRandomExtensions.html b/docs/website/api/NumSharp.Extensions.NDArrayRandomExtensions.html similarity index 100% rename from docs/api/NumSharp.Extensions.NDArrayRandomExtensions.html rename to docs/website/api/NumSharp.Extensions.NDArrayRandomExtensions.html diff --git a/docs/api/NumSharp.Extensions.NDArrayRandomExtensions.yml b/docs/website/api/NumSharp.Extensions.NDArrayRandomExtensions.yml similarity index 100% rename from docs/api/NumSharp.Extensions.NDArrayRandomExtensions.yml rename to docs/website/api/NumSharp.Extensions.NDArrayRandomExtensions.yml diff --git a/docs/api/NumSharp.Extensions.NumPyExtensions.html b/docs/website/api/NumSharp.Extensions.NumPyExtensions.html similarity index 100% rename from docs/api/NumSharp.Extensions.NumPyExtensions.html rename to docs/website/api/NumSharp.Extensions.NumPyExtensions.html diff --git a/docs/api/NumSharp.Extensions.NumPyExtensions.yml b/docs/website/api/NumSharp.Extensions.NumPyExtensions.yml similarity index 100% rename from docs/api/NumSharp.Extensions.NumPyExtensions.yml rename to docs/website/api/NumSharp.Extensions.NumPyExtensions.yml diff --git a/docs/website/api/NumSharp.Extensions.html b/docs/website/api/NumSharp.Extensions.html new file mode 100644 index 000000000..f048f5dc2 --- /dev/null +++ b/docs/website/api/NumSharp.Extensions.html @@ -0,0 +1,126 @@ + + + + + Namespace NumSharp.Extensions | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ +

Namespace NumSharp.Extensions

+
+
+
+ +

+Classes +

+
+
LinqExtensions
+
+
+ + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/api/NumSharp.Extensions.yml b/docs/website/api/NumSharp.Extensions.yml similarity index 100% rename from docs/api/NumSharp.Extensions.yml rename to docs/website/api/NumSharp.Extensions.yml diff --git a/docs/website/api/NumSharp.Generic.NDArray-1.html b/docs/website/api/NumSharp.Generic.NDArray-1.html new file mode 100644 index 000000000..935fe282e --- /dev/null +++ b/docs/website/api/NumSharp.Generic.NDArray-1.html @@ -0,0 +1,1770 @@ + + + + + Class NDArray<TDType> | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NDArray<TDType> +

+ +
+
Namespace
NumSharp.Generic
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class NDArray<TDType> : NDArray, IIndex, ICloneable, IEnumerable where TDType : unmanaged
+
+ + + +

Type Parameters

+
+
TDType
+
+
+ +
+
Inheritance
+
+ + +
NDArray<TDType>
+
+
+ +
+
Implements
+
+ + + +
+
+ + +
+
Inherited Members
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
Extension Methods
+
+ + + +
+ + + + + +

Constructors +

+ + + + +

+ NDArray() + +

+ +

Constructor for init data type +internal storage is 1D with 1 element

+
+
+ +
+
public NDArray()
+
+ + + + + + + + + +

Remarks

+

This constructor does not call allocation/>

+
+ + + + + + +

+ NDArray(IArraySlice, Shape, char) + +

+ +

Constructor which takes .NET array +dtype and shape is determined from array

+
+
+ +
+
public NDArray(IArraySlice values, Shape shape = default, char order = 'C')
+
+ +

Parameters

+
+
values IArraySlice
+
+
shape Shape
+
+
order char
+
+
+ + + + + + + + +

Remarks

+

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

+
+ + + + + + +

+ NDArray(UnmanagedStorage) + +

+ +

Creates a new NDArray with this storage.

+
+
+ +
+
protected NDArray(UnmanagedStorage storage)
+
+ +

Parameters

+
+
storage UnmanagedStorage
+
+
+ + + + + + + + + + + + + + +

+ NDArray(UnmanagedStorage, Shape) + +

+ +

Creates a new NDArray with this storage.

+
+
+ +
+
protected NDArray(UnmanagedStorage storage, Shape shape)
+
+ +

Parameters

+
+
storage UnmanagedStorage
+
+
shape Shape
+
+
+ + + + + + + + + + + + + + +

+ NDArray(UnmanagedStorage, ref Shape) + +

+ +

Creates a new NDArray with this storage.

+
+
+ +
+
protected NDArray(UnmanagedStorage storage, ref Shape shape)
+
+ +

Parameters

+
+
storage UnmanagedStorage
+
+
shape Shape
+
+
+ + + + + + + + + + + + + + +

+ NDArray(Shape) + +

+ +

Constructor which initialize elements with 0 +type and shape are given.

+
+
+ +
+
public NDArray(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+

Shape of NDArray

+
+
+ + + + + + + + +

Remarks

+

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

+
+ + + + + + +

+ NDArray(Shape, bool) + +

+ +

Constructor which initialize elements with 0 +type and shape are given.

+
+
+ +
+
public NDArray(Shape shape, bool fillZeros)
+
+ +

Parameters

+
+
shape Shape
+

Shape of NDArray

+
+
fillZeros bool
+

Should set the values of the new allocation to default(dtype)? otherwise - old memory noise

+
+
+ + + + + + + + +

Remarks

+

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

+
+ + + + + + +

+ NDArray(TensorEngine) + +

+ +

Constructor for init data type +internal storage is 1D with 1 element

+
+
+ +
+
protected NDArray(TensorEngine engine)
+
+ +

Parameters

+
+
engine TensorEngine
+

The engine of this NDArray

+
+
+ + + + + + + + +

Remarks

+

This constructor does not call allocation/>

+
+ + + + + + +

+ NDArray(Array, Shape, char) + +

+ +

Constructor which takes .NET array +dtype and shape is determined from array

+
+
+ +
+
public NDArray(Array values, Shape shape = default, char order = 'C')
+
+ +

Parameters

+
+
values Array
+
+
shape Shape
+
+
order char
+
+
+ + + + + + + + +

Remarks

+

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

+
+ + + + + + +

+ NDArray(int) + +

+ +

Constructor which initialize elements with length of size

+
+
+ +
+
public NDArray(int size)
+
+ +

Parameters

+
+
size int
+

The size as a single dimension shape

+
+
+ + + + + + + + +

Remarks

+

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

+
+ + + + + + +

+ NDArray(int, bool) + +

+ +

Constructor which initialize elements with length of size

+
+
+ +
+
public NDArray(int size, bool fillZeros)
+
+ +

Parameters

+
+
size int
+

The size as a single dimension shape

+
+
fillZeros bool
+

Should set the values of the new allocation to default(dtype)? otherwise - old memory noise

+
+
+ + + + + + + + +

Remarks

+

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

+
+ + + + +

Properties +

+ + + + +

+ Address + +

+ +

Gets the address that this NDArray starts from.

+
+
+ +
+
protected TDType* Address { get; }
+
+ + + + + +

Property Value

+
+
TDType*
+
+
+ + + + + + + + + + +

+ Array + +

+ +

Array access to storage data - overridden on purpose

+
+
+ +
+
protected ArraySlice<TDType> Array { get; set; }
+
+ + + + + +

Property Value

+
+
ArraySlice<TDType>
+
+
+ + + + + + + + + + +

+ this[Slice[]] + +

+ +

slicing of generic - overridden on purpose

+
+
+ +
+
public NDArray<TDType> this[params Slice[] slices] { get; set; }
+
+ +

Parameters

+
+
slices Slice[]
+
+
+ + + + +

Property Value

+
+
NDArray<TDType>
+
+
+ + + + + + + + + + +

+ this[int[]] + +

+ +
+
+ +
+
public TDType this[params int[] indices] { get; set; }
+
+ +

Parameters

+
+
indices int[]
+
+
+ + + + +

Property Value

+
+
TDType
+
+
+ + + + + + + + + + +

+ this[string] + +

+ +

slicing of generic - overridden on purpose

+
+
+ +
+
public NDArray<TDType> this[string slice] { get; set; }
+
+ +

Parameters

+
+
slice string
+
+
+ + + + +

Property Value

+
+
NDArray<TDType>
+
+
+ + + + + + + + + + +

+ T + +

+ +

The transposed array.
+Same as self.transpose().

+
+
+ +
+
public NDArray<TDType> T { get; }
+
+ + + + + +

Property Value

+
+
NDArray<TDType>
+
+
+ + + + +

Remarks

+ + + + + + + +

+ flat + +

+ +

A 1-D iterator over the array.

+
+
+ +
+
public NDArray<TDType> flat { get; }
+
+ + + + + +

Property Value

+
+
NDArray<TDType>
+
+
+ + + + +

Remarks

+ + + + + +

Methods +

+ + + + +

+ GetAtIndex(int) + +

+ +
+
+ +
+
public TDType GetAtIndex(int index)
+
+ +

Parameters

+
+
index int
+
+
+ +

Returns

+
+
TDType
+
+
+ + + + + + + + + + + + + +

+ reshape(Shape) + +

+ +

Gives a new shape to an array without changing its data.

+
+
+ +
+
public NDArray<TDType> reshape(Shape newShape)
+
+ +

Parameters

+
+
newShape Shape
+

The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

+
+
+ +

Returns

+
+
NDArray<TDType>
+

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ reshape(ref Shape) + +

+ +

Gives a new shape to an array without changing its data.

+
+
+ +
+
public NDArray<TDType> reshape(ref Shape newShape)
+
+ +

Parameters

+
+
newShape Shape
+

The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

+
+
+ +

Returns

+
+
NDArray<TDType>
+

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ reshape(params int[]) + +

+ +

Gives a new shape to an array without changing its data.

+
+
+ +
+
[SuppressMessage("ReSharper", "ParameterHidesMember")]
+public NDArray<TDType> reshape(params int[] shape)
+
+ +

Parameters

+
+
shape int[]
+

The new shape should be compatible with the original shape. If an integer, then the result will be a +1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array +and remaining dimensions.

+
+
+ +

Returns

+
+
NDArray<TDType>
+

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the +memory layout (C- or Fortran- contiguous) of the returned array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ reshape_unsafe(Shape) + +

+ +

Gives a new shape to an array without changing its data.

+
+
+ +
+
public NDArray<TDType> reshape_unsafe(Shape newshape)
+
+ +

Parameters

+
+
newshape Shape
+

The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

+
+
+ +

Returns

+
+
NDArray<TDType>
+

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ reshape_unsafe(ref Shape) + +

+ +

Gives a new shape to an array without changing its data.

+
+
+ +
+
public NDArray<TDType> reshape_unsafe(ref Shape newShape)
+
+ +

Parameters

+
+
newShape Shape
+
+
+ +

Returns

+
+
NDArray<TDType>
+

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ reshape_unsafe(params int[]) + +

+ +

Gives a new shape to an array without changing its data.

+
+
+ +
+
[SuppressMessage("ReSharper", "ParameterHidesMember")]
+public NDArray<TDType> reshape_unsafe(params int[] shape)
+
+ +

Parameters

+
+
shape int[]
+

The new shape should be compatible with the original shape. If an integer, then the result will be a +1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array +and remaining dimensions.

+
+
+ +

Returns

+
+
NDArray<TDType>
+

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the +memory layout (C- or Fortran- contiguous) of the returned array.

+
+
+ + + + + + + +

Remarks

+ + + + + +

Operators +

+ + + + +

+ explicit operator NDArray<TDType>(TDType[]) + +

+ +
+
+ +
+
public static explicit operator NDArray<TDType>(TDType[] tArray)
+
+ +

Parameters

+
+
tArray TDType[]
+
+
+ +

Returns

+
+
NDArray<TDType>
+
+
+ + + + + + + + + + + + + +

+ implicit operator ArraySlice<TDType>(NDArray<TDType>) + +

+ +
+
+ +
+
public static implicit operator ArraySlice<TDType>(NDArray<TDType> nd)
+
+ +

Parameters

+
+
nd NDArray<TDType>
+
+
+ +

Returns

+
+
ArraySlice<TDType>
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Generic.html b/docs/website/api/NumSharp.Generic.html new file mode 100644 index 000000000..f3f330853 --- /dev/null +++ b/docs/website/api/NumSharp.Generic.html @@ -0,0 +1,126 @@ + + + + + Namespace NumSharp.Generic | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ +

Namespace NumSharp.Generic

+
+
+
+ +

+Classes +

+
+
NDArray<TDType>
+
+
+ + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.IIndex.html b/docs/website/api/NumSharp.IIndex.html new file mode 100644 index 000000000..4dab76b67 --- /dev/null +++ b/docs/website/api/NumSharp.IIndex.html @@ -0,0 +1,151 @@ + + + + + Interface IIndex | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Interface IIndex +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +

Represents a class that can be served as an index, e.g. ndarray[new Slice(...)]

+
+
+ +
+
public interface IIndex
+
+ + + + + + + + +
+
Extension Methods
+
+ +
+ + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.INumSharpException.html b/docs/website/api/NumSharp.INumSharpException.html new file mode 100644 index 000000000..4cc3bd6fa --- /dev/null +++ b/docs/website/api/NumSharp.INumSharpException.html @@ -0,0 +1,150 @@ + + + + + Interface INumSharpException | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Interface INumSharpException +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public interface INumSharpException
+
+ + + + + + + + +
+
Extension Methods
+
+ +
+ + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.IncorrectShapeException.html b/docs/website/api/NumSharp.IncorrectShapeException.html new file mode 100644 index 000000000..f70998acb --- /dev/null +++ b/docs/website/api/NumSharp.IncorrectShapeException.html @@ -0,0 +1,282 @@ + + + + + Class IncorrectShapeException | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class IncorrectShapeException +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class IncorrectShapeException : NumSharpException, ISerializable, INumSharpException
+
+ + + + +
+
Inheritance
+
+ + + +
IncorrectShapeException
+
+
+ +
+
Implements
+
+ + +
+
+ + +
+
Inherited Members
+
+ + + + + + + + + + + + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ IncorrectShapeException() + +

+ +
+
+ +
+
public IncorrectShapeException()
+
+ + + + + + + + + + + + + + + +

+ IncorrectShapeException(string) + +

+ +
+
+ +
+
public IncorrectShapeException(string message)
+
+ +

Parameters

+
+
message string
+
+
+ + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.IncorrectSizeException.html b/docs/website/api/NumSharp.IncorrectSizeException.html new file mode 100644 index 000000000..bef85a391 --- /dev/null +++ b/docs/website/api/NumSharp.IncorrectSizeException.html @@ -0,0 +1,256 @@ + + + + + Class IncorrectSizeException | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class IncorrectSizeException +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class IncorrectSizeException : NumSharpException, ISerializable, INumSharpException
+
+ + + + +
+
Inheritance
+
+ + + +
IncorrectSizeException
+
+
+ +
+
Implements
+
+ + +
+
+ + +
+
Inherited Members
+
+ + + + + + + + + + + + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ IncorrectSizeException(string) + +

+ +
+
+ +
+
public IncorrectSizeException(string message)
+
+ +

Parameters

+
+
message string
+
+
+ + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.IncorrectTypeException.html b/docs/website/api/NumSharp.IncorrectTypeException.html new file mode 100644 index 000000000..da3458d46 --- /dev/null +++ b/docs/website/api/NumSharp.IncorrectTypeException.html @@ -0,0 +1,282 @@ + + + + + Class IncorrectTypeException | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class IncorrectTypeException +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class IncorrectTypeException : NumSharpException, ISerializable, INumSharpException
+
+ + + + +
+
Inheritance
+
+ + + +
IncorrectTypeException
+
+
+ +
+
Implements
+
+ + +
+
+ + +
+
Inherited Members
+
+ + + + + + + + + + + + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ IncorrectTypeException() + +

+ +
+
+ +
+
public IncorrectTypeException()
+
+ + + + + + + + + + + + + + + +

+ IncorrectTypeException(string) + +

+ +
+
+ +
+
public IncorrectTypeException(string message)
+
+ +

Parameters

+
+
message string
+
+
+ + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.IteratorType.html b/docs/website/api/NumSharp.IteratorType.html new file mode 100644 index 000000000..74598640c --- /dev/null +++ b/docs/website/api/NumSharp.IteratorType.html @@ -0,0 +1,165 @@ + + + + + Enum IteratorType | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + + +

+Enum IteratorType +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public enum IteratorType
+
+ + + + + + + + +
+
Extension Methods
+
+ +
+ +

Fields +

+
+
Scalar = 0
+ +
+
Vector = 1
+ +
+
Matrix = 2
+ +
+
Tensor = 3
+ +
+
+ + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Kwargs.html b/docs/website/api/NumSharp.Kwargs.html new file mode 100644 index 000000000..959e99263 --- /dev/null +++ b/docs/website/api/NumSharp.Kwargs.html @@ -0,0 +1,351 @@ + + + + + Class Kwargs | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class Kwargs +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class Kwargs
+
+ + + + +
+
Inheritance
+
+ +
Kwargs
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ Kwargs() + +

+ +
+
+ +
+
public Kwargs()
+
+ + + + + + + + + + + + + + + +

+ Kwargs(string, bool, bool) + +

+ +

Kwargs constructor

+
+
+ +
+
public Kwargs(string indexing, bool sparse, bool copy)
+
+ +

Parameters

+
+
indexing string
+

{'xy', 'ij'}, optional Cartesian('xy', default) or matrix('ij') indexing of output.

+
+
sparse bool
+

If True a sparse grid is returned in order to conserve memory. Default is False.

+
+
copy bool
+

If False, a view into the original arrays are returned in order to conserve memory. +Default is True.Please note that sparse= False, copy= False`` will likely return non-contiguous arrays.
+Furthermore, more than one element of a broadcast array may refer to a single memory location. +If you need to write to the arrays, make copies first.

+
+
+ + + + + + + + + + + + +

Properties +

+ + + + +

+ copy + +

+ +
+
+ +
+
public bool copy { get; set; }
+
+ + + + + +

Property Value

+
+
bool
+
+
+ + + + + + + + + + +

+ indexing + +

+ +
+
+ +
+
public string indexing { get; set; }
+
+ + + + + +

Property Value

+
+
string
+
+
+ + + + + + + + + + +

+ sparse + +

+ +
+
+ +
+
public bool sparse { get; set; }
+
+ + + + + +

Property Value

+
+
bool
+
+
+ + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/api/NumSharp.Matrix-1.html b/docs/website/api/NumSharp.Matrix-1.html similarity index 100% rename from docs/api/NumSharp.Matrix-1.html rename to docs/website/api/NumSharp.Matrix-1.html diff --git a/docs/api/NumSharp.Matrix-1.yml b/docs/website/api/NumSharp.Matrix-1.yml similarity index 100% rename from docs/api/NumSharp.Matrix-1.yml rename to docs/website/api/NumSharp.Matrix-1.yml diff --git a/docs/website/api/NumSharp.MoveNextReferencedDelegate-1.html b/docs/website/api/NumSharp.MoveNextReferencedDelegate-1.html new file mode 100644 index 000000000..c681a2ead --- /dev/null +++ b/docs/website/api/NumSharp.MoveNextReferencedDelegate-1.html @@ -0,0 +1,160 @@ + + + + + Delegate MoveNextReferencedDelegate<T> | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Delegate MoveNextReferencedDelegate<T> +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public delegate ref T MoveNextReferencedDelegate<T>() where T : unmanaged
+
+ + +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + +
+
Extension Methods
+
+ +
+ + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.MultiIterator.html b/docs/website/api/NumSharp.MultiIterator.html new file mode 100644 index 000000000..c3aca97f5 --- /dev/null +++ b/docs/website/api/NumSharp.MultiIterator.html @@ -0,0 +1,382 @@ + + + + + Class MultiIterator | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class MultiIterator +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public static class MultiIterator
+
+ + + + +
+
Inheritance
+
+ +
MultiIterator
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Methods +

+ + + + +

+ Assign(UnmanagedStorage, UnmanagedStorage) + +

+ +

Assigns rhs values to lhs.

+
+
+ +
+
public static void Assign(UnmanagedStorage lhs, UnmanagedStorage rhs)
+
+ +

Parameters

+
+
lhs UnmanagedStorage
+
+
rhs UnmanagedStorage
+
+
+ + + + + + + + +

Remarks

+

Stops at first iterator stop.

+
+ + + + + + +

+ Assign(NDArray, NDArray) + +

+ +

Assigns rhs values to lhs.

+
+
+ +
+
public static void Assign(NDArray lhs, NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ + + + + + + + +

Remarks

+

Stops at first iterator stop.

+
+ + + + + + +

+ AssignBroadcast<T>(NDIterator, NDIterator) + +

+ +

Assigns rhs values to lhs.

+
+
+ +
+
public static void AssignBroadcast<T>(NDIterator lhs, NDIterator rhs) where T : unmanaged
+
+ +

Parameters

+
+
lhs NDIterator
+
+
rhs NDIterator
+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+

Stops at first iterator stop.

+
+ + + + + + +

+ GetIterators(UnmanagedStorage, UnmanagedStorage, bool) + +

+ +

Gets the iterators of lhs and rhs.

+
+
+ +
+
public static (NDIterator, NDIterator) GetIterators(UnmanagedStorage lhs, UnmanagedStorage rhs, bool broadcast)
+
+ +

Parameters

+
+
lhs UnmanagedStorage
+
+
rhs UnmanagedStorage
+
+
broadcast bool
+
+
+ +

Returns

+
+
(NDIterator, NDIterator)
+
+
+ + + + + + + + + + + + + +

+ GetIterators<TOut>(UnmanagedStorage, UnmanagedStorage, bool) + +

+ +

Assigns rhs values to lhs.

+
+
+ +
+
public static (NDIterator<TOut>, NDIterator<TOut>) GetIterators<TOut>(UnmanagedStorage lhs, UnmanagedStorage rhs, bool broadcast) where TOut : unmanaged
+
+ +

Parameters

+
+
lhs UnmanagedStorage
+
+
rhs UnmanagedStorage
+
+
broadcast bool
+
+
+ +

Returns

+
+
(NDIterator<TOut>, NDIterator<TOut>)
+
+
+ +

Type Parameters

+
+
TOut
+
+
+ + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/api/NumSharp.NDArray-1.html b/docs/website/api/NumSharp.NDArray-1.html similarity index 100% rename from docs/api/NumSharp.NDArray-1.html rename to docs/website/api/NumSharp.NDArray-1.html diff --git a/docs/api/NumSharp.NDArray-1.yml b/docs/website/api/NumSharp.NDArray-1.yml similarity index 100% rename from docs/api/NumSharp.NDArray-1.yml rename to docs/website/api/NumSharp.NDArray-1.yml diff --git a/docs/website/api/NumSharp.NDArray._Unsafe._Pinning.html b/docs/website/api/NumSharp.NDArray._Unsafe._Pinning.html new file mode 100644 index 000000000..51a2a4bee --- /dev/null +++ b/docs/website/api/NumSharp.NDArray._Unsafe._Pinning.html @@ -0,0 +1,666 @@ + + + + + Struct NDArray._Unsafe._Pinning | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Struct NDArray._Unsafe._Pinning +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public readonly struct NDArray._Unsafe._Pinning
+
+ + + + + + + +
+
Inherited Members
+
+ + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Properties +

+ + + + +

+ Boolean + +

+ +
+
+ +
+
public ref bool Boolean { get; }
+
+ + + + + +

Property Value

+
+
bool
+
+
+ + + + + +

Exceptions

+
+
InvalidOperationException
+

When this NDArray is a slice.

+
+
+ + + + + +

+ Byte + +

+ +
+
+ +
+
public ref byte Byte { get; }
+
+ + + + + +

Property Value

+
+
byte
+
+
+ + + + + +

Exceptions

+
+
InvalidOperationException
+

When this NDArray is a slice.

+
+
+ + + + + +

+ Char + +

+ +
+
+ +
+
public ref char Char { get; }
+
+ + + + + +

Property Value

+
+
char
+
+
+ + + + + +

Exceptions

+
+
InvalidOperationException
+

When this NDArray is a slice.

+
+
+ + + + + +

+ Decimal + +

+ +
+
+ +
+
public ref decimal Decimal { get; }
+
+ + + + + +

Property Value

+
+
decimal
+
+
+ + + + + +

Exceptions

+
+
InvalidOperationException
+

When this NDArray is a slice.

+
+
+ + + + + +

+ Double + +

+ +
+
+ +
+
public ref double Double { get; }
+
+ + + + + +

Property Value

+
+
double
+
+
+ + + + + +

Exceptions

+
+
InvalidOperationException
+

When this NDArray is a slice.

+
+
+ + + + + +

+ Int16 + +

+ +
+
+ +
+
public ref short Int16 { get; }
+
+ + + + + +

Property Value

+
+
short
+
+
+ + + + + +

Exceptions

+
+
InvalidOperationException
+

When this NDArray is a slice.

+
+
+ + + + + +

+ Int32 + +

+ +
+
+ +
+
public ref int Int32 { get; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + + +

Exceptions

+
+
InvalidOperationException
+

When this NDArray is a slice.

+
+
+ + + + + +

+ Int64 + +

+ +
+
+ +
+
public ref long Int64 { get; }
+
+ + + + + +

Property Value

+
+
long
+
+
+ + + + + +

Exceptions

+
+
InvalidOperationException
+

When this NDArray is a slice.

+
+
+ + + + + +

+ Single + +

+ +
+
+ +
+
public ref float Single { get; }
+
+ + + + + +

Property Value

+
+
float
+
+
+ + + + + +

Exceptions

+
+
InvalidOperationException
+

When this NDArray is a slice.

+
+
+ + + + + +

+ UInt16 + +

+ +
+
+ +
+
public ref ushort UInt16 { get; }
+
+ + + + + +

Property Value

+
+
ushort
+
+
+ + + + + +

Exceptions

+
+
InvalidOperationException
+

When this NDArray is a slice.

+
+
+ + + + + +

+ UInt32 + +

+ +
+
+ +
+
public ref uint UInt32 { get; }
+
+ + + + + +

Property Value

+
+
uint
+
+
+ + + + + +

Exceptions

+
+
InvalidOperationException
+

When this NDArray is a slice.

+
+
+ + + + + +

+ UInt64 + +

+ +
+
+ +
+
public ref ulong UInt64 { get; }
+
+ + + + + +

Property Value

+
+
ulong
+
+
+ + + + + +

Exceptions

+
+
InvalidOperationException
+

When this NDArray is a slice.

+
+
+ + + +

Methods +

+ + + + +

+ GetPin<T>() + +

+ +
+
+ +
+
public ref T GetPin<T>()
+
+ + +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + +

Exceptions

+
+
InvalidOperationException
+

When this NDArray is a slice.

+
+
+ + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.NDArray._Unsafe.html b/docs/website/api/NumSharp.NDArray._Unsafe.html new file mode 100644 index 000000000..942a208f5 --- /dev/null +++ b/docs/website/api/NumSharp.NDArray._Unsafe.html @@ -0,0 +1,612 @@ + + + + + Struct NDArray._Unsafe | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Struct NDArray._Unsafe +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public readonly struct NDArray._Unsafe
+
+ + + + + + + +
+
Inherited Members
+
+ + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Properties +

+ + + + +

+ Address + +

+ +

Returns the memory address to the start of this block of memory.

+
+
+ +
+
public void* Address { get; }
+
+ + + + + +

Property Value

+
+
void*
+
+
+ + + + + +

Exceptions

+
+
InvalidOperationException
+

When this NDArray is a slice.

+
+
+ + + + + +

+ BytesLength + +

+ +

How many bytes are stored in this memory block.

+
+
+ +
+
public int BytesLength { get; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + +

Remarks

+

Calculated by Count*ItemLength

+
+ + + + + + +

+ Count + +

+ +

How many items are stored in Address.

+
+
+ +
+
public int Count { get; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + +

Remarks

+

Not to confuse with BytesLength

+
+ + + + + + +

+ ItemLength + +

+ +

The size of a single item stored in Address.

+
+
+ +
+
public int ItemLength { get; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + +

Remarks

+

Equivalent to NPTypeCode.SizeOf extension.

+
+ + + + + + +

+ Pin + +

+ +

Provides the ability to return a pin to the memory address of NDArray.

+
+
+ +
+
public NDArray._Unsafe._Pinning Pin { get; }
+
+ + + + + +

Property Value

+
+
NDArray._Unsafe._Pinning
+
+
+ + + + +

Remarks

+

Possible only when the ndarray is not sliced.

+
+ + + + + + +

+ Storage + +

+ +

Provides access to the internal UnmanagedStorage.

+
+
+ +
+
public UnmanagedStorage Storage { get; }
+
+ + + + + +

Property Value

+
+
UnmanagedStorage
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ AsSpan<T>() + +

+ +
+
+ +
+
public Span<T> AsSpan<T>()
+
+ + +

Returns

+
+
Span<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+

Does not perform copy.

+
+ + + + + + +

+ Fill(object) + +

+ +

Fills all indexes with value.

+
+
+ +
+
public void Fill(object value)
+
+ +

Parameters

+
+
value object
+
+
+ + + + + + + + + + + + + + +

+ GetIndex(int) + +

+ +
+
+ +
+
public object GetIndex(int index)
+
+ +

Parameters

+
+
index int
+
+
+ +

Returns

+
+
object
+
+
+ + + + + + + + + + + + + +

+ GetIndex<T>(int) + +

+ +
+
+ +
+
public T GetIndex<T>(int index) where T : unmanaged
+
+ +

Parameters

+
+
index int
+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ GetPinnableReference() + +

+ +
+
+ +
+
public ref byte GetPinnableReference()
+
+ + +

Returns

+
+
byte
+
+
+ + + + + + + + +

Exceptions

+
+
InvalidOperationException
+

When this NDArray is a slice.

+
+
+ + + + + +

+ GetPinnableReference<T>() + +

+ +

Gets pinnable reference of the first item in the memory block storage.

+
+
+ +
+
public ref T GetPinnableReference<T>() where T : unmanaged
+
+ + +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.NDArray.html b/docs/website/api/NumSharp.NDArray.html new file mode 100644 index 000000000..d1ac2d0eb --- /dev/null +++ b/docs/website/api/NumSharp.NDArray.html @@ -0,0 +1,14874 @@ + + + + + Class NDArray | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NDArray +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +

An array object represents a multidimensional, homogeneous array of fixed-size items.
+An associated data-type object describes the format of each element in the array (its byte-order,
+how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.)

+
+
+ +
+
[SuppressMessage("ReSharper", "ParameterHidesMember")]
+[SuppressMessage("ReSharper", "ParameterHidesMember")]
+[SuppressMessage("ReSharper", "ParameterHidesMember")]
+[SuppressMessage("ReSharper", "ParameterHidesMember")]
+[SuppressMessage("ReSharper", "CoVariantArrayConversion")]
+[SuppressMessage("ReSharper", "ParameterHidesMember")]
+[SuppressMessage("ReSharper", "ParameterHidesMember")]
+public class NDArray : IIndex, ICloneable, IEnumerable
+
+ + + + +
+
Inheritance
+
+ +
NDArray
+
+
+ +
+
Implements
+
+ + + +
+
+ +
+
Derived
+
+
NDArray<TDType>
+
+
+ +
+
Inherited Members
+
+ + + + + +
+ +
+
Extension Methods
+
+ + + +
+ + + +

Remarks

+ + + +

Constructors +

+ + + + +

+ NDArray(IArraySlice, Shape, char) + +

+ +

Constructor which takes .NET array +dtype and shape is determined from array

+
+
+ +
+
public NDArray(IArraySlice values, Shape shape = default, char order = 'C')
+
+ +

Parameters

+
+
values IArraySlice
+
+
shape Shape
+
+
order char
+
+
+ + + + + + + + +

Remarks

+

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

+
+ + + + + + +

+ NDArray(UnmanagedStorage) + +

+ +

Creates a new NDArray with this storage.

+
+
+ +
+
public NDArray(UnmanagedStorage storage)
+
+ +

Parameters

+
+
storage UnmanagedStorage
+
+
+ + + + + + + + + + + + + + +

+ NDArray(UnmanagedStorage, Shape) + +

+ +

Creates a new NDArray with this storage.

+
+
+ +
+
protected NDArray(UnmanagedStorage storage, Shape shape)
+
+ +

Parameters

+
+
storage UnmanagedStorage
+
+
shape Shape
+

The shape to set for this NDArray, does not perform checks.

+
+
+ + + + + + + + +

Remarks

+

Doesn't copy. Does not perform checks for shape.

+
+ + + + + + +

+ NDArray(UnmanagedStorage, ref Shape) + +

+ +

Creates a new NDArray with this storage.

+
+
+ +
+
protected NDArray(UnmanagedStorage storage, ref Shape shape)
+
+ +

Parameters

+
+
storage UnmanagedStorage
+
+
shape Shape
+

The shape to set for this NDArray, does not perform checks.

+
+
+ + + + + + + + +

Remarks

+

Doesn't copy. Does not perform checks for shape.

+
+ + + + + + +

+ NDArray(NPTypeCode) + +

+ +

Constructor for init data type +internal storage is 1D with 1 element

+
+
+ +
+
public NDArray(NPTypeCode typeCode)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+

Data type of elements

+
+
+ + + + + + + + +

Remarks

+

This constructor does not call allocation/>

+
+ + + + + + +

+ NDArray(NPTypeCode, Shape) + +

+ +

Constructor which initialize elements with 0 +type and shape are given.

+
+
+ +
+
public NDArray(NPTypeCode dtype, Shape shape)
+
+ +

Parameters

+
+
dtype NPTypeCode
+

internal data type

+
+
shape Shape
+

Shape of NDArray

+
+
+ + + + + + + + +

Remarks

+

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

+
+ + + + + + +

+ NDArray(NPTypeCode, Shape, bool) + +

+ +

Constructor which initialize elements with 0 +type and shape are given.

+
+
+ +
+
public NDArray(NPTypeCode dtype, Shape shape, bool fillZeros)
+
+ +

Parameters

+
+
dtype NPTypeCode
+

internal data type

+
+
shape Shape
+

Shape of NDArray

+
+
fillZeros bool
+

Should set the values of the new allocation to default(dtype)? otherwise - old memory noise

+
+
+ + + + + + + + +

Remarks

+

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

+
+ + + + + + +

+ NDArray(NPTypeCode, TensorEngine) + +

+ +

Constructor for init data type +internal storage is 1D with 1 element

+
+
+ +
+
protected NDArray(NPTypeCode typeCode, TensorEngine engine)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+

Data type of elements

+
+
engine TensorEngine
+

The engine of this NDArray

+
+
+ + + + + + + + +

Remarks

+

This constructor does not call allocation/>

+
+ + + + + + +

+ NDArray(NPTypeCode, int) + +

+ +

Constructor which initialize elements with length of size

+
+
+ +
+
public NDArray(NPTypeCode dtype, int size)
+
+ +

Parameters

+
+
dtype NPTypeCode
+

Internal data type

+
+
size int
+

The size as a single dimension shape

+
+
+ + + + + + + + +

Remarks

+

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

+
+ + + + + + +

+ NDArray(NPTypeCode, int, bool) + +

+ +

Constructor which initialize elements with length of size

+
+
+ +
+
public NDArray(NPTypeCode dtype, int size, bool fillZeros)
+
+ +

Parameters

+
+
dtype NPTypeCode
+

Internal data type

+
+
size int
+

The size as a single dimension shape

+
+
fillZeros bool
+

Should set the values of the new allocation to default(dtype)? otherwise - old memory noise

+
+
+ + + + + + + + +

Remarks

+

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

+
+ + + + + + +

+ NDArray(Array, Shape, char) + +

+ +

Constructor which takes .NET array +dtype and shape is determined from array

+
+
+ +
+
public NDArray(Array values, Shape shape = default, char order = 'C')
+
+ +

Parameters

+
+
values Array
+
+
shape Shape
+
+
order char
+
+
+ + + + + + + + +

Remarks

+

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

+
+ + + + + + +

+ NDArray(Type) + +

+ +

Constructor for init data type +internal storage is 1D with 1 element

+
+
+ +
+
public NDArray(Type dtype)
+
+ +

Parameters

+
+
dtype Type
+

Data type of elements

+
+
+ + + + + + + + +

Remarks

+

This constructor does not call allocation/>

+
+ + + + + + +

+ NDArray(Type, Shape) + +

+ +

Constructor which initialize elements with 0 +type and shape are given.

+
+
+ +
+
public NDArray(Type dtype, Shape shape)
+
+ +

Parameters

+
+
dtype Type
+

internal data type

+
+
shape Shape
+

Shape of NDArray

+
+
+ + + + + + + + +

Remarks

+

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

+
+ + + + + + +

+ NDArray(Type, Shape, bool) + +

+ +

Constructor which initialize elements with 0 +type and shape are given.

+
+
+ +
+
public NDArray(Type dtype, Shape shape, bool fillZeros)
+
+ +

Parameters

+
+
dtype Type
+

internal data type

+
+
shape Shape
+

Shape of NDArray

+
+
fillZeros bool
+

Should set the values of the new allocation to default(dtype)? otherwise - old memory noise

+
+
+ + + + + + + + +

Remarks

+

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

+
+ + + + + + +

+ NDArray(Type, TensorEngine) + +

+ +

Constructor for init data type +internal storage is 1D with 1 element

+
+
+ +
+
protected NDArray(Type dtype, TensorEngine engine)
+
+ +

Parameters

+
+
dtype Type
+

Data type of elements

+
+
engine TensorEngine
+

The engine of this NDArray

+
+
+ + + + + + + + +

Remarks

+

This constructor does not call allocation/>

+
+ + + + + + +

+ NDArray(Type, int) + +

+ +

Constructor which initialize elements with length of size

+
+
+ +
+
public NDArray(Type dtype, int size)
+
+ +

Parameters

+
+
dtype Type
+

Internal data type

+
+
size int
+

The size as a single dimension shape

+
+
+ + + + + + + + +

Remarks

+

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

+
+ + + + + + +

+ NDArray(Type, int, bool) + +

+ +

Constructor which initialize elements with length of size

+
+
+ +
+
public NDArray(Type dtype, int size, bool fillZeros)
+
+ +

Parameters

+
+
dtype Type
+

Internal data type

+
+
size int
+

The size as a single dimension shape

+
+
fillZeros bool
+

Should set the values of the new allocation to default(dtype)? otherwise - old memory noise

+
+
+ + + + + + + + +

Remarks

+

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

+
+ + + + +

Fields +

+ + + +

+ Storage + +

+ +

The internal storage that stores data for this NDArray.

+
+
+ +
+
protected UnmanagedStorage Storage
+
+ + + + +

Field Value

+
+
UnmanagedStorage
+
+
+ + + + + + + + + + +

+ tensorEngine + +

+ +
+
+ +
+
protected TensorEngine tensorEngine
+
+ + + + +

Field Value

+
+
TensorEngine
+
+
+ + + + + + + + + +

Properties +

+ + + + +

+ Address + +

+ +

Gets the address that this NDArray starts from.

+
+
+ +
+
protected void* Address { get; }
+
+ + + + + +

Property Value

+
+
void*
+
+
+ + + + + + + + + + +

+ Array + +

+ +

Get: Gets internal storage array by calling IStorage.GetData
+Set: Replace internal storage by calling IStorage.ReplaceData(System.Array)

+
+
+ +
+
protected IArraySlice Array { get; }
+
+ + + + + +

Property Value

+
+
IArraySlice
+
+
+ + + + +

Remarks

+

Setting does not replace internal storage array.

+
+ + + + + + +

+ this[NDArray<bool>] + +

+ +

Used to perform selection based on a boolean mask.

+
+
+ +
+
[SuppressMessage("ReSharper", "CoVariantArrayConversion")]
+public NDArray this[NDArray<bool> mask] { get; set; }
+
+ +

Parameters

+
+
mask NDArray<bool>
+
+
+ + + + +

Property Value

+
+
NDArray
+
+
+ + + + +

Remarks

+ + +

Exceptions

+
+
IndexOutOfRangeException
+

When one of the indices exceeds limits.

+
+
ArgumentException
+

indices must be of Int type (byte, u/short, u/int, u/long).

+
+
+ + + + + +

+ this[NDArray<int>[]] + +

+ +

Used to perform selection based on a selection indices.

+
+
+ +
+
public NDArray this[params NDArray<int>[] selection] { get; set; }
+
+ +

Parameters

+
+
selection NDArray<int>[]
+
+
+ + + + +

Property Value

+
+
NDArray
+
+
+ + + + +

Remarks

+ + +

Exceptions

+
+
IndexOutOfRangeException
+

When one of the indices exceeds limits.

+
+
ArgumentException
+

indices must be of Int type (byte, u/short, u/int, u/long).

+
+
+ + + + + +

+ this[Slice[]] + +

+ +

Slice the array with Python slice notation like this: ":, 2:7:1, ..., np.newaxis"

+
+
+ +
+
public NDArray this[params Slice[] slice] { get; set; }
+
+ +

Parameters

+
+
slice Slice[]
+

A string containing slice notations for every dimension, delimited by comma

+
+
+ + + + +

Property Value

+
+
NDArray
+

A sliced view

+
+
+ + + + + + + + + + +

+ this[int*, int] + +

+ +

Used to perform selection based on given indices.

+
+
+ +
+
public NDArray this[int* dims, int ndims] { get; set; }
+
+ +

Parameters

+
+
dims int*
+

The pointer to the dimensions

+
+
ndims int
+

The count of ints in dims

+
+
+ + + + +

Property Value

+
+
NDArray
+
+
+ + + + + + + + + + +

+ this[object[]] + +

+ +

Perform slicing, index extraction, masking and indexing all at the same time with mixed index objects

+
+
+ +
+
public NDArray this[params object[] indicesObjects] { get; set; }
+
+ +

Parameters

+
+
indicesObjects object[]
+
+
+ + + + +

Property Value

+
+
NDArray
+
+
+ + + + + + + + + + +

+ this[string] + +

+ +

Slice the array with Python slice notation like this: ":, 2:7:1, ..., np.newaxis"

+
+
+ +
+
public NDArray this[string slice] { get; set; }
+
+ +

Parameters

+
+
slice string
+

A string containing slice notations for every dimension, delimited by comma

+
+
+ + + + +

Property Value

+
+
NDArray
+

A sliced view

+
+
+ + + + + + + + + + +

+ Shape + +

+ +

The shape representing this NDArray.

+
+
+ +
+
public Shape Shape { get; set; }
+
+ + + + + +

Property Value

+
+
Shape
+
+
+ + + + + + + + + + +

+ T + +

+ +

The transposed array.
+Same as self.transpose().

+
+
+ +
+
public NDArray T { get; }
+
+ + + + + +

Property Value

+
+
NDArray
+
+
+ + + + +

Remarks

+ + + + + + + +

+ TensorEngine + +

+ +

The tensor engine that handles this NDArray.

+
+
+ +
+
public TensorEngine TensorEngine { get; set; }
+
+ + + + + +

Property Value

+
+
TensorEngine
+
+
+ + + + + + + + + + +

+ Unsafe + +

+ +

Provides an interface for unsafe methods in NDArray.

+
+
+ +
+
public NDArray._Unsafe Unsafe { get; }
+
+ + + + + +

Property Value

+
+
NDArray._Unsafe
+
+
+ + + + + + + + + + +

+ dtype + +

+ +

The dtype of this array.

+
+
+ +
+
public Type dtype { get; }
+
+ + + + + +

Property Value

+
+
Type
+
+
+ + + + + + + + + + +

+ dtypesize + +

+ +
+
+ +
+
public int dtypesize { get; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + + + + + + + +

+ flat + +

+ +

A 1-D iterator over the array.

+
+
+ +
+
public NDArray flat { get; }
+
+ + + + + +

Property Value

+
+
NDArray
+
+
+ + + + +

Remarks

+ + + + + + + +

+ ndim + +

+ +

Dimension count

+
+
+ +
+
public int ndim { get; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + + + + + + + +

+ order + +

+ +
+
+ +
+
public char order { get; }
+
+ + + + + +

Property Value

+
+
char
+
+
+ + + + + + + + + + +

+ shape + +

+ +

Data length of every dimension

+
+
+ +
+
public int[] shape { get; set; }
+
+ + + + + +

Property Value

+
+
int[]
+
+
+ + + + + + + + + + +

+ size + +

+ +

Total of elements

+
+
+ +
+
public int size { get; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + + + + + + + +

+ strides + +

+ +
+
+ +
+
public int[] strides { get; }
+
+ + + + + +

Property Value

+
+
int[]
+
+
+ + + + + + + + + + +

+ typecode + +

+ +

The NPTypeCode of this array.

+
+
+ +
+
public NPTypeCode typecode { get; }
+
+ + + + + +

Property Value

+
+
NPTypeCode
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ AsGeneric<T>() + +

+ +

Tries to cast to NDArray<TDType>, otherwise creates an alias without reallocating data.

+
+
+ +
+
public NDArray<T> AsGeneric<T>() where T : unmanaged
+
+ + +

Returns

+
+
NDArray<T>
+

This NDArray as a generic version.

+
+
+ +

Type Parameters

+
+
T
+

The type of the generic

+
+
+ + + + + + + +

Exceptions

+
+
InvalidOperationException
+

When T != dtype

+
+
+ + + + + +

+ AsOrMakeGeneric<T>() + +

+ +

Tries to cast to NDArray<TDType>, otherwise calls NDArray<T>.astype.

+
+
+ +
+
public NDArray<T> AsOrMakeGeneric<T>() where T : unmanaged
+
+ + +

Returns

+
+
NDArray<T>
+

This NDArray as a generic version.

+
+
+ +

Type Parameters

+
+
T
+

The type of the generic

+
+
+ + + + + + + +

Exceptions

+
+
InvalidOperationException
+

When T != dtype

+
+
+ + + + + +

+ AsString(NDArray) + +

+ +

Converts the entire NDArray to a string.

+
+
+ +
+
public static string AsString(NDArray arr)
+
+ +

Parameters

+
+
arr NDArray
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + +

Remarks

+

Performs a copy due to String .net-framework limitations.

+
+ + + + + + +

+ AsStringArray(NDArray) + +

+ +

Convert to String[] from NDArray

+
+
+ +
+
public static string[] AsStringArray(NDArray arr)
+
+ +

Parameters

+
+
arr NDArray
+
+
+ +

Returns

+
+
string[]
+
+
+ + + + + + + + + + + + + +

+ Clone() + +

+ +

Clone the whole NDArray +internal storage is also cloned into 2nd memory area

+
+
+ +
+
public NDArray Clone()
+
+ + +

Returns

+
+
NDArray
+

Cloned NDArray

+
+
+ + + + + + + + + + + + + +

+ CloneData() + +

+ +
+
+ +
+
public IArraySlice CloneData()
+
+ + +

Returns

+
+
IArraySlice
+
+
+ + + + + + + + + + + + + +

+ CloneData<T>() + +

+ +
+
+ +
+
public ArraySlice<T> CloneData<T>() where T : unmanaged
+
+ + +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ CopyTo(IMemoryBlock) + +

+ +

Copies the entire contents of this storage to given address (using Count).

+
+
+ +
+
public void CopyTo(IMemoryBlock slice)
+
+ +

Parameters

+
+
slice IMemoryBlock
+

The slice to copy to.

+
+
+ + + + + + + + + + + + + + +

+ CopyTo(nint) + +

+ +

Copies the entire contents of this storage to given address.

+
+
+ +
+
public void CopyTo(nint ptr)
+
+ +

Parameters

+
+
ptr nint
+
+
+ + + + + + + + + + + + + + +

+ CopyTo(void*) + +

+ +

Copies the entire contents of this storage to given address (using Count).

+
+
+ +
+
public void CopyTo(void* address)
+
+ +

Parameters

+
+
address void*
+

The address to copy to.

+
+
+ + + + + + + + + + + + + + +

+ CopyTo<T>(IMemoryBlock<T>) + +

+ +

Copies the entire contents of this storage to given address (using Count).

+
+
+ +
+
public void CopyTo<T>(IMemoryBlock<T> block) where T : unmanaged
+
+ +

Parameters

+
+
block IMemoryBlock<T>
+

The slice to copy to.

+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ CopyTo<T>(T*) + +

+ +

Copies the entire contents of this storage to given address.

+
+
+ +
+
public void CopyTo<T>(T* address) where T : unmanaged
+
+ +

Parameters

+
+
address T*
+

The address to copy to.

+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ CopyTo<T>(T[]) + +

+ +

Copies the entire contents of this storage to given array.

+
+
+ +
+
public void CopyTo<T>(T[] array) where T : unmanaged
+
+ +

Parameters

+
+
array T[]
+

The array to copy to.

+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Data<T>() + +

+ +

Shortcut for access internal elements

+
+
+ +
+
public ArraySlice<T> Data<T>() where T : unmanaged
+
+ + +

Returns

+
+
ArraySlice<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Equals(object) + +

+ +

Determines if NDArray data is same

+
+
+ +
+
public override bool Equals(object obj)
+
+ +

Parameters

+
+
obj object
+

NDArray to compare

+
+
+ +

Returns

+
+
bool
+

if reference is same

+
+
+ + + + + + + + + + + + + +

+ ExpandEllipsis(object[], int) + +

+ +
+
+ +
+
protected static IEnumerable<object> ExpandEllipsis(object[] ndarrays, int ndim)
+
+ +

Parameters

+
+
ndarrays object[]
+
+
ndim int
+
+
+ +

Returns

+
+
IEnumerable<object>
+
+
+ + + + + + + + + + + + + +

+ FetchIndices(NDArray, NDArray[], NDArray, bool) + +

+ +
+
+ +
+
protected static NDArray FetchIndices(NDArray src, NDArray[] indices, NDArray @out, bool extraDim)
+
+ +

Parameters

+
+
src NDArray
+
+
indices NDArray[]
+
+
out NDArray
+
+
extraDim bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ FetchIndicesNDNonLinear<T>(NDArray<T>, NDArray[], int, int[], int[], NDArray) + +

+ +

Accepts collapsed

+
+
+ +
+
[SuppressMessage("ReSharper", "SuggestVarOrType_Elsewhere")]
+protected static NDArray<T> FetchIndicesNDNonLinear<T>(NDArray<T> source, NDArray[] indices, int ndsCount, int[] retShape, int[] subShape, NDArray @out) where T : unmanaged
+
+ +

Parameters

+
+
source NDArray<T>
+
+
indices NDArray[]
+
+
ndsCount int
+
+
retShape int[]
+
+
subShape int[]
+
+
out NDArray
+
+
+ +

Returns

+
+
NDArray<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FetchIndicesND<T>(NDArray<T>, NDArray<int>, NDArray[], int, int[], int[], NDArray) + +

+ +

Accepts collapsed

+
+
+ +
+
protected static NDArray<T> FetchIndicesND<T>(NDArray<T> src, NDArray<int> offsets, NDArray[] indices, int ndsCount, int[] retShape, int[] subShape, NDArray @out) where T : unmanaged
+
+ +

Parameters

+
+
src NDArray<T>
+
+
offsets NDArray<int>
+
+
indices NDArray[]
+
+
ndsCount int
+
+
retShape int[]
+
+
subShape int[]
+
+
out NDArray
+
+
+ +

Returns

+
+
NDArray<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FetchIndices<T>(NDArray<T>, NDArray[], NDArray, bool) + +

+ +
+
+ +
+
protected static NDArray<T> FetchIndices<T>(NDArray<T> source, NDArray[] indices, NDArray @out, bool extraDim) where T : unmanaged
+
+ +

Parameters

+
+
source NDArray<T>
+
+
indices NDArray[]
+
+
out NDArray
+
+
extraDim bool
+
+
+ +

Returns

+
+
NDArray<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromMultiDimArray<T>(Array, bool) + +

+ +

Creates an NDArray out of given array of type T

+
+
+ +
+
public static NDArray FromMultiDimArray<T>(Array ndarray, bool copy = true) where T : unmanaged
+
+ +

Parameters

+
+
ndarray Array
+
+
copy bool
+

true for making

+
+
+ +

Returns

+
+
NDArray
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ FromString(string) + +

+ +

Converts a string to a vector ndarray of bytes.

+
+
+ +
+
public static NDArray FromString(string str)
+
+ +

Parameters

+
+
str string
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ GetAtIndex(int) + +

+ +

Retrieves value of

+
+
+ +
+
public ValueType GetAtIndex(int index)
+
+ +

Parameters

+
+
index int
+
+
+ +

Returns

+
+
ValueType
+
+
+ + + + + + + + + + + + + +

+ GetAtIndex<T>(int) + +

+ +

Retrieves value of

+
+
+ +
+
public T GetAtIndex<T>(int index) where T : unmanaged
+
+ +

Parameters

+
+
index int
+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ GetBoolean(params int[]) + +

+ +

Retrieves value of type bool.

+
+
+ +
+
public bool GetBoolean(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not bool

+
+
+ + + + + +

+ GetByte(params int[]) + +

+ +

Retrieves value of type byte.

+
+
+ +
+
public byte GetByte(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not byte

+
+
+ + + + + +

+ GetChar(params int[]) + +

+ +

Retrieves value of type char.

+
+
+ +
+
public char GetChar(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not char

+
+
+ + + + + +

+ GetData() + +

+ +

Get reference to internal data storage

+
+
+ +
+
public IArraySlice GetData()
+
+ + +

Returns

+
+
IArraySlice
+

reference to internal storage as System.Array

+
+
+ + + + + + + + + + + + + +

+ GetData(params int[]) + +

+ +

Gets a NDArray at given indices.

+
+
+ +
+
public NDArray GetData(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The coordinates to the wanted value

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+

Does not copy, returns a memory slice - this is similar to this[int[]]

+
+ + + + + + +

+ GetData<T>() + +

+ +

Gets the internal storage and converts it to T if necessary.

+
+
+ +
+
public ArraySlice<T> GetData<T>() where T : unmanaged
+
+ + +

Returns

+
+
ArraySlice<T>
+

An array of type T

+
+
+ +

Type Parameters

+
+
T
+

The returned type.

+
+
+ + + + + + + + + + + + +

+ GetDecimal(params int[]) + +

+ +

Retrieves value of type decimal.

+
+
+ +
+
public decimal GetDecimal(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not decimal

+
+
+ + + + + +

+ GetDouble(params int[]) + +

+ +

Retrieves value of type double.

+
+
+ +
+
public double GetDouble(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not double

+
+
+ + + + + +

+ GetEnumerator() + +

+ +

Returns an enumerator that iterates through a collection.

+
+
+ +
+
public IEnumerator GetEnumerator()
+
+ + +

Returns

+
+
IEnumerator
+

An IEnumerator object that can be used to iterate through the collection.

+
+
+ + + + + + + + + + + + + +

+ GetIndices(NDArray, NDArray[]) + +

+ +

Used to perform selection based on indices, equivalent to nd[NDArray[]].

+
+
+ +
+
public NDArray GetIndices(NDArray @out, NDArray[] indices)
+
+ +

Parameters

+
+
out NDArray
+
+
indices NDArray[]
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + +

Exceptions

+
+
IndexOutOfRangeException
+

When one of the indices exceeds limits.

+
+
ArgumentException
+

indices must be of Int type (byte, u/short, u/int, u/long).

+
+
+ + + + + +

+ GetIndicesFromSlice(Shape, Slice, int) + +

+ +

Converts a slice to indices for the special case where slices are mixed with NDArrays in this[...]

+
+
+ +
+
protected static NDArray<int> GetIndicesFromSlice(Shape shape, Slice slice, int axis)
+
+ +

Parameters

+
+
shape Shape
+
+
slice Slice
+
+
axis int
+
+
+ +

Returns

+
+
NDArray<int>
+
+
+ + + + + + + + + + + + + +

+ GetIndicesFromSlice(int[], Slice, int) + +

+ +

Converts a slice to indices for the special case where slices are mixed with NDArrays in this[...]

+
+
+ +
+
protected static NDArray<int> GetIndicesFromSlice(int[] shape, Slice slice, int axis)
+
+ +

Parameters

+
+
shape int[]
+
+
slice Slice
+
+
axis int
+
+
+ +

Returns

+
+
NDArray<int>
+
+
+ + + + + + + + + + + + + +

+ GetInt16(params int[]) + +

+ +

Retrieves value of type short.

+
+
+ +
+
public short GetInt16(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not short

+
+
+ + + + + +

+ GetInt32(params int[]) + +

+ +

Retrieves value of type int.

+
+
+ +
+
public int GetInt32(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not int

+
+
+ + + + + +

+ GetInt64(params int[]) + +

+ +

Retrieves value of type long.

+
+
+ +
+
public long GetInt64(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not long

+
+
+ + + + + +

+ GetNDArrays(int) + +

+ +

Get all NDArray slices at that specific dimension.

+
+
+ +
+
[SuppressMessage("ReSharper", "LoopCanBeConvertedToQuery")]
+public NDArray[] GetNDArrays(int axis = 0)
+
+ +

Parameters

+
+
axis int
+

Zero-based dimension index on which axis and forward of it to select data., e.g. dimensions=1, shape is (2,2,3,3), returned shape = 4 times of (3,3)

+
+
+ +

Returns

+
+
NDArray[]
+
+
+ + + + + + +

Examples

+
var nd = np.arange(27).reshape(3,1,3,3);
+var ret = nd.GetNDArrays(1);
+Assert.IsTrue(ret.All(n=>n.Shape == new Shape(3,3));
+Assert.IsTrue(ret.Length == 3);
+var nd = np.arange(27).reshape(3,1,3,3);
+
+var ret = nd.GetNDArrays(0);
+Assert.IsTrue(ret.All(n=>n.Shape == new Shape(1,3,3));
+Assert.IsTrue(ret.Length == 3);
+ + +

Remarks

+

Does not perform copy.

+
+ + + + + + +

+ GetSingle(params int[]) + +

+ +

Retrieves value of type float.

+
+
+ +
+
public float GetSingle(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not float

+
+
+ + + + + +

+ GetString(params int[]) + +

+ +

Get a string out of a vector of chars.

+
+
+ +
+
public string GetString(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + +

Remarks

+

Performs a copy due to String .net-framework limitations.

+
+ + + + + + +

+ GetStringAt(int) + +

+ +

Get a string out of a vector of chars.

+
+
+ +
+
public string GetStringAt(int offset)
+
+ +

Parameters

+
+
offset int
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + +

Remarks

+

Performs a copy due to String .net-framework limitations.

+
+ + + + + + +

+ GetUInt16(params int[]) + +

+ +

Retrieves value of type ushort.

+
+
+ +
+
public ushort GetUInt16(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not ushort

+
+
+ + + + + +

+ GetUInt32(params int[]) + +

+ +

Retrieves value of type uint.

+
+
+ +
+
public uint GetUInt32(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not uint

+
+
+ + + + + +

+ GetUInt64(params int[]) + +

+ +

Retrieves value of type ulong.

+
+
+ +
+
public ulong GetUInt64(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not ulong

+
+
+ + + + + +

+ GetValue(params int[]) + +

+ +

Retrieves value of unspecified type (will figure using DType).

+
+
+ +
+
public ValueType GetValue(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
ValueType
+
+
+ + + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not object

+
+
+ + + + + +

+ GetValue<T>(params int[]) + +

+ +

Retrieves value of unspecified type (will figure using DType).

+
+
+ +
+
public T GetValue<T>(params int[] indices) where T : unmanaged
+
+ +

Parameters

+
+
indices int[]
+

The shape's indices to get.

+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + +

Exceptions

+
+
NullReferenceException
+

When DType is not object

+
+
+ + + + + +

+ MakeGeneric<T>() + +

+ +

Creates an alias without reallocating data.

+
+
+ +
+
public NDArray<T> MakeGeneric<T>() where T : unmanaged
+
+ + +

Returns

+
+
NDArray<T>
+

This NDArray as a generic version.

+
+
+ +

Type Parameters

+
+
T
+

The type of the generic

+
+
+ + + + + + + +

Exceptions

+
+
InvalidOperationException
+

When T != dtype

+
+
+ + + + + +

+ Normalize() + +

+ +

Normalizes all entries into the range between 0 and 1

+

Note: this is not a numpy function.

+
+
+ +
+
public void Normalize()
+
+ + + + + + + + + + + + + + + +

+ PrepareIndexGetters(Shape, NDArray[]) + +

+ +

Generates index getter function based on given indices.

+
+
+ +
+
protected static Func<int, int>[] PrepareIndexGetters(Shape srcShape, NDArray[] indices)
+
+ +

Parameters

+
+
srcShape Shape
+

The shape to get indice from

+
+
indices NDArray[]
+

The indices trying to index.

+
+
+ +

Returns

+
+
Func<int, int>[]
+
+
+ + + + + + + + + + + + + +

+ ReplaceData(IArraySlice) + +

+ +

Sets values as the internal data source and changes the internal storage data type to values type.

+
+
+ +
+
public void ReplaceData(IArraySlice values)
+
+ +

Parameters

+
+
values IArraySlice
+
+
+ + + + + + + + +

Remarks

+

Does not copy values and doesn't change shape.

+
+ + + + + + +

+ ReplaceData(IArraySlice, Type) + +

+ +

Sets values as the internal data source and changes the internal storage data type to values type.

+
+
+ +
+
public void ReplaceData(IArraySlice values, Type dtype)
+
+ +

Parameters

+
+
values IArraySlice
+
+
dtype Type
+
+
+ + + + + + + + +

Remarks

+

Does not copy values and doesn't change shape.

+
+ + + + + + +

+ ReplaceData(NDArray) + +

+ +

Sets nd as the internal data storage and changes the internal storage data type to nd type.

+
+
+ +
+
public void ReplaceData(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ + + + + + + + +

Remarks

+

Does not copy values and does change shape and dtype.

+
+ + + + + + +

+ ReplaceData(Array) + +

+ +

Sets values as the internal data storage and changes the internal storage data type to values type.

+
+
+ +
+
public void ReplaceData(Array values)
+
+ +

Parameters

+
+
values Array
+
+
+ + + + + + + + +

Remarks

+

Does not copy values.

+
+ + + + + + +

+ ReplaceData(Array, NPTypeCode) + +

+ +

Set an Array to internal storage, cast it to new dtype and if necessary change dtype

+
+
+ +
+
public void ReplaceData(Array values, NPTypeCode typeCode)
+
+ +

Parameters

+
+
values Array
+
+
typeCode NPTypeCode
+
+
+ + + + + + + + +

Remarks

+

Does not copy values unless cast is necessary and doesn't change shape.

+
+ + + + + + +

+ ReplaceData(Array, Type) + +

+ +

Sets values as the internal data storage and changes the internal storage data type to dtype and casts values if necessary.

+
+
+ +
+
public void ReplaceData(Array values, Type dtype)
+
+ +

Parameters

+
+
values Array
+

The values to set as internal data soruce

+
+
dtype Type
+

The type to change this storage to and the type to cast values if necessary.

+
+
+ + + + + + + + +

Remarks

+

Does not copy values unless cast is necessary.

+
+ + + + + + +

+ Scalar(object) + +

+ +

Creates a scalar NDArray of value and dtype.

+
+
+ +
+
public static NDArray Scalar(object value)
+
+ +

Parameters

+
+
value object
+

The value of the scalar

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+

In case when value is not dtype, Converts.ChangeType(object,System.Type) will be called.

+
+ + + + + + +

+ Scalar(object, NPTypeCode) + +

+ +

Creates a scalar NDArray of value and dtype.

+
+
+ +
+
public static NDArray Scalar(object value, NPTypeCode typeCode)
+
+ +

Parameters

+
+
value object
+

The value of the scalar

+
+
typeCode NPTypeCode
+

The type code of the scalar.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+

In case when value is not dtype, Converts.ChangeType(object,System.Type) will be called.

+
+ + + + + + +

+ Scalar(object, Type) + +

+ +

Creates a scalar NDArray of value and dtype.

+
+
+ +
+
public static NDArray Scalar(object value, Type dtype)
+
+ +

Parameters

+
+
value object
+

The value of the scalar

+
+
dtype Type
+

The type of the scalar.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+

In case when value is not dtype, Converts.ChangeType(object,System.Type) will be called.

+
+ + + + + + +

+ Scalar(ValueType) + +

+ +

Creates a scalar NDArray of value and dtype.

+
+
+ +
+
public static NDArray Scalar(ValueType value)
+
+ +

Parameters

+
+
value ValueType
+

The value of the scalar

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+

In case when value is not dtype, Converts.ChangeType(object,System.Type) will be called.

+
+ + + + + + +

+ Scalar<T>(object) + +

+ +

Creates a scalar NDArray of value and dtype.

+
+
+ +
+
public static NDArray Scalar<T>(object value) where T : unmanaged
+
+ +

Parameters

+
+
value object
+

The value of the scalar, attempt to convert will be performed

+
+
+ +

Returns

+
+
NDArray
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+

In case when value is not dtype, Converts.ChangeType(object,System.Type) will be called.

+
+ + + + + + +

+ Scalar<T>(T) + +

+ +

Creates a scalar NDArray of value and dtype.

+
+
+ +
+
public static NDArray Scalar<T>(T value) where T : unmanaged
+
+ +

Parameters

+
+
value T
+

The value of the scalar

+
+
+ +

Returns

+
+
NDArray
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+

In case when value is not dtype, Converts.ChangeType(object,System.Type) will be called.

+
+ + + + + + +

+ SetAtIndex(object, int) + +

+ +

Retrieves value at given linear (offset) index.

+
+
+ +
+
public void SetAtIndex(object obj, int index)
+
+ +

Parameters

+
+
obj object
+
+
index int
+
+
+ + + + + + + + + + + + + + +

+ SetAtIndex<T>(T, int) + +

+ +

Retrieves value of

+
+
+ +
+
public void SetAtIndex<T>(T value, int index) where T : unmanaged
+
+ +

Parameters

+
+
value T
+
+
index int
+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ SetBoolean(bool, params int[]) + +

+ +

Sets a bool at specific coordinates.

+
+
+ +
+
public void SetBoolean(bool value, params int[] indices)
+
+ +

Parameters

+
+
value bool
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetByte(byte, params int[]) + +

+ +

Sets a byte at specific coordinates.

+
+
+ +
+
public void SetByte(byte value, params int[] indices)
+
+ +

Parameters

+
+
value byte
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetChar(char, params int[]) + +

+ +

Sets a char at specific coordinates.

+
+
+ +
+
public void SetChar(char value, params int[] indices)
+
+ +

Parameters

+
+
value char
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetData(IArraySlice, params int[]) + +

+ +

Set a IArraySlice at given indices.

+
+
+ +
+
public void SetData(IArraySlice value, params int[] indices)
+
+ +

Parameters

+
+
value IArraySlice
+

The value to set

+
+
indices int[]
+

The

+
+
+ + + + + + + + +

Remarks

+

Does not change internal storage data type.
+If value does not match DType, value will be converted.

+
+ + + + + + +

+ SetData(NDArray, params int[]) + +

+ +

Set a NDArray at given indices.

+
+
+ +
+
public void SetData(NDArray value, params int[] indices)
+
+ +

Parameters

+
+
value NDArray
+

The value to set

+
+
indices int[]
+

The

+
+
+ + + + + + + + +

Remarks

+

Does not change internal storage data type.
+If value does not match DType, value will be converted.

+
+ + + + + + +

+ SetData(object) + +

+ +
+
+ +
+
public void SetData(object p)
+
+ +

Parameters

+
+
p object
+
+
+ + + + + + + + + + + + + + +

+ SetData(object, params int[]) + +

+ +

Set a NDArray, IArraySlice, Array or a scalar value at given indices.

+
+
+ +
+
public void SetData(object value, params int[] indices)
+
+ +

Parameters

+
+
value object
+

The value to set

+
+
indices int[]
+

The

+
+
+ + + + + + + + +

Remarks

+

Does not change internal storage data type.
+If value does not match DType, value will be converted.

+
+ + + + + + +

+ SetDecimal(decimal, params int[]) + +

+ +

Sets a decimal at specific coordinates.

+
+
+ +
+
public void SetDecimal(decimal value, params int[] indices)
+
+ +

Parameters

+
+
value decimal
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetDouble(double, params int[]) + +

+ +

Sets a double at specific coordinates.

+
+
+ +
+
public void SetDouble(double value, params int[] indices)
+
+ +

Parameters

+
+
value double
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetIndices(NDArray, NDArray[]) + +

+ +

Used to perform set a selection based on indices, equivalent to nd[NDArray[]] = values.

+
+
+ +
+
public void SetIndices(NDArray values, NDArray[] indices)
+
+ +

Parameters

+
+
values NDArray
+

The values to set via .

+
+
indices NDArray[]
+
+
+ + + + + + + + +

Remarks

+ + +

Exceptions

+
+
IndexOutOfRangeException
+

When one of the indices exceeds limits.

+
+
ArgumentException
+

indices must be of Int type (byte, u/short, u/int, u/long).

+
+
+ + + + + +

+ SetIndices(NDArray, NDArray[], NDArray) + +

+ +
+
+ +
+
protected static void SetIndices(NDArray src, NDArray[] indices, NDArray values)
+
+ +

Parameters

+
+
src NDArray
+
+
indices NDArray[]
+
+
values NDArray
+
+
+ + + + + + + + + + + + + + +

+ SetIndices(object[], NDArray) + +

+ +
+
+ +
+
protected void SetIndices(object[] indicesObjects, NDArray values)
+
+ +

Parameters

+
+
indicesObjects object[]
+
+
values NDArray
+
+
+ + + + + + + + + + + + + + +

+ SetIndicesNDNonLinear<T>(NDArray<T>, NDArray[], int, int[], int[], NDArray<T>) + +

+ +

Accepts collapsed

+
+
+ +
+
[SuppressMessage("ReSharper", "SuggestVarOrType_Elsewhere")]
+protected static void SetIndicesNDNonLinear<T>(NDArray<T> source, NDArray[] indices, int ndsCount, int[] retShape, int[] subShape, NDArray<T> values) where T : unmanaged
+
+ +

Parameters

+
+
source NDArray<T>
+
+
indices NDArray[]
+
+
ndsCount int
+
+
retShape int[]
+
+
subShape int[]
+
+
values NDArray<T>
+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ SetIndicesND<T>(NDArray<T>, NDArray<int>, NDArray[], int, int[], int[], NDArray<T>) + +

+ +

Accepts collapsed

+
+
+ +
+
protected static void SetIndicesND<T>(NDArray<T> dst, NDArray<int> dstOffsets, NDArray[] dstIndices, int ndsCount, int[] retShape, int[] subShape, NDArray<T> values) where T : unmanaged
+
+ +

Parameters

+
+
dst NDArray<T>
+
+
dstOffsets NDArray<int>
+
+
dstIndices NDArray[]
+
+
ndsCount int
+
+
retShape int[]
+
+
subShape int[]
+
+
values NDArray<T>
+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ SetIndices<T>(NDArray<T>, NDArray[], NDArray) + +

+ +
+
+ +
+
protected static void SetIndices<T>(NDArray<T> source, NDArray[] indices, NDArray values) where T : unmanaged
+
+ +

Parameters

+
+
source NDArray<T>
+
+
indices NDArray[]
+
+
values NDArray
+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ SetInt16(short, params int[]) + +

+ +

Sets a short at specific coordinates.

+
+
+ +
+
public void SetInt16(short value, params int[] indices)
+
+ +

Parameters

+
+
value short
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetInt32(int, params int[]) + +

+ +

Sets a int at specific coordinates.

+
+
+ +
+
public void SetInt32(int value, params int[] indices)
+
+ +

Parameters

+
+
value int
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetInt64(long, params int[]) + +

+ +

Sets a long at specific coordinates.

+
+
+ +
+
public void SetInt64(long value, params int[] indices)
+
+ +

Parameters

+
+
value long
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetSingle(float, params int[]) + +

+ +

Sets a float at specific coordinates.

+
+
+ +
+
public void SetSingle(float value, params int[] indices)
+
+ +

Parameters

+
+
value float
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetString(string, params int[]) + +

+ +
+
+ +
+
public void SetString(string value, params int[] indices)
+
+ +

Parameters

+
+
value string
+
+
indices int[]
+
+
+ + + + + + + + + + + + + + +

+ SetStringAt(string, int) + +

+ +
+
+ +
+
public void SetStringAt(string value, int offset)
+
+ +

Parameters

+
+
value string
+
+
offset int
+
+
+ + + + + + + + + + + + + + +

+ SetUInt16(ushort, params int[]) + +

+ +

Sets a ushort at specific coordinates.

+
+
+ +
+
public void SetUInt16(ushort value, params int[] indices)
+
+ +

Parameters

+
+
value ushort
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetUInt32(uint, params int[]) + +

+ +

Sets a uint at specific coordinates.

+
+
+ +
+
public void SetUInt32(uint value, params int[] indices)
+
+ +

Parameters

+
+
value uint
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetUInt64(ulong, params int[]) + +

+ +

Sets a ulong at specific coordinates.

+
+
+ +
+
public void SetUInt64(ulong value, params int[] indices)
+
+ +

Parameters

+
+
value ulong
+

The values to assign

+
+
indices int[]
+

The coordinates to set value at.

+
+
+ + + + + + + + + + + + + + +

+ SetValue(object, params int[]) + +

+ +

Set a single value at given indices.

+
+
+ +
+
public void SetValue(object value, params int[] indices)
+
+ +

Parameters

+
+
value object
+

The value to set

+
+
indices int[]
+

The

+
+
+ + + + + + + + +

Remarks

+

Does not change internal storage data type.
+If value does not match DType, value will be converted.

+
+ + + + + + +

+ SetValue(ValueType, params int[]) + +

+ +

Set a single value at given indices.

+
+
+ +
+
public void SetValue(ValueType value, params int[] indices)
+
+ +

Parameters

+
+
value ValueType
+

The value to set

+
+
indices int[]
+

The

+
+
+ + + + + + + + +

Remarks

+

Does not change internal storage data type.
+If value does not match DType, value will be converted.

+
+ + + + + + +

+ SetValue<T>(T, params int[]) + +

+ +

Set a single value at given indices.

+
+
+ +
+
public void SetValue<T>(T value, params int[] indices) where T : unmanaged
+
+ +

Parameters

+
+
value T
+

The value to set

+
+
indices int[]
+

The

+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+

Does not change internal storage data type.
+If value does not match DType, value will be converted.

+
+ + + + + + +

+ ToArray<T>() + +

+ +
+
+ +
+
public T[] ToArray<T>() where T : unmanaged
+
+ + +

Returns

+
+
T[]
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ ToByteArray() + +

+ +
+
+ +
+
public byte[] ToByteArray()
+
+ + +

Returns

+
+
byte[]
+
+
+ + + + + + + + + + + + + +

+ ToJaggedArray<T>() + +

+ +
+
+ +
+
public Array ToJaggedArray<T>() where T : unmanaged
+
+ + +

Returns

+
+
Array
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ ToMuliDimArray<T>() + +

+ +
+
+ +
+
public Array ToMuliDimArray<T>() where T : unmanaged
+
+ + +

Returns

+
+
Array
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ ToString() + +

+ +

Returns a string that represents the current object.

+
+
+ +
+
public override string ToString()
+
+ + +

Returns

+
+
string
+

A string that represents the current object.

+
+
+ + + + + + + + + + + + + +

+ ToString(bool) + +

+ +
+
+ +
+
public string ToString(bool flat)
+
+ +

Parameters

+
+
flat bool
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ amax(int, bool, Type) + +

+ +

Return the maximum of an array or maximum along an axis.

+
+
+ +
+
[SuppressMessage("ReSharper", "TooWideLocalVariableScope")]
+[SuppressMessage("ReSharper", "ParameterHidesMember")]
+public NDArray amax(int axis, bool keepdims = false, Type dtype = null)
+
+ +

Parameters

+
+
axis int
+

Axis or axes along which to operate.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
dtype Type
+

the type expected as a return, null will remain the same dtype.

+
+
+ +

Returns

+
+
NDArray
+

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ amax(Type) + +

+ +

Return the maximum of an array or maximum along an axis.

+
+
+ +
+
[SuppressMessage("ReSharper", "TooWideLocalVariableScope")]
+[SuppressMessage("ReSharper", "ParameterHidesMember")]
+public NDArray amax(Type dtype = null)
+
+ +

Parameters

+
+
dtype Type
+

the type expected as a return, null will remain the same dtype.

+
+
+ +

Returns

+
+
NDArray
+

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ amax<T>() + +

+ +

Return the maximum of an array or maximum along an axis.

+
+
+ +
+
public T amax<T>() where T : unmanaged
+
+ + +

Returns

+
+
T
+

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ +

Type Parameters

+
+
T
+

The expected return type, cast will be performed if necessary.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ amin(int, bool, Type) + +

+ +

Return the minimum of an array or minimum along an axis.

+
+
+ +
+
[SuppressMessage("ReSharper", "TooWideLocalVariableScope")]
+[SuppressMessage("ReSharper", "ParameterHidesMember")]
+public NDArray amin(int axis, bool keepdims = false, Type dtype = null)
+
+ +

Parameters

+
+
axis int
+

Axis or axes along which to operate.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
dtype Type
+

the type expected as a return, null will remain the same dtype.

+
+
+ +

Returns

+
+
NDArray
+

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ amin(Type) + +

+ +

Return the minimum of an array or minimum along an axis.

+
+
+ +
+
[SuppressMessage("ReSharper", "TooWideLocalVariableScope")]
+[SuppressMessage("ReSharper", "ParameterHidesMember")]
+public NDArray amin(Type dtype = null)
+
+ +

Parameters

+
+
dtype Type
+

the type expected as a return, null will remain the same dtype.

+
+
+ +

Returns

+
+
NDArray
+

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ amin<T>() + +

+ +

Return the minimum of an array or minimum along an axis.

+
+
+ +
+
public T amin<T>() where T : unmanaged
+
+ + +

Returns

+
+
T
+

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ +

Type Parameters

+
+
T
+

The expected return type, cast will be performed if necessary.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ argmax() + +

+ +

Returns the indices of the maximum values along an axis.

+
+
+ +
+
public int argmax()
+
+ + +

Returns

+
+
int
+

The index of the maximal value in the array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ argmax(int) + +

+ +

Returns the indices of the maximum values along an axis.

+
+
+ +
+
public int argmax(int axis)
+
+ +

Parameters

+
+
axis int
+
+
+ +

Returns

+
+
int
+

Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ argmin() + +

+ +

Returns the indices of the minimum values along an axis.

+
+
+ +
+
public int argmin()
+
+ + +

Returns

+
+
int
+

The index of the minimum value in the array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ argmin(int) + +

+ +

Returns the indices of the minimum values along an axis.

+
+
+ +
+
public int argmin(int axis)
+
+ +

Parameters

+
+
axis int
+
+
+ +

Returns

+
+
int
+

Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ argsort<T>(int) + +

+ +

Returns the indices that would sort an array.

+

Perform an indirect sort along the given axis using the algorithm specified by the kind keyword.It returns an array of indices of the same shape as a that index data along the given axis in sorted order.

+
+
+ +
+
public NDArray argsort<T>(int axis = -1)
+
+ +

Parameters

+
+
axis int
+
+
+ +

Returns

+
+
NDArray
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ array_equal(NDArray) + +

+ +

True if two arrays have the same shape and elements, False otherwise.

+
+
+ +
+
public bool array_equal(NDArray rhs)
+
+ +

Parameters

+
+
rhs NDArray
+

Input array.

+
+
+ +

Returns

+
+
bool
+

Returns True if the arrays are equal.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ astype(NPTypeCode, bool) + +

+ +

Copy of the array, cast to a specified type.

+
+
+ +
+
public NDArray astype(NPTypeCode typeCode, bool copy = true)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+
+
copy bool
+

By default, astype always returns a newly allocated array. If this is set to false, the input internal array is replaced instead of returning a new NDArray with the casted data.

+
+
+ +

Returns

+
+
NDArray
+

An NDArray of given dtype.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ astype(Type, bool) + +

+ +

Copy of the array, cast to a specified type.

+
+
+ +
+
[SuppressMessage("ReSharper", "ParameterHidesMember")]
+public NDArray astype(Type dtype, bool copy = true)
+
+ +

Parameters

+
+
dtype Type
+

The dtype to cast this array.

+
+
copy bool
+

By default, astype always returns a newly allocated array. If this is set to false, the input internal array is replaced instead of returning a new NDArray with the casted data.

+
+
+ +

Returns

+
+
NDArray
+

An NDArray of given dtype.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ convolve(NDArray, string) + +

+ +

Returns the discrete, linear convolution of two one-dimensional sequences.

+

The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal[1]. In probability theory, the sum of two independent random variables is distributed according to the convolution of their individual distributions.

+

If v is longer than a, the arrays are swapped before computation.

+
+
+ +
+
public NDArray convolve(NDArray rhs, string mode = "full")
+
+ +

Parameters

+
+
rhs NDArray
+
+
mode string
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ copy(char) + +

+ +

Return a copy of the array.

+
+
+ +
+
public NDArray copy(char order = 'C')
+
+ +

Parameters

+
+
order char
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ cumsum(int?, Type) + +

+ +

Return the cumulative sum of the elements along a given axis.

+
+
+ +
+
public NDArray cumsum(int? axis = null, Type dtype = null)
+
+ +

Parameters

+
+
axis int?
+

Axis along which the cumulative sum is computed. The default (-1) is to compute the cumsum over the flattened array.

+
+
dtype Type
+

Type of the returned array and of the accumulator in which the elements are summed. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.

+
+
+ +

Returns

+
+
NDArray
+

A new array holding the result is returned unless out is specified, in which case a reference to out is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ delete(IEnumerable) + +

+ +
+
+ +
+
public NDArray delete(IEnumerable delete)
+
+ +

Parameters

+
+
delete IEnumerable
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ dot(in NDArray) + +

+ +

Dot product of two arrays. See remarks.

+
+
+ +
+
public NDArray dot(in NDArray b)
+
+ +

Parameters

+
+
b NDArray
+

Rhs, Second argument.

+
+
+ +

Returns

+
+
NDArray
+

Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If out is given, then it is returned.

+
+
+ + + + + + + +

Remarks

+

https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html
+Specifically,
+- If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).
+- If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.
+- If either a or b is 0-D(scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a* b is preferred.
+- If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.
+- If a is an N-D array and b is an M-D array(where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b:
+dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])

+
+ + + + + + +

+ dstack(params NDArray[]) + +

+ +

Stack arrays in sequence depth wise (along third axis). +This is equivalent to concatenation along the third axis after 2-D arrays of shape(M, N) have been reshaped to(M, N,1) and 1-D arrays of shape(N,) have been reshaped to(1, N,1). +Rebuilds arrays divided by dsplit. +This function makes most sense for arrays with up to 3 dimensions.For instance, for pixel-data with a height(first axis), width(second axis), and r/g/b channels(third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations.

+
+
+ +
+
public NDArray dstack(params NDArray[] tup)
+
+ +

Parameters

+
+
tup NDArray[]
+

The arrays must have the same shape along all but the third axis. 1-D or 2-D arrays must have the same shape.

+
+
+ +

Returns

+
+
NDArray
+

The array formed by stacking the given arrays, will be at least 3-D.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ flatten(bool) + +

+ +

Return a copy of the array collapsed into one dimension.

+
+
+ +
+
public NDArray flatten(bool clone)
+
+ +

Parameters

+
+
clone bool
+

Should the data be cloned, true by default.

+
+
+ +

Returns

+
+
NDArray
+

A copy of the input array, flattened to one dimension.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ flatten(char) + +

+ +

Return a copy of the array collapsed into one dimension.

+
+
+ +
+
public NDArray flatten(char order = 'C')
+
+ +

Parameters

+
+
order char
+
+
+ +

Returns

+
+
NDArray
+

A copy of the input array, flattened to one dimension.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ hstack(params NDArray[]) + +

+ +

Stack arrays in sequence horizontally (column wise). +This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis.Rebuilds arrays divided by hsplit. +This function makes most sense for arrays with up to 3 dimensions.For instance, for pixel-data with a height(first axis), width(second axis), and r/g/b channels(third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations.

+
+
+ +
+
public NDArray hstack(params NDArray[] tup)
+
+ +

Parameters

+
+
tup NDArray[]
+

The arrays must have the same shape along all but the second axis, except 1-D arrays which can be any length.

+
+
+ +

Returns

+
+
NDArray
+

The array formed by stacking the given arrays.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ inv() + +

+ +
+
+ +
+
public NDArray inv()
+
+ + +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ itemset(Shape, ValueType) + +

+ +

Insert scalar into an array (scalar is cast to array’s dtype, if possible)

+
+
+ +
+
public void itemset(Shape shape, ValueType val)
+
+ +

Parameters

+
+
shape Shape
+
+
val ValueType
+
+
+ + + + + + + + +

Remarks

+ + + + + + + +

+ itemset(ref Shape, ValueType) + +

+ +

Insert scalar into an array (scalar is cast to array’s dtype, if possible)

+
+
+ +
+
public void itemset(ref Shape shape, ValueType val)
+
+ +

Parameters

+
+
shape Shape
+
+
val ValueType
+
+
+ + + + + + + + +

Remarks

+ + + + + + + +

+ itemset(int[], ValueType) + +

+ +

Insert scalar into an array (scalar is cast to array’s dtype, if possible)

+
+
+ +
+
public void itemset(int[] shape, ValueType val)
+
+ +

Parameters

+
+
shape int[]
+
+
val ValueType
+
+
+ + + + + + + + +

Remarks

+ + + + + + + +

+ itemset<T>(int[], T) + +

+ +

Insert scalar into an array (scalar is cast to array’s dtype, if possible)

+
+
+ +
+
public void itemset<T>(int[] shape, T val) where T : unmanaged
+
+ +

Parameters

+
+
shape int[]
+
+
val T
+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ lstqr(NDArray, double) + +

+ +

Least Square method

+

Determines NDArray X which reduces least square error of Linear System A * X = B. +This NDArray is equal to A.

+
+
+ +
+
public NDArray lstqr(NDArray nDArrayB, double rcon = 0.0001)
+
+ +

Parameters

+
+
nDArrayB NDArray
+

Result NDArray B

+
+
rcon double
+
+
+ +

Returns

+
+
NDArray
+

NArray X

+
+
+ + + + + + + + + + + + + +

+ matrix_power(int) + +

+ +
+
+ +
+
public NDArray matrix_power(int power)
+
+ +

Parameters

+
+
power int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ max(int, bool, Type) + +

+ +

Return the maximum of an array or maximum along an axis.

+
+
+ +
+
[SuppressMessage("ReSharper", "TooWideLocalVariableScope")]
+[SuppressMessage("ReSharper", "ParameterHidesMember")]
+public NDArray max(int axis, bool keepdims = false, Type dtype = null)
+
+ +

Parameters

+
+
axis int
+

Axis or axes along which to operate.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
dtype Type
+

the type expected as a return, null will remain the same dtype.

+
+
+ +

Returns

+
+
NDArray
+

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ max(Type) + +

+ +

Return the maximum of an array or maximum along an axis.

+
+
+ +
+
[SuppressMessage("ReSharper", "TooWideLocalVariableScope")]
+[SuppressMessage("ReSharper", "ParameterHidesMember")]
+public NDArray max(Type dtype = null)
+
+ +

Parameters

+
+
dtype Type
+

the type expected as a return, null will remain the same dtype.

+
+
+ +

Returns

+
+
NDArray
+

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ max<T>() + +

+ +

Return the maximum of an array or maximum along an axis.

+
+
+ +
+
public T max<T>() where T : unmanaged
+
+ + +

Returns

+
+
T
+

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ +

Type Parameters

+
+
T
+

The expected return type, cast will be performed if necessary.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ mean() + +

+ +

Compute the arithmetic mean along the specified axis. +Returns the average of the array elements. +The average is taken over the flattened array by default, otherwise over the specified axis. +float64 intermediate and return values are used for integer inputs.

+
+
+ +
+
public NDArray mean()
+
+ + +

Returns

+
+
NDArray
+

returns a new array containing the mean values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ mean(int) + +

+ +

Compute the arithmetic mean along the specified axis. +Returns the average of the array elements. +The average is taken over the flattened array by default, otherwise over the specified axis. +float64 intermediate and return values are used for integer inputs.

+
+
+ +
+
public NDArray mean(int axis)
+
+ +

Parameters

+
+
axis int
+

Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the mean values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ mean(int, NPTypeCode, bool) + +

+ +

Compute the arithmetic mean along the specified axis. +Returns the average of the array elements. +The average is taken over the flattened array by default, otherwise over the specified axis. +float64 intermediate and return values are used for integer inputs.

+
+
+ +
+
public NDArray mean(int axis, NPTypeCode type, bool keepdims = false)
+
+ +

Parameters

+
+
axis int
+

Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

+
+
type NPTypeCode
+

Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. +If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the mean values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ mean(int, bool) + +

+ +

Compute the arithmetic mean along the specified axis. +Returns the average of the array elements. +The average is taken over the flattened array by default, otherwise over the specified axis. +float64 intermediate and return values are used for integer inputs.

+
+
+ +
+
public NDArray mean(int axis, bool keepdims)
+
+ +

Parameters

+
+
axis int
+

Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. +If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the mean values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + + + + + + + +

+ mean(int, Type, bool) + +

+ +

Compute the arithmetic mean along the specified axis. +Returns the average of the array elements. +The average is taken over the flattened array by default, otherwise over the specified axis. +float64 intermediate and return values are used for integer inputs.

+
+
+ +
+
public NDArray mean(int axis, Type type, bool keepdims = false)
+
+ +

Parameters

+
+
axis int
+

Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

+
+
type Type
+

Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. +If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the mean values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ mgrid(NDArray) + +

+ +

nd_grid instance which returns a dense multi-dimensional “meshgrid”. +An instance of numpy.lib.index_tricks.nd_grid which returns an dense (or fleshed out) mesh-grid when indexed, so that each returned argument has the same shape. +The dimensions and number of the output arrays are equal to the number of indexing dimensions.If the step length is not a complex number, then the stop is not inclusive.

+
+
+ +
+
public (NDArray, NDArray) mgrid(NDArray rhs)
+
+ +

Parameters

+
+
rhs NDArray
+
+
+ +

Returns

+
+
(NDArray Lhs, NDArray Rhs)
+

mesh-grid ndarrays all of the same dimensions

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ min(int, bool, Type) + +

+ +

Return the minimum of an array or minimum along an axis.

+
+
+ +
+
[SuppressMessage("ReSharper", "TooWideLocalVariableScope")]
+[SuppressMessage("ReSharper", "ParameterHidesMember")]
+public NDArray min(int axis, bool keepdims = false, Type dtype = null)
+
+ +

Parameters

+
+
axis int
+

Axis or axes along which to operate.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
dtype Type
+

the type expected as a return, null will remain the same dtype.

+
+
+ +

Returns

+
+
NDArray
+

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ min(Type) + +

+ +

Return the minimum of an array or minimum along an axis.

+
+
+ +
+
[SuppressMessage("ReSharper", "TooWideLocalVariableScope")]
+[SuppressMessage("ReSharper", "ParameterHidesMember")]
+public NDArray min(Type dtype = null)
+
+ +

Parameters

+
+
dtype Type
+

the type expected as a return, null will remain the same dtype.

+
+
+ +

Returns

+
+
NDArray
+

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ min<T>() + +

+ +

Return the minimum of an array or minimum along an axis.

+
+
+ +
+
public T min<T>() where T : unmanaged
+
+ + +

Returns

+
+
T
+

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ +

Type Parameters

+
+
T
+

The expected return type, cast will be performed if necessary.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ multi_dot(params NDArray[]) + +

+ +
+
+ +
+
public NDArray multi_dot(params NDArray[] np2Multi)
+
+ +

Parameters

+
+
np2Multi NDArray[]
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ negate() + +

+ +

Negates all values by performing: -x

+
+
+ +
+
public NDArray negate()
+
+ + +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ negative() + +

+ +

Negates all positive values.

+
+
+ +
+
public NDArray negative()
+
+ + +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ positive() + +

+ +

Positives all negative values.

+
+
+ +
+
public NDArray positive()
+
+ + +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ prod(int?, Type, bool) + +

+ +

Return the product of array elements over a given axis.

+
+
+ +
+
public NDArray prod(int? axis = null, Type dtype = null, bool keepdims = false)
+
+ +

Parameters

+
+
axis int?
+

Axis or axes along which a product is performed. The default, axis=None, will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis.

+
+
dtype Type
+

The type of the returned array, as well as of the accumulator in which the elements are multiplied. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
+ +

Returns

+
+
NDArray
+

An array shaped as a but with the specified axis removed.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ qr() + +

+ +
+
+ +
+
public (NDArray, NDArray) qr()
+
+ + +

Returns

+
+
(NDArray Lhs, NDArray Rhs)
+
+
+ + + + + + + + + + + + + +

+ ravel() + +

+ +

Return a contiguous flattened array. A 1-D array, containing the elements of the input, is returned

+
+
+ +
+
public NDArray ravel()
+
+ + +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ reshape(Shape) + +

+ +

Gives a new shape to an array without changing its data.

+
+
+ +
+
public NDArray reshape(Shape newShape)
+
+ +

Parameters

+
+
newShape Shape
+

The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

+
+
+ +

Returns

+
+
NDArray
+

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ reshape(ref Shape) + +

+ +

Gives a new shape to an array without changing its data.

+
+
+ +
+
public NDArray reshape(ref Shape newShape)
+
+ +

Parameters

+
+
newShape Shape
+

The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

+
+
+ +

Returns

+
+
NDArray
+

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ reshape(params int[]) + +

+ +

Gives a new shape to an array without changing its data.

+
+
+ +
+
[SuppressMessage("ReSharper", "ParameterHidesMember")]
+public NDArray reshape(params int[] shape)
+
+ +

Parameters

+
+
shape int[]
+

The new shape should be compatible with the original shape. If an integer, then the result will be a +1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array +and remaining dimensions.

+
+
+ +

Returns

+
+
NDArray
+

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the +memory layout (C- or Fortran- contiguous) of the returned array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ reshape_unsafe(Shape) + +

+ +

Gives a new shape to an array without changing its data.

+
+
+ +
+
public NDArray reshape_unsafe(Shape newshape)
+
+ +

Parameters

+
+
newshape Shape
+

The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

+
+
+ +

Returns

+
+
NDArray
+

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ reshape_unsafe(ref Shape) + +

+ +

Gives a new shape to an array without changing its data.

+
+
+ +
+
public NDArray reshape_unsafe(ref Shape newshape)
+
+ +

Parameters

+
+
newshape Shape
+

The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

+
+
+ +

Returns

+
+
NDArray
+

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ reshape_unsafe(params int[]) + +

+ +

Gives a new shape to an array without changing its data.

+
+
+ +
+
[SuppressMessage("ReSharper", "ParameterHidesMember")]
+public NDArray reshape_unsafe(params int[] shape)
+
+ +

Parameters

+
+
shape int[]
+

The new shape should be compatible with the original shape. If an integer, then the result will be a +1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array +and remaining dimensions.

+
+
+ +

Returns

+
+
NDArray
+

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the +memory layout (C- or Fortran- contiguous) of the returned array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ roll(int) + +

+ +
+
+ +
+
public NDArray roll(int shift)
+
+ +

Parameters

+
+
shift int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ roll(int, int) + +

+ +

Roll array elements along a given axis.

+

Elements that roll beyond the last position are re-introduced at the first.

+
+
+ +
+
public NDArray roll(int shift, int axis)
+
+ +

Parameters

+
+
shift int
+
+
axis int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ std(bool, int?, NPTypeCode?) + +

+ +

Compute the standard deviation along the specified axis. +Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public NDArray std(bool keepdims = false, int? ddof = null, NPTypeCode? dtype = null)
+
+ +

Parameters

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
dtype NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the std values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ std(int, bool, int?, NPTypeCode?) + +

+ +

Compute the standard deviation along the specified axis. +Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public NDArray std(int axis, bool keepdims = false, int? ddof = null, NPTypeCode? dtype = null)
+
+ +

Parameters

+
+
axis int
+

Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
dtype NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the std values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sum() + +

+ +

Sum of array elements into a scalar.

+
+
+ +
+
public NDArray sum()
+
+ + +

Returns

+
+
NDArray
+

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sum(int) + +

+ +

Sum of array elements over a given axis.

+
+
+ +
+
public NDArray sum(int axis)
+
+ +

Parameters

+
+
axis int
+

Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.

+
+
+ +

Returns

+
+
NDArray
+

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sum(int, bool, NPTypeCode?) + +

+ +

Sum of array elements over a given axis.

+
+
+ +
+
public NDArray sum(int axis, bool keepdims, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
axis int
+

Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

+
+
typeCode NPTypeCode?
+

The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

+
+
+ +

Returns

+
+
NDArray
+

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sum(int, bool, Type) + +

+ +

Sum of array elements over a given axis.

+
+
+ +
+
public NDArray sum(int axis, bool keepdims, Type dtype)
+
+ +

Parameters

+
+
axis int
+

Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

+
+
dtype Type
+

The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

+
+
+ +

Returns

+
+
NDArray
+

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ svd() + +

+ +
+
+ +
+
public (NDArray, NDArray, NDArray) svd()
+
+ + +

Returns

+
+
(NDArray, NDArray, NDArray)
+
+
+ + + + + + + + + + + + + +

+ swapaxes(int, int) + +

+ +

Interchange two axes of an array.

+
+
+ +
+
public NDArray swapaxes(int axis1, int axis2)
+
+ +

Parameters

+
+
axis1 int
+

First axis.

+
+
axis2 int
+

Second axis.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ tofile(string) + +

+ +

Write array to a file as text or binary (default).
+Data is always written in ‘C’ order, independent of the order of a.
The data produced by this method can be recovered using the function fromfile().

+
+
+ +
+
public void tofile(string fid)
+
+ +

Parameters

+
+
fid string
+

An open file object, or a string containing a filename.

+
+
+ + + + + + + + +

Remarks

+ + + + + + + +

+ transpose(int[]) + +

+ +

Permute the dimensions of an array.

+
+
+ +
+
public NDArray transpose(int[] premute = null)
+
+ +

Parameters

+
+
premute int[]
+

By default, reverse the dimensions, otherwise permute the axes according to the values given.

+
+
+ +

Returns

+
+
NDArray
+

a with its axes permuted. A view is returned whenever possible.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ unique() + +

+ +

Find the unique elements of an array.

+

Returns the sorted unique elements of an array.There are three optional outputs in addition to the unique elements:

+
    +
  • the indices of the input array that give the unique values
  • +
  • the indices of the unique array that reconstruct the input array
  • +
  • the number of times each unique value comes up in the input array
  • +
+
+
+ +
+
public NDArray unique()
+
+ + +

Returns

+
+
NDArray
+

The sorted unique values.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ unique<T>() + +

+ +

Find the unique elements of an array.

+

Returns the sorted unique elements of an array.There are three optional outputs in addition to the unique elements:

+
    +
  • the indices of the input array that give the unique values
  • +
  • the indices of the unique array that reconstruct the input array
  • +
  • the number of times each unique value comes up in the input array
  • +
+
+
+ +
+
protected NDArray unique<T>() where T : unmanaged
+
+ + +

Returns

+
+
NDArray
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ var(bool, int?, NPTypeCode?) + +

+ +

Compute the standard deviation along the specified axis. +Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public NDArray var(bool keepdims = false, int? ddof = null, NPTypeCode? dtype = null)
+
+ +

Parameters

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
dtype NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the std values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ var(int, bool, int?, NPTypeCode?) + +

+ +

Compute the standard deviation along the specified axis. +Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public NDArray var(int axis, bool keepdims = false, int? ddof = null, NPTypeCode? dtype = null)
+
+ +

Parameters

+
+
axis int
+

Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
dtype NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the std values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ view(Type) + +

+ +

New view of array with the same data.

+
+
+ +
+
public NDArray view(Type dtype = null)
+
+ +

Parameters

+
+
dtype Type
+

Data-type descriptor of the returned view, e.g., float32 or int16. The default, None, results in the view having the same data-type as a. +This argument can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the type parameter).

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ view<T>() + +

+ +

New view of array with the same data.

+
+
+ +
+
public NDArray<T> view<T>() where T : unmanaged
+
+ + +

Returns

+
+
NDArray<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ vstack(params NDArray[]) + +

+ +

Stack arrays in sequence vertically (row wise).
+This is equivalent to concatenation along the first axis after 1-D arrays of shape(N,) have been reshaped to(1, N). Rebuilds arrays divided by vsplit.

+
+
+ +
+
public NDArray vstack(params NDArray[] tup)
+
+ +

Parameters

+
+
tup NDArray[]
+

The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length.

+
+
+ +

Returns

+
+
NDArray
+

https://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html

+
+
+ + + + + + + + + + + +

Operators +

+ + + + +

+ operator +(NDArray, NDArray) + +

+ +
+
+ +
+
public static NDArray operator +(NDArray x, NDArray y)
+
+ +

Parameters

+
+
x NDArray
+
+
y NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(NDArray, bool) + +

+ +
+
+ +
+
public static NDArray operator +(NDArray left, bool right)
+
+ +

Parameters

+
+
left NDArray
+
+
right bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(NDArray, byte) + +

+ +
+
+ +
+
public static NDArray operator +(NDArray left, byte right)
+
+ +

Parameters

+
+
left NDArray
+
+
right byte
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(NDArray, char) + +

+ +
+
+ +
+
public static NDArray operator +(NDArray left, char right)
+
+ +

Parameters

+
+
left NDArray
+
+
right char
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(NDArray, decimal) + +

+ +
+
+ +
+
public static NDArray operator +(NDArray left, decimal right)
+
+ +

Parameters

+
+
left NDArray
+
+
right decimal
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(NDArray, double) + +

+ +
+
+ +
+
public static NDArray operator +(NDArray left, double right)
+
+ +

Parameters

+
+
left NDArray
+
+
right double
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(NDArray, short) + +

+ +
+
+ +
+
public static NDArray operator +(NDArray left, short right)
+
+ +

Parameters

+
+
left NDArray
+
+
right short
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(NDArray, int) + +

+ +
+
+ +
+
public static NDArray operator +(NDArray left, int right)
+
+ +

Parameters

+
+
left NDArray
+
+
right int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(NDArray, long) + +

+ +
+
+ +
+
public static NDArray operator +(NDArray left, long right)
+
+ +

Parameters

+
+
left NDArray
+
+
right long
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(NDArray, float) + +

+ +
+
+ +
+
public static NDArray operator +(NDArray left, float right)
+
+ +

Parameters

+
+
left NDArray
+
+
right float
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(NDArray, ushort) + +

+ +
+
+ +
+
public static NDArray operator +(NDArray left, ushort right)
+
+ +

Parameters

+
+
left NDArray
+
+
right ushort
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(NDArray, uint) + +

+ +
+
+ +
+
public static NDArray operator +(NDArray left, uint right)
+
+ +

Parameters

+
+
left NDArray
+
+
right uint
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(NDArray, ulong) + +

+ +
+
+ +
+
public static NDArray operator +(NDArray left, ulong right)
+
+ +

Parameters

+
+
left NDArray
+
+
right ulong
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(bool, NDArray) + +

+ +
+
+ +
+
public static NDArray operator +(bool left, NDArray right)
+
+ +

Parameters

+
+
left bool
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(byte, NDArray) + +

+ +
+
+ +
+
public static NDArray operator +(byte left, NDArray right)
+
+ +

Parameters

+
+
left byte
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(char, NDArray) + +

+ +
+
+ +
+
public static NDArray operator +(char left, NDArray right)
+
+ +

Parameters

+
+
left char
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(decimal, NDArray) + +

+ +
+
+ +
+
public static NDArray operator +(decimal left, NDArray right)
+
+ +

Parameters

+
+
left decimal
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(double, NDArray) + +

+ +
+
+ +
+
public static NDArray operator +(double left, NDArray right)
+
+ +

Parameters

+
+
left double
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(short, NDArray) + +

+ +
+
+ +
+
public static NDArray operator +(short left, NDArray right)
+
+ +

Parameters

+
+
left short
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(int, NDArray) + +

+ +
+
+ +
+
public static NDArray operator +(int left, NDArray right)
+
+ +

Parameters

+
+
left int
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(long, NDArray) + +

+ +
+
+ +
+
public static NDArray operator +(long left, NDArray right)
+
+ +

Parameters

+
+
left long
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(float, NDArray) + +

+ +
+
+ +
+
public static NDArray operator +(float left, NDArray right)
+
+ +

Parameters

+
+
left float
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(ushort, NDArray) + +

+ +
+
+ +
+
public static NDArray operator +(ushort left, NDArray right)
+
+ +

Parameters

+
+
left ushort
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(uint, NDArray) + +

+ +
+
+ +
+
public static NDArray operator +(uint left, NDArray right)
+
+ +

Parameters

+
+
left uint
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(ulong, NDArray) + +

+ +
+
+ +
+
public static NDArray operator +(ulong left, NDArray right)
+
+ +

Parameters

+
+
left ulong
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator &(NDArray, NDArray) + +

+ +
+
+ +
+
public static NDArray<bool> operator &(NDArray lhs, NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ operator &(NDArray, byte) + +

+ +
+
+ +
+
public static NDArray<byte> operator &(NDArray lhs, byte rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs byte
+
+
+ +

Returns

+
+
NDArray<byte>
+
+
+ + + + + + + + + + + + + +

+ operator |(NDArray, NDArray) + +

+ +
+
+ +
+
public static NDArray operator |(NDArray np_, NDArray obj_)
+
+ +

Parameters

+
+
np_ NDArray
+
+
obj_ NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(NDArray, NDArray) + +

+ +
+
+ +
+
public static NDArray operator /(NDArray x, NDArray y)
+
+ +

Parameters

+
+
x NDArray
+
+
y NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(NDArray, bool) + +

+ +
+
+ +
+
public static NDArray operator /(NDArray left, bool right)
+
+ +

Parameters

+
+
left NDArray
+
+
right bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(NDArray, byte) + +

+ +
+
+ +
+
public static NDArray operator /(NDArray left, byte right)
+
+ +

Parameters

+
+
left NDArray
+
+
right byte
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(NDArray, char) + +

+ +
+
+ +
+
public static NDArray operator /(NDArray left, char right)
+
+ +

Parameters

+
+
left NDArray
+
+
right char
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(NDArray, decimal) + +

+ +
+
+ +
+
public static NDArray operator /(NDArray left, decimal right)
+
+ +

Parameters

+
+
left NDArray
+
+
right decimal
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(NDArray, double) + +

+ +
+
+ +
+
public static NDArray operator /(NDArray left, double right)
+
+ +

Parameters

+
+
left NDArray
+
+
right double
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(NDArray, short) + +

+ +
+
+ +
+
public static NDArray operator /(NDArray left, short right)
+
+ +

Parameters

+
+
left NDArray
+
+
right short
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(NDArray, int) + +

+ +
+
+ +
+
public static NDArray operator /(NDArray left, int right)
+
+ +

Parameters

+
+
left NDArray
+
+
right int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(NDArray, long) + +

+ +
+
+ +
+
public static NDArray operator /(NDArray left, long right)
+
+ +

Parameters

+
+
left NDArray
+
+
right long
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(NDArray, float) + +

+ +
+
+ +
+
public static NDArray operator /(NDArray left, float right)
+
+ +

Parameters

+
+
left NDArray
+
+
right float
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(NDArray, ushort) + +

+ +
+
+ +
+
public static NDArray operator /(NDArray left, ushort right)
+
+ +

Parameters

+
+
left NDArray
+
+
right ushort
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(NDArray, uint) + +

+ +
+
+ +
+
public static NDArray operator /(NDArray left, uint right)
+
+ +

Parameters

+
+
left NDArray
+
+
right uint
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(NDArray, ulong) + +

+ +
+
+ +
+
public static NDArray operator /(NDArray left, ulong right)
+
+ +

Parameters

+
+
left NDArray
+
+
right ulong
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(bool, NDArray) + +

+ +
+
+ +
+
public static NDArray operator /(bool left, NDArray right)
+
+ +

Parameters

+
+
left bool
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(byte, NDArray) + +

+ +
+
+ +
+
public static NDArray operator /(byte left, NDArray right)
+
+ +

Parameters

+
+
left byte
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(char, NDArray) + +

+ +
+
+ +
+
public static NDArray operator /(char left, NDArray right)
+
+ +

Parameters

+
+
left char
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(decimal, NDArray) + +

+ +
+
+ +
+
public static NDArray operator /(decimal left, NDArray right)
+
+ +

Parameters

+
+
left decimal
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(double, NDArray) + +

+ +
+
+ +
+
public static NDArray operator /(double left, NDArray right)
+
+ +

Parameters

+
+
left double
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(short, NDArray) + +

+ +
+
+ +
+
public static NDArray operator /(short left, NDArray right)
+
+ +

Parameters

+
+
left short
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(int, NDArray) + +

+ +
+
+ +
+
public static NDArray operator /(int left, NDArray right)
+
+ +

Parameters

+
+
left int
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(long, NDArray) + +

+ +
+
+ +
+
public static NDArray operator /(long left, NDArray right)
+
+ +

Parameters

+
+
left long
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(float, NDArray) + +

+ +
+
+ +
+
public static NDArray operator /(float left, NDArray right)
+
+ +

Parameters

+
+
left float
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(ushort, NDArray) + +

+ +
+
+ +
+
public static NDArray operator /(ushort left, NDArray right)
+
+ +

Parameters

+
+
left ushort
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(uint, NDArray) + +

+ +
+
+ +
+
public static NDArray operator /(uint left, NDArray right)
+
+ +

Parameters

+
+
left uint
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator /(ulong, NDArray) + +

+ +
+
+ +
+
public static NDArray operator /(ulong left, NDArray right)
+
+ +

Parameters

+
+
left ulong
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator ==(NDArray, object) + +

+ +
+
+ +
+
public static NDArray<bool> operator ==(NDArray left, object right)
+
+ +

Parameters

+
+
left NDArray
+
+
right object
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ explicit operator Array(NDArray) + +

+ +
+
+ +
+
public static explicit operator Array(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
Array
+
+
+ + + + + + + + + + + + + +

+ explicit operator string(NDArray) + +

+ +
+
+ +
+
public static explicit operator string(NDArray d)
+
+ +

Parameters

+
+
d NDArray
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ explicit operator ushort(NDArray) + +

+ +
+
+ +
+
public static explicit operator ushort(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ explicit operator NDArray(ushort) + +

+ +
+
+ +
+
public static explicit operator NDArray(ushort d)
+
+ +

Parameters

+
+
d ushort
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator >(NDArray, int) + +

+ +
+
+ +
+
public static NDArray<bool> operator >(NDArray np, int obj)
+
+ +

Parameters

+
+
np NDArray
+
+
obj int
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ operator >(NDArray, object) + +

+ +
+
+ +
+
public static NDArray<bool> operator >(NDArray np, object obj)
+
+ +

Parameters

+
+
np NDArray
+
+
obj object
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ implicit operator bool(NDArray) + +

+ +
+
+ +
+
public static implicit operator bool(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ implicit operator char(NDArray) + +

+ +
+
+ +
+
public static implicit operator char(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ implicit operator decimal(NDArray) + +

+ +
+
+ +
+
public static implicit operator decimal(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ implicit operator double(NDArray) + +

+ +
+
+ +
+
public static implicit operator double(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ implicit operator short(NDArray) + +

+ +
+
+ +
+
public static implicit operator short(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ implicit operator int(NDArray) + +

+ +
+
+ +
+
public static implicit operator int(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ implicit operator long(NDArray) + +

+ +
+
+ +
+
public static implicit operator long(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ implicit operator float(NDArray) + +

+ +
+
+ +
+
public static implicit operator float(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ implicit operator uint(NDArray) + +

+ +
+
+ +
+
public static implicit operator uint(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ implicit operator ulong(NDArray) + +

+ +
+
+ +
+
public static implicit operator ulong(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ implicit operator NDArray(Array) + +

+ +
+
+ +
+
public static implicit operator NDArray(Array array)
+
+ +

Parameters

+
+
array Array
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ implicit operator NDArray(bool) + +

+ +
+
+ +
+
public static implicit operator NDArray(bool d)
+
+ +

Parameters

+
+
d bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ implicit operator NDArray(char) + +

+ +
+
+ +
+
public static implicit operator NDArray(char d)
+
+ +

Parameters

+
+
d char
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ implicit operator NDArray(decimal) + +

+ +
+
+ +
+
public static implicit operator NDArray(decimal d)
+
+ +

Parameters

+
+
d decimal
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ implicit operator NDArray(double) + +

+ +
+
+ +
+
public static implicit operator NDArray(double d)
+
+ +

Parameters

+
+
d double
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ implicit operator NDArray(short) + +

+ +
+
+ +
+
public static implicit operator NDArray(short d)
+
+ +

Parameters

+
+
d short
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ implicit operator NDArray(int) + +

+ +
+
+ +
+
public static implicit operator NDArray(int d)
+
+ +

Parameters

+
+
d int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ implicit operator NDArray(long) + +

+ +
+
+ +
+
public static implicit operator NDArray(long d)
+
+ +

Parameters

+
+
d long
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ implicit operator NDArray(Complex) + +

+ +
+
+ +
+
public static implicit operator NDArray(Complex d)
+
+ +

Parameters

+
+
d Complex
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ implicit operator NDArray(float) + +

+ +
+
+ +
+
public static implicit operator NDArray(float d)
+
+ +

Parameters

+
+
d float
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ implicit operator NDArray(string) + +

+ +
+
+ +
+
public static implicit operator NDArray(string str)
+
+ +

Parameters

+
+
str string
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ implicit operator NDArray(uint) + +

+ +
+
+ +
+
public static implicit operator NDArray(uint d)
+
+ +

Parameters

+
+
d uint
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ implicit operator NDArray(ulong) + +

+ +
+
+ +
+
public static implicit operator NDArray(ulong d)
+
+ +

Parameters

+
+
d ulong
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator !=(NDArray, object) + +

+ +
+
+ +
+
public static NDArray<bool> operator !=(NDArray np, object obj)
+
+ +

Parameters

+
+
np NDArray
+
+
obj object
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ operator <(NDArray, int) + +

+ +
+
+ +
+
public static NDArray<bool> operator <(NDArray np, int obj)
+
+ +

Parameters

+
+
np NDArray
+
+
obj int
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ operator <(NDArray, object) + +

+ +
+
+ +
+
public static NDArray<bool> operator <(NDArray np, object obj)
+
+ +

Parameters

+
+
np NDArray
+
+
obj object
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ operator !(NDArray) + +

+ +
+
+ +
+
public static NDArray<bool> operator !(NDArray self)
+
+ +

Parameters

+
+
self NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ operator %(NDArray, NDArray) + +

+ +
+
+ +
+
public static NDArray operator %(NDArray x, NDArray y)
+
+ +

Parameters

+
+
x NDArray
+
+
y NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(NDArray, bool) + +

+ +
+
+ +
+
public static NDArray operator %(NDArray left, bool right)
+
+ +

Parameters

+
+
left NDArray
+
+
right bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(NDArray, byte) + +

+ +
+
+ +
+
public static NDArray operator %(NDArray left, byte right)
+
+ +

Parameters

+
+
left NDArray
+
+
right byte
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(NDArray, char) + +

+ +
+
+ +
+
public static NDArray operator %(NDArray left, char right)
+
+ +

Parameters

+
+
left NDArray
+
+
right char
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(NDArray, decimal) + +

+ +
+
+ +
+
public static NDArray operator %(NDArray left, decimal right)
+
+ +

Parameters

+
+
left NDArray
+
+
right decimal
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(NDArray, double) + +

+ +
+
+ +
+
public static NDArray operator %(NDArray left, double right)
+
+ +

Parameters

+
+
left NDArray
+
+
right double
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(NDArray, short) + +

+ +
+
+ +
+
public static NDArray operator %(NDArray left, short right)
+
+ +

Parameters

+
+
left NDArray
+
+
right short
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(NDArray, int) + +

+ +
+
+ +
+
public static NDArray operator %(NDArray left, int right)
+
+ +

Parameters

+
+
left NDArray
+
+
right int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(NDArray, long) + +

+ +
+
+ +
+
public static NDArray operator %(NDArray left, long right)
+
+ +

Parameters

+
+
left NDArray
+
+
right long
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(NDArray, float) + +

+ +
+
+ +
+
public static NDArray operator %(NDArray left, float right)
+
+ +

Parameters

+
+
left NDArray
+
+
right float
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(NDArray, ushort) + +

+ +
+
+ +
+
public static NDArray operator %(NDArray left, ushort right)
+
+ +

Parameters

+
+
left NDArray
+
+
right ushort
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(NDArray, uint) + +

+ +
+
+ +
+
public static NDArray operator %(NDArray left, uint right)
+
+ +

Parameters

+
+
left NDArray
+
+
right uint
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(NDArray, ulong) + +

+ +
+
+ +
+
public static NDArray operator %(NDArray left, ulong right)
+
+ +

Parameters

+
+
left NDArray
+
+
right ulong
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(bool, NDArray) + +

+ +
+
+ +
+
public static NDArray operator %(bool left, NDArray right)
+
+ +

Parameters

+
+
left bool
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(byte, NDArray) + +

+ +
+
+ +
+
public static NDArray operator %(byte left, NDArray right)
+
+ +

Parameters

+
+
left byte
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(char, NDArray) + +

+ +
+
+ +
+
public static NDArray operator %(char left, NDArray right)
+
+ +

Parameters

+
+
left char
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(decimal, NDArray) + +

+ +
+
+ +
+
public static NDArray operator %(decimal left, NDArray right)
+
+ +

Parameters

+
+
left decimal
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(double, NDArray) + +

+ +
+
+ +
+
public static NDArray operator %(double left, NDArray right)
+
+ +

Parameters

+
+
left double
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(short, NDArray) + +

+ +
+
+ +
+
public static NDArray operator %(short left, NDArray right)
+
+ +

Parameters

+
+
left short
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(int, NDArray) + +

+ +
+
+ +
+
public static NDArray operator %(int left, NDArray right)
+
+ +

Parameters

+
+
left int
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(long, NDArray) + +

+ +
+
+ +
+
public static NDArray operator %(long left, NDArray right)
+
+ +

Parameters

+
+
left long
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(float, NDArray) + +

+ +
+
+ +
+
public static NDArray operator %(float left, NDArray right)
+
+ +

Parameters

+
+
left float
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(ushort, NDArray) + +

+ +
+
+ +
+
public static NDArray operator %(ushort left, NDArray right)
+
+ +

Parameters

+
+
left ushort
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(uint, NDArray) + +

+ +
+
+ +
+
public static NDArray operator %(uint left, NDArray right)
+
+ +

Parameters

+
+
left uint
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator %(ulong, NDArray) + +

+ +
+
+ +
+
public static NDArray operator %(ulong left, NDArray right)
+
+ +

Parameters

+
+
left ulong
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(NDArray, NDArray) + +

+ +
+
+ +
+
public static NDArray operator *(NDArray x, NDArray y)
+
+ +

Parameters

+
+
x NDArray
+
+
y NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(NDArray, bool) + +

+ +
+
+ +
+
public static NDArray operator *(NDArray left, bool right)
+
+ +

Parameters

+
+
left NDArray
+
+
right bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(NDArray, byte) + +

+ +
+
+ +
+
public static NDArray operator *(NDArray left, byte right)
+
+ +

Parameters

+
+
left NDArray
+
+
right byte
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(NDArray, char) + +

+ +
+
+ +
+
public static NDArray operator *(NDArray left, char right)
+
+ +

Parameters

+
+
left NDArray
+
+
right char
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(NDArray, decimal) + +

+ +
+
+ +
+
public static NDArray operator *(NDArray left, decimal right)
+
+ +

Parameters

+
+
left NDArray
+
+
right decimal
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(NDArray, double) + +

+ +
+
+ +
+
public static NDArray operator *(NDArray left, double right)
+
+ +

Parameters

+
+
left NDArray
+
+
right double
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(NDArray, short) + +

+ +
+
+ +
+
public static NDArray operator *(NDArray left, short right)
+
+ +

Parameters

+
+
left NDArray
+
+
right short
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(NDArray, int) + +

+ +
+
+ +
+
public static NDArray operator *(NDArray left, int right)
+
+ +

Parameters

+
+
left NDArray
+
+
right int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(NDArray, long) + +

+ +
+
+ +
+
public static NDArray operator *(NDArray left, long right)
+
+ +

Parameters

+
+
left NDArray
+
+
right long
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(NDArray, float) + +

+ +
+
+ +
+
public static NDArray operator *(NDArray left, float right)
+
+ +

Parameters

+
+
left NDArray
+
+
right float
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(NDArray, ushort) + +

+ +
+
+ +
+
public static NDArray operator *(NDArray left, ushort right)
+
+ +

Parameters

+
+
left NDArray
+
+
right ushort
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(NDArray, uint) + +

+ +
+
+ +
+
public static NDArray operator *(NDArray left, uint right)
+
+ +

Parameters

+
+
left NDArray
+
+
right uint
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(NDArray, ulong) + +

+ +
+
+ +
+
public static NDArray operator *(NDArray left, ulong right)
+
+ +

Parameters

+
+
left NDArray
+
+
right ulong
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(bool, NDArray) + +

+ +
+
+ +
+
public static NDArray operator *(bool left, NDArray right)
+
+ +

Parameters

+
+
left bool
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(byte, NDArray) + +

+ +
+
+ +
+
public static NDArray operator *(byte left, NDArray right)
+
+ +

Parameters

+
+
left byte
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(char, NDArray) + +

+ +
+
+ +
+
public static NDArray operator *(char left, NDArray right)
+
+ +

Parameters

+
+
left char
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(decimal, NDArray) + +

+ +
+
+ +
+
public static NDArray operator *(decimal left, NDArray right)
+
+ +

Parameters

+
+
left decimal
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(double, NDArray) + +

+ +
+
+ +
+
public static NDArray operator *(double left, NDArray right)
+
+ +

Parameters

+
+
left double
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(short, NDArray) + +

+ +
+
+ +
+
public static NDArray operator *(short left, NDArray right)
+
+ +

Parameters

+
+
left short
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(int, NDArray) + +

+ +
+
+ +
+
public static NDArray operator *(int left, NDArray right)
+
+ +

Parameters

+
+
left int
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(long, NDArray) + +

+ +
+
+ +
+
public static NDArray operator *(long left, NDArray right)
+
+ +

Parameters

+
+
left long
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(float, NDArray) + +

+ +
+
+ +
+
public static NDArray operator *(float left, NDArray right)
+
+ +

Parameters

+
+
left float
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(ushort, NDArray) + +

+ +
+
+ +
+
public static NDArray operator *(ushort left, NDArray right)
+
+ +

Parameters

+
+
left ushort
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(uint, NDArray) + +

+ +
+
+ +
+
public static NDArray operator *(uint left, NDArray right)
+
+ +

Parameters

+
+
left uint
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator *(ulong, NDArray) + +

+ +
+
+ +
+
public static NDArray operator *(ulong left, NDArray right)
+
+ +

Parameters

+
+
left ulong
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(NDArray, NDArray) + +

+ +
+
+ +
+
public static NDArray operator -(NDArray x, NDArray y)
+
+ +

Parameters

+
+
x NDArray
+
+
y NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(NDArray, bool) + +

+ +
+
+ +
+
public static NDArray operator -(NDArray left, bool right)
+
+ +

Parameters

+
+
left NDArray
+
+
right bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(NDArray, byte) + +

+ +
+
+ +
+
public static NDArray operator -(NDArray left, byte right)
+
+ +

Parameters

+
+
left NDArray
+
+
right byte
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(NDArray, char) + +

+ +
+
+ +
+
public static NDArray operator -(NDArray left, char right)
+
+ +

Parameters

+
+
left NDArray
+
+
right char
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(NDArray, decimal) + +

+ +
+
+ +
+
public static NDArray operator -(NDArray left, decimal right)
+
+ +

Parameters

+
+
left NDArray
+
+
right decimal
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(NDArray, double) + +

+ +
+
+ +
+
public static NDArray operator -(NDArray left, double right)
+
+ +

Parameters

+
+
left NDArray
+
+
right double
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(NDArray, short) + +

+ +
+
+ +
+
public static NDArray operator -(NDArray left, short right)
+
+ +

Parameters

+
+
left NDArray
+
+
right short
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(NDArray, int) + +

+ +
+
+ +
+
public static NDArray operator -(NDArray left, int right)
+
+ +

Parameters

+
+
left NDArray
+
+
right int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(NDArray, long) + +

+ +
+
+ +
+
public static NDArray operator -(NDArray left, long right)
+
+ +

Parameters

+
+
left NDArray
+
+
right long
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(NDArray, float) + +

+ +
+
+ +
+
public static NDArray operator -(NDArray left, float right)
+
+ +

Parameters

+
+
left NDArray
+
+
right float
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(NDArray, ushort) + +

+ +
+
+ +
+
public static NDArray operator -(NDArray left, ushort right)
+
+ +

Parameters

+
+
left NDArray
+
+
right ushort
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(NDArray, uint) + +

+ +
+
+ +
+
public static NDArray operator -(NDArray left, uint right)
+
+ +

Parameters

+
+
left NDArray
+
+
right uint
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(NDArray, ulong) + +

+ +
+
+ +
+
public static NDArray operator -(NDArray left, ulong right)
+
+ +

Parameters

+
+
left NDArray
+
+
right ulong
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(bool, NDArray) + +

+ +
+
+ +
+
public static NDArray operator -(bool left, NDArray right)
+
+ +

Parameters

+
+
left bool
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(byte, NDArray) + +

+ +
+
+ +
+
public static NDArray operator -(byte left, NDArray right)
+
+ +

Parameters

+
+
left byte
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(char, NDArray) + +

+ +
+
+ +
+
public static NDArray operator -(char left, NDArray right)
+
+ +

Parameters

+
+
left char
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(decimal, NDArray) + +

+ +
+
+ +
+
public static NDArray operator -(decimal left, NDArray right)
+
+ +

Parameters

+
+
left decimal
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(double, NDArray) + +

+ +
+
+ +
+
public static NDArray operator -(double left, NDArray right)
+
+ +

Parameters

+
+
left double
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(short, NDArray) + +

+ +
+
+ +
+
public static NDArray operator -(short left, NDArray right)
+
+ +

Parameters

+
+
left short
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(int, NDArray) + +

+ +
+
+ +
+
public static NDArray operator -(int left, NDArray right)
+
+ +

Parameters

+
+
left int
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(long, NDArray) + +

+ +
+
+ +
+
public static NDArray operator -(long left, NDArray right)
+
+ +

Parameters

+
+
left long
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(float, NDArray) + +

+ +
+
+ +
+
public static NDArray operator -(float left, NDArray right)
+
+ +

Parameters

+
+
left float
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(ushort, NDArray) + +

+ +
+
+ +
+
public static NDArray operator -(ushort left, NDArray right)
+
+ +

Parameters

+
+
left ushort
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(uint, NDArray) + +

+ +
+
+ +
+
public static NDArray operator -(uint left, NDArray right)
+
+ +

Parameters

+
+
left uint
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(ulong, NDArray) + +

+ +
+
+ +
+
public static NDArray operator -(ulong left, NDArray right)
+
+ +

Parameters

+
+
left ulong
+
+
right NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator -(NDArray) + +

+ +
+
+ +
+
public static NDArray operator -(NDArray x)
+
+ +

Parameters

+
+
x NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ operator +(NDArray) + +

+ +
+
+ +
+
public static NDArray operator +(NDArray x)
+
+ +

Parameters

+
+
x NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/api/NumSharp.NDArrayRandom.html b/docs/website/api/NumSharp.NDArrayRandom.html similarity index 100% rename from docs/api/NumSharp.NDArrayRandom.html rename to docs/website/api/NumSharp.NDArrayRandom.html diff --git a/docs/api/NumSharp.NDArrayRandom.yml b/docs/website/api/NumSharp.NDArrayRandom.yml similarity index 100% rename from docs/api/NumSharp.NDArrayRandom.yml rename to docs/website/api/NumSharp.NDArrayRandom.yml diff --git a/docs/api/NumSharp.NDArray_Legacy-1.html b/docs/website/api/NumSharp.NDArray_Legacy-1.html similarity index 100% rename from docs/api/NumSharp.NDArray_Legacy-1.html rename to docs/website/api/NumSharp.NDArray_Legacy-1.html diff --git a/docs/api/NumSharp.NDArray_Legacy-1.yml b/docs/website/api/NumSharp.NDArray_Legacy-1.yml similarity index 100% rename from docs/api/NumSharp.NDArray_Legacy-1.yml rename to docs/website/api/NumSharp.NDArray_Legacy-1.yml diff --git a/docs/website/api/NumSharp.NDIterator-1.html b/docs/website/api/NumSharp.NDIterator-1.html new file mode 100644 index 000000000..778d74a20 --- /dev/null +++ b/docs/website/api/NumSharp.NDIterator-1.html @@ -0,0 +1,1466 @@ + + + + + Class NDIterator<TOut> | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NDIterator<TOut> +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class NDIterator<TOut> : NDIterator, IEnumerable<TOut>, IEnumerable, IDisposable where TOut : unmanaged
+
+ + + +

Type Parameters

+
+
TOut
+
+
+ +
+
Inheritance
+
+ +
NDIterator<TOut>
+
+
+ +
+
Implements
+
+ + + + +
+
+ + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ NDIterator(IArraySlice, Shape, Shape?, bool) + +

+ +
+
+ +
+
public NDIterator(IArraySlice slice, Shape shape, Shape? broadcastedShape, bool autoReset = false)
+
+ +

Parameters

+
+
slice IArraySlice
+
+
shape Shape
+
+
broadcastedShape Shape?
+
+
autoReset bool
+
+
+ + + + + + + + + + + + + + +

+ NDIterator(IMemoryBlock, Shape, Shape?, bool) + +

+ +
+
+ +
+
public NDIterator(IMemoryBlock block, Shape shape, Shape? broadcastedShape, bool autoReset = false)
+
+ +

Parameters

+
+
block IMemoryBlock
+
+
shape Shape
+
+
broadcastedShape Shape?
+
+
autoReset bool
+
+
+ + + + + + + + + + + + + + +

+ NDIterator(UnmanagedStorage, bool) + +

+ +
+
+ +
+
public NDIterator(UnmanagedStorage storage, bool autoReset = false)
+
+ +

Parameters

+
+
storage UnmanagedStorage
+
+
autoReset bool
+
+
+ + + + + + + + + + + + + + +

+ NDIterator(NDArray, bool) + +

+ +
+
+ +
+
public NDIterator(NDArray arr, bool autoReset = false)
+
+ +

Parameters

+
+
arr NDArray
+
+
autoReset bool
+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ AutoReset + +

+ +

Does this iterator resets automatically when it finishes?

+
+
+ +
+
public bool AutoReset
+
+ + + + +

Field Value

+
+
bool
+
+
+ + + + + +

Remarks

+

When this is true, HasNext always returns true.

+
+ + + + + +

+ Block + +

+ +
+
+ +
+
public readonly IMemoryBlock Block
+
+ + + + +

Field Value

+
+
IMemoryBlock
+
+
+ + + + + + + + + + +

+ BroadcastedShape + +

+ +

The broadcasted version of Shape.

+
+
+ +
+
public Shape? BroadcastedShape
+
+ + + + +

Field Value

+
+
Shape?
+
+
+ + + + + +

Remarks

+

Might be null when iterating a non-broadcasted class

+
+ + + + + +

+ HasNext + +

+ +

Returns a function that when called, checks if there is a next element in this iterator.

+
+
+ +
+
public Func<bool> HasNext
+
+ + + + +

Field Value

+
+
Func<bool>
+
+
+ + + + + + + + + + +

+ MoveNext + +

+ +

Returns a function that when called, moves to next iteration and return the next value.

+
+
+ +
+
public Func<TOut> MoveNext
+
+ + + + +

Field Value

+
+
Func<TOut>
+
+
+ + + + + +

Remarks

+

Make sure to check HasNext first.

+
+ + + + + +

+ MoveNextReference + +

+ +

Returns a function that when called, moves to next iteration and return a reference to the next value.

+
+
+ +
+
public MoveNextReferencedDelegate<TOut> MoveNextReference
+
+ + + + +

Field Value

+
+
MoveNextReferencedDelegate<TOut>
+
+
+ + + + + +

Remarks

+

Make sure to check HasNext first.

+
+ + + + + +

+ Reset + +

+ +

Resets internal pointer/counter.

+
+
+ +
+
public Action Reset
+
+ + + + +

Field Value

+
+
Action
+
+
+ + + + + + + + + + +

+ Shape + +

+ +

The shape this iterator iterates

+
+
+ +
+
public Shape Shape
+
+ + + + +

Field Value

+
+
Shape
+
+
+ + + + + + + + + + +

+ Type + +

+ +
+
+ +
+
public readonly IteratorType Type
+
+ + + + +

Field Value

+
+
IteratorType
+
+
+ + + + + + + + + + +

+ size + +

+ +

The size of this iterator.

+
+
+ +
+
public int size
+
+ + + + +

Field Value

+
+
int
+
+
+ + + + + + + + + +

Methods +

+ + + + +

+ Dispose() + +

+ +

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

+
+
+ +
+
public void Dispose()
+
+ + + + + + + + + + + + + + + +

+ GetEnumerator() + +

+ +

Returns an enumerator that iterates through the collection.

+
+
+ +
+
public IEnumerator<TOut> GetEnumerator()
+
+ + +

Returns

+
+
IEnumerator<TOut>
+

An enumerator that can be used to iterate through the collection.

+
+
+ + + + + + + + + + + + + +

+ SetDefaults() + +

+ +
+
+ +
+
protected void SetDefaults()
+
+ + + + + + + + + + + + + + + +

+ SetMode(bool, Shape) + +

+ +

Set the mode according to given parameters

+
+
+ +
+
public void SetMode(bool autoreset, Shape reshape = default)
+
+ +

Parameters

+
+
autoreset bool
+

The iterator will transparently reset after it is done.

+
+
reshape Shape
+

Provide a different shape to the iterator.

+
+
+ + + + + + + + + + + + + + +

+ autoresetDefault_Boolean() + +

+ +
+
+ +
+
protected void autoresetDefault_Boolean()
+
+ + + + + + + + + + + + + + + +

+ autoresetDefault_Byte() + +

+ +
+
+ +
+
protected void autoresetDefault_Byte()
+
+ + + + + + + + + + + + + + + +

+ autoresetDefault_Char() + +

+ +
+
+ +
+
protected void autoresetDefault_Char()
+
+ + + + + + + + + + + + + + + +

+ autoresetDefault_Decimal() + +

+ +
+
+ +
+
protected void autoresetDefault_Decimal()
+
+ + + + + + + + + + + + + + + +

+ autoresetDefault_Double() + +

+ +
+
+ +
+
protected void autoresetDefault_Double()
+
+ + + + + + + + + + + + + + + +

+ autoresetDefault_Int16() + +

+ +
+
+ +
+
protected void autoresetDefault_Int16()
+
+ + + + + + + + + + + + + + + +

+ autoresetDefault_Int32() + +

+ +
+
+ +
+
protected void autoresetDefault_Int32()
+
+ + + + + + + + + + + + + + + +

+ autoresetDefault_Int64() + +

+ +
+
+ +
+
protected void autoresetDefault_Int64()
+
+ + + + + + + + + + + + + + + +

+ autoresetDefault_NoCast() + +

+ +
+
+ +
+
protected void autoresetDefault_NoCast()
+
+ + + + + + + + + + + + + + + +

+ autoresetDefault_Single() + +

+ +
+
+ +
+
protected void autoresetDefault_Single()
+
+ + + + + + + + + + + + + + + +

+ autoresetDefault_UInt16() + +

+ +
+
+ +
+
protected void autoresetDefault_UInt16()
+
+ + + + + + + + + + + + + + + +

+ autoresetDefault_UInt32() + +

+ +
+
+ +
+
protected void autoresetDefault_UInt32()
+
+ + + + + + + + + + + + + + + +

+ autoresetDefault_UInt64() + +

+ +
+
+ +
+
protected void autoresetDefault_UInt64()
+
+ + + + + + + + + + + + + + + +

+ setDefaults_Boolean() + +

+ +
+
+ +
+
protected void setDefaults_Boolean()
+
+ + + + + + + + + + + + + + + +

+ setDefaults_Byte() + +

+ +
+
+ +
+
protected void setDefaults_Byte()
+
+ + + + + + + + + + + + + + + +

+ setDefaults_Char() + +

+ +
+
+ +
+
protected void setDefaults_Char()
+
+ + + + + + + + + + + + + + + +

+ setDefaults_Decimal() + +

+ +
+
+ +
+
protected void setDefaults_Decimal()
+
+ + + + + + + + + + + + + + + +

+ setDefaults_Double() + +

+ +
+
+ +
+
protected void setDefaults_Double()
+
+ + + + + + + + + + + + + + + +

+ setDefaults_Int16() + +

+ +
+
+ +
+
protected void setDefaults_Int16()
+
+ + + + + + + + + + + + + + + +

+ setDefaults_Int32() + +

+ +
+
+ +
+
protected void setDefaults_Int32()
+
+ + + + + + + + + + + + + + + +

+ setDefaults_Int64() + +

+ +
+
+ +
+
protected void setDefaults_Int64()
+
+ + + + + + + + + + + + + + + +

+ setDefaults_NoCast() + +

+ +
+
+ +
+
protected void setDefaults_NoCast()
+
+ + + + + + + + + + + + + + + +

+ setDefaults_Single() + +

+ +
+
+ +
+
protected void setDefaults_Single()
+
+ + + + + + + + + + + + + + + +

+ setDefaults_UInt16() + +

+ +
+
+ +
+
protected void setDefaults_UInt16()
+
+ + + + + + + + + + + + + + + +

+ setDefaults_UInt32() + +

+ +
+
+ +
+
protected void setDefaults_UInt32()
+
+ + + + + + + + + + + + + + + +

+ setDefaults_UInt64() + +

+ +
+
+ +
+
protected void setDefaults_UInt64()
+
+ + + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.NDIterator.html b/docs/website/api/NumSharp.NDIterator.html new file mode 100644 index 000000000..4c367beef --- /dev/null +++ b/docs/website/api/NumSharp.NDIterator.html @@ -0,0 +1,454 @@ + + + + + Interface NDIterator | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Interface NDIterator +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public interface NDIterator : IEnumerable
+
+ + + + + + + +
+
Inherited Members
+
+ +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Properties +

+ + + + +

+ AutoReset + +

+ +
+
+ +
+
bool AutoReset { get; }
+
+ + + + + +

Property Value

+
+
bool
+
+
+ + + + + + + + + + +

+ Block + +

+ +
+
+ +
+
IMemoryBlock Block { get; }
+
+ + + + + +

Property Value

+
+
IMemoryBlock
+
+
+ + + + + + + + + + +

+ BroadcastedShape + +

+ +
+
+ +
+
Shape? BroadcastedShape { get; }
+
+ + + + + +

Property Value

+
+
Shape?
+
+
+ + + + + + + + + + +

+ HasNext + +

+ +
+
+ +
+
Func<bool> HasNext { get; }
+
+ + + + + +

Property Value

+
+
Func<bool>
+
+
+ + + + + + + + + + +

+ Reset + +

+ +
+
+ +
+
Action Reset { get; }
+
+ + + + + +

Property Value

+
+
Action
+
+
+ + + + + + + + + + +

+ Shape + +

+ +
+
+ +
+
Shape Shape { get; }
+
+ + + + + +

Property Value

+
+
Shape
+
+
+ + + + + + + + + + +

+ Type + +

+ +
+
+ +
+
IteratorType Type { get; }
+
+ + + + + +

Property Value

+
+
IteratorType
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ MoveNextReference<T>() + +

+ +
+
+ +
+
MoveNextReferencedDelegate<T> MoveNextReference<T>() where T : unmanaged
+
+ + +

Returns

+
+
MoveNextReferencedDelegate<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ MoveNext<T>() + +

+ +
+
+ +
+
Func<T> MoveNext<T>() where T : unmanaged
+
+ + +

Returns

+
+
Func<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.NDIteratorExtensions.html b/docs/website/api/NumSharp.NDIteratorExtensions.html new file mode 100644 index 000000000..b191019dc --- /dev/null +++ b/docs/website/api/NumSharp.NDIteratorExtensions.html @@ -0,0 +1,437 @@ + + + + + Class NDIteratorExtensions | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NDIteratorExtensions +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public static class NDIteratorExtensions
+
+ + + + +
+
Inheritance
+
+ +
NDIteratorExtensions
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Methods +

+ + + + +

+ AsIterator(IArraySlice, Shape) + +

+ +

Creates a new iterator to iterate given arr as if it were shaped like shape.

+
+
+ +
+
public static NDIterator AsIterator(this IArraySlice arr, Shape shape)
+
+ +

Parameters

+
+
arr IArraySlice
+

The IArraySlice to iterate.

+
+
shape Shape
+
+
+ +

Returns

+
+
NDIterator
+
+
+ + + + + + + + + + + + + +

+ AsIterator(IArraySlice, Shape, Shape, bool) + +

+ +

Creates a new iterator to iterate given arr as if it were shaped like shape.

+
+
+ +
+
public static NDIterator AsIterator(this IArraySlice arr, Shape shape, Shape broadcastShape, bool autoReset)
+
+ +

Parameters

+
+
arr IArraySlice
+

The IArraySlice to iterate.

+
+
shape Shape
+

The original shape, non-broadcasted.

+
+
broadcastShape Shape
+

The broadcasted shape of shape

+
+
autoReset bool
+
+
+ +

Returns

+
+
NDIterator
+
+
+ + + + + + + + + + + + + +

+ AsIterator(IArraySlice, Shape, bool) + +

+ +

Creates a new iterator to iterate given arr as if it were shaped like shape.

+
+
+ +
+
public static NDIterator AsIterator(this IArraySlice arr, Shape shape, bool autoreset)
+
+ +

Parameters

+
+
arr IArraySlice
+

The IArraySlice to iterate.

+
+
shape Shape
+

The original shape, non-broadcasted, to represent this iterator.

+
+
autoreset bool
+

Should this iterator loop forever?

+
+
+ +

Returns

+
+
NDIterator
+
+
+ + + + + + + + + + + + + +

+ AsIterator(UnmanagedStorage, bool) + +

+ +

Creates a new iterator to iterate given nd.

+
+
+ +
+
public static NDIterator AsIterator(this UnmanagedStorage us, bool autoreset = false)
+
+ +

Parameters

+
+
us UnmanagedStorage
+

The ndarray to iterate.

+
+
autoreset bool
+

Should this iterator loop forever?

+
+
+ +

Returns

+
+
NDIterator
+
+
+ + + + + + + + + + + + + +

+ AsIterator(NDArray, bool) + +

+ +

Creates a new iterator to iterate given nd.

+
+
+ +
+
public static NDIterator AsIterator(this NDArray nd, bool autoreset = false)
+
+ +

Parameters

+
+
nd NDArray
+

The ndarray to iterate.

+
+
autoreset bool
+

Should this iterator loop forever?

+
+
+ +

Returns

+
+
NDIterator
+
+
+ + + + + + + + + + + + + +

+ AsIterator<T>(NDArray, bool) + +

+ +

Creates a new iterator to iterate given nd.

+
+
+ +
+
public static NDIterator<T> AsIterator<T>(this NDArray nd, bool autoreset = false) where T : unmanaged
+
+ +

Parameters

+
+
nd NDArray
+

The ndarray to iterate.

+
+
autoreset bool
+

Should this iterator loop forever?

+
+
+ +

Returns

+
+
NDIterator<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.NPTypeCode.html b/docs/website/api/NumSharp.NPTypeCode.html new file mode 100644 index 000000000..4ce6484d0 --- /dev/null +++ b/docs/website/api/NumSharp.NPTypeCode.html @@ -0,0 +1,255 @@ + + + + + Enum NPTypeCode | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + + +

+Enum NPTypeCode +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +

Represents all available types in numpy.

+
+
+ +
+
public enum NPTypeCode
+
+ + + + + + + + +
+
Extension Methods
+
+ + + + + + + + + + + + + +
+ +

Fields +

+
+
Empty = 0
+ +

A null reference.

+
+
Boolean = 3
+ +

A simple type representing Boolean values of true or false.

+
+
Char = 4
+ +

An integral type representing unsigned 16-bit integers with values between 0 and 65535. The set of possible values for the Char type corresponds to the Unicode character set.

+
+
Byte = 6
+ +

An integral type representing unsigned 8-bit integers with values between 0 and 255.

+
+
Int16 = 7
+ +

An integral type representing signed 16-bit integers with values between -32768 and 32767.

+
+
UInt16 = 8
+ +

An integral type representing unsigned 16-bit integers with values between 0 and 65535.

+
+
Int32 = 9
+ +

An integral type representing signed 32-bit integers with values between -2147483648 and 2147483647.

+
+
UInt32 = 10
+ +

An integral type representing unsigned 32-bit integers with values between 0 and 4294967295.

+
+
Int64 = 11
+ +

An integral type representing signed 64-bit integers with values between -9223372036854775808 and 9223372036854775807.

+
+
UInt64 = 12
+ +

An integral type representing unsigned 64-bit integers with values between 0 and 18446744073709551615.

+
+
Single = 13
+ +

A floating point type representing values ranging from approximately 1.5 x 10 -45 to 3.4 x 10 38 with a precision of 7 digits.

+
+
Float = 13
+ +
+
Double = 14
+ +

A floating point type representing values ranging from approximately 5.0 x 10 -324 to 1.7 x 10 308 with a precision of 15-16 digits.

+
+
Decimal = 15
+ +

A simple type representing values ranging from 1.0 x 10 -28 to approximately 7.9 x 10 28 with 28-29 significant digits.

+
+
String = 18
+ +

A sealed class type representing Unicode character strings.

+
+
Complex = 128
+ +
+
+ + +

Remarks

+

The int values of the enum are a copy of TypeCode excluding types not available in numpy.

+
+ +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.NPTypeCodeExtensions.html b/docs/website/api/NumSharp.NPTypeCodeExtensions.html new file mode 100644 index 000000000..63b08356a --- /dev/null +++ b/docs/website/api/NumSharp.NPTypeCodeExtensions.html @@ -0,0 +1,672 @@ + + + + + Class NPTypeCodeExtensions | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NPTypeCodeExtensions +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public static class NPTypeCodeExtensions
+
+ + + + +
+
Inheritance
+
+ +
NPTypeCodeExtensions
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Methods +

+ + + + +

+ AsType(NPTypeCode) + +

+ +

Convert NPTypeCode into its Type

+
+
+ +
+
public static Type AsType(this NPTypeCode typeCode)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+
+
+ +

Returns

+
+
Type
+
+
+ + + + + + + + + + + + + +

+ CompareTo(NPTypeCode, NPTypeCode) + +

+ +
+
+ +
+
public static int CompareTo(this NPTypeCode left, NPTypeCode right)
+
+ +

Parameters

+
+
left NPTypeCode
+
+
right NPTypeCode
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ GetAccumulatingType(NPTypeCode) + +

+ +

Gets the dtype that is used as accumulation in case when statistics are computed like sum(in NDArray)

+
+
+ +
+
public static NPTypeCode GetAccumulatingType(this NPTypeCode typeCode)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+
+
+ +

Returns

+
+
NPTypeCode
+

dtype in case when statistics are computed like sum(in NDArray)

+
+
+ + + + + + + + + + + + + +

+ GetComputingType(NPTypeCode) + +

+ +

Gets the dtype that is used as return type in case when statistics are computed with high decimal precision like sin(in NDArray, NPTypeCode?)

+
+
+ +
+
public static NPTypeCode GetComputingType(this NPTypeCode typeCode)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+
+
+ +

Returns

+
+
NPTypeCode
+

dtype in case when statistics are computed like mean(in NDArray)

+
+
+ + + + + + + + + + + + + +

+ GetDefaultValue(NPTypeCode) + +

+ +

Gets the default value of typeCode.

+
+
+ +
+
public static ValueType GetDefaultValue(this NPTypeCode typeCode)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+
+
+ +

Returns

+
+
ValueType
+
+
+ + + + + + + + + + + + + +

+ GetTypeCode(Type) + +

+ +

Extracts NPTypeCode from given Type.

+
+
+ +
+
public static NPTypeCode GetTypeCode(this Type type)
+
+ +

Parameters

+
+
type Type
+
+
+ +

Returns

+
+
NPTypeCode
+
+
+ + + + + + + +

Remarks

+

In case there was no successful cast to NPTypeCode, return will be Empty

+
+ + + + + + +

+ GetTypeCode<T>() + +

+ +

Extracts NPTypeCode from given T.

+
+
+ +
+
public static NPTypeCode GetTypeCode<T>()
+
+ + +

Returns

+
+
NPTypeCode
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+

In case there was no successful cast to NPTypeCode, return will be Empty

+
+ + + + + + +

+ IsNumerical(NPTypeCode) + +

+ +

Returns true if typecode is a number (incl. bool, char and Complex).

+
+
+ +
+
public static bool IsNumerical(this NPTypeCode typeCode)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ IsRealNumber(NPTypeCode) + +

+ +

Is typeCode a float, double, complex or decimal?

+
+
+ +
+
public static bool IsRealNumber(this NPTypeCode typeCode)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ IsSigned(NPTypeCode) + +

+ +

Is typeCode a float, double, complex or decimal?

+
+
+ +
+
public static bool IsSigned(this NPTypeCode typeCode)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ IsUnsigned(NPTypeCode) + +

+ +

Is typeCode a uint, byte, ulong and so on.

+
+
+ +
+
public static bool IsUnsigned(this NPTypeCode typeCode)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ IsValidNPType(Type) + +

+ +

Checks if given Type has a match in NPTypeCode.

+
+
+ +
+
public static bool IsValidNPType(this Type type)
+
+ +

Parameters

+
+
type Type
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ SizeOf(NPTypeCode) + +

+ +

Gets the size of given typeCode

+
+
+ +
+
public static int SizeOf(this NPTypeCode typeCode)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + +

Remarks

+

The size is computed by SizeOf<T>()

+
+ + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.NativeRandomState.html b/docs/website/api/NumSharp.NativeRandomState.html new file mode 100644 index 000000000..d45ab08eb --- /dev/null +++ b/docs/website/api/NumSharp.NativeRandomState.html @@ -0,0 +1,242 @@ + + + + + Struct NativeRandomState | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Struct NativeRandomState +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +

Represents the stored state of Randomizer.

+
+
+ +
+
public struct NativeRandomState
+
+ + + + + + + +
+
Inherited Members
+
+ + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ NativeRandomState(byte[]) + +

+ +
+
+ +
+
public NativeRandomState(byte[] state)
+
+ +

Parameters

+
+
state byte[]
+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ State + +

+ +
+
+ +
+
public readonly byte[] State
+
+ + + + +

Field Value

+
+
byte[]
+
+
+ + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.NpzDictionary-1.html b/docs/website/api/NumSharp.NpzDictionary-1.html new file mode 100644 index 000000000..722696914 --- /dev/null +++ b/docs/website/api/NumSharp.NpzDictionary-1.html @@ -0,0 +1,947 @@ + + + + + Class NpzDictionary<T> | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NpzDictionary<T> +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class NpzDictionary<T> : IDisposable, IReadOnlyDictionary<string, T>, IReadOnlyCollection<KeyValuePair<string, T>>, IEnumerable<KeyValuePair<string, T>>, ICollection<T>, IEnumerable<T>, IEnumerable where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
+
+ + + +

Type Parameters

+
+
T
+
+
+ +
+
Inheritance
+
+ +
NpzDictionary<T>
+
+
+ +
+
Implements
+
+ + + + + + + +
+
+ +
+
Derived
+
+ +
+
+ +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ NpzDictionary(Stream) + +

+ +
+
+ +
+
public NpzDictionary(Stream stream)
+
+ +

Parameters

+
+
stream Stream
+
+
+ + + + + + + + + + + + +

Properties +

+ + + + +

+ Count + +

+ +

Gets the number of elements in the collection.

+
+
+ +
+
public int Count { get; }
+
+ + + + + +

Property Value

+
+
int
+

The number of elements in the collection.

+
+
+ + + + + + + + + + +

+ IsReadOnly + +

+ +

Gets a value indicating whether the ICollection<T> is read-only.

+
+
+ +
+
public bool IsReadOnly { get; }
+
+ + + + + +

Property Value

+
+
bool
+

true if the ICollection<T> is read-only; otherwise, false.

+
+
+ + + + + + + + + + +

+ IsSynchronized + +

+ +
+
+ +
+
public bool IsSynchronized { get; }
+
+ + + + + +

Property Value

+
+
bool
+
+
+ + + + + + + + + + +

+ this[string] + +

+ +

Gets the element that has the specified key in the read-only dictionary.

+
+
+ +
+
public T this[string key] { get; }
+
+ +

Parameters

+
+
key string
+

The key to locate.

+
+
+ + + + +

Property Value

+
+
T
+

The element that has the specified key in the read-only dictionary.

+
+
+ + + + + +

Exceptions

+
+
ArgumentNullException
+

key is null.

+
+
KeyNotFoundException
+

The property is retrieved and key is not found.

+
+
+ + + + + +

+ Keys + +

+ +

Gets an enumerable collection that contains the keys in the read-only dictionary.

+
+
+ +
+
public IEnumerable<string> Keys { get; }
+
+ + + + + +

Property Value

+
+
IEnumerable<string>
+

An enumerable collection that contains the keys in the read-only dictionary.

+
+
+ + + + + + + + + + +

+ SyncRoot + +

+ +
+
+ +
+
public object SyncRoot { get; }
+
+ + + + + +

Property Value

+
+
object
+
+
+ + + + + + + + + + +

+ Values + +

+ +

Gets an enumerable collection that contains the values in the read-only dictionary.

+
+
+ +
+
public IEnumerable<T> Values { get; }
+
+ + + + + +

Property Value

+
+
IEnumerable<T>
+

An enumerable collection that contains the values in the read-only dictionary.

+
+
+ + + + + + + + +

Methods +

+ + + + +

+ Add(T) + +

+ +

Adds an item to the ICollection<T>.

+
+
+ +
+
public void Add(T item)
+
+ +

Parameters

+
+
item T
+

The object to add to the ICollection<T>.

+
+
+ + + + + + + + + +

Exceptions

+
+
NotSupportedException
+

The ICollection<T> is read-only.

+
+
+ + + + + +

+ Clear() + +

+ +

Removes all items from the ICollection<T>.

+
+
+ +
+
public void Clear()
+
+ + + + + + + + + + +

Exceptions

+
+
NotSupportedException
+

The ICollection<T> is read-only.

+
+
+ + + + + +

+ Contains(T) + +

+ +

Determines whether the ICollection<T> contains a specific value.

+
+
+ +
+
public bool Contains(T item)
+
+ +

Parameters

+
+
item T
+

The object to locate in the ICollection<T>.

+
+
+ +

Returns

+
+
bool
+

true if item is found in the ICollection<T>; otherwise, false.

+
+
+ + + + + + + + + + + + + +

+ ContainsKey(string) + +

+ +

Determines whether the read-only dictionary contains an element that has the specified key.

+
+
+ +
+
public bool ContainsKey(string key)
+
+ +

Parameters

+
+
key string
+

The key to locate.

+
+
+ +

Returns

+
+
bool
+

true if the read-only dictionary contains an element that has the specified key; otherwise, false.

+
+
+ + + + + + + + +

Exceptions

+
+
ArgumentNullException
+

key is null.

+
+
+ + + + + +

+ CopyTo(Array, int) + +

+ +
+
+ +
+
public void CopyTo(Array array, int arrayIndex)
+
+ +

Parameters

+
+
array Array
+
+
arrayIndex int
+
+
+ + + + + + + + + + + + + + +

+ CopyTo(T[], int) + +

+ +

Copies the elements of the ICollection<T> to an Array, starting at a particular Array index.

+
+
+ +
+
public void CopyTo(T[] array, int arrayIndex)
+
+ +

Parameters

+
+
array T[]
+

The one-dimensional Array that is the destination of the elements copied from ICollection<T>. The Array must have zero-based indexing.

+
+
arrayIndex int
+

The zero-based index in array at which copying begins.

+
+
+ + + + + + + + + +

Exceptions

+
+
ArgumentNullException
+

array is null.

+
+
ArgumentOutOfRangeException
+

arrayIndex is less than 0.

+
+
ArgumentException
+

The number of elements in the source ICollection<T> is greater than the available space from arrayIndex to the end of the destination array.

+
+
+ + + + + +

+ Dispose() + +

+ +

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

+
+
+ +
+
public void Dispose()
+
+ + + + + + + + + + + + + + + +

+ Dispose(bool) + +

+ +
+
+ +
+
protected virtual void Dispose(bool disposing)
+
+ +

Parameters

+
+
disposing bool
+
+
+ + + + + + + + + + + + + + +

+ GetEnumerator() + +

+ +

Returns an enumerator that iterates through the collection.

+
+
+ +
+
public IEnumerator<KeyValuePair<string, T>> GetEnumerator()
+
+ + +

Returns

+
+
IEnumerator<KeyValuePair<string, T>>
+

An enumerator that can be used to iterate through the collection.

+
+
+ + + + + + + + + + + + + +

+ Load_Npz(Stream) + +

+ +
+
+ +
+
protected virtual T Load_Npz(Stream s)
+
+ +

Parameters

+
+
s Stream
+
+
+ +

Returns

+
+
T
+
+
+ + + + + + + + + + + + + +

+ Remove(T) + +

+ +

Removes the first occurrence of a specific object from the ICollection<T>.

+
+
+ +
+
public bool Remove(T item)
+
+ +

Parameters

+
+
item T
+

The object to remove from the ICollection<T>.

+
+
+ +

Returns

+
+
bool
+

true if item was successfully removed from the ICollection<T>; otherwise, false. This method also returns false if item is not found in the original ICollection<T>.

+
+
+ + + + + + + + +

Exceptions

+
+
NotSupportedException
+

The ICollection<T> is read-only.

+
+
+ + + + + +

+ TryGetValue(string, out T) + +

+ +

Gets the value that is associated with the specified key.

+
+
+ +
+
public bool TryGetValue(string key, out T value)
+
+ +

Parameters

+
+
key string
+

The key to locate.

+
+
value T
+

When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.

+
+
+ +

Returns

+
+
bool
+

true if the object that implements the IReadOnlyDictionary<TKey, TValue> interface contains an element that has the specified key; otherwise, false.

+
+
+ + + + + + + + +

Exceptions

+
+
ArgumentNullException
+

key is null.

+
+
+ + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.NpzDictionary.html b/docs/website/api/NumSharp.NpzDictionary.html new file mode 100644 index 000000000..ca604ba96 --- /dev/null +++ b/docs/website/api/NumSharp.NpzDictionary.html @@ -0,0 +1,326 @@ + + + + + Class NpzDictionary | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NpzDictionary +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class NpzDictionary : NpzDictionary<Array>, IDisposable, IReadOnlyDictionary<string, Array>, IReadOnlyCollection<KeyValuePair<string, Array>>, IEnumerable<KeyValuePair<string, Array>>, ICollection<Array>, IEnumerable<Array>, IEnumerable
+
+ + + + +
+
Inheritance
+
+ + +
NpzDictionary
+
+
+ +
+
Implements
+
+ + + + + + + +
+
+ + +
+
Inherited Members
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ NpzDictionary(Stream, bool) + +

+ +
+
+ +
+
public NpzDictionary(Stream stream, bool jagged)
+
+ +

Parameters

+
+
stream Stream
+
+
jagged bool
+
+
+ + + + + + + + + + + + +

Methods +

+ + + + +

+ Load_Npz(Stream) + +

+ +
+
+ +
+
protected override Array Load_Npz(Stream s)
+
+ +

Parameters

+
+
s Stream
+
+
+ +

Returns

+
+
Array
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/api/NumSharp.NumPy-1.html b/docs/website/api/NumSharp.NumPy-1.html similarity index 100% rename from docs/api/NumSharp.NumPy-1.html rename to docs/website/api/NumSharp.NumPy-1.html diff --git a/docs/api/NumSharp.NumPy-1.yml b/docs/website/api/NumSharp.NumPy-1.yml similarity index 100% rename from docs/api/NumSharp.NumPy-1.yml rename to docs/website/api/NumSharp.NumPy-1.yml diff --git a/docs/api/NumSharp.NumPyExtensions.html b/docs/website/api/NumSharp.NumPyExtensions.html similarity index 100% rename from docs/api/NumSharp.NumPyExtensions.html rename to docs/website/api/NumSharp.NumPyExtensions.html diff --git a/docs/api/NumSharp.NumPyExtensions.yml b/docs/website/api/NumSharp.NumPyExtensions.yml similarity index 100% rename from docs/api/NumSharp.NumPyExtensions.yml rename to docs/website/api/NumSharp.NumPyExtensions.yml diff --git a/docs/website/api/NumSharp.NumPyRandom.html b/docs/website/api/NumSharp.NumPyRandom.html new file mode 100644 index 000000000..d3842bb71 --- /dev/null +++ b/docs/website/api/NumSharp.NumPyRandom.html @@ -0,0 +1,2148 @@ + + + + + Class NumPyRandom | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NumPyRandom +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +

A class that serves as numpy.random.RandomState in python.

+
+
+ +
+
public class NumPyRandom
+
+ + + + +
+
Inheritance
+
+ +
NumPyRandom
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + +

Remarks

+ + + +

Constructors +

+ + + + +

+ NumPyRandom() + +

+ +
+
+ +
+
protected NumPyRandom()
+
+ + + + + + + + + + + + + + + +

+ NumPyRandom(NativeRandomState) + +

+ +
+
+ +
+
protected NumPyRandom(NativeRandomState nativeRandomState)
+
+ +

Parameters

+
+
nativeRandomState NativeRandomState
+
+
+ + + + + + + + + + + + + + +

+ NumPyRandom(Randomizer) + +

+ +
+
+ +
+
protected NumPyRandom(Randomizer randomizer)
+
+ +

Parameters

+
+
randomizer Randomizer
+
+
+ + + + + + + + + + + + + + +

+ NumPyRandom(int) + +

+ +
+
+ +
+
protected NumPyRandom(int seed)
+
+ +

Parameters

+
+
seed int
+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ randomizer + +

+ +
+
+ +
+
protected Randomizer randomizer
+
+ + + + +

Field Value

+
+
Randomizer
+
+
+ + + + + + + + + +

Properties +

+ + + + +

+ Seed + +

+ +
+
+ +
+
public int Seed { get; set; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ RandomState() + +

+ +

Returns a new instance of NumPyRandom.

+
+
+ +
+
public NumPyRandom RandomState()
+
+ + +

Returns

+
+
NumPyRandom
+
+
+ + + + + + + + + + + + + +

+ RandomState(NativeRandomState) + +

+ +

Returns a new instance of NumPyRandom.

+
+
+ +
+
public NumPyRandom RandomState(NativeRandomState state)
+
+ +

Parameters

+
+
state NativeRandomState
+
+
+ +

Returns

+
+
NumPyRandom
+
+
+ + + + + + + + + + + + + +

+ RandomState(int) + +

+ +

Returns a new instance of NumPyRandom.

+
+
+ +
+
public NumPyRandom RandomState(int seed)
+
+ +

Parameters

+
+
seed int
+
+
+ +

Returns

+
+
NumPyRandom
+
+
+ + + + + + + + + + + + + +

+ bernoulli(double, Shape) + +

+ +

Draw samples from a bernoulli distribution.

+
+
+ +
+
public NDArray bernoulli(double p, Shape shape)
+
+ +

Parameters

+
+
p double
+

Parameter of the distribution, >= 0 and <=1.

+
+
shape Shape
+

Output Shape

+
+
+ +

Returns

+
+
NDArray
+

Drawn samples from the parameterized bernoulli distribution.

+
+
+ + + + + + + + + + + + + +

+ bernoulli(double, params int[]) + +

+ +

Draw samples from a bernoulli distribution.

+
+
+ +
+
public NDArray bernoulli(double p, params int[] dims)
+
+ +

Parameters

+
+
p double
+

Parameter of the distribution, >= 0 and <=1.

+
+
dims int[]
+

Output Shape

+
+
+ +

Returns

+
+
NDArray
+

Drawn samples from the parameterized bernoulli distribution.

+
+
+ + + + + + + + + + + + + +

+ beta(double, double, Shape) + +

+ +

Draw samples from a Beta distribution. +The Beta distribution is a special case of the Dirichlet distribution, and is related to the Gamma distribution.It has the probability distribution function

+
+
+ +
+
public NDArray beta(double alpha, double betaValue, Shape shape)
+
+ +

Parameters

+
+
alpha double
+

Alpha value

+
+
betaValue double
+

Beta value

+
+
shape Shape
+

Output Shape

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ beta(double, double, params int[]) + +

+ +

Draw samples from a Beta distribution. +The Beta distribution is a special case of the Dirichlet distribution, and is related to the Gamma distribution.It has the probability distribution function

+
+
+ +
+
public NDArray beta(double alpha, double betaValue, params int[] dims)
+
+ +

Parameters

+
+
alpha double
+

Alpha value

+
+
betaValue double
+

Beta value

+
+
dims int[]
+

Output Shape

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ binomial(int, double, Shape) + +

+ +

Draw samples from a binomial distribution. +Samples are drawn from a binomial distribution with specified parameters, n trials and p probability of success where n an integer >= 0 and p is in the interval[0, 1]. (n may be input as a float, but it is truncated to an integer in use)

+
+
+ +
+
public NDArray binomial(int n, double p, Shape shape)
+
+ +

Parameters

+
+
n int
+

Parameter of the distribution, >= 0. Floats are also accepted, but they will be truncated to integers.

+
+
p double
+

Parameter of the distribution, >= 0 and <=1.

+
+
shape Shape
+

Output Shape

+
+
+ +

Returns

+
+
NDArray
+

Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ binomial(int, double, params int[]) + +

+ +

Draw samples from a binomial distribution. +Samples are drawn from a binomial distribution with specified parameters, n trials and p probability of success where n an integer >= 0 and p is in the interval[0, 1]. (n may be input as a float, but it is truncated to an integer in use)

+
+
+ +
+
public NDArray binomial(int n, double p, params int[] dims)
+
+ +

Parameters

+
+
n int
+

Parameter of the distribution, >= 0. Floats are also accepted, but they will be truncated to integers.

+
+
p double
+

Parameter of the distribution, >= 0 and <=1.

+
+
dims int[]
+

Output Shape

+
+
+ +

Returns

+
+
NDArray
+

Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ chisquare(double, Shape) + +

+ +

Draw samples from a chi-square distribution. +When df independent random variables, each with standard normal distributions(mean 0, variance 1), are squared and summed, +the resulting distribution is chi-square(see Notes). This distribution is often used in hypothesis testing.

+
+
+ +
+
public NDArray chisquare(double df, Shape shape)
+
+ +

Parameters

+
+
df double
+

Number of degrees of freedom, should be > 0.

+
+
shape Shape
+

Output Shape

+
+
+ +

Returns

+
+
NDArray
+

Drawn samples from the parameterized chi-square distribution.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ chisquare(double, params int[]) + +

+ +

Draw samples from a chi-square distribution. +When df independent random variables, each with standard normal distributions(mean 0, variance 1), are squared and summed, +the resulting distribution is chi-square(see Notes). This distribution is often used in hypothesis testing.

+
+
+ +
+
public NDArray chisquare(double df, params int[] dims)
+
+ +

Parameters

+
+
df double
+

Number of degrees of freedom, should be > 0.

+
+
dims int[]
+

Output Shape

+
+
+ +

Returns

+
+
NDArray
+

Drawn samples from the parameterized chi-square distribution.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ choice(NDArray, Shape, bool, double[]) + +

+ +

Generates a random sample from a given 1-D array

+
+
+ +
+
public NDArray choice(NDArray arr, Shape shape = default, bool replace = true, double[] probabilities = null)
+
+ +

Parameters

+
+
arr NDArray
+

If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a were np.arange(a)

+
+
shape Shape
+

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

+
+
replace bool
+

Whether the sample is with or without replacement

+
+
probabilities double[]
+

The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ choice(int, Shape, bool, double[]) + +

+ +

Generates a random sample from a given 1-D array

+
+
+ +
+
public NDArray choice(int a, Shape shape = default, bool replace = true, double[] probabilities = null)
+
+ +

Parameters

+
+
a int
+

If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a were np.arange(a)

+
+
shape Shape
+

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

+
+
replace bool
+

Whether the sample is with or without replacement

+
+
probabilities double[]
+

The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ exponential(double, Shape) + +

+ +

Draw samples from an exponential distribution. +The exponential distribution is a continuous analogue of the geometric distribution. It describes many common situations, such as the size of raindrops measured over many rainstorms

+
+
+ +
+
public NDArray exponential(double scale, Shape shape)
+
+ +

Parameters

+
+
scale double
+

The scale parameter, \beta = 1/\lambda.

+
+
shape Shape
+

Output Shape

+
+
+ +

Returns

+
+
NDArray
+

Drawn samples from the parameterized exponential distribution.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ exponential(double, params int[]) + +

+ +

Draw samples from an exponential distribution. +The exponential distribution is a continuous analogue of the geometric distribution. It describes many common situations, such as the size of raindrops measured over many rainstorms

+
+
+ +
+
public NDArray exponential(double scale, params int[] dims)
+
+ +

Parameters

+
+
scale double
+

The scale parameter, \beta = 1/\lambda.

+
+
dims int[]
+

Output Shape

+
+
+ +

Returns

+
+
NDArray
+

Drawn samples from the parameterized exponential distribution.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ gamma(double, double, Shape) + +

+ +

Draw samples from a Gamma distribution. +Samples are drawn from a Gamma distribution with specified parameters, shape (sometimes designated “k”) and scale(sometimes designated “theta”), +where both parameters are > 0.

+
+
+ +
+
public NDArray gamma(double shapeV, double scale, Shape shape)
+
+ +

Parameters

+
+
shapeV double
+

The shape of the gamma distribution. Should be greater than zero.

+
+
scale double
+

The scale of the gamma distribution. Should be greater than zero. Default is equal to 1.

+
+
shape Shape
+

Output shape.

+
+
+ +

Returns

+
+
NDArray
+

Drawn samples from the parameterized gamma distribution.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ gamma(double, double, params int[]) + +

+ +

Draw samples from a Gamma distribution. +Samples are drawn from a Gamma distribution with specified parameters, shape (sometimes designated “k”) and scale(sometimes designated “theta”), +where both parameters are > 0.

+
+
+ +
+
public NDArray gamma(double shape, double scale, params int[] dims)
+
+ +

Parameters

+
+
shape double
+

The shape of the gamma distribution. Should be greater than zero.

+
+
scale double
+

The scale of the gamma distribution. Should be greater than zero. Default is equal to 1.

+
+
dims int[]
+

Output shape.

+
+
+ +

Returns

+
+
NDArray
+

Drawn samples from the parameterized gamma distribution.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ geometric(double, Shape) + +

+ +

Draw samples from the geometric distribution. +Bernoulli trials are experiments with one of two outcomes: success or failure(an example of such an experiment is flipping a coin). +The geometric distribution models the number of trials that must be run in order to achieve success.It is therefore supported on the positive integers, k = 1, 2, ....

+
+
+ +
+
public NDArray geometric(double p, Shape shape)
+
+ +

Parameters

+
+
p double
+

The probability of success of an individual trial.

+
+
shape Shape
+

Output Shape

+
+
+ +

Returns

+
+
NDArray
+

Drawn samples from the parameterized geometric distribution.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ geometric(double, params int[]) + +

+ +

Draw samples from the geometric distribution. +Bernoulli trials are experiments with one of two outcomes: success or failure(an example of such an experiment is flipping a coin). +The geometric distribution models the number of trials that must be run in order to achieve success.It is therefore supported on the positive integers, k = 1, 2, ....

+
+
+ +
+
public NDArray geometric(double p, params int[] dims)
+
+ +

Parameters

+
+
p double
+

The probability of success of an individual trial.

+
+
dims int[]
+

Output Shape

+
+
+ +

Returns

+
+
NDArray
+

Drawn samples from the parameterized geometric distribution.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ get_state() + +

+ +

Return a NumPyRandom representing the internal state of the generator.

+
+
+ +
+
public NativeRandomState get_state()
+
+ + +

Returns

+
+
NativeRandomState
+
+
+ + + + + + + + + + + + + +

+ lognormal(double, double, Shape) + +

+ +

Draw samples from a log-normal distribution. +Draw samples from a log-normal distribution with specified mean, standard deviation, and array shape. +Note that the mean and standard deviation are not the values for the distribution itself, but of the underlying normal distribution it is derived from.

+
+
+ +
+
public NDArray lognormal(double mean, double sigma, Shape shape)
+
+ +

Parameters

+
+
mean double
+

Mean value of the underlying normal distribution. Default is 0.

+
+
sigma double
+

Standard deviation of the underlying normal distribution. Should be greater than zero. Default is 1.

+
+
shape Shape
+

Output Shape

+
+
+ +

Returns

+
+
NDArray
+

Drawn samples from the parameterized bernoulli distribution.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ lognormal(double, double, params int[]) + +

+ +

Draw samples from a log-normal distribution. +Draw samples from a log-normal distribution with specified mean, standard deviation, and array shape. +Note that the mean and standard deviation are not the values for the distribution itself, but of the underlying normal distribution it is derived from.

+
+
+ +
+
public NDArray lognormal(double mean, double sigma, params int[] dims)
+
+ +

Parameters

+
+
mean double
+

Mean value of the underlying normal distribution. Default is 0.

+
+
sigma double
+

Standard deviation of the underlying normal distribution. Should be greater than zero. Default is 1.

+
+
dims int[]
+

Output Shape

+
+
+ +

Returns

+
+
NDArray
+

Drawn samples from the parameterized bernoulli distribution.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ normal(double, double, params int[]) + +

+ +

Draw random samples from a normal (Gaussian) distribution.

+
+
+ +
+
public NDArray normal(double loc, double scale, params int[] dims)
+
+ +

Parameters

+
+
loc double
+

Mean of the distribution

+
+
scale double
+

Standard deviation of the distribution

+
+
dims int[]
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ permutation(NDArray) + +

+ +

Randomly permute a sequence, or return a permuted range.

+
+
+ +
+
public NDArray permutation(NDArray x)
+
+ +

Parameters

+
+
x NDArray
+

If x is an integer, randomly permute np.arange(x).

+
+
+ +

Returns

+
+
NDArray
+

Permuted sequence or array range.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ permutation(int) + +

+ +

Randomly permute a sequence, or return a permuted range.

+
+
+ +
+
public NDArray permutation(int x)
+
+ +

Parameters

+
+
x int
+

If x is an integer, randomly permute np.arange(x).

+
+
+ +

Returns

+
+
NDArray
+

Permuted sequence or array range.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ poisson(double, Shape) + +

+ +

Draw samples from a Poisson distribution. The Poisson distribution is the limit of the binomial distribution for large N.

+
+
+ +
+
public NDArray poisson(double lam, Shape shape)
+
+ +

Parameters

+
+
lam double
+

Expectation of interval, should be >= 0. A sequence of expectation intervals must be broadcastable over the requested size.

+
+
shape Shape
+

Output Shape

+
+
+ +

Returns

+
+
NDArray
+

Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ poisson(double, params int[]) + +

+ +

Draw samples from a Poisson distribution. The Poisson distribution is the limit of the binomial distribution for large N.

+
+
+ +
+
public NDArray poisson(double lam, params int[] dims)
+
+ +

Parameters

+
+
lam double
+

Expectation of interval, should be >= 0. A sequence of expectation intervals must be broadcastable over the requested size.

+
+
dims int[]
+

Output Shape

+
+
+ +

Returns

+
+
NDArray
+

Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ rand(Shape) + +

+ +

Random values in a given shape. +Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).

+
+
+ +
+
public NDArray rand(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ rand(params int[]) + +

+ +

Random values in a given shape. +Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).

+
+
+ +
+
public NDArray rand(params int[] size)
+
+ +

Parameters

+
+
size int[]
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ randint(long, long, Shape, Type) + +

+ +

Return random integers from the “discrete uniform” distribution of the specified dtype in the “half-open” interval [low, high). If high is None (the default), then results are from [0, low).

+
+
+ +
+
public NDArray randint(long low, long high = -1, Shape size = default, Type dtype = null)
+
+ +

Parameters

+
+
low long
+

Lowest (signed) integer to be drawn from the distribution (unless high=-1, in which case this parameter is one above the highest such integer).

+
+
high long
+

If provided, one above the largest (signed) integer to be drawn from the distribution (see above for behavior if high=-1).

+
+
size Shape
+

The shape of the array.

+
+
dtype Type
+

Desired dtype of the result. All dtypes are determined by their name, i.e., ‘int64’, ‘int’, etc, so byteorder is not available and a specific precision may have different C types depending on the platform. The default value is ‘np.int’.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ randn(params int[]) + +

+ +

Return a sample (or samples) from the “standard normal” distribution.

+
+
+ +
+
public NDArray randn(params int[] size)
+
+ +

Parameters

+
+
size int[]
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ randn<T>() + +

+ +

Scalar value

+
+
+ +
+
public T randn<T>()
+
+ + +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ random_sample(Shape) + +

+ +

Return random floats in the half-open interval [0.0, 1.0). +Results are from the “continuous uniform” distribution over the stated interval. To sample Unif[a, b), b > a multiply the output of random_sample by (b-a) and add a:

+
+
+ +
+
public NDArray random_sample(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+

The shape to randomize

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ random_sample(params int[]) + +

+ +

Return random floats in the half-open interval [0.0, 1.0). +Results are from the “continuous uniform” distribution over the stated interval. To sample Unif[a, b), b > a multiply the output of random_sample by (b-a) and add a:

+
+
+ +
+
public NDArray random_sample(params int[] size)
+
+ +

Parameters

+
+
size int[]
+

The samples

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ seed(int) + +

+ +

Seeds the generator. +It can be called again to re-seed the generator.

+
+
+ +
+
public void seed(int seed)
+
+ +

Parameters

+
+
seed int
+
+
+ + + + + + + + + + + + + + +

+ set_state(NativeRandomState) + +

+ +

Set the internal state of the generator from a NumPyRandom. +for use if one has reason to manually (re-)set the internal state of the pseudo-random number generating algorithm.

+
+
+ +
+
public void set_state(NativeRandomState nativeRandomState)
+
+ +

Parameters

+
+
nativeRandomState NativeRandomState
+

The state to restore onto this NumPyRandom

+
+
+ + + + + + + + + + + + + + +

+ shuffle(NDArray, int) + +

+ +

Modify a sequence in-place by shuffling its contents.

+
+
+ +
+
[SuppressMessage("ReSharper", "TooWideLocalVariableScope")]
+public void shuffle(NDArray x, int passes = 2)
+
+ +

Parameters

+
+
x NDArray
+

The array or list to be shuffled.

+
+
passes int
+

How many times to pass all items in a complexity of O(n*passes)

+
+
+ + + + + + + + +

Remarks

+ + + + + + + +

+ stardard_normal(params int[]) + +

+ +

Draw samples from a standard Normal distribution (mean=0, stdev=1).

+
+
+ +
+
public NDArray stardard_normal(params int[] size)
+
+ +

Parameters

+
+
size int[]
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ uniform(NDArray, NDArray, Type) + +

+ +

Draw samples from a uniform distribution. +Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform.

+
+
+ +
+
public NDArray uniform(NDArray low, NDArray high, Type dType = null)
+
+ +

Parameters

+
+
low NDArray
+

Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0.

+
+
high NDArray
+

Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0.

+
+
dType Type
+

The type of the output NDArray

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ uniform(double, double, Shape) + +

+ +

Draw samples from a uniform distribution. +Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform.

+
+
+ +
+
public NDArray uniform(double low, double high, Shape shape)
+
+ +

Parameters

+
+
low double
+

Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0.

+
+
high double
+

Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0.

+
+
shape Shape
+

Output shape. If the given shape is, e.g., m, n, k, then m * n * k samples are drawn. If size is None (default), a single value is returned if low and high are both scalars.

+
+
+ +

Returns

+
+
NDArray
+

NDArray with values of type double

+
+
+ + + + + + + + + + + + + +

+ uniform(double, double, params int[]) + +

+ +

Draw samples from a uniform distribution. +Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform.

+
+
+ +
+
public NDArray uniform(double low, double high, params int[] size)
+
+ +

Parameters

+
+
low double
+

Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0.

+
+
high double
+

Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0.

+
+
size int[]
+

Output shape. If the given shape is, e.g., m, n, k, then m * n * k samples are drawn. If size is None (default), a single value is returned if low and high are both scalars.

+
+
+ +

Returns

+
+
NDArray
+

NDArray with values of type double

+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.NumSharpException.html b/docs/website/api/NumSharp.NumSharpException.html new file mode 100644 index 000000000..0d6d9467e --- /dev/null +++ b/docs/website/api/NumSharp.NumSharpException.html @@ -0,0 +1,328 @@ + + + + + Class NumSharpException | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NumSharpException +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class NumSharpException : Exception, ISerializable, INumSharpException
+
+ + + + +
+
Inheritance
+
+ + +
NumSharpException
+
+
+ +
+
Implements
+
+ + +
+
+ +
+
Derived
+
+ + + +
+
+ +
+
Inherited Members
+
+ + + + + + + + + + + + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ NumSharpException() + +

+ +

Initializes a new instance of the Exception class.

+
+
+ +
+
public NumSharpException()
+
+ + + + + + + + + + + + + + + +

+ NumSharpException(string) + +

+ +

Initializes a new instance of the Exception class with a specified error message.

+
+
+ +
+
public NumSharpException(string message)
+
+ +

Parameters

+
+
message string
+

The message that describes the error.

+
+
+ + + + + + + + + + + + + + +

+ NumSharpException(string, Exception) + +

+ +

Initializes a new instance of the Exception class with a specified error message and a reference to the inner exception that is the cause of this exception.

+
+
+ +
+
public NumSharpException(string message, Exception innerException)
+
+ +

Parameters

+
+
message string
+

The error message that explains the reason for the exception.

+
+
innerException Exception
+

The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.

+
+
+ + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/api/NumSharp.PowerShell.GetGreeting.html b/docs/website/api/NumSharp.PowerShell.GetGreeting.html similarity index 100% rename from docs/api/NumSharp.PowerShell.GetGreeting.html rename to docs/website/api/NumSharp.PowerShell.GetGreeting.html diff --git a/docs/api/NumSharp.PowerShell.GetGreeting.yml b/docs/website/api/NumSharp.PowerShell.GetGreeting.yml similarity index 100% rename from docs/api/NumSharp.PowerShell.GetGreeting.yml rename to docs/website/api/NumSharp.PowerShell.GetGreeting.yml diff --git a/docs/api/NumSharp.PowerShell.NewNDArray.html b/docs/website/api/NumSharp.PowerShell.NewNDArray.html similarity index 100% rename from docs/api/NumSharp.PowerShell.NewNDArray.html rename to docs/website/api/NumSharp.PowerShell.NewNDArray.html diff --git a/docs/api/NumSharp.PowerShell.NewNDArray.yml b/docs/website/api/NumSharp.PowerShell.NewNDArray.yml similarity index 100% rename from docs/api/NumSharp.PowerShell.NewNDArray.yml rename to docs/website/api/NumSharp.PowerShell.NewNDArray.yml diff --git a/docs/api/NumSharp.PowerShell.html b/docs/website/api/NumSharp.PowerShell.html similarity index 100% rename from docs/api/NumSharp.PowerShell.html rename to docs/website/api/NumSharp.PowerShell.html diff --git a/docs/api/NumSharp.PowerShell.yml b/docs/website/api/NumSharp.PowerShell.yml similarity index 100% rename from docs/api/NumSharp.PowerShell.yml rename to docs/website/api/NumSharp.PowerShell.yml diff --git a/docs/website/api/NumSharp.Randomizer.html b/docs/website/api/NumSharp.Randomizer.html new file mode 100644 index 000000000..f7da33b96 --- /dev/null +++ b/docs/website/api/NumSharp.Randomizer.html @@ -0,0 +1,721 @@ + + + + + Class Randomizer | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class Randomizer +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +

Represents a pseudo-random number generator, which is a device that produces a sequence of numbers that meet certain statistical requirements for randomness.
+Equivalent of Random.

+
+
+ +
+
public sealed class Randomizer : ICloneable
+
+ + + + +
+
Inheritance
+
+ +
Randomizer
+
+
+ +
+
Implements
+
+ +
+
+ + +
+
Inherited Members
+
+ + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + +

Remarks

+ + + +

Constructors +

+ + + + +

+ Randomizer() + +

+ +

Initializes a new instance of the Randomizer class, using a time-dependent default seed value.

+
+
+ +
+
public Randomizer()
+
+ + + + + + + + + + + + + + + +

+ Randomizer(int) + +

+ +

Initializes a new instance of the Random class, using the specified seed value.

+
+
+ +
+
public Randomizer(int Seed)
+
+ +

Parameters

+
+
Seed int
+

A number used to calculate a starting value for the pseudo-random number sequence. If a negative number is specified, the absolute value of the number is used.

+
+
+ + + + + + + + + + + + +

Methods +

+ + + + +

+ Clone() + +

+ +

Creates a new object that is a copy of the current instance.

+
+
+ +
+
public Randomizer Clone()
+
+ + +

Returns

+
+
Randomizer
+

A new object that is a copy of this instance.

+
+
+ + + + + + + + + + + + + +

+ Deserialize(byte[]) + +

+ +
+
+ +
+
public static Randomizer Deserialize(byte[] bytes)
+
+ +

Parameters

+
+
bytes byte[]
+
+
+ +

Returns

+
+
Randomizer
+
+
+ + + + + + + + + + + + + +

+ Next() + +

+ +

Returns a non-negative random integer.

+
+
+ +
+
public int Next()
+
+ + +

Returns

+
+
int
+

A 32-bit signed integer that is greater than or equal to 0 and less than MaxValue.

+
+
+ + + + + + + + + + + + + +

+ Next(int) + +

+ +

Returns a non-negative random integer that is less than the specified maximum.

+
+
+ +
+
public int Next(int maxValue)
+
+ +

Parameters

+
+
maxValue int
+

The exclusive upper bound of the random number to be generated. maxValue must be greater than or equal to 0.

+
+
+ +

Returns

+
+
int
+

A 32-bit signed integer that is greater than or equal to 0, and less than maxValue; that is, the range of return values ordinarily includes 0 but not maxValue. However, if maxValue equals 0, maxValue is returned.

+
+
+ + + + + + + + +

Exceptions

+
+
ArgumentOutOfRangeException
+

maxValue is less than 0.

+
+
+ + + + + +

+ Next(int, int) + +

+ +

Returns a random integer that is within a specified range.

+
+
+ +
+
public int Next(int minValue, int maxValue)
+
+ +

Parameters

+
+
minValue int
+

The inclusive lower bound of the random number returned.

+
+
maxValue int
+

The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.

+
+
+ +

Returns

+
+
int
+

A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned.

+
+
+ + + + + + + + +

Exceptions

+
+
ArgumentOutOfRangeException
+

minValue is greater than maxValue.

+
+
+ + + + + +

+ NextBytes(byte[]) + +

+ +

Fills the elements of a specified array of bytes with random numbers.

+
+
+ +
+
public void NextBytes(byte[] buffer)
+
+ +

Parameters

+
+
buffer byte[]
+

An array of bytes to contain random numbers.

+
+
+ + + + + + + + + +

Exceptions

+
+
ArgumentNullException
+

buffer is null.

+
+
+ + + + + +

+ NextDouble() + +

+ +

Returns a random floating-point number that is greater than or equal to 0.0, and less than 1.0.

+
+
+ +
+
public double NextDouble()
+
+ + +

Returns

+
+
double
+

A double-precision floating point number that is greater than or equal to 0.0, and less than 1.0.

+
+
+ + + + + + + + + + + + + +

+ NextLong() + +

+ +

Returns a non-negative random integer that is less than the specified maximum.

+
+
+ +
+
public long NextLong()
+
+ + +

Returns

+
+
long
+

A 32-bit signed integer that is greater than or equal to 0, and less than maxValue; that is, the range of return values ordinarily includes 0 but not maxValue. However, if maxValue equals 0, maxValue is returned.

+
+
+ + + + + + + + +

Exceptions

+
+
ArgumentOutOfRangeException
+

maxValue is less than 0.

+
+
+ + + + + +

+ NextLong(long) + +

+ +

Returns a non-negative random integer that is less than the specified maximum.

+
+
+ +
+
public long NextLong(long maxValue)
+
+ +

Parameters

+
+
maxValue long
+

The exclusive upper bound of the random number to be generated. maxValue must be greater than or equal to 0.

+
+
+ +

Returns

+
+
long
+

A 32-bit signed integer that is greater than or equal to 0, and less than maxValue; that is, the range of return values ordinarily includes 0 but not maxValue. However, if maxValue equals 0, maxValue is returned.

+
+
+ + + + + + + + +

Exceptions

+
+
ArgumentOutOfRangeException
+

maxValue is less than 0.

+
+
+ + + + + +

+ NextLong(long, long) + +

+ +

Returns a random integer that is within a specified range.

+
+
+ +
+
public long NextLong(long minValue, long maxValue)
+
+ +

Parameters

+
+
minValue long
+

The inclusive lower bound of the random number returned.

+
+
maxValue long
+

The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.

+
+
+ +

Returns

+
+
long
+

A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned.

+
+
+ + + + + + + + +

Exceptions

+
+
ArgumentOutOfRangeException
+

minValue is greater than maxValue.

+
+
+ + + + + +

+ Sample() + +

+ +

Returns a random floating-point number between 0.0 and 1.0.

+
+
+ +
+
protected double Sample()
+
+ + +

Returns

+
+
double
+

A double-precision floating point number that is greater than or equal to 0.0, and less than 1.0.

+
+
+ + + + + + + + + + + + + +

+ Serialize() + +

+ +
+
+ +
+
public byte[] Serialize()
+
+ + +

Returns

+
+
byte[]
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Shape.html b/docs/website/api/NumSharp.Shape.html new file mode 100644 index 000000000..0d61f218d --- /dev/null +++ b/docs/website/api/NumSharp.Shape.html @@ -0,0 +1,2729 @@ + + + + + Struct Shape | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Struct Shape +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +

Represents a shape of an N-D array.

+
+
+ +
+
public struct Shape : ICloneable, IEquatable<Shape>
+
+ + + + + +
+
Implements
+
+ + +
+
+ + +
+
Inherited Members
+
+ + + +
+ +
+
Extension Methods
+
+ +
+ + + +

Remarks

+

Handles slicing, indexing based on coordinates or linear offset and broadcastted indexing.

+
+ + +

Constructors +

+ + + + +

+ Shape(Shape) + +

+ +
+
+ +
+
public Shape(Shape other)
+
+ +

Parameters

+
+
other Shape
+
+
+ + + + + + + + + + + + + + +

+ Shape(params int[]) + +

+ +
+
+ +
+
public Shape(params int[] dims)
+
+ +

Parameters

+
+
dims int[]
+
+
+ + + + + + + + + + + + + + +

+ Shape(int[], int[]) + +

+ +
+
+ +
+
public Shape(int[] dims, int[] strides)
+
+ +

Parameters

+
+
dims int[]
+
+
strides int[]
+
+
+ + + + + + + + + + + + + + +

+ Shape(int[], int[], Shape) + +

+ +
+
+ +
+
public Shape(int[] dims, int[] strides, Shape originalShape)
+
+ +

Parameters

+
+
dims int[]
+
+
strides int[]
+
+
originalShape Shape
+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ IsScalar + +

+ +
+
+ +
+
public bool IsScalar
+
+ + + + +

Field Value

+
+
bool
+
+
+ + + + + + + + + + +

+ ModifiedStrides + +

+ +

Does this Shape have modified strides, usually in scenarios like np.transpose.

+
+
+ +
+
public bool ModifiedStrides
+
+ + + + +

Field Value

+
+
bool
+
+
+ + + + + + + + + + +

+ Scalar + +

+ +

Singleton instance of a Shape that represents a scalar.

+
+
+ +
+
public static readonly Shape Scalar
+
+ + + + +

Field Value

+
+
Shape
+
+
+ + + + + + + + + +

Properties +

+ + + + +

+ Dimensions + +

+ +
+
+ +
+
public readonly int[] Dimensions { get; }
+
+ + + + + +

Property Value

+
+
int[]
+
+
+ + + + + + + + + + +

+ IsBroadcasted + +

+ +

Is this shape a broadcast and/or has modified strides?

+
+
+ +
+
public readonly bool IsBroadcasted { get; }
+
+ + + + + +

Property Value

+
+
bool
+
+
+ + + + + + + + + + +

+ IsContiguous + +

+ +

Does this Shape represents a non-sliced and non-broadcasted hence contagious unmanaged memory?

+
+
+ +
+
public readonly bool IsContiguous { get; }
+
+ + + + + +

Property Value

+
+
bool
+
+
+ + + + + + + + + + +

+ IsEmpty + +

+ +

True if the shape is not initialized. +Note: A scalar shape is not empty.

+
+
+ +
+
public readonly bool IsEmpty { get; }
+
+ + + + + +

Property Value

+
+
bool
+
+
+ + + + + + + + + + +

+ IsRecursive + +

+ +

Is this Shape a recusive view? (deeper than 1 view)

+
+
+ +
+
public readonly bool IsRecursive { get; }
+
+ + + + + +

Property Value

+
+
bool
+
+
+ + + + + + + + + + +

+ IsSliced + +

+ +

True if the shape of this array was obtained by a slicing operation that caused the underlying data to be non-contiguous

+
+
+ +
+
public readonly bool IsSliced { get; }
+
+ + + + + +

Property Value

+
+
bool
+
+
+ + + + + + + + + + +

+ this[int] + +

+ +
+
+ +
+
public readonly int this[int dim] { get; set; }
+
+ +

Parameters

+
+
dim int
+
+
+ + + + +

Property Value

+
+
int
+
+
+ + + + + + + + + + +

+ NDim + +

+ +
+
+ +
+
public readonly int NDim { get; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + + + + + + + +

+ Order + +

+ +
+
+ +
+
public readonly char Order { get; }
+
+ + + + + +

Property Value

+
+
char
+
+
+ + + + + + + + + + +

+ Size + +

+ +

The linear size of this shape.

+
+
+ +
+
public readonly int Size { get; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + + + + + + + +

+ Strides + +

+ +
+
+ +
+
public readonly int[] Strides { get; }
+
+ + + + + +

Property Value

+
+
int[]
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ ChangeTensorLayout(char) + +

+ +
+
+ +
+
public void ChangeTensorLayout(char order = 'C')
+
+ +

Parameters

+
+
order char
+
+
+ + + + + + + + + + + + + + +

+ Clean() + +

+ +

Returns a clean shape based on this. +Cleans ViewInfo and returns a newly constructed.

+
+
+ +
+
public readonly Shape Clean()
+
+ + +

Returns

+
+
Shape
+
+
+ + + + + + + + + + + + + +

+ Clone(bool, bool, bool) + +

+ +

Creates a complete copy of this Shape.

+
+
+ +
+
public readonly Shape Clone(bool deep = true, bool unview = false, bool unbroadcast = false)
+
+ +

Parameters

+
+
deep bool
+

Should make a complete deep clone or a shallow if false.

+
+
unview bool
+
+
unbroadcast bool
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + + + + + + + +

+ Deconstruct(out int, out int) + +

+ +
+
+ +
+
public readonly void Deconstruct(out int dim1, out int dim2)
+
+ +

Parameters

+
+
dim1 int
+
+
dim2 int
+
+
+ + + + + + + + + + + + + + +

+ Deconstruct(out int, out int, out int) + +

+ +
+
+ +
+
public readonly void Deconstruct(out int dim1, out int dim2, out int dim3)
+
+ +

Parameters

+
+
dim1 int
+
+
dim2 int
+
+
dim3 int
+
+
+ + + + + + + + + + + + + + +

+ Deconstruct(out int, out int, out int, out int) + +

+ +
+
+ +
+
public readonly void Deconstruct(out int dim1, out int dim2, out int dim3, out int dim4)
+
+ +

Parameters

+
+
dim1 int
+
+
dim2 int
+
+
dim3 int
+
+
dim4 int
+
+
+ + + + + + + + + + + + + + +

+ Deconstruct(out int, out int, out int, out int, out int) + +

+ +
+
+ +
+
public readonly void Deconstruct(out int dim1, out int dim2, out int dim3, out int dim4, out int dim5)
+
+ +

Parameters

+
+
dim1 int
+
+
dim2 int
+
+
dim3 int
+
+
dim4 int
+
+
dim5 int
+
+
+ + + + + + + + + + + + + + +

+ Deconstruct(out int, out int, out int, out int, out int, out int) + +

+ +
+
+ +
+
public readonly void Deconstruct(out int dim1, out int dim2, out int dim3, out int dim4, out int dim5, out int dim6)
+
+ +

Parameters

+
+
dim1 int
+
+
dim2 int
+
+
dim3 int
+
+
dim4 int
+
+
dim5 int
+
+
dim6 int
+
+
+ + + + + + + + + + + + + + +

+ Empty(int) + +

+ +

An empty shape without any fields set except all are default.

+
+
+ +
+
public static Shape Empty(int ndim)
+
+ +

Parameters

+
+
ndim int
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + +

Remarks

+

Used internally.

+
+ + + + + + +

+ Equals(Shape) + +

+ +

Indicates whether the current object is equal to another object of the same type.

+
+
+ +
+
public readonly bool Equals(Shape other)
+
+ +

Parameters

+
+
other Shape
+

An object to compare with this object.

+
+
+ +

Returns

+
+
bool
+

true if the current object is equal to the other parameter; otherwise, false.

+
+
+ + + + + + + + + + + + + +

+ Equals(object) + +

+ +

Indicates whether this instance and a specified object are equal.

+
+
+ +
+
public override readonly bool Equals(object obj)
+
+ +

Parameters

+
+
obj object
+

The object to compare with the current instance.

+
+
+ +

Returns

+
+
bool
+

true if obj and this instance are the same type and represent the same value; otherwise, false.

+
+
+ + + + + + + + + + + + + +

+ ExpandDimension(int) + +

+ +

Expands a specific axis with 1 dimension.

+
+
+ +
+
[SuppressMessage("ReSharper", "LocalVariableHidesMember")]
+public readonly Shape ExpandDimension(int axis)
+
+ +

Parameters

+
+
axis int
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + + + + + + + +

+ ExtractShape(Array) + +

+ +

Extracts the shape of given array.

+
+
+ +
+
public static int[] ExtractShape(Array array)
+
+ +

Parameters

+
+
array Array
+
+
+ +

Returns

+
+
int[]
+
+
+ + + + + + + +

Remarks

+

Supports both jagged and multi-dim.

+
+ + + + + + +

+ GetAxis(Shape, int) + +

+ +
+
+ +
+
public static int[] GetAxis(Shape shape, int axis)
+
+ +

Parameters

+
+
shape Shape
+
+
axis int
+
+
+ +

Returns

+
+
int[]
+
+
+ + + + + + + + + + + + + +

+ GetAxis(ref Shape, int) + +

+ +
+
+ +
+
public static int[] GetAxis(ref Shape shape, int axis)
+
+ +

Parameters

+
+
shape Shape
+
+
axis int
+
+
+ +

Returns

+
+
int[]
+
+
+ + + + + + + + + + + + + +

+ GetAxis(int[], int) + +

+ +
+
+ +
+
public static int[] GetAxis(int[] dims, int axis)
+
+ +

Parameters

+
+
dims int[]
+
+
axis int
+
+
+ +

Returns

+
+
int[]
+
+
+ + + + + + + + + + + + + +

+ GetCoordinates(int) + +

+ +

Gets coordinates in this shape from index in this shape (slicing is ignored). +Example: Shape (2,3) +0 => [0, 0] +1 => [0, 1] +... +6 => [1, 2]

+
+
+ +
+
public readonly int[] GetCoordinates(int offset)
+
+ +

Parameters

+
+
offset int
+

the index if you would iterate from 0 to shape.size in row major order

+
+
+ +

Returns

+
+
int[]
+
+
+ + + + + + + + + + + + + +

+ GetCoordinatesFromAbsoluteIndex(int) + +

+ +

Retrievs the coordinates in current shape (potentially sliced and reshaped) from index in original array.
+Note: this is the inverse operation of GetOffset
+Example: Shape a (2,3) => sliced to b (2,2) by a[:, 1:]
+The absolute indices in a are:
+[0, 1, 2,
+3, 4, 5]
+The absolute indices in b are:
+[1, 2,
+4, 5]
+
+
+Examples:
+a.GetCoordinatesFromAbsoluteIndex(1) returns [0, 1]
+b.GetCoordinatesFromAbsoluteIndex(0) returns [0, 0]
+b.GetCoordinatesFromAbsoluteIndex(0) returns [] because it is out of shape

+
+
+ +
+
public readonly int[] GetCoordinatesFromAbsoluteIndex(int offset)
+
+ +

Parameters

+
+
offset int
+

Is the index in the original array before it was sliced and/or reshaped

+
+
+ +

Returns

+
+
int[]
+
+
+ + + + + + + +

Remarks

+

Note: due to slicing the absolute indices (offset in memory) are different from what GetCoordinates would return, which are relative indices in the shape.

+
+ + + + + + +

+ GetHashCode() + +

+ +

Serves as the default hash function.

+
+
+ +
+
public override int GetHashCode()
+
+ + +

Returns

+
+
int
+

A hash code for the current object.

+
+
+ + + + + + + + + + + + + +

+ GetOffset(int*, int) + +

+ +

Get offset index out of coordinate indices.

+
+
+ +
+
public readonly int GetOffset(int* indices, int ndims)
+
+ +

Parameters

+
+
indices int*
+

A pointer to the coordinates to turn into linear offset

+
+
ndims int
+

The number of dimensions

+
+
+ +

Returns

+
+
int
+

The index in the memory block that refers to a specific value.

+
+
+ + + + + + + +

Remarks

+

Handles sliced indices and broadcasting

+
+ + + + + + +

+ GetOffset(params int[]) + +

+ +

Get offset index out of coordinate indices.

+

The offset is the absolute offset in memory for the given coordinates. +Even for shapes that were sliced and reshaped after slicing and sliced again (and so forth) +this returns the absolute memory offset.

+

Note: the inverse operation to this is GetCoordinatesFromAbsoluteIndex

+
+
+ +
+
public readonly int GetOffset(params int[] indices)
+
+ +

Parameters

+
+
indices int[]
+

The coordinates to turn into linear offset

+
+
+ +

Returns

+
+
int
+

The index in the memory block that refers to a specific value.

+
+
+ + + + + + + +

Remarks

+

Handles sliced indices and broadcasting

+
+ + + + + + +

+ GetSize(int[]) + +

+ +
+
+ +
+
public static int GetSize(int[] dims)
+
+ +

Parameters

+
+
dims int[]
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ GetSubshape(int*, int) + +

+ +

Gets the shape based on given indicies and the index offset (C-Contiguous) inside the current storage.

+
+
+ +
+
public readonly (Shape Shape, int Offset) GetSubshape(int* dims, int ndims)
+
+ +

Parameters

+
+
dims int*
+
+
ndims int
+
+
+ +

Returns

+
+
(Shape Shape, int Offset)
+
+
+ + + + + + + +

Remarks

+

Used for slicing, returned shape is the new shape of the slice and offset is the offset from current address.

+
+ + + + + + +

+ GetSubshape(params int[]) + +

+ +

Gets the shape based on given indicies and the index offset (C-Contiguous) inside the current storage.

+
+
+ +
+
public readonly (Shape Shape, int Offset) GetSubshape(params int[] indicies)
+
+ +

Parameters

+
+
indicies int[]
+

The selection of indexes 0 based.

+
+
+ +

Returns

+
+
(Shape Shape, int Offset)
+
+
+ + + + + + + +

Remarks

+

Used for slicing, returned shape is the new shape of the slice and offset is the offset from current address.

+
+ + + + + + +

+ InferNegativeCoordinates(int[], int*, int) + +

+ +

Translates coordinates with negative indices, e.g:
+np.arange(9)[-1] == np.arange(9)[8]
+np.arange(9)[-2] == np.arange(9)[7]

+
+
+ +
+
[SuppressMessage("ReSharper", "ParameterHidesMember")]
+public static void InferNegativeCoordinates(int[] dimensions, int* coords, int coordsCount)
+
+ +

Parameters

+
+
dimensions int[]
+

The dimensions these coordinates are targeting

+
+
coords int*
+

The coordinates.

+
+
coordsCount int
+
+
+ + + + + + + + + + + + + + +

+ InferNegativeCoordinates(int[], int[]) + +

+ +

Translates coordinates with negative indices, e.g:
+np.arange(9)[-1] == np.arange(9)[8]
+np.arange(9)[-2] == np.arange(9)[7]

+
+
+ +
+
[SuppressMessage("ReSharper", "ParameterHidesMember")]
+public static int[] InferNegativeCoordinates(int[] dimensions, int[] coords)
+
+ +

Parameters

+
+
dimensions int[]
+

The dimensions these coordinates are targeting

+
+
coords int[]
+

The coordinates.

+
+
+ +

Returns

+
+
int[]
+

Coordinates without negative indices.

+
+
+ + + + + + + + + + + + + +

+ Matrix(int, int) + +

+ +

Create a shape that represents a matrix.

+
+
+ +
+
public static Shape Matrix(int rows, int cols)
+
+ +

Parameters

+
+
rows int
+
+
cols int
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + +

Remarks

+

Faster than calling Shape's constructor

+
+ + + + + + +

+ Reshape(Shape, bool) + +

+ +

Changes the shape representing this storage.

+
+
+ +
+
public readonly Shape Reshape(Shape newShape, bool @unsafe = true)
+
+ +

Parameters

+
+
newShape Shape
+
+
unsafe bool
+

When true, then guards are skipped.

+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + + +

Exceptions

+
+
IncorrectShapeException
+

If shape's size mismatches current shape size.

+
+
ArgumentException
+

If newShape's size == 0

+
+
+ + + + + +

+ SetStridesModified(bool) + +

+ +

Flag this shape as stride-modified.

+
+
+ +
+
public void SetStridesModified(bool value)
+
+ +

Parameters

+
+
value bool
+
+
+ + + + + + + + + + + + + + +

+ Slice(params Slice[]) + +

+ +
+
+ +
+
public readonly Shape Slice(params Slice[] input_slices)
+
+ +

Parameters

+
+
input_slices Slice[]
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + + + + + + + +

+ Slice(string) + +

+ +
+
+ +
+
public readonly Shape Slice(string slicing_notation)
+
+ +

Parameters

+
+
slicing_notation string
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + + + + + + + +

+ ToString() + +

+ +

Returns the fully qualified type name of this instance.

+
+
+ +
+
public override string ToString()
+
+ + +

Returns

+
+
string
+

The fully qualified type name.

+
+
+ + + + + + + + + + + + + +

+ TransformOffset(int) + +

+ +

Retrieve the transformed offset if IsSliced is true, otherwise returns offset.

+
+
+ +
+
public readonly int TransformOffset(int offset)
+
+ +

Parameters

+
+
offset int
+

The offset within the bounds of NumSharp.Shape.size.

+
+
+ +

Returns

+
+
int
+

The transformed offset.

+
+
+ + + + + + + +

Remarks

+

Avoid using unless it is unclear if shape is sliced or not.

+
+ + + + + + +

+ Vector(int) + +

+ +

Create a shape that represents a vector.

+
+
+ +
+
public static Shape Vector(int length)
+
+ +

Parameters

+
+
length int
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + +

Remarks

+

Faster than calling Shape's constructor

+
+ + + + + + +

+ Vector(int, ViewInfo) + +

+ +

Create a shape that represents a vector.

+
+
+ +
+
public static Shape Vector(int length, ViewInfo viewInfo)
+
+ +

Parameters

+
+
length int
+
+
viewInfo ViewInfo
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + +

Remarks

+

Faster than calling Shape's constructor

+
+ + + + +

Operators +

+ + + + +

+ operator ==(Shape, Shape) + +

+ +
+
+ +
+
public static bool operator ==(Shape a, Shape b)
+
+ +

Parameters

+
+
a Shape
+
+
b Shape
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ explicit operator int(Shape) + +

+ +
+
+ +
+
public static explicit operator int(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ explicit operator int[](Shape) + +

+ +
+
+ +
+
public static explicit operator int[](Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ +

Returns

+
+
int[]
+
+
+ + + + + + + + + + + + + +

+ explicit operator (int, int, int, int, int, int)(Shape) + +

+ +
+
+ +
+
public static explicit operator (int, int, int, int, int, int)(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ +

Returns

+
+
(int, int, int, int, int, int)
+
+
+ + + + + + + + + + + + + +

+ explicit operator (int, int, int, int, int)(Shape) + +

+ +
+
+ +
+
public static explicit operator (int, int, int, int, int)(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ +

Returns

+
+
(int, int, int, int, int)
+
+
+ + + + + + + + + + + + + +

+ explicit operator (int, int, int, int)(Shape) + +

+ +
+
+ +
+
public static explicit operator (int, int, int, int)(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ +

Returns

+
+
(int, int, int, int)
+
+
+ + + + + + + + + + + + + +

+ explicit operator (int, int, int)(Shape) + +

+ +
+
+ +
+
public static explicit operator (int, int, int)(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ +

Returns

+
+
(int, int, int)
+
+
+ + + + + + + + + + + + + +

+ explicit operator (int, int)(Shape) + +

+ +
+
+ +
+
public static explicit operator (int, int)(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ +

Returns

+
+
(int, int)
+
+
+ + + + + + + + + + + + + +

+ explicit operator Shape(int) + +

+ +
+
+ +
+
public static explicit operator Shape(int dim)
+
+ +

Parameters

+
+
dim int
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + + + + + + + +

+ implicit operator Shape(int[]) + +

+ +
+
+ +
+
public static implicit operator Shape(int[] dims)
+
+ +

Parameters

+
+
dims int[]
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + + + + + + + +

+ implicit operator Shape((int, int, int, int, int, int)) + +

+ +
+
+ +
+
public static implicit operator Shape((int, int, int, int, int, int) dims)
+
+ +

Parameters

+
+
dims (int, int, int, int, int, int)
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + + + + + + + +

+ implicit operator Shape((int, int, int, int, int)) + +

+ +
+
+ +
+
public static implicit operator Shape((int, int, int, int, int) dims)
+
+ +

Parameters

+
+
dims (int, int, int, int, int)
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + + + + + + + +

+ implicit operator Shape((int, int, int, int)) + +

+ +
+
+ +
+
public static implicit operator Shape((int, int, int, int) dims)
+
+ +

Parameters

+
+
dims (int, int, int, int)
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + + + + + + + +

+ implicit operator Shape((int, int, int)) + +

+ +
+
+ +
+
public static implicit operator Shape((int, int, int) dims)
+
+ +

Parameters

+
+
dims (int, int, int)
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + + + + + + + +

+ implicit operator Shape((int, int)) + +

+ +
+
+ +
+
public static implicit operator Shape((int, int) dims)
+
+ +

Parameters

+
+
dims (int, int)
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + + + + + + + +

+ operator !=(Shape, Shape) + +

+ +
+
+ +
+
public static bool operator !=(Shape a, Shape b)
+
+ +

Parameters

+
+
a Shape
+
+
b Shape
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/api/NumSharp.Shape.yml b/docs/website/api/NumSharp.Shape.yml similarity index 100% rename from docs/api/NumSharp.Shape.yml rename to docs/website/api/NumSharp.Shape.yml diff --git a/docs/website/api/NumSharp.Slice.html b/docs/website/api/NumSharp.Slice.html new file mode 100644 index 000000000..f582bf4a8 --- /dev/null +++ b/docs/website/api/NumSharp.Slice.html @@ -0,0 +1,1158 @@ + + + + + Class Slice | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class Slice +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
                                                                                                                                 <br />
+
+

NDArray can be indexed using slicing
+A slice is constructed by start:stop:step notation
+
+Examples:
+
+a[start:stop] # items start through stop-1
+a[start:] # items start through the rest of the array
+a[:stop] # items from the beginning through stop-1
+
+The key point to remember is that the :stop value represents the first value that is not
+in the selected slice. So, the difference between stop and start is the number of elements
+selected (if step is 1, the default).
+
+There is also the step value, which can be used with any of the above:
+a[:] # a copy of the whole array
+a[start:stop:step] # start through not past stop, by step
+
+The other feature is that start or stop may be a negative number, which means it counts
+from the end of the array instead of the beginning. So:
+a[-1] # last item in the array
+a[-2:] # last two items in the array
+a[:-2] # everything except the last two items
+Similarly, step may be a negative number:
+
+a[::- 1] # all items in the array, reversed
+a[1::- 1] # the first two items, reversed
+a[:-3:-1] # the last two items, reversed
+a[-3::- 1] # everything except the last two items, reversed
+
+NumSharp is kind to the programmer if there are fewer items than
+you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an
+empty list instead of an error.Sometimes you would prefer the error, so you have to be aware
+that this may happen.
+
+Adapted from Greg Hewgill's answer on Stackoverflow: https://stackoverflow.com/questions/509211/understanding-slice-notation
+
+Note: special IsIndex == true
+It will pick only a single value at Start in this dimension effectively reducing the Shape of the sliced matrix by 1 dimension.
+It can be used to reduce an N-dimensional array/matrix to a (N-1)-dimensional array/matrix
+
+Example:
+a=[[1, 2], [3, 4]]
+a[:, 1] returns the second column of that 2x2 matrix as a 1-D vector

+
+
+ +
+
public class Slice : IIndex
+
+ + + + +
+
Inheritance
+
+ +
Slice
+
+
+ +
+
Implements
+
+ +
+
+ + +
+
Inherited Members
+
+ + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ Slice(int?, int?, int) + +

+ +

ndarray can be indexed using slicing +slice is constructed by start:stop:step notation

+
+
+ +
+
public Slice(int? start = null, int? stop = null, int step = 1)
+
+ +

Parameters

+
+
start int?
+

Start index of the slice, null means from the start of the array

+
+
stop int?
+

Stop index (first index after end of slice), null means to the end of the array

+
+
step int
+

Optional step to select every n-th element, defaults to 1

+
+
+ + + + + + + + + + + + + + +

+ Slice(string) + +

+ +
+
+ +
+
public Slice(string slice_notation)
+
+ +

Parameters

+
+
slice_notation string
+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ All + +

+ +

return : for this dimension

+
+
+ +
+
public static readonly Slice All
+
+ + + + +

Field Value

+
+
Slice
+
+
+ + + + + + + + + + +

+ Ellipsis + +

+ +

fill up the missing dimensions with : at this point, corresponds to ...

+
+
+ +
+
public static readonly Slice Ellipsis
+
+ + + + +

Field Value

+
+
Slice
+
+
+ + + + + + + + + + +

+ IsEllipsis + +

+ +
+
+ +
+
public bool IsEllipsis
+
+ + + + +

Field Value

+
+
bool
+
+
+ + + + + + + + + + +

+ IsIndex + +

+ +
+
+ +
+
public bool IsIndex
+
+ + + + +

Field Value

+
+
bool
+
+
+ + + + + + + + + + +

+ IsNewAxis + +

+ +
+
+ +
+
public bool IsNewAxis
+
+ + + + +

Field Value

+
+
bool
+
+
+ + + + + + + + + + +

+ NewAxis + +

+ +

insert a new dimension at this point

+
+
+ +
+
public static readonly Slice NewAxis
+
+ + + + +

Field Value

+
+
Slice
+
+
+ + + + + + + + + + +

+ None + +

+ +

return 0:0 for this dimension

+
+
+ +
+
public static readonly Slice None
+
+ + + + +

Field Value

+
+
Slice
+
+
+ + + + + + + + + + +

+ Start + +

+ +
+
+ +
+
public int? Start
+
+ + + + +

Field Value

+
+
int?
+
+
+ + + + + + + + + + +

+ Step + +

+ +
+
+ +
+
public int Step
+
+ + + + +

Field Value

+
+
int
+
+
+ + + + + + + + + + +

+ Stop + +

+ +
+
+ +
+
public int? Stop
+
+ + + + +

Field Value

+
+
int?
+
+
+ + + + + + + + + +

Properties +

+ + + + +

+ Length + +

+ +

Length of the slice. + +The length is not guaranteed to be known for i.e. a slice like ":". Make sure to check Start and Stop +for null before using it

+
+
+ +
+
public int? Length { get; }
+
+ + + + + +

Property Value

+
+
int?
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ Equals(object) + +

+ +

Determines whether the specified object is equal to the current object.

+
+
+ +
+
public override bool Equals(object obj)
+
+ +

Parameters

+
+
obj object
+

The object to compare with the current object.

+
+
+ +

Returns

+
+
bool
+

true if the specified object is equal to the current object; otherwise, false.

+
+
+ + + + + + + + + + + + + +

+ FormatSlices(params Slice[]) + +

+ +

Creates Python array slice notation out of an array of Slice objects (mainly used for tests)

+
+
+ +
+
public static string FormatSlices(params Slice[] slices)
+
+ +

Parameters

+
+
slices Slice[]
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ GetHashCode() + +

+ +

Serves as the default hash function.

+
+
+ +
+
public override int GetHashCode()
+
+ + +

Returns

+
+
int
+

A hash code for the current object.

+
+
+ + + + + + + + + + + + + +

+ GetSize() + +

+ +
+
+ +
+
public int GetSize()
+
+ + +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ Index(int) + +

+ +

return exactly one element at this dimension and reduce the shape from n-dim to (n-1)-dim

+
+
+ +
+
public static Slice Index(int index)
+
+ +

Parameters

+
+
index int
+
+
+ +

Returns

+
+
Slice
+
+
+ + + + + + + + + + + + + +

+ ParseSlices(string) + +

+ +

Parses Python array slice notation and returns an array of Slice objects

+
+
+ +
+
public static Slice[] ParseSlices(string multi_slice_notation)
+
+ +

Parameters

+
+
multi_slice_notation string
+
+
+ +

Returns

+
+
Slice[]
+
+
+ + + + + + + + + + + + + +

+ ToSliceDef(int) + +

+ +

Converts the user Slice into an internal SliceDef which is easier to calculate with

+
+
+ +
+
public SliceDef ToSliceDef(int dim)
+
+ +

Parameters

+
+
dim int
+
+
+ +

Returns

+
+
SliceDef
+
+
+ + + + + + + + + + + + + +

+ ToString() + +

+ +

Returns a string that represents the current object.

+
+
+ +
+
public override string ToString()
+
+ + +

Returns

+
+
string
+

A string that represents the current object.

+
+
+ + + + + + + + + + + +

Operators +

+ + + + +

+ operator --(Slice) + +

+ +
+
+ +
+
public static Slice operator --(Slice a)
+
+ +

Parameters

+
+
a Slice
+
+
+ +

Returns

+
+
Slice
+
+
+ + + + + + + + + + + + + +

+ operator ==(Slice, Slice) + +

+ +
+
+ +
+
public static bool operator ==(Slice a, Slice b)
+
+ +

Parameters

+
+
a Slice
+
+
b Slice
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ implicit operator Slice(int) + +

+ +
+
+ +
+
public static implicit operator Slice(int index)
+
+ +

Parameters

+
+
index int
+
+
+ +

Returns

+
+
Slice
+
+
+ + + + + + + + + + + + + +

+ implicit operator Slice(string) + +

+ +
+
+ +
+
public static implicit operator Slice(string slice)
+
+ +

Parameters

+
+
slice string
+
+
+ +

Returns

+
+
Slice
+
+
+ + + + + + + + + + + + + +

+ operator ++(Slice) + +

+ +
+
+ +
+
public static Slice operator ++(Slice a)
+
+ +

Parameters

+
+
a Slice
+
+
+ +

Returns

+
+
Slice
+
+
+ + + + + + + + + + + + + +

+ operator !=(Slice, Slice) + +

+ +
+
+ +
+
public static bool operator !=(Slice a, Slice b)
+
+ +

Parameters

+
+
a Slice
+
+
b Slice
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/api/NumSharp.Slice.yml b/docs/website/api/NumSharp.Slice.yml similarity index 100% rename from docs/api/NumSharp.Slice.yml rename to docs/website/api/NumSharp.Slice.yml diff --git a/docs/website/api/NumSharp.SliceDef.html b/docs/website/api/NumSharp.SliceDef.html new file mode 100644 index 000000000..8934d3f31 --- /dev/null +++ b/docs/website/api/NumSharp.SliceDef.html @@ -0,0 +1,506 @@ + + + + + Struct SliceDef | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Struct SliceDef +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public struct SliceDef
+
+ + + + + + + +
+
Inherited Members
+
+ + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ SliceDef(int) + +

+ +
+
+ +
+
public SliceDef(int idx)
+
+ +

Parameters

+
+
idx int
+
+
+ + + + + + + + + + + + + + +

+ SliceDef(int, int, int) + +

+ +
+
+ +
+
public SliceDef(int start, int step, int count)
+
+ +

Parameters

+
+
start int
+
+
step int
+
+
count int
+
+
+ + + + + + + + + + + + + + +

+ SliceDef(string) + +

+ +

(Start>>Step*Count)

+
+
+ +
+
public SliceDef(string def)
+
+ +

Parameters

+
+
def string
+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ Count + +

+ +
+
+ +
+
public int Count
+
+ + + + +

Field Value

+
+
int
+
+
+ + + + + + + + + + +

+ Start + +

+ +
+
+ +
+
public int Start
+
+ + + + +

Field Value

+
+
int
+
+
+ + + + + + + + + + +

+ Step + +

+ +
+
+ +
+
public int Step
+
+ + + + +

Field Value

+
+
int
+
+
+ + + + + + + + + +

Properties +

+ + + + +

+ IsIndex + +

+ +
+
+ +
+
public bool IsIndex { get; }
+
+ + + + + +

Property Value

+
+
bool
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ Invert() + +

+ +

reverts the order of the slice sequence

+
+
+ +
+
public SliceDef Invert()
+
+ + +

Returns

+
+
SliceDef
+
+
+ + + + + + + + + + + + + +

+ Merge(SliceDef) + +

+ +

Merge calculates the resulting one-time slice on the original data if it is sliced repeatedly

+
+
+ +
+
public SliceDef Merge(SliceDef other)
+
+ +

Parameters

+
+
other SliceDef
+
+
+ +

Returns

+
+
SliceDef
+
+
+ + + + + + + + + + + + + +

+ ToString() + +

+ +

Returns the fully qualified type name of this instance.

+
+
+ +
+
public override string ToString()
+
+ + +

Returns

+
+
string
+

The fully qualified type name.

+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.StorageType.html b/docs/website/api/NumSharp.StorageType.html new file mode 100644 index 000000000..21e61f2fb --- /dev/null +++ b/docs/website/api/NumSharp.StorageType.html @@ -0,0 +1,161 @@ + + + + + Enum StorageType | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + + +

+Enum StorageType +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public enum StorageType
+
+ + + + + + + + +
+
Extension Methods
+
+ +
+ +

Fields +

+
+
Unmanaged = 0
+ +

UnmanagedByteStorage<T>

+
+
TypedArray = 1
+ +

TypedArrayStorage

+
+
+ + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.TensorEngine.html b/docs/website/api/NumSharp.TensorEngine.html new file mode 100644 index 000000000..89c655551 --- /dev/null +++ b/docs/website/api/NumSharp.TensorEngine.html @@ -0,0 +1,4258 @@ + + + + + Class TensorEngine | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class TensorEngine +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public abstract class TensorEngine
+
+ + + + +
+
Inheritance
+
+ +
TensorEngine
+
+
+ + +
+
Derived
+
+ +
+
+ +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Methods +

+ + + + +

+ ACos(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray ACos(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ACos(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray ACos(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AMax(in NDArray, int, Type, bool) + +

+ +
+
+ +
+
public abstract NDArray AMax(in NDArray nd, int axis, Type dtype, bool keepdims = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int
+
+
dtype Type
+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AMax(in NDArray, int?, NPTypeCode?, bool) + +

+ +
+
+ +
+
public abstract NDArray AMax(in NDArray nd, int? axis = null, NPTypeCode? typeCode = null, bool keepdims = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int?
+
+
typeCode NPTypeCode?
+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AMin(in NDArray, int, Type, bool) + +

+ +
+
+ +
+
public abstract NDArray AMin(in NDArray nd, int axis, Type dtype, bool keepdims = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int
+
+
dtype Type
+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ AMin(in NDArray, int?, NPTypeCode?, bool) + +

+ +
+
+ +
+
public abstract NDArray AMin(in NDArray nd, int? axis = null, NPTypeCode? typeCode = null, bool keepdims = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int?
+
+
typeCode NPTypeCode?
+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ASin(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray ASin(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ASin(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray ASin(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ATan(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray ATan(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ATan(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray ATan(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ATan2(in NDArray, in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray ATan2(in NDArray y, in NDArray x, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
y NDArray
+
+
x NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ATan2(in NDArray, in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray ATan2(in NDArray y, in NDArray x, Type dtype)
+
+ +

Parameters

+
+
y NDArray
+
+
x NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Abs(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Abs(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Abs(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Abs(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Add(in NDArray, in NDArray) + +

+ +
+
+ +
+
public abstract NDArray Add(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ All(NDArray) + +

+ +
+
+ +
+
public abstract bool All(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ All(NDArray, int) + +

+ +
+
+ +
+
public abstract NDArray<bool> All(NDArray nd, int axis)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ AllClose(NDArray, NDArray, double, double, bool) + +

+ +
+
+ +
+
public abstract bool AllClose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false)
+
+ +

Parameters

+
+
a NDArray
+
+
b NDArray
+
+
rtol double
+
+
atol double
+
+
equal_nan bool
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ArgMax(in NDArray) + +

+ +
+
+ +
+
public abstract NDArray ArgMax(in NDArray a)
+
+ +

Parameters

+
+
a NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ArgMax(in NDArray, int) + +

+ +
+
+ +
+
public abstract NDArray ArgMax(in NDArray a, int axis)
+
+ +

Parameters

+
+
a NDArray
+
+
axis int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ArgMin(in NDArray) + +

+ +
+
+ +
+
public abstract NDArray ArgMin(in NDArray a)
+
+ +

Parameters

+
+
a NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ArgMin(in NDArray, int) + +

+ +
+
+ +
+
public abstract NDArray ArgMin(in NDArray a, int axis)
+
+ +

Parameters

+
+
a NDArray
+
+
axis int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Cast(NDArray, NPTypeCode, bool) + +

+ +
+
+ +
+
public abstract NDArray Cast(NDArray x, NPTypeCode dtype, bool copy)
+
+ +

Parameters

+
+
x NDArray
+
+
dtype NPTypeCode
+
+
copy bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Cast(NDArray, Type, bool) + +

+ +
+
+ +
+
public abstract NDArray Cast(NDArray x, Type dtype, bool copy)
+
+ +

Parameters

+
+
x NDArray
+
+
dtype Type
+
+
copy bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Ceil(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Ceil(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Ceil(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Ceil(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Clip(in NDArray, in ValueType, in ValueType, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Clip(in NDArray lhs, in ValueType min, in ValueType max, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
lhs NDArray
+
+
min ValueType
+
+
max ValueType
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Clip(in NDArray, in ValueType, in ValueType, Type) + +

+ +
+
+ +
+
public abstract NDArray Clip(in NDArray lhs, in ValueType min, in ValueType max, Type dtype)
+
+ +

Parameters

+
+
lhs NDArray
+
+
min ValueType
+
+
max ValueType
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ClipNDArray(in NDArray, in NDArray, in NDArray, NPTypeCode?, NDArray) + +

+ +
+
+ +
+
public abstract NDArray ClipNDArray(in NDArray lhs, in NDArray min, in NDArray max, NPTypeCode? typeCode = null, NDArray @out = null)
+
+ +

Parameters

+
+
lhs NDArray
+
+
min NDArray
+
+
max NDArray
+
+
typeCode NPTypeCode?
+
+
out NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ClipNDArray(in NDArray, in NDArray, in NDArray, Type, NDArray) + +

+ +
+
+ +
+
public abstract NDArray ClipNDArray(in NDArray lhs, in NDArray min, in NDArray max, Type dtype, NDArray @out = null)
+
+ +

Parameters

+
+
lhs NDArray
+
+
min NDArray
+
+
max NDArray
+
+
dtype Type
+
+
out NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Compare(in NDArray, in NDArray) + +

+ +
+
+ +
+
public abstract NDArray<bool> Compare(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ Cos(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Cos(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Cos(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Cos(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Cosh(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Cosh(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Cosh(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Cosh(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ CreateNDArray(Shape, Type, IArraySlice, char) + +

+ +
+
+ +
+
public abstract NDArray CreateNDArray(Shape shape, Type dtype = null, IArraySlice buffer = null, char order = 'C')
+
+ +

Parameters

+
+
shape Shape
+
+
dtype Type
+
+
buffer IArraySlice
+
+
order char
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ CreateNDArray(Shape, Type, Array, char) + +

+ +
+
+ +
+
public abstract NDArray CreateNDArray(Shape shape, Type dtype = null, Array buffer = null, char order = 'C')
+
+ +

Parameters

+
+
shape Shape
+
+
dtype Type
+
+
buffer Array
+
+
order char
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Divide(in NDArray, in NDArray) + +

+ +
+
+ +
+
public abstract NDArray Divide(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Dot(in NDArray, in NDArray) + +

+ +
+
+ +
+
public abstract NDArray Dot(in NDArray x, in NDArray y)
+
+ +

Parameters

+
+
x NDArray
+
+
y NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Exp(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Exp(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Exp(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Exp(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Exp2(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Exp2(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Exp2(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Exp2(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Expm1(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Expm1(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Expm1(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Expm1(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Floor(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Floor(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Floor(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Floor(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ GetStorage(NPTypeCode) + +

+ +

Get storage for given typeCode.

+
+
+ +
+
public abstract UnmanagedStorage GetStorage(NPTypeCode typeCode)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+
+
+ +

Returns

+
+
UnmanagedStorage
+
+
+ + + + + + + + + + + + + +

+ GetStorage(Type) + +

+ +

Get storage for given dtype.

+
+
+ +
+
public abstract UnmanagedStorage GetStorage(Type dtype)
+
+ +

Parameters

+
+
dtype Type
+
+
+ +

Returns

+
+
UnmanagedStorage
+
+
+ + + + + + + + + + + + + +

+ IsClose(NDArray, NDArray, double, double, bool) + +

+ +
+
+ +
+
public abstract NDArray<bool> IsClose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false)
+
+ +

Parameters

+
+
a NDArray
+
+
b NDArray
+
+
rtol double
+
+
atol double
+
+
equal_nan bool
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ IsFinite(NDArray) + +

+ +
+
+ +
+
public abstract NDArray<bool> IsFinite(NDArray a)
+
+ +

Parameters

+
+
a NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ IsNan(NDArray) + +

+ +
+
+ +
+
public abstract NDArray<bool> IsNan(NDArray a)
+
+ +

Parameters

+
+
a NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+
+
+ + + + + + + + + + + + + +

+ Log(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Log(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Log(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Log(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Log10(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Log10(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Log10(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Log10(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Log1p(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Log1p(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Log1p(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Log1p(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Log2(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Log2(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Log2(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Log2(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Matmul(NDArray, NDArray) + +

+ +
+
+ +
+
public abstract NDArray Matmul(NDArray lhs, NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Mean(in NDArray, int, Type, bool) + +

+ +
+
+ +
+
public abstract NDArray Mean(in NDArray nd, int axis, Type dtype, bool keepdims = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int
+
+
dtype Type
+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Mean(in NDArray, int?, NPTypeCode?, bool) + +

+ +
+
+ +
+
public abstract NDArray Mean(in NDArray nd, int? axis = null, NPTypeCode? typeCode = null, bool keepdims = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int?
+
+
typeCode NPTypeCode?
+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Mod(in NDArray, in NDArray) + +

+ +
+
+ +
+
public abstract NDArray Mod(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ModF(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract (NDArray Fractional, NDArray Intergral) ModF(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
(NDArray Lhs, NDArray Rhs)
+
+
+ + + + + + + + + + + + + +

+ ModF(in NDArray, Type) + +

+ +
+
+ +
+
public abstract (NDArray Fractional, NDArray Intergral) ModF(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
(NDArray Lhs, NDArray Rhs)
+
+
+ + + + + + + + + + + + + +

+ MoveAxis(in NDArray, int[], int[]) + +

+ +
+
+ +
+
public abstract NDArray MoveAxis(in NDArray nd, int[] source, int[] destinition)
+
+ +

Parameters

+
+
nd NDArray
+
+
source int[]
+
+
destinition int[]
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Multiply(NDArray, NDArray) + +

+ +
+
+ +
+
public abstract NDArray Multiply(NDArray lhs, NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Negate(in NDArray) + +

+ +
+
+ +
+
public abstract NDArray Negate(in NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ NonZero(in NDArray) + +

+ +
+
+ +
+
public abstract NDArray<int>[] NonZero(in NDArray a)
+
+ +

Parameters

+
+
a NDArray
+
+
+ +

Returns

+
+
NDArray<int>[]
+
+
+ + + + + + + + + + + + + +

+ Power(in NDArray, in ValueType, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Power(in NDArray lhs, in ValueType rhs, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs ValueType
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Power(in NDArray, in ValueType, Type) + +

+ +
+
+ +
+
public abstract NDArray Power(in NDArray lhs, in ValueType rhs, Type type)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs ValueType
+
+
type Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceAMax(NDArray, int?, bool, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray ReduceAMax(NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
keepdims bool
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceAMin(NDArray, int?, bool, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray ReduceAMin(NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
keepdims bool
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceAdd(in NDArray, int?, bool, NPTypeCode?, NDArray) + +

+ +
+
+ +
+
public abstract NDArray ReduceAdd(in NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null, NDArray @out = null)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
keepdims bool
+
+
typeCode NPTypeCode?
+
+
out NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceArgMax(NDArray, int?) + +

+ +
+
+ +
+
public abstract NDArray ReduceArgMax(NDArray arr, int? axis_)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceArgMin(NDArray, int?) + +

+ +
+
+ +
+
public abstract NDArray ReduceArgMin(NDArray arr, int? axis_)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceCumAdd(in NDArray, int?, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray ReduceCumAdd(in NDArray arr, int? axis_, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceMean(in NDArray, int?, bool, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray ReduceMean(in NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
keepdims bool
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceProduct(NDArray, int?, bool, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray ReduceProduct(NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
keepdims bool
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceStd(NDArray, int?, bool, int?, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray ReduceStd(NDArray arr, int? axis_, bool keepdims = false, int? ddof = null, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
keepdims bool
+
+
ddof int?
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ ReduceVar(NDArray, int?, bool, int?, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray ReduceVar(NDArray arr, int? axis_, bool keepdims = false, int? ddof = null, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
arr NDArray
+
+
axis_ int?
+
+
keepdims bool
+
+
ddof int?
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ RollAxis(in NDArray, int, int) + +

+ +
+
+ +
+
public abstract NDArray RollAxis(in NDArray nd, int axis, int start = 0)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int
+
+
start int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Round(in NDArray, int, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Round(in NDArray nd, int decimals, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
decimals int
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Round(in NDArray, int, Type) + +

+ +
+
+ +
+
public abstract NDArray Round(in NDArray nd, int decimals, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
decimals int
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Round(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Round(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Round(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Round(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sign(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Sign(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sign(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Sign(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sin(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Sin(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sin(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Sin(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sinh(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Sinh(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sinh(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Sinh(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sqrt(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Sqrt(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sqrt(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Sqrt(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Subtract(in NDArray, in NDArray) + +

+ +
+
+ +
+
public abstract NDArray Subtract(in NDArray lhs, in NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sum(in NDArray, int, Type, bool) + +

+ +
+
+ +
+
public abstract NDArray Sum(in NDArray nd, int axis, Type dtype, bool keepdims = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int
+
+
dtype Type
+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Sum(in NDArray, int?, NPTypeCode?, bool) + +

+ +
+
+ +
+
public abstract NDArray Sum(in NDArray nd, int? axis = null, NPTypeCode? typeCode = null, bool keepdims = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int?
+
+
typeCode NPTypeCode?
+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ SwapAxes(in NDArray, int, int) + +

+ +
+
+ +
+
public abstract NDArray SwapAxes(in NDArray nd, int axis1, int axis2)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis1 int
+
+
axis2 int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Tan(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Tan(in NDArray nd, NPTypeCode? typeCod = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCod NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Tan(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Tan(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Tanh(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public abstract NDArray Tanh(in NDArray nd, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
typeCode NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Tanh(in NDArray, Type) + +

+ +
+
+ +
+
public abstract NDArray Tanh(in NDArray nd, Type dtype)
+
+ +

Parameters

+
+
nd NDArray
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ Transpose(in NDArray, int[]) + +

+ +
+
+ +
+
public abstract NDArray Transpose(in NDArray nd, int[] premute = null)
+
+ +

Parameters

+
+
nd NDArray
+
+
premute int[]
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Unmanaged.Memory.ScalarMemoryPool.html b/docs/website/api/NumSharp.Unmanaged.Memory.ScalarMemoryPool.html new file mode 100644 index 000000000..687a6493e --- /dev/null +++ b/docs/website/api/NumSharp.Unmanaged.Memory.ScalarMemoryPool.html @@ -0,0 +1,216 @@ + + + + + Class ScalarMemoryPool | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class ScalarMemoryPool +

+ +
+
Namespace
NumSharp.Unmanaged.Memory
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class ScalarMemoryPool
+
+ + + + +
+
Inheritance
+
+ +
ScalarMemoryPool
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Fields +

+ + + +

+ Instance + +

+ +
+
+ +
+
public static readonly StackedMemoryPool Instance
+
+ + + + +

Field Value

+
+
StackedMemoryPool
+
+
+ + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Unmanaged.Memory.StackedMemoryPool.html b/docs/website/api/NumSharp.Unmanaged.Memory.StackedMemoryPool.html new file mode 100644 index 000000000..aa27d0d01 --- /dev/null +++ b/docs/website/api/NumSharp.Unmanaged.Memory.StackedMemoryPool.html @@ -0,0 +1,628 @@ + + + + + Class StackedMemoryPool | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class StackedMemoryPool +

+ +
+
Namespace
NumSharp.Unmanaged.Memory
+
Assembly
NumSharp.dll
+
+ +

Pool of allocated buffers managed by internal garbage collection mechanism.

+
+
+ +
+
public class StackedMemoryPool : IDisposable
+
+ + + + +
+
Inheritance
+
+ +
StackedMemoryPool
+
+
+ +
+
Implements
+
+ +
+
+ + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + +

Remarks

+

Used to speed up scalar allocation. Thread-safe.

+
+ + +

Constructors +

+ + + + +

+ StackedMemoryPool(int) + +

+ +
+
+ +
+
public StackedMemoryPool(int totalSize)
+
+ +

Parameters

+
+
totalSize int
+
+
+ + + + + + + + + + + + + + +

+ StackedMemoryPool(int, int) + +

+ +
+
+ +
+
public StackedMemoryPool(int singleSize, int count)
+
+ +

Parameters

+
+
singleSize int
+
+
count int
+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ GarbageCollectionDelay + +

+ +

After how many milliseconds should unused excess memory be deallocated. (only if allocated exceeded above 133% of firstly allocated).
+Default: 5000ms.

+
+
+ +
+
public int GarbageCollectionDelay
+
+ + + + +

Field Value

+
+
int
+
+
+ + + + + + + + + + +

+ SingleSize + +

+ +
+
+ +
+
public readonly int SingleSize
+
+ + + + +

Field Value

+
+
int
+
+
+ + + + + + + + + +

Properties +

+ + + + +

+ Available + +

+ +

How many pointers are currently preallocated and available for the taking.

+
+
+ +
+
public long Available { get; }
+
+ + + + + +

Property Value

+
+
long
+
+
+ + + + + + + + + + +

+ TotalAllocated + +

+ +

How many Scalar pointers are allocated.

+
+
+ +
+
public long TotalAllocated { get; }
+
+ + + + + +

Property Value

+
+
long
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ AllocateBytes(long) + +

+ +
+
+ +
+
public void AllocateBytes(long bytes)
+
+ +

Parameters

+
+
bytes long
+
+
+ + + + + + + + + + + + + + +

+ AllocateCount(long) + +

+ +
+
+ +
+
public void AllocateCount(long count)
+
+ +

Parameters

+
+
count long
+
+
+ + + + + + + + + + + + + + +

+ Dispose() + +

+ +

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

+
+
+ +
+
public void Dispose()
+
+ + + + + + + + + + + + + + + +

+ ~StackedMemoryPool() + +

+ +
+
+ +
+
protected ~StackedMemoryPool()
+
+ + + + + + + + + + + + + + + +

+ Return(nint) + +

+ +
+
+ +
+
public void Return(nint x)
+
+ +

Parameters

+
+
x nint
+
+
+ + + + + + + + + + + + + + +

+ Take() + +

+ +
+
+ +
+
public nint Take()
+
+ + +

Returns

+
+
nint
+
+
+ + + + + + + + + + + + + +

+ TrimExcess() + +

+ +
+
+ +
+
public void TrimExcess()
+
+ + + + + + + + + + + + + + + +

+ UpdateGarbageCollectionThreshold() + +

+ +

Set the point of GC activation to the current TotalAllocated multiplied by 1.33.

+
+
+ +
+
public void UpdateGarbageCollectionThreshold()
+
+ + + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Unmanaged.Memory.html b/docs/website/api/NumSharp.Unmanaged.Memory.html new file mode 100644 index 000000000..5b1d0eeaf --- /dev/null +++ b/docs/website/api/NumSharp.Unmanaged.Memory.html @@ -0,0 +1,131 @@ + + + + + Namespace NumSharp.Unmanaged.Memory | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ +

Namespace NumSharp.Unmanaged.Memory

+
+
+
+ +

+Classes +

+
+
ScalarMemoryPool
+
+
+
+
StackedMemoryPool
+

Pool of allocated buffers managed by internal garbage collection mechanism.

+
+
+ + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.ArrayConvert.html b/docs/website/api/NumSharp.Utilities.ArrayConvert.html new file mode 100644 index 000000000..4d235035f --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.ArrayConvert.html @@ -0,0 +1,8219 @@ + + + + + Class ArrayConvert | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class ArrayConvert +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +

Presents all possible combinations of array conversion of types supported by numpy.

+
+
+ +
+
public static class ArrayConvert
+
+ + + + +
+
Inheritance
+
+ +
ArrayConvert
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + +

Remarks

+ + + +

Methods +

+ + + + +

+ Clone(Array) + +

+ +

Creates a clone of given sourceArray.

+
+
+ +
+
public static Array Clone(Array sourceArray)
+
+ +

Parameters

+
+
sourceArray Array
+

The array to clone

+
+
+ +

Returns

+
+
Array
+
+
+ + + + + + + +

Remarks

+

If possible, for performance reasons use generic version of this method.

+
+ + + + + + +

+ Clone<T>(T[,,,]) + +

+ +

Creates a clone of given sourceArray using CopyTo(Array, int).

+
+
+ +
+
public static T[,,,] Clone<T>(T[,,,] sourceArray)
+
+ +

Parameters

+
+
sourceArray T[,,,]
+

The array to clone

+
+
+ +

Returns

+
+
T[,,,]
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Clone<T>(T[,,]) + +

+ +

Creates a clone of given sourceArray using CopyTo(Array, int).

+
+
+ +
+
public static T[,,] Clone<T>(T[,,] sourceArray)
+
+ +

Parameters

+
+
sourceArray T[,,]
+

The array to clone

+
+
+ +

Returns

+
+
T[,,]
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Clone<T>(T[,]) + +

+ +

Creates a clone of given sourceArray using CopyTo(Array, int).

+
+
+ +
+
public static T[,] Clone<T>(T[,] sourceArray)
+
+ +

Parameters

+
+
sourceArray T[,]
+

The array to clone

+
+
+ +

Returns

+
+
T[,]
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Clone<T>(T[]) + +

+ +

Creates a clone of given sourceArray.

+
+
+ +
+
public static T[] Clone<T>(T[] sourceArray)
+
+ +

Parameters

+
+
sourceArray T[]
+

The array to clone

+
+
+ +

Returns

+
+
T[]
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ To(Array, NPTypeCode) + +

+ +

Converts sourceArray to an array of type typeCode.

+
+
+ +
+
public static Array To(Array sourceArray, NPTypeCode typeCode)
+
+ +

Parameters

+
+
sourceArray Array
+

The array to convert

+
+
typeCode NPTypeCode
+

The type to convert the data to

+
+
+ +

Returns

+
+
Array
+
+
+ + + + + + + +

Remarks

+

If sourceArray's element type equals to typeCode then a copy is returned

+
+ + + + + + +

+ To(Array, Type) + +

+ +

Converts sourceArray to an array of type returnType.

+
+
+ +
+
public static Array To(Array sourceArray, Type returnType)
+
+ +

Parameters

+
+
sourceArray Array
+

The array to convert

+
+
returnType Type
+

The type to convert the data to

+
+
+ +

Returns

+
+
Array
+
+
+ + + + + + + +

Remarks

+

If sourceArray's element type equals to returnType then a copy is returned

+
+ + + + + + +

+ ToBoolean(Array) + +

+ +
+
+ +
+
public static bool[] ToBoolean(Array sourceArray)
+
+ +

Parameters

+
+
sourceArray Array
+
+
+ +

Returns

+
+
bool[]
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(bool[]) + +

+ +

Converts bool array to a bool array.

+
+
+ +
+
public static bool[] ToBoolean(bool[] sourceArray)
+
+ +

Parameters

+
+
sourceArray bool[]
+

The array to convert

+
+
+ +

Returns

+
+
bool[]
+

Converted array of type Boolean

+
+
+ + + + + + + +

Remarks

+

Based on benchmark ArrayCopying

+
+ + + + + + +

+ ToBoolean(byte[]) + +

+ +

Converts byte array to a bool array.

+
+
+ +
+
public static bool[] ToBoolean(byte[] sourceArray)
+
+ +

Parameters

+
+
sourceArray byte[]
+

The array to convert

+
+
+ +

Returns

+
+
bool[]
+

Converted array of type Boolean

+
+
+ + + + + + + + + + + + + +

+ ToBoolean(char[]) + +

+ +

Converts char array to a bool array.

+
+
+ +
+
public static bool[] ToBoolean(char[] sourceArray)
+
+ +

Parameters

+
+
sourceArray char[]
+

The array to convert

+
+
+ +

Returns

+
+
bool[]
+

Converted array of type Boolean

+
+
+ + + + + + + + + + + + + +

+ ToBoolean(decimal[]) + +

+ +

Converts decimal array to a bool array.

+
+
+ +
+
public static bool[] ToBoolean(decimal[] sourceArray)
+
+ +

Parameters

+
+
sourceArray decimal[]
+

The array to convert

+
+
+ +

Returns

+
+
bool[]
+

Converted array of type Boolean

+
+
+ + + + + + + + + + + + + +

+ ToBoolean(double[]) + +

+ +

Converts double array to a bool array.

+
+
+ +
+
public static bool[] ToBoolean(double[] sourceArray)
+
+ +

Parameters

+
+
sourceArray double[]
+

The array to convert

+
+
+ +

Returns

+
+
bool[]
+

Converted array of type Boolean

+
+
+ + + + + + + + + + + + + +

+ ToBoolean(short[]) + +

+ +

Converts short array to a bool array.

+
+
+ +
+
public static bool[] ToBoolean(short[] sourceArray)
+
+ +

Parameters

+
+
sourceArray short[]
+

The array to convert

+
+
+ +

Returns

+
+
bool[]
+

Converted array of type Boolean

+
+
+ + + + + + + + + + + + + +

+ ToBoolean(int[]) + +

+ +

Converts int array to a bool array.

+
+
+ +
+
public static bool[] ToBoolean(int[] sourceArray)
+
+ +

Parameters

+
+
sourceArray int[]
+

The array to convert

+
+
+ +

Returns

+
+
bool[]
+

Converted array of type Boolean

+
+
+ + + + + + + + + + + + + +

+ ToBoolean(long[]) + +

+ +

Converts long array to a bool array.

+
+
+ +
+
public static bool[] ToBoolean(long[] sourceArray)
+
+ +

Parameters

+
+
sourceArray long[]
+

The array to convert

+
+
+ +

Returns

+
+
bool[]
+

Converted array of type Boolean

+
+
+ + + + + + + + + + + + + +

+ ToBoolean(float[]) + +

+ +

Converts float array to a bool array.

+
+
+ +
+
public static bool[] ToBoolean(float[] sourceArray)
+
+ +

Parameters

+
+
sourceArray float[]
+

The array to convert

+
+
+ +

Returns

+
+
bool[]
+

Converted array of type Boolean

+
+
+ + + + + + + + + + + + + +

+ ToBoolean(string[]) + +

+ +

Converts string array to a bool array.

+
+
+ +
+
public static bool[] ToBoolean(string[] sourceArray)
+
+ +

Parameters

+
+
sourceArray string[]
+

The array to convert

+
+
+ +

Returns

+
+
bool[]
+

Converted array of type Boolean

+
+
+ + + + + + + + + + + + + +

+ ToBoolean(ushort[]) + +

+ +

Converts ushort array to a bool array.

+
+
+ +
+
public static bool[] ToBoolean(ushort[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ushort[]
+

The array to convert

+
+
+ +

Returns

+
+
bool[]
+

Converted array of type Boolean

+
+
+ + + + + + + + + + + + + +

+ ToBoolean(uint[]) + +

+ +

Converts uint array to a bool array.

+
+
+ +
+
public static bool[] ToBoolean(uint[] sourceArray)
+
+ +

Parameters

+
+
sourceArray uint[]
+

The array to convert

+
+
+ +

Returns

+
+
bool[]
+

Converted array of type Boolean

+
+
+ + + + + + + + + + + + + +

+ ToBoolean(ulong[]) + +

+ +

Converts ulong array to a bool array.

+
+
+ +
+
public static bool[] ToBoolean(ulong[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ulong[]
+

The array to convert

+
+
+ +

Returns

+
+
bool[]
+

Converted array of type Boolean

+
+
+ + + + + + + + + + + + + +

+ ToByte(Array) + +

+ +
+
+ +
+
public static byte[] ToByte(Array sourceArray)
+
+ +

Parameters

+
+
sourceArray Array
+
+
+ +

Returns

+
+
byte[]
+
+
+ + + + + + + + + + + + + +

+ ToByte(bool[]) + +

+ +

Converts bool array to a byte array.

+
+
+ +
+
public static byte[] ToByte(bool[] sourceArray)
+
+ +

Parameters

+
+
sourceArray bool[]
+

The array to convert

+
+
+ +

Returns

+
+
byte[]
+

Converted array of type Byte

+
+
+ + + + + + + + + + + + + +

+ ToByte(byte[]) + +

+ +

Converts byte array to a byte array.

+
+
+ +
+
public static byte[] ToByte(byte[] sourceArray)
+
+ +

Parameters

+
+
sourceArray byte[]
+

The array to convert

+
+
+ +

Returns

+
+
byte[]
+

Converted array of type Byte

+
+
+ + + + + + + +

Remarks

+

Based on benchmark ArrayCopying

+
+ + + + + + +

+ ToByte(char[]) + +

+ +

Converts char array to a byte array.

+
+
+ +
+
public static byte[] ToByte(char[] sourceArray)
+
+ +

Parameters

+
+
sourceArray char[]
+

The array to convert

+
+
+ +

Returns

+
+
byte[]
+

Converted array of type Byte

+
+
+ + + + + + + + + + + + + +

+ ToByte(decimal[]) + +

+ +

Converts decimal array to a byte array.

+
+
+ +
+
public static byte[] ToByte(decimal[] sourceArray)
+
+ +

Parameters

+
+
sourceArray decimal[]
+

The array to convert

+
+
+ +

Returns

+
+
byte[]
+

Converted array of type Byte

+
+
+ + + + + + + + + + + + + +

+ ToByte(double[]) + +

+ +

Converts double array to a byte array.

+
+
+ +
+
public static byte[] ToByte(double[] sourceArray)
+
+ +

Parameters

+
+
sourceArray double[]
+

The array to convert

+
+
+ +

Returns

+
+
byte[]
+

Converted array of type Byte

+
+
+ + + + + + + + + + + + + +

+ ToByte(short[]) + +

+ +

Converts short array to a byte array.

+
+
+ +
+
public static byte[] ToByte(short[] sourceArray)
+
+ +

Parameters

+
+
sourceArray short[]
+

The array to convert

+
+
+ +

Returns

+
+
byte[]
+

Converted array of type Byte

+
+
+ + + + + + + + + + + + + +

+ ToByte(int[]) + +

+ +

Converts int array to a byte array.

+
+
+ +
+
public static byte[] ToByte(int[] sourceArray)
+
+ +

Parameters

+
+
sourceArray int[]
+

The array to convert

+
+
+ +

Returns

+
+
byte[]
+

Converted array of type Byte

+
+
+ + + + + + + + + + + + + +

+ ToByte(long[]) + +

+ +

Converts long array to a byte array.

+
+
+ +
+
public static byte[] ToByte(long[] sourceArray)
+
+ +

Parameters

+
+
sourceArray long[]
+

The array to convert

+
+
+ +

Returns

+
+
byte[]
+

Converted array of type Byte

+
+
+ + + + + + + + + + + + + +

+ ToByte(float[]) + +

+ +

Converts float array to a byte array.

+
+
+ +
+
public static byte[] ToByte(float[] sourceArray)
+
+ +

Parameters

+
+
sourceArray float[]
+

The array to convert

+
+
+ +

Returns

+
+
byte[]
+

Converted array of type Byte

+
+
+ + + + + + + + + + + + + +

+ ToByte(string[]) + +

+ +

Converts string array to a byte array.

+
+
+ +
+
public static byte[] ToByte(string[] sourceArray)
+
+ +

Parameters

+
+
sourceArray string[]
+

The array to convert

+
+
+ +

Returns

+
+
byte[]
+

Converted array of type Byte

+
+
+ + + + + + + + + + + + + +

+ ToByte(ushort[]) + +

+ +

Converts ushort array to a byte array.

+
+
+ +
+
public static byte[] ToByte(ushort[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ushort[]
+

The array to convert

+
+
+ +

Returns

+
+
byte[]
+

Converted array of type Byte

+
+
+ + + + + + + + + + + + + +

+ ToByte(uint[]) + +

+ +

Converts uint array to a byte array.

+
+
+ +
+
public static byte[] ToByte(uint[] sourceArray)
+
+ +

Parameters

+
+
sourceArray uint[]
+

The array to convert

+
+
+ +

Returns

+
+
byte[]
+

Converted array of type Byte

+
+
+ + + + + + + + + + + + + +

+ ToByte(ulong[]) + +

+ +

Converts ulong array to a byte array.

+
+
+ +
+
public static byte[] ToByte(ulong[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ulong[]
+

The array to convert

+
+
+ +

Returns

+
+
byte[]
+

Converted array of type Byte

+
+
+ + + + + + + + + + + + + +

+ ToChar(Array) + +

+ +
+
+ +
+
public static char[] ToChar(Array sourceArray)
+
+ +

Parameters

+
+
sourceArray Array
+
+
+ +

Returns

+
+
char[]
+
+
+ + + + + + + + + + + + + +

+ ToChar(bool[]) + +

+ +

Converts bool array to a char array.

+
+
+ +
+
public static char[] ToChar(bool[] sourceArray)
+
+ +

Parameters

+
+
sourceArray bool[]
+

The array to convert

+
+
+ +

Returns

+
+
char[]
+

Converted array of type Char

+
+
+ + + + + + + + + + + + + +

+ ToChar(byte[]) + +

+ +

Converts byte array to a char array.

+
+
+ +
+
public static char[] ToChar(byte[] sourceArray)
+
+ +

Parameters

+
+
sourceArray byte[]
+

The array to convert

+
+
+ +

Returns

+
+
char[]
+

Converted array of type Char

+
+
+ + + + + + + + + + + + + +

+ ToChar(char[]) + +

+ +

Converts char array to a char array.

+
+
+ +
+
public static char[] ToChar(char[] sourceArray)
+
+ +

Parameters

+
+
sourceArray char[]
+

The array to convert

+
+
+ +

Returns

+
+
char[]
+

Converted array of type Char

+
+
+ + + + + + + +

Remarks

+

Based on benchmark ArrayCopying

+
+ + + + + + +

+ ToChar(decimal[]) + +

+ +

Converts decimal array to a char array.

+
+
+ +
+
public static char[] ToChar(decimal[] sourceArray)
+
+ +

Parameters

+
+
sourceArray decimal[]
+

The array to convert

+
+
+ +

Returns

+
+
char[]
+

Converted array of type Char

+
+
+ + + + + + + + + + + + + +

+ ToChar(double[]) + +

+ +

Converts double array to a char array.

+
+
+ +
+
public static char[] ToChar(double[] sourceArray)
+
+ +

Parameters

+
+
sourceArray double[]
+

The array to convert

+
+
+ +

Returns

+
+
char[]
+

Converted array of type Char

+
+
+ + + + + + + + + + + + + +

+ ToChar(short[]) + +

+ +

Converts short array to a char array.

+
+
+ +
+
public static char[] ToChar(short[] sourceArray)
+
+ +

Parameters

+
+
sourceArray short[]
+

The array to convert

+
+
+ +

Returns

+
+
char[]
+

Converted array of type Char

+
+
+ + + + + + + + + + + + + +

+ ToChar(int[]) + +

+ +

Converts int array to a char array.

+
+
+ +
+
public static char[] ToChar(int[] sourceArray)
+
+ +

Parameters

+
+
sourceArray int[]
+

The array to convert

+
+
+ +

Returns

+
+
char[]
+

Converted array of type Char

+
+
+ + + + + + + + + + + + + +

+ ToChar(long[]) + +

+ +

Converts long array to a char array.

+
+
+ +
+
public static char[] ToChar(long[] sourceArray)
+
+ +

Parameters

+
+
sourceArray long[]
+

The array to convert

+
+
+ +

Returns

+
+
char[]
+

Converted array of type Char

+
+
+ + + + + + + + + + + + + +

+ ToChar(float[]) + +

+ +

Converts float array to a char array.

+
+
+ +
+
public static char[] ToChar(float[] sourceArray)
+
+ +

Parameters

+
+
sourceArray float[]
+

The array to convert

+
+
+ +

Returns

+
+
char[]
+

Converted array of type Char

+
+
+ + + + + + + + + + + + + +

+ ToChar(string[]) + +

+ +

Converts string array to a char array.

+
+
+ +
+
public static char[] ToChar(string[] sourceArray)
+
+ +

Parameters

+
+
sourceArray string[]
+

The array to convert

+
+
+ +

Returns

+
+
char[]
+

Converted array of type Char

+
+
+ + + + + + + + + + + + + +

+ ToChar(ushort[]) + +

+ +

Converts ushort array to a char array.

+
+
+ +
+
public static char[] ToChar(ushort[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ushort[]
+

The array to convert

+
+
+ +

Returns

+
+
char[]
+

Converted array of type Char

+
+
+ + + + + + + + + + + + + +

+ ToChar(uint[]) + +

+ +

Converts uint array to a char array.

+
+
+ +
+
public static char[] ToChar(uint[] sourceArray)
+
+ +

Parameters

+
+
sourceArray uint[]
+

The array to convert

+
+
+ +

Returns

+
+
char[]
+

Converted array of type Char

+
+
+ + + + + + + + + + + + + +

+ ToChar(ulong[]) + +

+ +

Converts ulong array to a char array.

+
+
+ +
+
public static char[] ToChar(ulong[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ulong[]
+

The array to convert

+
+
+ +

Returns

+
+
char[]
+

Converted array of type Char

+
+
+ + + + + + + + + + + + + +

+ ToComplex(Array) + +

+ +
+
+ +
+
public static Complex[] ToComplex(Array sourceArray)
+
+ +

Parameters

+
+
sourceArray Array
+
+
+ +

Returns

+
+
Complex[]
+
+
+ + + + + + + + + + + + + +

+ ToComplex(bool[]) + +

+ +

Converts bool array to a Complex array.

+
+
+ +
+
public static Complex[] ToComplex(bool[] sourceArray)
+
+ +

Parameters

+
+
sourceArray bool[]
+

The array to convert

+
+
+ +

Returns

+
+
Complex[]
+

Converted array of type Complex

+
+
+ + + + + + + + + + + + + +

+ ToComplex(byte[]) + +

+ +

Converts byte array to a Complex array.

+
+
+ +
+
public static Complex[] ToComplex(byte[] sourceArray)
+
+ +

Parameters

+
+
sourceArray byte[]
+

The array to convert

+
+
+ +

Returns

+
+
Complex[]
+

Converted array of type Complex

+
+
+ + + + + + + + + + + + + +

+ ToComplex(char[]) + +

+ +

Converts char array to a Complex array.

+
+
+ +
+
public static Complex[] ToComplex(char[] sourceArray)
+
+ +

Parameters

+
+
sourceArray char[]
+

The array to convert

+
+
+ +

Returns

+
+
Complex[]
+

Converted array of type Complex

+
+
+ + + + + + + + + + + + + +

+ ToComplex(decimal[]) + +

+ +

Converts decimal array to a Complex array.

+
+
+ +
+
public static Complex[] ToComplex(decimal[] sourceArray)
+
+ +

Parameters

+
+
sourceArray decimal[]
+

The array to convert

+
+
+ +

Returns

+
+
Complex[]
+

Converted array of type Complex

+
+
+ + + + + + + + + + + + + +

+ ToComplex(double[]) + +

+ +

Converts double array to a Complex array.

+
+
+ +
+
public static Complex[] ToComplex(double[] sourceArray)
+
+ +

Parameters

+
+
sourceArray double[]
+

The array to convert

+
+
+ +

Returns

+
+
Complex[]
+

Converted array of type Complex

+
+
+ + + + + + + + + + + + + +

+ ToComplex(short[]) + +

+ +

Converts short array to a Complex array.

+
+
+ +
+
public static Complex[] ToComplex(short[] sourceArray)
+
+ +

Parameters

+
+
sourceArray short[]
+

The array to convert

+
+
+ +

Returns

+
+
Complex[]
+

Converted array of type Complex

+
+
+ + + + + + + + + + + + + +

+ ToComplex(int[]) + +

+ +

Converts int array to a Complex array.

+
+
+ +
+
public static Complex[] ToComplex(int[] sourceArray)
+
+ +

Parameters

+
+
sourceArray int[]
+

The array to convert

+
+
+ +

Returns

+
+
Complex[]
+

Converted array of type Complex

+
+
+ + + + + + + + + + + + + +

+ ToComplex(long[]) + +

+ +

Converts long array to a Complex array.

+
+
+ +
+
public static Complex[] ToComplex(long[] sourceArray)
+
+ +

Parameters

+
+
sourceArray long[]
+

The array to convert

+
+
+ +

Returns

+
+
Complex[]
+

Converted array of type Complex

+
+
+ + + + + + + + + + + + + +

+ ToComplex(Complex[]) + +

+ +

Converts Complex array to a Complex array.

+
+
+ +
+
public static Complex[] ToComplex(Complex[] sourceArray)
+
+ +

Parameters

+
+
sourceArray Complex[]
+

The array to convert

+
+
+ +

Returns

+
+
Complex[]
+

Converted array of type Complex

+
+
+ + + + + + + +

Remarks

+

Based on benchmark ArrayCopying

+
+ + + + + + +

+ ToComplex(float[]) + +

+ +

Converts float array to a Complex array.

+
+
+ +
+
public static Complex[] ToComplex(float[] sourceArray)
+
+ +

Parameters

+
+
sourceArray float[]
+

The array to convert

+
+
+ +

Returns

+
+
Complex[]
+

Converted array of type Complex

+
+
+ + + + + + + + + + + + + +

+ ToComplex(string[]) + +

+ +

Converts string array to a Complex array.

+
+
+ +
+
public static Complex[] ToComplex(string[] sourceArray)
+
+ +

Parameters

+
+
sourceArray string[]
+

The array to convert

+
+
+ +

Returns

+
+
Complex[]
+

Converted array of type Complex

+
+
+ + + + + + + + +

Exceptions

+
+
FormatException
+

A string in sourceArray has an invalid complex format

+
+
+ + + + + +

+ ToComplex(ushort[]) + +

+ +

Converts ushort array to a Complex array.

+
+
+ +
+
public static Complex[] ToComplex(ushort[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ushort[]
+

The array to convert

+
+
+ +

Returns

+
+
Complex[]
+

Converted array of type Complex

+
+
+ + + + + + + + + + + + + +

+ ToComplex(uint[]) + +

+ +

Converts uint array to a Complex array.

+
+
+ +
+
public static Complex[] ToComplex(uint[] sourceArray)
+
+ +

Parameters

+
+
sourceArray uint[]
+

The array to convert

+
+
+ +

Returns

+
+
Complex[]
+

Converted array of type Complex

+
+
+ + + + + + + + + + + + + +

+ ToComplex(ulong[]) + +

+ +

Converts ulong array to a Complex array.

+
+
+ +
+
public static Complex[] ToComplex(ulong[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ulong[]
+

The array to convert

+
+
+ +

Returns

+
+
Complex[]
+

Converted array of type Complex

+
+
+ + + + + + + + + + + + + +

+ ToDecimal(Array) + +

+ +
+
+ +
+
public static decimal[] ToDecimal(Array sourceArray)
+
+ +

Parameters

+
+
sourceArray Array
+
+
+ +

Returns

+
+
decimal[]
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(bool[]) + +

+ +

Converts bool array to a decimal array.

+
+
+ +
+
public static decimal[] ToDecimal(bool[] sourceArray)
+
+ +

Parameters

+
+
sourceArray bool[]
+

The array to convert

+
+
+ +

Returns

+
+
decimal[]
+

Converted array of type Decimal

+
+
+ + + + + + + + + + + + + +

+ ToDecimal(byte[]) + +

+ +

Converts byte array to a decimal array.

+
+
+ +
+
public static decimal[] ToDecimal(byte[] sourceArray)
+
+ +

Parameters

+
+
sourceArray byte[]
+

The array to convert

+
+
+ +

Returns

+
+
decimal[]
+

Converted array of type Decimal

+
+
+ + + + + + + + + + + + + +

+ ToDecimal(char[]) + +

+ +

Converts char array to a decimal array.

+
+
+ +
+
public static decimal[] ToDecimal(char[] sourceArray)
+
+ +

Parameters

+
+
sourceArray char[]
+

The array to convert

+
+
+ +

Returns

+
+
decimal[]
+

Converted array of type Decimal

+
+
+ + + + + + + + + + + + + +

+ ToDecimal(decimal[]) + +

+ +

Converts decimal array to a decimal array.

+
+
+ +
+
public static decimal[] ToDecimal(decimal[] sourceArray)
+
+ +

Parameters

+
+
sourceArray decimal[]
+

The array to convert

+
+
+ +

Returns

+
+
decimal[]
+

Converted array of type Decimal

+
+
+ + + + + + + +

Remarks

+

Based on benchmark ArrayCopying

+
+ + + + + + +

+ ToDecimal(double[]) + +

+ +

Converts double array to a decimal array.

+
+
+ +
+
public static decimal[] ToDecimal(double[] sourceArray)
+
+ +

Parameters

+
+
sourceArray double[]
+

The array to convert

+
+
+ +

Returns

+
+
decimal[]
+

Converted array of type Decimal

+
+
+ + + + + + + + + + + + + +

+ ToDecimal(short[]) + +

+ +

Converts short array to a decimal array.

+
+
+ +
+
public static decimal[] ToDecimal(short[] sourceArray)
+
+ +

Parameters

+
+
sourceArray short[]
+

The array to convert

+
+
+ +

Returns

+
+
decimal[]
+

Converted array of type Decimal

+
+
+ + + + + + + + + + + + + +

+ ToDecimal(int[]) + +

+ +

Converts int array to a decimal array.

+
+
+ +
+
public static decimal[] ToDecimal(int[] sourceArray)
+
+ +

Parameters

+
+
sourceArray int[]
+

The array to convert

+
+
+ +

Returns

+
+
decimal[]
+

Converted array of type Decimal

+
+
+ + + + + + + + + + + + + +

+ ToDecimal(long[]) + +

+ +

Converts long array to a decimal array.

+
+
+ +
+
public static decimal[] ToDecimal(long[] sourceArray)
+
+ +

Parameters

+
+
sourceArray long[]
+

The array to convert

+
+
+ +

Returns

+
+
decimal[]
+

Converted array of type Decimal

+
+
+ + + + + + + + + + + + + +

+ ToDecimal(float[]) + +

+ +

Converts float array to a decimal array.

+
+
+ +
+
public static decimal[] ToDecimal(float[] sourceArray)
+
+ +

Parameters

+
+
sourceArray float[]
+

The array to convert

+
+
+ +

Returns

+
+
decimal[]
+

Converted array of type Decimal

+
+
+ + + + + + + + + + + + + +

+ ToDecimal(string[]) + +

+ +

Converts string array to a decimal array.

+
+
+ +
+
public static decimal[] ToDecimal(string[] sourceArray)
+
+ +

Parameters

+
+
sourceArray string[]
+

The array to convert

+
+
+ +

Returns

+
+
decimal[]
+

Converted array of type Decimal

+
+
+ + + + + + + + + + + + + +

+ ToDecimal(ushort[]) + +

+ +

Converts ushort array to a decimal array.

+
+
+ +
+
public static decimal[] ToDecimal(ushort[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ushort[]
+

The array to convert

+
+
+ +

Returns

+
+
decimal[]
+

Converted array of type Decimal

+
+
+ + + + + + + + + + + + + +

+ ToDecimal(uint[]) + +

+ +

Converts uint array to a decimal array.

+
+
+ +
+
public static decimal[] ToDecimal(uint[] sourceArray)
+
+ +

Parameters

+
+
sourceArray uint[]
+

The array to convert

+
+
+ +

Returns

+
+
decimal[]
+

Converted array of type Decimal

+
+
+ + + + + + + + + + + + + +

+ ToDecimal(ulong[]) + +

+ +

Converts ulong array to a decimal array.

+
+
+ +
+
public static decimal[] ToDecimal(ulong[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ulong[]
+

The array to convert

+
+
+ +

Returns

+
+
decimal[]
+

Converted array of type Decimal

+
+
+ + + + + + + + + + + + + +

+ ToDouble(Array) + +

+ +
+
+ +
+
public static double[] ToDouble(Array sourceArray)
+
+ +

Parameters

+
+
sourceArray Array
+
+
+ +

Returns

+
+
double[]
+
+
+ + + + + + + + + + + + + +

+ ToDouble(bool[]) + +

+ +

Converts bool array to a double array.

+
+
+ +
+
public static double[] ToDouble(bool[] sourceArray)
+
+ +

Parameters

+
+
sourceArray bool[]
+

The array to convert

+
+
+ +

Returns

+
+
double[]
+

Converted array of type Double

+
+
+ + + + + + + + + + + + + +

+ ToDouble(byte[]) + +

+ +

Converts byte array to a double array.

+
+
+ +
+
public static double[] ToDouble(byte[] sourceArray)
+
+ +

Parameters

+
+
sourceArray byte[]
+

The array to convert

+
+
+ +

Returns

+
+
double[]
+

Converted array of type Double

+
+
+ + + + + + + + + + + + + +

+ ToDouble(char[]) + +

+ +

Converts char array to a double array.

+
+
+ +
+
public static double[] ToDouble(char[] sourceArray)
+
+ +

Parameters

+
+
sourceArray char[]
+

The array to convert

+
+
+ +

Returns

+
+
double[]
+

Converted array of type Double

+
+
+ + + + + + + + + + + + + +

+ ToDouble(decimal[]) + +

+ +

Converts decimal array to a double array.

+
+
+ +
+
public static double[] ToDouble(decimal[] sourceArray)
+
+ +

Parameters

+
+
sourceArray decimal[]
+

The array to convert

+
+
+ +

Returns

+
+
double[]
+

Converted array of type Double

+
+
+ + + + + + + + + + + + + +

+ ToDouble(double[]) + +

+ +

Converts double array to a double array.

+
+
+ +
+
public static double[] ToDouble(double[] sourceArray)
+
+ +

Parameters

+
+
sourceArray double[]
+

The array to convert

+
+
+ +

Returns

+
+
double[]
+

Converted array of type Double

+
+
+ + + + + + + +

Remarks

+

Based on benchmark ArrayCopying

+
+ + + + + + +

+ ToDouble(short[]) + +

+ +

Converts short array to a double array.

+
+
+ +
+
public static double[] ToDouble(short[] sourceArray)
+
+ +

Parameters

+
+
sourceArray short[]
+

The array to convert

+
+
+ +

Returns

+
+
double[]
+

Converted array of type Double

+
+
+ + + + + + + + + + + + + +

+ ToDouble(int[]) + +

+ +

Converts int array to a double array.

+
+
+ +
+
public static double[] ToDouble(int[] sourceArray)
+
+ +

Parameters

+
+
sourceArray int[]
+

The array to convert

+
+
+ +

Returns

+
+
double[]
+

Converted array of type Double

+
+
+ + + + + + + + + + + + + +

+ ToDouble(long[]) + +

+ +

Converts long array to a double array.

+
+
+ +
+
public static double[] ToDouble(long[] sourceArray)
+
+ +

Parameters

+
+
sourceArray long[]
+

The array to convert

+
+
+ +

Returns

+
+
double[]
+

Converted array of type Double

+
+
+ + + + + + + + + + + + + +

+ ToDouble(float[]) + +

+ +

Converts float array to a double array.

+
+
+ +
+
public static double[] ToDouble(float[] sourceArray)
+
+ +

Parameters

+
+
sourceArray float[]
+

The array to convert

+
+
+ +

Returns

+
+
double[]
+

Converted array of type Double

+
+
+ + + + + + + + + + + + + +

+ ToDouble(string[]) + +

+ +

Converts string array to a double array.

+
+
+ +
+
public static double[] ToDouble(string[] sourceArray)
+
+ +

Parameters

+
+
sourceArray string[]
+

The array to convert

+
+
+ +

Returns

+
+
double[]
+

Converted array of type Double

+
+
+ + + + + + + + + + + + + +

+ ToDouble(ushort[]) + +

+ +

Converts ushort array to a double array.

+
+
+ +
+
public static double[] ToDouble(ushort[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ushort[]
+

The array to convert

+
+
+ +

Returns

+
+
double[]
+

Converted array of type Double

+
+
+ + + + + + + + + + + + + +

+ ToDouble(uint[]) + +

+ +

Converts uint array to a double array.

+
+
+ +
+
public static double[] ToDouble(uint[] sourceArray)
+
+ +

Parameters

+
+
sourceArray uint[]
+

The array to convert

+
+
+ +

Returns

+
+
double[]
+

Converted array of type Double

+
+
+ + + + + + + + + + + + + +

+ ToDouble(ulong[]) + +

+ +

Converts ulong array to a double array.

+
+
+ +
+
public static double[] ToDouble(ulong[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ulong[]
+

The array to convert

+
+
+ +

Returns

+
+
double[]
+

Converted array of type Double

+
+
+ + + + + + + + + + + + + +

+ ToInt16(Array) + +

+ +
+
+ +
+
public static short[] ToInt16(Array sourceArray)
+
+ +

Parameters

+
+
sourceArray Array
+
+
+ +

Returns

+
+
short[]
+
+
+ + + + + + + + + + + + + +

+ ToInt16(bool[]) + +

+ +

Converts bool array to a short array.

+
+
+ +
+
public static short[] ToInt16(bool[] sourceArray)
+
+ +

Parameters

+
+
sourceArray bool[]
+

The array to convert

+
+
+ +

Returns

+
+
short[]
+

Converted array of type Int16

+
+
+ + + + + + + + + + + + + +

+ ToInt16(byte[]) + +

+ +

Converts byte array to a short array.

+
+
+ +
+
public static short[] ToInt16(byte[] sourceArray)
+
+ +

Parameters

+
+
sourceArray byte[]
+

The array to convert

+
+
+ +

Returns

+
+
short[]
+

Converted array of type Int16

+
+
+ + + + + + + + + + + + + +

+ ToInt16(char[]) + +

+ +

Converts char array to a short array.

+
+
+ +
+
public static short[] ToInt16(char[] sourceArray)
+
+ +

Parameters

+
+
sourceArray char[]
+

The array to convert

+
+
+ +

Returns

+
+
short[]
+

Converted array of type Int16

+
+
+ + + + + + + + + + + + + +

+ ToInt16(decimal[]) + +

+ +

Converts decimal array to a short array.

+
+
+ +
+
public static short[] ToInt16(decimal[] sourceArray)
+
+ +

Parameters

+
+
sourceArray decimal[]
+

The array to convert

+
+
+ +

Returns

+
+
short[]
+

Converted array of type Int16

+
+
+ + + + + + + + + + + + + +

+ ToInt16(double[]) + +

+ +

Converts double array to a short array.

+
+
+ +
+
public static short[] ToInt16(double[] sourceArray)
+
+ +

Parameters

+
+
sourceArray double[]
+

The array to convert

+
+
+ +

Returns

+
+
short[]
+

Converted array of type Int16

+
+
+ + + + + + + + + + + + + +

+ ToInt16(short[]) + +

+ +

Converts short array to a short array.

+
+
+ +
+
public static short[] ToInt16(short[] sourceArray)
+
+ +

Parameters

+
+
sourceArray short[]
+

The array to convert

+
+
+ +

Returns

+
+
short[]
+

Converted array of type Int16

+
+
+ + + + + + + +

Remarks

+

Based on benchmark ArrayCopying

+
+ + + + + + +

+ ToInt16(int[]) + +

+ +

Converts int array to a short array.

+
+
+ +
+
public static short[] ToInt16(int[] sourceArray)
+
+ +

Parameters

+
+
sourceArray int[]
+

The array to convert

+
+
+ +

Returns

+
+
short[]
+

Converted array of type Int16

+
+
+ + + + + + + + + + + + + +

+ ToInt16(long[]) + +

+ +

Converts long array to a short array.

+
+
+ +
+
public static short[] ToInt16(long[] sourceArray)
+
+ +

Parameters

+
+
sourceArray long[]
+

The array to convert

+
+
+ +

Returns

+
+
short[]
+

Converted array of type Int16

+
+
+ + + + + + + + + + + + + +

+ ToInt16(float[]) + +

+ +

Converts float array to a short array.

+
+
+ +
+
public static short[] ToInt16(float[] sourceArray)
+
+ +

Parameters

+
+
sourceArray float[]
+

The array to convert

+
+
+ +

Returns

+
+
short[]
+

Converted array of type Int16

+
+
+ + + + + + + + + + + + + +

+ ToInt16(string[]) + +

+ +

Converts string array to a short array.

+
+
+ +
+
public static short[] ToInt16(string[] sourceArray)
+
+ +

Parameters

+
+
sourceArray string[]
+

The array to convert

+
+
+ +

Returns

+
+
short[]
+

Converted array of type Int16

+
+
+ + + + + + + + + + + + + +

+ ToInt16(ushort[]) + +

+ +

Converts ushort array to a short array.

+
+
+ +
+
public static short[] ToInt16(ushort[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ushort[]
+

The array to convert

+
+
+ +

Returns

+
+
short[]
+

Converted array of type Int16

+
+
+ + + + + + + + + + + + + +

+ ToInt16(uint[]) + +

+ +

Converts uint array to a short array.

+
+
+ +
+
public static short[] ToInt16(uint[] sourceArray)
+
+ +

Parameters

+
+
sourceArray uint[]
+

The array to convert

+
+
+ +

Returns

+
+
short[]
+

Converted array of type Int16

+
+
+ + + + + + + + + + + + + +

+ ToInt16(ulong[]) + +

+ +

Converts ulong array to a short array.

+
+
+ +
+
public static short[] ToInt16(ulong[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ulong[]
+

The array to convert

+
+
+ +

Returns

+
+
short[]
+

Converted array of type Int16

+
+
+ + + + + + + + + + + + + +

+ ToInt32(Array) + +

+ +
+
+ +
+
public static int[] ToInt32(Array sourceArray)
+
+ +

Parameters

+
+
sourceArray Array
+
+
+ +

Returns

+
+
int[]
+
+
+ + + + + + + + + + + + + +

+ ToInt32(bool[]) + +

+ +

Converts bool array to a int array.

+
+
+ +
+
public static int[] ToInt32(bool[] sourceArray)
+
+ +

Parameters

+
+
sourceArray bool[]
+

The array to convert

+
+
+ +

Returns

+
+
int[]
+

Converted array of type Int32

+
+
+ + + + + + + + + + + + + +

+ ToInt32(byte[]) + +

+ +

Converts byte array to a int array.

+
+
+ +
+
public static int[] ToInt32(byte[] sourceArray)
+
+ +

Parameters

+
+
sourceArray byte[]
+

The array to convert

+
+
+ +

Returns

+
+
int[]
+

Converted array of type Int32

+
+
+ + + + + + + + + + + + + +

+ ToInt32(char[]) + +

+ +

Converts char array to a int array.

+
+
+ +
+
public static int[] ToInt32(char[] sourceArray)
+
+ +

Parameters

+
+
sourceArray char[]
+

The array to convert

+
+
+ +

Returns

+
+
int[]
+

Converted array of type Int32

+
+
+ + + + + + + + + + + + + +

+ ToInt32(decimal[]) + +

+ +

Converts decimal array to a int array.

+
+
+ +
+
public static int[] ToInt32(decimal[] sourceArray)
+
+ +

Parameters

+
+
sourceArray decimal[]
+

The array to convert

+
+
+ +

Returns

+
+
int[]
+

Converted array of type Int32

+
+
+ + + + + + + + + + + + + +

+ ToInt32(double[]) + +

+ +

Converts double array to a int array.

+
+
+ +
+
public static int[] ToInt32(double[] sourceArray)
+
+ +

Parameters

+
+
sourceArray double[]
+

The array to convert

+
+
+ +

Returns

+
+
int[]
+

Converted array of type Int32

+
+
+ + + + + + + + + + + + + +

+ ToInt32(short[]) + +

+ +

Converts short array to a int array.

+
+
+ +
+
public static int[] ToInt32(short[] sourceArray)
+
+ +

Parameters

+
+
sourceArray short[]
+

The array to convert

+
+
+ +

Returns

+
+
int[]
+

Converted array of type Int32

+
+
+ + + + + + + + + + + + + +

+ ToInt32(int[]) + +

+ +

Converts int array to a int array.

+
+
+ +
+
public static int[] ToInt32(int[] sourceArray)
+
+ +

Parameters

+
+
sourceArray int[]
+

The array to convert

+
+
+ +

Returns

+
+
int[]
+

Converted array of type Int32

+
+
+ + + + + + + +

Remarks

+

Based on benchmark ArrayCopying

+
+ + + + + + +

+ ToInt32(long[]) + +

+ +

Converts long array to a int array.

+
+
+ +
+
public static int[] ToInt32(long[] sourceArray)
+
+ +

Parameters

+
+
sourceArray long[]
+

The array to convert

+
+
+ +

Returns

+
+
int[]
+

Converted array of type Int32

+
+
+ + + + + + + + + + + + + +

+ ToInt32(float[]) + +

+ +

Converts float array to a int array.

+
+
+ +
+
public static int[] ToInt32(float[] sourceArray)
+
+ +

Parameters

+
+
sourceArray float[]
+

The array to convert

+
+
+ +

Returns

+
+
int[]
+

Converted array of type Int32

+
+
+ + + + + + + + + + + + + +

+ ToInt32(string[]) + +

+ +

Converts string array to a int array.

+
+
+ +
+
public static int[] ToInt32(string[] sourceArray)
+
+ +

Parameters

+
+
sourceArray string[]
+

The array to convert

+
+
+ +

Returns

+
+
int[]
+

Converted array of type Int32

+
+
+ + + + + + + + + + + + + +

+ ToInt32(ushort[]) + +

+ +

Converts ushort array to a int array.

+
+
+ +
+
public static int[] ToInt32(ushort[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ushort[]
+

The array to convert

+
+
+ +

Returns

+
+
int[]
+

Converted array of type Int32

+
+
+ + + + + + + + + + + + + +

+ ToInt32(uint[]) + +

+ +

Converts uint array to a int array.

+
+
+ +
+
public static int[] ToInt32(uint[] sourceArray)
+
+ +

Parameters

+
+
sourceArray uint[]
+

The array to convert

+
+
+ +

Returns

+
+
int[]
+

Converted array of type Int32

+
+
+ + + + + + + + + + + + + +

+ ToInt32(ulong[]) + +

+ +

Converts ulong array to a int array.

+
+
+ +
+
public static int[] ToInt32(ulong[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ulong[]
+

The array to convert

+
+
+ +

Returns

+
+
int[]
+

Converted array of type Int32

+
+
+ + + + + + + + + + + + + +

+ ToInt64(Array) + +

+ +
+
+ +
+
public static long[] ToInt64(Array sourceArray)
+
+ +

Parameters

+
+
sourceArray Array
+
+
+ +

Returns

+
+
long[]
+
+
+ + + + + + + + + + + + + +

+ ToInt64(bool[]) + +

+ +

Converts bool array to a long array.

+
+
+ +
+
public static long[] ToInt64(bool[] sourceArray)
+
+ +

Parameters

+
+
sourceArray bool[]
+

The array to convert

+
+
+ +

Returns

+
+
long[]
+

Converted array of type Int64

+
+
+ + + + + + + + + + + + + +

+ ToInt64(byte[]) + +

+ +

Converts byte array to a long array.

+
+
+ +
+
public static long[] ToInt64(byte[] sourceArray)
+
+ +

Parameters

+
+
sourceArray byte[]
+

The array to convert

+
+
+ +

Returns

+
+
long[]
+

Converted array of type Int64

+
+
+ + + + + + + + + + + + + +

+ ToInt64(char[]) + +

+ +

Converts char array to a long array.

+
+
+ +
+
public static long[] ToInt64(char[] sourceArray)
+
+ +

Parameters

+
+
sourceArray char[]
+

The array to convert

+
+
+ +

Returns

+
+
long[]
+

Converted array of type Int64

+
+
+ + + + + + + + + + + + + +

+ ToInt64(decimal[]) + +

+ +

Converts decimal array to a long array.

+
+
+ +
+
public static long[] ToInt64(decimal[] sourceArray)
+
+ +

Parameters

+
+
sourceArray decimal[]
+

The array to convert

+
+
+ +

Returns

+
+
long[]
+

Converted array of type Int64

+
+
+ + + + + + + + + + + + + +

+ ToInt64(double[]) + +

+ +

Converts double array to a long array.

+
+
+ +
+
public static long[] ToInt64(double[] sourceArray)
+
+ +

Parameters

+
+
sourceArray double[]
+

The array to convert

+
+
+ +

Returns

+
+
long[]
+

Converted array of type Int64

+
+
+ + + + + + + + + + + + + +

+ ToInt64(short[]) + +

+ +

Converts short array to a long array.

+
+
+ +
+
public static long[] ToInt64(short[] sourceArray)
+
+ +

Parameters

+
+
sourceArray short[]
+

The array to convert

+
+
+ +

Returns

+
+
long[]
+

Converted array of type Int64

+
+
+ + + + + + + + + + + + + +

+ ToInt64(int[]) + +

+ +

Converts int array to a long array.

+
+
+ +
+
public static long[] ToInt64(int[] sourceArray)
+
+ +

Parameters

+
+
sourceArray int[]
+

The array to convert

+
+
+ +

Returns

+
+
long[]
+

Converted array of type Int64

+
+
+ + + + + + + + + + + + + +

+ ToInt64(long[]) + +

+ +

Converts long array to a long array.

+
+
+ +
+
public static long[] ToInt64(long[] sourceArray)
+
+ +

Parameters

+
+
sourceArray long[]
+

The array to convert

+
+
+ +

Returns

+
+
long[]
+

Converted array of type Int64

+
+
+ + + + + + + +

Remarks

+

Based on benchmark ArrayCopying

+
+ + + + + + +

+ ToInt64(float[]) + +

+ +

Converts float array to a long array.

+
+
+ +
+
public static long[] ToInt64(float[] sourceArray)
+
+ +

Parameters

+
+
sourceArray float[]
+

The array to convert

+
+
+ +

Returns

+
+
long[]
+

Converted array of type Int64

+
+
+ + + + + + + + + + + + + +

+ ToInt64(string[]) + +

+ +

Converts string array to a long array.

+
+
+ +
+
public static long[] ToInt64(string[] sourceArray)
+
+ +

Parameters

+
+
sourceArray string[]
+

The array to convert

+
+
+ +

Returns

+
+
long[]
+

Converted array of type Int64

+
+
+ + + + + + + + + + + + + +

+ ToInt64(ushort[]) + +

+ +

Converts ushort array to a long array.

+
+
+ +
+
public static long[] ToInt64(ushort[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ushort[]
+

The array to convert

+
+
+ +

Returns

+
+
long[]
+

Converted array of type Int64

+
+
+ + + + + + + + + + + + + +

+ ToInt64(uint[]) + +

+ +

Converts uint array to a long array.

+
+
+ +
+
public static long[] ToInt64(uint[] sourceArray)
+
+ +

Parameters

+
+
sourceArray uint[]
+

The array to convert

+
+
+ +

Returns

+
+
long[]
+

Converted array of type Int64

+
+
+ + + + + + + + + + + + + +

+ ToInt64(ulong[]) + +

+ +

Converts ulong array to a long array.

+
+
+ +
+
public static long[] ToInt64(ulong[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ulong[]
+

The array to convert

+
+
+ +

Returns

+
+
long[]
+

Converted array of type Int64

+
+
+ + + + + + + + + + + + + +

+ ToSingle(Array) + +

+ +
+
+ +
+
public static float[] ToSingle(Array sourceArray)
+
+ +

Parameters

+
+
sourceArray Array
+
+
+ +

Returns

+
+
float[]
+
+
+ + + + + + + + + + + + + +

+ ToSingle(bool[]) + +

+ +

Converts bool array to a float array.

+
+
+ +
+
public static float[] ToSingle(bool[] sourceArray)
+
+ +

Parameters

+
+
sourceArray bool[]
+

The array to convert

+
+
+ +

Returns

+
+
float[]
+

Converted array of type Single

+
+
+ + + + + + + + + + + + + +

+ ToSingle(byte[]) + +

+ +

Converts byte array to a float array.

+
+
+ +
+
public static float[] ToSingle(byte[] sourceArray)
+
+ +

Parameters

+
+
sourceArray byte[]
+

The array to convert

+
+
+ +

Returns

+
+
float[]
+

Converted array of type Single

+
+
+ + + + + + + + + + + + + +

+ ToSingle(char[]) + +

+ +

Converts char array to a float array.

+
+
+ +
+
public static float[] ToSingle(char[] sourceArray)
+
+ +

Parameters

+
+
sourceArray char[]
+

The array to convert

+
+
+ +

Returns

+
+
float[]
+

Converted array of type Single

+
+
+ + + + + + + + + + + + + +

+ ToSingle(decimal[]) + +

+ +

Converts decimal array to a float array.

+
+
+ +
+
public static float[] ToSingle(decimal[] sourceArray)
+
+ +

Parameters

+
+
sourceArray decimal[]
+

The array to convert

+
+
+ +

Returns

+
+
float[]
+

Converted array of type Single

+
+
+ + + + + + + + + + + + + +

+ ToSingle(double[]) + +

+ +

Converts double array to a float array.

+
+
+ +
+
public static float[] ToSingle(double[] sourceArray)
+
+ +

Parameters

+
+
sourceArray double[]
+

The array to convert

+
+
+ +

Returns

+
+
float[]
+

Converted array of type Single

+
+
+ + + + + + + + + + + + + +

+ ToSingle(short[]) + +

+ +

Converts short array to a float array.

+
+
+ +
+
public static float[] ToSingle(short[] sourceArray)
+
+ +

Parameters

+
+
sourceArray short[]
+

The array to convert

+
+
+ +

Returns

+
+
float[]
+

Converted array of type Single

+
+
+ + + + + + + + + + + + + +

+ ToSingle(int[]) + +

+ +

Converts int array to a float array.

+
+
+ +
+
public static float[] ToSingle(int[] sourceArray)
+
+ +

Parameters

+
+
sourceArray int[]
+

The array to convert

+
+
+ +

Returns

+
+
float[]
+

Converted array of type Single

+
+
+ + + + + + + + + + + + + +

+ ToSingle(long[]) + +

+ +

Converts long array to a float array.

+
+
+ +
+
public static float[] ToSingle(long[] sourceArray)
+
+ +

Parameters

+
+
sourceArray long[]
+

The array to convert

+
+
+ +

Returns

+
+
float[]
+

Converted array of type Single

+
+
+ + + + + + + + + + + + + +

+ ToSingle(float[]) + +

+ +

Converts float array to a float array.

+
+
+ +
+
public static float[] ToSingle(float[] sourceArray)
+
+ +

Parameters

+
+
sourceArray float[]
+

The array to convert

+
+
+ +

Returns

+
+
float[]
+

Converted array of type Single

+
+
+ + + + + + + +

Remarks

+

Based on benchmark ArrayCopying

+
+ + + + + + +

+ ToSingle(string[]) + +

+ +

Converts string array to a float array.

+
+
+ +
+
public static float[] ToSingle(string[] sourceArray)
+
+ +

Parameters

+
+
sourceArray string[]
+

The array to convert

+
+
+ +

Returns

+
+
float[]
+

Converted array of type Single

+
+
+ + + + + + + + + + + + + +

+ ToSingle(ushort[]) + +

+ +

Converts ushort array to a float array.

+
+
+ +
+
public static float[] ToSingle(ushort[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ushort[]
+

The array to convert

+
+
+ +

Returns

+
+
float[]
+

Converted array of type Single

+
+
+ + + + + + + + + + + + + +

+ ToSingle(uint[]) + +

+ +

Converts uint array to a float array.

+
+
+ +
+
public static float[] ToSingle(uint[] sourceArray)
+
+ +

Parameters

+
+
sourceArray uint[]
+

The array to convert

+
+
+ +

Returns

+
+
float[]
+

Converted array of type Single

+
+
+ + + + + + + + + + + + + +

+ ToSingle(ulong[]) + +

+ +

Converts ulong array to a float array.

+
+
+ +
+
public static float[] ToSingle(ulong[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ulong[]
+

The array to convert

+
+
+ +

Returns

+
+
float[]
+

Converted array of type Single

+
+
+ + + + + + + + + + + + + +

+ ToString(Array) + +

+ +
+
+ +
+
public static string[] ToString(Array sourceArray)
+
+ +

Parameters

+
+
sourceArray Array
+
+
+ +

Returns

+
+
string[]
+
+
+ + + + + + + + + + + + + +

+ ToString(bool[]) + +

+ +

Converts bool array to a string array.

+
+
+ +
+
public static string[] ToString(bool[] sourceArray)
+
+ +

Parameters

+
+
sourceArray bool[]
+

The array to convert

+
+
+ +

Returns

+
+
string[]
+

Converted array of type String

+
+
+ + + + + + + + + + + + + +

+ ToString(byte[]) + +

+ +

Converts byte array to a string array.

+
+
+ +
+
public static string[] ToString(byte[] sourceArray)
+
+ +

Parameters

+
+
sourceArray byte[]
+

The array to convert

+
+
+ +

Returns

+
+
string[]
+

Converted array of type String

+
+
+ + + + + + + + + + + + + +

+ ToString(char[]) + +

+ +

Converts char array to a string array.

+
+
+ +
+
public static string[] ToString(char[] sourceArray)
+
+ +

Parameters

+
+
sourceArray char[]
+

The array to convert

+
+
+ +

Returns

+
+
string[]
+

Converted array of type String

+
+
+ + + + + + + + + + + + + +

+ ToString(decimal[]) + +

+ +

Converts decimal array to a string array.

+
+
+ +
+
public static string[] ToString(decimal[] sourceArray)
+
+ +

Parameters

+
+
sourceArray decimal[]
+

The array to convert

+
+
+ +

Returns

+
+
string[]
+

Converted array of type String

+
+
+ + + + + + + + + + + + + +

+ ToString(double[]) + +

+ +

Converts double array to a string array.

+
+
+ +
+
public static string[] ToString(double[] sourceArray)
+
+ +

Parameters

+
+
sourceArray double[]
+

The array to convert

+
+
+ +

Returns

+
+
string[]
+

Converted array of type String

+
+
+ + + + + + + + + + + + + +

+ ToString(short[]) + +

+ +

Converts short array to a string array.

+
+
+ +
+
public static string[] ToString(short[] sourceArray)
+
+ +

Parameters

+
+
sourceArray short[]
+

The array to convert

+
+
+ +

Returns

+
+
string[]
+

Converted array of type String

+
+
+ + + + + + + + + + + + + +

+ ToString(int[]) + +

+ +

Converts int array to a string array.

+
+
+ +
+
public static string[] ToString(int[] sourceArray)
+
+ +

Parameters

+
+
sourceArray int[]
+

The array to convert

+
+
+ +

Returns

+
+
string[]
+

Converted array of type String

+
+
+ + + + + + + + + + + + + +

+ ToString(long[]) + +

+ +

Converts long array to a string array.

+
+
+ +
+
public static string[] ToString(long[] sourceArray)
+
+ +

Parameters

+
+
sourceArray long[]
+

The array to convert

+
+
+ +

Returns

+
+
string[]
+

Converted array of type String

+
+
+ + + + + + + + + + + + + +

+ ToString(float[]) + +

+ +

Converts float array to a string array.

+
+
+ +
+
public static string[] ToString(float[] sourceArray)
+
+ +

Parameters

+
+
sourceArray float[]
+

The array to convert

+
+
+ +

Returns

+
+
string[]
+

Converted array of type String

+
+
+ + + + + + + + + + + + + +

+ ToString(string[]) + +

+ +

Converts string array to a string array.

+
+
+ +
+
public static string[] ToString(string[] sourceArray)
+
+ +

Parameters

+
+
sourceArray string[]
+

The array to convert

+
+
+ +

Returns

+
+
string[]
+

Converted array of type String

+
+
+ + + + + + + +

Remarks

+

Based on benchmark ArrayCopying

+
+ + + + + + +

+ ToString(ushort[]) + +

+ +

Converts ushort array to a string array.

+
+
+ +
+
public static string[] ToString(ushort[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ushort[]
+

The array to convert

+
+
+ +

Returns

+
+
string[]
+

Converted array of type String

+
+
+ + + + + + + + + + + + + +

+ ToString(uint[]) + +

+ +

Converts uint array to a string array.

+
+
+ +
+
public static string[] ToString(uint[] sourceArray)
+
+ +

Parameters

+
+
sourceArray uint[]
+

The array to convert

+
+
+ +

Returns

+
+
string[]
+

Converted array of type String

+
+
+ + + + + + + + + + + + + +

+ ToString(ulong[]) + +

+ +

Converts ulong array to a string array.

+
+
+ +
+
public static string[] ToString(ulong[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ulong[]
+

The array to convert

+
+
+ +

Returns

+
+
string[]
+

Converted array of type String

+
+
+ + + + + + + + + + + + + +

+ ToUInt16(Array) + +

+ +
+
+ +
+
public static ushort[] ToUInt16(Array sourceArray)
+
+ +

Parameters

+
+
sourceArray Array
+
+
+ +

Returns

+
+
ushort[]
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(bool[]) + +

+ +

Converts bool array to a ushort array.

+
+
+ +
+
public static ushort[] ToUInt16(bool[] sourceArray)
+
+ +

Parameters

+
+
sourceArray bool[]
+

The array to convert

+
+
+ +

Returns

+
+
ushort[]
+

Converted array of type UInt16

+
+
+ + + + + + + + + + + + + +

+ ToUInt16(byte[]) + +

+ +

Converts byte array to a ushort array.

+
+
+ +
+
public static ushort[] ToUInt16(byte[] sourceArray)
+
+ +

Parameters

+
+
sourceArray byte[]
+

The array to convert

+
+
+ +

Returns

+
+
ushort[]
+

Converted array of type UInt16

+
+
+ + + + + + + + + + + + + +

+ ToUInt16(char[]) + +

+ +

Converts char array to a ushort array.

+
+
+ +
+
public static ushort[] ToUInt16(char[] sourceArray)
+
+ +

Parameters

+
+
sourceArray char[]
+

The array to convert

+
+
+ +

Returns

+
+
ushort[]
+

Converted array of type UInt16

+
+
+ + + + + + + + + + + + + +

+ ToUInt16(decimal[]) + +

+ +

Converts decimal array to a ushort array.

+
+
+ +
+
public static ushort[] ToUInt16(decimal[] sourceArray)
+
+ +

Parameters

+
+
sourceArray decimal[]
+

The array to convert

+
+
+ +

Returns

+
+
ushort[]
+

Converted array of type UInt16

+
+
+ + + + + + + + + + + + + +

+ ToUInt16(double[]) + +

+ +

Converts double array to a ushort array.

+
+
+ +
+
public static ushort[] ToUInt16(double[] sourceArray)
+
+ +

Parameters

+
+
sourceArray double[]
+

The array to convert

+
+
+ +

Returns

+
+
ushort[]
+

Converted array of type UInt16

+
+
+ + + + + + + + + + + + + +

+ ToUInt16(short[]) + +

+ +

Converts short array to a ushort array.

+
+
+ +
+
public static ushort[] ToUInt16(short[] sourceArray)
+
+ +

Parameters

+
+
sourceArray short[]
+

The array to convert

+
+
+ +

Returns

+
+
ushort[]
+

Converted array of type UInt16

+
+
+ + + + + + + + + + + + + +

+ ToUInt16(int[]) + +

+ +

Converts int array to a ushort array.

+
+
+ +
+
public static ushort[] ToUInt16(int[] sourceArray)
+
+ +

Parameters

+
+
sourceArray int[]
+

The array to convert

+
+
+ +

Returns

+
+
ushort[]
+

Converted array of type UInt16

+
+
+ + + + + + + + + + + + + +

+ ToUInt16(long[]) + +

+ +

Converts long array to a ushort array.

+
+
+ +
+
public static ushort[] ToUInt16(long[] sourceArray)
+
+ +

Parameters

+
+
sourceArray long[]
+

The array to convert

+
+
+ +

Returns

+
+
ushort[]
+

Converted array of type UInt16

+
+
+ + + + + + + + + + + + + +

+ ToUInt16(float[]) + +

+ +

Converts float array to a ushort array.

+
+
+ +
+
public static ushort[] ToUInt16(float[] sourceArray)
+
+ +

Parameters

+
+
sourceArray float[]
+

The array to convert

+
+
+ +

Returns

+
+
ushort[]
+

Converted array of type UInt16

+
+
+ + + + + + + + + + + + + +

+ ToUInt16(string[]) + +

+ +

Converts string array to a ushort array.

+
+
+ +
+
public static ushort[] ToUInt16(string[] sourceArray)
+
+ +

Parameters

+
+
sourceArray string[]
+

The array to convert

+
+
+ +

Returns

+
+
ushort[]
+

Converted array of type UInt16

+
+
+ + + + + + + + + + + + + +

+ ToUInt16(ushort[]) + +

+ +

Converts ushort array to a ushort array.

+
+
+ +
+
public static ushort[] ToUInt16(ushort[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ushort[]
+

The array to convert

+
+
+ +

Returns

+
+
ushort[]
+

Converted array of type UInt16

+
+
+ + + + + + + +

Remarks

+

Based on benchmark ArrayCopying

+
+ + + + + + +

+ ToUInt16(uint[]) + +

+ +

Converts uint array to a ushort array.

+
+
+ +
+
public static ushort[] ToUInt16(uint[] sourceArray)
+
+ +

Parameters

+
+
sourceArray uint[]
+

The array to convert

+
+
+ +

Returns

+
+
ushort[]
+

Converted array of type UInt16

+
+
+ + + + + + + + + + + + + +

+ ToUInt16(ulong[]) + +

+ +

Converts ulong array to a ushort array.

+
+
+ +
+
public static ushort[] ToUInt16(ulong[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ulong[]
+

The array to convert

+
+
+ +

Returns

+
+
ushort[]
+

Converted array of type UInt16

+
+
+ + + + + + + + + + + + + +

+ ToUInt32(Array) + +

+ +
+
+ +
+
public static uint[] ToUInt32(Array sourceArray)
+
+ +

Parameters

+
+
sourceArray Array
+
+
+ +

Returns

+
+
uint[]
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(bool[]) + +

+ +

Converts bool array to a uint array.

+
+
+ +
+
public static uint[] ToUInt32(bool[] sourceArray)
+
+ +

Parameters

+
+
sourceArray bool[]
+

The array to convert

+
+
+ +

Returns

+
+
uint[]
+

Converted array of type UInt32

+
+
+ + + + + + + + + + + + + +

+ ToUInt32(byte[]) + +

+ +

Converts byte array to a uint array.

+
+
+ +
+
public static uint[] ToUInt32(byte[] sourceArray)
+
+ +

Parameters

+
+
sourceArray byte[]
+

The array to convert

+
+
+ +

Returns

+
+
uint[]
+

Converted array of type UInt32

+
+
+ + + + + + + + + + + + + +

+ ToUInt32(char[]) + +

+ +

Converts char array to a uint array.

+
+
+ +
+
public static uint[] ToUInt32(char[] sourceArray)
+
+ +

Parameters

+
+
sourceArray char[]
+

The array to convert

+
+
+ +

Returns

+
+
uint[]
+

Converted array of type UInt32

+
+
+ + + + + + + + + + + + + +

+ ToUInt32(decimal[]) + +

+ +

Converts decimal array to a uint array.

+
+
+ +
+
public static uint[] ToUInt32(decimal[] sourceArray)
+
+ +

Parameters

+
+
sourceArray decimal[]
+

The array to convert

+
+
+ +

Returns

+
+
uint[]
+

Converted array of type UInt32

+
+
+ + + + + + + + + + + + + +

+ ToUInt32(double[]) + +

+ +

Converts double array to a uint array.

+
+
+ +
+
public static uint[] ToUInt32(double[] sourceArray)
+
+ +

Parameters

+
+
sourceArray double[]
+

The array to convert

+
+
+ +

Returns

+
+
uint[]
+

Converted array of type UInt32

+
+
+ + + + + + + + + + + + + +

+ ToUInt32(short[]) + +

+ +

Converts short array to a uint array.

+
+
+ +
+
public static uint[] ToUInt32(short[] sourceArray)
+
+ +

Parameters

+
+
sourceArray short[]
+

The array to convert

+
+
+ +

Returns

+
+
uint[]
+

Converted array of type UInt32

+
+
+ + + + + + + + + + + + + +

+ ToUInt32(int[]) + +

+ +

Converts int array to a uint array.

+
+
+ +
+
public static uint[] ToUInt32(int[] sourceArray)
+
+ +

Parameters

+
+
sourceArray int[]
+

The array to convert

+
+
+ +

Returns

+
+
uint[]
+

Converted array of type UInt32

+
+
+ + + + + + + + + + + + + +

+ ToUInt32(long[]) + +

+ +

Converts long array to a uint array.

+
+
+ +
+
public static uint[] ToUInt32(long[] sourceArray)
+
+ +

Parameters

+
+
sourceArray long[]
+

The array to convert

+
+
+ +

Returns

+
+
uint[]
+

Converted array of type UInt32

+
+
+ + + + + + + + + + + + + +

+ ToUInt32(float[]) + +

+ +

Converts float array to a uint array.

+
+
+ +
+
public static uint[] ToUInt32(float[] sourceArray)
+
+ +

Parameters

+
+
sourceArray float[]
+

The array to convert

+
+
+ +

Returns

+
+
uint[]
+

Converted array of type UInt32

+
+
+ + + + + + + + + + + + + +

+ ToUInt32(string[]) + +

+ +

Converts string array to a uint array.

+
+
+ +
+
public static uint[] ToUInt32(string[] sourceArray)
+
+ +

Parameters

+
+
sourceArray string[]
+

The array to convert

+
+
+ +

Returns

+
+
uint[]
+

Converted array of type UInt32

+
+
+ + + + + + + + + + + + + +

+ ToUInt32(ushort[]) + +

+ +

Converts ushort array to a uint array.

+
+
+ +
+
public static uint[] ToUInt32(ushort[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ushort[]
+

The array to convert

+
+
+ +

Returns

+
+
uint[]
+

Converted array of type UInt32

+
+
+ + + + + + + + + + + + + +

+ ToUInt32(uint[]) + +

+ +

Converts uint array to a uint array.

+
+
+ +
+
public static uint[] ToUInt32(uint[] sourceArray)
+
+ +

Parameters

+
+
sourceArray uint[]
+

The array to convert

+
+
+ +

Returns

+
+
uint[]
+

Converted array of type UInt32

+
+
+ + + + + + + +

Remarks

+

Based on benchmark ArrayCopying

+
+ + + + + + +

+ ToUInt32(ulong[]) + +

+ +

Converts ulong array to a uint array.

+
+
+ +
+
public static uint[] ToUInt32(ulong[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ulong[]
+

The array to convert

+
+
+ +

Returns

+
+
uint[]
+

Converted array of type UInt32

+
+
+ + + + + + + + + + + + + +

+ ToUInt64(Array) + +

+ +
+
+ +
+
public static ulong[] ToUInt64(Array sourceArray)
+
+ +

Parameters

+
+
sourceArray Array
+
+
+ +

Returns

+
+
ulong[]
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(bool[]) + +

+ +

Converts bool array to a ulong array.

+
+
+ +
+
public static ulong[] ToUInt64(bool[] sourceArray)
+
+ +

Parameters

+
+
sourceArray bool[]
+

The array to convert

+
+
+ +

Returns

+
+
ulong[]
+

Converted array of type UInt64

+
+
+ + + + + + + + + + + + + +

+ ToUInt64(byte[]) + +

+ +

Converts byte array to a ulong array.

+
+
+ +
+
public static ulong[] ToUInt64(byte[] sourceArray)
+
+ +

Parameters

+
+
sourceArray byte[]
+

The array to convert

+
+
+ +

Returns

+
+
ulong[]
+

Converted array of type UInt64

+
+
+ + + + + + + + + + + + + +

+ ToUInt64(char[]) + +

+ +

Converts char array to a ulong array.

+
+
+ +
+
public static ulong[] ToUInt64(char[] sourceArray)
+
+ +

Parameters

+
+
sourceArray char[]
+

The array to convert

+
+
+ +

Returns

+
+
ulong[]
+

Converted array of type UInt64

+
+
+ + + + + + + + + + + + + +

+ ToUInt64(decimal[]) + +

+ +

Converts decimal array to a ulong array.

+
+
+ +
+
public static ulong[] ToUInt64(decimal[] sourceArray)
+
+ +

Parameters

+
+
sourceArray decimal[]
+

The array to convert

+
+
+ +

Returns

+
+
ulong[]
+

Converted array of type UInt64

+
+
+ + + + + + + + + + + + + +

+ ToUInt64(double[]) + +

+ +

Converts double array to a ulong array.

+
+
+ +
+
public static ulong[] ToUInt64(double[] sourceArray)
+
+ +

Parameters

+
+
sourceArray double[]
+

The array to convert

+
+
+ +

Returns

+
+
ulong[]
+

Converted array of type UInt64

+
+
+ + + + + + + + + + + + + +

+ ToUInt64(short[]) + +

+ +

Converts short array to a ulong array.

+
+
+ +
+
public static ulong[] ToUInt64(short[] sourceArray)
+
+ +

Parameters

+
+
sourceArray short[]
+

The array to convert

+
+
+ +

Returns

+
+
ulong[]
+

Converted array of type UInt64

+
+
+ + + + + + + + + + + + + +

+ ToUInt64(int[]) + +

+ +

Converts int array to a ulong array.

+
+
+ +
+
public static ulong[] ToUInt64(int[] sourceArray)
+
+ +

Parameters

+
+
sourceArray int[]
+

The array to convert

+
+
+ +

Returns

+
+
ulong[]
+

Converted array of type UInt64

+
+
+ + + + + + + + + + + + + +

+ ToUInt64(long[]) + +

+ +

Converts long array to a ulong array.

+
+
+ +
+
public static ulong[] ToUInt64(long[] sourceArray)
+
+ +

Parameters

+
+
sourceArray long[]
+

The array to convert

+
+
+ +

Returns

+
+
ulong[]
+

Converted array of type UInt64

+
+
+ + + + + + + + + + + + + +

+ ToUInt64(float[]) + +

+ +

Converts float array to a ulong array.

+
+
+ +
+
public static ulong[] ToUInt64(float[] sourceArray)
+
+ +

Parameters

+
+
sourceArray float[]
+

The array to convert

+
+
+ +

Returns

+
+
ulong[]
+

Converted array of type UInt64

+
+
+ + + + + + + + + + + + + +

+ ToUInt64(string[]) + +

+ +

Converts string array to a ulong array.

+
+
+ +
+
public static ulong[] ToUInt64(string[] sourceArray)
+
+ +

Parameters

+
+
sourceArray string[]
+

The array to convert

+
+
+ +

Returns

+
+
ulong[]
+

Converted array of type UInt64

+
+
+ + + + + + + + + + + + + +

+ ToUInt64(ushort[]) + +

+ +

Converts ushort array to a ulong array.

+
+
+ +
+
public static ulong[] ToUInt64(ushort[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ushort[]
+

The array to convert

+
+
+ +

Returns

+
+
ulong[]
+

Converted array of type UInt64

+
+
+ + + + + + + + + + + + + +

+ ToUInt64(uint[]) + +

+ +

Converts uint array to a ulong array.

+
+
+ +
+
public static ulong[] ToUInt64(uint[] sourceArray)
+
+ +

Parameters

+
+
sourceArray uint[]
+

The array to convert

+
+
+ +

Returns

+
+
ulong[]
+

Converted array of type UInt64

+
+
+ + + + + + + + + + + + + +

+ ToUInt64(ulong[]) + +

+ +

Converts ulong array to a ulong array.

+
+
+ +
+
public static ulong[] ToUInt64(ulong[] sourceArray)
+
+ +

Parameters

+
+
sourceArray ulong[]
+

The array to convert

+
+
+ +

Returns

+
+
ulong[]
+

Converted array of type UInt64

+
+
+ + + + + + + +

Remarks

+

Based on benchmark ArrayCopying

+
+ + + + + + +

+ To<T>(Array) + +

+ +

Converts sourceArray to an array of type returnType.

+
+
+ +
+
public static T[] To<T>(Array sourceArray)
+
+ +

Parameters

+
+
sourceArray Array
+

The array to convert

+
+
+ +

Returns

+
+
T[]
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+

If sourceArray's element type equals to returnType then a copy is returned

+
+ + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.Arrays.html b/docs/website/api/NumSharp.Utilities.Arrays.html new file mode 100644 index 000000000..3f8e0b321 --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.Arrays.html @@ -0,0 +1,1182 @@ + + + + + Class Arrays | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class Arrays +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public static class Arrays
+
+ + + + +
+
Inheritance
+
+ +
Arrays
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Methods +

+ + + + +

+ AppendAt<T>(T[], int, T) + +

+ +

Inserts item into a specific index.

+
+
+ +
+
public static T[] AppendAt<T>(T[] source, int index, T value)
+
+ +

Parameters

+
+
source T[]
+

The array to insert copy and insert value to.

+
+
index int
+

The index to insert to.

+
+
value T
+
+
+ +

Returns

+
+
T[]
+

a copy of source with the appended value.

+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Concat<T>(T[], T[]) + +

+ +

Performs fast concatenation of multiple arrays

+
+
+ +
+
public static T[] Concat<T>(T[] left, T[] right)
+
+ +

Parameters

+
+
left T[]
+
+
right T[]
+
+
+ +

Returns

+
+
T[]
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Concat<T>(params T[][]) + +

+ +

Performs fast concatenation of multiple arrays

+
+
+ +
+
public static T[] Concat<T>(params T[][] arrays)
+
+ +

Parameters

+
+
arrays T[][]
+
+
+ +

Returns

+
+
T[]
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ CopyToExceptAt<T>(T[], int, int, T[], int) + +

+ +

Copies an array contents except for a specific index.

+
+
+ +
+
public static void CopyToExceptAt<T>(this T[] source, int sourceOffset, int index, T[] destinition, int destOffset = 0)
+
+ +

Parameters

+
+
source T[]
+

The array to copy from.

+
+
sourceOffset int
+
+
index int
+

The index to ignore.

+
+
destinition T[]
+

The copying destinition

+
+
destOffset int
+

The destinition's offset

+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ CopyToExceptAt<T>(T[], int, T[], int) + +

+ +

Copies an array contents except for a specific index.

+
+
+ +
+
public static void CopyToExceptAt<T>(this T[] source, int index, T[] destinition, int destOffset = 0)
+
+ +

Parameters

+
+
source T[]
+

The array to copy from.

+
+
index int
+

The index to ignore.

+
+
destinition T[]
+

The copying destinition

+
+
destOffset int
+

The destinition's offset

+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Create(NPTypeCode, int) + +

+ +

Creates an array of 1D of type typeCode.

+
+
+ +
+
public static Array Create(NPTypeCode typeCode, int length)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+

The type to create this array.

+
+
length int
+

The length of the array

+
+
+ +

Returns

+
+
Array
+
+
+ + + + + + + +

Remarks

+

Do not use this if you are trying to create jagged or multidimensional array.

+
+ + + + + + +

+ Create(Type, IEnumerable) + +

+ +

Creates an array of 1D of type type.

+
+
+ +
+
public static Array Create(Type type, IEnumerable enumerable)
+
+ +

Parameters

+
+
type Type
+

The type to create this array.

+
+
enumerable IEnumerable
+
+
+ +

Returns

+
+
Array
+
+
+ + + + + + + +

Remarks

+

Do not use this if you are trying to create jagged or multidimensional array.

+
+ + + + + + +

+ Create(Type, int) + +

+ +

Creates an array of 1D of type type.

+
+
+ +
+
public static Array Create(Type type, int length)
+
+ +

Parameters

+
+
type Type
+

The type to create this array.

+
+
length int
+

The length of the array

+
+
+ +

Returns

+
+
Array
+
+
+ + + + + + + +

Remarks

+

Do not use this if you are trying to create jagged or multidimensional array.

+
+ + + + + + +

+ Create(Type, int[]) + +

+ +

Creates an array of specific length of type type.

+
+
+ +
+
public static Array Create(Type type, int[] length)
+
+ +

Parameters

+
+
type Type
+

The type to create this array.

+
+
length int[]
+

The length of the array

+
+
+ +

Returns

+
+
Array
+
+
+ + + + + + + + + + + + + +

+ Create<T>(int) + +

+ +

Creates an array 1D of type T.

+
+
+ +
+
public static T[] Create<T>(int length)
+
+ +

Parameters

+
+
length int
+

The length of the array

+
+
+ +

Returns

+
+
T[]
+
+
+ +

Type Parameters

+
+
T
+

The type of the array

+
+
+ + + + + + + + + + + + +

+ ExtractStructure(Array) + +

+ +

Extracts shape and type from given array.

+
+
+ +
+
public static (Shape Shape, Type DType) ExtractStructure(Array array)
+
+ +

Parameters

+
+
array Array
+

The array to extract DType and Shape from.

+
+
+ +

Returns

+
+
(Shape Shape, Type Type)
+
+
+ + + + + + + + + + + + + +

+ ExtractStructure<T>(T[]) + +

+ +

Extracts shape and type from given array.

+
+
+ +
+
public static (Shape Shape, Type DType) ExtractStructure<T>(T[] array)
+
+ +

Parameters

+
+
array T[]
+

The array to extract DType and Shape from.

+
+
+ +

Returns

+
+
(Shape Shape, Type Type)
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Flatten(Array) + +

+ +

Flattens any type of Array.

+
+
+ +
+
public static Array Flatten(Array array)
+
+ +

Parameters

+
+
array Array
+
+
+ +

Returns

+
+
Array
+
+
+ + + + + + + +

Remarks

+

Supports both jagged array and multi-dim arrays.

+
+ + + + + + +

+ Insert<T>(T[], int, T) + +

+ +

Inserts item into a specific index.

+
+
+ +
+
public static T[] Insert<T>(T[] source, int index, T value) where T : unmanaged
+
+ +

Parameters

+
+
source T[]
+

The array to insert the value to.

+
+
index int
+

The index to insert to.

+
+
value T
+
+
+ +

Returns

+
+
T[]
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Insert<T>(ref T[], int, T) + +

+ +

Inserts item into a specific index.

+
+
+ +
+
public static void Insert<T>(ref T[] source, int index, T value)
+
+ +

Parameters

+
+
source T[]
+

The array to insert the value to.

+
+
index int
+

The index to insert to.

+
+
value T
+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ RemoveAt<T>(T[], int) + +

+ +

Removes a specific index from given array.

+
+
+ +
+
public static T[] RemoveAt<T>(this T[] source, int index)
+
+ +

Parameters

+
+
source T[]
+

The array to remove index from.

+
+
index int
+

The index to remove.

+
+
+ +

Returns

+
+
T[]
+

A copy of source without given index

+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ ResolveElementType(Array) + +

+ +

Resolves Array element type recusivly.

+
+
+ +
+
public static Type ResolveElementType(this Array arr)
+
+ +

Parameters

+
+
arr Array
+
+
+ +

Returns

+
+
Type
+
+
+ + + + + + + + + + + + + +

+ ResolveRank(Array) + +

+ +

Resolves Array's rank, supports both jagged array and multidim array.

+
+
+ +
+
public static int ResolveRank(this Array arr)
+
+ +

Parameters

+
+
arr Array
+
+
+ +

Returns

+
+
int
+

The number of ranks arr has

+
+
+ + + + + + + + + + + + + +

+ ResolveShape(Array) + +

+ +

Resolves the shape of this given array.

+
+
+ +
+
public static Shape ResolveShape(this Array array)
+
+ +

Parameters

+
+
array Array
+
+
+ +

Returns

+
+
Shape
+
+
+ + + + + + + +

Remarks

+

Supports multi-dim and jagged arrays.

+
+ + + + + + +

+ ResolveShapeAndType(Array) + +

+ +

Resolves the shape of this given array.

+
+
+ +
+
public static (Shape Shape, Type Type) ResolveShapeAndType(this Array array)
+
+ +

Parameters

+
+
array Array
+
+
+ +

Returns

+
+
(Shape Shape, Type Type)
+
+
+ + + + + + + +

Remarks

+

Supports multi-dim and jagged arrays.

+
+ + + + + + +

+ Slice<T>(T[], int, int) + +

+ +

Slice an array.

+
+
+ +
+
public static T[] Slice<T>(this T[] source, int start, int end)
+
+ +

Parameters

+
+
source T[]
+
+
start int
+
+
end int
+
+
+ +

Returns

+
+
T[]
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+

Supports negative end index

+
+ + + + + + +

+ Slice<T>(T[], long, long) + +

+ +

Slice an array.

+
+
+ +
+
public static T[] Slice<T>(this T[] source, long start, long end)
+
+ +

Parameters

+
+
source T[]
+
+
start long
+
+
end long
+
+
+ +

Returns

+
+
T[]
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+

Supports negative end index

+
+ + + + + + +

+ Wrap(NPTypeCode, object) + +

+ +

Creates an array of 1D of type typeCode with length of 1 and a single value inside.

+
+
+ +
+
public static Array Wrap(NPTypeCode typeCode, object value)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+

The type to create this array.

+
+
value object
+

The value to insert

+
+
+ +

Returns

+
+
Array
+
+
+ + + + + + + +

Remarks

+

Do not use this if you are trying to create jagged or multidimensional array.

+
+ + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.ArraysExtensions.html b/docs/website/api/NumSharp.Utilities.ArraysExtensions.html new file mode 100644 index 000000000..d8f76b7c6 --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.ArraysExtensions.html @@ -0,0 +1,219 @@ + + + + + Class ArraysExtensions | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class ArraysExtensions +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public static class ArraysExtensions
+
+ + + + +
+
Inheritance
+
+ +
ArraysExtensions
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Methods +

+ + + + +

+ CloneArray(int[]) + +

+ +

Slice an array.

+
+
+ +
+
public static int[] CloneArray(this int[] source)
+
+ +

Parameters

+
+
source int[]
+
+
+ +

Returns

+
+
int[]
+
+
+ + + + + + + +

Remarks

+

Supports negative end index

+
+ + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.ConcurrentHashset-1.html b/docs/website/api/NumSharp.Utilities.ConcurrentHashset-1.html new file mode 100644 index 000000000..0ea0bec42 --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.ConcurrentHashset-1.html @@ -0,0 +1,1204 @@ + + + + + Class ConcurrentHashset<T> | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class ConcurrentHashset<T> +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class ConcurrentHashset<T> : ISet<T>, ICollection<T>, IEnumerable<T>, IEnumerable where T : unmanaged
+
+ + + +

Type Parameters

+
+
T
+
+
+ +
+
Inheritance
+
+ +
ConcurrentHashset<T>
+
+
+ +
+
Implements
+
+
ISet<T>
+ + + +
+
+ + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ ConcurrentHashset() + +

+ +
+
+ +
+
public ConcurrentHashset()
+
+ + + + + + + + + + + + + + + +

+ ConcurrentHashset(IEnumerable<T>) + +

+ +
+
+ +
+
public ConcurrentHashset(IEnumerable<T> collection)
+
+ +

Parameters

+
+
collection IEnumerable<T>
+
+
+ + + + + + + + + + + + + + +

+ ConcurrentHashset(IEnumerable<T>, IEqualityComparer<T>) + +

+ +
+
+ +
+
public ConcurrentHashset(IEnumerable<T> collection, IEqualityComparer<T> comparer)
+
+ +

Parameters

+
+
collection IEnumerable<T>
+
+
comparer IEqualityComparer<T>
+
+
+ + + + + + + + + + + + + + +

+ ConcurrentHashset(IEqualityComparer<T>) + +

+ +
+
+ +
+
public ConcurrentHashset(IEqualityComparer<T> comparer)
+
+ +

Parameters

+
+
comparer IEqualityComparer<T>
+
+
+ + + + + + + + + + + + +

Properties +

+ + + + +

+ Count + +

+ +

Gets the number of elements contained in the ICollection<T>.

+
+
+ +
+
public int Count { get; }
+
+ + + + + +

Property Value

+
+
int
+

The number of elements contained in the ICollection<T>.

+
+
+ + + + + + + + + + +

+ IsReadOnly + +

+ +

Gets a value indicating whether the ICollection<T> is read-only.

+
+
+ +
+
public bool IsReadOnly { get; }
+
+ + + + + +

Property Value

+
+
bool
+

true if the ICollection<T> is read-only; otherwise, false.

+
+
+ + + + + + + + +

Methods +

+ + + + +

+ Add(T) + +

+ +
+
+ +
+
public bool Add(T item)
+
+ +

Parameters

+
+
item T
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ Clear() + +

+ +

Removes all items from the ICollection<T>.

+
+
+ +
+
public void Clear()
+
+ + + + + + + + + + +

Exceptions

+
+
NotSupportedException
+

The ICollection<T> is read-only.

+
+
+ + + + + +

+ Contains(T) + +

+ +

Determines whether the ICollection<T> contains a specific value.

+
+
+ +
+
public bool Contains(T item)
+
+ +

Parameters

+
+
item T
+

The object to locate in the ICollection<T>.

+
+
+ +

Returns

+
+
bool
+

true if item is found in the ICollection<T>; otherwise, false.

+
+
+ + + + + + + + + + + + + +

+ CopyTo(ArraySlice<T>) + +

+ +
+
+ +
+
public void CopyTo(ArraySlice<T> array)
+
+ +

Parameters

+
+
array ArraySlice<T>
+
+
+ + + + + + + + + + + + + + +

+ CopyTo(ArraySlice<T>, int, int) + +

+ +
+
+ +
+
public void CopyTo(ArraySlice<T> array, int arrayIndex, int count)
+
+ +

Parameters

+
+
array ArraySlice<T>
+
+
arrayIndex int
+
+
count int
+
+
+ + + + + + + + + + + + + + +

+ CopyTo(T[], int) + +

+ +

Copies the elements of the ICollection<T> to an Array, starting at a particular Array index.

+
+
+ +
+
public void CopyTo(T[] array, int arrayIndex)
+
+ +

Parameters

+
+
array T[]
+

The one-dimensional Array that is the destination of the elements copied from ICollection<T>. The Array must have zero-based indexing.

+
+
arrayIndex int
+

The zero-based index in array at which copying begins.

+
+
+ + + + + + + + + +

Exceptions

+
+
ArgumentNullException
+

array is null.

+
+
ArgumentOutOfRangeException
+

arrayIndex is less than 0.

+
+
ArgumentException
+

The number of elements in the source ICollection<T> is greater than the available space from arrayIndex to the end of the destination array.

+
+
+ + + + + +

+ Dispose() + +

+ +
+
+ +
+
public void Dispose()
+
+ + + + + + + + + + + + + + + +

+ Dispose(bool) + +

+ +
+
+ +
+
protected virtual void Dispose(bool disposing)
+
+ +

Parameters

+
+
disposing bool
+
+
+ + + + + + + + + + + + + + +

+ ExceptWith(IEnumerable<T>) + +

+ +

Removes all elements in the specified collection from the current set.

+
+
+ +
+
public void ExceptWith(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+

The collection of items to remove from the set.

+
+
+ + + + + + + + + +

Exceptions

+
+
ArgumentNullException
+

other is null.

+
+
+ + + + + +

+ ~ConcurrentHashset() + +

+ +
+
+ +
+
protected ~ConcurrentHashset()
+
+ + + + + + + + + + + + + + + +

+ GetEnumerator() + +

+ +

Returns an enumerator that iterates through the collection.

+
+
+ +
+
public IEnumerator<T> GetEnumerator()
+
+ + +

Returns

+
+
IEnumerator<T>
+

An enumerator that can be used to iterate through the collection.

+
+
+ + + + + + + + + + + + + +

+ IntersectWith(IEnumerable<T>) + +

+ +

Modifies the current set so that it contains only elements that are also in a specified collection.

+
+
+ +
+
public void IntersectWith(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+

The collection to compare to the current set.

+
+
+ + + + + + + + + +

Exceptions

+
+
ArgumentNullException
+

other is null.

+
+
+ + + + + +

+ IsProperSubsetOf(IEnumerable<T>) + +

+ +

Determines whether the current set is a proper (strict) subset of a specified collection.

+
+
+ +
+
public bool IsProperSubsetOf(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+

The collection to compare to the current set.

+
+
+ +

Returns

+
+
bool
+

true if the current set is a proper subset of other; otherwise, false.

+
+
+ + + + + + + + +

Exceptions

+
+
ArgumentNullException
+

other is null.

+
+
+ + + + + +

+ IsProperSupersetOf(IEnumerable<T>) + +

+ +

Determines whether the current set is a proper (strict) superset of a specified collection.

+
+
+ +
+
public bool IsProperSupersetOf(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+

The collection to compare to the current set.

+
+
+ +

Returns

+
+
bool
+

true if the current set is a proper superset of other; otherwise, false.

+
+
+ + + + + + + + +

Exceptions

+
+
ArgumentNullException
+

other is null.

+
+
+ + + + + +

+ IsSubsetOf(IEnumerable<T>) + +

+ +

Determines whether a set is a subset of a specified collection.

+
+
+ +
+
public bool IsSubsetOf(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+

The collection to compare to the current set.

+
+
+ +

Returns

+
+
bool
+

true if the current set is a subset of other; otherwise, false.

+
+
+ + + + + + + + +

Exceptions

+
+
ArgumentNullException
+

other is null.

+
+
+ + + + + +

+ IsSupersetOf(IEnumerable<T>) + +

+ +

Determines whether the current set is a superset of a specified collection.

+
+
+ +
+
public bool IsSupersetOf(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+

The collection to compare to the current set.

+
+
+ +

Returns

+
+
bool
+

true if the current set is a superset of other; otherwise, false.

+
+
+ + + + + + + + +

Exceptions

+
+
ArgumentNullException
+

other is null.

+
+
+ + + + + +

+ Overlaps(IEnumerable<T>) + +

+ +

Determines whether the current set overlaps with the specified collection.

+
+
+ +
+
public bool Overlaps(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+

The collection to compare to the current set.

+
+
+ +

Returns

+
+
bool
+

true if the current set and other share at least one common element; otherwise, false.

+
+
+ + + + + + + + +

Exceptions

+
+
ArgumentNullException
+

other is null.

+
+
+ + + + + +

+ Remove(T) + +

+ +

Removes the first occurrence of a specific object from the ICollection<T>.

+
+
+ +
+
public bool Remove(T item)
+
+ +

Parameters

+
+
item T
+

The object to remove from the ICollection<T>.

+
+
+ +

Returns

+
+
bool
+

true if item was successfully removed from the ICollection<T>; otherwise, false. This method also returns false if item is not found in the original ICollection<T>.

+
+
+ + + + + + + + +

Exceptions

+
+
NotSupportedException
+

The ICollection<T> is read-only.

+
+
+ + + + + +

+ SetEquals(IEnumerable<T>) + +

+ +

Determines whether the current set and the specified collection contain the same elements.

+
+
+ +
+
public bool SetEquals(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+

The collection to compare to the current set.

+
+
+ +

Returns

+
+
bool
+

true if the current set is equal to other; otherwise, false.

+
+
+ + + + + + + + +

Exceptions

+
+
ArgumentNullException
+

other is null.

+
+
+ + + + + +

+ SymmetricExceptWith(IEnumerable<T>) + +

+ +

Modifies the current set so that it contains only elements that are present either in the current set or in the specified collection, but not both.

+
+
+ +
+
public void SymmetricExceptWith(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+

The collection to compare to the current set.

+
+
+ + + + + + + + + +

Exceptions

+
+
ArgumentNullException
+

other is null.

+
+
+ + + + + +

+ UnionWith(IEnumerable<T>) + +

+ +

Modifies the current set so that it contains all elements that are present in the current set, in the specified collection, or in both.

+
+
+ +
+
public void UnionWith(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+

The collection to compare to the current set.

+
+
+ + + + + + + + + +

Exceptions

+
+
ArgumentNullException
+

other is null.

+
+
+ + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.Converts-1.html b/docs/website/api/NumSharp.Utilities.Converts-1.html new file mode 100644 index 000000000..576f536bb --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.Converts-1.html @@ -0,0 +1,1199 @@ + + + + + Class Converts<T> | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class Converts<T> +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +

Provides various methods related to Convert based on give T.

+
+
+ +
+
public static class Converts<T>
+
+ + + +

Type Parameters

+
+
T
+
+
+ +
+
Inheritance
+
+ +
Converts<T>
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Methods +

+ + + + +

+ From(bool) + +

+ +

Converts bool to T using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static T From(bool obj)
+
+ +

Parameters

+
+
obj bool
+

The object to convert to T from bool

+
+
+ +

Returns

+
+
T
+

A T

+
+
+ + + + + + + + + + + + + +

+ From(byte) + +

+ +

Converts byte to T using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static T From(byte obj)
+
+ +

Parameters

+
+
obj byte
+

The object to convert to T from byte

+
+
+ +

Returns

+
+
T
+

A T

+
+
+ + + + + + + + + + + + + +

+ From(char) + +

+ +

Converts char to T using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static T From(char obj)
+
+ +

Parameters

+
+
obj char
+

The object to convert to T from char

+
+
+ +

Returns

+
+
T
+

A T

+
+
+ + + + + + + + + + + + + +

+ From(decimal) + +

+ +

Converts decimal to T using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static T From(decimal obj)
+
+ +

Parameters

+
+
obj decimal
+

The object to convert to T from decimal

+
+
+ +

Returns

+
+
T
+

A T

+
+
+ + + + + + + + + + + + + +

+ From(double) + +

+ +

Converts double to T using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static T From(double obj)
+
+ +

Parameters

+
+
obj double
+

The object to convert to T from double

+
+
+ +

Returns

+
+
T
+

A T

+
+
+ + + + + + + + + + + + + +

+ From(short) + +

+ +

Converts short to T using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static T From(short obj)
+
+ +

Parameters

+
+
obj short
+

The object to convert to T from short

+
+
+ +

Returns

+
+
T
+

A T

+
+
+ + + + + + + + + + + + + +

+ From(int) + +

+ +

Converts int to T using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static T From(int obj)
+
+ +

Parameters

+
+
obj int
+

The object to convert to T from int

+
+
+ +

Returns

+
+
T
+

A T

+
+
+ + + + + + + + + + + + + +

+ From(long) + +

+ +

Converts long to T using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static T From(long obj)
+
+ +

Parameters

+
+
obj long
+

The object to convert to T from long

+
+
+ +

Returns

+
+
T
+

A T

+
+
+ + + + + + + + + + + + + +

+ From(float) + +

+ +

Converts float to T using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static T From(float obj)
+
+ +

Parameters

+
+
obj float
+

The object to convert to T from float

+
+
+ +

Returns

+
+
T
+

A T

+
+
+ + + + + + + + + + + + + +

+ From(string) + +

+ +

Converts string to T using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static T From(string obj)
+
+ +

Parameters

+
+
obj string
+

The object to convert to T from string

+
+
+ +

Returns

+
+
T
+

A T

+
+
+ + + + + + + + + + + + + +

+ From(ushort) + +

+ +

Converts ushort to T using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static T From(ushort obj)
+
+ +

Parameters

+
+
obj ushort
+

The object to convert to T from ushort

+
+
+ +

Returns

+
+
T
+

A T

+
+
+ + + + + + + + + + + + + +

+ From(uint) + +

+ +

Converts uint to T using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static T From(uint obj)
+
+ +

Parameters

+
+
obj uint
+

The object to convert to T from uint

+
+
+ +

Returns

+
+
T
+

A T

+
+
+ + + + + + + + + + + + + +

+ From(ulong) + +

+ +

Converts ulong to T using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static T From(ulong obj)
+
+ +

Parameters

+
+
obj ulong
+

The object to convert to T from ulong

+
+
+ +

Returns

+
+
T
+

A T

+
+
+ + + + + + + + + + + + + +

+ ToBoolean(T) + +

+ +

Converts T to bool using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static bool ToBoolean(T obj)
+
+ +

Parameters

+
+
obj T
+

The object to convert to bool

+
+
+ +

Returns

+
+
bool
+

A bool

+
+
+ + + + + + + + + + + + + +

+ ToByte(T) + +

+ +

Converts T to byte using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static byte ToByte(T obj)
+
+ +

Parameters

+
+
obj T
+

The object to convert to byte

+
+
+ +

Returns

+
+
byte
+

A byte

+
+
+ + + + + + + + + + + + + +

+ ToChar(T) + +

+ +

Converts T to char using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static char ToChar(T obj)
+
+ +

Parameters

+
+
obj T
+

The object to convert to char

+
+
+ +

Returns

+
+
char
+

A char

+
+
+ + + + + + + + + + + + + +

+ ToDecimal(T) + +

+ +

Converts T to decimal using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static decimal ToDecimal(T obj)
+
+ +

Parameters

+
+
obj T
+

The object to convert to decimal

+
+
+ +

Returns

+
+
decimal
+

A decimal

+
+
+ + + + + + + + + + + + + +

+ ToDouble(T) + +

+ +

Converts T to double using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static double ToDouble(T obj)
+
+ +

Parameters

+
+
obj T
+

The object to convert to double

+
+
+ +

Returns

+
+
double
+

A double

+
+
+ + + + + + + + + + + + + +

+ ToInt16(T) + +

+ +

Converts T to short using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static short ToInt16(T obj)
+
+ +

Parameters

+
+
obj T
+

The object to convert to short

+
+
+ +

Returns

+
+
short
+

A short

+
+
+ + + + + + + + + + + + + +

+ ToInt32(T) + +

+ +

Converts T to int using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static int ToInt32(T obj)
+
+ +

Parameters

+
+
obj T
+

The object to convert to int

+
+
+ +

Returns

+
+
int
+

A int

+
+
+ + + + + + + + + + + + + +

+ ToInt64(T) + +

+ +

Converts T to long using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static long ToInt64(T obj)
+
+ +

Parameters

+
+
obj T
+

The object to convert to long

+
+
+ +

Returns

+
+
long
+

A long

+
+
+ + + + + + + + + + + + + +

+ ToSingle(T) + +

+ +

Converts T to float using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static float ToSingle(T obj)
+
+ +

Parameters

+
+
obj T
+

The object to convert to float

+
+
+ +

Returns

+
+
float
+

A float

+
+
+ + + + + + + + + + + + + +

+ ToString(T) + +

+ +

Converts T to string using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static string ToString(T obj)
+
+ +

Parameters

+
+
obj T
+

The object to convert to string

+
+
+ +

Returns

+
+
string
+

A string

+
+
+ + + + + + + + + + + + + +

+ ToUInt16(T) + +

+ +

Converts T to ushort using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static ushort ToUInt16(T obj)
+
+ +

Parameters

+
+
obj T
+

The object to convert to ushort

+
+
+ +

Returns

+
+
ushort
+

A ushort

+
+
+ + + + + + + + + + + + + +

+ ToUInt32(T) + +

+ +

Converts T to uint using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static uint ToUInt32(T obj)
+
+ +

Parameters

+
+
obj T
+

The object to convert to uint

+
+
+ +

Returns

+
+
uint
+

A uint

+
+
+ + + + + + + + + + + + + +

+ ToUInt64(T) + +

+ +

Converts T to ulong using staticly cached FindConverter<TIn, TOut>().

+
+
+ +
+
public static ulong ToUInt64(T obj)
+
+ +

Parameters

+
+
obj T
+

The object to convert to ulong

+
+
+ +

Returns

+
+
ulong
+

A ulong

+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.Converts.html b/docs/website/api/NumSharp.Utilities.Converts.html new file mode 100644 index 000000000..85e5fe5d1 --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.Converts.html @@ -0,0 +1,11656 @@ + + + + + Class Converts | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class Converts +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +

Provides various methods related to Convert.

+
+
+ +
+
[SuppressMessage("ReSharper", "MergeConditionalExpression")]
+[SuppressMessage("ReSharper", "JoinDeclarationAndInitializer")]
+public static class Converts
+
+ + + + +
+
Inheritance
+
+ +
Converts
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Fields +

+ + + +

+ DBNull + +

+ +
+
+ +
+
public static readonly object DBNull
+
+ + + + +

Field Value

+
+
object
+
+
+ + + + + + + + + +

Methods +

+ + + + +

+ ChangeType(object, NPTypeCode) + +

+ +

Returns an object of the specified type whose value is equivalent to the specified object.

+
+
+ +
+
public static object ChangeType(object value, NPTypeCode typeCode)
+
+ +

Parameters

+
+
value object
+

An object that implements the IConvertible interface.

+
+
typeCode NPTypeCode
+

The type of object to return.

+
+
+ +

Returns

+
+
object
+

An object whose underlying type is typeCode and whose value is equivalent to value. +-or- +A null reference (Nothing in Visual Basic), if value is null and typeCode is Empty, String, or Object.

+
+
+ + + + + + + + +

Exceptions

+
+
InvalidCastException
+

This conversion is not supported. +-or- +value is null and typeCode specifies a value type. +-or- +value does not implement the IConvertible interface.

+
+
FormatException
+

value is not in a format recognized by the typeCode type.

+
+
OverflowException
+

value represents a number that is out of the range of the typeCode type.

+
+
ArgumentException
+

typeCode is invalid.

+
+
+ + + + + +

+ ChangeType(object, NPTypeCode, IFormatProvider) + +

+ +

Returns an object of the specified type whose value is equivalent to the specified object.

+
+
+ +
+
public static object ChangeType(object value, NPTypeCode typeCode, IFormatProvider provider)
+
+ +

Parameters

+
+
value object
+

An object that implements the IConvertible interface.

+
+
typeCode NPTypeCode
+

The type of object to return.

+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
object
+

An object whose underlying type is typeCode and whose value is equivalent to value. +-or- +A null reference (Nothing in Visual Basic), if value is null and typeCode is Empty, String, or Object.

+
+
+ + + + + + + + +

Exceptions

+
+
InvalidCastException
+

This conversion is not supported. +-or- +value is null and typeCode specifies a value type. +-or- +value does not implement the IConvertible interface.

+
+
FormatException
+

value is not in a format recognized by the typeCode type.

+
+
OverflowException
+

value represents a number that is out of the range of the typeCode type.

+
+
ArgumentException
+

typeCode is invalid.

+
+
+ + + + + +

+ ChangeType(object, TypeCode) + +

+ +
+
+ +
+
public static object ChangeType(object value, TypeCode typeCode)
+
+ +

Parameters

+
+
value object
+
+
typeCode TypeCode
+
+
+ +

Returns

+
+
object
+
+
+ + + + + + + + + + + + + +

+ ChangeType(object, TypeCode, IFormatProvider) + +

+ +
+
+ +
+
public static object ChangeType(object value, TypeCode typeCode, IFormatProvider provider)
+
+ +

Parameters

+
+
value object
+
+
typeCode TypeCode
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
object
+
+
+ + + + + + + + + + + + + +

+ ChangeType<TOut>(object) + +

+ +

Returns an object of the specified type whose value is equivalent to the specified object.

+
+
+ +
+
public static TOut ChangeType<TOut>(object value)
+
+ +

Parameters

+
+
value object
+

An object that implements the IConvertible interface.

+
+
+ +

Returns

+
+
TOut
+

An object whose underlying type is typeCode and whose value is equivalent to value. +-or- +A null reference (Nothing in Visual Basic), if value is null and typeCode is Empty, String, or Object.

+
+
+ +

Type Parameters

+
+
TOut
+
+
+ + + + + + + +

Exceptions

+
+
InvalidCastException
+

This conversion is not supported. +-or- +value is null and typeCode specifies a value type. +-or- +value does not implement the IConvertible interface.

+
+
FormatException
+

value is not in a format recognized by the typeCode type.

+
+
OverflowException
+

value represents a number that is out of the range of the typeCode type.

+
+
ArgumentException
+

typeCode is invalid.

+
+
+ + + + + +

+ ChangeType<T>(T, NPTypeCode) + +

+ +

Returns an object of the specified type whose value is equivalent to the specified object.

+
+
+ +
+
public static object ChangeType<T>(T value, NPTypeCode typeCode) where T : IConvertible
+
+ +

Parameters

+
+
value T
+

An object that implements the IConvertible interface.

+
+
typeCode NPTypeCode
+

The type of object to return.

+
+
+ +

Returns

+
+
object
+

An object whose underlying type is typeCode and whose value is equivalent to value. +-or- +A null reference (Nothing in Visual Basic), if value is null and typeCode is Empty, String, or Object.

+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + +

Exceptions

+
+
InvalidCastException
+

This conversion is not supported. +-or- +value is null and typeCode specifies a value type. +-or- +value does not implement the IConvertible interface.

+
+
FormatException
+

value is not in a format recognized by the typeCode type.

+
+
OverflowException
+

value represents a number that is out of the range of the typeCode type.

+
+
ArgumentException
+

typeCode is invalid.

+
+
+ + + + + +

+ ChangeType<TIn, TOut>(TIn) + +

+ +

Returns an object of the specified type whose value is equivalent to the specified object.

+
+
+ +
+
public static TOut ChangeType<TIn, TOut>(TIn value) where TIn : IConvertible where TOut : IConvertible
+
+ +

Parameters

+
+
value TIn
+

An object that implements the IConvertible interface.

+
+
+ +

Returns

+
+
TOut
+

An object whose underlying type is typeCode and whose value is equivalent to value. +-or- +A null reference (Nothing in Visual Basic), if value is null and typeCode is Empty, String, or Object.

+
+
+ +

Type Parameters

+
+
TIn
+
+
TOut
+
+
+ + + + + + + +

Exceptions

+
+
InvalidCastException
+

This conversion is not supported. +-or- +value is null and typeCode specifies a value type. +-or- +value does not implement the IConvertible interface.

+
+
FormatException
+

value is not in a format recognized by the typeCode type.

+
+
OverflowException
+

value represents a number that is out of the range of the typeCode type.

+
+
ArgumentException
+

typeCode is invalid.

+
+
+ + + + + +

+ FindConverter<TIn, TOut>() + +

+ +

Finds the conversion method from Convert based on TIn and TOut.

+
+
+ +
+
public static Func<TIn, TOut> FindConverter<TIn, TOut>()
+
+ + +

Returns

+
+
Func<TIn, TOut>
+
+
+ +

Type Parameters

+
+
TIn
+

The type that is expected as input and to be converted from

+
+
TOut
+

The type we expect to convert to.

+
+
+ + + + + + + + + + + + +

+ FromBase64CharArray(char[], int, int) + +

+ +

Converts the specified range of a Char array, which encodes binary data as Base64 digits, to the equivalent byte array.

+
+
+ +
+
public static byte[] FromBase64CharArray(char[] inArray, int offset, int length)
+
+ +

Parameters

+
+
inArray char[]
+

Chars representing Base64 encoding characters

+
+
offset int
+

A position within the input array.

+
+
length int
+

Number of element to convert.

+
+
+ +

Returns

+
+
byte[]
+

The array of bytes represented by the specified Base64 encoding characters.

+
+
+ + + + + + + + + + + + + +

+ FromBase64String(string) + +

+ +

Converts the specified string, which encodes binary data as Base64 digits, to the equivalent byte array.

+
+
+ +
+
public static byte[] FromBase64String(string s)
+
+ +

Parameters

+
+
s string
+

The string to convert

+
+
+ +

Returns

+
+
byte[]
+

The array of bytes represented by the specifed Base64 string.

+
+
+ + + + + + + + + + + + + +

+ GetTypeCode(object) + +

+ +
+
+ +
+
[Pure]
+public static TypeCode GetTypeCode(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
TypeCode
+
+
+ + + + + + + + + + + + + +

+ IsDBNull(object) + +

+ +
+
+ +
+
[Pure]
+public static bool IsDBNull(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBase64CharArray(byte[], int, int, char[], int) + +

+ +
+
+ +
+
public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut)
+
+ +

Parameters

+
+
inArray byte[]
+
+
offsetIn int
+
+
length int
+
+
outArray char[]
+
+
offsetOut int
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToBase64CharArray(byte[], int, int, char[], int, Base64FormattingOptions) + +

+ +
+
+ +
+
[ComVisible(false)]
+public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut, Base64FormattingOptions options)
+
+ +

Parameters

+
+
inArray byte[]
+
+
offsetIn int
+
+
length int
+
+
outArray char[]
+
+
offsetOut int
+
+
options Base64FormattingOptions
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(NDArray) + +

+ +
+
+ +
+
public static bool ToBoolean(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(bool) + +

+ +
+
+ +
+
public static bool ToBoolean(bool value)
+
+ +

Parameters

+
+
value bool
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(byte) + +

+ +
+
+ +
+
public static bool ToBoolean(byte value)
+
+ +

Parameters

+
+
value byte
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(char) + +

+ +
+
+ +
+
public static bool ToBoolean(char value)
+
+ +

Parameters

+
+
value char
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(DateTime) + +

+ +
+
+ +
+
public static bool ToBoolean(DateTime value)
+
+ +

Parameters

+
+
value DateTime
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(decimal) + +

+ +
+
+ +
+
public static bool ToBoolean(decimal value)
+
+ +

Parameters

+
+
value decimal
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(double) + +

+ +
+
+ +
+
public static bool ToBoolean(double value)
+
+ +

Parameters

+
+
value double
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(short) + +

+ +
+
+ +
+
public static bool ToBoolean(short value)
+
+ +

Parameters

+
+
value short
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(int) + +

+ +
+
+ +
+
public static bool ToBoolean(int value)
+
+ +

Parameters

+
+
value int
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(long) + +

+ +
+
+ +
+
public static bool ToBoolean(long value)
+
+ +

Parameters

+
+
value long
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(object) + +

+ +
+
+ +
+
public static bool ToBoolean(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(object, IFormatProvider) + +

+ +
+
+ +
+
public static bool ToBoolean(object value, IFormatProvider provider)
+
+ +

Parameters

+
+
value object
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(sbyte) + +

+ +
+
+ +
+
public static bool ToBoolean(sbyte value)
+
+ +

Parameters

+
+
value sbyte
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(float) + +

+ +
+
+ +
+
public static bool ToBoolean(float value)
+
+ +

Parameters

+
+
value float
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(string) + +

+ +
+
+ +
+
public static bool ToBoolean(string value)
+
+ +

Parameters

+
+
value string
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(string, IFormatProvider) + +

+ +
+
+ +
+
public static bool ToBoolean(string value, IFormatProvider provider)
+
+ +

Parameters

+
+
value string
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(ushort) + +

+ +
+
+ +
+
public static bool ToBoolean(ushort value)
+
+ +

Parameters

+
+
value ushort
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(uint) + +

+ +
+
+ +
+
public static bool ToBoolean(uint value)
+
+ +

Parameters

+
+
value uint
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToBoolean(ulong) + +

+ +
+
+ +
+
public static bool ToBoolean(ulong value)
+
+ +

Parameters

+
+
value ulong
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ ToByte(NDArray) + +

+ +
+
+ +
+
public static byte ToByte(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(bool) + +

+ +
+
+ +
+
public static byte ToByte(bool value)
+
+ +

Parameters

+
+
value bool
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(byte) + +

+ +
+
+ +
+
public static byte ToByte(byte value)
+
+ +

Parameters

+
+
value byte
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(char) + +

+ +
+
+ +
+
public static byte ToByte(char value)
+
+ +

Parameters

+
+
value char
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(DateTime) + +

+ +
+
+ +
+
public static byte ToByte(DateTime value)
+
+ +

Parameters

+
+
value DateTime
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(decimal) + +

+ +
+
+ +
+
public static byte ToByte(decimal value)
+
+ +

Parameters

+
+
value decimal
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(double) + +

+ +
+
+ +
+
public static byte ToByte(double value)
+
+ +

Parameters

+
+
value double
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(short) + +

+ +
+
+ +
+
public static byte ToByte(short value)
+
+ +

Parameters

+
+
value short
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(int) + +

+ +
+
+ +
+
public static byte ToByte(int value)
+
+ +

Parameters

+
+
value int
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(long) + +

+ +
+
+ +
+
public static byte ToByte(long value)
+
+ +

Parameters

+
+
value long
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(object) + +

+ +
+
+ +
+
public static byte ToByte(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(object, IFormatProvider) + +

+ +
+
+ +
+
public static byte ToByte(object value, IFormatProvider provider)
+
+ +

Parameters

+
+
value object
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(sbyte) + +

+ +
+
+ +
+
public static byte ToByte(sbyte value)
+
+ +

Parameters

+
+
value sbyte
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(float) + +

+ +
+
+ +
+
public static byte ToByte(float value)
+
+ +

Parameters

+
+
value float
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(string) + +

+ +
+
+ +
+
public static byte ToByte(string value)
+
+ +

Parameters

+
+
value string
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(string, IFormatProvider) + +

+ +
+
+ +
+
public static byte ToByte(string value, IFormatProvider provider)
+
+ +

Parameters

+
+
value string
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(ushort) + +

+ +
+
+ +
+
public static byte ToByte(ushort value)
+
+ +

Parameters

+
+
value ushort
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(uint) + +

+ +
+
+ +
+
public static byte ToByte(uint value)
+
+ +

Parameters

+
+
value uint
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToByte(ulong) + +

+ +
+
+ +
+
public static byte ToByte(ulong value)
+
+ +

Parameters

+
+
value ulong
+
+
+ +

Returns

+
+
byte
+
+
+ + + + + + + + + + + + + +

+ ToChar(NDArray) + +

+ +
+
+ +
+
public static char ToChar(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(bool) + +

+ +
+
+ +
+
public static char ToChar(bool value)
+
+ +

Parameters

+
+
value bool
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(byte) + +

+ +
+
+ +
+
public static char ToChar(byte value)
+
+ +

Parameters

+
+
value byte
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(char) + +

+ +
+
+ +
+
public static char ToChar(char value)
+
+ +

Parameters

+
+
value char
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(DateTime) + +

+ +
+
+ +
+
public static char ToChar(DateTime value)
+
+ +

Parameters

+
+
value DateTime
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(decimal) + +

+ +
+
+ +
+
public static char ToChar(decimal value)
+
+ +

Parameters

+
+
value decimal
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(double) + +

+ +
+
+ +
+
public static char ToChar(double value)
+
+ +

Parameters

+
+
value double
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(short) + +

+ +
+
+ +
+
public static char ToChar(short value)
+
+ +

Parameters

+
+
value short
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(int) + +

+ +
+
+ +
+
public static char ToChar(int value)
+
+ +

Parameters

+
+
value int
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(long) + +

+ +
+
+ +
+
public static char ToChar(long value)
+
+ +

Parameters

+
+
value long
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(object) + +

+ +
+
+ +
+
public static char ToChar(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(object, IFormatProvider) + +

+ +
+
+ +
+
public static char ToChar(object value, IFormatProvider provider)
+
+ +

Parameters

+
+
value object
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(sbyte) + +

+ +
+
+ +
+
public static char ToChar(sbyte value)
+
+ +

Parameters

+
+
value sbyte
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(float) + +

+ +
+
+ +
+
public static char ToChar(float value)
+
+ +

Parameters

+
+
value float
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(string) + +

+ +
+
+ +
+
public static char ToChar(string value)
+
+ +

Parameters

+
+
value string
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(string, IFormatProvider) + +

+ +
+
+ +
+
public static char ToChar(string value, IFormatProvider provider)
+
+ +

Parameters

+
+
value string
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(ushort) + +

+ +
+
+ +
+
public static char ToChar(ushort value)
+
+ +

Parameters

+
+
value ushort
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(uint) + +

+ +
+
+ +
+
public static char ToChar(uint value)
+
+ +

Parameters

+
+
value uint
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToChar(ulong) + +

+ +
+
+ +
+
public static char ToChar(ulong value)
+
+ +

Parameters

+
+
value ulong
+
+
+ +

Returns

+
+
char
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(bool) + +

+ +
+
+ +
+
public static DateTime ToDateTime(bool value)
+
+ +

Parameters

+
+
value bool
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(byte) + +

+ +
+
+ +
+
public static DateTime ToDateTime(byte value)
+
+ +

Parameters

+
+
value byte
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(char) + +

+ +
+
+ +
+
public static DateTime ToDateTime(char value)
+
+ +

Parameters

+
+
value char
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(DateTime) + +

+ +
+
+ +
+
public static DateTime ToDateTime(DateTime value)
+
+ +

Parameters

+
+
value DateTime
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(decimal) + +

+ +
+
+ +
+
public static DateTime ToDateTime(decimal value)
+
+ +

Parameters

+
+
value decimal
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(double) + +

+ +
+
+ +
+
public static DateTime ToDateTime(double value)
+
+ +

Parameters

+
+
value double
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(short) + +

+ +
+
+ +
+
public static DateTime ToDateTime(short value)
+
+ +

Parameters

+
+
value short
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(int) + +

+ +
+
+ +
+
public static DateTime ToDateTime(int value)
+
+ +

Parameters

+
+
value int
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(long) + +

+ +
+
+ +
+
public static DateTime ToDateTime(long value)
+
+ +

Parameters

+
+
value long
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(object) + +

+ +
+
+ +
+
public static DateTime ToDateTime(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(object, IFormatProvider) + +

+ +
+
+ +
+
public static DateTime ToDateTime(object value, IFormatProvider provider)
+
+ +

Parameters

+
+
value object
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(sbyte) + +

+ +
+
+ +
+
public static DateTime ToDateTime(sbyte value)
+
+ +

Parameters

+
+
value sbyte
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(float) + +

+ +
+
+ +
+
public static DateTime ToDateTime(float value)
+
+ +

Parameters

+
+
value float
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(string) + +

+ +
+
+ +
+
public static DateTime ToDateTime(string value)
+
+ +

Parameters

+
+
value string
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(string, IFormatProvider) + +

+ +
+
+ +
+
public static DateTime ToDateTime(string value, IFormatProvider provider)
+
+ +

Parameters

+
+
value string
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(ushort) + +

+ +
+
+ +
+
public static DateTime ToDateTime(ushort value)
+
+ +

Parameters

+
+
value ushort
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(uint) + +

+ +
+
+ +
+
public static DateTime ToDateTime(uint value)
+
+ +

Parameters

+
+
value uint
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDateTime(ulong) + +

+ +
+
+ +
+
public static DateTime ToDateTime(ulong value)
+
+ +

Parameters

+
+
value ulong
+
+
+ +

Returns

+
+
DateTime
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(NDArray) + +

+ +
+
+ +
+
public static decimal ToDecimal(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(bool) + +

+ +
+
+ +
+
public static decimal ToDecimal(bool value)
+
+ +

Parameters

+
+
value bool
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(byte) + +

+ +
+
+ +
+
public static decimal ToDecimal(byte value)
+
+ +

Parameters

+
+
value byte
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(char) + +

+ +
+
+ +
+
public static decimal ToDecimal(char value)
+
+ +

Parameters

+
+
value char
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(DateTime) + +

+ +
+
+ +
+
public static decimal ToDecimal(DateTime value)
+
+ +

Parameters

+
+
value DateTime
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(decimal) + +

+ +
+
+ +
+
public static decimal ToDecimal(decimal value)
+
+ +

Parameters

+
+
value decimal
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(double) + +

+ +
+
+ +
+
public static decimal ToDecimal(double value)
+
+ +

Parameters

+
+
value double
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(short) + +

+ +
+
+ +
+
public static decimal ToDecimal(short value)
+
+ +

Parameters

+
+
value short
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(int) + +

+ +
+
+ +
+
public static decimal ToDecimal(int value)
+
+ +

Parameters

+
+
value int
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(long) + +

+ +
+
+ +
+
public static decimal ToDecimal(long value)
+
+ +

Parameters

+
+
value long
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(object) + +

+ +
+
+ +
+
public static decimal ToDecimal(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(object, IFormatProvider) + +

+ +
+
+ +
+
public static decimal ToDecimal(object value, IFormatProvider provider)
+
+ +

Parameters

+
+
value object
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(sbyte) + +

+ +
+
+ +
+
public static decimal ToDecimal(sbyte value)
+
+ +

Parameters

+
+
value sbyte
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(float) + +

+ +
+
+ +
+
public static decimal ToDecimal(float value)
+
+ +

Parameters

+
+
value float
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(string) + +

+ +
+
+ +
+
public static decimal ToDecimal(string value)
+
+ +

Parameters

+
+
value string
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(string, IFormatProvider) + +

+ +
+
+ +
+
public static decimal ToDecimal(string value, IFormatProvider provider)
+
+ +

Parameters

+
+
value string
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(ushort) + +

+ +
+
+ +
+
public static decimal ToDecimal(ushort value)
+
+ +

Parameters

+
+
value ushort
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(uint) + +

+ +
+
+ +
+
public static decimal ToDecimal(uint value)
+
+ +

Parameters

+
+
value uint
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDecimal(ulong) + +

+ +
+
+ +
+
public static decimal ToDecimal(ulong value)
+
+ +

Parameters

+
+
value ulong
+
+
+ +

Returns

+
+
decimal
+
+
+ + + + + + + + + + + + + +

+ ToDouble(NDArray) + +

+ +
+
+ +
+
public static double ToDouble(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(bool) + +

+ +
+
+ +
+
public static double ToDouble(bool value)
+
+ +

Parameters

+
+
value bool
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(byte) + +

+ +
+
+ +
+
public static double ToDouble(byte value)
+
+ +

Parameters

+
+
value byte
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(char) + +

+ +
+
+ +
+
public static double ToDouble(char value)
+
+ +

Parameters

+
+
value char
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(DateTime) + +

+ +
+
+ +
+
public static double ToDouble(DateTime value)
+
+ +

Parameters

+
+
value DateTime
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(decimal) + +

+ +
+
+ +
+
public static double ToDouble(decimal value)
+
+ +

Parameters

+
+
value decimal
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(double) + +

+ +
+
+ +
+
public static double ToDouble(double value)
+
+ +

Parameters

+
+
value double
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(short) + +

+ +
+
+ +
+
public static double ToDouble(short value)
+
+ +

Parameters

+
+
value short
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(int) + +

+ +
+
+ +
+
public static double ToDouble(int value)
+
+ +

Parameters

+
+
value int
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(long) + +

+ +
+
+ +
+
public static double ToDouble(long value)
+
+ +

Parameters

+
+
value long
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(object) + +

+ +
+
+ +
+
public static double ToDouble(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(object, IFormatProvider) + +

+ +
+
+ +
+
public static double ToDouble(object value, IFormatProvider provider)
+
+ +

Parameters

+
+
value object
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(sbyte) + +

+ +
+
+ +
+
public static double ToDouble(sbyte value)
+
+ +

Parameters

+
+
value sbyte
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(float) + +

+ +
+
+ +
+
public static double ToDouble(float value)
+
+ +

Parameters

+
+
value float
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(string) + +

+ +
+
+ +
+
public static double ToDouble(string value)
+
+ +

Parameters

+
+
value string
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(string, IFormatProvider) + +

+ +
+
+ +
+
public static double ToDouble(string value, IFormatProvider provider)
+
+ +

Parameters

+
+
value string
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(ushort) + +

+ +
+
+ +
+
public static double ToDouble(ushort value)
+
+ +

Parameters

+
+
value ushort
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(uint) + +

+ +
+
+ +
+
public static double ToDouble(uint value)
+
+ +

Parameters

+
+
value uint
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToDouble(ulong) + +

+ +
+
+ +
+
public static double ToDouble(ulong value)
+
+ +

Parameters

+
+
value ulong
+
+
+ +

Returns

+
+
double
+
+
+ + + + + + + + + + + + + +

+ ToInt16(NDArray) + +

+ +
+
+ +
+
public static short ToInt16(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(bool) + +

+ +
+
+ +
+
public static short ToInt16(bool value)
+
+ +

Parameters

+
+
value bool
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(byte) + +

+ +
+
+ +
+
public static short ToInt16(byte value)
+
+ +

Parameters

+
+
value byte
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(char) + +

+ +
+
+ +
+
public static short ToInt16(char value)
+
+ +

Parameters

+
+
value char
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(DateTime) + +

+ +
+
+ +
+
public static short ToInt16(DateTime value)
+
+ +

Parameters

+
+
value DateTime
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(decimal) + +

+ +
+
+ +
+
public static short ToInt16(decimal value)
+
+ +

Parameters

+
+
value decimal
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(double) + +

+ +
+
+ +
+
public static short ToInt16(double value)
+
+ +

Parameters

+
+
value double
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(short) + +

+ +
+
+ +
+
public static short ToInt16(short value)
+
+ +

Parameters

+
+
value short
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(int) + +

+ +
+
+ +
+
public static short ToInt16(int value)
+
+ +

Parameters

+
+
value int
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(long) + +

+ +
+
+ +
+
public static short ToInt16(long value)
+
+ +

Parameters

+
+
value long
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(object) + +

+ +
+
+ +
+
public static short ToInt16(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(object, IFormatProvider) + +

+ +
+
+ +
+
public static short ToInt16(object value, IFormatProvider provider)
+
+ +

Parameters

+
+
value object
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(sbyte) + +

+ +
+
+ +
+
public static short ToInt16(sbyte value)
+
+ +

Parameters

+
+
value sbyte
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(float) + +

+ +
+
+ +
+
public static short ToInt16(float value)
+
+ +

Parameters

+
+
value float
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(string) + +

+ +
+
+ +
+
public static short ToInt16(string value)
+
+ +

Parameters

+
+
value string
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(string, IFormatProvider) + +

+ +
+
+ +
+
public static short ToInt16(string value, IFormatProvider provider)
+
+ +

Parameters

+
+
value string
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(ushort) + +

+ +
+
+ +
+
public static short ToInt16(ushort value)
+
+ +

Parameters

+
+
value ushort
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(uint) + +

+ +
+
+ +
+
public static short ToInt16(uint value)
+
+ +

Parameters

+
+
value uint
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt16(ulong) + +

+ +
+
+ +
+
public static short ToInt16(ulong value)
+
+ +

Parameters

+
+
value ulong
+
+
+ +

Returns

+
+
short
+
+
+ + + + + + + + + + + + + +

+ ToInt32(NDArray) + +

+ +
+
+ +
+
public static int ToInt32(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(bool) + +

+ +
+
+ +
+
public static int ToInt32(bool value)
+
+ +

Parameters

+
+
value bool
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(byte) + +

+ +
+
+ +
+
public static int ToInt32(byte value)
+
+ +

Parameters

+
+
value byte
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(char) + +

+ +
+
+ +
+
public static int ToInt32(char value)
+
+ +

Parameters

+
+
value char
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(DateTime) + +

+ +
+
+ +
+
public static int ToInt32(DateTime value)
+
+ +

Parameters

+
+
value DateTime
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(decimal) + +

+ +
+
+ +
+
public static int ToInt32(decimal value)
+
+ +

Parameters

+
+
value decimal
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(double) + +

+ +
+
+ +
+
public static int ToInt32(double value)
+
+ +

Parameters

+
+
value double
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(short) + +

+ +
+
+ +
+
public static int ToInt32(short value)
+
+ +

Parameters

+
+
value short
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(int) + +

+ +
+
+ +
+
public static int ToInt32(int value)
+
+ +

Parameters

+
+
value int
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(long) + +

+ +
+
+ +
+
public static int ToInt32(long value)
+
+ +

Parameters

+
+
value long
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(object) + +

+ +
+
+ +
+
public static int ToInt32(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(object, IFormatProvider) + +

+ +
+
+ +
+
public static int ToInt32(object value, IFormatProvider provider)
+
+ +

Parameters

+
+
value object
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(sbyte) + +

+ +
+
+ +
+
public static int ToInt32(sbyte value)
+
+ +

Parameters

+
+
value sbyte
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(float) + +

+ +
+
+ +
+
public static int ToInt32(float value)
+
+ +

Parameters

+
+
value float
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(string) + +

+ +
+
+ +
+
public static int ToInt32(string value)
+
+ +

Parameters

+
+
value string
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(string, IFormatProvider) + +

+ +
+
+ +
+
public static int ToInt32(string value, IFormatProvider provider)
+
+ +

Parameters

+
+
value string
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(ushort) + +

+ +
+
+ +
+
public static int ToInt32(ushort value)
+
+ +

Parameters

+
+
value ushort
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(uint) + +

+ +
+
+ +
+
public static int ToInt32(uint value)
+
+ +

Parameters

+
+
value uint
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt32(ulong) + +

+ +
+
+ +
+
public static int ToInt32(ulong value)
+
+ +

Parameters

+
+
value ulong
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ ToInt64(NDArray) + +

+ +
+
+ +
+
public static long ToInt64(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(bool) + +

+ +
+
+ +
+
public static long ToInt64(bool value)
+
+ +

Parameters

+
+
value bool
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(byte) + +

+ +
+
+ +
+
public static long ToInt64(byte value)
+
+ +

Parameters

+
+
value byte
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(char) + +

+ +
+
+ +
+
public static long ToInt64(char value)
+
+ +

Parameters

+
+
value char
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(DateTime) + +

+ +
+
+ +
+
public static long ToInt64(DateTime value)
+
+ +

Parameters

+
+
value DateTime
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(decimal) + +

+ +
+
+ +
+
public static long ToInt64(decimal value)
+
+ +

Parameters

+
+
value decimal
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(double) + +

+ +
+
+ +
+
public static long ToInt64(double value)
+
+ +

Parameters

+
+
value double
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(short) + +

+ +
+
+ +
+
public static long ToInt64(short value)
+
+ +

Parameters

+
+
value short
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(int) + +

+ +
+
+ +
+
public static long ToInt64(int value)
+
+ +

Parameters

+
+
value int
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(long) + +

+ +
+
+ +
+
public static long ToInt64(long value)
+
+ +

Parameters

+
+
value long
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(object) + +

+ +
+
+ +
+
public static long ToInt64(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(object, IFormatProvider) + +

+ +
+
+ +
+
public static long ToInt64(object value, IFormatProvider provider)
+
+ +

Parameters

+
+
value object
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(sbyte) + +

+ +
+
+ +
+
public static long ToInt64(sbyte value)
+
+ +

Parameters

+
+
value sbyte
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(float) + +

+ +
+
+ +
+
public static long ToInt64(float value)
+
+ +

Parameters

+
+
value float
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(string) + +

+ +
+
+ +
+
public static long ToInt64(string value)
+
+ +

Parameters

+
+
value string
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(string, IFormatProvider) + +

+ +
+
+ +
+
public static long ToInt64(string value, IFormatProvider provider)
+
+ +

Parameters

+
+
value string
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(ushort) + +

+ +
+
+ +
+
public static long ToInt64(ushort value)
+
+ +

Parameters

+
+
value ushort
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(uint) + +

+ +
+
+ +
+
public static long ToInt64(uint value)
+
+ +

Parameters

+
+
value uint
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToInt64(ulong) + +

+ +
+
+ +
+
public static long ToInt64(ulong value)
+
+ +

Parameters

+
+
value ulong
+
+
+ +

Returns

+
+
long
+
+
+ + + + + + + + + + + + + +

+ ToSByte(bool) + +

+ +
+
+ +
+
public static sbyte ToSByte(bool value)
+
+ +

Parameters

+
+
value bool
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSByte(byte) + +

+ +
+
+ +
+
public static sbyte ToSByte(byte value)
+
+ +

Parameters

+
+
value byte
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSByte(char) + +

+ +
+
+ +
+
public static sbyte ToSByte(char value)
+
+ +

Parameters

+
+
value char
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSByte(DateTime) + +

+ +
+
+ +
+
public static sbyte ToSByte(DateTime value)
+
+ +

Parameters

+
+
value DateTime
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSByte(decimal) + +

+ +
+
+ +
+
public static sbyte ToSByte(decimal value)
+
+ +

Parameters

+
+
value decimal
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSByte(double) + +

+ +
+
+ +
+
public static sbyte ToSByte(double value)
+
+ +

Parameters

+
+
value double
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSByte(short) + +

+ +
+
+ +
+
public static sbyte ToSByte(short value)
+
+ +

Parameters

+
+
value short
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSByte(int) + +

+ +
+
+ +
+
public static sbyte ToSByte(int value)
+
+ +

Parameters

+
+
value int
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSByte(long) + +

+ +
+
+ +
+
public static sbyte ToSByte(long value)
+
+ +

Parameters

+
+
value long
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSByte(object) + +

+ +
+
+ +
+
public static sbyte ToSByte(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSByte(object, IFormatProvider) + +

+ +
+
+ +
+
public static sbyte ToSByte(object value, IFormatProvider provider)
+
+ +

Parameters

+
+
value object
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSByte(sbyte) + +

+ +
+
+ +
+
public static sbyte ToSByte(sbyte value)
+
+ +

Parameters

+
+
value sbyte
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSByte(float) + +

+ +
+
+ +
+
public static sbyte ToSByte(float value)
+
+ +

Parameters

+
+
value float
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSByte(string) + +

+ +
+
+ +
+
public static sbyte ToSByte(string value)
+
+ +

Parameters

+
+
value string
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSByte(string, IFormatProvider) + +

+ +
+
+ +
+
public static sbyte ToSByte(string value, IFormatProvider provider)
+
+ +

Parameters

+
+
value string
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSByte(ushort) + +

+ +
+
+ +
+
public static sbyte ToSByte(ushort value)
+
+ +

Parameters

+
+
value ushort
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSByte(uint) + +

+ +
+
+ +
+
public static sbyte ToSByte(uint value)
+
+ +

Parameters

+
+
value uint
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSByte(ulong) + +

+ +
+
+ +
+
public static sbyte ToSByte(ulong value)
+
+ +

Parameters

+
+
value ulong
+
+
+ +

Returns

+
+
sbyte
+
+
+ + + + + + + + + + + + + +

+ ToSingle(NDArray) + +

+ +
+
+ +
+
public static float ToSingle(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(bool) + +

+ +
+
+ +
+
public static float ToSingle(bool value)
+
+ +

Parameters

+
+
value bool
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(byte) + +

+ +
+
+ +
+
public static float ToSingle(byte value)
+
+ +

Parameters

+
+
value byte
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(char) + +

+ +
+
+ +
+
public static float ToSingle(char value)
+
+ +

Parameters

+
+
value char
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(DateTime) + +

+ +
+
+ +
+
public static float ToSingle(DateTime value)
+
+ +

Parameters

+
+
value DateTime
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(decimal) + +

+ +
+
+ +
+
public static float ToSingle(decimal value)
+
+ +

Parameters

+
+
value decimal
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(double) + +

+ +
+
+ +
+
public static float ToSingle(double value)
+
+ +

Parameters

+
+
value double
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(short) + +

+ +
+
+ +
+
public static float ToSingle(short value)
+
+ +

Parameters

+
+
value short
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(int) + +

+ +
+
+ +
+
public static float ToSingle(int value)
+
+ +

Parameters

+
+
value int
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(long) + +

+ +
+
+ +
+
public static float ToSingle(long value)
+
+ +

Parameters

+
+
value long
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(object) + +

+ +
+
+ +
+
public static float ToSingle(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(object, IFormatProvider) + +

+ +
+
+ +
+
public static float ToSingle(object value, IFormatProvider provider)
+
+ +

Parameters

+
+
value object
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(sbyte) + +

+ +
+
+ +
+
public static float ToSingle(sbyte value)
+
+ +

Parameters

+
+
value sbyte
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(float) + +

+ +
+
+ +
+
public static float ToSingle(float value)
+
+ +

Parameters

+
+
value float
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(string) + +

+ +
+
+ +
+
public static float ToSingle(string value)
+
+ +

Parameters

+
+
value string
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(string, IFormatProvider) + +

+ +
+
+ +
+
public static float ToSingle(string value, IFormatProvider provider)
+
+ +

Parameters

+
+
value string
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(ushort) + +

+ +
+
+ +
+
public static float ToSingle(ushort value)
+
+ +

Parameters

+
+
value ushort
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(uint) + +

+ +
+
+ +
+
public static float ToSingle(uint value)
+
+ +

Parameters

+
+
value uint
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToSingle(ulong) + +

+ +
+
+ +
+
public static float ToSingle(ulong value)
+
+ +

Parameters

+
+
value ulong
+
+
+ +

Returns

+
+
float
+
+
+ + + + + + + + + + + + + +

+ ToString(bool) + +

+ +
+
+ +
+
public static string ToString(bool value)
+
+ +

Parameters

+
+
value bool
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(bool, IFormatProvider) + +

+ +
+
+ +
+
public static string ToString(bool value, IFormatProvider provider)
+
+ +

Parameters

+
+
value bool
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(byte) + +

+ +
+
+ +
+
public static string ToString(byte value)
+
+ +

Parameters

+
+
value byte
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(byte, IFormatProvider) + +

+ +
+
+ +
+
public static string ToString(byte value, IFormatProvider provider)
+
+ +

Parameters

+
+
value byte
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(char) + +

+ +
+
+ +
+
public static string ToString(char value)
+
+ +

Parameters

+
+
value char
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(char, IFormatProvider) + +

+ +
+
+ +
+
public static string ToString(char value, IFormatProvider provider)
+
+ +

Parameters

+
+
value char
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(DateTime) + +

+ +
+
+ +
+
public static string ToString(DateTime value)
+
+ +

Parameters

+
+
value DateTime
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(DateTime, IFormatProvider) + +

+ +
+
+ +
+
public static string ToString(DateTime value, IFormatProvider provider)
+
+ +

Parameters

+
+
value DateTime
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(decimal) + +

+ +
+
+ +
+
public static string ToString(decimal value)
+
+ +

Parameters

+
+
value decimal
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(decimal, IFormatProvider) + +

+ +
+
+ +
+
public static string ToString(decimal value, IFormatProvider provider)
+
+ +

Parameters

+
+
value decimal
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(double) + +

+ +
+
+ +
+
public static string ToString(double value)
+
+ +

Parameters

+
+
value double
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(double, IFormatProvider) + +

+ +
+
+ +
+
public static string ToString(double value, IFormatProvider provider)
+
+ +

Parameters

+
+
value double
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(short) + +

+ +
+
+ +
+
public static string ToString(short value)
+
+ +

Parameters

+
+
value short
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(short, IFormatProvider) + +

+ +
+
+ +
+
public static string ToString(short value, IFormatProvider provider)
+
+ +

Parameters

+
+
value short
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(int) + +

+ +
+
+ +
+
public static string ToString(int value)
+
+ +

Parameters

+
+
value int
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(int, IFormatProvider) + +

+ +
+
+ +
+
public static string ToString(int value, IFormatProvider provider)
+
+ +

Parameters

+
+
value int
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(long) + +

+ +
+
+ +
+
public static string ToString(long value)
+
+ +

Parameters

+
+
value long
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(long, IFormatProvider) + +

+ +
+
+ +
+
public static string ToString(long value, IFormatProvider provider)
+
+ +

Parameters

+
+
value long
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(object) + +

+ +
+
+ +
+
public static string ToString(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(object, IFormatProvider) + +

+ +
+
+ +
+
public static string ToString(object value, IFormatProvider provider)
+
+ +

Parameters

+
+
value object
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(sbyte) + +

+ +
+
+ +
+
public static string ToString(sbyte value)
+
+ +

Parameters

+
+
value sbyte
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(sbyte, IFormatProvider) + +

+ +
+
+ +
+
public static string ToString(sbyte value, IFormatProvider provider)
+
+ +

Parameters

+
+
value sbyte
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(float) + +

+ +
+
+ +
+
public static string ToString(float value)
+
+ +

Parameters

+
+
value float
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(float, IFormatProvider) + +

+ +
+
+ +
+
public static string ToString(float value, IFormatProvider provider)
+
+ +

Parameters

+
+
value float
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(string) + +

+ +
+
+ +
+
public static string ToString(string value)
+
+ +

Parameters

+
+
value string
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(string, IFormatProvider) + +

+ +
+
+ +
+
public static string ToString(string value, IFormatProvider provider)
+
+ +

Parameters

+
+
value string
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(ushort) + +

+ +
+
+ +
+
public static string ToString(ushort value)
+
+ +

Parameters

+
+
value ushort
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(ushort, IFormatProvider) + +

+ +
+
+ +
+
public static string ToString(ushort value, IFormatProvider provider)
+
+ +

Parameters

+
+
value ushort
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(uint) + +

+ +
+
+ +
+
public static string ToString(uint value)
+
+ +

Parameters

+
+
value uint
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(uint, IFormatProvider) + +

+ +
+
+ +
+
public static string ToString(uint value, IFormatProvider provider)
+
+ +

Parameters

+
+
value uint
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(ulong) + +

+ +
+
+ +
+
public static string ToString(ulong value)
+
+ +

Parameters

+
+
value ulong
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToString(ulong, IFormatProvider) + +

+ +
+
+ +
+
public static string ToString(ulong value, IFormatProvider provider)
+
+ +

Parameters

+
+
value ulong
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
string
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(NDArray) + +

+ +
+
+ +
+
public static ushort ToUInt16(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(bool) + +

+ +
+
+ +
+
public static ushort ToUInt16(bool value)
+
+ +

Parameters

+
+
value bool
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(byte) + +

+ +
+
+ +
+
public static ushort ToUInt16(byte value)
+
+ +

Parameters

+
+
value byte
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(char) + +

+ +
+
+ +
+
public static ushort ToUInt16(char value)
+
+ +

Parameters

+
+
value char
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(DateTime) + +

+ +
+
+ +
+
public static ushort ToUInt16(DateTime value)
+
+ +

Parameters

+
+
value DateTime
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(decimal) + +

+ +
+
+ +
+
public static ushort ToUInt16(decimal value)
+
+ +

Parameters

+
+
value decimal
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(double) + +

+ +
+
+ +
+
public static ushort ToUInt16(double value)
+
+ +

Parameters

+
+
value double
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(short) + +

+ +
+
+ +
+
public static ushort ToUInt16(short value)
+
+ +

Parameters

+
+
value short
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(int) + +

+ +
+
+ +
+
public static ushort ToUInt16(int value)
+
+ +

Parameters

+
+
value int
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(long) + +

+ +
+
+ +
+
public static ushort ToUInt16(long value)
+
+ +

Parameters

+
+
value long
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(object) + +

+ +
+
+ +
+
public static ushort ToUInt16(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(object, IFormatProvider) + +

+ +
+
+ +
+
public static ushort ToUInt16(object value, IFormatProvider provider)
+
+ +

Parameters

+
+
value object
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(sbyte) + +

+ +
+
+ +
+
public static ushort ToUInt16(sbyte value)
+
+ +

Parameters

+
+
value sbyte
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(float) + +

+ +
+
+ +
+
public static ushort ToUInt16(float value)
+
+ +

Parameters

+
+
value float
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(string) + +

+ +
+
+ +
+
public static ushort ToUInt16(string value)
+
+ +

Parameters

+
+
value string
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(string, IFormatProvider) + +

+ +
+
+ +
+
public static ushort ToUInt16(string value, IFormatProvider provider)
+
+ +

Parameters

+
+
value string
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(ushort) + +

+ +
+
+ +
+
public static ushort ToUInt16(ushort value)
+
+ +

Parameters

+
+
value ushort
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(uint) + +

+ +
+
+ +
+
public static ushort ToUInt16(uint value)
+
+ +

Parameters

+
+
value uint
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt16(ulong) + +

+ +
+
+ +
+
public static ushort ToUInt16(ulong value)
+
+ +

Parameters

+
+
value ulong
+
+
+ +

Returns

+
+
ushort
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(NDArray) + +

+ +
+
+ +
+
public static uint ToUInt32(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(bool) + +

+ +
+
+ +
+
public static uint ToUInt32(bool value)
+
+ +

Parameters

+
+
value bool
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(byte) + +

+ +
+
+ +
+
public static uint ToUInt32(byte value)
+
+ +

Parameters

+
+
value byte
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(char) + +

+ +
+
+ +
+
public static uint ToUInt32(char value)
+
+ +

Parameters

+
+
value char
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(DateTime) + +

+ +
+
+ +
+
public static uint ToUInt32(DateTime value)
+
+ +

Parameters

+
+
value DateTime
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(decimal) + +

+ +
+
+ +
+
public static uint ToUInt32(decimal value)
+
+ +

Parameters

+
+
value decimal
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(double) + +

+ +
+
+ +
+
public static uint ToUInt32(double value)
+
+ +

Parameters

+
+
value double
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(short) + +

+ +
+
+ +
+
public static uint ToUInt32(short value)
+
+ +

Parameters

+
+
value short
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(int) + +

+ +
+
+ +
+
public static uint ToUInt32(int value)
+
+ +

Parameters

+
+
value int
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(long) + +

+ +
+
+ +
+
public static uint ToUInt32(long value)
+
+ +

Parameters

+
+
value long
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(object) + +

+ +
+
+ +
+
public static uint ToUInt32(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(object, IFormatProvider) + +

+ +
+
+ +
+
public static uint ToUInt32(object value, IFormatProvider provider)
+
+ +

Parameters

+
+
value object
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(sbyte) + +

+ +
+
+ +
+
public static uint ToUInt32(sbyte value)
+
+ +

Parameters

+
+
value sbyte
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(float) + +

+ +
+
+ +
+
public static uint ToUInt32(float value)
+
+ +

Parameters

+
+
value float
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(string) + +

+ +
+
+ +
+
public static uint ToUInt32(string value)
+
+ +

Parameters

+
+
value string
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(string, IFormatProvider) + +

+ +
+
+ +
+
public static uint ToUInt32(string value, IFormatProvider provider)
+
+ +

Parameters

+
+
value string
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(ushort) + +

+ +
+
+ +
+
public static uint ToUInt32(ushort value)
+
+ +

Parameters

+
+
value ushort
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(uint) + +

+ +
+
+ +
+
public static uint ToUInt32(uint value)
+
+ +

Parameters

+
+
value uint
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt32(ulong) + +

+ +
+
+ +
+
public static uint ToUInt32(ulong value)
+
+ +

Parameters

+
+
value ulong
+
+
+ +

Returns

+
+
uint
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(NDArray) + +

+ +
+
+ +
+
public static ulong ToUInt64(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(bool) + +

+ +
+
+ +
+
public static ulong ToUInt64(bool value)
+
+ +

Parameters

+
+
value bool
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(byte) + +

+ +
+
+ +
+
public static ulong ToUInt64(byte value)
+
+ +

Parameters

+
+
value byte
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(char) + +

+ +
+
+ +
+
public static ulong ToUInt64(char value)
+
+ +

Parameters

+
+
value char
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(DateTime) + +

+ +
+
+ +
+
public static ulong ToUInt64(DateTime value)
+
+ +

Parameters

+
+
value DateTime
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(decimal) + +

+ +
+
+ +
+
public static ulong ToUInt64(decimal value)
+
+ +

Parameters

+
+
value decimal
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(double) + +

+ +
+
+ +
+
public static ulong ToUInt64(double value)
+
+ +

Parameters

+
+
value double
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(short) + +

+ +
+
+ +
+
public static ulong ToUInt64(short value)
+
+ +

Parameters

+
+
value short
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(int) + +

+ +
+
+ +
+
public static ulong ToUInt64(int value)
+
+ +

Parameters

+
+
value int
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(long) + +

+ +
+
+ +
+
public static ulong ToUInt64(long value)
+
+ +

Parameters

+
+
value long
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(object) + +

+ +
+
+ +
+
public static ulong ToUInt64(object value)
+
+ +

Parameters

+
+
value object
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(object, IFormatProvider) + +

+ +
+
+ +
+
public static ulong ToUInt64(object value, IFormatProvider provider)
+
+ +

Parameters

+
+
value object
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(sbyte) + +

+ +
+
+ +
+
public static ulong ToUInt64(sbyte value)
+
+ +

Parameters

+
+
value sbyte
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(float) + +

+ +
+
+ +
+
public static ulong ToUInt64(float value)
+
+ +

Parameters

+
+
value float
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(string) + +

+ +
+
+ +
+
public static ulong ToUInt64(string value)
+
+ +

Parameters

+
+
value string
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(string, IFormatProvider) + +

+ +
+
+ +
+
public static ulong ToUInt64(string value, IFormatProvider provider)
+
+ +

Parameters

+
+
value string
+
+
provider IFormatProvider
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(ushort) + +

+ +
+
+ +
+
public static ulong ToUInt64(ushort value)
+
+ +

Parameters

+
+
value ushort
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(uint) + +

+ +
+
+ +
+
public static ulong ToUInt64(uint value)
+
+ +

Parameters

+
+
value uint
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ ToUInt64(ulong) + +

+ +
+
+ +
+
public static ulong ToUInt64(ulong value)
+
+ +

Parameters

+
+
value ulong
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.Hashset-1.Enumerator.html b/docs/website/api/NumSharp.Utilities.Hashset-1.Enumerator.html new file mode 100644 index 000000000..1fe53358e --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.Hashset-1.Enumerator.html @@ -0,0 +1,290 @@ + + + + + Struct Hashset<T>.Enumerator | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Struct Hashset<T>.Enumerator +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public struct Hashset<T>.Enumerator : IEnumerator<T>, IDisposable, IEnumerator
+
+ + + + + +
+
Implements
+
+ + + +
+
+ + +
+
Inherited Members
+
+ + + + + + +
+ +
+
Extension Methods
+
+ + +
+ + + + + +

Properties +

+ + + + +

+ Current + +

+ +

Gets the element in the collection at the current position of the enumerator.

+
+
+ +
+
public T Current { get; }
+
+ + + + + +

Property Value

+
+
T
+

The element in the collection at the current position of the enumerator.

+
+
+ + + + + + + + +

Methods +

+ + + + +

+ Dispose() + +

+ +

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

+
+
+ +
+
public void Dispose()
+
+ + + + + + + + + + + + + + + +

+ MoveNext() + +

+ +

Advances the enumerator to the next element of the collection.

+
+
+ +
+
public bool MoveNext()
+
+ + +

Returns

+
+
bool
+

true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.

+
+
+ + + + + + + + +

Exceptions

+
+
InvalidOperationException
+

The collection was modified after the enumerator was created.

+
+
+ + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.Hashset-1.html b/docs/website/api/NumSharp.Utilities.Hashset-1.html new file mode 100644 index 000000000..ee85fce8f --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.Hashset-1.html @@ -0,0 +1,1382 @@ + + + + + Class Hashset<T> | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class Hashset<T> +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "By design")]
+public class Hashset<T> : ISet<T>, ICollection<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
+
+ + + +

Type Parameters

+
+
T
+
+
+ +
+
Inheritance
+
+ +
Hashset<T>
+
+
+ +
+
Implements
+
+
ISet<T>
+ + + + +
+
+ + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ Hashset() + +

+ +
+
+ +
+
public Hashset()
+
+ + + + + + + + + + + + + + + +

+ Hashset(IEnumerable<T>) + +

+ +
+
+ +
+
public Hashset(IEnumerable<T> collection)
+
+ +

Parameters

+
+
collection IEnumerable<T>
+
+
+ + + + + + + + + + + + + + +

+ Hashset(IEnumerable<T>, IEqualityComparer<T>) + +

+ +

Implementation Notes: +Since resizes are relatively expensive (require rehashing), this attempts to minimize +the need to resize by setting the initial capacity based on size of collection.

+
+
+ +
+
public Hashset(IEnumerable<T> collection, IEqualityComparer<T> comparer)
+
+ +

Parameters

+
+
collection IEnumerable<T>
+
+
comparer IEqualityComparer<T>
+
+
+ + + + + + + + + + + + + + +

+ Hashset(IEqualityComparer<T>) + +

+ +
+
+ +
+
public Hashset(IEqualityComparer<T> comparer)
+
+ +

Parameters

+
+
comparer IEqualityComparer<T>
+
+
+ + + + + + + + + + + + + + +

+ Hashset(int) + +

+ +
+
+ +
+
public Hashset(int capacity)
+
+ +

Parameters

+
+
capacity int
+
+
+ + + + + + + + + + + + + + +

+ Hashset(int, IEqualityComparer<T>) + +

+ +
+
+ +
+
public Hashset(int capacity, IEqualityComparer<T> comparer)
+
+ +

Parameters

+
+
capacity int
+
+
comparer IEqualityComparer<T>
+
+
+ + + + + + + + + + + + +

Properties +

+ + + + +

+ Comparer + +

+ +

Gets the IEqualityComparer that is used to determine equality of keys for +the HashSet.

+
+
+ +
+
public IEqualityComparer<T> Comparer { get; }
+
+ + + + + +

Property Value

+
+
IEqualityComparer<T>
+
+
+ + + + + + + + + + +

+ Count + +

+ +

Number of elements in this hashset

+
+
+ +
+
public int Count { get; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ Add(T) + +

+ +

Add item to this HashSet. Returns bool indicating whether item was added (won't be +added if already present)

+
+
+ +
+
public bool Add(T item)
+
+ +

Parameters

+
+
item T
+
+
+ +

Returns

+
+
bool
+

true if added, false if already present

+
+
+ + + + + + + + + + + + + +

+ Clear() + +

+ +

Remove all items from this set. This clears the elements but not the underlying +buckets and slots array. Follow this call by TrimExcess to release these.

+
+
+ +
+
public void Clear()
+
+ + + + + + + + + + + + + + + +

+ Contains(T) + +

+ +

Checks if this hashset contains the item

+
+
+ +
+
public bool Contains(T item)
+
+ +

Parameters

+
+
item T
+

item to check for containment

+
+
+ +

Returns

+
+
bool
+

true if item contained; false if not

+
+
+ + + + + + + + + + + + + +

+ CopyTo(T[]) + +

+ +
+
+ +
+
public void CopyTo(T[] array)
+
+ +

Parameters

+
+
array T[]
+
+
+ + + + + + + + + + + + + + +

+ CopyTo(T[], int) + +

+ +

Copy items in this hashset to array, starting at arrayIndex

+
+
+ +
+
public void CopyTo(T[] array, int arrayIndex)
+
+ +

Parameters

+
+
array T[]
+

array to add items to

+
+
arrayIndex int
+

index to start at

+
+
+ + + + + + + + + + + + + + +

+ CopyTo(T[], int, int) + +

+ +
+
+ +
+
public void CopyTo(T[] array, int arrayIndex, int count)
+
+ +

Parameters

+
+
array T[]
+
+
arrayIndex int
+
+
count int
+
+
+ + + + + + + + + + + + + + +

+ CopyTo<T>(Hashset<T>, ArraySlice<T>) + +

+ +
+
+ +
+
public static void CopyTo<T>(Hashset<T> src, ArraySlice<T> array) where T : unmanaged
+
+ +

Parameters

+
+
src Hashset<T>
+
+
array ArraySlice<T>
+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ CopyTo<T>(Hashset<T>, ArraySlice<T>, int, int) + +

+ +
+
+ +
+
public static void CopyTo<T>(Hashset<T> src, ArraySlice<T> array, int arrayIndex, int count) where T : unmanaged
+
+ +

Parameters

+
+
src Hashset<T>
+
+
array ArraySlice<T>
+
+
arrayIndex int
+
+
count int
+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ CreateSetComparer() + +

+ +

Used for deep equality of HashSet testing

+
+
+ +
+
public static IEqualityComparer<Hashset<T>> CreateSetComparer()
+
+ + +

Returns

+
+
IEqualityComparer<Hashset<T>>
+
+
+ + + + + + + + + + + + + +

+ ExceptWith(IEnumerable<T>) + +

+ +

Remove items in other from this set. Modifies this set.

+
+
+ +
+
public void ExceptWith(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+

enumerable with items to remove

+
+
+ + + + + + + + + + + + + + +

+ GetEnumerator() + +

+ +
+
+ +
+
public Hashset<T>.Enumerator GetEnumerator()
+
+ + +

Returns

+
+
Hashset<T>.Enumerator
+
+
+ + + + + + + + + + + + + +

+ IntersectWith(IEnumerable<T>) + +

+ +

Takes the intersection of this set with other. Modifies this set.

+

Implementation Notes: +We get better perf if other is a hashset using same equality comparer, because we +get constant contains check in other. Resulting cost is O(n1) to iterate over this.

+

If we can't go above route, iterate over the other and mark intersection by checking +contains in this. Then loop over and delete any unmarked elements. Total cost is n2+n1.

+

Attempts to return early based on counts alone, using the property that the +intersection of anything with the empty set is the empty set.

+
+
+ +
+
public void IntersectWith(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+

enumerable with items to add

+
+
+ + + + + + + + + + + + + + +

+ IsProperSubsetOf(IEnumerable<T>) + +

+ +

Checks if this is a proper subset of other (i.e. strictly contained in)

+

Implementation Notes: +The following properties are used up-front to avoid element-wise checks:

+
    +
  1. If this is the empty set, then it's a proper subset of a set that contains at least +one element, but it's not a proper subset of the empty set.
  2. +
  3. If other has unique elements according to this equality comparer, and this has >= +the number of elements in other, then this can't be a proper subset.
  4. +
+

Furthermore, if other is a hashset using the same equality comparer, we can use a +faster element-wise check.

+
+
+ +
+
public bool IsProperSubsetOf(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+
+
+ +

Returns

+
+
bool
+

true if this is a proper subset of other; false if not

+
+
+ + + + + + + + + + + + + +

+ IsProperSupersetOf(IEnumerable<T>) + +

+ +

Checks if this is a proper superset of other (i.e. other strictly contained in this)

+

Implementation Notes: +This is slightly more complicated than above because we have to keep track if there +was at least one element not contained in other.

+

The following properties are used up-front to avoid element-wise checks:

+
    +
  1. If this is the empty set, then it can't be a proper superset of any set, even if +other is the empty set.
  2. +
  3. If other is an empty set and this contains at least 1 element, then this is a proper +superset.
  4. +
  5. If other has unique elements according to this equality comparer, and other's count +is greater than or equal to this count, then this can't be a proper superset
  6. +
+

Furthermore, if other has unique elements according to this equality comparer, we can +use a faster element-wise check.

+
+
+ +
+
public bool IsProperSupersetOf(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+
+
+ +

Returns

+
+
bool
+

true if this is a proper superset of other; false if not

+
+
+ + + + + + + + + + + + + +

+ IsSubsetOf(IEnumerable<T>) + +

+ +

Checks if this is a subset of other.

+

Implementation Notes: +The following properties are used up-front to avoid element-wise checks:

+
    +
  1. If this is the empty set, then it's a subset of anything, including the empty set
  2. +
  3. If other has unique elements according to this equality comparer, and this has more +elements than other, then it can't be a subset.
  4. +
+

Furthermore, if other is a hashset using the same equality comparer, we can use a +faster element-wise check.

+
+
+ +
+
public bool IsSubsetOf(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+
+
+ +

Returns

+
+
bool
+

true if this is a subset of other; false if not

+
+
+ + + + + + + + + + + + + +

+ IsSupersetOf(IEnumerable<T>) + +

+ +

Checks if this is a superset of other

+

Implementation Notes: +The following properties are used up-front to avoid element-wise checks:

+
    +
  1. If other has no elements (it's the empty set), then this is a superset, even if this +is also the empty set.
  2. +
  3. If other has unique elements according to this equality comparer, and this has less +than the number of elements in other, then this can't be a superset
  4. +
+
+
+ +
+
public bool IsSupersetOf(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+
+
+ +

Returns

+
+
bool
+

true if this is a superset of other; false if not

+
+
+ + + + + + + + + + + + + +

+ Overlaps(IEnumerable<T>) + +

+ +

Checks if this set overlaps other (i.e. they share at least one item)

+
+
+ +
+
public bool Overlaps(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+
+
+ +

Returns

+
+
bool
+

true if these have at least one common element; false if disjoint

+
+
+ + + + + + + + + + + + + +

+ Remove(T) + +

+ +

Remove item from this hashset

+
+
+ +
+
public bool Remove(T item)
+
+ +

Parameters

+
+
item T
+

item to remove

+
+
+ +

Returns

+
+
bool
+

true if removed; false if not (i.e. if the item wasn't in the HashSet)

+
+
+ + + + + + + + + + + + + +

+ RemoveWhere(Predicate<T>) + +

+ +

Remove elements that match specified predicate. Returns the number of elements removed

+
+
+ +
+
public int RemoveWhere(Predicate<T> match)
+
+ +

Parameters

+
+
match Predicate<T>
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ SetEquals(IEnumerable<T>) + +

+ +

Checks if this and other contain the same elements. This is set equality: +duplicates and order are ignored

+
+
+ +
+
public bool SetEquals(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ SymmetricExceptWith(IEnumerable<T>) + +

+ +

Takes symmetric difference (XOR) with other and this set. Modifies this set.

+
+
+ +
+
public void SymmetricExceptWith(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+

enumerable with items to XOR

+
+
+ + + + + + + + + + + + + + +

+ TrimExcess() + +

+ +

Sets the capacity of this list to the size of the list (rounded up to nearest prime), +unless count is 0, in which case we release references.

+

This method can be used to minimize a list's memory overhead once it is known that no +new elements will be added to the list. To completely clear a list and release all +memory referenced by the list, execute the following statements:

+

list.Clear(); +list.TrimExcess();

+
+
+ +
+
public void TrimExcess()
+
+ + + + + + + + + + + + + + + +

+ TryGetValue(T, out T) + +

+ +

Searches the set for a given value and returns the equal value it finds, if any.

+
+
+ +
+
public bool TryGetValue(T equalValue, out T actualValue)
+
+ +

Parameters

+
+
equalValue T
+

The value to search for.

+
+
actualValue T
+

The value from the set that the search found, or the default value of T when the search yielded no match.

+
+
+ +

Returns

+
+
bool
+

A value indicating whether the search was successful.

+
+
+ + + + + + + +

Remarks

+

This can be useful when you want to reuse a previously stored reference instead of +a newly constructed one (so that more sharing of references can occur) or to look up +a value that has more complete data than the value you currently have, although their +comparer functions indicate they are equal.

+
+ + + + + + +

+ UnionWith(IEnumerable<T>) + +

+ +

Take the union of this HashSet with other. Modifies this set.

+

Implementation note: GetSuggestedCapacity (to increase capacity in advance avoiding +multiple resizes ended up not being useful in practice; quickly gets to the +point where it's a wasteful check.

+
+
+ +
+
public void UnionWith(IEnumerable<T> other)
+
+ +

Parameters

+
+
other IEnumerable<T>
+

enumerable with items to add

+
+
+ + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.InfoOf-1.html b/docs/website/api/NumSharp.Utilities.InfoOf-1.html new file mode 100644 index 000000000..3e8dad008 --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.InfoOf-1.html @@ -0,0 +1,343 @@ + + + + + Class InfoOf<T> | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class InfoOf<T> +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +

Provides a cache for properties of T that requires computation.

+
+
+ +
+
[SuppressMessage("ReSharper", "StaticMemberInGenericType")]
+public class InfoOf<T>
+
+ + + +

Type Parameters

+
+
T
+
+
+ +
+
Inheritance
+
+ +
InfoOf<T>
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Fields +

+ + + +

+ MaxValue + +

+ +
+
+ +
+
public static readonly T MaxValue
+
+ + + + +

Field Value

+
+
T
+
+
+ + + + + + + + + + +

+ MinValue + +

+ +
+
+ +
+
public static readonly T MinValue
+
+ + + + +

Field Value

+
+
T
+
+
+ + + + + + + + + + +

+ NPTypeCode + +

+ +
+
+ +
+
public static readonly NPTypeCode NPTypeCode
+
+ + + + +

Field Value

+
+
NPTypeCode
+
+
+ + + + + + + + + + +

+ Size + +

+ +
+
+ +
+
public static readonly int Size
+
+ + + + +

Field Value

+
+
int
+
+
+ + + + + + + + + + +

+ Zero + +

+ +
+
+ +
+
public static readonly T Zero
+
+ + + + +

Field Value

+
+
T
+
+
+ + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.Linq.IEnumeratorExtensions.html b/docs/website/api/NumSharp.Utilities.Linq.IEnumeratorExtensions.html new file mode 100644 index 000000000..4e75a9bd1 --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.Linq.IEnumeratorExtensions.html @@ -0,0 +1,221 @@ + + + + + Class IEnumeratorExtensions | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class IEnumeratorExtensions +

+ +
+
Namespace
NumSharp.Utilities.Linq
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public static class IEnumeratorExtensions
+
+ + + + +
+
Inheritance
+
+ +
IEnumeratorExtensions
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Methods +

+ + + + +

+ ToIEnumerable<T>(IEnumerator<T>) + +

+ + +
+ +
+
public static IEnumerable<T> ToIEnumerable<T>(this IEnumerator<T> enumerator)
+
+ +

Parameters

+
+
enumerator IEnumerator<T>
+
+
+ +

Returns

+
+
IEnumerable<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.Linq.IExtremaEnumerable-1.html b/docs/website/api/NumSharp.Utilities.Linq.IExtremaEnumerable-1.html new file mode 100644 index 000000000..d8bdc3e3b --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.Linq.IExtremaEnumerable-1.html @@ -0,0 +1,251 @@ + + + + + Interface IExtremaEnumerable<T> | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Interface IExtremaEnumerable<T> +

+ +
+
Namespace
NumSharp.Utilities.Linq
+
Assembly
NumSharp.dll
+
+ +

Exposes the enumerator, which supports iteration over a sequence of +some extremum property (maximum or minimum) of a specified type.

+
+
+ +
+
public interface IExtremaEnumerable<out T> : IEnumerable<T>, IEnumerable
+
+ + + +

Type Parameters

+
+
T
+

The type of objects to enumerate.

+
+
+ + + + +
+
Inherited Members
+
+ +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Methods +

+ + + + +

+ Take(int) + +

+ +

Returns a specified number of contiguous elements from the start of +the sequence.

+
+
+ +
+
IEnumerable<out T> Take(int count)
+
+ +

Parameters

+
+
count int
+

The number of elements to return.

+
+
+ +

Returns

+
+
IEnumerable<T>
+

An IEnumerable<T> that contains the specified number +of elements from the start of the input sequence.

+
+
+ + + + + + + + + + + + + +

+ TakeLast(int) + +

+ +

Returns a specified number of contiguous elements at the end of the +sequence.

+
+
+ +
+
IEnumerable<out T> TakeLast(int count)
+
+ +

Parameters

+
+
count int
+

The number of elements to return.

+
+
+ +

Returns

+
+
IEnumerable<T>
+

An IEnumerable<T> that contains the specified number +of elements at the end of the input sequence.

+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.Linq.html b/docs/website/api/NumSharp.Utilities.Linq.html new file mode 100644 index 000000000..40dc95cca --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.Linq.html @@ -0,0 +1,135 @@ + + + + + Namespace NumSharp.Utilities.Linq | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ +

Namespace NumSharp.Utilities.Linq

+
+
+
+ +

+Classes +

+
+
IEnumeratorExtensions
+
+
+

+Interfaces +

+
+
IExtremaEnumerable<T>
+

Exposes the enumerator, which supports iteration over a sequence of +some extremum property (maximum or minimum) of a specified type.

+
+
+ + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.NDCoordinatesAxisIncrementor.html b/docs/website/api/NumSharp.Utilities.NDCoordinatesAxisIncrementor.html new file mode 100644 index 000000000..cb8aa7766 --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.NDCoordinatesAxisIncrementor.html @@ -0,0 +1,477 @@ + + + + + Class NDCoordinatesAxisIncrementor | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NDCoordinatesAxisIncrementor +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class NDCoordinatesAxisIncrementor
+
+ + + + +
+
Inheritance
+
+ +
NDCoordinatesAxisIncrementor
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ NDCoordinatesAxisIncrementor(ref Shape, int) + +

+ +
+
+ +
+
public NDCoordinatesAxisIncrementor(ref Shape shape, int axis)
+
+ +

Parameters

+
+
shape Shape
+
+
axis int
+
+
+ + + + + + + + + + + + + + +

+ NDCoordinatesAxisIncrementor(ref Shape, int, Action<NDCoordinatesAxisIncrementor>) + +

+ +
+
+ +
+
public NDCoordinatesAxisIncrementor(ref Shape shape, int axis, Action<NDCoordinatesAxisIncrementor> endCallback)
+
+ +

Parameters

+
+
shape Shape
+
+
axis int
+
+
endCallback Action<NDCoordinatesAxisIncrementor>
+
+
+ + + + + + + + + + + + + + +

+ NDCoordinatesAxisIncrementor(int[], int) + +

+ +
+
+ +
+
public NDCoordinatesAxisIncrementor(int[] dims, int axis)
+
+ +

Parameters

+
+
dims int[]
+
+
axis int
+
+
+ + + + + + + + + + + + + + +

+ NDCoordinatesAxisIncrementor(int[], int, Action<NDCoordinatesAxisIncrementor>) + +

+ +
+
+ +
+
public NDCoordinatesAxisIncrementor(int[] dims, int axis, Action<NDCoordinatesAxisIncrementor> endCallback)
+
+ +

Parameters

+
+
dims int[]
+
+
axis int
+
+
endCallback Action<NDCoordinatesAxisIncrementor>
+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ Axis + +

+ +
+
+ +
+
public int Axis
+
+ + + + +

Field Value

+
+
int
+
+
+ + + + + + + + + + +

+ Index + +

+ +
+
+ +
+
public readonly int[] Index
+
+ + + + +

Field Value

+
+
int[]
+
+
+ + + + + + + + + + +

+ Slices + +

+ +
+
+ +
+
public readonly Slice[] Slices
+
+ + + + +

Field Value

+
+
Slice[]
+
+
+ + + + + + + + + +

Methods +

+ + + + +

+ Next() + +

+ +
+
+ +
+
public Slice[] Next()
+
+ + +

Returns

+
+
Slice[]
+
+
+ + + + + + + + + + + + + +

+ Reset() + +

+ +
+
+ +
+
public void Reset()
+
+ + + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.NDCoordinatesIncrementor.html b/docs/website/api/NumSharp.Utilities.NDCoordinatesIncrementor.html new file mode 100644 index 000000000..192231e13 --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.NDCoordinatesIncrementor.html @@ -0,0 +1,410 @@ + + + + + Class NDCoordinatesIncrementor | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NDCoordinatesIncrementor +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class NDCoordinatesIncrementor
+
+ + + + +
+
Inheritance
+
+ +
NDCoordinatesIncrementor
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ NDCoordinatesIncrementor(ref Shape) + +

+ +

Initializes a new instance of the object class.

+
+
+ +
+
public NDCoordinatesIncrementor(ref Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ + + + + + + + + + + + + + +

+ NDCoordinatesIncrementor(ref Shape, Action<NDCoordinatesIncrementor>) + +

+ +
+
+ +
+
public NDCoordinatesIncrementor(ref Shape shape, Action<NDCoordinatesIncrementor> endCallback)
+
+ +

Parameters

+
+
shape Shape
+
+
endCallback Action<NDCoordinatesIncrementor>
+
+
+ + + + + + + + + + + + + + +

+ NDCoordinatesIncrementor(int[]) + +

+ +
+
+ +
+
public NDCoordinatesIncrementor(int[] dims)
+
+ +

Parameters

+
+
dims int[]
+
+
+ + + + + + + + + + + + + + +

+ NDCoordinatesIncrementor(int[], Action<NDCoordinatesIncrementor>) + +

+ +
+
+ +
+
public NDCoordinatesIncrementor(int[] dims, Action<NDCoordinatesIncrementor> endCallback)
+
+ +

Parameters

+
+
dims int[]
+
+
endCallback Action<NDCoordinatesIncrementor>
+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ Index + +

+ +
+
+ +
+
public readonly int[] Index
+
+ + + + +

Field Value

+
+
int[]
+
+
+ + + + + + + + + +

Methods +

+ + + + +

+ Next() + +

+ +
+
+ +
+
public int[] Next()
+
+ + +

Returns

+
+
int[]
+
+
+ + + + + + + + + + + + + +

+ Reset() + +

+ +
+
+ +
+
public void Reset()
+
+ + + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.NDCoordinatesIncrementorAutoResetting.html b/docs/website/api/NumSharp.Utilities.NDCoordinatesIncrementorAutoResetting.html new file mode 100644 index 000000000..2369780b2 --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.NDCoordinatesIncrementorAutoResetting.html @@ -0,0 +1,344 @@ + + + + + Class NDCoordinatesIncrementorAutoResetting | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NDCoordinatesIncrementorAutoResetting +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class NDCoordinatesIncrementorAutoResetting
+
+ + + + +
+
Inheritance
+
+ +
NDCoordinatesIncrementorAutoResetting
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ NDCoordinatesIncrementorAutoResetting(ref Shape) + +

+ +

Initializes a new instance of the object class.

+
+
+ +
+
public NDCoordinatesIncrementorAutoResetting(ref Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ + + + + + + + + + + + + + +

+ NDCoordinatesIncrementorAutoResetting(int[]) + +

+ +
+
+ +
+
public NDCoordinatesIncrementorAutoResetting(int[] dims)
+
+ +

Parameters

+
+
dims int[]
+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ Index + +

+ +
+
+ +
+
public readonly int[] Index
+
+ + + + +

Field Value

+
+
int[]
+
+
+ + + + + + + + + +

Methods +

+ + + + +

+ Next() + +

+ +
+
+ +
+
public int[] Next()
+
+ + +

Returns

+
+
int[]
+
+
+ + + + + + + + + + + + + +

+ Reset() + +

+ +
+
+ +
+
public void Reset()
+
+ + + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.NDCoordinatesLeftToAxisIncrementor.html b/docs/website/api/NumSharp.Utilities.NDCoordinatesLeftToAxisIncrementor.html new file mode 100644 index 000000000..34df55e2d --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.NDCoordinatesLeftToAxisIncrementor.html @@ -0,0 +1,409 @@ + + + + + Class NDCoordinatesLeftToAxisIncrementor | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NDCoordinatesLeftToAxisIncrementor +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class NDCoordinatesLeftToAxisIncrementor
+
+ + + + +
+
Inheritance
+
+ +
NDCoordinatesLeftToAxisIncrementor
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ NDCoordinatesLeftToAxisIncrementor(ref Shape, int) + +

+ +
+
+ +
+
public NDCoordinatesLeftToAxisIncrementor(ref Shape shape, int axis)
+
+ +

Parameters

+
+
shape Shape
+
+
axis int
+
+
+ + + + + + + + + + + + + + +

+ NDCoordinatesLeftToAxisIncrementor(ref Shape, int, Action<NDCoordinatesLeftToAxisIncrementor>) + +

+ +
+
+ +
+
public NDCoordinatesLeftToAxisIncrementor(ref Shape shape, int axis, Action<NDCoordinatesLeftToAxisIncrementor> endCallback)
+
+ +

Parameters

+
+
shape Shape
+
+
axis int
+
+
endCallback Action<NDCoordinatesLeftToAxisIncrementor>
+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ Axis + +

+ +
+
+ +
+
public int Axis
+
+ + + + +

Field Value

+
+
int
+
+
+ + + + + + + + + + +

+ Index + +

+ +
+
+ +
+
public readonly int[] Index
+
+ + + + +

Field Value

+
+
int[]
+
+
+ + + + + + + + + + +

+ Slices + +

+ +
+
+ +
+
public readonly Slice[] Slices
+
+ + + + +

Field Value

+
+
Slice[]
+
+
+ + + + + + + + + +

Methods +

+ + + + +

+ Next() + +

+ +
+
+ +
+
public Slice[] Next()
+
+ + +

Returns

+
+
Slice[]
+
+
+ + + + + + + + + + + + + +

+ Reset() + +

+ +
+
+ +
+
public void Reset()
+
+ + + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.NDExtendedCoordinatesIncrementor.html b/docs/website/api/NumSharp.Utilities.NDExtendedCoordinatesIncrementor.html new file mode 100644 index 000000000..fdff1eae8 --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.NDExtendedCoordinatesIncrementor.html @@ -0,0 +1,425 @@ + + + + + Class NDExtendedCoordinatesIncrementor | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NDExtendedCoordinatesIncrementor +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class NDExtendedCoordinatesIncrementor
+
+ + + + +
+
Inheritance
+
+ +
NDExtendedCoordinatesIncrementor
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ NDExtendedCoordinatesIncrementor(Shape, int, Action<NDExtendedCoordinatesIncrementor>) + +

+ +
+
+ +
+
public NDExtendedCoordinatesIncrementor(Shape shape, int extendBy, Action<NDExtendedCoordinatesIncrementor> endCallback = null)
+
+ +

Parameters

+
+
shape Shape
+
+
extendBy int
+

By how many items should Index be extended

+
+
endCallback Action<NDExtendedCoordinatesIncrementor>
+
+
+ + + + + + + + + + + + + + +

+ NDExtendedCoordinatesIncrementor(int[], int, Action<NDExtendedCoordinatesIncrementor>) + +

+ +
+
+ +
+
public NDExtendedCoordinatesIncrementor(int[] dims, int extendBy, Action<NDExtendedCoordinatesIncrementor> endCallback = null)
+
+ +

Parameters

+
+
dims int[]
+

The dims has to be not extended, use Resize<T>(ref T[], int) if it already extended

+
+
extendBy int
+

By how many items should Index be extended

+
+
endCallback Action<NDExtendedCoordinatesIncrementor>
+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ Index + +

+ +
+
+ +
+
public int[] Index
+
+ + + + +

Field Value

+
+
int[]
+
+
+ + + + + + + + + +

Properties +

+ + + + +

+ ResetEntireArray + +

+ +
+
+ +
+
public bool ResetEntireArray { get; set; }
+
+ + + + + +

Property Value

+
+
bool
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ Next() + +

+ +
+
+ +
+
public int[] Next()
+
+ + +

Returns

+
+
int[]
+
+
+ + + + + + + + + + + + + +

+ Next(params int[]) + +

+ +
+
+ +
+
public int[] Next(params int[] extendedIndices)
+
+ +

Parameters

+
+
extendedIndices int[]
+
+
+ +

Returns

+
+
int[]
+
+
+ + + + + + + + + + + + + +

+ Reset() + +

+ +
+
+ +
+
public void Reset()
+
+ + + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.NDOffsetIncrementor.html b/docs/website/api/NumSharp.Utilities.NDOffsetIncrementor.html new file mode 100644 index 000000000..91201057d --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.NDOffsetIncrementor.html @@ -0,0 +1,344 @@ + + + + + Class NDOffsetIncrementor | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NDOffsetIncrementor +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class NDOffsetIncrementor
+
+ + + + +
+
Inheritance
+
+ +
NDOffsetIncrementor
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ NDOffsetIncrementor(Shape) + +

+ +
+
+ +
+
public NDOffsetIncrementor(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ + + + + + + + + + + + + + +

+ NDOffsetIncrementor(int[]) + +

+ +
+
+ +
+
public NDOffsetIncrementor(int[] dims)
+
+ +

Parameters

+
+
dims int[]
+
+
+ + + + + + + + + + + + +

Properties +

+ + + + +

+ HasNext + +

+ +
+
+ +
+
public bool HasNext { get; }
+
+ + + + + +

Property Value

+
+
bool
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ Next() + +

+ +
+
+ +
+
public int Next()
+
+ + +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ Reset() + +

+ +
+
+ +
+
public void Reset()
+
+ + + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.NDOffsetIncrementorAutoresetting.html b/docs/website/api/NumSharp.Utilities.NDOffsetIncrementorAutoresetting.html new file mode 100644 index 000000000..c22cd6e61 --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.NDOffsetIncrementorAutoresetting.html @@ -0,0 +1,344 @@ + + + + + Class NDOffsetIncrementorAutoresetting | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NDOffsetIncrementorAutoresetting +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class NDOffsetIncrementorAutoresetting
+
+ + + + +
+
Inheritance
+
+ +
NDOffsetIncrementorAutoresetting
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ NDOffsetIncrementorAutoresetting(Shape) + +

+ +
+
+ +
+
public NDOffsetIncrementorAutoresetting(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ + + + + + + + + + + + + + +

+ NDOffsetIncrementorAutoresetting(int[]) + +

+ +
+
+ +
+
public NDOffsetIncrementorAutoresetting(int[] dims)
+
+ +

Parameters

+
+
dims int[]
+
+
+ + + + + + + + + + + + +

Properties +

+ + + + +

+ HasNext + +

+ +
+
+ +
+
public bool HasNext { get; }
+
+ + + + + +

Property Value

+
+
bool
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ Next() + +

+ +
+
+ +
+
public int Next()
+
+ + +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ Reset() + +

+ +
+
+ +
+
public void Reset()
+
+ + + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.NonGenericConvert.html b/docs/website/api/NumSharp.Utilities.NonGenericConvert.html new file mode 100644 index 000000000..89018d868 --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.NonGenericConvert.html @@ -0,0 +1,6264 @@ + + + + + Class NonGenericConvert | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NonGenericConvert +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +

Provides a way to convert boxed object from known time to specific type.

+
+
+ +
+
public static class NonGenericConvert
+
+ + + + +
+
Inheritance
+
+ +
NonGenericConvert
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Methods +

+ + + + +

+ FromBooleanToByte(object) + +

+ +

Convert from Boolean to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static byte FromBooleanToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to byte

+
+
+ +

Returns

+
+
byte
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToChar(object) + +

+ +

Convert from Boolean to Char when input is a boxed non-generic object.

+
+
+ +
+
public static char FromBooleanToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to char

+
+
+ +

Returns

+
+
char
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToDecimal(object) + +

+ +

Convert from Boolean to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static decimal FromBooleanToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to decimal

+
+
+ +

Returns

+
+
decimal
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToDouble(object) + +

+ +

Convert from Boolean to Double when input is a boxed non-generic object.

+
+
+ +
+
public static double FromBooleanToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to double

+
+
+ +

Returns

+
+
double
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToInt16(object) + +

+ +

Convert from Boolean to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static short FromBooleanToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to short

+
+
+ +

Returns

+
+
short
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToInt32(object) + +

+ +

Convert from Boolean to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static int FromBooleanToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to int

+
+
+ +

Returns

+
+
int
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToInt64(object) + +

+ +

Convert from Boolean to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static long FromBooleanToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to long

+
+
+ +

Returns

+
+
long
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToSingle(object) + +

+ +

Convert from Boolean to Single when input is a boxed non-generic object.

+
+
+ +
+
public static float FromBooleanToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to float

+
+
+ +

Returns

+
+
float
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToString(object) + +

+ +

Convert from Boolean to String when input is a boxed non-generic object.

+
+
+ +
+
public static string FromBooleanToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to string

+
+
+ +

Returns

+
+
string
+

String

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToUInt16(object) + +

+ +

Convert from Boolean to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static ushort FromBooleanToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to ushort

+
+
+ +

Returns

+
+
ushort
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToUInt32(object) + +

+ +

Convert from Boolean to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static uint FromBooleanToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to uint

+
+
+ +

Returns

+
+
uint
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToUInt64(object) + +

+ +

Convert from Boolean to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static ulong FromBooleanToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to ulong

+
+
+ +

Returns

+
+
ulong
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromByteToBoolean(object) + +

+ +

Convert from Byte to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static bool FromByteToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to bool

+
+
+ +

Returns

+
+
bool
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromByteToChar(object) + +

+ +

Convert from Byte to Char when input is a boxed non-generic object.

+
+
+ +
+
public static char FromByteToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to char

+
+
+ +

Returns

+
+
char
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromByteToDecimal(object) + +

+ +

Convert from Byte to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static decimal FromByteToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to decimal

+
+
+ +

Returns

+
+
decimal
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromByteToDouble(object) + +

+ +

Convert from Byte to Double when input is a boxed non-generic object.

+
+
+ +
+
public static double FromByteToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to double

+
+
+ +

Returns

+
+
double
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromByteToInt16(object) + +

+ +

Convert from Byte to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static short FromByteToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to short

+
+
+ +

Returns

+
+
short
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromByteToInt32(object) + +

+ +

Convert from Byte to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static int FromByteToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to int

+
+
+ +

Returns

+
+
int
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromByteToInt64(object) + +

+ +

Convert from Byte to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static long FromByteToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to long

+
+
+ +

Returns

+
+
long
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromByteToSingle(object) + +

+ +

Convert from Byte to Single when input is a boxed non-generic object.

+
+
+ +
+
public static float FromByteToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to float

+
+
+ +

Returns

+
+
float
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromByteToString(object) + +

+ +

Convert from Byte to String when input is a boxed non-generic object.

+
+
+ +
+
public static string FromByteToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to string

+
+
+ +

Returns

+
+
string
+

String

+
+
+ + + + + + + + + + + + + +

+ FromByteToUInt16(object) + +

+ +

Convert from Byte to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static ushort FromByteToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to ushort

+
+
+ +

Returns

+
+
ushort
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromByteToUInt32(object) + +

+ +

Convert from Byte to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static uint FromByteToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to uint

+
+
+ +

Returns

+
+
uint
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromByteToUInt64(object) + +

+ +

Convert from Byte to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static ulong FromByteToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to ulong

+
+
+ +

Returns

+
+
ulong
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromCharToBoolean(object) + +

+ +

Convert from Char to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static bool FromCharToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to bool

+
+
+ +

Returns

+
+
bool
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromCharToByte(object) + +

+ +

Convert from Char to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static byte FromCharToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to byte

+
+
+ +

Returns

+
+
byte
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromCharToDecimal(object) + +

+ +

Convert from Char to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static decimal FromCharToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to decimal

+
+
+ +

Returns

+
+
decimal
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromCharToDouble(object) + +

+ +

Convert from Char to Double when input is a boxed non-generic object.

+
+
+ +
+
public static double FromCharToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to double

+
+
+ +

Returns

+
+
double
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromCharToInt16(object) + +

+ +

Convert from Char to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static short FromCharToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to short

+
+
+ +

Returns

+
+
short
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromCharToInt32(object) + +

+ +

Convert from Char to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static int FromCharToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to int

+
+
+ +

Returns

+
+
int
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromCharToInt64(object) + +

+ +

Convert from Char to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static long FromCharToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to long

+
+
+ +

Returns

+
+
long
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromCharToSingle(object) + +

+ +

Convert from Char to Single when input is a boxed non-generic object.

+
+
+ +
+
public static float FromCharToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to float

+
+
+ +

Returns

+
+
float
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromCharToString(object) + +

+ +

Convert from Char to String when input is a boxed non-generic object.

+
+
+ +
+
public static string FromCharToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to string

+
+
+ +

Returns

+
+
string
+

String

+
+
+ + + + + + + + + + + + + +

+ FromCharToUInt16(object) + +

+ +

Convert from Char to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static ushort FromCharToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to ushort

+
+
+ +

Returns

+
+
ushort
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromCharToUInt32(object) + +

+ +

Convert from Char to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static uint FromCharToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to uint

+
+
+ +

Returns

+
+
uint
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromCharToUInt64(object) + +

+ +

Convert from Char to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static ulong FromCharToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to ulong

+
+
+ +

Returns

+
+
ulong
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToBoolean(object) + +

+ +

Convert from Decimal to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static bool FromDecimalToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to bool

+
+
+ +

Returns

+
+
bool
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToByte(object) + +

+ +

Convert from Decimal to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static byte FromDecimalToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to byte

+
+
+ +

Returns

+
+
byte
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToChar(object) + +

+ +

Convert from Decimal to Char when input is a boxed non-generic object.

+
+
+ +
+
public static char FromDecimalToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to char

+
+
+ +

Returns

+
+
char
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToDouble(object) + +

+ +

Convert from Decimal to Double when input is a boxed non-generic object.

+
+
+ +
+
public static double FromDecimalToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to double

+
+
+ +

Returns

+
+
double
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToInt16(object) + +

+ +

Convert from Decimal to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static short FromDecimalToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to short

+
+
+ +

Returns

+
+
short
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToInt32(object) + +

+ +

Convert from Decimal to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static int FromDecimalToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to int

+
+
+ +

Returns

+
+
int
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToInt64(object) + +

+ +

Convert from Decimal to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static long FromDecimalToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to long

+
+
+ +

Returns

+
+
long
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToSingle(object) + +

+ +

Convert from Decimal to Single when input is a boxed non-generic object.

+
+
+ +
+
public static float FromDecimalToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to float

+
+
+ +

Returns

+
+
float
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToString(object) + +

+ +

Convert from Decimal to String when input is a boxed non-generic object.

+
+
+ +
+
public static string FromDecimalToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to string

+
+
+ +

Returns

+
+
string
+

String

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToUInt16(object) + +

+ +

Convert from Decimal to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static ushort FromDecimalToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to ushort

+
+
+ +

Returns

+
+
ushort
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToUInt32(object) + +

+ +

Convert from Decimal to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static uint FromDecimalToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to uint

+
+
+ +

Returns

+
+
uint
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToUInt64(object) + +

+ +

Convert from Decimal to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static ulong FromDecimalToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to ulong

+
+
+ +

Returns

+
+
ulong
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToBoolean(object) + +

+ +

Convert from Double to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static bool FromDoubleToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to bool

+
+
+ +

Returns

+
+
bool
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToByte(object) + +

+ +

Convert from Double to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static byte FromDoubleToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to byte

+
+
+ +

Returns

+
+
byte
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToChar(object) + +

+ +

Convert from Double to Char when input is a boxed non-generic object.

+
+
+ +
+
public static char FromDoubleToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to char

+
+
+ +

Returns

+
+
char
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToDecimal(object) + +

+ +

Convert from Double to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static decimal FromDoubleToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to decimal

+
+
+ +

Returns

+
+
decimal
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToInt16(object) + +

+ +

Convert from Double to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static short FromDoubleToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to short

+
+
+ +

Returns

+
+
short
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToInt32(object) + +

+ +

Convert from Double to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static int FromDoubleToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to int

+
+
+ +

Returns

+
+
int
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToInt64(object) + +

+ +

Convert from Double to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static long FromDoubleToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to long

+
+
+ +

Returns

+
+
long
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToSingle(object) + +

+ +

Convert from Double to Single when input is a boxed non-generic object.

+
+
+ +
+
public static float FromDoubleToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to float

+
+
+ +

Returns

+
+
float
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToString(object) + +

+ +

Convert from Double to String when input is a boxed non-generic object.

+
+
+ +
+
public static string FromDoubleToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to string

+
+
+ +

Returns

+
+
string
+

String

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToUInt16(object) + +

+ +

Convert from Double to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static ushort FromDoubleToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to ushort

+
+
+ +

Returns

+
+
ushort
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToUInt32(object) + +

+ +

Convert from Double to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static uint FromDoubleToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to uint

+
+
+ +

Returns

+
+
uint
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToUInt64(object) + +

+ +

Convert from Double to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static ulong FromDoubleToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to ulong

+
+
+ +

Returns

+
+
ulong
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToBoolean(object) + +

+ +

Convert from Int16 to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static bool FromInt16ToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to bool

+
+
+ +

Returns

+
+
bool
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToByte(object) + +

+ +

Convert from Int16 to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static byte FromInt16ToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to byte

+
+
+ +

Returns

+
+
byte
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToChar(object) + +

+ +

Convert from Int16 to Char when input is a boxed non-generic object.

+
+
+ +
+
public static char FromInt16ToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to char

+
+
+ +

Returns

+
+
char
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToDecimal(object) + +

+ +

Convert from Int16 to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static decimal FromInt16ToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to decimal

+
+
+ +

Returns

+
+
decimal
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToDouble(object) + +

+ +

Convert from Int16 to Double when input is a boxed non-generic object.

+
+
+ +
+
public static double FromInt16ToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to double

+
+
+ +

Returns

+
+
double
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToInt32(object) + +

+ +

Convert from Int16 to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static int FromInt16ToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to int

+
+
+ +

Returns

+
+
int
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToInt64(object) + +

+ +

Convert from Int16 to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static long FromInt16ToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to long

+
+
+ +

Returns

+
+
long
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToSingle(object) + +

+ +

Convert from Int16 to Single when input is a boxed non-generic object.

+
+
+ +
+
public static float FromInt16ToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to float

+
+
+ +

Returns

+
+
float
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToString(object) + +

+ +

Convert from Int16 to String when input is a boxed non-generic object.

+
+
+ +
+
public static string FromInt16ToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to string

+
+
+ +

Returns

+
+
string
+

String

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToUInt16(object) + +

+ +

Convert from Int16 to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static ushort FromInt16ToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to ushort

+
+
+ +

Returns

+
+
ushort
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToUInt32(object) + +

+ +

Convert from Int16 to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static uint FromInt16ToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to uint

+
+
+ +

Returns

+
+
uint
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToUInt64(object) + +

+ +

Convert from Int16 to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static ulong FromInt16ToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to ulong

+
+
+ +

Returns

+
+
ulong
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToBoolean(object) + +

+ +

Convert from Int32 to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static bool FromInt32ToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to bool

+
+
+ +

Returns

+
+
bool
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToByte(object) + +

+ +

Convert from Int32 to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static byte FromInt32ToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to byte

+
+
+ +

Returns

+
+
byte
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToChar(object) + +

+ +

Convert from Int32 to Char when input is a boxed non-generic object.

+
+
+ +
+
public static char FromInt32ToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to char

+
+
+ +

Returns

+
+
char
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToDecimal(object) + +

+ +

Convert from Int32 to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static decimal FromInt32ToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to decimal

+
+
+ +

Returns

+
+
decimal
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToDouble(object) + +

+ +

Convert from Int32 to Double when input is a boxed non-generic object.

+
+
+ +
+
public static double FromInt32ToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to double

+
+
+ +

Returns

+
+
double
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToInt16(object) + +

+ +

Convert from Int32 to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static short FromInt32ToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to short

+
+
+ +

Returns

+
+
short
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToInt64(object) + +

+ +

Convert from Int32 to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static long FromInt32ToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to long

+
+
+ +

Returns

+
+
long
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToSingle(object) + +

+ +

Convert from Int32 to Single when input is a boxed non-generic object.

+
+
+ +
+
public static float FromInt32ToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to float

+
+
+ +

Returns

+
+
float
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToString(object) + +

+ +

Convert from Int32 to String when input is a boxed non-generic object.

+
+
+ +
+
public static string FromInt32ToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to string

+
+
+ +

Returns

+
+
string
+

String

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToUInt16(object) + +

+ +

Convert from Int32 to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static ushort FromInt32ToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to ushort

+
+
+ +

Returns

+
+
ushort
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToUInt32(object) + +

+ +

Convert from Int32 to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static uint FromInt32ToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to uint

+
+
+ +

Returns

+
+
uint
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToUInt64(object) + +

+ +

Convert from Int32 to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static ulong FromInt32ToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to ulong

+
+
+ +

Returns

+
+
ulong
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToBoolean(object) + +

+ +

Convert from Int64 to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static bool FromInt64ToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to bool

+
+
+ +

Returns

+
+
bool
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToByte(object) + +

+ +

Convert from Int64 to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static byte FromInt64ToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to byte

+
+
+ +

Returns

+
+
byte
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToChar(object) + +

+ +

Convert from Int64 to Char when input is a boxed non-generic object.

+
+
+ +
+
public static char FromInt64ToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to char

+
+
+ +

Returns

+
+
char
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToDecimal(object) + +

+ +

Convert from Int64 to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static decimal FromInt64ToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to decimal

+
+
+ +

Returns

+
+
decimal
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToDouble(object) + +

+ +

Convert from Int64 to Double when input is a boxed non-generic object.

+
+
+ +
+
public static double FromInt64ToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to double

+
+
+ +

Returns

+
+
double
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToInt16(object) + +

+ +

Convert from Int64 to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static short FromInt64ToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to short

+
+
+ +

Returns

+
+
short
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToInt32(object) + +

+ +

Convert from Int64 to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static int FromInt64ToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to int

+
+
+ +

Returns

+
+
int
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToSingle(object) + +

+ +

Convert from Int64 to Single when input is a boxed non-generic object.

+
+
+ +
+
public static float FromInt64ToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to float

+
+
+ +

Returns

+
+
float
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToString(object) + +

+ +

Convert from Int64 to String when input is a boxed non-generic object.

+
+
+ +
+
public static string FromInt64ToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to string

+
+
+ +

Returns

+
+
string
+

String

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToUInt16(object) + +

+ +

Convert from Int64 to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static ushort FromInt64ToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to ushort

+
+
+ +

Returns

+
+
ushort
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToUInt32(object) + +

+ +

Convert from Int64 to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static uint FromInt64ToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to uint

+
+
+ +

Returns

+
+
uint
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToUInt64(object) + +

+ +

Convert from Int64 to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static ulong FromInt64ToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to ulong

+
+
+ +

Returns

+
+
ulong
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromSingleToBoolean(object) + +

+ +

Convert from Single to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static bool FromSingleToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to bool

+
+
+ +

Returns

+
+
bool
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromSingleToByte(object) + +

+ +

Convert from Single to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static byte FromSingleToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to byte

+
+
+ +

Returns

+
+
byte
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromSingleToChar(object) + +

+ +

Convert from Single to Char when input is a boxed non-generic object.

+
+
+ +
+
public static char FromSingleToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to char

+
+
+ +

Returns

+
+
char
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromSingleToDecimal(object) + +

+ +

Convert from Single to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static decimal FromSingleToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to decimal

+
+
+ +

Returns

+
+
decimal
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromSingleToDouble(object) + +

+ +

Convert from Single to Double when input is a boxed non-generic object.

+
+
+ +
+
public static double FromSingleToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to double

+
+
+ +

Returns

+
+
double
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromSingleToInt16(object) + +

+ +

Convert from Single to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static short FromSingleToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to short

+
+
+ +

Returns

+
+
short
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromSingleToInt32(object) + +

+ +

Convert from Single to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static int FromSingleToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to int

+
+
+ +

Returns

+
+
int
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromSingleToInt64(object) + +

+ +

Convert from Single to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static long FromSingleToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to long

+
+
+ +

Returns

+
+
long
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromSingleToString(object) + +

+ +

Convert from Single to String when input is a boxed non-generic object.

+
+
+ +
+
public static string FromSingleToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to string

+
+
+ +

Returns

+
+
string
+

String

+
+
+ + + + + + + + + + + + + +

+ FromSingleToUInt16(object) + +

+ +

Convert from Single to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static ushort FromSingleToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to ushort

+
+
+ +

Returns

+
+
ushort
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromSingleToUInt32(object) + +

+ +

Convert from Single to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static uint FromSingleToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to uint

+
+
+ +

Returns

+
+
uint
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromSingleToUInt64(object) + +

+ +

Convert from Single to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static ulong FromSingleToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to ulong

+
+
+ +

Returns

+
+
ulong
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromStringToBoolean(object) + +

+ +

Convert from String to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static bool FromStringToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to bool

+
+
+ +

Returns

+
+
bool
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromStringToByte(object) + +

+ +

Convert from String to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static byte FromStringToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to byte

+
+
+ +

Returns

+
+
byte
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromStringToChar(object) + +

+ +

Convert from String to Char when input is a boxed non-generic object.

+
+
+ +
+
public static char FromStringToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to char

+
+
+ +

Returns

+
+
char
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromStringToDecimal(object) + +

+ +

Convert from String to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static decimal FromStringToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to decimal

+
+
+ +

Returns

+
+
decimal
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromStringToDouble(object) + +

+ +

Convert from String to Double when input is a boxed non-generic object.

+
+
+ +
+
public static double FromStringToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to double

+
+
+ +

Returns

+
+
double
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromStringToInt16(object) + +

+ +

Convert from String to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static short FromStringToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to short

+
+
+ +

Returns

+
+
short
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromStringToInt32(object) + +

+ +

Convert from String to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static int FromStringToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to int

+
+
+ +

Returns

+
+
int
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromStringToInt64(object) + +

+ +

Convert from String to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static long FromStringToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to long

+
+
+ +

Returns

+
+
long
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromStringToSingle(object) + +

+ +

Convert from String to Single when input is a boxed non-generic object.

+
+
+ +
+
public static float FromStringToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to float

+
+
+ +

Returns

+
+
float
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromStringToUInt16(object) + +

+ +

Convert from String to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static ushort FromStringToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to ushort

+
+
+ +

Returns

+
+
ushort
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromStringToUInt32(object) + +

+ +

Convert from String to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static uint FromStringToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to uint

+
+
+ +

Returns

+
+
uint
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromStringToUInt64(object) + +

+ +

Convert from String to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static ulong FromStringToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to ulong

+
+
+ +

Returns

+
+
ulong
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToBoolean(object) + +

+ +

Convert from UInt16 to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static bool FromUInt16ToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to bool

+
+
+ +

Returns

+
+
bool
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToByte(object) + +

+ +

Convert from UInt16 to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static byte FromUInt16ToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to byte

+
+
+ +

Returns

+
+
byte
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToChar(object) + +

+ +

Convert from UInt16 to Char when input is a boxed non-generic object.

+
+
+ +
+
public static char FromUInt16ToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to char

+
+
+ +

Returns

+
+
char
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToDecimal(object) + +

+ +

Convert from UInt16 to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static decimal FromUInt16ToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to decimal

+
+
+ +

Returns

+
+
decimal
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToDouble(object) + +

+ +

Convert from UInt16 to Double when input is a boxed non-generic object.

+
+
+ +
+
public static double FromUInt16ToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to double

+
+
+ +

Returns

+
+
double
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToInt16(object) + +

+ +

Convert from UInt16 to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static short FromUInt16ToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to short

+
+
+ +

Returns

+
+
short
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToInt32(object) + +

+ +

Convert from UInt16 to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static int FromUInt16ToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to int

+
+
+ +

Returns

+
+
int
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToInt64(object) + +

+ +

Convert from UInt16 to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static long FromUInt16ToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to long

+
+
+ +

Returns

+
+
long
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToSingle(object) + +

+ +

Convert from UInt16 to Single when input is a boxed non-generic object.

+
+
+ +
+
public static float FromUInt16ToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to float

+
+
+ +

Returns

+
+
float
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToString(object) + +

+ +

Convert from UInt16 to String when input is a boxed non-generic object.

+
+
+ +
+
public static string FromUInt16ToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to string

+
+
+ +

Returns

+
+
string
+

String

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToUInt32(object) + +

+ +

Convert from UInt16 to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static uint FromUInt16ToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to uint

+
+
+ +

Returns

+
+
uint
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToUInt64(object) + +

+ +

Convert from UInt16 to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static ulong FromUInt16ToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to ulong

+
+
+ +

Returns

+
+
ulong
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToBoolean(object) + +

+ +

Convert from UInt32 to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static bool FromUInt32ToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to bool

+
+
+ +

Returns

+
+
bool
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToByte(object) + +

+ +

Convert from UInt32 to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static byte FromUInt32ToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to byte

+
+
+ +

Returns

+
+
byte
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToChar(object) + +

+ +

Convert from UInt32 to Char when input is a boxed non-generic object.

+
+
+ +
+
public static char FromUInt32ToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to char

+
+
+ +

Returns

+
+
char
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToDecimal(object) + +

+ +

Convert from UInt32 to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static decimal FromUInt32ToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to decimal

+
+
+ +

Returns

+
+
decimal
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToDouble(object) + +

+ +

Convert from UInt32 to Double when input is a boxed non-generic object.

+
+
+ +
+
public static double FromUInt32ToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to double

+
+
+ +

Returns

+
+
double
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToInt16(object) + +

+ +

Convert from UInt32 to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static short FromUInt32ToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to short

+
+
+ +

Returns

+
+
short
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToInt32(object) + +

+ +

Convert from UInt32 to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static int FromUInt32ToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to int

+
+
+ +

Returns

+
+
int
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToInt64(object) + +

+ +

Convert from UInt32 to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static long FromUInt32ToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to long

+
+
+ +

Returns

+
+
long
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToSingle(object) + +

+ +

Convert from UInt32 to Single when input is a boxed non-generic object.

+
+
+ +
+
public static float FromUInt32ToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to float

+
+
+ +

Returns

+
+
float
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToString(object) + +

+ +

Convert from UInt32 to String when input is a boxed non-generic object.

+
+
+ +
+
public static string FromUInt32ToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to string

+
+
+ +

Returns

+
+
string
+

String

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToUInt16(object) + +

+ +

Convert from UInt32 to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static ushort FromUInt32ToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to ushort

+
+
+ +

Returns

+
+
ushort
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToUInt64(object) + +

+ +

Convert from UInt32 to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static ulong FromUInt32ToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to ulong

+
+
+ +

Returns

+
+
ulong
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToBoolean(object) + +

+ +

Convert from UInt64 to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static bool FromUInt64ToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to bool

+
+
+ +

Returns

+
+
bool
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToByte(object) + +

+ +

Convert from UInt64 to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static byte FromUInt64ToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to byte

+
+
+ +

Returns

+
+
byte
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToChar(object) + +

+ +

Convert from UInt64 to Char when input is a boxed non-generic object.

+
+
+ +
+
public static char FromUInt64ToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to char

+
+
+ +

Returns

+
+
char
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToDecimal(object) + +

+ +

Convert from UInt64 to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static decimal FromUInt64ToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to decimal

+
+
+ +

Returns

+
+
decimal
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToDouble(object) + +

+ +

Convert from UInt64 to Double when input is a boxed non-generic object.

+
+
+ +
+
public static double FromUInt64ToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to double

+
+
+ +

Returns

+
+
double
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToInt16(object) + +

+ +

Convert from UInt64 to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static short FromUInt64ToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to short

+
+
+ +

Returns

+
+
short
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToInt32(object) + +

+ +

Convert from UInt64 to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static int FromUInt64ToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to int

+
+
+ +

Returns

+
+
int
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToInt64(object) + +

+ +

Convert from UInt64 to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static long FromUInt64ToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to long

+
+
+ +

Returns

+
+
long
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToSingle(object) + +

+ +

Convert from UInt64 to Single when input is a boxed non-generic object.

+
+
+ +
+
public static float FromUInt64ToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to float

+
+
+ +

Returns

+
+
float
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToString(object) + +

+ +

Convert from UInt64 to String when input is a boxed non-generic object.

+
+
+ +
+
public static string FromUInt64ToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to string

+
+
+ +

Returns

+
+
string
+

String

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToUInt16(object) + +

+ +

Convert from UInt64 to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static ushort FromUInt64ToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to ushort

+
+
+ +

Returns

+
+
ushort
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToUInt32(object) + +

+ +

Convert from UInt64 to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static uint FromUInt64ToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to uint

+
+
+ +

Returns

+
+
uint
+

UInt32

+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.NumberInfo.html b/docs/website/api/NumSharp.Utilities.NumberInfo.html new file mode 100644 index 000000000..5ee15a18b --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.NumberInfo.html @@ -0,0 +1,253 @@ + + + + + Class NumberInfo | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class NumberInfo +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public static class NumberInfo
+
+ + + + +
+
Inheritance
+
+ +
NumberInfo
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Methods +

+ + + + +

+ MaxValue(NPTypeCode) + +

+ +

Get the min value of given NPTypeCode.

+
+
+ +
+
public static object MaxValue(this NPTypeCode typeCode)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+
+
+ +

Returns

+
+
object
+
+
+ + + + + + + + + + + + + +

+ MinValue(NPTypeCode) + +

+ +

Get the min value of given NPTypeCode.

+
+
+ +
+
public static object MinValue(this NPTypeCode typeCode)
+
+ +

Parameters

+
+
typeCode NPTypeCode
+
+
+ +

Returns

+
+
object
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.SteppingExtension.html b/docs/website/api/NumSharp.Utilities.SteppingExtension.html new file mode 100644 index 000000000..c62dd9e7c --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.SteppingExtension.html @@ -0,0 +1,222 @@ + + + + + Class SteppingExtension | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class SteppingExtension +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public static class SteppingExtension
+
+ + + + +
+
Inheritance
+
+ +
SteppingExtension
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Methods +

+ + + + +

+ Step<T>(T[], int) + +

+ +
+
+ +
+
public static T[] Step<T>(this T[] array, int step)
+
+ +

Parameters

+
+
array T[]
+
+
step int
+
+
+ +

Returns

+
+
T[]
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.TypelessConvert.html b/docs/website/api/NumSharp.Utilities.TypelessConvert.html new file mode 100644 index 000000000..7b023ac46 --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.TypelessConvert.html @@ -0,0 +1,6303 @@ + + + + + Class TypelessConvert | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class TypelessConvert +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +

Provides a way to convert boxed object from known input type to known output type. +By making it receive and return object - It is suitable for a common delegate: see TypelessConvertDelegate

+
+
+ +
+
public static class TypelessConvert
+
+ + + + +
+
Inheritance
+
+ +
TypelessConvert
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Methods +

+ + + + +

+ FromBooleanToByte(object) + +

+ +

Convert from Boolean to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static object FromBooleanToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to byte

+
+
+ +

Returns

+
+
object
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToChar(object) + +

+ +

Convert from Boolean to Char when input is a boxed non-generic object.

+
+
+ +
+
public static object FromBooleanToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to char

+
+
+ +

Returns

+
+
object
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToDecimal(object) + +

+ +

Convert from Boolean to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static object FromBooleanToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to decimal

+
+
+ +

Returns

+
+
object
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToDouble(object) + +

+ +

Convert from Boolean to Double when input is a boxed non-generic object.

+
+
+ +
+
public static object FromBooleanToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to double

+
+
+ +

Returns

+
+
object
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToInt16(object) + +

+ +

Convert from Boolean to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromBooleanToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to short

+
+
+ +

Returns

+
+
object
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToInt32(object) + +

+ +

Convert from Boolean to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromBooleanToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to int

+
+
+ +

Returns

+
+
object
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToInt64(object) + +

+ +

Convert from Boolean to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromBooleanToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to long

+
+
+ +

Returns

+
+
object
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToSingle(object) + +

+ +

Convert from Boolean to Single when input is a boxed non-generic object.

+
+
+ +
+
public static object FromBooleanToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to float

+
+
+ +

Returns

+
+
object
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToString(object) + +

+ +

Convert from Boolean to String when input is a boxed non-generic object.

+
+
+ +
+
public static object FromBooleanToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to string

+
+
+ +

Returns

+
+
object
+

String

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToUInt16(object) + +

+ +

Convert from Boolean to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromBooleanToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to ushort

+
+
+ +

Returns

+
+
object
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToUInt32(object) + +

+ +

Convert from Boolean to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromBooleanToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to uint

+
+
+ +

Returns

+
+
object
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromBooleanToUInt64(object) + +

+ +

Convert from Boolean to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromBooleanToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to bool and then converted to ulong

+
+
+ +

Returns

+
+
object
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromByteToBoolean(object) + +

+ +

Convert from Byte to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static object FromByteToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to bool

+
+
+ +

Returns

+
+
object
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromByteToChar(object) + +

+ +

Convert from Byte to Char when input is a boxed non-generic object.

+
+
+ +
+
public static object FromByteToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to char

+
+
+ +

Returns

+
+
object
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromByteToDecimal(object) + +

+ +

Convert from Byte to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static object FromByteToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to decimal

+
+
+ +

Returns

+
+
object
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromByteToDouble(object) + +

+ +

Convert from Byte to Double when input is a boxed non-generic object.

+
+
+ +
+
public static object FromByteToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to double

+
+
+ +

Returns

+
+
object
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromByteToInt16(object) + +

+ +

Convert from Byte to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromByteToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to short

+
+
+ +

Returns

+
+
object
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromByteToInt32(object) + +

+ +

Convert from Byte to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromByteToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to int

+
+
+ +

Returns

+
+
object
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromByteToInt64(object) + +

+ +

Convert from Byte to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromByteToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to long

+
+
+ +

Returns

+
+
object
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromByteToSingle(object) + +

+ +

Convert from Byte to Single when input is a boxed non-generic object.

+
+
+ +
+
public static object FromByteToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to float

+
+
+ +

Returns

+
+
object
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromByteToString(object) + +

+ +

Convert from Byte to String when input is a boxed non-generic object.

+
+
+ +
+
public static object FromByteToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to string

+
+
+ +

Returns

+
+
object
+

String

+
+
+ + + + + + + + + + + + + +

+ FromByteToUInt16(object) + +

+ +

Convert from Byte to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromByteToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to ushort

+
+
+ +

Returns

+
+
object
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromByteToUInt32(object) + +

+ +

Convert from Byte to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromByteToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to uint

+
+
+ +

Returns

+
+
object
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromByteToUInt64(object) + +

+ +

Convert from Byte to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromByteToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to byte and then converted to ulong

+
+
+ +

Returns

+
+
object
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromCharToBoolean(object) + +

+ +

Convert from Char to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static object FromCharToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to bool

+
+
+ +

Returns

+
+
object
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromCharToByte(object) + +

+ +

Convert from Char to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static object FromCharToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to byte

+
+
+ +

Returns

+
+
object
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromCharToDecimal(object) + +

+ +

Convert from Char to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static object FromCharToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to decimal

+
+
+ +

Returns

+
+
object
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromCharToDouble(object) + +

+ +

Convert from Char to Double when input is a boxed non-generic object.

+
+
+ +
+
public static object FromCharToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to double

+
+
+ +

Returns

+
+
object
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromCharToInt16(object) + +

+ +

Convert from Char to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromCharToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to short

+
+
+ +

Returns

+
+
object
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromCharToInt32(object) + +

+ +

Convert from Char to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromCharToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to int

+
+
+ +

Returns

+
+
object
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromCharToInt64(object) + +

+ +

Convert from Char to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromCharToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to long

+
+
+ +

Returns

+
+
object
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromCharToSingle(object) + +

+ +

Convert from Char to Single when input is a boxed non-generic object.

+
+
+ +
+
public static object FromCharToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to float

+
+
+ +

Returns

+
+
object
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromCharToString(object) + +

+ +

Convert from Char to String when input is a boxed non-generic object.

+
+
+ +
+
public static object FromCharToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to string

+
+
+ +

Returns

+
+
object
+

String

+
+
+ + + + + + + + + + + + + +

+ FromCharToUInt16(object) + +

+ +

Convert from Char to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromCharToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to ushort

+
+
+ +

Returns

+
+
object
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromCharToUInt32(object) + +

+ +

Convert from Char to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromCharToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to uint

+
+
+ +

Returns

+
+
object
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromCharToUInt64(object) + +

+ +

Convert from Char to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromCharToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to char and then converted to ulong

+
+
+ +

Returns

+
+
object
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToBoolean(object) + +

+ +

Convert from Decimal to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDecimalToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to bool

+
+
+ +

Returns

+
+
object
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToByte(object) + +

+ +

Convert from Decimal to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDecimalToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to byte

+
+
+ +

Returns

+
+
object
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToChar(object) + +

+ +

Convert from Decimal to Char when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDecimalToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to char

+
+
+ +

Returns

+
+
object
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToDouble(object) + +

+ +

Convert from Decimal to Double when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDecimalToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to double

+
+
+ +

Returns

+
+
object
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToInt16(object) + +

+ +

Convert from Decimal to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDecimalToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to short

+
+
+ +

Returns

+
+
object
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToInt32(object) + +

+ +

Convert from Decimal to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDecimalToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to int

+
+
+ +

Returns

+
+
object
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToInt64(object) + +

+ +

Convert from Decimal to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDecimalToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to long

+
+
+ +

Returns

+
+
object
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToSingle(object) + +

+ +

Convert from Decimal to Single when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDecimalToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to float

+
+
+ +

Returns

+
+
object
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToString(object) + +

+ +

Convert from Decimal to String when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDecimalToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to string

+
+
+ +

Returns

+
+
object
+

String

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToUInt16(object) + +

+ +

Convert from Decimal to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDecimalToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to ushort

+
+
+ +

Returns

+
+
object
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToUInt32(object) + +

+ +

Convert from Decimal to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDecimalToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to uint

+
+
+ +

Returns

+
+
object
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromDecimalToUInt64(object) + +

+ +

Convert from Decimal to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDecimalToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to decimal and then converted to ulong

+
+
+ +

Returns

+
+
object
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToBoolean(object) + +

+ +

Convert from Double to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDoubleToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to bool

+
+
+ +

Returns

+
+
object
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToByte(object) + +

+ +

Convert from Double to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDoubleToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to byte

+
+
+ +

Returns

+
+
object
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToChar(object) + +

+ +

Convert from Double to Char when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDoubleToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to char

+
+
+ +

Returns

+
+
object
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToDecimal(object) + +

+ +

Convert from Double to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDoubleToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to decimal

+
+
+ +

Returns

+
+
object
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToInt16(object) + +

+ +

Convert from Double to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDoubleToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to short

+
+
+ +

Returns

+
+
object
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToInt32(object) + +

+ +

Convert from Double to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDoubleToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to int

+
+
+ +

Returns

+
+
object
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToInt64(object) + +

+ +

Convert from Double to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDoubleToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to long

+
+
+ +

Returns

+
+
object
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToSingle(object) + +

+ +

Convert from Double to Single when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDoubleToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to float

+
+
+ +

Returns

+
+
object
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToString(object) + +

+ +

Convert from Double to String when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDoubleToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to string

+
+
+ +

Returns

+
+
object
+

String

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToUInt16(object) + +

+ +

Convert from Double to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDoubleToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to ushort

+
+
+ +

Returns

+
+
object
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToUInt32(object) + +

+ +

Convert from Double to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDoubleToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to uint

+
+
+ +

Returns

+
+
object
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromDoubleToUInt64(object) + +

+ +

Convert from Double to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromDoubleToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to double and then converted to ulong

+
+
+ +

Returns

+
+
object
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToBoolean(object) + +

+ +

Convert from Int16 to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt16ToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to bool

+
+
+ +

Returns

+
+
object
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToByte(object) + +

+ +

Convert from Int16 to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt16ToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to byte

+
+
+ +

Returns

+
+
object
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToChar(object) + +

+ +

Convert from Int16 to Char when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt16ToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to char

+
+
+ +

Returns

+
+
object
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToDecimal(object) + +

+ +

Convert from Int16 to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt16ToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to decimal

+
+
+ +

Returns

+
+
object
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToDouble(object) + +

+ +

Convert from Int16 to Double when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt16ToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to double

+
+
+ +

Returns

+
+
object
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToInt32(object) + +

+ +

Convert from Int16 to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt16ToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to int

+
+
+ +

Returns

+
+
object
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToInt64(object) + +

+ +

Convert from Int16 to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt16ToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to long

+
+
+ +

Returns

+
+
object
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToSingle(object) + +

+ +

Convert from Int16 to Single when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt16ToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to float

+
+
+ +

Returns

+
+
object
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToString(object) + +

+ +

Convert from Int16 to String when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt16ToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to string

+
+
+ +

Returns

+
+
object
+

String

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToUInt16(object) + +

+ +

Convert from Int16 to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt16ToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to ushort

+
+
+ +

Returns

+
+
object
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToUInt32(object) + +

+ +

Convert from Int16 to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt16ToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to uint

+
+
+ +

Returns

+
+
object
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromInt16ToUInt64(object) + +

+ +

Convert from Int16 to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt16ToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to short and then converted to ulong

+
+
+ +

Returns

+
+
object
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToBoolean(object) + +

+ +

Convert from Int32 to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt32ToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to bool

+
+
+ +

Returns

+
+
object
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToByte(object) + +

+ +

Convert from Int32 to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt32ToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to byte

+
+
+ +

Returns

+
+
object
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToChar(object) + +

+ +

Convert from Int32 to Char when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt32ToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to char

+
+
+ +

Returns

+
+
object
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToDecimal(object) + +

+ +

Convert from Int32 to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt32ToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to decimal

+
+
+ +

Returns

+
+
object
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToDouble(object) + +

+ +

Convert from Int32 to Double when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt32ToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to double

+
+
+ +

Returns

+
+
object
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToInt16(object) + +

+ +

Convert from Int32 to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt32ToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to short

+
+
+ +

Returns

+
+
object
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToInt64(object) + +

+ +

Convert from Int32 to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt32ToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to long

+
+
+ +

Returns

+
+
object
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToSingle(object) + +

+ +

Convert from Int32 to Single when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt32ToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to float

+
+
+ +

Returns

+
+
object
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToString(object) + +

+ +

Convert from Int32 to String when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt32ToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to string

+
+
+ +

Returns

+
+
object
+

String

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToUInt16(object) + +

+ +

Convert from Int32 to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt32ToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to ushort

+
+
+ +

Returns

+
+
object
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToUInt32(object) + +

+ +

Convert from Int32 to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt32ToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to uint

+
+
+ +

Returns

+
+
object
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromInt32ToUInt64(object) + +

+ +

Convert from Int32 to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt32ToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to int and then converted to ulong

+
+
+ +

Returns

+
+
object
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToBoolean(object) + +

+ +

Convert from Int64 to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt64ToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to bool

+
+
+ +

Returns

+
+
object
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToByte(object) + +

+ +

Convert from Int64 to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt64ToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to byte

+
+
+ +

Returns

+
+
object
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToChar(object) + +

+ +

Convert from Int64 to Char when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt64ToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to char

+
+
+ +

Returns

+
+
object
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToDecimal(object) + +

+ +

Convert from Int64 to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt64ToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to decimal

+
+
+ +

Returns

+
+
object
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToDouble(object) + +

+ +

Convert from Int64 to Double when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt64ToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to double

+
+
+ +

Returns

+
+
object
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToInt16(object) + +

+ +

Convert from Int64 to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt64ToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to short

+
+
+ +

Returns

+
+
object
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToInt32(object) + +

+ +

Convert from Int64 to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt64ToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to int

+
+
+ +

Returns

+
+
object
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToSingle(object) + +

+ +

Convert from Int64 to Single when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt64ToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to float

+
+
+ +

Returns

+
+
object
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToString(object) + +

+ +

Convert from Int64 to String when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt64ToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to string

+
+
+ +

Returns

+
+
object
+

String

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToUInt16(object) + +

+ +

Convert from Int64 to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt64ToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to ushort

+
+
+ +

Returns

+
+
object
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToUInt32(object) + +

+ +

Convert from Int64 to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt64ToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to uint

+
+
+ +

Returns

+
+
object
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromInt64ToUInt64(object) + +

+ +

Convert from Int64 to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromInt64ToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to long and then converted to ulong

+
+
+ +

Returns

+
+
object
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromSingleToBoolean(object) + +

+ +

Convert from Single to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static object FromSingleToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to bool

+
+
+ +

Returns

+
+
object
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromSingleToByte(object) + +

+ +

Convert from Single to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static object FromSingleToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to byte

+
+
+ +

Returns

+
+
object
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromSingleToChar(object) + +

+ +

Convert from Single to Char when input is a boxed non-generic object.

+
+
+ +
+
public static object FromSingleToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to char

+
+
+ +

Returns

+
+
object
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromSingleToDecimal(object) + +

+ +

Convert from Single to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static object FromSingleToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to decimal

+
+
+ +

Returns

+
+
object
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromSingleToDouble(object) + +

+ +

Convert from Single to Double when input is a boxed non-generic object.

+
+
+ +
+
public static object FromSingleToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to double

+
+
+ +

Returns

+
+
object
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromSingleToInt16(object) + +

+ +

Convert from Single to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromSingleToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to short

+
+
+ +

Returns

+
+
object
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromSingleToInt32(object) + +

+ +

Convert from Single to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromSingleToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to int

+
+
+ +

Returns

+
+
object
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromSingleToInt64(object) + +

+ +

Convert from Single to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromSingleToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to long

+
+
+ +

Returns

+
+
object
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromSingleToString(object) + +

+ +

Convert from Single to String when input is a boxed non-generic object.

+
+
+ +
+
public static object FromSingleToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to string

+
+
+ +

Returns

+
+
object
+

String

+
+
+ + + + + + + + + + + + + +

+ FromSingleToUInt16(object) + +

+ +

Convert from Single to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromSingleToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to ushort

+
+
+ +

Returns

+
+
object
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromSingleToUInt32(object) + +

+ +

Convert from Single to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromSingleToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to uint

+
+
+ +

Returns

+
+
object
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromSingleToUInt64(object) + +

+ +

Convert from Single to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromSingleToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to float and then converted to ulong

+
+
+ +

Returns

+
+
object
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromStringToBoolean(object) + +

+ +

Convert from String to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static object FromStringToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to bool

+
+
+ +

Returns

+
+
object
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromStringToByte(object) + +

+ +

Convert from String to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static object FromStringToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to byte

+
+
+ +

Returns

+
+
object
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromStringToChar(object) + +

+ +

Convert from String to Char when input is a boxed non-generic object.

+
+
+ +
+
public static object FromStringToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to char

+
+
+ +

Returns

+
+
object
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromStringToDecimal(object) + +

+ +

Convert from String to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static object FromStringToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to decimal

+
+
+ +

Returns

+
+
object
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromStringToDouble(object) + +

+ +

Convert from String to Double when input is a boxed non-generic object.

+
+
+ +
+
public static object FromStringToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to double

+
+
+ +

Returns

+
+
object
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromStringToInt16(object) + +

+ +

Convert from String to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromStringToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to short

+
+
+ +

Returns

+
+
object
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromStringToInt32(object) + +

+ +

Convert from String to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromStringToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to int

+
+
+ +

Returns

+
+
object
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromStringToInt64(object) + +

+ +

Convert from String to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromStringToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to long

+
+
+ +

Returns

+
+
object
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromStringToSingle(object) + +

+ +

Convert from String to Single when input is a boxed non-generic object.

+
+
+ +
+
public static object FromStringToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to float

+
+
+ +

Returns

+
+
object
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromStringToUInt16(object) + +

+ +

Convert from String to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromStringToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to ushort

+
+
+ +

Returns

+
+
object
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromStringToUInt32(object) + +

+ +

Convert from String to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromStringToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to uint

+
+
+ +

Returns

+
+
object
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromStringToUInt64(object) + +

+ +

Convert from String to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromStringToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to string and then converted to ulong

+
+
+ +

Returns

+
+
object
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToBoolean(object) + +

+ +

Convert from UInt16 to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt16ToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to bool

+
+
+ +

Returns

+
+
object
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToByte(object) + +

+ +

Convert from UInt16 to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt16ToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to byte

+
+
+ +

Returns

+
+
object
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToChar(object) + +

+ +

Convert from UInt16 to Char when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt16ToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to char

+
+
+ +

Returns

+
+
object
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToDecimal(object) + +

+ +

Convert from UInt16 to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt16ToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to decimal

+
+
+ +

Returns

+
+
object
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToDouble(object) + +

+ +

Convert from UInt16 to Double when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt16ToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to double

+
+
+ +

Returns

+
+
object
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToInt16(object) + +

+ +

Convert from UInt16 to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt16ToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to short

+
+
+ +

Returns

+
+
object
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToInt32(object) + +

+ +

Convert from UInt16 to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt16ToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to int

+
+
+ +

Returns

+
+
object
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToInt64(object) + +

+ +

Convert from UInt16 to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt16ToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to long

+
+
+ +

Returns

+
+
object
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToSingle(object) + +

+ +

Convert from UInt16 to Single when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt16ToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to float

+
+
+ +

Returns

+
+
object
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToString(object) + +

+ +

Convert from UInt16 to String when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt16ToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to string

+
+
+ +

Returns

+
+
object
+

String

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToUInt32(object) + +

+ +

Convert from UInt16 to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt16ToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to uint

+
+
+ +

Returns

+
+
object
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ FromUInt16ToUInt64(object) + +

+ +

Convert from UInt16 to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt16ToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ushort and then converted to ulong

+
+
+ +

Returns

+
+
object
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToBoolean(object) + +

+ +

Convert from UInt32 to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt32ToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to bool

+
+
+ +

Returns

+
+
object
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToByte(object) + +

+ +

Convert from UInt32 to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt32ToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to byte

+
+
+ +

Returns

+
+
object
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToChar(object) + +

+ +

Convert from UInt32 to Char when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt32ToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to char

+
+
+ +

Returns

+
+
object
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToDecimal(object) + +

+ +

Convert from UInt32 to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt32ToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to decimal

+
+
+ +

Returns

+
+
object
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToDouble(object) + +

+ +

Convert from UInt32 to Double when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt32ToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to double

+
+
+ +

Returns

+
+
object
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToInt16(object) + +

+ +

Convert from UInt32 to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt32ToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to short

+
+
+ +

Returns

+
+
object
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToInt32(object) + +

+ +

Convert from UInt32 to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt32ToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to int

+
+
+ +

Returns

+
+
object
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToInt64(object) + +

+ +

Convert from UInt32 to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt32ToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to long

+
+
+ +

Returns

+
+
object
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToSingle(object) + +

+ +

Convert from UInt32 to Single when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt32ToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to float

+
+
+ +

Returns

+
+
object
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToString(object) + +

+ +

Convert from UInt32 to String when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt32ToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to string

+
+
+ +

Returns

+
+
object
+

String

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToUInt16(object) + +

+ +

Convert from UInt32 to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt32ToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to ushort

+
+
+ +

Returns

+
+
object
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromUInt32ToUInt64(object) + +

+ +

Convert from UInt32 to UInt64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt32ToUInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to uint and then converted to ulong

+
+
+ +

Returns

+
+
object
+

UInt64

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToBoolean(object) + +

+ +

Convert from UInt64 to Boolean when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt64ToBoolean(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to bool

+
+
+ +

Returns

+
+
object
+

Boolean

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToByte(object) + +

+ +

Convert from UInt64 to Byte when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt64ToByte(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to byte

+
+
+ +

Returns

+
+
object
+

Byte

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToChar(object) + +

+ +

Convert from UInt64 to Char when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt64ToChar(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to char

+
+
+ +

Returns

+
+
object
+

Char

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToDecimal(object) + +

+ +

Convert from UInt64 to Decimal when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt64ToDecimal(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to decimal

+
+
+ +

Returns

+
+
object
+

Decimal

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToDouble(object) + +

+ +

Convert from UInt64 to Double when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt64ToDouble(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to double

+
+
+ +

Returns

+
+
object
+

Double

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToInt16(object) + +

+ +

Convert from UInt64 to Int16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt64ToInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to short

+
+
+ +

Returns

+
+
object
+

Int16

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToInt32(object) + +

+ +

Convert from UInt64 to Int32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt64ToInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to int

+
+
+ +

Returns

+
+
object
+

Int32

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToInt64(object) + +

+ +

Convert from UInt64 to Int64 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt64ToInt64(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to long

+
+
+ +

Returns

+
+
object
+

Int64

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToSingle(object) + +

+ +

Convert from UInt64 to Single when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt64ToSingle(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to float

+
+
+ +

Returns

+
+
object
+

Single

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToString(object) + +

+ +

Convert from UInt64 to String when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt64ToString(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to string

+
+
+ +

Returns

+
+
object
+

String

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToUInt16(object) + +

+ +

Convert from UInt64 to UInt16 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt64ToUInt16(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to ushort

+
+
+ +

Returns

+
+
object
+

UInt16

+
+
+ + + + + + + + + + + + + +

+ FromUInt64ToUInt32(object) + +

+ +

Convert from UInt64 to UInt32 when input is a boxed non-generic object.

+
+
+ +
+
public static object FromUInt64ToUInt32(object input)
+
+ +

Parameters

+
+
input object
+

The object that will be casted to ulong and then converted to uint

+
+
+ +

Returns

+
+
object
+

UInt32

+
+
+ + + + + + + + + + + + + +

+ GetConverter(Type, Type) + +

+ +
+
+ +
+
public static TypelessConvertDelegate GetConverter(Type input, Type output)
+
+ +

Parameters

+
+
input Type
+
+
output Type
+
+
+ +

Returns

+
+
TypelessConvertDelegate
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.TypelessConvertDelegate.html b/docs/website/api/NumSharp.Utilities.TypelessConvertDelegate.html new file mode 100644 index 000000000..f9b28423a --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.TypelessConvertDelegate.html @@ -0,0 +1,160 @@ + + + + + Delegate TypelessConvertDelegate | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Delegate TypelessConvertDelegate +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public delegate object TypelessConvertDelegate(object input)
+
+ +

Parameters

+
+
input object
+
+
+ +

Returns

+
+
object
+
+
+ + + + + + +
+
Extension Methods
+
+ +
+ + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.ValueCoordinatesIncrementor.EndCallbackHandler.html b/docs/website/api/NumSharp.Utilities.ValueCoordinatesIncrementor.EndCallbackHandler.html new file mode 100644 index 000000000..1b0430b04 --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.ValueCoordinatesIncrementor.EndCallbackHandler.html @@ -0,0 +1,155 @@ + + + + + Delegate ValueCoordinatesIncrementor.EndCallbackHandler | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Delegate ValueCoordinatesIncrementor.EndCallbackHandler +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public delegate void ValueCoordinatesIncrementor.EndCallbackHandler(ref ValueCoordinatesIncrementor incr)
+
+ +

Parameters

+
+
incr ValueCoordinatesIncrementor
+
+
+ + + + + + + +
+
Extension Methods
+
+ +
+ + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.ValueCoordinatesIncrementor.html b/docs/website/api/NumSharp.Utilities.ValueCoordinatesIncrementor.html new file mode 100644 index 000000000..300001bbd --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.ValueCoordinatesIncrementor.html @@ -0,0 +1,400 @@ + + + + + Struct ValueCoordinatesIncrementor | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Struct ValueCoordinatesIncrementor +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public struct ValueCoordinatesIncrementor
+
+ + + + + + + +
+
Inherited Members
+
+ + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ ValueCoordinatesIncrementor(ref Shape) + +

+ +

Initializes a new instance of the object class.

+
+
+ +
+
public ValueCoordinatesIncrementor(ref Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ + + + + + + + + + + + + + +

+ ValueCoordinatesIncrementor(ref Shape, EndCallbackHandler) + +

+ +
+
+ +
+
public ValueCoordinatesIncrementor(ref Shape shape, ValueCoordinatesIncrementor.EndCallbackHandler endCallback)
+
+ +

Parameters

+
+
shape Shape
+
+
endCallback ValueCoordinatesIncrementor.EndCallbackHandler
+
+
+ + + + + + + + + + + + + + +

+ ValueCoordinatesIncrementor(int[]) + +

+ +
+
+ +
+
public ValueCoordinatesIncrementor(int[] dims)
+
+ +

Parameters

+
+
dims int[]
+
+
+ + + + + + + + + + + + + + +

+ ValueCoordinatesIncrementor(int[], EndCallbackHandler) + +

+ +
+
+ +
+
public ValueCoordinatesIncrementor(int[] dims, ValueCoordinatesIncrementor.EndCallbackHandler endCallback)
+
+ +

Parameters

+
+
dims int[]
+
+
endCallback ValueCoordinatesIncrementor.EndCallbackHandler
+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ Index + +

+ +
+
+ +
+
public readonly int[] Index
+
+ + + + +

Field Value

+
+
int[]
+
+
+ + + + + + + + + +

Methods +

+ + + + +

+ Next() + +

+ +
+
+ +
+
public int[] Next()
+
+ + +

Returns

+
+
int[]
+
+
+ + + + + + + + + + + + + +

+ Reset() + +

+ +
+
+ +
+
public void Reset()
+
+ + + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.ValueCoordinatesIncrementorAutoResetting.html b/docs/website/api/NumSharp.Utilities.ValueCoordinatesIncrementorAutoResetting.html new file mode 100644 index 000000000..f646e5226 --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.ValueCoordinatesIncrementorAutoResetting.html @@ -0,0 +1,334 @@ + + + + + Struct ValueCoordinatesIncrementorAutoResetting | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Struct ValueCoordinatesIncrementorAutoResetting +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public struct ValueCoordinatesIncrementorAutoResetting
+
+ + + + + + + +
+
Inherited Members
+
+ + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ ValueCoordinatesIncrementorAutoResetting(ref Shape) + +

+ +

Initializes a new instance of the object class.

+
+
+ +
+
public ValueCoordinatesIncrementorAutoResetting(ref Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ + + + + + + + + + + + + + +

+ ValueCoordinatesIncrementorAutoResetting(int[]) + +

+ +
+
+ +
+
public ValueCoordinatesIncrementorAutoResetting(int[] dims)
+
+ +

Parameters

+
+
dims int[]
+
+
+ + + + + + + + + + + + +

Fields +

+ + + +

+ Index + +

+ +
+
+ +
+
public readonly int[] Index
+
+ + + + +

Field Value

+
+
int[]
+
+
+ + + + + + + + + +

Methods +

+ + + + +

+ Next() + +

+ +
+
+ +
+
public int[] Next()
+
+ + +

Returns

+
+
int[]
+
+
+ + + + + + + + + + + + + +

+ Reset() + +

+ +
+
+ +
+
public void Reset()
+
+ + + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.ValueOffsetIncrementor.html b/docs/website/api/NumSharp.Utilities.ValueOffsetIncrementor.html new file mode 100644 index 000000000..7bc26f40a --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.ValueOffsetIncrementor.html @@ -0,0 +1,334 @@ + + + + + Struct ValueOffsetIncrementor | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Struct ValueOffsetIncrementor +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public struct ValueOffsetIncrementor
+
+ + + + + + + +
+
Inherited Members
+
+ + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ ValueOffsetIncrementor(Shape) + +

+ +
+
+ +
+
public ValueOffsetIncrementor(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ + + + + + + + + + + + + + +

+ ValueOffsetIncrementor(int[]) + +

+ +
+
+ +
+
public ValueOffsetIncrementor(int[] dims)
+
+ +

Parameters

+
+
dims int[]
+
+
+ + + + + + + + + + + + +

Properties +

+ + + + +

+ HasNext + +

+ +
+
+ +
+
public bool HasNext { get; }
+
+ + + + + +

Property Value

+
+
bool
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ Next() + +

+ +
+
+ +
+
public int Next()
+
+ + +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ Reset() + +

+ +
+
+ +
+
public void Reset()
+
+ + + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.ValueOffsetIncrementorAutoresetting.html b/docs/website/api/NumSharp.Utilities.ValueOffsetIncrementorAutoresetting.html new file mode 100644 index 000000000..f66033382 --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.ValueOffsetIncrementorAutoresetting.html @@ -0,0 +1,334 @@ + + + + + Struct ValueOffsetIncrementorAutoresetting | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Struct ValueOffsetIncrementorAutoresetting +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public struct ValueOffsetIncrementorAutoresetting
+
+ + + + + + + +
+
Inherited Members
+
+ + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Constructors +

+ + + + +

+ ValueOffsetIncrementorAutoresetting(Shape) + +

+ +
+
+ +
+
public ValueOffsetIncrementorAutoresetting(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+
+
+ + + + + + + + + + + + + + +

+ ValueOffsetIncrementorAutoresetting(int[]) + +

+ +
+
+ +
+
public ValueOffsetIncrementorAutoresetting(int[] dims)
+
+ +

Parameters

+
+
dims int[]
+
+
+ + + + + + + + + + + + +

Properties +

+ + + + +

+ HasNext + +

+ +
+
+ +
+
public bool HasNext { get; }
+
+ + + + + +

Property Value

+
+
bool
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ Next() + +

+ +
+
+ +
+
public int Next()
+
+ + +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ Reset() + +

+ +
+
+ +
+
public void Reset()
+
+ + + + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.html b/docs/website/api/NumSharp.Utilities.html new file mode 100644 index 000000000..de6a3945e --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.html @@ -0,0 +1,244 @@ + + + + + Namespace NumSharp.Utilities | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ +

Namespace NumSharp.Utilities

+
+
+
+ +

+Classes +

+
+
ArrayConvert
+

Presents all possible combinations of array conversion of types supported by numpy.

+
+
+
+
Arrays
+
+
+
+
ArraysExtensions
+
+
+
+
ConcurrentHashset<T>
+
+
+
+
Converts
+

Provides various methods related to Convert.

+
+
+
+
Converts<T>
+

Provides various methods related to Convert based on give T.

+
+
+
+
Hashset<T>
+
+
+
+
InfoOf<T>
+

Provides a cache for properties of T that requires computation.

+
+
+
+
NDCoordinatesAxisIncrementor
+
+
+
+
NDCoordinatesIncrementor
+
+
+
+
NDCoordinatesIncrementorAutoResetting
+
+
+
+
NDCoordinatesLeftToAxisIncrementor
+
+
+
+
NDExtendedCoordinatesIncrementor
+
+
+
+
NDOffsetIncrementor
+
+
+
+
NDOffsetIncrementorAutoresetting
+
+
+
+
NonGenericConvert
+

Provides a way to convert boxed object from known time to specific type.

+
+
+
+
NumberInfo
+
+
+
+
SteppingExtension
+
+
+
+
TypelessConvert
+

Provides a way to convert boxed object from known input type to known output type. +By making it receive and return object - It is suitable for a common delegate: see TypelessConvertDelegate

+
+
+
+
py
+

Implements Python utility functions that are often used in connection with numpy

+
+
+

+Structs +

+
+
Hashset<T>.Enumerator
+
+
+
+
ValueCoordinatesIncrementor
+
+
+
+
ValueCoordinatesIncrementorAutoResetting
+
+
+
+
ValueOffsetIncrementor
+
+
+
+
ValueOffsetIncrementorAutoresetting
+
+
+

+Delegates +

+
+
TypelessConvertDelegate
+
+
+
+
ValueCoordinatesIncrementor.EndCallbackHandler
+
+
+ + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.Utilities.py.html b/docs/website/api/NumSharp.Utilities.py.html new file mode 100644 index 000000000..0a9981f28 --- /dev/null +++ b/docs/website/api/NumSharp.Utilities.py.html @@ -0,0 +1,252 @@ + + + + + Class py | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class py +

+ +
+
Namespace
NumSharp.Utilities
+
Assembly
NumSharp.dll
+
+ +

Implements Python utility functions that are often used in connection with numpy

+
+
+ +
+
public static class py
+
+ + + + +
+
Inheritance
+
+ +
py
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Methods +

+ + + + +

+ complex(string) + +

+ +
+
+ +
+
public static Complex complex(string input)
+
+ +

Parameters

+
+
input string
+
+
+ +

Returns

+
+
Complex
+
+
+ + + + + + + + + + + + + +

+ range(int) + +

+ +
+
+ +
+
public static int[] range(int n)
+
+ +

Parameters

+
+
n int
+
+
+ +

Returns

+
+
int[]
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.ViewInfo.html b/docs/website/api/NumSharp.ViewInfo.html new file mode 100644 index 000000000..e04ba6417 --- /dev/null +++ b/docs/website/api/NumSharp.ViewInfo.html @@ -0,0 +1,352 @@ + + + + + Class ViewInfo | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class ViewInfo +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class ViewInfo : ICloneable
+
+ + + + +
+
Inheritance
+
+ +
ViewInfo
+
+
+ +
+
Implements
+
+ +
+
+ + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Fields +

+ + + +

+ OriginalShape + +

+ +

OriginalShape is the primitive shape of the unsliced array

+
+
+ +
+
public Shape OriginalShape
+
+ + + + +

Field Value

+
+
Shape
+
+
+ + + + + + + + + + +

+ ParentShape + +

+ +

ParentShape points to a sliced shape that was reshaped. usually this is null, except if the Shape is a reshaped slice. +ParentShape always is a sliced shape!

+
+
+ +
+
public Shape ParentShape
+
+ + + + +

Field Value

+
+
Shape
+
+
+ + + + + + + + + + +

+ Slices + +

+ +

The slice definition for every dimension of the OriginalShape

+
+
+ +
+
public SliceDef[] Slices
+
+ + + + +

Field Value

+
+
SliceDef[]
+
+
+ + + + + + + + + + +

+ UnreducedShape + +

+ +

UnreducedShape is the shape after slicing but without dimensionality reductions due to index access

+
+
+ +
+
public Shape UnreducedShape
+
+ + + + +

Field Value

+
+
Shape
+
+
+ + + + + + + + + +

Methods +

+ + + + +

+ Clone() + +

+ +
+
+ +
+
public ViewInfo Clone()
+
+ + +

Returns

+
+
ViewInfo
+
+
+ + + + + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.html b/docs/website/api/NumSharp.html new file mode 100644 index 000000000..22acdf242 --- /dev/null +++ b/docs/website/api/NumSharp.html @@ -0,0 +1,334 @@ + + + + + Namespace NumSharp | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ +

Namespace NumSharp

+
+
+
+ +

+Classes +

+
+
AxisOutOfRangeException
+
+
+
+
BroadcastInfo
+
+
+
+
DType
+
+
+
+
IncorrectShapeException
+
+
+
+
IncorrectSizeException
+
+
+
+
IncorrectTypeException
+
+
+
+
Kwargs
+
+
+
+
MultiIterator
+
+
+
+
NDArray
+

An array object represents a multidimensional, homogeneous array of fixed-size items.
+An associated data-type object describes the format of each element in the array (its byte-order,
+how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.)

+
+
+
+
NDIteratorExtensions
+
+
+
+
NDIterator<TOut>
+
+
+
+
NPTypeCodeExtensions
+
+
+
+
NpzDictionary
+
+
+
+
NpzDictionary<T>
+
+
+
+
NumPyRandom
+

A class that serves as numpy.random.RandomState in python.

+
+
+
+
NumSharpException
+
+
+
+
Randomizer
+

Represents a pseudo-random number generator, which is a device that produces a sequence of numbers that meet certain statistical requirements for randomness.
+Equivalent of Random.

+
+
+
+
Slice
+
                                                                                                                                 <br />
+
+

NDArray can be indexed using slicing
+A slice is constructed by start:stop:step notation
+
+Examples:
+
+a[start:stop] # items start through stop-1
+a[start:] # items start through the rest of the array
+a[:stop] # items from the beginning through stop-1
+
+The key point to remember is that the :stop value represents the first value that is not
+in the selected slice. So, the difference between stop and start is the number of elements
+selected (if step is 1, the default).
+
+There is also the step value, which can be used with any of the above:
+a[:] # a copy of the whole array
+a[start:stop:step] # start through not past stop, by step
+
+The other feature is that start or stop may be a negative number, which means it counts
+from the end of the array instead of the beginning. So:
+a[-1] # last item in the array
+a[-2:] # last two items in the array
+a[:-2] # everything except the last two items
+Similarly, step may be a negative number:
+
+a[::- 1] # all items in the array, reversed
+a[1::- 1] # the first two items, reversed
+a[:-3:-1] # the last two items, reversed
+a[-3::- 1] # everything except the last two items, reversed
+
+NumSharp is kind to the programmer if there are fewer items than
+you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an
+empty list instead of an error.Sometimes you would prefer the error, so you have to be aware
+that this may happen.
+
+Adapted from Greg Hewgill's answer on Stackoverflow: https://stackoverflow.com/questions/509211/understanding-slice-notation
+
+Note: special IsIndex == true
+It will pick only a single value at Start in this dimension effectively reducing the Shape of the sliced matrix by 1 dimension.
+It can be used to reduce an N-dimensional array/matrix to a (N-1)-dimensional array/matrix
+
+Example:
+a=[[1, 2], [3, 4]]
+a[:, 1] returns the second column of that 2x2 matrix as a 1-D vector

+
+
+
+
TensorEngine
+
+
+
+
ViewInfo
+
+
+
+
np
+

API bridge between NumSharp and Python NumPy

+
+
+
+
np.Broadcast
+
+
+
+
np.linalg
+
+
+

+Structs +

+
+
NDArray._Unsafe
+
+
+
+
NDArray._Unsafe._Pinning
+
+
+
+
NativeRandomState
+

Represents the stored state of Randomizer.

+
+
+
+
Shape
+

Represents a shape of an N-D array.

+
+
+
+
SliceDef
+
+
+

+Interfaces +

+
+
IIndex
+

Represents a class that can be served as an index, e.g. ndarray[new Slice(...)]

+
+
+
+
INumSharpException
+
+
+
+
NDIterator
+
+
+

+Enums +

+
+
BackendType
+
+
+
+
IteratorType
+
+
+
+
NPTypeCode
+

Represents all available types in numpy.

+
+
+
+
StorageType
+
+
+

+Delegates +

+
+
MoveNextReferencedDelegate<T>
+
+
+ + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.np.Broadcast.html b/docs/website/api/NumSharp.np.Broadcast.html new file mode 100644 index 000000000..dd96cbfa1 --- /dev/null +++ b/docs/website/api/NumSharp.np.Broadcast.html @@ -0,0 +1,372 @@ + + + + + Class np.Broadcast | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class np.Broadcast +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +
+
+ +
+
public class np.Broadcast
+
+ + + + +
+
Inheritance
+
+ +
np.Broadcast
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ +
+
Extension Methods
+
+ +
+ + + + + +

Properties +

+ + + + +

+ index + +

+ +
+
+ +
+
public int index { get; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + + + + + + + +

+ iters + +

+ +
+
+ +
+
public NDIterator[] iters { get; }
+
+ + + + + +

Property Value

+
+
NDIterator[]
+
+
+ + + + + + + + + + +

+ nd + +

+ +
+
+ +
+
public int nd { get; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + + + + + + + +

+ ndim + +

+ +
+
+ +
+
public int ndim { get; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + + + + + + + +

+ shape + +

+ +
+
+ +
+
public Shape shape { get; }
+
+ + + + + +

Property Value

+
+
Shape
+
+
+ + + + + + + + + + +

+ size + +

+ +
+
+ +
+
public int size { get; }
+
+ + + + + +

Property Value

+
+
int
+
+
+ + + + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.np.html b/docs/website/api/NumSharp.np.html new file mode 100644 index 000000000..becd8a072 --- /dev/null +++ b/docs/website/api/NumSharp.np.html @@ -0,0 +1,17367 @@ + + + + + Class np | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+ + + +

+Class np +

+ +
+
Namespace
NumSharp
+
Assembly
NumSharp.dll
+
+ +

API bridge between NumSharp and Python NumPy

+
+
+ +
+
[SuppressMessage("ReSharper", "StaticMemberInitializerReferesToMemberBelow")]
+public static class np
+
+ + + + +
+
Inheritance
+
+ +
np
+
+
+ + + +
+
Inherited Members
+
+ + + + + + + +
+ + + + + + +

Fields +

+ + + +

+ bool + +

+ +
+
+ +
+
public static readonly Type @bool
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ bool8 + +

+ +
+
+ +
+
public static readonly Type bool8
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ bool_ + +

+ +
+
+ +
+
public static readonly Type bool_
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ byte + +

+ +
+
+ +
+
public static readonly Type @byte
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ char + +

+ +
+
+ +
+
public static readonly Type @char
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ complex128 + +

+ +
+
+ +
+
public static readonly Type complex128
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ complex64 + +

+ +
+
+ +
+
public static readonly Type complex64
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ complex_ + +

+ +
+
+ +
+
public static readonly Type complex_
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ decimal + +

+ +
+
+ +
+
public static readonly Type @decimal
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ double + +

+ +
+
+ +
+
public static readonly Type @double
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ float32 + +

+ +
+
+ +
+
public static readonly Type float32
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ float64 + +

+ +
+
+ +
+
public static readonly Type float64
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ float_ + +

+ +
+
+ +
+
public static readonly Type float_
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ int0 + +

+ +
+
+ +
+
public static readonly Type int0
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ int16 + +

+ +
+
+ +
+
public static readonly Type int16
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ int32 + +

+ +
+
+ +
+
public static readonly Type int32
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ int64 + +

+ +
+
+ +
+
public static readonly Type int64
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ int_ + +

+ +
+
+ +
+
public static readonly Type int_
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ intp + +

+ +
+
+ +
+
public static readonly Type intp
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ newaxis + +

+ +

A convenient alias for None, useful for indexing arrays.

+
+
+ +
+
public static readonly Slice newaxis
+
+ + + + +

Field Value

+
+
Slice
+
+
+ + + + + +

Remarks

+

https://docs.scipy.org/doc/numpy-1.17.0/reference/arrays.indexing.html

https://stackoverflow.com/questions/42190783/what-does-three-dots-in-python-mean-when-indexing-what-looks-like-a-number

+
+ + + + + +

+ ubyte + +

+ +
+
+ +
+
public static readonly Type ubyte
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ uint + +

+ +
+
+ +
+
public static readonly Type @uint
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ uint0 + +

+ +
+
+ +
+
public static readonly Type uint0
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ uint16 + +

+ +
+
+ +
+
public static readonly Type uint16
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ uint32 + +

+ +
+
+ +
+
public static readonly Type uint32
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ uint64 + +

+ +
+
+ +
+
public static readonly Type uint64
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + + +

+ uint8 + +

+ +
+
+ +
+
public static readonly Type uint8
+
+ + + + +

Field Value

+
+
Type
+
+
+ + + + + + + + + +

Properties +

+ + + + +

+ BackendEngine + +

+ +
+
+ +
+
public static BackendType BackendEngine { get; set; }
+
+ + + + + +

Property Value

+
+
BackendType
+
+
+ + + + + + + + + + +

+ Inf + +

+ +
+
+ +
+
public static double Inf { get; }
+
+ + + + + +

Property Value

+
+
double
+
+
+ + + + + + + + + + +

+ Infinity + +

+ +
+
+ +
+
public static double Infinity { get; }
+
+ + + + + +

Property Value

+
+
double
+
+
+ + + + + + + + + + +

+ NAN + +

+ +
+
+ +
+
public static double NAN { get; }
+
+ + + + + +

Property Value

+
+
double
+
+
+ + + + + + + + + + +

+ NINF + +

+ +
+
+ +
+
public static double NINF { get; }
+
+ + + + + +

Property Value

+
+
double
+
+
+ + + + + + + + + + +

+ NaN + +

+ +
+
+ +
+
public static double NaN { get; }
+
+ + + + + +

Property Value

+
+
double
+
+
+ + + + + + + + + + +

+ PINF + +

+ +
+
+ +
+
public static double PINF { get; }
+
+ + + + + +

Property Value

+
+
double
+
+
+ + + + + + + + + + +

+ chars + +

+ +
+
+ +
+
public static Type chars { get; }
+
+ + + + + +

Property Value

+
+
Type
+
+
+ + + + + + + + + + +

+ e + +

+ +
+
+ +
+
public static double e { get; }
+
+ + + + + +

Property Value

+
+
double
+
+
+ + + + + + + + + + +

+ euler_gamma + +

+ +
+
+ +
+
public static double euler_gamma { get; }
+
+ + + + + +

Property Value

+
+
double
+
+
+ + + + + + + + + + +

+ inf + +

+ +
+
+ +
+
public static double inf { get; }
+
+ + + + + +

Property Value

+
+
double
+
+
+ + + + + + + + + + +

+ infinity + +

+ +
+
+ +
+
public static double infinity { get; }
+
+ + + + + +

Property Value

+
+
double
+
+
+ + + + + + + + + + +

+ infty + +

+ +
+
+ +
+
public static double infty { get; }
+
+ + + + + +

Property Value

+
+
double
+
+
+ + + + + + + + + + +

+ nan + +

+ +
+
+ +
+
public static double nan { get; }
+
+ + + + + +

Property Value

+
+
double
+
+
+ + + + + + + + + + +

+ pi + +

+ +
+
+ +
+
public static double pi { get; }
+
+ + + + + +

Property Value

+
+
double
+
+
+ + + + + + + + + + +

+ random + +

+ +
+
+ +
+
public static NumPyRandom random { get; }
+
+ + + + + +

Property Value

+
+
NumPyRandom
+
+
+ + + + + + + + +

Methods +

+ + + + +

+ LoadJagged(byte[]) + +

+ +
+
+ +
+
public static Array LoadJagged(byte[] bytes)
+
+ +

Parameters

+
+
bytes byte[]
+
+
+ +

Returns

+
+
Array
+
+
+ + + + + + + + + + + + + +

+ LoadJagged(Stream, bool) + +

+ +
+
+ +
+
public static Array LoadJagged(Stream stream, bool trim = true)
+
+ +

Parameters

+
+
stream Stream
+
+
trim bool
+
+
+ +

Returns

+
+
Array
+
+
+ + + + + + + + + + + + + +

+ LoadJagged(string) + +

+ +
+
+ +
+
public static Array LoadJagged(string path)
+
+ +

Parameters

+
+
path string
+
+
+ +

Returns

+
+
Array
+
+
+ + + + + + + + + + + + + +

+ LoadJagged_Npz(byte[]) + +

+ +
+
+ +
+
public static NpzDictionary<Array> LoadJagged_Npz(byte[] bytes)
+
+ +

Parameters

+
+
bytes byte[]
+
+
+ +

Returns

+
+
NpzDictionary<Array>
+
+
+ + + + + + + + + + + + + +

+ LoadJagged_Npz(Stream, bool) + +

+ +
+
+ +
+
public static NpzDictionary<Array> LoadJagged_Npz(Stream stream, bool trim = true)
+
+ +

Parameters

+
+
stream Stream
+
+
trim bool
+
+
+ +

Returns

+
+
NpzDictionary<Array>
+
+
+ + + + + + + + + + + + + +

+ LoadJagged_Npz(string) + +

+ +
+
+ +
+
public static NpzDictionary<Array> LoadJagged_Npz(string path)
+
+ +

Parameters

+
+
path string
+
+
+ +

Returns

+
+
NpzDictionary<Array>
+
+
+ + + + + + + + + + + + + +

+ LoadMatrix(byte[]) + +

+ +
+
+ +
+
public static Array LoadMatrix(byte[] bytes)
+
+ +

Parameters

+
+
bytes byte[]
+
+
+ +

Returns

+
+
Array
+
+
+ + + + + + + + + + + + + +

+ LoadMatrix(Stream) + +

+ +
+
+ +
+
public static Array LoadMatrix(Stream stream)
+
+ +

Parameters

+
+
stream Stream
+
+
+ +

Returns

+
+
Array
+
+
+ + + + + + + + + + + + + +

+ LoadMatrix(string) + +

+ +
+
+ +
+
public static Array LoadMatrix(string path)
+
+ +

Parameters

+
+
path string
+
+
+ +

Returns

+
+
Array
+
+
+ + + + + + + + + + + + + +

+ LoadMatrix_Npz(byte[]) + +

+ +
+
+ +
+
public static NpzDictionary<Array> LoadMatrix_Npz(byte[] bytes)
+
+ +

Parameters

+
+
bytes byte[]
+
+
+ +

Returns

+
+
NpzDictionary<Array>
+
+
+ + + + + + + + + + + + + +

+ LoadMatrix_Npz(Stream) + +

+ +
+
+ +
+
public static NpzDictionary<Array> LoadMatrix_Npz(Stream stream)
+
+ +

Parameters

+
+
stream Stream
+
+
+ +

Returns

+
+
NpzDictionary<Array>
+
+
+ + + + + + + + + + + + + +

+ LoadMatrix_Npz(string) + +

+ +
+
+ +
+
public static NpzDictionary<Array> LoadMatrix_Npz(string path)
+
+ +

Parameters

+
+
path string
+
+
+ +

Returns

+
+
NpzDictionary<Array>
+
+
+ + + + + + + + + + + + + +

+ Load_Npz<T>(byte[]) + +

+ +
+
+ +
+
public static NpzDictionary<T> Load_Npz<T>(byte[] bytes) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
+
+ +

Parameters

+
+
bytes byte[]
+
+
+ +

Returns

+
+
NpzDictionary<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Load_Npz<T>(byte[], out T) + +

+ +
+
+ +
+
public static void Load_Npz<T>(byte[] bytes, out T value) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
+
+ +

Parameters

+
+
bytes byte[]
+
+
value T
+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Load_Npz<T>(Stream) + +

+ +
+
+ +
+
public static NpzDictionary<T> Load_Npz<T>(Stream stream) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
+
+ +

Parameters

+
+
stream Stream
+
+
+ +

Returns

+
+
NpzDictionary<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Load_Npz<T>(Stream, out NpzDictionary<T>) + +

+ +
+
+ +
+
public static NpzDictionary<T> Load_Npz<T>(Stream stream, out NpzDictionary<T> value) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
+
+ +

Parameters

+
+
stream Stream
+
+
value NpzDictionary<T>
+
+
+ +

Returns

+
+
NpzDictionary<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Load_Npz<T>(Stream, out T) + +

+ +
+
+ +
+
public static void Load_Npz<T>(Stream stream, out T value) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
+
+ +

Parameters

+
+
stream Stream
+
+
value T
+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Load_Npz<T>(string) + +

+ +
+
+ +
+
public static NpzDictionary<T> Load_Npz<T>(string path) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
+
+ +

Parameters

+
+
path string
+
+
+ +

Returns

+
+
NpzDictionary<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Load_Npz<T>(string, out NpzDictionary<T>) + +

+ +
+
+ +
+
public static NpzDictionary<T> Load_Npz<T>(string path, out NpzDictionary<T> value) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
+
+ +

Parameters

+
+
path string
+
+
value NpzDictionary<T>
+
+
+ +

Returns

+
+
NpzDictionary<T>
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Load_Npz<T>(string, out T) + +

+ +
+
+ +
+
public static void Load_Npz<T>(string path, out T value) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
+
+ +

Parameters

+
+
path string
+
+
value T
+
+
+ + +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Load<T>(byte[]) + +

+ +
+
+ +
+
public static T Load<T>(byte[] bytes) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
+
+ +

Parameters

+
+
bytes byte[]
+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Load<T>(byte[], out T) + +

+ +
+
+ +
+
public static T Load<T>(byte[] bytes, out T value) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
+
+ +

Parameters

+
+
bytes byte[]
+
+
value T
+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Load<T>(Stream) + +

+ +
+
+ +
+
public static T Load<T>(Stream stream) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
+
+ +

Parameters

+
+
stream Stream
+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Load<T>(Stream, out T) + +

+ +
+
+ +
+
public static T Load<T>(Stream stream, out T value) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
+
+ +

Parameters

+
+
stream Stream
+
+
value T
+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Load<T>(string) + +

+ +
+
+ +
+
public static T Load<T>(string path) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
+
+ +

Parameters

+
+
path string
+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Load<T>(string, out T) + +

+ +
+
+ +
+
public static T Load<T>(string path, out T value) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
+
+ +

Parameters

+
+
path string
+
+
value T
+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ Save(Array) + +

+ +
+
+ +
+
public static byte[] Save(Array array)
+
+ +

Parameters

+
+
array Array
+
+
+ +

Returns

+
+
byte[]
+
+
+ + + + + + + + + + + + + +

+ Save(Array, Stream) + +

+ +
+
+ +
+
public static ulong Save(Array array, Stream stream)
+
+ +

Parameters

+
+
array Array
+
+
stream Stream
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ Save(Array, string) + +

+ +
+
+ +
+
public static ulong Save(Array array, string path)
+
+ +

Parameters

+
+
array Array
+
+
path string
+
+
+ +

Returns

+
+
ulong
+
+
+ + + + + + + + + + + + + +

+ Save_Npz(Array, CompressionLevel) + +

+ +
+
+ +
+
public static byte[] Save_Npz(Array array, CompressionLevel compression = CompressionLevel.Fastest)
+
+ +

Parameters

+
+
array Array
+
+
compression CompressionLevel
+
+
+ +

Returns

+
+
byte[]
+
+
+ + + + + + + + + + + + + +

+ Save_Npz(Array, Stream, CompressionLevel, bool) + +

+ +
+
+ +
+
public static void Save_Npz(Array array, Stream stream, CompressionLevel compression = CompressionLevel.Fastest, bool leaveOpen = false)
+
+ +

Parameters

+
+
array Array
+
+
stream Stream
+
+
compression CompressionLevel
+
+
leaveOpen bool
+
+
+ + + + + + + + + + + + + + +

+ Save_Npz(Array, string, CompressionLevel) + +

+ +
+
+ +
+
public static void Save_Npz(Array array, string path, CompressionLevel compression = CompressionLevel.Fastest)
+
+ +

Parameters

+
+
array Array
+
+
path string
+
+
compression CompressionLevel
+
+
+ + + + + + + + + + + + + + +

+ Save_Npz(Dictionary<string, Array>, CompressionLevel) + +

+ +
+
+ +
+
public static byte[] Save_Npz(Dictionary<string, Array> arrays, CompressionLevel compression = CompressionLevel.Fastest)
+
+ +

Parameters

+
+
arrays Dictionary<string, Array>
+
+
compression CompressionLevel
+
+
+ +

Returns

+
+
byte[]
+
+
+ + + + + + + + + + + + + +

+ Save_Npz(Dictionary<string, Array>, Stream, CompressionLevel, bool) + +

+ +
+
+ +
+
public static void Save_Npz(Dictionary<string, Array> arrays, Stream stream, CompressionLevel compression = CompressionLevel.Fastest, bool leaveOpen = false)
+
+ +

Parameters

+
+
arrays Dictionary<string, Array>
+
+
stream Stream
+
+
compression CompressionLevel
+
+
leaveOpen bool
+
+
+ + + + + + + + + + + + + + +

+ Save_Npz(Dictionary<string, Array>, string, CompressionLevel) + +

+ +
+
+ +
+
public static void Save_Npz(Dictionary<string, Array> arrays, string path, CompressionLevel compression = CompressionLevel.Fastest)
+
+ +

Parameters

+
+
arrays Dictionary<string, Array>
+
+
path string
+
+
compression CompressionLevel
+
+
+ + + + + + + + + + + + + + +

+ abs(in NDArray) + +

+ +

Calculate the absolute value element-wise.
+np.abs is a shorthand for this function.

+
+
+ +
+
public static NDArray abs(in NDArray a)
+
+ +

Parameters

+
+
a NDArray
+

Input value.

+
+
+ +

Returns

+
+
NDArray
+

An ndarray containing the absolute value of each element in x.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ abs(in NDArray, NPTypeCode?) + +

+ +

Calculate the absolute value element-wise.
+np.abs is a shorthand for this function.

+
+
+ +
+
public static NDArray abs(in NDArray a, NPTypeCode? outType)
+
+ +

Parameters

+
+
a NDArray
+

Input value.

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

An ndarray containing the absolute value of each element in x.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ abs(in NDArray, Type) + +

+ +

Calculate the absolute value element-wise.
+np.abs is a shorthand for this function.

+
+
+ +
+
public static NDArray abs(in NDArray a, Type outType)
+
+ +

Parameters

+
+
a NDArray
+

Input value.

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

An ndarray containing the absolute value of each element in x.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ absolute(in NDArray) + +

+ +

Calculate the absolute value element-wise.
+np.abs is a shorthand for this function.

+
+
+ +
+
public static NDArray absolute(in NDArray a)
+
+ +

Parameters

+
+
a NDArray
+

Input value.

+
+
+ +

Returns

+
+
NDArray
+

An ndarray containing the absolute value of each element in x.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ absolute(in NDArray, NPTypeCode?) + +

+ +

Calculate the absolute value element-wise.
+np.abs is a shorthand for this function.

+
+
+ +
+
public static NDArray absolute(in NDArray a, NPTypeCode? outType)
+
+ +

Parameters

+
+
a NDArray
+

Input value.

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

An ndarray containing the absolute value of each element in x.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ absolute(in NDArray, Type) + +

+ +

Calculate the absolute value element-wise.
+np.abs is a shorthand for this function.

+
+
+ +
+
public static NDArray absolute(in NDArray a, Type outType)
+
+ +

Parameters

+
+
a NDArray
+

Input value.

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

An ndarray containing the absolute value of each element in x.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ add(in NDArray, in NDArray) + +

+ +
+
+ +
+
public static NDArray add(in NDArray x1, in NDArray x2)
+
+ +

Parameters

+
+
x1 NDArray
+
+
x2 NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ all(NDArray) + +

+ +

Test whether all array elements along a given axis evaluate to True.

+
+
+ +
+
public static bool all(NDArray a)
+
+ +

Parameters

+
+
a NDArray
+

Input array or object that can be converted to an array.

+
+
+ +

Returns

+
+
bool
+

A new boolean or ndarray is returned unless out is specified, in which case a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ all(NDArray, int, bool) + +

+ +

Test whether all array elements along a given axis evaluate to True.

+
+
+ +
+
public static NDArray<bool> all(NDArray nd, int axis, bool keepdims = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int
+

Axis or axes along which a logical AND reduction is performed. The default (axis = None) is to perform a logical OR over all the dimensions of the input array. axis may be negative, in which case it counts from the last to the first axis.

+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray<bool>
+

A new boolean or ndarray is returned unless out is specified, in which case a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ allclose(NDArray, NDArray, double, double, bool) + +

+ +

Returns True if two arrays are element-wise equal within a tolerance. +The tolerance values are positive, typically very small numbers.The

+

relative difference (rtol * abs(b)) and the absolute difference +atol are added together to compare against the absolute difference +between a and b. +If either array contains one or more NaNs, False is returned. +Infs are treated as equal if they are in the same place and of the same +sign in both arrays.

+
+
+ +
+
public static bool allclose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false)
+
+ +

Parameters

+
+
a NDArray
+

Input array to compare with b

+
+
b NDArray
+

Input array to compare with a.

+
+
rtol double
+

The relative tolerance parameter(see Notes)

+
+
atol double
+

The absolute tolerance parameter(see Notes)

+
+
equal_nan bool
+

Whether to compare NaN's as equal. If True, NaN's in a will be +considered equal to NaN's in b in the output array.

+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + + + + + + + +

+ amax(NDArray, int?, bool, Type) + +

+ +

Return the maximum of an array or maximum along an axis.

+
+
+ +
+
public static NDArray amax(NDArray a, int? axis = null, bool keepdims = false, Type dtype = null)
+
+ +

Parameters

+
+
a NDArray
+
+
axis int?
+

Axis or axes along which to operate.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
dtype Type
+

the type expected as a return, null will remain the same dtype.

+
+
+ +

Returns

+
+
NDArray
+

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ amax<T>(NDArray) + +

+ +

Return the maximum of an array or maximum along an axis.

+
+
+ +
+
public static T amax<T>(NDArray a) where T : unmanaged
+
+ +

Parameters

+
+
a NDArray
+
+
+ +

Returns

+
+
T
+

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ +

Type Parameters

+
+
T
+

the type expected as a return, cast is performed if necessary.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ amin(in NDArray, int?, bool, Type) + +

+ +

Return the minimum of an array or minimum along an axis.

+
+
+ +
+
public static NDArray amin(in NDArray a, int? axis = null, bool keepdims = false, Type dtype = null)
+
+ +

Parameters

+
+
a NDArray
+

Input data.

+
+
axis int?
+

Axis or axes along which to operate.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
dtype Type
+

the type expected as a return, null will remain the same dtype.

+
+
+ +

Returns

+
+
NDArray
+

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ amin<T>(in NDArray) + +

+ +

Return the minimum of an array or minimum along an axis.

+
+
+ +
+
public static T amin<T>(in NDArray a) where T : unmanaged
+
+ +

Parameters

+
+
a NDArray
+

Input data.

+
+
+ +

Returns

+
+
T
+

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ +

Type Parameters

+
+
T
+

the type expected as a return, cast is performed if necessary.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ any(NDArray) + +

+ +

Test whether any array element along a given axis evaluates to True.

+
+
+ +
+
public static bool any(NDArray a)
+
+ +

Parameters

+
+
a NDArray
+

Input array or object that can be converted to an array.

+
+
+ +

Returns

+
+
bool
+

A new boolean or ndarray is returned unless out is specified, in which case a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ any(NDArray, int, bool) + +

+ +

Test whether any array element along a given axis evaluates to True.

+
+
+ +
+
public static NDArray<bool> any(NDArray nd, int axis, bool keepdims)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int
+

Axis or axes along which a logical OR reduction is performed. The default (axis = None) is to perform a logical OR over all the dimensions of the input array. axis may be negative, in which case it counts from the last to the first axis.

+
+
keepdims bool
+
+
+ +

Returns

+
+
NDArray<bool>
+

A new boolean or ndarray is returned unless out is specified, in which case a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ arange(double) + +

+ +

Return evenly spaced values within a given interval.

+

Values are generated within the half-open interval [start, stop) +(in other words, the interval including start but excluding stop). +For integer arguments the function is equivalent to the Python built-in +range function, but returns an ndarray rather than a list.

+

When using a non-integer step, such as 0.1, the results will often not +be consistent. It is better to use numpy.linspace for these cases.

+
+
+ +
+
public static NDArray arange(double stop)
+
+ +

Parameters

+
+
stop double
+

End of interval. The interval does not include this value, except +in some cases where step is not an integer and floating point +round-off affects the length of out.

+
+
+ +

Returns

+
+
NDArray
+

Array of evenly spaced values.

+

For floating point arguments, the length of the result is +ceil((stop - start)/step). Because of floating point overflow, +this rule may result in the last element of out being greater +than stop.

+
+
+ + + + + + + + + + + + + +

+ arange(double, double, double) + +

+ +

Return evenly spaced values within a given interval.

+

Values are generated within the half-open interval [start, stop) +(in other words, the interval including start but excluding stop). +For integer arguments the function is equivalent to the Python built-in +range function, but returns an ndarray rather than a list.

+

When using a non-integer step, such as 0.1, the results will often not +be consistent. It is better to use numpy.linspace for these cases.

+
+
+ +
+
public static NDArray arange(double start, double stop, double step = 1)
+
+ +

Parameters

+
+
start double
+

Start of interval. The interval includes this value. The default +start value is 0.

+
+
stop double
+

End of interval. The interval does not include this value, except +in some cases where step is not an integer and floating point +round-off affects the length of out.

+
+
step double
+

Spacing between values. For any output out, this is the distance +between two adjacent values, out[i+1] - out[i]. The default +step size is 1. If step is specified as a position argument, +start must also be given.

+
+
+ +

Returns

+
+
NDArray
+

Array of evenly spaced values.

+

For floating point arguments, the length of the result is +ceil((stop - start)/step). Because of floating point overflow, +this rule may result in the last element of out being greater +than stop.

+
+
+ + + + + + + + + + + + + +

+ arange(int) + +

+ +

Return evenly spaced values within a given interval.

+

Values are generated within the half-open interval [start, stop) +(in other words, the interval including start but excluding stop). +For integer arguments the function is equivalent to the Python built-in +range function, but returns an ndarray rather than a list.

+

When using a non-integer step, such as 0.1, the results will often not +be consistent. It is better to use numpy.linspace for these cases.

+
+
+ +
+
public static NDArray arange(int stop)
+
+ +

Parameters

+
+
stop int
+

End of interval. The interval does not include this value, except +in some cases where step is not an integer and floating point +round-off affects the length of out.

+
+
+ +

Returns

+
+
NDArray
+

Array of evenly spaced values.

+

For floating point arguments, the length of the result is +ceil((stop - start)/step). Because of floating point overflow, +this rule may result in the last element of out being greater +than stop.

+
+
+ + + + + + + + + + + + + +

+ arange(int, int, int) + +

+ +

Return evenly spaced values within a given interval.

+

Values are generated within the half-open interval [start, stop) +(in other words, the interval including start but excluding stop). +For integer arguments the function is equivalent to the Python built-in +range function, but returns an ndarray rather than a list.

+

When using a non-integer step, such as 0.1, the results will often not +be consistent. It is better to use numpy.linspace for these cases.

+
+
+ +
+
public static NDArray arange(int start, int stop, int step = 1)
+
+ +

Parameters

+
+
start int
+

Start of interval. The interval includes this value. The default +start value is 0.

+
+
stop int
+

End of interval. The interval does not include this value, except +in some cases where step is not an integer and floating point +round-off affects the length of out.

+
+
step int
+

Spacing between values. For any output out, this is the distance +between two adjacent values, out[i+1] - out[i]. The default +step size is 1. If step is specified as a position argument, +start must also be given.

+
+
+ +

Returns

+
+
NDArray
+

Array of evenly spaced values.

+

For floating point arguments, the length of the result is +ceil((stop - start)/step). Because of floating point overflow, +this rule may result in the last element of out being greater +than stop.

+
+
+ + + + + + + + + + + + + +

+ arange(float) + +

+ +

Return evenly spaced values within a given interval.

+

Values are generated within the half-open interval [start, stop) +(in other words, the interval including start but excluding stop). +For integer arguments the function is equivalent to the Python built-in +range function, but returns an ndarray rather than a list.

+

When using a non-integer step, such as 0.1, the results will often not +be consistent. It is better to use numpy.linspace for these cases.

+
+
+ +
+
public static NDArray arange(float stop)
+
+ +

Parameters

+
+
stop float
+

End of interval. The interval does not include this value, except +in some cases where step is not an integer and floating point +round-off affects the length of out.

+
+
+ +

Returns

+
+
NDArray
+

Array of evenly spaced values.

+

For floating point arguments, the length of the result is +ceil((stop - start)/step). Because of floating point overflow, +this rule may result in the last element of out being greater +than stop.

+
+
+ + + + + + + + + + + + + +

+ arange(float, float, float) + +

+ +

Return evenly spaced values within a given interval.

+

Values are generated within the half-open interval [start, stop) +(in other words, the interval including start but excluding stop). +For integer arguments the function is equivalent to the Python built-in +range function, but returns an ndarray rather than a list.

+

When using a non-integer step, such as 0.1, the results will often not +be consistent. It is better to use numpy.linspace for these cases.

+
+
+ +
+
public static NDArray arange(float start, float stop, float step = 1)
+
+ +

Parameters

+
+
start float
+

Start of interval. The interval includes this value. The default +start value is 0.

+
+
stop float
+

End of interval. The interval does not include this value, except +in some cases where step is not an integer and floating point +round-off affects the length of out.

+
+
step float
+

Spacing between values. For any output out, this is the distance +between two adjacent values, out[i+1] - out[i]. The default +step size is 1. If step is specified as a position argument, +start must also be given.

+
+
+ +

Returns

+
+
NDArray
+

Array of evenly spaced values.

+

For floating point arguments, the length of the result is +ceil((stop - start)/step). Because of floating point overflow, +this rule may result in the last element of out being greater +than stop.

+
+
+ + + + + + + + + + + + + +

+ arccos(in NDArray, NPTypeCode?) + +

+ +

Trigonometric inverse cosine, element-wise.
+The inverse of cos so that, if y = cos(x), then x = arccos(y).

+
+
+ +
+
public static NDArray arccos(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Input array.

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The angle of the ray intersecting the unit circle at the given x-coordinate in radians [0, pi]. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ arccos(in NDArray, Type) + +

+ +

Trigonometric inverse cosine, element-wise.
+The inverse of cos so that, if y = cos(x), then x = arccos(y).

+
+
+ +
+
public static NDArray arccos(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Input array.

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The angle of the ray intersecting the unit circle at the given x-coordinate in radians [0, pi]. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ arcsin(in NDArray, NPTypeCode?) + +

+ +

Inverse sine, element-wise.
+The convention is to return the angle z whose real part lies in [-pi/2, pi/2].

+
+
+ +
+
public static NDArray arcsin(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Input array.

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The inverse sine of each element in x, in radians and in the closed interval [-pi/2, pi/2]. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ arcsin(in NDArray, Type) + +

+ +

Inverse sine, element-wise.
+The convention is to return the angle z whose real part lies in [-pi/2, pi/2].

+
+
+ +
+
public static NDArray arcsin(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Input array.

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The inverse sine of each element in x, in radians and in the closed interval [-pi/2, pi/2]. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ arctan(in NDArray, NPTypeCode?) + +

+ +

Compute trigonometric inverse tangent, element-wise.
+The inverse of tan, so that if y = tan(x) then x = arctan(y).

+
+
+ +
+
public static NDArray arctan(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Input array.

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

Return has the same shape as x. Its real part is in [-pi/2, pi/2] (arctan(+/-inf) returns +/-pi/2). This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ arctan(in NDArray, Type) + +

+ +

Compute trigonometric inverse tangent, element-wise.
+The inverse of tan, so that if y = tan(x) then x = arctan(y).

+
+
+ +
+
public static NDArray arctan(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Input array.

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

Return has the same shape as x. Its real part is in [-pi/2, pi/2] (arctan(+/-inf) returns +/-pi/2). This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ arctan2(in NDArray, in NDArray, NPTypeCode?) + +

+ +

Compute Element-wise arc tangent of x1/x2 choosing the quadrant correctly.
+By IEEE convention, this function is defined for x2 = +/-0 and for either or both of x1 and x2 = +/-inf

+
+
+ +
+
public static NDArray arctan2(in NDArray y, in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
y NDArray
+
+
x NDArray
+

Input array y-coordinates.

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The Array of angles in radians, in the range [-pi, pi]. This is a scalar if both x1 and x2 are scalars.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ arctan2(in NDArray, in NDArray, Type) + +

+ +

Compute Element-wise arc tangent of x1/x2 choosing the quadrant correctly.
+By IEEE convention, this function is defined for x2 = +/-0 and for either or both of x1 and x2 = +/-inf

+
+
+ +
+
public static NDArray arctan2(in NDArray y, in NDArray x, Type outType)
+
+ +

Parameters

+
+
y NDArray
+
+
x NDArray
+

Input array y-coordinates.

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The Array of angles in radians, in the range [-pi, pi]. This is a scalar if both x1 and x2 are scalars.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ are_broadcastable(NDArray, NDArray) + +

+ +

Tests if these two two arrays are broadcastable against each other.

+
+
+ +
+
public static bool are_broadcastable(NDArray lhs, NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+

An array to test for broadcasting.

+
+
rhs NDArray
+

An array to test for broadcasting.

+
+
+ +

Returns

+
+
bool
+

True if these can be broadcasted against each other.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ are_broadcastable(params NDArray[]) + +

+ +

Tests if these two two arrays are broadcastable against each other.

+
+
+ +
+
public static bool are_broadcastable(params NDArray[] ndArrays)
+
+ +

Parameters

+
+
ndArrays NDArray[]
+

The arrays to test for broadcasting.

+
+
+ +

Returns

+
+
bool
+

True if these can be broadcasted against each other.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ are_broadcastable(params Shape[]) + +

+ +

Tests if these two two arrays are broadcastable against each other.

+
+
+ +
+
public static bool are_broadcastable(params Shape[] shapes)
+
+ +

Parameters

+
+
shapes Shape[]
+

The shapes to test for broadcasting.

+
+
+ +

Returns

+
+
bool
+

True if these can be broadcasted against each other.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ are_broadcastable(params int[][]) + +

+ +

Tests if these two two arrays are broadcastable against each other.

+
+
+ +
+
public static bool are_broadcastable(params int[][] shapes)
+
+ +

Parameters

+
+
shapes int[][]
+

The shapes to test for broadcasting.

+
+
+ +

Returns

+
+
bool
+

True if these can be broadcasted against each other.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ argmax(NDArray) + +

+ +

Returns the index of the maximum value.

+
+
+ +
+
public static int argmax(NDArray a)
+
+ +

Parameters

+
+
a NDArray
+

Input array.

+
+
+ +

Returns

+
+
int
+

Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ argmax(NDArray, int) + +

+ +

Returns the indices of the maximum values along an axis.

+
+
+ +
+
public static NDArray argmax(NDArray a, int axis)
+
+ +

Parameters

+
+
a NDArray
+

Input array.

+
+
axis int
+

By default, the index is into the flattened array, otherwise along the specified axis.

+
+
+ +

Returns

+
+
NDArray
+

Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ argmin(NDArray) + +

+ +

Returns the index of the minimum value.

+
+
+ +
+
public static int argmin(NDArray a)
+
+ +

Parameters

+
+
a NDArray
+

Input array.

+
+
+ +

Returns

+
+
int
+

Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ argmin(NDArray, int) + +

+ +

Returns the indices of the minimum values along an axis.

+
+
+ +
+
public static NDArray argmin(NDArray a, int axis)
+
+ +

Parameters

+
+
a NDArray
+

Input array.

+
+
axis int
+

By default, the index is into the flattened array, otherwise along the specified axis.

+
+
+ +

Returns

+
+
NDArray
+

Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ argsort<T>(NDArray, int) + +

+ +

Returns the indices that would sort an array.

+

Perform an indirect sort along the given axis using the algorithm specified by the kind keyword.It returns an array of indices of the same shape as a that index data along the given axis in sorted order.

+
+
+ +
+
public static NDArray argsort<T>(NDArray nd, int axis = -1)
+
+ +

Parameters

+
+
nd NDArray
+
+
axis int
+
+
+ +

Returns

+
+
NDArray
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ around(in NDArray, int, NPTypeCode?) + +

+ +

Evenly round to the given number of decimals.

+
+
+ +
+
public static NDArray around(in NDArray x, int decimals, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Input array

+
+
decimals int
+

Number of decimal places to round to

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. +The real and imaginary parts of complex numbers are rounded separately.The result of rounding a float is a float.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ around(in NDArray, int, Type) + +

+ +

Evenly round to the given number of decimals.

+
+
+ +
+
public static NDArray around(in NDArray x, int decimals, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Input array

+
+
decimals int
+

Number of decimal places to round to

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. +The real and imaginary parts of complex numbers are rounded separately.The result of rounding a float is a float.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ around(in NDArray, NPTypeCode?) + +

+ +

Evenly round to the given number of decimals.

+
+
+ +
+
public static NDArray around(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Input array

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. +The real and imaginary parts of complex numbers are rounded separately.The result of rounding a float is a float.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ around(in NDArray, Type) + +

+ +

Evenly round to the given number of decimals.

+
+
+ +
+
public static NDArray around(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Input array

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. +The real and imaginary parts of complex numbers are rounded separately.The result of rounding a float is a float.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ array(NDArray, bool) + +

+ +

Wraps given nd in an alias. If copy is true then returns a clone.

+
+
+ +
+
public static NDArray array(NDArray nd, bool copy = false)
+
+ +

Parameters

+
+
nd NDArray
+
+
copy bool
+

If copy is true then returns a clone.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ array(Array, Type, int, bool, char) + +

+ +

Creates an NDArray from an array with an unknown size or dtype.

+
+
+ +
+
[SuppressMessage("ReSharper", "InvalidXmlDocComment")]
+public static NDArray array(Array array, Type dtype = null, int ndmin = 1, bool copy = true, char order = 'C')
+
+ +

Parameters

+
+
array Array
+
+
dtype Type
+
+
ndmin int
+

Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement.

+
+
copy bool
+

Always copies if the array is larger than 1-d.

+
+
order char
+

Not used.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ array(string) + +

+ +

Create a vector NDArray of dtype char.

+
+
+ +
+
public static NDArray array(string chars)
+
+ +

Parameters

+
+
chars string
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ array(string[]) + +

+ +
Create a vector ndarray of type <xref href="System.String" data-throw-if-not-resolved="false"></xref>.
+
+

Encode string array. +format: [numOfRow lenOfRow1 lenOfRow2 contents] +sample: [2 2 4 aacccc]

+
+
+ +
+
public static NDArray array(string[] strArray)
+
+ +

Parameters

+
+
strArray string[]
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ array_equal(NDArray, NDArray) + +

+ +

True if two arrays have the same shape and elements, False otherwise.

+
+
+ +
+
public static bool array_equal(NDArray a, NDArray b)
+
+ +

Parameters

+
+
a NDArray
+

Input array.

+
+
b NDArray
+

Input array.

+
+
+ +

Returns

+
+
bool
+

Returns True if the arrays are equal.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ array<T>(IEnumerable<T>) + +

+ +

Creates a Vector NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(IEnumerable<T> data) where T : unmanaged
+
+ +

Parameters

+
+
data IEnumerable<T>
+

The enumeration of data to create NDArray from.

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(IEnumerable<T>, int) + +

+ +

Creates a Vector NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(IEnumerable<T> data, int size) where T : unmanaged
+
+ +

Parameters

+
+
data IEnumerable<T>
+

The enumeration of data to create NDArray from.

+
+
size int
+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+

https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html
+Always performs a copy.
+size can be used to limit the amount of items to read form data. Reading stops on either size or data ends.

+
+ + + + + + +

+ array<T>(T[,,,,,,,,,,,,,,,], bool) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(T[,,,,,,,,,,,,,,,] data, bool copy = true) where T : unmanaged
+
+ +

Parameters

+
+
data T[,,,,,,,,,,,,,,,]
+

The array to create NDArray from.

+
+
copy bool
+

If true then the array will be copied to a newly allocated memory.
+If false then the array will be pinned by calling Alloc(object).

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[,,,,,,,,,,,,,,], bool) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(T[,,,,,,,,,,,,,,] data, bool copy = true) where T : unmanaged
+
+ +

Parameters

+
+
data T[,,,,,,,,,,,,,,]
+

The array to create NDArray from.

+
+
copy bool
+

If true then the array will be copied to a newly allocated memory.
+If false then the array will be pinned by calling Alloc(object).

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[,,,,,,,,,,,,,], bool) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(T[,,,,,,,,,,,,,] data, bool copy = true) where T : unmanaged
+
+ +

Parameters

+
+
data T[,,,,,,,,,,,,,]
+

The array to create NDArray from.

+
+
copy bool
+

If true then the array will be copied to a newly allocated memory.
+If false then the array will be pinned by calling Alloc(object).

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[,,,,,,,,,,,,], bool) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(T[,,,,,,,,,,,,] data, bool copy = true) where T : unmanaged
+
+ +

Parameters

+
+
data T[,,,,,,,,,,,,]
+

The array to create NDArray from.

+
+
copy bool
+

If true then the array will be copied to a newly allocated memory.
+If false then the array will be pinned by calling Alloc(object).

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[,,,,,,,,,,,], bool) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(T[,,,,,,,,,,,] data, bool copy = true) where T : unmanaged
+
+ +

Parameters

+
+
data T[,,,,,,,,,,,]
+

The array to create NDArray from.

+
+
copy bool
+

If true then the array will be copied to a newly allocated memory.
+If false then the array will be pinned by calling Alloc(object).

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[,,,,,,,,,,], bool) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(T[,,,,,,,,,,] data, bool copy = true) where T : unmanaged
+
+ +

Parameters

+
+
data T[,,,,,,,,,,]
+

The array to create NDArray from.

+
+
copy bool
+

If true then the array will be copied to a newly allocated memory.
+If false then the array will be pinned by calling Alloc(object).

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[,,,,,,,,,], bool) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(T[,,,,,,,,,] data, bool copy = true) where T : unmanaged
+
+ +

Parameters

+
+
data T[,,,,,,,,,]
+

The array to create NDArray from.

+
+
copy bool
+

If true then the array will be copied to a newly allocated memory.
+If false then the array will be pinned by calling Alloc(object).

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[,,,,,,,,], bool) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(T[,,,,,,,,] data, bool copy = true) where T : unmanaged
+
+ +

Parameters

+
+
data T[,,,,,,,,]
+

The array to create NDArray from.

+
+
copy bool
+

If true then the array will be copied to a newly allocated memory.
+If false then the array will be pinned by calling Alloc(object).

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[,,,,,,,], bool) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(T[,,,,,,,] data, bool copy = true) where T : unmanaged
+
+ +

Parameters

+
+
data T[,,,,,,,]
+

The array to create NDArray from.

+
+
copy bool
+

If true then the array will be copied to a newly allocated memory.
+If false then the array will be pinned by calling Alloc(object).

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[,,,,,,], bool) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(T[,,,,,,] data, bool copy = true) where T : unmanaged
+
+ +

Parameters

+
+
data T[,,,,,,]
+

The array to create NDArray from.

+
+
copy bool
+

If true then the array will be copied to a newly allocated memory.
+If false then the array will be pinned by calling Alloc(object).

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[,,,,,], bool) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(T[,,,,,] data, bool copy = true) where T : unmanaged
+
+ +

Parameters

+
+
data T[,,,,,]
+

The array to create NDArray from.

+
+
copy bool
+

If true then the array will be copied to a newly allocated memory.
+If false then the array will be pinned by calling Alloc(object).

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[,,,,], bool) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(T[,,,,] data, bool copy = true) where T : unmanaged
+
+ +

Parameters

+
+
data T[,,,,]
+

The array to create NDArray from.

+
+
copy bool
+

If true then the array will be copied to a newly allocated memory.
+If false then the array will be pinned by calling Alloc(object).

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[,,,], bool) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(T[,,,] data, bool copy = true) where T : unmanaged
+
+ +

Parameters

+
+
data T[,,,]
+

The array to create NDArray from.

+
+
copy bool
+

If true then the array will be copied to a newly allocated memory.
+If false then the array will be pinned by calling Alloc(object).

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[,,], bool) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(T[,,] data, bool copy = true) where T : unmanaged
+
+ +

Parameters

+
+
data T[,,]
+

The array to create NDArray from.

+
+
copy bool
+

If true then the array will be copied to a newly allocated memory.
+If false then the array will be pinned by calling Alloc(object).

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[,], bool) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(T[,] data, bool copy = true) where T : unmanaged
+
+ +

Parameters

+
+
data T[,]
+

The array to create NDArray from.

+
+
copy bool
+

If true then the array will be copied to a newly allocated memory.
+If false then the array will be pinned by calling Alloc(object).

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(params T[]) + +

+ +

Creates a Vector NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(params T[] data) where T : unmanaged
+
+ +

Parameters

+
+
data T[]
+

The array to create NDArray from.

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[], bool) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
public static NDArray array<T>(T[] data, bool copy) where T : unmanaged
+
+ +

Parameters

+
+
data T[]
+

The array to create NDArray from.

+
+
copy bool
+

If true then the array will be copied to a newly allocated memory.
+If false then the array will be pinned by calling Alloc(object).

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[][]) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
[SuppressMessage("ReSharper", "SuggestVarOrType_SimpleTypes")]
+[SuppressMessage("ReSharper", "SuggestVarOrType_Elsewhere")]
+public static NDArray array<T>(T[][] data) where T : unmanaged
+
+ +

Parameters

+
+
data T[][]
+

The array to create NDArray from. Shape is taken from the first item of each array/nested array.

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[][][]) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
[SuppressMessage("ReSharper", "SuggestVarOrType_SimpleTypes")]
+[SuppressMessage("ReSharper", "SuggestVarOrType_Elsewhere")]
+public static NDArray array<T>(T[][][] data) where T : unmanaged
+
+ +

Parameters

+
+
data T[][][]
+

The array to create NDArray from. Shape is taken from the first item of each array/nested array.

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[][][][]) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
[SuppressMessage("ReSharper", "SuggestVarOrType_SimpleTypes")]
+[SuppressMessage("ReSharper", "SuggestVarOrType_Elsewhere")]
+public static NDArray array<T>(T[][][][] data) where T : unmanaged
+
+ +

Parameters

+
+
data T[][][][]
+

The array to create NDArray from. Shape is taken from the first item of each array/nested array.

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ array<T>(T[][][][][]) + +

+ +

Creates an NDArray from given data.

+
+
+ +
+
[SuppressMessage("ReSharper", "SuggestVarOrType_SimpleTypes")]
+[SuppressMessage("ReSharper", "SuggestVarOrType_Elsewhere")]
+public static NDArray array<T>(T[][][][][] data) where T : unmanaged
+
+ +

Parameters

+
+
data T[][][][][]
+

The array to create NDArray from. Shape is taken from the first item of each array/nested array.

+
+
+ +

Returns

+
+
NDArray
+

An NDArray with the data and shape of the given array.

+
+
+ +

Type Parameters

+
+
T
+

The type of given array, must be compliant to numpy's supported dtypes.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ asanyarray(in object, Type) + +

+ +

Convert the input to an ndarray, but pass ndarray subclasses through.

+
+
+ +
+
public static NDArray asanyarray(in object a, Type dtype = null)
+
+ +

Parameters

+
+
a object
+

Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays.

+
+
dtype Type
+

By default, the data-type is inferred from the input data.

+
+
+ +

Returns

+
+
NDArray
+

Array interpretation of a. If a is an ndarray or a subclass of ndarray, it is returned as-is and no copy is performed.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ asarray(string) + +

+ +
+
+ +
+
public static NDArray asarray(string data)
+
+ +

Parameters

+
+
data string
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ asarray(string[], int) + +

+ +
+
+ +
+
public static NDArray asarray(string[] data, int ndim = 1)
+
+ +

Parameters

+
+
data string[]
+
+
ndim int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ asarray<T>(T) + +

+ +
+
+ +
+
public static NDArray asarray<T>(T data) where T : struct
+
+ +

Parameters

+
+
data T
+
+
+ +

Returns

+
+
NDArray
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ asarray<T>(T[], int) + +

+ +
+
+ +
+
public static NDArray asarray<T>(T[] data, int ndim = 1) where T : struct
+
+ +

Parameters

+
+
data T[]
+
+
ndim int
+
+
+ +

Returns

+
+
NDArray
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + + + + + + + +

+ asscalar(NDArray) + +

+ +

Convert an array of size 1 to its scalar equivalent.

+
+
+ +
+
public static ValueType asscalar(NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+

Input NDArray of size 1.

+
+
+ +

Returns

+
+
ValueType
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ asscalar(Array) + +

+ +

Convert an array of size 1 to its scalar equivalent.

+
+
+ +
+
public static ValueType asscalar(Array arr)
+
+ +

Parameters

+
+
arr Array
+

Input array of size 1.

+
+
+ +

Returns

+
+
ValueType
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ asscalar<T>(ArraySlice<T>) + +

+ +

Convert an array of size 1 to its scalar equivalent.

+
+
+ +
+
public static T asscalar<T>(ArraySlice<T> arr) where T : unmanaged
+
+ +

Parameters

+
+
arr ArraySlice<T>
+

Input array of size 1.

+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ asscalar<T>(IArraySlice) + +

+ +

Convert an array of size 1 to its scalar equivalent.

+
+
+ +
+
public static T asscalar<T>(IArraySlice arr) where T : unmanaged
+
+ +

Parameters

+
+
arr IArraySlice
+

Input array of size 1.

+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ asscalar<T>(NDArray) + +

+ +

Convert an array of size 1 to its scalar equivalent.

+
+
+ +
+
public static T asscalar<T>(NDArray nd) where T : unmanaged
+
+ +

Parameters

+
+
nd NDArray
+

Input NDArray of size 1.

+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ asscalar<T>(Array) + +

+ +

Convert an array of size 1 to its scalar equivalent.

+
+
+ +
+
public static T asscalar<T>(Array arr)
+
+ +

Parameters

+
+
arr Array
+

Input array of size 1.

+
+
+ +

Returns

+
+
T
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ atleast_1d(NDArray) + +

+ +

Convert inputs to arrays with at least one dimension. +Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.

+
+
+ +
+
public static NDArray atleast_1d(NDArray arr)
+
+ +

Parameters

+
+
arr NDArray
+
+
+ +

Returns

+
+
NDArray
+

An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ atleast_1d(params NDArray[]) + +

+ +

Convert inputs to arrays with at least one dimension. +Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.

+
+
+ +
+
public static NDArray[] atleast_1d(params NDArray[] arys)
+
+ +

Parameters

+
+
arys NDArray[]
+

One or more input arrays.

+
+
+ +

Returns

+
+
NDArray[]
+

An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ atleast_1d(object) + +

+ +

Convert inputs to arrays with at least one dimension. +Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.

+
+
+ +
+
public static NDArray atleast_1d(object arys)
+
+ +

Parameters

+
+
arys object
+

One or more input arrays.

+
+
+ +

Returns

+
+
NDArray
+

An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ atleast_1d(params object[]) + +

+ +

Convert inputs to arrays with at least one dimension. +Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.

+
+
+ +
+
public static NDArray[] atleast_1d(params object[] arys)
+
+ +

Parameters

+
+
arys object[]
+

One or more input arrays.

+
+
+ +

Returns

+
+
NDArray[]
+

An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ atleast_2d(NDArray) + +

+ +

View inputs as arrays with at least two dimensions.

+
+
+ +
+
public static NDArray atleast_2d(NDArray arr)
+
+ +

Parameters

+
+
arr NDArray
+

One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.

+
+
+ +

Returns

+
+
NDArray
+

An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ atleast_2d(params NDArray[]) + +

+ +

View inputs as arrays with at least two dimensions.

+
+
+ +
+
public static NDArray[] atleast_2d(params NDArray[] arys)
+
+ +

Parameters

+
+
arys NDArray[]
+

One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.

+
+
+ +

Returns

+
+
NDArray[]
+

An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ atleast_2d(object) + +

+ +

View inputs as arrays with at least two dimensions.

+
+
+ +
+
public static NDArray atleast_2d(object arys)
+
+ +

Parameters

+
+
arys object
+

One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.

+
+
+ +

Returns

+
+
NDArray
+

An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ atleast_2d(params object[]) + +

+ +

View inputs as arrays with at least two dimensions.

+
+
+ +
+
public static NDArray[] atleast_2d(params object[] arys)
+
+ +

Parameters

+
+
arys object[]
+

One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.

+
+
+ +

Returns

+
+
NDArray[]
+

An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ atleast_3d(NDArray) + +

+ +

View inputs as arrays with at least three dimensions.

+
+
+ +
+
public static NDArray atleast_3d(NDArray arr)
+
+ +

Parameters

+
+
arr NDArray
+
+
+ +

Returns

+
+
NDArray
+

An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1).

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ atleast_3d(params NDArray[]) + +

+ +

View inputs as arrays with at least three dimensions.

+
+
+ +
+
public static NDArray[] atleast_3d(params NDArray[] arys)
+
+ +

Parameters

+
+
arys NDArray[]
+

One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved.

+
+
+ +

Returns

+
+
NDArray[]
+

An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1).

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ atleast_3d(object) + +

+ +

View inputs as arrays with at least three dimensions.

+
+
+ +
+
public static NDArray atleast_3d(object arys)
+
+ +

Parameters

+
+
arys object
+

One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved.

+
+
+ +

Returns

+
+
NDArray
+

An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1).

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ atleast_3d(params object[]) + +

+ +

View inputs as arrays with at least three dimensions.

+
+
+ +
+
public static NDArray[] atleast_3d(params object[] arys)
+
+ +

Parameters

+
+
arys object[]
+

One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved.

+
+
+ +

Returns

+
+
NDArray[]
+

An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1).

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ broadcast(NDArray, NDArray) + +

+ +

Produce an object that mimics broadcasting.

+
+
+ +
+
public static np.Broadcast broadcast(NDArray nd1, NDArray nd2)
+
+ +

Parameters

+
+
nd1 NDArray
+
+
nd2 NDArray
+
+
+ +

Returns

+
+
np.Broadcast
+

Broadcast the input parameters against one another, and return an object that encapsulates the result. Amongst others, it has shape and nd properties, and may be used as an iterator.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ broadcast_arrays(NDArray, NDArray) + +

+ +

Broadcast two arrays against each other.

+
+
+ +
+
public static (NDArray Lhs, NDArray Rhs) broadcast_arrays(NDArray lhs, NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+

An array to broadcast.

+
+
rhs NDArray
+

An array to broadcast.

+
+
+ +

Returns

+
+
(NDArray Lhs, NDArray Rhs)
+

These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ broadcast_arrays(params NDArray[]) + +

+ +

Broadcast any number of arrays against each other.

+
+
+ +
+
public static NDArray[] broadcast_arrays(params NDArray[] ndArrays)
+
+ +

Parameters

+
+
ndArrays NDArray[]
+

The arrays to broadcast.

+
+
+ +

Returns

+
+
NDArray[]
+

These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ broadcast_to(UnmanagedStorage, UnmanagedStorage) + +

+ +

Broadcast an array to a new shape.

+
+
+ +
+
public static NDArray broadcast_to(UnmanagedStorage from, UnmanagedStorage against)
+
+ +

Parameters

+
+
from UnmanagedStorage
+

The UnmanagedStorage to broadcast.

+
+
against UnmanagedStorage
+

The shape to broadcast against.

+
+
+ +

Returns

+
+
NDArray
+

These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ broadcast_to(UnmanagedStorage, NDArray) + +

+ +

Broadcast an array to a new shape.

+
+
+ +
+
public static NDArray broadcast_to(UnmanagedStorage from, NDArray against)
+
+ +

Parameters

+
+
from UnmanagedStorage
+

The UnmanagedStorage to broadcast.

+
+
against NDArray
+

The shape to broadcast against.

+
+
+ +

Returns

+
+
NDArray
+

These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ broadcast_to(UnmanagedStorage, Shape) + +

+ +

Broadcast an array to a new shape.

+
+
+ +
+
public static NDArray broadcast_to(UnmanagedStorage from, Shape against)
+
+ +

Parameters

+
+
from UnmanagedStorage
+

The NDArray to broadcast.

+
+
against Shape
+

The shape to broadcast against.

+
+
+ +

Returns

+
+
NDArray
+

These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ broadcast_to(NDArray, UnmanagedStorage) + +

+ +

Broadcast an array to a new shape.

+
+
+ +
+
public static NDArray broadcast_to(NDArray from, UnmanagedStorage against)
+
+ +

Parameters

+
+
from NDArray
+

The NDArray to broadcast.

+
+
against UnmanagedStorage
+

The shape to broadcast against.

+
+
+ +

Returns

+
+
NDArray
+

These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ broadcast_to(NDArray, NDArray) + +

+ +

Broadcast an array to a new shape.

+
+
+ +
+
public static NDArray broadcast_to(NDArray from, NDArray against)
+
+ +

Parameters

+
+
from NDArray
+

The NDArray to broadcast.

+
+
against NDArray
+

The shape to broadcast against.

+
+
+ +

Returns

+
+
NDArray
+

These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ broadcast_to(NDArray, Shape) + +

+ +

Broadcast an array to a new shape.

+
+
+ +
+
public static NDArray broadcast_to(NDArray from, Shape against)
+
+ +

Parameters

+
+
from NDArray
+

The NDArray to broadcast.

+
+
against Shape
+

The shape to broadcast against.

+
+
+ +

Returns

+
+
NDArray
+

These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ broadcast_to(Shape, UnmanagedStorage) + +

+ +

Broadcast an shape against an other new shape.

+
+
+ +
+
public static Shape broadcast_to(Shape from, UnmanagedStorage against)
+
+ +

Parameters

+
+
from Shape
+

The shape that is to be broadcasted

+
+
against UnmanagedStorage
+

The shape that'll be used to broadcast from shape

+
+
+ +

Returns

+
+
Shape
+

A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ broadcast_to(Shape, NDArray) + +

+ +

Broadcast an shape against an other new shape.

+
+
+ +
+
public static Shape broadcast_to(Shape from, NDArray against)
+
+ +

Parameters

+
+
from Shape
+

The shape that is to be broadcasted

+
+
against NDArray
+

The shape that'll be used to broadcast from shape

+
+
+ +

Returns

+
+
Shape
+

A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ broadcast_to(Shape, Shape) + +

+ +

Broadcast an shape against an other new shape.

+
+
+ +
+
public static Shape broadcast_to(Shape from, Shape against)
+
+ +

Parameters

+
+
from Shape
+

The shape that is to be broadcasted

+
+
against Shape
+

The shape that'll be used to broadcast from shape

+
+
+ +

Returns

+
+
Shape
+

A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ ceil(in NDArray, NPTypeCode?) + +

+ +

Return the ceiling of the input, element-wise.
+The ceil of the scalar x is the smallest integer i, such that i >= x. It is often denoted as \lceil x \rceil.

+
+
+ +
+
public static NDArray ceil(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Input data.

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The ceiling of each element in x, with float dtype. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ ceil(in NDArray, Type) + +

+ +

Return the ceiling of the input, element-wise.
+The ceil of the scalar x is the smallest integer i, such that i >= x. It is often denoted as \lceil x \rceil.

+
+
+ +
+
public static NDArray ceil(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Input data.

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The ceiling of each element in x, with float dtype. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ clip(in NDArray, NDArray, NDArray, NDArray) + +

+ +

Clip (limit) the values in an array.
+Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1.

+
+
+ +
+
public static NDArray clip(in NDArray a, NDArray a_min, NDArray a_max, NDArray @out)
+
+ +

Parameters

+
+
a NDArray
+

Array containing elements to clip.

+
+
a_min NDArray
+

Minimum value. If None, clipping is not performed on lower interval edge. Not more than one of a_min and a_max may be None.

+
+
a_max NDArray
+

Maximum value. If None, clipping is not performed on upper interval edge. Not more than one of a_min and a_max may be None.

+
+
out NDArray
+

The results will be placed in this array. It may be the input array for in-place clipping. out must be of the right shape to hold the output. Its type is preserved.

+
+
+ +

Returns

+
+
NDArray
+

An array with the elements of a, but where values < a_min are replaced with a_min, and those > a_max with a_max.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ clip(in NDArray, NDArray, NDArray, NPTypeCode?) + +

+ +

Clip (limit) the values in an array.
+Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1.

+
+
+ +
+
public static NDArray clip(in NDArray a, NDArray a_min, NDArray a_max, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
a NDArray
+

Array containing elements to clip.

+
+
a_min NDArray
+

Minimum value. If None, clipping is not performed on lower interval edge. Not more than one of a_min and a_max may be None.

+
+
a_max NDArray
+

Maximum value. If None, clipping is not performed on upper interval edge. Not more than one of a_min and a_max may be None.

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

An array with the elements of a, but where values < a_min are replaced with a_min, and those > a_max with a_max.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ clip(in NDArray, NDArray, NDArray, Type) + +

+ +

Clip (limit) the values in an array.
+Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1.

+
+
+ +
+
public static NDArray clip(in NDArray a, NDArray a_min, NDArray a_max, Type outType)
+
+ +

Parameters

+
+
a NDArray
+

Array containing elements to clip.

+
+
a_min NDArray
+

Minimum value. If None, clipping is not performed on lower interval edge. Not more than one of a_min and a_max may be None.

+
+
a_max NDArray
+

Maximum value. If None, clipping is not performed on upper interval edge. Not more than one of a_min and a_max may be None.

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

An array with the elements of a, but where values < a_min are replaced with a_min, and those > a_max with a_max.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ concatenate(NDArray[], int) + +

+ +

Join a sequence of arrays along an existing axis.

+
+
+ +
+
public static NDArray concatenate(NDArray[] arrays, int axis = 0)
+
+ +

Parameters

+
+
arrays NDArray[]
+

The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

+
+
axis int
+

The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.

+
+
+ +

Returns

+
+
NDArray
+

The concatenated array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int) + +

+ +

Join a sequence of arrays along an existing axis.

+
+
+ +
+
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
+
+ +

Parameters

+
+
arrays (NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray)
+

The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

+
+
axis int
+

The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.

+
+
+ +

Returns

+
+
NDArray
+

The concatenated array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int) + +

+ +

Join a sequence of arrays along an existing axis.

+
+
+ +
+
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
+
+ +

Parameters

+
+
arrays (NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray)
+

The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

+
+
axis int
+

The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.

+
+
+ +

Returns

+
+
NDArray
+

The concatenated array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int) + +

+ +

Join a sequence of arrays along an existing axis.

+
+
+ +
+
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
+
+ +

Parameters

+
+
arrays (NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray)
+

The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

+
+
axis int
+

The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.

+
+
+ +

Returns

+
+
NDArray
+

The concatenated array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int) + +

+ +

Join a sequence of arrays along an existing axis.

+
+
+ +
+
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
+
+ +

Parameters

+
+
arrays (NDArray, NDArray, NDArray, NDArray, NDArray, NDArray)
+

The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

+
+
axis int
+

The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.

+
+
+ +

Returns

+
+
NDArray
+

The concatenated array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ concatenate((NDArray, NDArray, NDArray, NDArray, NDArray), int) + +

+ +

Join a sequence of arrays along an existing axis.

+
+
+ +
+
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
+
+ +

Parameters

+
+
arrays (NDArray, NDArray, NDArray, NDArray, NDArray)
+

The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

+
+
axis int
+

The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.

+
+
+ +

Returns

+
+
NDArray
+

The concatenated array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ concatenate((NDArray, NDArray, NDArray, NDArray), int) + +

+ +

Join a sequence of arrays along an existing axis.

+
+
+ +
+
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
+
+ +

Parameters

+
+
arrays (NDArray, NDArray, NDArray, NDArray)
+

The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

+
+
axis int
+

The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.

+
+
+ +

Returns

+
+
NDArray
+

The concatenated array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ concatenate((NDArray, NDArray, NDArray), int) + +

+ +

Join a sequence of arrays along an existing axis.

+
+
+ +
+
public static NDArray concatenate((NDArray, NDArray, NDArray) arrays, int axis = 0)
+
+ +

Parameters

+
+
arrays (NDArray, NDArray, NDArray)
+

The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

+
+
axis int
+

The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.

+
+
+ +

Returns

+
+
NDArray
+

The concatenated array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ concatenate((NDArray, NDArray), int) + +

+ +

Join a sequence of arrays along an existing axis.

+
+
+ +
+
public static NDArray concatenate((NDArray, NDArray) arrays, int axis = 0)
+
+ +

Parameters

+
+
arrays (NDArray Lhs, NDArray Rhs)
+

The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

+
+
axis int
+

The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.

+
+
+ +

Returns

+
+
NDArray
+

The concatenated array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ convolve(NDArray, NDArray, string) + +

+ +

Returns the discrete, linear convolution of two one-dimensional sequences.

+

The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal[1]. In probability theory, the sum of two independent random variables is distributed according to the convolution of their individual distributions.

+

If v is longer than a, the arrays are swapped before computation.

+
+
+ +
+
public static NDArray convolve(NDArray a, NDArray v, string mode = "full")
+
+ +

Parameters

+
+
a NDArray
+
+
v NDArray
+
+
mode string
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ copy(NDArray, char) + +

+ +

Return a copy of the array.

+
+
+ +
+
public static NDArray copy(NDArray a, char order = 'C')
+
+ +

Parameters

+
+
a NDArray
+

Input data.

+
+
order char
+
+
+ +

Returns

+
+
NDArray
+

Array interpretation of a.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ copyto(NDArray, NDArray) + +

+ +

Copies values from one array to another, broadcasting as necessary.

+
+
+ +
+
public static void copyto(NDArray dst, NDArray src)
+
+ +

Parameters

+
+
dst NDArray
+

The array into which values are copied.

+
+
src NDArray
+

The array from which values are copied.

+
+
+ + + + + + + + +

Remarks

+ + + + + + + +

+ cos(in NDArray, NPTypeCode?) + +

+ +

Cosine element-wise.

+
+
+ +
+
public static NDArray cos(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Input array in radians.

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The sine of each element of x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ cos(in NDArray, Type) + +

+ +

Cosine element-wise.

+
+
+ +
+
public static NDArray cos(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Input array in radians.

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The sine of each element of x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ cosh(in NDArray, NPTypeCode?) + +

+ +

Hyperbolic cosine, element-wise.
+Equivalent to 1/2 * (np.exp(x) + np.exp(-x)) and np.cos(1j* x).

+
+
+ +
+
public static NDArray cosh(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Input array.

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

Output array of same shape as x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ cosh(in NDArray, Type) + +

+ +

Hyperbolic cosine, element-wise.
+Equivalent to 1/2 * (np.exp(x) + np.exp(-x)) and np.cos(1j* x).

+
+
+ +
+
public static NDArray cosh(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Input array.

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

Output array of same shape as x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ cumsum(NDArray, int?, NPTypeCode?) + +

+ +

Return the cumulative sum of the elements along a given axis.

+
+
+ +
+
public static NDArray cumsum(NDArray arr, int? axis = null, NPTypeCode? typeCode = null)
+
+ +

Parameters

+
+
arr NDArray
+

Input array.

+
+
axis int?
+

Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.

+
+
typeCode NPTypeCode?
+

Type of the returned array and of the accumulator in which the elements are summed. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.

+
+
+ +

Returns

+
+
NDArray
+

A new array holding the result is returned unless out is specified, in which case a reference to out is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ divide(in NDArray, in NDArray) + +

+ +
+
+ +
+
public static NDArray divide(in NDArray x1, in NDArray x2)
+
+ +

Parameters

+
+
x1 NDArray
+
+
x2 NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ dot(in NDArray, in NDArray) + +

+ +

Dot product of two arrays. See remarks.

+
+
+ +
+
public static NDArray dot(in NDArray a, in NDArray b)
+
+ +

Parameters

+
+
a NDArray
+

Lhs, First argument.

+
+
b NDArray
+

Rhs, Second argument.

+
+
+ +

Returns

+
+
NDArray
+

Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If out is given, then it is returned.

+
+
+ + + + + + + +

Remarks

+

https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html
+Specifically,
+- If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).
+- If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.
+- If either a or b is 0-D(scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a* b is preferred.
+- If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.
+- If a is an N-D array and b is an M-D array(where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b:
+dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])

+
+ + + + + + +

+ dstack(params NDArray[]) + +

+ +

Stack arrays in sequence depth wise (along third axis). +This is equivalent to concatenation along the third axis after 2-D arrays of shape(M, N) have been reshaped to(M, N,1) and 1-D arrays of shape(N,) have been reshaped to(1, N,1). +Rebuilds arrays divided by dsplit. +This function makes most sense for arrays with up to 3 dimensions.For instance, for pixel-data with a height(first axis), width(second axis), and r/g/b channels(third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations.

+
+
+ +
+
public static NDArray dstack(params NDArray[] tup)
+
+ +

Parameters

+
+
tup NDArray[]
+

The arrays must have the same shape along all but the third axis. 1-D or 2-D arrays must have the same shape.

+
+
+ +

Returns

+
+
NDArray
+

The array formed by stacking the given arrays, will be at least 3-D.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ dtype(string) + +

+ +

Parse a string into a DType.

+
+
+ +
+
public static DType dtype(string dtype)
+
+ +

Parameters

+
+
dtype string
+
+
+ +

Returns

+
+
DType
+

A DType based on dtype, return can be null.

+
+
+ + + + + + + +

Remarks

+

https://docs.scipy.org/doc/numpy-1.16.0/reference/arrays.dtypes.html
+This was created to ease the porting of C++ numpy to C#.

+
+ + + + + + +

+ empty(Shape) + +

+ +

Return a new array of given shape and type, without initializing entries.

+
+
+ +
+
public static NDArray empty(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+

Shape of the empty array, e.g., (2, 3) or 2.

+
+
+ +

Returns

+
+
NDArray
+

Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ empty(Shape, NPTypeCode) + +

+ +

Return a new array of given shape and type, without initializing entries.

+
+
+ +
+
public static NDArray empty(Shape shape, NPTypeCode typeCode)
+
+ +

Parameters

+
+
shape Shape
+

Shape of the empty array, e.g., (2, 3) or 2.

+
+
typeCode NPTypeCode
+

Desired output data-type for the array, e.g, numpy.int8. Default is numpy.float64.

+
+
+ +

Returns

+
+
NDArray
+

Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ empty(Shape, Type) + +

+ +

Return a new array of given shape and type, without initializing entries.

+
+
+ +
+
public static NDArray empty(Shape shape, Type dtype)
+
+ +

Parameters

+
+
shape Shape
+

Shape of the empty array, e.g., (2, 3) or 2.

+
+
dtype Type
+

Desired output data-type for the array, e.g, numpy.int8. Default is numpy.float64.

+
+
+ +

Returns

+
+
NDArray
+

Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ empty(params int[]) + +

+ +

Return a new array of given shape and type, without initializing entries.

+
+
+ +
+
public static NDArray empty(params int[] shapes)
+
+ +

Parameters

+
+
shapes int[]
+

Shape of the empty array, e.g., (2, 3) or 2.

+
+
+ +

Returns

+
+
NDArray
+

Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ empty_like(NDArray, Type) + +

+ +

Return a new array with the same shape and type as a given array.

+
+
+ +
+
public static NDArray empty_like(NDArray prototype, Type dtype = null)
+
+ +

Parameters

+
+
prototype NDArray
+

The shape and data-type of prototype define these same attributes of the returned array.

+
+
dtype Type
+

Overrides the data type of the result.

+
+
+ +

Returns

+
+
NDArray
+

Array of uninitialized (arbitrary) data with the same shape and type as prototype.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ empty<T>(params int[]) + +

+ +

Return a new array of given shape and type, without initializing entries.

+
+
+ +
+
public static NDArray empty<T>(params int[] shapes)
+
+ +

Parameters

+
+
shapes int[]
+

Shape of the empty array, e.g., (2, 3) or 2.

+
+
+ +

Returns

+
+
NDArray
+

Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.

+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ exp(in NDArray) + +

+ +

Base-e exponential, element-wise.

+
+
+ +
+
public static NDArray exp(in NDArray a)
+
+ +

Parameters

+
+
a NDArray
+

Input value.

+
+
+ +

Returns

+
+
NDArray
+

The natural logarithm of x, element-wise. This is a scalar NDArray.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ exp(in NDArray, NPTypeCode) + +

+ +

Base-e exponential, element-wise.

+
+
+ +
+
public static NDArray exp(in NDArray a, NPTypeCode typeCode)
+
+ +

Parameters

+
+
a NDArray
+

Input value.

+
+
typeCode NPTypeCode
+

The dtype of the returned NDArray

+
+
+ +

Returns

+
+
NDArray
+

The natural logarithm of x, element-wise. This is a scalar NDArray.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ exp(in NDArray, Type) + +

+ +

Base-e exponential, element-wise.

+
+
+ +
+
public static NDArray exp(in NDArray a, Type dtype)
+
+ +

Parameters

+
+
a NDArray
+

Input value.

+
+
dtype Type
+

The dtype of the returned NDArray

+
+
+ +

Returns

+
+
NDArray
+

The natural logarithm of x, element-wise. This is a scalar NDArray.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ exp2(in NDArray) + +

+ +

Calculate 2**p for all p in the input array.

+
+
+ +
+
public static NDArray exp2(in NDArray a)
+
+ +

Parameters

+
+
a NDArray
+

Input value.

+
+
+ +

Returns

+
+
NDArray
+

Element-wise 2 to the power x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ exp2(in NDArray, NPTypeCode) + +

+ +

Calculate 2**p for all p in the input array.

+
+
+ +
+
public static NDArray exp2(in NDArray a, NPTypeCode typeCode)
+
+ +

Parameters

+
+
a NDArray
+

Input value.

+
+
typeCode NPTypeCode
+
+
+ +

Returns

+
+
NDArray
+

Element-wise 2 to the power x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ exp2(in NDArray, Type) + +

+ +

Calculate 2**p for all p in the input array.

+
+
+ +
+
public static NDArray exp2(in NDArray a, Type dtype)
+
+ +

Parameters

+
+
a NDArray
+

Input value.

+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+

Element-wise 2 to the power x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ expand_dims(NDArray, int) + +

+ +
+
+ +
+
public static NDArray expand_dims(NDArray a, int axis)
+
+ +

Parameters

+
+
a NDArray
+
+
axis int
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ expm1(in NDArray) + +

+ +

Calculate exp(x) - 1 for all elements in the array.

+
+
+ +
+
public static NDArray expm1(in NDArray a)
+
+ +

Parameters

+
+
a NDArray
+

Input value.

+
+
+ +

Returns

+
+
NDArray
+

Element-wise exponential minus one: out = exp(x) - 1. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ expm1(in NDArray, NPTypeCode) + +

+ +

Calculate exp(x) - 1 for all elements in the array.

+
+
+ +
+
public static NDArray expm1(in NDArray a, NPTypeCode typeCode)
+
+ +

Parameters

+
+
a NDArray
+

Input value.

+
+
typeCode NPTypeCode
+
+
+ +

Returns

+
+
NDArray
+

Element-wise exponential minus one: out = exp(x) - 1. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ expm1(in NDArray, Type) + +

+ +

Calculate exp(x) - 1 for all elements in the array.

+
+
+ +
+
public static NDArray expm1(in NDArray a, Type dtype)
+
+ +

Parameters

+
+
a NDArray
+

Input value.

+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+

Element-wise exponential minus one: out = exp(x) - 1. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ eye(int, int?, int, Type) + +

+ +

Return a 2-D array with ones on the diagonal and zeros elsewhere.

+
+
+ +
+
public static NDArray eye(int N, int? M = null, int k = 0, Type dtype = null)
+
+ +

Parameters

+
+
N int
+

Number of rows in the output.

+
+
M int?
+

Number of columns in the output. If None, defaults to N.

+
+
k int
+

Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal.

+
+
dtype Type
+

Data-type of the returned array.

+
+
+ +

Returns

+
+
NDArray
+

An array where all elements are equal to zero, except for the k-th diagonal, whose values are equal to one.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ find_common_type(NPTypeCode[], NPTypeCode[]) + +

+ +

Determine common type following standard coercion rules.

+
+
+ +
+
public static NPTypeCode find_common_type(NPTypeCode[] array_types, NPTypeCode[] scalar_types)
+
+ +

Parameters

+
+
array_types NPTypeCode[]
+

A list of dtypes or dtype convertible objects representing arrays. Can be null.

+
+
scalar_types NPTypeCode[]
+

A list of dtypes or dtype convertible objects representing scalars.Can be null.

+
+
+ +

Returns

+
+
NPTypeCode
+

The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ find_common_type(NPTypeCode[], Type[]) + +

+ +

Determine common type following standard coercion rules.

+
+
+ +
+
public static NPTypeCode find_common_type(NPTypeCode[] array_types, Type[] scalar_types)
+
+ +

Parameters

+
+
array_types NPTypeCode[]
+

A list of dtypes or dtype convertible objects representing arrays. Can be null.

+
+
scalar_types Type[]
+

A list of dtypes or dtype convertible objects representing scalars.Can be null.

+
+
+ +

Returns

+
+
NPTypeCode
+

The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ find_common_type(params string[]) + +

+ +

Resolves to which type should the output be.

+
+
+ +
+
public static NPTypeCode find_common_type(params string[] involvedTypes)
+
+ +

Parameters

+
+
involvedTypes string[]
+
+
+ +

Returns

+
+
NPTypeCode
+
+
+ + + + + + + + + + + + + +

+ find_common_type(string[], string[]) + +

+ +

Determine common type following standard coercion rules.

+
+
+ +
+
public static NPTypeCode find_common_type(string[] array_types, string[] scalar_types)
+
+ +

Parameters

+
+
array_types string[]
+

A list of dtypes or dtype convertible objects representing arrays. Can be null.

+
+
scalar_types string[]
+

A list of dtypes or dtype convertible objects representing scalars.Can be null.

+
+
+ +

Returns

+
+
NPTypeCode
+

The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ find_common_type(Type[]) + +

+ +

Determine common type following standard coercion rules.

+
+
+ +
+
public static NPTypeCode find_common_type(Type[] array_types)
+
+ +

Parameters

+
+
array_types Type[]
+

A list of dtypes or dtype convertible objects representing arrays. Can be null.

+
+
+ +

Returns

+
+
NPTypeCode
+

The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ find_common_type(Type[], NPTypeCode[]) + +

+ +

Determine common type following standard coercion rules.

+
+
+ +
+
public static NPTypeCode find_common_type(Type[] array_types, NPTypeCode[] scalar_types)
+
+ +

Parameters

+
+
array_types Type[]
+

A list of dtypes or dtype convertible objects representing arrays. Can be null.

+
+
scalar_types NPTypeCode[]
+

A list of dtypes or dtype convertible objects representing scalars.Can be null.

+
+
+ +

Returns

+
+
NPTypeCode
+

The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ find_common_type(Type[], Type[]) + +

+ +

Determine common type following standard coercion rules.

+
+
+ +
+
public static NPTypeCode find_common_type(Type[] array_types, Type[] scalar_types)
+
+ +

Parameters

+
+
array_types Type[]
+

A list of dtypes or dtype convertible objects representing arrays. Can be null.

+
+
scalar_types Type[]
+

A list of dtypes or dtype convertible objects representing scalars.Can be null.

+
+
+ +

Returns

+
+
NPTypeCode
+

The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ floor(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public static NDArray floor(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+
+
outType NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ floor(in NDArray, Type) + +

+ +
+
+ +
+
public static NDArray floor(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+
+
outType Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ fmax(in NDArray, in NDArray, NDArray) + +

+ +

Element-wise maximum of array elements. +Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are ignored when possible.

+
+
+ +
+
public static NDArray fmax(in NDArray x1, in NDArray x2, NDArray @out)
+
+ +

Parameters

+
+
x1 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
x2 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
out NDArray
+
+
+ +

Returns

+
+
NDArray
+

The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

+
+
+ + + + + + + + + + + + + +

+ fmax(in NDArray, in NDArray, NPTypeCode?) + +

+ +

Element-wise maximum of array elements. +Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are ignored when possible.

+
+
+ +
+
public static NDArray fmax(in NDArray x1, in NDArray x2, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x1 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
x2 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
outType NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+

The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

+
+
+ + + + + + + + + + + + + +

+ fmax(in NDArray, in NDArray, Type) + +

+ +

Element-wise maximum of array elements. +Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are ignored when possible.

+
+
+ +
+
public static NDArray fmax(in NDArray x1, in NDArray x2, Type outType)
+
+ +

Parameters

+
+
x1 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
x2 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
outType Type
+
+
+ +

Returns

+
+
NDArray
+

The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

+
+
+ + + + + + + + + + + + + +

+ fmin(in NDArray, in NDArray, NDArray) + +

+ +

Element-wise maximum of array elements. +Compare two arrays and returns a new array containing the element-wise maxima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated.

+
+
+ +
+
public static NDArray fmin(in NDArray x1, in NDArray x2, NDArray @out)
+
+ +

Parameters

+
+
x1 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
x2 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
out NDArray
+
+
+ +

Returns

+
+
NDArray
+

The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

+
+
+ + + + + + + + + + + + + +

+ fmin(in NDArray, in NDArray, NPTypeCode?) + +

+ +

Element-wise maximum of array elements. +Compare two arrays and returns a new array containing the element-wise maxima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated.

+
+
+ +
+
public static NDArray fmin(in NDArray x1, in NDArray x2, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x1 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
x2 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
outType NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+

The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

+
+
+ + + + + + + + + + + + + +

+ fmin(in NDArray, in NDArray, Type) + +

+ +

Element-wise maximum of array elements. +Compare two arrays and returns a new array containing the element-wise maxima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated.

+
+
+ +
+
public static NDArray fmin(in NDArray x1, in NDArray x2, Type outType)
+
+ +

Parameters

+
+
x1 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
x2 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
outType Type
+
+
+ +

Returns

+
+
NDArray
+

The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

+
+
+ + + + + + + + + + + + + +

+ frombuffer(byte[], string) + +

+ +
+
+ +
+
public static NDArray frombuffer(byte[] bytes, string dtype)
+
+ +

Parameters

+
+
bytes byte[]
+
+
dtype string
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ frombuffer(byte[], Type) + +

+ +
+
+ +
+
public static NDArray frombuffer(byte[] bytes, Type dtype)
+
+ +

Parameters

+
+
bytes byte[]
+
+
dtype Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ fromfile(string, NPTypeCode) + +

+ +

Construct an array from data in a text or binary file. +A highly efficient way of reading binary data with a known data-type, as well as parsing simply formatted text files. Data written using the tofile method can be read using this function.

+
+
+ +
+
public static NDArray fromfile(string file, NPTypeCode dtype)
+
+ +

Parameters

+
+
file string
+

filename.

+
+
dtype NPTypeCode
+

Data type of the returned array. For binary files, it is used to determine the size and byte-order of the items in the file.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ fromfile(string, Type) + +

+ +

Construct an array from data in a text or binary file. +A highly efficient way of reading binary data with a known data-type, as well as parsing simply formatted text files. Data written using the tofile method can be read using this function.

+
+
+ +
+
public static NDArray fromfile(string file, Type dtype)
+
+ +

Parameters

+
+
file string
+

filename.

+
+
dtype Type
+

Data type of the returned array. For binary files, it is used to determine the size and byte-order of the items in the file.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ full(Shape, ValueType) + +

+ +

Return a new array of given shape and type, filled with fill_value.

+
+
+ +
+
public static NDArray full(Shape shape, ValueType fill_value)
+
+ +

Parameters

+
+
shape Shape
+

Shape of the empty array, e.g., (2, 3) or 2.

+
+
fill_value ValueType
+

Fill value.

+
+
+ +

Returns

+
+
NDArray
+

Array of fill_value with the given shape, dtype, and order.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ full(Shape, ValueType, NPTypeCode) + +

+ +

Return a new array of given shape and type, filled with fill_value.

+
+
+ +
+
public static NDArray full(Shape shape, ValueType fill_value, NPTypeCode typeCode)
+
+ +

Parameters

+
+
shape Shape
+

Shape of the empty array, e.g., (2, 3) or 2.

+
+
fill_value ValueType
+

Fill value.

+
+
typeCode NPTypeCode
+

The desired data-type for the array The default, null, means np.array(fill_value).dtype.

+
+
+ +

Returns

+
+
NDArray
+

Array of fill_value with the given shape, dtype, and order.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ full(Shape, ValueType, Type) + +

+ +

Return a new array of given shape and type, filled with fill_value.

+
+
+ +
+
public static NDArray full(Shape shape, ValueType fill_value, Type dtype)
+
+ +

Parameters

+
+
shape Shape
+

Shape of the empty array, e.g., (2, 3) or 2.

+
+
fill_value ValueType
+

Fill value.

+
+
dtype Type
+

The desired data-type for the array The default, null, means np.array(fill_value).dtype.

+
+
+ +

Returns

+
+
NDArray
+

Array of fill_value with the given shape, dtype, and order.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ full(ValueType, Shape) + +

+ +

Return a new array of given shape and type, filled with fill_value.

+
+
+ +
+
public static NDArray full(ValueType fill_value, Shape shape)
+
+ +

Parameters

+
+
fill_value ValueType
+

Fill value.

+
+
shape Shape
+

Shape of the empty array, e.g., (2, 3) or 2.

+
+
+ +

Returns

+
+
NDArray
+

Array of fill_value with the given shape, dtype, and order.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ full(ValueType, Shape, NPTypeCode) + +

+ +

Return a new array of given shape and type, filled with fill_value.

+
+
+ +
+
public static NDArray full(ValueType fill_value, Shape shape, NPTypeCode typeCode)
+
+ +

Parameters

+
+
fill_value ValueType
+

Fill value.

+
+
shape Shape
+

Shape of the empty array, e.g., (2, 3) or 2.

+
+
typeCode NPTypeCode
+

The desired data-type for the array The default, null, means np.array(fill_value).dtype.

+
+
+ +

Returns

+
+
NDArray
+

Array of fill_value with the given shape, dtype, and order.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ full(ValueType, Shape, Type) + +

+ +

Return a new array of given shape and type, filled with fill_value.

+
+
+ +
+
public static NDArray full(ValueType fill_value, Shape shape, Type dtype)
+
+ +

Parameters

+
+
fill_value ValueType
+

Fill value.

+
+
shape Shape
+

Shape of the empty array, e.g., (2, 3) or 2.

+
+
dtype Type
+

The desired data-type for the array The default, null, means np.array(fill_value).dtype.

+
+
+ +

Returns

+
+
NDArray
+

Array of fill_value with the given shape, dtype, and order.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ full(ValueType, params int[]) + +

+ +

Return a new array of given shape and type, filled with fill_value.

+
+
+ +
+
public static NDArray full(ValueType fill_value, params int[] shapes)
+
+ +

Parameters

+
+
fill_value ValueType
+

Fill value.

+
+
shapes int[]
+

Shape of the empty array, e.g., (2, 3) or 2.

+
+
+ +

Returns

+
+
NDArray
+

Array of fill_value with the given shape, dtype, and order.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ full_like(NDArray, object, Type) + +

+ +

Return a full array with the same shape and type as a given array.

+
+
+ +
+
public static NDArray full_like(NDArray a, object fill_value, Type dtype = null)
+
+ +

Parameters

+
+
a NDArray
+

The shape and data-type of a define these same attributes of the returned array.

+
+
fill_value object
+

Fill value.

+
+
dtype Type
+

Overrides the data type of the result.

+
+
+ +

Returns

+
+
NDArray
+

Array of fill_value with the same shape and type as a.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ full<T>(ValueType, params int[]) + +

+ +

Return a new array of given shape and type, filled with fill_value.

+
+
+ +
+
public static NDArray full<T>(ValueType fill_value, params int[] shapes) where T : unmanaged
+
+ +

Parameters

+
+
fill_value ValueType
+

Fill value.

+
+
shapes int[]
+

Shape of the empty array, e.g., (2, 3) or 2.

+
+
+ +

Returns

+
+
NDArray
+

Array of fill_value with the given shape, dtype, and order.

+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ hstack(params NDArray[]) + +

+ +

Stack arrays in sequence horizontally (column wise). +This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis.Rebuilds arrays divided by hsplit. +This function makes most sense for arrays with up to 3 dimensions.For instance, for pixel-data with a height(first axis), width(second axis), +and r/g/b channels(third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations.

+
+
+ +
+
public static NDArray hstack(params NDArray[] tup)
+
+ +

Parameters

+
+
tup NDArray[]
+

The arrays must have the same shape along all but the second axis, except 1-D arrays which can be any length.

+
+
+ +

Returns

+
+
NDArray
+

The array formed by stacking the given arrays.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ identity(int, Type) + +

+ +

Return the identity array. The identity array is a square array with ones on the main diagonal.

+
+
+ +
+
public static NDArray identity(int n, Type dtype = null)
+
+ +

Parameters

+
+
n int
+

Number of rows (and columns) in n x n output.

+
+
dtype Type
+

Data-type of the output. Defaults to double.

+
+
+ +

Returns

+
+
NDArray
+

n x n array with its main diagonal set to one, and all other elements 0.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ isclose(NDArray, NDArray, double, double, bool) + +

+ +

Returns a boolean array where two arrays are element-wise equal within a +tolerance. +The tolerance values are positive, typically very small numbers.The
+relative difference (rtol * abs(b)) and the absolute difference +atol are added together to compare against the absolute difference +between a and b. +Warning: The default atol is not appropriate for comparing numbers +that are much smaller than one(see Notes).

+

See also allclose(NDArray, NDArray, double, double, bool)

+

Notes: +For finite values, isclose uses the following equation to test whether +two floating point values are equivalent.

+
absolute(`a` - `b`) less than or equal to (`atol` + `rtol` * absolute(`b`))
+

Unlike the built-in math.isclose, the above equation is not symmetric +in a and b -- it assumes b is the reference value -- so that +isclose(a, b) might be different from isclose(b, a). Furthermore, +the default value of atol is not zero, and is used to determine what +small values should be considered close to zero.The default value is +appropriate for expected values of order unity: if the expected values +are significantly smaller than one, it can result in false positives. +atol should be carefully selected for the use case at hand. A zero value +for atol will result in False if either a or b is zero.

+
+
+ +
+
public static NDArray<bool> isclose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false)
+
+ +

Parameters

+
+
a NDArray
+

Input array to compare with b

+
+
b NDArray
+

Input array to compare with a.

+
+
rtol double
+

The relative tolerance parameter(see Notes)

+
+
atol double
+

The absolute tolerance parameter(see Notes)

+
+
equal_nan bool
+

Whether to compare NaN's as equal. If True, NaN's in a will be +considered equal to NaN's in b in the output array.

+
+
+ +

Returns

+
+
NDArray<bool>
+

Returns a boolean array of where a and b are equal within the +given tolerance.If both a and b are scalars, returns a single +boolean value.

+
+
+ + + + + + + + + + + + + +

+ isfinite(NDArray) + +

+ +

Test element-wise for finiteness (not infinity or not Not a Number).

+
+
+ +
+
public static NDArray<bool> isfinite(NDArray a)
+
+ +

Parameters

+
+
a NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+

The result is returned as a boolean array.

+
+
+ + + + + + + + + + + + + +

+ isnan(NDArray) + +

+ +

Test element-wise for Not a Number.

+
+
+ +
+
public static NDArray<bool> isnan(NDArray a)
+
+ +

Parameters

+
+
a NDArray
+
+
+ +

Returns

+
+
NDArray<bool>
+

The result is returned as a boolean array.

+
+
+ + + + + + + + + + + + + +

+ isscalar(object) + +

+ +

Returns true incase of a number, bool or string. If null, returns false.

+
+
+ +
+
public static bool isscalar(object obj)
+
+ +

Parameters

+
+
obj object
+
+
+ +

Returns

+
+
bool
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ linspace(double, double, int, bool, NPTypeCode) + +

+ +

Return evenly spaced numbers over a specified interval.
+Returns num evenly spaced samples, calculated over the interval[start, stop].
+The endpoint of the interval can optionally be excluded.

+
+
+ +
+
public static NDArray linspace(double start, double stop, int num, bool endpoint = true, NPTypeCode typeCode = NPTypeCode.Double)
+
+ +

Parameters

+
+
start double
+

The starting value of the sequence.

+
+
stop double
+

The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False.

+
+
num int
+

Number of samples to generate. Default is 50. Must be non-negative.

+
+
endpoint bool
+

If True, stop is the last sample. Otherwise, it is not included. Default is True.

+
+
typeCode NPTypeCode
+

The type of the output array. If dtype is not given, infer the data type from the other input arguments.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ linspace(double, double, int, bool, Type) + +

+ +

Return evenly spaced numbers over a specified interval.
+Returns num evenly spaced samples, calculated over the interval[start, stop].
+The endpoint of the interval can optionally be excluded.

+
+
+ +
+
public static NDArray linspace(double start, double stop, int num, bool endpoint, Type dtype)
+
+ +

Parameters

+
+
start double
+

The starting value of the sequence.

+
+
stop double
+

The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False.

+
+
num int
+

Number of samples to generate. Default is 50. Must be non-negative.

+
+
endpoint bool
+

If True, stop is the last sample. Otherwise, it is not included. Default is True.

+
+
dtype Type
+

The type of the output array. If dtype is not given, infer the data type from the other input arguments.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ linspace(float, float, int, bool, NPTypeCode) + +

+ +

Return evenly spaced numbers over a specified interval.
+Returns num evenly spaced samples, calculated over the interval[start, stop].
+The endpoint of the interval can optionally be excluded.

+
+
+ +
+
public static NDArray linspace(float start, float stop, int num, bool endpoint = true, NPTypeCode typeCode = NPTypeCode.Float)
+
+ +

Parameters

+
+
start float
+

The starting value of the sequence.

+
+
stop float
+

The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False.

+
+
num int
+

Number of samples to generate. Default is 50. Must be non-negative.

+
+
endpoint bool
+

If True, stop is the last sample. Otherwise, it is not included. Default is True.

+
+
typeCode NPTypeCode
+

The type of the output array. If dtype is not given, infer the data type from the other input arguments.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ linspace(float, float, int, bool, Type) + +

+ +

Return evenly spaced numbers over a specified interval.
+Returns num evenly spaced samples, calculated over the interval[start, stop].
+The endpoint of the interval can optionally be excluded.

+
+
+ +
+
public static NDArray linspace(float start, float stop, int num, bool endpoint, Type dtype)
+
+ +

Parameters

+
+
start float
+

The starting value of the sequence.

+
+
stop float
+

The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False.

+
+
num int
+

Number of samples to generate. Default is 50. Must be non-negative.

+
+
endpoint bool
+

If True, stop is the last sample. Otherwise, it is not included. Default is True.

+
+
dtype Type
+

The type of the output array. If dtype is not given, infer the data type from the other input arguments.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ load(Stream) + +

+ +
+
+ +
+
public static NDArray load(Stream stream)
+
+ +

Parameters

+
+
stream Stream
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ load(string) + +

+ +
+
+ +
+
public static NDArray load(string path)
+
+ +

Parameters

+
+
path string
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ log(in NDArray) + +

+ +

Natural logarithm, element-wise. +The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x. +The natural logarithm is logarithm in base e.

+
+
+ +
+
public static NDArray log(in NDArray x)
+
+ +

Parameters

+
+
x NDArray
+

Input value.

+
+
+ +

Returns

+
+
NDArray
+

The natural logarithm of x, element-wise. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ log(in NDArray, NPTypeCode?) + +

+ +

Natural logarithm, element-wise. +The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x. +The natural logarithm is logarithm in base e.

+
+
+ +
+
public static NDArray log(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Input value.

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The natural logarithm of x, element-wise. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ log(in NDArray, Type) + +

+ +

Natural logarithm, element-wise. +The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x. +The natural logarithm is logarithm in base e.

+
+
+ +
+
public static NDArray log(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Input value.

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The natural logarithm of x, element-wise. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ log10(in NDArray) + +

+ +

Return the base 10 logarithm of the input array, element-wise.

+
+
+ +
+
public static NDArray log10(in NDArray x)
+
+ +

Parameters

+
+
x NDArray
+

Input value.

+
+
+ +

Returns

+
+
NDArray
+

The logarithm to the base 10 of x, element-wise. NaNs are returned where x is negative. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ log10(in NDArray, NPTypeCode?) + +

+ +

Return the base 10 logarithm of the input array, element-wise.

+
+
+ +
+
public static NDArray log10(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Input value.

+
+
outType NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+

The logarithm to the base 10 of x, element-wise. NaNs are returned where x is negative. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ log10(in NDArray, Type) + +

+ +

Return the base 10 logarithm of the input array, element-wise.

+
+
+ +
+
public static NDArray log10(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Input value.

+
+
outType Type
+
+
+ +

Returns

+
+
NDArray
+

The logarithm to the base 10 of x, element-wise. NaNs are returned where x is negative. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ log1p(in NDArray) + +

+ +

Return the natural logarithm of one plus the input array, element-wise.
+Calculates log(1 + x).

+
+
+ +
+
public static NDArray log1p(in NDArray x)
+
+ +

Parameters

+
+
x NDArray
+

Input value.

+
+
+ +

Returns

+
+
NDArray
+

Natural logarithm of 1 + x, element-wise. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ log1p(in NDArray, NPTypeCode?) + +

+ +

Return the natural logarithm of one plus the input array, element-wise.
+Calculates log(1 + x).

+
+
+ +
+
public static NDArray log1p(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Input value.

+
+
outType NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+

Natural logarithm of 1 + x, element-wise. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ log1p(in NDArray, Type) + +

+ +

Return the natural logarithm of one plus the input array, element-wise.
+Calculates log(1 + x).

+
+
+ +
+
public static NDArray log1p(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Input value.

+
+
outType Type
+
+
+ +

Returns

+
+
NDArray
+

Natural logarithm of 1 + x, element-wise. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ log2(in NDArray) + +

+ +

Base-2 logarithm of x.

+
+
+ +
+
public static NDArray log2(in NDArray x)
+
+ +

Parameters

+
+
x NDArray
+

Input value.

+
+
+ +

Returns

+
+
NDArray
+

Base-2 logarithm of x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ log2(in NDArray, NPTypeCode?) + +

+ +

Base-2 logarithm of x.

+
+
+ +
+
public static NDArray log2(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Input value.

+
+
outType NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+

Base-2 logarithm of x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ log2(in NDArray, Type) + +

+ +

Base-2 logarithm of x.

+
+
+ +
+
public static NDArray log2(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Input value.

+
+
outType Type
+
+
+ +

Returns

+
+
NDArray
+

Base-2 logarithm of x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ matmul(in NDArray, in NDArray) + +

+ +

Matrix product of two arrays.

+
+
+ +
+
public static NDArray matmul(in NDArray x1, in NDArray x2)
+
+ +

Parameters

+
+
x1 NDArray
+

Lhs Input array, scalars not allowed.

+
+
x2 NDArray
+

Rhs Input array, scalars not allowed.

+
+
+ +

Returns

+
+
NDArray
+

The matrix product of the inputs. This is a scalar only when both x1, x2 are 1-d vectors.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ max(NDArray, int?, bool, Type) + +

+ +

Return the maximum of an array or maximum along an axis.

+
+
+ +
+
public static NDArray max(NDArray a, int? axis = null, bool keepdims = false, Type dtype = null)
+
+ +

Parameters

+
+
a NDArray
+
+
axis int?
+

Axis or axes along which to operate.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
dtype Type
+

the type expected as a return, null will remain the same dtype.

+
+
+ +

Returns

+
+
NDArray
+

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ maximum(in NDArray, in NDArray, NDArray) + +

+ +

Element-wise maximum of array elements. +Compare two arrays and returns a new array containing the element-wise maxima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated.

+
+
+ +
+
public static NDArray maximum(in NDArray x1, in NDArray x2, NDArray @out)
+
+ +

Parameters

+
+
x1 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
x2 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
out NDArray
+
+
+ +

Returns

+
+
NDArray
+

The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

+
+
+ + + + + + + + + + + + + +

+ maximum(in NDArray, in NDArray, NPTypeCode?) + +

+ +

Element-wise maximum of array elements. +Compare two arrays and returns a new array containing the element-wise maxima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated.

+
+
+ +
+
public static NDArray maximum(in NDArray x1, in NDArray x2, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x1 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
x2 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
outType NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+

The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

+
+
+ + + + + + + + + + + + + +

+ maximum(in NDArray, in NDArray, Type) + +

+ +

Element-wise maximum of array elements. +Compare two arrays and returns a new array containing the element-wise maxima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated.

+
+
+ +
+
public static NDArray maximum(in NDArray x1, in NDArray x2, Type outType)
+
+ +

Parameters

+
+
x1 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
x2 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
outType Type
+
+
+ +

Returns

+
+
NDArray
+

The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

+
+
+ + + + + + + + + + + + + +

+ mean(in NDArray) + +

+ +

Compute the arithmetic mean along the specified axis. +Returns the average of the array elements. +The average is taken over the flattened array by default, otherwise over the specified axis. +float64 intermediate and return values are used for integer inputs.

+
+
+ +
+
public static NDArray mean(in NDArray a)
+
+ +

Parameters

+
+
a NDArray
+

Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the mean values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ mean(in NDArray, bool) + +

+ +

Compute the arithmetic mean along the specified axis. +Returns the average of the array elements. +The average is taken over the flattened array by default, otherwise over the specified axis. +float64 intermediate and return values are used for integer inputs.

+
+
+ +
+
public static NDArray mean(in NDArray a, bool keepdims)
+
+ +

Parameters

+
+
a NDArray
+

Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. +If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the mean values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ mean(in NDArray, int) + +

+ +

Compute the arithmetic mean along the specified axis. +Returns the average of the array elements. +The average is taken over the flattened array by default, otherwise over the specified axis. +float64 intermediate and return values are used for integer inputs.

+
+
+ +
+
public static NDArray mean(in NDArray a, int axis)
+
+ +

Parameters

+
+
a NDArray
+

Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

+
+
axis int
+

Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the mean values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ mean(in NDArray, int, NPTypeCode, bool) + +

+ +

Compute the arithmetic mean along the specified axis. +Returns the average of the array elements. +The average is taken over the flattened array by default, otherwise over the specified axis. +float64 intermediate and return values are used for integer inputs.

+
+
+ +
+
public static NDArray mean(in NDArray a, int axis, NPTypeCode type, bool keepdims = false)
+
+ +

Parameters

+
+
a NDArray
+

Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

+
+
axis int
+

Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

+
+
type NPTypeCode
+

Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. +If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the mean values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ mean(in NDArray, int, bool) + +

+ +

Compute the arithmetic mean along the specified axis. +Returns the average of the array elements. +The average is taken over the flattened array by default, otherwise over the specified axis. +float64 intermediate and return values are used for integer inputs.

+
+
+ +
+
public static NDArray mean(in NDArray a, int axis, bool keepdims)
+
+ +

Parameters

+
+
a NDArray
+

Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

+
+
axis int
+

Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. +If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the mean values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + + + + + + + +

+ mean(in NDArray, int, Type, bool) + +

+ +

Compute the arithmetic mean along the specified axis. +Returns the average of the array elements. +The average is taken over the flattened array by default, otherwise over the specified axis. +float64 intermediate and return values are used for integer inputs.

+
+
+ +
+
public static NDArray mean(in NDArray a, int axis, Type dtype, bool keepdims = false)
+
+ +

Parameters

+
+
a NDArray
+

Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

+
+
axis int
+

Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

+
+
dtype Type
+

Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. +If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the mean values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ meshgrid(NDArray, NDArray, Kwargs) + +

+ +

Return coordinate matrices from coordinate vectors. +Make N-D coordinate arrays for vectorized evaluations of +N-D scalar/vector fields over N-D grids, given +one-dimensional coordinate arrays x1, x2,..., xn. +.. versionchanged:: 1.9 +1-D and 0-D cases are allowed.

+
+
+ +
+
public static (NDArray, NDArray) meshgrid(NDArray x1, NDArray x2, Kwargs kwargs = null)
+
+ +

Parameters

+
+
x1 NDArray
+

1-D arrays representing the coordinates of a grid

+
+
x2 NDArray
+

1-D arrays representing the coordinates of a grid

+
+
kwargs Kwargs
+
+
+ +

Returns

+
+
(NDArray Lhs, NDArray Rhs)
+
+
+ + + + + + + + + + + + + +

+ mgrid(NDArray, NDArray) + +

+ +

nd_grid instance which returns a dense multi-dimensional “meshgrid”. +An instance of numpy.lib.index_tricks.nd_grid which returns an dense (or fleshed out) mesh-grid when indexed, so that each returned argument has the same shape. +The dimensions and number of the output arrays are equal to the number of indexing dimensions.If the step length is not a complex number, then the stop is not inclusive.

+
+
+ +
+
public static (NDArray, NDArray) mgrid(NDArray lhs, NDArray rhs)
+
+ +

Parameters

+
+
lhs NDArray
+
+
rhs NDArray
+
+
+ +

Returns

+
+
(NDArray Lhs, NDArray Rhs)
+

mesh-grid ndarrays all of the same dimensions

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ min(in NDArray, int?, bool, Type) + +

+ +

Return the minimum of an array or minimum along an axis.

+
+
+ +
+
public static NDArray min(in NDArray a, int? axis = null, bool keepdims = false, Type dtype = null)
+
+ +

Parameters

+
+
a NDArray
+

Input data.

+
+
axis int?
+

Axis or axes along which to operate.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
dtype Type
+

the type expected as a return, null will remain the same dtype.

+
+
+ +

Returns

+
+
NDArray
+

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ minimum(in NDArray, in NDArray, NDArray) + +

+ +

Element-wise minimum of array elements. +Compare two arrays and returns a new array containing the element-wise minima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated.

+
+
+ +
+
public static NDArray minimum(in NDArray x1, in NDArray x2, NDArray @out)
+
+ +

Parameters

+
+
x1 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
x2 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
out NDArray
+
+
+ +

Returns

+
+
NDArray
+

The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

+
+
+ + + + + + + + + + + + + +

+ minimum(in NDArray, in NDArray, NPTypeCode?) + +

+ +

Element-wise minimum of array elements. +Compare two arrays and returns a new array containing the element-wise minima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated.

+
+
+ +
+
public static NDArray minimum(in NDArray x1, in NDArray x2, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x1 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
x2 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
outType NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+

The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

+
+
+ + + + + + + + + + + + + +

+ minimum(in NDArray, in NDArray, Type) + +

+ +

Element-wise minimum of array elements. +Compare two arrays and returns a new array containing the element-wise minima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated.

+
+
+ +
+
public static NDArray minimum(in NDArray x1, in NDArray x2, Type outType)
+
+ +

Parameters

+
+
x1 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
x2 NDArray
+

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

+
+
outType Type
+
+
+ +

Returns

+
+
NDArray
+

The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

+
+
+ + + + + + + + + + + + + +

+ mintypecode(char[], string, char) + +

+ +

Return the character for the minimum-size type to which given types can be safely cast. +The returned type character must represent the smallest size dtype such that an array of the returned type can handle the data from an array of all types in typechars(or if typechars is an array, then its dtype.char).

+
+
+ +
+
public static char mintypecode(char[] typechars, string typeset = "GDFgdf", char @default = 'd')
+
+ +

Parameters

+
+
typechars char[]
+
+
typeset string
+

The set of characters that the returned character is chosen from. The default set is ‘GDFgdf’.

+
+
default char
+

The default character, this is returned if none of the characters in typechars matches a character in typeset.

+
+
+ +

Returns

+
+
char
+

The character representing the minimum-size type that was found.

+
+
+ + + + + + + + + + + + + +

+ mintypecode(string, string, char) + +

+ +

Return the character for the minimum-size type to which given types can be safely cast. +The returned type character must represent the smallest size dtype such that an array of the returned type can handle the data from an array of all types in typechars(or if typechars is an array, then its dtype.char).

+
+
+ +
+
public static char mintypecode(string typechars, string typeset = "GDFgdf", char @default = 'd')
+
+ +

Parameters

+
+
typechars string
+

every character represents a type. see char

+
+
typeset string
+

The set of characters that the returned character is chosen from. The default set is ‘GDFgdf’.

+
+
default char
+

The default character, this is returned if none of the characters in typechars matches a character in typeset.

+
+
+ +

Returns

+
+
char
+

The character representing the minimum-size type that was found.

+
+
+ + + + + + + + + + + + + +

+ mod(in NDArray, in NDArray) + +

+ +
+
+ +
+
public static NDArray mod(in NDArray x1, in NDArray x2)
+
+ +

Parameters

+
+
x1 NDArray
+
+
x2 NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ mod(in NDArray, in float) + +

+ +
+
+ +
+
public static NDArray mod(in NDArray x1, in float x2)
+
+ +

Parameters

+
+
x1 NDArray
+
+
x2 float
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ modf(in NDArray, NPTypeCode?) + +

+ +

Return the fractional and integral parts of an array, element-wise. +The fractional and integral parts are negative if the given number is negative.

+
+
+ +
+
public static (NDArray Fractional, NDArray Intergral) modf(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Input array.

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
(NDArray Lhs, NDArray Rhs)
+

Fractional part of x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ modf(in NDArray, Type) + +

+ +

Return the fractional and integral parts of an array, element-wise. +The fractional and integral parts are negative if the given number is negative.

+
+
+ +
+
public static (NDArray Fractional, NDArray Intergral) modf(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Input array.

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
(NDArray Lhs, NDArray Rhs)
+

Fractional part of x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ moveaxis(in NDArray, int, int) + +

+ +

Move axes of an array to new positions. +Other axes remain in their original order.

+
+
+ +
+
public static NDArray moveaxis(in NDArray a, int source, int destination)
+
+ +

Parameters

+
+
a NDArray
+

The array whose axes should be reordered.

+
+
source int
+

Original positions of the axes to move. These must be unique (distinct).

+
+
destination int
+

Destination positions for each of the original axes. These must also be unique (distinct).

+
+
+ +

Returns

+
+
NDArray
+

Array with moved axes.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ moveaxis(in NDArray, int, int[]) + +

+ +

Move axes of an array to new positions. +Other axes remain in their original order.

+
+
+ +
+
public static NDArray moveaxis(in NDArray a, int source, int[] destination)
+
+ +

Parameters

+
+
a NDArray
+

The array whose axes should be reordered.

+
+
source int
+

Original positions of the axes to move. These must be unique (distinct).

+
+
destination int[]
+

Destination positions for each of the original axes. These must also be unique (distinct).

+
+
+ +

Returns

+
+
NDArray
+

Array with moved axes.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ moveaxis(in NDArray, int[], int) + +

+ +

Move axes of an array to new positions. +Other axes remain in their original order.

+
+
+ +
+
public static NDArray moveaxis(in NDArray a, int[] source, int destination)
+
+ +

Parameters

+
+
a NDArray
+

The array whose axes should be reordered.

+
+
source int[]
+

Original positions of the axes to move. These must be unique (distinct).

+
+
destination int
+

Destination positions for each of the original axes. These must also be unique (distinct).

+
+
+ +

Returns

+
+
NDArray
+

Array with moved axes.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ moveaxis(in NDArray, int[], int[]) + +

+ +

Move axes of an array to new positions. +Other axes remain in their original order.

+
+
+ +
+
public static NDArray moveaxis(in NDArray a, int[] source, int[] destination)
+
+ +

Parameters

+
+
a NDArray
+

The array whose axes should be reordered.

+
+
source int[]
+

Original positions of the axes to move. These must be unique (distinct).

+
+
destination int[]
+

Destination positions for each of the original axes. These must also be unique (distinct).

+
+
+ +

Returns

+
+
NDArray
+

Array with moved axes.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ multiply(in NDArray, in NDArray) + +

+ +
+
+ +
+
public static NDArray multiply(in NDArray x1, in NDArray x2)
+
+ +

Parameters

+
+
x1 NDArray
+
+
x2 NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ ndarray(Shape, Type, Array, char) + +

+ +
+
+ +
+
public static NDArray ndarray(Shape shape, Type dtype = null, Array buffer = null, char order = 'F')
+
+ +

Parameters

+
+
shape Shape
+
+
dtype Type
+
+
buffer Array
+
+
order char
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ negative(in NDArray) + +

+ +

Numerical negative, element-wise.

+
+
+ +
+
public static NDArray negative(in NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ nonzero(in NDArray) + +

+ +

Return the indices of the elements that are non-zero. +Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension.The values in a are always tested and returned in row-major, C-style order. +To group the indices by element, rather than dimension, use argwhere, which returns a row for each non-zero element.

+
+
+ +
+
public static NDArray<int>[] nonzero(in NDArray a)
+
+ +

Parameters

+
+
a NDArray
+

Input array.

+
+
+ +

Returns

+
+
NDArray<int>[]
+

Indices of elements that are non-zero.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ ones(Shape) + +

+ +

Return a new array of given shape and type, filled with ones.

+
+
+ +
+
public static NDArray ones(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+

Shape of the new array.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ ones(Shape, NPTypeCode) + +

+ +

Return a new array of given shape and type, filled with ones.

+
+
+ +
+
public static NDArray ones(Shape shape, NPTypeCode typeCode)
+
+ +

Parameters

+
+
shape Shape
+

Shape of the new array.

+
+
typeCode NPTypeCode
+

The desired data-type for the array, e.g., uint8. Default is float64 / double.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ ones(Shape, Type) + +

+ +

Return a new array of given shape and type, filled with ones.

+
+
+ +
+
public static NDArray ones(Shape shape, Type dtype)
+
+ +

Parameters

+
+
shape Shape
+

Shape of the new array.

+
+
dtype Type
+

The desired data-type for the array, e.g., uint8. Default is float64 / double.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ ones(params int[]) + +

+ +

Return a new array of given shape and type, filled with ones.

+
+
+ +
+
public static NDArray ones(params int[] shapes)
+
+ +

Parameters

+
+
shapes int[]
+

Shape of the new array.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ ones(Type, params int[]) + +

+ +

Return a new array of given shape and type, filled with ones.

+
+
+ +
+
public static NDArray ones(Type dtype = null, params int[] shapes)
+
+ +

Parameters

+
+
dtype Type
+

The desired data-type for the array, e.g., uint8. Default is float64 / double.

+
+
shapes int[]
+

Shape of the new array.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ ones_like(NDArray, Type) + +

+ +

Return an array of ones with the same shape and type as a given array.

+
+
+ +
+
public static NDArray ones_like(NDArray a, Type dtype = null)
+
+ +

Parameters

+
+
a NDArray
+

Array of ones with the same shape and type as a.

+
+
dtype Type
+

Overrides the data type of the result.

+
+
+ +

Returns

+
+
NDArray
+

Array of zeros with the same shape and type as nd.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ ones<T>(params int[]) + +

+ +

Return a new array of given shape and type, filled with ones.

+
+
+ +
+
public static NDArray ones<T>(params int[] shapes) where T : unmanaged
+
+ +

Parameters

+
+
shapes int[]
+

Shape of the new array.

+
+
+ +

Returns

+
+
NDArray
+
+
+ +

Type Parameters

+
+
T
+

The desired data-type for the array, e.g., uint8. Default is float64 / double.

+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ outer(in NDArray, in NDArray) + +

+ +

Compute the outer product of two vectors. +Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product[R60] is:

+
+
+ +
+
public static NDArray outer(in NDArray a, in NDArray b)
+
+ +

Parameters

+
+
a NDArray
+

First input vector. Input is flattened if not already 1-dimensional.

+
+
b NDArray
+

Second input vector. Input is flattened if not already 1-dimensional.

+
+
+ +

Returns

+
+
NDArray
+

out[i, j] = a[i] * b[j]

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ positive(in NDArray) + +

+ +

Numerical positive, element-wise.

+
+
+ +
+
public static NDArray positive(in NDArray nd)
+
+ +

Parameters

+
+
nd NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ power(in NDArray, in ValueType) + +

+ +

First array elements raised to powers from second array, element-wise.

+
+
+ +
+
public static NDArray power(in NDArray x1, in ValueType x2)
+
+ +

Parameters

+
+
x1 NDArray
+

The bases.

+
+
x2 ValueType
+

The exponents.

+
+
+ +

Returns

+
+
NDArray
+

The bases in x1 raised to the exponents in x2. This is a scalar NDArray if both x1 and x2 are scalars.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ power(in NDArray, in ValueType, NPTypeCode) + +

+ +

First array elements raised to powers from second array, element-wise.

+
+
+ +
+
public static NDArray power(in NDArray x1, in ValueType x2, NPTypeCode typeCode)
+
+ +

Parameters

+
+
x1 NDArray
+

The bases.

+
+
x2 ValueType
+

The exponents.

+
+
typeCode NPTypeCode
+

The dtype of the returned NDArray

+
+
+ +

Returns

+
+
NDArray
+

The bases in x1 raised to the exponents in x2. This is a scalar NDArray if both x1 and x2 are scalars.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ power(in NDArray, in ValueType, Type) + +

+ +

First array elements raised to powers from second array, element-wise.

+
+
+ +
+
public static NDArray power(in NDArray x1, in ValueType x2, Type dtype)
+
+ +

Parameters

+
+
x1 NDArray
+

The bases.

+
+
x2 ValueType
+

The exponents.

+
+
dtype Type
+

The dtype of the returned NDArray

+
+
+ +

Returns

+
+
NDArray
+

The bases in x1 raised to the exponents in x2. This is a scalar NDArray if both x1 and x2 are scalars.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ prod(in NDArray, int?, Type, bool) + +

+ +

Return the product of array elements over a given axis.

+
+
+ +
+
public static NDArray prod(in NDArray a, int? axis = null, Type dtype = null, bool keepdims = false)
+
+ +

Parameters

+
+
a NDArray
+

Input data.

+
+
axis int?
+

Axis or axes along which a product is performed. The default, axis=None, will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis.

+
+
dtype Type
+

The type of the returned array, as well as of the accumulator in which the elements are multiplied. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
+ +

Returns

+
+
NDArray
+

An array shaped as a but with the specified axis removed.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ ravel(NDArray) + +

+ +

Return a contiguous flattened array. A 1-D array, containing the elements of the input, is returned

+
+
+ +
+
public static NDArray ravel(NDArray a)
+
+ +

Parameters

+
+
a NDArray
+

Input array. The elements in a are read in the order specified by order, and packed as a 1-D array.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ repeat(NDArray, int) + +

+ +

Repeat elements of an array.

+
+
+ +
+
public static NDArray repeat(NDArray a, int repeats)
+
+ +

Parameters

+
+
a NDArray
+

Input array.

+
+
repeats int
+

The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ repeat<T>(T, int) + +

+ +

Repeat a scalar.

+
+
+ +
+
public static NDArray repeat<T>(T a, int repeats) where T : unmanaged
+
+ +

Parameters

+
+
a T
+

Input scalar.

+
+
repeats int
+

The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.

+
+
+ +

Returns

+
+
NDArray
+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+ + + + + + + +

+ reshape(NDArray, Shape) + +

+ +

Gives a new shape to an array without changing its data.

+
+
+ +
+
public static NDArray reshape(NDArray nd, Shape shape)
+
+ +

Parameters

+
+
nd NDArray
+

Array to be reshaped.

+
+
shape Shape
+

The new shape should be compatible with the original shape.

+
+
+ +

Returns

+
+
NDArray
+

original nd reshaped without copying.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ reshape(NDArray, ref Shape) + +

+ +

Gives a new shape to an array without changing its data.

+
+
+ +
+
public static NDArray reshape(NDArray nd, ref Shape shape)
+
+ +

Parameters

+
+
nd NDArray
+

Array to be reshaped.

+
+
shape Shape
+

The new shape should be compatible with the original shape.

+
+
+ +

Returns

+
+
NDArray
+

original nd reshaped without copying.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ reshape(NDArray, params int[]) + +

+ +

Gives a new shape to an array without changing its data.

+
+
+ +
+
public static NDArray reshape(NDArray nd, params int[] shape)
+
+ +

Parameters

+
+
nd NDArray
+

Array to be reshaped.

+
+
shape int[]
+

The new shape should be compatible with the original shape.

+
+
+ +

Returns

+
+
NDArray
+

original nd reshaped without copying.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ roll(NDArray, int, int) + +

+ +

Roll array elements along a given axis.

+

Elements that roll beyond the last position are re-introduced at the first.

+
+
+ +
+
public static int roll(NDArray nd, int shift, int axis = -1)
+
+ +

Parameters

+
+
nd NDArray
+
+
shift int
+
+
axis int
+
+
+ +

Returns

+
+
int
+
+
+ + + + + + + + + + + + + +

+ rollaxis(in NDArray, int, int) + +

+ +

Roll the specified axis backwards, until it lies in a given position.
+This function continues to be supported for backward compatibility, but you should prefer moveaxis. The moveaxis function was added in NumPy 1.11.

+
+
+ +
+
public static NDArray rollaxis(in NDArray a, int axis, int start = 0)
+
+ +

Parameters

+
+
a NDArray
+

Input array.

+
+
axis int
+

The axis to roll backwards. The positions of the other axes do not change relative to one another.

+
+
start int
+

The axis is rolled until it lies before this position. The default, 0, results in a “complete” roll.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ round_(in NDArray, int, NPTypeCode?) + +

+ +

Evenly round to the given number of decimals.

+
+
+ +
+
public static NDArray round_(in NDArray x, int decimals, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Input array

+
+
decimals int
+

Number of decimal places to round to

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. +The real and imaginary parts of complex numbers are rounded separately.The result of rounding a float is a float.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ round_(in NDArray, int, Type) + +

+ +

Evenly round to the given number of decimals.

+
+
+ +
+
public static NDArray round_(in NDArray x, int decimals, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Input array

+
+
decimals int
+

Number of decimal places to round to

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. +The real and imaginary parts of complex numbers are rounded separately.The result of rounding a float is a float.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ round_(in NDArray, NPTypeCode?) + +

+ +

Evenly round to the given number of decimals.

+
+
+ +
+
public static NDArray round_(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Input array

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. +The real and imaginary parts of complex numbers are rounded separately.The result of rounding a float is a float.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ round_(in NDArray, Type) + +

+ +

Evenly round to the given number of decimals.

+
+
+ +
+
public static NDArray round_(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Input array

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. +The real and imaginary parts of complex numbers are rounded separately.The result of rounding a float is a float.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ save(string, NDArray) + +

+ +
+
+ +
+
public static void save(string filepath, NDArray arr)
+
+ +

Parameters

+
+
filepath string
+
+
arr NDArray
+
+
+ + + + + + + + + + + + + + +

+ save(string, Array) + +

+ +
+
+ +
+
public static void save(string filepath, Array arr)
+
+ +

Parameters

+
+
filepath string
+
+
arr Array
+
+
+ + + + + + + + + + + + + + +

+ searchsorted(NDArray, NDArray) + +

+ +

Find indices where elements should be inserted to maintain order.

+

Find the indices into a sorted array a such that, if the corresponding elements in v were inserted before the indices, the order of a would be preserved.

+
+
+ +
+
public static NDArray searchsorted(NDArray a, NDArray v)
+
+ +

Parameters

+
+
a NDArray
+

Input array. Must be sorted in ascending order.

+
+
v NDArray
+

Values to insert into a.

+
+
+ +

Returns

+
+
NDArray
+

Array of insertion points with the same shape as v.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sign(in NDArray, NPTypeCode?) + +

+ +
+
+ +
+
public static NDArray sign(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+
+
outType NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ sign(in NDArray, Type) + +

+ +
+
+ +
+
public static NDArray sign(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+
+
outType Type
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + + + + + + + +

+ sin(in NDArray, NPTypeCode?) + +

+ +

Trigonometric sine, element-wise.

+
+
+ +
+
public static NDArray sin(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Angle, in radians (2 \pi rad equals 360 degrees).

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The sine of each element of x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sin(in NDArray, Type) + +

+ +

Trigonometric sine, element-wise.

+
+
+ +
+
public static NDArray sin(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Angle, in radians (2 \pi rad equals 360 degrees).

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The sine of each element of x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sinh(in NDArray, NPTypeCode?) + +

+ +

Hyperbolic sine, element-wise.
+Equivalent to 1/2 * (np.exp(x) - np.exp(-x)) or -1j * np.sin(1j*x).

+
+
+ +
+
public static NDArray sinh(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Input array.

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The sine of each element of x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sinh(in NDArray, Type) + +

+ +

Hyperbolic sine, element-wise.
+Equivalent to 1/2 * (np.exp(x) - np.exp(-x)) or -1j * np.sin(1j*x).

+
+
+ +
+
public static NDArray sinh(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Input array.

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The sine of each element of x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ size(NDArray, int?) + +

+ +

Return the number of elements along a given axis.

+
+
+ +
+
public static int size(NDArray a, int? axis = null)
+
+ +

Parameters

+
+
a NDArray
+

Input data.

+
+
axis int?
+

Axis along which the elements are counted. By default, give the total number of elements.

+
+
+ +

Returns

+
+
int
+

Number of elements along the specified axis.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sqrt(in NDArray, NPTypeCode?) + +

+ +

Return the non-negative square-root of an array, element-wise.

+
+
+ +
+
public static NDArray sqrt(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

The values whose square-roots are required.

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

An array of the same shape as x, containing the positive square-root of each element in x. If any element in x is complex, a complex array is returned (and the square-roots of negative reals are calculated). If all of the elements in x are real, so is y, with negative elements returning nan. If out was provided, y is a reference to it. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sqrt(in NDArray, Type) + +

+ +

Return the non-negative square-root of an array, element-wise.

+
+
+ +
+
public static NDArray sqrt(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

The values whose square-roots are required.

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

An array of the same shape as x, containing the positive square-root of each element in x. If any element in x is complex, a complex array is returned (and the square-roots of negative reals are calculated). If all of the elements in x are real, so is y, with negative elements returning nan. If out was provided, y is a reference to it. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ square(in NDArray) + +

+ +

Return the element-wise square of the input.

+
+
+ +
+
public static NDArray square(in NDArray x)
+
+ +

Parameters

+
+
x NDArray
+

Input data.

+
+
+ +

Returns

+
+
NDArray
+

Element-wise x*x, of the same shape and dtype as x. Returns scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ squeeze(NDArray) + +

+ +

Remove single-dimensional entries from the shape of an array.

+
+
+ +
+
public static NDArray squeeze(NDArray a)
+
+ +

Parameters

+
+
a NDArray
+

Input data.

+
+
+ +

Returns

+
+
NDArray
+

The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into a.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ squeeze(NDArray, int) + +

+ +

Remove single-dimensional entries from the shape of an array.

+
+
+ +
+
public static NDArray squeeze(NDArray a, int axis)
+
+ +

Parameters

+
+
a NDArray
+

Input data.

+
+
axis int
+

Selects a subset of the single-dimensional entries in the shape. If an axis is selected with shape entry greater than one, an error is raised.

+
+
+ +

Returns

+
+
NDArray
+

The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into a.

+
+
+ + + + + + + +

Remarks

+ + +

Exceptions

+
+
IncorrectShapeException
+

If axis is not None, and an axis being squeezed is not of length 1

+
+
+ + + + + +

+ squeeze(Shape) + +

+ +

Remove single-dimensional entries from a shape.

+
+
+ +
+
public static Shape squeeze(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+

Input shape.

+
+
+ +

Returns

+
+
Shape
+

The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into a.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ stack(NDArray[], int) + +

+ +

Join a sequence of arrays along a new axis. +The axis parameter specifies the index of the new axis in the dimensions of the result. +For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension.

+
+
+ +
+
public static NDArray stack(NDArray[] arrays, int axis = 0)
+
+ +

Parameters

+
+
arrays NDArray[]
+

Each array must have the same shape.

+
+
axis int
+

The axis in the result array along which the input arrays are stacked.

+
+
+ +

Returns

+
+
NDArray
+

The stacked array has one more dimension than the input arrays.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ std(NDArray, bool, int?, NPTypeCode?) + +

+ +

Compute the standard deviation along the specified axis. +Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public static NDArray std(NDArray a, bool keepdims = false, int? ddof = null, NPTypeCode? dtype = null)
+
+ +

Parameters

+
+
a NDArray
+

Calculate the standard deviation of these values.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
dtype NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the std values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ std(NDArray, int, bool, int?, NPTypeCode?) + +

+ +

Compute the standard deviation along the specified axis. +Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public static NDArray std(NDArray a, int axis, bool keepdims = false, int? ddof = null, NPTypeCode? dtype = null)
+
+ +

Parameters

+
+
a NDArray
+

Calculate the standard deviation of these values.

+
+
axis int
+

Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
dtype NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the std values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ std(in NDArray, bool, int?) + +

+ +

Compute the standard deviation along the specified axis. +Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public static NDArray std(in NDArray a, bool keepdims, int? ddof = null)
+
+ +

Parameters

+
+
a NDArray
+

Calculate the standard deviation of these values.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the std values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ std(in NDArray, int, NPTypeCode, bool, int?) + +

+ +

Compute the standard deviation along the specified axis. +Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public static NDArray std(in NDArray a, int axis, NPTypeCode type, bool keepdims = false, int? ddof = null)
+
+ +

Parameters

+
+
a NDArray
+

Calculate the standard deviation of these values.

+
+
axis int
+

Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.

+
+
type NPTypeCode
+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the std values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ std(in NDArray, int, bool, int?) + +

+ +

Compute the standard deviation along the specified axis. +Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public static NDArray std(in NDArray a, int axis, bool keepdims, int? ddof = null)
+
+ +

Parameters

+
+
a NDArray
+

Calculate the standard deviation of these values.

+
+
axis int
+

Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the std values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ std(in NDArray, int, int?) + +

+ +

Compute the standard deviation along the specified axis. +Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public static NDArray std(in NDArray a, int axis, int? ddof = null)
+
+ +

Parameters

+
+
a NDArray
+

Calculate the standard deviation of these values.

+
+
axis int
+

Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the std values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ std(in NDArray, int, Type, bool, int?) + +

+ +

Compute the standard deviation along the specified axis. +Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public static NDArray std(in NDArray a, int axis, Type dtype, bool keepdims = false, int? ddof = null)
+
+ +

Parameters

+
+
a NDArray
+

Calculate the standard deviation of these values.

+
+
axis int
+

Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.

+
+
dtype Type
+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the std values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ std(in NDArray, int?) + +

+ +

Compute the standard deviation along the specified axis. +Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public static NDArray std(in NDArray a, int? ddof = null)
+
+ +

Parameters

+
+
a NDArray
+

Calculate the standard deviation of these values.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the std values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ subtract(in NDArray, in NDArray) + +

+ +
+
+ +
+
public static NDArray subtract(in NDArray x1, in NDArray x2)
+
+ +

Parameters

+
+
x1 NDArray
+
+
x2 NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sum(in NDArray) + +

+ +

Sum of array elements over a given axis.

+
+
+ +
+
public static NDArray sum(in NDArray a)
+
+ +

Parameters

+
+
a NDArray
+

Elements to sum.

+
+
+ +

Returns

+
+
NDArray
+

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sum(in NDArray, bool) + +

+ +

Sum of array elements over a given axis.

+
+
+ +
+
public static NDArray sum(in NDArray a, bool keepdims)
+
+ +

Parameters

+
+
a NDArray
+

Elements to sum.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

+
+
+ +

Returns

+
+
NDArray
+

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sum(in NDArray, int) + +

+ +

Sum of array elements over a given axis.

+
+
+ +
+
public static NDArray sum(in NDArray a, int axis)
+
+ +

Parameters

+
+
a NDArray
+

Elements to sum.

+
+
axis int
+

Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.

+
+
+ +

Returns

+
+
NDArray
+

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sum(in NDArray, NPTypeCode?) + +

+ +

Sum of array elements over a given axis.

+
+
+ +
+
public static NDArray sum(in NDArray a, NPTypeCode? typeCode)
+
+ +

Parameters

+
+
a NDArray
+

Elements to sum.

+
+
typeCode NPTypeCode?
+

The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

+
+
+ +

Returns

+
+
NDArray
+

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sum(in NDArray, int?, bool) + +

+ +

Sum of array elements over a given axis.

+
+
+ +
+
public static NDArray sum(in NDArray a, int? axis, bool keepdims)
+
+ +

Parameters

+
+
a NDArray
+

Elements to sum.

+
+
axis int?
+

Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

+
+
+ +

Returns

+
+
NDArray
+

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sum(in NDArray, int?, bool, NPTypeCode?) + +

+ +

Sum of array elements over a given axis.

+
+
+ +
+
public static NDArray sum(in NDArray a, int? axis, bool keepdims, NPTypeCode? typeCode)
+
+ +

Parameters

+
+
a NDArray
+

Elements to sum.

+
+
axis int?
+

Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

+
+
typeCode NPTypeCode?
+

The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

+
+
+ +

Returns

+
+
NDArray
+

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sum(in NDArray, int?, bool, Type) + +

+ +

Sum of array elements over a given axis.

+
+
+ +
+
public static NDArray sum(in NDArray a, int? axis, bool keepdims, Type dtype)
+
+ +

Parameters

+
+
a NDArray
+

Elements to sum.

+
+
axis int?
+

Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

+
+
dtype Type
+

The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

+
+
+ +

Returns

+
+
NDArray
+

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sum(in NDArray, int?, NPTypeCode?) + +

+ +

Sum of array elements over a given axis.

+
+
+ +
+
public static NDArray sum(in NDArray a, int? axis, NPTypeCode? typeCode)
+
+ +

Parameters

+
+
a NDArray
+

Elements to sum.

+
+
axis int?
+

Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.

+
+
typeCode NPTypeCode?
+

The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

+
+
+ +

Returns

+
+
NDArray
+

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sum(in NDArray, int?, Type) + +

+ +

Sum of array elements over a given axis.

+
+
+ +
+
public static NDArray sum(in NDArray a, int? axis, Type dtype)
+
+ +

Parameters

+
+
a NDArray
+

Elements to sum.

+
+
axis int?
+

Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.

+
+
dtype Type
+

The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

+
+
+ +

Returns

+
+
NDArray
+

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ sum(in NDArray, Type) + +

+ +

Sum of array elements over a given axis.

+
+
+ +
+
public static NDArray sum(in NDArray a, Type dtype)
+
+ +

Parameters

+
+
a NDArray
+

Elements to sum.

+
+
dtype Type
+

The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

+
+
+ +

Returns

+
+
NDArray
+

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ swapaxes(in NDArray, int, int) + +

+ +

Interchange two axes of an array.

+
+
+ +
+
public static NDArray swapaxes(in NDArray a, int axis1, int axis2)
+
+ +

Parameters

+
+
a NDArray
+

Input array.

+
+
axis1 int
+

First axis.

+
+
axis2 int
+

Second axis.

+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ tan(in NDArray, NPTypeCode?) + +

+ +

Compute tangent element-wise.
+Equivalent to np.sin(x)/np.cos(x) element-wise.

+
+
+ +
+
public static NDArray tan(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Angle, in radians (2 \pi rad equals 360 degrees).

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The sine of each element of x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ tan(in NDArray, Type) + +

+ +

Trigonometric sine, element-wise.

+
+
+ +
+
public static NDArray tan(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Angle, in radians (2 \pi rad equals 360 degrees).

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The sine of each element of x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ tanh(in NDArray, NPTypeCode?) + +

+ +

Compute hyperbolic tangent element-wise.
+Equivalent to np.sinh(x)/np.cosh(x) or -1j * np.tan(1j*x).

+
+
+ +
+
public static NDArray tanh(in NDArray x, NPTypeCode? outType = null)
+
+ +

Parameters

+
+
x NDArray
+

Input array.

+
+
outType NPTypeCode?
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The sine of each element of x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ tanh(in NDArray, Type) + +

+ +

Compute hyperbolic tangent element-wise.
+Equivalent to np.sinh(x)/np.cosh(x) or -1j * np.tan(1j*x).

+
+
+ +
+
public static NDArray tanh(in NDArray x, Type outType)
+
+ +

Parameters

+
+
x NDArray
+

Input array.

+
+
outType Type
+

The dtype the returned ndarray should be of, only non integer values are supported.

+
+
+ +

Returns

+
+
NDArray
+

The sine of each element of x. This is a scalar if x is a scalar.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ transpose(in NDArray, int[]) + +

+ +

Permute the dimensions of an array.

+
+
+ +
+
public static NDArray transpose(in NDArray a, int[] premute = null)
+
+ +

Parameters

+
+
a NDArray
+

Input array.

+
+
premute int[]
+

By default, reverse the dimensions, otherwise permute the axes according to the values given.

+
+
+ +

Returns

+
+
NDArray
+

a with its axes permuted. A view is returned whenever possible.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ true_divide(in NDArray, in NDArray) + +

+ +
+
+ +
+
public static NDArray true_divide(in NDArray x1, in NDArray x2)
+
+ +

Parameters

+
+
x1 NDArray
+
+
x2 NDArray
+
+
+ +

Returns

+
+
NDArray
+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ unique(in NDArray) + +

+ +

Find the unique elements of an array.

+

Returns the sorted unique elements of an array.There are three optional outputs in addition to the unique elements:

+
    +
  • the indices of the input array that give the unique values
  • +
  • the indices of the unique array that reconstruct the input array
  • +
  • the number of times each unique value comes up in the input array
  • +
+
+
+ +
+
public static NDArray unique(in NDArray a)
+
+ +

Parameters

+
+
a NDArray
+
+
+ +

Returns

+
+
NDArray
+

The sorted unique values.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ var(NDArray, bool, int?, NPTypeCode?) + +

+ +

Compute the variance along the specified axis. +Returns the variance of the array elements, a measure of the spread of a distribution. +The variance is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public static NDArray var(NDArray a, bool keepdims = false, int? ddof = null, NPTypeCode? dtype = null)
+
+ +

Parameters

+
+
a NDArray
+

Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. +With this option, the result will broadcast correctly against the input array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
dtype NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the var values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ var(NDArray, int, bool, int?, NPTypeCode?) + +

+ +

Compute the variance along the specified axis. +Returns the variance of the array elements, a measure of the spread of a distribution. +The variance is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public static NDArray var(NDArray a, int axis, bool keepdims = false, int? ddof = null, NPTypeCode? dtype = null)
+
+ +

Parameters

+
+
a NDArray
+

Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted.

+
+
axis int
+

Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. +With this option, the result will broadcast correctly against the input array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
dtype NPTypeCode?
+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the var values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ var(in NDArray, bool, int?) + +

+ +

Compute the variance along the specified axis. +Returns the variance of the array elements, a measure of the spread of a distribution. +The variance is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public static NDArray var(in NDArray a, bool keepdims, int? ddof = null)
+
+ +

Parameters

+
+
a NDArray
+

Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. +With this option, the result will broadcast correctly against the input array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the var values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ var(in NDArray, int, NPTypeCode, bool, int?) + +

+ +

Compute the variance along the specified axis. +Returns the variance of the array elements, a measure of the spread of a distribution. +The variance is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public static NDArray var(in NDArray a, int axis, NPTypeCode type, bool keepdims = false, int? ddof = null)
+
+ +

Parameters

+
+
a NDArray
+

Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted.

+
+
axis int
+

Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array.

+
+
type NPTypeCode
+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. +With this option, the result will broadcast correctly against the input array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the var values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ var(in NDArray, int, bool, int?) + +

+ +

Compute the variance along the specified axis. +Returns the variance of the array elements, a measure of the spread of a distribution. +The variance is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public static NDArray var(in NDArray a, int axis, bool keepdims, int? ddof = null)
+
+ +

Parameters

+
+
a NDArray
+

Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted.

+
+
axis int
+

Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array.

+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. +With this option, the result will broadcast correctly against the input array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the var values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ var(in NDArray, int, int?) + +

+ +

Compute the variance along the specified axis. +Returns the variance of the array elements, a measure of the spread of a distribution. +The variance is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public static NDArray var(in NDArray a, int axis, int? ddof = null)
+
+ +

Parameters

+
+
a NDArray
+

Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted.

+
+
axis int
+

Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the var values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ var(in NDArray, int, Type, bool, int?) + +

+ +

Compute the variance along the specified axis. +Returns the variance of the array elements, a measure of the spread of a distribution. +The variance is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public static NDArray var(in NDArray a, int axis, Type dtype, bool keepdims = false, int? ddof = null)
+
+ +

Parameters

+
+
a NDArray
+

Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted.

+
+
axis int
+

Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array.

+
+
dtype Type
+
+
keepdims bool
+

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. +With this option, the result will broadcast correctly against the input array.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the var values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ var(in NDArray, int?) + +

+ +

Compute the variance along the specified axis. +Returns the variance of the array elements, a measure of the spread of a distribution. +The variance is computed for the flattened array by default, otherwise over the specified axis.

+
+
+ +
+
public static NDArray var(in NDArray a, int? ddof = null)
+
+ +

Parameters

+
+
a NDArray
+

Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted.

+
+
ddof int?
+

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

+
+
+ +

Returns

+
+
NDArray
+

returns a new array containing the var values, otherwise a reference to the output array is returned.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ vstack(params NDArray[]) + +

+ +

Stack arrays in sequence vertically (row wise).
+This is equivalent to concatenation along the first axis after 1-D arrays of shape(N,) have been reshaped to(1, N). Rebuilds arrays divided by vsplit.

+
+
+ +
+
public static NDArray vstack(params NDArray[] tup)
+
+ +

Parameters

+
+
tup NDArray[]
+

The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length.

+
+
+ +

Returns

+
+
NDArray
+

The array formed by stacking the given arrays, will be at least 2-D.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ zeros(Shape) + +

+ +

Return a new double array of given shape, filled with zeros.

+
+
+ +
+
public static NDArray zeros(Shape shape)
+
+ +

Parameters

+
+
shape Shape
+

Shape of the new array,

+
+
+ +

Returns

+
+
NDArray
+

Array of zeros with the given shape, dtype.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ zeros(Shape, NPTypeCode) + +

+ +

Return a new double array of given shape, filled with zeros.

+
+
+ +
+
public static NDArray zeros(Shape shape, NPTypeCode typeCode)
+
+ +

Parameters

+
+
shape Shape
+

Shape of the new array,

+
+
typeCode NPTypeCode
+

The desired data-type for the array, e.g., uint8. Default is float64 / double.

+
+
+ +

Returns

+
+
NDArray
+

Array of zeros with the given shape, dtype.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ zeros(Shape, Type) + +

+ +

Return a new double array of given shape, filled with zeros.

+
+
+ +
+
public static NDArray zeros(Shape shape, Type dtype)
+
+ +

Parameters

+
+
shape Shape
+

Shape of the new array,

+
+
dtype Type
+

The desired data-type for the array, e.g., uint8. Default is float64 / double.

+
+
+ +

Returns

+
+
NDArray
+

Array of zeros with the given shape, dtype.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ zeros(params int[]) + +

+ +

Return a new double array of given shape, filled with zeros.

+
+
+ +
+
public static NDArray zeros(params int[] shapes)
+
+ +

Parameters

+
+
shapes int[]
+

Shape of the new array,

+
+
+ +

Returns

+
+
NDArray
+

Array of zeros with the given shape, dtype.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ zeros_like(NDArray, Type) + +

+ +

Return an array of zeros with the same shape and type as a given array.

+
+
+ +
+
public static NDArray zeros_like(NDArray a, Type dtype = null)
+
+ +

Parameters

+
+
a NDArray
+

The shape and data-type of a define these same attributes of the returned array.

+
+
dtype Type
+

Overrides the data type of the result.

+
+
+ +

Returns

+
+
NDArray
+

Array of zeros with the same shape and type as nd.

+
+
+ + + + + + + +

Remarks

+ + + + + + + +

+ zeros<T>(params int[]) + +

+ +

Return a new double array of given shape, filled with zeros.

+
+
+ +
+
public static NDArray zeros<T>(params int[] shapes) where T : unmanaged
+
+ +

Parameters

+
+
shapes int[]
+

Shape of the new array,

+
+
+ +

Returns

+
+
NDArray
+

Array of zeros with the given shape, type T.

+
+
+ +

Type Parameters

+
+
T
+
+
+ + + + + + +

Remarks

+ + + + + + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/NumSharp.np.linalg.html b/docs/website/api/NumSharp.np.linalg.html new file mode 100644 index 000000000..5ea04472a --- /dev/null +++ b/docs/website/api/NumSharp.np.linalg.html @@ -0,0 +1,175 @@ + + + + + Class np.linalg | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ + + +
+
+ + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/api/NumSharp.yml b/docs/website/api/NumSharp.yml similarity index 100% rename from docs/api/NumSharp.yml rename to docs/website/api/NumSharp.yml diff --git a/docs/website/api/index.html b/docs/website/api/index.html new file mode 100644 index 000000000..f37452acb --- /dev/null +++ b/docs/website/api/index.html @@ -0,0 +1,1027 @@ + + + + + NumSharp API Reference | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+

NumSharp API Reference

+ +

NumSharp is a .NET port of Python's NumPy library. This API reference is organized by functionality, matching NumPy's documentation structure.

+
+

Core Types

+

The essential types for working with NumSharp.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeDescription
NDArrayThe main n-dimensional array type
npStatic API class (like import numpy as np in Python)
ShapeArray dimensions and strides
SliceSlice specification for array indexing
NDArray<TDType>Generic typed wrapper for type-safe access
+

Quick Example

+
using NumSharp;
+
+// Create arrays
+var a = np.array(new[] { 1, 2, 3, 4, 5 });
+var b = np.zeros((3, 4));
+var c = np.arange(10);
+
+// Operations
+var sum = np.sum(a);
+var reshaped = a.reshape(5, 1);
+var sliced = a["1:4"];  // Elements 1, 2, 3
+
+
+

Array Creation

+

Functions for creating new arrays.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDescription
np.array(data)Create array from existing data
np.zeros(shape)Array filled with zeros
np.zeros_like(a)Array of zeros with same shape as a
np.ones(shape)Array filled with ones
np.ones_like(a)Array of ones with same shape as a
np.empty(shape)Uninitialized array
np.full(shape, value)Array filled with a constant value
np.eye(N)Identity matrix
np.arange(start, stop, step)Evenly spaced values within interval
np.linspace(start, stop, num)Evenly spaced values (specify count)
np.meshgrid(x, y)Coordinate matrices from vectors
np.copy(a)Return a copy of the array
np.asarray(a)Convert input to array
np.frombuffer(buffer)Create array from buffer
+
+

Stacking & Joining

+

Functions for combining multiple arrays.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDescription
np.concatenate(arrays, axis)Join arrays along an existing axis
np.stack(arrays, axis)Join arrays along a new axis
np.vstack(arrays)Stack arrays vertically (row-wise)
np.hstack(arrays)Stack arrays horizontally (column-wise)
np.dstack(arrays)Stack arrays depth-wise (along 3rd axis)
+
+

Math Operations

+

Arithmetic and mathematical functions.

+

Arithmetic Operators

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorDescription
a + bElement-wise addition
a - bElement-wise subtraction
a * bElement-wise multiplication
a / bElement-wise division
a % bElement-wise modulo
-aElement-wise negation
+

Math Functions

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDescription
np.sum(a, axis)Sum of array elements
np.prod(a)Product of array elements
np.cumsum(a)Cumulative sum
np.sqrt(a)Element-wise square root
np.power(a, n)Element-wise power
np.abs(a)Element-wise absolute value
np.sign(a)Element-wise sign
np.floor(a)Element-wise floor
np.ceil(a)Element-wise ceiling
np.round(a)Element-wise rounding
np.clip(a, min, max)Clip values to range
np.maximum(a, b)Element-wise maximum
np.minimum(a, b)Element-wise minimum
+

Exponentials & Logarithms

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDescription
np.exp(a)Element-wise exponential
np.exp2(a)Element-wise 2^x
np.expm1(a)exp(x) - 1
np.log(a)Natural logarithm
np.log2(a)Base-2 logarithm
np.log10(a)Base-10 logarithm
np.log1p(a)log(1 + x)
+

Trigonometric Functions

+ + + + + + + + + + + + + + + + + + + + + +
FunctionDescription
np.sin(a)Element-wise sine
np.cos(a)Element-wise cosine
np.tan(a)Element-wise tangent
+
+

Statistics

+

Statistical functions.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDescription
np.mean(a, axis)Arithmetic mean
np.std(a, axis)Standard deviation
np.var(a, axis)Variance
np.amax(a, axis)Maximum value
np.amin(a, axis)Minimum value
+
+

Sorting & Searching

+

Functions for sorting arrays and finding elements.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDescription
np.argsort(a)Indices that would sort an array
np.argmax(a, axis)Index of maximum value
np.argmin(a, axis)Index of minimum value
np.searchsorted(a, v)Find indices for inserting values
np.nonzero(a)Indices of non-zero elements
+
+

Linear Algebra

+

Matrix and vector operations.

+ + + + + + + + + + + + + + + + + + + + + +
FunctionDescription
np.dot(a, b)Dot product / matrix multiplication
np.matmul(a, b)Matrix product (@ operator)
np.outer(a, b)Outer product of two vectors
+
+

Shape Manipulation

+

Functions for changing array shape and dimensions.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDescription
np.reshape(a, shape)Reshape without changing data
a.reshape(shape)Instance method for reshape
np.transpose(a)Permute array dimensions
a.TTranspose property
np.ravel(a)Flatten to 1-D array (returns view)
a.flatten()Flatten to 1-D array (returns copy)
np.squeeze(a)Remove axes of length 1
np.expand_dims(a, axis)Insert a new axis
np.swapaxes(a, ax1, ax2)Swap two axes
np.moveaxis(a, src, dst)Move axes to new positions
np.rollaxis(a, axis)Roll axis backwards
np.atleast_1d(a)Convert to at least 1-D
np.atleast_2d(a)Convert to at least 2-D
np.atleast_3d(a)Convert to at least 3-D
+
+

Indexing & Slicing

+

NumSharp supports Python-style array indexing and slicing.

+

Slice Syntax

+
a[":"]           // All elements
+a["1:5"]         // Elements 1-4 (stop exclusive)
+a["::2"]         // Every 2nd element
+a["-1"]          // Last element (reduces dimension)
+a["::-1"]        // Reversed
+a[":, 0"]        // All rows, first column
+a["..., -1"]     // Ellipsis fills dimensions
+
+

Special Slice Constants

+ + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
Slice.AllAll elements (:)
Slice.EllipsisFill remaining dimensions (...)
Slice.NewAxisInsert new dimension
Slice.Index(n)Single element selection
+

Boolean Masking

+
var a = np.array(new[] { 1, 2, 3, 4, 5 });
+var mask = a > 2;        // [false, false, true, true, true]
+var filtered = a[mask];  // [3, 4, 5]
+
+
+

Logic Functions

+

Boolean operations and comparisons.

+

Comparison Operators

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorDescription
a == bElement-wise equality
a != bElement-wise inequality
a > bElement-wise greater than
a >= bElement-wise greater or equal
a < bElement-wise less than
a <= bElement-wise less or equal
!aElement-wise NOT (boolean arrays)
+

Logic Functions

+ + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDescription
np.all(a, axis)Test if all elements are true
np.any(a, axis)Test if any element is true
np.array_equal(a, b)Test if arrays are equal
np.isscalar(a)Test if input is scalar
+
+

Random Sampling

+

Random number generation. Access via NumPyRandom.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDescription
np.random.rand(d0, d1, ...)Random values in [0, 1)
np.random.randn(d0, d1, ...)Standard normal distribution
np.random.randint(low, high, size)Random integers
np.random.uniform(low, high, size)Uniform distribution
np.random.choice(a, size, replace)Random sample from array
np.random.shuffle(a)Shuffle array in-place
np.random.permutation(a)Random permutation
+

Distributions

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDescription
np.random.beta(a, b, size)Beta distribution
np.random.binomial(n, p, size)Binomial distribution
np.random.gamma(shape, scale, size)Gamma distribution
np.random.poisson(lam, size)Poisson distribution
np.random.exponential(scale, size)Exponential distribution
np.random.geometric(p, size)Geometric distribution
np.random.lognormal(mean, sigma, size)Log-normal distribution
np.random.chisquare(df, size)Chi-square distribution
np.random.bernoulli(p, size)Bernoulli distribution
+
+

Broadcasting

+

Functions for array broadcasting.

+ + + + + + + + + + + + + + + + + +
FunctionDescription
np.broadcast_to(a, shape)Broadcast array to new shape
np.broadcast_arrays(a, b, ...)Broadcast arrays against each other
+

Broadcasting automatically aligns array shapes for operations:

+
    +
  • Shapes align from the right
  • +
  • Dimensions must be equal OR one must be 1
  • +
  • Dimension of 1 "stretches" to match
  • +
+
+

File I/O

+

Functions for saving and loading arrays.

+ + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDescription
np.save(file, arr)Save array to .npy file
np.load(file)Load .npy or .npz file
np.fromfile(file, dtype)Load array from binary file
arr.tofile(file)Write array to binary file
+
+

Unique & Set Operations

+ + + + + + + + + + + + + + + + + +
FunctionDescription
np.unique(a)Find unique elements
np.repeat(a, repeats)Repeat elements of array
+
+

Internals & Advanced

+

These types are for advanced users extending NumSharp or understanding its internals.

+

Storage & Backends

+ + + + + + + + + + + + + + + + + + + + + +
TypeDescription
UnmanagedStorageRaw unmanaged memory management
TensorEngineAbstract computation backend interface
DefaultEnginePure C# implementation of TensorEngine
+

Iteration

+ + + + + + + + + + + + + + + + + +
TypeDescription
NDIteratorTraverses arrays with different memory layouts
MultiIteratorPaired iteration for broadcasting
+

Memory Management

+ + + + + + + + + + + + + + + + + +
TypeDescription
ArraySlice<T>Typed memory slice
IMemoryBlockMemory block interface
+

Utilities

+ + + + + + + + + + + + + + + + + +
TypeDescription
InfoOf<T>Static type information cache
NPTypeCodeEnum of supported data types
+
+

Supported Data Types

+

NumSharp supports 12 numeric data types:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NPTypeCodeC# TypeNumPy Equivalent
Booleanboolnp.bool_
Bytebytenp.uint8
Int16shortnp.int16
UInt16ushortnp.uint16
Int32intnp.int32
UInt32uintnp.uint32
Int64longnp.int64
UInt64ulongnp.uint64
Charchar(no equivalent)
Singlefloatnp.float32
Doubledoublenp.float64
Decimaldecimal(no equivalent)
+
+

See Also

+ + +
+ +
+
+ + + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/api/toc.html b/docs/website/api/toc.html new file mode 100644 index 000000000..87a5ebaa0 --- /dev/null +++ b/docs/website/api/toc.html @@ -0,0 +1,429 @@ + +
+
+
+
+ + + +
+
+
+
+ + +
+
+
+
diff --git a/docs/website/api/toc.json b/docs/website/api/toc.json new file mode 100644 index 000000000..3ebe30d3d --- /dev/null +++ b/docs/website/api/toc.json @@ -0,0 +1,2 @@ + +{"items":[{"name":"API Reference","href":"index.html","topicHref":"index.html"},{"name":"Core Types","items":[{"name":"NDArray","href":"NumSharp.NDArray.html","topicHref":"NumSharp.NDArray.html","topicUid":"NumSharp.NDArray"},{"name":"np (Static API)","href":"NumSharp.np.html","topicHref":"NumSharp.np.html","topicUid":"NumSharp.np"},{"name":"Shape","href":"NumSharp.Shape.html","topicHref":"NumSharp.Shape.html","topicUid":"NumSharp.Shape"},{"name":"Slice","href":"NumSharp.Slice.html","topicHref":"NumSharp.Slice.html","topicUid":"NumSharp.Slice"},{"name":"SliceDef","href":"NumSharp.SliceDef.html","topicHref":"NumSharp.SliceDef.html","topicUid":"NumSharp.SliceDef"},{"name":"NDArray","href":"NumSharp.Generic.NDArray-1.html","topicHref":"NumSharp.Generic.NDArray-1.html","topicUid":"NumSharp.Generic.NDArray`1"}]},{"name":"Random Sampling","items":[{"name":"NumPyRandom (np.random)","href":"NumSharp.NumPyRandom.html","topicHref":"NumSharp.NumPyRandom.html","topicUid":"NumSharp.NumPyRandom"},{"name":"Randomizer","href":"NumSharp.Randomizer.html","topicHref":"NumSharp.Randomizer.html","topicUid":"NumSharp.Randomizer"},{"name":"NativeRandomState","href":"NumSharp.NativeRandomState.html","topicHref":"NumSharp.NativeRandomState.html","topicUid":"NumSharp.NativeRandomState"}]},{"name":"Linear Algebra","items":[{"name":"np.linalg","href":"NumSharp.np.linalg.html","topicHref":"NumSharp.np.linalg.html","topicUid":"NumSharp.np.linalg"}]},{"name":"Broadcasting","items":[{"name":"np.Broadcast","href":"NumSharp.np.Broadcast.html","topicHref":"NumSharp.np.Broadcast.html","topicUid":"NumSharp.np.Broadcast"},{"name":"BroadcastInfo","href":"NumSharp.BroadcastInfo.html","topicHref":"NumSharp.BroadcastInfo.html","topicUid":"NumSharp.BroadcastInfo"},{"name":"ViewInfo","href":"NumSharp.ViewInfo.html","topicHref":"NumSharp.ViewInfo.html","topicUid":"NumSharp.ViewInfo"}]},{"name":"Type System","items":[{"name":"NPTypeCode","href":"NumSharp.NPTypeCode.html","topicHref":"NumSharp.NPTypeCode.html","topicUid":"NumSharp.NPTypeCode"},{"name":"NPTypeCodeExtensions","href":"NumSharp.NPTypeCodeExtensions.html","topicHref":"NumSharp.NPTypeCodeExtensions.html","topicUid":"NumSharp.NPTypeCodeExtensions"},{"name":"DType","href":"NumSharp.DType.html","topicHref":"NumSharp.DType.html","topicUid":"NumSharp.DType"}]},{"name":"File I/O","items":[{"name":"NpzDictionary","href":"NumSharp.NpzDictionary.html","topicHref":"NumSharp.NpzDictionary.html","topicUid":"NumSharp.NpzDictionary"},{"name":"NpzDictionary","href":"NumSharp.NpzDictionary-1.html","topicHref":"NumSharp.NpzDictionary-1.html","topicUid":"NumSharp.NpzDictionary`1"}]},{"name":"Iterators","items":[{"name":"NDIterator","href":"NumSharp.NDIterator.html","topicHref":"NumSharp.NDIterator.html","topicUid":"NumSharp.NDIterator"},{"name":"NDIterator","href":"NumSharp.NDIterator-1.html","topicHref":"NumSharp.NDIterator-1.html","topicUid":"NumSharp.NDIterator`1"},{"name":"NDIteratorExtensions","href":"NumSharp.NDIteratorExtensions.html","topicHref":"NumSharp.NDIteratorExtensions.html","topicUid":"NumSharp.NDIteratorExtensions"},{"name":"MultiIterator","href":"NumSharp.MultiIterator.html","topicHref":"NumSharp.MultiIterator.html","topicUid":"NumSharp.MultiIterator"},{"name":"IteratorType","href":"NumSharp.IteratorType.html","topicHref":"NumSharp.IteratorType.html","topicUid":"NumSharp.IteratorType"},{"name":"MoveNextReferencedDelegate","href":"NumSharp.MoveNextReferencedDelegate-1.html","topicHref":"NumSharp.MoveNextReferencedDelegate-1.html","topicUid":"NumSharp.MoveNextReferencedDelegate`1"}]},{"name":"Exceptions","items":[{"name":"INumSharpException","href":"NumSharp.INumSharpException.html","topicHref":"NumSharp.INumSharpException.html","topicUid":"NumSharp.INumSharpException"},{"name":"NumSharpException","href":"NumSharp.NumSharpException.html","topicHref":"NumSharp.NumSharpException.html","topicUid":"NumSharp.NumSharpException"},{"name":"AxisOutOfRangeException","href":"NumSharp.AxisOutOfRangeException.html","topicHref":"NumSharp.AxisOutOfRangeException.html","topicUid":"NumSharp.AxisOutOfRangeException"},{"name":"IncorrectShapeException","href":"NumSharp.IncorrectShapeException.html","topicHref":"NumSharp.IncorrectShapeException.html","topicUid":"NumSharp.IncorrectShapeException"},{"name":"IncorrectSizeException","href":"NumSharp.IncorrectSizeException.html","topicHref":"NumSharp.IncorrectSizeException.html","topicUid":"NumSharp.IncorrectSizeException"},{"name":"IncorrectTypeException","href":"NumSharp.IncorrectTypeException.html","topicHref":"NumSharp.IncorrectTypeException.html","topicUid":"NumSharp.IncorrectTypeException"}]},{"name":"Internals","items":[{"name":"Backends","items":[{"name":"TensorEngine","href":"NumSharp.TensorEngine.html","topicHref":"NumSharp.TensorEngine.html","topicUid":"NumSharp.TensorEngine"},{"name":"DefaultEngine","href":"NumSharp.Backends.DefaultEngine.html","topicHref":"NumSharp.Backends.DefaultEngine.html","topicUid":"NumSharp.Backends.DefaultEngine"},{"name":"UnmanagedStorage","href":"NumSharp.Backends.UnmanagedStorage.html","topicHref":"NumSharp.Backends.UnmanagedStorage.html","topicUid":"NumSharp.Backends.UnmanagedStorage"},{"name":"BackendFactory","href":"NumSharp.Backends.BackendFactory.html","topicHref":"NumSharp.Backends.BackendFactory.html","topicUid":"NumSharp.Backends.BackendFactory"},{"name":"BackendType","href":"NumSharp.BackendType.html","topicHref":"NumSharp.BackendType.html","topicUid":"NumSharp.BackendType"},{"name":"StorageType","href":"NumSharp.StorageType.html","topicHref":"NumSharp.StorageType.html","topicUid":"NumSharp.StorageType"}]},{"name":"Unmanaged Memory","items":[{"name":"ArraySlice","href":"NumSharp.Backends.Unmanaged.ArraySlice.html","topicHref":"NumSharp.Backends.Unmanaged.ArraySlice.html","topicUid":"NumSharp.Backends.Unmanaged.ArraySlice"},{"name":"ArraySlice","href":"NumSharp.Backends.Unmanaged.ArraySlice-1.html","topicHref":"NumSharp.Backends.Unmanaged.ArraySlice-1.html","topicUid":"NumSharp.Backends.Unmanaged.ArraySlice`1"},{"name":"IArraySlice","href":"NumSharp.Backends.Unmanaged.IArraySlice.html","topicHref":"NumSharp.Backends.Unmanaged.IArraySlice.html","topicUid":"NumSharp.Backends.Unmanaged.IArraySlice"},{"name":"IMemoryBlock","href":"NumSharp.Backends.Unmanaged.IMemoryBlock.html","topicHref":"NumSharp.Backends.Unmanaged.IMemoryBlock.html","topicUid":"NumSharp.Backends.Unmanaged.IMemoryBlock"},{"name":"IMemoryBlock","href":"NumSharp.Backends.Unmanaged.IMemoryBlock-1.html","topicHref":"NumSharp.Backends.Unmanaged.IMemoryBlock-1.html","topicUid":"NumSharp.Backends.Unmanaged.IMemoryBlock`1"},{"name":"IUnmanagedMemoryBlock","href":"NumSharp.Backends.Unmanaged.IUnmanagedMemoryBlock.html","topicHref":"NumSharp.Backends.Unmanaged.IUnmanagedMemoryBlock.html","topicUid":"NumSharp.Backends.Unmanaged.IUnmanagedMemoryBlock"},{"name":"UnmanagedMemoryBlock","href":"NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock.html","topicHref":"NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock.html","topicUid":"NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock"},{"name":"UnmanagedMemoryBlock","href":"NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock-1.html","topicHref":"NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock-1.html","topicUid":"NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock`1"},{"name":"UnmanagedHelper","href":"NumSharp.Backends.Unmanaged.UnmanagedHelper.html","topicHref":"NumSharp.Backends.Unmanaged.UnmanagedHelper.html","topicUid":"NumSharp.Backends.Unmanaged.UnmanagedHelper"}]},{"name":"Memory Pools","items":[{"name":"ScalarMemoryPool","href":"NumSharp.Unmanaged.Memory.ScalarMemoryPool.html","topicHref":"NumSharp.Unmanaged.Memory.ScalarMemoryPool.html","topicUid":"NumSharp.Unmanaged.Memory.ScalarMemoryPool"},{"name":"StackedMemoryPool","href":"NumSharp.Unmanaged.Memory.StackedMemoryPool.html","topicHref":"NumSharp.Unmanaged.Memory.StackedMemoryPool.html","topicUid":"NumSharp.Unmanaged.Memory.StackedMemoryPool"}]},{"name":"NDArray Internals","items":[{"name":"NDArray._Unsafe","href":"NumSharp.NDArray._Unsafe.html","topicHref":"NumSharp.NDArray._Unsafe.html","topicUid":"NumSharp.NDArray._Unsafe"},{"name":"NDArray._Unsafe._Pinning","href":"NumSharp.NDArray._Unsafe._Pinning.html","topicHref":"NumSharp.NDArray._Unsafe._Pinning.html","topicUid":"NumSharp.NDArray._Unsafe._Pinning"},{"name":"IIndex","href":"NumSharp.IIndex.html","topicHref":"NumSharp.IIndex.html","topicUid":"NumSharp.IIndex"},{"name":"Kwargs","href":"NumSharp.Kwargs.html","topicHref":"NumSharp.Kwargs.html","topicUid":"NumSharp.Kwargs"}]}]},{"name":"Utilities","items":[{"name":"Type Conversion","items":[{"name":"Converts","href":"NumSharp.Utilities.Converts.html","topicHref":"NumSharp.Utilities.Converts.html","topicUid":"NumSharp.Utilities.Converts"},{"name":"Converts","href":"NumSharp.Utilities.Converts-1.html","topicHref":"NumSharp.Utilities.Converts-1.html","topicUid":"NumSharp.Utilities.Converts`1"},{"name":"NonGenericConvert","href":"NumSharp.Utilities.NonGenericConvert.html","topicHref":"NumSharp.Utilities.NonGenericConvert.html","topicUid":"NumSharp.Utilities.NonGenericConvert"},{"name":"TypelessConvert","href":"NumSharp.Utilities.TypelessConvert.html","topicHref":"NumSharp.Utilities.TypelessConvert.html","topicUid":"NumSharp.Utilities.TypelessConvert"},{"name":"TypelessConvertDelegate","href":"NumSharp.Utilities.TypelessConvertDelegate.html","topicHref":"NumSharp.Utilities.TypelessConvertDelegate.html","topicUid":"NumSharp.Utilities.TypelessConvertDelegate"},{"name":"ArrayConvert","href":"NumSharp.Utilities.ArrayConvert.html","topicHref":"NumSharp.Utilities.ArrayConvert.html","topicUid":"NumSharp.Utilities.ArrayConvert"}]},{"name":"Type Info","items":[{"name":"InfoOf","href":"NumSharp.Utilities.InfoOf-1.html","topicHref":"NumSharp.Utilities.InfoOf-1.html","topicUid":"NumSharp.Utilities.InfoOf`1"},{"name":"NumberInfo","href":"NumSharp.Utilities.NumberInfo.html","topicHref":"NumSharp.Utilities.NumberInfo.html","topicUid":"NumSharp.Utilities.NumberInfo"}]},{"name":"Arrays","items":[{"name":"Arrays","href":"NumSharp.Utilities.Arrays.html","topicHref":"NumSharp.Utilities.Arrays.html","topicUid":"NumSharp.Utilities.Arrays"},{"name":"ArraysExtensions","href":"NumSharp.Utilities.ArraysExtensions.html","topicHref":"NumSharp.Utilities.ArraysExtensions.html","topicUid":"NumSharp.Utilities.ArraysExtensions"}]},{"name":"Coordinate Incrementors","items":[{"name":"NDCoordinatesIncrementor","href":"NumSharp.Utilities.NDCoordinatesIncrementor.html","topicHref":"NumSharp.Utilities.NDCoordinatesIncrementor.html","topicUid":"NumSharp.Utilities.NDCoordinatesIncrementor"},{"name":"NDCoordinatesIncrementorAutoResetting","href":"NumSharp.Utilities.NDCoordinatesIncrementorAutoResetting.html","topicHref":"NumSharp.Utilities.NDCoordinatesIncrementorAutoResetting.html","topicUid":"NumSharp.Utilities.NDCoordinatesIncrementorAutoResetting"},{"name":"NDCoordinatesAxisIncrementor","href":"NumSharp.Utilities.NDCoordinatesAxisIncrementor.html","topicHref":"NumSharp.Utilities.NDCoordinatesAxisIncrementor.html","topicUid":"NumSharp.Utilities.NDCoordinatesAxisIncrementor"},{"name":"NDCoordinatesLeftToAxisIncrementor","href":"NumSharp.Utilities.NDCoordinatesLeftToAxisIncrementor.html","topicHref":"NumSharp.Utilities.NDCoordinatesLeftToAxisIncrementor.html","topicUid":"NumSharp.Utilities.NDCoordinatesLeftToAxisIncrementor"},{"name":"NDExtendedCoordinatesIncrementor","href":"NumSharp.Utilities.NDExtendedCoordinatesIncrementor.html","topicHref":"NumSharp.Utilities.NDExtendedCoordinatesIncrementor.html","topicUid":"NumSharp.Utilities.NDExtendedCoordinatesIncrementor"},{"name":"NDOffsetIncrementor","href":"NumSharp.Utilities.NDOffsetIncrementor.html","topicHref":"NumSharp.Utilities.NDOffsetIncrementor.html","topicUid":"NumSharp.Utilities.NDOffsetIncrementor"},{"name":"NDOffsetIncrementorAutoresetting","href":"NumSharp.Utilities.NDOffsetIncrementorAutoresetting.html","topicHref":"NumSharp.Utilities.NDOffsetIncrementorAutoresetting.html","topicUid":"NumSharp.Utilities.NDOffsetIncrementorAutoresetting"},{"name":"ValueCoordinatesIncrementor","href":"NumSharp.Utilities.ValueCoordinatesIncrementor.html","topicHref":"NumSharp.Utilities.ValueCoordinatesIncrementor.html","topicUid":"NumSharp.Utilities.ValueCoordinatesIncrementor"},{"name":"ValueCoordinatesIncrementor.EndCallbackHandler","href":"NumSharp.Utilities.ValueCoordinatesIncrementor.EndCallbackHandler.html","topicHref":"NumSharp.Utilities.ValueCoordinatesIncrementor.EndCallbackHandler.html","topicUid":"NumSharp.Utilities.ValueCoordinatesIncrementor.EndCallbackHandler"},{"name":"ValueCoordinatesIncrementorAutoResetting","href":"NumSharp.Utilities.ValueCoordinatesIncrementorAutoResetting.html","topicHref":"NumSharp.Utilities.ValueCoordinatesIncrementorAutoResetting.html","topicUid":"NumSharp.Utilities.ValueCoordinatesIncrementorAutoResetting"},{"name":"ValueOffsetIncrementor","href":"NumSharp.Utilities.ValueOffsetIncrementor.html","topicHref":"NumSharp.Utilities.ValueOffsetIncrementor.html","topicUid":"NumSharp.Utilities.ValueOffsetIncrementor"},{"name":"ValueOffsetIncrementorAutoresetting","href":"NumSharp.Utilities.ValueOffsetIncrementorAutoresetting.html","topicHref":"NumSharp.Utilities.ValueOffsetIncrementorAutoresetting.html","topicUid":"NumSharp.Utilities.ValueOffsetIncrementorAutoresetting"}]},{"name":"Collections","items":[{"name":"Hashset","href":"NumSharp.Utilities.Hashset-1.html","topicHref":"NumSharp.Utilities.Hashset-1.html","topicUid":"NumSharp.Utilities.Hashset`1"},{"name":"Hashset.Enumerator","href":"NumSharp.Utilities.Hashset-1.Enumerator.html","topicHref":"NumSharp.Utilities.Hashset-1.Enumerator.html","topicUid":"NumSharp.Utilities.Hashset`1.Enumerator"},{"name":"ConcurrentHashset","href":"NumSharp.Utilities.ConcurrentHashset-1.html","topicHref":"NumSharp.Utilities.ConcurrentHashset-1.html","topicUid":"NumSharp.Utilities.ConcurrentHashset`1"}]},{"name":"LINQ Extensions","items":[{"name":"IEnumeratorExtensions","href":"NumSharp.Utilities.Linq.IEnumeratorExtensions.html","topicHref":"NumSharp.Utilities.Linq.IEnumeratorExtensions.html","topicUid":"NumSharp.Utilities.Linq.IEnumeratorExtensions"},{"name":"IExtremaEnumerable","href":"NumSharp.Utilities.Linq.IExtremaEnumerable-1.html","topicHref":"NumSharp.Utilities.Linq.IExtremaEnumerable-1.html","topicUid":"NumSharp.Utilities.Linq.IExtremaEnumerable`1"}]},{"name":"Other","items":[{"name":"SteppingExtension","href":"NumSharp.Utilities.SteppingExtension.html","topicHref":"NumSharp.Utilities.SteppingExtension.html","topicUid":"NumSharp.Utilities.SteppingExtension"},{"name":"py","href":"NumSharp.Utilities.py.html","topicHref":"NumSharp.Utilities.py.html","topicUid":"NumSharp.Utilities.py"}]}]},{"name":"Extensions","items":[{"name":"LinqExtensions","href":"NumSharp.Extensions.LinqExtensions.html","topicHref":"NumSharp.Extensions.LinqExtensions.html","topicUid":"NumSharp.Extensions.LinqExtensions"}]},{"name":"External","items":[{"name":"DecimalEx (DecimalMath)","href":"DecimalMath.DecimalEx.html","topicHref":"DecimalMath.DecimalEx.html","topicUid":"DecimalMath.DecimalEx"}]}],"memberLayout":"SamePage"} diff --git a/docs/api/toc.yml b/docs/website/api/toc.yml similarity index 100% rename from docs/api/toc.yml rename to docs/website/api/toc.yml diff --git a/docs/articles/NDArray.Creation.html b/docs/website/articles/NDArray.Creation.html similarity index 100% rename from docs/articles/NDArray.Creation.html rename to docs/website/articles/NDArray.Creation.html diff --git a/docs/articles/NDArray.LinAlg.html b/docs/website/articles/NDArray.LinAlg.html similarity index 100% rename from docs/articles/NDArray.LinAlg.html rename to docs/website/articles/NDArray.LinAlg.html diff --git a/docs/articles/intro.html b/docs/website/articles/intro.html similarity index 100% rename from docs/articles/intro.html rename to docs/website/articles/intro.html diff --git a/docs/articles/toc.html b/docs/website/articles/toc.html similarity index 100% rename from docs/articles/toc.html rename to docs/website/articles/toc.html diff --git a/docs/website/docs/array-api-standard.html b/docs/website/docs/array-api-standard.html new file mode 100644 index 000000000..cad29d201 --- /dev/null +++ b/docs/website/docs/array-api-standard.html @@ -0,0 +1,1112 @@ + + + + + Python Array API Standard | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+

Python Array API Standard

+ +

If you've ever tried to write code that works with NumPy, PyTorch, JAX, and CuPy, you know the pain. They all do similar things, but the APIs are just different enough that your code breaks when you switch libraries. The Python Array API Standard exists to fix this.

+

NumSharp is working toward Array API compliance because it means your code can be more portable—not just between Python libraries, but between Python and C#.

+
+

What Is the Array API Standard?

+

The Array API Standard is a specification developed by the Consortium for Python Data API Standards. It defines a common interface for array operations that any library can implement.

+

Think of it like USB for arrays. Before USB, every device had its own connector. Now they all use the same port. The Array API does the same thing for array libraries.

+

The Problem It Solves

+

By 2020, Python had accumulated a zoo of array libraries:

+
    +
  • NumPy — The original, CPU-only
  • +
  • PyTorch — Deep learning, GPU support
  • +
  • TensorFlow — Deep learning, different API
  • +
  • JAX — Functional, JIT compilation
  • +
  • CuPy — NumPy clone for NVIDIA GPUs
  • +
  • Dask — Distributed/parallel arrays
  • +
  • MXNet, PaddlePaddle, and more...
  • +
+

Each library evolved independently. They all have reshape(), but the parameters are slightly different. They all have sum(), but the axis handling varies. Code written for NumPy rarely works on PyTorch without modification.

+

The Array API Standard says: "Here's exactly what reshape() should look like. Here's exactly how sum() should behave. Implement these, and code becomes portable."

+

Who's Adopting It?

+

As of 2024, these libraries have adopted or are adopting the Array API:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
LibraryStatus
NumPy 2.0+Full support in main namespace
PyTorch 2.0+torch namespace is mostly compliant
JAXCompliant (with some extras)
CuPyCompliant
DaskCompliant
ndonnxCompliant
+

NumSharp aims to join this list.

+
+

Why Should You Care?

+

For NumPy Users Moving to C#

+

If you're porting Python ML code to C#, Array API compliance means fewer surprises. When NumSharp follows the same specification as NumPy 2.x, the behavior matches.

+

For Library Authors

+

If you're building a C# library that consumes arrays, coding against the Array API subset means your library works with any compliant array type—not just NumSharp.

+

For Cross-Platform Development

+

Write once, run anywhere. The same algorithms can work on NumPy in Python and NumSharp in C#, producing identical results.

+
+

The Specification: What's Required?

+

The Array API Standard (version 2024.12) specifies:

+
    +
  • 14 data types
  • +
  • 5 constants
  • +
  • 133 core functions
  • +
  • 7 array attributes
  • +
  • Full set of operators
  • +
  • 2 optional extensions (linear algebra, FFT)
  • +
+

Let's break these down.

+
+

Data Types: 14 Required

+

The standard mandates support for exactly these types:

+

Integer Types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeBitsRangeC# Equivalent
int88-128 to 127sbyte
int1616-32,768 to 32,767short
int3232-2B to 2Bint
int6464-9Q to 9Qlong
uint880 to 255byte
uint16160 to 65,535ushort
uint32320 to 4Buint
uint64640 to 18Qulong
+

Floating-Point Types

+ + + + + + + + + + + + + + + + + + + + + + + +
TypeBitsPrecisionC# Equivalent
float3232~7 digitsfloat
float6464~16 digitsdouble
+

Complex Types

+ + + + + + + + + + + + + + + + + + + + + + + +
TypeBitsComponentsC# Equivalent
complex6464Two float32Custom struct needed
complex128128Two float64System.Numerics.Complex
+

Boolean

+ + + + + + + + + + + + + + + +
TypeBitsC# Equivalent
bool1bool
+

NumSharp Status

+

We support 12 of 14 types. Missing: complex64 and complex128.

+

Complex numbers are our biggest gap. C# has System.Numerics.Complex, but it's always 128-bit. For complex64, we'd need to implement our own struct with two float components.

+
+

Constants: 5 Required

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantValueNumSharp
e2.71828...
infPositive infinity
nanNot a Number
newaxisNone (for dimension expansion)
pi3.14159...
+

Full compliance here.

+
+

Array Attributes: 7 Required

+

Every array object must have these properties:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributeDescriptionNumSharp
dtypeData type of elements
deviceHardware location (CPU/GPU)
mTMatrix transpose (last 2 axes)
ndimNumber of dimensions
shapeTuple of dimension sizes
sizeTotal number of elements
TFull transpose
+

What's device?

+

The device attribute tells you where the array lives—CPU, GPU, TPU, etc. For NumSharp (CPU-only), this would always return a CPU device object. We need to implement this for compliance, even though we only support one device.

+

What's mT?

+

The mT property is "matrix transpose"—it only transposes the last two dimensions. This matters for batched matrix operations:

+
# x has shape (batch, rows, cols)
+x.T    # Transposes ALL dimensions → (cols, rows, batch) — usually wrong!
+x.mT   # Transposes last two only → (batch, cols, rows) — what you want
+
+

NumPy 2.0 added mT for Array API compliance. NumSharp needs it too.

+
+

Operators: Complete Set Required

+

Arrays must support these operators with proper semantics:

+

Arithmetic

+

+, -, *, /, // (floor division), %, ** (power), unary -, unary +

+

Comparison

+

<, <=, >, >=, ==, !=

+

Bitwise

+

~ (NOT), & (AND), | (OR), ^ (XOR), <<, >>

+

Matrix

+

@ (matrix multiplication)

+

In-place

+

+=, -=, *=, /=, //=, %=, **=, &=, |=, ^=, <<=, >>=, @=

+

NumSharp implements most of these. We're missing the bitwise operators as named functions (though the operators themselves work) and @ (we have np.matmul() instead).

+
+

Core Functions: 133 Required

+

The specification groups functions into categories. Here's where NumSharp stands:

+

Creation Functions (16)

+

These create new arrays from scratch or from existing data.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDescriptionNumSharp
arangeEvenly spaced values in interval
asarrayConvert to array
emptyUninitialized array
empty_likeSame shape, uninitialized
eyeIdentity matrix
from_dlpackFrom DLPack capsule
fullFilled with constant
full_likeSame shape, filled
linspaceEvenly spaced (by count)
meshgridCoordinate matrices
onesFilled with ones
ones_likeSame shape, ones
trilLower triangle
triuUpper triangle
zerosFilled with zeros
zeros_likeSame shape, zeros
+

Coverage: 81% — Missing tril, triu, from_dlpack

+

Element-wise Functions (67)

+

The largest category. Mathematical operations applied to each element.

+

Arithmetic: add, subtract, multiply, divide, floor_divide, remainder, pow, negative, positive, abs, sign

+

Rounding: ceil, floor, trunc, round

+

Exponential/Log: exp, expm1, log, log1p, log2, log10

+

Trigonometric: sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh, asinh, acosh, atanh

+

Comparison: equal, not_equal, less, less_equal, greater, greater_equal, maximum, minimum

+

Logical: logical_and, logical_or, logical_xor, logical_not

+

Bitwise: bitwise_and, bitwise_or, bitwise_xor, bitwise_invert, bitwise_left_shift, bitwise_right_shift

+

Type checking: isfinite, isinf, isnan

+

Other: sqrt, square, clip, copysign, hypot, logaddexp, nextafter, signbit, conj, imag, real

+

NumSharp Coverage: ~75%

+

We're missing:

+
    +
  • copysign, hypot, logaddexp (math functions)
  • +
  • nextafter, signbit (floating-point utilities)
  • +
  • conj, imag, real (complex number functions—blocked on complex type support)
  • +
  • Named bitwise functions (we have the operators, not the functions)
  • +
+

Statistical Functions (9)

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDescriptionNumSharp
maxMaximum value✅ (amax)
meanArithmetic mean
minMinimum value✅ (amin)
prodProduct of elements
stdStandard deviation
sumSum of elements
varVariance
cumulative_sumCumulative sum✅ (cumsum)
cumulative_prodCumulative product
+

Coverage: 89% — Missing cumulative_prod

+

Note: The Array API uses a correction parameter for std/var:

+
# Array API
+std(x, correction=1)   # Sample standard deviation
+
+# NumPy (and NumSharp)
+np.std(x, ddof=1)      # Same thing, different name
+
+

Manipulation Functions (14)

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDescriptionNumSharp
broadcast_arraysBroadcast shapes
broadcast_toBroadcast to shape
concatJoin along axis✅ (concatenate)
expand_dimsAdd dimension
flipReverse along axis
moveaxisMove axis position
permute_dimsPermute dimensions✅ (transpose)
repeatRepeat elements
reshapeChange shape
rollShift elementsPartial
squeezeRemove size-1 dimensions
stackJoin along new axis
tileRepeat whole array
unstackSplit along axis
+

Coverage: ~79% — Missing tile, unstack; roll is partial

+

Set Functions (4)

+

This is our weakest area.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDescriptionNumSharp
unique_allValues + indices + inverse + counts
unique_countsValues + counts
unique_inverseValues + inverse indices
unique_valuesJust unique values✅ (np.unique)
+

Coverage: 25%

+

The Array API split NumPy's np.unique(return_counts=True, return_inverse=True) into four focused functions. We only have the basic version.

+

Other Categories

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CategoryRequiredNumSharpCoverage
Searching6~4~67%
Sorting22100%
Linear Algebra (core)44100%
Indexing200%
Data Types6~3~50%
Utility32~67%
+
+

Type Promotion Rules

+

The Array API specifies strict rules for what happens when you combine different types.

+

Same-Kind Promotion

+

Within a type category, smaller types promote to larger:

+
int8 + int16 → int16
+int16 + int32 → int32
+float32 + float64 → float64
+
+

Cross-Kind: Undefined!

+

Here's the crucial difference from NumPy 1.x: mixing integers and floats is undefined in the Array API.

+
# Array API says: DON'T DO THIS
+int32_array + float32_array  # Undefined behavior!
+
+

NumPy 2.x still allows it (promoting to float), but the Array API deliberately leaves this unspecified so libraries can make their own choices.

+

Scalar Promotion

+

When you mix a Python scalar with an array, the scalar is "weak"—it adopts the array's type:

+
uint8_array + 2  → uint8_array  # Scalar becomes uint8
+float32_array + 1.5 → float32_array  # Scalar becomes float32
+
+

This is consistent with NEP 50 in NumPy 2.x.

+
+

Extensions: Optional but Defined

+

The Array API defines two optional extensions. If a library implements an extension, it must implement all functions in that extension.

+

Linear Algebra Extension (23 functions)

+

Accessible via linalg namespace.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDescription
choleskyCholesky decomposition
crossCross product
detDeterminant
diagonalExtract diagonal
eighEigenvalues/vectors (Hermitian)
eigvalshEigenvalues only (Hermitian)
invMatrix inverse
matmulMatrix multiplication
matrix_normMatrix norm
matrix_powerMatrix to integer power
matrix_rankNumerical rank
matrix_transposeTranspose last 2 dims
outerOuter product
pinvPseudo-inverse
qrQR decomposition
slogdetSign and log-determinant
solveSolve linear system
svdSingular value decomposition
svdvalsSingular values only
tensordotTensor contraction
traceSum of diagonal
vecdotVector dot product
vector_normVector norm
+

NumSharp Status: We have matmul, outer, trace, and basic operations. The decompositions (qr, svd, eigh, cholesky, inv) are stubs that return null.

+

FFT Extension (14 functions)

+

Accessible via fft namespace.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionDescription
fft1-D discrete Fourier transform
ifftInverse of fft
fftnN-D DFT
ifftnInverse of fftn
rfft1-D DFT for real input
irfftInverse of rfft
rfftnN-D DFT for real input
irfftnInverse of rfftn
hfft1-D DFT for Hermitian input
ihfftInverse of hfft
fftfreqDFT sample frequencies
rfftfreqSample frequencies for rfft
fftshiftShift zero-frequency to center
ifftshiftInverse of fftshift
+

NumSharp Status: Not implemented. FFT requires complex number support.

+
+

What's NOT in the Standard

+

The Array API deliberately excludes some things to remain implementable across diverse libraries:

+

Out of Scope

+
    +
  • I/O operations — No save, load, fromfile
  • +
  • String dtypes — No StringDType or fixed-width strings
  • +
  • Datetime dtypes — No datetime64, timedelta64
  • +
  • Object dtype — No arrays of arbitrary Python objects
  • +
  • Specific error types — Error handling is implementation-defined
  • +
  • C API — Only Python-level interface specified
  • +
  • Execution semantics — Eager vs. lazy, parallelization, etc.
  • +
+

This means NumSharp can have these features (and we do—np.save, np.load work), they're just outside the Array API specification.

+
+

Real-World Use Cases

+

The specification documents several motivating use cases:

+

SciPy Without Dependencies

+

SciPy's signal processing functions are pure Python but tied to NumPy. With Array API compliance, scipy.signal.welch(x) could work on GPU arrays (CuPy), distributed arrays (Dask), or NumSharp arrays—without SciPy depending on any of them.

+

einops Without Backend Code

+

The einops library maintains ~550 lines of glue code to support multiple backends. Array API compliance would eliminate this entirely.

+

JIT Compilation

+

Numba and other JIT compilers struggle with NumPy's value-dependent type rules. The Array API's strict type-based promotion makes JIT compilation predictable.

+
+

NumSharp's Path to Compliance

+

Current Coverage

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CategoryFunctionsNumSharp%
Creation161381%
Element-wise67~5075%
Statistical9889%
Manipulation141179%
Set4125%
Searching6467%
Sorting22100%
Linear Algebra44100%
Indexing200%
Data Types6350%
Utility3267%
Total Core133~98~74%
+

Priority Items

+
    +
  1. Complex number types — Blocks FFT extension and many math functions
  2. +
  3. device and mT properties — Simple to add
  4. +
  5. Set functions (unique_* family) — Moderate effort
  6. +
  7. Missing element-wise functions — Incremental work
  8. +
  9. Indexing functions (take, take_along_axis) — Moderate effort
  10. +
+

Tracking

+

See Array API Standard Milestone for detailed issue tracking.

+
+

References

+ + +
+ +
+
+ + + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/docs/broadcasting.html b/docs/website/docs/broadcasting.html new file mode 100644 index 000000000..d85078832 --- /dev/null +++ b/docs/website/docs/broadcasting.html @@ -0,0 +1,386 @@ + + + + + Broadcasting | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+

Broadcasting

+ +

Broadcasting allows arithmetic operations between arrays of different shapes. When you add a (3, 4) matrix to a (4,) vector, NumSharp automatically "broadcasts" the vector across each row—no explicit loops or copying required.

+
+

How Broadcasting Works

+

NumSharp follows NumPy's broadcasting rules exactly:

+
    +
  1. Shapes align from the right. If arrays have different numbers of dimensions, prepend 1s to the shorter shape.

    +
  2. +
  3. Dimensions must be equal or 1. For each dimension, sizes must match OR one must be 1.

    +
  4. +
  5. Size-1 dimensions stretch. A dimension of size 1 expands to match the other array's size in that dimension.

    +
  6. +
+
// (3, 4) + (4,) → (3, 4) + (1, 4) → (3, 4)
+var matrix = np.ones((3, 4));
+var row = np.array(new[] {1, 2, 3, 4});
+var result = matrix + row;  // Shape: (3, 4)
+
+

Broadcasting creates views, not copies. The stretched array doesn't allocate new memory—it uses stride tricks to repeat values virtually.

+
+

Shape Compatibility

+

Compatible Shapes

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Shape AShape BResultNotes
(5,)(5,)(5,)Same shape
(5,)()(5,)Scalar broadcasts to any shape
(3, 4)(4,)(3, 4)Row vector broadcasts across rows
(3, 4)(3, 1)(3, 4)Column vector broadcasts across columns
(3, 1)(1, 4)(3, 4)Both arrays stretch
(2, 3, 4)(3, 4)(2, 3, 4)Lower-dimensional array broadcasts
(8, 1, 6, 1)(7, 1, 5)(8, 7, 6, 5)Complex case with multiple stretch dimensions
+

Incompatible Shapes

+ + + + + + + + + + + + + + + + + + + + + + + + + +
Shape AShape BError
(3,)(4,)3 ≠ 4, neither is 1
(3, 4)(3,)Trailing dimensions 4 ≠ 3
(2, 3)(3, 2)No valid alignment
+

Incompatible shapes throw IncorrectShapeException.

+
+

Broadcasting Functions

+

np.broadcast_to(array, shape)

+

Broadcasts an array to a specific shape. Returns a read-only view.

+
var a = np.array(new[] {1, 2, 3});
+var b = np.broadcast_to(a, (4, 3));
+// b.shape: (4, 3)
+// b[0]: [1, 2, 3]
+// b[1]: [1, 2, 3]  (same data, not copied)
+
+

Constraints: The source shape must be unilaterally broadcastable to the target. You can only stretch dimensions that are size 1:

+
np.broadcast_to(np.ones((2,)), (3, 3));   // Error: can't stretch 2 to 3
+np.broadcast_to(np.ones((1, 3)), (4, 3)); // OK: stretches 1 to 4
+
+

np.broadcast_arrays(array1, array2, ...)

+

Broadcasts multiple arrays against each other, returning views with a common shape.

+
var a = np.array(new[] {1, 2, 3});        // (3,)
+var b = np.array(new[,] {{1}, {2}});      // (2, 1)
+
+var (a_bc, b_bc) = np.broadcast_arrays(a, b);
+// Both now (2, 3)
+
+

Also available as:

+
NDArray[] results = np.broadcast_arrays(arr1, arr2, arr3);
+
+

Implicit Broadcasting

+

All arithmetic operators broadcast automatically:

+
var a = np.ones((3, 4));
+var b = np.array(new[] {1, 2, 3, 4});
+
+a + b;   // (3, 4)
+a - b;   // (3, 4)
+a * b;   // (3, 4)
+a / b;   // (3, 4)
+
+
+

Memory Behavior

+

Broadcasted arrays are views that share memory with the original:

+
var small = np.array(new[] {1, 2, 3});           // 3 elements
+var big = np.broadcast_to(small, (1000000, 3));  // Appears as 3M elements
+
+// big.size == 3_000_000
+// Actual memory: still just 3 elements
+// big.Shape.IsBroadcasted == true
+
+

Important: Broadcasted arrays should be treated as read-only. Writing to a broadcasted position affects all positions that share that memory. If you need to modify a broadcasted array, copy it first:

+
var writable = big.copy();  // Allocates full 3M elements
+
+
+

Implementation Details

+

NumSharp implements broadcasting through stride manipulation. When a dimension is broadcast:

+
    +
  • The shape shows the expanded size
  • +
  • The stride for that dimension is set to 0
  • +
+

A stride of 0 means the index doesn't advance in memory—the same element is read repeatedly.

+
var a = np.array(new[] {1, 2, 3});
+var b = np.broadcast_to(a, (4, 3));
+
+// b's internal representation:
+// Shape:   (4, 3)
+// Strides: (0, 1)  ← stride 0 in first dimension
+
+

This is tracked via Shape.IsBroadcasted and BroadcastInfo.

+
+

Common Patterns

+

Centering Data (subtract mean)

+
var data = np.random.rand(100, 5);           // 100 samples, 5 features
+var mean = np.mean(data, axis: 0);           // (5,)
+var centered = data - mean;                  // (100, 5) - broadcasts
+
+

Normalizing (divide by std)

+
var std = np.std(data, axis: 0);             // (5,)
+var normalized = centered / std;             // (100, 5)
+
+

Outer Product

+
var row = np.array(new[] {1, 2, 3});         // (3,)
+var col = np.array(new[,] {{10}, {20}});     // (2, 1)
+var outer = row * col;                       // (2, 3)
+
+

Batch Operations

+
var batch = np.random.rand(32, 28, 28);      // 32 images
+var mean_image = np.mean(batch, axis: 0);    // (28, 28)
+var normalized = batch - mean_image;         // (32, 28, 28)
+
+
+

Troubleshooting

+

"shape mismatch: objects cannot be broadcast"

+

Shapes don't follow broadcasting rules. Check alignment:

+
// Wrong
+var a = np.ones((3, 4));
+var b = np.ones((3,));    // Trailing dim 4 ≠ 3
+var c = a + b;            // Error
+
+// Fix: reshape to column vector
+var c = a + b.reshape(3, 1);  // Now (3, 4) + (3, 1) works
+
+

Unexpected Output Shape

+

If you get a larger shape than expected, you may have accidentally broadcast:

+
var a = np.ones((10, 1));
+var b = np.ones((1, 10));
+var c = a + b;  // (10, 10) — both stretched!
+
+

Row vs Column Vector

+

A 1-D array (n,) broadcasts as a row (1, n), not a column:

+
var vec = np.array(new[] {1, 2, 3});  // (3,) — not (1, 3) or (3, 1)
+
+// To broadcast as column:
+var col = vec.reshape(3, 1);          // (3, 1)
+// or
+var col = vec[np.newaxis].T;          // (3, 1)
+
+
+

API Reference

+ + + + + + + + + + + + + + + + + + + + + +
FunctionDescription
np.broadcast_to(arr, shape)Broadcast array to specific shape (returns view)
np.broadcast_arrays(a, b)Broadcast two arrays to common shape (returns tuple)
np.broadcast_arrays(params NDArray[])Broadcast multiple arrays (returns array)
+ + + + + + + + + + + + + + + + + +
PropertyDescription
Shape.IsBroadcastedTrue if shape has broadcast strides (stride 0)
BroadcastInfoInternal metadata for broadcast tracking
+ + + + + + + + + + + + + +
ExceptionWhen
IncorrectShapeExceptionShapes cannot be broadcast together
+ +
+ +
+
+ + + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/docs/compliance.html b/docs/website/docs/compliance.html new file mode 100644 index 000000000..8a63ebd3d --- /dev/null +++ b/docs/website/docs/compliance.html @@ -0,0 +1,528 @@ + + + + + NumPy Compliance & Compatibility | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+

NumPy Compliance & Compatibility

+ +

NumSharp exists for one reason: to let you write NumPy-style code in C#. But "NumPy-style" isn't just about having similar function names—it's about behaving the same way. When you add a scalar to an array, when you slice with negative indices, when you broadcast two arrays together, NumSharp should do exactly what NumPy does.

+

This page explains where we are on that journey, what challenges we face, and how you can help.

+
+

Why Compatibility Matters

+

If you're porting Python ML code to C#, the last thing you want is subtle behavioral differences causing bugs. Consider this Python code:

+
import numpy as np
+a = np.array([1, 2, 3], dtype=np.uint8)
+b = a + 255
+print(b)  # [0, 1, 2] - overflow wraps around
+
+

What should NumSharp do here? In NumPy 1.x, this would silently upcast to int16 to avoid overflow. In NumPy 2.x, it wraps with a warning. These differences matter when you're debugging why your neural network produces different results in C#.

+

Our goal is 1-to-1 behavioral compatibility with NumPy 2.x (currently targeting 2.4.2). We also aim to comply with the Python Array API Standard, which defines portable array operations across NumPy, PyTorch, JAX, and other libraries.

+
+

The Big Picture: Three Compliance Tracks

+

We're tracking compliance across three related but distinct standards:

+

1. NumPy 2.x Compatibility

+

NumPy 2.0 (released April 2024) was a major breaking release. It changed how types are promoted, removed deprecated functions, and added new APIs. If you learned NumPy before 2024, some of your intuitions might be wrong now.

+

Tracking: NumPy 2.x Compliance Milestone

+

2. Array API Standard

+

The Python Array API Standard is an industry consortium effort to define a common API that works across array libraries. Write code against the Array API, and it runs on NumPy, PyTorch, JAX, CuPy, or Dask without changes. NumPy adopted it in version 2.0.

+

Deep Dive: Array API Standard — Our dedicated page with full specification details

+

Tracking: Array API Standard Milestone

+

3. NumPy Enhancement Proposals (NEPs)

+

NEPs are the design documents that define NumPy's behavior. When we say "NumPy does X," there's usually a NEP that specifies exactly what X means. We track the NEPs most relevant to NumSharp.

+

Tracking: NEP Compliance Milestone

+
+

Type Promotion: The Biggest Change in NumPy 2.0

+

If there's one thing you need to understand about NumPy 2.x compatibility, it's NEP 50: Promotion Rules for Python Scalars.

+

The Old Way (NumPy 1.x)

+

NumPy 1.x used "value-based" promotion. It would inspect the actual value of a scalar to decide the output type:

+
# NumPy 1.x behavior
+np.result_type(np.int8, 1)    # → int8 (1 fits in int8)
+np.result_type(np.int8, 255)  # → int16 (255 doesn't fit, upcast!)
+
+

This was convenient—you rarely got overflow errors. But it was also unpredictable. The same code could produce different types depending on the runtime values, making optimization and type inference nearly impossible.

+

The New Way (NumPy 2.x)

+

NumPy 2.x uses "weak scalar" promotion. Python scalars defer to the array's dtype:

+
# NumPy 2.x behavior
+np.uint8(1) + 2    # → uint8(3)
+np.uint8(1) + 255  # → uint8(0) with overflow warning!
+
+

The scalar 2 is "weak"—it takes on whatever type the array has. This is more predictable and enables better optimization, but it can cause overflow where NumPy 1.x would have silently upcasted.

+

Where NumSharp Stands

+

NumSharp currently has mixed behavior. Some operations follow the old value-based rules, others follow NEP 50. We're working on consistent NEP 50 compliance.

+

Key Issue: #529 - Type promotion diverges from NumPy 2.x

+

What you might see: If you're porting NumPy code and get unexpected results with mixed types (especially unsigned + signed), this is likely why.

+
+

API Changes: What Got Removed and Added

+

Removed in NumPy 2.0 (NEP 52)

+

NumPy 2.0 cleaned house, removing ~100 deprecated functions and aliases. If you're porting old NumPy code, you might need to update these:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Don't UseUse InsteadWhy It Changed
np.round_np.roundUnderscore was to avoid Python keyword conflict (no longer needed)
np.productnp.prodConsistency with sumprod
np.sometruenp.anyClearer naming
np.alltruenp.allClearer naming
np.ranknp.ndimrank was confusing (matrix rank vs array rank)
+

NumSharp supports the canonical names. We never implemented most deprecated aliases, so this is actually an advantage—less legacy baggage.

+

Added in NumPy 2.0 (NEP 56)

+

NumPy 2.0 added Array API Standard functions. These are mostly aliases for existing functions, but some are genuinely new:

+

New Aliases (for Array API compatibility):

+
    +
  • np.acos, np.asin, np.atan → aliases for arccos, arcsin, arctan
  • +
  • np.concat → alias for concatenate
  • +
  • np.permute_dims → alias for transpose
  • +
  • np.pow → alias for power
  • +
+

Genuinely New:

+
    +
  • np.isdtype(dtype, kind) — Check if dtype belongs to a category
  • +
  • np.unique_values(), np.unique_counts(), np.unique_inverse(), np.unique_all() — Split the overloaded np.unique() into focused functions
  • +
  • ndarray.mT — Matrix transpose (transposes last two dimensions only)
  • +
  • ndarray.device — Returns the device (CPU for NumSharp)
  • +
+

NumSharp Status: We have most aliases but are missing isdtype(), the unique_* family, .mT, and .device.

+
+

Data Types: What We Support (and Don't)

+

NumSharp supports 12 numeric types—more than most users need, but not everything NumPy offers.

+

Fully Supported

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NumSharp TypeC# TypeNumPy TypeNotes
Booleanboolbool_
Bytebyteuint8
Int16shortint16
UInt16ushortuint16
Int32intint32Default integer type
UInt32uintuint32
Int64longint64
UInt64ulonguint64
Singlefloatfloat32
Doubledoublefloat64Default float type
CharcharC#-specific, no NumPy equivalent
DecimaldecimalC#-specific, 128-bit decimal
+

Not Yet Supported

+

Complex Numbers (complex64, complex128)

+

This is our biggest gap. Complex numbers are required by the Array API Standard and essential for signal processing, FFT, and many scientific applications. They're also tricky to implement efficiently in C#.

+

Why it's hard: C# has System.Numerics.Complex, but it's always 128-bit (complex128). There's no native complex64. We'd need to implement our own struct for float-based complex numbers.

+

DateTime Types (datetime64, timedelta64)

+

NumPy's datetime types (NEP 7) are powerful for time series analysis. We haven't implemented them.

+

Why it's hard: NumPy datetime64 has multiple resolutions (nanoseconds to years) stored in the dtype. C# has DateTime and TimeSpan, but they don't map cleanly to NumPy's model.

+

Variable-Width Strings (StringDType)

+

NumPy 2.0 added a new UTF-8 variable-width string type (NEP 55). The old fixed-width strings (S10, U10) wasted memory. We don't support either.

+
+

Memory Layout: C-Order Only

+

Here's a limitation that might surprise NumPy users: NumSharp only supports C-order (row-major) memory layout.

+

What This Means

+

NumPy arrays can be stored in two layouts:

+
    +
  • C-order (row-major): Last index varies fastest. Default in NumPy.
  • +
  • F-order (column-major): First index varies fastest. Default in Fortran, MATLAB.
  • +
+
# NumPy can do both
+c_array = np.zeros((3, 4), order='C')  # Row-major
+f_array = np.zeros((3, 4), order='F')  # Column-major
+
+

NumSharp always uses C-order. The order parameter exists on functions like reshape, ravel, and flatten, but it's ignored—we always use C-order.

+

When This Matters

+

Most of the time, you won't notice. But if you're:

+
    +
  • Interfacing with Fortran libraries (LAPACK, BLAS)
  • +
  • Reading data written by MATLAB
  • +
  • Optimizing cache access patterns for column-wise operations
  • +
+

...you might hit issues. See #546 for F-order support tracking.

+
+

Array API Standard

+

The Array API Standard specifies 133 core functions, 14 data types, and strict type promotion rules. NumSharp currently implements about 74% of the core specification.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CategoryRequiredNumSharpCoverage
Creation161381%
Element-wise67~5075%
Statistical9889%
Manipulation141179%
Set4125%
Other23~15~65%
+

Biggest Gaps:

+
    +
  • Complex number types (complex64, complex128) — blocks FFT and many math functions
  • +
  • Set functions (unique_all, unique_counts, unique_inverse)
  • +
  • Array properties (.device, .mT)
  • +
+

For the complete specification details, function lists, type promotion rules, and extension coverage, see our dedicated Array API Standard page.

+
+

Random Number Generation

+

Good news: NumSharp's np.random module provides 1-to-1 seed matching with NumPy.

+
// NumSharp
+np.random.seed(42);
+var a = np.random.rand(5);
+// Produces: [0.37454012, 0.95071431, 0.73199394, 0.59865848, 0.15601864]
+
+// Equivalent Python
+np.random.seed(42)
+a = np.random.rand(5)
+# Produces: [0.37454012, 0.95071431, 0.73199394, 0.59865848, 0.15601864]
+
+

This is critical for reproducibility. If you're porting ML code that depends on specific random sequences (for testing, debugging, or reproducible experiments), you'll get identical results.

+

Supported Distributions

+
    +
  • Uniform: rand, uniform, randint
  • +
  • Normal: randn, normal
  • +
  • Other: beta, binomial, gamma, poisson, exponential, geometric, lognormal, chisquare, bernoulli
  • +
  • Utilities: seed, shuffle, permutation, choice
  • +
+
+

File Format Interoperability

+

NumSharp can read and write NumPy's .npy file format. This means you can:

+
    +
  1. Create arrays in Python, save with np.save(), load in NumSharp
  2. +
  3. Create arrays in NumSharp, save with np.save(), load in Python
  4. +
  5. Share data files between Python and C# applications
  6. +
+
// Save
+var arr = np.arange(100).reshape(10, 10);
+np.save("mydata.npy", arr);
+
+// Load
+var loaded = np.load("mydata.npy");
+
+

.npz Archives

+

NumPy's .npz format stores multiple arrays in a ZIP archive. NumSharp can read .npz files but not write them yet.

+
// Load multiple arrays from .npz
+var archive = np.load("data.npz") as NpzDictionary;
+var weights = archive["weights"];
+var biases = archive["biases"];
+
+
+

Linear Algebra: Partial Support

+

NumSharp has basic linear algebra operations, but advanced decompositions are incomplete.

+

Working

+ + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionNotes
np.dotMatrix multiplication
np.matmulMatrix multiplication (equivalent to @ in Python)
np.outerOuter product
ndarray.TTranspose
+

Stubs (Return null/default)

+

These functions exist but don't work:

+
    +
  • np.linalg.inv — Matrix inverse
  • +
  • np.linalg.qr — QR decomposition
  • +
  • np.linalg.svd — Singular value decomposition
  • +
  • np.linalg.lstsq — Least squares
  • +
+

Why? These originally used native LAPACK bindings that have been removed. Implementing them in pure C# is possible but significant work.

+
+

What's Next: Implementation Roadmap

+

Phase 1: Core Compatibility (Current Focus)

+
    +
  • Fix type promotion to match NEP 50
  • +
  • Add Array API function aliases
  • +
  • Implement isdtype(), unique_* family
  • +
  • Add .mT and .device properties
  • +
+

Phase 2: Feature Completeness

+
    +
  • Complex number support (complex64, complex128)
  • +
  • datetime64 / timedelta64 types
  • +
  • Complete missing Array API functions
  • +
+

Phase 3: Linear Algebra

+
    +
  • Implement matrix decompositions (QR, SVD, etc.)
  • +
  • Either pure C# or via Math.NET Numerics integration
  • +
+

Phase 4: Performance

+
    +
  • SIMD optimization for element-wise operations
  • +
  • Iterator optimization for non-contiguous arrays
  • +
+
+

How You Can Help

+

NumSharp is open source. Here's how to contribute:

+
    +
  1. Report incompatibilities. If NumSharp behaves differently from NumPy, file an issue with both code snippets.

    +
  2. +
  3. Add tests. Write tests that verify NumPy behavior, then make them pass in NumSharp.

    +
  4. +
  5. Implement missing functions. Check the milestones for prioritized work.

    +
  6. +
+

GitHub Milestones

+ +
+

References

+ + +
+ +
+
+ + + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/docs/extensions/bitmap.html b/docs/website/docs/extensions/bitmap.html new file mode 100644 index 000000000..8454d1254 --- /dev/null +++ b/docs/website/docs/extensions/bitmap.html @@ -0,0 +1,448 @@ + + + + + NumSharp.Bitmap | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+

NumSharp.Bitmap

+ +

The NumSharp.Bitmap package provides seamless conversion between System.Drawing.Bitmap and NDArray. If you're working with images in .NET—loading them, processing pixels, applying filters, or feeding them to ML models—this extension makes it easy to move data between the image world and the array world.

+
+

Installation

+

NumSharp.Bitmap is a separate NuGet package:

+
dotnet add package NumSharp.Bitmap
+
+
+

Platform Note: This extension uses System.Drawing.Common, which is only fully supported on Windows. On Linux/macOS, you'll need additional setup (libgdiplus) or consider alternatives like ImageSharp.

+
+
+

Quick Start

+
using System.Drawing;
+using NumSharp;
+
+// Load an image and convert to NDArray
+var bitmap = new Bitmap("photo.jpg");
+var pixels = bitmap.ToNDArray();
+// Shape: (1, height, width, channels)
+// e.g., (1, 480, 640, 3) for a 640x480 RGB image
+
+// Manipulate the pixel data
+var brightened = (pixels.astype(NPTypeCode.Int32) + 50).clip(0, 255).astype(NPTypeCode.Byte);
+
+// Convert back to Bitmap
+var result = brightened.ToBitmap();
+result.Save("brightened.jpg");
+
+
+

Converting Bitmaps to NDArrays

+

Bitmap.ToNDArray()

+

The primary method for converting images to arrays.

+
public static NDArray ToNDArray(
+    this Bitmap image,
+    bool flat = false,
+    bool copy = true,
+    bool discardAlpha = false
+)
+
+

Parameters:

+ + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterDefaultDescription
flatfalseIf true, returns 1-D array of pixels: R1G1B1R2G2B2...
copytrueIf true, copies pixel data. If false, wraps bitmap memory directly.
discardAlphafalseIf true, strips the alpha channel (4th channel) from 32bpp images.
+

Return Shape:

+
    +
  • flat=false: (1, height, width, channels) — 4-D tensor suitable for ML models
  • +
  • flat=true: (height * width * channels,) — 1-D array of raw pixel bytes
  • +
+

Examples

+

Standard conversion (recommended for most uses):

+
var bitmap = new Bitmap("image.png");
+var nd = bitmap.ToNDArray();
+
+Console.WriteLine(nd.shape);  // e.g., (1, 480, 640, 4) for 32bpp ARGB
+Console.WriteLine(nd.dtype);  // Byte
+
+

Discard alpha channel:

+
// 32bpp ARGB → 3 channels (RGB only)
+var rgb = bitmap.ToNDArray(discardAlpha: true);
+Console.WriteLine(rgb.shape);  // (1, 480, 640, 3)
+
+

Flat pixel array:

+
// For algorithms that expect 1-D input
+var flat = bitmap.ToNDArray(flat: true);
+Console.WriteLine(flat.ndim);  // 1
+
+

Zero-copy mode (advanced):

+
// Wraps bitmap memory directly — faster but risky
+var wrapped = bitmap.ToNDArray(copy: false);
+// WARNING: The NDArray becomes invalid if the bitmap is disposed
+// or modified. The bitmap remains locked until the NDArray is GC'd.
+
+

Memory Layout

+

The pixel data is in BGR/BGRA order (Windows GDI convention), not RGB:

+
var nd = bitmap.ToNDArray();
+// nd[0, y, x, 0] = Blue
+// nd[0, y, x, 1] = Green
+// nd[0, y, x, 2] = Red
+// nd[0, y, x, 3] = Alpha (if 32bpp)
+
+

If you need RGB order for ML models, swap the channels:

+
// BGRA → RGBA
+var rgba = nd[Slice.All, Slice.All, Slice.All, new int[] {2, 1, 0, 3}];
+
+
+

Converting NDArrays to Bitmaps

+

NDArray.ToBitmap()

+

Converts an NDArray back to a Bitmap.

+
public static Bitmap ToBitmap(
+    this NDArray nd,
+    int width,
+    int height,
+    PixelFormat format = PixelFormat.DontCare
+)
+
+// Overload that infers dimensions from shape
+public static Bitmap ToBitmap(
+    this NDArray nd,
+    PixelFormat format = PixelFormat.DontCare
+)
+
+

Requirements:

+
    +
  • NDArray must be 4-D: (1, height, width, channels)
  • +
  • First dimension must be 1 (single image)
  • +
  • dtype should be Byte
  • +
  • Channels must match the pixel format (3 for 24bpp, 4 for 32bpp)
  • +
+

Examples

+

Basic conversion:

+
var nd = np.zeros(1, 100, 200, 3).astype(NPTypeCode.Byte);
+var bitmap = nd.ToBitmap();
+// Infers: 200x100 image, 24bpp RGB
+
+

Explicit format:

+
var nd = np.zeros(1, 100, 200, 4).astype(NPTypeCode.Byte);
+var bitmap = nd.ToBitmap(200, 100, PixelFormat.Format32bppArgb);
+
+

From flat array:

+
// If you have a 1-D array, provide dimensions and format
+var flat = np.arange(0, 200 * 100 * 3).astype(NPTypeCode.Byte);
+var bitmap = flat.ToBitmap(200, 100, PixelFormat.Format24bppRgb);
+
+

Supported Pixel Formats

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FormatChannelsBytes/Pixel
Format24bppRgb33
Format32bppArgb44
Format32bppPArgb44
Format32bppRgb44
Format48bppRgb36
Format64bppArgb48
Format64bppPArgb48
+
+

Working with BitmapData Directly

+

For performance-critical code, you can work with BitmapData directly.

+

BitmapData.AsNDArray()

+

Wraps locked bitmap data as an NDArray without copying.

+
var bitmap = new Bitmap("image.png");
+var bmpData = bitmap.LockBits(
+    new Rectangle(0, 0, bitmap.Width, bitmap.Height),
+    ImageLockMode.ReadOnly,
+    bitmap.PixelFormat
+);
+
+try
+{
+    var nd = bmpData.AsNDArray(flat: false, discardAlpha: false);
+    // Process pixels...
+    // WARNING: nd is only valid while bits are locked!
+}
+finally
+{
+    bitmap.UnlockBits(bmpData);
+}
+
+
+

Warning: The NDArray points directly to bitmap memory. If you call UnlockBits(), the NDArray becomes invalid and accessing it causes undefined behavior.

+
+
+

Common Patterns

+

Image Preprocessing for ML

+
// Load and normalize for neural network input
+var bitmap = new Bitmap("input.jpg");
+var nd = bitmap.ToNDArray(discardAlpha: true);  // (1, H, W, 3)
+
+// Normalize to [0, 1] range
+var normalized = nd.astype(NPTypeCode.Single) / 255.0f;
+
+// Resize would require additional libraries (not built into NumSharp)
+
+

Grayscale Conversion

+
var bitmap = new Bitmap("color.jpg");
+var rgb = bitmap.ToNDArray(discardAlpha: true);  // (1, H, W, 3)
+
+// Luminance formula: 0.299*R + 0.587*G + 0.114*B
+// Note: GDI uses BGR order, so channels are [B, G, R]
+var b = rgb[Slice.All, Slice.All, Slice.All, 0].astype(NPTypeCode.Single);
+var g = rgb[Slice.All, Slice.All, Slice.All, 1].astype(NPTypeCode.Single);
+var r = rgb[Slice.All, Slice.All, Slice.All, 2].astype(NPTypeCode.Single);
+
+var gray = (0.114f * b + 0.587f * g + 0.299f * r).astype(NPTypeCode.Byte);
+// Shape: (1, H, W) - single channel
+
+

Batch Processing

+
// Process multiple images
+var files = Directory.GetFiles("images/", "*.jpg");
+var batch = new List<NDArray>();
+
+foreach (var file in files)
+{
+    using var bitmap = new Bitmap(file);
+    var nd = bitmap.ToNDArray(discardAlpha: true);
+    batch.Add(nd);
+}
+
+// Stack into batch: (N, H, W, 3)
+// Note: All images must have same dimensions
+var batchArray = np.concatenate(batch.ToArray(), axis: 0);
+
+

Round-Trip (Load, Process, Save)

+
// Load
+var original = new Bitmap("photo.jpg");
+var nd = original.ToNDArray();
+
+// Process: invert colors
+var inverted = (255 - nd.astype(NPTypeCode.Int32)).clip(0, 255).astype(NPTypeCode.Byte);
+
+// Save
+var result = inverted.ToBitmap();
+result.Save("inverted.jpg", ImageFormat.Jpeg);
+
+
+

Known Limitations

+

Platform Support

+

System.Drawing.Common is Windows-only in .NET 6+. On other platforms:

+
// This throws PlatformNotSupportedException on Linux/macOS
+var bitmap = new Bitmap("image.png");
+
+

Workarounds:

+
    +
  • Use libgdiplus on Linux (limited compatibility)
  • +
  • Use ImageSharp or SkiaSharp (different API, not covered by this extension)
  • +
+

Stride Padding

+

Bitmaps may have stride padding (row alignment to 4-byte boundaries). The extension handles this in most cases, but odd-width 24bpp images may have issues with copy: true. Use copy: false for odd-width images.

+

Color Order

+

Windows bitmaps use BGR/BGRA byte order, not RGB. If your ML model expects RGB, you need to swap channels manually.

+

No Resize

+

NumSharp doesn't include image resizing. You'll need to resize in System.Drawing before converting, or use a library like ImageSharp.

+
+

API Reference

+

Extension Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + +
MethodDescription
Bitmap.ToNDArray(...)Convert Bitmap to NDArray
Image.ToNDArray(...)Convert Image to NDArray (creates Bitmap internally)
BitmapData.AsNDArray(...)Wrap locked BitmapData as NDArray (no copy)
NDArray.ToBitmap(...)Convert NDArray to Bitmap
+

Helper Methods

+ + + + + + + + + + + + + +
MethodDescription
PixelFormat.ToBytesPerPixel()Get bytes per pixel for a format
+ +
+ +
+
+ + + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/docs/extensions/index.html b/docs/website/docs/extensions/index.html new file mode 100644 index 000000000..d7d4e5561 --- /dev/null +++ b/docs/website/docs/extensions/index.html @@ -0,0 +1,142 @@ + + + + + Extending Libraries | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+

Extending Libraries

+ +

NumSharp is designed to integrate with the broader .NET ecosystem. Extension packages bridge NumSharp arrays with platform-specific features and external libraries.

+

Official Extensions

+ + + + + + + + + + + + + +
PackagePurpose
NumSharp.BitmapImage ↔ NDArray conversion via System.Drawing
+

Build Your Own

+

NumSharp exposes low-level memory access for integration with native libraries, GPU frameworks, or domain-specific formats:

+
// Access raw memory for interop
+byte* ptr = (byte*)ndarray.Unsafe.Address;
+
+// Wrap external memory as NDArray
+var nd = new NDArray(new ArraySlice<byte>(
+    new UnmanagedMemoryBlock<byte>(ptr, length, onDispose)
+));
+
+

Have an extension to share? Open a PR to add it to this list.

+ +
+ +
+
+ + + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/docs/intro.html b/docs/website/docs/intro.html new file mode 100644 index 000000000..c1554f8ed --- /dev/null +++ b/docs/website/docs/intro.html @@ -0,0 +1,169 @@ + + + + + Introduction | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+
Table of Contents
+ +
+
+ +
+
+
+ +
+
+ + + +
+ +
+

Introduction

+ +

The following pages are for the users who want to use NumSharp.

+

Before you read the code examples you should read this page which explain some basis concepts. +An other reference can be numpy since we try our best to follow their APIs (High level - not lower level).

+

NDArray, NDStorgage and Shape

+

The 3 main classes in NumSharp are NDArray, NDStorage and Shape. +If you want to have a better understanding for NumSharp, you can read the following lines to see how all works together.

+

Let's start with the question - what is a Tensor?

+

From programming point of view a tensor is a multi-dimensional array (scalar, vector, matrix, ...) mostly for numerical data like int32, int64, doubles, ... which can be accessed via indexes like np[idx], np[idx,jdx], np[idx,jdx,kdx], ... depending on its dimension.

+

Ok - in this sentence we got already some properties.

+
    +
  • a tensor is an object for storing (mostly) numerical data
  • +
  • a tensor has a dimension
  • +
  • the dimension decides how many indexes are necessary to access the stored data
  • +
+

Each tensor type (dimension 1 - vector, dimension 2 - matrix, ...) has its own .NET type like double[,].

+

NumSharp brings its own tensor / array type called NDArray.

+

So now the question - .NET offers already multi-dimensional arrays - why a new array type?

+

NumSharps NDArray offers the capability of storing any tensor (independent of dimension!) into its internal storage. +So NumSharps NDArray can store a vector, a matrix or sth with dimension 5 and higher. This is not possible with .NET arrays since each tensor type is a different class. This offers users the possibility to use same methods for different tensor types.

+

Now the next question - how a NDArray can do this?

+

First of all we need to be a little bit more abstract. Why we use tensors? Because we want to store data and we want to get them. How we get and set them? We get and set via indexes (which are always integers). So just this data are important and the corresponding indexes. That's it. Data + Indexes. :)

+

With this in mind we easily can understand the NDStorage of NumSharp.

+

NDStorage is an object which stores the data of a tesor in a single 1D array. Since it is a 1D array independend of the tensor dimension NDStorage can be used for all kind of tensors. A vector is stored inside a 1D array, a matrix, a 3 dimensional tensor and so on.

+

But hold on! How the data comes into this 1D arrayand how we get them back?

+

NDStorage has a property called "shape". The shape is a small but important class in NumSharp. It stores the dimensions and most important! it determines which element in the 1D array is selected by given indexes.

+

To understand the methods for determines 1D internal storage index by NDArray indexes and vice versa we give examples of different tensor types.

+

Vector

+

Imagine a 1D tensor (a vector). Here it is easy because you can access the data with a single index like 'a = np[idx]'. The internal data store in NDStorage is a 1D array - so index to access is the same index in internal storage.

+

Matrix

+

Here it is a little bit more tricky. Each data element is stored by 2 indexes like np[idx,jdx] = 5. The internal storage is a 1D array so .... there must be a way to map the 2 indexes [idx,jdx] at NDArray level to a single index [kdx] in NDStorage level.

+

Indeed there is!

+

Not just in NumSharp but also in many other frameworks, libs or (general spoken) languages it is good style to store the elements of a matrix row wise or column wise into a 1D array. For a more professional description you can check https://en.wikipedia.org/wiki/Row-_and_column-major_order. Row wise Layout and column wise layout often also called row major and column major.

+

General spoken when imagine a matrix as a table - Row wise means that you start with element [0,0] (as your first element in 1D array) and take elements from columns of 1st row (and store them in the 1D array) until all elements of the 1st row are stored inside the 1D array. You go on with the 2nd row - take element [1,0],[1,1],[1,2],...,[1,n-1]. Go on with this pattern until all elements are inside the 1D array.

+

Column wise also starts with the element [0,0] but! it stays in the 1st column and takes elements along the rows until all elements from 1st column is stored. Repeat this with 2nd column, 3rd and so on.

+

The image below (taken from https://en.wikipedia.org/wiki/File:Row_and_column_major_order.svg) shows again the 'algorithm' for storing data from matrix to vector.

+

Row Wise Column Wise

+

N dim tensor

+

Now we come to the most tricky question - how to store a general n dimensional tensor inside a 1D array.

+

Short anwser - exactly like a matrix - just more generalized.

+

First we look again the row wise order.

+

[0,0] -> [0,1] -> [0,2] -> [0,3] -> [0,n-1] -> [1,0] -> [1,1] -> [1,2] -> [1,3] -> ...

+

So here we stay in one dimension (the first / rows) and fill the other dimensions until the dimension is full. +After we switch to the next higher level of dimension (so change to next row).

+

For higher dimensions like 3D - NumSharp follow this pattern.

+

[0,0,0] -> [0,0,1] -> [0,0,2] -> [0,0,3] -> [0,0,n-1] -> [0,1,0] -> [0,1,1] -> [0,1,n-1] -> [0,2,0] -> [0,2,n-1] -> [0,m-1,0] -> ...

+

General spoken - you can image it as a backward filling layout.

+

As you can see the dimensions are filled beginning from last dimension, if one dimension is full, the dimension before is increased.

+

Next we look the column wise order.

+

[0,0] -> [1,0] -> [2,0] -> [3,0] -> [n-1,0] -> [0,1] -> [1,1] -> [2,1] -> [3,1] -> ...

+

Again we stay in one dimension but here in the last / column. The rows are filled until the 1st column is full and next dimension is increased.

+

So fill first dimension, increase next, fill again, etc. also in n dimensional tensor.

+

[0,0,0] -> [1,0,0] -> [2,0,0] -> [3,0,0] -> [n-1,0,0] -> [0,1,0] -> [1,1,0] -> [n-1,1,0] -> [0,2,0] -> [n-1,2,0] -> [0,m-1,0] ->

+

And this you can imagine as forward filling layout.

+

That's it. Now you have enough knowledge about NDArray, NDStorage and Shape. Check the other chapters for a how to use. :)

+ +
+ +
+
+ + + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/docs/toc.html b/docs/website/docs/toc.html new file mode 100644 index 000000000..570f21b89 --- /dev/null +++ b/docs/website/docs/toc.html @@ -0,0 +1,41 @@ + +
+
+
+
+ + + +
+
+ +
+
diff --git a/docs/website/docs/toc.json b/docs/website/docs/toc.json new file mode 100644 index 000000000..1c6993b93 --- /dev/null +++ b/docs/website/docs/toc.json @@ -0,0 +1,2 @@ + +{"items":[{"name":"Introduction","href":"intro.html","topicHref":"intro.html"},{"name":"Broadcasting","href":"broadcasting.html","topicHref":"broadcasting.html"},{"name":"NumPy Compliance & Compatibility","href":"compliance.html","topicHref":"compliance.html"},{"name":"Array API Standard","href":"array-api-standard.html","topicHref":"array-api-standard.html"},{"name":"Extending Libraries","href":"extensions/index.html","topicHref":"extensions/index.html","items":[{"name":"NumSharp.Bitmap","href":"extensions/bitmap.html","topicHref":"extensions/bitmap.html"}],"expanded":false}]} diff --git a/docs/favicon.ico b/docs/website/favicon.ico similarity index 100% rename from docs/favicon.ico rename to docs/website/favicon.ico diff --git a/docs/fonts/glyphicons-halflings-regular.eot b/docs/website/fonts/glyphicons-halflings-regular.eot similarity index 100% rename from docs/fonts/glyphicons-halflings-regular.eot rename to docs/website/fonts/glyphicons-halflings-regular.eot diff --git a/docs/fonts/glyphicons-halflings-regular.svg b/docs/website/fonts/glyphicons-halflings-regular.svg similarity index 100% rename from docs/fonts/glyphicons-halflings-regular.svg rename to docs/website/fonts/glyphicons-halflings-regular.svg diff --git a/docs/fonts/glyphicons-halflings-regular.ttf b/docs/website/fonts/glyphicons-halflings-regular.ttf similarity index 100% rename from docs/fonts/glyphicons-halflings-regular.ttf rename to docs/website/fonts/glyphicons-halflings-regular.ttf diff --git a/docs/fonts/glyphicons-halflings-regular.woff b/docs/website/fonts/glyphicons-halflings-regular.woff similarity index 100% rename from docs/fonts/glyphicons-halflings-regular.woff rename to docs/website/fonts/glyphicons-halflings-regular.woff diff --git a/docs/fonts/glyphicons-halflings-regular.woff2 b/docs/website/fonts/glyphicons-halflings-regular.woff2 similarity index 100% rename from docs/fonts/glyphicons-halflings-regular.woff2 rename to docs/website/fonts/glyphicons-halflings-regular.woff2 diff --git a/docs/website/images/Logo.md b/docs/website/images/Logo.md new file mode 100644 index 000000000..b08b0758e --- /dev/null +++ b/docs/website/images/Logo.md @@ -0,0 +1 @@ +NumSharp logo (c) 2019 by Meinrad Recheis. \ No newline at end of file diff --git a/docs/images/linear regression ploting.png b/docs/website/images/linear regression ploting.png similarity index 100% rename from docs/images/linear regression ploting.png rename to docs/website/images/linear regression ploting.png diff --git a/docs/images/maxresdefault_LI.jpg b/docs/website/images/maxresdefault_LI.jpg similarity index 100% rename from docs/images/maxresdefault_LI.jpg rename to docs/website/images/maxresdefault_LI.jpg diff --git a/docs/website/images/numsharp.icon.svg b/docs/website/images/numsharp.icon.svg new file mode 100644 index 000000000..2be77864c --- /dev/null +++ b/docs/website/images/numsharp.icon.svg @@ -0,0 +1,238 @@ + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/website/images/numsharp.icon128.png b/docs/website/images/numsharp.icon128.png new file mode 100644 index 000000000..b8b689e00 Binary files /dev/null and b/docs/website/images/numsharp.icon128.png differ diff --git a/docs/website/images/numsharp.icon512.png b/docs/website/images/numsharp.icon512.png new file mode 100644 index 000000000..f697f3b57 Binary files /dev/null and b/docs/website/images/numsharp.icon512.png differ diff --git a/docs/website/images/numsharp.logo.png b/docs/website/images/numsharp.logo.png new file mode 100644 index 000000000..001295393 Binary files /dev/null and b/docs/website/images/numsharp.logo.png differ diff --git a/docs/website/images/numsharp.logo.svg b/docs/website/images/numsharp.logo.svg new file mode 100644 index 000000000..2e8791be2 --- /dev/null +++ b/docs/website/images/numsharp.logo.svg @@ -0,0 +1,296 @@ + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/website/images/numsharp.logo512.png b/docs/website/images/numsharp.logo512.png new file mode 100644 index 000000000..26772e4d0 Binary files /dev/null and b/docs/website/images/numsharp.logo512.png differ diff --git a/docs/website/images/python-csharp-comparision.png b/docs/website/images/python-csharp-comparision.png new file mode 100644 index 000000000..87d04283e Binary files /dev/null and b/docs/website/images/python-csharp-comparision.png differ diff --git a/docs/images/rowWise_ColumnWise.png b/docs/website/images/rowWise_ColumnWise.png similarity index 100% rename from docs/images/rowWise_ColumnWise.png rename to docs/website/images/rowWise_ColumnWise.png diff --git a/docs/website/images/slicing/multiple_views.svg b/docs/website/images/slicing/multiple_views.svg new file mode 100644 index 000000000..490f153bc --- /dev/null +++ b/docs/website/images/slicing/multiple_views.svg @@ -0,0 +1,1811 @@ + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + a["3:,6:"] + + + + + + + + + a["1:7,2:7"] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + var a=np.array(data).reshape(9,12); + + + diff --git a/docs/website/images/slicing/repeated_slicing.svg b/docs/website/images/slicing/repeated_slicing.svg new file mode 100644 index 000000000..389088c7a --- /dev/null +++ b/docs/website/images/slicing/repeated_slicing.svg @@ -0,0 +1,1434 @@ + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + var a=np.array(data).reshape(9,12) + var a1=a["2:8,::2"] + + + + + + + + + + + + + + var a2=a1["1::3"] + + + + + + + + + + + + + + + + + + a2[":,2:"] + + + + + diff --git a/docs/website/images/slicing/reshape_and_slice.svg b/docs/website/images/slicing/reshape_and_slice.svg new file mode 100644 index 000000000..6e186f07d --- /dev/null +++ b/docs/website/images/slicing/reshape_and_slice.svg @@ -0,0 +1,975 @@ + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .reshape(3,4,6); + + + a[":,1,1"] + + + + + + + + + + + + + + var a=np.array(new double[72]) + + + diff --git a/docs/website/index.html b/docs/website/index.html new file mode 100644 index 000000000..e5ad9ddc4 --- /dev/null +++ b/docs/website/index.html @@ -0,0 +1,139 @@ + + + + + Welcome to NumSharp | NumSharp Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+ +
+
+ + +
+ +
+

Welcome to NumSharp

+ +

NumSharp is a .NET port of Python's NumPy library, bringing powerful numerical computing to the .NET ecosystem.

+

Why NumSharp?

+
    +
  • NumPy API compatibility - Feel right at home if you're coming from Python
  • +
  • High-performance NDArray - Multi-dimensional arrays stored efficiently in unmanaged memory
  • +
  • Full .NET integration - Works seamlessly with C#, F#, VB.NET, and other .NET languages
  • +
  • Part of the SciSharp ecosystem - Works alongside TensorFlow.NET, ML.NET, and other ML libraries
  • +
+

Quick Start

+
dotnet add package NumSharp
+
+
using NumSharp;
+
+var a = np.array(new int[] { 1, 2, 3, 4, 5 });
+var b = np.arange(5);
+var c = a + b;
+Console.WriteLine(c);  // [1, 3, 5, 7, 9]
+
+

Features

+
    +
  • Array Creation - np.zeros, np.ones, np.arange, np.linspace, and more
  • +
  • Array Manipulation - Reshape, transpose, concatenate, stack operations
  • +
  • Math Operations - Element-wise arithmetic, broadcasting, linear algebra
  • +
  • Slicing & Indexing - NumPy-style slicing with views, not copies
  • +
  • Random Sampling - Full numpy.random compatibility with seed/state matching
  • +
  • File I/O - Load and save .npy and .npz files
  • +
+

Get Started

+ +

Community

+ + +
+ +
+
+ + + +
+ +
+ +
+
+ +
+ + + + diff --git a/docs/website/index.json b/docs/website/index.json new file mode 100644 index 000000000..3771b0b89 --- /dev/null +++ b/docs/website/index.json @@ -0,0 +1,497 @@ +{ + "api/DecimalMath.DecimalEx.html": { + "href": "api/DecimalMath.DecimalEx.html", + "title": "Class DecimalEx | NumSharp Documentation", + "summary": "Class DecimalEx Namespace DecimalMath Assembly NumSharp.dll Contains mathematical operations performed in Decimal precision. public static class DecimalEx Inheritance object DecimalEx Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Fields E The e constant, also known as \"Euler's number\" or \"Napier's constant\" public const decimal E = 2.7182818284590452353602874714 Field Value decimal Remarks Full value is 2.718281828459045235360287471352662497757, see http://mathworld.wolfram.com/e.html Ln10 The value of the natural logarithm of 10. public const decimal Ln10 = 2.3025850929940456840179914547 Field Value decimal Remarks Full value is: 2.30258509299404568401799145468436420760110148862877297603332790096757 From: http://oeis.org/A002392/constant Ln2 The value of the natural logarithm of 2. public const decimal Ln2 = 0.6931471805599453094172321215 Field Value decimal Remarks Full value is: .693147180559945309417232121458176568075500134360255254120680009493393621969694715605863326996418687 From: http://oeis.org/A002162/constant Pi The pi (π) constant. Pi radians is equivalent to 180 degrees. public const decimal Pi = 3.1415926535897932384626433833 Field Value decimal Remarks See http://en.wikipedia.org/wiki/Pi PiHalf π/2 - in radians is equivalent to 90 degrees. public const decimal PiHalf = 1.5707963267948966192313216916 Field Value decimal PiQuarter π/4 - in radians is equivalent to 45 degrees. public const decimal PiQuarter = 0.7853981633974483096156608458 Field Value decimal PiTwelfth π/12 - in radians is equivalent to 15 degrees. public const decimal PiTwelfth = 0.2617993877991494365385536153 Field Value decimal SmallestNonZeroDec Smallest non-zero decimal value. public const decimal SmallestNonZeroDec = 0.0000000000000000000000000001 Field Value decimal TwoPi 2π - in radians is equivalent to 360 degrees. public const decimal TwoPi = 6.2831853071795864769252867666 Field Value decimal Methods ACos(decimal) Returns the angle whose cosine is the specified number. public static decimal ACos(decimal z) Parameters z decimal A number representing a cosine, where -1 ≤d≤ 1. Returns decimal Remarks See http://en.wikipedia.org/wiki/Inverse_trigonometric_function and http://mathworld.wolfram.com/InverseCosine.html AGMean(decimal, decimal) Computes arithmetic-geometric mean which is the convergence of the series of the arithmetic and geometric means and their mean values. public static decimal AGMean(decimal x, decimal y) Parameters x decimal A number. y decimal A number. Returns decimal Remarks See http://en.wikipedia.org/wiki/Arithmetic-geometric_mean Originally implemented to try to get a fast approximation of the natural logarithm: http://en.wikipedia.org/wiki/Natural_logarithm#High_precision But it didn't yield a precise enough answer. ASin(decimal) Returns the angle whose sine is the specified number. public static decimal ASin(decimal z) Parameters z decimal A number representing a sine, where -1 ≤d≤ 1. Returns decimal Remarks See http://en.wikipedia.org/wiki/Inverse_trigonometric_function and http://mathworld.wolfram.com/InverseSine.html I originally used the Taylor series for ASin, but it was extremely slow around -1 and 1 (millions of iterations) and still ends up being less accurate than deriving from the ATan function. ATan(decimal) Returns the angle whose tangent is the quotient of two specified numbers. public static decimal ATan(decimal x) Parameters x decimal A number representing a tangent. Returns decimal Remarks See http://mathworld.wolfram.com/InverseTangent.html for faster converging series from Euler that was used here. ATan2(decimal, decimal) Returns the angle whose tangent is the quotient of two specified numbers. public static decimal ATan2(decimal y, decimal x) Parameters y decimal The y coordinate of a point. x decimal The x coordinate of a point. Returns decimal An angle, θ, measured in radians, such that -π≤θ≤π, and tan(θ) = y / x, where (x, y) is a point in the Cartesian plane. Observe the following: For (x, y) in quadrant 1, 0 < θ < π/2. For (x, y) in quadrant 2, π/2 < θ ≤ π. For (x, y) in quadrant 3, -π < θ < -π/2. For (x, y) in quadrant 4, -π/2 < θ < 0. Abs(decimal) public static decimal Abs(decimal a) Parameters a decimal Returns decimal Average(params decimal[]) Calculates the average of the supplied numbers. public static decimal Average(params decimal[] values) Parameters values decimal[] The numbers to average. Returns decimal Remarks Simply uses LINQ's Average function, but switches to a potentially less accurate method of summing each value divided by the number of values. Ceiling(decimal, int) Returns the ceiling of a Decimal value at the given number of digits. public static decimal Ceiling(decimal value, int places = 0) Parameters value decimal A decimal value. places int An integer representing the maximum number of digits after the decimal point to end up with. Returns decimal Cos(decimal) Returns the cosine of the specified angle. public static decimal Cos(decimal x) Parameters x decimal An angle, measured in radians. Returns decimal Remarks Uses a Taylor series to calculate sine. See http://en.wikipedia.org/wiki/Trigonometric_functions for details. Exp(decimal) Returns e raised to the specified power. public static decimal Exp(decimal d) Parameters d decimal A number specifying a power. Returns decimal Factorial(decimal) Returns the factorial of a number n expressed as n!. Factorial is calculated as follows: n * (n - 1) * (n - 2) * ... * 1 public static decimal Factorial(decimal n) Parameters n decimal An integer. Returns decimal Remarks Only supports non-negative integers. Floor(decimal, int) Returns the floor of a Decimal value at the given number of digits. public static decimal Floor(decimal value, int places = 0) Parameters value decimal A decimal value. places int An integer representing the maximum number of digits after the decimal point to end up with. Returns decimal GCF(decimal, decimal) Calculates the greatest common factor of a and b to the highest level of precision represented by either number. public static decimal GCF(decimal a, decimal b) Parameters a decimal b decimal Returns decimal Remarks If either number is not an integer, the factor sought will be at the same precision as the most precise value. For example, 1.2 and 0.42 will yield 0.06. GCF(decimal, decimal, params decimal[]) Gets the greatest common factor of three or more numbers. public static decimal GCF(decimal a, decimal b, params decimal[] values) Parameters a decimal b decimal values decimal[] Returns decimal GetDecimalPlaces(decimal, bool) Gets the number of decimal places in a decimal value. public static int GetDecimalPlaces(decimal dec, bool countTrailingZeros) Parameters dec decimal countTrailingZeros bool Returns int Remarks Started with something found here: http://stackoverflow.com/a/6092298/856595 Log(decimal) Returns the natural (base e) logarithm of a specified number. public static decimal Log(decimal d) Parameters d decimal A number whose logarithm is to be found. Returns decimal Remarks I'm still not satisfied with the speed. I tried several different algorithms that you can find in a historical version of this source file. The one I settled on was the best of mediocrity. Log(decimal, decimal) Returns the logarithm of a specified number in a specified base. public static decimal Log(decimal d, decimal newBase) Parameters d decimal A number whose logarithm is to be found. newBase decimal The base of the logarithm. Returns decimal Remarks This is a relatively naive implementation that simply divides the natural log of d by the natural log of the base. Log10(decimal) Returns the base 10 logarithm of a specified number. public static decimal Log10(decimal d) Parameters d decimal A number whose logarithm is to be found. Returns decimal Log2(decimal) Returns the base 2 logarithm of a specified number. public static decimal Log2(decimal d) Parameters d decimal A number whose logarithm is to be found. Returns decimal NormalizeAngle(decimal) Normalizes an angle in radians to the 0 to 2Pi interval. public static decimal NormalizeAngle(decimal radians) Parameters radians decimal Angle in radians. Returns decimal NormalizeAngleDeg(decimal) Normalizes an angle in degrees to the 0 to 360 degree interval. public static decimal NormalizeAngleDeg(decimal degrees) Parameters degrees decimal Angle in degrees. Returns decimal Pow(decimal, decimal) Returns a specified number raised to the specified power. public static decimal Pow(decimal x, decimal y) Parameters x decimal A number to be raised to a power. y decimal A number that specifies a power. Returns decimal Remainder(decimal, decimal) Gets the remainder of one number divided by another number in such a way as to retain maximum precision. public static decimal Remainder(decimal d1, decimal d2) Parameters d1 decimal d2 decimal Returns decimal Sin(decimal) Returns the sine of the specified angle. public static decimal Sin(decimal x) Parameters x decimal An angle, measured in radians. Returns decimal Remarks Uses a Taylor series to calculate sine. See http://en.wikipedia.org/wiki/Trigonometric_functions for details. SolveQuadratic(decimal, decimal, decimal) Uses the quadratic formula to factor and solve the equation ax^2 + bx + c = 0 public static decimal[] SolveQuadratic(decimal a, decimal b, decimal c) Parameters a decimal The coefficient of x^2. b decimal The coefficient of x. c decimal The constant. Returns decimal[] Remarks Will return empty results where there is no solution and for complex solutions. See http://www.wikihow.com/Factor-Second-Degree-Polynomials-%28Quadratic-Equations%29 Sqrt(decimal) Returns the square root of a given number. public static decimal Sqrt(decimal s) Parameters s decimal A non-negative number. Returns decimal Remarks Uses an implementation of the \"Babylonian Method\". See http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method Tan(decimal) Returns the tangent of the specified angle. public static decimal Tan(decimal radians) Parameters radians decimal An angle, measured in radians. Returns decimal Remarks Uses a Taylor series to calculate sine. See http://en.wikipedia.org/wiki/Trigonometric_functions for details. ToDeg(decimal) Converts radians to degrees. (π radians = 180 degrees) public static decimal ToDeg(decimal radians) Parameters radians decimal The radians to convert. Returns decimal ToRad(decimal) Converts degrees to radians. (π radians = 180 degrees) public static decimal ToRad(decimal degrees) Parameters degrees decimal The degrees to convert. Returns decimal" + }, + "api/DecimalMath.html": { + "href": "api/DecimalMath.html", + "title": "Namespace DecimalMath | NumSharp Documentation", + "summary": "Namespace DecimalMath Classes DecimalEx Contains mathematical operations performed in Decimal precision." + }, + "api/NumSharp.AxisOutOfRangeException.html": { + "href": "api/NumSharp.AxisOutOfRangeException.html", + "title": "Class AxisOutOfRangeException | NumSharp Documentation", + "summary": "Class AxisOutOfRangeException Namespace NumSharp Assembly NumSharp.dll public class AxisOutOfRangeException : ArgumentOutOfRangeException, ISerializable, INumSharpException Inheritance object Exception SystemException ArgumentException ArgumentOutOfRangeException AxisOutOfRangeException Implements ISerializable INumSharpException Inherited Members ArgumentOutOfRangeException.ThrowIfEqual(T, T, string) ArgumentOutOfRangeException.ThrowIfGreaterThan(T, T, string) ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(T, T, string) ArgumentOutOfRangeException.ThrowIfLessThan(T, T, string) ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(T, T, string) ArgumentOutOfRangeException.ThrowIfNegative(T, string) ArgumentOutOfRangeException.ThrowIfNegativeOrZero(T, string) ArgumentOutOfRangeException.ThrowIfNotEqual(T, T, string) ArgumentOutOfRangeException.ThrowIfZero(T, string) ArgumentOutOfRangeException.ActualValue ArgumentOutOfRangeException.Message ArgumentException.ThrowIfNullOrEmpty(string, string) ArgumentException.ThrowIfNullOrWhiteSpace(string, string) ArgumentException.ParamName Exception.GetBaseException() Exception.GetType() Exception.ToString() Exception.Data Exception.HelpLink Exception.HResult Exception.InnerException Exception.Source Exception.StackTrace Exception.TargetSite Exception.SerializeObjectState object.Equals(object) object.Equals(object, object) object.GetHashCode() object.MemberwiseClone() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) Constructors AxisOutOfRangeException() public AxisOutOfRangeException() AxisOutOfRangeException(int, int) public AxisOutOfRangeException(int ndim, int axis) Parameters ndim int axis int AxisOutOfRangeException(string) public AxisOutOfRangeException(string message) Parameters message string" + }, + "api/NumSharp.BackendType.html": { + "href": "api/NumSharp.BackendType.html", + "title": "Enum BackendType | NumSharp Documentation", + "summary": "Enum BackendType Namespace NumSharp Assembly NumSharp.dll public enum BackendType Extension Methods LinqExtensions.Yield(T) Fields Default = 0 Pure micro-optimized C# implementation." + }, + "api/NumSharp.Backends.BackendFactory.html": { + "href": "api/NumSharp.Backends.BackendFactory.html", + "title": "Class BackendFactory | NumSharp Documentation", + "summary": "Class BackendFactory Namespace NumSharp.Backends Assembly NumSharp.dll public class BackendFactory Inheritance object BackendFactory Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Methods GetEngine(BackendType) public static TensorEngine GetEngine(BackendType backendType = BackendType.Default) Parameters backendType BackendType Returns TensorEngine GetEngine() public static TensorEngine GetEngine() where T : TensorEngine, new() Returns TensorEngine Type Parameters T" + }, + "api/NumSharp.Backends.DefaultEngine.html": { + "href": "api/NumSharp.Backends.DefaultEngine.html", + "title": "Class DefaultEngine | NumSharp Documentation", + "summary": "Class DefaultEngine Namespace NumSharp.Backends Assembly NumSharp.dll Default Tensor Engine implemented in pure micro-optimized C#. public class DefaultEngine : TensorEngine Inheritance object TensorEngine DefaultEngine Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Fields ParallelAbove The threshold atwhich after n-items in an array, computation will use Parallel.For public const int ParallelAbove = 84999 Field Value int Methods ACos(in NDArray, NPTypeCode?) public override NDArray ACos(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray ACos(in NDArray, Type) public override NDArray ACos(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray AMax(in NDArray, int, Type, bool) public override NDArray AMax(in NDArray nd, int axis, Type dtype, bool keepdims = false) Parameters nd NDArray axis int dtype Type keepdims bool Returns NDArray AMax(in NDArray, int?, NPTypeCode?, bool) public override NDArray AMax(in NDArray nd, int? axis = null, NPTypeCode? typeCode = null, bool keepdims = false) Parameters nd NDArray axis int? typeCode NPTypeCode? keepdims bool Returns NDArray AMaxElementwise(NDArray, NPTypeCode?) public T AMaxElementwise(NDArray arr, NPTypeCode? typeCode) where T : unmanaged Parameters arr NDArray typeCode NPTypeCode? Returns T Type Parameters T AMin(in NDArray, int, Type, bool) public override NDArray AMin(in NDArray nd, int axis, Type dtype, bool keepdims = false) Parameters nd NDArray axis int dtype Type keepdims bool Returns NDArray AMin(in NDArray, int?, NPTypeCode?, bool) public override NDArray AMin(in NDArray nd, int? axis = null, NPTypeCode? typeCode = null, bool keepdims = false) Parameters nd NDArray axis int? typeCode NPTypeCode? keepdims bool Returns NDArray AMinElementwise(NDArray, NPTypeCode?) public T AMinElementwise(NDArray arr, NPTypeCode? typeCode) where T : unmanaged Parameters arr NDArray typeCode NPTypeCode? Returns T Type Parameters T ASin(in NDArray, NPTypeCode?) public override NDArray ASin(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray ASin(in NDArray, Type) public override NDArray ASin(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray ATan(in NDArray, NPTypeCode?) public override NDArray ATan(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray ATan(in NDArray, Type) public override NDArray ATan(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray ATan2(in NDArray, in NDArray, NPTypeCode?) public override NDArray ATan2(in NDArray y, in NDArray x, NPTypeCode? typeCode = null) Parameters y NDArray x NDArray typeCode NPTypeCode? Returns NDArray ATan2(in NDArray, in NDArray, Type) public override NDArray ATan2(in NDArray y, in NDArray x, Type dtype) Parameters y NDArray x NDArray dtype Type Returns NDArray Abs(in NDArray, NPTypeCode?) public override NDArray Abs(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Abs(in NDArray, Type) public override NDArray Abs(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Add(in NDArray, in NDArray) public override NDArray Add(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray AddBoolean(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray AddBoolean(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray AddByte(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray AddByte(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray AddChar(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray AddChar(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray AddDecimal(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray AddDecimal(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray AddDouble(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray AddDouble(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray AddInt16(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray AddInt16(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray AddInt32(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray AddInt32(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray AddInt64(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray AddInt64(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray AddSingle(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray AddSingle(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray AddUInt16(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray AddUInt16(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray AddUInt32(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray AddUInt32(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray AddUInt64(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray AddUInt64(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray All(NDArray) Test whether all array elements evaluate to True. public override bool All(NDArray nd) Parameters nd NDArray Returns bool All(NDArray, int) Test whether all array elements along a given axis evaluate to True. public override NDArray All(NDArray nd, int axis) Parameters nd NDArray axis int Returns NDArray Returns an array of bools AllClose(NDArray, NDArray, double, double, bool) Returns True if two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers.The relative difference (rtol * abs(b)) and the absolute difference atol are added together to compare against the absolute difference between a and b. If either array contains one or more NaNs, False is returned. Infs are treated as equal if they are in the same place and of the same sign in both arrays. public override bool AllClose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false) Parameters a NDArray b NDArray Input array to compare with a. rtol double The relative tolerance parameter(see Notes) atol double The absolute tolerance parameter(see Notes) equal_nan bool Whether to compare NaN's as equal. If True, NaN's in a will be considered equal to NaN's in b in the output array. Returns bool AreBroadcastable(params NDArray[]) public static bool AreBroadcastable(params NDArray[] arrays) Parameters arrays NDArray[] Returns bool Remarks Based on https://docs.scipy.org/doc/numpy-1.16.1/user/basics.broadcasting.html AreBroadcastable(params Shape[]) public static bool AreBroadcastable(params Shape[] shapes) Parameters shapes Shape[] Returns bool Remarks Based on https://docs.scipy.org/doc/numpy-1.16.1/user/basics.broadcasting.html AreBroadcastable(params int[][]) public static bool AreBroadcastable(params int[][] shapes) Parameters shapes int[][] Returns bool Remarks Based on https://docs.scipy.org/doc/numpy-1.16.1/user/basics.broadcasting.html ArgMax(in NDArray) public override NDArray ArgMax(in NDArray a) Parameters a NDArray Returns NDArray ArgMax(in NDArray, int) public override NDArray ArgMax(in NDArray a, int axis) Parameters a NDArray axis int Returns NDArray ArgMaxElementwise(NDArray) public int ArgMaxElementwise(NDArray arr) Parameters arr NDArray Returns int ArgMin(in NDArray) public override NDArray ArgMin(in NDArray a) Parameters a NDArray Returns NDArray ArgMin(in NDArray, int) public override NDArray ArgMin(in NDArray a, int axis) Parameters a NDArray axis int Returns NDArray ArgMinElementwise(NDArray) public int ArgMinElementwise(NDArray arr) Parameters arr NDArray Returns int Broadcast(params NDArray[]) public static NDArray[] Broadcast(params NDArray[] arrays) Parameters arrays NDArray[] Returns NDArray[] Remarks Based on https://docs.scipy.org/doc/numpy-1.16.1/user/basics.broadcasting.html Broadcast(Shape, Shape) public static (Shape LeftShape, Shape RightShape) Broadcast(Shape leftShape, Shape rightShape) Parameters leftShape Shape rightShape Shape Returns (Shape LeftShape, Shape RightShape) Remarks Based on https://docs.scipy.org/doc/numpy-1.16.1/user/basics.broadcasting.html Broadcast(params Shape[]) public static Shape[] Broadcast(params Shape[] shapes) Parameters shapes Shape[] Returns Shape[] Remarks Based on https://docs.scipy.org/doc/numpy-1.16.1/user/basics.broadcasting.html Cast(NDArray, NPTypeCode, bool) public override NDArray Cast(NDArray nd, NPTypeCode dtype, bool copy) Parameters nd NDArray dtype NPTypeCode copy bool Returns NDArray Cast(NDArray, Type, bool) public override NDArray Cast(NDArray nd, Type dtype, bool copy) Parameters nd NDArray dtype Type copy bool Returns NDArray Ceil(in NDArray, NPTypeCode?) public override NDArray Ceil(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Ceil(in NDArray, Type) public override NDArray Ceil(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Clip(in NDArray, in ValueType, in ValueType, NPTypeCode?) public override NDArray Clip(in NDArray lhs, in ValueType min, in ValueType max, NPTypeCode? typeCode = null) Parameters lhs NDArray min ValueType max ValueType typeCode NPTypeCode? Returns NDArray Clip(in NDArray, in ValueType, in ValueType, Type) public override NDArray Clip(in NDArray lhs, in ValueType min, in ValueType max, Type dtype) Parameters lhs NDArray min ValueType max ValueType dtype Type Returns NDArray ClipNDArray(in NDArray, in NDArray, in NDArray, NPTypeCode?, NDArray) public override NDArray ClipNDArray(in NDArray lhs, in NDArray min, in NDArray max, NPTypeCode? typeCode = null, NDArray @out = null) Parameters lhs NDArray min NDArray max NDArray typeCode NPTypeCode? out NDArray Returns NDArray ClipNDArray(in NDArray, in NDArray, in NDArray, Type, NDArray) public override NDArray ClipNDArray(in NDArray lhs, in NDArray min, in NDArray max, Type dtype, NDArray @out = null) Parameters lhs NDArray min NDArray max NDArray dtype Type out NDArray Returns NDArray Compare(in NDArray, in NDArray) public override NDArray Compare(in NDArray x, in NDArray y) Parameters x NDArray y NDArray Returns NDArray Cos(in NDArray, NPTypeCode?) public override NDArray Cos(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Cos(in NDArray, Type) public override NDArray Cos(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Cosh(in NDArray, NPTypeCode?) public override NDArray Cosh(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Cosh(in NDArray, Type) public override NDArray Cosh(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray CreateNDArray(Shape, Type, IArraySlice, char) public override NDArray CreateNDArray(Shape shape, Type dtype = null, IArraySlice buffer = null, char order = 'C') Parameters shape Shape dtype Type buffer IArraySlice order char Returns NDArray CreateNDArray(Shape, Type, Array, char) public override NDArray CreateNDArray(Shape shape, Type dtype = null, Array buffer = null, char order = 'C') Parameters shape Shape dtype Type buffer Array order char Returns NDArray CumSumElementwise(in NDArray, NPTypeCode?) public NDArray CumSumElementwise(in NDArray arr, NPTypeCode? typeCode) where T : unmanaged Parameters arr NDArray typeCode NPTypeCode? Returns NDArray Type Parameters T Divide(in NDArray, in NDArray) public override NDArray Divide(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray DivideBoolean(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray DivideBoolean(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray DivideByte(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray DivideByte(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray DivideChar(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray DivideChar(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray DivideDecimal(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray DivideDecimal(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray DivideDouble(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray DivideDouble(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray DivideInt16(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray DivideInt16(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray DivideInt32(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray DivideInt32(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray DivideInt64(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray DivideInt64(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray DivideSingle(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray DivideSingle(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray DivideUInt16(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray DivideUInt16(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray DivideUInt32(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray DivideUInt32(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray DivideUInt64(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray DivideUInt64(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray Dot(in NDArray, in NDArray) public override NDArray Dot(in NDArray left, in NDArray right) Parameters left NDArray right NDArray Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html DotNDMD(in NDArray, in NDArray) public static NDArray DotNDMD(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray EqualsBoolean(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray EqualsBoolean(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray EqualsByte(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray EqualsByte(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray EqualsChar(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray EqualsChar(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray EqualsDecimal(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray EqualsDecimal(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray EqualsDouble(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray EqualsDouble(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray EqualsInt16(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray EqualsInt16(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray EqualsInt32(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray EqualsInt32(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray EqualsInt64(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray EqualsInt64(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray EqualsSingle(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray EqualsSingle(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray EqualsUInt16(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray EqualsUInt16(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray EqualsUInt32(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray EqualsUInt32(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray EqualsUInt64(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray EqualsUInt64(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray Exp(in NDArray, NPTypeCode?) public override NDArray Exp(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Exp(in NDArray, Type) public override NDArray Exp(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Exp2(in NDArray, NPTypeCode?) public override NDArray Exp2(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Exp2(in NDArray, Type) public override NDArray Exp2(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Expm1(in NDArray, NPTypeCode?) public override NDArray Expm1(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Expm1(in NDArray, Type) public override NDArray Expm1(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Floor(in NDArray, NPTypeCode?) public override NDArray Floor(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Floor(in NDArray, Type) public override NDArray Floor(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray GetStorage(NPTypeCode) Get storage for given typeCode. public override UnmanagedStorage GetStorage(NPTypeCode typeCode) Parameters typeCode NPTypeCode Returns UnmanagedStorage GetStorage(Type) Get storage for given dtype. public override UnmanagedStorage GetStorage(Type dtype) Parameters dtype Type Returns UnmanagedStorage IsClose(NDArray, NDArray, double, double, bool) Returns a boolean array where two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers.The relative difference (rtol * abs(b)) and the absolute difference atol are added together to compare against the absolute difference between a and b. Warning: The default atol is not appropriate for comparing numbers that are much smaller than one(see Notes). See also allclose Notes: For finite values, isclose uses the following equation to test whether two floating point values are equivalent. absolute(`a` - `b`) less than or equal to (`atol` + `rtol` * absolute(`b`)) Unlike the built-in math.isclose, the above equation is not symmetric in a and b -- it assumes b is the reference value -- so that isclose(a, b) might be different from isclose(b, a). Furthermore, the default value of atol is not zero, and is used to determine what small values should be considered close to zero.The default value is appropriate for expected values of order unity: if the expected values are significantly smaller than one, it can result in false positives. atol should be carefully selected for the use case at hand. A zero value for atol will result in False if either a or b is zero. public override NDArray IsClose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false) Parameters a NDArray Input array to compare with b b NDArray Input array to compare with a. rtol double The relative tolerance parameter(see Notes) atol double The absolute tolerance parameter(see Notes) equal_nan bool Whether to compare NaN's as equal. If True, NaN's in a will be considered equal to NaN's in b in the output array. Returns NDArray Returns a boolean array of where a and b are equal within the given tolerance.If both a and b are scalars, returns a single boolean value. IsFinite(NDArray) Test element-wise for finiteness (not infinity or not Not a Number). public override NDArray IsFinite(NDArray a) Parameters a NDArray Returns NDArray The result is returned as a boolean array. IsNan(NDArray) Test element-wise for Not a Number. public override NDArray IsNan(NDArray a) Parameters a NDArray Returns NDArray The result is returned as a boolean array. Log(in NDArray, NPTypeCode?) public override NDArray Log(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Log(in NDArray, Type) public override NDArray Log(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Log10(in NDArray, NPTypeCode?) public override NDArray Log10(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Log10(in NDArray, Type) public override NDArray Log10(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Log1p(in NDArray, NPTypeCode?) public override NDArray Log1p(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Log1p(in NDArray, Type) public override NDArray Log1p(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Log2(in NDArray, NPTypeCode?) public override NDArray Log2(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Log2(in NDArray, Type) public override NDArray Log2(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Matmul(NDArray, NDArray) public override NDArray Matmul(NDArray lhs, NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.matmul.html Mean(in NDArray, int, Type, bool) public override NDArray Mean(in NDArray nd, int axis, Type dtype, bool keepdims = false) Parameters nd NDArray axis int dtype Type keepdims bool Returns NDArray Mean(in NDArray, int?, NPTypeCode?, bool) public override NDArray Mean(in NDArray nd, int? axis = null, NPTypeCode? typeCode = null, bool keepdims = false) Parameters nd NDArray axis int? typeCode NPTypeCode? keepdims bool Returns NDArray MeanElementwise(NDArray, NPTypeCode?) public T MeanElementwise(NDArray arr, NPTypeCode? typeCode) where T : unmanaged Parameters arr NDArray typeCode NPTypeCode? Returns T Type Parameters T Mod(in NDArray, in NDArray) public override NDArray Mod(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray ModBoolean(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray ModBoolean(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray ModByte(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray ModByte(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray ModChar(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray ModChar(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray ModDecimal(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray ModDecimal(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray ModDouble(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray ModDouble(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray ModF(in NDArray, NPTypeCode?) public override (NDArray Fractional, NDArray Intergral) ModF(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns (NDArray Lhs, NDArray Rhs) ModF(in NDArray, Type) public override (NDArray Fractional, NDArray Intergral) ModF(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns (NDArray Lhs, NDArray Rhs) ModInt16(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray ModInt16(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray ModInt32(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray ModInt32(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray ModInt64(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray ModInt64(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray ModSingle(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray ModSingle(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray ModUInt16(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray ModUInt16(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray ModUInt32(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray ModUInt32(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray ModUInt64(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray ModUInt64(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray MoveAxis(in NDArray, int[], int[]) public override NDArray MoveAxis(in NDArray nd, int[] source, int[] destinition) Parameters nd NDArray source int[] destinition int[] Returns NDArray Multiply(NDArray, NDArray) public override NDArray Multiply(NDArray lhs, NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray MultiplyBoolean(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray MultiplyBoolean(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray MultiplyByte(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray MultiplyByte(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray MultiplyChar(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray MultiplyChar(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray MultiplyDecimal(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray MultiplyDecimal(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray MultiplyDouble(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray MultiplyDouble(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray MultiplyInt16(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray MultiplyInt16(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray MultiplyInt32(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray MultiplyInt32(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray MultiplyInt64(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray MultiplyInt64(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray MultiplyMatrix(NDArray, NDArray, NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] protected static NDArray MultiplyMatrix(NDArray left, NDArray right, NDArray @out = null) Parameters left NDArray right NDArray out NDArray Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.multiply.html MultiplySingle(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray MultiplySingle(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray MultiplyUInt16(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray MultiplyUInt16(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray MultiplyUInt32(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray MultiplyUInt32(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray MultiplyUInt64(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray MultiplyUInt64(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray Negate(in NDArray) public override NDArray Negate(in NDArray nd) Parameters nd NDArray Returns NDArray NonZero(in NDArray) Test whether all array elements evaluate to True. public override NDArray[] NonZero(in NDArray nd) Parameters nd NDArray Returns NDArray[] Power(in NDArray, in ValueType, NPTypeCode?) public override NDArray Power(in NDArray lhs, in ValueType rhs, NPTypeCode? typeCode = null) Parameters lhs NDArray rhs ValueType typeCode NPTypeCode? Returns NDArray Power(in NDArray, in ValueType, Type) public override NDArray Power(in NDArray lhs, in ValueType rhs, Type dtype) Parameters lhs NDArray rhs ValueType dtype Type Returns NDArray ProductElementwise(NDArray, NPTypeCode?) public T ProductElementwise(NDArray arr, NPTypeCode? typeCode) where T : unmanaged Parameters arr NDArray typeCode NPTypeCode? Returns T Type Parameters T ReduceAMax(NDArray, int?, bool, NPTypeCode?) public override NDArray ReduceAMax(NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null) Parameters arr NDArray axis_ int? keepdims bool typeCode NPTypeCode? Returns NDArray ReduceAMin(NDArray, int?, bool, NPTypeCode?) public override NDArray ReduceAMin(NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null) Parameters arr NDArray axis_ int? keepdims bool typeCode NPTypeCode? Returns NDArray ReduceAdd(in NDArray, int?, bool, NPTypeCode?, NDArray) public override NDArray ReduceAdd(in NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null, NDArray @out = null) Parameters arr NDArray axis_ int? keepdims bool typeCode NPTypeCode? out NDArray Returns NDArray ReduceArgMax(NDArray, int?) public override NDArray ReduceArgMax(NDArray arr, int? axis_) Parameters arr NDArray axis_ int? Returns NDArray ReduceArgMin(NDArray, int?) public override NDArray ReduceArgMin(NDArray arr, int? axis_) Parameters arr NDArray axis_ int? Returns NDArray ReduceCumAdd(in NDArray, int?, NPTypeCode?) public override NDArray ReduceCumAdd(in NDArray arr, int? axis_, NPTypeCode? typeCode = null) Parameters arr NDArray axis_ int? typeCode NPTypeCode? Returns NDArray ReduceMean(in NDArray, int?, bool, NPTypeCode?) public override NDArray ReduceMean(in NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null) Parameters arr NDArray axis_ int? keepdims bool typeCode NPTypeCode? Returns NDArray ReduceProduct(NDArray, int?, bool, NPTypeCode?) public override NDArray ReduceProduct(NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null) Parameters arr NDArray axis_ int? keepdims bool typeCode NPTypeCode? Returns NDArray ReduceStd(NDArray, int?, bool, int?, NPTypeCode?) public override NDArray ReduceStd(NDArray arr, int? axis_, bool keepdims = false, int? ddof = null, NPTypeCode? typeCode = null) Parameters arr NDArray axis_ int? keepdims bool ddof int? typeCode NPTypeCode? Returns NDArray ReduceVar(NDArray, int?, bool, int?, NPTypeCode?) public override NDArray ReduceVar(NDArray arr, int? axis_, bool keepdims = false, int? ddof = null, NPTypeCode? typeCode = null) Parameters arr NDArray axis_ int? keepdims bool ddof int? typeCode NPTypeCode? Returns NDArray ResolveReturnShape(params NDArray[]) public static Shape ResolveReturnShape(params NDArray[] shapes) Parameters shapes NDArray[] Returns Shape Remarks Based on https://docs.scipy.org/doc/numpy-1.16.1/user/basics.broadcasting.html ResolveReturnShape(Shape, Shape) public static Shape ResolveReturnShape(Shape leftShape, Shape rightShape) Parameters leftShape Shape rightShape Shape Returns Shape Remarks Based on https://docs.scipy.org/doc/numpy-1.16.1/user/basics.broadcasting.html ResolveReturnShape(params Shape[]) public static Shape ResolveReturnShape(params Shape[] shapes) Parameters shapes Shape[] Returns Shape Remarks Based on https://docs.scipy.org/doc/numpy-1.16.1/user/basics.broadcasting.html ResolveUnaryReturnType(in NDArray, NPTypeCode?) public NPTypeCode ResolveUnaryReturnType(in NDArray nd, NPTypeCode? @override) Parameters nd NDArray override NPTypeCode? Returns NPTypeCode ResolveUnaryReturnType(in NDArray, Type) public NPTypeCode ResolveUnaryReturnType(in NDArray nd, Type @override) Parameters nd NDArray override Type Returns NPTypeCode RollAxis(in NDArray, int, int) public override NDArray RollAxis(in NDArray nd, int axis, int start = 0) Parameters nd NDArray axis int start int Returns NDArray Round(in NDArray, int, NPTypeCode?) public override NDArray Round(in NDArray nd, int decimals, NPTypeCode? typeCode = null) Parameters nd NDArray decimals int typeCode NPTypeCode? Returns NDArray Round(in NDArray, int, Type) public override NDArray Round(in NDArray nd, int decimals, Type dtype) Parameters nd NDArray decimals int dtype Type Returns NDArray Round(in NDArray, NPTypeCode?) public override NDArray Round(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Round(in NDArray, Type) public override NDArray Round(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Sign(in NDArray, NPTypeCode?) public override NDArray Sign(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Sign(in NDArray, Type) public override NDArray Sign(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Sin(in NDArray, NPTypeCode?) public override NDArray Sin(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Sin(in NDArray, Type) public override NDArray Sin(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Sinh(in NDArray, NPTypeCode?) public override NDArray Sinh(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Sinh(in NDArray, Type) public override NDArray Sinh(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Sqrt(in NDArray, NPTypeCode?) public override NDArray Sqrt(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Sqrt(in NDArray, Type) public override NDArray Sqrt(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray StdElementwise(NDArray, NPTypeCode?, int?) public T StdElementwise(NDArray arr, NPTypeCode? typeCode, int? ddof) where T : unmanaged Parameters arr NDArray typeCode NPTypeCode? ddof int? Returns T Type Parameters T Subtract(in NDArray, in NDArray) public override NDArray Subtract(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray SubtractBoolean(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray SubtractBoolean(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray SubtractByte(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray SubtractByte(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray SubtractChar(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray SubtractChar(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray SubtractDecimal(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray SubtractDecimal(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray SubtractDouble(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray SubtractDouble(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray SubtractInt16(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray SubtractInt16(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray SubtractInt32(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray SubtractInt32(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray SubtractInt64(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray SubtractInt64(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray SubtractSingle(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray SubtractSingle(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray SubtractUInt16(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray SubtractUInt16(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray SubtractUInt32(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray SubtractUInt32(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray SubtractUInt64(in NDArray, in NDArray) [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] [SuppressMessage(\"ReSharper\", \"CompareOfFloatsByEqualityOperator\")] public NDArray SubtractUInt64(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray Sum(in NDArray, int, Type, bool) public override NDArray Sum(in NDArray nd, int axis, Type dtype, bool keepdims = false) Parameters nd NDArray axis int dtype Type keepdims bool Returns NDArray Sum(in NDArray, int?, NPTypeCode?, bool) public override NDArray Sum(in NDArray nd, int? axis = null, NPTypeCode? typeCode = null, bool keepdims = false) Parameters nd NDArray axis int? typeCode NPTypeCode? keepdims bool Returns NDArray SumElementwise(NDArray, NPTypeCode?) public T SumElementwise(NDArray arr, NPTypeCode? typeCode) where T : unmanaged Parameters arr NDArray typeCode NPTypeCode? Returns T Type Parameters T SwapAxes(in NDArray, int, int) public override NDArray SwapAxes(in NDArray nd, int axis1, int axis2) Parameters nd NDArray axis1 int axis2 int Returns NDArray Tan(in NDArray, NPTypeCode?) public override NDArray Tan(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Tan(in NDArray, Type) public override NDArray Tan(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Tanh(in NDArray, NPTypeCode?) public override NDArray Tanh(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Tanh(in NDArray, Type) public override NDArray Tanh(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Transpose(in NDArray, int[]) public override NDArray Transpose(in NDArray nd, int[] premute = null) Parameters nd NDArray premute int[] Returns NDArray VarElementwise(NDArray, NPTypeCode?, int?) public T VarElementwise(NDArray arr, NPTypeCode? typeCode, int? ddof) where T : unmanaged Parameters arr NDArray typeCode NPTypeCode? ddof int? Returns T Type Parameters T amax_elementwise(NDArray, NPTypeCode?) protected object amax_elementwise(NDArray arr, NPTypeCode? typeCode) Parameters arr NDArray typeCode NPTypeCode? Returns object amin_elementwise(NDArray, NPTypeCode?) protected object amin_elementwise(NDArray arr, NPTypeCode? typeCode) Parameters arr NDArray typeCode NPTypeCode? Returns object argmax_elementwise(NDArray) protected object argmax_elementwise(NDArray arr) Parameters arr NDArray Returns object argmin_elementwise(NDArray) protected object argmin_elementwise(NDArray arr) Parameters arr NDArray Returns object check_and_adjust_axis(NDArray, int) public static int check_and_adjust_axis(NDArray nd, int axis) Parameters nd NDArray axis int Returns int check_and_adjust_axis(int, int) public static int check_and_adjust_axis(int ndims, int axis) Parameters ndims int axis int Returns int cumsum_elementwise(in NDArray, NPTypeCode?) protected NDArray cumsum_elementwise(in NDArray arr, NPTypeCode? typeCode) Parameters arr NDArray typeCode NPTypeCode? Returns NDArray mean_elementwise(NDArray, NPTypeCode?) protected object mean_elementwise(NDArray arr, NPTypeCode? typeCode) Parameters arr NDArray typeCode NPTypeCode? Returns object normalize_axis_tuple(int, object, bool) public static int[] normalize_axis_tuple(int axis, object argname = null, bool allow_duplicate = false) Parameters axis int argname object allow_duplicate bool Returns int[] normalize_axis_tuple(int[], object, bool) public static int[] normalize_axis_tuple(int[] axis, object argname = null, bool allow_duplicate = false) Parameters axis int[] argname object allow_duplicate bool Returns int[] product_elementwise(NDArray, NPTypeCode?) protected object product_elementwise(NDArray arr, NPTypeCode? typeCode) Parameters arr NDArray typeCode NPTypeCode? Returns object std_elementwise(NDArray, NPTypeCode?, int?) protected object std_elementwise(NDArray arr, NPTypeCode? typeCode, int? ddof) Parameters arr NDArray typeCode NPTypeCode? ddof int? Returns object sum_elementwise(NDArray, NPTypeCode?) protected object sum_elementwise(NDArray arr, NPTypeCode? typeCode) Parameters arr NDArray typeCode NPTypeCode? Returns object var_elementwise(NDArray, NPTypeCode?, int?) protected object var_elementwise(NDArray arr, NPTypeCode? typeCode, int? ddof) Parameters arr NDArray typeCode NPTypeCode? ddof int? Returns object" + }, + "api/NumSharp.Backends.Unmanaged.ArraySlice-1.html": { + "href": "api/NumSharp.Backends.Unmanaged.ArraySlice-1.html", + "title": "Struct ArraySlice | NumSharp Documentation", + "summary": "Struct ArraySlice Namespace NumSharp.Backends.Unmanaged Assembly NumSharp.dll ArraySlice is similar to Span but it can be moved around without having to follow ref struct rules. public readonly struct ArraySlice : IArraySlice, ICloneable, IMemoryBlock, IMemoryBlock, IEnumerable, IEnumerable where T : unmanaged Type Parameters T The type that the MemoryBlock implements. Implements IArraySlice ICloneable IMemoryBlock IMemoryBlock IEnumerable IEnumerable Inherited Members ValueType.Equals(object) ValueType.GetHashCode() ValueType.ToString() object.Equals(object, object) object.GetType() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) NDIteratorExtensions.AsIterator(IArraySlice, Shape) NDIteratorExtensions.AsIterator(IArraySlice, Shape, Shape, bool) NDIteratorExtensions.AsIterator(IArraySlice, Shape, bool) UnmanagedHelper.CopyTo(IMemoryBlock, IMemoryBlock) UnmanagedHelper.CopyTo(IMemoryBlock, IMemoryBlock, int) UnmanagedHelper.CopyTo(IMemoryBlock, void*) UnmanagedHelper.CopyTo(IMemoryBlock, void*, int) UnmanagedMemoryBlock.CastTo(IMemoryBlock, IMemoryBlock, int?, int?) UnmanagedMemoryBlock.CastTo(IMemoryBlock, NPTypeCode) UnmanagedMemoryBlock.CastTo(IMemoryBlock) UnmanagedMemoryBlock.CastTo(IMemoryBlock) UnmanagedMemoryBlock.CastTo(IMemoryBlock) Constructors ArraySlice(UnmanagedMemoryBlock) public ArraySlice(UnmanagedMemoryBlock memoryBlock) Parameters memoryBlock UnmanagedMemoryBlock ArraySlice(UnmanagedMemoryBlock, Span) public ArraySlice(UnmanagedMemoryBlock memoryBlock, Span slice) Parameters memoryBlock UnmanagedMemoryBlock slice Span ArraySlice(UnmanagedMemoryBlock, T*, int) Creates a sliced ArraySlice. public ArraySlice(UnmanagedMemoryBlock memoryBlock, T* address, int count) Parameters memoryBlock UnmanagedMemoryBlock address T* count int The number of T this slice should contain - relative to the memoryBlock ArraySlice(UnmanagedMemoryBlock, T*, long) Creates a sliced ArraySlice. public ArraySlice(UnmanagedMemoryBlock memoryBlock, T* address, long count) Parameters memoryBlock UnmanagedMemoryBlock address T* count long The number of T this slice should contain - relative to the memoryBlock Fields Address public readonly T* Address Field Value T* Count public readonly int Count Field Value int IsSlice Is this ArraySlice a smaller part/slice of an unmanaged allocation? public readonly bool IsSlice Field Value bool MemoryBlock The memory block this ArraySlice is stored in. public readonly UnmanagedMemoryBlock MemoryBlock Field Value UnmanagedMemoryBlock Remarks If IsSlice is false then this slice represents the entire MemoryBlock. VoidAddress public readonly void* VoidAddress Field Value void* Properties this[int] public T this[int index] { get; set; } Parameters index int Property Value T ItemLength The size of a single item stored in Address. public int ItemLength { get; } Property Value int Remarks Equivalent to NPTypeCode.SizeOf extension. TypeCode public static NPTypeCode TypeCode { get; } Property Value NPTypeCode Methods Allocate(int) Allocate an array filled with noisy memory. public static ArraySlice Allocate(int count) Parameters count int How many items this array will have (aka Count). Returns ArraySlice A newly allocated array. Allocate(int, bool) Allocate an array filled with default value of T. public static ArraySlice Allocate(int count, bool fillDefault) Parameters count int How many items this array will have (aka Count). fillDefault bool Should the newly allocated memory be filled with the default of T Returns ArraySlice A newly allocated array. Allocate(int, T) Allocate an array filled filled with fill. public static ArraySlice Allocate(int count, T fill) Parameters count int How many items this array will have (aka Count). fill T The item to fill the newly allocated memory with. Returns ArraySlice A newly allocated array. Clone() public ArraySlice Clone() Returns ArraySlice Contains(T) public bool Contains(T item) Parameters item T Returns bool CopyTo(nint) Copies the entire array to address. public void CopyTo(nint dst) Parameters dst nint The address to copy to Remarks The destiniton has to be atleast the size of this array, otherwise memory corruption is likely to occur. CopyTo(nint, int, int) Copies the entire array to address. public void CopyTo(nint dst, int sourceOffset, int sourceCount) Parameters dst nint The address to copy to sourceOffset int sourceCount int Remarks The destiniton has to be atleast the size of this array, otherwise memory corruption is likely to occur. CopyTo(Span) public void CopyTo(Span destination) Parameters destination Span CopyTo(Span, int) public void CopyTo(Span destination, int sourceOffset) Parameters destination Span sourceOffset int offset of source via count (not bytes) CopyTo(Span, int, int) public void CopyTo(Span destination, int sourceOffset, int sourceLength) Parameters destination Span sourceOffset int offset of source via count (not bytes) sourceLength int How many items to copy DangerousFree() Performs dispose on the internal unmanaged memory block. public void DangerousFree() Remarks Dangerous because this ArraySlice might be a IsSlice therefore there might be other slices that point to current MemoryBlock. So releasing the MemoryBlock might cause memory corruption elsewhere. It is best to leave MemoryBlock to GC. Fill(T) public void Fill(T value) Parameters value T GetEnumerator() Returns an enumerator that iterates through the collection. public IEnumerator GetEnumerator() Returns IEnumerator An enumerator that can be used to iterate through the collection. GetIndex(int) public T GetIndex(int index) Parameters index int Returns T SetIndex(int, object) public void SetIndex(int index, object value) Parameters index int value object SetIndex(int, T) public void SetIndex(int index, T value) Parameters index int value T Slice(int) public ArraySlice Slice(int start) Parameters start int Returns ArraySlice Slice(int, int) public ArraySlice Slice(int start, int length) Parameters start int length int Returns ArraySlice ToArray() Copies the contents of this span into a new array. This heap allocates, so should generally be avoided, however it is sometimes necessary to bridge the gap with APIs written in terms of arrays. public T[] ToArray() Returns T[] TryCopyTo(Span) public bool TryCopyTo(Span destination) Parameters destination Span Returns bool" + }, + "api/NumSharp.Backends.Unmanaged.ArraySlice.html": { + "href": "api/NumSharp.Backends.Unmanaged.ArraySlice.html", + "title": "Class ArraySlice | NumSharp Documentation", + "summary": "Class ArraySlice Namespace NumSharp.Backends.Unmanaged Assembly NumSharp.dll public static class ArraySlice Inheritance object ArraySlice Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Methods Allocate(NPTypeCode, int) public static IArraySlice Allocate(NPTypeCode typeCode, int count) Parameters typeCode NPTypeCode count int Returns IArraySlice Allocate(NPTypeCode, int, bool) public static IArraySlice Allocate(NPTypeCode typeCode, int count, bool fillDefault) Parameters typeCode NPTypeCode count int fillDefault bool Returns IArraySlice Allocate(NPTypeCode, int, object) public static IArraySlice Allocate(NPTypeCode typeCode, int count, object fill) Parameters typeCode NPTypeCode count int fill object Returns IArraySlice Allocate(Type, int) public static IArraySlice Allocate(Type elementType, int count) Parameters elementType Type count int Returns IArraySlice Allocate(Type, int, bool) public static IArraySlice Allocate(Type elementType, int count, bool fillDefault) Parameters elementType Type count int fillDefault bool Returns IArraySlice Allocate(Type, int, object) public static IArraySlice Allocate(Type elementType, int count, object fill) Parameters elementType Type count int fill object Returns IArraySlice Allocate(int) Allocate an array filled with noisy memory. public static ArraySlice Allocate(int count) where T : unmanaged Parameters count int How many items this array will have (aka Count). Returns ArraySlice A newly allocated array. Type Parameters T Allocate(int, bool) Allocate an array filled with default value of T. public static ArraySlice Allocate(int count, bool fillDefault) where T : unmanaged Parameters count int How many items this array will have (aka Count). fillDefault bool Should the newly allocated memory be filled with the default of T Returns ArraySlice A newly allocated array. Type Parameters T Allocate(int, T) Allocate an array filled filled with fill. public static ArraySlice Allocate(int count, T fill) where T : unmanaged Parameters count int How many items this array will have (aka Count). fill T The item to fill the newly allocated memory with. Returns ArraySlice A newly allocated array. Type Parameters T FromArray(Array, bool) public static IArraySlice FromArray(Array arr, bool copy = false) Parameters arr Array copy bool Returns IArraySlice FromArray(bool[], bool) public static ArraySlice FromArray(bool[] bools, bool copy = false) Parameters bools bool[] copy bool Returns ArraySlice FromArray(byte[], bool) public static ArraySlice FromArray(byte[] bytes, bool copy = false) Parameters bytes byte[] copy bool Returns ArraySlice FromArray(char[], bool) public static ArraySlice FromArray(char[] chars, bool copy = false) Parameters chars char[] copy bool Returns ArraySlice FromArray(decimal[], bool) public static ArraySlice FromArray(decimal[] decimals, bool copy = false) Parameters decimals decimal[] copy bool Returns ArraySlice FromArray(double[], bool) public static ArraySlice FromArray(double[] doubles, bool copy = false) Parameters doubles double[] copy bool Returns ArraySlice FromArray(short[], bool) public static ArraySlice FromArray(short[] shorts, bool copy = false) Parameters shorts short[] copy bool Returns ArraySlice FromArray(int[], bool) public static ArraySlice FromArray(int[] ints, bool copy = false) Parameters ints int[] copy bool Returns ArraySlice FromArray(long[], bool) public static ArraySlice FromArray(long[] longs, bool copy = false) Parameters longs long[] copy bool Returns ArraySlice FromArray(float[], bool) public static ArraySlice FromArray(float[] floats, bool copy = false) Parameters floats float[] copy bool Returns ArraySlice FromArray(ushort[], bool) public static ArraySlice FromArray(ushort[] ushorts, bool copy = false) Parameters ushorts ushort[] copy bool Returns ArraySlice FromArray(uint[], bool) public static ArraySlice FromArray(uint[] uints, bool copy = false) Parameters uints uint[] copy bool Returns ArraySlice FromArray(ulong[], bool) public static ArraySlice FromArray(ulong[] ulongs, bool copy = false) Parameters ulongs ulong[] copy bool Returns ArraySlice FromArray(T[,,,,,,,,,,,,,,,], bool) public static ArraySlice FromArray(T[,,,,,,,,,,,,,,,] array, bool copy = false) where T : unmanaged Parameters array T[,,,,,,,,,,,,,,,] copy bool Returns ArraySlice Type Parameters T FromArray(T[,,,,,,,,,,,,,,], bool) public static ArraySlice FromArray(T[,,,,,,,,,,,,,,] array, bool copy = false) where T : unmanaged Parameters array T[,,,,,,,,,,,,,,] copy bool Returns ArraySlice Type Parameters T FromArray(T[,,,,,,,,,,,,,], bool) public static ArraySlice FromArray(T[,,,,,,,,,,,,,] array, bool copy = false) where T : unmanaged Parameters array T[,,,,,,,,,,,,,] copy bool Returns ArraySlice Type Parameters T FromArray(T[,,,,,,,,,,,,], bool) public static ArraySlice FromArray(T[,,,,,,,,,,,,] array, bool copy = false) where T : unmanaged Parameters array T[,,,,,,,,,,,,] copy bool Returns ArraySlice Type Parameters T FromArray(T[,,,,,,,,,,,], bool) public static ArraySlice FromArray(T[,,,,,,,,,,,] array, bool copy = false) where T : unmanaged Parameters array T[,,,,,,,,,,,] copy bool Returns ArraySlice Type Parameters T FromArray(T[,,,,,,,,,,], bool) public static ArraySlice FromArray(T[,,,,,,,,,,] array, bool copy = false) where T : unmanaged Parameters array T[,,,,,,,,,,] copy bool Returns ArraySlice Type Parameters T FromArray(T[,,,,,,,,,], bool) public static ArraySlice FromArray(T[,,,,,,,,,] array, bool copy = false) where T : unmanaged Parameters array T[,,,,,,,,,] copy bool Returns ArraySlice Type Parameters T FromArray(T[,,,,,,,,], bool) public static ArraySlice FromArray(T[,,,,,,,,] array, bool copy = false) where T : unmanaged Parameters array T[,,,,,,,,] copy bool Returns ArraySlice Type Parameters T FromArray(T[,,,,,,,], bool) public static ArraySlice FromArray(T[,,,,,,,] array, bool copy = false) where T : unmanaged Parameters array T[,,,,,,,] copy bool Returns ArraySlice Type Parameters T FromArray(T[,,,,,,], bool) public static ArraySlice FromArray(T[,,,,,,] array, bool copy = false) where T : unmanaged Parameters array T[,,,,,,] copy bool Returns ArraySlice Type Parameters T FromArray(T[,,,,,], bool) public static ArraySlice FromArray(T[,,,,,] array, bool copy = false) where T : unmanaged Parameters array T[,,,,,] copy bool Returns ArraySlice Type Parameters T FromArray(T[,,,,], bool) public static ArraySlice FromArray(T[,,,,] array, bool copy = false) where T : unmanaged Parameters array T[,,,,] copy bool Returns ArraySlice Type Parameters T FromArray(T[,,,], bool) public static ArraySlice FromArray(T[,,,] array, bool copy = false) where T : unmanaged Parameters array T[,,,] copy bool Returns ArraySlice Type Parameters T FromArray(T[,,], bool) public static ArraySlice FromArray(T[,,] array, bool copy = false) where T : unmanaged Parameters array T[,,] copy bool Returns ArraySlice Type Parameters T FromArray(T[,], bool) public static ArraySlice FromArray(T[,] array, bool copy = false) where T : unmanaged Parameters array T[,] copy bool Returns ArraySlice Type Parameters T FromArray(T[], bool) public static ArraySlice FromArray(T[] array, bool copy = false) where T : unmanaged Parameters array T[] copy bool Returns ArraySlice Type Parameters T FromBuffer(byte[], bool) public static ArraySlice FromBuffer(byte[] arr, bool copy = false) where T : unmanaged Parameters arr byte[] copy bool Returns ArraySlice Type Parameters T FromMemoryBlock(IMemoryBlock, bool) public static IArraySlice FromMemoryBlock(IMemoryBlock block, bool copy = false) Parameters block IMemoryBlock copy bool Returns IArraySlice FromPool(StackedMemoryPool) public static ArraySlice FromPool(StackedMemoryPool pool) where T : unmanaged Parameters pool StackedMemoryPool Returns ArraySlice Type Parameters T Scalar(object) Wrap a val inside ArraySlice. public static IArraySlice Scalar(object val) Parameters val object The value to wrap into an arrayslice. Returns IArraySlice Scalar(object, NPTypeCode) Wrap a T inside ArraySlice. public static IArraySlice Scalar(object val, NPTypeCode typeCode) Parameters val object The value to wrap into an arrayslice. typeCode NPTypeCode The type expected to be returned Returns IArraySlice Scalar(T) Wrap a T inside ArraySlice. public static ArraySlice Scalar(T val) where T : unmanaged Parameters val T Returns ArraySlice Type Parameters T Wrap(void*, int) Wrap around a address with given count without claiming ownership of the address. public static ArraySlice Wrap(void* address, int count) where T : unmanaged Parameters address void* The address at which the memory block starts count int The count of items of type T (not bytes count) Returns ArraySlice A wrapped memory block as ArraySlice Type Parameters T Wrap(T*, int) Wrap around a address with given count without claiming ownership of the address. public static ArraySlice Wrap(T* address, int count) where T : unmanaged Parameters address T* The address at which the memory block starts count int The count of items of type T (not bytes count) Returns ArraySlice A wrapped memory block as ArraySlice Type Parameters T" + }, + "api/NumSharp.Backends.Unmanaged.IArraySlice.html": { + "href": "api/NumSharp.Backends.Unmanaged.IArraySlice.html", + "title": "Interface IArraySlice | NumSharp Documentation", + "summary": "Interface IArraySlice Namespace NumSharp.Backends.Unmanaged Assembly NumSharp.dll public interface IArraySlice : IMemoryBlock, ICloneable, IEnumerable Inherited Members IMemoryBlock.ItemLength IMemoryBlock.Address IMemoryBlock.Count IMemoryBlock.BytesLength IMemoryBlock.TypeCode IEnumerable.GetEnumerator() Extension Methods LinqExtensions.Yield(T) NDIteratorExtensions.AsIterator(IArraySlice, Shape) NDIteratorExtensions.AsIterator(IArraySlice, Shape, Shape, bool) NDIteratorExtensions.AsIterator(IArraySlice, Shape, bool) UnmanagedHelper.CopyTo(IMemoryBlock, IMemoryBlock) UnmanagedHelper.CopyTo(IMemoryBlock, IMemoryBlock, int) UnmanagedHelper.CopyTo(IMemoryBlock, void*) UnmanagedHelper.CopyTo(IMemoryBlock, void*, int) UnmanagedMemoryBlock.CastTo(IMemoryBlock, IMemoryBlock, int?, int?) UnmanagedMemoryBlock.CastTo(IMemoryBlock, NPTypeCode) UnmanagedMemoryBlock.CastTo(IMemoryBlock) UnmanagedMemoryBlock.CastTo(IMemoryBlock) Properties this[int] object this[int index] { get; set; } Parameters index int Property Value object MemoryBlock IMemoryBlock MemoryBlock { get; } Property Value IMemoryBlock Methods AsSpan() Span AsSpan() Returns Span Type Parameters T Remarks Does not perform copy. Clone() IArraySlice Clone() Returns IArraySlice Clone() ArraySlice Clone() where T : unmanaged Returns ArraySlice Type Parameters T CopyTo(Span) void CopyTo(Span destination) Parameters destination Span Type Parameters T DangerousFree() Performs dispose on the internal unmanaged memory block. void DangerousFree() Remarks Dangerous because this ArraySlice might be a IsSlice therefore there might be other slices that point to current MemoryBlock. So releasing the MemoryBlock might cause memory corruption elsewhere. It is best to leave MemoryBlock to GC. Fill(object) Fills all indexes with value. void Fill(object value) Parameters value object GetIndex(int) object GetIndex(int index) Parameters index int Returns object GetIndex(int) T GetIndex(int index) where T : unmanaged Parameters index int Returns T Type Parameters T GetPinnableReference() Gets pinnable reference of the first item in the memory block storage. ref T GetPinnableReference() where T : unmanaged Returns T Type Parameters T SetIndex(int, object) void SetIndex(int index, object value) Parameters index int value object SetIndex(int, T) void SetIndex(int index, T value) where T : unmanaged Parameters index int value T Type Parameters T Slice(int) Perform a slicing on this IMemoryBlock without copying data. IArraySlice Slice(int start) Parameters start int The index to start from Returns IArraySlice Remarks Creates a slice without copying. Slice(int, int) Perform a slicing on this IMemoryBlock without copying data. IArraySlice Slice(int start, int count) Parameters start int The index to start from count int The number of items to slice (not bytes) Returns IArraySlice Remarks Creates a slice without copying. ToArray() Copies this IArraySlice contents into a new array. Array ToArray() Returns Array" + }, + "api/NumSharp.Backends.Unmanaged.IMemoryBlock-1.html": { + "href": "api/NumSharp.Backends.Unmanaged.IMemoryBlock-1.html", + "title": "Interface IMemoryBlock | NumSharp Documentation", + "summary": "Interface IMemoryBlock Namespace NumSharp.Backends.Unmanaged Assembly NumSharp.dll public interface IMemoryBlock : IMemoryBlock where T : unmanaged Type Parameters T Inherited Members IMemoryBlock.ItemLength IMemoryBlock.Count IMemoryBlock.BytesLength IMemoryBlock.TypeCode Extension Methods UnmanagedHelper.CopyTo(IMemoryBlock, IMemoryBlock) UnmanagedHelper.CopyTo(IMemoryBlock, IMemoryBlock, int) UnmanagedHelper.CopyTo(IMemoryBlock, void*) UnmanagedHelper.CopyTo(IMemoryBlock, void*, int) UnmanagedMemoryBlock.CastTo(IMemoryBlock, IMemoryBlock, int?, int?) UnmanagedMemoryBlock.CastTo(IMemoryBlock, NPTypeCode) UnmanagedMemoryBlock.CastTo(IMemoryBlock) UnmanagedMemoryBlock.CastTo(IMemoryBlock) UnmanagedMemoryBlock.CastTo(IMemoryBlock) LinqExtensions.Yield(T) Properties Address The start address of this memory block. T* Address { get; } Property Value T*" + }, + "api/NumSharp.Backends.Unmanaged.IMemoryBlock.html": { + "href": "api/NumSharp.Backends.Unmanaged.IMemoryBlock.html", + "title": "Interface IMemoryBlock | NumSharp Documentation", + "summary": "Interface IMemoryBlock Namespace NumSharp.Backends.Unmanaged Assembly NumSharp.dll public interface IMemoryBlock Extension Methods UnmanagedHelper.CopyTo(IMemoryBlock, IMemoryBlock) UnmanagedHelper.CopyTo(IMemoryBlock, IMemoryBlock, int) UnmanagedHelper.CopyTo(IMemoryBlock, void*) UnmanagedHelper.CopyTo(IMemoryBlock, void*, int) UnmanagedMemoryBlock.CastTo(IMemoryBlock, IMemoryBlock, int?, int?) UnmanagedMemoryBlock.CastTo(IMemoryBlock, NPTypeCode) UnmanagedMemoryBlock.CastTo(IMemoryBlock) UnmanagedMemoryBlock.CastTo(IMemoryBlock) LinqExtensions.Yield(T) Properties Address The start address of this memory block. void* Address { get; } Property Value void* BytesLength How many bytes are stored in this memory block. long BytesLength { get; } Property Value long Remarks Calculated by Count*ItemLength Count How many items are stored in Address. long Count { get; } Property Value long Remarks Not to confuse with BytesLength ItemLength The size of a single item stored in Address. int ItemLength { get; } Property Value int Remarks Equivalent to NPTypeCode.SizeOf extension. TypeCode The NPTypeCode of the type stored inside this memory block. NPTypeCode TypeCode { get; } Property Value NPTypeCode" + }, + "api/NumSharp.Backends.Unmanaged.IUnmanagedMemoryBlock.html": { + "href": "api/NumSharp.Backends.Unmanaged.IUnmanagedMemoryBlock.html", + "title": "Interface IUnmanagedMemoryBlock | NumSharp Documentation", + "summary": "Interface IUnmanagedMemoryBlock Namespace NumSharp.Backends.Unmanaged Assembly NumSharp.dll public interface IUnmanagedMemoryBlock : IEnumerable, IMemoryBlock, ICloneable Inherited Members IEnumerable.GetEnumerator() IMemoryBlock.ItemLength IMemoryBlock.Address IMemoryBlock.Count IMemoryBlock.BytesLength IMemoryBlock.TypeCode ICloneable.Clone() Extension Methods UnmanagedHelper.CopyTo(IMemoryBlock, IMemoryBlock) UnmanagedHelper.CopyTo(IMemoryBlock, IMemoryBlock, int) UnmanagedHelper.CopyTo(IMemoryBlock, void*) UnmanagedHelper.CopyTo(IMemoryBlock, void*, int) UnmanagedMemoryBlock.CastTo(IMemoryBlock, IMemoryBlock, int?, int?) UnmanagedMemoryBlock.CastTo(IMemoryBlock, NPTypeCode) UnmanagedMemoryBlock.CastTo(IMemoryBlock) UnmanagedMemoryBlock.CastTo(IMemoryBlock) LinqExtensions.Yield(T) Methods Free() void Free() Reallocate(long, bool) void Reallocate(long length, bool copyOldValues = false) Parameters length long copyOldValues bool" + }, + "api/NumSharp.Backends.Unmanaged.UnmanagedHelper.html": { + "href": "api/NumSharp.Backends.Unmanaged.UnmanagedHelper.html", + "title": "Class UnmanagedHelper | NumSharp Documentation", + "summary": "Class UnmanagedHelper Namespace NumSharp.Backends.Unmanaged Assembly NumSharp.dll public static class UnmanagedHelper Inheritance object UnmanagedHelper Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Methods CopyTo(IMemoryBlock, IMemoryBlock) Copies the entire contents of this storage to given address (using Count). public static void CopyTo(this IMemoryBlock src, IMemoryBlock dst) Parameters src IMemoryBlock dst IMemoryBlock The block to copy to. CopyTo(IMemoryBlock, IMemoryBlock, int) Copies the entire contents of this storage to given address (using Count). public static void CopyTo(this IMemoryBlock src, IMemoryBlock dst, int countOffsetDesitinion) Parameters src IMemoryBlock dst IMemoryBlock The block to copy to. countOffsetDesitinion int CopyTo(IMemoryBlock, void*) Copies the entire contents of this storage to given address. public static void CopyTo(this IMemoryBlock src, void* dstAddress) Parameters src IMemoryBlock The source of the copying dstAddress void* The address to copy to. CopyTo(IMemoryBlock, void*, int) Copies the entire contents of this storage to given address (using Count). public static void CopyTo(this IMemoryBlock src, void* dstAddress, int countOffsetDesitinion) Parameters src IMemoryBlock dstAddress void* countOffsetDesitinion int CopyTo(UnmanagedMemoryBlock, UnmanagedMemoryBlock) Copies the entire contents of this storage to given address (using Count). public static void CopyTo(this UnmanagedMemoryBlock src, UnmanagedMemoryBlock dst) where T : unmanaged Parameters src UnmanagedMemoryBlock dst UnmanagedMemoryBlock The block to copy to. Type Parameters T" + }, + "api/NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock-1.html": { + "href": "api/NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock-1.html", + "title": "Struct UnmanagedMemoryBlock | NumSharp Documentation", + "summary": "Struct UnmanagedMemoryBlock Namespace NumSharp.Backends.Unmanaged Assembly NumSharp.dll public struct UnmanagedMemoryBlock : IUnmanagedMemoryBlock, IMemoryBlock, IMemoryBlock, IEnumerable, IEnumerable, IEquatable>, ICloneable where T : unmanaged Type Parameters T Implements IUnmanagedMemoryBlock IMemoryBlock IMemoryBlock IEnumerable IEnumerable IEquatable> ICloneable Inherited Members ValueType.ToString() object.Equals(object, object) object.GetType() object.ReferenceEquals(object, object) Extension Methods UnmanagedHelper.CopyTo(IMemoryBlock, IMemoryBlock) UnmanagedHelper.CopyTo(IMemoryBlock, IMemoryBlock, int) UnmanagedHelper.CopyTo(IMemoryBlock, void*) UnmanagedHelper.CopyTo(IMemoryBlock, void*, int) UnmanagedMemoryBlock.CastTo(IMemoryBlock, IMemoryBlock, int?, int?) UnmanagedMemoryBlock.CastTo(IMemoryBlock, NPTypeCode) UnmanagedMemoryBlock.CastTo(IMemoryBlock) UnmanagedMemoryBlock.CastTo(IMemoryBlock) UnmanagedMemoryBlock.CastTo(IMemoryBlock) UnmanagedHelper.CopyTo(UnmanagedMemoryBlock, UnmanagedMemoryBlock) LinqExtensions.Yield(T) Constructors UnmanagedMemoryBlock(long) public UnmanagedMemoryBlock(long count) Parameters count long The length in objects of T and not in bytes. Remarks Does claim ownership since allocation is publicly. UnmanagedMemoryBlock(long, T) public UnmanagedMemoryBlock(long count, T fill) Parameters count long The length in objects of T and not in bytes. fill T UnmanagedMemoryBlock(GCHandle, long) Construct with externally allocated memory settings this memory block as owner. public UnmanagedMemoryBlock(GCHandle handle, long count) Parameters handle GCHandle count long The length in objects of T and not in bytes. Remarks Does claim ownership. UnmanagedMemoryBlock(GCHandle, long, Action) Construct with externally allocated memory and a custom dispose function. public UnmanagedMemoryBlock(GCHandle handle, long count, Action dispose) Parameters handle GCHandle count long The length in objects of T and not in bytes. dispose Action Remarks Does claim ownership. UnmanagedMemoryBlock(T*, long) Construct as a wrapper around pointer and given length without claiming ownership. public UnmanagedMemoryBlock(T* ptr, long count) Parameters ptr T* count long The length in objects of T and not in bytes. Remarks Does claim ownership. UnmanagedMemoryBlock(T*, long, Action) Construct with externally allocated memory and a custom dispose function. public UnmanagedMemoryBlock(T* start, long count, Action dispose) Parameters start T* count long The length in objects of T and not in bytes. dispose Action Remarks Does claim ownership. Fields Address public readonly T* Address Field Value T* BytesCount public readonly long BytesCount Field Value long Count public readonly long Count Field Value long Properties this[int] public T this[int index] { get; set; } Parameters index int Property Value T Methods Clone() Performs a copy to this memory block. public UnmanagedMemoryBlock Clone() Returns UnmanagedMemoryBlock Contains(T) public bool Contains(T item) Parameters item T Returns bool Copy(UnmanagedMemoryBlock) public static UnmanagedMemoryBlock Copy(UnmanagedMemoryBlock source) Parameters source UnmanagedMemoryBlock Returns UnmanagedMemoryBlock Copy(nint, int) public static UnmanagedMemoryBlock Copy(nint address, int count) Parameters address nint count int How many T to copy, not how many bytes. Returns UnmanagedMemoryBlock Copy(void*, int) public static UnmanagedMemoryBlock Copy(void* address, int count) Parameters address void* The address of the first T count int How many T to copy, not how many bytes. Returns UnmanagedMemoryBlock Copy(T*, int) public static UnmanagedMemoryBlock Copy(T* address, int count) Parameters address T* The address of the first T count int How many T to copy, not how many bytes. Returns UnmanagedMemoryBlock CopyTo(UnmanagedMemoryBlock, long) public void CopyTo(UnmanagedMemoryBlock memoryBlock, long arrayIndex) Parameters memoryBlock UnmanagedMemoryBlock arrayIndex long CopyTo(Array, int) Copies the elements of the ICollection to an Array, starting at a particular Array index. public void CopyTo(Array array, int arrayIndex) Parameters array Array The one-dimensional Array that is the destination of the elements copied from ICollection. The Array must have zero-based indexing. arrayIndex int The zero-based index in array at which copying begins. Exceptions ArgumentNullException array is null. ArgumentOutOfRangeException arrayIndex is less than zero. ArgumentException array is multidimensional.-or- The number of elements in the source ICollection is greater than the available space from arrayIndex to the end of the destination array.-or-The type of the source ICollection cannot be cast automatically to the type of the destination array. CopyTo(T*, long, long) public void CopyTo(T* array, long arrayIndex, long lengthToCopy) Parameters array T* arrayIndex long lengthToCopy long CopyTo(T[], int) public void CopyTo(T[] array, int arrayIndex) Parameters array T[] arrayIndex int Equals(UnmanagedMemoryBlock) Indicates whether the current object is equal to another object of the same type. public bool Equals(UnmanagedMemoryBlock other) Parameters other UnmanagedMemoryBlock An object to compare with this object. Returns bool true if the current object is equal to the other parameter; otherwise, false. Equals(object) Indicates whether this instance and a specified object are equal. public override bool Equals(object obj) Parameters obj object The object to compare with the current instance. Returns bool true if obj and this instance are the same type and represent the same value; otherwise, false. Fill(T) Fills the contents of this span with the given value. public void Fill(T value) Parameters value T Fill(T, long, long) Fills the contents of this span with the given value. public void Fill(T value, long offset, long count) Parameters value T offset long count long Free() public void Free() FromArray(T[,,,,,,,,,,,,,,,]) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,,,,,] arr) Parameters arr T[,,,,,,,,,,,,,,,] Returns UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,,,,,], bool) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,,,,,] arr, bool copy) Parameters arr T[,,,,,,,,,,,,,,,] copy bool Returns UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,,,,]) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,,,,] arr) Parameters arr T[,,,,,,,,,,,,,,] Returns UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,,,,], bool) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,,,,] arr, bool copy) Parameters arr T[,,,,,,,,,,,,,,] copy bool Returns UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,,,]) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,,,] arr) Parameters arr T[,,,,,,,,,,,,,] Returns UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,,,], bool) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,,,] arr, bool copy) Parameters arr T[,,,,,,,,,,,,,] copy bool Returns UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,,]) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,,] arr) Parameters arr T[,,,,,,,,,,,,] Returns UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,,], bool) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,,] arr, bool copy) Parameters arr T[,,,,,,,,,,,,] copy bool Returns UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,]) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,] arr) Parameters arr T[,,,,,,,,,,,] Returns UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,], bool) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,,] arr, bool copy) Parameters arr T[,,,,,,,,,,,] copy bool Returns UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,]) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,] arr) Parameters arr T[,,,,,,,,,,] Returns UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,], bool) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,,,,] arr, bool copy) Parameters arr T[,,,,,,,,,,] copy bool Returns UnmanagedMemoryBlock FromArray(T[,,,,,,,,,]) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,,,] arr) Parameters arr T[,,,,,,,,,] Returns UnmanagedMemoryBlock FromArray(T[,,,,,,,,,], bool) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,,,] arr, bool copy) Parameters arr T[,,,,,,,,,] copy bool Returns UnmanagedMemoryBlock FromArray(T[,,,,,,,,]) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,,] arr) Parameters arr T[,,,,,,,,] Returns UnmanagedMemoryBlock FromArray(T[,,,,,,,,], bool) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,,] arr, bool copy) Parameters arr T[,,,,,,,,] copy bool Returns UnmanagedMemoryBlock FromArray(T[,,,,,,,]) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,] arr) Parameters arr T[,,,,,,,] Returns UnmanagedMemoryBlock FromArray(T[,,,,,,,], bool) public static UnmanagedMemoryBlock FromArray(T[,,,,,,,] arr, bool copy) Parameters arr T[,,,,,,,] copy bool Returns UnmanagedMemoryBlock FromArray(T[,,,,,,]) public static UnmanagedMemoryBlock FromArray(T[,,,,,,] arr) Parameters arr T[,,,,,,] Returns UnmanagedMemoryBlock FromArray(T[,,,,,,], bool) public static UnmanagedMemoryBlock FromArray(T[,,,,,,] arr, bool copy) Parameters arr T[,,,,,,] copy bool Returns UnmanagedMemoryBlock FromArray(T[,,,,,]) public static UnmanagedMemoryBlock FromArray(T[,,,,,] arr) Parameters arr T[,,,,,] Returns UnmanagedMemoryBlock FromArray(T[,,,,,], bool) public static UnmanagedMemoryBlock FromArray(T[,,,,,] arr, bool copy) Parameters arr T[,,,,,] copy bool Returns UnmanagedMemoryBlock FromArray(T[,,,,]) public static UnmanagedMemoryBlock FromArray(T[,,,,] arr) Parameters arr T[,,,,] Returns UnmanagedMemoryBlock FromArray(T[,,,,], bool) public static UnmanagedMemoryBlock FromArray(T[,,,,] arr, bool copy) Parameters arr T[,,,,] copy bool Returns UnmanagedMemoryBlock FromArray(T[,,,]) public static UnmanagedMemoryBlock FromArray(T[,,,] arr) Parameters arr T[,,,] Returns UnmanagedMemoryBlock FromArray(T[,,,], bool) public static UnmanagedMemoryBlock FromArray(T[,,,] arr, bool copy) Parameters arr T[,,,] copy bool Returns UnmanagedMemoryBlock FromArray(T[,,]) public static UnmanagedMemoryBlock FromArray(T[,,] arr) Parameters arr T[,,] Returns UnmanagedMemoryBlock FromArray(T[,,], bool) public static UnmanagedMemoryBlock FromArray(T[,,] arr, bool copy) Parameters arr T[,,] copy bool Returns UnmanagedMemoryBlock FromArray(T[,]) public static UnmanagedMemoryBlock FromArray(T[,] arr) Parameters arr T[,] Returns UnmanagedMemoryBlock FromArray(T[,], bool) public static UnmanagedMemoryBlock FromArray(T[,] arr, bool copy) Parameters arr T[,] copy bool Returns UnmanagedMemoryBlock FromArray(T[]) public static UnmanagedMemoryBlock FromArray(T[] arr) Parameters arr T[] Returns UnmanagedMemoryBlock FromArray(T[], bool) public static UnmanagedMemoryBlock FromArray(T[] arr, bool copy) Parameters arr T[] copy bool Returns UnmanagedMemoryBlock FromBuffer(byte[]) public static UnmanagedMemoryBlock FromBuffer(byte[] arr) Parameters arr byte[] Returns UnmanagedMemoryBlock FromBuffer(byte[], bool) public static UnmanagedMemoryBlock FromBuffer(byte[] arr, bool copy) Parameters arr byte[] copy bool Returns UnmanagedMemoryBlock FromPool(StackedMemoryPool) public static UnmanagedMemoryBlock FromPool(StackedMemoryPool manager) Parameters manager StackedMemoryPool Returns UnmanagedMemoryBlock GetEnumerator() Returns an enumerator that iterates through the collection. public IEnumerator GetEnumerator() Returns IEnumerator An enumerator that can be used to iterate through the collection. GetHashCode() Returns the hash code for this instance. public override int GetHashCode() Returns int A 32-bit signed integer that is the hash code for this instance. GetIndex(int) public T GetIndex(int index) Parameters index int Returns T GetIndex(long) public T GetIndex(long index) Parameters index long Returns T GetRefTo(int) public ref T GetRefTo(int index) Parameters index int Returns T GetRefTo(long) public ref T GetRefTo(long index) Parameters index long Returns T Reallocate(long, bool) public void Reallocate(long length, bool copyOldValues = false) Parameters length long copyOldValues bool Reallocate(long, T, bool) public void Reallocate(long length, T fill, bool copyOldValues = false) Parameters length long fill T copyOldValues bool SetIndex(int, T) public void SetIndex(int index, T value) Parameters index int value T SetIndex(int, ref T) public void SetIndex(int index, ref T value) Parameters index int value T SetIndex(long, T) public void SetIndex(long index, T value) Parameters index long value T SetIndex(long, ref T) public void SetIndex(long index, ref T value) Parameters index long value T Operators operator ==(UnmanagedMemoryBlock, UnmanagedMemoryBlock) Returns a value that indicates whether the values of two NumSharp.Backends.Unmanaged.UnmanagedArray`1 objects are equal. public static bool operator ==(UnmanagedMemoryBlock left, UnmanagedMemoryBlock right) Parameters left UnmanagedMemoryBlock The first value to compare. right UnmanagedMemoryBlock The second value to compare. Returns bool true if the left and right parameters have the same value; otherwise, false. operator !=(UnmanagedMemoryBlock, UnmanagedMemoryBlock) Returns a value that indicates whether two NumSharp.Backends.Unmanaged.UnmanagedArray`1 objects have different values. public static bool operator !=(UnmanagedMemoryBlock left, UnmanagedMemoryBlock right) Parameters left UnmanagedMemoryBlock The first value to compare. right UnmanagedMemoryBlock The second value to compare. Returns bool true if left and right are not equal; otherwise, false." + }, + "api/NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock.html": { + "href": "api/NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock.html", + "title": "Class UnmanagedMemoryBlock | NumSharp Documentation", + "summary": "Class UnmanagedMemoryBlock Namespace NumSharp.Backends.Unmanaged Assembly NumSharp.dll public static class UnmanagedMemoryBlock Inheritance object UnmanagedMemoryBlock Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Methods Allocate(Type, int) public static IMemoryBlock Allocate(Type elementType, int count) Parameters elementType Type count int Returns IMemoryBlock Allocate(Type, int, object) public static IMemoryBlock Allocate(Type elementType, int count, object fill) Parameters elementType Type count int fill object Returns IMemoryBlock CastTo(IMemoryBlock, IMemoryBlock, int?, int?) public static void CastTo(this IMemoryBlock source, IMemoryBlock @out, int? bytesOffset = null, int? countOffset = null) Parameters source IMemoryBlock out IMemoryBlock bytesOffset int? countOffset int? Remarks Returns a copy. CastTo(IMemoryBlock, NPTypeCode) public static IMemoryBlock CastTo(this IMemoryBlock source, NPTypeCode to) Parameters source IMemoryBlock to NPTypeCode The type to cast this memory block to. Returns IMemoryBlock Remarks Returns a copy. CastTo(IMemoryBlock) public static IMemoryBlock CastTo(this IMemoryBlock source) where TOut : unmanaged Parameters source IMemoryBlock Returns IMemoryBlock Type Parameters TOut Remarks Returns a copy. CastTo(IMemoryBlock) public static IMemoryBlock CastTo(this IMemoryBlock source) where TIn : unmanaged where TOut : unmanaged Parameters source IMemoryBlock Returns IMemoryBlock Type Parameters TIn TOut Remarks Returns a copy. CastTo(IMemoryBlock) public static IMemoryBlock CastTo(this IMemoryBlock source) where TIn : unmanaged where TOut : unmanaged Parameters source IMemoryBlock Returns IMemoryBlock Type Parameters TIn TOut Remarks Returns a copy. FromArray(Array, bool, Type) public static IMemoryBlock FromArray(Array arr, bool copy, Type elementType = null) Parameters arr Array copy bool elementType Type Returns IMemoryBlock" + }, + "api/NumSharp.Backends.Unmanaged.html": { + "href": "api/NumSharp.Backends.Unmanaged.html", + "title": "Namespace NumSharp.Backends.Unmanaged | NumSharp Documentation", + "summary": "Namespace NumSharp.Backends.Unmanaged Classes ArraySlice UnmanagedHelper UnmanagedMemoryBlock Structs ArraySlice ArraySlice is similar to Span but it can be moved around without having to follow ref struct rules. UnmanagedMemoryBlock Interfaces IArraySlice IMemoryBlock IMemoryBlock IUnmanagedMemoryBlock" + }, + "api/NumSharp.Backends.UnmanagedStorage.html": { + "href": "api/NumSharp.Backends.UnmanagedStorage.html", + "title": "Class UnmanagedStorage | NumSharp Documentation", + "summary": "Class UnmanagedStorage Namespace NumSharp.Backends Assembly NumSharp.dll Serves as a typed storage for an array. public class UnmanagedStorage : ICloneable Inheritance object UnmanagedStorage Implements ICloneable Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) NDIteratorExtensions.AsIterator(UnmanagedStorage, bool) Remarks Responsible for : store data type, elements, Shape offers methods for accessing elements depending on shape offers methods for casting elements offers methods for change tensor order GetData always return reference object to the true storage GetData{T} and SetData{T} change dtype and cast storage CloneData always create a clone of storage and return this as reference object CloneData{T} clone storage and cast this clone Constructors UnmanagedStorage(IArraySlice, Shape) Wraps given arraySlice in UnmanagedStorage. public UnmanagedStorage(IArraySlice arraySlice, Shape shape) Parameters arraySlice IArraySlice The slice to wrap shape Shape UnmanagedStorage(NPTypeCode) Creates an empty storage of type typeCode. public UnmanagedStorage(NPTypeCode typeCode) Parameters typeCode NPTypeCode The type of this storage Remarks Usually Allocate(Shape, Type) is called after this constructor. UnmanagedStorage(bool) public UnmanagedStorage(bool scalar) Parameters scalar bool UnmanagedStorage(bool[]) public UnmanagedStorage(bool[] values) Parameters values bool[] UnmanagedStorage(byte) public UnmanagedStorage(byte scalar) Parameters scalar byte UnmanagedStorage(byte[]) public UnmanagedStorage(byte[] values) Parameters values byte[] UnmanagedStorage(char) public UnmanagedStorage(char scalar) Parameters scalar char UnmanagedStorage(char[]) public UnmanagedStorage(char[] values) Parameters values char[] UnmanagedStorage(decimal) public UnmanagedStorage(decimal scalar) Parameters scalar decimal UnmanagedStorage(decimal[]) public UnmanagedStorage(decimal[] values) Parameters values decimal[] UnmanagedStorage(double) public UnmanagedStorage(double scalar) Parameters scalar double UnmanagedStorage(double[]) public UnmanagedStorage(double[] values) Parameters values double[] UnmanagedStorage(short) public UnmanagedStorage(short scalar) Parameters scalar short UnmanagedStorage(short[]) public UnmanagedStorage(short[] values) Parameters values short[] UnmanagedStorage(int) public UnmanagedStorage(int scalar) Parameters scalar int UnmanagedStorage(int[]) public UnmanagedStorage(int[] values) Parameters values int[] UnmanagedStorage(long) public UnmanagedStorage(long scalar) Parameters scalar long UnmanagedStorage(long[]) public UnmanagedStorage(long[] values) Parameters values long[] UnmanagedStorage(float) public UnmanagedStorage(float scalar) Parameters scalar float UnmanagedStorage(float[]) public UnmanagedStorage(float[] values) Parameters values float[] UnmanagedStorage(Type) Creates an empty storage of type dtype. public UnmanagedStorage(Type dtype) Parameters dtype Type The type of this storage Remarks Usually Allocate(Shape, Type) is called after this constructor. UnmanagedStorage(ushort) public UnmanagedStorage(ushort scalar) Parameters scalar ushort UnmanagedStorage(ushort[]) public UnmanagedStorage(ushort[] values) Parameters values ushort[] UnmanagedStorage(uint) public UnmanagedStorage(uint scalar) Parameters scalar uint UnmanagedStorage(uint[]) public UnmanagedStorage(uint[] values) Parameters values uint[] UnmanagedStorage(ulong) public UnmanagedStorage(ulong scalar) Parameters scalar ulong UnmanagedStorage(ulong[]) public UnmanagedStorage(ulong[] values) Parameters values ulong[] Fields Address public byte* Address Field Value byte* Count public int Count Field Value int InternalArray public IArraySlice InternalArray Field Value IArraySlice _arrayBoolean protected ArraySlice _arrayBoolean Field Value ArraySlice _arrayByte protected ArraySlice _arrayByte Field Value ArraySlice _arrayChar protected ArraySlice _arrayChar Field Value ArraySlice _arrayDecimal protected ArraySlice _arrayDecimal Field Value ArraySlice _arrayDouble protected ArraySlice _arrayDouble Field Value ArraySlice _arrayInt16 protected ArraySlice _arrayInt16 Field Value ArraySlice _arrayInt32 protected ArraySlice _arrayInt32 Field Value ArraySlice _arrayInt64 protected ArraySlice _arrayInt64 Field Value ArraySlice _arraySingle protected ArraySlice _arraySingle Field Value ArraySlice _arrayUInt16 protected ArraySlice _arrayUInt16 Field Value ArraySlice _arrayUInt32 protected ArraySlice _arrayUInt32 Field Value ArraySlice _arrayUInt64 protected ArraySlice _arrayUInt64 Field Value ArraySlice _dtype protected Type _dtype Field Value Type _shape protected Shape _shape Field Value Shape _typecode protected NPTypeCode _typecode Field Value NPTypeCode Properties DType The data type of internal storage array. public Type DType { get; } Property Value Type numpys equal dtype Remarks Has to be compliant with NPTypeCode. DTypeSize The size in bytes of a single value of DType public int DTypeSize { get; } Property Value int Remarks Computed by SizeOf(object) Engine The engine that was used to create this IStorage. public TensorEngine Engine { get; protected set; } Property Value TensorEngine Shape The shape representing the data in this storage. public Shape Shape { get; set; } Property Value Shape ShapeReference The shape representing the data in this storage. public ref Shape ShapeReference { get; } Property Value Shape Remarks It is dangerous to set Shape by reference. use Reshape(Shape) instead. TypeCode The NPTypeCode of IStorage.DType. public NPTypeCode TypeCode { get; } Property Value NPTypeCode Methods Alias() Creates an alias to this UnmanagedStorage. public UnmanagedStorage Alias() Returns UnmanagedStorage Alias(Shape) Creates an alias to this UnmanagedStorage with a specific shape. public UnmanagedStorage Alias(Shape shape) Parameters shape Shape Returns UnmanagedStorage Remarks Doesn't check if Shape matches the internal storage. Alias(ref Shape) Creates an alias to this UnmanagedStorage with a specific shape. public UnmanagedStorage Alias(ref Shape shape) Parameters shape Shape Returns UnmanagedStorage Remarks Doesn't check if Shape matches the internal storage. Allocate(IArraySlice, Shape, bool) Allocate values into memory. public void Allocate(IArraySlice values, Shape shape, bool copy = false) Parameters values IArraySlice The array to set as internal data storage shape Shape The shape of the array. copy bool Should perform a copy of values Remarks Does not copy values Allocate(Shape, NPTypeCode, bool) Allocates a new Array into memory. public void Allocate(Shape shape, NPTypeCode dtype, bool fillZeros) Parameters shape Shape The shape of the array. dtype NPTypeCode The type of the Array, if null DType is used. fillZeros bool Allocate(Shape, Type) Allocates a new Array into memory. public void Allocate(Shape shape, Type dtype = null) Parameters shape Shape The shape of the array. dtype Type The type of the Array, if null DType is used. Allocate(Shape, Type, bool) Allocates a new Array into memory. public void Allocate(Shape shape, Type dtype, bool fillZeros) Parameters shape Shape The shape of the array. dtype Type The type of the Array, if null DType is used. fillZeros bool Allocate(Array) Allocate array into memory. public void Allocate(Array array) Parameters array Array The array to set as internal data storage Remarks Does not copy array Allocate(Array, Shape) Allocate values into memory. public void Allocate(Array values, Shape shape) Parameters values Array The array to set as internal data storage shape Shape The shape of given array Remarks Does not copy values Allocate(ArraySlice, Shape, bool) Assign this ArraySlice as the internal array storage and assign shape to it. public void Allocate(ArraySlice values, Shape shape, bool copy = false) where T : unmanaged Parameters values ArraySlice The array to set as internal data storage shape Shape The shape of the array. copy bool Should perform a copy of values Type Parameters T Remarks Does not copy values Allocate(T[]) Allocate values into memory. public void Allocate(T[] values) where T : unmanaged Parameters values T[] The array to set as internal data storage Type Parameters T Remarks Does not copy values AsSpan() Spans Address <-> Count public Span AsSpan() Returns Span Type Parameters T Remarks This ignores completely slicing. Cast(NPTypeCode) Return a casted UnmanagedStorage to a specific dtype. public UnmanagedStorage Cast(NPTypeCode typeCode) Parameters typeCode NPTypeCode The dtype to convert to Returns UnmanagedStorage A copy of this UnmanagedStorage casted to a specific dtype. Remarks Always copies, If dtype==typeof(T) then a Clone() is returned. Cast(Type) Return a casted UnmanagedStorage to a specific dtype. public UnmanagedStorage Cast(Type dtype) Parameters dtype Type The dtype to convert to Returns UnmanagedStorage A copy of this UnmanagedStorage casted to a specific dtype. Remarks Always copies, If dtype==typeof(T) then a Clone() is returned. CastIfNecessary(NPTypeCode) Return a casted UnmanagedStorage to a specific dtype only if necessary public UnmanagedStorage CastIfNecessary(NPTypeCode typeCode) Parameters typeCode NPTypeCode The dtype to convert to Returns UnmanagedStorage A copy of this UnmanagedStorage casted to a specific dtype. Remarks Copies only if dtypes does not match typeCode CastIfNecessary(Type) Return a casted UnmanagedStorage to a specific dtype. public UnmanagedStorage CastIfNecessary(Type dtype) Parameters dtype Type The dtype to convert to Returns UnmanagedStorage A copy of this UnmanagedStorage casted to a specific dtype. Remarks Copies only if dtypes does not match typeCode CastIfNecessary() Return a casted UnmanagedStorage to a specific dtype only if necessary. public UnmanagedStorage CastIfNecessary() where T : unmanaged Returns UnmanagedStorage A copy of this UnmanagedStorage casted to a specific dtype. Type Parameters T The dtype to convert to Remarks Copies only if dtypes does not match T Cast() Return a casted UnmanagedStorage to a specific dtype. public UnmanagedStorage Cast() where T : unmanaged Returns UnmanagedStorage A copy of this UnmanagedStorage casted to a specific dtype. Type Parameters T The dtype to convert to Remarks Always copies, If dtype==typeof(T) then a Clone() is returned. Clone() Perform a complete copy of this UnmanagedStorage and InternalArray. public UnmanagedStorage Clone() Returns UnmanagedStorage Remarks If shape is sliced, discards any slicing properties but copies only the sliced data CloneData() Clone internal storage and get reference to it public IArraySlice CloneData() Returns IArraySlice reference to cloned storage as System.Array CloneData() Get all elements from cloned storage as ArraySlice and cast if necessary. public ArraySlice CloneData() where T : unmanaged Returns ArraySlice reference to cloned storage and casted (if necessary) as ArraySlice Type Parameters T cloned storgae dtype CopyTo(IMemoryBlock) Copies the entire contents of this storage to given address (using Count). public void CopyTo(IMemoryBlock block) Parameters block IMemoryBlock The block to copy to. CopyTo(nint) Copies the entire contents of this storage to given address. public void CopyTo(nint ptr) Parameters ptr nint CopyTo(void*) Copies the entire contents of this storage to given address. public void CopyTo(void* address) Parameters address void* The address to copy to. CopyTo(IMemoryBlock) Copies the entire contents of this storage to given address (using Count). public void CopyTo(IMemoryBlock block) where T : unmanaged Parameters block IMemoryBlock The block to copy to. Type Parameters T CopyTo(T*) Copies the entire contents of this storage to given address. public void CopyTo(T* address) where T : unmanaged Parameters address T* The address to copy to. Type Parameters T CopyTo(T[]) Copies the entire contents of this storage to given array. public void CopyTo(T[] array) where T : unmanaged Parameters array T[] The array to copy to. Type Parameters T CreateBroadcastedUnsafe(IArraySlice, Shape) Wraps given arraySlice in UnmanagedStorage with a broadcasted shape. public static UnmanagedStorage CreateBroadcastedUnsafe(IArraySlice arraySlice, Shape shape) Parameters arraySlice IArraySlice The slice to wrap shape Shape The shape to represent this storage, can be a broadcast. Returns UnmanagedStorage Remarks Named unsafe because there it does not perform a check if the shape is valid for this storage size. CreateBroadcastedUnsafe(UnmanagedStorage, Shape) Wraps given storage in UnmanagedStorage with a broadcasted shape. public static UnmanagedStorage CreateBroadcastedUnsafe(UnmanagedStorage storage, Shape shape) Parameters storage UnmanagedStorage The storage to take InternalArray from. shape Shape The shape to represent this storage, can be a broadcast. Returns UnmanagedStorage Remarks Named unsafe because there it does not perform a check if the shape is valid for this storage size. ExpandDimension(int) protected void ExpandDimension(int axis) Parameters axis int GetAtIndex(int) public ValueType GetAtIndex(int index) Parameters index int Returns ValueType GetAtIndex(int) public T GetAtIndex(int index) where T : unmanaged Parameters index int Returns T Type Parameters T GetBoolean(params int[]) Retrieves value of type bool from internal storage. public bool GetBoolean(params int[] indices) Parameters indices int[] The shape's indices to get. Returns bool Exceptions NullReferenceException When DType is not bool GetByte(params int[]) Retrieves value of type byte from internal storage. public byte GetByte(params int[] indices) Parameters indices int[] The shape's indices to get. Returns byte Exceptions NullReferenceException When DType is not byte GetChar(params int[]) Retrieves value of type char from internal storage. public char GetChar(params int[] indices) Parameters indices int[] The shape's indices to get. Returns char Exceptions NullReferenceException When DType is not char GetData() Get reference to internal data storage public IArraySlice GetData() Returns IArraySlice reference to internal storage as System.Array GetData(int*, int) Gets a subshape based on given indices. public UnmanagedStorage GetData(int* dims, int ndims) Parameters dims int* ndims int Returns UnmanagedStorage Remarks Does not copy, returns a Slice or a memory slice GetData(params int[]) Gets a subshape based on given indices. public UnmanagedStorage GetData(params int[] indices) Parameters indices int[] Returns UnmanagedStorage Remarks Does not copy, returns a Slice or a memory slice GetData() Get reference to internal data storage and cast (also copies) elements to new dtype if necessary public ArraySlice GetData() where T : unmanaged Returns ArraySlice reference to internal (casted) storage as T[] Type Parameters T new storage data type Remarks Copies if T does not equal to DType or if Shape is sliced. GetDecimal(params int[]) Retrieves value of type decimal from internal storage. public decimal GetDecimal(params int[] indices) Parameters indices int[] The shape's indices to get. Returns decimal Exceptions NullReferenceException When DType is not decimal GetDouble(params int[]) Retrieves value of type double from internal storage. public double GetDouble(params int[] indices) Parameters indices int[] The shape's indices to get. Returns double Exceptions NullReferenceException When DType is not double GetInt16(params int[]) Retrieves value of type short from internal storage. public short GetInt16(params int[] indices) Parameters indices int[] The shape's indices to get. Returns short Exceptions NullReferenceException When DType is not short GetInt32(params int[]) Retrieves value of type int from internal storage. public int GetInt32(params int[] indices) Parameters indices int[] The shape's indices to get. Returns int Exceptions NullReferenceException When DType is not int GetInt64(params int[]) Retrieves value of type long from internal storage. public long GetInt64(params int[] indices) Parameters indices int[] The shape's indices to get. Returns long Exceptions NullReferenceException When DType is not long GetSingle(params int[]) Retrieves value of type float from internal storage. public float GetSingle(params int[] indices) Parameters indices int[] The shape's indices to get. Returns float Exceptions NullReferenceException When DType is not float GetUInt16(params int[]) Retrieves value of type ushort from internal storage. public ushort GetUInt16(params int[] indices) Parameters indices int[] The shape's indices to get. Returns ushort Exceptions NullReferenceException When DType is not ushort GetUInt32(params int[]) Retrieves value of type uint from internal storage. public uint GetUInt32(params int[] indices) Parameters indices int[] The shape's indices to get. Returns uint Exceptions NullReferenceException When DType is not uint GetUInt64(params int[]) Retrieves value of type ulong from internal storage. public ulong GetUInt64(params int[] indices) Parameters indices int[] The shape's indices to get. Returns ulong Exceptions NullReferenceException When DType is not ulong GetValue(params int[]) Retrieves value of unspecified type (will figure using IStorage.DType). public ValueType GetValue(params int[] indices) Parameters indices int[] The shape's indices to get. Returns ValueType Exceptions NullReferenceException When IStorage.DType is not object GetValue(params int[]) Get single value from internal storage as type T and cast dtype to T public T GetValue(params int[] indices) where T : unmanaged Parameters indices int[] indices Returns T element from internal storage Type Parameters T new storage data type Remarks If you provide less indices than there are dimensions, the rest are filled with 0. Exceptions NullReferenceException When T does not equal to DType GetView(params Slice[]) public UnmanagedStorage GetView(params Slice[] slices) Parameters slices Slice[] Returns UnmanagedStorage GetView(string) public UnmanagedStorage GetView(string slicing_notation) Parameters slicing_notation string Returns UnmanagedStorage ReplaceData(IArraySlice) Sets values as the internal data source and changes the internal storage data type to values type. public void ReplaceData(IArraySlice values) Parameters values IArraySlice Remarks Does not copy values and doesn't change shape. ReplaceData(IArraySlice, Shape) Sets values as the internal data source and changes the internal storage data type to values type. public void ReplaceData(IArraySlice values, Shape shape) Parameters values IArraySlice shape Shape The shape to set in this storage. (without checking if shape matches storage) Remarks Does not copy values and doesn't change shape. Doesn't check if shape size matches. ReplaceData(IArraySlice, Type) Sets values as the internal data source and changes the internal storage data type to values type. public void ReplaceData(IArraySlice values, Type dtype) Parameters values IArraySlice dtype Type Remarks Does not copy values and doesn't change shape. ReplaceData(IArraySlice, Type, Shape) Sets values as the internal data source and changes the internal storage data type to values type. public void ReplaceData(IArraySlice values, Type dtype, Shape shape) Parameters values IArraySlice dtype Type shape Shape The shape to set in this storage. (without checking if shape matches storage) Remarks Does not copy values and doesn't change shape. Doesn't check if shape size matches. ReplaceData(NDArray) Sets nd as the internal data storage and changes the internal storage data type to nd type. public void ReplaceData(NDArray nd) Parameters nd NDArray Remarks Does not copy values and does change shape and dtype. ReplaceData(NDArray, Shape) Sets nd as the internal data storage and changes the internal storage data type to nd type. public void ReplaceData(NDArray nd, Shape shape) Parameters nd NDArray shape Shape The shape to set in this storage. (without checking if shape matches storage) Remarks Does not copy values and does change shape and dtype. Doesn't check if shape size matches. ReplaceData(Array) Sets values as the internal data source and changes the internal storage data type to values type. public void ReplaceData(Array values) Parameters values Array Remarks Copies values only if values type does not match DType and doesn't change shape. ReplaceData(Array, NPTypeCode) Set an Array to internal storage, cast it to new dtype and if necessary change dtype public void ReplaceData(Array values, NPTypeCode typeCode) Parameters values Array typeCode NPTypeCode Remarks Does not copy values unless cast is necessary and doesn't change shape. ReplaceData(Array, NPTypeCode, Shape) Set an Array to internal storage, cast it to new dtype and if necessary change dtype public void ReplaceData(Array values, NPTypeCode typeCode, Shape shape) Parameters values Array typeCode NPTypeCode shape Shape The shape to set in this storage. (without checking if shape matches storage) Remarks Does not copy values unless cast is necessary and doesn't change shape. Doesn't check if shape size matches. ReplaceData(Array, Shape) Sets values as the internal data source and changes the internal storage data type to values type. public void ReplaceData(Array values, Shape shape) Parameters values Array shape Shape The shape to set in this storage. (without checking if shape matches storage) Remarks Copies values only if values type does not match DType and doesn't change shape. Doesn't check if shape size matches. ReplaceData(Array, Type) Set an Array to internal storage, cast it to new dtype and change dtype public void ReplaceData(Array values, Type dtype) Parameters values Array dtype Type Remarks Does not copy values unless cast in necessary and doesn't change shape. ReplaceData(Array, Type, Shape) Set an Array to internal storage, cast it to new dtype and change dtype public void ReplaceData(Array values, Type dtype, Shape shape) Parameters values Array dtype Type shape Shape The shape to set in this storage. (without checking if shape matches storage) Remarks Does not copy values unless cast in necessary and doesn't change shape. Doesn't check if shape size matches. Reshape(Shape, bool) Changes the shape representing this storage. public void Reshape(Shape newShape, bool @unsafe = false) Parameters newShape Shape unsafe bool Exceptions IncorrectShapeException If shape's size mismatches current shape size. ArgumentException If newShape's size == 0 Reshape(ref Shape, bool) Changes the shape representing this storage. public void Reshape(ref Shape newShape, bool @unsafe = false) Parameters newShape Shape unsafe bool Exceptions IncorrectShapeException If shape's size mismatches current shape size. ArgumentException If newShape's size == 0 Reshape(params int[]) Changes the shape representing this storage. public void Reshape(params int[] dimensions) Parameters dimensions int[] Exceptions IncorrectShapeException If shape's size mismatches current shape size. Reshape(int[], bool) Changes the shape representing this storage. public void Reshape(int[] dimensions, bool @unsafe) Parameters dimensions int[] unsafe bool Exceptions IncorrectShapeException If shape's size mismatches current shape size. ArgumentException If dimensions's size == 0 Scalar(object) public static UnmanagedStorage Scalar(object value) Parameters value object Returns UnmanagedStorage Scalar(object, NPTypeCode) public static UnmanagedStorage Scalar(object value, NPTypeCode typeCode) Parameters value object typeCode NPTypeCode Returns UnmanagedStorage Scalar(T) public static UnmanagedStorage Scalar(T value) where T : unmanaged Parameters value T Returns UnmanagedStorage Type Parameters T SetAtIndex(object, int) public void SetAtIndex(object value, int index) Parameters value object index int SetAtIndexUnsafe(ValueType, int) Performs a set of index without calling TransformOffset(int). public void SetAtIndexUnsafe(ValueType value, int index) Parameters value ValueType index int SetAtIndexUnsafe(T, int) Performs a set of index without calling TransformOffset(int). public void SetAtIndexUnsafe(T value, int index) where T : unmanaged Parameters value T index int Type Parameters T SetAtIndex(T, int) public void SetAtIndex(T value, int index) where T : unmanaged Parameters value T index int Type Parameters T SetBoolean(bool, params int[]) Sets a bool at specific coordinates. public void SetBoolean(bool value, params int[] indices) Parameters value bool The values to assign indices int[] The coordinates to set value at. SetByte(byte, params int[]) Sets a byte at specific coordinates. public void SetByte(byte value, params int[] indices) Parameters value byte The values to assign indices int[] The coordinates to set value at. SetChar(char, params int[]) Sets a char at specific coordinates. public void SetChar(char value, params int[] indices) Parameters value char The values to assign indices int[] The coordinates to set value at. SetData(IArraySlice, params int[]) Set a IArraySlice at given indices. public void SetData(IArraySlice value, params int[] indices) Parameters value IArraySlice The value to set indices int[] The Remarks Does not change internal storage data type. If value does not match DType, value will be converted. SetData(NDArray, params int[]) Set a NDArray at given indices. public void SetData(NDArray value, params int[] indices) Parameters value NDArray The value to set indices int[] The Remarks Does not change internal storage data type. If value does not match DType, value will be converted. SetData(object, params int[]) Set a single value at given indices. public void SetData(object value, params int[] indices) Parameters value object The value to set indices int[] The Remarks Does not change internal storage data type. If value does not match DType, value will be converted. SetDecimal(decimal, params int[]) Sets a decimal at specific coordinates. public void SetDecimal(decimal value, params int[] indices) Parameters value decimal The values to assign indices int[] The coordinates to set value at. SetDouble(double, params int[]) Sets a double at specific coordinates. public void SetDouble(double value, params int[] indices) Parameters value double The values to assign indices int[] The coordinates to set value at. SetInt16(short, params int[]) Sets a short at specific coordinates. public void SetInt16(short value, params int[] indices) Parameters value short The values to assign indices int[] The coordinates to set value at. SetInt32(int, params int[]) Sets a int at specific coordinates. public void SetInt32(int value, params int[] indices) Parameters value int The values to assign indices int[] The coordinates to set value at. SetInt64(long, params int[]) Sets a long at specific coordinates. public void SetInt64(long value, params int[] indices) Parameters value long The values to assign indices int[] The coordinates to set value at. SetInternalArray(IArraySlice) Replace internal storage array with given array. protected void SetInternalArray(IArraySlice array) Parameters array IArraySlice The array to set as internal storage Exceptions InvalidCastException When type of array does not match DType of this storage SetInternalArray(Array) Replace internal storage array with given array. protected void SetInternalArray(Array array) Parameters array Array The array to set as internal storage Exceptions InvalidCastException When type of array does not match DType of this storage SetShapeUnsafe(Shape) Set the shape of this storage without checking if sizes match. protected void SetShapeUnsafe(Shape shape) Parameters shape Shape Remarks Used during broadcasting SetShapeUnsafe(ref Shape) Set the shape of this storage without checking if sizes match. protected void SetShapeUnsafe(ref Shape shape) Parameters shape Shape Remarks Used during broadcasting SetSingle(float, params int[]) Sets a float at specific coordinates. public void SetSingle(float value, params int[] indices) Parameters value float The values to assign indices int[] The coordinates to set value at. SetUInt16(ushort, params int[]) Sets a ushort at specific coordinates. public void SetUInt16(ushort value, params int[] indices) Parameters value ushort The values to assign indices int[] The coordinates to set value at. SetUInt32(uint, params int[]) Sets a uint at specific coordinates. public void SetUInt32(uint value, params int[] indices) Parameters value uint The values to assign indices int[] The coordinates to set value at. SetUInt64(ulong, params int[]) Sets a ulong at specific coordinates. public void SetUInt64(ulong value, params int[] indices) Parameters value ulong The values to assign indices int[] The coordinates to set value at. SetValue(object, params int[]) Set a single value at given indices. public void SetValue(object value, params int[] indices) Parameters value object The value to set indices int[] The Remarks Does not change internal storage data type. If value does not match DType, value will be converted. SetValue(T, params int[]) Set a single value at given indices. public void SetValue(T value, params int[] indices) where T : unmanaged Parameters value T The value to set indices int[] The Type Parameters T Remarks Does not change internal storage data type. If value does not match DType, value will be converted. ToArray() public T[] ToArray() where T : unmanaged Returns T[] Type Parameters T _Allocate(Shape, IArraySlice) protected void _Allocate(Shape shape, IArraySlice values) Parameters shape Shape values IArraySlice _ChangeTypeOfArray(Array, Type) Changes the type of sourceArray to to_dtype if necessary. [SuppressMessage(\"ReSharper\", \"AssignNullToNotNullAttribute\")] protected static Array _ChangeTypeOfArray(Array sourceArray, Type to_dtype) Parameters sourceArray Array The array to change his type to_dtype Type The type to change to. Returns Array Returns sourceArray or new array with changed type to to_dtype Remarks If the return type is equal to source type, this method does not return a copy. _ChangeTypeOfArray(IArraySlice) Changes the type of sourceArray to to_dtype if necessary. [SuppressMessage(\"ReSharper\", \"AssignNullToNotNullAttribute\")] protected static ArraySlice _ChangeTypeOfArray(IArraySlice sourceArray) where TOut : unmanaged Parameters sourceArray IArraySlice The array to change his type Returns ArraySlice Returns sourceArray or new array with changed type to to_dtype Type Parameters TOut Remarks If the return type is equal to source type, this method does not return a copy." + }, + "api/NumSharp.Backends.html": { + "href": "api/NumSharp.Backends.html", + "title": "Namespace NumSharp.Backends | NumSharp Documentation", + "summary": "Namespace NumSharp.Backends Classes BackendFactory DefaultEngine Default Tensor Engine implemented in pure micro-optimized C#. UnmanagedStorage Serves as a typed storage for an array." + }, + "api/NumSharp.BroadcastInfo.html": { + "href": "api/NumSharp.BroadcastInfo.html", + "title": "Class BroadcastInfo | NumSharp Documentation", + "summary": "Class BroadcastInfo Namespace NumSharp Assembly NumSharp.dll public class BroadcastInfo : ICloneable Inheritance object BroadcastInfo Implements ICloneable Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Constructors BroadcastInfo() public BroadcastInfo() BroadcastInfo(Shape) public BroadcastInfo(Shape originalShape) Parameters originalShape Shape Fields OriginalShape The original shape prior to broadcasting. public Shape OriginalShape Field Value Shape UnreducedBroadcastedShape Represents a shape with the same number of dimensions that the broadcasted ones are set to dim of 1. public Shape? UnreducedBroadcastedShape Field Value Shape? Remarks This shape is lazyloaded during runtime when calling Shape.GetOffset and other methods. Methods Clone() public BroadcastInfo Clone() Returns BroadcastInfo" + }, + "api/NumSharp.DType.html": { + "href": "api/NumSharp.DType.html", + "title": "Class DType | NumSharp Documentation", + "summary": "Class DType Namespace NumSharp Assembly NumSharp.dll public class DType Inheritance object DType Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.dtype.html#numpy.dtype Constructors DType(Type) Initializes a new instance of the object class. public DType(Type type) Parameters type Type Fields _kind_list_map protected static readonly FrozenDictionary _kind_list_map Field Value FrozenDictionary byteorder A character indicating the byte-order of this data-type object. One of: '=' native '<' little-endian '>' big-endian '|' not applicable public char byteorder Field Value char itemsize The size of the dtype in bytes. public int itemsize Field Value int kind A character code (one of ‘biufcmMOSUV’) identifying the general kind of data. b boolean i signed integer u unsigned integer f floating-point c complex floating-point m timedelta M datetime O object S(byte-)string U Unicode V void public char kind Field Value char name The name of this dtype. public string name Field Value string type The actual type this dtype represents. public Type type Field Value Type typecode The NumSharp type code. public NPTypeCode typecode Field Value NPTypeCode Properties char A unique character code for each of the 21 different built-in types. public char @char { get; } Property Value char Methods newbyteorder(char) Return a new dtype with a different byte order. Changes are also made in all fields and sub-arrays of the data type. public DType newbyteorder(char new_order = 'S') Parameters new_order char Byte order to force; a value from the byte order specifications below. The default value (‘S’) results in swapping the current byte order. new_order codes can be any of: ‘S’ - swap dtype from current to opposite endian '=' - native order '<' - little-endian '>' - big-endian '|' - ignore(no change to byte order) The code does a case-insensitive check on the first letter of new_order for these alternatives. For example, any of ‘>’ or ‘B’ or ‘b’ or ‘brian’ are valid to specify big-endian. Returns DType New dtype object with the given change to the byte order." + }, + "api/NumSharp.Extensions.LinqExtensions.html": { + "href": "api/NumSharp.Extensions.LinqExtensions.html", + "title": "Class LinqExtensions | NumSharp Documentation", + "summary": "Class LinqExtensions Namespace NumSharp.Extensions Assembly NumSharp.dll public static class LinqExtensions Inheritance object LinqExtensions Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Methods Yield(T) public static IEnumerable Yield(this T item) Parameters item T Returns IEnumerable Type Parameters T" + }, + "api/NumSharp.Extensions.html": { + "href": "api/NumSharp.Extensions.html", + "title": "Namespace NumSharp.Extensions | NumSharp Documentation", + "summary": "Namespace NumSharp.Extensions Classes LinqExtensions" + }, + "api/NumSharp.Generic.NDArray-1.html": { + "href": "api/NumSharp.Generic.NDArray-1.html", + "title": "Class NDArray | NumSharp Documentation", + "summary": "Class NDArray Namespace NumSharp.Generic Assembly NumSharp.dll public class NDArray : NDArray, IIndex, ICloneable, IEnumerable where TDType : unmanaged Type Parameters TDType Inheritance object NDArray NDArray Implements IIndex ICloneable IEnumerable Inherited Members NDArray.tofile(string) NDArray.CopyTo(IMemoryBlock) NDArray.CopyTo(void*) NDArray.CopyTo(T[]) NDArray.CopyTo(nint) NDArray.CopyTo(IMemoryBlock) NDArray.CopyTo(T*) NDArray.tensorEngine NDArray.dtype NDArray.typecode NDArray.shape NDArray.ndim NDArray.size NDArray.dtypesize NDArray.order NDArray.strides NDArray.Shape NDArray.Storage NDArray.TensorEngine NDArray.Data() NDArray.CloneData() NDArray.CloneData() NDArray.astype(Type, bool) NDArray.astype(NPTypeCode, bool) NDArray.Clone() NDArray.GetEnumerator() NDArray.view(Type) NDArray.view() NDArray.GetNDArrays(int) NDArray.GetData() NDArray.GetData() NDArray.GetData(params int[]) NDArray.GetBoolean(params int[]) NDArray.GetByte(params int[]) NDArray.GetChar(params int[]) NDArray.GetDecimal(params int[]) NDArray.GetDouble(params int[]) NDArray.GetInt16(params int[]) NDArray.GetInt32(params int[]) NDArray.GetInt64(params int[]) NDArray.GetSingle(params int[]) NDArray.GetUInt16(params int[]) NDArray.GetUInt32(params int[]) NDArray.GetUInt64(params int[]) NDArray.GetValue(params int[]) NDArray.GetValue(params int[]) NDArray.GetAtIndex(int) NDArray.SetData(IArraySlice, params int[]) NDArray.SetData(NDArray, params int[]) NDArray.SetData(object, params int[]) NDArray.SetValue(ValueType, params int[]) NDArray.SetValue(object, params int[]) NDArray.SetValue(T, params int[]) NDArray.ReplaceData(Array, Type) NDArray.ReplaceData(Array) NDArray.ReplaceData(NDArray) NDArray.ReplaceData(Array, NPTypeCode) NDArray.ReplaceData(IArraySlice, Type) NDArray.ReplaceData(IArraySlice) NDArray.SetAtIndex(object, int) NDArray.SetAtIndex(T, int) NDArray.SetBoolean(bool, params int[]) NDArray.SetByte(byte, params int[]) NDArray.SetInt16(short, params int[]) NDArray.SetUInt16(ushort, params int[]) NDArray.SetInt32(int, params int[]) NDArray.SetUInt32(uint, params int[]) NDArray.SetInt64(long, params int[]) NDArray.SetUInt64(ulong, params int[]) NDArray.SetChar(char, params int[]) NDArray.SetDouble(double, params int[]) NDArray.SetSingle(float, params int[]) NDArray.SetDecimal(decimal, params int[]) NDArray.FromString(string) NDArray.AsString(NDArray) NDArray.AsStringArray(NDArray) NDArray.GetString(params int[]) NDArray.SetString(string, params int[]) NDArray.GetStringAt(int) NDArray.SetStringAt(string, int) NDArray.Unsafe NDArray.ToByteArray() NDArray.ToString() NDArray.ToString(bool) NDArray.FromMultiDimArray(Array, bool) NDArray.ToJaggedArray() NDArray.ToArray() NDArray.ToMuliDimArray() NDArray.copy(char) NDArray.dstack(params NDArray[]) NDArray.flatten(char) NDArray.hstack(params NDArray[]) NDArray.MakeGeneric() NDArray.AsGeneric() NDArray.AsOrMakeGeneric() NDArray.mgrid(NDArray) NDArray.Scalar(object, Type) NDArray.Scalar(object) NDArray.Scalar(ValueType) NDArray.Scalar(T) NDArray.Scalar(object) NDArray.Scalar(object, NPTypeCode) NDArray.vstack(params NDArray[]) NDArray.Normalize() NDArray.dot(in NDArray) NDArray.inv() NDArray.lstqr(NDArray, double) NDArray.matrix_power(int) NDArray.multi_dot(params NDArray[]) NDArray.qr() NDArray.svd() NDArray.SetData(object) NDArray.delete(IEnumerable) NDArray.flatten(bool) NDArray.itemset(ref Shape, ValueType) NDArray.itemset(Shape, ValueType) NDArray.itemset(int[], ValueType) NDArray.itemset(int[], T) NDArray.ravel() NDArray.roll(int, int) NDArray.roll(int) NDArray.swapaxes(int, int) NDArray.transpose(int[]) NDArray.unique() NDArray.unique() NDArray.convolve(NDArray, string) NDArray.cumsum(int?, Type) NDArray.negate() NDArray.negative() NDArray.positive() NDArray.prod(int?, Type, bool) NDArray.sum(int, bool, Type) NDArray.sum(int, bool, NPTypeCode?) NDArray.sum(int) NDArray.sum() NDArray.Equals(object) NDArray.array_equal(NDArray) NDArray.this[int*, int] NDArray.this[NDArray[]] NDArray.this[object[]] NDArray.this[NDArray] NDArray.ExpandEllipsis(object[], int) NDArray.GetIndicesFromSlice(Shape, Slice, int) NDArray.GetIndicesFromSlice(int[], Slice, int) NDArray.PrepareIndexGetters(Shape, NDArray[]) NDArray.GetIndices(NDArray, NDArray[]) NDArray.FetchIndices(NDArray, NDArray[], NDArray, bool) NDArray.FetchIndices(NDArray, NDArray[], NDArray, bool) NDArray.FetchIndicesND(NDArray, NDArray, NDArray[], int, int[], int[], NDArray) NDArray.FetchIndicesNDNonLinear(NDArray, NDArray[], int, int[], int[], NDArray) NDArray.SetIndices(NDArray, NDArray[]) NDArray.SetIndices(object[], NDArray) NDArray.SetIndices(NDArray, NDArray[], NDArray) NDArray.SetIndices(NDArray, NDArray[], NDArray) NDArray.SetIndicesND(NDArray, NDArray, NDArray[], int, int[], int[], NDArray) NDArray.SetIndicesNDNonLinear(NDArray, NDArray[], int, int[], int[], NDArray) NDArray.argsort(int) NDArray.amax() NDArray.amax(int, bool, Type) NDArray.amax(Type) NDArray.max() NDArray.max(int, bool, Type) NDArray.max(Type) NDArray.amin() NDArray.amin(int, bool, Type) NDArray.amin(Type) NDArray.min() NDArray.min(int, bool, Type) NDArray.min(Type) NDArray.argmax() NDArray.argmax(int) NDArray.argmin() NDArray.argmin(int) NDArray.mean() NDArray.mean(int) NDArray.mean(int, Type, bool) NDArray.mean(int, NPTypeCode, bool) NDArray.mean(int, bool) NDArray.std(bool, int?, NPTypeCode?) NDArray.std(int, bool, int?, NPTypeCode?) NDArray.var(bool, int?, NPTypeCode?) NDArray.var(int, bool, int?, NPTypeCode?) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) NDIteratorExtensions.AsIterator(NDArray, bool) NDIteratorExtensions.AsIterator(NDArray, bool) Constructors NDArray() Constructor for init data type internal storage is 1D with 1 element public NDArray() Remarks This constructor does not call allocation/> NDArray(IArraySlice, Shape, char) Constructor which takes .NET array dtype and shape is determined from array public NDArray(IArraySlice values, Shape shape = default, char order = 'C') Parameters values IArraySlice shape Shape order char Remarks This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type) NDArray(UnmanagedStorage) Creates a new NDArray with this storage. protected NDArray(UnmanagedStorage storage) Parameters storage UnmanagedStorage NDArray(UnmanagedStorage, Shape) Creates a new NDArray with this storage. protected NDArray(UnmanagedStorage storage, Shape shape) Parameters storage UnmanagedStorage shape Shape NDArray(UnmanagedStorage, ref Shape) Creates a new NDArray with this storage. protected NDArray(UnmanagedStorage storage, ref Shape shape) Parameters storage UnmanagedStorage shape Shape NDArray(Shape) Constructor which initialize elements with 0 type and shape are given. public NDArray(Shape shape) Parameters shape Shape Shape of NDArray Remarks This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type) NDArray(Shape, bool) Constructor which initialize elements with 0 type and shape are given. public NDArray(Shape shape, bool fillZeros) Parameters shape Shape Shape of NDArray fillZeros bool Should set the values of the new allocation to default(dtype)? otherwise - old memory noise Remarks This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type) NDArray(TensorEngine) Constructor for init data type internal storage is 1D with 1 element protected NDArray(TensorEngine engine) Parameters engine TensorEngine The engine of this NDArray Remarks This constructor does not call allocation/> NDArray(Array, Shape, char) Constructor which takes .NET array dtype and shape is determined from array public NDArray(Array values, Shape shape = default, char order = 'C') Parameters values Array shape Shape order char Remarks This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type) NDArray(int) Constructor which initialize elements with length of size public NDArray(int size) Parameters size int The size as a single dimension shape Remarks This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type) NDArray(int, bool) Constructor which initialize elements with length of size public NDArray(int size, bool fillZeros) Parameters size int The size as a single dimension shape fillZeros bool Should set the values of the new allocation to default(dtype)? otherwise - old memory noise Remarks This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type) Properties Address Gets the address that this NDArray starts from. protected TDType* Address { get; } Property Value TDType* Array Array access to storage data - overridden on purpose protected ArraySlice Array { get; set; } Property Value ArraySlice this[Slice[]] slicing of generic - overridden on purpose public NDArray this[params Slice[] slices] { get; set; } Parameters slices Slice[] Property Value NDArray this[int[]] public TDType this[params int[] indices] { get; set; } Parameters indices int[] Property Value TDType this[string] slicing of generic - overridden on purpose public NDArray this[string slice] { get; set; } Parameters slice string Property Value NDArray T The transposed array. Same as self.transpose(). public NDArray T { get; } Property Value NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.T.html flat A 1-D iterator over the array. public NDArray flat { get; } Property Value NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flat.html Methods GetAtIndex(int) public TDType GetAtIndex(int index) Parameters index int Returns TDType reshape(Shape) Gives a new shape to an array without changing its data. public NDArray reshape(Shape newShape) Parameters newShape Shape The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions. Returns NDArray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html reshape(ref Shape) Gives a new shape to an array without changing its data. public NDArray reshape(ref Shape newShape) Parameters newShape Shape The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions. Returns NDArray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html reshape(params int[]) Gives a new shape to an array without changing its data. [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] public NDArray reshape(params int[] shape) Parameters shape int[] The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions. Returns NDArray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html reshape_unsafe(Shape) Gives a new shape to an array without changing its data. public NDArray reshape_unsafe(Shape newshape) Parameters newshape Shape The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions. Returns NDArray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html reshape_unsafe(ref Shape) Gives a new shape to an array without changing its data. public NDArray reshape_unsafe(ref Shape newShape) Parameters newShape Shape Returns NDArray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html reshape_unsafe(params int[]) Gives a new shape to an array without changing its data. [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] public NDArray reshape_unsafe(params int[] shape) Parameters shape int[] The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions. Returns NDArray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html Operators explicit operator NDArray(TDType[]) public static explicit operator NDArray(TDType[] tArray) Parameters tArray TDType[] Returns NDArray implicit operator ArraySlice(NDArray) public static implicit operator ArraySlice(NDArray nd) Parameters nd NDArray Returns ArraySlice" + }, + "api/NumSharp.Generic.html": { + "href": "api/NumSharp.Generic.html", + "title": "Namespace NumSharp.Generic | NumSharp Documentation", + "summary": "Namespace NumSharp.Generic Classes NDArray" + }, + "api/NumSharp.IIndex.html": { + "href": "api/NumSharp.IIndex.html", + "title": "Interface IIndex | NumSharp Documentation", + "summary": "Interface IIndex Namespace NumSharp Assembly NumSharp.dll Represents a class that can be served as an index, e.g. ndarray[new Slice(...)] public interface IIndex Extension Methods LinqExtensions.Yield(T)" + }, + "api/NumSharp.INumSharpException.html": { + "href": "api/NumSharp.INumSharpException.html", + "title": "Interface INumSharpException | NumSharp Documentation", + "summary": "Interface INumSharpException Namespace NumSharp Assembly NumSharp.dll public interface INumSharpException Extension Methods LinqExtensions.Yield(T)" + }, + "api/NumSharp.IncorrectShapeException.html": { + "href": "api/NumSharp.IncorrectShapeException.html", + "title": "Class IncorrectShapeException | NumSharp Documentation", + "summary": "Class IncorrectShapeException Namespace NumSharp Assembly NumSharp.dll public class IncorrectShapeException : NumSharpException, ISerializable, INumSharpException Inheritance object Exception NumSharpException IncorrectShapeException Implements ISerializable INumSharpException Inherited Members Exception.GetBaseException() Exception.GetType() Exception.ToString() Exception.Data Exception.HelpLink Exception.HResult Exception.InnerException Exception.Message Exception.Source Exception.StackTrace Exception.TargetSite Exception.SerializeObjectState object.Equals(object) object.Equals(object, object) object.GetHashCode() object.MemberwiseClone() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) Constructors IncorrectShapeException() public IncorrectShapeException() IncorrectShapeException(string) public IncorrectShapeException(string message) Parameters message string" + }, + "api/NumSharp.IncorrectSizeException.html": { + "href": "api/NumSharp.IncorrectSizeException.html", + "title": "Class IncorrectSizeException | NumSharp Documentation", + "summary": "Class IncorrectSizeException Namespace NumSharp Assembly NumSharp.dll public class IncorrectSizeException : NumSharpException, ISerializable, INumSharpException Inheritance object Exception NumSharpException IncorrectSizeException Implements ISerializable INumSharpException Inherited Members Exception.GetBaseException() Exception.GetType() Exception.ToString() Exception.Data Exception.HelpLink Exception.HResult Exception.InnerException Exception.Message Exception.Source Exception.StackTrace Exception.TargetSite Exception.SerializeObjectState object.Equals(object) object.Equals(object, object) object.GetHashCode() object.MemberwiseClone() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) Constructors IncorrectSizeException(string) public IncorrectSizeException(string message) Parameters message string" + }, + "api/NumSharp.IncorrectTypeException.html": { + "href": "api/NumSharp.IncorrectTypeException.html", + "title": "Class IncorrectTypeException | NumSharp Documentation", + "summary": "Class IncorrectTypeException Namespace NumSharp Assembly NumSharp.dll public class IncorrectTypeException : NumSharpException, ISerializable, INumSharpException Inheritance object Exception NumSharpException IncorrectTypeException Implements ISerializable INumSharpException Inherited Members Exception.GetBaseException() Exception.GetType() Exception.ToString() Exception.Data Exception.HelpLink Exception.HResult Exception.InnerException Exception.Message Exception.Source Exception.StackTrace Exception.TargetSite Exception.SerializeObjectState object.Equals(object) object.Equals(object, object) object.GetHashCode() object.MemberwiseClone() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) Constructors IncorrectTypeException() public IncorrectTypeException() IncorrectTypeException(string) public IncorrectTypeException(string message) Parameters message string" + }, + "api/NumSharp.IteratorType.html": { + "href": "api/NumSharp.IteratorType.html", + "title": "Enum IteratorType | NumSharp Documentation", + "summary": "Enum IteratorType Namespace NumSharp Assembly NumSharp.dll public enum IteratorType Extension Methods LinqExtensions.Yield(T) Fields Scalar = 0 Vector = 1 Matrix = 2 Tensor = 3" + }, + "api/NumSharp.Kwargs.html": { + "href": "api/NumSharp.Kwargs.html", + "title": "Class Kwargs | NumSharp Documentation", + "summary": "Class Kwargs Namespace NumSharp Assembly NumSharp.dll public class Kwargs Inheritance object Kwargs Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Constructors Kwargs() public Kwargs() Kwargs(string, bool, bool) Kwargs constructor public Kwargs(string indexing, bool sparse, bool copy) Parameters indexing string {'xy', 'ij'}, optional Cartesian('xy', default) or matrix('ij') indexing of output. sparse bool If True a sparse grid is returned in order to conserve memory. Default is False. copy bool If False, a view into the original arrays are returned in order to conserve memory. Default is True.Please note that sparse= False, copy= False`` will likely return non-contiguous arrays. Furthermore, more than one element of a broadcast array may refer to a single memory location. If you need to write to the arrays, make copies first. Properties copy public bool copy { get; set; } Property Value bool indexing public string indexing { get; set; } Property Value string sparse public bool sparse { get; set; } Property Value bool" + }, + "api/NumSharp.MoveNextReferencedDelegate-1.html": { + "href": "api/NumSharp.MoveNextReferencedDelegate-1.html", + "title": "Delegate MoveNextReferencedDelegate | NumSharp Documentation", + "summary": "Delegate MoveNextReferencedDelegate Namespace NumSharp Assembly NumSharp.dll public delegate ref T MoveNextReferencedDelegate() where T : unmanaged Returns T Type Parameters T Extension Methods LinqExtensions.Yield(T)" + }, + "api/NumSharp.MultiIterator.html": { + "href": "api/NumSharp.MultiIterator.html", + "title": "Class MultiIterator | NumSharp Documentation", + "summary": "Class MultiIterator Namespace NumSharp Assembly NumSharp.dll public static class MultiIterator Inheritance object MultiIterator Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Methods Assign(UnmanagedStorage, UnmanagedStorage) Assigns rhs values to lhs. public static void Assign(UnmanagedStorage lhs, UnmanagedStorage rhs) Parameters lhs UnmanagedStorage rhs UnmanagedStorage Remarks Stops at first iterator stop. Assign(NDArray, NDArray) Assigns rhs values to lhs. public static void Assign(NDArray lhs, NDArray rhs) Parameters lhs NDArray rhs NDArray Remarks Stops at first iterator stop. AssignBroadcast(NDIterator, NDIterator) Assigns rhs values to lhs. public static void AssignBroadcast(NDIterator lhs, NDIterator rhs) where T : unmanaged Parameters lhs NDIterator rhs NDIterator Type Parameters T Remarks Stops at first iterator stop. GetIterators(UnmanagedStorage, UnmanagedStorage, bool) Gets the iterators of lhs and rhs. public static (NDIterator, NDIterator) GetIterators(UnmanagedStorage lhs, UnmanagedStorage rhs, bool broadcast) Parameters lhs UnmanagedStorage rhs UnmanagedStorage broadcast bool Returns (NDIterator, NDIterator) GetIterators(UnmanagedStorage, UnmanagedStorage, bool) Assigns rhs values to lhs. public static (NDIterator, NDIterator) GetIterators(UnmanagedStorage lhs, UnmanagedStorage rhs, bool broadcast) where TOut : unmanaged Parameters lhs UnmanagedStorage rhs UnmanagedStorage broadcast bool Returns (NDIterator, NDIterator) Type Parameters TOut" + }, + "api/NumSharp.NDArray._Unsafe._Pinning.html": { + "href": "api/NumSharp.NDArray._Unsafe._Pinning.html", + "title": "Struct NDArray._Unsafe._Pinning | NumSharp Documentation", + "summary": "Struct NDArray._Unsafe._Pinning Namespace NumSharp Assembly NumSharp.dll public readonly struct NDArray._Unsafe._Pinning Inherited Members ValueType.Equals(object) ValueType.GetHashCode() ValueType.ToString() object.Equals(object, object) object.GetType() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) Properties Boolean public ref bool Boolean { get; } Property Value bool Exceptions InvalidOperationException When this NDArray is a slice. Byte public ref byte Byte { get; } Property Value byte Exceptions InvalidOperationException When this NDArray is a slice. Char public ref char Char { get; } Property Value char Exceptions InvalidOperationException When this NDArray is a slice. Decimal public ref decimal Decimal { get; } Property Value decimal Exceptions InvalidOperationException When this NDArray is a slice. Double public ref double Double { get; } Property Value double Exceptions InvalidOperationException When this NDArray is a slice. Int16 public ref short Int16 { get; } Property Value short Exceptions InvalidOperationException When this NDArray is a slice. Int32 public ref int Int32 { get; } Property Value int Exceptions InvalidOperationException When this NDArray is a slice. Int64 public ref long Int64 { get; } Property Value long Exceptions InvalidOperationException When this NDArray is a slice. Single public ref float Single { get; } Property Value float Exceptions InvalidOperationException When this NDArray is a slice. UInt16 public ref ushort UInt16 { get; } Property Value ushort Exceptions InvalidOperationException When this NDArray is a slice. UInt32 public ref uint UInt32 { get; } Property Value uint Exceptions InvalidOperationException When this NDArray is a slice. UInt64 public ref ulong UInt64 { get; } Property Value ulong Exceptions InvalidOperationException When this NDArray is a slice. Methods GetPin() public ref T GetPin() Returns T Type Parameters T Exceptions InvalidOperationException When this NDArray is a slice." + }, + "api/NumSharp.NDArray._Unsafe.html": { + "href": "api/NumSharp.NDArray._Unsafe.html", + "title": "Struct NDArray._Unsafe | NumSharp Documentation", + "summary": "Struct NDArray._Unsafe Namespace NumSharp Assembly NumSharp.dll public readonly struct NDArray._Unsafe Inherited Members ValueType.Equals(object) ValueType.GetHashCode() ValueType.ToString() object.Equals(object, object) object.GetType() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) Properties Address Returns the memory address to the start of this block of memory. public void* Address { get; } Property Value void* Exceptions InvalidOperationException When this NDArray is a slice. BytesLength How many bytes are stored in this memory block. public int BytesLength { get; } Property Value int Remarks Calculated by Count*ItemLength Count How many items are stored in Address. public int Count { get; } Property Value int Remarks Not to confuse with BytesLength ItemLength The size of a single item stored in Address. public int ItemLength { get; } Property Value int Remarks Equivalent to NPTypeCode.SizeOf extension. Pin Provides the ability to return a pin to the memory address of NDArray. public NDArray._Unsafe._Pinning Pin { get; } Property Value NDArray._Unsafe._Pinning Remarks Possible only when the ndarray is not sliced. Storage Provides access to the internal UnmanagedStorage. public UnmanagedStorage Storage { get; } Property Value UnmanagedStorage Methods AsSpan() public Span AsSpan() Returns Span Type Parameters T Remarks Does not perform copy. Fill(object) Fills all indexes with value. public void Fill(object value) Parameters value object GetIndex(int) public object GetIndex(int index) Parameters index int Returns object GetIndex(int) public T GetIndex(int index) where T : unmanaged Parameters index int Returns T Type Parameters T GetPinnableReference() public ref byte GetPinnableReference() Returns byte Exceptions InvalidOperationException When this NDArray is a slice. GetPinnableReference() Gets pinnable reference of the first item in the memory block storage. public ref T GetPinnableReference() where T : unmanaged Returns T Type Parameters T" + }, + "api/NumSharp.NDArray.html": { + "href": "api/NumSharp.NDArray.html", + "title": "Class NDArray | NumSharp Documentation", + "summary": "Class NDArray Namespace NumSharp Assembly NumSharp.dll An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.) [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] [SuppressMessage(\"ReSharper\", \"CoVariantArrayConversion\")] [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] public class NDArray : IIndex, ICloneable, IEnumerable Inheritance object NDArray Implements IIndex ICloneable IEnumerable Derived NDArray Inherited Members object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) NDIteratorExtensions.AsIterator(NDArray, bool) NDIteratorExtensions.AsIterator(NDArray, bool) Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html Constructors NDArray(IArraySlice, Shape, char) Constructor which takes .NET array dtype and shape is determined from array public NDArray(IArraySlice values, Shape shape = default, char order = 'C') Parameters values IArraySlice shape Shape order char Remarks This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type) NDArray(UnmanagedStorage) Creates a new NDArray with this storage. public NDArray(UnmanagedStorage storage) Parameters storage UnmanagedStorage NDArray(UnmanagedStorage, Shape) Creates a new NDArray with this storage. protected NDArray(UnmanagedStorage storage, Shape shape) Parameters storage UnmanagedStorage shape Shape The shape to set for this NDArray, does not perform checks. Remarks Doesn't copy. Does not perform checks for shape. NDArray(UnmanagedStorage, ref Shape) Creates a new NDArray with this storage. protected NDArray(UnmanagedStorage storage, ref Shape shape) Parameters storage UnmanagedStorage shape Shape The shape to set for this NDArray, does not perform checks. Remarks Doesn't copy. Does not perform checks for shape. NDArray(NPTypeCode) Constructor for init data type internal storage is 1D with 1 element public NDArray(NPTypeCode typeCode) Parameters typeCode NPTypeCode Data type of elements Remarks This constructor does not call allocation/> NDArray(NPTypeCode, Shape) Constructor which initialize elements with 0 type and shape are given. public NDArray(NPTypeCode dtype, Shape shape) Parameters dtype NPTypeCode internal data type shape Shape Shape of NDArray Remarks This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type) NDArray(NPTypeCode, Shape, bool) Constructor which initialize elements with 0 type and shape are given. public NDArray(NPTypeCode dtype, Shape shape, bool fillZeros) Parameters dtype NPTypeCode internal data type shape Shape Shape of NDArray fillZeros bool Should set the values of the new allocation to default(dtype)? otherwise - old memory noise Remarks This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type) NDArray(NPTypeCode, TensorEngine) Constructor for init data type internal storage is 1D with 1 element protected NDArray(NPTypeCode typeCode, TensorEngine engine) Parameters typeCode NPTypeCode Data type of elements engine TensorEngine The engine of this NDArray Remarks This constructor does not call allocation/> NDArray(NPTypeCode, int) Constructor which initialize elements with length of size public NDArray(NPTypeCode dtype, int size) Parameters dtype NPTypeCode Internal data type size int The size as a single dimension shape Remarks This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type) NDArray(NPTypeCode, int, bool) Constructor which initialize elements with length of size public NDArray(NPTypeCode dtype, int size, bool fillZeros) Parameters dtype NPTypeCode Internal data type size int The size as a single dimension shape fillZeros bool Should set the values of the new allocation to default(dtype)? otherwise - old memory noise Remarks This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type) NDArray(Array, Shape, char) Constructor which takes .NET array dtype and shape is determined from array public NDArray(Array values, Shape shape = default, char order = 'C') Parameters values Array shape Shape order char Remarks This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type) NDArray(Type) Constructor for init data type internal storage is 1D with 1 element public NDArray(Type dtype) Parameters dtype Type Data type of elements Remarks This constructor does not call allocation/> NDArray(Type, Shape) Constructor which initialize elements with 0 type and shape are given. public NDArray(Type dtype, Shape shape) Parameters dtype Type internal data type shape Shape Shape of NDArray Remarks This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type) NDArray(Type, Shape, bool) Constructor which initialize elements with 0 type and shape are given. public NDArray(Type dtype, Shape shape, bool fillZeros) Parameters dtype Type internal data type shape Shape Shape of NDArray fillZeros bool Should set the values of the new allocation to default(dtype)? otherwise - old memory noise Remarks This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type) NDArray(Type, TensorEngine) Constructor for init data type internal storage is 1D with 1 element protected NDArray(Type dtype, TensorEngine engine) Parameters dtype Type Data type of elements engine TensorEngine The engine of this NDArray Remarks This constructor does not call allocation/> NDArray(Type, int) Constructor which initialize elements with length of size public NDArray(Type dtype, int size) Parameters dtype Type Internal data type size int The size as a single dimension shape Remarks This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type) NDArray(Type, int, bool) Constructor which initialize elements with length of size public NDArray(Type dtype, int size, bool fillZeros) Parameters dtype Type Internal data type size int The size as a single dimension shape fillZeros bool Should set the values of the new allocation to default(dtype)? otherwise - old memory noise Remarks This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type) Fields Storage The internal storage that stores data for this NDArray. protected UnmanagedStorage Storage Field Value UnmanagedStorage tensorEngine protected TensorEngine tensorEngine Field Value TensorEngine Properties Address Gets the address that this NDArray starts from. protected void* Address { get; } Property Value void* Array Get: Gets internal storage array by calling IStorage.GetData Set: Replace internal storage by calling IStorage.ReplaceData(System.Array) protected IArraySlice Array { get; } Property Value IArraySlice Remarks Setting does not replace internal storage array. this[NDArray] Used to perform selection based on a boolean mask. [SuppressMessage(\"ReSharper\", \"CoVariantArrayConversion\")] public NDArray this[NDArray mask] { get; set; } Parameters mask NDArray Property Value NDArray Remarks https://docs.scipy.org/doc/numpy-1.17.0/user/basics.indexing.html Exceptions IndexOutOfRangeException When one of the indices exceeds limits. ArgumentException indices must be of Int type (byte, u/short, u/int, u/long). this[NDArray[]] Used to perform selection based on a selection indices. public NDArray this[params NDArray[] selection] { get; set; } Parameters selection NDArray[] Property Value NDArray Remarks https://docs.scipy.org/doc/numpy-1.17.0/user/basics.indexing.html Exceptions IndexOutOfRangeException When one of the indices exceeds limits. ArgumentException indices must be of Int type (byte, u/short, u/int, u/long). this[Slice[]] Slice the array with Python slice notation like this: \":, 2:7:1, ..., np.newaxis\" public NDArray this[params Slice[] slice] { get; set; } Parameters slice Slice[] A string containing slice notations for every dimension, delimited by comma Property Value NDArray A sliced view this[int*, int] Used to perform selection based on given indices. public NDArray this[int* dims, int ndims] { get; set; } Parameters dims int* The pointer to the dimensions ndims int The count of ints in dims Property Value NDArray this[object[]] Perform slicing, index extraction, masking and indexing all at the same time with mixed index objects public NDArray this[params object[] indicesObjects] { get; set; } Parameters indicesObjects object[] Property Value NDArray this[string] Slice the array with Python slice notation like this: \":, 2:7:1, ..., np.newaxis\" public NDArray this[string slice] { get; set; } Parameters slice string A string containing slice notations for every dimension, delimited by comma Property Value NDArray A sliced view Shape The shape representing this NDArray. public Shape Shape { get; set; } Property Value Shape T The transposed array. Same as self.transpose(). public NDArray T { get; } Property Value NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.T.html TensorEngine The tensor engine that handles this NDArray. public TensorEngine TensorEngine { get; set; } Property Value TensorEngine Unsafe Provides an interface for unsafe methods in NDArray. public NDArray._Unsafe Unsafe { get; } Property Value NDArray._Unsafe dtype The dtype of this array. public Type dtype { get; } Property Value Type dtypesize public int dtypesize { get; } Property Value int flat A 1-D iterator over the array. public NDArray flat { get; } Property Value NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flat.html ndim Dimension count public int ndim { get; } Property Value int order public char order { get; } Property Value char shape Data length of every dimension public int[] shape { get; set; } Property Value int[] size Total of elements public int size { get; } Property Value int strides public int[] strides { get; } Property Value int[] typecode The NPTypeCode of this array. public NPTypeCode typecode { get; } Property Value NPTypeCode Methods AsGeneric() Tries to cast to NDArray, otherwise creates an alias without reallocating data. public NDArray AsGeneric() where T : unmanaged Returns NDArray This NDArray as a generic version. Type Parameters T The type of the generic Exceptions InvalidOperationException When T != dtype AsOrMakeGeneric() Tries to cast to NDArray, otherwise calls NDArray.astype. public NDArray AsOrMakeGeneric() where T : unmanaged Returns NDArray This NDArray as a generic version. Type Parameters T The type of the generic Exceptions InvalidOperationException When T != dtype AsString(NDArray) Converts the entire NDArray to a string. public static string AsString(NDArray arr) Parameters arr NDArray Returns string Remarks Performs a copy due to String .net-framework limitations. AsStringArray(NDArray) Convert to String[] from NDArray public static string[] AsStringArray(NDArray arr) Parameters arr NDArray Returns string[] Clone() Clone the whole NDArray internal storage is also cloned into 2nd memory area public NDArray Clone() Returns NDArray Cloned NDArray CloneData() public IArraySlice CloneData() Returns IArraySlice CloneData() public ArraySlice CloneData() where T : unmanaged Returns ArraySlice Type Parameters T CopyTo(IMemoryBlock) Copies the entire contents of this storage to given address (using Count). public void CopyTo(IMemoryBlock slice) Parameters slice IMemoryBlock The slice to copy to. CopyTo(nint) Copies the entire contents of this storage to given address. public void CopyTo(nint ptr) Parameters ptr nint CopyTo(void*) Copies the entire contents of this storage to given address (using Count). public void CopyTo(void* address) Parameters address void* The address to copy to. CopyTo(IMemoryBlock) Copies the entire contents of this storage to given address (using Count). public void CopyTo(IMemoryBlock block) where T : unmanaged Parameters block IMemoryBlock The slice to copy to. Type Parameters T CopyTo(T*) Copies the entire contents of this storage to given address. public void CopyTo(T* address) where T : unmanaged Parameters address T* The address to copy to. Type Parameters T CopyTo(T[]) Copies the entire contents of this storage to given array. public void CopyTo(T[] array) where T : unmanaged Parameters array T[] The array to copy to. Type Parameters T Data() Shortcut for access internal elements public ArraySlice Data() where T : unmanaged Returns ArraySlice Type Parameters T Equals(object) Determines if NDArray data is same public override bool Equals(object obj) Parameters obj object NDArray to compare Returns bool if reference is same ExpandEllipsis(object[], int) protected static IEnumerable ExpandEllipsis(object[] ndarrays, int ndim) Parameters ndarrays object[] ndim int Returns IEnumerable FetchIndices(NDArray, NDArray[], NDArray, bool) protected static NDArray FetchIndices(NDArray src, NDArray[] indices, NDArray @out, bool extraDim) Parameters src NDArray indices NDArray[] out NDArray extraDim bool Returns NDArray FetchIndicesNDNonLinear(NDArray, NDArray[], int, int[], int[], NDArray) Accepts collapsed [SuppressMessage(\"ReSharper\", \"SuggestVarOrType_Elsewhere\")] protected static NDArray FetchIndicesNDNonLinear(NDArray source, NDArray[] indices, int ndsCount, int[] retShape, int[] subShape, NDArray @out) where T : unmanaged Parameters source NDArray indices NDArray[] ndsCount int retShape int[] subShape int[] out NDArray Returns NDArray Type Parameters T FetchIndicesND(NDArray, NDArray, NDArray[], int, int[], int[], NDArray) Accepts collapsed protected static NDArray FetchIndicesND(NDArray src, NDArray offsets, NDArray[] indices, int ndsCount, int[] retShape, int[] subShape, NDArray @out) where T : unmanaged Parameters src NDArray offsets NDArray indices NDArray[] ndsCount int retShape int[] subShape int[] out NDArray Returns NDArray Type Parameters T FetchIndices(NDArray, NDArray[], NDArray, bool) protected static NDArray FetchIndices(NDArray source, NDArray[] indices, NDArray @out, bool extraDim) where T : unmanaged Parameters source NDArray indices NDArray[] out NDArray extraDim bool Returns NDArray Type Parameters T FromMultiDimArray(Array, bool) Creates an NDArray out of given array of type T public static NDArray FromMultiDimArray(Array ndarray, bool copy = true) where T : unmanaged Parameters ndarray Array copy bool true for making Returns NDArray Type Parameters T FromString(string) Converts a string to a vector ndarray of bytes. public static NDArray FromString(string str) Parameters str string Returns NDArray GetAtIndex(int) Retrieves value of public ValueType GetAtIndex(int index) Parameters index int Returns ValueType GetAtIndex(int) Retrieves value of public T GetAtIndex(int index) where T : unmanaged Parameters index int Returns T Type Parameters T GetBoolean(params int[]) Retrieves value of type bool. public bool GetBoolean(params int[] indices) Parameters indices int[] The shape's indices to get. Returns bool Exceptions NullReferenceException When DType is not bool GetByte(params int[]) Retrieves value of type byte. public byte GetByte(params int[] indices) Parameters indices int[] The shape's indices to get. Returns byte Exceptions NullReferenceException When DType is not byte GetChar(params int[]) Retrieves value of type char. public char GetChar(params int[] indices) Parameters indices int[] The shape's indices to get. Returns char Exceptions NullReferenceException When DType is not char GetData() Get reference to internal data storage public IArraySlice GetData() Returns IArraySlice reference to internal storage as System.Array GetData(params int[]) Gets a NDArray at given indices. public NDArray GetData(params int[] indices) Parameters indices int[] The coordinates to the wanted value Returns NDArray Remarks Does not copy, returns a memory slice - this is similar to this[int[]] GetData() Gets the internal storage and converts it to T if necessary. public ArraySlice GetData() where T : unmanaged Returns ArraySlice An array of type T Type Parameters T The returned type. GetDecimal(params int[]) Retrieves value of type decimal. public decimal GetDecimal(params int[] indices) Parameters indices int[] The shape's indices to get. Returns decimal Exceptions NullReferenceException When DType is not decimal GetDouble(params int[]) Retrieves value of type double. public double GetDouble(params int[] indices) Parameters indices int[] The shape's indices to get. Returns double Exceptions NullReferenceException When DType is not double GetEnumerator() Returns an enumerator that iterates through a collection. public IEnumerator GetEnumerator() Returns IEnumerator An IEnumerator object that can be used to iterate through the collection. GetIndices(NDArray, NDArray[]) Used to perform selection based on indices, equivalent to nd[NDArray[]]. public NDArray GetIndices(NDArray @out, NDArray[] indices) Parameters out NDArray indices NDArray[] Returns NDArray Remarks https://docs.scipy.org/doc/numpy-1.17.0/user/basics.indexing.html Exceptions IndexOutOfRangeException When one of the indices exceeds limits. ArgumentException indices must be of Int type (byte, u/short, u/int, u/long). GetIndicesFromSlice(Shape, Slice, int) Converts a slice to indices for the special case where slices are mixed with NDArrays in this[...] protected static NDArray GetIndicesFromSlice(Shape shape, Slice slice, int axis) Parameters shape Shape slice Slice axis int Returns NDArray GetIndicesFromSlice(int[], Slice, int) Converts a slice to indices for the special case where slices are mixed with NDArrays in this[...] protected static NDArray GetIndicesFromSlice(int[] shape, Slice slice, int axis) Parameters shape int[] slice Slice axis int Returns NDArray GetInt16(params int[]) Retrieves value of type short. public short GetInt16(params int[] indices) Parameters indices int[] The shape's indices to get. Returns short Exceptions NullReferenceException When DType is not short GetInt32(params int[]) Retrieves value of type int. public int GetInt32(params int[] indices) Parameters indices int[] The shape's indices to get. Returns int Exceptions NullReferenceException When DType is not int GetInt64(params int[]) Retrieves value of type long. public long GetInt64(params int[] indices) Parameters indices int[] The shape's indices to get. Returns long Exceptions NullReferenceException When DType is not long GetNDArrays(int) Get all NDArray slices at that specific dimension. [SuppressMessage(\"ReSharper\", \"LoopCanBeConvertedToQuery\")] public NDArray[] GetNDArrays(int axis = 0) Parameters axis int Zero-based dimension index on which axis and forward of it to select data., e.g. dimensions=1, shape is (2,2,3,3), returned shape = 4 times of (3,3) Returns NDArray[] Examples var nd = np.arange(27).reshape(3,1,3,3); var ret = nd.GetNDArrays(1); Assert.IsTrue(ret.All(n=>n.Shape == new Shape(3,3)); Assert.IsTrue(ret.Length == 3); var nd = np.arange(27).reshape(3,1,3,3); var ret = nd.GetNDArrays(0); Assert.IsTrue(ret.All(n=>n.Shape == new Shape(1,3,3)); Assert.IsTrue(ret.Length == 3); Remarks Does not perform copy. GetSingle(params int[]) Retrieves value of type float. public float GetSingle(params int[] indices) Parameters indices int[] The shape's indices to get. Returns float Exceptions NullReferenceException When DType is not float GetString(params int[]) Get a string out of a vector of chars. public string GetString(params int[] indices) Parameters indices int[] Returns string Remarks Performs a copy due to String .net-framework limitations. GetStringAt(int) Get a string out of a vector of chars. public string GetStringAt(int offset) Parameters offset int Returns string Remarks Performs a copy due to String .net-framework limitations. GetUInt16(params int[]) Retrieves value of type ushort. public ushort GetUInt16(params int[] indices) Parameters indices int[] The shape's indices to get. Returns ushort Exceptions NullReferenceException When DType is not ushort GetUInt32(params int[]) Retrieves value of type uint. public uint GetUInt32(params int[] indices) Parameters indices int[] The shape's indices to get. Returns uint Exceptions NullReferenceException When DType is not uint GetUInt64(params int[]) Retrieves value of type ulong. public ulong GetUInt64(params int[] indices) Parameters indices int[] The shape's indices to get. Returns ulong Exceptions NullReferenceException When DType is not ulong GetValue(params int[]) Retrieves value of unspecified type (will figure using DType). public ValueType GetValue(params int[] indices) Parameters indices int[] The shape's indices to get. Returns ValueType Exceptions NullReferenceException When DType is not object GetValue(params int[]) Retrieves value of unspecified type (will figure using DType). public T GetValue(params int[] indices) where T : unmanaged Parameters indices int[] The shape's indices to get. Returns T Type Parameters T Exceptions NullReferenceException When DType is not object MakeGeneric() Creates an alias without reallocating data. public NDArray MakeGeneric() where T : unmanaged Returns NDArray This NDArray as a generic version. Type Parameters T The type of the generic Exceptions InvalidOperationException When T != dtype Normalize() Normalizes all entries into the range between 0 and 1 Note: this is not a numpy function. public void Normalize() PrepareIndexGetters(Shape, NDArray[]) Generates index getter function based on given indices. protected static Func[] PrepareIndexGetters(Shape srcShape, NDArray[] indices) Parameters srcShape Shape The shape to get indice from indices NDArray[] The indices trying to index. Returns Func[] ReplaceData(IArraySlice) Sets values as the internal data source and changes the internal storage data type to values type. public void ReplaceData(IArraySlice values) Parameters values IArraySlice Remarks Does not copy values and doesn't change shape. ReplaceData(IArraySlice, Type) Sets values as the internal data source and changes the internal storage data type to values type. public void ReplaceData(IArraySlice values, Type dtype) Parameters values IArraySlice dtype Type Remarks Does not copy values and doesn't change shape. ReplaceData(NDArray) Sets nd as the internal data storage and changes the internal storage data type to nd type. public void ReplaceData(NDArray nd) Parameters nd NDArray Remarks Does not copy values and does change shape and dtype. ReplaceData(Array) Sets values as the internal data storage and changes the internal storage data type to values type. public void ReplaceData(Array values) Parameters values Array Remarks Does not copy values. ReplaceData(Array, NPTypeCode) Set an Array to internal storage, cast it to new dtype and if necessary change dtype public void ReplaceData(Array values, NPTypeCode typeCode) Parameters values Array typeCode NPTypeCode Remarks Does not copy values unless cast is necessary and doesn't change shape. ReplaceData(Array, Type) Sets values as the internal data storage and changes the internal storage data type to dtype and casts values if necessary. public void ReplaceData(Array values, Type dtype) Parameters values Array The values to set as internal data soruce dtype Type The type to change this storage to and the type to cast values if necessary. Remarks Does not copy values unless cast is necessary. Scalar(object) Creates a scalar NDArray of value and dtype. public static NDArray Scalar(object value) Parameters value object The value of the scalar Returns NDArray Remarks In case when value is not dtype, Converts.ChangeType(object,System.Type) will be called. Scalar(object, NPTypeCode) Creates a scalar NDArray of value and dtype. public static NDArray Scalar(object value, NPTypeCode typeCode) Parameters value object The value of the scalar typeCode NPTypeCode The type code of the scalar. Returns NDArray Remarks In case when value is not dtype, Converts.ChangeType(object,System.Type) will be called. Scalar(object, Type) Creates a scalar NDArray of value and dtype. public static NDArray Scalar(object value, Type dtype) Parameters value object The value of the scalar dtype Type The type of the scalar. Returns NDArray Remarks In case when value is not dtype, Converts.ChangeType(object,System.Type) will be called. Scalar(ValueType) Creates a scalar NDArray of value and dtype. public static NDArray Scalar(ValueType value) Parameters value ValueType The value of the scalar Returns NDArray Remarks In case when value is not dtype, Converts.ChangeType(object,System.Type) will be called. Scalar(object) Creates a scalar NDArray of value and dtype. public static NDArray Scalar(object value) where T : unmanaged Parameters value object The value of the scalar, attempt to convert will be performed Returns NDArray Type Parameters T Remarks In case when value is not dtype, Converts.ChangeType(object,System.Type) will be called. Scalar(T) Creates a scalar NDArray of value and dtype. public static NDArray Scalar(T value) where T : unmanaged Parameters value T The value of the scalar Returns NDArray Type Parameters T Remarks In case when value is not dtype, Converts.ChangeType(object,System.Type) will be called. SetAtIndex(object, int) Retrieves value at given linear (offset) index. public void SetAtIndex(object obj, int index) Parameters obj object index int SetAtIndex(T, int) Retrieves value of public void SetAtIndex(T value, int index) where T : unmanaged Parameters value T index int Type Parameters T SetBoolean(bool, params int[]) Sets a bool at specific coordinates. public void SetBoolean(bool value, params int[] indices) Parameters value bool The values to assign indices int[] The coordinates to set value at. SetByte(byte, params int[]) Sets a byte at specific coordinates. public void SetByte(byte value, params int[] indices) Parameters value byte The values to assign indices int[] The coordinates to set value at. SetChar(char, params int[]) Sets a char at specific coordinates. public void SetChar(char value, params int[] indices) Parameters value char The values to assign indices int[] The coordinates to set value at. SetData(IArraySlice, params int[]) Set a IArraySlice at given indices. public void SetData(IArraySlice value, params int[] indices) Parameters value IArraySlice The value to set indices int[] The Remarks Does not change internal storage data type. If value does not match DType, value will be converted. SetData(NDArray, params int[]) Set a NDArray at given indices. public void SetData(NDArray value, params int[] indices) Parameters value NDArray The value to set indices int[] The Remarks Does not change internal storage data type. If value does not match DType, value will be converted. SetData(object) public void SetData(object p) Parameters p object SetData(object, params int[]) Set a NDArray, IArraySlice, Array or a scalar value at given indices. public void SetData(object value, params int[] indices) Parameters value object The value to set indices int[] The Remarks Does not change internal storage data type. If value does not match DType, value will be converted. SetDecimal(decimal, params int[]) Sets a decimal at specific coordinates. public void SetDecimal(decimal value, params int[] indices) Parameters value decimal The values to assign indices int[] The coordinates to set value at. SetDouble(double, params int[]) Sets a double at specific coordinates. public void SetDouble(double value, params int[] indices) Parameters value double The values to assign indices int[] The coordinates to set value at. SetIndices(NDArray, NDArray[]) Used to perform set a selection based on indices, equivalent to nd[NDArray[]] = values. public void SetIndices(NDArray values, NDArray[] indices) Parameters values NDArray The values to set via . indices NDArray[] Remarks https://docs.scipy.org/doc/numpy-1.17.0/user/basics.indexing.html Exceptions IndexOutOfRangeException When one of the indices exceeds limits. ArgumentException indices must be of Int type (byte, u/short, u/int, u/long). SetIndices(NDArray, NDArray[], NDArray) protected static void SetIndices(NDArray src, NDArray[] indices, NDArray values) Parameters src NDArray indices NDArray[] values NDArray SetIndices(object[], NDArray) protected void SetIndices(object[] indicesObjects, NDArray values) Parameters indicesObjects object[] values NDArray SetIndicesNDNonLinear(NDArray, NDArray[], int, int[], int[], NDArray) Accepts collapsed [SuppressMessage(\"ReSharper\", \"SuggestVarOrType_Elsewhere\")] protected static void SetIndicesNDNonLinear(NDArray source, NDArray[] indices, int ndsCount, int[] retShape, int[] subShape, NDArray values) where T : unmanaged Parameters source NDArray indices NDArray[] ndsCount int retShape int[] subShape int[] values NDArray Type Parameters T SetIndicesND(NDArray, NDArray, NDArray[], int, int[], int[], NDArray) Accepts collapsed protected static void SetIndicesND(NDArray dst, NDArray dstOffsets, NDArray[] dstIndices, int ndsCount, int[] retShape, int[] subShape, NDArray values) where T : unmanaged Parameters dst NDArray dstOffsets NDArray dstIndices NDArray[] ndsCount int retShape int[] subShape int[] values NDArray Type Parameters T SetIndices(NDArray, NDArray[], NDArray) protected static void SetIndices(NDArray source, NDArray[] indices, NDArray values) where T : unmanaged Parameters source NDArray indices NDArray[] values NDArray Type Parameters T SetInt16(short, params int[]) Sets a short at specific coordinates. public void SetInt16(short value, params int[] indices) Parameters value short The values to assign indices int[] The coordinates to set value at. SetInt32(int, params int[]) Sets a int at specific coordinates. public void SetInt32(int value, params int[] indices) Parameters value int The values to assign indices int[] The coordinates to set value at. SetInt64(long, params int[]) Sets a long at specific coordinates. public void SetInt64(long value, params int[] indices) Parameters value long The values to assign indices int[] The coordinates to set value at. SetSingle(float, params int[]) Sets a float at specific coordinates. public void SetSingle(float value, params int[] indices) Parameters value float The values to assign indices int[] The coordinates to set value at. SetString(string, params int[]) public void SetString(string value, params int[] indices) Parameters value string indices int[] SetStringAt(string, int) public void SetStringAt(string value, int offset) Parameters value string offset int SetUInt16(ushort, params int[]) Sets a ushort at specific coordinates. public void SetUInt16(ushort value, params int[] indices) Parameters value ushort The values to assign indices int[] The coordinates to set value at. SetUInt32(uint, params int[]) Sets a uint at specific coordinates. public void SetUInt32(uint value, params int[] indices) Parameters value uint The values to assign indices int[] The coordinates to set value at. SetUInt64(ulong, params int[]) Sets a ulong at specific coordinates. public void SetUInt64(ulong value, params int[] indices) Parameters value ulong The values to assign indices int[] The coordinates to set value at. SetValue(object, params int[]) Set a single value at given indices. public void SetValue(object value, params int[] indices) Parameters value object The value to set indices int[] The Remarks Does not change internal storage data type. If value does not match DType, value will be converted. SetValue(ValueType, params int[]) Set a single value at given indices. public void SetValue(ValueType value, params int[] indices) Parameters value ValueType The value to set indices int[] The Remarks Does not change internal storage data type. If value does not match DType, value will be converted. SetValue(T, params int[]) Set a single value at given indices. public void SetValue(T value, params int[] indices) where T : unmanaged Parameters value T The value to set indices int[] The Type Parameters T Remarks Does not change internal storage data type. If value does not match DType, value will be converted. ToArray() public T[] ToArray() where T : unmanaged Returns T[] Type Parameters T ToByteArray() public byte[] ToByteArray() Returns byte[] ToJaggedArray() public Array ToJaggedArray() where T : unmanaged Returns Array Type Parameters T ToMuliDimArray() public Array ToMuliDimArray() where T : unmanaged Returns Array Type Parameters T ToString() Returns a string that represents the current object. public override string ToString() Returns string A string that represents the current object. ToString(bool) public string ToString(bool flat) Parameters flat bool Returns string amax(int, bool, Type) Return the maximum of an array or maximum along an axis. [SuppressMessage(\"ReSharper\", \"TooWideLocalVariableScope\")] [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] public NDArray amax(int axis, bool keepdims = false, Type dtype = null) Parameters axis int Axis or axes along which to operate. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. dtype Type the type expected as a return, null will remain the same dtype. Returns NDArray Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amax.html amax(Type) Return the maximum of an array or maximum along an axis. [SuppressMessage(\"ReSharper\", \"TooWideLocalVariableScope\")] [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] public NDArray amax(Type dtype = null) Parameters dtype Type the type expected as a return, null will remain the same dtype. Returns NDArray Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amax.html amax() Return the maximum of an array or maximum along an axis. public T amax() where T : unmanaged Returns T Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Type Parameters T The expected return type, cast will be performed if necessary. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amax.html amin(int, bool, Type) Return the minimum of an array or minimum along an axis. [SuppressMessage(\"ReSharper\", \"TooWideLocalVariableScope\")] [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] public NDArray amin(int axis, bool keepdims = false, Type dtype = null) Parameters axis int Axis or axes along which to operate. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. dtype Type the type expected as a return, null will remain the same dtype. Returns NDArray Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amin.html amin(Type) Return the minimum of an array or minimum along an axis. [SuppressMessage(\"ReSharper\", \"TooWideLocalVariableScope\")] [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] public NDArray amin(Type dtype = null) Parameters dtype Type the type expected as a return, null will remain the same dtype. Returns NDArray Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amin.html amin() Return the minimum of an array or minimum along an axis. public T amin() where T : unmanaged Returns T Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Type Parameters T The expected return type, cast will be performed if necessary. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amin.html argmax() Returns the indices of the maximum values along an axis. public int argmax() Returns int The index of the maximal value in the array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html argmax(int) Returns the indices of the maximum values along an axis. public int argmax(int axis) Parameters axis int Returns int Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html argmin() Returns the indices of the minimum values along an axis. public int argmin() Returns int The index of the minimum value in the array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html argmin(int) Returns the indices of the minimum values along an axis. public int argmin(int axis) Parameters axis int Returns int Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html argsort(int) Returns the indices that would sort an array. Perform an indirect sort along the given axis using the algorithm specified by the kind keyword.It returns an array of indices of the same shape as a that index data along the given axis in sorted order. public NDArray argsort(int axis = -1) Parameters axis int Returns NDArray Type Parameters T array_equal(NDArray) True if two arrays have the same shape and elements, False otherwise. public bool array_equal(NDArray rhs) Parameters rhs NDArray Input array. Returns bool Returns True if the arrays are equal. Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.array_equal.html astype(NPTypeCode, bool) Copy of the array, cast to a specified type. public NDArray astype(NPTypeCode typeCode, bool copy = true) Parameters typeCode NPTypeCode copy bool By default, astype always returns a newly allocated array. If this is set to false, the input internal array is replaced instead of returning a new NDArray with the casted data. Returns NDArray An NDArray of given dtype. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.html astype(Type, bool) Copy of the array, cast to a specified type. [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] public NDArray astype(Type dtype, bool copy = true) Parameters dtype Type The dtype to cast this array. copy bool By default, astype always returns a newly allocated array. If this is set to false, the input internal array is replaced instead of returning a new NDArray with the casted data. Returns NDArray An NDArray of given dtype. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.html convolve(NDArray, string) Returns the discrete, linear convolution of two one-dimensional sequences. The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal[1]. In probability theory, the sum of two independent random variables is distributed according to the convolution of their individual distributions. If v is longer than a, the arrays are swapped before computation. public NDArray convolve(NDArray rhs, string mode = \"full\") Parameters rhs NDArray mode string Returns NDArray copy(char) Return a copy of the array. public NDArray copy(char order = 'C') Parameters order char Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.copy.html cumsum(int?, Type) Return the cumulative sum of the elements along a given axis. public NDArray cumsum(int? axis = null, Type dtype = null) Parameters axis int? Axis along which the cumulative sum is computed. The default (-1) is to compute the cumsum over the flattened array. dtype Type Type of the returned array and of the accumulator in which the elements are summed. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used. Returns NDArray A new array holding the result is returned unless out is specified, in which case a reference to out is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html delete(IEnumerable) public NDArray delete(IEnumerable delete) Parameters delete IEnumerable Returns NDArray dot(in NDArray) Dot product of two arrays. See remarks. public NDArray dot(in NDArray b) Parameters b NDArray Rhs, Second argument. Returns NDArray Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If out is given, then it is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html Specifically, - If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation). - If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred. - If either a or b is 0-D(scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a* b is preferred. - If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b. - If a is an N-D array and b is an M-D array(where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b: dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m]) dstack(params NDArray[]) Stack arrays in sequence depth wise (along third axis). This is equivalent to concatenation along the third axis after 2-D arrays of shape(M, N) have been reshaped to(M, N,1) and 1-D arrays of shape(N,) have been reshaped to(1, N,1). Rebuilds arrays divided by dsplit. This function makes most sense for arrays with up to 3 dimensions.For instance, for pixel-data with a height(first axis), width(second axis), and r/g/b channels(third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations. public NDArray dstack(params NDArray[] tup) Parameters tup NDArray[] The arrays must have the same shape along all but the third axis. 1-D or 2-D arrays must have the same shape. Returns NDArray The array formed by stacking the given arrays, will be at least 3-D. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.dstack.html flatten(bool) Return a copy of the array collapsed into one dimension. public NDArray flatten(bool clone) Parameters clone bool Should the data be cloned, true by default. Returns NDArray A copy of the input array, flattened to one dimension. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html flatten(char) Return a copy of the array collapsed into one dimension. public NDArray flatten(char order = 'C') Parameters order char Returns NDArray A copy of the input array, flattened to one dimension. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html hstack(params NDArray[]) Stack arrays in sequence horizontally (column wise). This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis.Rebuilds arrays divided by hsplit. This function makes most sense for arrays with up to 3 dimensions.For instance, for pixel-data with a height(first axis), width(second axis), and r/g/b channels(third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations. public NDArray hstack(params NDArray[] tup) Parameters tup NDArray[] The arrays must have the same shape along all but the second axis, except 1-D arrays which can be any length. Returns NDArray The array formed by stacking the given arrays. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.hstack.html inv() public NDArray inv() Returns NDArray itemset(Shape, ValueType) Insert scalar into an array (scalar is cast to array’s dtype, if possible) public void itemset(Shape shape, ValueType val) Parameters shape Shape val ValueType Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.itemset.html itemset(ref Shape, ValueType) Insert scalar into an array (scalar is cast to array’s dtype, if possible) public void itemset(ref Shape shape, ValueType val) Parameters shape Shape val ValueType Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.itemset.html itemset(int[], ValueType) Insert scalar into an array (scalar is cast to array’s dtype, if possible) public void itemset(int[] shape, ValueType val) Parameters shape int[] val ValueType Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.itemset.html itemset(int[], T) Insert scalar into an array (scalar is cast to array’s dtype, if possible) public void itemset(int[] shape, T val) where T : unmanaged Parameters shape int[] val T Type Parameters T Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.itemset.html lstqr(NDArray, double) Least Square method Determines NDArray X which reduces least square error of Linear System A * X = B. This NDArray is equal to A. public NDArray lstqr(NDArray nDArrayB, double rcon = 0.0001) Parameters nDArrayB NDArray Result NDArray B rcon double Returns NDArray NArray X matrix_power(int) public NDArray matrix_power(int power) Parameters power int Returns NDArray max(int, bool, Type) Return the maximum of an array or maximum along an axis. [SuppressMessage(\"ReSharper\", \"TooWideLocalVariableScope\")] [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] public NDArray max(int axis, bool keepdims = false, Type dtype = null) Parameters axis int Axis or axes along which to operate. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. dtype Type the type expected as a return, null will remain the same dtype. Returns NDArray Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amax.html max(Type) Return the maximum of an array or maximum along an axis. [SuppressMessage(\"ReSharper\", \"TooWideLocalVariableScope\")] [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] public NDArray max(Type dtype = null) Parameters dtype Type the type expected as a return, null will remain the same dtype. Returns NDArray Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amax.html max() Return the maximum of an array or maximum along an axis. public T max() where T : unmanaged Returns T Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Type Parameters T The expected return type, cast will be performed if necessary. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amax.html mean() Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs. public NDArray mean() Returns NDArray returns a new array containing the mean values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html mean(int) Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs. public NDArray mean(int axis) Parameters axis int Axis or axes along which the means are computed. The default is to compute the mean of the flattened array. Returns NDArray returns a new array containing the mean values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html mean(int, NPTypeCode, bool) Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs. public NDArray mean(int axis, NPTypeCode type, bool keepdims = false) Parameters axis int Axis or axes along which the means are computed. The default is to compute the mean of the flattened array. type NPTypeCode Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised. Returns NDArray returns a new array containing the mean values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html mean(int, bool) Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs. public NDArray mean(int axis, bool keepdims) Parameters axis int Axis or axes along which the means are computed. The default is to compute the mean of the flattened array. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised. Returns NDArray returns a new array containing the mean values, otherwise a reference to the output array is returned. mean(int, Type, bool) Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs. public NDArray mean(int axis, Type type, bool keepdims = false) Parameters axis int Axis or axes along which the means are computed. The default is to compute the mean of the flattened array. type Type Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised. Returns NDArray returns a new array containing the mean values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html mgrid(NDArray) nd_grid instance which returns a dense multi-dimensional “meshgrid”. An instance of numpy.lib.index_tricks.nd_grid which returns an dense (or fleshed out) mesh-grid when indexed, so that each returned argument has the same shape. The dimensions and number of the output arrays are equal to the number of indexing dimensions.If the step length is not a complex number, then the stop is not inclusive. public (NDArray, NDArray) mgrid(NDArray rhs) Parameters rhs NDArray Returns (NDArray Lhs, NDArray Rhs) mesh-grid ndarrays all of the same dimensions Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.mgrid.html min(int, bool, Type) Return the minimum of an array or minimum along an axis. [SuppressMessage(\"ReSharper\", \"TooWideLocalVariableScope\")] [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] public NDArray min(int axis, bool keepdims = false, Type dtype = null) Parameters axis int Axis or axes along which to operate. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. dtype Type the type expected as a return, null will remain the same dtype. Returns NDArray Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amin.html min(Type) Return the minimum of an array or minimum along an axis. [SuppressMessage(\"ReSharper\", \"TooWideLocalVariableScope\")] [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] public NDArray min(Type dtype = null) Parameters dtype Type the type expected as a return, null will remain the same dtype. Returns NDArray Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amin.html min() Return the minimum of an array or minimum along an axis. public T min() where T : unmanaged Returns T Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Type Parameters T The expected return type, cast will be performed if necessary. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amin.html multi_dot(params NDArray[]) public NDArray multi_dot(params NDArray[] np2Multi) Parameters np2Multi NDArray[] Returns NDArray negate() Negates all values by performing: -x public NDArray negate() Returns NDArray negative() Negates all positive values. public NDArray negative() Returns NDArray positive() Positives all negative values. public NDArray positive() Returns NDArray prod(int?, Type, bool) Return the product of array elements over a given axis. public NDArray prod(int? axis = null, Type dtype = null, bool keepdims = false) Parameters axis int? Axis or axes along which a product is performed. The default, axis=None, will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis. dtype Type The type of the returned array, as well as of the accumulator in which the elements are multiplied. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. Returns NDArray An array shaped as a but with the specified axis removed. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.prod.html qr() public (NDArray, NDArray) qr() Returns (NDArray Lhs, NDArray Rhs) ravel() Return a contiguous flattened array. A 1-D array, containing the elements of the input, is returned public NDArray ravel() Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html reshape(Shape) Gives a new shape to an array without changing its data. public NDArray reshape(Shape newShape) Parameters newShape Shape The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions. Returns NDArray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html reshape(ref Shape) Gives a new shape to an array without changing its data. public NDArray reshape(ref Shape newShape) Parameters newShape Shape The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions. Returns NDArray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html reshape(params int[]) Gives a new shape to an array without changing its data. [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] public NDArray reshape(params int[] shape) Parameters shape int[] The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions. Returns NDArray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html reshape_unsafe(Shape) Gives a new shape to an array without changing its data. public NDArray reshape_unsafe(Shape newshape) Parameters newshape Shape The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions. Returns NDArray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html reshape_unsafe(ref Shape) Gives a new shape to an array without changing its data. public NDArray reshape_unsafe(ref Shape newshape) Parameters newshape Shape The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions. Returns NDArray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html reshape_unsafe(params int[]) Gives a new shape to an array without changing its data. [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] public NDArray reshape_unsafe(params int[] shape) Parameters shape int[] The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions. Returns NDArray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html roll(int) public NDArray roll(int shift) Parameters shift int Returns NDArray roll(int, int) Roll array elements along a given axis. Elements that roll beyond the last position are re-introduced at the first. public NDArray roll(int shift, int axis) Parameters shift int axis int Returns NDArray std(bool, int?, NPTypeCode?) Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. public NDArray std(bool keepdims = false, int? ddof = null, NPTypeCode? dtype = null) Parameters keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. dtype NPTypeCode? Returns NDArray returns a new array containing the std values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html std(int, bool, int?, NPTypeCode?) Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. public NDArray std(int axis, bool keepdims = false, int? ddof = null, NPTypeCode? dtype = null) Parameters axis int Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. dtype NPTypeCode? Returns NDArray returns a new array containing the std values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html sum() Sum of array elements into a scalar. public NDArray sum() Returns NDArray An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.sum.html sum(int) Sum of array elements over a given axis. public NDArray sum(int axis) Parameters axis int Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. Returns NDArray An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.sum.html sum(int, bool, NPTypeCode?) Sum of array elements over a given axis. public NDArray sum(int axis, bool keepdims, NPTypeCode? typeCode = null) Parameters axis int Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised. typeCode NPTypeCode? The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used. Returns NDArray An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.sum.html sum(int, bool, Type) Sum of array elements over a given axis. public NDArray sum(int axis, bool keepdims, Type dtype) Parameters axis int Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised. dtype Type The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used. Returns NDArray An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.sum.html svd() public (NDArray, NDArray, NDArray) svd() Returns (NDArray, NDArray, NDArray) swapaxes(int, int) Interchange two axes of an array. public NDArray swapaxes(int axis1, int axis2) Parameters axis1 int First axis. axis2 int Second axis. Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.swapaxes.html tofile(string) Write array to a file as text or binary (default). Data is always written in ‘C’ order, independent of the order of a. The data produced by this method can be recovered using the function fromfile(). public void tofile(string fid) Parameters fid string An open file object, or a string containing a filename. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tofile.html transpose(int[]) Permute the dimensions of an array. public NDArray transpose(int[] premute = null) Parameters premute int[] By default, reverse the dimensions, otherwise permute the axes according to the values given. Returns NDArray a with its axes permuted. A view is returned whenever possible. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html unique() Find the unique elements of an array. Returns the sorted unique elements of an array.There are three optional outputs in addition to the unique elements: the indices of the input array that give the unique values the indices of the unique array that reconstruct the input array the number of times each unique value comes up in the input array public NDArray unique() Returns NDArray The sorted unique values. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html unique() Find the unique elements of an array. Returns the sorted unique elements of an array.There are three optional outputs in addition to the unique elements: the indices of the input array that give the unique values the indices of the unique array that reconstruct the input array the number of times each unique value comes up in the input array protected NDArray unique() where T : unmanaged Returns NDArray Type Parameters T Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html var(bool, int?, NPTypeCode?) Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. public NDArray var(bool keepdims = false, int? ddof = null, NPTypeCode? dtype = null) Parameters keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. dtype NPTypeCode? Returns NDArray returns a new array containing the std values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html var(int, bool, int?, NPTypeCode?) Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. public NDArray var(int axis, bool keepdims = false, int? ddof = null, NPTypeCode? dtype = null) Parameters axis int Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. dtype NPTypeCode? Returns NDArray returns a new array containing the std values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html view(Type) New view of array with the same data. public NDArray view(Type dtype = null) Parameters dtype Type Data-type descriptor of the returned view, e.g., float32 or int16. The default, None, results in the view having the same data-type as a. This argument can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the type parameter). Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.view.html view() New view of array with the same data. public NDArray view() where T : unmanaged Returns NDArray Type Parameters T Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.view.html vstack(params NDArray[]) Stack arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape(N,) have been reshaped to(1, N). Rebuilds arrays divided by vsplit. public NDArray vstack(params NDArray[] tup) Parameters tup NDArray[] The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length. Returns NDArray https://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html Operators operator +(NDArray, NDArray) public static NDArray operator +(NDArray x, NDArray y) Parameters x NDArray y NDArray Returns NDArray operator +(NDArray, bool) public static NDArray operator +(NDArray left, bool right) Parameters left NDArray right bool Returns NDArray operator +(NDArray, byte) public static NDArray operator +(NDArray left, byte right) Parameters left NDArray right byte Returns NDArray operator +(NDArray, char) public static NDArray operator +(NDArray left, char right) Parameters left NDArray right char Returns NDArray operator +(NDArray, decimal) public static NDArray operator +(NDArray left, decimal right) Parameters left NDArray right decimal Returns NDArray operator +(NDArray, double) public static NDArray operator +(NDArray left, double right) Parameters left NDArray right double Returns NDArray operator +(NDArray, short) public static NDArray operator +(NDArray left, short right) Parameters left NDArray right short Returns NDArray operator +(NDArray, int) public static NDArray operator +(NDArray left, int right) Parameters left NDArray right int Returns NDArray operator +(NDArray, long) public static NDArray operator +(NDArray left, long right) Parameters left NDArray right long Returns NDArray operator +(NDArray, float) public static NDArray operator +(NDArray left, float right) Parameters left NDArray right float Returns NDArray operator +(NDArray, ushort) public static NDArray operator +(NDArray left, ushort right) Parameters left NDArray right ushort Returns NDArray operator +(NDArray, uint) public static NDArray operator +(NDArray left, uint right) Parameters left NDArray right uint Returns NDArray operator +(NDArray, ulong) public static NDArray operator +(NDArray left, ulong right) Parameters left NDArray right ulong Returns NDArray operator +(bool, NDArray) public static NDArray operator +(bool left, NDArray right) Parameters left bool right NDArray Returns NDArray operator +(byte, NDArray) public static NDArray operator +(byte left, NDArray right) Parameters left byte right NDArray Returns NDArray operator +(char, NDArray) public static NDArray operator +(char left, NDArray right) Parameters left char right NDArray Returns NDArray operator +(decimal, NDArray) public static NDArray operator +(decimal left, NDArray right) Parameters left decimal right NDArray Returns NDArray operator +(double, NDArray) public static NDArray operator +(double left, NDArray right) Parameters left double right NDArray Returns NDArray operator +(short, NDArray) public static NDArray operator +(short left, NDArray right) Parameters left short right NDArray Returns NDArray operator +(int, NDArray) public static NDArray operator +(int left, NDArray right) Parameters left int right NDArray Returns NDArray operator +(long, NDArray) public static NDArray operator +(long left, NDArray right) Parameters left long right NDArray Returns NDArray operator +(float, NDArray) public static NDArray operator +(float left, NDArray right) Parameters left float right NDArray Returns NDArray operator +(ushort, NDArray) public static NDArray operator +(ushort left, NDArray right) Parameters left ushort right NDArray Returns NDArray operator +(uint, NDArray) public static NDArray operator +(uint left, NDArray right) Parameters left uint right NDArray Returns NDArray operator +(ulong, NDArray) public static NDArray operator +(ulong left, NDArray right) Parameters left ulong right NDArray Returns NDArray operator &(NDArray, NDArray) public static NDArray operator &(NDArray lhs, NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray operator &(NDArray, byte) public static NDArray operator &(NDArray lhs, byte rhs) Parameters lhs NDArray rhs byte Returns NDArray operator |(NDArray, NDArray) public static NDArray operator |(NDArray np_, NDArray obj_) Parameters np_ NDArray obj_ NDArray Returns NDArray operator /(NDArray, NDArray) public static NDArray operator /(NDArray x, NDArray y) Parameters x NDArray y NDArray Returns NDArray operator /(NDArray, bool) public static NDArray operator /(NDArray left, bool right) Parameters left NDArray right bool Returns NDArray operator /(NDArray, byte) public static NDArray operator /(NDArray left, byte right) Parameters left NDArray right byte Returns NDArray operator /(NDArray, char) public static NDArray operator /(NDArray left, char right) Parameters left NDArray right char Returns NDArray operator /(NDArray, decimal) public static NDArray operator /(NDArray left, decimal right) Parameters left NDArray right decimal Returns NDArray operator /(NDArray, double) public static NDArray operator /(NDArray left, double right) Parameters left NDArray right double Returns NDArray operator /(NDArray, short) public static NDArray operator /(NDArray left, short right) Parameters left NDArray right short Returns NDArray operator /(NDArray, int) public static NDArray operator /(NDArray left, int right) Parameters left NDArray right int Returns NDArray operator /(NDArray, long) public static NDArray operator /(NDArray left, long right) Parameters left NDArray right long Returns NDArray operator /(NDArray, float) public static NDArray operator /(NDArray left, float right) Parameters left NDArray right float Returns NDArray operator /(NDArray, ushort) public static NDArray operator /(NDArray left, ushort right) Parameters left NDArray right ushort Returns NDArray operator /(NDArray, uint) public static NDArray operator /(NDArray left, uint right) Parameters left NDArray right uint Returns NDArray operator /(NDArray, ulong) public static NDArray operator /(NDArray left, ulong right) Parameters left NDArray right ulong Returns NDArray operator /(bool, NDArray) public static NDArray operator /(bool left, NDArray right) Parameters left bool right NDArray Returns NDArray operator /(byte, NDArray) public static NDArray operator /(byte left, NDArray right) Parameters left byte right NDArray Returns NDArray operator /(char, NDArray) public static NDArray operator /(char left, NDArray right) Parameters left char right NDArray Returns NDArray operator /(decimal, NDArray) public static NDArray operator /(decimal left, NDArray right) Parameters left decimal right NDArray Returns NDArray operator /(double, NDArray) public static NDArray operator /(double left, NDArray right) Parameters left double right NDArray Returns NDArray operator /(short, NDArray) public static NDArray operator /(short left, NDArray right) Parameters left short right NDArray Returns NDArray operator /(int, NDArray) public static NDArray operator /(int left, NDArray right) Parameters left int right NDArray Returns NDArray operator /(long, NDArray) public static NDArray operator /(long left, NDArray right) Parameters left long right NDArray Returns NDArray operator /(float, NDArray) public static NDArray operator /(float left, NDArray right) Parameters left float right NDArray Returns NDArray operator /(ushort, NDArray) public static NDArray operator /(ushort left, NDArray right) Parameters left ushort right NDArray Returns NDArray operator /(uint, NDArray) public static NDArray operator /(uint left, NDArray right) Parameters left uint right NDArray Returns NDArray operator /(ulong, NDArray) public static NDArray operator /(ulong left, NDArray right) Parameters left ulong right NDArray Returns NDArray operator ==(NDArray, object) public static NDArray operator ==(NDArray left, object right) Parameters left NDArray right object Returns NDArray explicit operator Array(NDArray) public static explicit operator Array(NDArray nd) Parameters nd NDArray Returns Array explicit operator string(NDArray) public static explicit operator string(NDArray d) Parameters d NDArray Returns string explicit operator ushort(NDArray) public static explicit operator ushort(NDArray nd) Parameters nd NDArray Returns ushort explicit operator NDArray(ushort) public static explicit operator NDArray(ushort d) Parameters d ushort Returns NDArray operator >(NDArray, int) public static NDArray operator >(NDArray np, int obj) Parameters np NDArray obj int Returns NDArray operator >(NDArray, object) public static NDArray operator >(NDArray np, object obj) Parameters np NDArray obj object Returns NDArray implicit operator bool(NDArray) public static implicit operator bool(NDArray nd) Parameters nd NDArray Returns bool implicit operator char(NDArray) public static implicit operator char(NDArray nd) Parameters nd NDArray Returns char implicit operator decimal(NDArray) public static implicit operator decimal(NDArray nd) Parameters nd NDArray Returns decimal implicit operator double(NDArray) public static implicit operator double(NDArray nd) Parameters nd NDArray Returns double implicit operator short(NDArray) public static implicit operator short(NDArray nd) Parameters nd NDArray Returns short implicit operator int(NDArray) public static implicit operator int(NDArray nd) Parameters nd NDArray Returns int implicit operator long(NDArray) public static implicit operator long(NDArray nd) Parameters nd NDArray Returns long implicit operator float(NDArray) public static implicit operator float(NDArray nd) Parameters nd NDArray Returns float implicit operator uint(NDArray) public static implicit operator uint(NDArray nd) Parameters nd NDArray Returns uint implicit operator ulong(NDArray) public static implicit operator ulong(NDArray nd) Parameters nd NDArray Returns ulong implicit operator NDArray(Array) public static implicit operator NDArray(Array array) Parameters array Array Returns NDArray implicit operator NDArray(bool) public static implicit operator NDArray(bool d) Parameters d bool Returns NDArray implicit operator NDArray(char) public static implicit operator NDArray(char d) Parameters d char Returns NDArray implicit operator NDArray(decimal) public static implicit operator NDArray(decimal d) Parameters d decimal Returns NDArray implicit operator NDArray(double) public static implicit operator NDArray(double d) Parameters d double Returns NDArray implicit operator NDArray(short) public static implicit operator NDArray(short d) Parameters d short Returns NDArray implicit operator NDArray(int) public static implicit operator NDArray(int d) Parameters d int Returns NDArray implicit operator NDArray(long) public static implicit operator NDArray(long d) Parameters d long Returns NDArray implicit operator NDArray(Complex) public static implicit operator NDArray(Complex d) Parameters d Complex Returns NDArray implicit operator NDArray(float) public static implicit operator NDArray(float d) Parameters d float Returns NDArray implicit operator NDArray(string) public static implicit operator NDArray(string str) Parameters str string Returns NDArray implicit operator NDArray(uint) public static implicit operator NDArray(uint d) Parameters d uint Returns NDArray implicit operator NDArray(ulong) public static implicit operator NDArray(ulong d) Parameters d ulong Returns NDArray operator !=(NDArray, object) public static NDArray operator !=(NDArray np, object obj) Parameters np NDArray obj object Returns NDArray operator <(NDArray, int) public static NDArray operator <(NDArray np, int obj) Parameters np NDArray obj int Returns NDArray operator <(NDArray, object) public static NDArray operator <(NDArray np, object obj) Parameters np NDArray obj object Returns NDArray operator !(NDArray) public static NDArray operator !(NDArray self) Parameters self NDArray Returns NDArray operator %(NDArray, NDArray) public static NDArray operator %(NDArray x, NDArray y) Parameters x NDArray y NDArray Returns NDArray operator %(NDArray, bool) public static NDArray operator %(NDArray left, bool right) Parameters left NDArray right bool Returns NDArray operator %(NDArray, byte) public static NDArray operator %(NDArray left, byte right) Parameters left NDArray right byte Returns NDArray operator %(NDArray, char) public static NDArray operator %(NDArray left, char right) Parameters left NDArray right char Returns NDArray operator %(NDArray, decimal) public static NDArray operator %(NDArray left, decimal right) Parameters left NDArray right decimal Returns NDArray operator %(NDArray, double) public static NDArray operator %(NDArray left, double right) Parameters left NDArray right double Returns NDArray operator %(NDArray, short) public static NDArray operator %(NDArray left, short right) Parameters left NDArray right short Returns NDArray operator %(NDArray, int) public static NDArray operator %(NDArray left, int right) Parameters left NDArray right int Returns NDArray operator %(NDArray, long) public static NDArray operator %(NDArray left, long right) Parameters left NDArray right long Returns NDArray operator %(NDArray, float) public static NDArray operator %(NDArray left, float right) Parameters left NDArray right float Returns NDArray operator %(NDArray, ushort) public static NDArray operator %(NDArray left, ushort right) Parameters left NDArray right ushort Returns NDArray operator %(NDArray, uint) public static NDArray operator %(NDArray left, uint right) Parameters left NDArray right uint Returns NDArray operator %(NDArray, ulong) public static NDArray operator %(NDArray left, ulong right) Parameters left NDArray right ulong Returns NDArray operator %(bool, NDArray) public static NDArray operator %(bool left, NDArray right) Parameters left bool right NDArray Returns NDArray operator %(byte, NDArray) public static NDArray operator %(byte left, NDArray right) Parameters left byte right NDArray Returns NDArray operator %(char, NDArray) public static NDArray operator %(char left, NDArray right) Parameters left char right NDArray Returns NDArray operator %(decimal, NDArray) public static NDArray operator %(decimal left, NDArray right) Parameters left decimal right NDArray Returns NDArray operator %(double, NDArray) public static NDArray operator %(double left, NDArray right) Parameters left double right NDArray Returns NDArray operator %(short, NDArray) public static NDArray operator %(short left, NDArray right) Parameters left short right NDArray Returns NDArray operator %(int, NDArray) public static NDArray operator %(int left, NDArray right) Parameters left int right NDArray Returns NDArray operator %(long, NDArray) public static NDArray operator %(long left, NDArray right) Parameters left long right NDArray Returns NDArray operator %(float, NDArray) public static NDArray operator %(float left, NDArray right) Parameters left float right NDArray Returns NDArray operator %(ushort, NDArray) public static NDArray operator %(ushort left, NDArray right) Parameters left ushort right NDArray Returns NDArray operator %(uint, NDArray) public static NDArray operator %(uint left, NDArray right) Parameters left uint right NDArray Returns NDArray operator %(ulong, NDArray) public static NDArray operator %(ulong left, NDArray right) Parameters left ulong right NDArray Returns NDArray operator *(NDArray, NDArray) public static NDArray operator *(NDArray x, NDArray y) Parameters x NDArray y NDArray Returns NDArray operator *(NDArray, bool) public static NDArray operator *(NDArray left, bool right) Parameters left NDArray right bool Returns NDArray operator *(NDArray, byte) public static NDArray operator *(NDArray left, byte right) Parameters left NDArray right byte Returns NDArray operator *(NDArray, char) public static NDArray operator *(NDArray left, char right) Parameters left NDArray right char Returns NDArray operator *(NDArray, decimal) public static NDArray operator *(NDArray left, decimal right) Parameters left NDArray right decimal Returns NDArray operator *(NDArray, double) public static NDArray operator *(NDArray left, double right) Parameters left NDArray right double Returns NDArray operator *(NDArray, short) public static NDArray operator *(NDArray left, short right) Parameters left NDArray right short Returns NDArray operator *(NDArray, int) public static NDArray operator *(NDArray left, int right) Parameters left NDArray right int Returns NDArray operator *(NDArray, long) public static NDArray operator *(NDArray left, long right) Parameters left NDArray right long Returns NDArray operator *(NDArray, float) public static NDArray operator *(NDArray left, float right) Parameters left NDArray right float Returns NDArray operator *(NDArray, ushort) public static NDArray operator *(NDArray left, ushort right) Parameters left NDArray right ushort Returns NDArray operator *(NDArray, uint) public static NDArray operator *(NDArray left, uint right) Parameters left NDArray right uint Returns NDArray operator *(NDArray, ulong) public static NDArray operator *(NDArray left, ulong right) Parameters left NDArray right ulong Returns NDArray operator *(bool, NDArray) public static NDArray operator *(bool left, NDArray right) Parameters left bool right NDArray Returns NDArray operator *(byte, NDArray) public static NDArray operator *(byte left, NDArray right) Parameters left byte right NDArray Returns NDArray operator *(char, NDArray) public static NDArray operator *(char left, NDArray right) Parameters left char right NDArray Returns NDArray operator *(decimal, NDArray) public static NDArray operator *(decimal left, NDArray right) Parameters left decimal right NDArray Returns NDArray operator *(double, NDArray) public static NDArray operator *(double left, NDArray right) Parameters left double right NDArray Returns NDArray operator *(short, NDArray) public static NDArray operator *(short left, NDArray right) Parameters left short right NDArray Returns NDArray operator *(int, NDArray) public static NDArray operator *(int left, NDArray right) Parameters left int right NDArray Returns NDArray operator *(long, NDArray) public static NDArray operator *(long left, NDArray right) Parameters left long right NDArray Returns NDArray operator *(float, NDArray) public static NDArray operator *(float left, NDArray right) Parameters left float right NDArray Returns NDArray operator *(ushort, NDArray) public static NDArray operator *(ushort left, NDArray right) Parameters left ushort right NDArray Returns NDArray operator *(uint, NDArray) public static NDArray operator *(uint left, NDArray right) Parameters left uint right NDArray Returns NDArray operator *(ulong, NDArray) public static NDArray operator *(ulong left, NDArray right) Parameters left ulong right NDArray Returns NDArray operator -(NDArray, NDArray) public static NDArray operator -(NDArray x, NDArray y) Parameters x NDArray y NDArray Returns NDArray operator -(NDArray, bool) public static NDArray operator -(NDArray left, bool right) Parameters left NDArray right bool Returns NDArray operator -(NDArray, byte) public static NDArray operator -(NDArray left, byte right) Parameters left NDArray right byte Returns NDArray operator -(NDArray, char) public static NDArray operator -(NDArray left, char right) Parameters left NDArray right char Returns NDArray operator -(NDArray, decimal) public static NDArray operator -(NDArray left, decimal right) Parameters left NDArray right decimal Returns NDArray operator -(NDArray, double) public static NDArray operator -(NDArray left, double right) Parameters left NDArray right double Returns NDArray operator -(NDArray, short) public static NDArray operator -(NDArray left, short right) Parameters left NDArray right short Returns NDArray operator -(NDArray, int) public static NDArray operator -(NDArray left, int right) Parameters left NDArray right int Returns NDArray operator -(NDArray, long) public static NDArray operator -(NDArray left, long right) Parameters left NDArray right long Returns NDArray operator -(NDArray, float) public static NDArray operator -(NDArray left, float right) Parameters left NDArray right float Returns NDArray operator -(NDArray, ushort) public static NDArray operator -(NDArray left, ushort right) Parameters left NDArray right ushort Returns NDArray operator -(NDArray, uint) public static NDArray operator -(NDArray left, uint right) Parameters left NDArray right uint Returns NDArray operator -(NDArray, ulong) public static NDArray operator -(NDArray left, ulong right) Parameters left NDArray right ulong Returns NDArray operator -(bool, NDArray) public static NDArray operator -(bool left, NDArray right) Parameters left bool right NDArray Returns NDArray operator -(byte, NDArray) public static NDArray operator -(byte left, NDArray right) Parameters left byte right NDArray Returns NDArray operator -(char, NDArray) public static NDArray operator -(char left, NDArray right) Parameters left char right NDArray Returns NDArray operator -(decimal, NDArray) public static NDArray operator -(decimal left, NDArray right) Parameters left decimal right NDArray Returns NDArray operator -(double, NDArray) public static NDArray operator -(double left, NDArray right) Parameters left double right NDArray Returns NDArray operator -(short, NDArray) public static NDArray operator -(short left, NDArray right) Parameters left short right NDArray Returns NDArray operator -(int, NDArray) public static NDArray operator -(int left, NDArray right) Parameters left int right NDArray Returns NDArray operator -(long, NDArray) public static NDArray operator -(long left, NDArray right) Parameters left long right NDArray Returns NDArray operator -(float, NDArray) public static NDArray operator -(float left, NDArray right) Parameters left float right NDArray Returns NDArray operator -(ushort, NDArray) public static NDArray operator -(ushort left, NDArray right) Parameters left ushort right NDArray Returns NDArray operator -(uint, NDArray) public static NDArray operator -(uint left, NDArray right) Parameters left uint right NDArray Returns NDArray operator -(ulong, NDArray) public static NDArray operator -(ulong left, NDArray right) Parameters left ulong right NDArray Returns NDArray operator -(NDArray) public static NDArray operator -(NDArray x) Parameters x NDArray Returns NDArray operator +(NDArray) public static NDArray operator +(NDArray x) Parameters x NDArray Returns NDArray" + }, + "api/NumSharp.NDIterator-1.html": { + "href": "api/NumSharp.NDIterator-1.html", + "title": "Class NDIterator | NumSharp Documentation", + "summary": "Class NDIterator Namespace NumSharp Assembly NumSharp.dll public class NDIterator : NDIterator, IEnumerable, IEnumerable, IDisposable where TOut : unmanaged Type Parameters TOut Inheritance object NDIterator Implements NDIterator IEnumerable IEnumerable IDisposable Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Constructors NDIterator(IArraySlice, Shape, Shape?, bool) public NDIterator(IArraySlice slice, Shape shape, Shape? broadcastedShape, bool autoReset = false) Parameters slice IArraySlice shape Shape broadcastedShape Shape? autoReset bool NDIterator(IMemoryBlock, Shape, Shape?, bool) public NDIterator(IMemoryBlock block, Shape shape, Shape? broadcastedShape, bool autoReset = false) Parameters block IMemoryBlock shape Shape broadcastedShape Shape? autoReset bool NDIterator(UnmanagedStorage, bool) public NDIterator(UnmanagedStorage storage, bool autoReset = false) Parameters storage UnmanagedStorage autoReset bool NDIterator(NDArray, bool) public NDIterator(NDArray arr, bool autoReset = false) Parameters arr NDArray autoReset bool Fields AutoReset Does this iterator resets automatically when it finishes? public bool AutoReset Field Value bool Remarks When this is true, HasNext always returns true. Block public readonly IMemoryBlock Block Field Value IMemoryBlock BroadcastedShape The broadcasted version of Shape. public Shape? BroadcastedShape Field Value Shape? Remarks Might be null when iterating a non-broadcasted class HasNext Returns a function that when called, checks if there is a next element in this iterator. public Func HasNext Field Value Func MoveNext Returns a function that when called, moves to next iteration and return the next value. public Func MoveNext Field Value Func Remarks Make sure to check HasNext first. MoveNextReference Returns a function that when called, moves to next iteration and return a reference to the next value. public MoveNextReferencedDelegate MoveNextReference Field Value MoveNextReferencedDelegate Remarks Make sure to check HasNext first. Reset Resets internal pointer/counter. public Action Reset Field Value Action Shape The shape this iterator iterates public Shape Shape Field Value Shape Type public readonly IteratorType Type Field Value IteratorType size The size of this iterator. public int size Field Value int Methods Dispose() Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. public void Dispose() GetEnumerator() Returns an enumerator that iterates through the collection. public IEnumerator GetEnumerator() Returns IEnumerator An enumerator that can be used to iterate through the collection. SetDefaults() protected void SetDefaults() SetMode(bool, Shape) Set the mode according to given parameters public void SetMode(bool autoreset, Shape reshape = default) Parameters autoreset bool The iterator will transparently reset after it is done. reshape Shape Provide a different shape to the iterator. autoresetDefault_Boolean() protected void autoresetDefault_Boolean() autoresetDefault_Byte() protected void autoresetDefault_Byte() autoresetDefault_Char() protected void autoresetDefault_Char() autoresetDefault_Decimal() protected void autoresetDefault_Decimal() autoresetDefault_Double() protected void autoresetDefault_Double() autoresetDefault_Int16() protected void autoresetDefault_Int16() autoresetDefault_Int32() protected void autoresetDefault_Int32() autoresetDefault_Int64() protected void autoresetDefault_Int64() autoresetDefault_NoCast() protected void autoresetDefault_NoCast() autoresetDefault_Single() protected void autoresetDefault_Single() autoresetDefault_UInt16() protected void autoresetDefault_UInt16() autoresetDefault_UInt32() protected void autoresetDefault_UInt32() autoresetDefault_UInt64() protected void autoresetDefault_UInt64() setDefaults_Boolean() protected void setDefaults_Boolean() setDefaults_Byte() protected void setDefaults_Byte() setDefaults_Char() protected void setDefaults_Char() setDefaults_Decimal() protected void setDefaults_Decimal() setDefaults_Double() protected void setDefaults_Double() setDefaults_Int16() protected void setDefaults_Int16() setDefaults_Int32() protected void setDefaults_Int32() setDefaults_Int64() protected void setDefaults_Int64() setDefaults_NoCast() protected void setDefaults_NoCast() setDefaults_Single() protected void setDefaults_Single() setDefaults_UInt16() protected void setDefaults_UInt16() setDefaults_UInt32() protected void setDefaults_UInt32() setDefaults_UInt64() protected void setDefaults_UInt64()" + }, + "api/NumSharp.NDIterator.html": { + "href": "api/NumSharp.NDIterator.html", + "title": "Interface NDIterator | NumSharp Documentation", + "summary": "Interface NDIterator Namespace NumSharp Assembly NumSharp.dll public interface NDIterator : IEnumerable Inherited Members IEnumerable.GetEnumerator() Extension Methods LinqExtensions.Yield(T) Properties AutoReset bool AutoReset { get; } Property Value bool Block IMemoryBlock Block { get; } Property Value IMemoryBlock BroadcastedShape Shape? BroadcastedShape { get; } Property Value Shape? HasNext Func HasNext { get; } Property Value Func Reset Action Reset { get; } Property Value Action Shape Shape Shape { get; } Property Value Shape Type IteratorType Type { get; } Property Value IteratorType Methods MoveNextReference() MoveNextReferencedDelegate MoveNextReference() where T : unmanaged Returns MoveNextReferencedDelegate Type Parameters T MoveNext() Func MoveNext() where T : unmanaged Returns Func Type Parameters T" + }, + "api/NumSharp.NDIteratorExtensions.html": { + "href": "api/NumSharp.NDIteratorExtensions.html", + "title": "Class NDIteratorExtensions | NumSharp Documentation", + "summary": "Class NDIteratorExtensions Namespace NumSharp Assembly NumSharp.dll public static class NDIteratorExtensions Inheritance object NDIteratorExtensions Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Methods AsIterator(IArraySlice, Shape) Creates a new iterator to iterate given arr as if it were shaped like shape. public static NDIterator AsIterator(this IArraySlice arr, Shape shape) Parameters arr IArraySlice The IArraySlice to iterate. shape Shape Returns NDIterator AsIterator(IArraySlice, Shape, Shape, bool) Creates a new iterator to iterate given arr as if it were shaped like shape. public static NDIterator AsIterator(this IArraySlice arr, Shape shape, Shape broadcastShape, bool autoReset) Parameters arr IArraySlice The IArraySlice to iterate. shape Shape The original shape, non-broadcasted. broadcastShape Shape The broadcasted shape of shape autoReset bool Returns NDIterator AsIterator(IArraySlice, Shape, bool) Creates a new iterator to iterate given arr as if it were shaped like shape. public static NDIterator AsIterator(this IArraySlice arr, Shape shape, bool autoreset) Parameters arr IArraySlice The IArraySlice to iterate. shape Shape The original shape, non-broadcasted, to represent this iterator. autoreset bool Should this iterator loop forever? Returns NDIterator AsIterator(UnmanagedStorage, bool) Creates a new iterator to iterate given nd. public static NDIterator AsIterator(this UnmanagedStorage us, bool autoreset = false) Parameters us UnmanagedStorage The ndarray to iterate. autoreset bool Should this iterator loop forever? Returns NDIterator AsIterator(NDArray, bool) Creates a new iterator to iterate given nd. public static NDIterator AsIterator(this NDArray nd, bool autoreset = false) Parameters nd NDArray The ndarray to iterate. autoreset bool Should this iterator loop forever? Returns NDIterator AsIterator(NDArray, bool) Creates a new iterator to iterate given nd. public static NDIterator AsIterator(this NDArray nd, bool autoreset = false) where T : unmanaged Parameters nd NDArray The ndarray to iterate. autoreset bool Should this iterator loop forever? Returns NDIterator Type Parameters T" + }, + "api/NumSharp.NPTypeCode.html": { + "href": "api/NumSharp.NPTypeCode.html", + "title": "Enum NPTypeCode | NumSharp Documentation", + "summary": "Enum NPTypeCode Namespace NumSharp Assembly NumSharp.dll Represents all available types in numpy. public enum NPTypeCode Extension Methods LinqExtensions.Yield(T) NPTypeCodeExtensions.AsType(NPTypeCode) NPTypeCodeExtensions.CompareTo(NPTypeCode, NPTypeCode) NPTypeCodeExtensions.GetAccumulatingType(NPTypeCode) NPTypeCodeExtensions.GetComputingType(NPTypeCode) NPTypeCodeExtensions.GetDefaultValue(NPTypeCode) NPTypeCodeExtensions.IsNumerical(NPTypeCode) NPTypeCodeExtensions.IsRealNumber(NPTypeCode) NPTypeCodeExtensions.IsSigned(NPTypeCode) NPTypeCodeExtensions.IsUnsigned(NPTypeCode) NPTypeCodeExtensions.SizeOf(NPTypeCode) NumberInfo.MaxValue(NPTypeCode) NumberInfo.MinValue(NPTypeCode) Fields Empty = 0 A null reference. Boolean = 3 A simple type representing Boolean values of true or false. Char = 4 An integral type representing unsigned 16-bit integers with values between 0 and 65535. The set of possible values for the Char type corresponds to the Unicode character set. Byte = 6 An integral type representing unsigned 8-bit integers with values between 0 and 255. Int16 = 7 An integral type representing signed 16-bit integers with values between -32768 and 32767. UInt16 = 8 An integral type representing unsigned 16-bit integers with values between 0 and 65535. Int32 = 9 An integral type representing signed 32-bit integers with values between -2147483648 and 2147483647. UInt32 = 10 An integral type representing unsigned 32-bit integers with values between 0 and 4294967295. Int64 = 11 An integral type representing signed 64-bit integers with values between -9223372036854775808 and 9223372036854775807. UInt64 = 12 An integral type representing unsigned 64-bit integers with values between 0 and 18446744073709551615. Single = 13 A floating point type representing values ranging from approximately 1.5 x 10 -45 to 3.4 x 10 38 with a precision of 7 digits. Float = 13 Double = 14 A floating point type representing values ranging from approximately 5.0 x 10 -324 to 1.7 x 10 308 with a precision of 15-16 digits. Decimal = 15 A simple type representing values ranging from 1.0 x 10 -28 to approximately 7.9 x 10 28 with 28-29 significant digits. String = 18 A sealed class type representing Unicode character strings. Complex = 128 Remarks The int values of the enum are a copy of TypeCode excluding types not available in numpy." + }, + "api/NumSharp.NPTypeCodeExtensions.html": { + "href": "api/NumSharp.NPTypeCodeExtensions.html", + "title": "Class NPTypeCodeExtensions | NumSharp Documentation", + "summary": "Class NPTypeCodeExtensions Namespace NumSharp Assembly NumSharp.dll public static class NPTypeCodeExtensions Inheritance object NPTypeCodeExtensions Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Methods AsType(NPTypeCode) Convert NPTypeCode into its Type public static Type AsType(this NPTypeCode typeCode) Parameters typeCode NPTypeCode Returns Type CompareTo(NPTypeCode, NPTypeCode) public static int CompareTo(this NPTypeCode left, NPTypeCode right) Parameters left NPTypeCode right NPTypeCode Returns int GetAccumulatingType(NPTypeCode) Gets the dtype that is used as accumulation in case when statistics are computed like sum(in NDArray) public static NPTypeCode GetAccumulatingType(this NPTypeCode typeCode) Parameters typeCode NPTypeCode Returns NPTypeCode dtype in case when statistics are computed like sum(in NDArray) GetComputingType(NPTypeCode) Gets the dtype that is used as return type in case when statistics are computed with high decimal precision like sin(in NDArray, NPTypeCode?) public static NPTypeCode GetComputingType(this NPTypeCode typeCode) Parameters typeCode NPTypeCode Returns NPTypeCode dtype in case when statistics are computed like mean(in NDArray) GetDefaultValue(NPTypeCode) Gets the default value of typeCode. public static ValueType GetDefaultValue(this NPTypeCode typeCode) Parameters typeCode NPTypeCode Returns ValueType GetTypeCode(Type) Extracts NPTypeCode from given Type. public static NPTypeCode GetTypeCode(this Type type) Parameters type Type Returns NPTypeCode Remarks In case there was no successful cast to NPTypeCode, return will be Empty GetTypeCode() Extracts NPTypeCode from given T. public static NPTypeCode GetTypeCode() Returns NPTypeCode Type Parameters T Remarks In case there was no successful cast to NPTypeCode, return will be Empty IsNumerical(NPTypeCode) Returns true if typecode is a number (incl. bool, char and Complex). public static bool IsNumerical(this NPTypeCode typeCode) Parameters typeCode NPTypeCode Returns bool IsRealNumber(NPTypeCode) Is typeCode a float, double, complex or decimal? public static bool IsRealNumber(this NPTypeCode typeCode) Parameters typeCode NPTypeCode Returns bool IsSigned(NPTypeCode) Is typeCode a float, double, complex or decimal? public static bool IsSigned(this NPTypeCode typeCode) Parameters typeCode NPTypeCode Returns bool IsUnsigned(NPTypeCode) Is typeCode a uint, byte, ulong and so on. public static bool IsUnsigned(this NPTypeCode typeCode) Parameters typeCode NPTypeCode Returns bool IsValidNPType(Type) Checks if given Type has a match in NPTypeCode. public static bool IsValidNPType(this Type type) Parameters type Type Returns bool SizeOf(NPTypeCode) Gets the size of given typeCode public static int SizeOf(this NPTypeCode typeCode) Parameters typeCode NPTypeCode Returns int Remarks The size is computed by SizeOf()" + }, + "api/NumSharp.NativeRandomState.html": { + "href": "api/NumSharp.NativeRandomState.html", + "title": "Struct NativeRandomState | NumSharp Documentation", + "summary": "Struct NativeRandomState Namespace NumSharp Assembly NumSharp.dll Represents the stored state of Randomizer. public struct NativeRandomState Inherited Members ValueType.Equals(object) ValueType.GetHashCode() ValueType.ToString() object.Equals(object, object) object.GetType() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) Constructors NativeRandomState(byte[]) public NativeRandomState(byte[] state) Parameters state byte[] Fields State public readonly byte[] State Field Value byte[]" + }, + "api/NumSharp.NpzDictionary-1.html": { + "href": "api/NumSharp.NpzDictionary-1.html", + "title": "Class NpzDictionary | NumSharp Documentation", + "summary": "Class NpzDictionary Namespace NumSharp Assembly NumSharp.dll public class NpzDictionary : IDisposable, IReadOnlyDictionary, IReadOnlyCollection>, IEnumerable>, ICollection, IEnumerable, IEnumerable where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable Type Parameters T Inheritance object NpzDictionary Implements IDisposable IReadOnlyDictionary IReadOnlyCollection> IEnumerable> ICollection IEnumerable IEnumerable Derived NpzDictionary Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Constructors NpzDictionary(Stream) public NpzDictionary(Stream stream) Parameters stream Stream Properties Count Gets the number of elements in the collection. public int Count { get; } Property Value int The number of elements in the collection. IsReadOnly Gets a value indicating whether the ICollection is read-only. public bool IsReadOnly { get; } Property Value bool true if the ICollection is read-only; otherwise, false. IsSynchronized public bool IsSynchronized { get; } Property Value bool this[string] Gets the element that has the specified key in the read-only dictionary. public T this[string key] { get; } Parameters key string The key to locate. Property Value T The element that has the specified key in the read-only dictionary. Exceptions ArgumentNullException key is null. KeyNotFoundException The property is retrieved and key is not found. Keys Gets an enumerable collection that contains the keys in the read-only dictionary. public IEnumerable Keys { get; } Property Value IEnumerable An enumerable collection that contains the keys in the read-only dictionary. SyncRoot public object SyncRoot { get; } Property Value object Values Gets an enumerable collection that contains the values in the read-only dictionary. public IEnumerable Values { get; } Property Value IEnumerable An enumerable collection that contains the values in the read-only dictionary. Methods Add(T) Adds an item to the ICollection. public void Add(T item) Parameters item T The object to add to the ICollection. Exceptions NotSupportedException The ICollection is read-only. Clear() Removes all items from the ICollection. public void Clear() Exceptions NotSupportedException The ICollection is read-only. Contains(T) Determines whether the ICollection contains a specific value. public bool Contains(T item) Parameters item T The object to locate in the ICollection. Returns bool true if item is found in the ICollection; otherwise, false. ContainsKey(string) Determines whether the read-only dictionary contains an element that has the specified key. public bool ContainsKey(string key) Parameters key string The key to locate. Returns bool true if the read-only dictionary contains an element that has the specified key; otherwise, false. Exceptions ArgumentNullException key is null. CopyTo(Array, int) public void CopyTo(Array array, int arrayIndex) Parameters array Array arrayIndex int CopyTo(T[], int) Copies the elements of the ICollection to an Array, starting at a particular Array index. public void CopyTo(T[] array, int arrayIndex) Parameters array T[] The one-dimensional Array that is the destination of the elements copied from ICollection. The Array must have zero-based indexing. arrayIndex int The zero-based index in array at which copying begins. Exceptions ArgumentNullException array is null. ArgumentOutOfRangeException arrayIndex is less than 0. ArgumentException The number of elements in the source ICollection is greater than the available space from arrayIndex to the end of the destination array. Dispose() Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. public void Dispose() Dispose(bool) protected virtual void Dispose(bool disposing) Parameters disposing bool GetEnumerator() Returns an enumerator that iterates through the collection. public IEnumerator> GetEnumerator() Returns IEnumerator> An enumerator that can be used to iterate through the collection. Load_Npz(Stream) protected virtual T Load_Npz(Stream s) Parameters s Stream Returns T Remove(T) Removes the first occurrence of a specific object from the ICollection. public bool Remove(T item) Parameters item T The object to remove from the ICollection. Returns bool true if item was successfully removed from the ICollection; otherwise, false. This method also returns false if item is not found in the original ICollection. Exceptions NotSupportedException The ICollection is read-only. TryGetValue(string, out T) Gets the value that is associated with the specified key. public bool TryGetValue(string key, out T value) Parameters key string The key to locate. value T When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized. Returns bool true if the object that implements the IReadOnlyDictionary interface contains an element that has the specified key; otherwise, false. Exceptions ArgumentNullException key is null." + }, + "api/NumSharp.NpzDictionary.html": { + "href": "api/NumSharp.NpzDictionary.html", + "title": "Class NpzDictionary | NumSharp Documentation", + "summary": "Class NpzDictionary Namespace NumSharp Assembly NumSharp.dll public class NpzDictionary : NpzDictionary, IDisposable, IReadOnlyDictionary, IReadOnlyCollection>, IEnumerable>, ICollection, IEnumerable, IEnumerable Inheritance object NpzDictionary NpzDictionary Implements IDisposable IReadOnlyDictionary IReadOnlyCollection> IEnumerable> ICollection IEnumerable IEnumerable Inherited Members NpzDictionary.Keys NpzDictionary.Values NpzDictionary.Count NpzDictionary.SyncRoot NpzDictionary.IsSynchronized NpzDictionary.IsReadOnly NpzDictionary.this[string] NpzDictionary.ContainsKey(string) NpzDictionary.TryGetValue(string, out Array) NpzDictionary.GetEnumerator() NpzDictionary.CopyTo(Array, int) NpzDictionary.CopyTo(Array[], int) NpzDictionary.Add(Array) NpzDictionary.Clear() NpzDictionary.Contains(Array) NpzDictionary.Remove(Array) NpzDictionary.Dispose(bool) NpzDictionary.Dispose() object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Constructors NpzDictionary(Stream, bool) public NpzDictionary(Stream stream, bool jagged) Parameters stream Stream jagged bool Methods Load_Npz(Stream) protected override Array Load_Npz(Stream s) Parameters s Stream Returns Array" + }, + "api/NumSharp.NumPyRandom.html": { + "href": "api/NumSharp.NumPyRandom.html", + "title": "Class NumPyRandom | NumSharp Documentation", + "summary": "Class NumPyRandom Namespace NumSharp Assembly NumSharp.dll A class that serves as numpy.random.RandomState in python. public class NumPyRandom Inheritance object NumPyRandom Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Remarks https://docs.scipy.org/doc/numpy-1.16.1/reference/routines.random.html Constructors NumPyRandom() protected NumPyRandom() NumPyRandom(NativeRandomState) protected NumPyRandom(NativeRandomState nativeRandomState) Parameters nativeRandomState NativeRandomState NumPyRandom(Randomizer) protected NumPyRandom(Randomizer randomizer) Parameters randomizer Randomizer NumPyRandom(int) protected NumPyRandom(int seed) Parameters seed int Fields randomizer protected Randomizer randomizer Field Value Randomizer Properties Seed public int Seed { get; set; } Property Value int Methods RandomState() Returns a new instance of NumPyRandom. public NumPyRandom RandomState() Returns NumPyRandom RandomState(NativeRandomState) Returns a new instance of NumPyRandom. public NumPyRandom RandomState(NativeRandomState state) Parameters state NativeRandomState Returns NumPyRandom RandomState(int) Returns a new instance of NumPyRandom. public NumPyRandom RandomState(int seed) Parameters seed int Returns NumPyRandom bernoulli(double, Shape) Draw samples from a bernoulli distribution. public NDArray bernoulli(double p, Shape shape) Parameters p double Parameter of the distribution, >= 0 and <=1. shape Shape Output Shape Returns NDArray Drawn samples from the parameterized bernoulli distribution. bernoulli(double, params int[]) Draw samples from a bernoulli distribution. public NDArray bernoulli(double p, params int[] dims) Parameters p double Parameter of the distribution, >= 0 and <=1. dims int[] Output Shape Returns NDArray Drawn samples from the parameterized bernoulli distribution. beta(double, double, Shape) Draw samples from a Beta distribution. The Beta distribution is a special case of the Dirichlet distribution, and is related to the Gamma distribution.It has the probability distribution function public NDArray beta(double alpha, double betaValue, Shape shape) Parameters alpha double Alpha value betaValue double Beta value shape Shape Output Shape Returns NDArray beta(double, double, params int[]) Draw samples from a Beta distribution. The Beta distribution is a special case of the Dirichlet distribution, and is related to the Gamma distribution.It has the probability distribution function public NDArray beta(double alpha, double betaValue, params int[] dims) Parameters alpha double Alpha value betaValue double Beta value dims int[] Output Shape Returns NDArray binomial(int, double, Shape) Draw samples from a binomial distribution. Samples are drawn from a binomial distribution with specified parameters, n trials and p probability of success where n an integer >= 0 and p is in the interval[0, 1]. (n may be input as a float, but it is truncated to an integer in use) public NDArray binomial(int n, double p, Shape shape) Parameters n int Parameter of the distribution, >= 0. Floats are also accepted, but they will be truncated to integers. p double Parameter of the distribution, >= 0 and <=1. shape Shape Output Shape Returns NDArray Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials. Remarks https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.random.binomial.html binomial(int, double, params int[]) Draw samples from a binomial distribution. Samples are drawn from a binomial distribution with specified parameters, n trials and p probability of success where n an integer >= 0 and p is in the interval[0, 1]. (n may be input as a float, but it is truncated to an integer in use) public NDArray binomial(int n, double p, params int[] dims) Parameters n int Parameter of the distribution, >= 0. Floats are also accepted, but they will be truncated to integers. p double Parameter of the distribution, >= 0 and <=1. dims int[] Output Shape Returns NDArray Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials. Remarks https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.random.binomial.html chisquare(double, Shape) Draw samples from a chi-square distribution. When df independent random variables, each with standard normal distributions(mean 0, variance 1), are squared and summed, the resulting distribution is chi-square(see Notes). This distribution is often used in hypothesis testing. public NDArray chisquare(double df, Shape shape) Parameters df double Number of degrees of freedom, should be > 0. shape Shape Output Shape Returns NDArray Drawn samples from the parameterized chi-square distribution. Remarks https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.chisquare.html chisquare(double, params int[]) Draw samples from a chi-square distribution. When df independent random variables, each with standard normal distributions(mean 0, variance 1), are squared and summed, the resulting distribution is chi-square(see Notes). This distribution is often used in hypothesis testing. public NDArray chisquare(double df, params int[] dims) Parameters df double Number of degrees of freedom, should be > 0. dims int[] Output Shape Returns NDArray Drawn samples from the parameterized chi-square distribution. Remarks https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.chisquare.html choice(NDArray, Shape, bool, double[]) Generates a random sample from a given 1-D array public NDArray choice(NDArray arr, Shape shape = default, bool replace = true, double[] probabilities = null) Parameters arr NDArray If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a were np.arange(a) shape Shape Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned. replace bool Whether the sample is with or without replacement probabilities double[] The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a. Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html choice(int, Shape, bool, double[]) Generates a random sample from a given 1-D array public NDArray choice(int a, Shape shape = default, bool replace = true, double[] probabilities = null) Parameters a int If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a were np.arange(a) shape Shape Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned. replace bool Whether the sample is with or without replacement probabilities double[] The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a. Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html exponential(double, Shape) Draw samples from an exponential distribution. The exponential distribution is a continuous analogue of the geometric distribution. It describes many common situations, such as the size of raindrops measured over many rainstorms public NDArray exponential(double scale, Shape shape) Parameters scale double The scale parameter, \\beta = 1/\\lambda. shape Shape Output Shape Returns NDArray Drawn samples from the parameterized exponential distribution. Remarks https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.exponential.html exponential(double, params int[]) Draw samples from an exponential distribution. The exponential distribution is a continuous analogue of the geometric distribution. It describes many common situations, such as the size of raindrops measured over many rainstorms public NDArray exponential(double scale, params int[] dims) Parameters scale double The scale parameter, \\beta = 1/\\lambda. dims int[] Output Shape Returns NDArray Drawn samples from the parameterized exponential distribution. Remarks https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.exponential.html gamma(double, double, Shape) Draw samples from a Gamma distribution. Samples are drawn from a Gamma distribution with specified parameters, shape (sometimes designated “k”) and scale(sometimes designated “theta”), where both parameters are > 0. public NDArray gamma(double shapeV, double scale, Shape shape) Parameters shapeV double The shape of the gamma distribution. Should be greater than zero. scale double The scale of the gamma distribution. Should be greater than zero. Default is equal to 1. shape Shape Output shape. Returns NDArray Drawn samples from the parameterized gamma distribution. Remarks https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.gamma.html gamma(double, double, params int[]) Draw samples from a Gamma distribution. Samples are drawn from a Gamma distribution with specified parameters, shape (sometimes designated “k”) and scale(sometimes designated “theta”), where both parameters are > 0. public NDArray gamma(double shape, double scale, params int[] dims) Parameters shape double The shape of the gamma distribution. Should be greater than zero. scale double The scale of the gamma distribution. Should be greater than zero. Default is equal to 1. dims int[] Output shape. Returns NDArray Drawn samples from the parameterized gamma distribution. Remarks https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.gamma.html geometric(double, Shape) Draw samples from the geometric distribution. Bernoulli trials are experiments with one of two outcomes: success or failure(an example of such an experiment is flipping a coin). The geometric distribution models the number of trials that must be run in order to achieve success.It is therefore supported on the positive integers, k = 1, 2, .... public NDArray geometric(double p, Shape shape) Parameters p double The probability of success of an individual trial. shape Shape Output Shape Returns NDArray Drawn samples from the parameterized geometric distribution. Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.random.geometric.html geometric(double, params int[]) Draw samples from the geometric distribution. Bernoulli trials are experiments with one of two outcomes: success or failure(an example of such an experiment is flipping a coin). The geometric distribution models the number of trials that must be run in order to achieve success.It is therefore supported on the positive integers, k = 1, 2, .... public NDArray geometric(double p, params int[] dims) Parameters p double The probability of success of an individual trial. dims int[] Output Shape Returns NDArray Drawn samples from the parameterized geometric distribution. Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.random.geometric.html get_state() Return a NumPyRandom representing the internal state of the generator. public NativeRandomState get_state() Returns NativeRandomState lognormal(double, double, Shape) Draw samples from a log-normal distribution. Draw samples from a log-normal distribution with specified mean, standard deviation, and array shape. Note that the mean and standard deviation are not the values for the distribution itself, but of the underlying normal distribution it is derived from. public NDArray lognormal(double mean, double sigma, Shape shape) Parameters mean double Mean value of the underlying normal distribution. Default is 0. sigma double Standard deviation of the underlying normal distribution. Should be greater than zero. Default is 1. shape Shape Output Shape Returns NDArray Drawn samples from the parameterized bernoulli distribution. Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.random.lognormal.html lognormal(double, double, params int[]) Draw samples from a log-normal distribution. Draw samples from a log-normal distribution with specified mean, standard deviation, and array shape. Note that the mean and standard deviation are not the values for the distribution itself, but of the underlying normal distribution it is derived from. public NDArray lognormal(double mean, double sigma, params int[] dims) Parameters mean double Mean value of the underlying normal distribution. Default is 0. sigma double Standard deviation of the underlying normal distribution. Should be greater than zero. Default is 1. dims int[] Output Shape Returns NDArray Drawn samples from the parameterized bernoulli distribution. Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.random.lognormal.html normal(double, double, params int[]) Draw random samples from a normal (Gaussian) distribution. public NDArray normal(double loc, double scale, params int[] dims) Parameters loc double Mean of the distribution scale double Standard deviation of the distribution dims int[] Returns NDArray permutation(NDArray) Randomly permute a sequence, or return a permuted range. public NDArray permutation(NDArray x) Parameters x NDArray If x is an integer, randomly permute np.arange(x). Returns NDArray Permuted sequence or array range. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.permutation.html permutation(int) Randomly permute a sequence, or return a permuted range. public NDArray permutation(int x) Parameters x int If x is an integer, randomly permute np.arange(x). Returns NDArray Permuted sequence or array range. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.permutation.html poisson(double, Shape) Draw samples from a Poisson distribution. The Poisson distribution is the limit of the binomial distribution for large N. public NDArray poisson(double lam, Shape shape) Parameters lam double Expectation of interval, should be >= 0. A sequence of expectation intervals must be broadcastable over the requested size. shape Shape Output Shape Returns NDArray Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials. Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.random.poisson.html poisson(double, params int[]) Draw samples from a Poisson distribution. The Poisson distribution is the limit of the binomial distribution for large N. public NDArray poisson(double lam, params int[] dims) Parameters lam double Expectation of interval, should be >= 0. A sequence of expectation intervals must be broadcastable over the requested size. dims int[] Output Shape Returns NDArray Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials. Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.random.poisson.html rand(Shape) Random values in a given shape. Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1). public NDArray rand(Shape shape) Parameters shape Shape Returns NDArray rand(params int[]) Random values in a given shape. Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1). public NDArray rand(params int[] size) Parameters size int[] Returns NDArray randint(long, long, Shape, Type) Return random integers from the “discrete uniform” distribution of the specified dtype in the “half-open” interval [low, high). If high is None (the default), then results are from [0, low). public NDArray randint(long low, long high = -1, Shape size = default, Type dtype = null) Parameters low long Lowest (signed) integer to be drawn from the distribution (unless high=-1, in which case this parameter is one above the highest such integer). high long If provided, one above the largest (signed) integer to be drawn from the distribution (see above for behavior if high=-1). size Shape The shape of the array. dtype Type Desired dtype of the result. All dtypes are determined by their name, i.e., ‘int64’, ‘int’, etc, so byteorder is not available and a specific precision may have different C types depending on the platform. The default value is ‘np.int’. Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html randn(params int[]) Return a sample (or samples) from the “standard normal” distribution. public NDArray randn(params int[] size) Parameters size int[] Returns NDArray randn() Scalar value public T randn() Returns T Type Parameters T random_sample(Shape) Return random floats in the half-open interval [0.0, 1.0). Results are from the “continuous uniform” distribution over the stated interval. To sample Unif[a, b), b > a multiply the output of random_sample by (b-a) and add a: public NDArray random_sample(Shape shape) Parameters shape Shape The shape to randomize Returns NDArray random_sample(params int[]) Return random floats in the half-open interval [0.0, 1.0). Results are from the “continuous uniform” distribution over the stated interval. To sample Unif[a, b), b > a multiply the output of random_sample by (b-a) and add a: public NDArray random_sample(params int[] size) Parameters size int[] The samples Returns NDArray seed(int) Seeds the generator. It can be called again to re-seed the generator. public void seed(int seed) Parameters seed int set_state(NativeRandomState) Set the internal state of the generator from a NumPyRandom. for use if one has reason to manually (re-)set the internal state of the pseudo-random number generating algorithm. public void set_state(NativeRandomState nativeRandomState) Parameters nativeRandomState NativeRandomState The state to restore onto this NumPyRandom shuffle(NDArray, int) Modify a sequence in-place by shuffling its contents. [SuppressMessage(\"ReSharper\", \"TooWideLocalVariableScope\")] public void shuffle(NDArray x, int passes = 2) Parameters x NDArray The array or list to be shuffled. passes int How many times to pass all items in a complexity of O(n*passes) Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.shuffle.html Does not copy x stardard_normal(params int[]) Draw samples from a standard Normal distribution (mean=0, stdev=1). public NDArray stardard_normal(params int[] size) Parameters size int[] Returns NDArray uniform(NDArray, NDArray, Type) Draw samples from a uniform distribution. Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform. public NDArray uniform(NDArray low, NDArray high, Type dType = null) Parameters low NDArray Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0. high NDArray Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0. dType Type The type of the output NDArray Returns NDArray uniform(double, double, Shape) Draw samples from a uniform distribution. Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform. public NDArray uniform(double low, double high, Shape shape) Parameters low double Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0. high double Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0. shape Shape Output shape. If the given shape is, e.g., m, n, k, then m * n * k samples are drawn. If size is None (default), a single value is returned if low and high are both scalars. Returns NDArray NDArray with values of type double uniform(double, double, params int[]) Draw samples from a uniform distribution. Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform. public NDArray uniform(double low, double high, params int[] size) Parameters low double Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0. high double Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0. size int[] Output shape. If the given shape is, e.g., m, n, k, then m * n * k samples are drawn. If size is None (default), a single value is returned if low and high are both scalars. Returns NDArray NDArray with values of type double" + }, + "api/NumSharp.NumSharpException.html": { + "href": "api/NumSharp.NumSharpException.html", + "title": "Class NumSharpException | NumSharp Documentation", + "summary": "Class NumSharpException Namespace NumSharp Assembly NumSharp.dll public class NumSharpException : Exception, ISerializable, INumSharpException Inheritance object Exception NumSharpException Implements ISerializable INumSharpException Derived IncorrectShapeException IncorrectSizeException IncorrectTypeException Inherited Members Exception.GetBaseException() Exception.GetType() Exception.ToString() Exception.Data Exception.HelpLink Exception.HResult Exception.InnerException Exception.Message Exception.Source Exception.StackTrace Exception.TargetSite Exception.SerializeObjectState object.Equals(object) object.Equals(object, object) object.GetHashCode() object.MemberwiseClone() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) Constructors NumSharpException() Initializes a new instance of the Exception class. public NumSharpException() NumSharpException(string) Initializes a new instance of the Exception class with a specified error message. public NumSharpException(string message) Parameters message string The message that describes the error. NumSharpException(string, Exception) Initializes a new instance of the Exception class with a specified error message and a reference to the inner exception that is the cause of this exception. public NumSharpException(string message, Exception innerException) Parameters message string The error message that explains the reason for the exception. innerException Exception The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified." + }, + "api/NumSharp.Randomizer.html": { + "href": "api/NumSharp.Randomizer.html", + "title": "Class Randomizer | NumSharp Documentation", + "summary": "Class Randomizer Namespace NumSharp Assembly NumSharp.dll Represents a pseudo-random number generator, which is a device that produces a sequence of numbers that meet certain statistical requirements for randomness. Equivalent of Random. public sealed class Randomizer : ICloneable Inheritance object Randomizer Implements ICloneable Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Remarks Copied and modified from https://referencesource.microsoft.com/#mscorlib/system/random.cs Constructors Randomizer() Initializes a new instance of the Randomizer class, using a time-dependent default seed value. public Randomizer() Randomizer(int) Initializes a new instance of the Random class, using the specified seed value. public Randomizer(int Seed) Parameters Seed int A number used to calculate a starting value for the pseudo-random number sequence. If a negative number is specified, the absolute value of the number is used. Methods Clone() Creates a new object that is a copy of the current instance. public Randomizer Clone() Returns Randomizer A new object that is a copy of this instance. Deserialize(byte[]) public static Randomizer Deserialize(byte[] bytes) Parameters bytes byte[] Returns Randomizer Next() Returns a non-negative random integer. public int Next() Returns int A 32-bit signed integer that is greater than or equal to 0 and less than MaxValue. Next(int) Returns a non-negative random integer that is less than the specified maximum. public int Next(int maxValue) Parameters maxValue int The exclusive upper bound of the random number to be generated. maxValue must be greater than or equal to 0. Returns int A 32-bit signed integer that is greater than or equal to 0, and less than maxValue; that is, the range of return values ordinarily includes 0 but not maxValue. However, if maxValue equals 0, maxValue is returned. Exceptions ArgumentOutOfRangeException maxValue is less than 0. Next(int, int) Returns a random integer that is within a specified range. public int Next(int minValue, int maxValue) Parameters minValue int The inclusive lower bound of the random number returned. maxValue int The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue. Returns int A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned. Exceptions ArgumentOutOfRangeException minValue is greater than maxValue. NextBytes(byte[]) Fills the elements of a specified array of bytes with random numbers. public void NextBytes(byte[] buffer) Parameters buffer byte[] An array of bytes to contain random numbers. Exceptions ArgumentNullException buffer is null. NextDouble() Returns a random floating-point number that is greater than or equal to 0.0, and less than 1.0. public double NextDouble() Returns double A double-precision floating point number that is greater than or equal to 0.0, and less than 1.0. NextLong() Returns a non-negative random integer that is less than the specified maximum. public long NextLong() Returns long A 32-bit signed integer that is greater than or equal to 0, and less than maxValue; that is, the range of return values ordinarily includes 0 but not maxValue. However, if maxValue equals 0, maxValue is returned. Exceptions ArgumentOutOfRangeException maxValue is less than 0. NextLong(long) Returns a non-negative random integer that is less than the specified maximum. public long NextLong(long maxValue) Parameters maxValue long The exclusive upper bound of the random number to be generated. maxValue must be greater than or equal to 0. Returns long A 32-bit signed integer that is greater than or equal to 0, and less than maxValue; that is, the range of return values ordinarily includes 0 but not maxValue. However, if maxValue equals 0, maxValue is returned. Exceptions ArgumentOutOfRangeException maxValue is less than 0. NextLong(long, long) Returns a random integer that is within a specified range. public long NextLong(long minValue, long maxValue) Parameters minValue long The inclusive lower bound of the random number returned. maxValue long The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue. Returns long A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned. Exceptions ArgumentOutOfRangeException minValue is greater than maxValue. Sample() Returns a random floating-point number between 0.0 and 1.0. protected double Sample() Returns double A double-precision floating point number that is greater than or equal to 0.0, and less than 1.0. Serialize() public byte[] Serialize() Returns byte[]" + }, + "api/NumSharp.Shape.html": { + "href": "api/NumSharp.Shape.html", + "title": "Struct Shape | NumSharp Documentation", + "summary": "Struct Shape Namespace NumSharp Assembly NumSharp.dll Represents a shape of an N-D array. public struct Shape : ICloneable, IEquatable Implements ICloneable IEquatable Inherited Members object.Equals(object, object) object.GetType() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) Remarks Handles slicing, indexing based on coordinates or linear offset and broadcastted indexing. Constructors Shape(Shape) public Shape(Shape other) Parameters other Shape Shape(params int[]) public Shape(params int[] dims) Parameters dims int[] Shape(int[], int[]) public Shape(int[] dims, int[] strides) Parameters dims int[] strides int[] Shape(int[], int[], Shape) public Shape(int[] dims, int[] strides, Shape originalShape) Parameters dims int[] strides int[] originalShape Shape Fields IsScalar public bool IsScalar Field Value bool ModifiedStrides Does this Shape have modified strides, usually in scenarios like np.transpose. public bool ModifiedStrides Field Value bool Scalar Singleton instance of a Shape that represents a scalar. public static readonly Shape Scalar Field Value Shape Properties Dimensions public readonly int[] Dimensions { get; } Property Value int[] IsBroadcasted Is this shape a broadcast and/or has modified strides? public readonly bool IsBroadcasted { get; } Property Value bool IsContiguous Does this Shape represents a non-sliced and non-broadcasted hence contagious unmanaged memory? public readonly bool IsContiguous { get; } Property Value bool IsEmpty True if the shape is not initialized. Note: A scalar shape is not empty. public readonly bool IsEmpty { get; } Property Value bool IsRecursive Is this Shape a recusive view? (deeper than 1 view) public readonly bool IsRecursive { get; } Property Value bool IsSliced True if the shape of this array was obtained by a slicing operation that caused the underlying data to be non-contiguous public readonly bool IsSliced { get; } Property Value bool this[int] public readonly int this[int dim] { get; set; } Parameters dim int Property Value int NDim public readonly int NDim { get; } Property Value int Order public readonly char Order { get; } Property Value char Size The linear size of this shape. public readonly int Size { get; } Property Value int Strides public readonly int[] Strides { get; } Property Value int[] Methods ChangeTensorLayout(char) public void ChangeTensorLayout(char order = 'C') Parameters order char Clean() Returns a clean shape based on this. Cleans ViewInfo and returns a newly constructed. public readonly Shape Clean() Returns Shape Clone(bool, bool, bool) Creates a complete copy of this Shape. public readonly Shape Clone(bool deep = true, bool unview = false, bool unbroadcast = false) Parameters deep bool Should make a complete deep clone or a shallow if false. unview bool unbroadcast bool Returns Shape Deconstruct(out int, out int) public readonly void Deconstruct(out int dim1, out int dim2) Parameters dim1 int dim2 int Deconstruct(out int, out int, out int) public readonly void Deconstruct(out int dim1, out int dim2, out int dim3) Parameters dim1 int dim2 int dim3 int Deconstruct(out int, out int, out int, out int) public readonly void Deconstruct(out int dim1, out int dim2, out int dim3, out int dim4) Parameters dim1 int dim2 int dim3 int dim4 int Deconstruct(out int, out int, out int, out int, out int) public readonly void Deconstruct(out int dim1, out int dim2, out int dim3, out int dim4, out int dim5) Parameters dim1 int dim2 int dim3 int dim4 int dim5 int Deconstruct(out int, out int, out int, out int, out int, out int) public readonly void Deconstruct(out int dim1, out int dim2, out int dim3, out int dim4, out int dim5, out int dim6) Parameters dim1 int dim2 int dim3 int dim4 int dim5 int dim6 int Empty(int) An empty shape without any fields set except all are default. public static Shape Empty(int ndim) Parameters ndim int Returns Shape Remarks Used internally. Equals(Shape) Indicates whether the current object is equal to another object of the same type. public readonly bool Equals(Shape other) Parameters other Shape An object to compare with this object. Returns bool true if the current object is equal to the other parameter; otherwise, false. Equals(object) Indicates whether this instance and a specified object are equal. public override readonly bool Equals(object obj) Parameters obj object The object to compare with the current instance. Returns bool true if obj and this instance are the same type and represent the same value; otherwise, false. ExpandDimension(int) Expands a specific axis with 1 dimension. [SuppressMessage(\"ReSharper\", \"LocalVariableHidesMember\")] public readonly Shape ExpandDimension(int axis) Parameters axis int Returns Shape ExtractShape(Array) Extracts the shape of given array. public static int[] ExtractShape(Array array) Parameters array Array Returns int[] Remarks Supports both jagged and multi-dim. GetAxis(Shape, int) public static int[] GetAxis(Shape shape, int axis) Parameters shape Shape axis int Returns int[] GetAxis(ref Shape, int) public static int[] GetAxis(ref Shape shape, int axis) Parameters shape Shape axis int Returns int[] GetAxis(int[], int) public static int[] GetAxis(int[] dims, int axis) Parameters dims int[] axis int Returns int[] GetCoordinates(int) Gets coordinates in this shape from index in this shape (slicing is ignored). Example: Shape (2,3) 0 => [0, 0] 1 => [0, 1] ... 6 => [1, 2] public readonly int[] GetCoordinates(int offset) Parameters offset int the index if you would iterate from 0 to shape.size in row major order Returns int[] GetCoordinatesFromAbsoluteIndex(int) Retrievs the coordinates in current shape (potentially sliced and reshaped) from index in original array. Note: this is the inverse operation of GetOffset Example: Shape a (2,3) => sliced to b (2,2) by a[:, 1:] The absolute indices in a are: [0, 1, 2, 3, 4, 5] The absolute indices in b are: [1, 2, 4, 5] Examples: a.GetCoordinatesFromAbsoluteIndex(1) returns [0, 1] b.GetCoordinatesFromAbsoluteIndex(0) returns [0, 0] b.GetCoordinatesFromAbsoluteIndex(0) returns [] because it is out of shape public readonly int[] GetCoordinatesFromAbsoluteIndex(int offset) Parameters offset int Is the index in the original array before it was sliced and/or reshaped Returns int[] Remarks Note: due to slicing the absolute indices (offset in memory) are different from what GetCoordinates would return, which are relative indices in the shape. GetHashCode() Serves as the default hash function. public override int GetHashCode() Returns int A hash code for the current object. GetOffset(int*, int) Get offset index out of coordinate indices. public readonly int GetOffset(int* indices, int ndims) Parameters indices int* A pointer to the coordinates to turn into linear offset ndims int The number of dimensions Returns int The index in the memory block that refers to a specific value. Remarks Handles sliced indices and broadcasting GetOffset(params int[]) Get offset index out of coordinate indices. The offset is the absolute offset in memory for the given coordinates. Even for shapes that were sliced and reshaped after slicing and sliced again (and so forth) this returns the absolute memory offset. Note: the inverse operation to this is GetCoordinatesFromAbsoluteIndex public readonly int GetOffset(params int[] indices) Parameters indices int[] The coordinates to turn into linear offset Returns int The index in the memory block that refers to a specific value. Remarks Handles sliced indices and broadcasting GetSize(int[]) public static int GetSize(int[] dims) Parameters dims int[] Returns int GetSubshape(int*, int) Gets the shape based on given indicies and the index offset (C-Contiguous) inside the current storage. public readonly (Shape Shape, int Offset) GetSubshape(int* dims, int ndims) Parameters dims int* ndims int Returns (Shape Shape, int Offset) Remarks Used for slicing, returned shape is the new shape of the slice and offset is the offset from current address. GetSubshape(params int[]) Gets the shape based on given indicies and the index offset (C-Contiguous) inside the current storage. public readonly (Shape Shape, int Offset) GetSubshape(params int[] indicies) Parameters indicies int[] The selection of indexes 0 based. Returns (Shape Shape, int Offset) Remarks Used for slicing, returned shape is the new shape of the slice and offset is the offset from current address. InferNegativeCoordinates(int[], int*, int) Translates coordinates with negative indices, e.g: np.arange(9)[-1] == np.arange(9)[8] np.arange(9)[-2] == np.arange(9)[7] [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] public static void InferNegativeCoordinates(int[] dimensions, int* coords, int coordsCount) Parameters dimensions int[] The dimensions these coordinates are targeting coords int* The coordinates. coordsCount int InferNegativeCoordinates(int[], int[]) Translates coordinates with negative indices, e.g: np.arange(9)[-1] == np.arange(9)[8] np.arange(9)[-2] == np.arange(9)[7] [SuppressMessage(\"ReSharper\", \"ParameterHidesMember\")] public static int[] InferNegativeCoordinates(int[] dimensions, int[] coords) Parameters dimensions int[] The dimensions these coordinates are targeting coords int[] The coordinates. Returns int[] Coordinates without negative indices. Matrix(int, int) Create a shape that represents a matrix. public static Shape Matrix(int rows, int cols) Parameters rows int cols int Returns Shape Remarks Faster than calling Shape's constructor Reshape(Shape, bool) Changes the shape representing this storage. public readonly Shape Reshape(Shape newShape, bool @unsafe = true) Parameters newShape Shape unsafe bool When true, then guards are skipped. Returns Shape Exceptions IncorrectShapeException If shape's size mismatches current shape size. ArgumentException If newShape's size == 0 SetStridesModified(bool) Flag this shape as stride-modified. public void SetStridesModified(bool value) Parameters value bool Slice(params Slice[]) public readonly Shape Slice(params Slice[] input_slices) Parameters input_slices Slice[] Returns Shape Slice(string) public readonly Shape Slice(string slicing_notation) Parameters slicing_notation string Returns Shape ToString() Returns the fully qualified type name of this instance. public override string ToString() Returns string The fully qualified type name. TransformOffset(int) Retrieve the transformed offset if IsSliced is true, otherwise returns offset. public readonly int TransformOffset(int offset) Parameters offset int The offset within the bounds of NumSharp.Shape.size. Returns int The transformed offset. Remarks Avoid using unless it is unclear if shape is sliced or not. Vector(int) Create a shape that represents a vector. public static Shape Vector(int length) Parameters length int Returns Shape Remarks Faster than calling Shape's constructor Vector(int, ViewInfo) Create a shape that represents a vector. public static Shape Vector(int length, ViewInfo viewInfo) Parameters length int viewInfo ViewInfo Returns Shape Remarks Faster than calling Shape's constructor Operators operator ==(Shape, Shape) public static bool operator ==(Shape a, Shape b) Parameters a Shape b Shape Returns bool explicit operator int(Shape) public static explicit operator int(Shape shape) Parameters shape Shape Returns int explicit operator int[](Shape) public static explicit operator int[](Shape shape) Parameters shape Shape Returns int[] explicit operator (int, int, int, int, int, int)(Shape) public static explicit operator (int, int, int, int, int, int)(Shape shape) Parameters shape Shape Returns (int, int, int, int, int, int) explicit operator (int, int, int, int, int)(Shape) public static explicit operator (int, int, int, int, int)(Shape shape) Parameters shape Shape Returns (int, int, int, int, int) explicit operator (int, int, int, int)(Shape) public static explicit operator (int, int, int, int)(Shape shape) Parameters shape Shape Returns (int, int, int, int) explicit operator (int, int, int)(Shape) public static explicit operator (int, int, int)(Shape shape) Parameters shape Shape Returns (int, int, int) explicit operator (int, int)(Shape) public static explicit operator (int, int)(Shape shape) Parameters shape Shape Returns (int, int) explicit operator Shape(int) public static explicit operator Shape(int dim) Parameters dim int Returns Shape implicit operator Shape(int[]) public static implicit operator Shape(int[] dims) Parameters dims int[] Returns Shape implicit operator Shape((int, int, int, int, int, int)) public static implicit operator Shape((int, int, int, int, int, int) dims) Parameters dims (int, int, int, int, int, int) Returns Shape implicit operator Shape((int, int, int, int, int)) public static implicit operator Shape((int, int, int, int, int) dims) Parameters dims (int, int, int, int, int) Returns Shape implicit operator Shape((int, int, int, int)) public static implicit operator Shape((int, int, int, int) dims) Parameters dims (int, int, int, int) Returns Shape implicit operator Shape((int, int, int)) public static implicit operator Shape((int, int, int) dims) Parameters dims (int, int, int) Returns Shape implicit operator Shape((int, int)) public static implicit operator Shape((int, int) dims) Parameters dims (int, int) Returns Shape operator !=(Shape, Shape) public static bool operator !=(Shape a, Shape b) Parameters a Shape b Shape Returns bool" + }, + "api/NumSharp.Slice.html": { + "href": "api/NumSharp.Slice.html", + "title": "Class Slice | NumSharp Documentation", + "summary": "Class Slice Namespace NumSharp Assembly NumSharp.dll
NDArray can be indexed using slicing A slice is constructed by start:stop:step notation Examples: a[start:stop] # items start through stop-1 a[start:] # items start through the rest of the array a[:stop] # items from the beginning through stop-1 The key point to remember is that the :stop value represents the first value that is not in the selected slice. So, the difference between stop and start is the number of elements selected (if step is 1, the default). There is also the step value, which can be used with any of the above: a[:] # a copy of the whole array a[start:stop:step] # start through not past stop, by step The other feature is that start or stop may be a negative number, which means it counts from the end of the array instead of the beginning. So: a[-1] # last item in the array a[-2:] # last two items in the array a[:-2] # everything except the last two items Similarly, step may be a negative number: a[::- 1] # all items in the array, reversed a[1::- 1] # the first two items, reversed a[:-3:-1] # the last two items, reversed a[-3::- 1] # everything except the last two items, reversed NumSharp is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error.Sometimes you would prefer the error, so you have to be aware that this may happen. Adapted from Greg Hewgill's answer on Stackoverflow: https://stackoverflow.com/questions/509211/understanding-slice-notation Note: special IsIndex == true It will pick only a single value at Start in this dimension effectively reducing the Shape of the sliced matrix by 1 dimension. It can be used to reduce an N-dimensional array/matrix to a (N-1)-dimensional array/matrix Example: a=[[1, 2], [3, 4]] a[:, 1] returns the second column of that 2x2 matrix as a 1-D vector public class Slice : IIndex Inheritance object Slice Implements IIndex Inherited Members object.Equals(object, object) object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) Constructors Slice(int?, int?, int) ndarray can be indexed using slicing slice is constructed by start:stop:step notation public Slice(int? start = null, int? stop = null, int step = 1) Parameters start int? Start index of the slice, null means from the start of the array stop int? Stop index (first index after end of slice), null means to the end of the array step int Optional step to select every n-th element, defaults to 1 Slice(string) public Slice(string slice_notation) Parameters slice_notation string Fields All return : for this dimension public static readonly Slice All Field Value Slice Ellipsis fill up the missing dimensions with : at this point, corresponds to ... public static readonly Slice Ellipsis Field Value Slice IsEllipsis public bool IsEllipsis Field Value bool IsIndex public bool IsIndex Field Value bool IsNewAxis public bool IsNewAxis Field Value bool NewAxis insert a new dimension at this point public static readonly Slice NewAxis Field Value Slice None return 0:0 for this dimension public static readonly Slice None Field Value Slice Start public int? Start Field Value int? Step public int Step Field Value int Stop public int? Stop Field Value int? Properties Length Length of the slice. The length is not guaranteed to be known for i.e. a slice like \":\". Make sure to check Start and Stop for null before using it public int? Length { get; } Property Value int? Methods Equals(object) Determines whether the specified object is equal to the current object. public override bool Equals(object obj) Parameters obj object The object to compare with the current object. Returns bool true if the specified object is equal to the current object; otherwise, false. FormatSlices(params Slice[]) Creates Python array slice notation out of an array of Slice objects (mainly used for tests) public static string FormatSlices(params Slice[] slices) Parameters slices Slice[] Returns string GetHashCode() Serves as the default hash function. public override int GetHashCode() Returns int A hash code for the current object. GetSize() public int GetSize() Returns int Index(int) return exactly one element at this dimension and reduce the shape from n-dim to (n-1)-dim public static Slice Index(int index) Parameters index int Returns Slice ParseSlices(string) Parses Python array slice notation and returns an array of Slice objects public static Slice[] ParseSlices(string multi_slice_notation) Parameters multi_slice_notation string Returns Slice[] ToSliceDef(int) Converts the user Slice into an internal SliceDef which is easier to calculate with public SliceDef ToSliceDef(int dim) Parameters dim int Returns SliceDef ToString() Returns a string that represents the current object. public override string ToString() Returns string A string that represents the current object. Operators operator --(Slice) public static Slice operator --(Slice a) Parameters a Slice Returns Slice operator ==(Slice, Slice) public static bool operator ==(Slice a, Slice b) Parameters a Slice b Slice Returns bool implicit operator Slice(int) public static implicit operator Slice(int index) Parameters index int Returns Slice implicit operator Slice(string) public static implicit operator Slice(string slice) Parameters slice string Returns Slice operator ++(Slice) public static Slice operator ++(Slice a) Parameters a Slice Returns Slice operator !=(Slice, Slice) public static bool operator !=(Slice a, Slice b) Parameters a Slice b Slice Returns bool" + }, + "api/NumSharp.SliceDef.html": { + "href": "api/NumSharp.SliceDef.html", + "title": "Struct SliceDef | NumSharp Documentation", + "summary": "Struct SliceDef Namespace NumSharp Assembly NumSharp.dll public struct SliceDef Inherited Members ValueType.Equals(object) ValueType.GetHashCode() object.Equals(object, object) object.GetType() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) Constructors SliceDef(int) public SliceDef(int idx) Parameters idx int SliceDef(int, int, int) public SliceDef(int start, int step, int count) Parameters start int step int count int SliceDef(string) (Start>>Step*Count) public SliceDef(string def) Parameters def string Fields Count public int Count Field Value int Start public int Start Field Value int Step public int Step Field Value int Properties IsIndex public bool IsIndex { get; } Property Value bool Methods Invert() reverts the order of the slice sequence public SliceDef Invert() Returns SliceDef Merge(SliceDef) Merge calculates the resulting one-time slice on the original data if it is sliced repeatedly public SliceDef Merge(SliceDef other) Parameters other SliceDef Returns SliceDef ToString() Returns the fully qualified type name of this instance. public override string ToString() Returns string The fully qualified type name." + }, + "api/NumSharp.StorageType.html": { + "href": "api/NumSharp.StorageType.html", + "title": "Enum StorageType | NumSharp Documentation", + "summary": "Enum StorageType Namespace NumSharp Assembly NumSharp.dll public enum StorageType Extension Methods LinqExtensions.Yield(T) Fields Unmanaged = 0 UnmanagedByteStorage TypedArray = 1 TypedArrayStorage" + }, + "api/NumSharp.TensorEngine.html": { + "href": "api/NumSharp.TensorEngine.html", + "title": "Class TensorEngine | NumSharp Documentation", + "summary": "Class TensorEngine Namespace NumSharp Assembly NumSharp.dll public abstract class TensorEngine Inheritance object TensorEngine Derived DefaultEngine Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Methods ACos(in NDArray, NPTypeCode?) public abstract NDArray ACos(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray ACos(in NDArray, Type) public abstract NDArray ACos(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray AMax(in NDArray, int, Type, bool) public abstract NDArray AMax(in NDArray nd, int axis, Type dtype, bool keepdims = false) Parameters nd NDArray axis int dtype Type keepdims bool Returns NDArray AMax(in NDArray, int?, NPTypeCode?, bool) public abstract NDArray AMax(in NDArray nd, int? axis = null, NPTypeCode? typeCode = null, bool keepdims = false) Parameters nd NDArray axis int? typeCode NPTypeCode? keepdims bool Returns NDArray AMin(in NDArray, int, Type, bool) public abstract NDArray AMin(in NDArray nd, int axis, Type dtype, bool keepdims = false) Parameters nd NDArray axis int dtype Type keepdims bool Returns NDArray AMin(in NDArray, int?, NPTypeCode?, bool) public abstract NDArray AMin(in NDArray nd, int? axis = null, NPTypeCode? typeCode = null, bool keepdims = false) Parameters nd NDArray axis int? typeCode NPTypeCode? keepdims bool Returns NDArray ASin(in NDArray, NPTypeCode?) public abstract NDArray ASin(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray ASin(in NDArray, Type) public abstract NDArray ASin(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray ATan(in NDArray, NPTypeCode?) public abstract NDArray ATan(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray ATan(in NDArray, Type) public abstract NDArray ATan(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray ATan2(in NDArray, in NDArray, NPTypeCode?) public abstract NDArray ATan2(in NDArray y, in NDArray x, NPTypeCode? typeCode = null) Parameters y NDArray x NDArray typeCode NPTypeCode? Returns NDArray ATan2(in NDArray, in NDArray, Type) public abstract NDArray ATan2(in NDArray y, in NDArray x, Type dtype) Parameters y NDArray x NDArray dtype Type Returns NDArray Abs(in NDArray, NPTypeCode?) public abstract NDArray Abs(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Abs(in NDArray, Type) public abstract NDArray Abs(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Add(in NDArray, in NDArray) public abstract NDArray Add(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray All(NDArray) public abstract bool All(NDArray nd) Parameters nd NDArray Returns bool All(NDArray, int) public abstract NDArray All(NDArray nd, int axis) Parameters nd NDArray axis int Returns NDArray AllClose(NDArray, NDArray, double, double, bool) public abstract bool AllClose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false) Parameters a NDArray b NDArray rtol double atol double equal_nan bool Returns bool ArgMax(in NDArray) public abstract NDArray ArgMax(in NDArray a) Parameters a NDArray Returns NDArray ArgMax(in NDArray, int) public abstract NDArray ArgMax(in NDArray a, int axis) Parameters a NDArray axis int Returns NDArray ArgMin(in NDArray) public abstract NDArray ArgMin(in NDArray a) Parameters a NDArray Returns NDArray ArgMin(in NDArray, int) public abstract NDArray ArgMin(in NDArray a, int axis) Parameters a NDArray axis int Returns NDArray Cast(NDArray, NPTypeCode, bool) public abstract NDArray Cast(NDArray x, NPTypeCode dtype, bool copy) Parameters x NDArray dtype NPTypeCode copy bool Returns NDArray Cast(NDArray, Type, bool) public abstract NDArray Cast(NDArray x, Type dtype, bool copy) Parameters x NDArray dtype Type copy bool Returns NDArray Ceil(in NDArray, NPTypeCode?) public abstract NDArray Ceil(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Ceil(in NDArray, Type) public abstract NDArray Ceil(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Clip(in NDArray, in ValueType, in ValueType, NPTypeCode?) public abstract NDArray Clip(in NDArray lhs, in ValueType min, in ValueType max, NPTypeCode? typeCode = null) Parameters lhs NDArray min ValueType max ValueType typeCode NPTypeCode? Returns NDArray Clip(in NDArray, in ValueType, in ValueType, Type) public abstract NDArray Clip(in NDArray lhs, in ValueType min, in ValueType max, Type dtype) Parameters lhs NDArray min ValueType max ValueType dtype Type Returns NDArray ClipNDArray(in NDArray, in NDArray, in NDArray, NPTypeCode?, NDArray) public abstract NDArray ClipNDArray(in NDArray lhs, in NDArray min, in NDArray max, NPTypeCode? typeCode = null, NDArray @out = null) Parameters lhs NDArray min NDArray max NDArray typeCode NPTypeCode? out NDArray Returns NDArray ClipNDArray(in NDArray, in NDArray, in NDArray, Type, NDArray) public abstract NDArray ClipNDArray(in NDArray lhs, in NDArray min, in NDArray max, Type dtype, NDArray @out = null) Parameters lhs NDArray min NDArray max NDArray dtype Type out NDArray Returns NDArray Compare(in NDArray, in NDArray) public abstract NDArray Compare(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray Cos(in NDArray, NPTypeCode?) public abstract NDArray Cos(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Cos(in NDArray, Type) public abstract NDArray Cos(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Cosh(in NDArray, NPTypeCode?) public abstract NDArray Cosh(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Cosh(in NDArray, Type) public abstract NDArray Cosh(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray CreateNDArray(Shape, Type, IArraySlice, char) public abstract NDArray CreateNDArray(Shape shape, Type dtype = null, IArraySlice buffer = null, char order = 'C') Parameters shape Shape dtype Type buffer IArraySlice order char Returns NDArray CreateNDArray(Shape, Type, Array, char) public abstract NDArray CreateNDArray(Shape shape, Type dtype = null, Array buffer = null, char order = 'C') Parameters shape Shape dtype Type buffer Array order char Returns NDArray Divide(in NDArray, in NDArray) public abstract NDArray Divide(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray Dot(in NDArray, in NDArray) public abstract NDArray Dot(in NDArray x, in NDArray y) Parameters x NDArray y NDArray Returns NDArray Exp(in NDArray, NPTypeCode?) public abstract NDArray Exp(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Exp(in NDArray, Type) public abstract NDArray Exp(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Exp2(in NDArray, NPTypeCode?) public abstract NDArray Exp2(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Exp2(in NDArray, Type) public abstract NDArray Exp2(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Expm1(in NDArray, NPTypeCode?) public abstract NDArray Expm1(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Expm1(in NDArray, Type) public abstract NDArray Expm1(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Floor(in NDArray, NPTypeCode?) public abstract NDArray Floor(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Floor(in NDArray, Type) public abstract NDArray Floor(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray GetStorage(NPTypeCode) Get storage for given typeCode. public abstract UnmanagedStorage GetStorage(NPTypeCode typeCode) Parameters typeCode NPTypeCode Returns UnmanagedStorage GetStorage(Type) Get storage for given dtype. public abstract UnmanagedStorage GetStorage(Type dtype) Parameters dtype Type Returns UnmanagedStorage IsClose(NDArray, NDArray, double, double, bool) public abstract NDArray IsClose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false) Parameters a NDArray b NDArray rtol double atol double equal_nan bool Returns NDArray IsFinite(NDArray) public abstract NDArray IsFinite(NDArray a) Parameters a NDArray Returns NDArray IsNan(NDArray) public abstract NDArray IsNan(NDArray a) Parameters a NDArray Returns NDArray Log(in NDArray, NPTypeCode?) public abstract NDArray Log(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Log(in NDArray, Type) public abstract NDArray Log(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Log10(in NDArray, NPTypeCode?) public abstract NDArray Log10(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Log10(in NDArray, Type) public abstract NDArray Log10(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Log1p(in NDArray, NPTypeCode?) public abstract NDArray Log1p(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Log1p(in NDArray, Type) public abstract NDArray Log1p(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Log2(in NDArray, NPTypeCode?) public abstract NDArray Log2(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Log2(in NDArray, Type) public abstract NDArray Log2(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Matmul(NDArray, NDArray) public abstract NDArray Matmul(NDArray lhs, NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray Mean(in NDArray, int, Type, bool) public abstract NDArray Mean(in NDArray nd, int axis, Type dtype, bool keepdims = false) Parameters nd NDArray axis int dtype Type keepdims bool Returns NDArray Mean(in NDArray, int?, NPTypeCode?, bool) public abstract NDArray Mean(in NDArray nd, int? axis = null, NPTypeCode? typeCode = null, bool keepdims = false) Parameters nd NDArray axis int? typeCode NPTypeCode? keepdims bool Returns NDArray Mod(in NDArray, in NDArray) public abstract NDArray Mod(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray ModF(in NDArray, NPTypeCode?) public abstract (NDArray Fractional, NDArray Intergral) ModF(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns (NDArray Lhs, NDArray Rhs) ModF(in NDArray, Type) public abstract (NDArray Fractional, NDArray Intergral) ModF(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns (NDArray Lhs, NDArray Rhs) MoveAxis(in NDArray, int[], int[]) public abstract NDArray MoveAxis(in NDArray nd, int[] source, int[] destinition) Parameters nd NDArray source int[] destinition int[] Returns NDArray Multiply(NDArray, NDArray) public abstract NDArray Multiply(NDArray lhs, NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray Negate(in NDArray) public abstract NDArray Negate(in NDArray nd) Parameters nd NDArray Returns NDArray NonZero(in NDArray) public abstract NDArray[] NonZero(in NDArray a) Parameters a NDArray Returns NDArray[] Power(in NDArray, in ValueType, NPTypeCode?) public abstract NDArray Power(in NDArray lhs, in ValueType rhs, NPTypeCode? typeCode = null) Parameters lhs NDArray rhs ValueType typeCode NPTypeCode? Returns NDArray Power(in NDArray, in ValueType, Type) public abstract NDArray Power(in NDArray lhs, in ValueType rhs, Type type) Parameters lhs NDArray rhs ValueType type Type Returns NDArray ReduceAMax(NDArray, int?, bool, NPTypeCode?) public abstract NDArray ReduceAMax(NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null) Parameters arr NDArray axis_ int? keepdims bool typeCode NPTypeCode? Returns NDArray ReduceAMin(NDArray, int?, bool, NPTypeCode?) public abstract NDArray ReduceAMin(NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null) Parameters arr NDArray axis_ int? keepdims bool typeCode NPTypeCode? Returns NDArray ReduceAdd(in NDArray, int?, bool, NPTypeCode?, NDArray) public abstract NDArray ReduceAdd(in NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null, NDArray @out = null) Parameters arr NDArray axis_ int? keepdims bool typeCode NPTypeCode? out NDArray Returns NDArray ReduceArgMax(NDArray, int?) public abstract NDArray ReduceArgMax(NDArray arr, int? axis_) Parameters arr NDArray axis_ int? Returns NDArray ReduceArgMin(NDArray, int?) public abstract NDArray ReduceArgMin(NDArray arr, int? axis_) Parameters arr NDArray axis_ int? Returns NDArray ReduceCumAdd(in NDArray, int?, NPTypeCode?) public abstract NDArray ReduceCumAdd(in NDArray arr, int? axis_, NPTypeCode? typeCode = null) Parameters arr NDArray axis_ int? typeCode NPTypeCode? Returns NDArray ReduceMean(in NDArray, int?, bool, NPTypeCode?) public abstract NDArray ReduceMean(in NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null) Parameters arr NDArray axis_ int? keepdims bool typeCode NPTypeCode? Returns NDArray ReduceProduct(NDArray, int?, bool, NPTypeCode?) public abstract NDArray ReduceProduct(NDArray arr, int? axis_, bool keepdims = false, NPTypeCode? typeCode = null) Parameters arr NDArray axis_ int? keepdims bool typeCode NPTypeCode? Returns NDArray ReduceStd(NDArray, int?, bool, int?, NPTypeCode?) public abstract NDArray ReduceStd(NDArray arr, int? axis_, bool keepdims = false, int? ddof = null, NPTypeCode? typeCode = null) Parameters arr NDArray axis_ int? keepdims bool ddof int? typeCode NPTypeCode? Returns NDArray ReduceVar(NDArray, int?, bool, int?, NPTypeCode?) public abstract NDArray ReduceVar(NDArray arr, int? axis_, bool keepdims = false, int? ddof = null, NPTypeCode? typeCode = null) Parameters arr NDArray axis_ int? keepdims bool ddof int? typeCode NPTypeCode? Returns NDArray RollAxis(in NDArray, int, int) public abstract NDArray RollAxis(in NDArray nd, int axis, int start = 0) Parameters nd NDArray axis int start int Returns NDArray Round(in NDArray, int, NPTypeCode?) public abstract NDArray Round(in NDArray nd, int decimals, NPTypeCode? typeCode = null) Parameters nd NDArray decimals int typeCode NPTypeCode? Returns NDArray Round(in NDArray, int, Type) public abstract NDArray Round(in NDArray nd, int decimals, Type dtype) Parameters nd NDArray decimals int dtype Type Returns NDArray Round(in NDArray, NPTypeCode?) public abstract NDArray Round(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Round(in NDArray, Type) public abstract NDArray Round(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Sign(in NDArray, NPTypeCode?) public abstract NDArray Sign(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Sign(in NDArray, Type) public abstract NDArray Sign(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Sin(in NDArray, NPTypeCode?) public abstract NDArray Sin(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Sin(in NDArray, Type) public abstract NDArray Sin(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Sinh(in NDArray, NPTypeCode?) public abstract NDArray Sinh(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Sinh(in NDArray, Type) public abstract NDArray Sinh(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Sqrt(in NDArray, NPTypeCode?) public abstract NDArray Sqrt(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Sqrt(in NDArray, Type) public abstract NDArray Sqrt(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Subtract(in NDArray, in NDArray) public abstract NDArray Subtract(in NDArray lhs, in NDArray rhs) Parameters lhs NDArray rhs NDArray Returns NDArray Sum(in NDArray, int, Type, bool) public abstract NDArray Sum(in NDArray nd, int axis, Type dtype, bool keepdims = false) Parameters nd NDArray axis int dtype Type keepdims bool Returns NDArray Sum(in NDArray, int?, NPTypeCode?, bool) public abstract NDArray Sum(in NDArray nd, int? axis = null, NPTypeCode? typeCode = null, bool keepdims = false) Parameters nd NDArray axis int? typeCode NPTypeCode? keepdims bool Returns NDArray SwapAxes(in NDArray, int, int) public abstract NDArray SwapAxes(in NDArray nd, int axis1, int axis2) Parameters nd NDArray axis1 int axis2 int Returns NDArray Tan(in NDArray, NPTypeCode?) public abstract NDArray Tan(in NDArray nd, NPTypeCode? typeCod = null) Parameters nd NDArray typeCod NPTypeCode? Returns NDArray Tan(in NDArray, Type) public abstract NDArray Tan(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Tanh(in NDArray, NPTypeCode?) public abstract NDArray Tanh(in NDArray nd, NPTypeCode? typeCode = null) Parameters nd NDArray typeCode NPTypeCode? Returns NDArray Tanh(in NDArray, Type) public abstract NDArray Tanh(in NDArray nd, Type dtype) Parameters nd NDArray dtype Type Returns NDArray Transpose(in NDArray, int[]) public abstract NDArray Transpose(in NDArray nd, int[] premute = null) Parameters nd NDArray premute int[] Returns NDArray" + }, + "api/NumSharp.Unmanaged.Memory.ScalarMemoryPool.html": { + "href": "api/NumSharp.Unmanaged.Memory.ScalarMemoryPool.html", + "title": "Class ScalarMemoryPool | NumSharp Documentation", + "summary": "Class ScalarMemoryPool Namespace NumSharp.Unmanaged.Memory Assembly NumSharp.dll public class ScalarMemoryPool Inheritance object ScalarMemoryPool Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Fields Instance public static readonly StackedMemoryPool Instance Field Value StackedMemoryPool" + }, + "api/NumSharp.Unmanaged.Memory.StackedMemoryPool.html": { + "href": "api/NumSharp.Unmanaged.Memory.StackedMemoryPool.html", + "title": "Class StackedMemoryPool | NumSharp Documentation", + "summary": "Class StackedMemoryPool Namespace NumSharp.Unmanaged.Memory Assembly NumSharp.dll Pool of allocated buffers managed by internal garbage collection mechanism. public class StackedMemoryPool : IDisposable Inheritance object StackedMemoryPool Implements IDisposable Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Remarks Used to speed up scalar allocation. Thread-safe. Constructors StackedMemoryPool(int) public StackedMemoryPool(int totalSize) Parameters totalSize int StackedMemoryPool(int, int) public StackedMemoryPool(int singleSize, int count) Parameters singleSize int count int Fields GarbageCollectionDelay After how many milliseconds should unused excess memory be deallocated. (only if allocated exceeded above 133% of firstly allocated). Default: 5000ms. public int GarbageCollectionDelay Field Value int SingleSize public readonly int SingleSize Field Value int Properties Available How many pointers are currently preallocated and available for the taking. public long Available { get; } Property Value long TotalAllocated How many Scalar pointers are allocated. public long TotalAllocated { get; } Property Value long Methods AllocateBytes(long) public void AllocateBytes(long bytes) Parameters bytes long AllocateCount(long) public void AllocateCount(long count) Parameters count long Dispose() Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. public void Dispose() ~StackedMemoryPool() protected ~StackedMemoryPool() Return(nint) public void Return(nint x) Parameters x nint Take() public nint Take() Returns nint TrimExcess() public void TrimExcess() UpdateGarbageCollectionThreshold() Set the point of GC activation to the current TotalAllocated multiplied by 1.33. public void UpdateGarbageCollectionThreshold()" + }, + "api/NumSharp.Unmanaged.Memory.html": { + "href": "api/NumSharp.Unmanaged.Memory.html", + "title": "Namespace NumSharp.Unmanaged.Memory | NumSharp Documentation", + "summary": "Namespace NumSharp.Unmanaged.Memory Classes ScalarMemoryPool StackedMemoryPool Pool of allocated buffers managed by internal garbage collection mechanism." + }, + "api/NumSharp.Utilities.ArrayConvert.html": { + "href": "api/NumSharp.Utilities.ArrayConvert.html", + "title": "Class ArrayConvert | NumSharp Documentation", + "summary": "Class ArrayConvert Namespace NumSharp.Utilities Assembly NumSharp.dll Presents all possible combinations of array conversion of types supported by numpy. public static class ArrayConvert Inheritance object ArrayConvert Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Remarks Implementation is based on Array.ConvertAll from corefx source at https://github.com/dotnet/corefx/blob/b2097cbdcb26f7f317252334ddcce101a20b7f3d/src/Common/src/CoreLib/System/Array.cs#L586 Methods Clone(Array) Creates a clone of given sourceArray. public static Array Clone(Array sourceArray) Parameters sourceArray Array The array to clone Returns Array Remarks If possible, for performance reasons use generic version of this method. Clone(T[,,,]) Creates a clone of given sourceArray using CopyTo(Array, int). public static T[,,,] Clone(T[,,,] sourceArray) Parameters sourceArray T[,,,] The array to clone Returns T[,,,] Type Parameters T Clone(T[,,]) Creates a clone of given sourceArray using CopyTo(Array, int). public static T[,,] Clone(T[,,] sourceArray) Parameters sourceArray T[,,] The array to clone Returns T[,,] Type Parameters T Clone(T[,]) Creates a clone of given sourceArray using CopyTo(Array, int). public static T[,] Clone(T[,] sourceArray) Parameters sourceArray T[,] The array to clone Returns T[,] Type Parameters T Clone(T[]) Creates a clone of given sourceArray. public static T[] Clone(T[] sourceArray) Parameters sourceArray T[] The array to clone Returns T[] Type Parameters T To(Array, NPTypeCode) Converts sourceArray to an array of type typeCode. public static Array To(Array sourceArray, NPTypeCode typeCode) Parameters sourceArray Array The array to convert typeCode NPTypeCode The type to convert the data to Returns Array Remarks If sourceArray's element type equals to typeCode then a copy is returned To(Array, Type) Converts sourceArray to an array of type returnType. public static Array To(Array sourceArray, Type returnType) Parameters sourceArray Array The array to convert returnType Type The type to convert the data to Returns Array Remarks If sourceArray's element type equals to returnType then a copy is returned ToBoolean(Array) public static bool[] ToBoolean(Array sourceArray) Parameters sourceArray Array Returns bool[] ToBoolean(bool[]) Converts bool array to a bool array. public static bool[] ToBoolean(bool[] sourceArray) Parameters sourceArray bool[] The array to convert Returns bool[] Converted array of type Boolean Remarks Based on benchmark ArrayCopying ToBoolean(byte[]) Converts byte array to a bool array. public static bool[] ToBoolean(byte[] sourceArray) Parameters sourceArray byte[] The array to convert Returns bool[] Converted array of type Boolean ToBoolean(char[]) Converts char array to a bool array. public static bool[] ToBoolean(char[] sourceArray) Parameters sourceArray char[] The array to convert Returns bool[] Converted array of type Boolean ToBoolean(decimal[]) Converts decimal array to a bool array. public static bool[] ToBoolean(decimal[] sourceArray) Parameters sourceArray decimal[] The array to convert Returns bool[] Converted array of type Boolean ToBoolean(double[]) Converts double array to a bool array. public static bool[] ToBoolean(double[] sourceArray) Parameters sourceArray double[] The array to convert Returns bool[] Converted array of type Boolean ToBoolean(short[]) Converts short array to a bool array. public static bool[] ToBoolean(short[] sourceArray) Parameters sourceArray short[] The array to convert Returns bool[] Converted array of type Boolean ToBoolean(int[]) Converts int array to a bool array. public static bool[] ToBoolean(int[] sourceArray) Parameters sourceArray int[] The array to convert Returns bool[] Converted array of type Boolean ToBoolean(long[]) Converts long array to a bool array. public static bool[] ToBoolean(long[] sourceArray) Parameters sourceArray long[] The array to convert Returns bool[] Converted array of type Boolean ToBoolean(float[]) Converts float array to a bool array. public static bool[] ToBoolean(float[] sourceArray) Parameters sourceArray float[] The array to convert Returns bool[] Converted array of type Boolean ToBoolean(string[]) Converts string array to a bool array. public static bool[] ToBoolean(string[] sourceArray) Parameters sourceArray string[] The array to convert Returns bool[] Converted array of type Boolean ToBoolean(ushort[]) Converts ushort array to a bool array. public static bool[] ToBoolean(ushort[] sourceArray) Parameters sourceArray ushort[] The array to convert Returns bool[] Converted array of type Boolean ToBoolean(uint[]) Converts uint array to a bool array. public static bool[] ToBoolean(uint[] sourceArray) Parameters sourceArray uint[] The array to convert Returns bool[] Converted array of type Boolean ToBoolean(ulong[]) Converts ulong array to a bool array. public static bool[] ToBoolean(ulong[] sourceArray) Parameters sourceArray ulong[] The array to convert Returns bool[] Converted array of type Boolean ToByte(Array) public static byte[] ToByte(Array sourceArray) Parameters sourceArray Array Returns byte[] ToByte(bool[]) Converts bool array to a byte array. public static byte[] ToByte(bool[] sourceArray) Parameters sourceArray bool[] The array to convert Returns byte[] Converted array of type Byte ToByte(byte[]) Converts byte array to a byte array. public static byte[] ToByte(byte[] sourceArray) Parameters sourceArray byte[] The array to convert Returns byte[] Converted array of type Byte Remarks Based on benchmark ArrayCopying ToByte(char[]) Converts char array to a byte array. public static byte[] ToByte(char[] sourceArray) Parameters sourceArray char[] The array to convert Returns byte[] Converted array of type Byte ToByte(decimal[]) Converts decimal array to a byte array. public static byte[] ToByte(decimal[] sourceArray) Parameters sourceArray decimal[] The array to convert Returns byte[] Converted array of type Byte ToByte(double[]) Converts double array to a byte array. public static byte[] ToByte(double[] sourceArray) Parameters sourceArray double[] The array to convert Returns byte[] Converted array of type Byte ToByte(short[]) Converts short array to a byte array. public static byte[] ToByte(short[] sourceArray) Parameters sourceArray short[] The array to convert Returns byte[] Converted array of type Byte ToByte(int[]) Converts int array to a byte array. public static byte[] ToByte(int[] sourceArray) Parameters sourceArray int[] The array to convert Returns byte[] Converted array of type Byte ToByte(long[]) Converts long array to a byte array. public static byte[] ToByte(long[] sourceArray) Parameters sourceArray long[] The array to convert Returns byte[] Converted array of type Byte ToByte(float[]) Converts float array to a byte array. public static byte[] ToByte(float[] sourceArray) Parameters sourceArray float[] The array to convert Returns byte[] Converted array of type Byte ToByte(string[]) Converts string array to a byte array. public static byte[] ToByte(string[] sourceArray) Parameters sourceArray string[] The array to convert Returns byte[] Converted array of type Byte ToByte(ushort[]) Converts ushort array to a byte array. public static byte[] ToByte(ushort[] sourceArray) Parameters sourceArray ushort[] The array to convert Returns byte[] Converted array of type Byte ToByte(uint[]) Converts uint array to a byte array. public static byte[] ToByte(uint[] sourceArray) Parameters sourceArray uint[] The array to convert Returns byte[] Converted array of type Byte ToByte(ulong[]) Converts ulong array to a byte array. public static byte[] ToByte(ulong[] sourceArray) Parameters sourceArray ulong[] The array to convert Returns byte[] Converted array of type Byte ToChar(Array) public static char[] ToChar(Array sourceArray) Parameters sourceArray Array Returns char[] ToChar(bool[]) Converts bool array to a char array. public static char[] ToChar(bool[] sourceArray) Parameters sourceArray bool[] The array to convert Returns char[] Converted array of type Char ToChar(byte[]) Converts byte array to a char array. public static char[] ToChar(byte[] sourceArray) Parameters sourceArray byte[] The array to convert Returns char[] Converted array of type Char ToChar(char[]) Converts char array to a char array. public static char[] ToChar(char[] sourceArray) Parameters sourceArray char[] The array to convert Returns char[] Converted array of type Char Remarks Based on benchmark ArrayCopying ToChar(decimal[]) Converts decimal array to a char array. public static char[] ToChar(decimal[] sourceArray) Parameters sourceArray decimal[] The array to convert Returns char[] Converted array of type Char ToChar(double[]) Converts double array to a char array. public static char[] ToChar(double[] sourceArray) Parameters sourceArray double[] The array to convert Returns char[] Converted array of type Char ToChar(short[]) Converts short array to a char array. public static char[] ToChar(short[] sourceArray) Parameters sourceArray short[] The array to convert Returns char[] Converted array of type Char ToChar(int[]) Converts int array to a char array. public static char[] ToChar(int[] sourceArray) Parameters sourceArray int[] The array to convert Returns char[] Converted array of type Char ToChar(long[]) Converts long array to a char array. public static char[] ToChar(long[] sourceArray) Parameters sourceArray long[] The array to convert Returns char[] Converted array of type Char ToChar(float[]) Converts float array to a char array. public static char[] ToChar(float[] sourceArray) Parameters sourceArray float[] The array to convert Returns char[] Converted array of type Char ToChar(string[]) Converts string array to a char array. public static char[] ToChar(string[] sourceArray) Parameters sourceArray string[] The array to convert Returns char[] Converted array of type Char ToChar(ushort[]) Converts ushort array to a char array. public static char[] ToChar(ushort[] sourceArray) Parameters sourceArray ushort[] The array to convert Returns char[] Converted array of type Char ToChar(uint[]) Converts uint array to a char array. public static char[] ToChar(uint[] sourceArray) Parameters sourceArray uint[] The array to convert Returns char[] Converted array of type Char ToChar(ulong[]) Converts ulong array to a char array. public static char[] ToChar(ulong[] sourceArray) Parameters sourceArray ulong[] The array to convert Returns char[] Converted array of type Char ToComplex(Array) public static Complex[] ToComplex(Array sourceArray) Parameters sourceArray Array Returns Complex[] ToComplex(bool[]) Converts bool array to a Complex array. public static Complex[] ToComplex(bool[] sourceArray) Parameters sourceArray bool[] The array to convert Returns Complex[] Converted array of type Complex ToComplex(byte[]) Converts byte array to a Complex array. public static Complex[] ToComplex(byte[] sourceArray) Parameters sourceArray byte[] The array to convert Returns Complex[] Converted array of type Complex ToComplex(char[]) Converts char array to a Complex array. public static Complex[] ToComplex(char[] sourceArray) Parameters sourceArray char[] The array to convert Returns Complex[] Converted array of type Complex ToComplex(decimal[]) Converts decimal array to a Complex array. public static Complex[] ToComplex(decimal[] sourceArray) Parameters sourceArray decimal[] The array to convert Returns Complex[] Converted array of type Complex ToComplex(double[]) Converts double array to a Complex array. public static Complex[] ToComplex(double[] sourceArray) Parameters sourceArray double[] The array to convert Returns Complex[] Converted array of type Complex ToComplex(short[]) Converts short array to a Complex array. public static Complex[] ToComplex(short[] sourceArray) Parameters sourceArray short[] The array to convert Returns Complex[] Converted array of type Complex ToComplex(int[]) Converts int array to a Complex array. public static Complex[] ToComplex(int[] sourceArray) Parameters sourceArray int[] The array to convert Returns Complex[] Converted array of type Complex ToComplex(long[]) Converts long array to a Complex array. public static Complex[] ToComplex(long[] sourceArray) Parameters sourceArray long[] The array to convert Returns Complex[] Converted array of type Complex ToComplex(Complex[]) Converts Complex array to a Complex array. public static Complex[] ToComplex(Complex[] sourceArray) Parameters sourceArray Complex[] The array to convert Returns Complex[] Converted array of type Complex Remarks Based on benchmark ArrayCopying ToComplex(float[]) Converts float array to a Complex array. public static Complex[] ToComplex(float[] sourceArray) Parameters sourceArray float[] The array to convert Returns Complex[] Converted array of type Complex ToComplex(string[]) Converts string array to a Complex array. public static Complex[] ToComplex(string[] sourceArray) Parameters sourceArray string[] The array to convert Returns Complex[] Converted array of type Complex Exceptions FormatException A string in sourceArray has an invalid complex format ToComplex(ushort[]) Converts ushort array to a Complex array. public static Complex[] ToComplex(ushort[] sourceArray) Parameters sourceArray ushort[] The array to convert Returns Complex[] Converted array of type Complex ToComplex(uint[]) Converts uint array to a Complex array. public static Complex[] ToComplex(uint[] sourceArray) Parameters sourceArray uint[] The array to convert Returns Complex[] Converted array of type Complex ToComplex(ulong[]) Converts ulong array to a Complex array. public static Complex[] ToComplex(ulong[] sourceArray) Parameters sourceArray ulong[] The array to convert Returns Complex[] Converted array of type Complex ToDecimal(Array) public static decimal[] ToDecimal(Array sourceArray) Parameters sourceArray Array Returns decimal[] ToDecimal(bool[]) Converts bool array to a decimal array. public static decimal[] ToDecimal(bool[] sourceArray) Parameters sourceArray bool[] The array to convert Returns decimal[] Converted array of type Decimal ToDecimal(byte[]) Converts byte array to a decimal array. public static decimal[] ToDecimal(byte[] sourceArray) Parameters sourceArray byte[] The array to convert Returns decimal[] Converted array of type Decimal ToDecimal(char[]) Converts char array to a decimal array. public static decimal[] ToDecimal(char[] sourceArray) Parameters sourceArray char[] The array to convert Returns decimal[] Converted array of type Decimal ToDecimal(decimal[]) Converts decimal array to a decimal array. public static decimal[] ToDecimal(decimal[] sourceArray) Parameters sourceArray decimal[] The array to convert Returns decimal[] Converted array of type Decimal Remarks Based on benchmark ArrayCopying ToDecimal(double[]) Converts double array to a decimal array. public static decimal[] ToDecimal(double[] sourceArray) Parameters sourceArray double[] The array to convert Returns decimal[] Converted array of type Decimal ToDecimal(short[]) Converts short array to a decimal array. public static decimal[] ToDecimal(short[] sourceArray) Parameters sourceArray short[] The array to convert Returns decimal[] Converted array of type Decimal ToDecimal(int[]) Converts int array to a decimal array. public static decimal[] ToDecimal(int[] sourceArray) Parameters sourceArray int[] The array to convert Returns decimal[] Converted array of type Decimal ToDecimal(long[]) Converts long array to a decimal array. public static decimal[] ToDecimal(long[] sourceArray) Parameters sourceArray long[] The array to convert Returns decimal[] Converted array of type Decimal ToDecimal(float[]) Converts float array to a decimal array. public static decimal[] ToDecimal(float[] sourceArray) Parameters sourceArray float[] The array to convert Returns decimal[] Converted array of type Decimal ToDecimal(string[]) Converts string array to a decimal array. public static decimal[] ToDecimal(string[] sourceArray) Parameters sourceArray string[] The array to convert Returns decimal[] Converted array of type Decimal ToDecimal(ushort[]) Converts ushort array to a decimal array. public static decimal[] ToDecimal(ushort[] sourceArray) Parameters sourceArray ushort[] The array to convert Returns decimal[] Converted array of type Decimal ToDecimal(uint[]) Converts uint array to a decimal array. public static decimal[] ToDecimal(uint[] sourceArray) Parameters sourceArray uint[] The array to convert Returns decimal[] Converted array of type Decimal ToDecimal(ulong[]) Converts ulong array to a decimal array. public static decimal[] ToDecimal(ulong[] sourceArray) Parameters sourceArray ulong[] The array to convert Returns decimal[] Converted array of type Decimal ToDouble(Array) public static double[] ToDouble(Array sourceArray) Parameters sourceArray Array Returns double[] ToDouble(bool[]) Converts bool array to a double array. public static double[] ToDouble(bool[] sourceArray) Parameters sourceArray bool[] The array to convert Returns double[] Converted array of type Double ToDouble(byte[]) Converts byte array to a double array. public static double[] ToDouble(byte[] sourceArray) Parameters sourceArray byte[] The array to convert Returns double[] Converted array of type Double ToDouble(char[]) Converts char array to a double array. public static double[] ToDouble(char[] sourceArray) Parameters sourceArray char[] The array to convert Returns double[] Converted array of type Double ToDouble(decimal[]) Converts decimal array to a double array. public static double[] ToDouble(decimal[] sourceArray) Parameters sourceArray decimal[] The array to convert Returns double[] Converted array of type Double ToDouble(double[]) Converts double array to a double array. public static double[] ToDouble(double[] sourceArray) Parameters sourceArray double[] The array to convert Returns double[] Converted array of type Double Remarks Based on benchmark ArrayCopying ToDouble(short[]) Converts short array to a double array. public static double[] ToDouble(short[] sourceArray) Parameters sourceArray short[] The array to convert Returns double[] Converted array of type Double ToDouble(int[]) Converts int array to a double array. public static double[] ToDouble(int[] sourceArray) Parameters sourceArray int[] The array to convert Returns double[] Converted array of type Double ToDouble(long[]) Converts long array to a double array. public static double[] ToDouble(long[] sourceArray) Parameters sourceArray long[] The array to convert Returns double[] Converted array of type Double ToDouble(float[]) Converts float array to a double array. public static double[] ToDouble(float[] sourceArray) Parameters sourceArray float[] The array to convert Returns double[] Converted array of type Double ToDouble(string[]) Converts string array to a double array. public static double[] ToDouble(string[] sourceArray) Parameters sourceArray string[] The array to convert Returns double[] Converted array of type Double ToDouble(ushort[]) Converts ushort array to a double array. public static double[] ToDouble(ushort[] sourceArray) Parameters sourceArray ushort[] The array to convert Returns double[] Converted array of type Double ToDouble(uint[]) Converts uint array to a double array. public static double[] ToDouble(uint[] sourceArray) Parameters sourceArray uint[] The array to convert Returns double[] Converted array of type Double ToDouble(ulong[]) Converts ulong array to a double array. public static double[] ToDouble(ulong[] sourceArray) Parameters sourceArray ulong[] The array to convert Returns double[] Converted array of type Double ToInt16(Array) public static short[] ToInt16(Array sourceArray) Parameters sourceArray Array Returns short[] ToInt16(bool[]) Converts bool array to a short array. public static short[] ToInt16(bool[] sourceArray) Parameters sourceArray bool[] The array to convert Returns short[] Converted array of type Int16 ToInt16(byte[]) Converts byte array to a short array. public static short[] ToInt16(byte[] sourceArray) Parameters sourceArray byte[] The array to convert Returns short[] Converted array of type Int16 ToInt16(char[]) Converts char array to a short array. public static short[] ToInt16(char[] sourceArray) Parameters sourceArray char[] The array to convert Returns short[] Converted array of type Int16 ToInt16(decimal[]) Converts decimal array to a short array. public static short[] ToInt16(decimal[] sourceArray) Parameters sourceArray decimal[] The array to convert Returns short[] Converted array of type Int16 ToInt16(double[]) Converts double array to a short array. public static short[] ToInt16(double[] sourceArray) Parameters sourceArray double[] The array to convert Returns short[] Converted array of type Int16 ToInt16(short[]) Converts short array to a short array. public static short[] ToInt16(short[] sourceArray) Parameters sourceArray short[] The array to convert Returns short[] Converted array of type Int16 Remarks Based on benchmark ArrayCopying ToInt16(int[]) Converts int array to a short array. public static short[] ToInt16(int[] sourceArray) Parameters sourceArray int[] The array to convert Returns short[] Converted array of type Int16 ToInt16(long[]) Converts long array to a short array. public static short[] ToInt16(long[] sourceArray) Parameters sourceArray long[] The array to convert Returns short[] Converted array of type Int16 ToInt16(float[]) Converts float array to a short array. public static short[] ToInt16(float[] sourceArray) Parameters sourceArray float[] The array to convert Returns short[] Converted array of type Int16 ToInt16(string[]) Converts string array to a short array. public static short[] ToInt16(string[] sourceArray) Parameters sourceArray string[] The array to convert Returns short[] Converted array of type Int16 ToInt16(ushort[]) Converts ushort array to a short array. public static short[] ToInt16(ushort[] sourceArray) Parameters sourceArray ushort[] The array to convert Returns short[] Converted array of type Int16 ToInt16(uint[]) Converts uint array to a short array. public static short[] ToInt16(uint[] sourceArray) Parameters sourceArray uint[] The array to convert Returns short[] Converted array of type Int16 ToInt16(ulong[]) Converts ulong array to a short array. public static short[] ToInt16(ulong[] sourceArray) Parameters sourceArray ulong[] The array to convert Returns short[] Converted array of type Int16 ToInt32(Array) public static int[] ToInt32(Array sourceArray) Parameters sourceArray Array Returns int[] ToInt32(bool[]) Converts bool array to a int array. public static int[] ToInt32(bool[] sourceArray) Parameters sourceArray bool[] The array to convert Returns int[] Converted array of type Int32 ToInt32(byte[]) Converts byte array to a int array. public static int[] ToInt32(byte[] sourceArray) Parameters sourceArray byte[] The array to convert Returns int[] Converted array of type Int32 ToInt32(char[]) Converts char array to a int array. public static int[] ToInt32(char[] sourceArray) Parameters sourceArray char[] The array to convert Returns int[] Converted array of type Int32 ToInt32(decimal[]) Converts decimal array to a int array. public static int[] ToInt32(decimal[] sourceArray) Parameters sourceArray decimal[] The array to convert Returns int[] Converted array of type Int32 ToInt32(double[]) Converts double array to a int array. public static int[] ToInt32(double[] sourceArray) Parameters sourceArray double[] The array to convert Returns int[] Converted array of type Int32 ToInt32(short[]) Converts short array to a int array. public static int[] ToInt32(short[] sourceArray) Parameters sourceArray short[] The array to convert Returns int[] Converted array of type Int32 ToInt32(int[]) Converts int array to a int array. public static int[] ToInt32(int[] sourceArray) Parameters sourceArray int[] The array to convert Returns int[] Converted array of type Int32 Remarks Based on benchmark ArrayCopying ToInt32(long[]) Converts long array to a int array. public static int[] ToInt32(long[] sourceArray) Parameters sourceArray long[] The array to convert Returns int[] Converted array of type Int32 ToInt32(float[]) Converts float array to a int array. public static int[] ToInt32(float[] sourceArray) Parameters sourceArray float[] The array to convert Returns int[] Converted array of type Int32 ToInt32(string[]) Converts string array to a int array. public static int[] ToInt32(string[] sourceArray) Parameters sourceArray string[] The array to convert Returns int[] Converted array of type Int32 ToInt32(ushort[]) Converts ushort array to a int array. public static int[] ToInt32(ushort[] sourceArray) Parameters sourceArray ushort[] The array to convert Returns int[] Converted array of type Int32 ToInt32(uint[]) Converts uint array to a int array. public static int[] ToInt32(uint[] sourceArray) Parameters sourceArray uint[] The array to convert Returns int[] Converted array of type Int32 ToInt32(ulong[]) Converts ulong array to a int array. public static int[] ToInt32(ulong[] sourceArray) Parameters sourceArray ulong[] The array to convert Returns int[] Converted array of type Int32 ToInt64(Array) public static long[] ToInt64(Array sourceArray) Parameters sourceArray Array Returns long[] ToInt64(bool[]) Converts bool array to a long array. public static long[] ToInt64(bool[] sourceArray) Parameters sourceArray bool[] The array to convert Returns long[] Converted array of type Int64 ToInt64(byte[]) Converts byte array to a long array. public static long[] ToInt64(byte[] sourceArray) Parameters sourceArray byte[] The array to convert Returns long[] Converted array of type Int64 ToInt64(char[]) Converts char array to a long array. public static long[] ToInt64(char[] sourceArray) Parameters sourceArray char[] The array to convert Returns long[] Converted array of type Int64 ToInt64(decimal[]) Converts decimal array to a long array. public static long[] ToInt64(decimal[] sourceArray) Parameters sourceArray decimal[] The array to convert Returns long[] Converted array of type Int64 ToInt64(double[]) Converts double array to a long array. public static long[] ToInt64(double[] sourceArray) Parameters sourceArray double[] The array to convert Returns long[] Converted array of type Int64 ToInt64(short[]) Converts short array to a long array. public static long[] ToInt64(short[] sourceArray) Parameters sourceArray short[] The array to convert Returns long[] Converted array of type Int64 ToInt64(int[]) Converts int array to a long array. public static long[] ToInt64(int[] sourceArray) Parameters sourceArray int[] The array to convert Returns long[] Converted array of type Int64 ToInt64(long[]) Converts long array to a long array. public static long[] ToInt64(long[] sourceArray) Parameters sourceArray long[] The array to convert Returns long[] Converted array of type Int64 Remarks Based on benchmark ArrayCopying ToInt64(float[]) Converts float array to a long array. public static long[] ToInt64(float[] sourceArray) Parameters sourceArray float[] The array to convert Returns long[] Converted array of type Int64 ToInt64(string[]) Converts string array to a long array. public static long[] ToInt64(string[] sourceArray) Parameters sourceArray string[] The array to convert Returns long[] Converted array of type Int64 ToInt64(ushort[]) Converts ushort array to a long array. public static long[] ToInt64(ushort[] sourceArray) Parameters sourceArray ushort[] The array to convert Returns long[] Converted array of type Int64 ToInt64(uint[]) Converts uint array to a long array. public static long[] ToInt64(uint[] sourceArray) Parameters sourceArray uint[] The array to convert Returns long[] Converted array of type Int64 ToInt64(ulong[]) Converts ulong array to a long array. public static long[] ToInt64(ulong[] sourceArray) Parameters sourceArray ulong[] The array to convert Returns long[] Converted array of type Int64 ToSingle(Array) public static float[] ToSingle(Array sourceArray) Parameters sourceArray Array Returns float[] ToSingle(bool[]) Converts bool array to a float array. public static float[] ToSingle(bool[] sourceArray) Parameters sourceArray bool[] The array to convert Returns float[] Converted array of type Single ToSingle(byte[]) Converts byte array to a float array. public static float[] ToSingle(byte[] sourceArray) Parameters sourceArray byte[] The array to convert Returns float[] Converted array of type Single ToSingle(char[]) Converts char array to a float array. public static float[] ToSingle(char[] sourceArray) Parameters sourceArray char[] The array to convert Returns float[] Converted array of type Single ToSingle(decimal[]) Converts decimal array to a float array. public static float[] ToSingle(decimal[] sourceArray) Parameters sourceArray decimal[] The array to convert Returns float[] Converted array of type Single ToSingle(double[]) Converts double array to a float array. public static float[] ToSingle(double[] sourceArray) Parameters sourceArray double[] The array to convert Returns float[] Converted array of type Single ToSingle(short[]) Converts short array to a float array. public static float[] ToSingle(short[] sourceArray) Parameters sourceArray short[] The array to convert Returns float[] Converted array of type Single ToSingle(int[]) Converts int array to a float array. public static float[] ToSingle(int[] sourceArray) Parameters sourceArray int[] The array to convert Returns float[] Converted array of type Single ToSingle(long[]) Converts long array to a float array. public static float[] ToSingle(long[] sourceArray) Parameters sourceArray long[] The array to convert Returns float[] Converted array of type Single ToSingle(float[]) Converts float array to a float array. public static float[] ToSingle(float[] sourceArray) Parameters sourceArray float[] The array to convert Returns float[] Converted array of type Single Remarks Based on benchmark ArrayCopying ToSingle(string[]) Converts string array to a float array. public static float[] ToSingle(string[] sourceArray) Parameters sourceArray string[] The array to convert Returns float[] Converted array of type Single ToSingle(ushort[]) Converts ushort array to a float array. public static float[] ToSingle(ushort[] sourceArray) Parameters sourceArray ushort[] The array to convert Returns float[] Converted array of type Single ToSingle(uint[]) Converts uint array to a float array. public static float[] ToSingle(uint[] sourceArray) Parameters sourceArray uint[] The array to convert Returns float[] Converted array of type Single ToSingle(ulong[]) Converts ulong array to a float array. public static float[] ToSingle(ulong[] sourceArray) Parameters sourceArray ulong[] The array to convert Returns float[] Converted array of type Single ToString(Array) public static string[] ToString(Array sourceArray) Parameters sourceArray Array Returns string[] ToString(bool[]) Converts bool array to a string array. public static string[] ToString(bool[] sourceArray) Parameters sourceArray bool[] The array to convert Returns string[] Converted array of type String ToString(byte[]) Converts byte array to a string array. public static string[] ToString(byte[] sourceArray) Parameters sourceArray byte[] The array to convert Returns string[] Converted array of type String ToString(char[]) Converts char array to a string array. public static string[] ToString(char[] sourceArray) Parameters sourceArray char[] The array to convert Returns string[] Converted array of type String ToString(decimal[]) Converts decimal array to a string array. public static string[] ToString(decimal[] sourceArray) Parameters sourceArray decimal[] The array to convert Returns string[] Converted array of type String ToString(double[]) Converts double array to a string array. public static string[] ToString(double[] sourceArray) Parameters sourceArray double[] The array to convert Returns string[] Converted array of type String ToString(short[]) Converts short array to a string array. public static string[] ToString(short[] sourceArray) Parameters sourceArray short[] The array to convert Returns string[] Converted array of type String ToString(int[]) Converts int array to a string array. public static string[] ToString(int[] sourceArray) Parameters sourceArray int[] The array to convert Returns string[] Converted array of type String ToString(long[]) Converts long array to a string array. public static string[] ToString(long[] sourceArray) Parameters sourceArray long[] The array to convert Returns string[] Converted array of type String ToString(float[]) Converts float array to a string array. public static string[] ToString(float[] sourceArray) Parameters sourceArray float[] The array to convert Returns string[] Converted array of type String ToString(string[]) Converts string array to a string array. public static string[] ToString(string[] sourceArray) Parameters sourceArray string[] The array to convert Returns string[] Converted array of type String Remarks Based on benchmark ArrayCopying ToString(ushort[]) Converts ushort array to a string array. public static string[] ToString(ushort[] sourceArray) Parameters sourceArray ushort[] The array to convert Returns string[] Converted array of type String ToString(uint[]) Converts uint array to a string array. public static string[] ToString(uint[] sourceArray) Parameters sourceArray uint[] The array to convert Returns string[] Converted array of type String ToString(ulong[]) Converts ulong array to a string array. public static string[] ToString(ulong[] sourceArray) Parameters sourceArray ulong[] The array to convert Returns string[] Converted array of type String ToUInt16(Array) public static ushort[] ToUInt16(Array sourceArray) Parameters sourceArray Array Returns ushort[] ToUInt16(bool[]) Converts bool array to a ushort array. public static ushort[] ToUInt16(bool[] sourceArray) Parameters sourceArray bool[] The array to convert Returns ushort[] Converted array of type UInt16 ToUInt16(byte[]) Converts byte array to a ushort array. public static ushort[] ToUInt16(byte[] sourceArray) Parameters sourceArray byte[] The array to convert Returns ushort[] Converted array of type UInt16 ToUInt16(char[]) Converts char array to a ushort array. public static ushort[] ToUInt16(char[] sourceArray) Parameters sourceArray char[] The array to convert Returns ushort[] Converted array of type UInt16 ToUInt16(decimal[]) Converts decimal array to a ushort array. public static ushort[] ToUInt16(decimal[] sourceArray) Parameters sourceArray decimal[] The array to convert Returns ushort[] Converted array of type UInt16 ToUInt16(double[]) Converts double array to a ushort array. public static ushort[] ToUInt16(double[] sourceArray) Parameters sourceArray double[] The array to convert Returns ushort[] Converted array of type UInt16 ToUInt16(short[]) Converts short array to a ushort array. public static ushort[] ToUInt16(short[] sourceArray) Parameters sourceArray short[] The array to convert Returns ushort[] Converted array of type UInt16 ToUInt16(int[]) Converts int array to a ushort array. public static ushort[] ToUInt16(int[] sourceArray) Parameters sourceArray int[] The array to convert Returns ushort[] Converted array of type UInt16 ToUInt16(long[]) Converts long array to a ushort array. public static ushort[] ToUInt16(long[] sourceArray) Parameters sourceArray long[] The array to convert Returns ushort[] Converted array of type UInt16 ToUInt16(float[]) Converts float array to a ushort array. public static ushort[] ToUInt16(float[] sourceArray) Parameters sourceArray float[] The array to convert Returns ushort[] Converted array of type UInt16 ToUInt16(string[]) Converts string array to a ushort array. public static ushort[] ToUInt16(string[] sourceArray) Parameters sourceArray string[] The array to convert Returns ushort[] Converted array of type UInt16 ToUInt16(ushort[]) Converts ushort array to a ushort array. public static ushort[] ToUInt16(ushort[] sourceArray) Parameters sourceArray ushort[] The array to convert Returns ushort[] Converted array of type UInt16 Remarks Based on benchmark ArrayCopying ToUInt16(uint[]) Converts uint array to a ushort array. public static ushort[] ToUInt16(uint[] sourceArray) Parameters sourceArray uint[] The array to convert Returns ushort[] Converted array of type UInt16 ToUInt16(ulong[]) Converts ulong array to a ushort array. public static ushort[] ToUInt16(ulong[] sourceArray) Parameters sourceArray ulong[] The array to convert Returns ushort[] Converted array of type UInt16 ToUInt32(Array) public static uint[] ToUInt32(Array sourceArray) Parameters sourceArray Array Returns uint[] ToUInt32(bool[]) Converts bool array to a uint array. public static uint[] ToUInt32(bool[] sourceArray) Parameters sourceArray bool[] The array to convert Returns uint[] Converted array of type UInt32 ToUInt32(byte[]) Converts byte array to a uint array. public static uint[] ToUInt32(byte[] sourceArray) Parameters sourceArray byte[] The array to convert Returns uint[] Converted array of type UInt32 ToUInt32(char[]) Converts char array to a uint array. public static uint[] ToUInt32(char[] sourceArray) Parameters sourceArray char[] The array to convert Returns uint[] Converted array of type UInt32 ToUInt32(decimal[]) Converts decimal array to a uint array. public static uint[] ToUInt32(decimal[] sourceArray) Parameters sourceArray decimal[] The array to convert Returns uint[] Converted array of type UInt32 ToUInt32(double[]) Converts double array to a uint array. public static uint[] ToUInt32(double[] sourceArray) Parameters sourceArray double[] The array to convert Returns uint[] Converted array of type UInt32 ToUInt32(short[]) Converts short array to a uint array. public static uint[] ToUInt32(short[] sourceArray) Parameters sourceArray short[] The array to convert Returns uint[] Converted array of type UInt32 ToUInt32(int[]) Converts int array to a uint array. public static uint[] ToUInt32(int[] sourceArray) Parameters sourceArray int[] The array to convert Returns uint[] Converted array of type UInt32 ToUInt32(long[]) Converts long array to a uint array. public static uint[] ToUInt32(long[] sourceArray) Parameters sourceArray long[] The array to convert Returns uint[] Converted array of type UInt32 ToUInt32(float[]) Converts float array to a uint array. public static uint[] ToUInt32(float[] sourceArray) Parameters sourceArray float[] The array to convert Returns uint[] Converted array of type UInt32 ToUInt32(string[]) Converts string array to a uint array. public static uint[] ToUInt32(string[] sourceArray) Parameters sourceArray string[] The array to convert Returns uint[] Converted array of type UInt32 ToUInt32(ushort[]) Converts ushort array to a uint array. public static uint[] ToUInt32(ushort[] sourceArray) Parameters sourceArray ushort[] The array to convert Returns uint[] Converted array of type UInt32 ToUInt32(uint[]) Converts uint array to a uint array. public static uint[] ToUInt32(uint[] sourceArray) Parameters sourceArray uint[] The array to convert Returns uint[] Converted array of type UInt32 Remarks Based on benchmark ArrayCopying ToUInt32(ulong[]) Converts ulong array to a uint array. public static uint[] ToUInt32(ulong[] sourceArray) Parameters sourceArray ulong[] The array to convert Returns uint[] Converted array of type UInt32 ToUInt64(Array) public static ulong[] ToUInt64(Array sourceArray) Parameters sourceArray Array Returns ulong[] ToUInt64(bool[]) Converts bool array to a ulong array. public static ulong[] ToUInt64(bool[] sourceArray) Parameters sourceArray bool[] The array to convert Returns ulong[] Converted array of type UInt64 ToUInt64(byte[]) Converts byte array to a ulong array. public static ulong[] ToUInt64(byte[] sourceArray) Parameters sourceArray byte[] The array to convert Returns ulong[] Converted array of type UInt64 ToUInt64(char[]) Converts char array to a ulong array. public static ulong[] ToUInt64(char[] sourceArray) Parameters sourceArray char[] The array to convert Returns ulong[] Converted array of type UInt64 ToUInt64(decimal[]) Converts decimal array to a ulong array. public static ulong[] ToUInt64(decimal[] sourceArray) Parameters sourceArray decimal[] The array to convert Returns ulong[] Converted array of type UInt64 ToUInt64(double[]) Converts double array to a ulong array. public static ulong[] ToUInt64(double[] sourceArray) Parameters sourceArray double[] The array to convert Returns ulong[] Converted array of type UInt64 ToUInt64(short[]) Converts short array to a ulong array. public static ulong[] ToUInt64(short[] sourceArray) Parameters sourceArray short[] The array to convert Returns ulong[] Converted array of type UInt64 ToUInt64(int[]) Converts int array to a ulong array. public static ulong[] ToUInt64(int[] sourceArray) Parameters sourceArray int[] The array to convert Returns ulong[] Converted array of type UInt64 ToUInt64(long[]) Converts long array to a ulong array. public static ulong[] ToUInt64(long[] sourceArray) Parameters sourceArray long[] The array to convert Returns ulong[] Converted array of type UInt64 ToUInt64(float[]) Converts float array to a ulong array. public static ulong[] ToUInt64(float[] sourceArray) Parameters sourceArray float[] The array to convert Returns ulong[] Converted array of type UInt64 ToUInt64(string[]) Converts string array to a ulong array. public static ulong[] ToUInt64(string[] sourceArray) Parameters sourceArray string[] The array to convert Returns ulong[] Converted array of type UInt64 ToUInt64(ushort[]) Converts ushort array to a ulong array. public static ulong[] ToUInt64(ushort[] sourceArray) Parameters sourceArray ushort[] The array to convert Returns ulong[] Converted array of type UInt64 ToUInt64(uint[]) Converts uint array to a ulong array. public static ulong[] ToUInt64(uint[] sourceArray) Parameters sourceArray uint[] The array to convert Returns ulong[] Converted array of type UInt64 ToUInt64(ulong[]) Converts ulong array to a ulong array. public static ulong[] ToUInt64(ulong[] sourceArray) Parameters sourceArray ulong[] The array to convert Returns ulong[] Converted array of type UInt64 Remarks Based on benchmark ArrayCopying To(Array) Converts sourceArray to an array of type returnType. public static T[] To(Array sourceArray) Parameters sourceArray Array The array to convert Returns T[] Type Parameters T Remarks If sourceArray's element type equals to returnType then a copy is returned" + }, + "api/NumSharp.Utilities.Arrays.html": { + "href": "api/NumSharp.Utilities.Arrays.html", + "title": "Class Arrays | NumSharp Documentation", + "summary": "Class Arrays Namespace NumSharp.Utilities Assembly NumSharp.dll public static class Arrays Inheritance object Arrays Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Methods AppendAt(T[], int, T) Inserts item into a specific index. public static T[] AppendAt(T[] source, int index, T value) Parameters source T[] The array to insert copy and insert value to. index int The index to insert to. value T Returns T[] a copy of source with the appended value. Type Parameters T Concat(T[], T[]) Performs fast concatenation of multiple arrays public static T[] Concat(T[] left, T[] right) Parameters left T[] right T[] Returns T[] Type Parameters T Concat(params T[][]) Performs fast concatenation of multiple arrays public static T[] Concat(params T[][] arrays) Parameters arrays T[][] Returns T[] Type Parameters T CopyToExceptAt(T[], int, int, T[], int) Copies an array contents except for a specific index. public static void CopyToExceptAt(this T[] source, int sourceOffset, int index, T[] destinition, int destOffset = 0) Parameters source T[] The array to copy from. sourceOffset int index int The index to ignore. destinition T[] The copying destinition destOffset int The destinition's offset Type Parameters T CopyToExceptAt(T[], int, T[], int) Copies an array contents except for a specific index. public static void CopyToExceptAt(this T[] source, int index, T[] destinition, int destOffset = 0) Parameters source T[] The array to copy from. index int The index to ignore. destinition T[] The copying destinition destOffset int The destinition's offset Type Parameters T Create(NPTypeCode, int) Creates an array of 1D of type typeCode. public static Array Create(NPTypeCode typeCode, int length) Parameters typeCode NPTypeCode The type to create this array. length int The length of the array Returns Array Remarks Do not use this if you are trying to create jagged or multidimensional array. Create(Type, IEnumerable) Creates an array of 1D of type type. public static Array Create(Type type, IEnumerable enumerable) Parameters type Type The type to create this array. enumerable IEnumerable Returns Array Remarks Do not use this if you are trying to create jagged or multidimensional array. Create(Type, int) Creates an array of 1D of type type. public static Array Create(Type type, int length) Parameters type Type The type to create this array. length int The length of the array Returns Array Remarks Do not use this if you are trying to create jagged or multidimensional array. Create(Type, int[]) Creates an array of specific length of type type. public static Array Create(Type type, int[] length) Parameters type Type The type to create this array. length int[] The length of the array Returns Array Create(int) Creates an array 1D of type T. public static T[] Create(int length) Parameters length int The length of the array Returns T[] Type Parameters T The type of the array ExtractStructure(Array) Extracts shape and type from given array. public static (Shape Shape, Type DType) ExtractStructure(Array array) Parameters array Array The array to extract DType and Shape from. Returns (Shape Shape, Type Type) ExtractStructure(T[]) Extracts shape and type from given array. public static (Shape Shape, Type DType) ExtractStructure(T[] array) Parameters array T[] The array to extract DType and Shape from. Returns (Shape Shape, Type Type) Type Parameters T Flatten(Array) Flattens any type of Array. public static Array Flatten(Array array) Parameters array Array Returns Array Remarks Supports both jagged array and multi-dim arrays. Insert(T[], int, T) Inserts item into a specific index. public static T[] Insert(T[] source, int index, T value) where T : unmanaged Parameters source T[] The array to insert the value to. index int The index to insert to. value T Returns T[] Type Parameters T Insert(ref T[], int, T) Inserts item into a specific index. public static void Insert(ref T[] source, int index, T value) Parameters source T[] The array to insert the value to. index int The index to insert to. value T Type Parameters T RemoveAt(T[], int) Removes a specific index from given array. public static T[] RemoveAt(this T[] source, int index) Parameters source T[] The array to remove index from. index int The index to remove. Returns T[] A copy of source without given index Type Parameters T ResolveElementType(Array) Resolves Array element type recusivly. public static Type ResolveElementType(this Array arr) Parameters arr Array Returns Type ResolveRank(Array) Resolves Array's rank, supports both jagged array and multidim array. public static int ResolveRank(this Array arr) Parameters arr Array Returns int The number of ranks arr has ResolveShape(Array) Resolves the shape of this given array. public static Shape ResolveShape(this Array array) Parameters array Array Returns Shape Remarks Supports multi-dim and jagged arrays. ResolveShapeAndType(Array) Resolves the shape of this given array. public static (Shape Shape, Type Type) ResolveShapeAndType(this Array array) Parameters array Array Returns (Shape Shape, Type Type) Remarks Supports multi-dim and jagged arrays. Slice(T[], int, int) Slice an array. public static T[] Slice(this T[] source, int start, int end) Parameters source T[] start int end int Returns T[] Type Parameters T Remarks Supports negative end index Slice(T[], long, long) Slice an array. public static T[] Slice(this T[] source, long start, long end) Parameters source T[] start long end long Returns T[] Type Parameters T Remarks Supports negative end index Wrap(NPTypeCode, object) Creates an array of 1D of type typeCode with length of 1 and a single value inside. public static Array Wrap(NPTypeCode typeCode, object value) Parameters typeCode NPTypeCode The type to create this array. value object The value to insert Returns Array Remarks Do not use this if you are trying to create jagged or multidimensional array." + }, + "api/NumSharp.Utilities.ArraysExtensions.html": { + "href": "api/NumSharp.Utilities.ArraysExtensions.html", + "title": "Class ArraysExtensions | NumSharp Documentation", + "summary": "Class ArraysExtensions Namespace NumSharp.Utilities Assembly NumSharp.dll public static class ArraysExtensions Inheritance object ArraysExtensions Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Methods CloneArray(int[]) Slice an array. public static int[] CloneArray(this int[] source) Parameters source int[] Returns int[] Remarks Supports negative end index" + }, + "api/NumSharp.Utilities.ConcurrentHashset-1.html": { + "href": "api/NumSharp.Utilities.ConcurrentHashset-1.html", + "title": "Class ConcurrentHashset | NumSharp Documentation", + "summary": "Class ConcurrentHashset Namespace NumSharp.Utilities Assembly NumSharp.dll public class ConcurrentHashset : ISet, ICollection, IEnumerable, IEnumerable where T : unmanaged Type Parameters T Inheritance object ConcurrentHashset Implements ISet ICollection IEnumerable IEnumerable Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Constructors ConcurrentHashset() public ConcurrentHashset() ConcurrentHashset(IEnumerable) public ConcurrentHashset(IEnumerable collection) Parameters collection IEnumerable ConcurrentHashset(IEnumerable, IEqualityComparer) public ConcurrentHashset(IEnumerable collection, IEqualityComparer comparer) Parameters collection IEnumerable comparer IEqualityComparer ConcurrentHashset(IEqualityComparer) public ConcurrentHashset(IEqualityComparer comparer) Parameters comparer IEqualityComparer Properties Count Gets the number of elements contained in the ICollection. public int Count { get; } Property Value int The number of elements contained in the ICollection. IsReadOnly Gets a value indicating whether the ICollection is read-only. public bool IsReadOnly { get; } Property Value bool true if the ICollection is read-only; otherwise, false. Methods Add(T) public bool Add(T item) Parameters item T Returns bool Clear() Removes all items from the ICollection. public void Clear() Exceptions NotSupportedException The ICollection is read-only. Contains(T) Determines whether the ICollection contains a specific value. public bool Contains(T item) Parameters item T The object to locate in the ICollection. Returns bool true if item is found in the ICollection; otherwise, false. CopyTo(ArraySlice) public void CopyTo(ArraySlice array) Parameters array ArraySlice CopyTo(ArraySlice, int, int) public void CopyTo(ArraySlice array, int arrayIndex, int count) Parameters array ArraySlice arrayIndex int count int CopyTo(T[], int) Copies the elements of the ICollection to an Array, starting at a particular Array index. public void CopyTo(T[] array, int arrayIndex) Parameters array T[] The one-dimensional Array that is the destination of the elements copied from ICollection. The Array must have zero-based indexing. arrayIndex int The zero-based index in array at which copying begins. Exceptions ArgumentNullException array is null. ArgumentOutOfRangeException arrayIndex is less than 0. ArgumentException The number of elements in the source ICollection is greater than the available space from arrayIndex to the end of the destination array. Dispose() public void Dispose() Dispose(bool) protected virtual void Dispose(bool disposing) Parameters disposing bool ExceptWith(IEnumerable) Removes all elements in the specified collection from the current set. public void ExceptWith(IEnumerable other) Parameters other IEnumerable The collection of items to remove from the set. Exceptions ArgumentNullException other is null. ~ConcurrentHashset() protected ~ConcurrentHashset() GetEnumerator() Returns an enumerator that iterates through the collection. public IEnumerator GetEnumerator() Returns IEnumerator An enumerator that can be used to iterate through the collection. IntersectWith(IEnumerable) Modifies the current set so that it contains only elements that are also in a specified collection. public void IntersectWith(IEnumerable other) Parameters other IEnumerable The collection to compare to the current set. Exceptions ArgumentNullException other is null. IsProperSubsetOf(IEnumerable) Determines whether the current set is a proper (strict) subset of a specified collection. public bool IsProperSubsetOf(IEnumerable other) Parameters other IEnumerable The collection to compare to the current set. Returns bool true if the current set is a proper subset of other; otherwise, false. Exceptions ArgumentNullException other is null. IsProperSupersetOf(IEnumerable) Determines whether the current set is a proper (strict) superset of a specified collection. public bool IsProperSupersetOf(IEnumerable other) Parameters other IEnumerable The collection to compare to the current set. Returns bool true if the current set is a proper superset of other; otherwise, false. Exceptions ArgumentNullException other is null. IsSubsetOf(IEnumerable) Determines whether a set is a subset of a specified collection. public bool IsSubsetOf(IEnumerable other) Parameters other IEnumerable The collection to compare to the current set. Returns bool true if the current set is a subset of other; otherwise, false. Exceptions ArgumentNullException other is null. IsSupersetOf(IEnumerable) Determines whether the current set is a superset of a specified collection. public bool IsSupersetOf(IEnumerable other) Parameters other IEnumerable The collection to compare to the current set. Returns bool true if the current set is a superset of other; otherwise, false. Exceptions ArgumentNullException other is null. Overlaps(IEnumerable) Determines whether the current set overlaps with the specified collection. public bool Overlaps(IEnumerable other) Parameters other IEnumerable The collection to compare to the current set. Returns bool true if the current set and other share at least one common element; otherwise, false. Exceptions ArgumentNullException other is null. Remove(T) Removes the first occurrence of a specific object from the ICollection. public bool Remove(T item) Parameters item T The object to remove from the ICollection. Returns bool true if item was successfully removed from the ICollection; otherwise, false. This method also returns false if item is not found in the original ICollection. Exceptions NotSupportedException The ICollection is read-only. SetEquals(IEnumerable) Determines whether the current set and the specified collection contain the same elements. public bool SetEquals(IEnumerable other) Parameters other IEnumerable The collection to compare to the current set. Returns bool true if the current set is equal to other; otherwise, false. Exceptions ArgumentNullException other is null. SymmetricExceptWith(IEnumerable) Modifies the current set so that it contains only elements that are present either in the current set or in the specified collection, but not both. public void SymmetricExceptWith(IEnumerable other) Parameters other IEnumerable The collection to compare to the current set. Exceptions ArgumentNullException other is null. UnionWith(IEnumerable) Modifies the current set so that it contains all elements that are present in the current set, in the specified collection, or in both. public void UnionWith(IEnumerable other) Parameters other IEnumerable The collection to compare to the current set. Exceptions ArgumentNullException other is null." + }, + "api/NumSharp.Utilities.Converts-1.html": { + "href": "api/NumSharp.Utilities.Converts-1.html", + "title": "Class Converts | NumSharp Documentation", + "summary": "Class Converts Namespace NumSharp.Utilities Assembly NumSharp.dll Provides various methods related to Convert based on give T. public static class Converts Type Parameters T Inheritance object Converts Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Methods From(bool) Converts bool to T using staticly cached FindConverter(). public static T From(bool obj) Parameters obj bool The object to convert to T from bool Returns T A T From(byte) Converts byte to T using staticly cached FindConverter(). public static T From(byte obj) Parameters obj byte The object to convert to T from byte Returns T A T From(char) Converts char to T using staticly cached FindConverter(). public static T From(char obj) Parameters obj char The object to convert to T from char Returns T A T From(decimal) Converts decimal to T using staticly cached FindConverter(). public static T From(decimal obj) Parameters obj decimal The object to convert to T from decimal Returns T A T From(double) Converts double to T using staticly cached FindConverter(). public static T From(double obj) Parameters obj double The object to convert to T from double Returns T A T From(short) Converts short to T using staticly cached FindConverter(). public static T From(short obj) Parameters obj short The object to convert to T from short Returns T A T From(int) Converts int to T using staticly cached FindConverter(). public static T From(int obj) Parameters obj int The object to convert to T from int Returns T A T From(long) Converts long to T using staticly cached FindConverter(). public static T From(long obj) Parameters obj long The object to convert to T from long Returns T A T From(float) Converts float to T using staticly cached FindConverter(). public static T From(float obj) Parameters obj float The object to convert to T from float Returns T A T From(string) Converts string to T using staticly cached FindConverter(). public static T From(string obj) Parameters obj string The object to convert to T from string Returns T A T From(ushort) Converts ushort to T using staticly cached FindConverter(). public static T From(ushort obj) Parameters obj ushort The object to convert to T from ushort Returns T A T From(uint) Converts uint to T using staticly cached FindConverter(). public static T From(uint obj) Parameters obj uint The object to convert to T from uint Returns T A T From(ulong) Converts ulong to T using staticly cached FindConverter(). public static T From(ulong obj) Parameters obj ulong The object to convert to T from ulong Returns T A T ToBoolean(T) Converts T to bool using staticly cached FindConverter(). public static bool ToBoolean(T obj) Parameters obj T The object to convert to bool Returns bool A bool ToByte(T) Converts T to byte using staticly cached FindConverter(). public static byte ToByte(T obj) Parameters obj T The object to convert to byte Returns byte A byte ToChar(T) Converts T to char using staticly cached FindConverter(). public static char ToChar(T obj) Parameters obj T The object to convert to char Returns char A char ToDecimal(T) Converts T to decimal using staticly cached FindConverter(). public static decimal ToDecimal(T obj) Parameters obj T The object to convert to decimal Returns decimal A decimal ToDouble(T) Converts T to double using staticly cached FindConverter(). public static double ToDouble(T obj) Parameters obj T The object to convert to double Returns double A double ToInt16(T) Converts T to short using staticly cached FindConverter(). public static short ToInt16(T obj) Parameters obj T The object to convert to short Returns short A short ToInt32(T) Converts T to int using staticly cached FindConverter(). public static int ToInt32(T obj) Parameters obj T The object to convert to int Returns int A int ToInt64(T) Converts T to long using staticly cached FindConverter(). public static long ToInt64(T obj) Parameters obj T The object to convert to long Returns long A long ToSingle(T) Converts T to float using staticly cached FindConverter(). public static float ToSingle(T obj) Parameters obj T The object to convert to float Returns float A float ToString(T) Converts T to string using staticly cached FindConverter(). public static string ToString(T obj) Parameters obj T The object to convert to string Returns string A string ToUInt16(T) Converts T to ushort using staticly cached FindConverter(). public static ushort ToUInt16(T obj) Parameters obj T The object to convert to ushort Returns ushort A ushort ToUInt32(T) Converts T to uint using staticly cached FindConverter(). public static uint ToUInt32(T obj) Parameters obj T The object to convert to uint Returns uint A uint ToUInt64(T) Converts T to ulong using staticly cached FindConverter(). public static ulong ToUInt64(T obj) Parameters obj T The object to convert to ulong Returns ulong A ulong" + }, + "api/NumSharp.Utilities.Converts.html": { + "href": "api/NumSharp.Utilities.Converts.html", + "title": "Class Converts | NumSharp Documentation", + "summary": "Class Converts Namespace NumSharp.Utilities Assembly NumSharp.dll Provides various methods related to Convert. [SuppressMessage(\"ReSharper\", \"MergeConditionalExpression\")] [SuppressMessage(\"ReSharper\", \"JoinDeclarationAndInitializer\")] public static class Converts Inheritance object Converts Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Fields DBNull public static readonly object DBNull Field Value object Methods ChangeType(object, NPTypeCode) Returns an object of the specified type whose value is equivalent to the specified object. public static object ChangeType(object value, NPTypeCode typeCode) Parameters value object An object that implements the IConvertible interface. typeCode NPTypeCode The type of object to return. Returns object An object whose underlying type is typeCode and whose value is equivalent to value. -or- A null reference (Nothing in Visual Basic), if value is null and typeCode is Empty, String, or Object. Exceptions InvalidCastException This conversion is not supported. -or- value is null and typeCode specifies a value type. -or- value does not implement the IConvertible interface. FormatException value is not in a format recognized by the typeCode type. OverflowException value represents a number that is out of the range of the typeCode type. ArgumentException typeCode is invalid. ChangeType(object, NPTypeCode, IFormatProvider) Returns an object of the specified type whose value is equivalent to the specified object. public static object ChangeType(object value, NPTypeCode typeCode, IFormatProvider provider) Parameters value object An object that implements the IConvertible interface. typeCode NPTypeCode The type of object to return. provider IFormatProvider Returns object An object whose underlying type is typeCode and whose value is equivalent to value. -or- A null reference (Nothing in Visual Basic), if value is null and typeCode is Empty, String, or Object. Exceptions InvalidCastException This conversion is not supported. -or- value is null and typeCode specifies a value type. -or- value does not implement the IConvertible interface. FormatException value is not in a format recognized by the typeCode type. OverflowException value represents a number that is out of the range of the typeCode type. ArgumentException typeCode is invalid. ChangeType(object, TypeCode) public static object ChangeType(object value, TypeCode typeCode) Parameters value object typeCode TypeCode Returns object ChangeType(object, TypeCode, IFormatProvider) public static object ChangeType(object value, TypeCode typeCode, IFormatProvider provider) Parameters value object typeCode TypeCode provider IFormatProvider Returns object ChangeType(object) Returns an object of the specified type whose value is equivalent to the specified object. public static TOut ChangeType(object value) Parameters value object An object that implements the IConvertible interface. Returns TOut An object whose underlying type is typeCode and whose value is equivalent to value. -or- A null reference (Nothing in Visual Basic), if value is null and typeCode is Empty, String, or Object. Type Parameters TOut Exceptions InvalidCastException This conversion is not supported. -or- value is null and typeCode specifies a value type. -or- value does not implement the IConvertible interface. FormatException value is not in a format recognized by the typeCode type. OverflowException value represents a number that is out of the range of the typeCode type. ArgumentException typeCode is invalid. ChangeType(T, NPTypeCode) Returns an object of the specified type whose value is equivalent to the specified object. public static object ChangeType(T value, NPTypeCode typeCode) where T : IConvertible Parameters value T An object that implements the IConvertible interface. typeCode NPTypeCode The type of object to return. Returns object An object whose underlying type is typeCode and whose value is equivalent to value. -or- A null reference (Nothing in Visual Basic), if value is null and typeCode is Empty, String, or Object. Type Parameters T Exceptions InvalidCastException This conversion is not supported. -or- value is null and typeCode specifies a value type. -or- value does not implement the IConvertible interface. FormatException value is not in a format recognized by the typeCode type. OverflowException value represents a number that is out of the range of the typeCode type. ArgumentException typeCode is invalid. ChangeType(TIn) Returns an object of the specified type whose value is equivalent to the specified object. public static TOut ChangeType(TIn value) where TIn : IConvertible where TOut : IConvertible Parameters value TIn An object that implements the IConvertible interface. Returns TOut An object whose underlying type is typeCode and whose value is equivalent to value. -or- A null reference (Nothing in Visual Basic), if value is null and typeCode is Empty, String, or Object. Type Parameters TIn TOut Exceptions InvalidCastException This conversion is not supported. -or- value is null and typeCode specifies a value type. -or- value does not implement the IConvertible interface. FormatException value is not in a format recognized by the typeCode type. OverflowException value represents a number that is out of the range of the typeCode type. ArgumentException typeCode is invalid. FindConverter() Finds the conversion method from Convert based on TIn and TOut. public static Func FindConverter() Returns Func Type Parameters TIn The type that is expected as input and to be converted from TOut The type we expect to convert to. FromBase64CharArray(char[], int, int) Converts the specified range of a Char array, which encodes binary data as Base64 digits, to the equivalent byte array. public static byte[] FromBase64CharArray(char[] inArray, int offset, int length) Parameters inArray char[] Chars representing Base64 encoding characters offset int A position within the input array. length int Number of element to convert. Returns byte[] The array of bytes represented by the specified Base64 encoding characters. FromBase64String(string) Converts the specified string, which encodes binary data as Base64 digits, to the equivalent byte array. public static byte[] FromBase64String(string s) Parameters s string The string to convert Returns byte[] The array of bytes represented by the specifed Base64 string. GetTypeCode(object) [Pure] public static TypeCode GetTypeCode(object value) Parameters value object Returns TypeCode IsDBNull(object) [Pure] public static bool IsDBNull(object value) Parameters value object Returns bool ToBase64CharArray(byte[], int, int, char[], int) public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut) Parameters inArray byte[] offsetIn int length int outArray char[] offsetOut int Returns int ToBase64CharArray(byte[], int, int, char[], int, Base64FormattingOptions) [ComVisible(false)] public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut, Base64FormattingOptions options) Parameters inArray byte[] offsetIn int length int outArray char[] offsetOut int options Base64FormattingOptions Returns int ToBoolean(NDArray) public static bool ToBoolean(NDArray nd) Parameters nd NDArray Returns bool ToBoolean(bool) public static bool ToBoolean(bool value) Parameters value bool Returns bool ToBoolean(byte) public static bool ToBoolean(byte value) Parameters value byte Returns bool ToBoolean(char) public static bool ToBoolean(char value) Parameters value char Returns bool ToBoolean(DateTime) public static bool ToBoolean(DateTime value) Parameters value DateTime Returns bool ToBoolean(decimal) public static bool ToBoolean(decimal value) Parameters value decimal Returns bool ToBoolean(double) public static bool ToBoolean(double value) Parameters value double Returns bool ToBoolean(short) public static bool ToBoolean(short value) Parameters value short Returns bool ToBoolean(int) public static bool ToBoolean(int value) Parameters value int Returns bool ToBoolean(long) public static bool ToBoolean(long value) Parameters value long Returns bool ToBoolean(object) public static bool ToBoolean(object value) Parameters value object Returns bool ToBoolean(object, IFormatProvider) public static bool ToBoolean(object value, IFormatProvider provider) Parameters value object provider IFormatProvider Returns bool ToBoolean(sbyte) public static bool ToBoolean(sbyte value) Parameters value sbyte Returns bool ToBoolean(float) public static bool ToBoolean(float value) Parameters value float Returns bool ToBoolean(string) public static bool ToBoolean(string value) Parameters value string Returns bool ToBoolean(string, IFormatProvider) public static bool ToBoolean(string value, IFormatProvider provider) Parameters value string provider IFormatProvider Returns bool ToBoolean(ushort) public static bool ToBoolean(ushort value) Parameters value ushort Returns bool ToBoolean(uint) public static bool ToBoolean(uint value) Parameters value uint Returns bool ToBoolean(ulong) public static bool ToBoolean(ulong value) Parameters value ulong Returns bool ToByte(NDArray) public static byte ToByte(NDArray nd) Parameters nd NDArray Returns byte ToByte(bool) public static byte ToByte(bool value) Parameters value bool Returns byte ToByte(byte) public static byte ToByte(byte value) Parameters value byte Returns byte ToByte(char) public static byte ToByte(char value) Parameters value char Returns byte ToByte(DateTime) public static byte ToByte(DateTime value) Parameters value DateTime Returns byte ToByte(decimal) public static byte ToByte(decimal value) Parameters value decimal Returns byte ToByte(double) public static byte ToByte(double value) Parameters value double Returns byte ToByte(short) public static byte ToByte(short value) Parameters value short Returns byte ToByte(int) public static byte ToByte(int value) Parameters value int Returns byte ToByte(long) public static byte ToByte(long value) Parameters value long Returns byte ToByte(object) public static byte ToByte(object value) Parameters value object Returns byte ToByte(object, IFormatProvider) public static byte ToByte(object value, IFormatProvider provider) Parameters value object provider IFormatProvider Returns byte ToByte(sbyte) public static byte ToByte(sbyte value) Parameters value sbyte Returns byte ToByte(float) public static byte ToByte(float value) Parameters value float Returns byte ToByte(string) public static byte ToByte(string value) Parameters value string Returns byte ToByte(string, IFormatProvider) public static byte ToByte(string value, IFormatProvider provider) Parameters value string provider IFormatProvider Returns byte ToByte(ushort) public static byte ToByte(ushort value) Parameters value ushort Returns byte ToByte(uint) public static byte ToByte(uint value) Parameters value uint Returns byte ToByte(ulong) public static byte ToByte(ulong value) Parameters value ulong Returns byte ToChar(NDArray) public static char ToChar(NDArray nd) Parameters nd NDArray Returns char ToChar(bool) public static char ToChar(bool value) Parameters value bool Returns char ToChar(byte) public static char ToChar(byte value) Parameters value byte Returns char ToChar(char) public static char ToChar(char value) Parameters value char Returns char ToChar(DateTime) public static char ToChar(DateTime value) Parameters value DateTime Returns char ToChar(decimal) public static char ToChar(decimal value) Parameters value decimal Returns char ToChar(double) public static char ToChar(double value) Parameters value double Returns char ToChar(short) public static char ToChar(short value) Parameters value short Returns char ToChar(int) public static char ToChar(int value) Parameters value int Returns char ToChar(long) public static char ToChar(long value) Parameters value long Returns char ToChar(object) public static char ToChar(object value) Parameters value object Returns char ToChar(object, IFormatProvider) public static char ToChar(object value, IFormatProvider provider) Parameters value object provider IFormatProvider Returns char ToChar(sbyte) public static char ToChar(sbyte value) Parameters value sbyte Returns char ToChar(float) public static char ToChar(float value) Parameters value float Returns char ToChar(string) public static char ToChar(string value) Parameters value string Returns char ToChar(string, IFormatProvider) public static char ToChar(string value, IFormatProvider provider) Parameters value string provider IFormatProvider Returns char ToChar(ushort) public static char ToChar(ushort value) Parameters value ushort Returns char ToChar(uint) public static char ToChar(uint value) Parameters value uint Returns char ToChar(ulong) public static char ToChar(ulong value) Parameters value ulong Returns char ToDateTime(bool) public static DateTime ToDateTime(bool value) Parameters value bool Returns DateTime ToDateTime(byte) public static DateTime ToDateTime(byte value) Parameters value byte Returns DateTime ToDateTime(char) public static DateTime ToDateTime(char value) Parameters value char Returns DateTime ToDateTime(DateTime) public static DateTime ToDateTime(DateTime value) Parameters value DateTime Returns DateTime ToDateTime(decimal) public static DateTime ToDateTime(decimal value) Parameters value decimal Returns DateTime ToDateTime(double) public static DateTime ToDateTime(double value) Parameters value double Returns DateTime ToDateTime(short) public static DateTime ToDateTime(short value) Parameters value short Returns DateTime ToDateTime(int) public static DateTime ToDateTime(int value) Parameters value int Returns DateTime ToDateTime(long) public static DateTime ToDateTime(long value) Parameters value long Returns DateTime ToDateTime(object) public static DateTime ToDateTime(object value) Parameters value object Returns DateTime ToDateTime(object, IFormatProvider) public static DateTime ToDateTime(object value, IFormatProvider provider) Parameters value object provider IFormatProvider Returns DateTime ToDateTime(sbyte) public static DateTime ToDateTime(sbyte value) Parameters value sbyte Returns DateTime ToDateTime(float) public static DateTime ToDateTime(float value) Parameters value float Returns DateTime ToDateTime(string) public static DateTime ToDateTime(string value) Parameters value string Returns DateTime ToDateTime(string, IFormatProvider) public static DateTime ToDateTime(string value, IFormatProvider provider) Parameters value string provider IFormatProvider Returns DateTime ToDateTime(ushort) public static DateTime ToDateTime(ushort value) Parameters value ushort Returns DateTime ToDateTime(uint) public static DateTime ToDateTime(uint value) Parameters value uint Returns DateTime ToDateTime(ulong) public static DateTime ToDateTime(ulong value) Parameters value ulong Returns DateTime ToDecimal(NDArray) public static decimal ToDecimal(NDArray nd) Parameters nd NDArray Returns decimal ToDecimal(bool) public static decimal ToDecimal(bool value) Parameters value bool Returns decimal ToDecimal(byte) public static decimal ToDecimal(byte value) Parameters value byte Returns decimal ToDecimal(char) public static decimal ToDecimal(char value) Parameters value char Returns decimal ToDecimal(DateTime) public static decimal ToDecimal(DateTime value) Parameters value DateTime Returns decimal ToDecimal(decimal) public static decimal ToDecimal(decimal value) Parameters value decimal Returns decimal ToDecimal(double) public static decimal ToDecimal(double value) Parameters value double Returns decimal ToDecimal(short) public static decimal ToDecimal(short value) Parameters value short Returns decimal ToDecimal(int) public static decimal ToDecimal(int value) Parameters value int Returns decimal ToDecimal(long) public static decimal ToDecimal(long value) Parameters value long Returns decimal ToDecimal(object) public static decimal ToDecimal(object value) Parameters value object Returns decimal ToDecimal(object, IFormatProvider) public static decimal ToDecimal(object value, IFormatProvider provider) Parameters value object provider IFormatProvider Returns decimal ToDecimal(sbyte) public static decimal ToDecimal(sbyte value) Parameters value sbyte Returns decimal ToDecimal(float) public static decimal ToDecimal(float value) Parameters value float Returns decimal ToDecimal(string) public static decimal ToDecimal(string value) Parameters value string Returns decimal ToDecimal(string, IFormatProvider) public static decimal ToDecimal(string value, IFormatProvider provider) Parameters value string provider IFormatProvider Returns decimal ToDecimal(ushort) public static decimal ToDecimal(ushort value) Parameters value ushort Returns decimal ToDecimal(uint) public static decimal ToDecimal(uint value) Parameters value uint Returns decimal ToDecimal(ulong) public static decimal ToDecimal(ulong value) Parameters value ulong Returns decimal ToDouble(NDArray) public static double ToDouble(NDArray nd) Parameters nd NDArray Returns double ToDouble(bool) public static double ToDouble(bool value) Parameters value bool Returns double ToDouble(byte) public static double ToDouble(byte value) Parameters value byte Returns double ToDouble(char) public static double ToDouble(char value) Parameters value char Returns double ToDouble(DateTime) public static double ToDouble(DateTime value) Parameters value DateTime Returns double ToDouble(decimal) public static double ToDouble(decimal value) Parameters value decimal Returns double ToDouble(double) public static double ToDouble(double value) Parameters value double Returns double ToDouble(short) public static double ToDouble(short value) Parameters value short Returns double ToDouble(int) public static double ToDouble(int value) Parameters value int Returns double ToDouble(long) public static double ToDouble(long value) Parameters value long Returns double ToDouble(object) public static double ToDouble(object value) Parameters value object Returns double ToDouble(object, IFormatProvider) public static double ToDouble(object value, IFormatProvider provider) Parameters value object provider IFormatProvider Returns double ToDouble(sbyte) public static double ToDouble(sbyte value) Parameters value sbyte Returns double ToDouble(float) public static double ToDouble(float value) Parameters value float Returns double ToDouble(string) public static double ToDouble(string value) Parameters value string Returns double ToDouble(string, IFormatProvider) public static double ToDouble(string value, IFormatProvider provider) Parameters value string provider IFormatProvider Returns double ToDouble(ushort) public static double ToDouble(ushort value) Parameters value ushort Returns double ToDouble(uint) public static double ToDouble(uint value) Parameters value uint Returns double ToDouble(ulong) public static double ToDouble(ulong value) Parameters value ulong Returns double ToInt16(NDArray) public static short ToInt16(NDArray nd) Parameters nd NDArray Returns short ToInt16(bool) public static short ToInt16(bool value) Parameters value bool Returns short ToInt16(byte) public static short ToInt16(byte value) Parameters value byte Returns short ToInt16(char) public static short ToInt16(char value) Parameters value char Returns short ToInt16(DateTime) public static short ToInt16(DateTime value) Parameters value DateTime Returns short ToInt16(decimal) public static short ToInt16(decimal value) Parameters value decimal Returns short ToInt16(double) public static short ToInt16(double value) Parameters value double Returns short ToInt16(short) public static short ToInt16(short value) Parameters value short Returns short ToInt16(int) public static short ToInt16(int value) Parameters value int Returns short ToInt16(long) public static short ToInt16(long value) Parameters value long Returns short ToInt16(object) public static short ToInt16(object value) Parameters value object Returns short ToInt16(object, IFormatProvider) public static short ToInt16(object value, IFormatProvider provider) Parameters value object provider IFormatProvider Returns short ToInt16(sbyte) public static short ToInt16(sbyte value) Parameters value sbyte Returns short ToInt16(float) public static short ToInt16(float value) Parameters value float Returns short ToInt16(string) public static short ToInt16(string value) Parameters value string Returns short ToInt16(string, IFormatProvider) public static short ToInt16(string value, IFormatProvider provider) Parameters value string provider IFormatProvider Returns short ToInt16(ushort) public static short ToInt16(ushort value) Parameters value ushort Returns short ToInt16(uint) public static short ToInt16(uint value) Parameters value uint Returns short ToInt16(ulong) public static short ToInt16(ulong value) Parameters value ulong Returns short ToInt32(NDArray) public static int ToInt32(NDArray nd) Parameters nd NDArray Returns int ToInt32(bool) public static int ToInt32(bool value) Parameters value bool Returns int ToInt32(byte) public static int ToInt32(byte value) Parameters value byte Returns int ToInt32(char) public static int ToInt32(char value) Parameters value char Returns int ToInt32(DateTime) public static int ToInt32(DateTime value) Parameters value DateTime Returns int ToInt32(decimal) public static int ToInt32(decimal value) Parameters value decimal Returns int ToInt32(double) public static int ToInt32(double value) Parameters value double Returns int ToInt32(short) public static int ToInt32(short value) Parameters value short Returns int ToInt32(int) public static int ToInt32(int value) Parameters value int Returns int ToInt32(long) public static int ToInt32(long value) Parameters value long Returns int ToInt32(object) public static int ToInt32(object value) Parameters value object Returns int ToInt32(object, IFormatProvider) public static int ToInt32(object value, IFormatProvider provider) Parameters value object provider IFormatProvider Returns int ToInt32(sbyte) public static int ToInt32(sbyte value) Parameters value sbyte Returns int ToInt32(float) public static int ToInt32(float value) Parameters value float Returns int ToInt32(string) public static int ToInt32(string value) Parameters value string Returns int ToInt32(string, IFormatProvider) public static int ToInt32(string value, IFormatProvider provider) Parameters value string provider IFormatProvider Returns int ToInt32(ushort) public static int ToInt32(ushort value) Parameters value ushort Returns int ToInt32(uint) public static int ToInt32(uint value) Parameters value uint Returns int ToInt32(ulong) public static int ToInt32(ulong value) Parameters value ulong Returns int ToInt64(NDArray) public static long ToInt64(NDArray nd) Parameters nd NDArray Returns long ToInt64(bool) public static long ToInt64(bool value) Parameters value bool Returns long ToInt64(byte) public static long ToInt64(byte value) Parameters value byte Returns long ToInt64(char) public static long ToInt64(char value) Parameters value char Returns long ToInt64(DateTime) public static long ToInt64(DateTime value) Parameters value DateTime Returns long ToInt64(decimal) public static long ToInt64(decimal value) Parameters value decimal Returns long ToInt64(double) public static long ToInt64(double value) Parameters value double Returns long ToInt64(short) public static long ToInt64(short value) Parameters value short Returns long ToInt64(int) public static long ToInt64(int value) Parameters value int Returns long ToInt64(long) public static long ToInt64(long value) Parameters value long Returns long ToInt64(object) public static long ToInt64(object value) Parameters value object Returns long ToInt64(object, IFormatProvider) public static long ToInt64(object value, IFormatProvider provider) Parameters value object provider IFormatProvider Returns long ToInt64(sbyte) public static long ToInt64(sbyte value) Parameters value sbyte Returns long ToInt64(float) public static long ToInt64(float value) Parameters value float Returns long ToInt64(string) public static long ToInt64(string value) Parameters value string Returns long ToInt64(string, IFormatProvider) public static long ToInt64(string value, IFormatProvider provider) Parameters value string provider IFormatProvider Returns long ToInt64(ushort) public static long ToInt64(ushort value) Parameters value ushort Returns long ToInt64(uint) public static long ToInt64(uint value) Parameters value uint Returns long ToInt64(ulong) public static long ToInt64(ulong value) Parameters value ulong Returns long ToSByte(bool) public static sbyte ToSByte(bool value) Parameters value bool Returns sbyte ToSByte(byte) public static sbyte ToSByte(byte value) Parameters value byte Returns sbyte ToSByte(char) public static sbyte ToSByte(char value) Parameters value char Returns sbyte ToSByte(DateTime) public static sbyte ToSByte(DateTime value) Parameters value DateTime Returns sbyte ToSByte(decimal) public static sbyte ToSByte(decimal value) Parameters value decimal Returns sbyte ToSByte(double) public static sbyte ToSByte(double value) Parameters value double Returns sbyte ToSByte(short) public static sbyte ToSByte(short value) Parameters value short Returns sbyte ToSByte(int) public static sbyte ToSByte(int value) Parameters value int Returns sbyte ToSByte(long) public static sbyte ToSByte(long value) Parameters value long Returns sbyte ToSByte(object) public static sbyte ToSByte(object value) Parameters value object Returns sbyte ToSByte(object, IFormatProvider) public static sbyte ToSByte(object value, IFormatProvider provider) Parameters value object provider IFormatProvider Returns sbyte ToSByte(sbyte) public static sbyte ToSByte(sbyte value) Parameters value sbyte Returns sbyte ToSByte(float) public static sbyte ToSByte(float value) Parameters value float Returns sbyte ToSByte(string) public static sbyte ToSByte(string value) Parameters value string Returns sbyte ToSByte(string, IFormatProvider) public static sbyte ToSByte(string value, IFormatProvider provider) Parameters value string provider IFormatProvider Returns sbyte ToSByte(ushort) public static sbyte ToSByte(ushort value) Parameters value ushort Returns sbyte ToSByte(uint) public static sbyte ToSByte(uint value) Parameters value uint Returns sbyte ToSByte(ulong) public static sbyte ToSByte(ulong value) Parameters value ulong Returns sbyte ToSingle(NDArray) public static float ToSingle(NDArray nd) Parameters nd NDArray Returns float ToSingle(bool) public static float ToSingle(bool value) Parameters value bool Returns float ToSingle(byte) public static float ToSingle(byte value) Parameters value byte Returns float ToSingle(char) public static float ToSingle(char value) Parameters value char Returns float ToSingle(DateTime) public static float ToSingle(DateTime value) Parameters value DateTime Returns float ToSingle(decimal) public static float ToSingle(decimal value) Parameters value decimal Returns float ToSingle(double) public static float ToSingle(double value) Parameters value double Returns float ToSingle(short) public static float ToSingle(short value) Parameters value short Returns float ToSingle(int) public static float ToSingle(int value) Parameters value int Returns float ToSingle(long) public static float ToSingle(long value) Parameters value long Returns float ToSingle(object) public static float ToSingle(object value) Parameters value object Returns float ToSingle(object, IFormatProvider) public static float ToSingle(object value, IFormatProvider provider) Parameters value object provider IFormatProvider Returns float ToSingle(sbyte) public static float ToSingle(sbyte value) Parameters value sbyte Returns float ToSingle(float) public static float ToSingle(float value) Parameters value float Returns float ToSingle(string) public static float ToSingle(string value) Parameters value string Returns float ToSingle(string, IFormatProvider) public static float ToSingle(string value, IFormatProvider provider) Parameters value string provider IFormatProvider Returns float ToSingle(ushort) public static float ToSingle(ushort value) Parameters value ushort Returns float ToSingle(uint) public static float ToSingle(uint value) Parameters value uint Returns float ToSingle(ulong) public static float ToSingle(ulong value) Parameters value ulong Returns float ToString(bool) public static string ToString(bool value) Parameters value bool Returns string ToString(bool, IFormatProvider) public static string ToString(bool value, IFormatProvider provider) Parameters value bool provider IFormatProvider Returns string ToString(byte) public static string ToString(byte value) Parameters value byte Returns string ToString(byte, IFormatProvider) public static string ToString(byte value, IFormatProvider provider) Parameters value byte provider IFormatProvider Returns string ToString(char) public static string ToString(char value) Parameters value char Returns string ToString(char, IFormatProvider) public static string ToString(char value, IFormatProvider provider) Parameters value char provider IFormatProvider Returns string ToString(DateTime) public static string ToString(DateTime value) Parameters value DateTime Returns string ToString(DateTime, IFormatProvider) public static string ToString(DateTime value, IFormatProvider provider) Parameters value DateTime provider IFormatProvider Returns string ToString(decimal) public static string ToString(decimal value) Parameters value decimal Returns string ToString(decimal, IFormatProvider) public static string ToString(decimal value, IFormatProvider provider) Parameters value decimal provider IFormatProvider Returns string ToString(double) public static string ToString(double value) Parameters value double Returns string ToString(double, IFormatProvider) public static string ToString(double value, IFormatProvider provider) Parameters value double provider IFormatProvider Returns string ToString(short) public static string ToString(short value) Parameters value short Returns string ToString(short, IFormatProvider) public static string ToString(short value, IFormatProvider provider) Parameters value short provider IFormatProvider Returns string ToString(int) public static string ToString(int value) Parameters value int Returns string ToString(int, IFormatProvider) public static string ToString(int value, IFormatProvider provider) Parameters value int provider IFormatProvider Returns string ToString(long) public static string ToString(long value) Parameters value long Returns string ToString(long, IFormatProvider) public static string ToString(long value, IFormatProvider provider) Parameters value long provider IFormatProvider Returns string ToString(object) public static string ToString(object value) Parameters value object Returns string ToString(object, IFormatProvider) public static string ToString(object value, IFormatProvider provider) Parameters value object provider IFormatProvider Returns string ToString(sbyte) public static string ToString(sbyte value) Parameters value sbyte Returns string ToString(sbyte, IFormatProvider) public static string ToString(sbyte value, IFormatProvider provider) Parameters value sbyte provider IFormatProvider Returns string ToString(float) public static string ToString(float value) Parameters value float Returns string ToString(float, IFormatProvider) public static string ToString(float value, IFormatProvider provider) Parameters value float provider IFormatProvider Returns string ToString(string) public static string ToString(string value) Parameters value string Returns string ToString(string, IFormatProvider) public static string ToString(string value, IFormatProvider provider) Parameters value string provider IFormatProvider Returns string ToString(ushort) public static string ToString(ushort value) Parameters value ushort Returns string ToString(ushort, IFormatProvider) public static string ToString(ushort value, IFormatProvider provider) Parameters value ushort provider IFormatProvider Returns string ToString(uint) public static string ToString(uint value) Parameters value uint Returns string ToString(uint, IFormatProvider) public static string ToString(uint value, IFormatProvider provider) Parameters value uint provider IFormatProvider Returns string ToString(ulong) public static string ToString(ulong value) Parameters value ulong Returns string ToString(ulong, IFormatProvider) public static string ToString(ulong value, IFormatProvider provider) Parameters value ulong provider IFormatProvider Returns string ToUInt16(NDArray) public static ushort ToUInt16(NDArray nd) Parameters nd NDArray Returns ushort ToUInt16(bool) public static ushort ToUInt16(bool value) Parameters value bool Returns ushort ToUInt16(byte) public static ushort ToUInt16(byte value) Parameters value byte Returns ushort ToUInt16(char) public static ushort ToUInt16(char value) Parameters value char Returns ushort ToUInt16(DateTime) public static ushort ToUInt16(DateTime value) Parameters value DateTime Returns ushort ToUInt16(decimal) public static ushort ToUInt16(decimal value) Parameters value decimal Returns ushort ToUInt16(double) public static ushort ToUInt16(double value) Parameters value double Returns ushort ToUInt16(short) public static ushort ToUInt16(short value) Parameters value short Returns ushort ToUInt16(int) public static ushort ToUInt16(int value) Parameters value int Returns ushort ToUInt16(long) public static ushort ToUInt16(long value) Parameters value long Returns ushort ToUInt16(object) public static ushort ToUInt16(object value) Parameters value object Returns ushort ToUInt16(object, IFormatProvider) public static ushort ToUInt16(object value, IFormatProvider provider) Parameters value object provider IFormatProvider Returns ushort ToUInt16(sbyte) public static ushort ToUInt16(sbyte value) Parameters value sbyte Returns ushort ToUInt16(float) public static ushort ToUInt16(float value) Parameters value float Returns ushort ToUInt16(string) public static ushort ToUInt16(string value) Parameters value string Returns ushort ToUInt16(string, IFormatProvider) public static ushort ToUInt16(string value, IFormatProvider provider) Parameters value string provider IFormatProvider Returns ushort ToUInt16(ushort) public static ushort ToUInt16(ushort value) Parameters value ushort Returns ushort ToUInt16(uint) public static ushort ToUInt16(uint value) Parameters value uint Returns ushort ToUInt16(ulong) public static ushort ToUInt16(ulong value) Parameters value ulong Returns ushort ToUInt32(NDArray) public static uint ToUInt32(NDArray nd) Parameters nd NDArray Returns uint ToUInt32(bool) public static uint ToUInt32(bool value) Parameters value bool Returns uint ToUInt32(byte) public static uint ToUInt32(byte value) Parameters value byte Returns uint ToUInt32(char) public static uint ToUInt32(char value) Parameters value char Returns uint ToUInt32(DateTime) public static uint ToUInt32(DateTime value) Parameters value DateTime Returns uint ToUInt32(decimal) public static uint ToUInt32(decimal value) Parameters value decimal Returns uint ToUInt32(double) public static uint ToUInt32(double value) Parameters value double Returns uint ToUInt32(short) public static uint ToUInt32(short value) Parameters value short Returns uint ToUInt32(int) public static uint ToUInt32(int value) Parameters value int Returns uint ToUInt32(long) public static uint ToUInt32(long value) Parameters value long Returns uint ToUInt32(object) public static uint ToUInt32(object value) Parameters value object Returns uint ToUInt32(object, IFormatProvider) public static uint ToUInt32(object value, IFormatProvider provider) Parameters value object provider IFormatProvider Returns uint ToUInt32(sbyte) public static uint ToUInt32(sbyte value) Parameters value sbyte Returns uint ToUInt32(float) public static uint ToUInt32(float value) Parameters value float Returns uint ToUInt32(string) public static uint ToUInt32(string value) Parameters value string Returns uint ToUInt32(string, IFormatProvider) public static uint ToUInt32(string value, IFormatProvider provider) Parameters value string provider IFormatProvider Returns uint ToUInt32(ushort) public static uint ToUInt32(ushort value) Parameters value ushort Returns uint ToUInt32(uint) public static uint ToUInt32(uint value) Parameters value uint Returns uint ToUInt32(ulong) public static uint ToUInt32(ulong value) Parameters value ulong Returns uint ToUInt64(NDArray) public static ulong ToUInt64(NDArray nd) Parameters nd NDArray Returns ulong ToUInt64(bool) public static ulong ToUInt64(bool value) Parameters value bool Returns ulong ToUInt64(byte) public static ulong ToUInt64(byte value) Parameters value byte Returns ulong ToUInt64(char) public static ulong ToUInt64(char value) Parameters value char Returns ulong ToUInt64(DateTime) public static ulong ToUInt64(DateTime value) Parameters value DateTime Returns ulong ToUInt64(decimal) public static ulong ToUInt64(decimal value) Parameters value decimal Returns ulong ToUInt64(double) public static ulong ToUInt64(double value) Parameters value double Returns ulong ToUInt64(short) public static ulong ToUInt64(short value) Parameters value short Returns ulong ToUInt64(int) public static ulong ToUInt64(int value) Parameters value int Returns ulong ToUInt64(long) public static ulong ToUInt64(long value) Parameters value long Returns ulong ToUInt64(object) public static ulong ToUInt64(object value) Parameters value object Returns ulong ToUInt64(object, IFormatProvider) public static ulong ToUInt64(object value, IFormatProvider provider) Parameters value object provider IFormatProvider Returns ulong ToUInt64(sbyte) public static ulong ToUInt64(sbyte value) Parameters value sbyte Returns ulong ToUInt64(float) public static ulong ToUInt64(float value) Parameters value float Returns ulong ToUInt64(string) public static ulong ToUInt64(string value) Parameters value string Returns ulong ToUInt64(string, IFormatProvider) public static ulong ToUInt64(string value, IFormatProvider provider) Parameters value string provider IFormatProvider Returns ulong ToUInt64(ushort) public static ulong ToUInt64(ushort value) Parameters value ushort Returns ulong ToUInt64(uint) public static ulong ToUInt64(uint value) Parameters value uint Returns ulong ToUInt64(ulong) public static ulong ToUInt64(ulong value) Parameters value ulong Returns ulong" + }, + "api/NumSharp.Utilities.Hashset-1.Enumerator.html": { + "href": "api/NumSharp.Utilities.Hashset-1.Enumerator.html", + "title": "Struct Hashset.Enumerator | NumSharp Documentation", + "summary": "Struct Hashset.Enumerator Namespace NumSharp.Utilities Assembly NumSharp.dll public struct Hashset.Enumerator : IEnumerator, IDisposable, IEnumerator Implements IEnumerator IDisposable IEnumerator Inherited Members ValueType.Equals(object) ValueType.GetHashCode() ValueType.ToString() object.Equals(object, object) object.GetType() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) IEnumeratorExtensions.ToIEnumerable(IEnumerator) Properties Current Gets the element in the collection at the current position of the enumerator. public T Current { get; } Property Value T The element in the collection at the current position of the enumerator. Methods Dispose() Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. public void Dispose() MoveNext() Advances the enumerator to the next element of the collection. public bool MoveNext() Returns bool true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection. Exceptions InvalidOperationException The collection was modified after the enumerator was created." + }, + "api/NumSharp.Utilities.Hashset-1.html": { + "href": "api/NumSharp.Utilities.Hashset-1.html", + "title": "Class Hashset | NumSharp Documentation", + "summary": "Class Hashset Namespace NumSharp.Utilities Assembly NumSharp.dll [SuppressMessage(\"Microsoft.Naming\", \"CA1710:IdentifiersShouldHaveCorrectSuffix\", Justification = \"By design\")] public class Hashset : ISet, ICollection, IReadOnlyCollection, IEnumerable, IEnumerable Type Parameters T Inheritance object Hashset Implements ISet ICollection IReadOnlyCollection IEnumerable IEnumerable Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Constructors Hashset() public Hashset() Hashset(IEnumerable) public Hashset(IEnumerable collection) Parameters collection IEnumerable Hashset(IEnumerable, IEqualityComparer) Implementation Notes: Since resizes are relatively expensive (require rehashing), this attempts to minimize the need to resize by setting the initial capacity based on size of collection. public Hashset(IEnumerable collection, IEqualityComparer comparer) Parameters collection IEnumerable comparer IEqualityComparer Hashset(IEqualityComparer) public Hashset(IEqualityComparer comparer) Parameters comparer IEqualityComparer Hashset(int) public Hashset(int capacity) Parameters capacity int Hashset(int, IEqualityComparer) public Hashset(int capacity, IEqualityComparer comparer) Parameters capacity int comparer IEqualityComparer Properties Comparer Gets the IEqualityComparer that is used to determine equality of keys for the HashSet. public IEqualityComparer Comparer { get; } Property Value IEqualityComparer Count Number of elements in this hashset public int Count { get; } Property Value int Methods Add(T) Add item to this HashSet. Returns bool indicating whether item was added (won't be added if already present) public bool Add(T item) Parameters item T Returns bool true if added, false if already present Clear() Remove all items from this set. This clears the elements but not the underlying buckets and slots array. Follow this call by TrimExcess to release these. public void Clear() Contains(T) Checks if this hashset contains the item public bool Contains(T item) Parameters item T item to check for containment Returns bool true if item contained; false if not CopyTo(T[]) public void CopyTo(T[] array) Parameters array T[] CopyTo(T[], int) Copy items in this hashset to array, starting at arrayIndex public void CopyTo(T[] array, int arrayIndex) Parameters array T[] array to add items to arrayIndex int index to start at CopyTo(T[], int, int) public void CopyTo(T[] array, int arrayIndex, int count) Parameters array T[] arrayIndex int count int CopyTo(Hashset, ArraySlice) public static void CopyTo(Hashset src, ArraySlice array) where T : unmanaged Parameters src Hashset array ArraySlice Type Parameters T CopyTo(Hashset, ArraySlice, int, int) public static void CopyTo(Hashset src, ArraySlice array, int arrayIndex, int count) where T : unmanaged Parameters src Hashset array ArraySlice arrayIndex int count int Type Parameters T CreateSetComparer() Used for deep equality of HashSet testing public static IEqualityComparer> CreateSetComparer() Returns IEqualityComparer> ExceptWith(IEnumerable) Remove items in other from this set. Modifies this set. public void ExceptWith(IEnumerable other) Parameters other IEnumerable enumerable with items to remove GetEnumerator() public Hashset.Enumerator GetEnumerator() Returns Hashset.Enumerator IntersectWith(IEnumerable) Takes the intersection of this set with other. Modifies this set. Implementation Notes: We get better perf if other is a hashset using same equality comparer, because we get constant contains check in other. Resulting cost is O(n1) to iterate over this. If we can't go above route, iterate over the other and mark intersection by checking contains in this. Then loop over and delete any unmarked elements. Total cost is n2+n1. Attempts to return early based on counts alone, using the property that the intersection of anything with the empty set is the empty set. public void IntersectWith(IEnumerable other) Parameters other IEnumerable enumerable with items to add IsProperSubsetOf(IEnumerable) Checks if this is a proper subset of other (i.e. strictly contained in) Implementation Notes: The following properties are used up-front to avoid element-wise checks: If this is the empty set, then it's a proper subset of a set that contains at least one element, but it's not a proper subset of the empty set. If other has unique elements according to this equality comparer, and this has >= the number of elements in other, then this can't be a proper subset. Furthermore, if other is a hashset using the same equality comparer, we can use a faster element-wise check. public bool IsProperSubsetOf(IEnumerable other) Parameters other IEnumerable Returns bool true if this is a proper subset of other; false if not IsProperSupersetOf(IEnumerable) Checks if this is a proper superset of other (i.e. other strictly contained in this) Implementation Notes: This is slightly more complicated than above because we have to keep track if there was at least one element not contained in other. The following properties are used up-front to avoid element-wise checks: If this is the empty set, then it can't be a proper superset of any set, even if other is the empty set. If other is an empty set and this contains at least 1 element, then this is a proper superset. If other has unique elements according to this equality comparer, and other's count is greater than or equal to this count, then this can't be a proper superset Furthermore, if other has unique elements according to this equality comparer, we can use a faster element-wise check. public bool IsProperSupersetOf(IEnumerable other) Parameters other IEnumerable Returns bool true if this is a proper superset of other; false if not IsSubsetOf(IEnumerable) Checks if this is a subset of other. Implementation Notes: The following properties are used up-front to avoid element-wise checks: If this is the empty set, then it's a subset of anything, including the empty set If other has unique elements according to this equality comparer, and this has more elements than other, then it can't be a subset. Furthermore, if other is a hashset using the same equality comparer, we can use a faster element-wise check. public bool IsSubsetOf(IEnumerable other) Parameters other IEnumerable Returns bool true if this is a subset of other; false if not IsSupersetOf(IEnumerable) Checks if this is a superset of other Implementation Notes: The following properties are used up-front to avoid element-wise checks: If other has no elements (it's the empty set), then this is a superset, even if this is also the empty set. If other has unique elements according to this equality comparer, and this has less than the number of elements in other, then this can't be a superset public bool IsSupersetOf(IEnumerable other) Parameters other IEnumerable Returns bool true if this is a superset of other; false if not Overlaps(IEnumerable) Checks if this set overlaps other (i.e. they share at least one item) public bool Overlaps(IEnumerable other) Parameters other IEnumerable Returns bool true if these have at least one common element; false if disjoint Remove(T) Remove item from this hashset public bool Remove(T item) Parameters item T item to remove Returns bool true if removed; false if not (i.e. if the item wasn't in the HashSet) RemoveWhere(Predicate) Remove elements that match specified predicate. Returns the number of elements removed public int RemoveWhere(Predicate match) Parameters match Predicate Returns int SetEquals(IEnumerable) Checks if this and other contain the same elements. This is set equality: duplicates and order are ignored public bool SetEquals(IEnumerable other) Parameters other IEnumerable Returns bool SymmetricExceptWith(IEnumerable) Takes symmetric difference (XOR) with other and this set. Modifies this set. public void SymmetricExceptWith(IEnumerable other) Parameters other IEnumerable enumerable with items to XOR TrimExcess() Sets the capacity of this list to the size of the list (rounded up to nearest prime), unless count is 0, in which case we release references. This method can be used to minimize a list's memory overhead once it is known that no new elements will be added to the list. To completely clear a list and release all memory referenced by the list, execute the following statements: list.Clear(); list.TrimExcess(); public void TrimExcess() TryGetValue(T, out T) Searches the set for a given value and returns the equal value it finds, if any. public bool TryGetValue(T equalValue, out T actualValue) Parameters equalValue T The value to search for. actualValue T The value from the set that the search found, or the default value of T when the search yielded no match. Returns bool A value indicating whether the search was successful. Remarks This can be useful when you want to reuse a previously stored reference instead of a newly constructed one (so that more sharing of references can occur) or to look up a value that has more complete data than the value you currently have, although their comparer functions indicate they are equal. UnionWith(IEnumerable) Take the union of this HashSet with other. Modifies this set. Implementation note: GetSuggestedCapacity (to increase capacity in advance avoiding multiple resizes ended up not being useful in practice; quickly gets to the point where it's a wasteful check. public void UnionWith(IEnumerable other) Parameters other IEnumerable enumerable with items to add" + }, + "api/NumSharp.Utilities.InfoOf-1.html": { + "href": "api/NumSharp.Utilities.InfoOf-1.html", + "title": "Class InfoOf | NumSharp Documentation", + "summary": "Class InfoOf Namespace NumSharp.Utilities Assembly NumSharp.dll Provides a cache for properties of T that requires computation. [SuppressMessage(\"ReSharper\", \"StaticMemberInGenericType\")] public class InfoOf Type Parameters T Inheritance object InfoOf Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Fields MaxValue public static readonly T MaxValue Field Value T MinValue public static readonly T MinValue Field Value T NPTypeCode public static readonly NPTypeCode NPTypeCode Field Value NPTypeCode Size public static readonly int Size Field Value int Zero public static readonly T Zero Field Value T" + }, + "api/NumSharp.Utilities.Linq.IEnumeratorExtensions.html": { + "href": "api/NumSharp.Utilities.Linq.IEnumeratorExtensions.html", + "title": "Class IEnumeratorExtensions | NumSharp Documentation", + "summary": "Class IEnumeratorExtensions Namespace NumSharp.Utilities.Linq Assembly NumSharp.dll public static class IEnumeratorExtensions Inheritance object IEnumeratorExtensions Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Methods ToIEnumerable(IEnumerator) Turns IEnumerator to an IEnumerable. public static IEnumerable ToIEnumerable(this IEnumerator enumerator) Parameters enumerator IEnumerator Returns IEnumerable Type Parameters T" + }, + "api/NumSharp.Utilities.Linq.IExtremaEnumerable-1.html": { + "href": "api/NumSharp.Utilities.Linq.IExtremaEnumerable-1.html", + "title": "Interface IExtremaEnumerable | NumSharp Documentation", + "summary": "Interface IExtremaEnumerable Namespace NumSharp.Utilities.Linq Assembly NumSharp.dll Exposes the enumerator, which supports iteration over a sequence of some extremum property (maximum or minimum) of a specified type. public interface IExtremaEnumerable : IEnumerable, IEnumerable Type Parameters T The type of objects to enumerate. Inherited Members IEnumerable.GetEnumerator() Extension Methods LinqExtensions.Yield(T) Methods Take(int) Returns a specified number of contiguous elements from the start of the sequence. IEnumerable Take(int count) Parameters count int The number of elements to return. Returns IEnumerable An IEnumerable that contains the specified number of elements from the start of the input sequence. TakeLast(int) Returns a specified number of contiguous elements at the end of the sequence. IEnumerable TakeLast(int count) Parameters count int The number of elements to return. Returns IEnumerable An IEnumerable that contains the specified number of elements at the end of the input sequence." + }, + "api/NumSharp.Utilities.Linq.html": { + "href": "api/NumSharp.Utilities.Linq.html", + "title": "Namespace NumSharp.Utilities.Linq | NumSharp Documentation", + "summary": "Namespace NumSharp.Utilities.Linq Classes IEnumeratorExtensions Interfaces IExtremaEnumerable Exposes the enumerator, which supports iteration over a sequence of some extremum property (maximum or minimum) of a specified type." + }, + "api/NumSharp.Utilities.NDCoordinatesAxisIncrementor.html": { + "href": "api/NumSharp.Utilities.NDCoordinatesAxisIncrementor.html", + "title": "Class NDCoordinatesAxisIncrementor | NumSharp Documentation", + "summary": "Class NDCoordinatesAxisIncrementor Namespace NumSharp.Utilities Assembly NumSharp.dll public class NDCoordinatesAxisIncrementor Inheritance object NDCoordinatesAxisIncrementor Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Constructors NDCoordinatesAxisIncrementor(ref Shape, int) public NDCoordinatesAxisIncrementor(ref Shape shape, int axis) Parameters shape Shape axis int NDCoordinatesAxisIncrementor(ref Shape, int, Action) public NDCoordinatesAxisIncrementor(ref Shape shape, int axis, Action endCallback) Parameters shape Shape axis int endCallback Action NDCoordinatesAxisIncrementor(int[], int) public NDCoordinatesAxisIncrementor(int[] dims, int axis) Parameters dims int[] axis int NDCoordinatesAxisIncrementor(int[], int, Action) public NDCoordinatesAxisIncrementor(int[] dims, int axis, Action endCallback) Parameters dims int[] axis int endCallback Action Fields Axis public int Axis Field Value int Index public readonly int[] Index Field Value int[] Slices public readonly Slice[] Slices Field Value Slice[] Methods Next() public Slice[] Next() Returns Slice[] Reset() public void Reset()" + }, + "api/NumSharp.Utilities.NDCoordinatesIncrementor.html": { + "href": "api/NumSharp.Utilities.NDCoordinatesIncrementor.html", + "title": "Class NDCoordinatesIncrementor | NumSharp Documentation", + "summary": "Class NDCoordinatesIncrementor Namespace NumSharp.Utilities Assembly NumSharp.dll public class NDCoordinatesIncrementor Inheritance object NDCoordinatesIncrementor Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Constructors NDCoordinatesIncrementor(ref Shape) Initializes a new instance of the object class. public NDCoordinatesIncrementor(ref Shape shape) Parameters shape Shape NDCoordinatesIncrementor(ref Shape, Action) public NDCoordinatesIncrementor(ref Shape shape, Action endCallback) Parameters shape Shape endCallback Action NDCoordinatesIncrementor(int[]) public NDCoordinatesIncrementor(int[] dims) Parameters dims int[] NDCoordinatesIncrementor(int[], Action) public NDCoordinatesIncrementor(int[] dims, Action endCallback) Parameters dims int[] endCallback Action Fields Index public readonly int[] Index Field Value int[] Methods Next() public int[] Next() Returns int[] Reset() public void Reset()" + }, + "api/NumSharp.Utilities.NDCoordinatesIncrementorAutoResetting.html": { + "href": "api/NumSharp.Utilities.NDCoordinatesIncrementorAutoResetting.html", + "title": "Class NDCoordinatesIncrementorAutoResetting | NumSharp Documentation", + "summary": "Class NDCoordinatesIncrementorAutoResetting Namespace NumSharp.Utilities Assembly NumSharp.dll public class NDCoordinatesIncrementorAutoResetting Inheritance object NDCoordinatesIncrementorAutoResetting Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Constructors NDCoordinatesIncrementorAutoResetting(ref Shape) Initializes a new instance of the object class. public NDCoordinatesIncrementorAutoResetting(ref Shape shape) Parameters shape Shape NDCoordinatesIncrementorAutoResetting(int[]) public NDCoordinatesIncrementorAutoResetting(int[] dims) Parameters dims int[] Fields Index public readonly int[] Index Field Value int[] Methods Next() public int[] Next() Returns int[] Reset() public void Reset()" + }, + "api/NumSharp.Utilities.NDCoordinatesLeftToAxisIncrementor.html": { + "href": "api/NumSharp.Utilities.NDCoordinatesLeftToAxisIncrementor.html", + "title": "Class NDCoordinatesLeftToAxisIncrementor | NumSharp Documentation", + "summary": "Class NDCoordinatesLeftToAxisIncrementor Namespace NumSharp.Utilities Assembly NumSharp.dll public class NDCoordinatesLeftToAxisIncrementor Inheritance object NDCoordinatesLeftToAxisIncrementor Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Constructors NDCoordinatesLeftToAxisIncrementor(ref Shape, int) public NDCoordinatesLeftToAxisIncrementor(ref Shape shape, int axis) Parameters shape Shape axis int NDCoordinatesLeftToAxisIncrementor(ref Shape, int, Action) public NDCoordinatesLeftToAxisIncrementor(ref Shape shape, int axis, Action endCallback) Parameters shape Shape axis int endCallback Action Fields Axis public int Axis Field Value int Index public readonly int[] Index Field Value int[] Slices public readonly Slice[] Slices Field Value Slice[] Methods Next() public Slice[] Next() Returns Slice[] Reset() public void Reset()" + }, + "api/NumSharp.Utilities.NDExtendedCoordinatesIncrementor.html": { + "href": "api/NumSharp.Utilities.NDExtendedCoordinatesIncrementor.html", + "title": "Class NDExtendedCoordinatesIncrementor | NumSharp Documentation", + "summary": "Class NDExtendedCoordinatesIncrementor Namespace NumSharp.Utilities Assembly NumSharp.dll public class NDExtendedCoordinatesIncrementor Inheritance object NDExtendedCoordinatesIncrementor Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Constructors NDExtendedCoordinatesIncrementor(Shape, int, Action) public NDExtendedCoordinatesIncrementor(Shape shape, int extendBy, Action endCallback = null) Parameters shape Shape extendBy int By how many items should Index be extended endCallback Action NDExtendedCoordinatesIncrementor(int[], int, Action) public NDExtendedCoordinatesIncrementor(int[] dims, int extendBy, Action endCallback = null) Parameters dims int[] The dims has to be not extended, use Resize(ref T[], int) if it already extended extendBy int By how many items should Index be extended endCallback Action Fields Index public int[] Index Field Value int[] Properties ResetEntireArray public bool ResetEntireArray { get; set; } Property Value bool Methods Next() public int[] Next() Returns int[] Next(params int[]) public int[] Next(params int[] extendedIndices) Parameters extendedIndices int[] Returns int[] Reset() public void Reset()" + }, + "api/NumSharp.Utilities.NDOffsetIncrementor.html": { + "href": "api/NumSharp.Utilities.NDOffsetIncrementor.html", + "title": "Class NDOffsetIncrementor | NumSharp Documentation", + "summary": "Class NDOffsetIncrementor Namespace NumSharp.Utilities Assembly NumSharp.dll public class NDOffsetIncrementor Inheritance object NDOffsetIncrementor Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Constructors NDOffsetIncrementor(Shape) public NDOffsetIncrementor(Shape shape) Parameters shape Shape NDOffsetIncrementor(int[]) public NDOffsetIncrementor(int[] dims) Parameters dims int[] Properties HasNext public bool HasNext { get; } Property Value bool Methods Next() public int Next() Returns int Reset() public void Reset()" + }, + "api/NumSharp.Utilities.NDOffsetIncrementorAutoresetting.html": { + "href": "api/NumSharp.Utilities.NDOffsetIncrementorAutoresetting.html", + "title": "Class NDOffsetIncrementorAutoresetting | NumSharp Documentation", + "summary": "Class NDOffsetIncrementorAutoresetting Namespace NumSharp.Utilities Assembly NumSharp.dll public class NDOffsetIncrementorAutoresetting Inheritance object NDOffsetIncrementorAutoresetting Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Constructors NDOffsetIncrementorAutoresetting(Shape) public NDOffsetIncrementorAutoresetting(Shape shape) Parameters shape Shape NDOffsetIncrementorAutoresetting(int[]) public NDOffsetIncrementorAutoresetting(int[] dims) Parameters dims int[] Properties HasNext public bool HasNext { get; } Property Value bool Methods Next() public int Next() Returns int Reset() public void Reset()" + }, + "api/NumSharp.Utilities.NonGenericConvert.html": { + "href": "api/NumSharp.Utilities.NonGenericConvert.html", + "title": "Class NonGenericConvert | NumSharp Documentation", + "summary": "Class NonGenericConvert Namespace NumSharp.Utilities Assembly NumSharp.dll Provides a way to convert boxed object from known time to specific type. public static class NonGenericConvert Inheritance object NonGenericConvert Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Methods FromBooleanToByte(object) Convert from Boolean to Byte when input is a boxed non-generic object. public static byte FromBooleanToByte(object input) Parameters input object The object that will be casted to bool and then converted to byte Returns byte Byte FromBooleanToChar(object) Convert from Boolean to Char when input is a boxed non-generic object. public static char FromBooleanToChar(object input) Parameters input object The object that will be casted to bool and then converted to char Returns char Char FromBooleanToDecimal(object) Convert from Boolean to Decimal when input is a boxed non-generic object. public static decimal FromBooleanToDecimal(object input) Parameters input object The object that will be casted to bool and then converted to decimal Returns decimal Decimal FromBooleanToDouble(object) Convert from Boolean to Double when input is a boxed non-generic object. public static double FromBooleanToDouble(object input) Parameters input object The object that will be casted to bool and then converted to double Returns double Double FromBooleanToInt16(object) Convert from Boolean to Int16 when input is a boxed non-generic object. public static short FromBooleanToInt16(object input) Parameters input object The object that will be casted to bool and then converted to short Returns short Int16 FromBooleanToInt32(object) Convert from Boolean to Int32 when input is a boxed non-generic object. public static int FromBooleanToInt32(object input) Parameters input object The object that will be casted to bool and then converted to int Returns int Int32 FromBooleanToInt64(object) Convert from Boolean to Int64 when input is a boxed non-generic object. public static long FromBooleanToInt64(object input) Parameters input object The object that will be casted to bool and then converted to long Returns long Int64 FromBooleanToSingle(object) Convert from Boolean to Single when input is a boxed non-generic object. public static float FromBooleanToSingle(object input) Parameters input object The object that will be casted to bool and then converted to float Returns float Single FromBooleanToString(object) Convert from Boolean to String when input is a boxed non-generic object. public static string FromBooleanToString(object input) Parameters input object The object that will be casted to bool and then converted to string Returns string String FromBooleanToUInt16(object) Convert from Boolean to UInt16 when input is a boxed non-generic object. public static ushort FromBooleanToUInt16(object input) Parameters input object The object that will be casted to bool and then converted to ushort Returns ushort UInt16 FromBooleanToUInt32(object) Convert from Boolean to UInt32 when input is a boxed non-generic object. public static uint FromBooleanToUInt32(object input) Parameters input object The object that will be casted to bool and then converted to uint Returns uint UInt32 FromBooleanToUInt64(object) Convert from Boolean to UInt64 when input is a boxed non-generic object. public static ulong FromBooleanToUInt64(object input) Parameters input object The object that will be casted to bool and then converted to ulong Returns ulong UInt64 FromByteToBoolean(object) Convert from Byte to Boolean when input is a boxed non-generic object. public static bool FromByteToBoolean(object input) Parameters input object The object that will be casted to byte and then converted to bool Returns bool Boolean FromByteToChar(object) Convert from Byte to Char when input is a boxed non-generic object. public static char FromByteToChar(object input) Parameters input object The object that will be casted to byte and then converted to char Returns char Char FromByteToDecimal(object) Convert from Byte to Decimal when input is a boxed non-generic object. public static decimal FromByteToDecimal(object input) Parameters input object The object that will be casted to byte and then converted to decimal Returns decimal Decimal FromByteToDouble(object) Convert from Byte to Double when input is a boxed non-generic object. public static double FromByteToDouble(object input) Parameters input object The object that will be casted to byte and then converted to double Returns double Double FromByteToInt16(object) Convert from Byte to Int16 when input is a boxed non-generic object. public static short FromByteToInt16(object input) Parameters input object The object that will be casted to byte and then converted to short Returns short Int16 FromByteToInt32(object) Convert from Byte to Int32 when input is a boxed non-generic object. public static int FromByteToInt32(object input) Parameters input object The object that will be casted to byte and then converted to int Returns int Int32 FromByteToInt64(object) Convert from Byte to Int64 when input is a boxed non-generic object. public static long FromByteToInt64(object input) Parameters input object The object that will be casted to byte and then converted to long Returns long Int64 FromByteToSingle(object) Convert from Byte to Single when input is a boxed non-generic object. public static float FromByteToSingle(object input) Parameters input object The object that will be casted to byte and then converted to float Returns float Single FromByteToString(object) Convert from Byte to String when input is a boxed non-generic object. public static string FromByteToString(object input) Parameters input object The object that will be casted to byte and then converted to string Returns string String FromByteToUInt16(object) Convert from Byte to UInt16 when input is a boxed non-generic object. public static ushort FromByteToUInt16(object input) Parameters input object The object that will be casted to byte and then converted to ushort Returns ushort UInt16 FromByteToUInt32(object) Convert from Byte to UInt32 when input is a boxed non-generic object. public static uint FromByteToUInt32(object input) Parameters input object The object that will be casted to byte and then converted to uint Returns uint UInt32 FromByteToUInt64(object) Convert from Byte to UInt64 when input is a boxed non-generic object. public static ulong FromByteToUInt64(object input) Parameters input object The object that will be casted to byte and then converted to ulong Returns ulong UInt64 FromCharToBoolean(object) Convert from Char to Boolean when input is a boxed non-generic object. public static bool FromCharToBoolean(object input) Parameters input object The object that will be casted to char and then converted to bool Returns bool Boolean FromCharToByte(object) Convert from Char to Byte when input is a boxed non-generic object. public static byte FromCharToByte(object input) Parameters input object The object that will be casted to char and then converted to byte Returns byte Byte FromCharToDecimal(object) Convert from Char to Decimal when input is a boxed non-generic object. public static decimal FromCharToDecimal(object input) Parameters input object The object that will be casted to char and then converted to decimal Returns decimal Decimal FromCharToDouble(object) Convert from Char to Double when input is a boxed non-generic object. public static double FromCharToDouble(object input) Parameters input object The object that will be casted to char and then converted to double Returns double Double FromCharToInt16(object) Convert from Char to Int16 when input is a boxed non-generic object. public static short FromCharToInt16(object input) Parameters input object The object that will be casted to char and then converted to short Returns short Int16 FromCharToInt32(object) Convert from Char to Int32 when input is a boxed non-generic object. public static int FromCharToInt32(object input) Parameters input object The object that will be casted to char and then converted to int Returns int Int32 FromCharToInt64(object) Convert from Char to Int64 when input is a boxed non-generic object. public static long FromCharToInt64(object input) Parameters input object The object that will be casted to char and then converted to long Returns long Int64 FromCharToSingle(object) Convert from Char to Single when input is a boxed non-generic object. public static float FromCharToSingle(object input) Parameters input object The object that will be casted to char and then converted to float Returns float Single FromCharToString(object) Convert from Char to String when input is a boxed non-generic object. public static string FromCharToString(object input) Parameters input object The object that will be casted to char and then converted to string Returns string String FromCharToUInt16(object) Convert from Char to UInt16 when input is a boxed non-generic object. public static ushort FromCharToUInt16(object input) Parameters input object The object that will be casted to char and then converted to ushort Returns ushort UInt16 FromCharToUInt32(object) Convert from Char to UInt32 when input is a boxed non-generic object. public static uint FromCharToUInt32(object input) Parameters input object The object that will be casted to char and then converted to uint Returns uint UInt32 FromCharToUInt64(object) Convert from Char to UInt64 when input is a boxed non-generic object. public static ulong FromCharToUInt64(object input) Parameters input object The object that will be casted to char and then converted to ulong Returns ulong UInt64 FromDecimalToBoolean(object) Convert from Decimal to Boolean when input is a boxed non-generic object. public static bool FromDecimalToBoolean(object input) Parameters input object The object that will be casted to decimal and then converted to bool Returns bool Boolean FromDecimalToByte(object) Convert from Decimal to Byte when input is a boxed non-generic object. public static byte FromDecimalToByte(object input) Parameters input object The object that will be casted to decimal and then converted to byte Returns byte Byte FromDecimalToChar(object) Convert from Decimal to Char when input is a boxed non-generic object. public static char FromDecimalToChar(object input) Parameters input object The object that will be casted to decimal and then converted to char Returns char Char FromDecimalToDouble(object) Convert from Decimal to Double when input is a boxed non-generic object. public static double FromDecimalToDouble(object input) Parameters input object The object that will be casted to decimal and then converted to double Returns double Double FromDecimalToInt16(object) Convert from Decimal to Int16 when input is a boxed non-generic object. public static short FromDecimalToInt16(object input) Parameters input object The object that will be casted to decimal and then converted to short Returns short Int16 FromDecimalToInt32(object) Convert from Decimal to Int32 when input is a boxed non-generic object. public static int FromDecimalToInt32(object input) Parameters input object The object that will be casted to decimal and then converted to int Returns int Int32 FromDecimalToInt64(object) Convert from Decimal to Int64 when input is a boxed non-generic object. public static long FromDecimalToInt64(object input) Parameters input object The object that will be casted to decimal and then converted to long Returns long Int64 FromDecimalToSingle(object) Convert from Decimal to Single when input is a boxed non-generic object. public static float FromDecimalToSingle(object input) Parameters input object The object that will be casted to decimal and then converted to float Returns float Single FromDecimalToString(object) Convert from Decimal to String when input is a boxed non-generic object. public static string FromDecimalToString(object input) Parameters input object The object that will be casted to decimal and then converted to string Returns string String FromDecimalToUInt16(object) Convert from Decimal to UInt16 when input is a boxed non-generic object. public static ushort FromDecimalToUInt16(object input) Parameters input object The object that will be casted to decimal and then converted to ushort Returns ushort UInt16 FromDecimalToUInt32(object) Convert from Decimal to UInt32 when input is a boxed non-generic object. public static uint FromDecimalToUInt32(object input) Parameters input object The object that will be casted to decimal and then converted to uint Returns uint UInt32 FromDecimalToUInt64(object) Convert from Decimal to UInt64 when input is a boxed non-generic object. public static ulong FromDecimalToUInt64(object input) Parameters input object The object that will be casted to decimal and then converted to ulong Returns ulong UInt64 FromDoubleToBoolean(object) Convert from Double to Boolean when input is a boxed non-generic object. public static bool FromDoubleToBoolean(object input) Parameters input object The object that will be casted to double and then converted to bool Returns bool Boolean FromDoubleToByte(object) Convert from Double to Byte when input is a boxed non-generic object. public static byte FromDoubleToByte(object input) Parameters input object The object that will be casted to double and then converted to byte Returns byte Byte FromDoubleToChar(object) Convert from Double to Char when input is a boxed non-generic object. public static char FromDoubleToChar(object input) Parameters input object The object that will be casted to double and then converted to char Returns char Char FromDoubleToDecimal(object) Convert from Double to Decimal when input is a boxed non-generic object. public static decimal FromDoubleToDecimal(object input) Parameters input object The object that will be casted to double and then converted to decimal Returns decimal Decimal FromDoubleToInt16(object) Convert from Double to Int16 when input is a boxed non-generic object. public static short FromDoubleToInt16(object input) Parameters input object The object that will be casted to double and then converted to short Returns short Int16 FromDoubleToInt32(object) Convert from Double to Int32 when input is a boxed non-generic object. public static int FromDoubleToInt32(object input) Parameters input object The object that will be casted to double and then converted to int Returns int Int32 FromDoubleToInt64(object) Convert from Double to Int64 when input is a boxed non-generic object. public static long FromDoubleToInt64(object input) Parameters input object The object that will be casted to double and then converted to long Returns long Int64 FromDoubleToSingle(object) Convert from Double to Single when input is a boxed non-generic object. public static float FromDoubleToSingle(object input) Parameters input object The object that will be casted to double and then converted to float Returns float Single FromDoubleToString(object) Convert from Double to String when input is a boxed non-generic object. public static string FromDoubleToString(object input) Parameters input object The object that will be casted to double and then converted to string Returns string String FromDoubleToUInt16(object) Convert from Double to UInt16 when input is a boxed non-generic object. public static ushort FromDoubleToUInt16(object input) Parameters input object The object that will be casted to double and then converted to ushort Returns ushort UInt16 FromDoubleToUInt32(object) Convert from Double to UInt32 when input is a boxed non-generic object. public static uint FromDoubleToUInt32(object input) Parameters input object The object that will be casted to double and then converted to uint Returns uint UInt32 FromDoubleToUInt64(object) Convert from Double to UInt64 when input is a boxed non-generic object. public static ulong FromDoubleToUInt64(object input) Parameters input object The object that will be casted to double and then converted to ulong Returns ulong UInt64 FromInt16ToBoolean(object) Convert from Int16 to Boolean when input is a boxed non-generic object. public static bool FromInt16ToBoolean(object input) Parameters input object The object that will be casted to short and then converted to bool Returns bool Boolean FromInt16ToByte(object) Convert from Int16 to Byte when input is a boxed non-generic object. public static byte FromInt16ToByte(object input) Parameters input object The object that will be casted to short and then converted to byte Returns byte Byte FromInt16ToChar(object) Convert from Int16 to Char when input is a boxed non-generic object. public static char FromInt16ToChar(object input) Parameters input object The object that will be casted to short and then converted to char Returns char Char FromInt16ToDecimal(object) Convert from Int16 to Decimal when input is a boxed non-generic object. public static decimal FromInt16ToDecimal(object input) Parameters input object The object that will be casted to short and then converted to decimal Returns decimal Decimal FromInt16ToDouble(object) Convert from Int16 to Double when input is a boxed non-generic object. public static double FromInt16ToDouble(object input) Parameters input object The object that will be casted to short and then converted to double Returns double Double FromInt16ToInt32(object) Convert from Int16 to Int32 when input is a boxed non-generic object. public static int FromInt16ToInt32(object input) Parameters input object The object that will be casted to short and then converted to int Returns int Int32 FromInt16ToInt64(object) Convert from Int16 to Int64 when input is a boxed non-generic object. public static long FromInt16ToInt64(object input) Parameters input object The object that will be casted to short and then converted to long Returns long Int64 FromInt16ToSingle(object) Convert from Int16 to Single when input is a boxed non-generic object. public static float FromInt16ToSingle(object input) Parameters input object The object that will be casted to short and then converted to float Returns float Single FromInt16ToString(object) Convert from Int16 to String when input is a boxed non-generic object. public static string FromInt16ToString(object input) Parameters input object The object that will be casted to short and then converted to string Returns string String FromInt16ToUInt16(object) Convert from Int16 to UInt16 when input is a boxed non-generic object. public static ushort FromInt16ToUInt16(object input) Parameters input object The object that will be casted to short and then converted to ushort Returns ushort UInt16 FromInt16ToUInt32(object) Convert from Int16 to UInt32 when input is a boxed non-generic object. public static uint FromInt16ToUInt32(object input) Parameters input object The object that will be casted to short and then converted to uint Returns uint UInt32 FromInt16ToUInt64(object) Convert from Int16 to UInt64 when input is a boxed non-generic object. public static ulong FromInt16ToUInt64(object input) Parameters input object The object that will be casted to short and then converted to ulong Returns ulong UInt64 FromInt32ToBoolean(object) Convert from Int32 to Boolean when input is a boxed non-generic object. public static bool FromInt32ToBoolean(object input) Parameters input object The object that will be casted to int and then converted to bool Returns bool Boolean FromInt32ToByte(object) Convert from Int32 to Byte when input is a boxed non-generic object. public static byte FromInt32ToByte(object input) Parameters input object The object that will be casted to int and then converted to byte Returns byte Byte FromInt32ToChar(object) Convert from Int32 to Char when input is a boxed non-generic object. public static char FromInt32ToChar(object input) Parameters input object The object that will be casted to int and then converted to char Returns char Char FromInt32ToDecimal(object) Convert from Int32 to Decimal when input is a boxed non-generic object. public static decimal FromInt32ToDecimal(object input) Parameters input object The object that will be casted to int and then converted to decimal Returns decimal Decimal FromInt32ToDouble(object) Convert from Int32 to Double when input is a boxed non-generic object. public static double FromInt32ToDouble(object input) Parameters input object The object that will be casted to int and then converted to double Returns double Double FromInt32ToInt16(object) Convert from Int32 to Int16 when input is a boxed non-generic object. public static short FromInt32ToInt16(object input) Parameters input object The object that will be casted to int and then converted to short Returns short Int16 FromInt32ToInt64(object) Convert from Int32 to Int64 when input is a boxed non-generic object. public static long FromInt32ToInt64(object input) Parameters input object The object that will be casted to int and then converted to long Returns long Int64 FromInt32ToSingle(object) Convert from Int32 to Single when input is a boxed non-generic object. public static float FromInt32ToSingle(object input) Parameters input object The object that will be casted to int and then converted to float Returns float Single FromInt32ToString(object) Convert from Int32 to String when input is a boxed non-generic object. public static string FromInt32ToString(object input) Parameters input object The object that will be casted to int and then converted to string Returns string String FromInt32ToUInt16(object) Convert from Int32 to UInt16 when input is a boxed non-generic object. public static ushort FromInt32ToUInt16(object input) Parameters input object The object that will be casted to int and then converted to ushort Returns ushort UInt16 FromInt32ToUInt32(object) Convert from Int32 to UInt32 when input is a boxed non-generic object. public static uint FromInt32ToUInt32(object input) Parameters input object The object that will be casted to int and then converted to uint Returns uint UInt32 FromInt32ToUInt64(object) Convert from Int32 to UInt64 when input is a boxed non-generic object. public static ulong FromInt32ToUInt64(object input) Parameters input object The object that will be casted to int and then converted to ulong Returns ulong UInt64 FromInt64ToBoolean(object) Convert from Int64 to Boolean when input is a boxed non-generic object. public static bool FromInt64ToBoolean(object input) Parameters input object The object that will be casted to long and then converted to bool Returns bool Boolean FromInt64ToByte(object) Convert from Int64 to Byte when input is a boxed non-generic object. public static byte FromInt64ToByte(object input) Parameters input object The object that will be casted to long and then converted to byte Returns byte Byte FromInt64ToChar(object) Convert from Int64 to Char when input is a boxed non-generic object. public static char FromInt64ToChar(object input) Parameters input object The object that will be casted to long and then converted to char Returns char Char FromInt64ToDecimal(object) Convert from Int64 to Decimal when input is a boxed non-generic object. public static decimal FromInt64ToDecimal(object input) Parameters input object The object that will be casted to long and then converted to decimal Returns decimal Decimal FromInt64ToDouble(object) Convert from Int64 to Double when input is a boxed non-generic object. public static double FromInt64ToDouble(object input) Parameters input object The object that will be casted to long and then converted to double Returns double Double FromInt64ToInt16(object) Convert from Int64 to Int16 when input is a boxed non-generic object. public static short FromInt64ToInt16(object input) Parameters input object The object that will be casted to long and then converted to short Returns short Int16 FromInt64ToInt32(object) Convert from Int64 to Int32 when input is a boxed non-generic object. public static int FromInt64ToInt32(object input) Parameters input object The object that will be casted to long and then converted to int Returns int Int32 FromInt64ToSingle(object) Convert from Int64 to Single when input is a boxed non-generic object. public static float FromInt64ToSingle(object input) Parameters input object The object that will be casted to long and then converted to float Returns float Single FromInt64ToString(object) Convert from Int64 to String when input is a boxed non-generic object. public static string FromInt64ToString(object input) Parameters input object The object that will be casted to long and then converted to string Returns string String FromInt64ToUInt16(object) Convert from Int64 to UInt16 when input is a boxed non-generic object. public static ushort FromInt64ToUInt16(object input) Parameters input object The object that will be casted to long and then converted to ushort Returns ushort UInt16 FromInt64ToUInt32(object) Convert from Int64 to UInt32 when input is a boxed non-generic object. public static uint FromInt64ToUInt32(object input) Parameters input object The object that will be casted to long and then converted to uint Returns uint UInt32 FromInt64ToUInt64(object) Convert from Int64 to UInt64 when input is a boxed non-generic object. public static ulong FromInt64ToUInt64(object input) Parameters input object The object that will be casted to long and then converted to ulong Returns ulong UInt64 FromSingleToBoolean(object) Convert from Single to Boolean when input is a boxed non-generic object. public static bool FromSingleToBoolean(object input) Parameters input object The object that will be casted to float and then converted to bool Returns bool Boolean FromSingleToByte(object) Convert from Single to Byte when input is a boxed non-generic object. public static byte FromSingleToByte(object input) Parameters input object The object that will be casted to float and then converted to byte Returns byte Byte FromSingleToChar(object) Convert from Single to Char when input is a boxed non-generic object. public static char FromSingleToChar(object input) Parameters input object The object that will be casted to float and then converted to char Returns char Char FromSingleToDecimal(object) Convert from Single to Decimal when input is a boxed non-generic object. public static decimal FromSingleToDecimal(object input) Parameters input object The object that will be casted to float and then converted to decimal Returns decimal Decimal FromSingleToDouble(object) Convert from Single to Double when input is a boxed non-generic object. public static double FromSingleToDouble(object input) Parameters input object The object that will be casted to float and then converted to double Returns double Double FromSingleToInt16(object) Convert from Single to Int16 when input is a boxed non-generic object. public static short FromSingleToInt16(object input) Parameters input object The object that will be casted to float and then converted to short Returns short Int16 FromSingleToInt32(object) Convert from Single to Int32 when input is a boxed non-generic object. public static int FromSingleToInt32(object input) Parameters input object The object that will be casted to float and then converted to int Returns int Int32 FromSingleToInt64(object) Convert from Single to Int64 when input is a boxed non-generic object. public static long FromSingleToInt64(object input) Parameters input object The object that will be casted to float and then converted to long Returns long Int64 FromSingleToString(object) Convert from Single to String when input is a boxed non-generic object. public static string FromSingleToString(object input) Parameters input object The object that will be casted to float and then converted to string Returns string String FromSingleToUInt16(object) Convert from Single to UInt16 when input is a boxed non-generic object. public static ushort FromSingleToUInt16(object input) Parameters input object The object that will be casted to float and then converted to ushort Returns ushort UInt16 FromSingleToUInt32(object) Convert from Single to UInt32 when input is a boxed non-generic object. public static uint FromSingleToUInt32(object input) Parameters input object The object that will be casted to float and then converted to uint Returns uint UInt32 FromSingleToUInt64(object) Convert from Single to UInt64 when input is a boxed non-generic object. public static ulong FromSingleToUInt64(object input) Parameters input object The object that will be casted to float and then converted to ulong Returns ulong UInt64 FromStringToBoolean(object) Convert from String to Boolean when input is a boxed non-generic object. public static bool FromStringToBoolean(object input) Parameters input object The object that will be casted to string and then converted to bool Returns bool Boolean FromStringToByte(object) Convert from String to Byte when input is a boxed non-generic object. public static byte FromStringToByte(object input) Parameters input object The object that will be casted to string and then converted to byte Returns byte Byte FromStringToChar(object) Convert from String to Char when input is a boxed non-generic object. public static char FromStringToChar(object input) Parameters input object The object that will be casted to string and then converted to char Returns char Char FromStringToDecimal(object) Convert from String to Decimal when input is a boxed non-generic object. public static decimal FromStringToDecimal(object input) Parameters input object The object that will be casted to string and then converted to decimal Returns decimal Decimal FromStringToDouble(object) Convert from String to Double when input is a boxed non-generic object. public static double FromStringToDouble(object input) Parameters input object The object that will be casted to string and then converted to double Returns double Double FromStringToInt16(object) Convert from String to Int16 when input is a boxed non-generic object. public static short FromStringToInt16(object input) Parameters input object The object that will be casted to string and then converted to short Returns short Int16 FromStringToInt32(object) Convert from String to Int32 when input is a boxed non-generic object. public static int FromStringToInt32(object input) Parameters input object The object that will be casted to string and then converted to int Returns int Int32 FromStringToInt64(object) Convert from String to Int64 when input is a boxed non-generic object. public static long FromStringToInt64(object input) Parameters input object The object that will be casted to string and then converted to long Returns long Int64 FromStringToSingle(object) Convert from String to Single when input is a boxed non-generic object. public static float FromStringToSingle(object input) Parameters input object The object that will be casted to string and then converted to float Returns float Single FromStringToUInt16(object) Convert from String to UInt16 when input is a boxed non-generic object. public static ushort FromStringToUInt16(object input) Parameters input object The object that will be casted to string and then converted to ushort Returns ushort UInt16 FromStringToUInt32(object) Convert from String to UInt32 when input is a boxed non-generic object. public static uint FromStringToUInt32(object input) Parameters input object The object that will be casted to string and then converted to uint Returns uint UInt32 FromStringToUInt64(object) Convert from String to UInt64 when input is a boxed non-generic object. public static ulong FromStringToUInt64(object input) Parameters input object The object that will be casted to string and then converted to ulong Returns ulong UInt64 FromUInt16ToBoolean(object) Convert from UInt16 to Boolean when input is a boxed non-generic object. public static bool FromUInt16ToBoolean(object input) Parameters input object The object that will be casted to ushort and then converted to bool Returns bool Boolean FromUInt16ToByte(object) Convert from UInt16 to Byte when input is a boxed non-generic object. public static byte FromUInt16ToByte(object input) Parameters input object The object that will be casted to ushort and then converted to byte Returns byte Byte FromUInt16ToChar(object) Convert from UInt16 to Char when input is a boxed non-generic object. public static char FromUInt16ToChar(object input) Parameters input object The object that will be casted to ushort and then converted to char Returns char Char FromUInt16ToDecimal(object) Convert from UInt16 to Decimal when input is a boxed non-generic object. public static decimal FromUInt16ToDecimal(object input) Parameters input object The object that will be casted to ushort and then converted to decimal Returns decimal Decimal FromUInt16ToDouble(object) Convert from UInt16 to Double when input is a boxed non-generic object. public static double FromUInt16ToDouble(object input) Parameters input object The object that will be casted to ushort and then converted to double Returns double Double FromUInt16ToInt16(object) Convert from UInt16 to Int16 when input is a boxed non-generic object. public static short FromUInt16ToInt16(object input) Parameters input object The object that will be casted to ushort and then converted to short Returns short Int16 FromUInt16ToInt32(object) Convert from UInt16 to Int32 when input is a boxed non-generic object. public static int FromUInt16ToInt32(object input) Parameters input object The object that will be casted to ushort and then converted to int Returns int Int32 FromUInt16ToInt64(object) Convert from UInt16 to Int64 when input is a boxed non-generic object. public static long FromUInt16ToInt64(object input) Parameters input object The object that will be casted to ushort and then converted to long Returns long Int64 FromUInt16ToSingle(object) Convert from UInt16 to Single when input is a boxed non-generic object. public static float FromUInt16ToSingle(object input) Parameters input object The object that will be casted to ushort and then converted to float Returns float Single FromUInt16ToString(object) Convert from UInt16 to String when input is a boxed non-generic object. public static string FromUInt16ToString(object input) Parameters input object The object that will be casted to ushort and then converted to string Returns string String FromUInt16ToUInt32(object) Convert from UInt16 to UInt32 when input is a boxed non-generic object. public static uint FromUInt16ToUInt32(object input) Parameters input object The object that will be casted to ushort and then converted to uint Returns uint UInt32 FromUInt16ToUInt64(object) Convert from UInt16 to UInt64 when input is a boxed non-generic object. public static ulong FromUInt16ToUInt64(object input) Parameters input object The object that will be casted to ushort and then converted to ulong Returns ulong UInt64 FromUInt32ToBoolean(object) Convert from UInt32 to Boolean when input is a boxed non-generic object. public static bool FromUInt32ToBoolean(object input) Parameters input object The object that will be casted to uint and then converted to bool Returns bool Boolean FromUInt32ToByte(object) Convert from UInt32 to Byte when input is a boxed non-generic object. public static byte FromUInt32ToByte(object input) Parameters input object The object that will be casted to uint and then converted to byte Returns byte Byte FromUInt32ToChar(object) Convert from UInt32 to Char when input is a boxed non-generic object. public static char FromUInt32ToChar(object input) Parameters input object The object that will be casted to uint and then converted to char Returns char Char FromUInt32ToDecimal(object) Convert from UInt32 to Decimal when input is a boxed non-generic object. public static decimal FromUInt32ToDecimal(object input) Parameters input object The object that will be casted to uint and then converted to decimal Returns decimal Decimal FromUInt32ToDouble(object) Convert from UInt32 to Double when input is a boxed non-generic object. public static double FromUInt32ToDouble(object input) Parameters input object The object that will be casted to uint and then converted to double Returns double Double FromUInt32ToInt16(object) Convert from UInt32 to Int16 when input is a boxed non-generic object. public static short FromUInt32ToInt16(object input) Parameters input object The object that will be casted to uint and then converted to short Returns short Int16 FromUInt32ToInt32(object) Convert from UInt32 to Int32 when input is a boxed non-generic object. public static int FromUInt32ToInt32(object input) Parameters input object The object that will be casted to uint and then converted to int Returns int Int32 FromUInt32ToInt64(object) Convert from UInt32 to Int64 when input is a boxed non-generic object. public static long FromUInt32ToInt64(object input) Parameters input object The object that will be casted to uint and then converted to long Returns long Int64 FromUInt32ToSingle(object) Convert from UInt32 to Single when input is a boxed non-generic object. public static float FromUInt32ToSingle(object input) Parameters input object The object that will be casted to uint and then converted to float Returns float Single FromUInt32ToString(object) Convert from UInt32 to String when input is a boxed non-generic object. public static string FromUInt32ToString(object input) Parameters input object The object that will be casted to uint and then converted to string Returns string String FromUInt32ToUInt16(object) Convert from UInt32 to UInt16 when input is a boxed non-generic object. public static ushort FromUInt32ToUInt16(object input) Parameters input object The object that will be casted to uint and then converted to ushort Returns ushort UInt16 FromUInt32ToUInt64(object) Convert from UInt32 to UInt64 when input is a boxed non-generic object. public static ulong FromUInt32ToUInt64(object input) Parameters input object The object that will be casted to uint and then converted to ulong Returns ulong UInt64 FromUInt64ToBoolean(object) Convert from UInt64 to Boolean when input is a boxed non-generic object. public static bool FromUInt64ToBoolean(object input) Parameters input object The object that will be casted to ulong and then converted to bool Returns bool Boolean FromUInt64ToByte(object) Convert from UInt64 to Byte when input is a boxed non-generic object. public static byte FromUInt64ToByte(object input) Parameters input object The object that will be casted to ulong and then converted to byte Returns byte Byte FromUInt64ToChar(object) Convert from UInt64 to Char when input is a boxed non-generic object. public static char FromUInt64ToChar(object input) Parameters input object The object that will be casted to ulong and then converted to char Returns char Char FromUInt64ToDecimal(object) Convert from UInt64 to Decimal when input is a boxed non-generic object. public static decimal FromUInt64ToDecimal(object input) Parameters input object The object that will be casted to ulong and then converted to decimal Returns decimal Decimal FromUInt64ToDouble(object) Convert from UInt64 to Double when input is a boxed non-generic object. public static double FromUInt64ToDouble(object input) Parameters input object The object that will be casted to ulong and then converted to double Returns double Double FromUInt64ToInt16(object) Convert from UInt64 to Int16 when input is a boxed non-generic object. public static short FromUInt64ToInt16(object input) Parameters input object The object that will be casted to ulong and then converted to short Returns short Int16 FromUInt64ToInt32(object) Convert from UInt64 to Int32 when input is a boxed non-generic object. public static int FromUInt64ToInt32(object input) Parameters input object The object that will be casted to ulong and then converted to int Returns int Int32 FromUInt64ToInt64(object) Convert from UInt64 to Int64 when input is a boxed non-generic object. public static long FromUInt64ToInt64(object input) Parameters input object The object that will be casted to ulong and then converted to long Returns long Int64 FromUInt64ToSingle(object) Convert from UInt64 to Single when input is a boxed non-generic object. public static float FromUInt64ToSingle(object input) Parameters input object The object that will be casted to ulong and then converted to float Returns float Single FromUInt64ToString(object) Convert from UInt64 to String when input is a boxed non-generic object. public static string FromUInt64ToString(object input) Parameters input object The object that will be casted to ulong and then converted to string Returns string String FromUInt64ToUInt16(object) Convert from UInt64 to UInt16 when input is a boxed non-generic object. public static ushort FromUInt64ToUInt16(object input) Parameters input object The object that will be casted to ulong and then converted to ushort Returns ushort UInt16 FromUInt64ToUInt32(object) Convert from UInt64 to UInt32 when input is a boxed non-generic object. public static uint FromUInt64ToUInt32(object input) Parameters input object The object that will be casted to ulong and then converted to uint Returns uint UInt32" + }, + "api/NumSharp.Utilities.NumberInfo.html": { + "href": "api/NumSharp.Utilities.NumberInfo.html", + "title": "Class NumberInfo | NumSharp Documentation", + "summary": "Class NumberInfo Namespace NumSharp.Utilities Assembly NumSharp.dll public static class NumberInfo Inheritance object NumberInfo Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Methods MaxValue(NPTypeCode) Get the min value of given NPTypeCode. public static object MaxValue(this NPTypeCode typeCode) Parameters typeCode NPTypeCode Returns object MinValue(NPTypeCode) Get the min value of given NPTypeCode. public static object MinValue(this NPTypeCode typeCode) Parameters typeCode NPTypeCode Returns object" + }, + "api/NumSharp.Utilities.SteppingExtension.html": { + "href": "api/NumSharp.Utilities.SteppingExtension.html", + "title": "Class SteppingExtension | NumSharp Documentation", + "summary": "Class SteppingExtension Namespace NumSharp.Utilities Assembly NumSharp.dll public static class SteppingExtension Inheritance object SteppingExtension Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Methods Step(T[], int) public static T[] Step(this T[] array, int step) Parameters array T[] step int Returns T[] Type Parameters T" + }, + "api/NumSharp.Utilities.TypelessConvert.html": { + "href": "api/NumSharp.Utilities.TypelessConvert.html", + "title": "Class TypelessConvert | NumSharp Documentation", + "summary": "Class TypelessConvert Namespace NumSharp.Utilities Assembly NumSharp.dll Provides a way to convert boxed object from known input type to known output type. By making it receive and return object - It is suitable for a common delegate: see TypelessConvertDelegate public static class TypelessConvert Inheritance object TypelessConvert Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Methods FromBooleanToByte(object) Convert from Boolean to Byte when input is a boxed non-generic object. public static object FromBooleanToByte(object input) Parameters input object The object that will be casted to bool and then converted to byte Returns object Byte FromBooleanToChar(object) Convert from Boolean to Char when input is a boxed non-generic object. public static object FromBooleanToChar(object input) Parameters input object The object that will be casted to bool and then converted to char Returns object Char FromBooleanToDecimal(object) Convert from Boolean to Decimal when input is a boxed non-generic object. public static object FromBooleanToDecimal(object input) Parameters input object The object that will be casted to bool and then converted to decimal Returns object Decimal FromBooleanToDouble(object) Convert from Boolean to Double when input is a boxed non-generic object. public static object FromBooleanToDouble(object input) Parameters input object The object that will be casted to bool and then converted to double Returns object Double FromBooleanToInt16(object) Convert from Boolean to Int16 when input is a boxed non-generic object. public static object FromBooleanToInt16(object input) Parameters input object The object that will be casted to bool and then converted to short Returns object Int16 FromBooleanToInt32(object) Convert from Boolean to Int32 when input is a boxed non-generic object. public static object FromBooleanToInt32(object input) Parameters input object The object that will be casted to bool and then converted to int Returns object Int32 FromBooleanToInt64(object) Convert from Boolean to Int64 when input is a boxed non-generic object. public static object FromBooleanToInt64(object input) Parameters input object The object that will be casted to bool and then converted to long Returns object Int64 FromBooleanToSingle(object) Convert from Boolean to Single when input is a boxed non-generic object. public static object FromBooleanToSingle(object input) Parameters input object The object that will be casted to bool and then converted to float Returns object Single FromBooleanToString(object) Convert from Boolean to String when input is a boxed non-generic object. public static object FromBooleanToString(object input) Parameters input object The object that will be casted to bool and then converted to string Returns object String FromBooleanToUInt16(object) Convert from Boolean to UInt16 when input is a boxed non-generic object. public static object FromBooleanToUInt16(object input) Parameters input object The object that will be casted to bool and then converted to ushort Returns object UInt16 FromBooleanToUInt32(object) Convert from Boolean to UInt32 when input is a boxed non-generic object. public static object FromBooleanToUInt32(object input) Parameters input object The object that will be casted to bool and then converted to uint Returns object UInt32 FromBooleanToUInt64(object) Convert from Boolean to UInt64 when input is a boxed non-generic object. public static object FromBooleanToUInt64(object input) Parameters input object The object that will be casted to bool and then converted to ulong Returns object UInt64 FromByteToBoolean(object) Convert from Byte to Boolean when input is a boxed non-generic object. public static object FromByteToBoolean(object input) Parameters input object The object that will be casted to byte and then converted to bool Returns object Boolean FromByteToChar(object) Convert from Byte to Char when input is a boxed non-generic object. public static object FromByteToChar(object input) Parameters input object The object that will be casted to byte and then converted to char Returns object Char FromByteToDecimal(object) Convert from Byte to Decimal when input is a boxed non-generic object. public static object FromByteToDecimal(object input) Parameters input object The object that will be casted to byte and then converted to decimal Returns object Decimal FromByteToDouble(object) Convert from Byte to Double when input is a boxed non-generic object. public static object FromByteToDouble(object input) Parameters input object The object that will be casted to byte and then converted to double Returns object Double FromByteToInt16(object) Convert from Byte to Int16 when input is a boxed non-generic object. public static object FromByteToInt16(object input) Parameters input object The object that will be casted to byte and then converted to short Returns object Int16 FromByteToInt32(object) Convert from Byte to Int32 when input is a boxed non-generic object. public static object FromByteToInt32(object input) Parameters input object The object that will be casted to byte and then converted to int Returns object Int32 FromByteToInt64(object) Convert from Byte to Int64 when input is a boxed non-generic object. public static object FromByteToInt64(object input) Parameters input object The object that will be casted to byte and then converted to long Returns object Int64 FromByteToSingle(object) Convert from Byte to Single when input is a boxed non-generic object. public static object FromByteToSingle(object input) Parameters input object The object that will be casted to byte and then converted to float Returns object Single FromByteToString(object) Convert from Byte to String when input is a boxed non-generic object. public static object FromByteToString(object input) Parameters input object The object that will be casted to byte and then converted to string Returns object String FromByteToUInt16(object) Convert from Byte to UInt16 when input is a boxed non-generic object. public static object FromByteToUInt16(object input) Parameters input object The object that will be casted to byte and then converted to ushort Returns object UInt16 FromByteToUInt32(object) Convert from Byte to UInt32 when input is a boxed non-generic object. public static object FromByteToUInt32(object input) Parameters input object The object that will be casted to byte and then converted to uint Returns object UInt32 FromByteToUInt64(object) Convert from Byte to UInt64 when input is a boxed non-generic object. public static object FromByteToUInt64(object input) Parameters input object The object that will be casted to byte and then converted to ulong Returns object UInt64 FromCharToBoolean(object) Convert from Char to Boolean when input is a boxed non-generic object. public static object FromCharToBoolean(object input) Parameters input object The object that will be casted to char and then converted to bool Returns object Boolean FromCharToByte(object) Convert from Char to Byte when input is a boxed non-generic object. public static object FromCharToByte(object input) Parameters input object The object that will be casted to char and then converted to byte Returns object Byte FromCharToDecimal(object) Convert from Char to Decimal when input is a boxed non-generic object. public static object FromCharToDecimal(object input) Parameters input object The object that will be casted to char and then converted to decimal Returns object Decimal FromCharToDouble(object) Convert from Char to Double when input is a boxed non-generic object. public static object FromCharToDouble(object input) Parameters input object The object that will be casted to char and then converted to double Returns object Double FromCharToInt16(object) Convert from Char to Int16 when input is a boxed non-generic object. public static object FromCharToInt16(object input) Parameters input object The object that will be casted to char and then converted to short Returns object Int16 FromCharToInt32(object) Convert from Char to Int32 when input is a boxed non-generic object. public static object FromCharToInt32(object input) Parameters input object The object that will be casted to char and then converted to int Returns object Int32 FromCharToInt64(object) Convert from Char to Int64 when input is a boxed non-generic object. public static object FromCharToInt64(object input) Parameters input object The object that will be casted to char and then converted to long Returns object Int64 FromCharToSingle(object) Convert from Char to Single when input is a boxed non-generic object. public static object FromCharToSingle(object input) Parameters input object The object that will be casted to char and then converted to float Returns object Single FromCharToString(object) Convert from Char to String when input is a boxed non-generic object. public static object FromCharToString(object input) Parameters input object The object that will be casted to char and then converted to string Returns object String FromCharToUInt16(object) Convert from Char to UInt16 when input is a boxed non-generic object. public static object FromCharToUInt16(object input) Parameters input object The object that will be casted to char and then converted to ushort Returns object UInt16 FromCharToUInt32(object) Convert from Char to UInt32 when input is a boxed non-generic object. public static object FromCharToUInt32(object input) Parameters input object The object that will be casted to char and then converted to uint Returns object UInt32 FromCharToUInt64(object) Convert from Char to UInt64 when input is a boxed non-generic object. public static object FromCharToUInt64(object input) Parameters input object The object that will be casted to char and then converted to ulong Returns object UInt64 FromDecimalToBoolean(object) Convert from Decimal to Boolean when input is a boxed non-generic object. public static object FromDecimalToBoolean(object input) Parameters input object The object that will be casted to decimal and then converted to bool Returns object Boolean FromDecimalToByte(object) Convert from Decimal to Byte when input is a boxed non-generic object. public static object FromDecimalToByte(object input) Parameters input object The object that will be casted to decimal and then converted to byte Returns object Byte FromDecimalToChar(object) Convert from Decimal to Char when input is a boxed non-generic object. public static object FromDecimalToChar(object input) Parameters input object The object that will be casted to decimal and then converted to char Returns object Char FromDecimalToDouble(object) Convert from Decimal to Double when input is a boxed non-generic object. public static object FromDecimalToDouble(object input) Parameters input object The object that will be casted to decimal and then converted to double Returns object Double FromDecimalToInt16(object) Convert from Decimal to Int16 when input is a boxed non-generic object. public static object FromDecimalToInt16(object input) Parameters input object The object that will be casted to decimal and then converted to short Returns object Int16 FromDecimalToInt32(object) Convert from Decimal to Int32 when input is a boxed non-generic object. public static object FromDecimalToInt32(object input) Parameters input object The object that will be casted to decimal and then converted to int Returns object Int32 FromDecimalToInt64(object) Convert from Decimal to Int64 when input is a boxed non-generic object. public static object FromDecimalToInt64(object input) Parameters input object The object that will be casted to decimal and then converted to long Returns object Int64 FromDecimalToSingle(object) Convert from Decimal to Single when input is a boxed non-generic object. public static object FromDecimalToSingle(object input) Parameters input object The object that will be casted to decimal and then converted to float Returns object Single FromDecimalToString(object) Convert from Decimal to String when input is a boxed non-generic object. public static object FromDecimalToString(object input) Parameters input object The object that will be casted to decimal and then converted to string Returns object String FromDecimalToUInt16(object) Convert from Decimal to UInt16 when input is a boxed non-generic object. public static object FromDecimalToUInt16(object input) Parameters input object The object that will be casted to decimal and then converted to ushort Returns object UInt16 FromDecimalToUInt32(object) Convert from Decimal to UInt32 when input is a boxed non-generic object. public static object FromDecimalToUInt32(object input) Parameters input object The object that will be casted to decimal and then converted to uint Returns object UInt32 FromDecimalToUInt64(object) Convert from Decimal to UInt64 when input is a boxed non-generic object. public static object FromDecimalToUInt64(object input) Parameters input object The object that will be casted to decimal and then converted to ulong Returns object UInt64 FromDoubleToBoolean(object) Convert from Double to Boolean when input is a boxed non-generic object. public static object FromDoubleToBoolean(object input) Parameters input object The object that will be casted to double and then converted to bool Returns object Boolean FromDoubleToByte(object) Convert from Double to Byte when input is a boxed non-generic object. public static object FromDoubleToByte(object input) Parameters input object The object that will be casted to double and then converted to byte Returns object Byte FromDoubleToChar(object) Convert from Double to Char when input is a boxed non-generic object. public static object FromDoubleToChar(object input) Parameters input object The object that will be casted to double and then converted to char Returns object Char FromDoubleToDecimal(object) Convert from Double to Decimal when input is a boxed non-generic object. public static object FromDoubleToDecimal(object input) Parameters input object The object that will be casted to double and then converted to decimal Returns object Decimal FromDoubleToInt16(object) Convert from Double to Int16 when input is a boxed non-generic object. public static object FromDoubleToInt16(object input) Parameters input object The object that will be casted to double and then converted to short Returns object Int16 FromDoubleToInt32(object) Convert from Double to Int32 when input is a boxed non-generic object. public static object FromDoubleToInt32(object input) Parameters input object The object that will be casted to double and then converted to int Returns object Int32 FromDoubleToInt64(object) Convert from Double to Int64 when input is a boxed non-generic object. public static object FromDoubleToInt64(object input) Parameters input object The object that will be casted to double and then converted to long Returns object Int64 FromDoubleToSingle(object) Convert from Double to Single when input is a boxed non-generic object. public static object FromDoubleToSingle(object input) Parameters input object The object that will be casted to double and then converted to float Returns object Single FromDoubleToString(object) Convert from Double to String when input is a boxed non-generic object. public static object FromDoubleToString(object input) Parameters input object The object that will be casted to double and then converted to string Returns object String FromDoubleToUInt16(object) Convert from Double to UInt16 when input is a boxed non-generic object. public static object FromDoubleToUInt16(object input) Parameters input object The object that will be casted to double and then converted to ushort Returns object UInt16 FromDoubleToUInt32(object) Convert from Double to UInt32 when input is a boxed non-generic object. public static object FromDoubleToUInt32(object input) Parameters input object The object that will be casted to double and then converted to uint Returns object UInt32 FromDoubleToUInt64(object) Convert from Double to UInt64 when input is a boxed non-generic object. public static object FromDoubleToUInt64(object input) Parameters input object The object that will be casted to double and then converted to ulong Returns object UInt64 FromInt16ToBoolean(object) Convert from Int16 to Boolean when input is a boxed non-generic object. public static object FromInt16ToBoolean(object input) Parameters input object The object that will be casted to short and then converted to bool Returns object Boolean FromInt16ToByte(object) Convert from Int16 to Byte when input is a boxed non-generic object. public static object FromInt16ToByte(object input) Parameters input object The object that will be casted to short and then converted to byte Returns object Byte FromInt16ToChar(object) Convert from Int16 to Char when input is a boxed non-generic object. public static object FromInt16ToChar(object input) Parameters input object The object that will be casted to short and then converted to char Returns object Char FromInt16ToDecimal(object) Convert from Int16 to Decimal when input is a boxed non-generic object. public static object FromInt16ToDecimal(object input) Parameters input object The object that will be casted to short and then converted to decimal Returns object Decimal FromInt16ToDouble(object) Convert from Int16 to Double when input is a boxed non-generic object. public static object FromInt16ToDouble(object input) Parameters input object The object that will be casted to short and then converted to double Returns object Double FromInt16ToInt32(object) Convert from Int16 to Int32 when input is a boxed non-generic object. public static object FromInt16ToInt32(object input) Parameters input object The object that will be casted to short and then converted to int Returns object Int32 FromInt16ToInt64(object) Convert from Int16 to Int64 when input is a boxed non-generic object. public static object FromInt16ToInt64(object input) Parameters input object The object that will be casted to short and then converted to long Returns object Int64 FromInt16ToSingle(object) Convert from Int16 to Single when input is a boxed non-generic object. public static object FromInt16ToSingle(object input) Parameters input object The object that will be casted to short and then converted to float Returns object Single FromInt16ToString(object) Convert from Int16 to String when input is a boxed non-generic object. public static object FromInt16ToString(object input) Parameters input object The object that will be casted to short and then converted to string Returns object String FromInt16ToUInt16(object) Convert from Int16 to UInt16 when input is a boxed non-generic object. public static object FromInt16ToUInt16(object input) Parameters input object The object that will be casted to short and then converted to ushort Returns object UInt16 FromInt16ToUInt32(object) Convert from Int16 to UInt32 when input is a boxed non-generic object. public static object FromInt16ToUInt32(object input) Parameters input object The object that will be casted to short and then converted to uint Returns object UInt32 FromInt16ToUInt64(object) Convert from Int16 to UInt64 when input is a boxed non-generic object. public static object FromInt16ToUInt64(object input) Parameters input object The object that will be casted to short and then converted to ulong Returns object UInt64 FromInt32ToBoolean(object) Convert from Int32 to Boolean when input is a boxed non-generic object. public static object FromInt32ToBoolean(object input) Parameters input object The object that will be casted to int and then converted to bool Returns object Boolean FromInt32ToByte(object) Convert from Int32 to Byte when input is a boxed non-generic object. public static object FromInt32ToByte(object input) Parameters input object The object that will be casted to int and then converted to byte Returns object Byte FromInt32ToChar(object) Convert from Int32 to Char when input is a boxed non-generic object. public static object FromInt32ToChar(object input) Parameters input object The object that will be casted to int and then converted to char Returns object Char FromInt32ToDecimal(object) Convert from Int32 to Decimal when input is a boxed non-generic object. public static object FromInt32ToDecimal(object input) Parameters input object The object that will be casted to int and then converted to decimal Returns object Decimal FromInt32ToDouble(object) Convert from Int32 to Double when input is a boxed non-generic object. public static object FromInt32ToDouble(object input) Parameters input object The object that will be casted to int and then converted to double Returns object Double FromInt32ToInt16(object) Convert from Int32 to Int16 when input is a boxed non-generic object. public static object FromInt32ToInt16(object input) Parameters input object The object that will be casted to int and then converted to short Returns object Int16 FromInt32ToInt64(object) Convert from Int32 to Int64 when input is a boxed non-generic object. public static object FromInt32ToInt64(object input) Parameters input object The object that will be casted to int and then converted to long Returns object Int64 FromInt32ToSingle(object) Convert from Int32 to Single when input is a boxed non-generic object. public static object FromInt32ToSingle(object input) Parameters input object The object that will be casted to int and then converted to float Returns object Single FromInt32ToString(object) Convert from Int32 to String when input is a boxed non-generic object. public static object FromInt32ToString(object input) Parameters input object The object that will be casted to int and then converted to string Returns object String FromInt32ToUInt16(object) Convert from Int32 to UInt16 when input is a boxed non-generic object. public static object FromInt32ToUInt16(object input) Parameters input object The object that will be casted to int and then converted to ushort Returns object UInt16 FromInt32ToUInt32(object) Convert from Int32 to UInt32 when input is a boxed non-generic object. public static object FromInt32ToUInt32(object input) Parameters input object The object that will be casted to int and then converted to uint Returns object UInt32 FromInt32ToUInt64(object) Convert from Int32 to UInt64 when input is a boxed non-generic object. public static object FromInt32ToUInt64(object input) Parameters input object The object that will be casted to int and then converted to ulong Returns object UInt64 FromInt64ToBoolean(object) Convert from Int64 to Boolean when input is a boxed non-generic object. public static object FromInt64ToBoolean(object input) Parameters input object The object that will be casted to long and then converted to bool Returns object Boolean FromInt64ToByte(object) Convert from Int64 to Byte when input is a boxed non-generic object. public static object FromInt64ToByte(object input) Parameters input object The object that will be casted to long and then converted to byte Returns object Byte FromInt64ToChar(object) Convert from Int64 to Char when input is a boxed non-generic object. public static object FromInt64ToChar(object input) Parameters input object The object that will be casted to long and then converted to char Returns object Char FromInt64ToDecimal(object) Convert from Int64 to Decimal when input is a boxed non-generic object. public static object FromInt64ToDecimal(object input) Parameters input object The object that will be casted to long and then converted to decimal Returns object Decimal FromInt64ToDouble(object) Convert from Int64 to Double when input is a boxed non-generic object. public static object FromInt64ToDouble(object input) Parameters input object The object that will be casted to long and then converted to double Returns object Double FromInt64ToInt16(object) Convert from Int64 to Int16 when input is a boxed non-generic object. public static object FromInt64ToInt16(object input) Parameters input object The object that will be casted to long and then converted to short Returns object Int16 FromInt64ToInt32(object) Convert from Int64 to Int32 when input is a boxed non-generic object. public static object FromInt64ToInt32(object input) Parameters input object The object that will be casted to long and then converted to int Returns object Int32 FromInt64ToSingle(object) Convert from Int64 to Single when input is a boxed non-generic object. public static object FromInt64ToSingle(object input) Parameters input object The object that will be casted to long and then converted to float Returns object Single FromInt64ToString(object) Convert from Int64 to String when input is a boxed non-generic object. public static object FromInt64ToString(object input) Parameters input object The object that will be casted to long and then converted to string Returns object String FromInt64ToUInt16(object) Convert from Int64 to UInt16 when input is a boxed non-generic object. public static object FromInt64ToUInt16(object input) Parameters input object The object that will be casted to long and then converted to ushort Returns object UInt16 FromInt64ToUInt32(object) Convert from Int64 to UInt32 when input is a boxed non-generic object. public static object FromInt64ToUInt32(object input) Parameters input object The object that will be casted to long and then converted to uint Returns object UInt32 FromInt64ToUInt64(object) Convert from Int64 to UInt64 when input is a boxed non-generic object. public static object FromInt64ToUInt64(object input) Parameters input object The object that will be casted to long and then converted to ulong Returns object UInt64 FromSingleToBoolean(object) Convert from Single to Boolean when input is a boxed non-generic object. public static object FromSingleToBoolean(object input) Parameters input object The object that will be casted to float and then converted to bool Returns object Boolean FromSingleToByte(object) Convert from Single to Byte when input is a boxed non-generic object. public static object FromSingleToByte(object input) Parameters input object The object that will be casted to float and then converted to byte Returns object Byte FromSingleToChar(object) Convert from Single to Char when input is a boxed non-generic object. public static object FromSingleToChar(object input) Parameters input object The object that will be casted to float and then converted to char Returns object Char FromSingleToDecimal(object) Convert from Single to Decimal when input is a boxed non-generic object. public static object FromSingleToDecimal(object input) Parameters input object The object that will be casted to float and then converted to decimal Returns object Decimal FromSingleToDouble(object) Convert from Single to Double when input is a boxed non-generic object. public static object FromSingleToDouble(object input) Parameters input object The object that will be casted to float and then converted to double Returns object Double FromSingleToInt16(object) Convert from Single to Int16 when input is a boxed non-generic object. public static object FromSingleToInt16(object input) Parameters input object The object that will be casted to float and then converted to short Returns object Int16 FromSingleToInt32(object) Convert from Single to Int32 when input is a boxed non-generic object. public static object FromSingleToInt32(object input) Parameters input object The object that will be casted to float and then converted to int Returns object Int32 FromSingleToInt64(object) Convert from Single to Int64 when input is a boxed non-generic object. public static object FromSingleToInt64(object input) Parameters input object The object that will be casted to float and then converted to long Returns object Int64 FromSingleToString(object) Convert from Single to String when input is a boxed non-generic object. public static object FromSingleToString(object input) Parameters input object The object that will be casted to float and then converted to string Returns object String FromSingleToUInt16(object) Convert from Single to UInt16 when input is a boxed non-generic object. public static object FromSingleToUInt16(object input) Parameters input object The object that will be casted to float and then converted to ushort Returns object UInt16 FromSingleToUInt32(object) Convert from Single to UInt32 when input is a boxed non-generic object. public static object FromSingleToUInt32(object input) Parameters input object The object that will be casted to float and then converted to uint Returns object UInt32 FromSingleToUInt64(object) Convert from Single to UInt64 when input is a boxed non-generic object. public static object FromSingleToUInt64(object input) Parameters input object The object that will be casted to float and then converted to ulong Returns object UInt64 FromStringToBoolean(object) Convert from String to Boolean when input is a boxed non-generic object. public static object FromStringToBoolean(object input) Parameters input object The object that will be casted to string and then converted to bool Returns object Boolean FromStringToByte(object) Convert from String to Byte when input is a boxed non-generic object. public static object FromStringToByte(object input) Parameters input object The object that will be casted to string and then converted to byte Returns object Byte FromStringToChar(object) Convert from String to Char when input is a boxed non-generic object. public static object FromStringToChar(object input) Parameters input object The object that will be casted to string and then converted to char Returns object Char FromStringToDecimal(object) Convert from String to Decimal when input is a boxed non-generic object. public static object FromStringToDecimal(object input) Parameters input object The object that will be casted to string and then converted to decimal Returns object Decimal FromStringToDouble(object) Convert from String to Double when input is a boxed non-generic object. public static object FromStringToDouble(object input) Parameters input object The object that will be casted to string and then converted to double Returns object Double FromStringToInt16(object) Convert from String to Int16 when input is a boxed non-generic object. public static object FromStringToInt16(object input) Parameters input object The object that will be casted to string and then converted to short Returns object Int16 FromStringToInt32(object) Convert from String to Int32 when input is a boxed non-generic object. public static object FromStringToInt32(object input) Parameters input object The object that will be casted to string and then converted to int Returns object Int32 FromStringToInt64(object) Convert from String to Int64 when input is a boxed non-generic object. public static object FromStringToInt64(object input) Parameters input object The object that will be casted to string and then converted to long Returns object Int64 FromStringToSingle(object) Convert from String to Single when input is a boxed non-generic object. public static object FromStringToSingle(object input) Parameters input object The object that will be casted to string and then converted to float Returns object Single FromStringToUInt16(object) Convert from String to UInt16 when input is a boxed non-generic object. public static object FromStringToUInt16(object input) Parameters input object The object that will be casted to string and then converted to ushort Returns object UInt16 FromStringToUInt32(object) Convert from String to UInt32 when input is a boxed non-generic object. public static object FromStringToUInt32(object input) Parameters input object The object that will be casted to string and then converted to uint Returns object UInt32 FromStringToUInt64(object) Convert from String to UInt64 when input is a boxed non-generic object. public static object FromStringToUInt64(object input) Parameters input object The object that will be casted to string and then converted to ulong Returns object UInt64 FromUInt16ToBoolean(object) Convert from UInt16 to Boolean when input is a boxed non-generic object. public static object FromUInt16ToBoolean(object input) Parameters input object The object that will be casted to ushort and then converted to bool Returns object Boolean FromUInt16ToByte(object) Convert from UInt16 to Byte when input is a boxed non-generic object. public static object FromUInt16ToByte(object input) Parameters input object The object that will be casted to ushort and then converted to byte Returns object Byte FromUInt16ToChar(object) Convert from UInt16 to Char when input is a boxed non-generic object. public static object FromUInt16ToChar(object input) Parameters input object The object that will be casted to ushort and then converted to char Returns object Char FromUInt16ToDecimal(object) Convert from UInt16 to Decimal when input is a boxed non-generic object. public static object FromUInt16ToDecimal(object input) Parameters input object The object that will be casted to ushort and then converted to decimal Returns object Decimal FromUInt16ToDouble(object) Convert from UInt16 to Double when input is a boxed non-generic object. public static object FromUInt16ToDouble(object input) Parameters input object The object that will be casted to ushort and then converted to double Returns object Double FromUInt16ToInt16(object) Convert from UInt16 to Int16 when input is a boxed non-generic object. public static object FromUInt16ToInt16(object input) Parameters input object The object that will be casted to ushort and then converted to short Returns object Int16 FromUInt16ToInt32(object) Convert from UInt16 to Int32 when input is a boxed non-generic object. public static object FromUInt16ToInt32(object input) Parameters input object The object that will be casted to ushort and then converted to int Returns object Int32 FromUInt16ToInt64(object) Convert from UInt16 to Int64 when input is a boxed non-generic object. public static object FromUInt16ToInt64(object input) Parameters input object The object that will be casted to ushort and then converted to long Returns object Int64 FromUInt16ToSingle(object) Convert from UInt16 to Single when input is a boxed non-generic object. public static object FromUInt16ToSingle(object input) Parameters input object The object that will be casted to ushort and then converted to float Returns object Single FromUInt16ToString(object) Convert from UInt16 to String when input is a boxed non-generic object. public static object FromUInt16ToString(object input) Parameters input object The object that will be casted to ushort and then converted to string Returns object String FromUInt16ToUInt32(object) Convert from UInt16 to UInt32 when input is a boxed non-generic object. public static object FromUInt16ToUInt32(object input) Parameters input object The object that will be casted to ushort and then converted to uint Returns object UInt32 FromUInt16ToUInt64(object) Convert from UInt16 to UInt64 when input is a boxed non-generic object. public static object FromUInt16ToUInt64(object input) Parameters input object The object that will be casted to ushort and then converted to ulong Returns object UInt64 FromUInt32ToBoolean(object) Convert from UInt32 to Boolean when input is a boxed non-generic object. public static object FromUInt32ToBoolean(object input) Parameters input object The object that will be casted to uint and then converted to bool Returns object Boolean FromUInt32ToByte(object) Convert from UInt32 to Byte when input is a boxed non-generic object. public static object FromUInt32ToByte(object input) Parameters input object The object that will be casted to uint and then converted to byte Returns object Byte FromUInt32ToChar(object) Convert from UInt32 to Char when input is a boxed non-generic object. public static object FromUInt32ToChar(object input) Parameters input object The object that will be casted to uint and then converted to char Returns object Char FromUInt32ToDecimal(object) Convert from UInt32 to Decimal when input is a boxed non-generic object. public static object FromUInt32ToDecimal(object input) Parameters input object The object that will be casted to uint and then converted to decimal Returns object Decimal FromUInt32ToDouble(object) Convert from UInt32 to Double when input is a boxed non-generic object. public static object FromUInt32ToDouble(object input) Parameters input object The object that will be casted to uint and then converted to double Returns object Double FromUInt32ToInt16(object) Convert from UInt32 to Int16 when input is a boxed non-generic object. public static object FromUInt32ToInt16(object input) Parameters input object The object that will be casted to uint and then converted to short Returns object Int16 FromUInt32ToInt32(object) Convert from UInt32 to Int32 when input is a boxed non-generic object. public static object FromUInt32ToInt32(object input) Parameters input object The object that will be casted to uint and then converted to int Returns object Int32 FromUInt32ToInt64(object) Convert from UInt32 to Int64 when input is a boxed non-generic object. public static object FromUInt32ToInt64(object input) Parameters input object The object that will be casted to uint and then converted to long Returns object Int64 FromUInt32ToSingle(object) Convert from UInt32 to Single when input is a boxed non-generic object. public static object FromUInt32ToSingle(object input) Parameters input object The object that will be casted to uint and then converted to float Returns object Single FromUInt32ToString(object) Convert from UInt32 to String when input is a boxed non-generic object. public static object FromUInt32ToString(object input) Parameters input object The object that will be casted to uint and then converted to string Returns object String FromUInt32ToUInt16(object) Convert from UInt32 to UInt16 when input is a boxed non-generic object. public static object FromUInt32ToUInt16(object input) Parameters input object The object that will be casted to uint and then converted to ushort Returns object UInt16 FromUInt32ToUInt64(object) Convert from UInt32 to UInt64 when input is a boxed non-generic object. public static object FromUInt32ToUInt64(object input) Parameters input object The object that will be casted to uint and then converted to ulong Returns object UInt64 FromUInt64ToBoolean(object) Convert from UInt64 to Boolean when input is a boxed non-generic object. public static object FromUInt64ToBoolean(object input) Parameters input object The object that will be casted to ulong and then converted to bool Returns object Boolean FromUInt64ToByte(object) Convert from UInt64 to Byte when input is a boxed non-generic object. public static object FromUInt64ToByte(object input) Parameters input object The object that will be casted to ulong and then converted to byte Returns object Byte FromUInt64ToChar(object) Convert from UInt64 to Char when input is a boxed non-generic object. public static object FromUInt64ToChar(object input) Parameters input object The object that will be casted to ulong and then converted to char Returns object Char FromUInt64ToDecimal(object) Convert from UInt64 to Decimal when input is a boxed non-generic object. public static object FromUInt64ToDecimal(object input) Parameters input object The object that will be casted to ulong and then converted to decimal Returns object Decimal FromUInt64ToDouble(object) Convert from UInt64 to Double when input is a boxed non-generic object. public static object FromUInt64ToDouble(object input) Parameters input object The object that will be casted to ulong and then converted to double Returns object Double FromUInt64ToInt16(object) Convert from UInt64 to Int16 when input is a boxed non-generic object. public static object FromUInt64ToInt16(object input) Parameters input object The object that will be casted to ulong and then converted to short Returns object Int16 FromUInt64ToInt32(object) Convert from UInt64 to Int32 when input is a boxed non-generic object. public static object FromUInt64ToInt32(object input) Parameters input object The object that will be casted to ulong and then converted to int Returns object Int32 FromUInt64ToInt64(object) Convert from UInt64 to Int64 when input is a boxed non-generic object. public static object FromUInt64ToInt64(object input) Parameters input object The object that will be casted to ulong and then converted to long Returns object Int64 FromUInt64ToSingle(object) Convert from UInt64 to Single when input is a boxed non-generic object. public static object FromUInt64ToSingle(object input) Parameters input object The object that will be casted to ulong and then converted to float Returns object Single FromUInt64ToString(object) Convert from UInt64 to String when input is a boxed non-generic object. public static object FromUInt64ToString(object input) Parameters input object The object that will be casted to ulong and then converted to string Returns object String FromUInt64ToUInt16(object) Convert from UInt64 to UInt16 when input is a boxed non-generic object. public static object FromUInt64ToUInt16(object input) Parameters input object The object that will be casted to ulong and then converted to ushort Returns object UInt16 FromUInt64ToUInt32(object) Convert from UInt64 to UInt32 when input is a boxed non-generic object. public static object FromUInt64ToUInt32(object input) Parameters input object The object that will be casted to ulong and then converted to uint Returns object UInt32 GetConverter(Type, Type) public static TypelessConvertDelegate GetConverter(Type input, Type output) Parameters input Type output Type Returns TypelessConvertDelegate" + }, + "api/NumSharp.Utilities.TypelessConvertDelegate.html": { + "href": "api/NumSharp.Utilities.TypelessConvertDelegate.html", + "title": "Delegate TypelessConvertDelegate | NumSharp Documentation", + "summary": "Delegate TypelessConvertDelegate Namespace NumSharp.Utilities Assembly NumSharp.dll public delegate object TypelessConvertDelegate(object input) Parameters input object Returns object Extension Methods LinqExtensions.Yield(T)" + }, + "api/NumSharp.Utilities.ValueCoordinatesIncrementor.EndCallbackHandler.html": { + "href": "api/NumSharp.Utilities.ValueCoordinatesIncrementor.EndCallbackHandler.html", + "title": "Delegate ValueCoordinatesIncrementor.EndCallbackHandler | NumSharp Documentation", + "summary": "Delegate ValueCoordinatesIncrementor.EndCallbackHandler Namespace NumSharp.Utilities Assembly NumSharp.dll public delegate void ValueCoordinatesIncrementor.EndCallbackHandler(ref ValueCoordinatesIncrementor incr) Parameters incr ValueCoordinatesIncrementor Extension Methods LinqExtensions.Yield(T)" + }, + "api/NumSharp.Utilities.ValueCoordinatesIncrementor.html": { + "href": "api/NumSharp.Utilities.ValueCoordinatesIncrementor.html", + "title": "Struct ValueCoordinatesIncrementor | NumSharp Documentation", + "summary": "Struct ValueCoordinatesIncrementor Namespace NumSharp.Utilities Assembly NumSharp.dll public struct ValueCoordinatesIncrementor Inherited Members ValueType.Equals(object) ValueType.GetHashCode() ValueType.ToString() object.Equals(object, object) object.GetType() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) Constructors ValueCoordinatesIncrementor(ref Shape) Initializes a new instance of the object class. public ValueCoordinatesIncrementor(ref Shape shape) Parameters shape Shape ValueCoordinatesIncrementor(ref Shape, EndCallbackHandler) public ValueCoordinatesIncrementor(ref Shape shape, ValueCoordinatesIncrementor.EndCallbackHandler endCallback) Parameters shape Shape endCallback ValueCoordinatesIncrementor.EndCallbackHandler ValueCoordinatesIncrementor(int[]) public ValueCoordinatesIncrementor(int[] dims) Parameters dims int[] ValueCoordinatesIncrementor(int[], EndCallbackHandler) public ValueCoordinatesIncrementor(int[] dims, ValueCoordinatesIncrementor.EndCallbackHandler endCallback) Parameters dims int[] endCallback ValueCoordinatesIncrementor.EndCallbackHandler Fields Index public readonly int[] Index Field Value int[] Methods Next() public int[] Next() Returns int[] Reset() public void Reset()" + }, + "api/NumSharp.Utilities.ValueCoordinatesIncrementorAutoResetting.html": { + "href": "api/NumSharp.Utilities.ValueCoordinatesIncrementorAutoResetting.html", + "title": "Struct ValueCoordinatesIncrementorAutoResetting | NumSharp Documentation", + "summary": "Struct ValueCoordinatesIncrementorAutoResetting Namespace NumSharp.Utilities Assembly NumSharp.dll public struct ValueCoordinatesIncrementorAutoResetting Inherited Members ValueType.Equals(object) ValueType.GetHashCode() ValueType.ToString() object.Equals(object, object) object.GetType() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) Constructors ValueCoordinatesIncrementorAutoResetting(ref Shape) Initializes a new instance of the object class. public ValueCoordinatesIncrementorAutoResetting(ref Shape shape) Parameters shape Shape ValueCoordinatesIncrementorAutoResetting(int[]) public ValueCoordinatesIncrementorAutoResetting(int[] dims) Parameters dims int[] Fields Index public readonly int[] Index Field Value int[] Methods Next() public int[] Next() Returns int[] Reset() public void Reset()" + }, + "api/NumSharp.Utilities.ValueOffsetIncrementor.html": { + "href": "api/NumSharp.Utilities.ValueOffsetIncrementor.html", + "title": "Struct ValueOffsetIncrementor | NumSharp Documentation", + "summary": "Struct ValueOffsetIncrementor Namespace NumSharp.Utilities Assembly NumSharp.dll public struct ValueOffsetIncrementor Inherited Members ValueType.Equals(object) ValueType.GetHashCode() ValueType.ToString() object.Equals(object, object) object.GetType() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) Constructors ValueOffsetIncrementor(Shape) public ValueOffsetIncrementor(Shape shape) Parameters shape Shape ValueOffsetIncrementor(int[]) public ValueOffsetIncrementor(int[] dims) Parameters dims int[] Properties HasNext public bool HasNext { get; } Property Value bool Methods Next() public int Next() Returns int Reset() public void Reset()" + }, + "api/NumSharp.Utilities.ValueOffsetIncrementorAutoresetting.html": { + "href": "api/NumSharp.Utilities.ValueOffsetIncrementorAutoresetting.html", + "title": "Struct ValueOffsetIncrementorAutoresetting | NumSharp Documentation", + "summary": "Struct ValueOffsetIncrementorAutoresetting Namespace NumSharp.Utilities Assembly NumSharp.dll public struct ValueOffsetIncrementorAutoresetting Inherited Members ValueType.Equals(object) ValueType.GetHashCode() ValueType.ToString() object.Equals(object, object) object.GetType() object.ReferenceEquals(object, object) Extension Methods LinqExtensions.Yield(T) Constructors ValueOffsetIncrementorAutoresetting(Shape) public ValueOffsetIncrementorAutoresetting(Shape shape) Parameters shape Shape ValueOffsetIncrementorAutoresetting(int[]) public ValueOffsetIncrementorAutoresetting(int[] dims) Parameters dims int[] Properties HasNext public bool HasNext { get; } Property Value bool Methods Next() public int Next() Returns int Reset() public void Reset()" + }, + "api/NumSharp.Utilities.html": { + "href": "api/NumSharp.Utilities.html", + "title": "Namespace NumSharp.Utilities | NumSharp Documentation", + "summary": "Namespace NumSharp.Utilities Classes ArrayConvert Presents all possible combinations of array conversion of types supported by numpy. Arrays ArraysExtensions ConcurrentHashset Converts Provides various methods related to Convert. Converts Provides various methods related to Convert based on give T. Hashset InfoOf Provides a cache for properties of T that requires computation. NDCoordinatesAxisIncrementor NDCoordinatesIncrementor NDCoordinatesIncrementorAutoResetting NDCoordinatesLeftToAxisIncrementor NDExtendedCoordinatesIncrementor NDOffsetIncrementor NDOffsetIncrementorAutoresetting NonGenericConvert Provides a way to convert boxed object from known time to specific type. NumberInfo SteppingExtension TypelessConvert Provides a way to convert boxed object from known input type to known output type. By making it receive and return object - It is suitable for a common delegate: see TypelessConvertDelegate py Implements Python utility functions that are often used in connection with numpy Structs Hashset.Enumerator ValueCoordinatesIncrementor ValueCoordinatesIncrementorAutoResetting ValueOffsetIncrementor ValueOffsetIncrementorAutoresetting Delegates TypelessConvertDelegate ValueCoordinatesIncrementor.EndCallbackHandler" + }, + "api/NumSharp.Utilities.py.html": { + "href": "api/NumSharp.Utilities.py.html", + "title": "Class py | NumSharp Documentation", + "summary": "Class py Namespace NumSharp.Utilities Assembly NumSharp.dll Implements Python utility functions that are often used in connection with numpy public static class py Inheritance object py Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Methods complex(string) public static Complex complex(string input) Parameters input string Returns Complex range(int) public static int[] range(int n) Parameters n int Returns int[]" + }, + "api/NumSharp.ViewInfo.html": { + "href": "api/NumSharp.ViewInfo.html", + "title": "Class ViewInfo | NumSharp Documentation", + "summary": "Class ViewInfo Namespace NumSharp Assembly NumSharp.dll public class ViewInfo : ICloneable Inheritance object ViewInfo Implements ICloneable Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Fields OriginalShape OriginalShape is the primitive shape of the unsliced array public Shape OriginalShape Field Value Shape ParentShape ParentShape points to a sliced shape that was reshaped. usually this is null, except if the Shape is a reshaped slice. ParentShape always is a sliced shape! public Shape ParentShape Field Value Shape Slices The slice definition for every dimension of the OriginalShape public SliceDef[] Slices Field Value SliceDef[] UnreducedShape UnreducedShape is the shape after slicing but without dimensionality reductions due to index access public Shape UnreducedShape Field Value Shape Methods Clone() public ViewInfo Clone() Returns ViewInfo" + }, + "api/NumSharp.html": { + "href": "api/NumSharp.html", + "title": "Namespace NumSharp | NumSharp Documentation", + "summary": "Namespace NumSharp Classes AxisOutOfRangeException BroadcastInfo DType IncorrectShapeException IncorrectSizeException IncorrectTypeException Kwargs MultiIterator NDArray An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.) NDIteratorExtensions NDIterator NPTypeCodeExtensions NpzDictionary NpzDictionary NumPyRandom A class that serves as numpy.random.RandomState in python. NumSharpException Randomizer Represents a pseudo-random number generator, which is a device that produces a sequence of numbers that meet certain statistical requirements for randomness. Equivalent of Random. Slice
NDArray can be indexed using slicing A slice is constructed by start:stop:step notation Examples: a[start:stop] # items start through stop-1 a[start:] # items start through the rest of the array a[:stop] # items from the beginning through stop-1 The key point to remember is that the :stop value represents the first value that is not in the selected slice. So, the difference between stop and start is the number of elements selected (if step is 1, the default). There is also the step value, which can be used with any of the above: a[:] # a copy of the whole array a[start:stop:step] # start through not past stop, by step The other feature is that start or stop may be a negative number, which means it counts from the end of the array instead of the beginning. So: a[-1] # last item in the array a[-2:] # last two items in the array a[:-2] # everything except the last two items Similarly, step may be a negative number: a[::- 1] # all items in the array, reversed a[1::- 1] # the first two items, reversed a[:-3:-1] # the last two items, reversed a[-3::- 1] # everything except the last two items, reversed NumSharp is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error.Sometimes you would prefer the error, so you have to be aware that this may happen. Adapted from Greg Hewgill's answer on Stackoverflow: https://stackoverflow.com/questions/509211/understanding-slice-notation Note: special IsIndex == true It will pick only a single value at Start in this dimension effectively reducing the Shape of the sliced matrix by 1 dimension. It can be used to reduce an N-dimensional array/matrix to a (N-1)-dimensional array/matrix Example: a=[[1, 2], [3, 4]] a[:, 1] returns the second column of that 2x2 matrix as a 1-D vector TensorEngine ViewInfo np API bridge between NumSharp and Python NumPy np.Broadcast np.linalg Structs NDArray._Unsafe NDArray._Unsafe._Pinning NativeRandomState Represents the stored state of Randomizer. Shape Represents a shape of an N-D array. SliceDef Interfaces IIndex Represents a class that can be served as an index, e.g. ndarray[new Slice(...)] INumSharpException NDIterator Enums BackendType IteratorType NPTypeCode Represents all available types in numpy. StorageType Delegates MoveNextReferencedDelegate" + }, + "api/NumSharp.np.Broadcast.html": { + "href": "api/NumSharp.np.Broadcast.html", + "title": "Class np.Broadcast | NumSharp Documentation", + "summary": "Class np.Broadcast Namespace NumSharp Assembly NumSharp.dll public class np.Broadcast Inheritance object np.Broadcast Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Extension Methods LinqExtensions.Yield(T) Properties index public int index { get; } Property Value int iters public NDIterator[] iters { get; } Property Value NDIterator[] nd public int nd { get; } Property Value int ndim public int ndim { get; } Property Value int shape public Shape shape { get; } Property Value Shape size public int size { get; } Property Value int" + }, + "api/NumSharp.np.html": { + "href": "api/NumSharp.np.html", + "title": "Class np | NumSharp Documentation", + "summary": "Class np Namespace NumSharp Assembly NumSharp.dll API bridge between NumSharp and Python NumPy [SuppressMessage(\"ReSharper\", \"StaticMemberInitializerReferesToMemberBelow\")] public static class np Inheritance object np Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Fields bool public static readonly Type @bool Field Value Type bool8 public static readonly Type bool8 Field Value Type bool_ public static readonly Type bool_ Field Value Type byte public static readonly Type @byte Field Value Type char public static readonly Type @char Field Value Type complex128 public static readonly Type complex128 Field Value Type complex64 public static readonly Type complex64 Field Value Type complex_ public static readonly Type complex_ Field Value Type decimal public static readonly Type @decimal Field Value Type double public static readonly Type @double Field Value Type float32 public static readonly Type float32 Field Value Type float64 public static readonly Type float64 Field Value Type float_ public static readonly Type float_ Field Value Type int0 public static readonly Type int0 Field Value Type int16 public static readonly Type int16 Field Value Type int32 public static readonly Type int32 Field Value Type int64 public static readonly Type int64 Field Value Type int_ public static readonly Type int_ Field Value Type intp public static readonly Type intp Field Value Type newaxis A convenient alias for None, useful for indexing arrays. public static readonly Slice newaxis Field Value Slice Remarks https://docs.scipy.org/doc/numpy-1.17.0/reference/arrays.indexing.html https://stackoverflow.com/questions/42190783/what-does-three-dots-in-python-mean-when-indexing-what-looks-like-a-number ubyte public static readonly Type ubyte Field Value Type uint public static readonly Type @uint Field Value Type uint0 public static readonly Type uint0 Field Value Type uint16 public static readonly Type uint16 Field Value Type uint32 public static readonly Type uint32 Field Value Type uint64 public static readonly Type uint64 Field Value Type uint8 public static readonly Type uint8 Field Value Type Properties BackendEngine public static BackendType BackendEngine { get; set; } Property Value BackendType Inf public static double Inf { get; } Property Value double Infinity public static double Infinity { get; } Property Value double NAN public static double NAN { get; } Property Value double NINF public static double NINF { get; } Property Value double NaN public static double NaN { get; } Property Value double PINF public static double PINF { get; } Property Value double chars public static Type chars { get; } Property Value Type e public static double e { get; } Property Value double euler_gamma public static double euler_gamma { get; } Property Value double inf public static double inf { get; } Property Value double infinity public static double infinity { get; } Property Value double infty public static double infty { get; } Property Value double nan public static double nan { get; } Property Value double pi public static double pi { get; } Property Value double random public static NumPyRandom random { get; } Property Value NumPyRandom Methods LoadJagged(byte[]) public static Array LoadJagged(byte[] bytes) Parameters bytes byte[] Returns Array LoadJagged(Stream, bool) public static Array LoadJagged(Stream stream, bool trim = true) Parameters stream Stream trim bool Returns Array LoadJagged(string) public static Array LoadJagged(string path) Parameters path string Returns Array LoadJagged_Npz(byte[]) public static NpzDictionary LoadJagged_Npz(byte[] bytes) Parameters bytes byte[] Returns NpzDictionary LoadJagged_Npz(Stream, bool) public static NpzDictionary LoadJagged_Npz(Stream stream, bool trim = true) Parameters stream Stream trim bool Returns NpzDictionary LoadJagged_Npz(string) public static NpzDictionary LoadJagged_Npz(string path) Parameters path string Returns NpzDictionary LoadMatrix(byte[]) public static Array LoadMatrix(byte[] bytes) Parameters bytes byte[] Returns Array LoadMatrix(Stream) public static Array LoadMatrix(Stream stream) Parameters stream Stream Returns Array LoadMatrix(string) public static Array LoadMatrix(string path) Parameters path string Returns Array LoadMatrix_Npz(byte[]) public static NpzDictionary LoadMatrix_Npz(byte[] bytes) Parameters bytes byte[] Returns NpzDictionary LoadMatrix_Npz(Stream) public static NpzDictionary LoadMatrix_Npz(Stream stream) Parameters stream Stream Returns NpzDictionary LoadMatrix_Npz(string) public static NpzDictionary LoadMatrix_Npz(string path) Parameters path string Returns NpzDictionary Load_Npz(byte[]) public static NpzDictionary Load_Npz(byte[] bytes) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable Parameters bytes byte[] Returns NpzDictionary Type Parameters T Load_Npz(byte[], out T) public static void Load_Npz(byte[] bytes, out T value) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable Parameters bytes byte[] value T Type Parameters T Load_Npz(Stream) public static NpzDictionary Load_Npz(Stream stream) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable Parameters stream Stream Returns NpzDictionary Type Parameters T Load_Npz(Stream, out NpzDictionary) public static NpzDictionary Load_Npz(Stream stream, out NpzDictionary value) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable Parameters stream Stream value NpzDictionary Returns NpzDictionary Type Parameters T Load_Npz(Stream, out T) public static void Load_Npz(Stream stream, out T value) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable Parameters stream Stream value T Type Parameters T Load_Npz(string) public static NpzDictionary Load_Npz(string path) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable Parameters path string Returns NpzDictionary Type Parameters T Load_Npz(string, out NpzDictionary) public static NpzDictionary Load_Npz(string path, out NpzDictionary value) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable Parameters path string value NpzDictionary Returns NpzDictionary Type Parameters T Load_Npz(string, out T) public static void Load_Npz(string path, out T value) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable Parameters path string value T Type Parameters T Load(byte[]) public static T Load(byte[] bytes) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable Parameters bytes byte[] Returns T Type Parameters T Load(byte[], out T) public static T Load(byte[] bytes, out T value) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable Parameters bytes byte[] value T Returns T Type Parameters T Load(Stream) public static T Load(Stream stream) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable Parameters stream Stream Returns T Type Parameters T Load(Stream, out T) public static T Load(Stream stream, out T value) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable Parameters stream Stream value T Returns T Type Parameters T Load(string) public static T Load(string path) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable Parameters path string Returns T Type Parameters T Load(string, out T) public static T Load(string path, out T value) where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable Parameters path string value T Returns T Type Parameters T Save(Array) public static byte[] Save(Array array) Parameters array Array Returns byte[] Save(Array, Stream) public static ulong Save(Array array, Stream stream) Parameters array Array stream Stream Returns ulong Save(Array, string) public static ulong Save(Array array, string path) Parameters array Array path string Returns ulong Save_Npz(Array, CompressionLevel) public static byte[] Save_Npz(Array array, CompressionLevel compression = CompressionLevel.Fastest) Parameters array Array compression CompressionLevel Returns byte[] Save_Npz(Array, Stream, CompressionLevel, bool) public static void Save_Npz(Array array, Stream stream, CompressionLevel compression = CompressionLevel.Fastest, bool leaveOpen = false) Parameters array Array stream Stream compression CompressionLevel leaveOpen bool Save_Npz(Array, string, CompressionLevel) public static void Save_Npz(Array array, string path, CompressionLevel compression = CompressionLevel.Fastest) Parameters array Array path string compression CompressionLevel Save_Npz(Dictionary, CompressionLevel) public static byte[] Save_Npz(Dictionary arrays, CompressionLevel compression = CompressionLevel.Fastest) Parameters arrays Dictionary compression CompressionLevel Returns byte[] Save_Npz(Dictionary, Stream, CompressionLevel, bool) public static void Save_Npz(Dictionary arrays, Stream stream, CompressionLevel compression = CompressionLevel.Fastest, bool leaveOpen = false) Parameters arrays Dictionary stream Stream compression CompressionLevel leaveOpen bool Save_Npz(Dictionary, string, CompressionLevel) public static void Save_Npz(Dictionary arrays, string path, CompressionLevel compression = CompressionLevel.Fastest) Parameters arrays Dictionary path string compression CompressionLevel abs(in NDArray) Calculate the absolute value element-wise. np.abs is a shorthand for this function. public static NDArray abs(in NDArray a) Parameters a NDArray Input value. Returns NDArray An ndarray containing the absolute value of each element in x. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.absolute.html abs(in NDArray, NPTypeCode?) Calculate the absolute value element-wise. np.abs is a shorthand for this function. public static NDArray abs(in NDArray a, NPTypeCode? outType) Parameters a NDArray Input value. outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray An ndarray containing the absolute value of each element in x. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.absolute.html abs(in NDArray, Type) Calculate the absolute value element-wise. np.abs is a shorthand for this function. public static NDArray abs(in NDArray a, Type outType) Parameters a NDArray Input value. outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray An ndarray containing the absolute value of each element in x. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.absolute.html absolute(in NDArray) Calculate the absolute value element-wise. np.abs is a shorthand for this function. public static NDArray absolute(in NDArray a) Parameters a NDArray Input value. Returns NDArray An ndarray containing the absolute value of each element in x. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.absolute.html absolute(in NDArray, NPTypeCode?) Calculate the absolute value element-wise. np.abs is a shorthand for this function. public static NDArray absolute(in NDArray a, NPTypeCode? outType) Parameters a NDArray Input value. outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray An ndarray containing the absolute value of each element in x. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.absolute.html absolute(in NDArray, Type) Calculate the absolute value element-wise. np.abs is a shorthand for this function. public static NDArray absolute(in NDArray a, Type outType) Parameters a NDArray Input value. outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray An ndarray containing the absolute value of each element in x. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.absolute.html add(in NDArray, in NDArray) public static NDArray add(in NDArray x1, in NDArray x2) Parameters x1 NDArray x2 NDArray Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.add.html all(NDArray) Test whether all array elements along a given axis evaluate to True. public static bool all(NDArray a) Parameters a NDArray Input array or object that can be converted to an array. Returns bool A new boolean or ndarray is returned unless out is specified, in which case a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html all(NDArray, int, bool) Test whether all array elements along a given axis evaluate to True. public static NDArray all(NDArray nd, int axis, bool keepdims = false) Parameters nd NDArray axis int Axis or axes along which a logical AND reduction is performed. The default (axis = None) is to perform a logical OR over all the dimensions of the input array. axis may be negative, in which case it counts from the last to the first axis. keepdims bool Returns NDArray A new boolean or ndarray is returned unless out is specified, in which case a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html allclose(NDArray, NDArray, double, double, bool) Returns True if two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers.The relative difference (rtol * abs(b)) and the absolute difference atol are added together to compare against the absolute difference between a and b. If either array contains one or more NaNs, False is returned. Infs are treated as equal if they are in the same place and of the same sign in both arrays. public static bool allclose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false) Parameters a NDArray Input array to compare with b b NDArray Input array to compare with a. rtol double The relative tolerance parameter(see Notes) atol double The absolute tolerance parameter(see Notes) equal_nan bool Whether to compare NaN's as equal. If True, NaN's in a will be considered equal to NaN's in b in the output array. Returns bool amax(NDArray, int?, bool, Type) Return the maximum of an array or maximum along an axis. public static NDArray amax(NDArray a, int? axis = null, bool keepdims = false, Type dtype = null) Parameters a NDArray axis int? Axis or axes along which to operate. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. dtype Type the type expected as a return, null will remain the same dtype. Returns NDArray Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amax.html amax(NDArray) Return the maximum of an array or maximum along an axis. public static T amax(NDArray a) where T : unmanaged Parameters a NDArray Returns T Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Type Parameters T the type expected as a return, cast is performed if necessary. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amax.html amin(in NDArray, int?, bool, Type) Return the minimum of an array or minimum along an axis. public static NDArray amin(in NDArray a, int? axis = null, bool keepdims = false, Type dtype = null) Parameters a NDArray Input data. axis int? Axis or axes along which to operate. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. dtype Type the type expected as a return, null will remain the same dtype. Returns NDArray Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amin.html amin(in NDArray) Return the minimum of an array or minimum along an axis. public static T amin(in NDArray a) where T : unmanaged Parameters a NDArray Input data. Returns T Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Type Parameters T the type expected as a return, cast is performed if necessary. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amin.html any(NDArray) Test whether any array element along a given axis evaluates to True. public static bool any(NDArray a) Parameters a NDArray Input array or object that can be converted to an array. Returns bool A new boolean or ndarray is returned unless out is specified, in which case a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.any.html any(NDArray, int, bool) Test whether any array element along a given axis evaluates to True. public static NDArray any(NDArray nd, int axis, bool keepdims) Parameters nd NDArray axis int Axis or axes along which a logical OR reduction is performed. The default (axis = None) is to perform a logical OR over all the dimensions of the input array. axis may be negative, in which case it counts from the last to the first axis. keepdims bool Returns NDArray A new boolean or ndarray is returned unless out is specified, in which case a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.any.html arange(double) Return evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list. When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use numpy.linspace for these cases. public static NDArray arange(double stop) Parameters stop double End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out. Returns NDArray Array of evenly spaced values. For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop. arange(double, double, double) Return evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list. When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use numpy.linspace for these cases. public static NDArray arange(double start, double stop, double step = 1) Parameters start double Start of interval. The interval includes this value. The default start value is 0. stop double End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out. step double Spacing between values. For any output out, this is the distance between two adjacent values, out[i+1] - out[i]. The default step size is 1. If step is specified as a position argument, start must also be given. Returns NDArray Array of evenly spaced values. For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop. arange(int) Return evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list. When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use numpy.linspace for these cases. public static NDArray arange(int stop) Parameters stop int End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out. Returns NDArray Array of evenly spaced values. For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop. arange(int, int, int) Return evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list. When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use numpy.linspace for these cases. public static NDArray arange(int start, int stop, int step = 1) Parameters start int Start of interval. The interval includes this value. The default start value is 0. stop int End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out. step int Spacing between values. For any output out, this is the distance between two adjacent values, out[i+1] - out[i]. The default step size is 1. If step is specified as a position argument, start must also be given. Returns NDArray Array of evenly spaced values. For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop. arange(float) Return evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list. When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use numpy.linspace for these cases. public static NDArray arange(float stop) Parameters stop float End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out. Returns NDArray Array of evenly spaced values. For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop. arange(float, float, float) Return evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list. When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use numpy.linspace for these cases. public static NDArray arange(float start, float stop, float step = 1) Parameters start float Start of interval. The interval includes this value. The default start value is 0. stop float End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out. step float Spacing between values. For any output out, this is the distance between two adjacent values, out[i+1] - out[i]. The default step size is 1. If step is specified as a position argument, start must also be given. Returns NDArray Array of evenly spaced values. For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop. arccos(in NDArray, NPTypeCode?) Trigonometric inverse cosine, element-wise. The inverse of cos so that, if y = cos(x), then x = arccos(y). public static NDArray arccos(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray Input array. outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The angle of the ray intersecting the unit circle at the given x-coordinate in radians [0, pi]. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.arccos.html arccos(in NDArray, Type) Trigonometric inverse cosine, element-wise. The inverse of cos so that, if y = cos(x), then x = arccos(y). public static NDArray arccos(in NDArray x, Type outType) Parameters x NDArray Input array. outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The angle of the ray intersecting the unit circle at the given x-coordinate in radians [0, pi]. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.arccos.html arcsin(in NDArray, NPTypeCode?) Inverse sine, element-wise. The convention is to return the angle z whose real part lies in [-pi/2, pi/2]. public static NDArray arcsin(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray Input array. outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The inverse sine of each element in x, in radians and in the closed interval [-pi/2, pi/2]. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.arcsin.html arcsin(in NDArray, Type) Inverse sine, element-wise. The convention is to return the angle z whose real part lies in [-pi/2, pi/2]. public static NDArray arcsin(in NDArray x, Type outType) Parameters x NDArray Input array. outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The inverse sine of each element in x, in radians and in the closed interval [-pi/2, pi/2]. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.arcsin.html arctan(in NDArray, NPTypeCode?) Compute trigonometric inverse tangent, element-wise. The inverse of tan, so that if y = tan(x) then x = arctan(y). public static NDArray arctan(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray Input array. outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray Return has the same shape as x. Its real part is in [-pi/2, pi/2] (arctan(+/-inf) returns +/-pi/2). This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.arctan.html arctan(in NDArray, Type) Compute trigonometric inverse tangent, element-wise. The inverse of tan, so that if y = tan(x) then x = arctan(y). public static NDArray arctan(in NDArray x, Type outType) Parameters x NDArray Input array. outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray Return has the same shape as x. Its real part is in [-pi/2, pi/2] (arctan(+/-inf) returns +/-pi/2). This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.arctan.html arctan2(in NDArray, in NDArray, NPTypeCode?) Compute Element-wise arc tangent of x1/x2 choosing the quadrant correctly. By IEEE convention, this function is defined for x2 = +/-0 and for either or both of x1 and x2 = +/-inf public static NDArray arctan2(in NDArray y, in NDArray x, NPTypeCode? outType = null) Parameters y NDArray x NDArray Input array y-coordinates. outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The Array of angles in radians, in the range [-pi, pi]. This is a scalar if both x1 and x2 are scalars. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.arctan2.html arctan2(in NDArray, in NDArray, Type) Compute Element-wise arc tangent of x1/x2 choosing the quadrant correctly. By IEEE convention, this function is defined for x2 = +/-0 and for either or both of x1 and x2 = +/-inf public static NDArray arctan2(in NDArray y, in NDArray x, Type outType) Parameters y NDArray x NDArray Input array y-coordinates. outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The Array of angles in radians, in the range [-pi, pi]. This is a scalar if both x1 and x2 are scalars. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.arctan2.html are_broadcastable(NDArray, NDArray) Tests if these two two arrays are broadcastable against each other. public static bool are_broadcastable(NDArray lhs, NDArray rhs) Parameters lhs NDArray An array to test for broadcasting. rhs NDArray An array to test for broadcasting. Returns bool True if these can be broadcasted against each other. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_arrays.html are_broadcastable(params NDArray[]) Tests if these two two arrays are broadcastable against each other. public static bool are_broadcastable(params NDArray[] ndArrays) Parameters ndArrays NDArray[] The arrays to test for broadcasting. Returns bool True if these can be broadcasted against each other. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_arrays.html are_broadcastable(params Shape[]) Tests if these two two arrays are broadcastable against each other. public static bool are_broadcastable(params Shape[] shapes) Parameters shapes Shape[] The shapes to test for broadcasting. Returns bool True if these can be broadcasted against each other. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_arrays.html are_broadcastable(params int[][]) Tests if these two two arrays are broadcastable against each other. public static bool are_broadcastable(params int[][] shapes) Parameters shapes int[][] The shapes to test for broadcasting. Returns bool True if these can be broadcasted against each other. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_arrays.html argmax(NDArray) Returns the index of the maximum value. public static int argmax(NDArray a) Parameters a NDArray Input array. Returns int Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html argmax(NDArray, int) Returns the indices of the maximum values along an axis. public static NDArray argmax(NDArray a, int axis) Parameters a NDArray Input array. axis int By default, the index is into the flattened array, otherwise along the specified axis. Returns NDArray Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html argmin(NDArray) Returns the index of the minimum value. public static int argmin(NDArray a) Parameters a NDArray Input array. Returns int Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html argmin(NDArray, int) Returns the indices of the minimum values along an axis. public static NDArray argmin(NDArray a, int axis) Parameters a NDArray Input array. axis int By default, the index is into the flattened array, otherwise along the specified axis. Returns NDArray Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html argsort(NDArray, int) Returns the indices that would sort an array. Perform an indirect sort along the given axis using the algorithm specified by the kind keyword.It returns an array of indices of the same shape as a that index data along the given axis in sorted order. public static NDArray argsort(NDArray nd, int axis = -1) Parameters nd NDArray axis int Returns NDArray Type Parameters T around(in NDArray, int, NPTypeCode?) Evenly round to the given number of decimals. public static NDArray around(in NDArray x, int decimals, NPTypeCode? outType = null) Parameters x NDArray Input array decimals int Number of decimal places to round to outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. The real and imaginary parts of complex numbers are rounded separately.The result of rounding a float is a float. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.around.html around(in NDArray, int, Type) Evenly round to the given number of decimals. public static NDArray around(in NDArray x, int decimals, Type outType) Parameters x NDArray Input array decimals int Number of decimal places to round to outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. The real and imaginary parts of complex numbers are rounded separately.The result of rounding a float is a float. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.around.html around(in NDArray, NPTypeCode?) Evenly round to the given number of decimals. public static NDArray around(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray Input array outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. The real and imaginary parts of complex numbers are rounded separately.The result of rounding a float is a float. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.around.html around(in NDArray, Type) Evenly round to the given number of decimals. public static NDArray around(in NDArray x, Type outType) Parameters x NDArray Input array outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. The real and imaginary parts of complex numbers are rounded separately.The result of rounding a float is a float. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.around.html array(NDArray, bool) Wraps given nd in an alias. If copy is true then returns a clone. public static NDArray array(NDArray nd, bool copy = false) Parameters nd NDArray copy bool If copy is true then returns a clone. Returns NDArray array(Array, Type, int, bool, char) Creates an NDArray from an array with an unknown size or dtype. [SuppressMessage(\"ReSharper\", \"InvalidXmlDocComment\")] public static NDArray array(Array array, Type dtype = null, int ndmin = 1, bool copy = true, char order = 'C') Parameters array Array dtype Type ndmin int Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement. copy bool Always copies if the array is larger than 1-d. order char Not used. Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html array(string) Create a vector NDArray of dtype char. public static NDArray array(string chars) Parameters chars string Returns NDArray array(string[]) Create a vector ndarray of type . Encode string array. format: [numOfRow lenOfRow1 lenOfRow2 contents] sample: [2 2 4 aacccc] public static NDArray array(string[] strArray) Parameters strArray string[] Returns NDArray array_equal(NDArray, NDArray) True if two arrays have the same shape and elements, False otherwise. public static bool array_equal(NDArray a, NDArray b) Parameters a NDArray Input array. b NDArray Input array. Returns bool Returns True if the arrays are equal. Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.array_equal.html array(IEnumerable) Creates a Vector NDArray from given data. public static NDArray array(IEnumerable data) where T : unmanaged Parameters data IEnumerable The enumeration of data to create NDArray from. Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html Always performs a copy. array(IEnumerable, int) Creates a Vector NDArray from given data. public static NDArray array(IEnumerable data, int size) where T : unmanaged Parameters data IEnumerable The enumeration of data to create NDArray from. size int Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html Always performs a copy. size can be used to limit the amount of items to read form data. Reading stops on either size or data ends. array(T[,,,,,,,,,,,,,,,], bool) Creates an NDArray from given data. public static NDArray array(T[,,,,,,,,,,,,,,,] data, bool copy = true) where T : unmanaged Parameters data T[,,,,,,,,,,,,,,,] The array to create NDArray from. copy bool If true then the array will be copied to a newly allocated memory. If false then the array will be pinned by calling Alloc(object). Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html array(T[,,,,,,,,,,,,,,], bool) Creates an NDArray from given data. public static NDArray array(T[,,,,,,,,,,,,,,] data, bool copy = true) where T : unmanaged Parameters data T[,,,,,,,,,,,,,,] The array to create NDArray from. copy bool If true then the array will be copied to a newly allocated memory. If false then the array will be pinned by calling Alloc(object). Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html array(T[,,,,,,,,,,,,,], bool) Creates an NDArray from given data. public static NDArray array(T[,,,,,,,,,,,,,] data, bool copy = true) where T : unmanaged Parameters data T[,,,,,,,,,,,,,] The array to create NDArray from. copy bool If true then the array will be copied to a newly allocated memory. If false then the array will be pinned by calling Alloc(object). Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html array(T[,,,,,,,,,,,,], bool) Creates an NDArray from given data. public static NDArray array(T[,,,,,,,,,,,,] data, bool copy = true) where T : unmanaged Parameters data T[,,,,,,,,,,,,] The array to create NDArray from. copy bool If true then the array will be copied to a newly allocated memory. If false then the array will be pinned by calling Alloc(object). Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html array(T[,,,,,,,,,,,], bool) Creates an NDArray from given data. public static NDArray array(T[,,,,,,,,,,,] data, bool copy = true) where T : unmanaged Parameters data T[,,,,,,,,,,,] The array to create NDArray from. copy bool If true then the array will be copied to a newly allocated memory. If false then the array will be pinned by calling Alloc(object). Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html array(T[,,,,,,,,,,], bool) Creates an NDArray from given data. public static NDArray array(T[,,,,,,,,,,] data, bool copy = true) where T : unmanaged Parameters data T[,,,,,,,,,,] The array to create NDArray from. copy bool If true then the array will be copied to a newly allocated memory. If false then the array will be pinned by calling Alloc(object). Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html array(T[,,,,,,,,,], bool) Creates an NDArray from given data. public static NDArray array(T[,,,,,,,,,] data, bool copy = true) where T : unmanaged Parameters data T[,,,,,,,,,] The array to create NDArray from. copy bool If true then the array will be copied to a newly allocated memory. If false then the array will be pinned by calling Alloc(object). Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html array(T[,,,,,,,,], bool) Creates an NDArray from given data. public static NDArray array(T[,,,,,,,,] data, bool copy = true) where T : unmanaged Parameters data T[,,,,,,,,] The array to create NDArray from. copy bool If true then the array will be copied to a newly allocated memory. If false then the array will be pinned by calling Alloc(object). Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html array(T[,,,,,,,], bool) Creates an NDArray from given data. public static NDArray array(T[,,,,,,,] data, bool copy = true) where T : unmanaged Parameters data T[,,,,,,,] The array to create NDArray from. copy bool If true then the array will be copied to a newly allocated memory. If false then the array will be pinned by calling Alloc(object). Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html array(T[,,,,,,], bool) Creates an NDArray from given data. public static NDArray array(T[,,,,,,] data, bool copy = true) where T : unmanaged Parameters data T[,,,,,,] The array to create NDArray from. copy bool If true then the array will be copied to a newly allocated memory. If false then the array will be pinned by calling Alloc(object). Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html array(T[,,,,,], bool) Creates an NDArray from given data. public static NDArray array(T[,,,,,] data, bool copy = true) where T : unmanaged Parameters data T[,,,,,] The array to create NDArray from. copy bool If true then the array will be copied to a newly allocated memory. If false then the array will be pinned by calling Alloc(object). Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html array(T[,,,,], bool) Creates an NDArray from given data. public static NDArray array(T[,,,,] data, bool copy = true) where T : unmanaged Parameters data T[,,,,] The array to create NDArray from. copy bool If true then the array will be copied to a newly allocated memory. If false then the array will be pinned by calling Alloc(object). Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html array(T[,,,], bool) Creates an NDArray from given data. public static NDArray array(T[,,,] data, bool copy = true) where T : unmanaged Parameters data T[,,,] The array to create NDArray from. copy bool If true then the array will be copied to a newly allocated memory. If false then the array will be pinned by calling Alloc(object). Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html array(T[,,], bool) Creates an NDArray from given data. public static NDArray array(T[,,] data, bool copy = true) where T : unmanaged Parameters data T[,,] The array to create NDArray from. copy bool If true then the array will be copied to a newly allocated memory. If false then the array will be pinned by calling Alloc(object). Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html array(T[,], bool) Creates an NDArray from given data. public static NDArray array(T[,] data, bool copy = true) where T : unmanaged Parameters data T[,] The array to create NDArray from. copy bool If true then the array will be copied to a newly allocated memory. If false then the array will be pinned by calling Alloc(object). Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html array(params T[]) Creates a Vector NDArray from given data. public static NDArray array(params T[] data) where T : unmanaged Parameters data T[] The array to create NDArray from. Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html Always performs a copy. array(T[], bool) Creates an NDArray from given data. public static NDArray array(T[] data, bool copy) where T : unmanaged Parameters data T[] The array to create NDArray from. copy bool If true then the array will be copied to a newly allocated memory. If false then the array will be pinned by calling Alloc(object). Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html array(T[][]) Creates an NDArray from given data. [SuppressMessage(\"ReSharper\", \"SuggestVarOrType_SimpleTypes\")] [SuppressMessage(\"ReSharper\", \"SuggestVarOrType_Elsewhere\")] public static NDArray array(T[][] data) where T : unmanaged Parameters data T[][] The array to create NDArray from. Shape is taken from the first item of each array/nested array. Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html Always performs a copy. array(T[][][]) Creates an NDArray from given data. [SuppressMessage(\"ReSharper\", \"SuggestVarOrType_SimpleTypes\")] [SuppressMessage(\"ReSharper\", \"SuggestVarOrType_Elsewhere\")] public static NDArray array(T[][][] data) where T : unmanaged Parameters data T[][][] The array to create NDArray from. Shape is taken from the first item of each array/nested array. Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html Always performs a copy. array(T[][][][]) Creates an NDArray from given data. [SuppressMessage(\"ReSharper\", \"SuggestVarOrType_SimpleTypes\")] [SuppressMessage(\"ReSharper\", \"SuggestVarOrType_Elsewhere\")] public static NDArray array(T[][][][] data) where T : unmanaged Parameters data T[][][][] The array to create NDArray from. Shape is taken from the first item of each array/nested array. Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html Always performs a copy. array(T[][][][][]) Creates an NDArray from given data. [SuppressMessage(\"ReSharper\", \"SuggestVarOrType_SimpleTypes\")] [SuppressMessage(\"ReSharper\", \"SuggestVarOrType_Elsewhere\")] public static NDArray array(T[][][][][] data) where T : unmanaged Parameters data T[][][][][] The array to create NDArray from. Shape is taken from the first item of each array/nested array. Returns NDArray An NDArray with the data and shape of the given array. Type Parameters T The type of given array, must be compliant to numpy's supported dtypes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html Always performs a copy. asanyarray(in object, Type) Convert the input to an ndarray, but pass ndarray subclasses through. public static NDArray asanyarray(in object a, Type dtype = null) Parameters a object Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays. dtype Type By default, the data-type is inferred from the input data. Returns NDArray Array interpretation of a. If a is an ndarray or a subclass of ndarray, it is returned as-is and no copy is performed. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.asanyarray.html asarray(string) public static NDArray asarray(string data) Parameters data string Returns NDArray asarray(string[], int) public static NDArray asarray(string[] data, int ndim = 1) Parameters data string[] ndim int Returns NDArray asarray(T) public static NDArray asarray(T data) where T : struct Parameters data T Returns NDArray Type Parameters T asarray(T[], int) public static NDArray asarray(T[] data, int ndim = 1) where T : struct Parameters data T[] ndim int Returns NDArray Type Parameters T asscalar(NDArray) Convert an array of size 1 to its scalar equivalent. public static ValueType asscalar(NDArray nd) Parameters nd NDArray Input NDArray of size 1. Returns ValueType Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.asscalar.html asscalar(Array) Convert an array of size 1 to its scalar equivalent. public static ValueType asscalar(Array arr) Parameters arr Array Input array of size 1. Returns ValueType Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.asscalar.html asscalar(ArraySlice) Convert an array of size 1 to its scalar equivalent. public static T asscalar(ArraySlice arr) where T : unmanaged Parameters arr ArraySlice Input array of size 1. Returns T Type Parameters T Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.asscalar.html asscalar(IArraySlice) Convert an array of size 1 to its scalar equivalent. public static T asscalar(IArraySlice arr) where T : unmanaged Parameters arr IArraySlice Input array of size 1. Returns T Type Parameters T Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.asscalar.html asscalar(NDArray) Convert an array of size 1 to its scalar equivalent. public static T asscalar(NDArray nd) where T : unmanaged Parameters nd NDArray Input NDArray of size 1. Returns T Type Parameters T Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.asscalar.html asscalar(Array) Convert an array of size 1 to its scalar equivalent. public static T asscalar(Array arr) Parameters arr Array Input array of size 1. Returns T Type Parameters T Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.asscalar.html atleast_1d(NDArray) Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved. public static NDArray atleast_1d(NDArray arr) Parameters arr NDArray Returns NDArray An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_1d.html atleast_1d(params NDArray[]) Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved. public static NDArray[] atleast_1d(params NDArray[] arys) Parameters arys NDArray[] One or more input arrays. Returns NDArray[] An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_1d.html atleast_1d(object) Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved. public static NDArray atleast_1d(object arys) Parameters arys object One or more input arrays. Returns NDArray An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_1d.html atleast_1d(params object[]) Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved. public static NDArray[] atleast_1d(params object[] arys) Parameters arys object[] One or more input arrays. Returns NDArray[] An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_1d.html atleast_2d(NDArray) View inputs as arrays with at least two dimensions. public static NDArray atleast_2d(NDArray arr) Parameters arr NDArray One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved. Returns NDArray An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_2d.html atleast_2d(params NDArray[]) View inputs as arrays with at least two dimensions. public static NDArray[] atleast_2d(params NDArray[] arys) Parameters arys NDArray[] One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved. Returns NDArray[] An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_2d.html atleast_2d(object) View inputs as arrays with at least two dimensions. public static NDArray atleast_2d(object arys) Parameters arys object One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved. Returns NDArray An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_2d.html atleast_2d(params object[]) View inputs as arrays with at least two dimensions. public static NDArray[] atleast_2d(params object[] arys) Parameters arys object[] One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved. Returns NDArray[] An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_2d.html atleast_3d(NDArray) View inputs as arrays with at least three dimensions. public static NDArray atleast_3d(NDArray arr) Parameters arr NDArray Returns NDArray An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1). Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_3d.html atleast_3d(params NDArray[]) View inputs as arrays with at least three dimensions. public static NDArray[] atleast_3d(params NDArray[] arys) Parameters arys NDArray[] One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved. Returns NDArray[] An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1). Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_3d.html atleast_3d(object) View inputs as arrays with at least three dimensions. public static NDArray atleast_3d(object arys) Parameters arys object One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved. Returns NDArray An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1). Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_3d.html atleast_3d(params object[]) View inputs as arrays with at least three dimensions. public static NDArray[] atleast_3d(params object[] arys) Parameters arys object[] One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved. Returns NDArray[] An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1). Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_3d.html broadcast(NDArray, NDArray) Produce an object that mimics broadcasting. public static np.Broadcast broadcast(NDArray nd1, NDArray nd2) Parameters nd1 NDArray nd2 NDArray Returns np.Broadcast Broadcast the input parameters against one another, and return an object that encapsulates the result. Amongst others, it has shape and nd properties, and may be used as an iterator. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast.html broadcast_arrays(NDArray, NDArray) Broadcast two arrays against each other. public static (NDArray Lhs, NDArray Rhs) broadcast_arrays(NDArray lhs, NDArray rhs) Parameters lhs NDArray An array to broadcast. rhs NDArray An array to broadcast. Returns (NDArray Lhs, NDArray Rhs) These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_arrays.html broadcast_arrays(params NDArray[]) Broadcast any number of arrays against each other. public static NDArray[] broadcast_arrays(params NDArray[] ndArrays) Parameters ndArrays NDArray[] The arrays to broadcast. Returns NDArray[] These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_arrays.html broadcast_to(UnmanagedStorage, UnmanagedStorage) Broadcast an array to a new shape. public static NDArray broadcast_to(UnmanagedStorage from, UnmanagedStorage against) Parameters from UnmanagedStorage The UnmanagedStorage to broadcast. against UnmanagedStorage The shape to broadcast against. Returns NDArray These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_to.html broadcast_to(UnmanagedStorage, NDArray) Broadcast an array to a new shape. public static NDArray broadcast_to(UnmanagedStorage from, NDArray against) Parameters from UnmanagedStorage The UnmanagedStorage to broadcast. against NDArray The shape to broadcast against. Returns NDArray These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_to.html broadcast_to(UnmanagedStorage, Shape) Broadcast an array to a new shape. public static NDArray broadcast_to(UnmanagedStorage from, Shape against) Parameters from UnmanagedStorage The NDArray to broadcast. against Shape The shape to broadcast against. Returns NDArray These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_to.html broadcast_to(NDArray, UnmanagedStorage) Broadcast an array to a new shape. public static NDArray broadcast_to(NDArray from, UnmanagedStorage against) Parameters from NDArray The NDArray to broadcast. against UnmanagedStorage The shape to broadcast against. Returns NDArray These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_to.html broadcast_to(NDArray, NDArray) Broadcast an array to a new shape. public static NDArray broadcast_to(NDArray from, NDArray against) Parameters from NDArray The NDArray to broadcast. against NDArray The shape to broadcast against. Returns NDArray These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_to.html broadcast_to(NDArray, Shape) Broadcast an array to a new shape. public static NDArray broadcast_to(NDArray from, Shape against) Parameters from NDArray The NDArray to broadcast. against Shape The shape to broadcast against. Returns NDArray These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_to.html broadcast_to(Shape, UnmanagedStorage) Broadcast an shape against an other new shape. public static Shape broadcast_to(Shape from, UnmanagedStorage against) Parameters from Shape The shape that is to be broadcasted against UnmanagedStorage The shape that'll be used to broadcast from shape Returns Shape A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_to.html broadcast_to(Shape, NDArray) Broadcast an shape against an other new shape. public static Shape broadcast_to(Shape from, NDArray against) Parameters from Shape The shape that is to be broadcasted against NDArray The shape that'll be used to broadcast from shape Returns Shape A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_to.html broadcast_to(Shape, Shape) Broadcast an shape against an other new shape. public static Shape broadcast_to(Shape from, Shape against) Parameters from Shape The shape that is to be broadcasted against Shape The shape that'll be used to broadcast from shape Returns Shape A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_to.html ceil(in NDArray, NPTypeCode?) Return the ceiling of the input, element-wise. The ceil of the scalar x is the smallest integer i, such that i >= x. It is often denoted as \\lceil x \\rceil. public static NDArray ceil(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray Input data. outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The ceiling of each element in x, with float dtype. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ceil.html ceil(in NDArray, Type) Return the ceiling of the input, element-wise. The ceil of the scalar x is the smallest integer i, such that i >= x. It is often denoted as \\lceil x \\rceil. public static NDArray ceil(in NDArray x, Type outType) Parameters x NDArray Input data. outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The ceiling of each element in x, with float dtype. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ceil.html clip(in NDArray, NDArray, NDArray, NDArray) Clip (limit) the values in an array. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1. public static NDArray clip(in NDArray a, NDArray a_min, NDArray a_max, NDArray @out) Parameters a NDArray Array containing elements to clip. a_min NDArray Minimum value. If None, clipping is not performed on lower interval edge. Not more than one of a_min and a_max may be None. a_max NDArray Maximum value. If None, clipping is not performed on upper interval edge. Not more than one of a_min and a_max may be None. out NDArray The results will be placed in this array. It may be the input array for in-place clipping. out must be of the right shape to hold the output. Its type is preserved. Returns NDArray An array with the elements of a, but where values < a_min are replaced with a_min, and those > a_max with a_max. Remarks https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.clip.html clip(in NDArray, NDArray, NDArray, NPTypeCode?) Clip (limit) the values in an array. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1. public static NDArray clip(in NDArray a, NDArray a_min, NDArray a_max, NPTypeCode? outType = null) Parameters a NDArray Array containing elements to clip. a_min NDArray Minimum value. If None, clipping is not performed on lower interval edge. Not more than one of a_min and a_max may be None. a_max NDArray Maximum value. If None, clipping is not performed on upper interval edge. Not more than one of a_min and a_max may be None. outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray An array with the elements of a, but where values < a_min are replaced with a_min, and those > a_max with a_max. Remarks https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.clip.html clip(in NDArray, NDArray, NDArray, Type) Clip (limit) the values in an array. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1. public static NDArray clip(in NDArray a, NDArray a_min, NDArray a_max, Type outType) Parameters a NDArray Array containing elements to clip. a_min NDArray Minimum value. If None, clipping is not performed on lower interval edge. Not more than one of a_min and a_max may be None. a_max NDArray Maximum value. If None, clipping is not performed on upper interval edge. Not more than one of a_min and a_max may be None. outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray An array with the elements of a, but where values < a_min are replaced with a_min, and those > a_max with a_max. Remarks https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.clip.html concatenate(NDArray[], int) Join a sequence of arrays along an existing axis. public static NDArray concatenate(NDArray[] arrays, int axis = 0) Parameters arrays NDArray[] The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default). axis int The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0. Returns NDArray The concatenated array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int) Join a sequence of arrays along an existing axis. public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0) Parameters arrays (NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default). axis int The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0. Returns NDArray The concatenated array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int) Join a sequence of arrays along an existing axis. public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0) Parameters arrays (NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default). axis int The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0. Returns NDArray The concatenated array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int) Join a sequence of arrays along an existing axis. public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0) Parameters arrays (NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default). axis int The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0. Returns NDArray The concatenated array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int) Join a sequence of arrays along an existing axis. public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0) Parameters arrays (NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default). axis int The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0. Returns NDArray The concatenated array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html concatenate((NDArray, NDArray, NDArray, NDArray, NDArray), int) Join a sequence of arrays along an existing axis. public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0) Parameters arrays (NDArray, NDArray, NDArray, NDArray, NDArray) The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default). axis int The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0. Returns NDArray The concatenated array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html concatenate((NDArray, NDArray, NDArray, NDArray), int) Join a sequence of arrays along an existing axis. public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0) Parameters arrays (NDArray, NDArray, NDArray, NDArray) The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default). axis int The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0. Returns NDArray The concatenated array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html concatenate((NDArray, NDArray, NDArray), int) Join a sequence of arrays along an existing axis. public static NDArray concatenate((NDArray, NDArray, NDArray) arrays, int axis = 0) Parameters arrays (NDArray, NDArray, NDArray) The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default). axis int The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0. Returns NDArray The concatenated array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html concatenate((NDArray, NDArray), int) Join a sequence of arrays along an existing axis. public static NDArray concatenate((NDArray, NDArray) arrays, int axis = 0) Parameters arrays (NDArray Lhs, NDArray Rhs) The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default). axis int The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0. Returns NDArray The concatenated array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html convolve(NDArray, NDArray, string) Returns the discrete, linear convolution of two one-dimensional sequences. The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal[1]. In probability theory, the sum of two independent random variables is distributed according to the convolution of their individual distributions. If v is longer than a, the arrays are swapped before computation. public static NDArray convolve(NDArray a, NDArray v, string mode = \"full\") Parameters a NDArray v NDArray mode string Returns NDArray copy(NDArray, char) Return a copy of the array. public static NDArray copy(NDArray a, char order = 'C') Parameters a NDArray Input data. order char Returns NDArray Array interpretation of a. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.copy.html copyto(NDArray, NDArray) Copies values from one array to another, broadcasting as necessary. public static void copyto(NDArray dst, NDArray src) Parameters dst NDArray The array into which values are copied. src NDArray The array from which values are copied. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.copyto.html cos(in NDArray, NPTypeCode?) Cosine element-wise. public static NDArray cos(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray Input array in radians. outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The sine of each element of x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.cos.html cos(in NDArray, Type) Cosine element-wise. public static NDArray cos(in NDArray x, Type outType) Parameters x NDArray Input array in radians. outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The sine of each element of x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.cos.html cosh(in NDArray, NPTypeCode?) Hyperbolic cosine, element-wise. Equivalent to 1/2 * (np.exp(x) + np.exp(-x)) and np.cos(1j* x). public static NDArray cosh(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray Input array. outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray Output array of same shape as x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.cosh.html cosh(in NDArray, Type) Hyperbolic cosine, element-wise. Equivalent to 1/2 * (np.exp(x) + np.exp(-x)) and np.cos(1j* x). public static NDArray cosh(in NDArray x, Type outType) Parameters x NDArray Input array. outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray Output array of same shape as x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.cosh.html cumsum(NDArray, int?, NPTypeCode?) Return the cumulative sum of the elements along a given axis. public static NDArray cumsum(NDArray arr, int? axis = null, NPTypeCode? typeCode = null) Parameters arr NDArray Input array. axis int? Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array. typeCode NPTypeCode? Type of the returned array and of the accumulator in which the elements are summed. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used. Returns NDArray A new array holding the result is returned unless out is specified, in which case a reference to out is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html divide(in NDArray, in NDArray) public static NDArray divide(in NDArray x1, in NDArray x2) Parameters x1 NDArray x2 NDArray Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.divide.html dot(in NDArray, in NDArray) Dot product of two arrays. See remarks. public static NDArray dot(in NDArray a, in NDArray b) Parameters a NDArray Lhs, First argument. b NDArray Rhs, Second argument. Returns NDArray Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If out is given, then it is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html Specifically, - If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation). - If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred. - If either a or b is 0-D(scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a* b is preferred. - If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b. - If a is an N-D array and b is an M-D array(where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b: dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m]) dstack(params NDArray[]) Stack arrays in sequence depth wise (along third axis). This is equivalent to concatenation along the third axis after 2-D arrays of shape(M, N) have been reshaped to(M, N,1) and 1-D arrays of shape(N,) have been reshaped to(1, N,1). Rebuilds arrays divided by dsplit. This function makes most sense for arrays with up to 3 dimensions.For instance, for pixel-data with a height(first axis), width(second axis), and r/g/b channels(third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations. public static NDArray dstack(params NDArray[] tup) Parameters tup NDArray[] The arrays must have the same shape along all but the third axis. 1-D or 2-D arrays must have the same shape. Returns NDArray The array formed by stacking the given arrays, will be at least 3-D. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.dstack.html dtype(string) Parse a string into a DType. public static DType dtype(string dtype) Parameters dtype string Returns DType A DType based on dtype, return can be null. Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/arrays.dtypes.html This was created to ease the porting of C++ numpy to C#. empty(Shape) Return a new array of given shape and type, without initializing entries. public static NDArray empty(Shape shape) Parameters shape Shape Shape of the empty array, e.g., (2, 3) or 2. Returns NDArray Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html empty(Shape, NPTypeCode) Return a new array of given shape and type, without initializing entries. public static NDArray empty(Shape shape, NPTypeCode typeCode) Parameters shape Shape Shape of the empty array, e.g., (2, 3) or 2. typeCode NPTypeCode Desired output data-type for the array, e.g, numpy.int8. Default is numpy.float64. Returns NDArray Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html empty(Shape, Type) Return a new array of given shape and type, without initializing entries. public static NDArray empty(Shape shape, Type dtype) Parameters shape Shape Shape of the empty array, e.g., (2, 3) or 2. dtype Type Desired output data-type for the array, e.g, numpy.int8. Default is numpy.float64. Returns NDArray Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html empty(params int[]) Return a new array of given shape and type, without initializing entries. public static NDArray empty(params int[] shapes) Parameters shapes int[] Shape of the empty array, e.g., (2, 3) or 2. Returns NDArray Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html empty_like(NDArray, Type) Return a new array with the same shape and type as a given array. public static NDArray empty_like(NDArray prototype, Type dtype = null) Parameters prototype NDArray The shape and data-type of prototype define these same attributes of the returned array. dtype Type Overrides the data type of the result. Returns NDArray Array of uninitialized (arbitrary) data with the same shape and type as prototype. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.empty_like.html empty(params int[]) Return a new array of given shape and type, without initializing entries. public static NDArray empty(params int[] shapes) Parameters shapes int[] Shape of the empty array, e.g., (2, 3) or 2. Returns NDArray Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None. Type Parameters T Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html exp(in NDArray) Base-e exponential, element-wise. public static NDArray exp(in NDArray a) Parameters a NDArray Input value. Returns NDArray The natural logarithm of x, element-wise. This is a scalar NDArray. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.exp.html exp(in NDArray, NPTypeCode) Base-e exponential, element-wise. public static NDArray exp(in NDArray a, NPTypeCode typeCode) Parameters a NDArray Input value. typeCode NPTypeCode The dtype of the returned NDArray Returns NDArray The natural logarithm of x, element-wise. This is a scalar NDArray. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.exp.html exp(in NDArray, Type) Base-e exponential, element-wise. public static NDArray exp(in NDArray a, Type dtype) Parameters a NDArray Input value. dtype Type The dtype of the returned NDArray Returns NDArray The natural logarithm of x, element-wise. This is a scalar NDArray. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.exp.html exp2(in NDArray) Calculate 2**p for all p in the input array. public static NDArray exp2(in NDArray a) Parameters a NDArray Input value. Returns NDArray Element-wise 2 to the power x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.exp2.html exp2(in NDArray, NPTypeCode) Calculate 2**p for all p in the input array. public static NDArray exp2(in NDArray a, NPTypeCode typeCode) Parameters a NDArray Input value. typeCode NPTypeCode Returns NDArray Element-wise 2 to the power x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.exp2.html exp2(in NDArray, Type) Calculate 2**p for all p in the input array. public static NDArray exp2(in NDArray a, Type dtype) Parameters a NDArray Input value. dtype Type Returns NDArray Element-wise 2 to the power x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.exp2.html expand_dims(NDArray, int) public static NDArray expand_dims(NDArray a, int axis) Parameters a NDArray axis int Returns NDArray expm1(in NDArray) Calculate exp(x) - 1 for all elements in the array. public static NDArray expm1(in NDArray a) Parameters a NDArray Input value. Returns NDArray Element-wise exponential minus one: out = exp(x) - 1. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.expm1.html expm1(in NDArray, NPTypeCode) Calculate exp(x) - 1 for all elements in the array. public static NDArray expm1(in NDArray a, NPTypeCode typeCode) Parameters a NDArray Input value. typeCode NPTypeCode Returns NDArray Element-wise exponential minus one: out = exp(x) - 1. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.expm1.html expm1(in NDArray, Type) Calculate exp(x) - 1 for all elements in the array. public static NDArray expm1(in NDArray a, Type dtype) Parameters a NDArray Input value. dtype Type Returns NDArray Element-wise exponential minus one: out = exp(x) - 1. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.expm1.html eye(int, int?, int, Type) Return a 2-D array with ones on the diagonal and zeros elsewhere. public static NDArray eye(int N, int? M = null, int k = 0, Type dtype = null) Parameters N int Number of rows in the output. M int? Number of columns in the output. If None, defaults to N. k int Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal. dtype Type Data-type of the returned array. Returns NDArray An array where all elements are equal to zero, except for the k-th diagonal, whose values are equal to one. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.eye.html find_common_type(NPTypeCode[], NPTypeCode[]) Determine common type following standard coercion rules. public static NPTypeCode find_common_type(NPTypeCode[] array_types, NPTypeCode[] scalar_types) Parameters array_types NPTypeCode[] A list of dtypes or dtype convertible objects representing arrays. Can be null. scalar_types NPTypeCode[] A list of dtypes or dtype convertible objects representing scalars.Can be null. Returns NPTypeCode The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.find_common_type.html find_common_type(NPTypeCode[], Type[]) Determine common type following standard coercion rules. public static NPTypeCode find_common_type(NPTypeCode[] array_types, Type[] scalar_types) Parameters array_types NPTypeCode[] A list of dtypes or dtype convertible objects representing arrays. Can be null. scalar_types Type[] A list of dtypes or dtype convertible objects representing scalars.Can be null. Returns NPTypeCode The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.find_common_type.html find_common_type(params string[]) Resolves to which type should the output be. public static NPTypeCode find_common_type(params string[] involvedTypes) Parameters involvedTypes string[] Returns NPTypeCode find_common_type(string[], string[]) Determine common type following standard coercion rules. public static NPTypeCode find_common_type(string[] array_types, string[] scalar_types) Parameters array_types string[] A list of dtypes or dtype convertible objects representing arrays. Can be null. scalar_types string[] A list of dtypes or dtype convertible objects representing scalars.Can be null. Returns NPTypeCode The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.find_common_type.html find_common_type(Type[]) Determine common type following standard coercion rules. public static NPTypeCode find_common_type(Type[] array_types) Parameters array_types Type[] A list of dtypes or dtype convertible objects representing arrays. Can be null. Returns NPTypeCode The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.find_common_type.html find_common_type(Type[], NPTypeCode[]) Determine common type following standard coercion rules. public static NPTypeCode find_common_type(Type[] array_types, NPTypeCode[] scalar_types) Parameters array_types Type[] A list of dtypes or dtype convertible objects representing arrays. Can be null. scalar_types NPTypeCode[] A list of dtypes or dtype convertible objects representing scalars.Can be null. Returns NPTypeCode The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.find_common_type.html find_common_type(Type[], Type[]) Determine common type following standard coercion rules. public static NPTypeCode find_common_type(Type[] array_types, Type[] scalar_types) Parameters array_types Type[] A list of dtypes or dtype convertible objects representing arrays. Can be null. scalar_types Type[] A list of dtypes or dtype convertible objects representing scalars.Can be null. Returns NPTypeCode The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.find_common_type.html floor(in NDArray, NPTypeCode?) public static NDArray floor(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray outType NPTypeCode? Returns NDArray floor(in NDArray, Type) public static NDArray floor(in NDArray x, Type outType) Parameters x NDArray outType Type Returns NDArray fmax(in NDArray, in NDArray, NDArray) Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are ignored when possible. public static NDArray fmax(in NDArray x1, in NDArray x2, NDArray @out) Parameters x1 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). x2 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). out NDArray Returns NDArray The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. fmax(in NDArray, in NDArray, NPTypeCode?) Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are ignored when possible. public static NDArray fmax(in NDArray x1, in NDArray x2, NPTypeCode? outType = null) Parameters x1 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). x2 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). outType NPTypeCode? Returns NDArray The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. fmax(in NDArray, in NDArray, Type) Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are ignored when possible. public static NDArray fmax(in NDArray x1, in NDArray x2, Type outType) Parameters x1 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). x2 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). outType Type Returns NDArray The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. fmin(in NDArray, in NDArray, NDArray) Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise maxima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated. public static NDArray fmin(in NDArray x1, in NDArray x2, NDArray @out) Parameters x1 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). x2 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). out NDArray Returns NDArray The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. fmin(in NDArray, in NDArray, NPTypeCode?) Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise maxima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated. public static NDArray fmin(in NDArray x1, in NDArray x2, NPTypeCode? outType = null) Parameters x1 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). x2 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). outType NPTypeCode? Returns NDArray The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. fmin(in NDArray, in NDArray, Type) Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise maxima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated. public static NDArray fmin(in NDArray x1, in NDArray x2, Type outType) Parameters x1 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). x2 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). outType Type Returns NDArray The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. frombuffer(byte[], string) public static NDArray frombuffer(byte[] bytes, string dtype) Parameters bytes byte[] dtype string Returns NDArray frombuffer(byte[], Type) public static NDArray frombuffer(byte[] bytes, Type dtype) Parameters bytes byte[] dtype Type Returns NDArray fromfile(string, NPTypeCode) Construct an array from data in a text or binary file. A highly efficient way of reading binary data with a known data-type, as well as parsing simply formatted text files. Data written using the tofile method can be read using this function. public static NDArray fromfile(string file, NPTypeCode dtype) Parameters file string filename. dtype NPTypeCode Data type of the returned array. For binary files, it is used to determine the size and byte-order of the items in the file. Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html fromfile(string, Type) Construct an array from data in a text or binary file. A highly efficient way of reading binary data with a known data-type, as well as parsing simply formatted text files. Data written using the tofile method can be read using this function. public static NDArray fromfile(string file, Type dtype) Parameters file string filename. dtype Type Data type of the returned array. For binary files, it is used to determine the size and byte-order of the items in the file. Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html full(Shape, ValueType) Return a new array of given shape and type, filled with fill_value. public static NDArray full(Shape shape, ValueType fill_value) Parameters shape Shape Shape of the empty array, e.g., (2, 3) or 2. fill_value ValueType Fill value. Returns NDArray Array of fill_value with the given shape, dtype, and order. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html full(Shape, ValueType, NPTypeCode) Return a new array of given shape and type, filled with fill_value. public static NDArray full(Shape shape, ValueType fill_value, NPTypeCode typeCode) Parameters shape Shape Shape of the empty array, e.g., (2, 3) or 2. fill_value ValueType Fill value. typeCode NPTypeCode The desired data-type for the array The default, null, means np.array(fill_value).dtype. Returns NDArray Array of fill_value with the given shape, dtype, and order. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html full(Shape, ValueType, Type) Return a new array of given shape and type, filled with fill_value. public static NDArray full(Shape shape, ValueType fill_value, Type dtype) Parameters shape Shape Shape of the empty array, e.g., (2, 3) or 2. fill_value ValueType Fill value. dtype Type The desired data-type for the array The default, null, means np.array(fill_value).dtype. Returns NDArray Array of fill_value with the given shape, dtype, and order. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html full(ValueType, Shape) Return a new array of given shape and type, filled with fill_value. public static NDArray full(ValueType fill_value, Shape shape) Parameters fill_value ValueType Fill value. shape Shape Shape of the empty array, e.g., (2, 3) or 2. Returns NDArray Array of fill_value with the given shape, dtype, and order. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html full(ValueType, Shape, NPTypeCode) Return a new array of given shape and type, filled with fill_value. public static NDArray full(ValueType fill_value, Shape shape, NPTypeCode typeCode) Parameters fill_value ValueType Fill value. shape Shape Shape of the empty array, e.g., (2, 3) or 2. typeCode NPTypeCode The desired data-type for the array The default, null, means np.array(fill_value).dtype. Returns NDArray Array of fill_value with the given shape, dtype, and order. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html full(ValueType, Shape, Type) Return a new array of given shape and type, filled with fill_value. public static NDArray full(ValueType fill_value, Shape shape, Type dtype) Parameters fill_value ValueType Fill value. shape Shape Shape of the empty array, e.g., (2, 3) or 2. dtype Type The desired data-type for the array The default, null, means np.array(fill_value).dtype. Returns NDArray Array of fill_value with the given shape, dtype, and order. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html full(ValueType, params int[]) Return a new array of given shape and type, filled with fill_value. public static NDArray full(ValueType fill_value, params int[] shapes) Parameters fill_value ValueType Fill value. shapes int[] Shape of the empty array, e.g., (2, 3) or 2. Returns NDArray Array of fill_value with the given shape, dtype, and order. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html full_like(NDArray, object, Type) Return a full array with the same shape and type as a given array. public static NDArray full_like(NDArray a, object fill_value, Type dtype = null) Parameters a NDArray The shape and data-type of a define these same attributes of the returned array. fill_value object Fill value. dtype Type Overrides the data type of the result. Returns NDArray Array of fill_value with the same shape and type as a. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.full_like.html full(ValueType, params int[]) Return a new array of given shape and type, filled with fill_value. public static NDArray full(ValueType fill_value, params int[] shapes) where T : unmanaged Parameters fill_value ValueType Fill value. shapes int[] Shape of the empty array, e.g., (2, 3) or 2. Returns NDArray Array of fill_value with the given shape, dtype, and order. Type Parameters T Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html hstack(params NDArray[]) Stack arrays in sequence horizontally (column wise). This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis.Rebuilds arrays divided by hsplit. This function makes most sense for arrays with up to 3 dimensions.For instance, for pixel-data with a height(first axis), width(second axis), and r/g/b channels(third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations. public static NDArray hstack(params NDArray[] tup) Parameters tup NDArray[] The arrays must have the same shape along all but the second axis, except 1-D arrays which can be any length. Returns NDArray The array formed by stacking the given arrays. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.hstack.html identity(int, Type) Return the identity array. The identity array is a square array with ones on the main diagonal. public static NDArray identity(int n, Type dtype = null) Parameters n int Number of rows (and columns) in n x n output. dtype Type Data-type of the output. Defaults to double. Returns NDArray n x n array with its main diagonal set to one, and all other elements 0. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.identity.html isclose(NDArray, NDArray, double, double, bool) Returns a boolean array where two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers.The relative difference (rtol * abs(b)) and the absolute difference atol are added together to compare against the absolute difference between a and b. Warning: The default atol is not appropriate for comparing numbers that are much smaller than one(see Notes). See also allclose(NDArray, NDArray, double, double, bool) Notes: For finite values, isclose uses the following equation to test whether two floating point values are equivalent. absolute(`a` - `b`) less than or equal to (`atol` + `rtol` * absolute(`b`)) Unlike the built-in math.isclose, the above equation is not symmetric in a and b -- it assumes b is the reference value -- so that isclose(a, b) might be different from isclose(b, a). Furthermore, the default value of atol is not zero, and is used to determine what small values should be considered close to zero.The default value is appropriate for expected values of order unity: if the expected values are significantly smaller than one, it can result in false positives. atol should be carefully selected for the use case at hand. A zero value for atol will result in False if either a or b is zero. public static NDArray isclose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false) Parameters a NDArray Input array to compare with b b NDArray Input array to compare with a. rtol double The relative tolerance parameter(see Notes) atol double The absolute tolerance parameter(see Notes) equal_nan bool Whether to compare NaN's as equal. If True, NaN's in a will be considered equal to NaN's in b in the output array. Returns NDArray Returns a boolean array of where a and b are equal within the given tolerance.If both a and b are scalars, returns a single boolean value. isfinite(NDArray) Test element-wise for finiteness (not infinity or not Not a Number). public static NDArray isfinite(NDArray a) Parameters a NDArray Returns NDArray The result is returned as a boolean array. isnan(NDArray) Test element-wise for Not a Number. public static NDArray isnan(NDArray a) Parameters a NDArray Returns NDArray The result is returned as a boolean array. isscalar(object) Returns true incase of a number, bool or string. If null, returns false. public static bool isscalar(object obj) Parameters obj object Returns bool Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.isscalar.html linspace(double, double, int, bool, NPTypeCode) Return evenly spaced numbers over a specified interval. Returns num evenly spaced samples, calculated over the interval[start, stop]. The endpoint of the interval can optionally be excluded. public static NDArray linspace(double start, double stop, int num, bool endpoint = true, NPTypeCode typeCode = NPTypeCode.Double) Parameters start double The starting value of the sequence. stop double The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False. num int Number of samples to generate. Default is 50. Must be non-negative. endpoint bool If True, stop is the last sample. Otherwise, it is not included. Default is True. typeCode NPTypeCode The type of the output array. If dtype is not given, infer the data type from the other input arguments. Returns NDArray Remarks https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.linspace.html linspace(double, double, int, bool, Type) Return evenly spaced numbers over a specified interval. Returns num evenly spaced samples, calculated over the interval[start, stop]. The endpoint of the interval can optionally be excluded. public static NDArray linspace(double start, double stop, int num, bool endpoint, Type dtype) Parameters start double The starting value of the sequence. stop double The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False. num int Number of samples to generate. Default is 50. Must be non-negative. endpoint bool If True, stop is the last sample. Otherwise, it is not included. Default is True. dtype Type The type of the output array. If dtype is not given, infer the data type from the other input arguments. Returns NDArray Remarks https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.linspace.html linspace(float, float, int, bool, NPTypeCode) Return evenly spaced numbers over a specified interval. Returns num evenly spaced samples, calculated over the interval[start, stop]. The endpoint of the interval can optionally be excluded. public static NDArray linspace(float start, float stop, int num, bool endpoint = true, NPTypeCode typeCode = NPTypeCode.Float) Parameters start float The starting value of the sequence. stop float The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False. num int Number of samples to generate. Default is 50. Must be non-negative. endpoint bool If True, stop is the last sample. Otherwise, it is not included. Default is True. typeCode NPTypeCode The type of the output array. If dtype is not given, infer the data type from the other input arguments. Returns NDArray Remarks https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.linspace.html linspace(float, float, int, bool, Type) Return evenly spaced numbers over a specified interval. Returns num evenly spaced samples, calculated over the interval[start, stop]. The endpoint of the interval can optionally be excluded. public static NDArray linspace(float start, float stop, int num, bool endpoint, Type dtype) Parameters start float The starting value of the sequence. stop float The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False. num int Number of samples to generate. Default is 50. Must be non-negative. endpoint bool If True, stop is the last sample. Otherwise, it is not included. Default is True. dtype Type The type of the output array. If dtype is not given, infer the data type from the other input arguments. Returns NDArray Remarks https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.linspace.html load(Stream) public static NDArray load(Stream stream) Parameters stream Stream Returns NDArray load(string) public static NDArray load(string path) Parameters path string Returns NDArray log(in NDArray) Natural logarithm, element-wise. The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x. The natural logarithm is logarithm in base e. public static NDArray log(in NDArray x) Parameters x NDArray Input value. Returns NDArray The natural logarithm of x, element-wise. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html log(in NDArray, NPTypeCode?) Natural logarithm, element-wise. The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x. The natural logarithm is logarithm in base e. public static NDArray log(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray Input value. outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The natural logarithm of x, element-wise. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html log(in NDArray, Type) Natural logarithm, element-wise. The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x. The natural logarithm is logarithm in base e. public static NDArray log(in NDArray x, Type outType) Parameters x NDArray Input value. outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The natural logarithm of x, element-wise. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html log10(in NDArray) Return the base 10 logarithm of the input array, element-wise. public static NDArray log10(in NDArray x) Parameters x NDArray Input value. Returns NDArray The logarithm to the base 10 of x, element-wise. NaNs are returned where x is negative. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.log10.html log10(in NDArray, NPTypeCode?) Return the base 10 logarithm of the input array, element-wise. public static NDArray log10(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray Input value. outType NPTypeCode? Returns NDArray The logarithm to the base 10 of x, element-wise. NaNs are returned where x is negative. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.log10.html log10(in NDArray, Type) Return the base 10 logarithm of the input array, element-wise. public static NDArray log10(in NDArray x, Type outType) Parameters x NDArray Input value. outType Type Returns NDArray The logarithm to the base 10 of x, element-wise. NaNs are returned where x is negative. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.log10.html log1p(in NDArray) Return the natural logarithm of one plus the input array, element-wise. Calculates log(1 + x). public static NDArray log1p(in NDArray x) Parameters x NDArray Input value. Returns NDArray Natural logarithm of 1 + x, element-wise. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.log1p.html log1p(in NDArray, NPTypeCode?) Return the natural logarithm of one plus the input array, element-wise. Calculates log(1 + x). public static NDArray log1p(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray Input value. outType NPTypeCode? Returns NDArray Natural logarithm of 1 + x, element-wise. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.log1p.html log1p(in NDArray, Type) Return the natural logarithm of one plus the input array, element-wise. Calculates log(1 + x). public static NDArray log1p(in NDArray x, Type outType) Parameters x NDArray Input value. outType Type Returns NDArray Natural logarithm of 1 + x, element-wise. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.log1p.html log2(in NDArray) Base-2 logarithm of x. public static NDArray log2(in NDArray x) Parameters x NDArray Input value. Returns NDArray Base-2 logarithm of x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.log2.html log2(in NDArray, NPTypeCode?) Base-2 logarithm of x. public static NDArray log2(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray Input value. outType NPTypeCode? Returns NDArray Base-2 logarithm of x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.log2.html log2(in NDArray, Type) Base-2 logarithm of x. public static NDArray log2(in NDArray x, Type outType) Parameters x NDArray Input value. outType Type Returns NDArray Base-2 logarithm of x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.log2.html matmul(in NDArray, in NDArray) Matrix product of two arrays. public static NDArray matmul(in NDArray x1, in NDArray x2) Parameters x1 NDArray Lhs Input array, scalars not allowed. x2 NDArray Rhs Input array, scalars not allowed. Returns NDArray The matrix product of the inputs. This is a scalar only when both x1, x2 are 1-d vectors. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.matmul.html max(NDArray, int?, bool, Type) Return the maximum of an array or maximum along an axis. public static NDArray max(NDArray a, int? axis = null, bool keepdims = false, Type dtype = null) Parameters a NDArray axis int? Axis or axes along which to operate. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. dtype Type the type expected as a return, null will remain the same dtype. Returns NDArray Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amax.html maximum(in NDArray, in NDArray, NDArray) Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise maxima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated. public static NDArray maximum(in NDArray x1, in NDArray x2, NDArray @out) Parameters x1 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). x2 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). out NDArray Returns NDArray The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. maximum(in NDArray, in NDArray, NPTypeCode?) Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise maxima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated. public static NDArray maximum(in NDArray x1, in NDArray x2, NPTypeCode? outType = null) Parameters x1 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). x2 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). outType NPTypeCode? Returns NDArray The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. maximum(in NDArray, in NDArray, Type) Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise maxima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated. public static NDArray maximum(in NDArray x1, in NDArray x2, Type outType) Parameters x1 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). x2 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). outType Type Returns NDArray The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. mean(in NDArray) Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs. public static NDArray mean(in NDArray a) Parameters a NDArray Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted. Returns NDArray returns a new array containing the mean values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html mean(in NDArray, bool) Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs. public static NDArray mean(in NDArray a, bool keepdims) Parameters a NDArray Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised. Returns NDArray returns a new array containing the mean values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html mean(in NDArray, int) Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs. public static NDArray mean(in NDArray a, int axis) Parameters a NDArray Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted. axis int Axis or axes along which the means are computed. The default is to compute the mean of the flattened array. Returns NDArray returns a new array containing the mean values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html mean(in NDArray, int, NPTypeCode, bool) Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs. public static NDArray mean(in NDArray a, int axis, NPTypeCode type, bool keepdims = false) Parameters a NDArray Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted. axis int Axis or axes along which the means are computed. The default is to compute the mean of the flattened array. type NPTypeCode Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised. Returns NDArray returns a new array containing the mean values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html mean(in NDArray, int, bool) Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs. public static NDArray mean(in NDArray a, int axis, bool keepdims) Parameters a NDArray Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted. axis int Axis or axes along which the means are computed. The default is to compute the mean of the flattened array. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised. Returns NDArray returns a new array containing the mean values, otherwise a reference to the output array is returned. mean(in NDArray, int, Type, bool) Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs. public static NDArray mean(in NDArray a, int axis, Type dtype, bool keepdims = false) Parameters a NDArray Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted. axis int Axis or axes along which the means are computed. The default is to compute the mean of the flattened array. dtype Type Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised. Returns NDArray returns a new array containing the mean values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html meshgrid(NDArray, NDArray, Kwargs) Return coordinate matrices from coordinate vectors. Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, given one-dimensional coordinate arrays x1, x2,..., xn. .. versionchanged:: 1.9 1-D and 0-D cases are allowed. public static (NDArray, NDArray) meshgrid(NDArray x1, NDArray x2, Kwargs kwargs = null) Parameters x1 NDArray 1-D arrays representing the coordinates of a grid x2 NDArray 1-D arrays representing the coordinates of a grid kwargs Kwargs Returns (NDArray Lhs, NDArray Rhs) mgrid(NDArray, NDArray) nd_grid instance which returns a dense multi-dimensional “meshgrid”. An instance of numpy.lib.index_tricks.nd_grid which returns an dense (or fleshed out) mesh-grid when indexed, so that each returned argument has the same shape. The dimensions and number of the output arrays are equal to the number of indexing dimensions.If the step length is not a complex number, then the stop is not inclusive. public static (NDArray, NDArray) mgrid(NDArray lhs, NDArray rhs) Parameters lhs NDArray rhs NDArray Returns (NDArray Lhs, NDArray Rhs) mesh-grid ndarrays all of the same dimensions Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.mgrid.html min(in NDArray, int?, bool, Type) Return the minimum of an array or minimum along an axis. public static NDArray min(in NDArray a, int? axis = null, bool keepdims = false, Type dtype = null) Parameters a NDArray Input data. axis int? Axis or axes along which to operate. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. dtype Type the type expected as a return, null will remain the same dtype. Returns NDArray Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.amin.html minimum(in NDArray, in NDArray, NDArray) Element-wise minimum of array elements. Compare two arrays and returns a new array containing the element-wise minima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated. public static NDArray minimum(in NDArray x1, in NDArray x2, NDArray @out) Parameters x1 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). x2 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). out NDArray Returns NDArray The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. minimum(in NDArray, in NDArray, NPTypeCode?) Element-wise minimum of array elements. Compare two arrays and returns a new array containing the element-wise minima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated. public static NDArray minimum(in NDArray x1, in NDArray x2, NPTypeCode? outType = null) Parameters x1 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). x2 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). outType NPTypeCode? Returns NDArray The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. minimum(in NDArray, in NDArray, Type) Element-wise minimum of array elements. Compare two arrays and returns a new array containing the element-wise minima.If one of the elements being compared is a NaN, then that element is returned.If both elements are NaNs then the first is returned.The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated. public static NDArray minimum(in NDArray x1, in NDArray x2, Type outType) Parameters x1 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). x2 NDArray The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). outType Type Returns NDArray The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. mintypecode(char[], string, char) Return the character for the minimum-size type to which given types can be safely cast. The returned type character must represent the smallest size dtype such that an array of the returned type can handle the data from an array of all types in typechars(or if typechars is an array, then its dtype.char). public static char mintypecode(char[] typechars, string typeset = \"GDFgdf\", char @default = 'd') Parameters typechars char[] typeset string The set of characters that the returned character is chosen from. The default set is ‘GDFgdf’. default char The default character, this is returned if none of the characters in typechars matches a character in typeset. Returns char The character representing the minimum-size type that was found. mintypecode(string, string, char) Return the character for the minimum-size type to which given types can be safely cast. The returned type character must represent the smallest size dtype such that an array of the returned type can handle the data from an array of all types in typechars(or if typechars is an array, then its dtype.char). public static char mintypecode(string typechars, string typeset = \"GDFgdf\", char @default = 'd') Parameters typechars string every character represents a type. see char typeset string The set of characters that the returned character is chosen from. The default set is ‘GDFgdf’. default char The default character, this is returned if none of the characters in typechars matches a character in typeset. Returns char The character representing the minimum-size type that was found. mod(in NDArray, in NDArray) public static NDArray mod(in NDArray x1, in NDArray x2) Parameters x1 NDArray x2 NDArray Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.mod.html mod(in NDArray, in float) public static NDArray mod(in NDArray x1, in float x2) Parameters x1 NDArray x2 float Returns NDArray modf(in NDArray, NPTypeCode?) Return the fractional and integral parts of an array, element-wise. The fractional and integral parts are negative if the given number is negative. public static (NDArray Fractional, NDArray Intergral) modf(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray Input array. outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns (NDArray Lhs, NDArray Rhs) Fractional part of x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.modf.html modf(in NDArray, Type) Return the fractional and integral parts of an array, element-wise. The fractional and integral parts are negative if the given number is negative. public static (NDArray Fractional, NDArray Intergral) modf(in NDArray x, Type outType) Parameters x NDArray Input array. outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns (NDArray Lhs, NDArray Rhs) Fractional part of x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.modf.html moveaxis(in NDArray, int, int) Move axes of an array to new positions. Other axes remain in their original order. public static NDArray moveaxis(in NDArray a, int source, int destination) Parameters a NDArray The array whose axes should be reordered. source int Original positions of the axes to move. These must be unique (distinct). destination int Destination positions for each of the original axes. These must also be unique (distinct). Returns NDArray Array with moved axes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.moveaxis.html moveaxis(in NDArray, int, int[]) Move axes of an array to new positions. Other axes remain in their original order. public static NDArray moveaxis(in NDArray a, int source, int[] destination) Parameters a NDArray The array whose axes should be reordered. source int Original positions of the axes to move. These must be unique (distinct). destination int[] Destination positions for each of the original axes. These must also be unique (distinct). Returns NDArray Array with moved axes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.moveaxis.html moveaxis(in NDArray, int[], int) Move axes of an array to new positions. Other axes remain in their original order. public static NDArray moveaxis(in NDArray a, int[] source, int destination) Parameters a NDArray The array whose axes should be reordered. source int[] Original positions of the axes to move. These must be unique (distinct). destination int Destination positions for each of the original axes. These must also be unique (distinct). Returns NDArray Array with moved axes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.moveaxis.html moveaxis(in NDArray, int[], int[]) Move axes of an array to new positions. Other axes remain in their original order. public static NDArray moveaxis(in NDArray a, int[] source, int[] destination) Parameters a NDArray The array whose axes should be reordered. source int[] Original positions of the axes to move. These must be unique (distinct). destination int[] Destination positions for each of the original axes. These must also be unique (distinct). Returns NDArray Array with moved axes. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.moveaxis.html multiply(in NDArray, in NDArray) public static NDArray multiply(in NDArray x1, in NDArray x2) Parameters x1 NDArray x2 NDArray Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.multiply.html ndarray(Shape, Type, Array, char) public static NDArray ndarray(Shape shape, Type dtype = null, Array buffer = null, char order = 'F') Parameters shape Shape dtype Type buffer Array order char Returns NDArray negative(in NDArray) Numerical negative, element-wise. public static NDArray negative(in NDArray nd) Parameters nd NDArray Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.negative.html nonzero(in NDArray) Return the indices of the elements that are non-zero. Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension.The values in a are always tested and returned in row-major, C-style order. To group the indices by element, rather than dimension, use argwhere, which returns a row for each non-zero element. public static NDArray[] nonzero(in NDArray a) Parameters a NDArray Input array. Returns NDArray[] Indices of elements that are non-zero. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html ones(Shape) Return a new array of given shape and type, filled with ones. public static NDArray ones(Shape shape) Parameters shape Shape Shape of the new array. Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ones.html ones(Shape, NPTypeCode) Return a new array of given shape and type, filled with ones. public static NDArray ones(Shape shape, NPTypeCode typeCode) Parameters shape Shape Shape of the new array. typeCode NPTypeCode The desired data-type for the array, e.g., uint8. Default is float64 / double. Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ones.html ones(Shape, Type) Return a new array of given shape and type, filled with ones. public static NDArray ones(Shape shape, Type dtype) Parameters shape Shape Shape of the new array. dtype Type The desired data-type for the array, e.g., uint8. Default is float64 / double. Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ones.html ones(params int[]) Return a new array of given shape and type, filled with ones. public static NDArray ones(params int[] shapes) Parameters shapes int[] Shape of the new array. Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ones.html ones(Type, params int[]) Return a new array of given shape and type, filled with ones. public static NDArray ones(Type dtype = null, params int[] shapes) Parameters dtype Type The desired data-type for the array, e.g., uint8. Default is float64 / double. shapes int[] Shape of the new array. Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ones.html ones_like(NDArray, Type) Return an array of ones with the same shape and type as a given array. public static NDArray ones_like(NDArray a, Type dtype = null) Parameters a NDArray Array of ones with the same shape and type as a. dtype Type Overrides the data type of the result. Returns NDArray Array of zeros with the same shape and type as nd. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ones_like.html ones(params int[]) Return a new array of given shape and type, filled with ones. public static NDArray ones(params int[] shapes) where T : unmanaged Parameters shapes int[] Shape of the new array. Returns NDArray Type Parameters T The desired data-type for the array, e.g., uint8. Default is float64 / double. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ones.html outer(in NDArray, in NDArray) Compute the outer product of two vectors. Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product[R60] is: public static NDArray outer(in NDArray a, in NDArray b) Parameters a NDArray First input vector. Input is flattened if not already 1-dimensional. b NDArray Second input vector. Input is flattened if not already 1-dimensional. Returns NDArray out[i, j] = a[i] * b[j] Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.outer.html positive(in NDArray) Numerical positive, element-wise. public static NDArray positive(in NDArray nd) Parameters nd NDArray Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.positive.html power(in NDArray, in ValueType) First array elements raised to powers from second array, element-wise. public static NDArray power(in NDArray x1, in ValueType x2) Parameters x1 NDArray The bases. x2 ValueType The exponents. Returns NDArray The bases in x1 raised to the exponents in x2. This is a scalar NDArray if both x1 and x2 are scalars. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.power.html power(in NDArray, in ValueType, NPTypeCode) First array elements raised to powers from second array, element-wise. public static NDArray power(in NDArray x1, in ValueType x2, NPTypeCode typeCode) Parameters x1 NDArray The bases. x2 ValueType The exponents. typeCode NPTypeCode The dtype of the returned NDArray Returns NDArray The bases in x1 raised to the exponents in x2. This is a scalar NDArray if both x1 and x2 are scalars. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.power.html power(in NDArray, in ValueType, Type) First array elements raised to powers from second array, element-wise. public static NDArray power(in NDArray x1, in ValueType x2, Type dtype) Parameters x1 NDArray The bases. x2 ValueType The exponents. dtype Type The dtype of the returned NDArray Returns NDArray The bases in x1 raised to the exponents in x2. This is a scalar NDArray if both x1 and x2 are scalars. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.power.html prod(in NDArray, int?, Type, bool) Return the product of array elements over a given axis. public static NDArray prod(in NDArray a, int? axis = null, Type dtype = null, bool keepdims = false) Parameters a NDArray Input data. axis int? Axis or axes along which a product is performed. The default, axis=None, will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis. dtype Type The type of the returned array, as well as of the accumulator in which the elements are multiplied. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. Returns NDArray An array shaped as a but with the specified axis removed. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.prod.html ravel(NDArray) Return a contiguous flattened array. A 1-D array, containing the elements of the input, is returned public static NDArray ravel(NDArray a) Parameters a NDArray Input array. The elements in a are read in the order specified by order, and packed as a 1-D array. Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html repeat(NDArray, int) Repeat elements of an array. public static NDArray repeat(NDArray a, int repeats) Parameters a NDArray Input array. repeats int The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis. Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html repeat(T, int) Repeat a scalar. public static NDArray repeat(T a, int repeats) where T : unmanaged Parameters a T Input scalar. repeats int The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis. Returns NDArray Type Parameters T Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html reshape(NDArray, Shape) Gives a new shape to an array without changing its data. public static NDArray reshape(NDArray nd, Shape shape) Parameters nd NDArray Array to be reshaped. shape Shape The new shape should be compatible with the original shape. Returns NDArray original nd reshaped without copying. Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.reshape.html reshape(NDArray, ref Shape) Gives a new shape to an array without changing its data. public static NDArray reshape(NDArray nd, ref Shape shape) Parameters nd NDArray Array to be reshaped. shape Shape The new shape should be compatible with the original shape. Returns NDArray original nd reshaped without copying. Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.reshape.html reshape(NDArray, params int[]) Gives a new shape to an array without changing its data. public static NDArray reshape(NDArray nd, params int[] shape) Parameters nd NDArray Array to be reshaped. shape int[] The new shape should be compatible with the original shape. Returns NDArray original nd reshaped without copying. Remarks https://docs.scipy.org/doc/numpy-1.16.0/reference/generated/numpy.reshape.html roll(NDArray, int, int) Roll array elements along a given axis. Elements that roll beyond the last position are re-introduced at the first. public static int roll(NDArray nd, int shift, int axis = -1) Parameters nd NDArray shift int axis int Returns int rollaxis(in NDArray, int, int) Roll the specified axis backwards, until it lies in a given position. This function continues to be supported for backward compatibility, but you should prefer moveaxis. The moveaxis function was added in NumPy 1.11. public static NDArray rollaxis(in NDArray a, int axis, int start = 0) Parameters a NDArray Input array. axis int The axis to roll backwards. The positions of the other axes do not change relative to one another. start int The axis is rolled until it lies before this position. The default, 0, results in a “complete” roll. Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html round_(in NDArray, int, NPTypeCode?) Evenly round to the given number of decimals. public static NDArray round_(in NDArray x, int decimals, NPTypeCode? outType = null) Parameters x NDArray Input array decimals int Number of decimal places to round to outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. The real and imaginary parts of complex numbers are rounded separately.The result of rounding a float is a float. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.around.html round_(in NDArray, int, Type) Evenly round to the given number of decimals. public static NDArray round_(in NDArray x, int decimals, Type outType) Parameters x NDArray Input array decimals int Number of decimal places to round to outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. The real and imaginary parts of complex numbers are rounded separately.The result of rounding a float is a float. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.around.html round_(in NDArray, NPTypeCode?) Evenly round to the given number of decimals. public static NDArray round_(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray Input array outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. The real and imaginary parts of complex numbers are rounded separately.The result of rounding a float is a float. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.around.html round_(in NDArray, Type) Evenly round to the given number of decimals. public static NDArray round_(in NDArray x, Type outType) Parameters x NDArray Input array outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. The real and imaginary parts of complex numbers are rounded separately.The result of rounding a float is a float. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.around.html save(string, NDArray) public static void save(string filepath, NDArray arr) Parameters filepath string arr NDArray save(string, Array) public static void save(string filepath, Array arr) Parameters filepath string arr Array searchsorted(NDArray, NDArray) Find indices where elements should be inserted to maintain order. Find the indices into a sorted array a such that, if the corresponding elements in v were inserted before the indices, the order of a would be preserved. public static NDArray searchsorted(NDArray a, NDArray v) Parameters a NDArray Input array. Must be sorted in ascending order. v NDArray Values to insert into a. Returns NDArray Array of insertion points with the same shape as v. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html sign(in NDArray, NPTypeCode?) public static NDArray sign(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray outType NPTypeCode? Returns NDArray sign(in NDArray, Type) public static NDArray sign(in NDArray x, Type outType) Parameters x NDArray outType Type Returns NDArray sin(in NDArray, NPTypeCode?) Trigonometric sine, element-wise. public static NDArray sin(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray Angle, in radians (2 \\pi rad equals 360 degrees). outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The sine of each element of x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.sin.html sin(in NDArray, Type) Trigonometric sine, element-wise. public static NDArray sin(in NDArray x, Type outType) Parameters x NDArray Angle, in radians (2 \\pi rad equals 360 degrees). outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The sine of each element of x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.sin.html sinh(in NDArray, NPTypeCode?) Hyperbolic sine, element-wise. Equivalent to 1/2 * (np.exp(x) - np.exp(-x)) or -1j * np.sin(1j*x). public static NDArray sinh(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray Input array. outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The sine of each element of x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.sinh.html sinh(in NDArray, Type) Hyperbolic sine, element-wise. Equivalent to 1/2 * (np.exp(x) - np.exp(-x)) or -1j * np.sin(1j*x). public static NDArray sinh(in NDArray x, Type outType) Parameters x NDArray Input array. outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The sine of each element of x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.sinh.html size(NDArray, int?) Return the number of elements along a given axis. public static int size(NDArray a, int? axis = null) Parameters a NDArray Input data. axis int? Axis along which the elements are counted. By default, give the total number of elements. Returns int Number of elements along the specified axis. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.ma.size.html sqrt(in NDArray, NPTypeCode?) Return the non-negative square-root of an array, element-wise. public static NDArray sqrt(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray The values whose square-roots are required. outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray An array of the same shape as x, containing the positive square-root of each element in x. If any element in x is complex, a complex array is returned (and the square-roots of negative reals are calculated). If all of the elements in x are real, so is y, with negative elements returning nan. If out was provided, y is a reference to it. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.sqrt.html sqrt(in NDArray, Type) Return the non-negative square-root of an array, element-wise. public static NDArray sqrt(in NDArray x, Type outType) Parameters x NDArray The values whose square-roots are required. outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray An array of the same shape as x, containing the positive square-root of each element in x. If any element in x is complex, a complex array is returned (and the square-roots of negative reals are calculated). If all of the elements in x are real, so is y, with negative elements returning nan. If out was provided, y is a reference to it. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.sqrt.html square(in NDArray) Return the element-wise square of the input. public static NDArray square(in NDArray x) Parameters x NDArray Input data. Returns NDArray Element-wise x*x, of the same shape and dtype as x. Returns scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.square.html squeeze(NDArray) Remove single-dimensional entries from the shape of an array. public static NDArray squeeze(NDArray a) Parameters a NDArray Input data. Returns NDArray The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into a. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.squeeze.html squeeze(NDArray, int) Remove single-dimensional entries from the shape of an array. public static NDArray squeeze(NDArray a, int axis) Parameters a NDArray Input data. axis int Selects a subset of the single-dimensional entries in the shape. If an axis is selected with shape entry greater than one, an error is raised. Returns NDArray The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into a. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.squeeze.html Exceptions IncorrectShapeException If axis is not None, and an axis being squeezed is not of length 1 squeeze(Shape) Remove single-dimensional entries from a shape. public static Shape squeeze(Shape shape) Parameters shape Shape Input shape. Returns Shape The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into a. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.squeeze.html stack(NDArray[], int) Join a sequence of arrays along a new axis. The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension. public static NDArray stack(NDArray[] arrays, int axis = 0) Parameters arrays NDArray[] Each array must have the same shape. axis int The axis in the result array along which the input arrays are stacked. Returns NDArray The stacked array has one more dimension than the input arrays. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.stack.html std(NDArray, bool, int?, NPTypeCode?) Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. public static NDArray std(NDArray a, bool keepdims = false, int? ddof = null, NPTypeCode? dtype = null) Parameters a NDArray Calculate the standard deviation of these values. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. dtype NPTypeCode? Returns NDArray returns a new array containing the std values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html std(NDArray, int, bool, int?, NPTypeCode?) Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. public static NDArray std(NDArray a, int axis, bool keepdims = false, int? ddof = null, NPTypeCode? dtype = null) Parameters a NDArray Calculate the standard deviation of these values. axis int Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. dtype NPTypeCode? Returns NDArray returns a new array containing the std values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html std(in NDArray, bool, int?) Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. public static NDArray std(in NDArray a, bool keepdims, int? ddof = null) Parameters a NDArray Calculate the standard deviation of these values. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. Returns NDArray returns a new array containing the std values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html std(in NDArray, int, NPTypeCode, bool, int?) Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. public static NDArray std(in NDArray a, int axis, NPTypeCode type, bool keepdims = false, int? ddof = null) Parameters a NDArray Calculate the standard deviation of these values. axis int Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array. type NPTypeCode keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. Returns NDArray returns a new array containing the std values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html std(in NDArray, int, bool, int?) Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. public static NDArray std(in NDArray a, int axis, bool keepdims, int? ddof = null) Parameters a NDArray Calculate the standard deviation of these values. axis int Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. Returns NDArray returns a new array containing the std values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html std(in NDArray, int, int?) Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. public static NDArray std(in NDArray a, int axis, int? ddof = null) Parameters a NDArray Calculate the standard deviation of these values. axis int Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. Returns NDArray returns a new array containing the std values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html std(in NDArray, int, Type, bool, int?) Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. public static NDArray std(in NDArray a, int axis, Type dtype, bool keepdims = false, int? ddof = null) Parameters a NDArray Calculate the standard deviation of these values. axis int Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array. dtype Type keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. Returns NDArray returns a new array containing the std values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html std(in NDArray, int?) Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. public static NDArray std(in NDArray a, int? ddof = null) Parameters a NDArray Calculate the standard deviation of these values. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. Returns NDArray returns a new array containing the std values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html subtract(in NDArray, in NDArray) public static NDArray subtract(in NDArray x1, in NDArray x2) Parameters x1 NDArray x2 NDArray Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.subtract.html sum(in NDArray) Sum of array elements over a given axis. public static NDArray sum(in NDArray a) Parameters a NDArray Elements to sum. Returns NDArray An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html sum(in NDArray, bool) Sum of array elements over a given axis. public static NDArray sum(in NDArray a, bool keepdims) Parameters a NDArray Elements to sum. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised. Returns NDArray An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html sum(in NDArray, int) Sum of array elements over a given axis. public static NDArray sum(in NDArray a, int axis) Parameters a NDArray Elements to sum. axis int Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. Returns NDArray An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html sum(in NDArray, NPTypeCode?) Sum of array elements over a given axis. public static NDArray sum(in NDArray a, NPTypeCode? typeCode) Parameters a NDArray Elements to sum. typeCode NPTypeCode? The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used. Returns NDArray An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html sum(in NDArray, int?, bool) Sum of array elements over a given axis. public static NDArray sum(in NDArray a, int? axis, bool keepdims) Parameters a NDArray Elements to sum. axis int? Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised. Returns NDArray An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html sum(in NDArray, int?, bool, NPTypeCode?) Sum of array elements over a given axis. public static NDArray sum(in NDArray a, int? axis, bool keepdims, NPTypeCode? typeCode) Parameters a NDArray Elements to sum. axis int? Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised. typeCode NPTypeCode? The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used. Returns NDArray An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html sum(in NDArray, int?, bool, Type) Sum of array elements over a given axis. public static NDArray sum(in NDArray a, int? axis, bool keepdims, Type dtype) Parameters a NDArray Elements to sum. axis int? Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised. dtype Type The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used. Returns NDArray An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html sum(in NDArray, int?, NPTypeCode?) Sum of array elements over a given axis. public static NDArray sum(in NDArray a, int? axis, NPTypeCode? typeCode) Parameters a NDArray Elements to sum. axis int? Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. typeCode NPTypeCode? The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used. Returns NDArray An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html sum(in NDArray, int?, Type) Sum of array elements over a given axis. public static NDArray sum(in NDArray a, int? axis, Type dtype) Parameters a NDArray Elements to sum. axis int? Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. dtype Type The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used. Returns NDArray An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html sum(in NDArray, Type) Sum of array elements over a given axis. public static NDArray sum(in NDArray a, Type dtype) Parameters a NDArray Elements to sum. dtype Type The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used. Returns NDArray An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html swapaxes(in NDArray, int, int) Interchange two axes of an array. public static NDArray swapaxes(in NDArray a, int axis1, int axis2) Parameters a NDArray Input array. axis1 int First axis. axis2 int Second axis. Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.swapaxes.html tan(in NDArray, NPTypeCode?) Compute tangent element-wise. Equivalent to np.sin(x)/np.cos(x) element-wise. public static NDArray tan(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray Angle, in radians (2 \\pi rad equals 360 degrees). outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The sine of each element of x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.tan.html tan(in NDArray, Type) Trigonometric sine, element-wise. public static NDArray tan(in NDArray x, Type outType) Parameters x NDArray Angle, in radians (2 \\pi rad equals 360 degrees). outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The sine of each element of x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.tan.html tanh(in NDArray, NPTypeCode?) Compute hyperbolic tangent element-wise. Equivalent to np.sinh(x)/np.cosh(x) or -1j * np.tan(1j*x). public static NDArray tanh(in NDArray x, NPTypeCode? outType = null) Parameters x NDArray Input array. outType NPTypeCode? The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The sine of each element of x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.tanh.html tanh(in NDArray, Type) Compute hyperbolic tangent element-wise. Equivalent to np.sinh(x)/np.cosh(x) or -1j * np.tan(1j*x). public static NDArray tanh(in NDArray x, Type outType) Parameters x NDArray Input array. outType Type The dtype the returned ndarray should be of, only non integer values are supported. Returns NDArray The sine of each element of x. This is a scalar if x is a scalar. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.tanh.html transpose(in NDArray, int[]) Permute the dimensions of an array. public static NDArray transpose(in NDArray a, int[] premute = null) Parameters a NDArray Input array. premute int[] By default, reverse the dimensions, otherwise permute the axes according to the values given. Returns NDArray a with its axes permuted. A view is returned whenever possible. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html true_divide(in NDArray, in NDArray) public static NDArray true_divide(in NDArray x1, in NDArray x2) Parameters x1 NDArray x2 NDArray Returns NDArray Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.true_divide.html unique(in NDArray) Find the unique elements of an array. Returns the sorted unique elements of an array.There are three optional outputs in addition to the unique elements: the indices of the input array that give the unique values the indices of the unique array that reconstruct the input array the number of times each unique value comes up in the input array public static NDArray unique(in NDArray a) Parameters a NDArray Returns NDArray The sorted unique values. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html var(NDArray, bool, int?, NPTypeCode?) Compute the variance along the specified axis. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. public static NDArray var(NDArray a, bool keepdims = false, int? ddof = null, NPTypeCode? dtype = null) Parameters a NDArray Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. dtype NPTypeCode? Returns NDArray returns a new array containing the var values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.var.html var(NDArray, int, bool, int?, NPTypeCode?) Compute the variance along the specified axis. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. public static NDArray var(NDArray a, int axis, bool keepdims = false, int? ddof = null, NPTypeCode? dtype = null) Parameters a NDArray Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted. axis int Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. dtype NPTypeCode? Returns NDArray returns a new array containing the var values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.var.html var(in NDArray, bool, int?) Compute the variance along the specified axis. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. public static NDArray var(in NDArray a, bool keepdims, int? ddof = null) Parameters a NDArray Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. Returns NDArray returns a new array containing the var values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.var.html var(in NDArray, int, NPTypeCode, bool, int?) Compute the variance along the specified axis. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. public static NDArray var(in NDArray a, int axis, NPTypeCode type, bool keepdims = false, int? ddof = null) Parameters a NDArray Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted. axis int Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array. type NPTypeCode keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. Returns NDArray returns a new array containing the var values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.var.html var(in NDArray, int, bool, int?) Compute the variance along the specified axis. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. public static NDArray var(in NDArray a, int axis, bool keepdims, int? ddof = null) Parameters a NDArray Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted. axis int Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array. keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. Returns NDArray returns a new array containing the var values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.var.html var(in NDArray, int, int?) Compute the variance along the specified axis. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. public static NDArray var(in NDArray a, int axis, int? ddof = null) Parameters a NDArray Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted. axis int Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. Returns NDArray returns a new array containing the var values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.var.html var(in NDArray, int, Type, bool, int?) Compute the variance along the specified axis. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. public static NDArray var(in NDArray a, int axis, Type dtype, bool keepdims = false, int? ddof = null) Parameters a NDArray Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted. axis int Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array. dtype Type keepdims bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. Returns NDArray returns a new array containing the var values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.var.html var(in NDArray, int?) Compute the variance along the specified axis. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. public static NDArray var(in NDArray a, int? ddof = null) Parameters a NDArray Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted. ddof int? Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. Returns NDArray returns a new array containing the var values, otherwise a reference to the output array is returned. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.var.html vstack(params NDArray[]) Stack arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape(N,) have been reshaped to(1, N). Rebuilds arrays divided by vsplit. public static NDArray vstack(params NDArray[] tup) Parameters tup NDArray[] The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length. Returns NDArray The array formed by stacking the given arrays, will be at least 2-D. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html zeros(Shape) Return a new double array of given shape, filled with zeros. public static NDArray zeros(Shape shape) Parameters shape Shape Shape of the new array, Returns NDArray Array of zeros with the given shape, dtype. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html zeros(Shape, NPTypeCode) Return a new double array of given shape, filled with zeros. public static NDArray zeros(Shape shape, NPTypeCode typeCode) Parameters shape Shape Shape of the new array, typeCode NPTypeCode The desired data-type for the array, e.g., uint8. Default is float64 / double. Returns NDArray Array of zeros with the given shape, dtype. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html zeros(Shape, Type) Return a new double array of given shape, filled with zeros. public static NDArray zeros(Shape shape, Type dtype) Parameters shape Shape Shape of the new array, dtype Type The desired data-type for the array, e.g., uint8. Default is float64 / double. Returns NDArray Array of zeros with the given shape, dtype. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html zeros(params int[]) Return a new double array of given shape, filled with zeros. public static NDArray zeros(params int[] shapes) Parameters shapes int[] Shape of the new array, Returns NDArray Array of zeros with the given shape, dtype. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html zeros_like(NDArray, Type) Return an array of zeros with the same shape and type as a given array. public static NDArray zeros_like(NDArray a, Type dtype = null) Parameters a NDArray The shape and data-type of a define these same attributes of the returned array. dtype Type Overrides the data type of the result. Returns NDArray Array of zeros with the same shape and type as nd. Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros_like.html zeros(params int[]) Return a new double array of given shape, filled with zeros. public static NDArray zeros(params int[] shapes) where T : unmanaged Parameters shapes int[] Shape of the new array, Returns NDArray Array of zeros with the given shape, type T. Type Parameters T Remarks https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html" + }, + "api/NumSharp.np.linalg.html": { + "href": "api/NumSharp.np.linalg.html", + "title": "Class np.linalg | NumSharp Documentation", + "summary": "Class np.linalg Namespace NumSharp Assembly NumSharp.dll public static class np.linalg Inheritance object np.linalg Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString()" + }, + "api/index.html": { + "href": "api/index.html", + "title": "NumSharp API Reference | NumSharp Documentation", + "summary": "NumSharp API Reference NumSharp is a .NET port of Python's NumPy library. This API reference is organized by functionality, matching NumPy's documentation structure. Core Types The essential types for working with NumSharp. Type Description NDArray The main n-dimensional array type np Static API class (like import numpy as np in Python) Shape Array dimensions and strides Slice Slice specification for array indexing NDArray Generic typed wrapper for type-safe access Quick Example using NumSharp; // Create arrays var a = np.array(new[] { 1, 2, 3, 4, 5 }); var b = np.zeros((3, 4)); var c = np.arange(10); // Operations var sum = np.sum(a); var reshaped = a.reshape(5, 1); var sliced = a[\"1:4\"]; // Elements 1, 2, 3 Array Creation Functions for creating new arrays. Function Description np.array(data) Create array from existing data np.zeros(shape) Array filled with zeros np.zeros_like(a) Array of zeros with same shape as a np.ones(shape) Array filled with ones np.ones_like(a) Array of ones with same shape as a np.empty(shape) Uninitialized array np.full(shape, value) Array filled with a constant value np.eye(N) Identity matrix np.arange(start, stop, step) Evenly spaced values within interval np.linspace(start, stop, num) Evenly spaced values (specify count) np.meshgrid(x, y) Coordinate matrices from vectors np.copy(a) Return a copy of the array np.asarray(a) Convert input to array np.frombuffer(buffer) Create array from buffer Stacking & Joining Functions for combining multiple arrays. Function Description np.concatenate(arrays, axis) Join arrays along an existing axis np.stack(arrays, axis) Join arrays along a new axis np.vstack(arrays) Stack arrays vertically (row-wise) np.hstack(arrays) Stack arrays horizontally (column-wise) np.dstack(arrays) Stack arrays depth-wise (along 3rd axis) Math Operations Arithmetic and mathematical functions. Arithmetic Operators Operator Description a + b Element-wise addition a - b Element-wise subtraction a * b Element-wise multiplication a / b Element-wise division a % b Element-wise modulo -a Element-wise negation Math Functions Function Description np.sum(a, axis) Sum of array elements np.prod(a) Product of array elements np.cumsum(a) Cumulative sum np.sqrt(a) Element-wise square root np.power(a, n) Element-wise power np.abs(a) Element-wise absolute value np.sign(a) Element-wise sign np.floor(a) Element-wise floor np.ceil(a) Element-wise ceiling np.round(a) Element-wise rounding np.clip(a, min, max) Clip values to range np.maximum(a, b) Element-wise maximum np.minimum(a, b) Element-wise minimum Exponentials & Logarithms Function Description np.exp(a) Element-wise exponential np.exp2(a) Element-wise 2^x np.expm1(a) exp(x) - 1 np.log(a) Natural logarithm np.log2(a) Base-2 logarithm np.log10(a) Base-10 logarithm np.log1p(a) log(1 + x) Trigonometric Functions Function Description np.sin(a) Element-wise sine np.cos(a) Element-wise cosine np.tan(a) Element-wise tangent Statistics Statistical functions. Function Description np.mean(a, axis) Arithmetic mean np.std(a, axis) Standard deviation np.var(a, axis) Variance np.amax(a, axis) Maximum value np.amin(a, axis) Minimum value Sorting & Searching Functions for sorting arrays and finding elements. Function Description np.argsort(a) Indices that would sort an array np.argmax(a, axis) Index of maximum value np.argmin(a, axis) Index of minimum value np.searchsorted(a, v) Find indices for inserting values np.nonzero(a) Indices of non-zero elements Linear Algebra Matrix and vector operations. Function Description np.dot(a, b) Dot product / matrix multiplication np.matmul(a, b) Matrix product (@ operator) np.outer(a, b) Outer product of two vectors Shape Manipulation Functions for changing array shape and dimensions. Function Description np.reshape(a, shape) Reshape without changing data a.reshape(shape) Instance method for reshape np.transpose(a) Permute array dimensions a.T Transpose property np.ravel(a) Flatten to 1-D array (returns view) a.flatten() Flatten to 1-D array (returns copy) np.squeeze(a) Remove axes of length 1 np.expand_dims(a, axis) Insert a new axis np.swapaxes(a, ax1, ax2) Swap two axes np.moveaxis(a, src, dst) Move axes to new positions np.rollaxis(a, axis) Roll axis backwards np.atleast_1d(a) Convert to at least 1-D np.atleast_2d(a) Convert to at least 2-D np.atleast_3d(a) Convert to at least 3-D Indexing & Slicing NumSharp supports Python-style array indexing and slicing. Slice Syntax a[\":\"] // All elements a[\"1:5\"] // Elements 1-4 (stop exclusive) a[\"::2\"] // Every 2nd element a[\"-1\"] // Last element (reduces dimension) a[\"::-1\"] // Reversed a[\":, 0\"] // All rows, first column a[\"..., -1\"] // Ellipsis fills dimensions Special Slice Constants Constant Description Slice.All All elements (:) Slice.Ellipsis Fill remaining dimensions (...) Slice.NewAxis Insert new dimension Slice.Index(n) Single element selection Boolean Masking var a = np.array(new[] { 1, 2, 3, 4, 5 }); var mask = a > 2; // [false, false, true, true, true] var filtered = a[mask]; // [3, 4, 5] Logic Functions Boolean operations and comparisons. Comparison Operators Operator Description a == b Element-wise equality a != b Element-wise inequality a > b Element-wise greater than a >= b Element-wise greater or equal a < b Element-wise less than a <= b Element-wise less or equal !a Element-wise NOT (boolean arrays) Logic Functions Function Description np.all(a, axis) Test if all elements are true np.any(a, axis) Test if any element is true np.array_equal(a, b) Test if arrays are equal np.isscalar(a) Test if input is scalar Random Sampling Random number generation. Access via NumPyRandom. Function Description np.random.rand(d0, d1, ...) Random values in [0, 1) np.random.randn(d0, d1, ...) Standard normal distribution np.random.randint(low, high, size) Random integers np.random.uniform(low, high, size) Uniform distribution np.random.choice(a, size, replace) Random sample from array np.random.shuffle(a) Shuffle array in-place np.random.permutation(a) Random permutation Distributions Function Description np.random.beta(a, b, size) Beta distribution np.random.binomial(n, p, size) Binomial distribution np.random.gamma(shape, scale, size) Gamma distribution np.random.poisson(lam, size) Poisson distribution np.random.exponential(scale, size) Exponential distribution np.random.geometric(p, size) Geometric distribution np.random.lognormal(mean, sigma, size) Log-normal distribution np.random.chisquare(df, size) Chi-square distribution np.random.bernoulli(p, size) Bernoulli distribution Broadcasting Functions for array broadcasting. Function Description np.broadcast_to(a, shape) Broadcast array to new shape np.broadcast_arrays(a, b, ...) Broadcast arrays against each other Broadcasting automatically aligns array shapes for operations: Shapes align from the right Dimensions must be equal OR one must be 1 Dimension of 1 \"stretches\" to match File I/O Functions for saving and loading arrays. Function Description np.save(file, arr) Save array to .npy file np.load(file) Load .npy or .npz file np.fromfile(file, dtype) Load array from binary file arr.tofile(file) Write array to binary file Unique & Set Operations Function Description np.unique(a) Find unique elements np.repeat(a, repeats) Repeat elements of array Internals & Advanced These types are for advanced users extending NumSharp or understanding its internals. Storage & Backends Type Description UnmanagedStorage Raw unmanaged memory management TensorEngine Abstract computation backend interface DefaultEngine Pure C# implementation of TensorEngine Iteration Type Description NDIterator Traverses arrays with different memory layouts MultiIterator Paired iteration for broadcasting Memory Management Type Description ArraySlice Typed memory slice IMemoryBlock Memory block interface Utilities Type Description InfoOf Static type information cache NPTypeCode Enum of supported data types Supported Data Types NumSharp supports 12 numeric data types: NPTypeCode C# Type NumPy Equivalent Boolean bool np.bool_ Byte byte np.uint8 Int16 short np.int16 UInt16 ushort np.uint16 Int32 int np.int32 UInt32 uint np.uint32 Int64 long np.int64 UInt64 ulong np.uint64 Char char (no equivalent) Single float np.float32 Double double np.float64 Decimal decimal (no equivalent) See Also User Documentation - Tutorials and guides GitHub Repository - Source code and issues" + }, + "docs/array-api-standard.html": { + "href": "docs/array-api-standard.html", + "title": "Python Array API Standard | NumSharp Documentation", + "summary": "Python Array API Standard If you've ever tried to write code that works with NumPy, PyTorch, JAX, and CuPy, you know the pain. They all do similar things, but the APIs are just different enough that your code breaks when you switch libraries. The Python Array API Standard exists to fix this. NumSharp is working toward Array API compliance because it means your code can be more portable—not just between Python libraries, but between Python and C#. What Is the Array API Standard? The Array API Standard is a specification developed by the Consortium for Python Data API Standards. It defines a common interface for array operations that any library can implement. Think of it like USB for arrays. Before USB, every device had its own connector. Now they all use the same port. The Array API does the same thing for array libraries. The Problem It Solves By 2020, Python had accumulated a zoo of array libraries: NumPy — The original, CPU-only PyTorch — Deep learning, GPU support TensorFlow — Deep learning, different API JAX — Functional, JIT compilation CuPy — NumPy clone for NVIDIA GPUs Dask — Distributed/parallel arrays MXNet, PaddlePaddle, and more... Each library evolved independently. They all have reshape(), but the parameters are slightly different. They all have sum(), but the axis handling varies. Code written for NumPy rarely works on PyTorch without modification. The Array API Standard says: \"Here's exactly what reshape() should look like. Here's exactly how sum() should behave. Implement these, and code becomes portable.\" Who's Adopting It? As of 2024, these libraries have adopted or are adopting the Array API: Library Status NumPy 2.0+ Full support in main namespace PyTorch 2.0+ torch namespace is mostly compliant JAX Compliant (with some extras) CuPy Compliant Dask Compliant ndonnx Compliant NumSharp aims to join this list. Why Should You Care? For NumPy Users Moving to C# If you're porting Python ML code to C#, Array API compliance means fewer surprises. When NumSharp follows the same specification as NumPy 2.x, the behavior matches. For Library Authors If you're building a C# library that consumes arrays, coding against the Array API subset means your library works with any compliant array type—not just NumSharp. For Cross-Platform Development Write once, run anywhere. The same algorithms can work on NumPy in Python and NumSharp in C#, producing identical results. The Specification: What's Required? The Array API Standard (version 2024.12) specifies: 14 data types 5 constants 133 core functions 7 array attributes Full set of operators 2 optional extensions (linear algebra, FFT) Let's break these down. Data Types: 14 Required The standard mandates support for exactly these types: Integer Types Type Bits Range C# Equivalent int8 8 -128 to 127 sbyte int16 16 -32,768 to 32,767 short int32 32 -2B to 2B int int64 64 -9Q to 9Q long uint8 8 0 to 255 byte uint16 16 0 to 65,535 ushort uint32 32 0 to 4B uint uint64 64 0 to 18Q ulong Floating-Point Types Type Bits Precision C# Equivalent float32 32 ~7 digits float float64 64 ~16 digits double Complex Types Type Bits Components C# Equivalent complex64 64 Two float32 Custom struct needed complex128 128 Two float64 System.Numerics.Complex Boolean Type Bits C# Equivalent bool 1 bool NumSharp Status We support 12 of 14 types. Missing: complex64 and complex128. Complex numbers are our biggest gap. C# has System.Numerics.Complex, but it's always 128-bit. For complex64, we'd need to implement our own struct with two float components. Constants: 5 Required Constant Value NumSharp e 2.71828... ✅ inf Positive infinity ✅ nan Not a Number ✅ newaxis None (for dimension expansion) ✅ pi 3.14159... ✅ Full compliance here. Array Attributes: 7 Required Every array object must have these properties: Attribute Description NumSharp dtype Data type of elements ✅ device Hardware location (CPU/GPU) ❌ mT Matrix transpose (last 2 axes) ❌ ndim Number of dimensions ✅ shape Tuple of dimension sizes ✅ size Total number of elements ✅ T Full transpose ✅ What's device? The device attribute tells you where the array lives—CPU, GPU, TPU, etc. For NumSharp (CPU-only), this would always return a CPU device object. We need to implement this for compliance, even though we only support one device. What's mT? The mT property is \"matrix transpose\"—it only transposes the last two dimensions. This matters for batched matrix operations: # x has shape (batch, rows, cols) x.T # Transposes ALL dimensions → (cols, rows, batch) — usually wrong! x.mT # Transposes last two only → (batch, cols, rows) — what you want NumPy 2.0 added mT for Array API compliance. NumSharp needs it too. Operators: Complete Set Required Arrays must support these operators with proper semantics: Arithmetic +, -, *, /, // (floor division), %, ** (power), unary -, unary + Comparison <, <=, >, >=, ==, != Bitwise ~ (NOT), & (AND), | (OR), ^ (XOR), <<, >> Matrix @ (matrix multiplication) In-place +=, -=, *=, /=, //=, %=, **=, &=, |=, ^=, <<=, >>=, @= NumSharp implements most of these. We're missing the bitwise operators as named functions (though the operators themselves work) and @ (we have np.matmul() instead). Core Functions: 133 Required The specification groups functions into categories. Here's where NumSharp stands: Creation Functions (16) These create new arrays from scratch or from existing data. Function Description NumSharp arange Evenly spaced values in interval ✅ asarray Convert to array ✅ empty Uninitialized array ✅ empty_like Same shape, uninitialized ✅ eye Identity matrix ✅ from_dlpack From DLPack capsule ❌ full Filled with constant ✅ full_like Same shape, filled ✅ linspace Evenly spaced (by count) ✅ meshgrid Coordinate matrices ✅ ones Filled with ones ✅ ones_like Same shape, ones ✅ tril Lower triangle ❌ triu Upper triangle ❌ zeros Filled with zeros ✅ zeros_like Same shape, zeros ✅ Coverage: 81% — Missing tril, triu, from_dlpack Element-wise Functions (67) The largest category. Mathematical operations applied to each element. Arithmetic: add, subtract, multiply, divide, floor_divide, remainder, pow, negative, positive, abs, sign Rounding: ceil, floor, trunc, round Exponential/Log: exp, expm1, log, log1p, log2, log10 Trigonometric: sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh, asinh, acosh, atanh Comparison: equal, not_equal, less, less_equal, greater, greater_equal, maximum, minimum Logical: logical_and, logical_or, logical_xor, logical_not Bitwise: bitwise_and, bitwise_or, bitwise_xor, bitwise_invert, bitwise_left_shift, bitwise_right_shift Type checking: isfinite, isinf, isnan Other: sqrt, square, clip, copysign, hypot, logaddexp, nextafter, signbit, conj, imag, real NumSharp Coverage: ~75% We're missing: copysign, hypot, logaddexp (math functions) nextafter, signbit (floating-point utilities) conj, imag, real (complex number functions—blocked on complex type support) Named bitwise functions (we have the operators, not the functions) Statistical Functions (9) Function Description NumSharp max Maximum value ✅ (amax) mean Arithmetic mean ✅ min Minimum value ✅ (amin) prod Product of elements ✅ std Standard deviation ✅ sum Sum of elements ✅ var Variance ✅ cumulative_sum Cumulative sum ✅ (cumsum) cumulative_prod Cumulative product ❌ Coverage: 89% — Missing cumulative_prod Note: The Array API uses a correction parameter for std/var: # Array API std(x, correction=1) # Sample standard deviation # NumPy (and NumSharp) np.std(x, ddof=1) # Same thing, different name Manipulation Functions (14) Function Description NumSharp broadcast_arrays Broadcast shapes ✅ broadcast_to Broadcast to shape ✅ concat Join along axis ✅ (concatenate) expand_dims Add dimension ✅ flip Reverse along axis ✅ moveaxis Move axis position ✅ permute_dims Permute dimensions ✅ (transpose) repeat Repeat elements ✅ reshape Change shape ✅ roll Shift elements Partial squeeze Remove size-1 dimensions ✅ stack Join along new axis ✅ tile Repeat whole array ❌ unstack Split along axis ❌ Coverage: ~79% — Missing tile, unstack; roll is partial Set Functions (4) This is our weakest area. Function Description NumSharp unique_all Values + indices + inverse + counts ❌ unique_counts Values + counts ❌ unique_inverse Values + inverse indices ❌ unique_values Just unique values ✅ (np.unique) Coverage: 25% The Array API split NumPy's np.unique(return_counts=True, return_inverse=True) into four focused functions. We only have the basic version. Other Categories Category Required NumSharp Coverage Searching 6 ~4 ~67% Sorting 2 2 100% Linear Algebra (core) 4 4 100% Indexing 2 0 0% Data Types 6 ~3 ~50% Utility 3 2 ~67% Type Promotion Rules The Array API specifies strict rules for what happens when you combine different types. Same-Kind Promotion Within a type category, smaller types promote to larger: int8 + int16 → int16 int16 + int32 → int32 float32 + float64 → float64 Cross-Kind: Undefined! Here's the crucial difference from NumPy 1.x: mixing integers and floats is undefined in the Array API. # Array API says: DON'T DO THIS int32_array + float32_array # Undefined behavior! NumPy 2.x still allows it (promoting to float), but the Array API deliberately leaves this unspecified so libraries can make their own choices. Scalar Promotion When you mix a Python scalar with an array, the scalar is \"weak\"—it adopts the array's type: uint8_array + 2 → uint8_array # Scalar becomes uint8 float32_array + 1.5 → float32_array # Scalar becomes float32 This is consistent with NEP 50 in NumPy 2.x. Extensions: Optional but Defined The Array API defines two optional extensions. If a library implements an extension, it must implement all functions in that extension. Linear Algebra Extension (23 functions) Accessible via linalg namespace. Function Description cholesky Cholesky decomposition cross Cross product det Determinant diagonal Extract diagonal eigh Eigenvalues/vectors (Hermitian) eigvalsh Eigenvalues only (Hermitian) inv Matrix inverse matmul Matrix multiplication matrix_norm Matrix norm matrix_power Matrix to integer power matrix_rank Numerical rank matrix_transpose Transpose last 2 dims outer Outer product pinv Pseudo-inverse qr QR decomposition slogdet Sign and log-determinant solve Solve linear system svd Singular value decomposition svdvals Singular values only tensordot Tensor contraction trace Sum of diagonal vecdot Vector dot product vector_norm Vector norm NumSharp Status: We have matmul, outer, trace, and basic operations. The decompositions (qr, svd, eigh, cholesky, inv) are stubs that return null. FFT Extension (14 functions) Accessible via fft namespace. Function Description fft 1-D discrete Fourier transform ifft Inverse of fft fftn N-D DFT ifftn Inverse of fftn rfft 1-D DFT for real input irfft Inverse of rfft rfftn N-D DFT for real input irfftn Inverse of rfftn hfft 1-D DFT for Hermitian input ihfft Inverse of hfft fftfreq DFT sample frequencies rfftfreq Sample frequencies for rfft fftshift Shift zero-frequency to center ifftshift Inverse of fftshift NumSharp Status: Not implemented. FFT requires complex number support. What's NOT in the Standard The Array API deliberately excludes some things to remain implementable across diverse libraries: Out of Scope I/O operations — No save, load, fromfile String dtypes — No StringDType or fixed-width strings Datetime dtypes — No datetime64, timedelta64 Object dtype — No arrays of arbitrary Python objects Specific error types — Error handling is implementation-defined C API — Only Python-level interface specified Execution semantics — Eager vs. lazy, parallelization, etc. This means NumSharp can have these features (and we do—np.save, np.load work), they're just outside the Array API specification. Real-World Use Cases The specification documents several motivating use cases: SciPy Without Dependencies SciPy's signal processing functions are pure Python but tied to NumPy. With Array API compliance, scipy.signal.welch(x) could work on GPU arrays (CuPy), distributed arrays (Dask), or NumSharp arrays—without SciPy depending on any of them. einops Without Backend Code The einops library maintains ~550 lines of glue code to support multiple backends. Array API compliance would eliminate this entirely. JIT Compilation Numba and other JIT compilers struggle with NumPy's value-dependent type rules. The Array API's strict type-based promotion makes JIT compilation predictable. NumSharp's Path to Compliance Current Coverage Category Functions NumSharp % Creation 16 13 81% Element-wise 67 ~50 75% Statistical 9 8 89% Manipulation 14 11 79% Set 4 1 25% Searching 6 4 67% Sorting 2 2 100% Linear Algebra 4 4 100% Indexing 2 0 0% Data Types 6 3 50% Utility 3 2 67% Total Core 133 ~98 ~74% Priority Items Complex number types — Blocks FFT extension and many math functions device and mT properties — Simple to add Set functions (unique_* family) — Moderate effort Missing element-wise functions — Incremental work Indexing functions (take, take_along_axis) — Moderate effort Tracking See Array API Standard Milestone for detailed issue tracking. References Array API Standard Specification — The full specification Type Promotion Rules — How types combine Linear Algebra Extension — All linalg functions FFT Extension — All FFT functions Consortium for Python Data API Standards — The organization behind the standard NumPy Array API Support — NumPy's implementation notes" + }, + "docs/broadcasting.html": { + "href": "docs/broadcasting.html", + "title": "Broadcasting | NumSharp Documentation", + "summary": "Broadcasting Broadcasting allows arithmetic operations between arrays of different shapes. When you add a (3, 4) matrix to a (4,) vector, NumSharp automatically \"broadcasts\" the vector across each row—no explicit loops or copying required. How Broadcasting Works NumSharp follows NumPy's broadcasting rules exactly: Shapes align from the right. If arrays have different numbers of dimensions, prepend 1s to the shorter shape. Dimensions must be equal or 1. For each dimension, sizes must match OR one must be 1. Size-1 dimensions stretch. A dimension of size 1 expands to match the other array's size in that dimension. // (3, 4) + (4,) → (3, 4) + (1, 4) → (3, 4) var matrix = np.ones((3, 4)); var row = np.array(new[] {1, 2, 3, 4}); var result = matrix + row; // Shape: (3, 4) Broadcasting creates views, not copies. The stretched array doesn't allocate new memory—it uses stride tricks to repeat values virtually. Shape Compatibility Compatible Shapes Shape A Shape B Result Notes (5,) (5,) (5,) Same shape (5,) () (5,) Scalar broadcasts to any shape (3, 4) (4,) (3, 4) Row vector broadcasts across rows (3, 4) (3, 1) (3, 4) Column vector broadcasts across columns (3, 1) (1, 4) (3, 4) Both arrays stretch (2, 3, 4) (3, 4) (2, 3, 4) Lower-dimensional array broadcasts (8, 1, 6, 1) (7, 1, 5) (8, 7, 6, 5) Complex case with multiple stretch dimensions Incompatible Shapes Shape A Shape B Error (3,) (4,) 3 ≠ 4, neither is 1 (3, 4) (3,) Trailing dimensions 4 ≠ 3 (2, 3) (3, 2) No valid alignment Incompatible shapes throw IncorrectShapeException. Broadcasting Functions np.broadcast_to(array, shape) Broadcasts an array to a specific shape. Returns a read-only view. var a = np.array(new[] {1, 2, 3}); var b = np.broadcast_to(a, (4, 3)); // b.shape: (4, 3) // b[0]: [1, 2, 3] // b[1]: [1, 2, 3] (same data, not copied) Constraints: The source shape must be unilaterally broadcastable to the target. You can only stretch dimensions that are size 1: np.broadcast_to(np.ones((2,)), (3, 3)); // Error: can't stretch 2 to 3 np.broadcast_to(np.ones((1, 3)), (4, 3)); // OK: stretches 1 to 4 np.broadcast_arrays(array1, array2, ...) Broadcasts multiple arrays against each other, returning views with a common shape. var a = np.array(new[] {1, 2, 3}); // (3,) var b = np.array(new[,] {{1}, {2}}); // (2, 1) var (a_bc, b_bc) = np.broadcast_arrays(a, b); // Both now (2, 3) Also available as: NDArray[] results = np.broadcast_arrays(arr1, arr2, arr3); Implicit Broadcasting All arithmetic operators broadcast automatically: var a = np.ones((3, 4)); var b = np.array(new[] {1, 2, 3, 4}); a + b; // (3, 4) a - b; // (3, 4) a * b; // (3, 4) a / b; // (3, 4) Memory Behavior Broadcasted arrays are views that share memory with the original: var small = np.array(new[] {1, 2, 3}); // 3 elements var big = np.broadcast_to(small, (1000000, 3)); // Appears as 3M elements // big.size == 3_000_000 // Actual memory: still just 3 elements // big.Shape.IsBroadcasted == true Important: Broadcasted arrays should be treated as read-only. Writing to a broadcasted position affects all positions that share that memory. If you need to modify a broadcasted array, copy it first: var writable = big.copy(); // Allocates full 3M elements Implementation Details NumSharp implements broadcasting through stride manipulation. When a dimension is broadcast: The shape shows the expanded size The stride for that dimension is set to 0 A stride of 0 means the index doesn't advance in memory—the same element is read repeatedly. var a = np.array(new[] {1, 2, 3}); var b = np.broadcast_to(a, (4, 3)); // b's internal representation: // Shape: (4, 3) // Strides: (0, 1) ← stride 0 in first dimension This is tracked via Shape.IsBroadcasted and BroadcastInfo. Common Patterns Centering Data (subtract mean) var data = np.random.rand(100, 5); // 100 samples, 5 features var mean = np.mean(data, axis: 0); // (5,) var centered = data - mean; // (100, 5) - broadcasts Normalizing (divide by std) var std = np.std(data, axis: 0); // (5,) var normalized = centered / std; // (100, 5) Outer Product var row = np.array(new[] {1, 2, 3}); // (3,) var col = np.array(new[,] {{10}, {20}}); // (2, 1) var outer = row * col; // (2, 3) Batch Operations var batch = np.random.rand(32, 28, 28); // 32 images var mean_image = np.mean(batch, axis: 0); // (28, 28) var normalized = batch - mean_image; // (32, 28, 28) Troubleshooting \"shape mismatch: objects cannot be broadcast\" Shapes don't follow broadcasting rules. Check alignment: // Wrong var a = np.ones((3, 4)); var b = np.ones((3,)); // Trailing dim 4 ≠ 3 var c = a + b; // Error // Fix: reshape to column vector var c = a + b.reshape(3, 1); // Now (3, 4) + (3, 1) works Unexpected Output Shape If you get a larger shape than expected, you may have accidentally broadcast: var a = np.ones((10, 1)); var b = np.ones((1, 10)); var c = a + b; // (10, 10) — both stretched! Row vs Column Vector A 1-D array (n,) broadcasts as a row (1, n), not a column: var vec = np.array(new[] {1, 2, 3}); // (3,) — not (1, 3) or (3, 1) // To broadcast as column: var col = vec.reshape(3, 1); // (3, 1) // or var col = vec[np.newaxis].T; // (3, 1) API Reference Function Description np.broadcast_to(arr, shape) Broadcast array to specific shape (returns view) np.broadcast_arrays(a, b) Broadcast two arrays to common shape (returns tuple) np.broadcast_arrays(params NDArray[]) Broadcast multiple arrays (returns array) Property Description Shape.IsBroadcasted True if shape has broadcast strides (stride 0) BroadcastInfo Internal metadata for broadcast tracking Exception When IncorrectShapeException Shapes cannot be broadcast together" + }, + "docs/compliance.html": { + "href": "docs/compliance.html", + "title": "NumPy Compliance & Compatibility | NumSharp Documentation", + "summary": "NumPy Compliance & Compatibility NumSharp exists for one reason: to let you write NumPy-style code in C#. But \"NumPy-style\" isn't just about having similar function names—it's about behaving the same way. When you add a scalar to an array, when you slice with negative indices, when you broadcast two arrays together, NumSharp should do exactly what NumPy does. This page explains where we are on that journey, what challenges we face, and how you can help. Why Compatibility Matters If you're porting Python ML code to C#, the last thing you want is subtle behavioral differences causing bugs. Consider this Python code: import numpy as np a = np.array([1, 2, 3], dtype=np.uint8) b = a + 255 print(b) # [0, 1, 2] - overflow wraps around What should NumSharp do here? In NumPy 1.x, this would silently upcast to int16 to avoid overflow. In NumPy 2.x, it wraps with a warning. These differences matter when you're debugging why your neural network produces different results in C#. Our goal is 1-to-1 behavioral compatibility with NumPy 2.x (currently targeting 2.4.2). We also aim to comply with the Python Array API Standard, which defines portable array operations across NumPy, PyTorch, JAX, and other libraries. The Big Picture: Three Compliance Tracks We're tracking compliance across three related but distinct standards: 1. NumPy 2.x Compatibility NumPy 2.0 (released April 2024) was a major breaking release. It changed how types are promoted, removed deprecated functions, and added new APIs. If you learned NumPy before 2024, some of your intuitions might be wrong now. Tracking: NumPy 2.x Compliance Milestone 2. Array API Standard The Python Array API Standard is an industry consortium effort to define a common API that works across array libraries. Write code against the Array API, and it runs on NumPy, PyTorch, JAX, CuPy, or Dask without changes. NumPy adopted it in version 2.0. Deep Dive: Array API Standard — Our dedicated page with full specification details Tracking: Array API Standard Milestone 3. NumPy Enhancement Proposals (NEPs) NEPs are the design documents that define NumPy's behavior. When we say \"NumPy does X,\" there's usually a NEP that specifies exactly what X means. We track the NEPs most relevant to NumSharp. Tracking: NEP Compliance Milestone Type Promotion: The Biggest Change in NumPy 2.0 If there's one thing you need to understand about NumPy 2.x compatibility, it's NEP 50: Promotion Rules for Python Scalars. The Old Way (NumPy 1.x) NumPy 1.x used \"value-based\" promotion. It would inspect the actual value of a scalar to decide the output type: # NumPy 1.x behavior np.result_type(np.int8, 1) # → int8 (1 fits in int8) np.result_type(np.int8, 255) # → int16 (255 doesn't fit, upcast!) This was convenient—you rarely got overflow errors. But it was also unpredictable. The same code could produce different types depending on the runtime values, making optimization and type inference nearly impossible. The New Way (NumPy 2.x) NumPy 2.x uses \"weak scalar\" promotion. Python scalars defer to the array's dtype: # NumPy 2.x behavior np.uint8(1) + 2 # → uint8(3) np.uint8(1) + 255 # → uint8(0) with overflow warning! The scalar 2 is \"weak\"—it takes on whatever type the array has. This is more predictable and enables better optimization, but it can cause overflow where NumPy 1.x would have silently upcasted. Where NumSharp Stands NumSharp currently has mixed behavior. Some operations follow the old value-based rules, others follow NEP 50. We're working on consistent NEP 50 compliance. Key Issue: #529 - Type promotion diverges from NumPy 2.x What you might see: If you're porting NumPy code and get unexpected results with mixed types (especially unsigned + signed), this is likely why. API Changes: What Got Removed and Added Removed in NumPy 2.0 (NEP 52) NumPy 2.0 cleaned house, removing ~100 deprecated functions and aliases. If you're porting old NumPy code, you might need to update these: Don't Use Use Instead Why It Changed np.round_ np.round Underscore was to avoid Python keyword conflict (no longer needed) np.product np.prod Consistency with sum → prod np.sometrue np.any Clearer naming np.alltrue np.all Clearer naming np.rank np.ndim rank was confusing (matrix rank vs array rank) NumSharp supports the canonical names. We never implemented most deprecated aliases, so this is actually an advantage—less legacy baggage. Added in NumPy 2.0 (NEP 56) NumPy 2.0 added Array API Standard functions. These are mostly aliases for existing functions, but some are genuinely new: New Aliases (for Array API compatibility): np.acos, np.asin, np.atan → aliases for arccos, arcsin, arctan np.concat → alias for concatenate np.permute_dims → alias for transpose np.pow → alias for power Genuinely New: np.isdtype(dtype, kind) — Check if dtype belongs to a category np.unique_values(), np.unique_counts(), np.unique_inverse(), np.unique_all() — Split the overloaded np.unique() into focused functions ndarray.mT — Matrix transpose (transposes last two dimensions only) ndarray.device — Returns the device (CPU for NumSharp) NumSharp Status: We have most aliases but are missing isdtype(), the unique_* family, .mT, and .device. Data Types: What We Support (and Don't) NumSharp supports 12 numeric types—more than most users need, but not everything NumPy offers. Fully Supported NumSharp Type C# Type NumPy Type Notes Boolean bool bool_ Byte byte uint8 Int16 short int16 UInt16 ushort uint16 Int32 int int32 Default integer type UInt32 uint uint32 Int64 long int64 UInt64 ulong uint64 Single float float32 Double double float64 Default float type Char char — C#-specific, no NumPy equivalent Decimal decimal — C#-specific, 128-bit decimal Not Yet Supported Complex Numbers (complex64, complex128) This is our biggest gap. Complex numbers are required by the Array API Standard and essential for signal processing, FFT, and many scientific applications. They're also tricky to implement efficiently in C#. Why it's hard: C# has System.Numerics.Complex, but it's always 128-bit (complex128). There's no native complex64. We'd need to implement our own struct for float-based complex numbers. DateTime Types (datetime64, timedelta64) NumPy's datetime types (NEP 7) are powerful for time series analysis. We haven't implemented them. Why it's hard: NumPy datetime64 has multiple resolutions (nanoseconds to years) stored in the dtype. C# has DateTime and TimeSpan, but they don't map cleanly to NumPy's model. Variable-Width Strings (StringDType) NumPy 2.0 added a new UTF-8 variable-width string type (NEP 55). The old fixed-width strings (S10, U10) wasted memory. We don't support either. Memory Layout: C-Order Only Here's a limitation that might surprise NumPy users: NumSharp only supports C-order (row-major) memory layout. What This Means NumPy arrays can be stored in two layouts: C-order (row-major): Last index varies fastest. Default in NumPy. F-order (column-major): First index varies fastest. Default in Fortran, MATLAB. # NumPy can do both c_array = np.zeros((3, 4), order='C') # Row-major f_array = np.zeros((3, 4), order='F') # Column-major NumSharp always uses C-order. The order parameter exists on functions like reshape, ravel, and flatten, but it's ignored—we always use C-order. When This Matters Most of the time, you won't notice. But if you're: Interfacing with Fortran libraries (LAPACK, BLAS) Reading data written by MATLAB Optimizing cache access patterns for column-wise operations ...you might hit issues. See #546 for F-order support tracking. Array API Standard The Array API Standard specifies 133 core functions, 14 data types, and strict type promotion rules. NumSharp currently implements about 74% of the core specification. Category Required NumSharp Coverage Creation 16 13 81% Element-wise 67 ~50 75% Statistical 9 8 89% Manipulation 14 11 79% Set 4 1 25% Other 23 ~15 ~65% Biggest Gaps: Complex number types (complex64, complex128) — blocks FFT and many math functions Set functions (unique_all, unique_counts, unique_inverse) Array properties (.device, .mT) For the complete specification details, function lists, type promotion rules, and extension coverage, see our dedicated Array API Standard page. Random Number Generation Good news: NumSharp's np.random module provides 1-to-1 seed matching with NumPy. // NumSharp np.random.seed(42); var a = np.random.rand(5); // Produces: [0.37454012, 0.95071431, 0.73199394, 0.59865848, 0.15601864] // Equivalent Python np.random.seed(42) a = np.random.rand(5) # Produces: [0.37454012, 0.95071431, 0.73199394, 0.59865848, 0.15601864] This is critical for reproducibility. If you're porting ML code that depends on specific random sequences (for testing, debugging, or reproducible experiments), you'll get identical results. Supported Distributions Uniform: rand, uniform, randint Normal: randn, normal Other: beta, binomial, gamma, poisson, exponential, geometric, lognormal, chisquare, bernoulli Utilities: seed, shuffle, permutation, choice File Format Interoperability NumSharp can read and write NumPy's .npy file format. This means you can: Create arrays in Python, save with np.save(), load in NumSharp Create arrays in NumSharp, save with np.save(), load in Python Share data files between Python and C# applications // Save var arr = np.arange(100).reshape(10, 10); np.save(\"mydata.npy\", arr); // Load var loaded = np.load(\"mydata.npy\"); .npz Archives NumPy's .npz format stores multiple arrays in a ZIP archive. NumSharp can read .npz files but not write them yet. // Load multiple arrays from .npz var archive = np.load(\"data.npz\") as NpzDictionary; var weights = archive[\"weights\"]; var biases = archive[\"biases\"]; Linear Algebra: Partial Support NumSharp has basic linear algebra operations, but advanced decompositions are incomplete. Working Function Notes np.dot Matrix multiplication np.matmul Matrix multiplication (equivalent to @ in Python) np.outer Outer product ndarray.T Transpose Stubs (Return null/default) These functions exist but don't work: np.linalg.inv — Matrix inverse np.linalg.qr — QR decomposition np.linalg.svd — Singular value decomposition np.linalg.lstsq — Least squares Why? These originally used native LAPACK bindings that have been removed. Implementing them in pure C# is possible but significant work. What's Next: Implementation Roadmap Phase 1: Core Compatibility (Current Focus) Fix type promotion to match NEP 50 Add Array API function aliases Implement isdtype(), unique_* family Add .mT and .device properties Phase 2: Feature Completeness Complex number support (complex64, complex128) datetime64 / timedelta64 types Complete missing Array API functions Phase 3: Linear Algebra Implement matrix decompositions (QR, SVD, etc.) Either pure C# or via Math.NET Numerics integration Phase 4: Performance SIMD optimization for element-wise operations Iterator optimization for non-contiguous arrays How You Can Help NumSharp is open source. Here's how to contribute: Report incompatibilities. If NumSharp behaves differently from NumPy, file an issue with both code snippets. Add tests. Write tests that verify NumPy behavior, then make them pass in NumSharp. Implement missing functions. Check the milestones for prioritized work. GitHub Milestones NumPy 2.x Compliance — 7 open issues Array API Standard — 1 open issue NEP Compliance — 9 open issues References NumPy 2.0 Migration Guide — What changed in NumPy 2.0 Python Array API Standard — The specification we're implementing NumPy Enhancement Proposals — Design documents for NumPy behavior NumPy Source (v2.4.2) — Reference implementation (also at src/numpy/ in our repo)" + }, + "docs/extensions/bitmap.html": { + "href": "docs/extensions/bitmap.html", + "title": "NumSharp.Bitmap | NumSharp Documentation", + "summary": "NumSharp.Bitmap The NumSharp.Bitmap package provides seamless conversion between System.Drawing.Bitmap and NDArray. If you're working with images in .NET—loading them, processing pixels, applying filters, or feeding them to ML models—this extension makes it easy to move data between the image world and the array world. Installation NumSharp.Bitmap is a separate NuGet package: dotnet add package NumSharp.Bitmap Platform Note: This extension uses System.Drawing.Common, which is only fully supported on Windows. On Linux/macOS, you'll need additional setup (libgdiplus) or consider alternatives like ImageSharp. Quick Start using System.Drawing; using NumSharp; // Load an image and convert to NDArray var bitmap = new Bitmap(\"photo.jpg\"); var pixels = bitmap.ToNDArray(); // Shape: (1, height, width, channels) // e.g., (1, 480, 640, 3) for a 640x480 RGB image // Manipulate the pixel data var brightened = (pixels.astype(NPTypeCode.Int32) + 50).clip(0, 255).astype(NPTypeCode.Byte); // Convert back to Bitmap var result = brightened.ToBitmap(); result.Save(\"brightened.jpg\"); Converting Bitmaps to NDArrays Bitmap.ToNDArray() The primary method for converting images to arrays. public static NDArray ToNDArray( this Bitmap image, bool flat = false, bool copy = true, bool discardAlpha = false ) Parameters: Parameter Default Description flat false If true, returns 1-D array of pixels: R1G1B1R2G2B2... copy true If true, copies pixel data. If false, wraps bitmap memory directly. discardAlpha false If true, strips the alpha channel (4th channel) from 32bpp images. Return Shape: flat=false: (1, height, width, channels) — 4-D tensor suitable for ML models flat=true: (height * width * channels,) — 1-D array of raw pixel bytes Examples Standard conversion (recommended for most uses): var bitmap = new Bitmap(\"image.png\"); var nd = bitmap.ToNDArray(); Console.WriteLine(nd.shape); // e.g., (1, 480, 640, 4) for 32bpp ARGB Console.WriteLine(nd.dtype); // Byte Discard alpha channel: // 32bpp ARGB → 3 channels (RGB only) var rgb = bitmap.ToNDArray(discardAlpha: true); Console.WriteLine(rgb.shape); // (1, 480, 640, 3) Flat pixel array: // For algorithms that expect 1-D input var flat = bitmap.ToNDArray(flat: true); Console.WriteLine(flat.ndim); // 1 Zero-copy mode (advanced): // Wraps bitmap memory directly — faster but risky var wrapped = bitmap.ToNDArray(copy: false); // WARNING: The NDArray becomes invalid if the bitmap is disposed // or modified. The bitmap remains locked until the NDArray is GC'd. Memory Layout The pixel data is in BGR/BGRA order (Windows GDI convention), not RGB: var nd = bitmap.ToNDArray(); // nd[0, y, x, 0] = Blue // nd[0, y, x, 1] = Green // nd[0, y, x, 2] = Red // nd[0, y, x, 3] = Alpha (if 32bpp) If you need RGB order for ML models, swap the channels: // BGRA → RGBA var rgba = nd[Slice.All, Slice.All, Slice.All, new int[] {2, 1, 0, 3}]; Converting NDArrays to Bitmaps NDArray.ToBitmap() Converts an NDArray back to a Bitmap. public static Bitmap ToBitmap( this NDArray nd, int width, int height, PixelFormat format = PixelFormat.DontCare ) // Overload that infers dimensions from shape public static Bitmap ToBitmap( this NDArray nd, PixelFormat format = PixelFormat.DontCare ) Requirements: NDArray must be 4-D: (1, height, width, channels) First dimension must be 1 (single image) dtype should be Byte Channels must match the pixel format (3 for 24bpp, 4 for 32bpp) Examples Basic conversion: var nd = np.zeros(1, 100, 200, 3).astype(NPTypeCode.Byte); var bitmap = nd.ToBitmap(); // Infers: 200x100 image, 24bpp RGB Explicit format: var nd = np.zeros(1, 100, 200, 4).astype(NPTypeCode.Byte); var bitmap = nd.ToBitmap(200, 100, PixelFormat.Format32bppArgb); From flat array: // If you have a 1-D array, provide dimensions and format var flat = np.arange(0, 200 * 100 * 3).astype(NPTypeCode.Byte); var bitmap = flat.ToBitmap(200, 100, PixelFormat.Format24bppRgb); Supported Pixel Formats Format Channels Bytes/Pixel Format24bppRgb 3 3 Format32bppArgb 4 4 Format32bppPArgb 4 4 Format32bppRgb 4 4 Format48bppRgb 3 6 Format64bppArgb 4 8 Format64bppPArgb 4 8 Working with BitmapData Directly For performance-critical code, you can work with BitmapData directly. BitmapData.AsNDArray() Wraps locked bitmap data as an NDArray without copying. var bitmap = new Bitmap(\"image.png\"); var bmpData = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat ); try { var nd = bmpData.AsNDArray(flat: false, discardAlpha: false); // Process pixels... // WARNING: nd is only valid while bits are locked! } finally { bitmap.UnlockBits(bmpData); } Warning: The NDArray points directly to bitmap memory. If you call UnlockBits(), the NDArray becomes invalid and accessing it causes undefined behavior. Common Patterns Image Preprocessing for ML // Load and normalize for neural network input var bitmap = new Bitmap(\"input.jpg\"); var nd = bitmap.ToNDArray(discardAlpha: true); // (1, H, W, 3) // Normalize to [0, 1] range var normalized = nd.astype(NPTypeCode.Single) / 255.0f; // Resize would require additional libraries (not built into NumSharp) Grayscale Conversion var bitmap = new Bitmap(\"color.jpg\"); var rgb = bitmap.ToNDArray(discardAlpha: true); // (1, H, W, 3) // Luminance formula: 0.299*R + 0.587*G + 0.114*B // Note: GDI uses BGR order, so channels are [B, G, R] var b = rgb[Slice.All, Slice.All, Slice.All, 0].astype(NPTypeCode.Single); var g = rgb[Slice.All, Slice.All, Slice.All, 1].astype(NPTypeCode.Single); var r = rgb[Slice.All, Slice.All, Slice.All, 2].astype(NPTypeCode.Single); var gray = (0.114f * b + 0.587f * g + 0.299f * r).astype(NPTypeCode.Byte); // Shape: (1, H, W) - single channel Batch Processing // Process multiple images var files = Directory.GetFiles(\"images/\", \"*.jpg\"); var batch = new List(); foreach (var file in files) { using var bitmap = new Bitmap(file); var nd = bitmap.ToNDArray(discardAlpha: true); batch.Add(nd); } // Stack into batch: (N, H, W, 3) // Note: All images must have same dimensions var batchArray = np.concatenate(batch.ToArray(), axis: 0); Round-Trip (Load, Process, Save) // Load var original = new Bitmap(\"photo.jpg\"); var nd = original.ToNDArray(); // Process: invert colors var inverted = (255 - nd.astype(NPTypeCode.Int32)).clip(0, 255).astype(NPTypeCode.Byte); // Save var result = inverted.ToBitmap(); result.Save(\"inverted.jpg\", ImageFormat.Jpeg); Known Limitations Platform Support System.Drawing.Common is Windows-only in .NET 6+. On other platforms: // This throws PlatformNotSupportedException on Linux/macOS var bitmap = new Bitmap(\"image.png\"); Workarounds: Use libgdiplus on Linux (limited compatibility) Use ImageSharp or SkiaSharp (different API, not covered by this extension) Stride Padding Bitmaps may have stride padding (row alignment to 4-byte boundaries). The extension handles this in most cases, but odd-width 24bpp images may have issues with copy: true. Use copy: false for odd-width images. Color Order Windows bitmaps use BGR/BGRA byte order, not RGB. If your ML model expects RGB, you need to swap channels manually. No Resize NumSharp doesn't include image resizing. You'll need to resize in System.Drawing before converting, or use a library like ImageSharp. API Reference Extension Methods Method Description Bitmap.ToNDArray(...) Convert Bitmap to NDArray Image.ToNDArray(...) Convert Image to NDArray (creates Bitmap internally) BitmapData.AsNDArray(...) Wrap locked BitmapData as NDArray (no copy) NDArray.ToBitmap(...) Convert NDArray to Bitmap Helper Methods Method Description PixelFormat.ToBytesPerPixel() Get bytes per pixel for a format" + }, + "docs/extensions/index.html": { + "href": "docs/extensions/index.html", + "title": "Extending Libraries | NumSharp Documentation", + "summary": "Extending Libraries NumSharp is designed to integrate with the broader .NET ecosystem. Extension packages bridge NumSharp arrays with platform-specific features and external libraries. Official Extensions Package Purpose NumSharp.Bitmap Image ↔ NDArray conversion via System.Drawing Build Your Own NumSharp exposes low-level memory access for integration with native libraries, GPU frameworks, or domain-specific formats: // Access raw memory for interop byte* ptr = (byte*)ndarray.Unsafe.Address; // Wrap external memory as NDArray var nd = new NDArray(new ArraySlice( new UnmanagedMemoryBlock(ptr, length, onDispose) )); Have an extension to share? Open a PR to add it to this list." + }, + "docs/intro.html": { + "href": "docs/intro.html", + "title": "Introduction | NumSharp Documentation", + "summary": "Introduction The following pages are for the users who want to use NumSharp. Before you read the code examples you should read this page which explain some basis concepts. An other reference can be numpy since we try our best to follow their APIs (High level - not lower level). NDArray, NDStorgage and Shape The 3 main classes in NumSharp are NDArray, NDStorage and Shape. If you want to have a better understanding for NumSharp, you can read the following lines to see how all works together. Let's start with the question - what is a Tensor? From programming point of view a tensor is a multi-dimensional array (scalar, vector, matrix, ...) mostly for numerical data like int32, int64, doubles, ... which can be accessed via indexes like np[idx], np[idx,jdx], np[idx,jdx,kdx], ... depending on its dimension. Ok - in this sentence we got already some properties. a tensor is an object for storing (mostly) numerical data a tensor has a dimension the dimension decides how many indexes are necessary to access the stored data Each tensor type (dimension 1 - vector, dimension 2 - matrix, ...) has its own .NET type like double[,]. NumSharp brings its own tensor / array type called NDArray. So now the question - .NET offers already multi-dimensional arrays - why a new array type? NumSharps NDArray offers the capability of storing any tensor (independent of dimension!) into its internal storage. So NumSharps NDArray can store a vector, a matrix or sth with dimension 5 and higher. This is not possible with .NET arrays since each tensor type is a different class. This offers users the possibility to use same methods for different tensor types. Now the next question - how a NDArray can do this? First of all we need to be a little bit more abstract. Why we use tensors? Because we want to store data and we want to get them. How we get and set them? We get and set via indexes (which are always integers). So just this data are important and the corresponding indexes. That's it. Data + Indexes. :) With this in mind we easily can understand the NDStorage of NumSharp. NDStorage is an object which stores the data of a tesor in a single 1D array. Since it is a 1D array independend of the tensor dimension NDStorage can be used for all kind of tensors. A vector is stored inside a 1D array, a matrix, a 3 dimensional tensor and so on. But hold on! How the data comes into this 1D arrayand how we get them back? NDStorage has a property called \"shape\". The shape is a small but important class in NumSharp. It stores the dimensions and most important! it determines which element in the 1D array is selected by given indexes. To understand the methods for determines 1D internal storage index by NDArray indexes and vice versa we give examples of different tensor types. Vector Imagine a 1D tensor (a vector). Here it is easy because you can access the data with a single index like 'a = np[idx]'. The internal data store in NDStorage is a 1D array - so index to access is the same index in internal storage. Matrix Here it is a little bit more tricky. Each data element is stored by 2 indexes like np[idx,jdx] = 5. The internal storage is a 1D array so .... there must be a way to map the 2 indexes [idx,jdx] at NDArray level to a single index [kdx] in NDStorage level. Indeed there is! Not just in NumSharp but also in many other frameworks, libs or (general spoken) languages it is good style to store the elements of a matrix row wise or column wise into a 1D array. For a more professional description you can check https://en.wikipedia.org/wiki/Row-_and_column-major_order. Row wise Layout and column wise layout often also called row major and column major. General spoken when imagine a matrix as a table - Row wise means that you start with element [0,0] (as your first element in 1D array) and take elements from columns of 1st row (and store them in the 1D array) until all elements of the 1st row are stored inside the 1D array. You go on with the 2nd row - take element [1,0],[1,1],[1,2],...,[1,n-1]. Go on with this pattern until all elements are inside the 1D array. Column wise also starts with the element [0,0] but! it stays in the 1st column and takes elements along the rows until all elements from 1st column is stored. Repeat this with 2nd column, 3rd and so on. The image below (taken from https://en.wikipedia.org/wiki/File:Row_and_column_major_order.svg) shows again the 'algorithm' for storing data from matrix to vector. N dim tensor Now we come to the most tricky question - how to store a general n dimensional tensor inside a 1D array. Short anwser - exactly like a matrix - just more generalized. First we look again the row wise order. [0,0] -> [0,1] -> [0,2] -> [0,3] -> [0,n-1] -> [1,0] -> [1,1] -> [1,2] -> [1,3] -> ... So here we stay in one dimension (the first / rows) and fill the other dimensions until the dimension is full. After we switch to the next higher level of dimension (so change to next row). For higher dimensions like 3D - NumSharp follow this pattern. [0,0,0] -> [0,0,1] -> [0,0,2] -> [0,0,3] -> [0,0,n-1] -> [0,1,0] -> [0,1,1] -> [0,1,n-1] -> [0,2,0] -> [0,2,n-1] -> [0,m-1,0] -> ... General spoken - you can image it as a backward filling layout. As you can see the dimensions are filled beginning from last dimension, if one dimension is full, the dimension before is increased. Next we look the column wise order. [0,0] -> [1,0] -> [2,0] -> [3,0] -> [n-1,0] -> [0,1] -> [1,1] -> [2,1] -> [3,1] -> ... Again we stay in one dimension but here in the last / column. The rows are filled until the 1st column is full and next dimension is increased. So fill first dimension, increase next, fill again, etc. also in n dimensional tensor. [0,0,0] -> [1,0,0] -> [2,0,0] -> [3,0,0] -> [n-1,0,0] -> [0,1,0] -> [1,1,0] -> [n-1,1,0] -> [0,2,0] -> [n-1,2,0] -> [0,m-1,0] -> And this you can imagine as forward filling layout. That's it. Now you have enough knowledge about NDArray, NDStorage and Shape. Check the other chapters for a how to use. :)" + }, + "index.html": { + "href": "index.html", + "title": "Welcome to NumSharp | NumSharp Documentation", + "summary": "Welcome to NumSharp NumSharp is a .NET port of Python's NumPy library, bringing powerful numerical computing to the .NET ecosystem. Why NumSharp? NumPy API compatibility - Feel right at home if you're coming from Python High-performance NDArray - Multi-dimensional arrays stored efficiently in unmanaged memory Full .NET integration - Works seamlessly with C#, F#, VB.NET, and other .NET languages Part of the SciSharp ecosystem - Works alongside TensorFlow.NET, ML.NET, and other ML libraries Quick Start dotnet add package NumSharp using NumSharp; var a = np.array(new int[] { 1, 2, 3, 4, 5 }); var b = np.arange(5); var c = a + b; Console.WriteLine(c); // [1, 3, 5, 7, 9] Features Array Creation - np.zeros, np.ones, np.arange, np.linspace, and more Array Manipulation - Reshape, transpose, concatenate, stack operations Math Operations - Element-wise arithmetic, broadcasting, linear algebra Slicing & Indexing - NumPy-style slicing with views, not copies Random Sampling - Full numpy.random compatibility with seed/state matching File I/O - Load and save .npy and .npz files Get Started Introduction - Learn about NDArray, Shape, and Storage NumPy Compliance - Compatibility status and roadmap API Reference - Full API documentation Community GitHub Repository - Star us, report issues, contribute NuGet Package - Latest stable release" + } +} \ No newline at end of file diff --git a/docs/website/llms-full.txt b/docs/website/llms-full.txt new file mode 100644 index 000000000..a90417f91 --- /dev/null +++ b/docs/website/llms-full.txt @@ -0,0 +1,269 @@ +# NumSharp - Complete Documentation + +> This file contains the complete NumSharp documentation for AI/LLM ingestion. +> Auto-generated from source markdown files. + +--- + +## Table of Contents + +1. Introduction +2. Array creation +3. Linear algebra + +--- + +# Introduction + +The following pages are for the users who want to use NumSharp. + +Before you read the code examples you should read this page which explain some basis concepts. +An other reference can be numpy since we try our best to follow their APIs (**High level - not lower level**). + +## NDArray, NDStorgage and Shape + +The 3 main classes in NumSharp are NDArray, NDStorage and Shape. +If you want to have a better understanding for NumSharp, you can read the following lines to see how all works together. + +Let's start with the question - what is a Tensor? + +From programming point of view a tensor is a multi-dimensional array (scalar, vector, matrix, ...) mostly for numerical data like int32, int64, doubles, ... which can be accessed via indexes like np[idx], np[idx,jdx], np[idx,jdx,kdx], ... depending on its dimension. + +Ok - in this sentence we got already some properties. + +- a tensor is an object for storing (mostly) numerical data +- a tensor has a dimension +- the dimension decides how many indexes are necessary to access the stored data + +Each tensor type (dimension 1 - vector, dimension 2 - matrix, ...) has its own .NET type like double[,]. + +NumSharp brings its own tensor / array type called **NDArray**. + +So now the question - .NET offers already multi-dimensional arrays - why a new array type? + +NumSharps NDArray offers the capability of storing any tensor (independent of dimension!) into its internal storage. +So NumSharps NDArray can store a vector, a matrix or sth with dimension 5 and higher. This is not possible with .NET arrays since each tensor type is a different class. This offers users the possibility to use same methods for different tensor types. + +Now the next question - how a NDArray can do this? + +First of all we need to be a little bit more abstract. Why we use tensors? Because we want to store data and we want to get them. How we get and set them? We get and set via indexes (which are always integers). So just this data are important and the corresponding indexes. That's it. Data + Indexes. :) + +With this in mind we easily can understand the NDStorage of NumSharp. + +NDStorage is an object which stores the data of a tesor in a single 1D array. Since it is a 1D array independend of the tensor dimension NDStorage can be used for all kind of tensors. A vector is stored inside a 1D array, a matrix, a 3 dimensional tensor and so on. + +**But hold on! How the data comes into this 1D arrayand how we get them back?** + +NDStorage has a property called "shape". The shape is a small but important class in NumSharp. It stores the dimensions and most important! it determines which element in the 1D array is selected by given indexes. + +To understand the methods for determines 1D internal storage index by NDArray indexes and vice versa we give examples of different tensor types. + +**Vector** + +Imagine a 1D tensor (a vector). Here it is easy because you can access the data with a single index like 'a = np[idx]'. The internal data store in NDStorage is a 1D array - so index to access is the same index in internal storage. + +**Matrix** + +Here it is a little bit more tricky. Each data element is stored by 2 indexes like np[idx,jdx] = 5. The internal storage is a 1D array so .... there must be a way to map the 2 indexes [idx,jdx] at NDArray level to a single index [kdx] in NDStorage level. + +Indeed there is! + +Not just in NumSharp but also in many other frameworks, libs or (general spoken) languages it is good style to store the elements of a matrix row wise or column wise into a 1D array. For a more professional description you can check https://en.wikipedia.org/wiki/Row-_and_column-major_order. Row wise Layout and column wise layout often also called row major and column major. + +General spoken when imagine a matrix as a table - Row wise means that you start with element [0,0] (as your first element in 1D array) and take elements from columns of 1st row (and store them in the 1D array) until all elements of the 1st row are stored inside the 1D array. You go on with the 2nd row - take element [1,0],[1,1],[1,2],...,[1,n-1]. Go on with this pattern until all elements are inside the 1D array. + +Column wise also starts with the element [0,0] but! it stays in the 1st column and takes elements along the rows until all elements from 1st column is stored. Repeat this with 2nd column, 3rd and so on. + +The image below (taken from https://en.wikipedia.org/wiki/File:Row_and_column_major_order.svg) shows again the 'algorithm' for storing data from matrix to vector. + + +![Row Wise Column Wise](../images/rowWise_ColumnWise.png) + + + +**N dim tensor** + +Now we come to the most tricky question - how to store a general n dimensional tensor inside a 1D array. + +Short anwser - exactly like a matrix - just more generalized. + +First we look again the row wise order. + +[0,0] -> [0,1] -> [0,2] -> [0,3] -> [0,n-1] -> [1,0] -> [1,1] -> [1,2] -> [1,3] -> ... + +So here we stay in one dimension (the first / rows) and fill the other dimensions until the dimension is full. +After we switch to the next higher level of dimension (so change to next row). + +For higher dimensions like 3D - NumSharp follow this pattern. + +[0,0,0] -> [0,0,1] -> [0,0,2] -> [0,0,3] -> [0,0,n-1] -> [0,1,0] -> [0,1,1] -> [0,1,n-1] -> [0,2,0] -> [0,2,n-1] -> [0,m-1,0] -> ... + +General spoken - you can image it as a **backward filling layout**. + +As you can see the dimensions are filled beginning from last dimension, if one dimension is full, the dimension before is increased. + +Next we look the column wise order. + +[0,0] -> [1,0] -> [2,0] -> [3,0] -> [n-1,0] -> [0,1] -> [1,1] -> [2,1] -> [3,1] -> ... + +Again we stay in one dimension but here in the last / column. The rows are filled until the 1st column is full and next dimension is increased. + +So fill first dimension, increase next, fill again, etc. also in n dimensional tensor. + +[0,0,0] -> [1,0,0] -> [2,0,0] -> [3,0,0] -> [n-1,0,0] -> [0,1,0] -> [1,1,0] -> [n-1,1,0] -> [0,2,0] -> [n-1,2,0] -> [0,m-1,0] -> + +And this you can imagine as **forward filling layout**. + +That's it. Now you have enough knowledge about NDArray, NDStorage and Shape. Check the other chapters for a how to use. :) + + + + + + + + + + + + + + + +--- + + # Array creation + +Before we do some fancy numeric stuff or even machine learning we have to clear one thing. + +**How do we generate NDArrays?** + +Since NDArray is the key class in SciSharp stack there must be numerous possibilities how to generate this arrays. And yes that’s the case. + +Maybe first of all we should see the dump way – which can be always used but is not too user friendly. +In this example we access the Storage property directly - one more reason to avoid it. + +**Dump way** + +```CSHARP +// first constructor with data type and shape (here 3x3 matrix) +var nd = new NDArray(typeof(double),3,3); + +// set 9 elements into the storage of this array. +np.Storage.SetData(new double[] {1,2,3,4,5,6,7,8,9}); +``` + +Ok looks not too difficult. But also not too userfriendly. + +We create an empty NDArray with 3x3 shape, fill it with 9 elements. +We followed the row wise matrix layour by default. + +So with this 3x3 shaped NDArray we can do matrix multiplication, QR decomposition, SVD, ... + +But keep in mind - always be careful with your shape and be sure what you want to do with your elements in this shape. + +**Create by enumeration** + +The next example shows the numpy style creation. + +```CSHARP +using NumSharp.Core; + +// we take the Data / elements from an array +// we do not need to define the shape here - it is automaticly shaped to 1D +var np1 = np.array(new double[] {1,2,3,4,5,6} ); +``` + +Ok as we can see, this time the array was created without define the shape. + +This is possible since the method expect that the double[] array shall be transformed into a NDArray directly. + +**Create by implicit cast** + +Beside this numpy style C# offers its own flavour of creation. + +```CSHARP +using NumSharp.Core; + +// implicit cast double[] to NDArray - dtype & shape are deduced by array type and shape +NDArray nd = new double[]{1,2,3,4}; +``` + +And for matrix and n dim tensors also work the same. + +```CSHARP +using NumSharp.Core; + +NDArray nd = new double[,]{{1,2,3},{4,5,6}}; +``` + +Beside the .NET array to NDArray converting there exist different kinds of methods which also exist in numpy. + +**Create by given range** + +```CSHARP +using NumSharp.Core; + +// we simple say "create an array with 10 elements" +// start is expected to be 0 and step 1 +var np1 = np.arange(10); + +// this time start with 1, step 2 +// and do it as long as smaller than 10 +var np2 = np.arange(1,10,2); +``` + +**Create diagonal matrix** + +```CSHARP +using NumSharp.Core; + +// simple 5x5 eye matrix +var nd1 = np.eye(5); + +// 3x3 eye matrix but elements different diagonal +nd1 = np.eye(3,1); +``` + +**Create by linspace** + +```CSHARP +using NumSharp.Core; + +// create vector with 50 elements, from 4 to 10 +// include last element +// and convert them to double (float64) +var nd1 = np.linspace(4,10, 50, true, np.float64); +``` + + +--- + + # Linear algebra + + Now we got some arrays so we should understand what we can do with it. + +## element wise operation + +## Matrix Transpose + +## Matrix and Vector multiplication + + ## Solve Linear Equation + + ## QR decomposition + + ## Inverse of Matrix + + ## SVD + +--- + +# API Quick Reference + +## Namespaces and Types + + +--- + +*Auto-generated from NumSharp documentation source files* diff --git a/docs/website/llms.txt b/docs/website/llms.txt new file mode 100644 index 000000000..e279ab34c --- /dev/null +++ b/docs/website/llms.txt @@ -0,0 +1,49 @@ +# NumSharp + +> NumSharp is a .NET port of Python's NumPy library, bringing powerful numerical computing to the .NET ecosystem. + +## Installation + +```bash +dotnet add package NumSharp +``` + +## Quick Start + +```csharp +using NumSharp; + +var a = np.array(new[] { 1, 2, 3, 4, 5 }); +var b = np.zeros((3, 4)); +var result = np.sum(a); +var slice = a["1:4"]; // Slicing returns views +``` + +## Documentation + +- [Introduction](https://scisharp.github.io/NumSharp/docs/intro.html): The following pages are for the users who want to use NumSharp. +- [Array creation](https://scisharp.github.io/NumSharp/docs/NDArray.Creation.html): Before we do some fancy numeric stuff or even machine learning we have to clear one thing. +- [Linear algebra](https://scisharp.github.io/NumSharp/docs/NDArray.LinAlg.html): Now we got some arrays so we should understand what we can do with it. + +## API Reference + +- [NumSharp.NDArray](https://scisharp.github.io/NumSharp/api/NumSharp.NDArray.html): Main n-dimensional array type +- [NumSharp.np](https://scisharp.github.io/NumSharp/api/NumSharp.np.html): Static NumPy-style API +- [NumSharp.Shape](https://scisharp.github.io/NumSharp/api/NumSharp.Shape.html): Array dimensions and strides + +## Supported Data Types + +bool, byte, short, ushort, int, uint, long, ulong, float, double, decimal, char + +## Key Concepts + +- **NDArray**: Multi-dimensional array in unmanaged memory +- **Shape**: Dimensions and strides for offset calculation +- **Broadcasting**: Arrays with different shapes operate element-wise +- **Views**: Slicing returns views (shared memory), use `.copy()` for copies + +## Optional + +- [Full API Reference](https://scisharp.github.io/NumSharp/api/): Complete class and method documentation +- [GitHub Repository](https://github.com/SciSharp/NumSharp): Source code and issues +- [NuGet Package](https://www.nuget.org/packages/NumSharp): Latest releases diff --git a/docs/logo.svg b/docs/website/logo.svg similarity index 100% rename from docs/logo.svg rename to docs/website/logo.svg diff --git a/docs/website/manifest.json b/docs/website/manifest.json new file mode 100644 index 000000000..99d033d13 --- /dev/null +++ b/docs/website/manifest.json @@ -0,0 +1,1457 @@ +{ + "sitemap": { + "baseUrl": "https://scisharp.github.io/NumSharp/", + "changefreq": "weekly", + "priority": 0.5 + }, + "source_base_path": "K:/source/NumSharp-docfx2/docs/website-src", + "xrefmap": "xrefmap.yml", + "files": [ + { + "type": "Resource", + "output": { + "resource": { + "relative_path": "index.json" + } + } + }, + { + "type": "ManagedReference", + "source_relative_path": "api/DecimalMath.DecimalEx.yml", + "output": { + ".html": { + "relative_path": "api/DecimalMath.DecimalEx.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "DecimalMath.DecimalEx", + "Summary": "

Contains mathematical operations performed in Decimal precision.

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/DecimalMath.yml", + "output": { + ".html": { + "relative_path": "api/DecimalMath.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "DecimalMath", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.AxisOutOfRangeException.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.AxisOutOfRangeException.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.AxisOutOfRangeException", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.BackendType.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.BackendType.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.BackendType", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Backends.BackendFactory.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Backends.BackendFactory.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Backends.BackendFactory", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Backends.DefaultEngine.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Backends.DefaultEngine.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Backends.DefaultEngine", + "Summary": "

Default Tensor Engine implemented in pure micro-optimized C#.

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Backends.Unmanaged.ArraySlice-1.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Backends.Unmanaged.ArraySlice-1.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Backends.Unmanaged.ArraySlice", + "Summary": "

is similar to but it can be moved around without having to follow ref struct rules.

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Backends.Unmanaged.ArraySlice.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Backends.Unmanaged.ArraySlice.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Backends.Unmanaged.ArraySlice", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Backends.Unmanaged.IArraySlice.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Backends.Unmanaged.IArraySlice.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Backends.Unmanaged.IArraySlice", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Backends.Unmanaged.IMemoryBlock-1.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Backends.Unmanaged.IMemoryBlock-1.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Backends.Unmanaged.IMemoryBlock", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Backends.Unmanaged.IMemoryBlock.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Backends.Unmanaged.IMemoryBlock.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Backends.Unmanaged.IMemoryBlock", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Backends.Unmanaged.IUnmanagedMemoryBlock.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Backends.Unmanaged.IUnmanagedMemoryBlock.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Backends.Unmanaged.IUnmanagedMemoryBlock", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Backends.Unmanaged.UnmanagedHelper.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Backends.Unmanaged.UnmanagedHelper.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Backends.Unmanaged.UnmanagedHelper", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock-1.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock-1.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Backends.Unmanaged.UnmanagedMemoryBlock", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Backends.Unmanaged.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Backends.Unmanaged.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Backends.Unmanaged", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Backends.UnmanagedStorage.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Backends.UnmanagedStorage.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Backends.UnmanagedStorage", + "Summary": "

Serves as a typed storage for an array.

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Backends.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Backends.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Backends", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.BroadcastInfo.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.BroadcastInfo.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.BroadcastInfo", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.DType.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.DType.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.DType", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Extensions.LinqExtensions.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Extensions.LinqExtensions.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Extensions.LinqExtensions", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Extensions.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Extensions.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Extensions", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Generic.NDArray-1.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Generic.NDArray-1.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Generic.NDArray", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Generic.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Generic.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Generic", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.IIndex.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.IIndex.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.IIndex", + "Summary": "

Represents a class that can be served as an index, e.g. ndarray[new Slice(...)]

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.INumSharpException.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.INumSharpException.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.INumSharpException", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.IncorrectShapeException.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.IncorrectShapeException.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.IncorrectShapeException", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.IncorrectSizeException.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.IncorrectSizeException.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.IncorrectSizeException", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.IncorrectTypeException.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.IncorrectTypeException.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.IncorrectTypeException", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.IteratorType.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.IteratorType.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.IteratorType", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Kwargs.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Kwargs.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Kwargs", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.MoveNextReferencedDelegate-1.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.MoveNextReferencedDelegate-1.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.MoveNextReferencedDelegate", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.MultiIterator.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.MultiIterator.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.MultiIterator", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.NDArray._Unsafe._Pinning.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.NDArray._Unsafe._Pinning.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.NDArray._Unsafe._Pinning", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.NDArray._Unsafe.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.NDArray._Unsafe.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.NDArray._Unsafe", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.NDArray.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.NDArray.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.NDArray", + "Summary": "

An array object represents a multidimensional, homogeneous array of fixed-size items.
\nAn associated data-type object describes the format of each element in the array (its byte-order,
\nhow many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.)

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.NDIterator-1.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.NDIterator-1.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.NDIterator", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.NDIterator.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.NDIterator.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.NDIterator", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.NDIteratorExtensions.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.NDIteratorExtensions.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.NDIteratorExtensions", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.NPTypeCode.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.NPTypeCode.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.NPTypeCode", + "Summary": "

Represents all available types in numpy.

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.NPTypeCodeExtensions.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.NPTypeCodeExtensions.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.NPTypeCodeExtensions", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.NativeRandomState.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.NativeRandomState.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.NativeRandomState", + "Summary": "

Represents the stored state of .

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.NpzDictionary-1.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.NpzDictionary-1.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.NpzDictionary", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.NpzDictionary.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.NpzDictionary.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.NpzDictionary", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.NumPyRandom.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.NumPyRandom.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.NumPyRandom", + "Summary": "

A class that serves as numpy.random.RandomState in python.

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.NumSharpException.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.NumSharpException.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.NumSharpException", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Randomizer.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Randomizer.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Randomizer", + "Summary": "

Represents a pseudo-random number generator, which is a device that produces a sequence of numbers that meet certain statistical requirements for randomness.
\nEquivalent of .

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Shape.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Shape.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Shape", + "Summary": "

Represents a shape of an N-D array.

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Slice.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Slice.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Slice", + "Summary": "
                                                                                                                                 <br />\n
\n

NDArray can be indexed using slicing
\nA slice is constructed by start:stop:step notation
\n
\nExamples:
\n
\na[start:stop] # items start through stop-1
\na[start:] # items start through the rest of the array
\na[:stop] # items from the beginning through stop-1
\n
\nThe key point to remember is that the :stop value represents the first value that is not
\nin the selected slice. So, the difference between stop and start is the number of elements
\nselected (if step is 1, the default).
\n
\nThere is also the step value, which can be used with any of the above:
\na[:] # a copy of the whole array
\na[start:stop:step] # start through not past stop, by step
\n
\nThe other feature is that start or stop may be a negative number, which means it counts
\nfrom the end of the array instead of the beginning. So:
\na[-1] # last item in the array
\na[-2:] # last two items in the array
\na[:-2] # everything except the last two items
\nSimilarly, step may be a negative number:
\n
\na[::- 1] # all items in the array, reversed
\na[1::- 1] # the first two items, reversed
\na[:-3:-1] # the last two items, reversed
\na[-3::- 1] # everything except the last two items, reversed
\n
\nNumSharp is kind to the programmer if there are fewer items than
\nyou ask for. For example, if you ask for a[:-2] and a only contains one element, you get an
\nempty list instead of an error.Sometimes you would prefer the error, so you have to be aware
\nthat this may happen.
\n
\nAdapted from Greg Hewgill's answer on Stackoverflow: https://stackoverflow.com/questions/509211/understanding-slice-notation
\n
\nNote: special IsIndex == true
\nIt will pick only a single value at Start in this dimension effectively reducing the Shape of the sliced matrix by 1 dimension.
\nIt can be used to reduce an N-dimensional array/matrix to a (N-1)-dimensional array/matrix
\n
\nExample:
\na=[[1, 2], [3, 4]]
\na[:, 1] returns the second column of that 2x2 matrix as a 1-D vector

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.SliceDef.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.SliceDef.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.SliceDef", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.StorageType.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.StorageType.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.StorageType", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.TensorEngine.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.TensorEngine.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.TensorEngine", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Unmanaged.Memory.ScalarMemoryPool.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Unmanaged.Memory.ScalarMemoryPool.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Unmanaged.Memory.ScalarMemoryPool", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Unmanaged.Memory.StackedMemoryPool.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Unmanaged.Memory.StackedMemoryPool.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Unmanaged.Memory.StackedMemoryPool", + "Summary": "

Pool of allocated buffers managed by internal garbage collection mechanism.

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Unmanaged.Memory.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Unmanaged.Memory.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Unmanaged.Memory", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.ArrayConvert.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.ArrayConvert.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.ArrayConvert", + "Summary": "

Presents all possible combinations of array conversion of types supported by numpy.

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.Arrays.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.Arrays.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.Arrays", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.ArraysExtensions.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.ArraysExtensions.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.ArraysExtensions", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.ConcurrentHashset-1.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.ConcurrentHashset-1.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.ConcurrentHashset", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.Converts-1.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.Converts-1.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.Converts", + "Summary": "

Provides various methods related to based on give T.

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.Converts.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.Converts.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.Converts", + "Summary": "

Provides various methods related to .

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.Hashset-1.Enumerator.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.Hashset-1.Enumerator.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.Hashset.Enumerator", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.Hashset-1.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.Hashset-1.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.Hashset", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.InfoOf-1.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.InfoOf-1.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.InfoOf", + "Summary": "

Provides a cache for properties of T that requires computation.

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.Linq.IEnumeratorExtensions.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.Linq.IEnumeratorExtensions.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.Linq.IEnumeratorExtensions", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.Linq.IExtremaEnumerable-1.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.Linq.IExtremaEnumerable-1.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.Linq.IExtremaEnumerable", + "Summary": "

Exposes the enumerator, which supports iteration over a sequence of\nsome extremum property (maximum or minimum) of a specified type.

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.Linq.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.Linq.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.Linq", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.NDCoordinatesAxisIncrementor.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.NDCoordinatesAxisIncrementor.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.NDCoordinatesAxisIncrementor", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.NDCoordinatesIncrementor.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.NDCoordinatesIncrementor.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.NDCoordinatesIncrementor", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.NDCoordinatesIncrementorAutoResetting.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.NDCoordinatesIncrementorAutoResetting.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.NDCoordinatesIncrementorAutoResetting", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.NDCoordinatesLeftToAxisIncrementor.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.NDCoordinatesLeftToAxisIncrementor.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.NDCoordinatesLeftToAxisIncrementor", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.NDExtendedCoordinatesIncrementor.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.NDExtendedCoordinatesIncrementor.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.NDExtendedCoordinatesIncrementor", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.NDOffsetIncrementor.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.NDOffsetIncrementor.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.NDOffsetIncrementor", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.NDOffsetIncrementorAutoresetting.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.NDOffsetIncrementorAutoresetting.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.NDOffsetIncrementorAutoresetting", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.NonGenericConvert.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.NonGenericConvert.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.NonGenericConvert", + "Summary": "

Provides a way to convert boxed object from known time to specific type.

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.NumberInfo.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.NumberInfo.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.NumberInfo", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.SteppingExtension.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.SteppingExtension.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.SteppingExtension", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.TypelessConvert.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.TypelessConvert.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.TypelessConvert", + "Summary": "

Provides a way to convert boxed object from known input type to known output type.\nBy making it receive and return - It is suitable for a common delegate: see

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.TypelessConvertDelegate.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.TypelessConvertDelegate.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.TypelessConvertDelegate", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.ValueCoordinatesIncrementor.EndCallbackHandler.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.ValueCoordinatesIncrementor.EndCallbackHandler.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.ValueCoordinatesIncrementor.EndCallbackHandler", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.ValueCoordinatesIncrementor.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.ValueCoordinatesIncrementor.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.ValueCoordinatesIncrementor", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.ValueCoordinatesIncrementorAutoResetting.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.ValueCoordinatesIncrementorAutoResetting.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.ValueCoordinatesIncrementorAutoResetting", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.ValueOffsetIncrementor.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.ValueOffsetIncrementor.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.ValueOffsetIncrementor", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.ValueOffsetIncrementorAutoresetting.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.ValueOffsetIncrementorAutoresetting.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.ValueOffsetIncrementorAutoresetting", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.py.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.py.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities.py", + "Summary": "

Implements Python utility functions that are often used in connection with numpy

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.Utilities.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.Utilities.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.Utilities", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.ViewInfo.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.ViewInfo.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.ViewInfo", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.np.Broadcast.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.np.Broadcast.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.np.Broadcast", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.np.linalg.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.np.linalg.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.np.linalg", + "Summary": null + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.np.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.np.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp.np", + "Summary": "

API bridge between NumSharp and Python NumPy

\n" + }, + { + "type": "ManagedReference", + "source_relative_path": "api/NumSharp.yml", + "output": { + ".html": { + "relative_path": "api/NumSharp.html" + } + }, + "version": "", + "Uid": null, + "IsMRef": true, + "Title": "NumSharp", + "Summary": null + }, + { + "type": "Conceptual", + "source_relative_path": "api/index.md", + "output": { + ".html": { + "relative_path": "api/index.html" + } + }, + "version": "" + }, + { + "type": "Toc", + "source_relative_path": "api/toc.yml", + "output": { + ".html": { + "relative_path": "api/toc.html" + }, + ".json": { + "relative_path": "api/toc.json" + } + }, + "version": "" + }, + { + "type": "Conceptual", + "source_relative_path": "docs/array-api-standard.md", + "output": { + ".html": { + "relative_path": "docs/array-api-standard.html" + } + }, + "version": "" + }, + { + "type": "Conceptual", + "source_relative_path": "docs/broadcasting.md", + "output": { + ".html": { + "relative_path": "docs/broadcasting.html" + } + }, + "version": "" + }, + { + "type": "Conceptual", + "source_relative_path": "docs/compliance.md", + "output": { + ".html": { + "relative_path": "docs/compliance.html" + } + }, + "version": "" + }, + { + "type": "Conceptual", + "source_relative_path": "docs/extensions/bitmap.md", + "output": { + ".html": { + "relative_path": "docs/extensions/bitmap.html" + } + }, + "version": "" + }, + { + "type": "Conceptual", + "source_relative_path": "docs/extensions/index.md", + "output": { + ".html": { + "relative_path": "docs/extensions/index.html" + } + }, + "version": "" + }, + { + "type": "Conceptual", + "source_relative_path": "docs/intro.md", + "output": { + ".html": { + "relative_path": "docs/intro.html" + } + }, + "version": "" + }, + { + "type": "Toc", + "source_relative_path": "docs/toc.yml", + "output": { + ".html": { + "relative_path": "docs/toc.html" + }, + ".json": { + "relative_path": "docs/toc.json" + } + }, + "version": "" + }, + { + "type": "Resource", + "source_relative_path": "images/numsharp.icon.svg", + "output": { + "resource": { + "relative_path": "images/numsharp.icon.svg" + } + }, + "version": "" + }, + { + "type": "Resource", + "source_relative_path": "images/numsharp.icon128.png", + "output": { + "resource": { + "relative_path": "images/numsharp.icon128.png" + } + }, + "version": "" + }, + { + "type": "Resource", + "source_relative_path": "images/python-csharp-comparision.png", + "output": { + "resource": { + "relative_path": "images/python-csharp-comparision.png" + } + }, + "version": "" + }, + { + "type": "Resource", + "source_relative_path": "images/rowWise_ColumnWise.png", + "output": { + "resource": { + "relative_path": "images/rowWise_ColumnWise.png" + } + }, + "version": "" + }, + { + "type": "Conceptual", + "source_relative_path": "index.md", + "output": { + ".html": { + "relative_path": "index.html" + } + }, + "version": "" + }, + { + "type": "Toc", + "source_relative_path": "toc.yml", + "output": { + ".html": { + "relative_path": "toc.html" + }, + ".json": { + "relative_path": "toc.json" + } + }, + "version": "" + } + ], + "groups": [ + { + "xrefmap": "xrefmap.yml" + } + ] +} \ No newline at end of file diff --git a/docs/website/public/architecture-O4VJ6CD3-GQAMQMPJ.min.js b/docs/website/public/architecture-O4VJ6CD3-GQAMQMPJ.min.js new file mode 100644 index 000000000..24618f02b --- /dev/null +++ b/docs/website/public/architecture-O4VJ6CD3-GQAMQMPJ.min.js @@ -0,0 +1,2 @@ +import{a as e,b as r}from"./chunk-6B6J5Z6Z.min.js";import"./chunk-LBFZT66H.min.js";import"./chunk-R5JLOOQ4.min.js";import"./chunk-PTL4EUOE.min.js";import"./chunk-E5F23VE2.min.js";import"./chunk-OSRY5VT3.min.js";export{e as ArchitectureModule,r as createArchitectureServices}; +//# sourceMappingURL=architecture-O4VJ6CD3-GQAMQMPJ.min.js.map diff --git a/docs/website/public/architecture-O4VJ6CD3-GQAMQMPJ.min.js.map b/docs/website/public/architecture-O4VJ6CD3-GQAMQMPJ.min.js.map new file mode 100644 index 000000000..98652118b --- /dev/null +++ b/docs/website/public/architecture-O4VJ6CD3-GQAMQMPJ.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": [], + "sourcesContent": [], + "mappings": "", + "names": [] +} diff --git a/docs/website/public/architectureDiagram-VXUJARFQ-H4V63UKK.min.js b/docs/website/public/architectureDiagram-VXUJARFQ-H4V63UKK.min.js new file mode 100644 index 000000000..99141ae04 --- /dev/null +++ b/docs/website/public/architectureDiagram-VXUJARFQ-H4V63UKK.min.js @@ -0,0 +1,37 @@ +import{a as qe}from"./chunk-V3WVIUUL.min.js";import{a as Qe}from"./chunk-I6VG5SPK.min.js";import"./chunk-LK7NMYKK.min.js";import{a as ze}from"./chunk-7EBV5LUJ.min.js";import"./chunk-6RTTMAJH.min.js";import"./chunk-LGVO22YL.min.js";import"./chunk-HVSI2YYT.min.js";import"./chunk-6B6J5Z6Z.min.js";import"./chunk-EU44H33B.min.js";import"./chunk-CQUFH26W.min.js";import"./chunk-LBFZT66H.min.js";import{b as Ze,c as ke,d as he,g as le}from"./chunk-XCAVDAZC.min.js";import"./chunk-R5JLOOQ4.min.js";import"./chunk-PTL4EUOE.min.js";import{a as Ee}from"./chunk-XXYYAETH.min.js";import{l as Be,p as $e}from"./chunk-QZZKR5JD.min.js";import"./chunk-CM5D5KZN.min.js";import{D as Fe,M as be,P as Pe,Q as Ge,R as Ue,S as Ye,T as Xe,U as He,V as We,W as se,q as Re,y as Se}from"./chunk-3EE2TK35.min.js";import"./chunk-E5F23VE2.min.js";import{b as ct,d as ye,j as Ve}from"./chunk-6TVUEPFY.min.js";import{a as pe,d as ur}from"./chunk-OSRY5VT3.min.js";var Te=pe((re,me)=>{(function(w,N){typeof re=="object"&&typeof me=="object"?me.exports=N():typeof define=="function"&&define.amd?define([],N):typeof re=="object"?re.layoutBase=N():w.layoutBase=N()})(re,function(){return(function(m){var w={};function N(u){if(w[u])return w[u].exports;var o=w[u]={i:u,l:!1,exports:{}};return m[u].call(o.exports,o,o.exports,N),o.l=!0,o.exports}return N.m=m,N.c=w,N.i=function(u){return u},N.d=function(u,o,n){N.o(u,o)||Object.defineProperty(u,o,{configurable:!1,enumerable:!0,get:n})},N.n=function(u){var o=u&&u.__esModule?function(){return u.default}:function(){return u};return N.d(o,"a",o),o},N.o=function(u,o){return Object.prototype.hasOwnProperty.call(u,o)},N.p="",N(N.s=28)})([(function(m,w,N){"use strict";function u(){}u.QUALITY=1,u.DEFAULT_CREATE_BENDS_AS_NEEDED=!1,u.DEFAULT_INCREMENTAL=!1,u.DEFAULT_ANIMATION_ON_LAYOUT=!0,u.DEFAULT_ANIMATION_DURING_LAYOUT=!1,u.DEFAULT_ANIMATION_PERIOD=50,u.DEFAULT_UNIFORM_LEAF_NODE_SIZES=!1,u.DEFAULT_GRAPH_MARGIN=15,u.NODE_DIMENSIONS_INCLUDE_LABELS=!1,u.SIMPLE_NODE_SIZE=40,u.SIMPLE_NODE_HALF_SIZE=u.SIMPLE_NODE_SIZE/2,u.EMPTY_COMPOUND_NODE_SIZE=40,u.MIN_EDGE_LENGTH=1,u.WORLD_BOUNDARY=1e6,u.INITIAL_WORLD_BOUNDARY=u.WORLD_BOUNDARY/1e3,u.WORLD_CENTER_X=1200,u.WORLD_CENTER_Y=900,m.exports=u}),(function(m,w,N){"use strict";var u=N(2),o=N(8),n=N(9);function e(c,t,g){u.call(this,g),this.isOverlapingSourceAndTarget=!1,this.vGraphObject=g,this.bendpoints=[],this.source=c,this.target=t}e.prototype=Object.create(u.prototype);for(var a in u)e[a]=u[a];e.prototype.getSource=function(){return this.source},e.prototype.getTarget=function(){return this.target},e.prototype.isInterGraph=function(){return this.isInterGraph},e.prototype.getLength=function(){return this.length},e.prototype.isOverlapingSourceAndTarget=function(){return this.isOverlapingSourceAndTarget},e.prototype.getBendpoints=function(){return this.bendpoints},e.prototype.getLca=function(){return this.lca},e.prototype.getSourceInLca=function(){return this.sourceInLca},e.prototype.getTargetInLca=function(){return this.targetInLca},e.prototype.getOtherEnd=function(c){if(this.source===c)return this.target;if(this.target===c)return this.source;throw"Node is not incident with this edge"},e.prototype.getOtherEndInGraph=function(c,t){for(var g=this.getOtherEnd(c),i=t.getGraphManager().getRoot();;){if(g.getOwner()==t)return g;if(g.getOwner()==i)break;g=g.getOwner().getParent()}return null},e.prototype.updateLength=function(){var c=new Array(4);this.isOverlapingSourceAndTarget=o.getIntersection(this.target.getRect(),this.source.getRect(),c),this.isOverlapingSourceAndTarget||(this.lengthX=c[0]-c[2],this.lengthY=c[1]-c[3],Math.abs(this.lengthX)<1&&(this.lengthX=n.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=n.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY))},e.prototype.updateLengthSimple=function(){this.lengthX=this.target.getCenterX()-this.source.getCenterX(),this.lengthY=this.target.getCenterY()-this.source.getCenterY(),Math.abs(this.lengthX)<1&&(this.lengthX=n.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=n.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY)},m.exports=e}),(function(m,w,N){"use strict";function u(o){this.vGraphObject=o}m.exports=u}),(function(m,w,N){"use strict";var u=N(2),o=N(10),n=N(13),e=N(0),a=N(16),c=N(5);function t(i,r,h,f){h==null&&f==null&&(f=r),u.call(this,f),i.graphManager!=null&&(i=i.graphManager),this.estimatedSize=o.MIN_VALUE,this.inclusionTreeDepth=o.MAX_VALUE,this.vGraphObject=f,this.edges=[],this.graphManager=i,h!=null&&r!=null?this.rect=new n(r.x,r.y,h.width,h.height):this.rect=new n}t.prototype=Object.create(u.prototype);for(var g in u)t[g]=u[g];t.prototype.getEdges=function(){return this.edges},t.prototype.getChild=function(){return this.child},t.prototype.getOwner=function(){return this.owner},t.prototype.getWidth=function(){return this.rect.width},t.prototype.setWidth=function(i){this.rect.width=i},t.prototype.getHeight=function(){return this.rect.height},t.prototype.setHeight=function(i){this.rect.height=i},t.prototype.getCenterX=function(){return this.rect.x+this.rect.width/2},t.prototype.getCenterY=function(){return this.rect.y+this.rect.height/2},t.prototype.getCenter=function(){return new c(this.rect.x+this.rect.width/2,this.rect.y+this.rect.height/2)},t.prototype.getLocation=function(){return new c(this.rect.x,this.rect.y)},t.prototype.getRect=function(){return this.rect},t.prototype.getDiagonal=function(){return Math.sqrt(this.rect.width*this.rect.width+this.rect.height*this.rect.height)},t.prototype.getHalfTheDiagonal=function(){return Math.sqrt(this.rect.height*this.rect.height+this.rect.width*this.rect.width)/2},t.prototype.setRect=function(i,r){this.rect.x=i.x,this.rect.y=i.y,this.rect.width=r.width,this.rect.height=r.height},t.prototype.setCenter=function(i,r){this.rect.x=i-this.rect.width/2,this.rect.y=r-this.rect.height/2},t.prototype.setLocation=function(i,r){this.rect.x=i,this.rect.y=r},t.prototype.moveBy=function(i,r){this.rect.x+=i,this.rect.y+=r},t.prototype.getEdgeListToNode=function(i){var r=[],h,f=this;return f.edges.forEach(function(l){if(l.target==i){if(l.source!=f)throw"Incorrect edge source!";r.push(l)}}),r},t.prototype.getEdgesBetween=function(i){var r=[],h,f=this;return f.edges.forEach(function(l){if(!(l.source==f||l.target==f))throw"Incorrect edge source and/or target";(l.target==i||l.source==i)&&r.push(l)}),r},t.prototype.getNeighborsList=function(){var i=new Set,r=this;return r.edges.forEach(function(h){if(h.source==r)i.add(h.target);else{if(h.target!=r)throw"Incorrect incidency!";i.add(h.source)}}),i},t.prototype.withChildren=function(){var i=new Set,r,h;if(i.add(this),this.child!=null)for(var f=this.child.getNodes(),l=0;lr?(this.rect.x-=(this.labelWidth-r)/2,this.setWidth(this.labelWidth)):this.labelPosHorizontal=="right"&&this.setWidth(r+this.labelWidth)),this.labelHeight&&(this.labelPosVertical=="top"?(this.rect.y-=this.labelHeight,this.setHeight(h+this.labelHeight)):this.labelPosVertical=="center"&&this.labelHeight>h?(this.rect.y-=(this.labelHeight-h)/2,this.setHeight(this.labelHeight)):this.labelPosVertical=="bottom"&&this.setHeight(h+this.labelHeight))}}},t.prototype.getInclusionTreeDepth=function(){if(this.inclusionTreeDepth==o.MAX_VALUE)throw"assert failed";return this.inclusionTreeDepth},t.prototype.transform=function(i){var r=this.rect.x;r>e.WORLD_BOUNDARY?r=e.WORLD_BOUNDARY:r<-e.WORLD_BOUNDARY&&(r=-e.WORLD_BOUNDARY);var h=this.rect.y;h>e.WORLD_BOUNDARY?h=e.WORLD_BOUNDARY:h<-e.WORLD_BOUNDARY&&(h=-e.WORLD_BOUNDARY);var f=new c(r,h),l=i.inverseTransformPoint(f);this.setLocation(l.x,l.y)},t.prototype.getLeft=function(){return this.rect.x},t.prototype.getRight=function(){return this.rect.x+this.rect.width},t.prototype.getTop=function(){return this.rect.y},t.prototype.getBottom=function(){return this.rect.y+this.rect.height},t.prototype.getParent=function(){return this.owner==null?null:this.owner.getParent()},m.exports=t}),(function(m,w,N){"use strict";var u=N(0);function o(){}for(var n in u)o[n]=u[n];o.MAX_ITERATIONS=2500,o.DEFAULT_EDGE_LENGTH=50,o.DEFAULT_SPRING_STRENGTH=.45,o.DEFAULT_REPULSION_STRENGTH=4500,o.DEFAULT_GRAVITY_STRENGTH=.4,o.DEFAULT_COMPOUND_GRAVITY_STRENGTH=1,o.DEFAULT_GRAVITY_RANGE_FACTOR=3.8,o.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=1.5,o.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION=!0,o.DEFAULT_USE_SMART_REPULSION_RANGE_CALCULATION=!0,o.DEFAULT_COOLING_FACTOR_INCREMENTAL=.3,o.COOLING_ADAPTATION_FACTOR=.33,o.ADAPTATION_LOWER_NODE_LIMIT=1e3,o.ADAPTATION_UPPER_NODE_LIMIT=5e3,o.MAX_NODE_DISPLACEMENT_INCREMENTAL=100,o.MAX_NODE_DISPLACEMENT=o.MAX_NODE_DISPLACEMENT_INCREMENTAL*3,o.MIN_REPULSION_DIST=o.DEFAULT_EDGE_LENGTH/10,o.CONVERGENCE_CHECK_PERIOD=100,o.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=.1,o.MIN_EDGE_LENGTH=1,o.GRID_CALCULATION_CHECK_PERIOD=10,m.exports=o}),(function(m,w,N){"use strict";function u(o,n){o==null&&n==null?(this.x=0,this.y=0):(this.x=o,this.y=n)}u.prototype.getX=function(){return this.x},u.prototype.getY=function(){return this.y},u.prototype.setX=function(o){this.x=o},u.prototype.setY=function(o){this.y=o},u.prototype.getDifference=function(o){return new DimensionD(this.x-o.x,this.y-o.y)},u.prototype.getCopy=function(){return new u(this.x,this.y)},u.prototype.translate=function(o){return this.x+=o.width,this.y+=o.height,this},m.exports=u}),(function(m,w,N){"use strict";var u=N(2),o=N(10),n=N(0),e=N(7),a=N(3),c=N(1),t=N(13),g=N(12),i=N(11);function r(f,l,L){u.call(this,L),this.estimatedSize=o.MIN_VALUE,this.margin=n.DEFAULT_GRAPH_MARGIN,this.edges=[],this.nodes=[],this.isConnected=!1,this.parent=f,l!=null&&l instanceof e?this.graphManager=l:l!=null&&l instanceof Layout&&(this.graphManager=l.graphManager)}r.prototype=Object.create(u.prototype);for(var h in u)r[h]=u[h];r.prototype.getNodes=function(){return this.nodes},r.prototype.getEdges=function(){return this.edges},r.prototype.getGraphManager=function(){return this.graphManager},r.prototype.getParent=function(){return this.parent},r.prototype.getLeft=function(){return this.left},r.prototype.getRight=function(){return this.right},r.prototype.getTop=function(){return this.top},r.prototype.getBottom=function(){return this.bottom},r.prototype.isConnected=function(){return this.isConnected},r.prototype.add=function(f,l,L){if(l==null&&L==null){var y=f;if(this.graphManager==null)throw"Graph has no graph mgr!";if(this.getNodes().indexOf(y)>-1)throw"Node already in graph!";return y.owner=this,this.getNodes().push(y),y}else{var p=f;if(!(this.getNodes().indexOf(l)>-1&&this.getNodes().indexOf(L)>-1))throw"Source or target not in graph!";if(!(l.owner==L.owner&&l.owner==this))throw"Both owners must be this graph!";return l.owner!=L.owner?null:(p.source=l,p.target=L,p.isInterGraph=!1,this.getEdges().push(p),l.edges.push(p),L!=l&&L.edges.push(p),p)}},r.prototype.remove=function(f){var l=f;if(f instanceof a){if(l==null)throw"Node is null!";if(!(l.owner!=null&&l.owner==this))throw"Owner graph is invalid!";if(this.graphManager==null)throw"Owner graph manager is invalid!";for(var L=l.edges.slice(),y,p=L.length,C=0;C-1&&S>-1))throw"Source and/or target doesn't know this edge!";y.source.edges.splice(A,1),y.target!=y.source&&y.target.edges.splice(S,1);var R=y.source.owner.getEdges().indexOf(y);if(R==-1)throw"Not in owner's edge list!";y.source.owner.getEdges().splice(R,1)}},r.prototype.updateLeftTop=function(){for(var f=o.MAX_VALUE,l=o.MAX_VALUE,L,y,p,C=this.getNodes(),R=C.length,A=0;AL&&(f=L),l>y&&(l=y)}return f==o.MAX_VALUE?null:(C[0].getParent().paddingLeft!=null?p=C[0].getParent().paddingLeft:p=this.margin,this.left=l-p,this.top=f-p,new g(this.left,this.top))},r.prototype.updateBounds=function(f){for(var l=o.MAX_VALUE,L=-o.MAX_VALUE,y=o.MAX_VALUE,p=-o.MAX_VALUE,C,R,A,S,B,Y=this.nodes,tt=Y.length,x=0;xC&&(l=C),LA&&(y=A),pC&&(l=C),LA&&(y=A),p=this.nodes.length){var tt=0;L.forEach(function(x){x.owner==f&&tt++}),tt==this.nodes.length&&(this.isConnected=!0)}},m.exports=r}),(function(m,w,N){"use strict";var u,o=N(1);function n(e){u=N(6),this.layout=e,this.graphs=[],this.edges=[]}n.prototype.addRoot=function(){var e=this.layout.newGraph(),a=this.layout.newNode(null),c=this.add(e,a);return this.setRootGraph(c),this.rootGraph},n.prototype.add=function(e,a,c,t,g){if(c==null&&t==null&&g==null){if(e==null)throw"Graph is null!";if(a==null)throw"Parent node is null!";if(this.graphs.indexOf(e)>-1)throw"Graph already in this graph mgr!";if(this.graphs.push(e),e.parent!=null)throw"Already has a parent!";if(a.child!=null)throw"Already has a child!";return e.parent=a,a.child=e,e}else{g=c,t=a,c=e;var i=t.getOwner(),r=g.getOwner();if(!(i!=null&&i.getGraphManager()==this))throw"Source not in this graph mgr!";if(!(r!=null&&r.getGraphManager()==this))throw"Target not in this graph mgr!";if(i==r)return c.isInterGraph=!1,i.add(c,t,g);if(c.isInterGraph=!0,c.source=t,c.target=g,this.edges.indexOf(c)>-1)throw"Edge already in inter-graph edge list!";if(this.edges.push(c),!(c.source!=null&&c.target!=null))throw"Edge source and/or target is null!";if(!(c.source.edges.indexOf(c)==-1&&c.target.edges.indexOf(c)==-1))throw"Edge already in source and/or target incidency list!";return c.source.edges.push(c),c.target.edges.push(c),c}},n.prototype.remove=function(e){if(e instanceof u){var a=e;if(a.getGraphManager()!=this)throw"Graph not in this graph mgr";if(!(a==this.rootGraph||a.parent!=null&&a.parent.graphManager==this))throw"Invalid parent node!";var c=[];c=c.concat(a.getEdges());for(var t,g=c.length,i=0;i=e.getRight()?a[0]+=Math.min(e.getX()-n.getX(),n.getRight()-e.getRight()):e.getX()<=n.getX()&&e.getRight()>=n.getRight()&&(a[0]+=Math.min(n.getX()-e.getX(),e.getRight()-n.getRight())),n.getY()<=e.getY()&&n.getBottom()>=e.getBottom()?a[1]+=Math.min(e.getY()-n.getY(),n.getBottom()-e.getBottom()):e.getY()<=n.getY()&&e.getBottom()>=n.getBottom()&&(a[1]+=Math.min(n.getY()-e.getY(),e.getBottom()-n.getBottom()));var g=Math.abs((e.getCenterY()-n.getCenterY())/(e.getCenterX()-n.getCenterX()));e.getCenterY()===n.getCenterY()&&e.getCenterX()===n.getCenterX()&&(g=1);var i=g*a[0],r=a[1]/g;a[0]i)return a[0]=c,a[1]=h,a[2]=g,a[3]=Y,!1;if(tg)return a[0]=r,a[1]=t,a[2]=S,a[3]=i,!1;if(cg?(a[0]=l,a[1]=L,s=!0):(a[0]=f,a[1]=h,s=!0):v===d&&(c>g?(a[0]=r,a[1]=h,s=!0):(a[0]=y,a[1]=L,s=!0)),-T===d?g>c?(a[2]=B,a[3]=Y,E=!0):(a[2]=S,a[3]=A,E=!0):T===d&&(g>c?(a[2]=R,a[3]=A,E=!0):(a[2]=tt,a[3]=Y,E=!0)),s&&E)return!1;if(c>g?t>i?(D=this.getCardinalDirection(v,d,4),O=this.getCardinalDirection(T,d,2)):(D=this.getCardinalDirection(-v,d,3),O=this.getCardinalDirection(-T,d,1)):t>i?(D=this.getCardinalDirection(-v,d,1),O=this.getCardinalDirection(-T,d,3)):(D=this.getCardinalDirection(v,d,2),O=this.getCardinalDirection(T,d,4)),!s)switch(D){case 1:F=h,P=c+-C/d,a[0]=P,a[1]=F;break;case 2:P=y,F=t+p*d,a[0]=P,a[1]=F;break;case 3:F=L,P=c+C/d,a[0]=P,a[1]=F;break;case 4:P=l,F=t+-p*d,a[0]=P,a[1]=F;break}if(!E)switch(O){case 1:Z=A,I=g+-k/d,a[2]=I,a[3]=Z;break;case 2:I=tt,Z=i+x*d,a[2]=I,a[3]=Z;break;case 3:Z=Y,I=g+k/d,a[2]=I,a[3]=Z;break;case 4:I=B,Z=i+-x*d,a[2]=I,a[3]=Z;break}}return!1},o.getCardinalDirection=function(n,e,a){return n>e?a:1+a%4},o.getIntersection=function(n,e,a,c){if(c==null)return this.getIntersection2(n,e,a);var t=n.x,g=n.y,i=e.x,r=e.y,h=a.x,f=a.y,l=c.x,L=c.y,y=void 0,p=void 0,C=void 0,R=void 0,A=void 0,S=void 0,B=void 0,Y=void 0,tt=void 0;return C=r-g,A=t-i,B=i*g-t*r,R=L-f,S=h-l,Y=l*f-h*L,tt=C*S-R*A,tt===0?null:(y=(A*Y-S*B)/tt,p=(R*B-C*Y)/tt,new u(y,p))},o.angleOfVector=function(n,e,a,c){var t=void 0;return n!==a?(t=Math.atan((c-e)/(a-n)),a=0){var L=(-h+Math.sqrt(h*h-4*r*f))/(2*r),y=(-h-Math.sqrt(h*h-4*r*f))/(2*r),p=null;return L>=0&&L<=1?[L]:y>=0&&y<=1?[y]:p}else return null},o.HALF_PI=.5*Math.PI,o.ONE_AND_HALF_PI=1.5*Math.PI,o.TWO_PI=2*Math.PI,o.THREE_PI=3*Math.PI,m.exports=o}),(function(m,w,N){"use strict";function u(){}u.sign=function(o){return o>0?1:o<0?-1:0},u.floor=function(o){return o<0?Math.ceil(o):Math.floor(o)},u.ceil=function(o){return o<0?Math.floor(o):Math.ceil(o)},m.exports=u}),(function(m,w,N){"use strict";function u(){}u.MAX_VALUE=2147483647,u.MIN_VALUE=-2147483648,m.exports=u}),(function(m,w,N){"use strict";var u=(function(){function t(g,i){for(var r=0;r"u"?"undefined":u(n);return n==null||e!="object"&&e!="function"},m.exports=o}),(function(m,w,N){"use strict";function u(h){if(Array.isArray(h)){for(var f=0,l=Array(h.length);f0&&f;){for(C.push(A[0]);C.length>0&&f;){var S=C[0];C.splice(0,1),p.add(S);for(var B=S.getEdges(),y=0;y-1&&A.splice(k,1)}p=new Set,R=new Map}}return h},r.prototype.createDummyNodesForBendpoints=function(h){for(var f=[],l=h.source,L=this.graphManager.calcLowestCommonAncestor(h.source,h.target),y=0;y0){for(var L=this.edgeToDummyNodes.get(l),y=0;y=0&&f.splice(Y,1);var tt=R.getNeighborsList();tt.forEach(function(s){if(l.indexOf(s)<0){var E=L.get(s),v=E-1;v==1&&S.push(s),L.set(s,v)}})}l=l.concat(S),(f.length==1||f.length==2)&&(y=!0,p=f[0])}return p},r.prototype.setGraphManager=function(h){this.graphManager=h},m.exports=r}),(function(m,w,N){"use strict";function u(){}u.seed=1,u.x=0,u.nextDouble=function(){return u.x=Math.sin(u.seed++)*1e4,u.x-Math.floor(u.x)},m.exports=u}),(function(m,w,N){"use strict";var u=N(5);function o(n,e){this.lworldOrgX=0,this.lworldOrgY=0,this.ldeviceOrgX=0,this.ldeviceOrgY=0,this.lworldExtX=1,this.lworldExtY=1,this.ldeviceExtX=1,this.ldeviceExtY=1}o.prototype.getWorldOrgX=function(){return this.lworldOrgX},o.prototype.setWorldOrgX=function(n){this.lworldOrgX=n},o.prototype.getWorldOrgY=function(){return this.lworldOrgY},o.prototype.setWorldOrgY=function(n){this.lworldOrgY=n},o.prototype.getWorldExtX=function(){return this.lworldExtX},o.prototype.setWorldExtX=function(n){this.lworldExtX=n},o.prototype.getWorldExtY=function(){return this.lworldExtY},o.prototype.setWorldExtY=function(n){this.lworldExtY=n},o.prototype.getDeviceOrgX=function(){return this.ldeviceOrgX},o.prototype.setDeviceOrgX=function(n){this.ldeviceOrgX=n},o.prototype.getDeviceOrgY=function(){return this.ldeviceOrgY},o.prototype.setDeviceOrgY=function(n){this.ldeviceOrgY=n},o.prototype.getDeviceExtX=function(){return this.ldeviceExtX},o.prototype.setDeviceExtX=function(n){this.ldeviceExtX=n},o.prototype.getDeviceExtY=function(){return this.ldeviceExtY},o.prototype.setDeviceExtY=function(n){this.ldeviceExtY=n},o.prototype.transformX=function(n){var e=0,a=this.lworldExtX;return a!=0&&(e=this.ldeviceOrgX+(n-this.lworldOrgX)*this.ldeviceExtX/a),e},o.prototype.transformY=function(n){var e=0,a=this.lworldExtY;return a!=0&&(e=this.ldeviceOrgY+(n-this.lworldOrgY)*this.ldeviceExtY/a),e},o.prototype.inverseTransformX=function(n){var e=0,a=this.ldeviceExtX;return a!=0&&(e=this.lworldOrgX+(n-this.ldeviceOrgX)*this.lworldExtX/a),e},o.prototype.inverseTransformY=function(n){var e=0,a=this.ldeviceExtY;return a!=0&&(e=this.lworldOrgY+(n-this.ldeviceOrgY)*this.lworldExtY/a),e},o.prototype.inverseTransformPoint=function(n){var e=new u(this.inverseTransformX(n.x),this.inverseTransformY(n.y));return e},m.exports=o}),(function(m,w,N){"use strict";function u(i){if(Array.isArray(i)){for(var r=0,h=Array(i.length);rn.ADAPTATION_LOWER_NODE_LIMIT&&(this.coolingFactor=Math.max(this.coolingFactor*n.COOLING_ADAPTATION_FACTOR,this.coolingFactor-(i-n.ADAPTATION_LOWER_NODE_LIMIT)/(n.ADAPTATION_UPPER_NODE_LIMIT-n.ADAPTATION_LOWER_NODE_LIMIT)*this.coolingFactor*(1-n.COOLING_ADAPTATION_FACTOR))),this.maxNodeDisplacement=n.MAX_NODE_DISPLACEMENT_INCREMENTAL):(i>n.ADAPTATION_LOWER_NODE_LIMIT?this.coolingFactor=Math.max(n.COOLING_ADAPTATION_FACTOR,1-(i-n.ADAPTATION_LOWER_NODE_LIMIT)/(n.ADAPTATION_UPPER_NODE_LIMIT-n.ADAPTATION_LOWER_NODE_LIMIT)*(1-n.COOLING_ADAPTATION_FACTOR)):this.coolingFactor=1,this.initialCoolingFactor=this.coolingFactor,this.maxNodeDisplacement=n.MAX_NODE_DISPLACEMENT),this.maxIterations=Math.max(this.getAllNodes().length*5,this.maxIterations),this.displacementThresholdPerNode=3*n.DEFAULT_EDGE_LENGTH/100,this.totalDisplacementThreshold=this.displacementThresholdPerNode*this.getAllNodes().length,this.repulsionRange=this.calcRepulsionRange()},t.prototype.calcSpringForces=function(){for(var i=this.getAllEdges(),r,h=0;h0&&arguments[0]!==void 0?arguments[0]:!0,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,h,f,l,L,y=this.getAllNodes(),p;if(this.useFRGridVariant)for(this.totalIterations%n.GRID_CALCULATION_CHECK_PERIOD==1&&i&&this.updateGrid(),p=new Set,h=0;hC||p>C)&&(i.gravitationForceX=-this.gravityConstant*l,i.gravitationForceY=-this.gravityConstant*L)):(C=r.getEstimatedSize()*this.compoundGravityRangeFactor,(y>C||p>C)&&(i.gravitationForceX=-this.gravityConstant*l*this.compoundGravityConstant,i.gravitationForceY=-this.gravityConstant*L*this.compoundGravityConstant))},t.prototype.isConverged=function(){var i,r=!1;return this.totalIterations>this.maxIterations/3&&(r=Math.abs(this.totalDisplacement-this.oldTotalDisplacement)<2),i=this.totalDisplacement=y.length||C>=y[0].length)){for(var R=0;Rt}}]),a})();m.exports=e}),(function(m,w,N){"use strict";function u(){}u.svd=function(o){this.U=null,this.V=null,this.s=null,this.m=0,this.n=0,this.m=o.length,this.n=o[0].length;var n=Math.min(this.m,this.n);this.s=(function(Dt){for(var Nt=[];Dt-- >0;)Nt.push(0);return Nt})(Math.min(this.m+1,this.n)),this.U=(function(Dt){var Nt=function $t(Rt){if(Rt.length==0)return 0;for(var Xt=[],zt=0;zt0;)Nt.push(0);return Nt})(this.n),a=(function(Dt){for(var Nt=[];Dt-- >0;)Nt.push(0);return Nt})(this.m),c=!0,t=!0,g=Math.min(this.m-1,this.n),i=Math.max(0,Math.min(this.n-2,this.m)),r=0;r=0;d--)if(this.s[d]!==0){for(var D=d+1;D=0;b--){if((function(Dt,Nt){return Dt&&Nt})(b0;){var Q=void 0,Ut=void 0;for(Q=E-2;Q>=-1&&Q!==-1;Q--)if(Math.abs(e[Q])<=St+Lt*(Math.abs(this.s[Q])+Math.abs(this.s[Q+1]))){e[Q]=0;break}if(Q===E-2)Ut=4;else{var wt=void 0;for(wt=E-1;wt>=Q&&wt!==Q;wt--){var nt=(wt!==E?Math.abs(e[wt]):0)+(wt!==Q+1?Math.abs(e[wt-1]):0);if(Math.abs(this.s[wt])<=St+Lt*nt){this.s[wt]=0;break}}wt===Q?Ut=3:wt===E-1?Ut=1:(Ut=2,Q=wt)}switch(Q++,Ut){case 1:{var et=e[E-2];e[E-2]=0;for(var pt=E-2;pt>=Q;pt--){var Et=u.hypot(this.s[pt],et),Ct=this.s[pt]/Et,mt=et/Et;if(this.s[pt]=Et,pt!==Q&&(et=-mt*e[pt-1],e[pt-1]=Ct*e[pt-1]),t)for(var Tt=0;Tt=this.s[Q+1]);){var lt=this.s[Q];if(this.s[Q]=this.s[Q+1],this.s[Q+1]=lt,t&&QMath.abs(n)?(e=n/o,e=Math.abs(o)*Math.sqrt(1+e*e)):n!=0?(e=o/n,e=Math.abs(n)*Math.sqrt(1+e*e)):e=0,e},m.exports=u}),(function(m,w,N){"use strict";var u=(function(){function e(a,c){for(var t=0;t2&&arguments[2]!==void 0?arguments[2]:1,g=arguments.length>3&&arguments[3]!==void 0?arguments[3]:-1,i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:-1;o(this,e),this.sequence1=a,this.sequence2=c,this.match_score=t,this.mismatch_penalty=g,this.gap_penalty=i,this.iMax=a.length+1,this.jMax=c.length+1,this.grid=new Array(this.iMax);for(var r=0;r=0;a--){var c=this.listeners[a];c.event===n&&c.callback===e&&this.listeners.splice(a,1)}},o.emit=function(n,e){for(var a=0;a{(function(w,N){typeof ie=="object"&&typeof Ne=="object"?Ne.exports=N(Te()):typeof define=="function"&&define.amd?define(["layout-base"],N):typeof ie=="object"?ie.coseBase=N(Te()):w.coseBase=N(w.layoutBase)})(ie,function(m){return(()=>{"use strict";var w={45:((n,e,a)=>{var c={};c.layoutBase=a(551),c.CoSEConstants=a(806),c.CoSEEdge=a(767),c.CoSEGraph=a(880),c.CoSEGraphManager=a(578),c.CoSELayout=a(765),c.CoSENode=a(991),c.ConstraintHandler=a(902),n.exports=c}),806:((n,e,a)=>{var c=a(551).FDLayoutConstants;function t(){}for(var g in c)t[g]=c[g];t.DEFAULT_USE_MULTI_LEVEL_SCALING=!1,t.DEFAULT_RADIAL_SEPARATION=c.DEFAULT_EDGE_LENGTH,t.DEFAULT_COMPONENT_SEPERATION=60,t.TILE=!0,t.TILING_PADDING_VERTICAL=10,t.TILING_PADDING_HORIZONTAL=10,t.TRANSFORM_ON_CONSTRAINT_HANDLING=!0,t.ENFORCE_CONSTRAINTS=!0,t.APPLY_LAYOUT=!0,t.RELAX_MOVEMENT_ON_CONSTRAINTS=!0,t.TREE_REDUCTION_ON_INCREMENTAL=!0,t.PURE_INCREMENTAL=t.DEFAULT_INCREMENTAL,n.exports=t}),767:((n,e,a)=>{var c=a(551).FDLayoutEdge;function t(i,r,h){c.call(this,i,r,h)}t.prototype=Object.create(c.prototype);for(var g in c)t[g]=c[g];n.exports=t}),880:((n,e,a)=>{var c=a(551).LGraph;function t(i,r,h){c.call(this,i,r,h)}t.prototype=Object.create(c.prototype);for(var g in c)t[g]=c[g];n.exports=t}),578:((n,e,a)=>{var c=a(551).LGraphManager;function t(i){c.call(this,i)}t.prototype=Object.create(c.prototype);for(var g in c)t[g]=c[g];n.exports=t}),765:((n,e,a)=>{var c=a(551).FDLayout,t=a(578),g=a(880),i=a(991),r=a(767),h=a(806),f=a(902),l=a(551).FDLayoutConstants,L=a(551).LayoutConstants,y=a(551).Point,p=a(551).PointD,C=a(551).DimensionD,R=a(551).Layout,A=a(551).Integer,S=a(551).IGeometry,B=a(551).LGraph,Y=a(551).Transform,tt=a(551).LinkedList;function x(){c.call(this),this.toBeTiled={},this.constraints={}}x.prototype=Object.create(c.prototype);for(var k in c)x[k]=c[k];x.prototype.newGraphManager=function(){var s=new t(this);return this.graphManager=s,s},x.prototype.newGraph=function(s){return new g(null,this.graphManager,s)},x.prototype.newNode=function(s){return new i(this.graphManager,s)},x.prototype.newEdge=function(s){return new r(null,null,s)},x.prototype.initParameters=function(){c.prototype.initParameters.call(this,arguments),this.isSubLayout||(h.DEFAULT_EDGE_LENGTH<10?this.idealEdgeLength=10:this.idealEdgeLength=h.DEFAULT_EDGE_LENGTH,this.useSmartIdealEdgeLengthCalculation=h.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION,this.gravityConstant=l.DEFAULT_GRAVITY_STRENGTH,this.compoundGravityConstant=l.DEFAULT_COMPOUND_GRAVITY_STRENGTH,this.gravityRangeFactor=l.DEFAULT_GRAVITY_RANGE_FACTOR,this.compoundGravityRangeFactor=l.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR,this.prunedNodesAll=[],this.growTreeIterations=0,this.afterGrowthIterations=0,this.isTreeGrowing=!1,this.isGrowthFinished=!1)},x.prototype.initSpringEmbedder=function(){c.prototype.initSpringEmbedder.call(this),this.coolingCycle=0,this.maxCoolingCycle=this.maxIterations/l.CONVERGENCE_CHECK_PERIOD,this.finalTemperature=.04,this.coolingAdjuster=1},x.prototype.layout=function(){var s=L.DEFAULT_CREATE_BENDS_AS_NEEDED;return s&&(this.createBendpoints(),this.graphManager.resetAllEdges()),this.level=0,this.classicLayout()},x.prototype.classicLayout=function(){if(this.nodesWithGravity=this.calculateNodesToApplyGravitationTo(),this.graphManager.setAllNodesToApplyGravitation(this.nodesWithGravity),this.calcNoOfChildrenForAllNodes(),this.graphManager.calcLowestCommonAncestors(),this.graphManager.calcInclusionTreeDepths(),this.graphManager.getRoot().calcEstimatedSize(),this.calcIdealEdgeLengths(),this.incremental){if(h.TREE_REDUCTION_ON_INCREMENTAL){this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var E=new Set(this.getAllNodes()),v=this.nodesWithGravity.filter(function(D){return E.has(D)});this.graphManager.setAllNodesToApplyGravitation(v)}}else{var s=this.getFlatForest();if(s.length>0)this.positionNodesRadially(s);else{this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var E=new Set(this.getAllNodes()),v=this.nodesWithGravity.filter(function(T){return E.has(T)});this.graphManager.setAllNodesToApplyGravitation(v),this.positionNodesRandomly()}}return Object.keys(this.constraints).length>0&&(f.handleConstraints(this),this.initConstraintVariables()),this.initSpringEmbedder(),h.APPLY_LAYOUT&&this.runSpringEmbedder(),!0},x.prototype.tick=function(){if(this.totalIterations++,this.totalIterations===this.maxIterations&&!this.isTreeGrowing&&!this.isGrowthFinished)if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;if(this.totalIterations%l.CONVERGENCE_CHECK_PERIOD==0&&!this.isTreeGrowing&&!this.isGrowthFinished){if(this.isConverged())if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;this.coolingCycle++,this.layoutQuality==0?this.coolingAdjuster=this.coolingCycle:this.layoutQuality==1&&(this.coolingAdjuster=this.coolingCycle/3),this.coolingFactor=Math.max(this.initialCoolingFactor-Math.pow(this.coolingCycle,Math.log(100*(this.initialCoolingFactor-this.finalTemperature))/Math.log(this.maxCoolingCycle))/100*this.coolingAdjuster,this.finalTemperature),this.animationPeriod=Math.ceil(this.initialAnimationPeriod*Math.sqrt(this.coolingFactor))}if(this.isTreeGrowing){if(this.growTreeIterations%10==0)if(this.prunedNodesAll.length>0){this.graphManager.updateBounds(),this.updateGrid(),this.growTree(this.prunedNodesAll),this.graphManager.resetAllNodesToApplyGravitation();var s=new Set(this.getAllNodes()),E=this.nodesWithGravity.filter(function(d){return s.has(d)});this.graphManager.setAllNodesToApplyGravitation(E),this.graphManager.updateBounds(),this.updateGrid(),h.PURE_INCREMENTAL?this.coolingFactor=l.DEFAULT_COOLING_FACTOR_INCREMENTAL/2:this.coolingFactor=l.DEFAULT_COOLING_FACTOR_INCREMENTAL}else this.isTreeGrowing=!1,this.isGrowthFinished=!0;this.growTreeIterations++}if(this.isGrowthFinished){if(this.isConverged())return!0;this.afterGrowthIterations%10==0&&(this.graphManager.updateBounds(),this.updateGrid()),h.PURE_INCREMENTAL?this.coolingFactor=l.DEFAULT_COOLING_FACTOR_INCREMENTAL/2*((100-this.afterGrowthIterations)/100):this.coolingFactor=l.DEFAULT_COOLING_FACTOR_INCREMENTAL*((100-this.afterGrowthIterations)/100),this.afterGrowthIterations++}var v=!this.isTreeGrowing&&!this.isGrowthFinished,T=this.growTreeIterations%10==1&&this.isTreeGrowing||this.afterGrowthIterations%10==1&&this.isGrowthFinished;return this.totalDisplacement=0,this.graphManager.updateBounds(),this.calcSpringForces(),this.calcRepulsionForces(v,T),this.calcGravitationalForces(),this.moveNodes(),this.animate(),!1},x.prototype.getPositionsData=function(){for(var s=this.graphManager.getAllNodes(),E={},v=0;v0&&this.updateDisplacements();for(var v=0;v0&&(T.fixedNodeWeight=D)}}if(this.constraints.relativePlacementConstraint){var O=new Map,P=new Map;if(this.dummyToNodeForVerticalAlignment=new Map,this.dummyToNodeForHorizontalAlignment=new Map,this.fixedNodesOnHorizontal=new Set,this.fixedNodesOnVertical=new Set,this.fixedNodeSet.forEach(function(M){s.fixedNodesOnHorizontal.add(M),s.fixedNodesOnVertical.add(M)}),this.constraints.alignmentConstraint){if(this.constraints.alignmentConstraint.vertical)for(var F=this.constraints.alignmentConstraint.vertical,v=0;v=2*M.length/3;J--)U=Math.floor(Math.random()*(J+1)),X=M[J],M[J]=M[U],M[U]=X;return M},this.nodesInRelativeHorizontal=[],this.nodesInRelativeVertical=[],this.nodeToRelativeConstraintMapHorizontal=new Map,this.nodeToRelativeConstraintMapVertical=new Map,this.nodeToTempPositionMapHorizontal=new Map,this.nodeToTempPositionMapVertical=new Map,this.constraints.relativePlacementConstraint.forEach(function(M){if(M.left){var U=O.has(M.left)?O.get(M.left):M.left,X=O.has(M.right)?O.get(M.right):M.right;s.nodesInRelativeHorizontal.includes(U)||(s.nodesInRelativeHorizontal.push(U),s.nodeToRelativeConstraintMapHorizontal.set(U,[]),s.dummyToNodeForVerticalAlignment.has(U)?s.nodeToTempPositionMapHorizontal.set(U,s.idToNodeMap.get(s.dummyToNodeForVerticalAlignment.get(U)[0]).getCenterX()):s.nodeToTempPositionMapHorizontal.set(U,s.idToNodeMap.get(U).getCenterX())),s.nodesInRelativeHorizontal.includes(X)||(s.nodesInRelativeHorizontal.push(X),s.nodeToRelativeConstraintMapHorizontal.set(X,[]),s.dummyToNodeForVerticalAlignment.has(X)?s.nodeToTempPositionMapHorizontal.set(X,s.idToNodeMap.get(s.dummyToNodeForVerticalAlignment.get(X)[0]).getCenterX()):s.nodeToTempPositionMapHorizontal.set(X,s.idToNodeMap.get(X).getCenterX())),s.nodeToRelativeConstraintMapHorizontal.get(U).push({right:X,gap:M.gap}),s.nodeToRelativeConstraintMapHorizontal.get(X).push({left:U,gap:M.gap})}else{var J=P.has(M.top)?P.get(M.top):M.top,st=P.has(M.bottom)?P.get(M.bottom):M.bottom;s.nodesInRelativeVertical.includes(J)||(s.nodesInRelativeVertical.push(J),s.nodeToRelativeConstraintMapVertical.set(J,[]),s.dummyToNodeForHorizontalAlignment.has(J)?s.nodeToTempPositionMapVertical.set(J,s.idToNodeMap.get(s.dummyToNodeForHorizontalAlignment.get(J)[0]).getCenterY()):s.nodeToTempPositionMapVertical.set(J,s.idToNodeMap.get(J).getCenterY())),s.nodesInRelativeVertical.includes(st)||(s.nodesInRelativeVertical.push(st),s.nodeToRelativeConstraintMapVertical.set(st,[]),s.dummyToNodeForHorizontalAlignment.has(st)?s.nodeToTempPositionMapVertical.set(st,s.idToNodeMap.get(s.dummyToNodeForHorizontalAlignment.get(st)[0]).getCenterY()):s.nodeToTempPositionMapVertical.set(st,s.idToNodeMap.get(st).getCenterY())),s.nodeToRelativeConstraintMapVertical.get(J).push({bottom:st,gap:M.gap}),s.nodeToRelativeConstraintMapVertical.get(st).push({top:J,gap:M.gap})}});else{var Z=new Map,_=new Map;this.constraints.relativePlacementConstraint.forEach(function(M){if(M.left){var U=O.has(M.left)?O.get(M.left):M.left,X=O.has(M.right)?O.get(M.right):M.right;Z.has(U)?Z.get(U).push(X):Z.set(U,[X]),Z.has(X)?Z.get(X).push(U):Z.set(X,[U])}else{var J=P.has(M.top)?P.get(M.top):M.top,st=P.has(M.bottom)?P.get(M.bottom):M.bottom;_.has(J)?_.get(J).push(st):_.set(J,[st]),_.has(st)?_.get(st).push(J):_.set(st,[J])}});var b=function(U,X){var J=[],st=[],Lt=new tt,St=new Set,Q=0;return U.forEach(function(Ut,wt){if(!St.has(wt)){J[Q]=[],st[Q]=!1;var nt=wt;for(Lt.push(nt),St.add(nt),J[Q].push(nt);Lt.length!=0;){nt=Lt.shift(),X.has(nt)&&(st[Q]=!0);var et=U.get(nt);et.forEach(function(pt){St.has(pt)||(Lt.push(pt),St.add(pt),J[Q].push(pt))})}Q++}}),{components:J,isFixed:st}},j=b(Z,s.fixedNodesOnHorizontal);this.componentsOnHorizontal=j.components,this.fixedComponentsOnHorizontal=j.isFixed;var V=b(_,s.fixedNodesOnVertical);this.componentsOnVertical=V.components,this.fixedComponentsOnVertical=V.isFixed}}},x.prototype.updateDisplacements=function(){var s=this;if(this.constraints.fixedNodeConstraint&&this.constraints.fixedNodeConstraint.forEach(function(V){var M=s.idToNodeMap.get(V.nodeId);M.displacementX=0,M.displacementY=0}),this.constraints.alignmentConstraint){if(this.constraints.alignmentConstraint.vertical)for(var E=this.constraints.alignmentConstraint.vertical,v=0;v1){var P;for(P=0;PT&&(T=Math.floor(O.y)),D=Math.floor(O.x+h.DEFAULT_COMPONENT_SEPERATION)}this.transform(new p(L.WORLD_CENTER_X-O.x/2,L.WORLD_CENTER_Y-O.y/2))},x.radialLayout=function(s,E,v){var T=Math.max(this.maxDiagonalInTree(s),h.DEFAULT_RADIAL_SEPARATION);x.branchRadialLayout(E,null,0,359,0,T);var d=B.calculateBounds(s),D=new Y;D.setDeviceOrgX(d.getMinX()),D.setDeviceOrgY(d.getMinY()),D.setWorldOrgX(v.x),D.setWorldOrgY(v.y);for(var O=0;O1;){var J=X[0];X.splice(0,1);var st=b.indexOf(J);st>=0&&b.splice(st,1),M--,j--}E!=null?U=(b.indexOf(X[0])+1)%M:U=0;for(var Lt=Math.abs(T-v)/j,St=U;V!=j;St=++St%M){var Q=b[St].getOtherEnd(s);if(Q!=E){var Ut=(v+V*Lt)%360,wt=(Ut+Lt)%360;x.branchRadialLayout(Q,s,Ut,wt,d+D,D),V++}}},x.maxDiagonalInTree=function(s){for(var E=A.MIN_VALUE,v=0;vE&&(E=d)}return E},x.prototype.calcRepulsionRange=function(){return 2*(this.level+1)*this.idealEdgeLength},x.prototype.groupZeroDegreeMembers=function(){var s=this,E={};this.memberGroups={},this.idToDummyNode={};for(var v=[],T=this.graphManager.getAllNodes(),d=0;d"u"&&(E[P]=[]),E[P]=E[P].concat(D)}Object.keys(E).forEach(function(F){if(E[F].length>1){var I="DummyCompound_"+F;s.memberGroups[I]=E[F];var Z=E[F][0].getParent(),_=new i(s.graphManager);_.id=I,_.paddingLeft=Z.paddingLeft||0,_.paddingRight=Z.paddingRight||0,_.paddingBottom=Z.paddingBottom||0,_.paddingTop=Z.paddingTop||0,s.idToDummyNode[I]=_;var b=s.getGraphManager().add(s.newGraph(),_),j=Z.getChild();j.add(_);for(var V=0;Vd?(T.rect.x-=(T.labelWidth-d)/2,T.setWidth(T.labelWidth),T.labelMarginLeft=(T.labelWidth-d)/2):T.labelPosHorizontal=="right"&&T.setWidth(d+T.labelWidth)),T.labelHeight&&(T.labelPosVertical=="top"?(T.rect.y-=T.labelHeight,T.setHeight(D+T.labelHeight),T.labelMarginTop=T.labelHeight):T.labelPosVertical=="center"&&T.labelHeight>D?(T.rect.y-=(T.labelHeight-D)/2,T.setHeight(T.labelHeight),T.labelMarginTop=(T.labelHeight-D)/2):T.labelPosVertical=="bottom"&&T.setHeight(D+T.labelHeight))}})},x.prototype.repopulateCompounds=function(){for(var s=this.compoundOrder.length-1;s>=0;s--){var E=this.compoundOrder[s],v=E.id,T=E.paddingLeft,d=E.paddingTop,D=E.labelMarginLeft,O=E.labelMarginTop;this.adjustLocations(this.tiledMemberPack[v],E.rect.x,E.rect.y,T,d,D,O)}},x.prototype.repopulateZeroDegreeMembers=function(){var s=this,E=this.tiledZeroDegreePack;Object.keys(E).forEach(function(v){var T=s.idToDummyNode[v],d=T.paddingLeft,D=T.paddingTop,O=T.labelMarginLeft,P=T.labelMarginTop;s.adjustLocations(E[v],T.rect.x,T.rect.y,d,D,O,P)})},x.prototype.getToBeTiled=function(s){var E=s.id;if(this.toBeTiled[E]!=null)return this.toBeTiled[E];var v=s.getChild();if(v==null)return this.toBeTiled[E]=!1,!1;for(var T=v.getNodes(),d=0;d0)return this.toBeTiled[E]=!1,!1;if(D.getChild()==null){this.toBeTiled[D.id]=!1;continue}if(!this.getToBeTiled(D))return this.toBeTiled[E]=!1,!1}return this.toBeTiled[E]=!0,!0},x.prototype.getNodeDegree=function(s){for(var E=s.id,v=s.getEdges(),T=0,d=0;dZ&&(Z=b.rect.height)}v+=Z+s.verticalPadding}},x.prototype.tileCompoundMembers=function(s,E){var v=this;this.tiledMemberPack=[],Object.keys(s).forEach(function(T){var d=E[T];if(v.tiledMemberPack[T]=v.tileNodes(s[T],d.paddingLeft+d.paddingRight),d.rect.width=v.tiledMemberPack[T].width,d.rect.height=v.tiledMemberPack[T].height,d.setCenter(v.tiledMemberPack[T].centerX,v.tiledMemberPack[T].centerY),d.labelMarginLeft=0,d.labelMarginTop=0,h.NODE_DIMENSIONS_INCLUDE_LABELS){var D=d.rect.width,O=d.rect.height;d.labelWidth&&(d.labelPosHorizontal=="left"?(d.rect.x-=d.labelWidth,d.setWidth(D+d.labelWidth),d.labelMarginLeft=d.labelWidth):d.labelPosHorizontal=="center"&&d.labelWidth>D?(d.rect.x-=(d.labelWidth-D)/2,d.setWidth(d.labelWidth),d.labelMarginLeft=(d.labelWidth-D)/2):d.labelPosHorizontal=="right"&&d.setWidth(D+d.labelWidth)),d.labelHeight&&(d.labelPosVertical=="top"?(d.rect.y-=d.labelHeight,d.setHeight(O+d.labelHeight),d.labelMarginTop=d.labelHeight):d.labelPosVertical=="center"&&d.labelHeight>O?(d.rect.y-=(d.labelHeight-O)/2,d.setHeight(d.labelHeight),d.labelMarginTop=(d.labelHeight-O)/2):d.labelPosVertical=="bottom"&&d.setHeight(O+d.labelHeight))}})},x.prototype.tileNodes=function(s,E){var v=this.tileNodesByFavoringDim(s,E,!0),T=this.tileNodesByFavoringDim(s,E,!1),d=this.getOrgRatio(v),D=this.getOrgRatio(T),O;return DP&&(P=V.getWidth())});var F=D/d,I=O/d,Z=Math.pow(v-T,2)+4*(F+T)*(I+v)*d,_=(T-v+Math.sqrt(Z))/(2*(F+T)),b;E?(b=Math.ceil(_),b==_&&b++):b=Math.floor(_);var j=b*(F+T)-T;return P>j&&(j=P),j+=T*2,j},x.prototype.tileNodesByFavoringDim=function(s,E,v){var T=h.TILING_PADDING_VERTICAL,d=h.TILING_PADDING_HORIZONTAL,D=h.TILING_COMPARE_BY,O={rows:[],rowWidth:[],rowHeight:[],width:0,height:E,verticalPadding:T,horizontalPadding:d,centerX:0,centerY:0};D&&(O.idealRowWidth=this.calcIdealRowWidth(s,v));var P=function(M){return M.rect.width*M.rect.height},F=function(M,U){return P(U)-P(M)};s.sort(function(V,M){var U=F;return O.idealRowWidth?(U=D,U(V.id,M.id)):U(V,M)});for(var I=0,Z=0,_=0;_0&&(O+=s.horizontalPadding),s.rowWidth[v]=O,s.width0&&(P+=s.verticalPadding);var F=0;P>s.rowHeight[v]&&(F=s.rowHeight[v],s.rowHeight[v]=P,F=s.rowHeight[v]-F),s.height+=F,s.rows[v].push(E)},x.prototype.getShortestRowIndex=function(s){for(var E=-1,v=Number.MAX_VALUE,T=0;Tv&&(E=T,v=s.rowWidth[T]);return E},x.prototype.canAddHorizontal=function(s,E,v){if(s.idealRowWidth){var T=s.rows.length-1,d=s.rowWidth[T];return d+E+s.horizontalPadding<=s.idealRowWidth}var D=this.getShortestRowIndex(s);if(D<0)return!0;var O=s.rowWidth[D];if(O+s.horizontalPadding+E<=s.width)return!0;var P=0;s.rowHeight[D]0&&(P=v+s.verticalPadding-s.rowHeight[D]);var F;s.width-O>=E+s.horizontalPadding?F=(s.height+P)/(O+E+s.horizontalPadding):F=(s.height+P)/s.width,P=v+s.verticalPadding;var I;return s.widthD&&E!=v){T.splice(-1,1),s.rows[v].push(d),s.rowWidth[E]=s.rowWidth[E]-D,s.rowWidth[v]=s.rowWidth[v]+D,s.width=s.rowWidth[instance.getLongestRowIndex(s)];for(var O=Number.MIN_VALUE,P=0;PO&&(O=T[P].height);E>0&&(O+=s.verticalPadding);var F=s.rowHeight[E]+s.rowHeight[v];s.rowHeight[E]=O,s.rowHeight[v]0)for(var j=d;j<=D;j++)b[0]+=this.grid[j][O-1].length+this.grid[j][O].length-1;if(D0)for(var j=O;j<=P;j++)b[3]+=this.grid[d-1][j].length+this.grid[d][j].length-1;for(var V=A.MAX_VALUE,M,U,X=0;X{var c=a(551).FDLayoutNode,t=a(551).IMath;function g(r,h,f,l){c.call(this,r,h,f,l)}g.prototype=Object.create(c.prototype);for(var i in c)g[i]=c[i];g.prototype.calculateDisplacement=function(){var r=this.graphManager.getLayout();this.getChild()!=null&&this.fixedNodeWeight?(this.displacementX+=r.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.fixedNodeWeight,this.displacementY+=r.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.fixedNodeWeight):(this.displacementX+=r.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.noOfChildren,this.displacementY+=r.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.noOfChildren),Math.abs(this.displacementX)>r.coolingFactor*r.maxNodeDisplacement&&(this.displacementX=r.coolingFactor*r.maxNodeDisplacement*t.sign(this.displacementX)),Math.abs(this.displacementY)>r.coolingFactor*r.maxNodeDisplacement&&(this.displacementY=r.coolingFactor*r.maxNodeDisplacement*t.sign(this.displacementY)),this.child&&this.child.getNodes().length>0&&this.propogateDisplacementToChildren(this.displacementX,this.displacementY)},g.prototype.propogateDisplacementToChildren=function(r,h){for(var f=this.getChild().getNodes(),l,L=0;L{function c(f){if(Array.isArray(f)){for(var l=0,L=Array(f.length);l0){var dt=0;it.forEach(function(lt){W=="horizontal"?(q.set(lt,y.has(lt)?p[y.get(lt)]:$.get(lt)),dt+=q.get(lt)):(q.set(lt,y.has(lt)?C[y.get(lt)]:$.get(lt)),dt+=q.get(lt))}),dt=dt/it.length,ot.forEach(function(lt){z.has(lt)||q.set(lt,dt)})}else{var at=0;ot.forEach(function(lt){W=="horizontal"?at+=y.has(lt)?p[y.get(lt)]:$.get(lt):at+=y.has(lt)?C[y.get(lt)]:$.get(lt)}),at=at/ot.length,ot.forEach(function(lt){q.set(lt,at)})}});for(var rt=function(){var it=gt.shift(),dt=H.get(it);dt.forEach(function(at){if(q.get(at.id)lt&&(lt=Xt),ztFt&&(Ft=zt)}}catch(_t){Vt=!0,Dt=_t}finally{try{!xt&&Nt.return&&Nt.return()}finally{if(Vt)throw Dt}}var ce=(dt+lt)/2-(at+Ft)/2,qt=!0,Jt=!1,Kt=void 0;try{for(var Qt=ot[Symbol.iterator](),oe;!(qt=(oe=Qt.next()).done);qt=!0){var jt=oe.value;q.set(jt,q.get(jt)+ce)}}catch(_t){Jt=!0,Kt=_t}finally{try{!qt&&Qt.return&&Qt.return()}finally{if(Jt)throw Kt}}})}return q},k=function(H){var W=0,z=0,$=0,K=0;if(H.forEach(function(ht){ht.left?p[y.get(ht.left)]-p[y.get(ht.right)]>=0?W++:z++:C[y.get(ht.top)]-C[y.get(ht.bottom)]>=0?$++:K++}),W>z&&$>K)for(var ut=0;utz)for(var ft=0;ftK)for(var q=0;q1)l.fixedNodeConstraint.forEach(function(G,H){T[H]=[G.position.x,G.position.y],d[H]=[p[y.get(G.nodeId)],C[y.get(G.nodeId)]]}),D=!0;else if(l.alignmentConstraint)(function(){var G=0;if(l.alignmentConstraint.vertical){for(var H=l.alignmentConstraint.vertical,W=function(q){var ht=new Set;H[q].forEach(function(vt){ht.add(vt)});var gt=new Set([].concat(c(ht)).filter(function(vt){return P.has(vt)})),rt=void 0;gt.size>0?rt=p[y.get(gt.values().next().value)]:rt=tt(ht).x,H[q].forEach(function(vt){T[G]=[rt,C[y.get(vt)]],d[G]=[p[y.get(vt)],C[y.get(vt)]],G++})},z=0;z0?rt=p[y.get(gt.values().next().value)]:rt=tt(ht).y,$[q].forEach(function(vt){T[G]=[p[y.get(vt)],rt],d[G]=[p[y.get(vt)],C[y.get(vt)]],G++})},ut=0;ut<$.length;ut++)K(ut);D=!0}l.relativePlacementConstraint&&(O=!0)})();else if(l.relativePlacementConstraint){for(var _=0,b=0,j=0;j_&&(_=Z[j].length,b=j);if(_0){var Ct={x:0,y:0};l.fixedNodeConstraint.forEach(function(G,H){var W={x:p[y.get(G.nodeId)],y:C[y.get(G.nodeId)]},z=G.position,$=Y(z,W);Ct.x+=$.x,Ct.y+=$.y}),Ct.x/=l.fixedNodeConstraint.length,Ct.y/=l.fixedNodeConstraint.length,p.forEach(function(G,H){p[H]+=Ct.x}),C.forEach(function(G,H){C[H]+=Ct.y}),l.fixedNodeConstraint.forEach(function(G){p[y.get(G.nodeId)]=G.position.x,C[y.get(G.nodeId)]=G.position.y})}if(l.alignmentConstraint){if(l.alignmentConstraint.vertical)for(var mt=l.alignmentConstraint.vertical,Tt=function(H){var W=new Set;mt[H].forEach(function(K){W.add(K)});var z=new Set([].concat(c(W)).filter(function(K){return P.has(K)})),$=void 0;z.size>0?$=p[y.get(z.values().next().value)]:$=tt(W).x,W.forEach(function(K){P.has(K)||(p[y.get(K)]=$)})},Ot=0;Ot0?$=C[y.get(z.values().next().value)]:$=tt(W).y,W.forEach(function(K){P.has(K)||(C[y.get(K)]=$)})},Pt=0;Pt{n.exports=m})},N={};function u(n){var e=N[n];if(e!==void 0)return e.exports;var a=N[n]={exports:{}};return w[n](a,a.exports,u),a.exports}var o=u(45);return o})()})});var Je=pe((ae,Ce)=>{(function(w,N){typeof ae=="object"&&typeof Ce=="object"?Ce.exports=N(Le()):typeof define=="function"&&define.amd?define(["cose-base"],N):typeof ae=="object"?ae.cytoscapeFcose=N(Le()):w.cytoscapeFcose=N(w.coseBase)})(ae,function(m){return(()=>{"use strict";var w={658:(n=>{n.exports=Object.assign!=null?Object.assign.bind(Object):function(e){for(var a=arguments.length,c=Array(a>1?a-1:0),t=1;t{var c=(function(){function i(r,h){var f=[],l=!0,L=!1,y=void 0;try{for(var p=r[Symbol.iterator](),C;!(l=(C=p.next()).done)&&(f.push(C.value),!(h&&f.length===h));l=!0);}catch(R){L=!0,y=R}finally{try{!l&&p.return&&p.return()}finally{if(L)throw y}}return f}return function(r,h){if(Array.isArray(r))return r;if(Symbol.iterator in Object(r))return i(r,h);throw new TypeError("Invalid attempt to destructure non-iterable instance")}})(),t=a(140).layoutBase.LinkedList,g={};g.getTopMostNodes=function(i){for(var r={},h=0;h0&&D.merge(I)});for(var O=0;O1){C=y[0],R=C.connectedEdges().length,y.forEach(function(d){d.connectedEdges().length0&&f.set("dummy"+(f.size+1),B),Y},g.relocateComponent=function(i,r,h){if(!h.fixedNodeConstraint){var f=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY,L=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY;if(h.quality=="draft"){var p=!0,C=!1,R=void 0;try{for(var A=r.nodeIndexes[Symbol.iterator](),S;!(p=(S=A.next()).done);p=!0){var B=S.value,Y=c(B,2),tt=Y[0],x=Y[1],k=h.cy.getElementById(tt);if(k){var s=k.boundingBox(),E=r.xCoords[x]-s.w/2,v=r.xCoords[x]+s.w/2,T=r.yCoords[x]-s.h/2,d=r.yCoords[x]+s.h/2;El&&(l=v),Ty&&(y=d)}}}catch(I){C=!0,R=I}finally{try{!p&&A.return&&A.return()}finally{if(C)throw R}}var D=i.x-(l+f)/2,O=i.y-(y+L)/2;r.xCoords=r.xCoords.map(function(I){return I+D}),r.yCoords=r.yCoords.map(function(I){return I+O})}else{Object.keys(r).forEach(function(I){var Z=r[I],_=Z.getRect().x,b=Z.getRect().x+Z.getRect().width,j=Z.getRect().y,V=Z.getRect().y+Z.getRect().height;_l&&(l=b),jy&&(y=V)});var P=i.x-(l+f)/2,F=i.y-(y+L)/2;Object.keys(r).forEach(function(I){var Z=r[I];Z.setCenter(Z.getCenterX()+P,Z.getCenterY()+F)})}}},g.calcBoundingBox=function(i,r,h,f){for(var l=Number.MAX_SAFE_INTEGER,L=Number.MIN_SAFE_INTEGER,y=Number.MAX_SAFE_INTEGER,p=Number.MIN_SAFE_INTEGER,C=void 0,R=void 0,A=void 0,S=void 0,B=i.descendants().not(":parent"),Y=B.length,tt=0;ttC&&(l=C),LA&&(y=A),p{var c=a(548),t=a(140).CoSELayout,g=a(140).CoSENode,i=a(140).layoutBase.PointD,r=a(140).layoutBase.DimensionD,h=a(140).layoutBase.LayoutConstants,f=a(140).layoutBase.FDLayoutConstants,l=a(140).CoSEConstants,L=function(p,C){var R=p.cy,A=p.eles,S=A.nodes(),B=A.edges(),Y=void 0,tt=void 0,x=void 0,k={};p.randomize&&(Y=C.nodeIndexes,tt=C.xCoords,x=C.yCoords);var s=function(I){return typeof I=="function"},E=function(I,Z){return s(I)?I(Z):I},v=c.calcParentsWithoutChildren(R,A),T=function F(I,Z,_,b){for(var j=Z.length,V=0;V0){var Lt=void 0;Lt=_.getGraphManager().add(_.newGraph(),X),F(Lt,U,_,b)}}},d=function(I,Z,_){for(var b=0,j=0,V=0;V<_.length;V++){var M=_[V],U=k[M.data("source")],X=k[M.data("target")];if(U&&X&&U!==X&&U.getEdgesBetween(X).length==0){var J=Z.add(I.newEdge(),U,X);J.id=M.id(),J.idealLength=E(p.idealEdgeLength,M),J.edgeElasticity=E(p.edgeElasticity,M),b+=J.idealLength,j++}}p.idealEdgeLength!=null&&(j>0?l.DEFAULT_EDGE_LENGTH=f.DEFAULT_EDGE_LENGTH=b/j:s(p.idealEdgeLength)?l.DEFAULT_EDGE_LENGTH=f.DEFAULT_EDGE_LENGTH=50:l.DEFAULT_EDGE_LENGTH=f.DEFAULT_EDGE_LENGTH=p.idealEdgeLength,l.MIN_REPULSION_DIST=f.MIN_REPULSION_DIST=f.DEFAULT_EDGE_LENGTH/10,l.DEFAULT_RADIAL_SEPARATION=f.DEFAULT_EDGE_LENGTH)},D=function(I,Z){Z.fixedNodeConstraint&&(I.constraints.fixedNodeConstraint=Z.fixedNodeConstraint),Z.alignmentConstraint&&(I.constraints.alignmentConstraint=Z.alignmentConstraint),Z.relativePlacementConstraint&&(I.constraints.relativePlacementConstraint=Z.relativePlacementConstraint)};p.nestingFactor!=null&&(l.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=f.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=p.nestingFactor),p.gravity!=null&&(l.DEFAULT_GRAVITY_STRENGTH=f.DEFAULT_GRAVITY_STRENGTH=p.gravity),p.numIter!=null&&(l.MAX_ITERATIONS=f.MAX_ITERATIONS=p.numIter),p.gravityRange!=null&&(l.DEFAULT_GRAVITY_RANGE_FACTOR=f.DEFAULT_GRAVITY_RANGE_FACTOR=p.gravityRange),p.gravityCompound!=null&&(l.DEFAULT_COMPOUND_GRAVITY_STRENGTH=f.DEFAULT_COMPOUND_GRAVITY_STRENGTH=p.gravityCompound),p.gravityRangeCompound!=null&&(l.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=f.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=p.gravityRangeCompound),p.initialEnergyOnIncremental!=null&&(l.DEFAULT_COOLING_FACTOR_INCREMENTAL=f.DEFAULT_COOLING_FACTOR_INCREMENTAL=p.initialEnergyOnIncremental),p.tilingCompareBy!=null&&(l.TILING_COMPARE_BY=p.tilingCompareBy),p.quality=="proof"?h.QUALITY=2:h.QUALITY=0,l.NODE_DIMENSIONS_INCLUDE_LABELS=f.NODE_DIMENSIONS_INCLUDE_LABELS=h.NODE_DIMENSIONS_INCLUDE_LABELS=p.nodeDimensionsIncludeLabels,l.DEFAULT_INCREMENTAL=f.DEFAULT_INCREMENTAL=h.DEFAULT_INCREMENTAL=!p.randomize,l.ANIMATE=f.ANIMATE=h.ANIMATE=p.animate,l.TILE=p.tile,l.TILING_PADDING_VERTICAL=typeof p.tilingPaddingVertical=="function"?p.tilingPaddingVertical.call():p.tilingPaddingVertical,l.TILING_PADDING_HORIZONTAL=typeof p.tilingPaddingHorizontal=="function"?p.tilingPaddingHorizontal.call():p.tilingPaddingHorizontal,l.DEFAULT_INCREMENTAL=f.DEFAULT_INCREMENTAL=h.DEFAULT_INCREMENTAL=!0,l.PURE_INCREMENTAL=!p.randomize,h.DEFAULT_UNIFORM_LEAF_NODE_SIZES=p.uniformNodeDimensions,p.step=="transformed"&&(l.TRANSFORM_ON_CONSTRAINT_HANDLING=!0,l.ENFORCE_CONSTRAINTS=!1,l.APPLY_LAYOUT=!1),p.step=="enforced"&&(l.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,l.ENFORCE_CONSTRAINTS=!0,l.APPLY_LAYOUT=!1),p.step=="cose"&&(l.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,l.ENFORCE_CONSTRAINTS=!1,l.APPLY_LAYOUT=!0),p.step=="all"&&(p.randomize?l.TRANSFORM_ON_CONSTRAINT_HANDLING=!0:l.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,l.ENFORCE_CONSTRAINTS=!0,l.APPLY_LAYOUT=!0),p.fixedNodeConstraint||p.alignmentConstraint||p.relativePlacementConstraint?l.TREE_REDUCTION_ON_INCREMENTAL=!1:l.TREE_REDUCTION_ON_INCREMENTAL=!0;var O=new t,P=O.newGraphManager();return T(P.addRoot(),c.getTopMostNodes(S),O,p),d(O,P,B),D(O,p),O.runLayout(),k};n.exports={coseLayout:L}}),212:((n,e,a)=>{var c=(function(){function p(C,R){for(var A=0;A0)if(d){var P=i.getTopMostNodes(A.eles.nodes());if(s=i.connectComponents(S,A.eles,P),s.forEach(function(nt){var et=nt.boundingBox();E.push({x:et.x1+et.w/2,y:et.y1+et.h/2})}),A.randomize&&s.forEach(function(nt){A.eles=nt,Y.push(h(A))}),A.quality=="default"||A.quality=="proof"){var F=S.collection();if(A.tile){var I=new Map,Z=[],_=[],b=0,j={nodeIndexes:I,xCoords:Z,yCoords:_},V=[];if(s.forEach(function(nt,et){nt.edges().length==0&&(nt.nodes().forEach(function(pt,Et){F.merge(nt.nodes()[Et]),pt.isParent()||(j.nodeIndexes.set(nt.nodes()[Et].id(),b++),j.xCoords.push(nt.nodes()[0].position().x),j.yCoords.push(nt.nodes()[0].position().y))}),V.push(et))}),F.length>1){var M=F.boundingBox();E.push({x:M.x1+M.w/2,y:M.y1+M.h/2}),s.push(F),Y.push(j);for(var U=V.length-1;U>=0;U--)s.splice(V[U],1),Y.splice(V[U],1),E.splice(V[U],1)}}s.forEach(function(nt,et){A.eles=nt,k.push(l(A,Y[et])),i.relocateComponent(E[et],k[et],A)})}else s.forEach(function(nt,et){i.relocateComponent(E[et],Y[et],A)});var X=new Set;if(s.length>1){var J=[],st=B.filter(function(nt){return nt.css("display")=="none"});s.forEach(function(nt,et){var pt=void 0;if(A.quality=="draft"&&(pt=Y[et].nodeIndexes),nt.nodes().not(st).length>0){var Et={};Et.edges=[],Et.nodes=[];var Ct=void 0;nt.nodes().not(st).forEach(function(mt){if(A.quality=="draft")if(!mt.isParent())Ct=pt.get(mt.id()),Et.nodes.push({x:Y[et].xCoords[Ct]-mt.boundingbox().w/2,y:Y[et].yCoords[Ct]-mt.boundingbox().h/2,width:mt.boundingbox().w,height:mt.boundingbox().h});else{var Tt=i.calcBoundingBox(mt,Y[et].xCoords,Y[et].yCoords,pt);Et.nodes.push({x:Tt.topLeftX,y:Tt.topLeftY,width:Tt.width,height:Tt.height})}else k[et][mt.id()]&&Et.nodes.push({x:k[et][mt.id()].getLeft(),y:k[et][mt.id()].getTop(),width:k[et][mt.id()].getWidth(),height:k[et][mt.id()].getHeight()})}),nt.edges().forEach(function(mt){var Tt=mt.source(),Ot=mt.target();if(Tt.css("display")!="none"&&Ot.css("display")!="none")if(A.quality=="draft"){var It=pt.get(Tt.id()),Wt=pt.get(Ot.id()),Pt=[],Yt=[];if(Tt.isParent()){var bt=i.calcBoundingBox(Tt,Y[et].xCoords,Y[et].yCoords,pt);Pt.push(bt.topLeftX+bt.width/2),Pt.push(bt.topLeftY+bt.height/2)}else Pt.push(Y[et].xCoords[It]),Pt.push(Y[et].yCoords[It]);if(Ot.isParent()){var G=i.calcBoundingBox(Ot,Y[et].xCoords,Y[et].yCoords,pt);Yt.push(G.topLeftX+G.width/2),Yt.push(G.topLeftY+G.height/2)}else Yt.push(Y[et].xCoords[Wt]),Yt.push(Y[et].yCoords[Wt]);Et.edges.push({startX:Pt[0],startY:Pt[1],endX:Yt[0],endY:Yt[1]})}else k[et][Tt.id()]&&k[et][Ot.id()]&&Et.edges.push({startX:k[et][Tt.id()].getCenterX(),startY:k[et][Tt.id()].getCenterY(),endX:k[et][Ot.id()].getCenterX(),endY:k[et][Ot.id()].getCenterY()})}),Et.nodes.length>0&&(J.push(Et),X.add(et))}});var Lt=T.packComponents(J,A.randomize).shifts;if(A.quality=="draft")Y.forEach(function(nt,et){var pt=nt.xCoords.map(function(Ct){return Ct+Lt[et].dx}),Et=nt.yCoords.map(function(Ct){return Ct+Lt[et].dy});nt.xCoords=pt,nt.yCoords=Et});else{var St=0;X.forEach(function(nt){Object.keys(k[nt]).forEach(function(et){var pt=k[nt][et];pt.setCenter(pt.getCenterX()+Lt[St].dx,pt.getCenterY()+Lt[St].dy)}),St++})}}}else{var D=A.eles.boundingBox();if(E.push({x:D.x1+D.w/2,y:D.y1+D.h/2}),A.randomize){var O=h(A);Y.push(O)}A.quality=="default"||A.quality=="proof"?(k.push(l(A,Y[0])),i.relocateComponent(E[0],k[0],A)):i.relocateComponent(E[0],Y[0],A)}var Q=function(et,pt){if(A.quality=="default"||A.quality=="proof"){typeof et=="number"&&(et=pt);var Et=void 0,Ct=void 0,mt=et.data("id");return k.forEach(function(Ot){mt in Ot&&(Et={x:Ot[mt].getRect().getCenterX(),y:Ot[mt].getRect().getCenterY()},Ct=Ot[mt])}),A.nodeDimensionsIncludeLabels&&(Ct.labelWidth&&(Ct.labelPosHorizontal=="left"?Et.x+=Ct.labelWidth/2:Ct.labelPosHorizontal=="right"&&(Et.x-=Ct.labelWidth/2)),Ct.labelHeight&&(Ct.labelPosVertical=="top"?Et.y+=Ct.labelHeight/2:Ct.labelPosVertical=="bottom"&&(Et.y-=Ct.labelHeight/2))),Et==null&&(Et={x:et.position("x"),y:et.position("y")}),{x:Et.x,y:Et.y}}else{var Tt=void 0;return Y.forEach(function(Ot){var It=Ot.nodeIndexes.get(et.id());It!=null&&(Tt={x:Ot.xCoords[It],y:Ot.yCoords[It]})}),Tt==null&&(Tt={x:et.position("x"),y:et.position("y")}),{x:Tt.x,y:Tt.y}}};if(A.quality=="default"||A.quality=="proof"||A.randomize){var Ut=i.calcParentsWithoutChildren(S,B),wt=B.filter(function(nt){return nt.css("display")=="none"});A.eles=B.not(wt),B.nodes().not(":parent").not(wt).layoutPositions(R,A,Q),Ut.length>0&&Ut.forEach(function(nt){nt.position(Q(nt))})}else console.log("If randomize option is set to false, then quality option must be 'default' or 'proof'.")}}]),p})();n.exports=y}),657:((n,e,a)=>{var c=a(548),t=a(140).layoutBase.Matrix,g=a(140).layoutBase.SVD,i=function(h){var f=h.cy,l=h.eles,L=l.nodes(),y=l.nodes(":parent"),p=new Map,C=new Map,R=new Map,A=[],S=[],B=[],Y=[],tt=[],x=[],k=[],s=[],E=void 0,v=void 0,T=1e8,d=1e-9,D=h.piTol,O=h.samplingType,P=h.nodeSeparation,F=void 0,I=function(){for(var W=0,z=0,$=!1;z=ut;){q=K[ut++];for(var ot=A[q],it=0;itrt&&(rt=tt[at],vt=at)}return vt},_=function(W){var z=void 0;if(W){z=Math.floor(Math.random()*v),E=z;for(var K=0;K=1)break;rt=gt}for(var ot=0;ot=1)break;rt=gt}for(var dt=0;dt0&&(z.isParent()?A[W].push(R.get(z.id())):A[W].push(z.id()))})});var Ut=function(W){var z=C.get(W),$=void 0;p.get(W).forEach(function(K){f.getElementById(K).isParent()?$=R.get(K):$=K,A[z].push($),A[C.get($)].push(W)})},wt=!0,nt=!1,et=void 0;try{for(var pt=p.keys()[Symbol.iterator](),Et;!(wt=(Et=pt.next()).done);wt=!0){var Ct=Et.value;Ut(Ct)}}catch(H){nt=!0,et=H}finally{try{!wt&&pt.return&&pt.return()}finally{if(nt)throw et}}v=C.size;var mt=void 0;if(v>2){F=v{var c=a(212),t=function(i){i&&i("layout","fcose",c)};typeof cytoscape<"u"&&t(cytoscape),n.exports=t}),140:(n=>{n.exports=m})},N={};function u(n){var e=N[n];if(e!==void 0)return e.exports;var a=N[n]={exports:{}};return w[n](a,a.exports,u),a.exports}var o=u(579);return o})()})});var ir=ur(Je(),1);var Ke={L:"left",R:"right",T:"top",B:"bottom"},je={L:ct(m=>`${m},${m/2} 0,${m} 0,0`,"L"),R:ct(m=>`0,${m/2} ${m},0 ${m},${m}`,"R"),T:ct(m=>`0,0 ${m},0 ${m/2},${m}`,"T"),B:ct(m=>`${m/2},0 ${m},${m} 0,${m}`,"B")},fe={L:ct((m,w)=>m-w+2,"L"),R:ct((m,w)=>m-2,"R"),T:ct((m,w)=>m-w+2,"T"),B:ct((m,w)=>m-2,"B")},dr=ct(function(m){return Ht(m)?m==="L"?"R":"L":m==="T"?"B":"T"},"getOppositeArchitectureDirection"),_e=ct(function(m){let w=m;return w==="L"||w==="R"||w==="T"||w==="B"},"isArchitectureDirection"),Ht=ct(function(m){let w=m;return w==="L"||w==="R"},"isArchitectureDirectionX"),kt=ct(function(m){let w=m;return w==="T"||w==="B"},"isArchitectureDirectionY"),Me=ct(function(m,w){let N=Ht(m)&&kt(w),u=kt(m)&&Ht(w);return N||u},"isArchitectureDirectionXY"),vr=ct(function(m){let w=m[0],N=m[1],u=Ht(w)&&kt(N),o=kt(w)&&Ht(N);return u||o},"isArchitecturePairXY"),pr=ct(function(m){return m!=="LL"&&m!=="RR"&&m!=="TT"&&m!=="BB"},"isValidArchitectureDirectionPair"),Ae=ct(function(m,w){let N=`${m}${w}`;return pr(N)?N:void 0},"getArchitectureDirectionPair"),yr=ct(function([m,w],N){let u=N[0],o=N[1];return Ht(u)?kt(o)?[m+(u==="L"?-1:1),w+(o==="T"?1:-1)]:[m+(u==="L"?-1:1),w]:Ht(o)?[m+(o==="L"?1:-1),w+(u==="T"?1:-1)]:[m,w+(u==="T"?1:-1)]},"shiftPositionByArchitectureDirectionPair"),Er=ct(function(m){return m==="LT"||m==="TL"?[1,1]:m==="BL"||m==="LB"?[1,-1]:m==="BR"||m==="RB"?[-1,-1]:[-1,1]},"getArchitectureDirectionXYFactors"),mr=ct(function(m,w){return Me(m,w)?"bend":Ht(m)?"horizontal":"vertical"},"getArchitectureDirectionAlignment"),Tr=ct(function(m){return m.type==="service"},"isArchitectureService"),Nr=ct(function(m){return m.type==="junction"},"isArchitectureJunction"),tr=ct(m=>m.data(),"edgeData"),ee=ct(m=>m.data(),"nodeData"),Lr=Re.architecture,er=class{constructor(){this.nodes={},this.groups={},this.edges=[],this.registeredIds={},this.elements={},this.setAccTitle=Ge,this.getAccTitle=Ue,this.setDiagramTitle=He,this.getDiagramTitle=We,this.getAccDescription=Xe,this.setAccDescription=Ye,this.clear()}static{ct(this,"ArchitectureDB")}clear(){this.nodes={},this.groups={},this.edges=[],this.registeredIds={},this.dataStructures=void 0,this.elements={},Pe()}addService({id:m,icon:w,in:N,title:u,iconText:o}){if(this.registeredIds[m]!==void 0)throw new Error(`The service id [${m}] is already in use by another ${this.registeredIds[m]}`);if(N!==void 0){if(m===N)throw new Error(`The service [${m}] cannot be placed within itself`);if(this.registeredIds[N]===void 0)throw new Error(`The service [${m}]'s parent does not exist. Please make sure the parent is created before this service`);if(this.registeredIds[N]==="node")throw new Error(`The service [${m}]'s parent is not a group`)}this.registeredIds[m]="node",this.nodes[m]={id:m,type:"service",icon:w,iconText:o,title:u,edges:[],in:N}}getServices(){return Object.values(this.nodes).filter(Tr)}addJunction({id:m,in:w}){this.registeredIds[m]="node",this.nodes[m]={id:m,type:"junction",edges:[],in:w}}getJunctions(){return Object.values(this.nodes).filter(Nr)}getNodes(){return Object.values(this.nodes)}getNode(m){return this.nodes[m]??null}addGroup({id:m,icon:w,in:N,title:u}){if(this.registeredIds?.[m]!==void 0)throw new Error(`The group id [${m}] is already in use by another ${this.registeredIds[m]}`);if(N!==void 0){if(m===N)throw new Error(`The group [${m}] cannot be placed within itself`);if(this.registeredIds?.[N]===void 0)throw new Error(`The group [${m}]'s parent does not exist. Please make sure the parent is created before this group`);if(this.registeredIds?.[N]==="node")throw new Error(`The group [${m}]'s parent is not a group`)}this.registeredIds[m]="group",this.groups[m]={id:m,icon:w,title:u,in:N}}getGroups(){return Object.values(this.groups)}addEdge({lhsId:m,rhsId:w,lhsDir:N,rhsDir:u,lhsInto:o,rhsInto:n,lhsGroup:e,rhsGroup:a,title:c}){if(!_e(N))throw new Error(`Invalid direction given for left hand side of edge ${m}--${w}. Expected (L,R,T,B) got ${String(N)}`);if(!_e(u))throw new Error(`Invalid direction given for right hand side of edge ${m}--${w}. Expected (L,R,T,B) got ${String(u)}`);if(this.nodes[m]===void 0&&this.groups[m]===void 0)throw new Error(`The left-hand id [${m}] does not yet exist. Please create the service/group before declaring an edge to it.`);if(this.nodes[w]===void 0&&this.groups[w]===void 0)throw new Error(`The right-hand id [${w}] does not yet exist. Please create the service/group before declaring an edge to it.`);let t=this.nodes[m].in,g=this.nodes[w].in;if(e&&t&&g&&t==g)throw new Error(`The left-hand id [${m}] is modified to traverse the group boundary, but the edge does not pass through two groups.`);if(a&&t&&g&&t==g)throw new Error(`The right-hand id [${w}] is modified to traverse the group boundary, but the edge does not pass through two groups.`);let i={lhsId:m,lhsDir:N,lhsInto:o,lhsGroup:e,rhsId:w,rhsDir:u,rhsInto:n,rhsGroup:a,title:c};this.edges.push(i),this.nodes[m]&&this.nodes[w]&&(this.nodes[m].edges.push(this.edges[this.edges.length-1]),this.nodes[w].edges.push(this.edges[this.edges.length-1]))}getEdges(){return this.edges}getDataStructures(){if(this.dataStructures===void 0){let m={},w=Object.entries(this.nodes).reduce((a,[c,t])=>(a[c]=t.edges.reduce((g,i)=>{let r=this.getNode(i.lhsId)?.in,h=this.getNode(i.rhsId)?.in;if(r&&h&&r!==h){let f=mr(i.lhsDir,i.rhsDir);f!=="bend"&&(m[r]??={},m[r][h]=f,m[h]??={},m[h][r]=f)}if(i.lhsId===c){let f=Ae(i.lhsDir,i.rhsDir);f&&(g[f]=i.rhsId)}else{let f=Ae(i.rhsDir,i.lhsDir);f&&(g[f]=i.lhsId)}return g},{}),a),{}),N=Object.keys(w)[0],u={[N]:1},o=Object.keys(w).reduce((a,c)=>c===N?a:{...a,[c]:1},{}),n=ct(a=>{let c={[a]:[0,0]},t=[a];for(;t.length>0;){let g=t.shift();if(g){u[g]=1,delete o[g];let i=w[g],[r,h]=c[g];Object.entries(i).forEach(([f,l])=>{u[l]||(c[l]=yr([r,h],f),t.push(l))})}}return c},"BFS"),e=[n(N)];for(;Object.keys(o).length>0;)e.push(n(Object.keys(o)[0]));this.dataStructures={adjList:w,spatialMaps:e,groupAlignments:m}}return this.dataStructures}setElementForId(m,w){this.elements[m]=w}getElementById(m){return this.elements[m]}getConfig(){return Be({...Lr,...Se().architecture})}getConfigField(m){return this.getConfig()[m]}},Cr=ct((m,w)=>{qe(m,w),m.groups.map(N=>w.addGroup(N)),m.services.map(N=>w.addService({...N,type:"service"})),m.junctions.map(N=>w.addJunction({...N,type:"junction"})),m.edges.map(N=>w.addEdge(N))},"populateDb"),rr={parser:{yy:void 0},parse:ct(async m=>{let w=await Qe("architecture",m);ye.debug(w);let N=rr.parser?.yy;if(!(N instanceof er))throw new Error("parser.parser?.yy was not a ArchitectureDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.");Cr(w,N)},"parse")},Ar=ct(m=>` + .edge { + stroke-width: ${m.archEdgeWidth}; + stroke: ${m.archEdgeColor}; + fill: none; + } + + .arrow { + fill: ${m.archEdgeArrowColor}; + } + + .node-bkg { + fill: none; + stroke: ${m.archGroupBorderColor}; + stroke-width: ${m.archGroupBorderWidth}; + stroke-dasharray: 8; + } + .node-icon-text { + display: flex; + align-items: center; + } + + .node-icon-text > div { + color: #fff; + margin: 1px; + height: fit-content; + text-align: center; + overflow: hidden; + display: -webkit-box; + -webkit-box-orient: vertical; + } +`,"getStyles"),Mr=Ar,te=ct(m=>`${m}`,"wrapIcon"),ne={prefix:"mermaid-architecture",height:80,width:80,icons:{database:{body:te('')},server:{body:te('')},disk:{body:te('')},internet:{body:te('')},cloud:{body:te('')},unknown:Ze,blank:{body:te("")}}},wr=ct(async function(m,w,N){let u=N.getConfigField("padding"),o=N.getConfigField("iconSize"),n=o/2,e=o/6,a=e/2;await Promise.all(w.edges().map(async c=>{let{source:t,sourceDir:g,sourceArrow:i,sourceGroup:r,target:h,targetDir:f,targetArrow:l,targetGroup:L,label:y}=tr(c),{x:p,y:C}=c[0].sourceEndpoint(),{x:R,y:A}=c[0].midpoint(),{x:S,y:B}=c[0].targetEndpoint(),Y=u+4;if(r&&(Ht(g)?p+=g==="L"?-Y:Y:C+=g==="T"?-Y:Y+18),L&&(Ht(f)?S+=f==="L"?-Y:Y:B+=f==="T"?-Y:Y+18),!r&&N.getNode(t)?.type==="junction"&&(Ht(g)?p+=g==="L"?n:-n:C+=g==="T"?n:-n),!L&&N.getNode(h)?.type==="junction"&&(Ht(f)?S+=f==="L"?n:-n:B+=f==="T"?n:-n),c[0]._private.rscratch){let tt=m.insert("g");if(tt.insert("path").attr("d",`M ${p},${C} L ${R},${A} L${S},${B} `).attr("class","edge").attr("id",$e(t,h,{prefix:"L"})),i){let x=Ht(g)?fe[g](p,e):p-a,k=kt(g)?fe[g](C,e):C-a;tt.insert("polygon").attr("points",je[g](e)).attr("transform",`translate(${x},${k})`).attr("class","arrow")}if(l){let x=Ht(f)?fe[f](S,e):S-a,k=kt(f)?fe[f](B,e):B-a;tt.insert("polygon").attr("points",je[f](e)).attr("transform",`translate(${x},${k})`).attr("class","arrow")}if(y){let x=Me(g,f)?"XY":Ht(g)?"X":"Y",k=0;x==="X"?k=Math.abs(p-S):x==="Y"?k=Math.abs(C-B)/1.5:k=Math.abs(p-S)/2;let s=tt.append("g");if(await le(s,y,{useHtmlLabels:!1,width:k,classes:"architecture-service-label"},se()),s.attr("dy","1em").attr("alignment-baseline","middle").attr("dominant-baseline","middle").attr("text-anchor","middle"),x==="X")s.attr("transform","translate("+R+", "+A+")");else if(x==="Y")s.attr("transform","translate("+R+", "+A+") rotate(-90)");else if(x==="XY"){let E=Ae(g,f);if(E&&vr(E)){let v=s.node().getBoundingClientRect(),[T,d]=Er(E);s.attr("dominant-baseline","auto").attr("transform",`rotate(${-1*T*d*45})`);let D=s.node().getBoundingClientRect();s.attr("transform",` + translate(${R}, ${A-v.height/2}) + translate(${T*D.width/2}, ${d*D.height/2}) + rotate(${-1*T*d*45}, 0, ${v.height/2}) + `)}}}}}))},"drawEdges"),Or=ct(async function(m,w,N){let o=N.getConfigField("padding")*.75,n=N.getConfigField("fontSize"),a=N.getConfigField("iconSize")/2;await Promise.all(w.nodes().map(async c=>{let t=ee(c);if(t.type==="group"){let{h:g,w:i,x1:r,y1:h}=c.boundingBox(),f=m.append("rect");f.attr("id",`group-${t.id}`).attr("x",r+a).attr("y",h+a).attr("width",i).attr("height",g).attr("class","node-bkg");let l=m.append("g"),L=r,y=h;if(t.icon){let p=l.append("g");p.html(`${await he(t.icon,{height:o,width:o,fallbackPrefix:ne.prefix})}`),p.attr("transform","translate("+(L+a+1)+", "+(y+a+1)+")"),L+=o,y+=n/2-1-2}if(t.label){let p=l.append("g");await le(p,t.label,{useHtmlLabels:!1,width:i,classes:"architecture-service-label"},se()),p.attr("dy","1em").attr("alignment-baseline","middle").attr("dominant-baseline","start").attr("text-anchor","start"),p.attr("transform","translate("+(L+a+4)+", "+(y+a+2)+")")}N.setElementForId(t.id,f)}}))},"drawGroups"),Dr=ct(async function(m,w,N){let u=se();for(let o of N){let n=w.append("g"),e=m.getConfigField("iconSize");if(o.title){let g=n.append("g");await le(g,o.title,{useHtmlLabels:!1,width:e*1.5,classes:"architecture-service-label"},u),g.attr("dy","1em").attr("alignment-baseline","middle").attr("dominant-baseline","middle").attr("text-anchor","middle"),g.attr("transform","translate("+e/2+", "+e+")")}let a=n.append("g");if(o.icon)a.html(`${await he(o.icon,{height:e,width:e,fallbackPrefix:ne.prefix})}`);else if(o.iconText){a.html(`${await he("blank",{height:e,width:e,fallbackPrefix:ne.prefix})}`);let r=a.append("g").append("foreignObject").attr("width",e).attr("height",e).append("div").attr("class","node-icon-text").attr("style",`height: ${e}px;`).append("div").html(Fe(o.iconText,u)),h=parseInt(window.getComputedStyle(r.node(),null).getPropertyValue("font-size").replace(/\D/g,""))??16;r.attr("style",`-webkit-line-clamp: ${Math.floor((e-2)/h)};`)}else a.append("path").attr("class","node-bkg").attr("id","node-"+o.id).attr("d",`M0 ${e} v${-e} q0,-5 5,-5 h${e} q5,0 5,5 v${e} H0 Z`);n.attr("id",`service-${o.id}`).attr("class","architecture-service");let{width:c,height:t}=n.node().getBBox();o.width=c,o.height=t,m.setElementForId(o.id,n)}return 0},"drawServices"),xr=ct(function(m,w,N){N.forEach(u=>{let o=w.append("g"),n=m.getConfigField("iconSize");o.append("g").append("rect").attr("id","node-"+u.id).attr("fill-opacity","0").attr("width",n).attr("height",n),o.attr("class","architecture-junction");let{width:a,height:c}=o._groups[0][0].getBBox();o.width=a,o.height=c,m.setElementForId(u.id,o)})},"drawJunctions");ke([{name:ne.prefix,icons:ne}]);Ee.use(ir.default);function ar(m,w,N){m.forEach(u=>{w.add({group:"nodes",data:{type:"service",id:u.id,icon:u.icon,label:u.title,parent:u.in,width:N.getConfigField("iconSize"),height:N.getConfigField("iconSize")},classes:"node-service"})})}ct(ar,"addServices");function nr(m,w,N){m.forEach(u=>{w.add({group:"nodes",data:{type:"junction",id:u.id,parent:u.in,width:N.getConfigField("iconSize"),height:N.getConfigField("iconSize")},classes:"node-junction"})})}ct(nr,"addJunctions");function or(m,w){w.nodes().map(N=>{let u=ee(N);if(u.type==="group")return;u.x=N.position().x,u.y=N.position().y,m.getElementById(u.id).attr("transform","translate("+(u.x||0)+","+(u.y||0)+")")})}ct(or,"positionNodes");function sr(m,w){m.forEach(N=>{w.add({group:"nodes",data:{type:"group",id:N.id,icon:N.icon,label:N.title,parent:N.in},classes:"node-group"})})}ct(sr,"addGroups");function hr(m,w){m.forEach(N=>{let{lhsId:u,rhsId:o,lhsInto:n,lhsGroup:e,rhsInto:a,lhsDir:c,rhsDir:t,rhsGroup:g,title:i}=N,r=Me(N.lhsDir,N.rhsDir)?"segments":"straight",h={id:`${u}-${o}`,label:i,source:u,sourceDir:c,sourceArrow:n,sourceGroup:e,sourceEndpoint:c==="L"?"0 50%":c==="R"?"100% 50%":c==="T"?"50% 0":"50% 100%",target:o,targetDir:t,targetArrow:a,targetGroup:g,targetEndpoint:t==="L"?"0 50%":t==="R"?"100% 50%":t==="T"?"50% 0":"50% 100%"};w.add({group:"edges",data:h,classes:r})})}ct(hr,"addEdges");function lr(m,w,N){let u=ct((a,c)=>Object.entries(a).reduce((t,[g,i])=>{let r=0,h=Object.entries(i);if(h.length===1)return t[g]=h[0][1],t;for(let f=0;f{let c={},t={};return Object.entries(a).forEach(([g,[i,r]])=>{let h=m.getNode(g)?.in??"default";c[r]??={},c[r][h]??=[],c[r][h].push(g),t[i]??={},t[i][h]??=[],t[i][h].push(g)}),{horiz:Object.values(u(c,"horizontal")).filter(g=>g.length>1),vert:Object.values(u(t,"vertical")).filter(g=>g.length>1)}}),[n,e]=o.reduce(([a,c],{horiz:t,vert:g})=>[[...a,...t],[...c,...g]],[[],[]]);return{horizontal:n,vertical:e}}ct(lr,"getAlignments");function fr(m,w){let N=[],u=ct(n=>`${n[0]},${n[1]}`,"posToStr"),o=ct(n=>n.split(",").map(e=>parseInt(e)),"strToPos");return m.forEach(n=>{let e=Object.fromEntries(Object.entries(n).map(([g,i])=>[u(i),g])),a=[u([0,0])],c={},t={L:[-1,0],R:[1,0],T:[0,1],B:[0,-1]};for(;a.length>0;){let g=a.shift();if(g){c[g]=1;let i=e[g];if(i){let r=o(g);Object.entries(t).forEach(([h,f])=>{let l=u([r[0]+f[0],r[1]+f[1]]),L=e[l];L&&!c[l]&&(a.push(l),N.push({[Ke[h]]:L,[Ke[dr(h)]]:i,gap:1.5*w.getConfigField("iconSize")}))})}}}}),N}ct(fr,"getRelativeConstraints");function cr(m,w,N,u,o,{spatialMaps:n,groupAlignments:e}){return new Promise(a=>{let c=Ve("body").append("div").attr("id","cy").attr("style","display:none"),t=Ee({container:document.getElementById("cy"),style:[{selector:"edge",style:{"curve-style":"straight",label:"data(label)","source-endpoint":"data(sourceEndpoint)","target-endpoint":"data(targetEndpoint)"}},{selector:"edge.segments",style:{"curve-style":"segments","segment-weights":"0","segment-distances":[.5],"edge-distances":"endpoints","source-endpoint":"data(sourceEndpoint)","target-endpoint":"data(targetEndpoint)"}},{selector:"node",style:{"compound-sizing-wrt-labels":"include"}},{selector:"node[label]",style:{"text-valign":"bottom","text-halign":"center","font-size":`${o.getConfigField("fontSize")}px`}},{selector:".node-service",style:{label:"data(label)",width:"data(width)",height:"data(height)"}},{selector:".node-junction",style:{width:"data(width)",height:"data(height)"}},{selector:".node-group",style:{padding:`${o.getConfigField("padding")}px`}}],layout:{name:"grid",boundingBox:{x1:0,x2:100,y1:0,y2:100}}});c.remove(),sr(N,t),ar(m,t,o),nr(w,t,o),hr(u,t);let g=lr(o,n,e),i=fr(n,o),r=t.layout({name:"fcose",quality:"proof",styleEnabled:!1,animate:!1,nodeDimensionsIncludeLabels:!1,idealEdgeLength(h){let[f,l]=h.connectedNodes(),{parent:L}=ee(f),{parent:y}=ee(l);return L===y?1.5*o.getConfigField("iconSize"):.5*o.getConfigField("iconSize")},edgeElasticity(h){let[f,l]=h.connectedNodes(),{parent:L}=ee(f),{parent:y}=ee(l);return L===y?.45:.001},alignmentConstraint:g,relativePlacementConstraint:i});r.one("layoutstop",()=>{function h(f,l,L,y){let p,C,{x:R,y:A}=f,{x:S,y:B}=l;C=(y-A+(R-L)*(A-B)/(R-S))/Math.sqrt(1+Math.pow((A-B)/(R-S),2)),p=Math.sqrt(Math.pow(y-A,2)+Math.pow(L-R,2)-Math.pow(C,2));let Y=Math.sqrt(Math.pow(S-R,2)+Math.pow(B-A,2));p=p/Y;let tt=(S-R)*(y-A)-(B-A)*(L-R);switch(!0){case tt>=0:tt=1;break;case tt<0:tt=-1;break}let x=(S-R)*(L-R)+(B-A)*(y-A);switch(!0){case x>=0:x=1;break;case x<0:x=-1;break}return C=Math.abs(C)*tt,p=p*x,{distances:C,weights:p}}ct(h,"getSegmentWeights"),t.startBatch();for(let f of Object.values(t.edges()))if(f.data?.()){let{x:l,y:L}=f.source().position(),{x:y,y:p}=f.target().position();if(l!==y&&L!==p){let C=f.sourceEndpoint(),R=f.targetEndpoint(),{sourceDir:A}=tr(f),[S,B]=kt(A)?[C.x,R.y]:[R.x,C.y],{weights:Y,distances:tt}=h(C,R,S,B);f.style("segment-distances",tt),f.style("segment-weights",Y)}}t.endBatch(),r.run()}),r.run(),t.ready(h=>{ye.info("Ready",h),a(t)})})}ct(cr,"layoutArchitecture");var Ir=ct(async(m,w,N,u)=>{let o=u.db,n=o.getServices(),e=o.getJunctions(),a=o.getGroups(),c=o.getEdges(),t=o.getDataStructures(),g=ze(w),i=g.append("g");i.attr("class","architecture-edges");let r=g.append("g");r.attr("class","architecture-services");let h=g.append("g");h.attr("class","architecture-groups"),await Dr(o,r,n),xr(o,r,e);let f=await cr(n,e,a,c,o,t);await wr(i,f,o),await Or(h,f,o),or(o,f),be(void 0,g,o.getConfigField("padding"),o.getConfigField("useMaxWidth"))},"draw"),Rr={draw:Ir},Wr={parser:rr,get db(){return new er},renderer:Rr,styles:Mr};export{Wr as diagram}; +//# sourceMappingURL=architectureDiagram-VXUJARFQ-H4V63UKK.min.js.map diff --git a/docs/website/public/architectureDiagram-VXUJARFQ-H4V63UKK.min.js.map b/docs/website/public/architectureDiagram-VXUJARFQ-H4V63UKK.min.js.map new file mode 100644 index 000000000..7ce83b02b --- /dev/null +++ b/docs/website/public/architectureDiagram-VXUJARFQ-H4V63UKK.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/cytoscape-fcose/node_modules/layout-base/layout-base.js", "../../node_modules/cytoscape-fcose/node_modules/cose-base/cose-base.js", "../../node_modules/cytoscape-fcose/cytoscape-fcose.js", "../../node_modules/mermaid/dist/chunks/mermaid.core/architectureDiagram-VXUJARFQ.mjs"], + "sourcesContent": ["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"layoutBase\"] = factory();\n\telse\n\t\troot[\"layoutBase\"] = factory();\n})(this, function() {\nreturn /******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n/******/\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId]) {\n/******/ \t\t\treturn installedModules[moduleId].exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\ti: moduleId,\n/******/ \t\t\tl: false,\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.l = true;\n/******/\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/\n/******/\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n/******/\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n/******/\n/******/ \t// identity function for calling harmony imports with the correct context\n/******/ \t__webpack_require__.i = function(value) { return value; };\n/******/\n/******/ \t// define getter function for harmony exports\n/******/ \t__webpack_require__.d = function(exports, name, getter) {\n/******/ \t\tif(!__webpack_require__.o(exports, name)) {\n/******/ \t\t\tObject.defineProperty(exports, name, {\n/******/ \t\t\t\tconfigurable: false,\n/******/ \t\t\t\tenumerable: true,\n/******/ \t\t\t\tget: getter\n/******/ \t\t\t});\n/******/ \t\t}\n/******/ \t};\n/******/\n/******/ \t// getDefaultExport function for compatibility with non-harmony modules\n/******/ \t__webpack_require__.n = function(module) {\n/******/ \t\tvar getter = module && module.__esModule ?\n/******/ \t\t\tfunction getDefault() { return module['default']; } :\n/******/ \t\t\tfunction getModuleExports() { return module; };\n/******/ \t\t__webpack_require__.d(getter, 'a', getter);\n/******/ \t\treturn getter;\n/******/ \t};\n/******/\n/******/ \t// Object.prototype.hasOwnProperty.call\n/******/ \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n/******/\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"\";\n/******/\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(__webpack_require__.s = 28);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction LayoutConstants() {}\n\n/**\r\n * Layout Quality: 0:draft, 1:default, 2:proof\r\n */\nLayoutConstants.QUALITY = 1;\n\n/**\r\n * Default parameters\r\n */\nLayoutConstants.DEFAULT_CREATE_BENDS_AS_NEEDED = false;\nLayoutConstants.DEFAULT_INCREMENTAL = false;\nLayoutConstants.DEFAULT_ANIMATION_ON_LAYOUT = true;\nLayoutConstants.DEFAULT_ANIMATION_DURING_LAYOUT = false;\nLayoutConstants.DEFAULT_ANIMATION_PERIOD = 50;\nLayoutConstants.DEFAULT_UNIFORM_LEAF_NODE_SIZES = false;\n\n// -----------------------------------------------------------------------------\n// Section: General other constants\n// -----------------------------------------------------------------------------\n/*\r\n * Margins of a graph to be applied on bouding rectangle of its contents. We\r\n * assume margins on all four sides to be uniform.\r\n */\nLayoutConstants.DEFAULT_GRAPH_MARGIN = 15;\n\n/*\r\n * Whether to consider labels in node dimensions or not\r\n */\nLayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS = false;\n\n/*\r\n * Default dimension of a non-compound node.\r\n */\nLayoutConstants.SIMPLE_NODE_SIZE = 40;\n\n/*\r\n * Default dimension of a non-compound node.\r\n */\nLayoutConstants.SIMPLE_NODE_HALF_SIZE = LayoutConstants.SIMPLE_NODE_SIZE / 2;\n\n/*\r\n * Empty compound node size. When a compound node is empty, its both\r\n * dimensions should be of this value.\r\n */\nLayoutConstants.EMPTY_COMPOUND_NODE_SIZE = 40;\n\n/*\r\n * Minimum length that an edge should take during layout\r\n */\nLayoutConstants.MIN_EDGE_LENGTH = 1;\n\n/*\r\n * World boundaries that layout operates on\r\n */\nLayoutConstants.WORLD_BOUNDARY = 1000000;\n\n/*\r\n * World boundaries that random positioning can be performed with\r\n */\nLayoutConstants.INITIAL_WORLD_BOUNDARY = LayoutConstants.WORLD_BOUNDARY / 1000;\n\n/*\r\n * Coordinates of the world center\r\n */\nLayoutConstants.WORLD_CENTER_X = 1200;\nLayoutConstants.WORLD_CENTER_Y = 900;\n\nmodule.exports = LayoutConstants;\n\n/***/ }),\n/* 1 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar LGraphObject = __webpack_require__(2);\nvar IGeometry = __webpack_require__(8);\nvar IMath = __webpack_require__(9);\n\nfunction LEdge(source, target, vEdge) {\n LGraphObject.call(this, vEdge);\n\n this.isOverlapingSourceAndTarget = false;\n this.vGraphObject = vEdge;\n this.bendpoints = [];\n this.source = source;\n this.target = target;\n}\n\nLEdge.prototype = Object.create(LGraphObject.prototype);\n\nfor (var prop in LGraphObject) {\n LEdge[prop] = LGraphObject[prop];\n}\n\nLEdge.prototype.getSource = function () {\n return this.source;\n};\n\nLEdge.prototype.getTarget = function () {\n return this.target;\n};\n\nLEdge.prototype.isInterGraph = function () {\n return this.isInterGraph;\n};\n\nLEdge.prototype.getLength = function () {\n return this.length;\n};\n\nLEdge.prototype.isOverlapingSourceAndTarget = function () {\n return this.isOverlapingSourceAndTarget;\n};\n\nLEdge.prototype.getBendpoints = function () {\n return this.bendpoints;\n};\n\nLEdge.prototype.getLca = function () {\n return this.lca;\n};\n\nLEdge.prototype.getSourceInLca = function () {\n return this.sourceInLca;\n};\n\nLEdge.prototype.getTargetInLca = function () {\n return this.targetInLca;\n};\n\nLEdge.prototype.getOtherEnd = function (node) {\n if (this.source === node) {\n return this.target;\n } else if (this.target === node) {\n return this.source;\n } else {\n throw \"Node is not incident with this edge\";\n }\n};\n\nLEdge.prototype.getOtherEndInGraph = function (node, graph) {\n var otherEnd = this.getOtherEnd(node);\n var root = graph.getGraphManager().getRoot();\n\n while (true) {\n if (otherEnd.getOwner() == graph) {\n return otherEnd;\n }\n\n if (otherEnd.getOwner() == root) {\n break;\n }\n\n otherEnd = otherEnd.getOwner().getParent();\n }\n\n return null;\n};\n\nLEdge.prototype.updateLength = function () {\n var clipPointCoordinates = new Array(4);\n\n this.isOverlapingSourceAndTarget = IGeometry.getIntersection(this.target.getRect(), this.source.getRect(), clipPointCoordinates);\n\n if (!this.isOverlapingSourceAndTarget) {\n this.lengthX = clipPointCoordinates[0] - clipPointCoordinates[2];\n this.lengthY = clipPointCoordinates[1] - clipPointCoordinates[3];\n\n if (Math.abs(this.lengthX) < 1.0) {\n this.lengthX = IMath.sign(this.lengthX);\n }\n\n if (Math.abs(this.lengthY) < 1.0) {\n this.lengthY = IMath.sign(this.lengthY);\n }\n\n this.length = Math.sqrt(this.lengthX * this.lengthX + this.lengthY * this.lengthY);\n }\n};\n\nLEdge.prototype.updateLengthSimple = function () {\n this.lengthX = this.target.getCenterX() - this.source.getCenterX();\n this.lengthY = this.target.getCenterY() - this.source.getCenterY();\n\n if (Math.abs(this.lengthX) < 1.0) {\n this.lengthX = IMath.sign(this.lengthX);\n }\n\n if (Math.abs(this.lengthY) < 1.0) {\n this.lengthY = IMath.sign(this.lengthY);\n }\n\n this.length = Math.sqrt(this.lengthX * this.lengthX + this.lengthY * this.lengthY);\n};\n\nmodule.exports = LEdge;\n\n/***/ }),\n/* 2 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction LGraphObject(vGraphObject) {\n this.vGraphObject = vGraphObject;\n}\n\nmodule.exports = LGraphObject;\n\n/***/ }),\n/* 3 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar LGraphObject = __webpack_require__(2);\nvar Integer = __webpack_require__(10);\nvar RectangleD = __webpack_require__(13);\nvar LayoutConstants = __webpack_require__(0);\nvar RandomSeed = __webpack_require__(16);\nvar PointD = __webpack_require__(5);\n\nfunction LNode(gm, loc, size, vNode) {\n //Alternative constructor 1 : LNode(LGraphManager gm, Point loc, Dimension size, Object vNode)\n if (size == null && vNode == null) {\n vNode = loc;\n }\n\n LGraphObject.call(this, vNode);\n\n //Alternative constructor 2 : LNode(Layout layout, Object vNode)\n if (gm.graphManager != null) gm = gm.graphManager;\n\n this.estimatedSize = Integer.MIN_VALUE;\n this.inclusionTreeDepth = Integer.MAX_VALUE;\n this.vGraphObject = vNode;\n this.edges = [];\n this.graphManager = gm;\n\n if (size != null && loc != null) this.rect = new RectangleD(loc.x, loc.y, size.width, size.height);else this.rect = new RectangleD();\n}\n\nLNode.prototype = Object.create(LGraphObject.prototype);\nfor (var prop in LGraphObject) {\n LNode[prop] = LGraphObject[prop];\n}\n\nLNode.prototype.getEdges = function () {\n return this.edges;\n};\n\nLNode.prototype.getChild = function () {\n return this.child;\n};\n\nLNode.prototype.getOwner = function () {\n // if (this.owner != null) {\n // if (!(this.owner == null || this.owner.getNodes().indexOf(this) > -1)) {\n // throw \"assert failed\";\n // }\n // }\n\n return this.owner;\n};\n\nLNode.prototype.getWidth = function () {\n return this.rect.width;\n};\n\nLNode.prototype.setWidth = function (width) {\n this.rect.width = width;\n};\n\nLNode.prototype.getHeight = function () {\n return this.rect.height;\n};\n\nLNode.prototype.setHeight = function (height) {\n this.rect.height = height;\n};\n\nLNode.prototype.getCenterX = function () {\n return this.rect.x + this.rect.width / 2;\n};\n\nLNode.prototype.getCenterY = function () {\n return this.rect.y + this.rect.height / 2;\n};\n\nLNode.prototype.getCenter = function () {\n return new PointD(this.rect.x + this.rect.width / 2, this.rect.y + this.rect.height / 2);\n};\n\nLNode.prototype.getLocation = function () {\n return new PointD(this.rect.x, this.rect.y);\n};\n\nLNode.prototype.getRect = function () {\n return this.rect;\n};\n\nLNode.prototype.getDiagonal = function () {\n return Math.sqrt(this.rect.width * this.rect.width + this.rect.height * this.rect.height);\n};\n\n/**\n * This method returns half the diagonal length of this node.\n */\nLNode.prototype.getHalfTheDiagonal = function () {\n return Math.sqrt(this.rect.height * this.rect.height + this.rect.width * this.rect.width) / 2;\n};\n\nLNode.prototype.setRect = function (upperLeft, dimension) {\n this.rect.x = upperLeft.x;\n this.rect.y = upperLeft.y;\n this.rect.width = dimension.width;\n this.rect.height = dimension.height;\n};\n\nLNode.prototype.setCenter = function (cx, cy) {\n this.rect.x = cx - this.rect.width / 2;\n this.rect.y = cy - this.rect.height / 2;\n};\n\nLNode.prototype.setLocation = function (x, y) {\n this.rect.x = x;\n this.rect.y = y;\n};\n\nLNode.prototype.moveBy = function (dx, dy) {\n this.rect.x += dx;\n this.rect.y += dy;\n};\n\nLNode.prototype.getEdgeListToNode = function (to) {\n var edgeList = [];\n var edge;\n var self = this;\n\n self.edges.forEach(function (edge) {\n\n if (edge.target == to) {\n if (edge.source != self) throw \"Incorrect edge source!\";\n\n edgeList.push(edge);\n }\n });\n\n return edgeList;\n};\n\nLNode.prototype.getEdgesBetween = function (other) {\n var edgeList = [];\n var edge;\n\n var self = this;\n self.edges.forEach(function (edge) {\n\n if (!(edge.source == self || edge.target == self)) throw \"Incorrect edge source and/or target\";\n\n if (edge.target == other || edge.source == other) {\n edgeList.push(edge);\n }\n });\n\n return edgeList;\n};\n\nLNode.prototype.getNeighborsList = function () {\n var neighbors = new Set();\n\n var self = this;\n self.edges.forEach(function (edge) {\n\n if (edge.source == self) {\n neighbors.add(edge.target);\n } else {\n if (edge.target != self) {\n throw \"Incorrect incidency!\";\n }\n\n neighbors.add(edge.source);\n }\n });\n\n return neighbors;\n};\n\nLNode.prototype.withChildren = function () {\n var withNeighborsList = new Set();\n var childNode;\n var children;\n\n withNeighborsList.add(this);\n\n if (this.child != null) {\n var nodes = this.child.getNodes();\n for (var i = 0; i < nodes.length; i++) {\n childNode = nodes[i];\n children = childNode.withChildren();\n children.forEach(function (node) {\n withNeighborsList.add(node);\n });\n }\n }\n\n return withNeighborsList;\n};\n\nLNode.prototype.getNoOfChildren = function () {\n var noOfChildren = 0;\n var childNode;\n\n if (this.child == null) {\n noOfChildren = 1;\n } else {\n var nodes = this.child.getNodes();\n for (var i = 0; i < nodes.length; i++) {\n childNode = nodes[i];\n\n noOfChildren += childNode.getNoOfChildren();\n }\n }\n\n if (noOfChildren == 0) {\n noOfChildren = 1;\n }\n return noOfChildren;\n};\n\nLNode.prototype.getEstimatedSize = function () {\n if (this.estimatedSize == Integer.MIN_VALUE) {\n throw \"assert failed\";\n }\n return this.estimatedSize;\n};\n\nLNode.prototype.calcEstimatedSize = function () {\n if (this.child == null) {\n return this.estimatedSize = (this.rect.width + this.rect.height) / 2;\n } else {\n this.estimatedSize = this.child.calcEstimatedSize();\n this.rect.width = this.estimatedSize;\n this.rect.height = this.estimatedSize;\n\n return this.estimatedSize;\n }\n};\n\nLNode.prototype.scatter = function () {\n var randomCenterX;\n var randomCenterY;\n\n var minX = -LayoutConstants.INITIAL_WORLD_BOUNDARY;\n var maxX = LayoutConstants.INITIAL_WORLD_BOUNDARY;\n randomCenterX = LayoutConstants.WORLD_CENTER_X + RandomSeed.nextDouble() * (maxX - minX) + minX;\n\n var minY = -LayoutConstants.INITIAL_WORLD_BOUNDARY;\n var maxY = LayoutConstants.INITIAL_WORLD_BOUNDARY;\n randomCenterY = LayoutConstants.WORLD_CENTER_Y + RandomSeed.nextDouble() * (maxY - minY) + minY;\n\n this.rect.x = randomCenterX;\n this.rect.y = randomCenterY;\n};\n\nLNode.prototype.updateBounds = function () {\n if (this.getChild() == null) {\n throw \"assert failed\";\n }\n if (this.getChild().getNodes().length != 0) {\n // wrap the children nodes by re-arranging the boundaries\n var childGraph = this.getChild();\n childGraph.updateBounds(true);\n\n this.rect.x = childGraph.getLeft();\n this.rect.y = childGraph.getTop();\n\n this.setWidth(childGraph.getRight() - childGraph.getLeft());\n this.setHeight(childGraph.getBottom() - childGraph.getTop());\n\n // Update compound bounds considering its label properties \n if (LayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS) {\n\n var width = childGraph.getRight() - childGraph.getLeft();\n var height = childGraph.getBottom() - childGraph.getTop();\n\n if (this.labelWidth) {\n if (this.labelPosHorizontal == \"left\") {\n this.rect.x -= this.labelWidth;\n this.setWidth(width + this.labelWidth);\n } else if (this.labelPosHorizontal == \"center\" && this.labelWidth > width) {\n this.rect.x -= (this.labelWidth - width) / 2;\n this.setWidth(this.labelWidth);\n } else if (this.labelPosHorizontal == \"right\") {\n this.setWidth(width + this.labelWidth);\n }\n }\n\n if (this.labelHeight) {\n if (this.labelPosVertical == \"top\") {\n this.rect.y -= this.labelHeight;\n this.setHeight(height + this.labelHeight);\n } else if (this.labelPosVertical == \"center\" && this.labelHeight > height) {\n this.rect.y -= (this.labelHeight - height) / 2;\n this.setHeight(this.labelHeight);\n } else if (this.labelPosVertical == \"bottom\") {\n this.setHeight(height + this.labelHeight);\n }\n }\n }\n }\n};\n\nLNode.prototype.getInclusionTreeDepth = function () {\n if (this.inclusionTreeDepth == Integer.MAX_VALUE) {\n throw \"assert failed\";\n }\n return this.inclusionTreeDepth;\n};\n\nLNode.prototype.transform = function (trans) {\n var left = this.rect.x;\n\n if (left > LayoutConstants.WORLD_BOUNDARY) {\n left = LayoutConstants.WORLD_BOUNDARY;\n } else if (left < -LayoutConstants.WORLD_BOUNDARY) {\n left = -LayoutConstants.WORLD_BOUNDARY;\n }\n\n var top = this.rect.y;\n\n if (top > LayoutConstants.WORLD_BOUNDARY) {\n top = LayoutConstants.WORLD_BOUNDARY;\n } else if (top < -LayoutConstants.WORLD_BOUNDARY) {\n top = -LayoutConstants.WORLD_BOUNDARY;\n }\n\n var leftTop = new PointD(left, top);\n var vLeftTop = trans.inverseTransformPoint(leftTop);\n\n this.setLocation(vLeftTop.x, vLeftTop.y);\n};\n\nLNode.prototype.getLeft = function () {\n return this.rect.x;\n};\n\nLNode.prototype.getRight = function () {\n return this.rect.x + this.rect.width;\n};\n\nLNode.prototype.getTop = function () {\n return this.rect.y;\n};\n\nLNode.prototype.getBottom = function () {\n return this.rect.y + this.rect.height;\n};\n\nLNode.prototype.getParent = function () {\n if (this.owner == null) {\n return null;\n }\n\n return this.owner.getParent();\n};\n\nmodule.exports = LNode;\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar LayoutConstants = __webpack_require__(0);\n\nfunction FDLayoutConstants() {}\n\n//FDLayoutConstants inherits static props in LayoutConstants\nfor (var prop in LayoutConstants) {\n FDLayoutConstants[prop] = LayoutConstants[prop];\n}\n\nFDLayoutConstants.MAX_ITERATIONS = 2500;\n\nFDLayoutConstants.DEFAULT_EDGE_LENGTH = 50;\nFDLayoutConstants.DEFAULT_SPRING_STRENGTH = 0.45;\nFDLayoutConstants.DEFAULT_REPULSION_STRENGTH = 4500.0;\nFDLayoutConstants.DEFAULT_GRAVITY_STRENGTH = 0.4;\nFDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH = 1.0;\nFDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR = 3.8;\nFDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR = 1.5;\nFDLayoutConstants.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION = true;\nFDLayoutConstants.DEFAULT_USE_SMART_REPULSION_RANGE_CALCULATION = true;\nFDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL = 0.3;\nFDLayoutConstants.COOLING_ADAPTATION_FACTOR = 0.33;\nFDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT = 1000;\nFDLayoutConstants.ADAPTATION_UPPER_NODE_LIMIT = 5000;\nFDLayoutConstants.MAX_NODE_DISPLACEMENT_INCREMENTAL = 100.0;\nFDLayoutConstants.MAX_NODE_DISPLACEMENT = FDLayoutConstants.MAX_NODE_DISPLACEMENT_INCREMENTAL * 3;\nFDLayoutConstants.MIN_REPULSION_DIST = FDLayoutConstants.DEFAULT_EDGE_LENGTH / 10.0;\nFDLayoutConstants.CONVERGENCE_CHECK_PERIOD = 100;\nFDLayoutConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR = 0.1;\nFDLayoutConstants.MIN_EDGE_LENGTH = 1;\nFDLayoutConstants.GRID_CALCULATION_CHECK_PERIOD = 10;\n\nmodule.exports = FDLayoutConstants;\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction PointD(x, y) {\n if (x == null && y == null) {\n this.x = 0;\n this.y = 0;\n } else {\n this.x = x;\n this.y = y;\n }\n}\n\nPointD.prototype.getX = function () {\n return this.x;\n};\n\nPointD.prototype.getY = function () {\n return this.y;\n};\n\nPointD.prototype.setX = function (x) {\n this.x = x;\n};\n\nPointD.prototype.setY = function (y) {\n this.y = y;\n};\n\nPointD.prototype.getDifference = function (pt) {\n return new DimensionD(this.x - pt.x, this.y - pt.y);\n};\n\nPointD.prototype.getCopy = function () {\n return new PointD(this.x, this.y);\n};\n\nPointD.prototype.translate = function (dim) {\n this.x += dim.width;\n this.y += dim.height;\n return this;\n};\n\nmodule.exports = PointD;\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar LGraphObject = __webpack_require__(2);\nvar Integer = __webpack_require__(10);\nvar LayoutConstants = __webpack_require__(0);\nvar LGraphManager = __webpack_require__(7);\nvar LNode = __webpack_require__(3);\nvar LEdge = __webpack_require__(1);\nvar RectangleD = __webpack_require__(13);\nvar Point = __webpack_require__(12);\nvar LinkedList = __webpack_require__(11);\n\nfunction LGraph(parent, obj2, vGraph) {\n LGraphObject.call(this, vGraph);\n this.estimatedSize = Integer.MIN_VALUE;\n this.margin = LayoutConstants.DEFAULT_GRAPH_MARGIN;\n this.edges = [];\n this.nodes = [];\n this.isConnected = false;\n this.parent = parent;\n\n if (obj2 != null && obj2 instanceof LGraphManager) {\n this.graphManager = obj2;\n } else if (obj2 != null && obj2 instanceof Layout) {\n this.graphManager = obj2.graphManager;\n }\n}\n\nLGraph.prototype = Object.create(LGraphObject.prototype);\nfor (var prop in LGraphObject) {\n LGraph[prop] = LGraphObject[prop];\n}\n\nLGraph.prototype.getNodes = function () {\n return this.nodes;\n};\n\nLGraph.prototype.getEdges = function () {\n return this.edges;\n};\n\nLGraph.prototype.getGraphManager = function () {\n return this.graphManager;\n};\n\nLGraph.prototype.getParent = function () {\n return this.parent;\n};\n\nLGraph.prototype.getLeft = function () {\n return this.left;\n};\n\nLGraph.prototype.getRight = function () {\n return this.right;\n};\n\nLGraph.prototype.getTop = function () {\n return this.top;\n};\n\nLGraph.prototype.getBottom = function () {\n return this.bottom;\n};\n\nLGraph.prototype.isConnected = function () {\n return this.isConnected;\n};\n\nLGraph.prototype.add = function (obj1, sourceNode, targetNode) {\n if (sourceNode == null && targetNode == null) {\n var newNode = obj1;\n if (this.graphManager == null) {\n throw \"Graph has no graph mgr!\";\n }\n if (this.getNodes().indexOf(newNode) > -1) {\n throw \"Node already in graph!\";\n }\n newNode.owner = this;\n this.getNodes().push(newNode);\n\n return newNode;\n } else {\n var newEdge = obj1;\n if (!(this.getNodes().indexOf(sourceNode) > -1 && this.getNodes().indexOf(targetNode) > -1)) {\n throw \"Source or target not in graph!\";\n }\n\n if (!(sourceNode.owner == targetNode.owner && sourceNode.owner == this)) {\n throw \"Both owners must be this graph!\";\n }\n\n if (sourceNode.owner != targetNode.owner) {\n return null;\n }\n\n // set source and target\n newEdge.source = sourceNode;\n newEdge.target = targetNode;\n\n // set as intra-graph edge\n newEdge.isInterGraph = false;\n\n // add to graph edge list\n this.getEdges().push(newEdge);\n\n // add to incidency lists\n sourceNode.edges.push(newEdge);\n\n if (targetNode != sourceNode) {\n targetNode.edges.push(newEdge);\n }\n\n return newEdge;\n }\n};\n\nLGraph.prototype.remove = function (obj) {\n var node = obj;\n if (obj instanceof LNode) {\n if (node == null) {\n throw \"Node is null!\";\n }\n if (!(node.owner != null && node.owner == this)) {\n throw \"Owner graph is invalid!\";\n }\n if (this.graphManager == null) {\n throw \"Owner graph manager is invalid!\";\n }\n // remove incident edges first (make a copy to do it safely)\n var edgesToBeRemoved = node.edges.slice();\n var edge;\n var s = edgesToBeRemoved.length;\n for (var i = 0; i < s; i++) {\n edge = edgesToBeRemoved[i];\n\n if (edge.isInterGraph) {\n this.graphManager.remove(edge);\n } else {\n edge.source.owner.remove(edge);\n }\n }\n\n // now the node itself\n var index = this.nodes.indexOf(node);\n if (index == -1) {\n throw \"Node not in owner node list!\";\n }\n\n this.nodes.splice(index, 1);\n } else if (obj instanceof LEdge) {\n var edge = obj;\n if (edge == null) {\n throw \"Edge is null!\";\n }\n if (!(edge.source != null && edge.target != null)) {\n throw \"Source and/or target is null!\";\n }\n if (!(edge.source.owner != null && edge.target.owner != null && edge.source.owner == this && edge.target.owner == this)) {\n throw \"Source and/or target owner is invalid!\";\n }\n\n var sourceIndex = edge.source.edges.indexOf(edge);\n var targetIndex = edge.target.edges.indexOf(edge);\n if (!(sourceIndex > -1 && targetIndex > -1)) {\n throw \"Source and/or target doesn't know this edge!\";\n }\n\n edge.source.edges.splice(sourceIndex, 1);\n\n if (edge.target != edge.source) {\n edge.target.edges.splice(targetIndex, 1);\n }\n\n var index = edge.source.owner.getEdges().indexOf(edge);\n if (index == -1) {\n throw \"Not in owner's edge list!\";\n }\n\n edge.source.owner.getEdges().splice(index, 1);\n }\n};\n\nLGraph.prototype.updateLeftTop = function () {\n var top = Integer.MAX_VALUE;\n var left = Integer.MAX_VALUE;\n var nodeTop;\n var nodeLeft;\n var margin;\n\n var nodes = this.getNodes();\n var s = nodes.length;\n\n for (var i = 0; i < s; i++) {\n var lNode = nodes[i];\n nodeTop = lNode.getTop();\n nodeLeft = lNode.getLeft();\n\n if (top > nodeTop) {\n top = nodeTop;\n }\n\n if (left > nodeLeft) {\n left = nodeLeft;\n }\n }\n\n // Do we have any nodes in this graph?\n if (top == Integer.MAX_VALUE) {\n return null;\n }\n\n if (nodes[0].getParent().paddingLeft != undefined) {\n margin = nodes[0].getParent().paddingLeft;\n } else {\n margin = this.margin;\n }\n\n this.left = left - margin;\n this.top = top - margin;\n\n // Apply the margins and return the result\n return new Point(this.left, this.top);\n};\n\nLGraph.prototype.updateBounds = function (recursive) {\n // calculate bounds\n var left = Integer.MAX_VALUE;\n var right = -Integer.MAX_VALUE;\n var top = Integer.MAX_VALUE;\n var bottom = -Integer.MAX_VALUE;\n var nodeLeft;\n var nodeRight;\n var nodeTop;\n var nodeBottom;\n var margin;\n\n var nodes = this.nodes;\n var s = nodes.length;\n for (var i = 0; i < s; i++) {\n var lNode = nodes[i];\n\n if (recursive && lNode.child != null) {\n lNode.updateBounds();\n }\n nodeLeft = lNode.getLeft();\n nodeRight = lNode.getRight();\n nodeTop = lNode.getTop();\n nodeBottom = lNode.getBottom();\n\n if (left > nodeLeft) {\n left = nodeLeft;\n }\n\n if (right < nodeRight) {\n right = nodeRight;\n }\n\n if (top > nodeTop) {\n top = nodeTop;\n }\n\n if (bottom < nodeBottom) {\n bottom = nodeBottom;\n }\n }\n\n var boundingRect = new RectangleD(left, top, right - left, bottom - top);\n if (left == Integer.MAX_VALUE) {\n this.left = this.parent.getLeft();\n this.right = this.parent.getRight();\n this.top = this.parent.getTop();\n this.bottom = this.parent.getBottom();\n }\n\n if (nodes[0].getParent().paddingLeft != undefined) {\n margin = nodes[0].getParent().paddingLeft;\n } else {\n margin = this.margin;\n }\n\n this.left = boundingRect.x - margin;\n this.right = boundingRect.x + boundingRect.width + margin;\n this.top = boundingRect.y - margin;\n this.bottom = boundingRect.y + boundingRect.height + margin;\n};\n\nLGraph.calculateBounds = function (nodes) {\n var left = Integer.MAX_VALUE;\n var right = -Integer.MAX_VALUE;\n var top = Integer.MAX_VALUE;\n var bottom = -Integer.MAX_VALUE;\n var nodeLeft;\n var nodeRight;\n var nodeTop;\n var nodeBottom;\n\n var s = nodes.length;\n\n for (var i = 0; i < s; i++) {\n var lNode = nodes[i];\n nodeLeft = lNode.getLeft();\n nodeRight = lNode.getRight();\n nodeTop = lNode.getTop();\n nodeBottom = lNode.getBottom();\n\n if (left > nodeLeft) {\n left = nodeLeft;\n }\n\n if (right < nodeRight) {\n right = nodeRight;\n }\n\n if (top > nodeTop) {\n top = nodeTop;\n }\n\n if (bottom < nodeBottom) {\n bottom = nodeBottom;\n }\n }\n\n var boundingRect = new RectangleD(left, top, right - left, bottom - top);\n\n return boundingRect;\n};\n\nLGraph.prototype.getInclusionTreeDepth = function () {\n if (this == this.graphManager.getRoot()) {\n return 1;\n } else {\n return this.parent.getInclusionTreeDepth();\n }\n};\n\nLGraph.prototype.getEstimatedSize = function () {\n if (this.estimatedSize == Integer.MIN_VALUE) {\n throw \"assert failed\";\n }\n return this.estimatedSize;\n};\n\nLGraph.prototype.calcEstimatedSize = function () {\n var size = 0;\n var nodes = this.nodes;\n var s = nodes.length;\n\n for (var i = 0; i < s; i++) {\n var lNode = nodes[i];\n size += lNode.calcEstimatedSize();\n }\n\n if (size == 0) {\n this.estimatedSize = LayoutConstants.EMPTY_COMPOUND_NODE_SIZE;\n } else {\n this.estimatedSize = size / Math.sqrt(this.nodes.length);\n }\n\n return this.estimatedSize;\n};\n\nLGraph.prototype.updateConnected = function () {\n var self = this;\n if (this.nodes.length == 0) {\n this.isConnected = true;\n return;\n }\n\n var queue = new LinkedList();\n var visited = new Set();\n var currentNode = this.nodes[0];\n var neighborEdges;\n var currentNeighbor;\n var childrenOfNode = currentNode.withChildren();\n childrenOfNode.forEach(function (node) {\n queue.push(node);\n visited.add(node);\n });\n\n while (queue.length !== 0) {\n currentNode = queue.shift();\n\n // Traverse all neighbors of this node\n neighborEdges = currentNode.getEdges();\n var size = neighborEdges.length;\n for (var i = 0; i < size; i++) {\n var neighborEdge = neighborEdges[i];\n currentNeighbor = neighborEdge.getOtherEndInGraph(currentNode, this);\n\n // Add unvisited neighbors to the list to visit\n if (currentNeighbor != null && !visited.has(currentNeighbor)) {\n var childrenOfNeighbor = currentNeighbor.withChildren();\n\n childrenOfNeighbor.forEach(function (node) {\n queue.push(node);\n visited.add(node);\n });\n }\n }\n }\n\n this.isConnected = false;\n\n if (visited.size >= this.nodes.length) {\n var noOfVisitedInThisGraph = 0;\n\n visited.forEach(function (visitedNode) {\n if (visitedNode.owner == self) {\n noOfVisitedInThisGraph++;\n }\n });\n\n if (noOfVisitedInThisGraph == this.nodes.length) {\n this.isConnected = true;\n }\n }\n};\n\nmodule.exports = LGraph;\n\n/***/ }),\n/* 7 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar LGraph;\nvar LEdge = __webpack_require__(1);\n\nfunction LGraphManager(layout) {\n LGraph = __webpack_require__(6); // It may be better to initilize this out of this function but it gives an error (Right-hand side of 'instanceof' is not callable) now.\n this.layout = layout;\n\n this.graphs = [];\n this.edges = [];\n}\n\nLGraphManager.prototype.addRoot = function () {\n var ngraph = this.layout.newGraph();\n var nnode = this.layout.newNode(null);\n var root = this.add(ngraph, nnode);\n this.setRootGraph(root);\n return this.rootGraph;\n};\n\nLGraphManager.prototype.add = function (newGraph, parentNode, newEdge, sourceNode, targetNode) {\n //there are just 2 parameters are passed then it adds an LGraph else it adds an LEdge\n if (newEdge == null && sourceNode == null && targetNode == null) {\n if (newGraph == null) {\n throw \"Graph is null!\";\n }\n if (parentNode == null) {\n throw \"Parent node is null!\";\n }\n if (this.graphs.indexOf(newGraph) > -1) {\n throw \"Graph already in this graph mgr!\";\n }\n\n this.graphs.push(newGraph);\n\n if (newGraph.parent != null) {\n throw \"Already has a parent!\";\n }\n if (parentNode.child != null) {\n throw \"Already has a child!\";\n }\n\n newGraph.parent = parentNode;\n parentNode.child = newGraph;\n\n return newGraph;\n } else {\n //change the order of the parameters\n targetNode = newEdge;\n sourceNode = parentNode;\n newEdge = newGraph;\n var sourceGraph = sourceNode.getOwner();\n var targetGraph = targetNode.getOwner();\n\n if (!(sourceGraph != null && sourceGraph.getGraphManager() == this)) {\n throw \"Source not in this graph mgr!\";\n }\n if (!(targetGraph != null && targetGraph.getGraphManager() == this)) {\n throw \"Target not in this graph mgr!\";\n }\n\n if (sourceGraph == targetGraph) {\n newEdge.isInterGraph = false;\n return sourceGraph.add(newEdge, sourceNode, targetNode);\n } else {\n newEdge.isInterGraph = true;\n\n // set source and target\n newEdge.source = sourceNode;\n newEdge.target = targetNode;\n\n // add edge to inter-graph edge list\n if (this.edges.indexOf(newEdge) > -1) {\n throw \"Edge already in inter-graph edge list!\";\n }\n\n this.edges.push(newEdge);\n\n // add edge to source and target incidency lists\n if (!(newEdge.source != null && newEdge.target != null)) {\n throw \"Edge source and/or target is null!\";\n }\n\n if (!(newEdge.source.edges.indexOf(newEdge) == -1 && newEdge.target.edges.indexOf(newEdge) == -1)) {\n throw \"Edge already in source and/or target incidency list!\";\n }\n\n newEdge.source.edges.push(newEdge);\n newEdge.target.edges.push(newEdge);\n\n return newEdge;\n }\n }\n};\n\nLGraphManager.prototype.remove = function (lObj) {\n if (lObj instanceof LGraph) {\n var graph = lObj;\n if (graph.getGraphManager() != this) {\n throw \"Graph not in this graph mgr\";\n }\n if (!(graph == this.rootGraph || graph.parent != null && graph.parent.graphManager == this)) {\n throw \"Invalid parent node!\";\n }\n\n // first the edges (make a copy to do it safely)\n var edgesToBeRemoved = [];\n\n edgesToBeRemoved = edgesToBeRemoved.concat(graph.getEdges());\n\n var edge;\n var s = edgesToBeRemoved.length;\n for (var i = 0; i < s; i++) {\n edge = edgesToBeRemoved[i];\n graph.remove(edge);\n }\n\n // then the nodes (make a copy to do it safely)\n var nodesToBeRemoved = [];\n\n nodesToBeRemoved = nodesToBeRemoved.concat(graph.getNodes());\n\n var node;\n s = nodesToBeRemoved.length;\n for (var i = 0; i < s; i++) {\n node = nodesToBeRemoved[i];\n graph.remove(node);\n }\n\n // check if graph is the root\n if (graph == this.rootGraph) {\n this.setRootGraph(null);\n }\n\n // now remove the graph itself\n var index = this.graphs.indexOf(graph);\n this.graphs.splice(index, 1);\n\n // also reset the parent of the graph\n graph.parent = null;\n } else if (lObj instanceof LEdge) {\n edge = lObj;\n if (edge == null) {\n throw \"Edge is null!\";\n }\n if (!edge.isInterGraph) {\n throw \"Not an inter-graph edge!\";\n }\n if (!(edge.source != null && edge.target != null)) {\n throw \"Source and/or target is null!\";\n }\n\n // remove edge from source and target nodes' incidency lists\n\n if (!(edge.source.edges.indexOf(edge) != -1 && edge.target.edges.indexOf(edge) != -1)) {\n throw \"Source and/or target doesn't know this edge!\";\n }\n\n var index = edge.source.edges.indexOf(edge);\n edge.source.edges.splice(index, 1);\n index = edge.target.edges.indexOf(edge);\n edge.target.edges.splice(index, 1);\n\n // remove edge from owner graph manager's inter-graph edge list\n\n if (!(edge.source.owner != null && edge.source.owner.getGraphManager() != null)) {\n throw \"Edge owner graph or owner graph manager is null!\";\n }\n if (edge.source.owner.getGraphManager().edges.indexOf(edge) == -1) {\n throw \"Not in owner graph manager's edge list!\";\n }\n\n var index = edge.source.owner.getGraphManager().edges.indexOf(edge);\n edge.source.owner.getGraphManager().edges.splice(index, 1);\n }\n};\n\nLGraphManager.prototype.updateBounds = function () {\n this.rootGraph.updateBounds(true);\n};\n\nLGraphManager.prototype.getGraphs = function () {\n return this.graphs;\n};\n\nLGraphManager.prototype.getAllNodes = function () {\n if (this.allNodes == null) {\n var nodeList = [];\n var graphs = this.getGraphs();\n var s = graphs.length;\n for (var i = 0; i < s; i++) {\n nodeList = nodeList.concat(graphs[i].getNodes());\n }\n this.allNodes = nodeList;\n }\n return this.allNodes;\n};\n\nLGraphManager.prototype.resetAllNodes = function () {\n this.allNodes = null;\n};\n\nLGraphManager.prototype.resetAllEdges = function () {\n this.allEdges = null;\n};\n\nLGraphManager.prototype.resetAllNodesToApplyGravitation = function () {\n this.allNodesToApplyGravitation = null;\n};\n\nLGraphManager.prototype.getAllEdges = function () {\n if (this.allEdges == null) {\n var edgeList = [];\n var graphs = this.getGraphs();\n var s = graphs.length;\n for (var i = 0; i < graphs.length; i++) {\n edgeList = edgeList.concat(graphs[i].getEdges());\n }\n\n edgeList = edgeList.concat(this.edges);\n\n this.allEdges = edgeList;\n }\n return this.allEdges;\n};\n\nLGraphManager.prototype.getAllNodesToApplyGravitation = function () {\n return this.allNodesToApplyGravitation;\n};\n\nLGraphManager.prototype.setAllNodesToApplyGravitation = function (nodeList) {\n if (this.allNodesToApplyGravitation != null) {\n throw \"assert failed\";\n }\n\n this.allNodesToApplyGravitation = nodeList;\n};\n\nLGraphManager.prototype.getRoot = function () {\n return this.rootGraph;\n};\n\nLGraphManager.prototype.setRootGraph = function (graph) {\n if (graph.getGraphManager() != this) {\n throw \"Root not in this graph mgr!\";\n }\n\n this.rootGraph = graph;\n // root graph must have a root node associated with it for convenience\n if (graph.parent == null) {\n graph.parent = this.layout.newNode(\"Root node\");\n }\n};\n\nLGraphManager.prototype.getLayout = function () {\n return this.layout;\n};\n\nLGraphManager.prototype.isOneAncestorOfOther = function (firstNode, secondNode) {\n if (!(firstNode != null && secondNode != null)) {\n throw \"assert failed\";\n }\n\n if (firstNode == secondNode) {\n return true;\n }\n // Is second node an ancestor of the first one?\n var ownerGraph = firstNode.getOwner();\n var parentNode;\n\n do {\n parentNode = ownerGraph.getParent();\n\n if (parentNode == null) {\n break;\n }\n\n if (parentNode == secondNode) {\n return true;\n }\n\n ownerGraph = parentNode.getOwner();\n if (ownerGraph == null) {\n break;\n }\n } while (true);\n // Is first node an ancestor of the second one?\n ownerGraph = secondNode.getOwner();\n\n do {\n parentNode = ownerGraph.getParent();\n\n if (parentNode == null) {\n break;\n }\n\n if (parentNode == firstNode) {\n return true;\n }\n\n ownerGraph = parentNode.getOwner();\n if (ownerGraph == null) {\n break;\n }\n } while (true);\n\n return false;\n};\n\nLGraphManager.prototype.calcLowestCommonAncestors = function () {\n var edge;\n var sourceNode;\n var targetNode;\n var sourceAncestorGraph;\n var targetAncestorGraph;\n\n var edges = this.getAllEdges();\n var s = edges.length;\n for (var i = 0; i < s; i++) {\n edge = edges[i];\n\n sourceNode = edge.source;\n targetNode = edge.target;\n edge.lca = null;\n edge.sourceInLca = sourceNode;\n edge.targetInLca = targetNode;\n\n if (sourceNode == targetNode) {\n edge.lca = sourceNode.getOwner();\n continue;\n }\n\n sourceAncestorGraph = sourceNode.getOwner();\n\n while (edge.lca == null) {\n edge.targetInLca = targetNode;\n targetAncestorGraph = targetNode.getOwner();\n\n while (edge.lca == null) {\n if (targetAncestorGraph == sourceAncestorGraph) {\n edge.lca = targetAncestorGraph;\n break;\n }\n\n if (targetAncestorGraph == this.rootGraph) {\n break;\n }\n\n if (edge.lca != null) {\n throw \"assert failed\";\n }\n edge.targetInLca = targetAncestorGraph.getParent();\n targetAncestorGraph = edge.targetInLca.getOwner();\n }\n\n if (sourceAncestorGraph == this.rootGraph) {\n break;\n }\n\n if (edge.lca == null) {\n edge.sourceInLca = sourceAncestorGraph.getParent();\n sourceAncestorGraph = edge.sourceInLca.getOwner();\n }\n }\n\n if (edge.lca == null) {\n throw \"assert failed\";\n }\n }\n};\n\nLGraphManager.prototype.calcLowestCommonAncestor = function (firstNode, secondNode) {\n if (firstNode == secondNode) {\n return firstNode.getOwner();\n }\n var firstOwnerGraph = firstNode.getOwner();\n\n do {\n if (firstOwnerGraph == null) {\n break;\n }\n var secondOwnerGraph = secondNode.getOwner();\n\n do {\n if (secondOwnerGraph == null) {\n break;\n }\n\n if (secondOwnerGraph == firstOwnerGraph) {\n return secondOwnerGraph;\n }\n secondOwnerGraph = secondOwnerGraph.getParent().getOwner();\n } while (true);\n\n firstOwnerGraph = firstOwnerGraph.getParent().getOwner();\n } while (true);\n\n return firstOwnerGraph;\n};\n\nLGraphManager.prototype.calcInclusionTreeDepths = function (graph, depth) {\n if (graph == null && depth == null) {\n graph = this.rootGraph;\n depth = 1;\n }\n var node;\n\n var nodes = graph.getNodes();\n var s = nodes.length;\n for (var i = 0; i < s; i++) {\n node = nodes[i];\n node.inclusionTreeDepth = depth;\n\n if (node.child != null) {\n this.calcInclusionTreeDepths(node.child, depth + 1);\n }\n }\n};\n\nLGraphManager.prototype.includesInvalidEdge = function () {\n var edge;\n var edgesToRemove = [];\n\n var s = this.edges.length;\n for (var i = 0; i < s; i++) {\n edge = this.edges[i];\n\n if (this.isOneAncestorOfOther(edge.source, edge.target)) {\n edgesToRemove.push(edge);\n }\n }\n\n // Remove invalid edges from graph manager\n for (var i = 0; i < edgesToRemove.length; i++) {\n this.remove(edgesToRemove[i]);\n }\n\n // Invalid edges are cleared, so return false\n return false;\n};\n\nmodule.exports = LGraphManager;\n\n/***/ }),\n/* 8 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\n/**\n * This class maintains a list of static geometry related utility methods.\n *\n *\n * Copyright: i-Vis Research Group, Bilkent University, 2007 - present\n */\n\nvar Point = __webpack_require__(12);\n\nfunction IGeometry() {}\n\n/**\n * This method calculates *half* the amount in x and y directions of the two\n * input rectangles needed to separate them keeping their respective\n * positioning, and returns the result in the input array. An input\n * separation buffer added to the amount in both directions. We assume that\n * the two rectangles do intersect.\n */\nIGeometry.calcSeparationAmount = function (rectA, rectB, overlapAmount, separationBuffer) {\n if (!rectA.intersects(rectB)) {\n throw \"assert failed\";\n }\n\n var directions = new Array(2);\n\n this.decideDirectionsForOverlappingNodes(rectA, rectB, directions);\n\n overlapAmount[0] = Math.min(rectA.getRight(), rectB.getRight()) - Math.max(rectA.x, rectB.x);\n overlapAmount[1] = Math.min(rectA.getBottom(), rectB.getBottom()) - Math.max(rectA.y, rectB.y);\n\n // update the overlapping amounts for the following cases:\n if (rectA.getX() <= rectB.getX() && rectA.getRight() >= rectB.getRight()) {\n /* Case x.1:\n *\n * rectA\n * \t| |\n * \t| _________ |\n * \t| | | |\n * \t|________|_______|______|\n * \t\t\t | |\n * | |\n * rectB\n */\n overlapAmount[0] += Math.min(rectB.getX() - rectA.getX(), rectA.getRight() - rectB.getRight());\n } else if (rectB.getX() <= rectA.getX() && rectB.getRight() >= rectA.getRight()) {\n /* Case x.2:\n *\n * rectB\n * \t| |\n * \t| _________ |\n * \t| | | |\n * \t|________|_______|______|\n * \t\t\t | |\n * | |\n * rectA\n */\n overlapAmount[0] += Math.min(rectA.getX() - rectB.getX(), rectB.getRight() - rectA.getRight());\n }\n if (rectA.getY() <= rectB.getY() && rectA.getBottom() >= rectB.getBottom()) {\n /* Case y.1:\n * ________ rectA\n * |\n * |\n * ______|____ rectB\n * | |\n * | |\n * ______|____|\n * |\n * |\n * |________\n *\n */\n overlapAmount[1] += Math.min(rectB.getY() - rectA.getY(), rectA.getBottom() - rectB.getBottom());\n } else if (rectB.getY() <= rectA.getY() && rectB.getBottom() >= rectA.getBottom()) {\n /* Case y.2:\n * ________ rectB\n * |\n * |\n * ______|____ rectA\n * | |\n * | |\n * ______|____|\n * |\n * |\n * |________\n *\n */\n overlapAmount[1] += Math.min(rectA.getY() - rectB.getY(), rectB.getBottom() - rectA.getBottom());\n }\n\n // find slope of the line passes two centers\n var slope = Math.abs((rectB.getCenterY() - rectA.getCenterY()) / (rectB.getCenterX() - rectA.getCenterX()));\n // if centers are overlapped\n if (rectB.getCenterY() === rectA.getCenterY() && rectB.getCenterX() === rectA.getCenterX()) {\n // assume the slope is 1 (45 degree)\n slope = 1.0;\n }\n\n var moveByY = slope * overlapAmount[0];\n var moveByX = overlapAmount[1] / slope;\n if (overlapAmount[0] < moveByX) {\n moveByX = overlapAmount[0];\n } else {\n moveByY = overlapAmount[1];\n }\n // return half the amount so that if each rectangle is moved by these\n // amounts in opposite directions, overlap will be resolved\n overlapAmount[0] = -1 * directions[0] * (moveByX / 2 + separationBuffer);\n overlapAmount[1] = -1 * directions[1] * (moveByY / 2 + separationBuffer);\n};\n\n/**\n * This method decides the separation direction of overlapping nodes\n *\n * if directions[0] = -1, then rectA goes left\n * if directions[0] = 1, then rectA goes right\n * if directions[1] = -1, then rectA goes up\n * if directions[1] = 1, then rectA goes down\n */\nIGeometry.decideDirectionsForOverlappingNodes = function (rectA, rectB, directions) {\n if (rectA.getCenterX() < rectB.getCenterX()) {\n directions[0] = -1;\n } else {\n directions[0] = 1;\n }\n\n if (rectA.getCenterY() < rectB.getCenterY()) {\n directions[1] = -1;\n } else {\n directions[1] = 1;\n }\n};\n\n/**\n * This method calculates the intersection (clipping) points of the two\n * input rectangles with line segment defined by the centers of these two\n * rectangles. The clipping points are saved in the input double array and\n * whether or not the two rectangles overlap is returned.\n */\nIGeometry.getIntersection2 = function (rectA, rectB, result) {\n //result[0-1] will contain clipPoint of rectA, result[2-3] will contain clipPoint of rectB\n var p1x = rectA.getCenterX();\n var p1y = rectA.getCenterY();\n var p2x = rectB.getCenterX();\n var p2y = rectB.getCenterY();\n\n //if two rectangles intersect, then clipping points are centers\n if (rectA.intersects(rectB)) {\n result[0] = p1x;\n result[1] = p1y;\n result[2] = p2x;\n result[3] = p2y;\n return true;\n }\n //variables for rectA\n var topLeftAx = rectA.getX();\n var topLeftAy = rectA.getY();\n var topRightAx = rectA.getRight();\n var bottomLeftAx = rectA.getX();\n var bottomLeftAy = rectA.getBottom();\n var bottomRightAx = rectA.getRight();\n var halfWidthA = rectA.getWidthHalf();\n var halfHeightA = rectA.getHeightHalf();\n //variables for rectB\n var topLeftBx = rectB.getX();\n var topLeftBy = rectB.getY();\n var topRightBx = rectB.getRight();\n var bottomLeftBx = rectB.getX();\n var bottomLeftBy = rectB.getBottom();\n var bottomRightBx = rectB.getRight();\n var halfWidthB = rectB.getWidthHalf();\n var halfHeightB = rectB.getHeightHalf();\n\n //flag whether clipping points are found\n var clipPointAFound = false;\n var clipPointBFound = false;\n\n // line is vertical\n if (p1x === p2x) {\n if (p1y > p2y) {\n result[0] = p1x;\n result[1] = topLeftAy;\n result[2] = p2x;\n result[3] = bottomLeftBy;\n return false;\n } else if (p1y < p2y) {\n result[0] = p1x;\n result[1] = bottomLeftAy;\n result[2] = p2x;\n result[3] = topLeftBy;\n return false;\n } else {\n //not line, return null;\n }\n }\n // line is horizontal\n else if (p1y === p2y) {\n if (p1x > p2x) {\n result[0] = topLeftAx;\n result[1] = p1y;\n result[2] = topRightBx;\n result[3] = p2y;\n return false;\n } else if (p1x < p2x) {\n result[0] = topRightAx;\n result[1] = p1y;\n result[2] = topLeftBx;\n result[3] = p2y;\n return false;\n } else {\n //not valid line, return null;\n }\n } else {\n //slopes of rectA's and rectB's diagonals\n var slopeA = rectA.height / rectA.width;\n var slopeB = rectB.height / rectB.width;\n\n //slope of line between center of rectA and center of rectB\n var slopePrime = (p2y - p1y) / (p2x - p1x);\n var cardinalDirectionA = void 0;\n var cardinalDirectionB = void 0;\n var tempPointAx = void 0;\n var tempPointAy = void 0;\n var tempPointBx = void 0;\n var tempPointBy = void 0;\n\n //determine whether clipping point is the corner of nodeA\n if (-slopeA === slopePrime) {\n if (p1x > p2x) {\n result[0] = bottomLeftAx;\n result[1] = bottomLeftAy;\n clipPointAFound = true;\n } else {\n result[0] = topRightAx;\n result[1] = topLeftAy;\n clipPointAFound = true;\n }\n } else if (slopeA === slopePrime) {\n if (p1x > p2x) {\n result[0] = topLeftAx;\n result[1] = topLeftAy;\n clipPointAFound = true;\n } else {\n result[0] = bottomRightAx;\n result[1] = bottomLeftAy;\n clipPointAFound = true;\n }\n }\n\n //determine whether clipping point is the corner of nodeB\n if (-slopeB === slopePrime) {\n if (p2x > p1x) {\n result[2] = bottomLeftBx;\n result[3] = bottomLeftBy;\n clipPointBFound = true;\n } else {\n result[2] = topRightBx;\n result[3] = topLeftBy;\n clipPointBFound = true;\n }\n } else if (slopeB === slopePrime) {\n if (p2x > p1x) {\n result[2] = topLeftBx;\n result[3] = topLeftBy;\n clipPointBFound = true;\n } else {\n result[2] = bottomRightBx;\n result[3] = bottomLeftBy;\n clipPointBFound = true;\n }\n }\n\n //if both clipping points are corners\n if (clipPointAFound && clipPointBFound) {\n return false;\n }\n\n //determine Cardinal Direction of rectangles\n if (p1x > p2x) {\n if (p1y > p2y) {\n cardinalDirectionA = this.getCardinalDirection(slopeA, slopePrime, 4);\n cardinalDirectionB = this.getCardinalDirection(slopeB, slopePrime, 2);\n } else {\n cardinalDirectionA = this.getCardinalDirection(-slopeA, slopePrime, 3);\n cardinalDirectionB = this.getCardinalDirection(-slopeB, slopePrime, 1);\n }\n } else {\n if (p1y > p2y) {\n cardinalDirectionA = this.getCardinalDirection(-slopeA, slopePrime, 1);\n cardinalDirectionB = this.getCardinalDirection(-slopeB, slopePrime, 3);\n } else {\n cardinalDirectionA = this.getCardinalDirection(slopeA, slopePrime, 2);\n cardinalDirectionB = this.getCardinalDirection(slopeB, slopePrime, 4);\n }\n }\n //calculate clipping Point if it is not found before\n if (!clipPointAFound) {\n switch (cardinalDirectionA) {\n case 1:\n tempPointAy = topLeftAy;\n tempPointAx = p1x + -halfHeightA / slopePrime;\n result[0] = tempPointAx;\n result[1] = tempPointAy;\n break;\n case 2:\n tempPointAx = bottomRightAx;\n tempPointAy = p1y + halfWidthA * slopePrime;\n result[0] = tempPointAx;\n result[1] = tempPointAy;\n break;\n case 3:\n tempPointAy = bottomLeftAy;\n tempPointAx = p1x + halfHeightA / slopePrime;\n result[0] = tempPointAx;\n result[1] = tempPointAy;\n break;\n case 4:\n tempPointAx = bottomLeftAx;\n tempPointAy = p1y + -halfWidthA * slopePrime;\n result[0] = tempPointAx;\n result[1] = tempPointAy;\n break;\n }\n }\n if (!clipPointBFound) {\n switch (cardinalDirectionB) {\n case 1:\n tempPointBy = topLeftBy;\n tempPointBx = p2x + -halfHeightB / slopePrime;\n result[2] = tempPointBx;\n result[3] = tempPointBy;\n break;\n case 2:\n tempPointBx = bottomRightBx;\n tempPointBy = p2y + halfWidthB * slopePrime;\n result[2] = tempPointBx;\n result[3] = tempPointBy;\n break;\n case 3:\n tempPointBy = bottomLeftBy;\n tempPointBx = p2x + halfHeightB / slopePrime;\n result[2] = tempPointBx;\n result[3] = tempPointBy;\n break;\n case 4:\n tempPointBx = bottomLeftBx;\n tempPointBy = p2y + -halfWidthB * slopePrime;\n result[2] = tempPointBx;\n result[3] = tempPointBy;\n break;\n }\n }\n }\n return false;\n};\n\n/**\n * This method returns in which cardinal direction does input point stays\n * 1: North\n * 2: East\n * 3: South\n * 4: West\n */\nIGeometry.getCardinalDirection = function (slope, slopePrime, line) {\n if (slope > slopePrime) {\n return line;\n } else {\n return 1 + line % 4;\n }\n};\n\n/**\n * This method calculates the intersection of the two lines defined by\n * point pairs (s1,s2) and (f1,f2).\n */\nIGeometry.getIntersection = function (s1, s2, f1, f2) {\n if (f2 == null) {\n return this.getIntersection2(s1, s2, f1);\n }\n\n var x1 = s1.x;\n var y1 = s1.y;\n var x2 = s2.x;\n var y2 = s2.y;\n var x3 = f1.x;\n var y3 = f1.y;\n var x4 = f2.x;\n var y4 = f2.y;\n var x = void 0,\n y = void 0; // intersection point\n var a1 = void 0,\n a2 = void 0,\n b1 = void 0,\n b2 = void 0,\n c1 = void 0,\n c2 = void 0; // coefficients of line eqns.\n var denom = void 0;\n\n a1 = y2 - y1;\n b1 = x1 - x2;\n c1 = x2 * y1 - x1 * y2; // { a1*x + b1*y + c1 = 0 is line 1 }\n\n a2 = y4 - y3;\n b2 = x3 - x4;\n c2 = x4 * y3 - x3 * y4; // { a2*x + b2*y + c2 = 0 is line 2 }\n\n denom = a1 * b2 - a2 * b1;\n\n if (denom === 0) {\n return null;\n }\n\n x = (b1 * c2 - b2 * c1) / denom;\n y = (a2 * c1 - a1 * c2) / denom;\n\n return new Point(x, y);\n};\n\n/**\n * This method finds and returns the angle of the vector from the + x-axis\n * in clockwise direction (compatible w/ Java coordinate system!).\n */\nIGeometry.angleOfVector = function (Cx, Cy, Nx, Ny) {\n var C_angle = void 0;\n\n if (Cx !== Nx) {\n C_angle = Math.atan((Ny - Cy) / (Nx - Cx));\n\n if (Nx < Cx) {\n C_angle += Math.PI;\n } else if (Ny < Cy) {\n C_angle += this.TWO_PI;\n }\n } else if (Ny < Cy) {\n C_angle = this.ONE_AND_HALF_PI; // 270 degrees\n } else {\n C_angle = this.HALF_PI; // 90 degrees\n }\n\n return C_angle;\n};\n\n/**\n * This method checks whether the given two line segments (one with point\n * p1 and p2, the other with point p3 and p4) intersect at a point other\n * than these points.\n */\nIGeometry.doIntersect = function (p1, p2, p3, p4) {\n var a = p1.x;\n var b = p1.y;\n var c = p2.x;\n var d = p2.y;\n var p = p3.x;\n var q = p3.y;\n var r = p4.x;\n var s = p4.y;\n var det = (c - a) * (s - q) - (r - p) * (d - b);\n\n if (det === 0) {\n return false;\n } else {\n var lambda = ((s - q) * (r - a) + (p - r) * (s - b)) / det;\n var gamma = ((b - d) * (r - a) + (c - a) * (s - b)) / det;\n return 0 < lambda && lambda < 1 && 0 < gamma && gamma < 1;\n }\n};\n\n/**\n * This method checks and calculates the intersection of \n * a line segment and a circle.\n */\nIGeometry.findCircleLineIntersections = function (Ex, Ey, Lx, Ly, Cx, Cy, r) {\n\n // E is the starting point of the ray,\n // L is the end point of the ray,\n // C is the center of sphere you're testing against\n // r is the radius of that sphere\n\n // Compute:\n // d = L - E ( Direction vector of ray, from start to end )\n // f = E - C ( Vector from center sphere to ray start )\n\n // Then the intersection is found by..\n // P = E + t * d\n // This is a parametric equation:\n // Px = Ex + tdx\n // Py = Ey + tdy\n\n // get a, b, c values\n var a = (Lx - Ex) * (Lx - Ex) + (Ly - Ey) * (Ly - Ey);\n var b = 2 * ((Ex - Cx) * (Lx - Ex) + (Ey - Cy) * (Ly - Ey));\n var c = (Ex - Cx) * (Ex - Cx) + (Ey - Cy) * (Ey - Cy) - r * r;\n\n // get discriminant\n var disc = b * b - 4 * a * c;\n if (disc >= 0) {\n // insert into quadratic formula\n var t1 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);\n var t2 = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a);\n var intersections = null;\n if (t1 >= 0 && t1 <= 1) {\n // t1 is the intersection, and it's closer than t2\n // (since t1 uses -b - discriminant)\n // Impale, Poke\n return [t1];\n }\n\n // here t1 didn't intersect so we are either started\n // inside the sphere or completely past it\n if (t2 >= 0 && t2 <= 1) {\n // ExitWound\n return [t2];\n }\n\n return intersections;\n } else return null;\n};\n\n// -----------------------------------------------------------------------------\n// Section: Class Constants\n// -----------------------------------------------------------------------------\n/**\n * Some useful pre-calculated constants\n */\nIGeometry.HALF_PI = 0.5 * Math.PI;\nIGeometry.ONE_AND_HALF_PI = 1.5 * Math.PI;\nIGeometry.TWO_PI = 2.0 * Math.PI;\nIGeometry.THREE_PI = 3.0 * Math.PI;\n\nmodule.exports = IGeometry;\n\n/***/ }),\n/* 9 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction IMath() {}\n\n/**\n * This method returns the sign of the input value.\n */\nIMath.sign = function (value) {\n if (value > 0) {\n return 1;\n } else if (value < 0) {\n return -1;\n } else {\n return 0;\n }\n};\n\nIMath.floor = function (value) {\n return value < 0 ? Math.ceil(value) : Math.floor(value);\n};\n\nIMath.ceil = function (value) {\n return value < 0 ? Math.floor(value) : Math.ceil(value);\n};\n\nmodule.exports = IMath;\n\n/***/ }),\n/* 10 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction Integer() {}\n\nInteger.MAX_VALUE = 2147483647;\nInteger.MIN_VALUE = -2147483648;\n\nmodule.exports = Integer;\n\n/***/ }),\n/* 11 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar nodeFrom = function nodeFrom(value) {\n return { value: value, next: null, prev: null };\n};\n\nvar add = function add(prev, node, next, list) {\n if (prev !== null) {\n prev.next = node;\n } else {\n list.head = node;\n }\n\n if (next !== null) {\n next.prev = node;\n } else {\n list.tail = node;\n }\n\n node.prev = prev;\n node.next = next;\n\n list.length++;\n\n return node;\n};\n\nvar _remove = function _remove(node, list) {\n var prev = node.prev,\n next = node.next;\n\n\n if (prev !== null) {\n prev.next = next;\n } else {\n list.head = next;\n }\n\n if (next !== null) {\n next.prev = prev;\n } else {\n list.tail = prev;\n }\n\n node.prev = node.next = null;\n\n list.length--;\n\n return node;\n};\n\nvar LinkedList = function () {\n function LinkedList(vals) {\n var _this = this;\n\n _classCallCheck(this, LinkedList);\n\n this.length = 0;\n this.head = null;\n this.tail = null;\n\n if (vals != null) {\n vals.forEach(function (v) {\n return _this.push(v);\n });\n }\n }\n\n _createClass(LinkedList, [{\n key: \"size\",\n value: function size() {\n return this.length;\n }\n }, {\n key: \"insertBefore\",\n value: function insertBefore(val, otherNode) {\n return add(otherNode.prev, nodeFrom(val), otherNode, this);\n }\n }, {\n key: \"insertAfter\",\n value: function insertAfter(val, otherNode) {\n return add(otherNode, nodeFrom(val), otherNode.next, this);\n }\n }, {\n key: \"insertNodeBefore\",\n value: function insertNodeBefore(newNode, otherNode) {\n return add(otherNode.prev, newNode, otherNode, this);\n }\n }, {\n key: \"insertNodeAfter\",\n value: function insertNodeAfter(newNode, otherNode) {\n return add(otherNode, newNode, otherNode.next, this);\n }\n }, {\n key: \"push\",\n value: function push(val) {\n return add(this.tail, nodeFrom(val), null, this);\n }\n }, {\n key: \"unshift\",\n value: function unshift(val) {\n return add(null, nodeFrom(val), this.head, this);\n }\n }, {\n key: \"remove\",\n value: function remove(node) {\n return _remove(node, this);\n }\n }, {\n key: \"pop\",\n value: function pop() {\n return _remove(this.tail, this).value;\n }\n }, {\n key: \"popNode\",\n value: function popNode() {\n return _remove(this.tail, this);\n }\n }, {\n key: \"shift\",\n value: function shift() {\n return _remove(this.head, this).value;\n }\n }, {\n key: \"shiftNode\",\n value: function shiftNode() {\n return _remove(this.head, this);\n }\n }, {\n key: \"get_object_at\",\n value: function get_object_at(index) {\n if (index <= this.length()) {\n var i = 1;\n var current = this.head;\n while (i < index) {\n current = current.next;\n i++;\n }\n return current.value;\n }\n }\n }, {\n key: \"set_object_at\",\n value: function set_object_at(index, value) {\n if (index <= this.length()) {\n var i = 1;\n var current = this.head;\n while (i < index) {\n current = current.next;\n i++;\n }\n current.value = value;\n }\n }\n }]);\n\n return LinkedList;\n}();\n\nmodule.exports = LinkedList;\n\n/***/ }),\n/* 12 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\n/*\r\n *This class is the javascript implementation of the Point.java class in jdk\r\n */\nfunction Point(x, y, p) {\n this.x = null;\n this.y = null;\n if (x == null && y == null && p == null) {\n this.x = 0;\n this.y = 0;\n } else if (typeof x == 'number' && typeof y == 'number' && p == null) {\n this.x = x;\n this.y = y;\n } else if (x.constructor.name == 'Point' && y == null && p == null) {\n p = x;\n this.x = p.x;\n this.y = p.y;\n }\n}\n\nPoint.prototype.getX = function () {\n return this.x;\n};\n\nPoint.prototype.getY = function () {\n return this.y;\n};\n\nPoint.prototype.getLocation = function () {\n return new Point(this.x, this.y);\n};\n\nPoint.prototype.setLocation = function (x, y, p) {\n if (x.constructor.name == 'Point' && y == null && p == null) {\n p = x;\n this.setLocation(p.x, p.y);\n } else if (typeof x == 'number' && typeof y == 'number' && p == null) {\n //if both parameters are integer just move (x,y) location\n if (parseInt(x) == x && parseInt(y) == y) {\n this.move(x, y);\n } else {\n this.x = Math.floor(x + 0.5);\n this.y = Math.floor(y + 0.5);\n }\n }\n};\n\nPoint.prototype.move = function (x, y) {\n this.x = x;\n this.y = y;\n};\n\nPoint.prototype.translate = function (dx, dy) {\n this.x += dx;\n this.y += dy;\n};\n\nPoint.prototype.equals = function (obj) {\n if (obj.constructor.name == \"Point\") {\n var pt = obj;\n return this.x == pt.x && this.y == pt.y;\n }\n return this == obj;\n};\n\nPoint.prototype.toString = function () {\n return new Point().constructor.name + \"[x=\" + this.x + \",y=\" + this.y + \"]\";\n};\n\nmodule.exports = Point;\n\n/***/ }),\n/* 13 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction RectangleD(x, y, width, height) {\n this.x = 0;\n this.y = 0;\n this.width = 0;\n this.height = 0;\n\n if (x != null && y != null && width != null && height != null) {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n }\n}\n\nRectangleD.prototype.getX = function () {\n return this.x;\n};\n\nRectangleD.prototype.setX = function (x) {\n this.x = x;\n};\n\nRectangleD.prototype.getY = function () {\n return this.y;\n};\n\nRectangleD.prototype.setY = function (y) {\n this.y = y;\n};\n\nRectangleD.prototype.getWidth = function () {\n return this.width;\n};\n\nRectangleD.prototype.setWidth = function (width) {\n this.width = width;\n};\n\nRectangleD.prototype.getHeight = function () {\n return this.height;\n};\n\nRectangleD.prototype.setHeight = function (height) {\n this.height = height;\n};\n\nRectangleD.prototype.getRight = function () {\n return this.x + this.width;\n};\n\nRectangleD.prototype.getBottom = function () {\n return this.y + this.height;\n};\n\nRectangleD.prototype.intersects = function (a) {\n if (this.getRight() < a.x) {\n return false;\n }\n\n if (this.getBottom() < a.y) {\n return false;\n }\n\n if (a.getRight() < this.x) {\n return false;\n }\n\n if (a.getBottom() < this.y) {\n return false;\n }\n\n return true;\n};\n\nRectangleD.prototype.getCenterX = function () {\n return this.x + this.width / 2;\n};\n\nRectangleD.prototype.getMinX = function () {\n return this.getX();\n};\n\nRectangleD.prototype.getMaxX = function () {\n return this.getX() + this.width;\n};\n\nRectangleD.prototype.getCenterY = function () {\n return this.y + this.height / 2;\n};\n\nRectangleD.prototype.getMinY = function () {\n return this.getY();\n};\n\nRectangleD.prototype.getMaxY = function () {\n return this.getY() + this.height;\n};\n\nRectangleD.prototype.getWidthHalf = function () {\n return this.width / 2;\n};\n\nRectangleD.prototype.getHeightHalf = function () {\n return this.height / 2;\n};\n\nmodule.exports = RectangleD;\n\n/***/ }),\n/* 14 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nfunction UniqueIDGeneretor() {}\n\nUniqueIDGeneretor.lastID = 0;\n\nUniqueIDGeneretor.createID = function (obj) {\n if (UniqueIDGeneretor.isPrimitive(obj)) {\n return obj;\n }\n if (obj.uniqueID != null) {\n return obj.uniqueID;\n }\n obj.uniqueID = UniqueIDGeneretor.getString();\n UniqueIDGeneretor.lastID++;\n return obj.uniqueID;\n};\n\nUniqueIDGeneretor.getString = function (id) {\n if (id == null) id = UniqueIDGeneretor.lastID;\n return \"Object#\" + id + \"\";\n};\n\nUniqueIDGeneretor.isPrimitive = function (arg) {\n var type = typeof arg === \"undefined\" ? \"undefined\" : _typeof(arg);\n return arg == null || type != \"object\" && type != \"function\";\n};\n\nmodule.exports = UniqueIDGeneretor;\n\n/***/ }),\n/* 15 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }\n\nvar LayoutConstants = __webpack_require__(0);\nvar LGraphManager = __webpack_require__(7);\nvar LNode = __webpack_require__(3);\nvar LEdge = __webpack_require__(1);\nvar LGraph = __webpack_require__(6);\nvar PointD = __webpack_require__(5);\nvar Transform = __webpack_require__(17);\nvar Emitter = __webpack_require__(29);\n\nfunction Layout(isRemoteUse) {\n Emitter.call(this);\n\n //Layout Quality: 0:draft, 1:default, 2:proof\n this.layoutQuality = LayoutConstants.QUALITY;\n //Whether layout should create bendpoints as needed or not\n this.createBendsAsNeeded = LayoutConstants.DEFAULT_CREATE_BENDS_AS_NEEDED;\n //Whether layout should be incremental or not\n this.incremental = LayoutConstants.DEFAULT_INCREMENTAL;\n //Whether we animate from before to after layout node positions\n this.animationOnLayout = LayoutConstants.DEFAULT_ANIMATION_ON_LAYOUT;\n //Whether we animate the layout process or not\n this.animationDuringLayout = LayoutConstants.DEFAULT_ANIMATION_DURING_LAYOUT;\n //Number iterations that should be done between two successive animations\n this.animationPeriod = LayoutConstants.DEFAULT_ANIMATION_PERIOD;\n /**\r\n * Whether or not leaf nodes (non-compound nodes) are of uniform sizes. When\r\n * they are, both spring and repulsion forces between two leaf nodes can be\r\n * calculated without the expensive clipping point calculations, resulting\r\n * in major speed-up.\r\n */\n this.uniformLeafNodeSizes = LayoutConstants.DEFAULT_UNIFORM_LEAF_NODE_SIZES;\n /**\r\n * This is used for creation of bendpoints by using dummy nodes and edges.\r\n * Maps an LEdge to its dummy bendpoint path.\r\n */\n this.edgeToDummyNodes = new Map();\n this.graphManager = new LGraphManager(this);\n this.isLayoutFinished = false;\n this.isSubLayout = false;\n this.isRemoteUse = false;\n\n if (isRemoteUse != null) {\n this.isRemoteUse = isRemoteUse;\n }\n}\n\nLayout.RANDOM_SEED = 1;\n\nLayout.prototype = Object.create(Emitter.prototype);\n\nLayout.prototype.getGraphManager = function () {\n return this.graphManager;\n};\n\nLayout.prototype.getAllNodes = function () {\n return this.graphManager.getAllNodes();\n};\n\nLayout.prototype.getAllEdges = function () {\n return this.graphManager.getAllEdges();\n};\n\nLayout.prototype.getAllNodesToApplyGravitation = function () {\n return this.graphManager.getAllNodesToApplyGravitation();\n};\n\nLayout.prototype.newGraphManager = function () {\n var gm = new LGraphManager(this);\n this.graphManager = gm;\n return gm;\n};\n\nLayout.prototype.newGraph = function (vGraph) {\n return new LGraph(null, this.graphManager, vGraph);\n};\n\nLayout.prototype.newNode = function (vNode) {\n return new LNode(this.graphManager, vNode);\n};\n\nLayout.prototype.newEdge = function (vEdge) {\n return new LEdge(null, null, vEdge);\n};\n\nLayout.prototype.checkLayoutSuccess = function () {\n return this.graphManager.getRoot() == null || this.graphManager.getRoot().getNodes().length == 0 || this.graphManager.includesInvalidEdge();\n};\n\nLayout.prototype.runLayout = function () {\n this.isLayoutFinished = false;\n\n if (this.tilingPreLayout) {\n this.tilingPreLayout();\n }\n\n this.initParameters();\n var isLayoutSuccessfull;\n\n if (this.checkLayoutSuccess()) {\n isLayoutSuccessfull = false;\n } else {\n isLayoutSuccessfull = this.layout();\n }\n\n if (LayoutConstants.ANIMATE === 'during') {\n // If this is a 'during' layout animation. Layout is not finished yet. \n // We need to perform these in index.js when layout is really finished.\n return false;\n }\n\n if (isLayoutSuccessfull) {\n if (!this.isSubLayout) {\n this.doPostLayout();\n }\n }\n\n if (this.tilingPostLayout) {\n this.tilingPostLayout();\n }\n\n this.isLayoutFinished = true;\n\n return isLayoutSuccessfull;\n};\n\n/**\r\n * This method performs the operations required after layout.\r\n */\nLayout.prototype.doPostLayout = function () {\n //assert !isSubLayout : \"Should not be called on sub-layout!\";\n // Propagate geometric changes to v-level objects\n if (!this.incremental) {\n this.transform();\n }\n this.update();\n};\n\n/**\r\n * This method updates the geometry of the target graph according to\r\n * calculated layout.\r\n */\nLayout.prototype.update2 = function () {\n // update bend points\n if (this.createBendsAsNeeded) {\n this.createBendpointsFromDummyNodes();\n\n // reset all edges, since the topology has changed\n this.graphManager.resetAllEdges();\n }\n\n // perform edge, node and root updates if layout is not called\n // remotely\n if (!this.isRemoteUse) {\n // update all edges\n var edge;\n var allEdges = this.graphManager.getAllEdges();\n for (var i = 0; i < allEdges.length; i++) {\n edge = allEdges[i];\n // this.update(edge);\n }\n\n // recursively update nodes\n var node;\n var nodes = this.graphManager.getRoot().getNodes();\n for (var i = 0; i < nodes.length; i++) {\n node = nodes[i];\n // this.update(node);\n }\n\n // update root graph\n this.update(this.graphManager.getRoot());\n }\n};\n\nLayout.prototype.update = function (obj) {\n if (obj == null) {\n this.update2();\n } else if (obj instanceof LNode) {\n var node = obj;\n if (node.getChild() != null) {\n // since node is compound, recursively update child nodes\n var nodes = node.getChild().getNodes();\n for (var i = 0; i < nodes.length; i++) {\n update(nodes[i]);\n }\n }\n\n // if the l-level node is associated with a v-level graph object,\n // then it is assumed that the v-level node implements the\n // interface Updatable.\n if (node.vGraphObject != null) {\n // cast to Updatable without any type check\n var vNode = node.vGraphObject;\n\n // call the update method of the interface\n vNode.update(node);\n }\n } else if (obj instanceof LEdge) {\n var edge = obj;\n // if the l-level edge is associated with a v-level graph object,\n // then it is assumed that the v-level edge implements the\n // interface Updatable.\n\n if (edge.vGraphObject != null) {\n // cast to Updatable without any type check\n var vEdge = edge.vGraphObject;\n\n // call the update method of the interface\n vEdge.update(edge);\n }\n } else if (obj instanceof LGraph) {\n var graph = obj;\n // if the l-level graph is associated with a v-level graph object,\n // then it is assumed that the v-level object implements the\n // interface Updatable.\n\n if (graph.vGraphObject != null) {\n // cast to Updatable without any type check\n var vGraph = graph.vGraphObject;\n\n // call the update method of the interface\n vGraph.update(graph);\n }\n }\n};\n\n/**\r\n * This method is used to set all layout parameters to default values\r\n * determined at compile time.\r\n */\nLayout.prototype.initParameters = function () {\n if (!this.isSubLayout) {\n this.layoutQuality = LayoutConstants.QUALITY;\n this.animationDuringLayout = LayoutConstants.DEFAULT_ANIMATION_DURING_LAYOUT;\n this.animationPeriod = LayoutConstants.DEFAULT_ANIMATION_PERIOD;\n this.animationOnLayout = LayoutConstants.DEFAULT_ANIMATION_ON_LAYOUT;\n this.incremental = LayoutConstants.DEFAULT_INCREMENTAL;\n this.createBendsAsNeeded = LayoutConstants.DEFAULT_CREATE_BENDS_AS_NEEDED;\n this.uniformLeafNodeSizes = LayoutConstants.DEFAULT_UNIFORM_LEAF_NODE_SIZES;\n }\n\n if (this.animationDuringLayout) {\n this.animationOnLayout = false;\n }\n};\n\nLayout.prototype.transform = function (newLeftTop) {\n if (newLeftTop == undefined) {\n this.transform(new PointD(0, 0));\n } else {\n // create a transformation object (from Eclipse to layout). When an\n // inverse transform is applied, we get upper-left coordinate of the\n // drawing or the root graph at given input coordinate (some margins\n // already included in calculation of left-top).\n\n var trans = new Transform();\n var leftTop = this.graphManager.getRoot().updateLeftTop();\n\n if (leftTop != null) {\n trans.setWorldOrgX(newLeftTop.x);\n trans.setWorldOrgY(newLeftTop.y);\n\n trans.setDeviceOrgX(leftTop.x);\n trans.setDeviceOrgY(leftTop.y);\n\n var nodes = this.getAllNodes();\n var node;\n\n for (var i = 0; i < nodes.length; i++) {\n node = nodes[i];\n node.transform(trans);\n }\n }\n }\n};\n\nLayout.prototype.positionNodesRandomly = function (graph) {\n\n if (graph == undefined) {\n //assert !this.incremental;\n this.positionNodesRandomly(this.getGraphManager().getRoot());\n this.getGraphManager().getRoot().updateBounds(true);\n } else {\n var lNode;\n var childGraph;\n\n var nodes = graph.getNodes();\n for (var i = 0; i < nodes.length; i++) {\n lNode = nodes[i];\n childGraph = lNode.getChild();\n\n if (childGraph == null) {\n lNode.scatter();\n } else if (childGraph.getNodes().length == 0) {\n lNode.scatter();\n } else {\n this.positionNodesRandomly(childGraph);\n lNode.updateBounds();\n }\n }\n }\n};\n\n/**\r\n * This method returns a list of trees where each tree is represented as a\r\n * list of l-nodes. The method returns a list of size 0 when:\r\n * - The graph is not flat or\r\n * - One of the component(s) of the graph is not a tree.\r\n */\nLayout.prototype.getFlatForest = function () {\n var flatForest = [];\n var isForest = true;\n\n // Quick reference for all nodes in the graph manager associated with\n // this layout. The list should not be changed.\n var allNodes = this.graphManager.getRoot().getNodes();\n\n // First be sure that the graph is flat\n var isFlat = true;\n\n for (var i = 0; i < allNodes.length; i++) {\n if (allNodes[i].getChild() != null) {\n isFlat = false;\n }\n }\n\n // Return empty forest if the graph is not flat.\n if (!isFlat) {\n return flatForest;\n }\n\n // Run BFS for each component of the graph.\n\n var visited = new Set();\n var toBeVisited = [];\n var parents = new Map();\n var unProcessedNodes = [];\n\n unProcessedNodes = unProcessedNodes.concat(allNodes);\n\n // Each iteration of this loop finds a component of the graph and\n // decides whether it is a tree or not. If it is a tree, adds it to the\n // forest and continued with the next component.\n\n while (unProcessedNodes.length > 0 && isForest) {\n toBeVisited.push(unProcessedNodes[0]);\n\n // Start the BFS. Each iteration of this loop visits a node in a\n // BFS manner.\n while (toBeVisited.length > 0 && isForest) {\n //pool operation\n var currentNode = toBeVisited[0];\n toBeVisited.splice(0, 1);\n visited.add(currentNode);\n\n // Traverse all neighbors of this node\n var neighborEdges = currentNode.getEdges();\n\n for (var i = 0; i < neighborEdges.length; i++) {\n var currentNeighbor = neighborEdges[i].getOtherEnd(currentNode);\n\n // If BFS is not growing from this neighbor.\n if (parents.get(currentNode) != currentNeighbor) {\n // We haven't previously visited this neighbor.\n if (!visited.has(currentNeighbor)) {\n toBeVisited.push(currentNeighbor);\n parents.set(currentNeighbor, currentNode);\n }\n // Since we have previously visited this neighbor and\n // this neighbor is not parent of currentNode, given\n // graph contains a component that is not tree, hence\n // it is not a forest.\n else {\n isForest = false;\n break;\n }\n }\n }\n }\n\n // The graph contains a component that is not a tree. Empty\n // previously found trees. The method will end.\n if (!isForest) {\n flatForest = [];\n }\n // Save currently visited nodes as a tree in our forest. Reset\n // visited and parents lists. Continue with the next component of\n // the graph, if any.\n else {\n var temp = [].concat(_toConsumableArray(visited));\n flatForest.push(temp);\n //flatForest = flatForest.concat(temp);\n //unProcessedNodes.removeAll(visited);\n for (var i = 0; i < temp.length; i++) {\n var value = temp[i];\n var index = unProcessedNodes.indexOf(value);\n if (index > -1) {\n unProcessedNodes.splice(index, 1);\n }\n }\n visited = new Set();\n parents = new Map();\n }\n }\n\n return flatForest;\n};\n\n/**\r\n * This method creates dummy nodes (an l-level node with minimal dimensions)\r\n * for the given edge (one per bendpoint). The existing l-level structure\r\n * is updated accordingly.\r\n */\nLayout.prototype.createDummyNodesForBendpoints = function (edge) {\n var dummyNodes = [];\n var prev = edge.source;\n\n var graph = this.graphManager.calcLowestCommonAncestor(edge.source, edge.target);\n\n for (var i = 0; i < edge.bendpoints.length; i++) {\n // create new dummy node\n var dummyNode = this.newNode(null);\n dummyNode.setRect(new Point(0, 0), new Dimension(1, 1));\n\n graph.add(dummyNode);\n\n // create new dummy edge between prev and dummy node\n var dummyEdge = this.newEdge(null);\n this.graphManager.add(dummyEdge, prev, dummyNode);\n\n dummyNodes.add(dummyNode);\n prev = dummyNode;\n }\n\n var dummyEdge = this.newEdge(null);\n this.graphManager.add(dummyEdge, prev, edge.target);\n\n this.edgeToDummyNodes.set(edge, dummyNodes);\n\n // remove real edge from graph manager if it is inter-graph\n if (edge.isInterGraph()) {\n this.graphManager.remove(edge);\n }\n // else, remove the edge from the current graph\n else {\n graph.remove(edge);\n }\n\n return dummyNodes;\n};\n\n/**\r\n * This method creates bendpoints for edges from the dummy nodes\r\n * at l-level.\r\n */\nLayout.prototype.createBendpointsFromDummyNodes = function () {\n var edges = [];\n edges = edges.concat(this.graphManager.getAllEdges());\n edges = [].concat(_toConsumableArray(this.edgeToDummyNodes.keys())).concat(edges);\n\n for (var k = 0; k < edges.length; k++) {\n var lEdge = edges[k];\n\n if (lEdge.bendpoints.length > 0) {\n var path = this.edgeToDummyNodes.get(lEdge);\n\n for (var i = 0; i < path.length; i++) {\n var dummyNode = path[i];\n var p = new PointD(dummyNode.getCenterX(), dummyNode.getCenterY());\n\n // update bendpoint's location according to dummy node\n var ebp = lEdge.bendpoints.get(i);\n ebp.x = p.x;\n ebp.y = p.y;\n\n // remove the dummy node, dummy edges incident with this\n // dummy node is also removed (within the remove method)\n dummyNode.getOwner().remove(dummyNode);\n }\n\n // add the real edge to graph\n this.graphManager.add(lEdge, lEdge.source, lEdge.target);\n }\n }\n};\n\nLayout.transform = function (sliderValue, defaultValue, minDiv, maxMul) {\n if (minDiv != undefined && maxMul != undefined) {\n var value = defaultValue;\n\n if (sliderValue <= 50) {\n var minValue = defaultValue / minDiv;\n value -= (defaultValue - minValue) / 50 * (50 - sliderValue);\n } else {\n var maxValue = defaultValue * maxMul;\n value += (maxValue - defaultValue) / 50 * (sliderValue - 50);\n }\n\n return value;\n } else {\n var a, b;\n\n if (sliderValue <= 50) {\n a = 9.0 * defaultValue / 500.0;\n b = defaultValue / 10.0;\n } else {\n a = 9.0 * defaultValue / 50.0;\n b = -8 * defaultValue;\n }\n\n return a * sliderValue + b;\n }\n};\n\n/**\r\n * This method finds and returns the center of the given nodes, assuming\r\n * that the given nodes form a tree in themselves.\r\n */\nLayout.findCenterOfTree = function (nodes) {\n var list = [];\n list = list.concat(nodes);\n\n var removedNodes = [];\n var remainingDegrees = new Map();\n var foundCenter = false;\n var centerNode = null;\n\n if (list.length == 1 || list.length == 2) {\n foundCenter = true;\n centerNode = list[0];\n }\n\n for (var i = 0; i < list.length; i++) {\n var node = list[i];\n var degree = node.getNeighborsList().size;\n remainingDegrees.set(node, node.getNeighborsList().size);\n\n if (degree == 1) {\n removedNodes.push(node);\n }\n }\n\n var tempList = [];\n tempList = tempList.concat(removedNodes);\n\n while (!foundCenter) {\n var tempList2 = [];\n tempList2 = tempList2.concat(tempList);\n tempList = [];\n\n for (var i = 0; i < list.length; i++) {\n var node = list[i];\n\n var index = list.indexOf(node);\n if (index >= 0) {\n list.splice(index, 1);\n }\n\n var neighbours = node.getNeighborsList();\n\n neighbours.forEach(function (neighbour) {\n if (removedNodes.indexOf(neighbour) < 0) {\n var otherDegree = remainingDegrees.get(neighbour);\n var newDegree = otherDegree - 1;\n\n if (newDegree == 1) {\n tempList.push(neighbour);\n }\n\n remainingDegrees.set(neighbour, newDegree);\n }\n });\n }\n\n removedNodes = removedNodes.concat(tempList);\n\n if (list.length == 1 || list.length == 2) {\n foundCenter = true;\n centerNode = list[0];\n }\n }\n\n return centerNode;\n};\n\n/**\r\n * During the coarsening process, this layout may be referenced by two graph managers\r\n * this setter function grants access to change the currently being used graph manager\r\n */\nLayout.prototype.setGraphManager = function (gm) {\n this.graphManager = gm;\n};\n\nmodule.exports = Layout;\n\n/***/ }),\n/* 16 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction RandomSeed() {}\n// adapted from: https://stackoverflow.com/a/19303725\nRandomSeed.seed = 1;\nRandomSeed.x = 0;\n\nRandomSeed.nextDouble = function () {\n RandomSeed.x = Math.sin(RandomSeed.seed++) * 10000;\n return RandomSeed.x - Math.floor(RandomSeed.x);\n};\n\nmodule.exports = RandomSeed;\n\n/***/ }),\n/* 17 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar PointD = __webpack_require__(5);\n\nfunction Transform(x, y) {\n this.lworldOrgX = 0.0;\n this.lworldOrgY = 0.0;\n this.ldeviceOrgX = 0.0;\n this.ldeviceOrgY = 0.0;\n this.lworldExtX = 1.0;\n this.lworldExtY = 1.0;\n this.ldeviceExtX = 1.0;\n this.ldeviceExtY = 1.0;\n}\n\nTransform.prototype.getWorldOrgX = function () {\n return this.lworldOrgX;\n};\n\nTransform.prototype.setWorldOrgX = function (wox) {\n this.lworldOrgX = wox;\n};\n\nTransform.prototype.getWorldOrgY = function () {\n return this.lworldOrgY;\n};\n\nTransform.prototype.setWorldOrgY = function (woy) {\n this.lworldOrgY = woy;\n};\n\nTransform.prototype.getWorldExtX = function () {\n return this.lworldExtX;\n};\n\nTransform.prototype.setWorldExtX = function (wex) {\n this.lworldExtX = wex;\n};\n\nTransform.prototype.getWorldExtY = function () {\n return this.lworldExtY;\n};\n\nTransform.prototype.setWorldExtY = function (wey) {\n this.lworldExtY = wey;\n};\n\n/* Device related */\n\nTransform.prototype.getDeviceOrgX = function () {\n return this.ldeviceOrgX;\n};\n\nTransform.prototype.setDeviceOrgX = function (dox) {\n this.ldeviceOrgX = dox;\n};\n\nTransform.prototype.getDeviceOrgY = function () {\n return this.ldeviceOrgY;\n};\n\nTransform.prototype.setDeviceOrgY = function (doy) {\n this.ldeviceOrgY = doy;\n};\n\nTransform.prototype.getDeviceExtX = function () {\n return this.ldeviceExtX;\n};\n\nTransform.prototype.setDeviceExtX = function (dex) {\n this.ldeviceExtX = dex;\n};\n\nTransform.prototype.getDeviceExtY = function () {\n return this.ldeviceExtY;\n};\n\nTransform.prototype.setDeviceExtY = function (dey) {\n this.ldeviceExtY = dey;\n};\n\nTransform.prototype.transformX = function (x) {\n var xDevice = 0.0;\n var worldExtX = this.lworldExtX;\n if (worldExtX != 0.0) {\n xDevice = this.ldeviceOrgX + (x - this.lworldOrgX) * this.ldeviceExtX / worldExtX;\n }\n\n return xDevice;\n};\n\nTransform.prototype.transformY = function (y) {\n var yDevice = 0.0;\n var worldExtY = this.lworldExtY;\n if (worldExtY != 0.0) {\n yDevice = this.ldeviceOrgY + (y - this.lworldOrgY) * this.ldeviceExtY / worldExtY;\n }\n\n return yDevice;\n};\n\nTransform.prototype.inverseTransformX = function (x) {\n var xWorld = 0.0;\n var deviceExtX = this.ldeviceExtX;\n if (deviceExtX != 0.0) {\n xWorld = this.lworldOrgX + (x - this.ldeviceOrgX) * this.lworldExtX / deviceExtX;\n }\n\n return xWorld;\n};\n\nTransform.prototype.inverseTransformY = function (y) {\n var yWorld = 0.0;\n var deviceExtY = this.ldeviceExtY;\n if (deviceExtY != 0.0) {\n yWorld = this.lworldOrgY + (y - this.ldeviceOrgY) * this.lworldExtY / deviceExtY;\n }\n return yWorld;\n};\n\nTransform.prototype.inverseTransformPoint = function (inPoint) {\n var outPoint = new PointD(this.inverseTransformX(inPoint.x), this.inverseTransformY(inPoint.y));\n return outPoint;\n};\n\nmodule.exports = Transform;\n\n/***/ }),\n/* 18 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }\n\nvar Layout = __webpack_require__(15);\nvar FDLayoutConstants = __webpack_require__(4);\nvar LayoutConstants = __webpack_require__(0);\nvar IGeometry = __webpack_require__(8);\nvar IMath = __webpack_require__(9);\n\nfunction FDLayout() {\n Layout.call(this);\n\n this.useSmartIdealEdgeLengthCalculation = FDLayoutConstants.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION;\n this.gravityConstant = FDLayoutConstants.DEFAULT_GRAVITY_STRENGTH;\n this.compoundGravityConstant = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH;\n this.gravityRangeFactor = FDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR;\n this.compoundGravityRangeFactor = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR;\n this.displacementThresholdPerNode = 3.0 * FDLayoutConstants.DEFAULT_EDGE_LENGTH / 100;\n this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL;\n this.initialCoolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL;\n this.totalDisplacement = 0.0;\n this.oldTotalDisplacement = 0.0;\n this.maxIterations = FDLayoutConstants.MAX_ITERATIONS;\n}\n\nFDLayout.prototype = Object.create(Layout.prototype);\n\nfor (var prop in Layout) {\n FDLayout[prop] = Layout[prop];\n}\n\nFDLayout.prototype.initParameters = function () {\n Layout.prototype.initParameters.call(this, arguments);\n\n this.totalIterations = 0;\n this.notAnimatedIterations = 0;\n\n this.useFRGridVariant = FDLayoutConstants.DEFAULT_USE_SMART_REPULSION_RANGE_CALCULATION;\n\n this.grid = [];\n};\n\nFDLayout.prototype.calcIdealEdgeLengths = function () {\n var edge;\n var originalIdealLength;\n var lcaDepth;\n var source;\n var target;\n var sizeOfSourceInLca;\n var sizeOfTargetInLca;\n\n var allEdges = this.getGraphManager().getAllEdges();\n for (var i = 0; i < allEdges.length; i++) {\n edge = allEdges[i];\n\n originalIdealLength = edge.idealLength;\n\n if (edge.isInterGraph) {\n source = edge.getSource();\n target = edge.getTarget();\n\n sizeOfSourceInLca = edge.getSourceInLca().getEstimatedSize();\n sizeOfTargetInLca = edge.getTargetInLca().getEstimatedSize();\n\n if (this.useSmartIdealEdgeLengthCalculation) {\n edge.idealLength += sizeOfSourceInLca + sizeOfTargetInLca - 2 * LayoutConstants.SIMPLE_NODE_SIZE;\n }\n\n lcaDepth = edge.getLca().getInclusionTreeDepth();\n\n edge.idealLength += originalIdealLength * FDLayoutConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR * (source.getInclusionTreeDepth() + target.getInclusionTreeDepth() - 2 * lcaDepth);\n }\n }\n};\n\nFDLayout.prototype.initSpringEmbedder = function () {\n\n var s = this.getAllNodes().length;\n if (this.incremental) {\n if (s > FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) {\n this.coolingFactor = Math.max(this.coolingFactor * FDLayoutConstants.COOLING_ADAPTATION_FACTOR, this.coolingFactor - (s - FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) / (FDLayoutConstants.ADAPTATION_UPPER_NODE_LIMIT - FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) * this.coolingFactor * (1 - FDLayoutConstants.COOLING_ADAPTATION_FACTOR));\n }\n this.maxNodeDisplacement = FDLayoutConstants.MAX_NODE_DISPLACEMENT_INCREMENTAL;\n } else {\n if (s > FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) {\n this.coolingFactor = Math.max(FDLayoutConstants.COOLING_ADAPTATION_FACTOR, 1.0 - (s - FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) / (FDLayoutConstants.ADAPTATION_UPPER_NODE_LIMIT - FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) * (1 - FDLayoutConstants.COOLING_ADAPTATION_FACTOR));\n } else {\n this.coolingFactor = 1.0;\n }\n this.initialCoolingFactor = this.coolingFactor;\n this.maxNodeDisplacement = FDLayoutConstants.MAX_NODE_DISPLACEMENT;\n }\n\n this.maxIterations = Math.max(this.getAllNodes().length * 5, this.maxIterations);\n\n // Reassign this attribute by using new constant value\n this.displacementThresholdPerNode = 3.0 * FDLayoutConstants.DEFAULT_EDGE_LENGTH / 100;\n this.totalDisplacementThreshold = this.displacementThresholdPerNode * this.getAllNodes().length;\n\n this.repulsionRange = this.calcRepulsionRange();\n};\n\nFDLayout.prototype.calcSpringForces = function () {\n var lEdges = this.getAllEdges();\n var edge;\n\n for (var i = 0; i < lEdges.length; i++) {\n edge = lEdges[i];\n\n this.calcSpringForce(edge, edge.idealLength);\n }\n};\n\nFDLayout.prototype.calcRepulsionForces = function () {\n var gridUpdateAllowed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;\n var forceToNodeSurroundingUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n var i, j;\n var nodeA, nodeB;\n var lNodes = this.getAllNodes();\n var processedNodeSet;\n\n if (this.useFRGridVariant) {\n if (this.totalIterations % FDLayoutConstants.GRID_CALCULATION_CHECK_PERIOD == 1 && gridUpdateAllowed) {\n this.updateGrid();\n }\n\n processedNodeSet = new Set();\n\n // calculate repulsion forces between each nodes and its surrounding\n for (i = 0; i < lNodes.length; i++) {\n nodeA = lNodes[i];\n this.calculateRepulsionForceOfANode(nodeA, processedNodeSet, gridUpdateAllowed, forceToNodeSurroundingUpdate);\n processedNodeSet.add(nodeA);\n }\n } else {\n for (i = 0; i < lNodes.length; i++) {\n nodeA = lNodes[i];\n\n for (j = i + 1; j < lNodes.length; j++) {\n nodeB = lNodes[j];\n\n // If both nodes are not members of the same graph, skip.\n if (nodeA.getOwner() != nodeB.getOwner()) {\n continue;\n }\n\n this.calcRepulsionForce(nodeA, nodeB);\n }\n }\n }\n};\n\nFDLayout.prototype.calcGravitationalForces = function () {\n var node;\n var lNodes = this.getAllNodesToApplyGravitation();\n\n for (var i = 0; i < lNodes.length; i++) {\n node = lNodes[i];\n this.calcGravitationalForce(node);\n }\n};\n\nFDLayout.prototype.moveNodes = function () {\n var lNodes = this.getAllNodes();\n var node;\n\n for (var i = 0; i < lNodes.length; i++) {\n node = lNodes[i];\n node.move();\n }\n};\n\nFDLayout.prototype.calcSpringForce = function (edge, idealLength) {\n var sourceNode = edge.getSource();\n var targetNode = edge.getTarget();\n\n var length;\n var springForce;\n var springForceX;\n var springForceY;\n\n // Update edge length\n if (this.uniformLeafNodeSizes && sourceNode.getChild() == null && targetNode.getChild() == null) {\n edge.updateLengthSimple();\n } else {\n edge.updateLength();\n\n if (edge.isOverlapingSourceAndTarget) {\n return;\n }\n }\n\n length = edge.getLength();\n\n if (length == 0) return;\n\n // Calculate spring forces\n springForce = edge.edgeElasticity * (length - idealLength);\n\n // Project force onto x and y axes\n springForceX = springForce * (edge.lengthX / length);\n springForceY = springForce * (edge.lengthY / length);\n\n // Apply forces on the end nodes\n sourceNode.springForceX += springForceX;\n sourceNode.springForceY += springForceY;\n targetNode.springForceX -= springForceX;\n targetNode.springForceY -= springForceY;\n};\n\nFDLayout.prototype.calcRepulsionForce = function (nodeA, nodeB) {\n var rectA = nodeA.getRect();\n var rectB = nodeB.getRect();\n var overlapAmount = new Array(2);\n var clipPoints = new Array(4);\n var distanceX;\n var distanceY;\n var distanceSquared;\n var distance;\n var repulsionForce;\n var repulsionForceX;\n var repulsionForceY;\n\n if (rectA.intersects(rectB)) // two nodes overlap\n {\n // calculate separation amount in x and y directions\n IGeometry.calcSeparationAmount(rectA, rectB, overlapAmount, FDLayoutConstants.DEFAULT_EDGE_LENGTH / 2.0);\n\n repulsionForceX = 2 * overlapAmount[0];\n repulsionForceY = 2 * overlapAmount[1];\n\n var childrenConstant = nodeA.noOfChildren * nodeB.noOfChildren / (nodeA.noOfChildren + nodeB.noOfChildren);\n\n // Apply forces on the two nodes\n nodeA.repulsionForceX -= childrenConstant * repulsionForceX;\n nodeA.repulsionForceY -= childrenConstant * repulsionForceY;\n nodeB.repulsionForceX += childrenConstant * repulsionForceX;\n nodeB.repulsionForceY += childrenConstant * repulsionForceY;\n } else // no overlap\n {\n // calculate distance\n\n if (this.uniformLeafNodeSizes && nodeA.getChild() == null && nodeB.getChild() == null) // simply base repulsion on distance of node centers\n {\n distanceX = rectB.getCenterX() - rectA.getCenterX();\n distanceY = rectB.getCenterY() - rectA.getCenterY();\n } else // use clipping points\n {\n IGeometry.getIntersection(rectA, rectB, clipPoints);\n\n distanceX = clipPoints[2] - clipPoints[0];\n distanceY = clipPoints[3] - clipPoints[1];\n }\n\n // No repulsion range. FR grid variant should take care of this.\n if (Math.abs(distanceX) < FDLayoutConstants.MIN_REPULSION_DIST) {\n distanceX = IMath.sign(distanceX) * FDLayoutConstants.MIN_REPULSION_DIST;\n }\n\n if (Math.abs(distanceY) < FDLayoutConstants.MIN_REPULSION_DIST) {\n distanceY = IMath.sign(distanceY) * FDLayoutConstants.MIN_REPULSION_DIST;\n }\n\n distanceSquared = distanceX * distanceX + distanceY * distanceY;\n distance = Math.sqrt(distanceSquared);\n\n // Here we use half of the nodes' repulsion values for backward compatibility\n repulsionForce = (nodeA.nodeRepulsion / 2 + nodeB.nodeRepulsion / 2) * nodeA.noOfChildren * nodeB.noOfChildren / distanceSquared;\n\n // Project force onto x and y axes\n repulsionForceX = repulsionForce * distanceX / distance;\n repulsionForceY = repulsionForce * distanceY / distance;\n\n // Apply forces on the two nodes \n nodeA.repulsionForceX -= repulsionForceX;\n nodeA.repulsionForceY -= repulsionForceY;\n nodeB.repulsionForceX += repulsionForceX;\n nodeB.repulsionForceY += repulsionForceY;\n }\n};\n\nFDLayout.prototype.calcGravitationalForce = function (node) {\n var ownerGraph;\n var ownerCenterX;\n var ownerCenterY;\n var distanceX;\n var distanceY;\n var absDistanceX;\n var absDistanceY;\n var estimatedSize;\n ownerGraph = node.getOwner();\n\n ownerCenterX = (ownerGraph.getRight() + ownerGraph.getLeft()) / 2;\n ownerCenterY = (ownerGraph.getTop() + ownerGraph.getBottom()) / 2;\n distanceX = node.getCenterX() - ownerCenterX;\n distanceY = node.getCenterY() - ownerCenterY;\n absDistanceX = Math.abs(distanceX) + node.getWidth() / 2;\n absDistanceY = Math.abs(distanceY) + node.getHeight() / 2;\n\n if (node.getOwner() == this.graphManager.getRoot()) // in the root graph\n {\n estimatedSize = ownerGraph.getEstimatedSize() * this.gravityRangeFactor;\n\n if (absDistanceX > estimatedSize || absDistanceY > estimatedSize) {\n node.gravitationForceX = -this.gravityConstant * distanceX;\n node.gravitationForceY = -this.gravityConstant * distanceY;\n }\n } else // inside a compound\n {\n estimatedSize = ownerGraph.getEstimatedSize() * this.compoundGravityRangeFactor;\n\n if (absDistanceX > estimatedSize || absDistanceY > estimatedSize) {\n node.gravitationForceX = -this.gravityConstant * distanceX * this.compoundGravityConstant;\n node.gravitationForceY = -this.gravityConstant * distanceY * this.compoundGravityConstant;\n }\n }\n};\n\nFDLayout.prototype.isConverged = function () {\n var converged;\n var oscilating = false;\n\n if (this.totalIterations > this.maxIterations / 3) {\n oscilating = Math.abs(this.totalDisplacement - this.oldTotalDisplacement) < 2;\n }\n\n converged = this.totalDisplacement < this.totalDisplacementThreshold;\n\n this.oldTotalDisplacement = this.totalDisplacement;\n\n return converged || oscilating;\n};\n\nFDLayout.prototype.animate = function () {\n if (this.animationDuringLayout && !this.isSubLayout) {\n if (this.notAnimatedIterations == this.animationPeriod) {\n this.update();\n this.notAnimatedIterations = 0;\n } else {\n this.notAnimatedIterations++;\n }\n }\n};\n\n//This method calculates the number of children (weight) for all nodes\nFDLayout.prototype.calcNoOfChildrenForAllNodes = function () {\n var node;\n var allNodes = this.graphManager.getAllNodes();\n\n for (var i = 0; i < allNodes.length; i++) {\n node = allNodes[i];\n node.noOfChildren = node.getNoOfChildren();\n }\n};\n\n// -----------------------------------------------------------------------------\n// Section: FR-Grid Variant Repulsion Force Calculation\n// -----------------------------------------------------------------------------\n\nFDLayout.prototype.calcGrid = function (graph) {\n\n var sizeX = 0;\n var sizeY = 0;\n\n sizeX = parseInt(Math.ceil((graph.getRight() - graph.getLeft()) / this.repulsionRange));\n sizeY = parseInt(Math.ceil((graph.getBottom() - graph.getTop()) / this.repulsionRange));\n\n var grid = new Array(sizeX);\n\n for (var i = 0; i < sizeX; i++) {\n grid[i] = new Array(sizeY);\n }\n\n for (var i = 0; i < sizeX; i++) {\n for (var j = 0; j < sizeY; j++) {\n grid[i][j] = new Array();\n }\n }\n\n return grid;\n};\n\nFDLayout.prototype.addNodeToGrid = function (v, left, top) {\n\n var startX = 0;\n var finishX = 0;\n var startY = 0;\n var finishY = 0;\n\n startX = parseInt(Math.floor((v.getRect().x - left) / this.repulsionRange));\n finishX = parseInt(Math.floor((v.getRect().width + v.getRect().x - left) / this.repulsionRange));\n startY = parseInt(Math.floor((v.getRect().y - top) / this.repulsionRange));\n finishY = parseInt(Math.floor((v.getRect().height + v.getRect().y - top) / this.repulsionRange));\n\n for (var i = startX; i <= finishX; i++) {\n for (var j = startY; j <= finishY; j++) {\n this.grid[i][j].push(v);\n v.setGridCoordinates(startX, finishX, startY, finishY);\n }\n }\n};\n\nFDLayout.prototype.updateGrid = function () {\n var i;\n var nodeA;\n var lNodes = this.getAllNodes();\n\n this.grid = this.calcGrid(this.graphManager.getRoot());\n\n // put all nodes to proper grid cells\n for (i = 0; i < lNodes.length; i++) {\n nodeA = lNodes[i];\n this.addNodeToGrid(nodeA, this.graphManager.getRoot().getLeft(), this.graphManager.getRoot().getTop());\n }\n};\n\nFDLayout.prototype.calculateRepulsionForceOfANode = function (nodeA, processedNodeSet, gridUpdateAllowed, forceToNodeSurroundingUpdate) {\n\n if (this.totalIterations % FDLayoutConstants.GRID_CALCULATION_CHECK_PERIOD == 1 && gridUpdateAllowed || forceToNodeSurroundingUpdate) {\n var surrounding = new Set();\n nodeA.surrounding = new Array();\n var nodeB;\n var grid = this.grid;\n\n for (var i = nodeA.startX - 1; i < nodeA.finishX + 2; i++) {\n for (var j = nodeA.startY - 1; j < nodeA.finishY + 2; j++) {\n if (!(i < 0 || j < 0 || i >= grid.length || j >= grid[0].length)) {\n for (var k = 0; k < grid[i][j].length; k++) {\n nodeB = grid[i][j][k];\n\n // If both nodes are not members of the same graph, \n // or both nodes are the same, skip.\n if (nodeA.getOwner() != nodeB.getOwner() || nodeA == nodeB) {\n continue;\n }\n\n // check if the repulsion force between\n // nodeA and nodeB has already been calculated\n if (!processedNodeSet.has(nodeB) && !surrounding.has(nodeB)) {\n var distanceX = Math.abs(nodeA.getCenterX() - nodeB.getCenterX()) - (nodeA.getWidth() / 2 + nodeB.getWidth() / 2);\n var distanceY = Math.abs(nodeA.getCenterY() - nodeB.getCenterY()) - (nodeA.getHeight() / 2 + nodeB.getHeight() / 2);\n\n // if the distance between nodeA and nodeB \n // is less then calculation range\n if (distanceX <= this.repulsionRange && distanceY <= this.repulsionRange) {\n //then add nodeB to surrounding of nodeA\n surrounding.add(nodeB);\n }\n }\n }\n }\n }\n }\n\n nodeA.surrounding = [].concat(_toConsumableArray(surrounding));\n }\n for (i = 0; i < nodeA.surrounding.length; i++) {\n this.calcRepulsionForce(nodeA, nodeA.surrounding[i]);\n }\n};\n\nFDLayout.prototype.calcRepulsionRange = function () {\n return 0.0;\n};\n\nmodule.exports = FDLayout;\n\n/***/ }),\n/* 19 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar LEdge = __webpack_require__(1);\nvar FDLayoutConstants = __webpack_require__(4);\n\nfunction FDLayoutEdge(source, target, vEdge) {\n LEdge.call(this, source, target, vEdge);\n\n // Ideal length and elasticity value for this edge\n this.idealLength = FDLayoutConstants.DEFAULT_EDGE_LENGTH;\n this.edgeElasticity = FDLayoutConstants.DEFAULT_SPRING_STRENGTH;\n}\n\nFDLayoutEdge.prototype = Object.create(LEdge.prototype);\n\nfor (var prop in LEdge) {\n FDLayoutEdge[prop] = LEdge[prop];\n}\n\nmodule.exports = FDLayoutEdge;\n\n/***/ }),\n/* 20 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar LNode = __webpack_require__(3);\nvar FDLayoutConstants = __webpack_require__(4);\n\nfunction FDLayoutNode(gm, loc, size, vNode) {\n // alternative constructor is handled inside LNode\n LNode.call(this, gm, loc, size, vNode);\n\n // Repulsion value of this node\n this.nodeRepulsion = FDLayoutConstants.DEFAULT_REPULSION_STRENGTH;\n\n //Spring, repulsion and gravitational forces acting on this node\n this.springForceX = 0;\n this.springForceY = 0;\n this.repulsionForceX = 0;\n this.repulsionForceY = 0;\n this.gravitationForceX = 0;\n this.gravitationForceY = 0;\n //Amount by which this node is to be moved in this iteration\n this.displacementX = 0;\n this.displacementY = 0;\n\n //Start and finish grid coordinates that this node is fallen into\n this.startX = 0;\n this.finishX = 0;\n this.startY = 0;\n this.finishY = 0;\n\n //Geometric neighbors of this node\n this.surrounding = [];\n}\n\nFDLayoutNode.prototype = Object.create(LNode.prototype);\n\nfor (var prop in LNode) {\n FDLayoutNode[prop] = LNode[prop];\n}\n\nFDLayoutNode.prototype.setGridCoordinates = function (_startX, _finishX, _startY, _finishY) {\n this.startX = _startX;\n this.finishX = _finishX;\n this.startY = _startY;\n this.finishY = _finishY;\n};\n\nmodule.exports = FDLayoutNode;\n\n/***/ }),\n/* 21 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction DimensionD(width, height) {\n this.width = 0;\n this.height = 0;\n if (width !== null && height !== null) {\n this.height = height;\n this.width = width;\n }\n}\n\nDimensionD.prototype.getWidth = function () {\n return this.width;\n};\n\nDimensionD.prototype.setWidth = function (width) {\n this.width = width;\n};\n\nDimensionD.prototype.getHeight = function () {\n return this.height;\n};\n\nDimensionD.prototype.setHeight = function (height) {\n this.height = height;\n};\n\nmodule.exports = DimensionD;\n\n/***/ }),\n/* 22 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar UniqueIDGeneretor = __webpack_require__(14);\n\nfunction HashMap() {\n this.map = {};\n this.keys = [];\n}\n\nHashMap.prototype.put = function (key, value) {\n var theId = UniqueIDGeneretor.createID(key);\n if (!this.contains(theId)) {\n this.map[theId] = value;\n this.keys.push(key);\n }\n};\n\nHashMap.prototype.contains = function (key) {\n var theId = UniqueIDGeneretor.createID(key);\n return this.map[key] != null;\n};\n\nHashMap.prototype.get = function (key) {\n var theId = UniqueIDGeneretor.createID(key);\n return this.map[theId];\n};\n\nHashMap.prototype.keySet = function () {\n return this.keys;\n};\n\nmodule.exports = HashMap;\n\n/***/ }),\n/* 23 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar UniqueIDGeneretor = __webpack_require__(14);\n\nfunction HashSet() {\n this.set = {};\n}\n;\n\nHashSet.prototype.add = function (obj) {\n var theId = UniqueIDGeneretor.createID(obj);\n if (!this.contains(theId)) this.set[theId] = obj;\n};\n\nHashSet.prototype.remove = function (obj) {\n delete this.set[UniqueIDGeneretor.createID(obj)];\n};\n\nHashSet.prototype.clear = function () {\n this.set = {};\n};\n\nHashSet.prototype.contains = function (obj) {\n return this.set[UniqueIDGeneretor.createID(obj)] == obj;\n};\n\nHashSet.prototype.isEmpty = function () {\n return this.size() === 0;\n};\n\nHashSet.prototype.size = function () {\n return Object.keys(this.set).length;\n};\n\n//concats this.set to the given list\nHashSet.prototype.addAllTo = function (list) {\n var keys = Object.keys(this.set);\n var length = keys.length;\n for (var i = 0; i < length; i++) {\n list.push(this.set[keys[i]]);\n }\n};\n\nHashSet.prototype.size = function () {\n return Object.keys(this.set).length;\n};\n\nHashSet.prototype.addAll = function (list) {\n var s = list.length;\n for (var i = 0; i < s; i++) {\n var v = list[i];\n this.add(v);\n }\n};\n\nmodule.exports = HashSet;\n\n/***/ }),\n/* 24 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\n// Some matrix (1d and 2d array) operations\nfunction Matrix() {}\n\n/**\n * matrix multiplication\n * array1, array2 and result are 2d arrays\n */\nMatrix.multMat = function (array1, array2) {\n var result = [];\n\n for (var i = 0; i < array1.length; i++) {\n result[i] = [];\n for (var j = 0; j < array2[0].length; j++) {\n result[i][j] = 0;\n for (var k = 0; k < array1[0].length; k++) {\n result[i][j] += array1[i][k] * array2[k][j];\n }\n }\n }\n return result;\n};\n\n/**\n * matrix transpose\n * array and result are 2d arrays\n */\nMatrix.transpose = function (array) {\n var result = [];\n\n for (var i = 0; i < array[0].length; i++) {\n result[i] = [];\n for (var j = 0; j < array.length; j++) {\n result[i][j] = array[j][i];\n }\n }\n\n return result;\n};\n\n/**\n * multiply array with constant\n * array and result are 1d arrays\n */\nMatrix.multCons = function (array, constant) {\n var result = [];\n\n for (var i = 0; i < array.length; i++) {\n result[i] = array[i] * constant;\n }\n\n return result;\n};\n\n/**\n * substract two arrays\n * array1, array2 and result are 1d arrays\n */\nMatrix.minusOp = function (array1, array2) {\n var result = [];\n\n for (var i = 0; i < array1.length; i++) {\n result[i] = array1[i] - array2[i];\n }\n\n return result;\n};\n\n/**\n * dot product of two arrays with same size\n * array1 and array2 are 1d arrays\n */\nMatrix.dotProduct = function (array1, array2) {\n var product = 0;\n\n for (var i = 0; i < array1.length; i++) {\n product += array1[i] * array2[i];\n }\n\n return product;\n};\n\n/**\n * magnitude of an array\n * array is 1d array\n */\nMatrix.mag = function (array) {\n return Math.sqrt(this.dotProduct(array, array));\n};\n\n/**\n * normalization of an array\n * array and result are 1d array\n */\nMatrix.normalize = function (array) {\n var result = [];\n var magnitude = this.mag(array);\n\n for (var i = 0; i < array.length; i++) {\n result[i] = array[i] / magnitude;\n }\n\n return result;\n};\n\n/**\n * multiply an array with centering matrix\n * array and result are 1d array\n */\nMatrix.multGamma = function (array) {\n var result = [];\n var sum = 0;\n\n for (var i = 0; i < array.length; i++) {\n sum += array[i];\n }\n\n sum *= -1 / array.length;\n\n for (var _i = 0; _i < array.length; _i++) {\n result[_i] = sum + array[_i];\n }\n return result;\n};\n\n/**\n * a special matrix multiplication\n * result = 0.5 * C * INV * C^T * array\n * array and result are 1d, C and INV are 2d arrays\n */\nMatrix.multL = function (array, C, INV) {\n var result = [];\n var temp1 = [];\n var temp2 = [];\n\n // multiply by C^T\n for (var i = 0; i < C[0].length; i++) {\n var sum = 0;\n for (var j = 0; j < C.length; j++) {\n sum += -0.5 * C[j][i] * array[j];\n }\n temp1[i] = sum;\n }\n // multiply the result by INV\n for (var _i2 = 0; _i2 < INV.length; _i2++) {\n var _sum = 0;\n for (var _j = 0; _j < INV.length; _j++) {\n _sum += INV[_i2][_j] * temp1[_j];\n }\n temp2[_i2] = _sum;\n }\n // multiply the result by C\n for (var _i3 = 0; _i3 < C.length; _i3++) {\n var _sum2 = 0;\n for (var _j2 = 0; _j2 < C[0].length; _j2++) {\n _sum2 += C[_i3][_j2] * temp2[_j2];\n }\n result[_i3] = _sum2;\n }\n\n return result;\n};\n\nmodule.exports = Matrix;\n\n/***/ }),\n/* 25 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * A classic Quicksort algorithm with Hoare's partition\n * - Works also on LinkedList objects\n *\n * Copyright: i-Vis Research Group, Bilkent University, 2007 - present\n */\n\nvar LinkedList = __webpack_require__(11);\n\nvar Quicksort = function () {\n function Quicksort(A, compareFunction) {\n _classCallCheck(this, Quicksort);\n\n if (compareFunction !== null || compareFunction !== undefined) this.compareFunction = this._defaultCompareFunction;\n\n var length = void 0;\n if (A instanceof LinkedList) length = A.size();else length = A.length;\n\n this._quicksort(A, 0, length - 1);\n }\n\n _createClass(Quicksort, [{\n key: '_quicksort',\n value: function _quicksort(A, p, r) {\n if (p < r) {\n var q = this._partition(A, p, r);\n this._quicksort(A, p, q);\n this._quicksort(A, q + 1, r);\n }\n }\n }, {\n key: '_partition',\n value: function _partition(A, p, r) {\n var x = this._get(A, p);\n var i = p;\n var j = r;\n while (true) {\n while (this.compareFunction(x, this._get(A, j))) {\n j--;\n }while (this.compareFunction(this._get(A, i), x)) {\n i++;\n }if (i < j) {\n this._swap(A, i, j);\n i++;\n j--;\n } else return j;\n }\n }\n }, {\n key: '_get',\n value: function _get(object, index) {\n if (object instanceof LinkedList) return object.get_object_at(index);else return object[index];\n }\n }, {\n key: '_set',\n value: function _set(object, index, value) {\n if (object instanceof LinkedList) object.set_object_at(index, value);else object[index] = value;\n }\n }, {\n key: '_swap',\n value: function _swap(A, i, j) {\n var temp = this._get(A, i);\n this._set(A, i, this._get(A, j));\n this._set(A, j, temp);\n }\n }, {\n key: '_defaultCompareFunction',\n value: function _defaultCompareFunction(a, b) {\n return b > a;\n }\n }]);\n\n return Quicksort;\n}();\n\nmodule.exports = Quicksort;\n\n/***/ }),\n/* 26 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\n// Singular Value Decomposition implementation\nfunction SVD() {};\n\n/* Below singular value decomposition (svd) code including hypot function is adopted from https://github.com/dragonfly-ai/JamaJS\n Some changes are applied to make the code compatible with the fcose code and to make it independent from Jama.\n Input matrix is changed to a 2D array instead of Jama matrix. Matrix dimensions are taken according to 2D array instead of using Jama functions.\n An object that includes singular value components is created for return. \n The types of input parameters of the hypot function are removed. \n let is used instead of var for the variable initialization.\n*/\n/*\n Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\n TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n 1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright owner\n or by an individual or Legal Entity authorized to submit on behalf of\n the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n 2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n 3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n 4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n 5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n 6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n 7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n 8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n 9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability.\n\n END OF TERMS AND CONDITIONS\n\n APPENDIX: How to apply the Apache License to your work.\n\n To apply the Apache License to your work, attach the following\n boilerplate notice, with the fields enclosed by brackets \"{}\"\n replaced with your own identifying information. (Don't include\n the brackets!) The text should be enclosed in the appropriate\n comment syntax for the file format. We also recommend that a\n file or class name and description of purpose be included on the\n same \"printed page\" as the copyright notice for easier\n identification within third-party archives.\n\n Copyright {yyyy} {name of copyright owner}\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\nSVD.svd = function (A) {\n this.U = null;\n this.V = null;\n this.s = null;\n this.m = 0;\n this.n = 0;\n this.m = A.length;\n this.n = A[0].length;\n var nu = Math.min(this.m, this.n);\n this.s = function (s) {\n var a = [];\n while (s-- > 0) {\n a.push(0);\n }return a;\n }(Math.min(this.m + 1, this.n));\n this.U = function (dims) {\n var allocate = function allocate(dims) {\n if (dims.length == 0) {\n return 0;\n } else {\n var array = [];\n for (var i = 0; i < dims[0]; i++) {\n array.push(allocate(dims.slice(1)));\n }\n return array;\n }\n };\n return allocate(dims);\n }([this.m, nu]);\n this.V = function (dims) {\n var allocate = function allocate(dims) {\n if (dims.length == 0) {\n return 0;\n } else {\n var array = [];\n for (var i = 0; i < dims[0]; i++) {\n array.push(allocate(dims.slice(1)));\n }\n return array;\n }\n };\n return allocate(dims);\n }([this.n, this.n]);\n var e = function (s) {\n var a = [];\n while (s-- > 0) {\n a.push(0);\n }return a;\n }(this.n);\n var work = function (s) {\n var a = [];\n while (s-- > 0) {\n a.push(0);\n }return a;\n }(this.m);\n var wantu = true;\n var wantv = true;\n var nct = Math.min(this.m - 1, this.n);\n var nrt = Math.max(0, Math.min(this.n - 2, this.m));\n for (var k = 0; k < Math.max(nct, nrt); k++) {\n if (k < nct) {\n this.s[k] = 0;\n for (var i = k; i < this.m; i++) {\n this.s[k] = SVD.hypot(this.s[k], A[i][k]);\n }\n ;\n if (this.s[k] !== 0.0) {\n if (A[k][k] < 0.0) {\n this.s[k] = -this.s[k];\n }\n for (var _i = k; _i < this.m; _i++) {\n A[_i][k] /= this.s[k];\n }\n ;\n A[k][k] += 1.0;\n }\n this.s[k] = -this.s[k];\n }\n for (var j = k + 1; j < this.n; j++) {\n if (function (lhs, rhs) {\n return lhs && rhs;\n }(k < nct, this.s[k] !== 0.0)) {\n var t = 0;\n for (var _i2 = k; _i2 < this.m; _i2++) {\n t += A[_i2][k] * A[_i2][j];\n }\n ;\n t = -t / A[k][k];\n for (var _i3 = k; _i3 < this.m; _i3++) {\n A[_i3][j] += t * A[_i3][k];\n }\n ;\n }\n e[j] = A[k][j];\n }\n ;\n if (function (lhs, rhs) {\n return lhs && rhs;\n }(wantu, k < nct)) {\n for (var _i4 = k; _i4 < this.m; _i4++) {\n this.U[_i4][k] = A[_i4][k];\n }\n ;\n }\n if (k < nrt) {\n e[k] = 0;\n for (var _i5 = k + 1; _i5 < this.n; _i5++) {\n e[k] = SVD.hypot(e[k], e[_i5]);\n }\n ;\n if (e[k] !== 0.0) {\n if (e[k + 1] < 0.0) {\n e[k] = -e[k];\n }\n for (var _i6 = k + 1; _i6 < this.n; _i6++) {\n e[_i6] /= e[k];\n }\n ;\n e[k + 1] += 1.0;\n }\n e[k] = -e[k];\n if (function (lhs, rhs) {\n return lhs && rhs;\n }(k + 1 < this.m, e[k] !== 0.0)) {\n for (var _i7 = k + 1; _i7 < this.m; _i7++) {\n work[_i7] = 0.0;\n }\n ;\n for (var _j = k + 1; _j < this.n; _j++) {\n for (var _i8 = k + 1; _i8 < this.m; _i8++) {\n work[_i8] += e[_j] * A[_i8][_j];\n }\n ;\n }\n ;\n for (var _j2 = k + 1; _j2 < this.n; _j2++) {\n var _t = -e[_j2] / e[k + 1];\n for (var _i9 = k + 1; _i9 < this.m; _i9++) {\n A[_i9][_j2] += _t * work[_i9];\n }\n ;\n }\n ;\n }\n if (wantv) {\n for (var _i10 = k + 1; _i10 < this.n; _i10++) {\n this.V[_i10][k] = e[_i10];\n };\n }\n }\n };\n var p = Math.min(this.n, this.m + 1);\n if (nct < this.n) {\n this.s[nct] = A[nct][nct];\n }\n if (this.m < p) {\n this.s[p - 1] = 0.0;\n }\n if (nrt + 1 < p) {\n e[nrt] = A[nrt][p - 1];\n }\n e[p - 1] = 0.0;\n if (wantu) {\n for (var _j3 = nct; _j3 < nu; _j3++) {\n for (var _i11 = 0; _i11 < this.m; _i11++) {\n this.U[_i11][_j3] = 0.0;\n }\n ;\n this.U[_j3][_j3] = 1.0;\n };\n for (var _k = nct - 1; _k >= 0; _k--) {\n if (this.s[_k] !== 0.0) {\n for (var _j4 = _k + 1; _j4 < nu; _j4++) {\n var _t2 = 0;\n for (var _i12 = _k; _i12 < this.m; _i12++) {\n _t2 += this.U[_i12][_k] * this.U[_i12][_j4];\n };\n _t2 = -_t2 / this.U[_k][_k];\n for (var _i13 = _k; _i13 < this.m; _i13++) {\n this.U[_i13][_j4] += _t2 * this.U[_i13][_k];\n };\n };\n for (var _i14 = _k; _i14 < this.m; _i14++) {\n this.U[_i14][_k] = -this.U[_i14][_k];\n };\n this.U[_k][_k] = 1.0 + this.U[_k][_k];\n for (var _i15 = 0; _i15 < _k - 1; _i15++) {\n this.U[_i15][_k] = 0.0;\n };\n } else {\n for (var _i16 = 0; _i16 < this.m; _i16++) {\n this.U[_i16][_k] = 0.0;\n };\n this.U[_k][_k] = 1.0;\n }\n };\n }\n if (wantv) {\n for (var _k2 = this.n - 1; _k2 >= 0; _k2--) {\n if (function (lhs, rhs) {\n return lhs && rhs;\n }(_k2 < nrt, e[_k2] !== 0.0)) {\n for (var _j5 = _k2 + 1; _j5 < nu; _j5++) {\n var _t3 = 0;\n for (var _i17 = _k2 + 1; _i17 < this.n; _i17++) {\n _t3 += this.V[_i17][_k2] * this.V[_i17][_j5];\n };\n _t3 = -_t3 / this.V[_k2 + 1][_k2];\n for (var _i18 = _k2 + 1; _i18 < this.n; _i18++) {\n this.V[_i18][_j5] += _t3 * this.V[_i18][_k2];\n };\n };\n }\n for (var _i19 = 0; _i19 < this.n; _i19++) {\n this.V[_i19][_k2] = 0.0;\n };\n this.V[_k2][_k2] = 1.0;\n };\n }\n var pp = p - 1;\n var iter = 0;\n var eps = Math.pow(2.0, -52.0);\n var tiny = Math.pow(2.0, -966.0);\n while (p > 0) {\n var _k3 = void 0;\n var kase = void 0;\n for (_k3 = p - 2; _k3 >= -1; _k3--) {\n if (_k3 === -1) {\n break;\n }\n if (Math.abs(e[_k3]) <= tiny + eps * (Math.abs(this.s[_k3]) + Math.abs(this.s[_k3 + 1]))) {\n e[_k3] = 0.0;\n break;\n }\n };\n if (_k3 === p - 2) {\n kase = 4;\n } else {\n var ks = void 0;\n for (ks = p - 1; ks >= _k3; ks--) {\n if (ks === _k3) {\n break;\n }\n var _t4 = (ks !== p ? Math.abs(e[ks]) : 0.0) + (ks !== _k3 + 1 ? Math.abs(e[ks - 1]) : 0.0);\n if (Math.abs(this.s[ks]) <= tiny + eps * _t4) {\n this.s[ks] = 0.0;\n break;\n }\n };\n if (ks === _k3) {\n kase = 3;\n } else if (ks === p - 1) {\n kase = 1;\n } else {\n kase = 2;\n _k3 = ks;\n }\n }\n _k3++;\n switch (kase) {\n case 1:\n {\n var f = e[p - 2];\n e[p - 2] = 0.0;\n for (var _j6 = p - 2; _j6 >= _k3; _j6--) {\n var _t5 = SVD.hypot(this.s[_j6], f);\n var cs = this.s[_j6] / _t5;\n var sn = f / _t5;\n this.s[_j6] = _t5;\n if (_j6 !== _k3) {\n f = -sn * e[_j6 - 1];\n e[_j6 - 1] = cs * e[_j6 - 1];\n }\n if (wantv) {\n for (var _i20 = 0; _i20 < this.n; _i20++) {\n _t5 = cs * this.V[_i20][_j6] + sn * this.V[_i20][p - 1];\n this.V[_i20][p - 1] = -sn * this.V[_i20][_j6] + cs * this.V[_i20][p - 1];\n this.V[_i20][_j6] = _t5;\n };\n }\n };\n };\n break;\n case 2:\n {\n var _f = e[_k3 - 1];\n e[_k3 - 1] = 0.0;\n for (var _j7 = _k3; _j7 < p; _j7++) {\n var _t6 = SVD.hypot(this.s[_j7], _f);\n var _cs = this.s[_j7] / _t6;\n var _sn = _f / _t6;\n this.s[_j7] = _t6;\n _f = -_sn * e[_j7];\n e[_j7] = _cs * e[_j7];\n if (wantu) {\n for (var _i21 = 0; _i21 < this.m; _i21++) {\n _t6 = _cs * this.U[_i21][_j7] + _sn * this.U[_i21][_k3 - 1];\n this.U[_i21][_k3 - 1] = -_sn * this.U[_i21][_j7] + _cs * this.U[_i21][_k3 - 1];\n this.U[_i21][_j7] = _t6;\n };\n }\n };\n };\n break;\n case 3:\n {\n var scale = Math.max(Math.max(Math.max(Math.max(Math.abs(this.s[p - 1]), Math.abs(this.s[p - 2])), Math.abs(e[p - 2])), Math.abs(this.s[_k3])), Math.abs(e[_k3]));\n var sp = this.s[p - 1] / scale;\n var spm1 = this.s[p - 2] / scale;\n var epm1 = e[p - 2] / scale;\n var sk = this.s[_k3] / scale;\n var ek = e[_k3] / scale;\n var b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2.0;\n var c = sp * epm1 * (sp * epm1);\n var shift = 0.0;\n if (function (lhs, rhs) {\n return lhs || rhs;\n }(b !== 0.0, c !== 0.0)) {\n shift = Math.sqrt(b * b + c);\n if (b < 0.0) {\n shift = -shift;\n }\n shift = c / (b + shift);\n }\n var _f2 = (sk + sp) * (sk - sp) + shift;\n var g = sk * ek;\n for (var _j8 = _k3; _j8 < p - 1; _j8++) {\n var _t7 = SVD.hypot(_f2, g);\n var _cs2 = _f2 / _t7;\n var _sn2 = g / _t7;\n if (_j8 !== _k3) {\n e[_j8 - 1] = _t7;\n }\n _f2 = _cs2 * this.s[_j8] + _sn2 * e[_j8];\n e[_j8] = _cs2 * e[_j8] - _sn2 * this.s[_j8];\n g = _sn2 * this.s[_j8 + 1];\n this.s[_j8 + 1] = _cs2 * this.s[_j8 + 1];\n if (wantv) {\n for (var _i22 = 0; _i22 < this.n; _i22++) {\n _t7 = _cs2 * this.V[_i22][_j8] + _sn2 * this.V[_i22][_j8 + 1];\n this.V[_i22][_j8 + 1] = -_sn2 * this.V[_i22][_j8] + _cs2 * this.V[_i22][_j8 + 1];\n this.V[_i22][_j8] = _t7;\n };\n }\n _t7 = SVD.hypot(_f2, g);\n _cs2 = _f2 / _t7;\n _sn2 = g / _t7;\n this.s[_j8] = _t7;\n _f2 = _cs2 * e[_j8] + _sn2 * this.s[_j8 + 1];\n this.s[_j8 + 1] = -_sn2 * e[_j8] + _cs2 * this.s[_j8 + 1];\n g = _sn2 * e[_j8 + 1];\n e[_j8 + 1] = _cs2 * e[_j8 + 1];\n if (wantu && _j8 < this.m - 1) {\n for (var _i23 = 0; _i23 < this.m; _i23++) {\n _t7 = _cs2 * this.U[_i23][_j8] + _sn2 * this.U[_i23][_j8 + 1];\n this.U[_i23][_j8 + 1] = -_sn2 * this.U[_i23][_j8] + _cs2 * this.U[_i23][_j8 + 1];\n this.U[_i23][_j8] = _t7;\n };\n }\n };\n e[p - 2] = _f2;\n iter = iter + 1;\n };\n break;\n case 4:\n {\n if (this.s[_k3] <= 0.0) {\n this.s[_k3] = this.s[_k3] < 0.0 ? -this.s[_k3] : 0.0;\n if (wantv) {\n for (var _i24 = 0; _i24 <= pp; _i24++) {\n this.V[_i24][_k3] = -this.V[_i24][_k3];\n };\n }\n }\n while (_k3 < pp) {\n if (this.s[_k3] >= this.s[_k3 + 1]) {\n break;\n }\n var _t8 = this.s[_k3];\n this.s[_k3] = this.s[_k3 + 1];\n this.s[_k3 + 1] = _t8;\n if (wantv && _k3 < this.n - 1) {\n for (var _i25 = 0; _i25 < this.n; _i25++) {\n _t8 = this.V[_i25][_k3 + 1];\n this.V[_i25][_k3 + 1] = this.V[_i25][_k3];\n this.V[_i25][_k3] = _t8;\n };\n }\n if (wantu && _k3 < this.m - 1) {\n for (var _i26 = 0; _i26 < this.m; _i26++) {\n _t8 = this.U[_i26][_k3 + 1];\n this.U[_i26][_k3 + 1] = this.U[_i26][_k3];\n this.U[_i26][_k3] = _t8;\n };\n }\n _k3++;\n };\n iter = 0;\n p--;\n };\n break;\n }\n };\n var result = { U: this.U, V: this.V, S: this.s };\n return result;\n};\n\n// sqrt(a^2 + b^2) without under/overflow.\nSVD.hypot = function (a, b) {\n var r = void 0;\n if (Math.abs(a) > Math.abs(b)) {\n r = b / a;\n r = Math.abs(a) * Math.sqrt(1 + r * r);\n } else if (b != 0) {\n r = a / b;\n r = Math.abs(b) * Math.sqrt(1 + r * r);\n } else {\n r = 0.0;\n }\n return r;\n};\n\nmodule.exports = SVD;\n\n/***/ }),\n/* 27 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * Needleman-Wunsch algorithm is an procedure to compute the optimal global alignment of two string\n * sequences by S.B.Needleman and C.D.Wunsch (1970).\n *\n * Aside from the inputs, you can assign the scores for,\n * - Match: The two characters at the current index are same.\n * - Mismatch: The two characters at the current index are different.\n * - Insertion/Deletion(gaps): The best alignment involves one letter aligning to a gap in the other string.\n */\n\nvar NeedlemanWunsch = function () {\n function NeedlemanWunsch(sequence1, sequence2) {\n var match_score = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n var mismatch_penalty = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : -1;\n var gap_penalty = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : -1;\n\n _classCallCheck(this, NeedlemanWunsch);\n\n this.sequence1 = sequence1;\n this.sequence2 = sequence2;\n this.match_score = match_score;\n this.mismatch_penalty = mismatch_penalty;\n this.gap_penalty = gap_penalty;\n\n // Just the remove redundancy\n this.iMax = sequence1.length + 1;\n this.jMax = sequence2.length + 1;\n\n // Grid matrix of scores\n this.grid = new Array(this.iMax);\n for (var i = 0; i < this.iMax; i++) {\n this.grid[i] = new Array(this.jMax);\n\n for (var j = 0; j < this.jMax; j++) {\n this.grid[i][j] = 0;\n }\n }\n\n // Traceback matrix (2D array, each cell is an array of boolean values for [`Diag`, `Up`, `Left`] positions)\n this.tracebackGrid = new Array(this.iMax);\n for (var _i = 0; _i < this.iMax; _i++) {\n this.tracebackGrid[_i] = new Array(this.jMax);\n\n for (var _j = 0; _j < this.jMax; _j++) {\n this.tracebackGrid[_i][_j] = [null, null, null];\n }\n }\n\n // The aligned sequences (return multiple possibilities)\n this.alignments = [];\n\n // Final alignment score\n this.score = -1;\n\n // Calculate scores and tracebacks\n this.computeGrids();\n }\n\n _createClass(NeedlemanWunsch, [{\n key: \"getScore\",\n value: function getScore() {\n return this.score;\n }\n }, {\n key: \"getAlignments\",\n value: function getAlignments() {\n return this.alignments;\n }\n\n // Main dynamic programming procedure\n\n }, {\n key: \"computeGrids\",\n value: function computeGrids() {\n // Fill in the first row\n for (var j = 1; j < this.jMax; j++) {\n this.grid[0][j] = this.grid[0][j - 1] + this.gap_penalty;\n this.tracebackGrid[0][j] = [false, false, true];\n }\n\n // Fill in the first column\n for (var i = 1; i < this.iMax; i++) {\n this.grid[i][0] = this.grid[i - 1][0] + this.gap_penalty;\n this.tracebackGrid[i][0] = [false, true, false];\n }\n\n // Fill the rest of the grid\n for (var _i2 = 1; _i2 < this.iMax; _i2++) {\n for (var _j2 = 1; _j2 < this.jMax; _j2++) {\n // Find the max score(s) among [`Diag`, `Up`, `Left`]\n var diag = void 0;\n if (this.sequence1[_i2 - 1] === this.sequence2[_j2 - 1]) diag = this.grid[_i2 - 1][_j2 - 1] + this.match_score;else diag = this.grid[_i2 - 1][_j2 - 1] + this.mismatch_penalty;\n\n var up = this.grid[_i2 - 1][_j2] + this.gap_penalty;\n var left = this.grid[_i2][_j2 - 1] + this.gap_penalty;\n\n // If there exists multiple max values, capture them for multiple paths\n var maxOf = [diag, up, left];\n var indices = this.arrayAllMaxIndexes(maxOf);\n\n // Update Grids\n this.grid[_i2][_j2] = maxOf[indices[0]];\n this.tracebackGrid[_i2][_j2] = [indices.includes(0), indices.includes(1), indices.includes(2)];\n }\n }\n\n // Update alignment score\n this.score = this.grid[this.iMax - 1][this.jMax - 1];\n }\n\n // Gets all possible valid sequence combinations\n\n }, {\n key: \"alignmentTraceback\",\n value: function alignmentTraceback() {\n var inProcessAlignments = [];\n\n inProcessAlignments.push({ pos: [this.sequence1.length, this.sequence2.length],\n seq1: \"\",\n seq2: \"\"\n });\n\n while (inProcessAlignments[0]) {\n var current = inProcessAlignments[0];\n var directions = this.tracebackGrid[current.pos[0]][current.pos[1]];\n\n if (directions[0]) {\n inProcessAlignments.push({ pos: [current.pos[0] - 1, current.pos[1] - 1],\n seq1: this.sequence1[current.pos[0] - 1] + current.seq1,\n seq2: this.sequence2[current.pos[1] - 1] + current.seq2\n });\n }\n if (directions[1]) {\n inProcessAlignments.push({ pos: [current.pos[0] - 1, current.pos[1]],\n seq1: this.sequence1[current.pos[0] - 1] + current.seq1,\n seq2: '-' + current.seq2\n });\n }\n if (directions[2]) {\n inProcessAlignments.push({ pos: [current.pos[0], current.pos[1] - 1],\n seq1: '-' + current.seq1,\n seq2: this.sequence2[current.pos[1] - 1] + current.seq2\n });\n }\n\n if (current.pos[0] === 0 && current.pos[1] === 0) this.alignments.push({ sequence1: current.seq1,\n sequence2: current.seq2\n });\n\n inProcessAlignments.shift();\n }\n\n return this.alignments;\n }\n\n // Helper Functions\n\n }, {\n key: \"getAllIndexes\",\n value: function getAllIndexes(arr, val) {\n var indexes = [],\n i = -1;\n while ((i = arr.indexOf(val, i + 1)) !== -1) {\n indexes.push(i);\n }\n return indexes;\n }\n }, {\n key: \"arrayAllMaxIndexes\",\n value: function arrayAllMaxIndexes(array) {\n return this.getAllIndexes(array, Math.max.apply(null, array));\n }\n }]);\n\n return NeedlemanWunsch;\n}();\n\nmodule.exports = NeedlemanWunsch;\n\n/***/ }),\n/* 28 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar layoutBase = function layoutBase() {\n return;\n};\n\nlayoutBase.FDLayout = __webpack_require__(18);\nlayoutBase.FDLayoutConstants = __webpack_require__(4);\nlayoutBase.FDLayoutEdge = __webpack_require__(19);\nlayoutBase.FDLayoutNode = __webpack_require__(20);\nlayoutBase.DimensionD = __webpack_require__(21);\nlayoutBase.HashMap = __webpack_require__(22);\nlayoutBase.HashSet = __webpack_require__(23);\nlayoutBase.IGeometry = __webpack_require__(8);\nlayoutBase.IMath = __webpack_require__(9);\nlayoutBase.Integer = __webpack_require__(10);\nlayoutBase.Point = __webpack_require__(12);\nlayoutBase.PointD = __webpack_require__(5);\nlayoutBase.RandomSeed = __webpack_require__(16);\nlayoutBase.RectangleD = __webpack_require__(13);\nlayoutBase.Transform = __webpack_require__(17);\nlayoutBase.UniqueIDGeneretor = __webpack_require__(14);\nlayoutBase.Quicksort = __webpack_require__(25);\nlayoutBase.LinkedList = __webpack_require__(11);\nlayoutBase.LGraphObject = __webpack_require__(2);\nlayoutBase.LGraph = __webpack_require__(6);\nlayoutBase.LEdge = __webpack_require__(1);\nlayoutBase.LGraphManager = __webpack_require__(7);\nlayoutBase.LNode = __webpack_require__(3);\nlayoutBase.Layout = __webpack_require__(15);\nlayoutBase.LayoutConstants = __webpack_require__(0);\nlayoutBase.NeedlemanWunsch = __webpack_require__(27);\nlayoutBase.Matrix = __webpack_require__(24);\nlayoutBase.SVD = __webpack_require__(26);\n\nmodule.exports = layoutBase;\n\n/***/ }),\n/* 29 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction Emitter() {\n this.listeners = [];\n}\n\nvar p = Emitter.prototype;\n\np.addListener = function (event, callback) {\n this.listeners.push({\n event: event,\n callback: callback\n });\n};\n\np.removeListener = function (event, callback) {\n for (var i = this.listeners.length; i >= 0; i--) {\n var l = this.listeners[i];\n\n if (l.event === event && l.callback === callback) {\n this.listeners.splice(i, 1);\n }\n }\n};\n\np.emit = function (event, data) {\n for (var i = 0; i < this.listeners.length; i++) {\n var l = this.listeners[i];\n\n if (event === l.event) {\n l.callback(data);\n }\n }\n};\n\nmodule.exports = Emitter;\n\n/***/ })\n/******/ ]);\n});", "(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"layout-base\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"layout-base\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"coseBase\"] = factory(require(\"layout-base\"));\n\telse\n\t\troot[\"coseBase\"] = factory(root[\"layoutBase\"]);\n})(this, function(__WEBPACK_EXTERNAL_MODULE__551__) {\nreturn /******/ (() => { // webpackBootstrap\n/******/ \t\"use strict\";\n/******/ \tvar __webpack_modules__ = ({\n\n/***/ 45:\n/***/ ((module, __unused_webpack_exports, __webpack_require__) => {\n\n\n\nvar coseBase = {};\n\ncoseBase.layoutBase = __webpack_require__(551);\ncoseBase.CoSEConstants = __webpack_require__(806);\ncoseBase.CoSEEdge = __webpack_require__(767);\ncoseBase.CoSEGraph = __webpack_require__(880);\ncoseBase.CoSEGraphManager = __webpack_require__(578);\ncoseBase.CoSELayout = __webpack_require__(765);\ncoseBase.CoSENode = __webpack_require__(991);\ncoseBase.ConstraintHandler = __webpack_require__(902);\n\nmodule.exports = coseBase;\n\n/***/ }),\n\n/***/ 806:\n/***/ ((module, __unused_webpack_exports, __webpack_require__) => {\n\n\n\nvar FDLayoutConstants = __webpack_require__(551).FDLayoutConstants;\n\nfunction CoSEConstants() {}\n\n//CoSEConstants inherits static props in FDLayoutConstants\nfor (var prop in FDLayoutConstants) {\n CoSEConstants[prop] = FDLayoutConstants[prop];\n}\n\nCoSEConstants.DEFAULT_USE_MULTI_LEVEL_SCALING = false;\nCoSEConstants.DEFAULT_RADIAL_SEPARATION = FDLayoutConstants.DEFAULT_EDGE_LENGTH;\nCoSEConstants.DEFAULT_COMPONENT_SEPERATION = 60;\nCoSEConstants.TILE = true;\nCoSEConstants.TILING_PADDING_VERTICAL = 10;\nCoSEConstants.TILING_PADDING_HORIZONTAL = 10;\nCoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = true;\nCoSEConstants.ENFORCE_CONSTRAINTS = true;\nCoSEConstants.APPLY_LAYOUT = true;\nCoSEConstants.RELAX_MOVEMENT_ON_CONSTRAINTS = true;\nCoSEConstants.TREE_REDUCTION_ON_INCREMENTAL = true; // this should be set to false if there will be a constraint\n// This constant is for differentiating whether actual layout algorithm that uses cose-base wants to apply only incremental layout or \n// an incremental layout on top of a randomized layout. If it is only incremental layout, then this constant should be true.\nCoSEConstants.PURE_INCREMENTAL = CoSEConstants.DEFAULT_INCREMENTAL;\n\nmodule.exports = CoSEConstants;\n\n/***/ }),\n\n/***/ 767:\n/***/ ((module, __unused_webpack_exports, __webpack_require__) => {\n\n\n\nvar FDLayoutEdge = __webpack_require__(551).FDLayoutEdge;\n\nfunction CoSEEdge(source, target, vEdge) {\n FDLayoutEdge.call(this, source, target, vEdge);\n}\n\nCoSEEdge.prototype = Object.create(FDLayoutEdge.prototype);\nfor (var prop in FDLayoutEdge) {\n CoSEEdge[prop] = FDLayoutEdge[prop];\n}\n\nmodule.exports = CoSEEdge;\n\n/***/ }),\n\n/***/ 880:\n/***/ ((module, __unused_webpack_exports, __webpack_require__) => {\n\n\n\nvar LGraph = __webpack_require__(551).LGraph;\n\nfunction CoSEGraph(parent, graphMgr, vGraph) {\n LGraph.call(this, parent, graphMgr, vGraph);\n}\n\nCoSEGraph.prototype = Object.create(LGraph.prototype);\nfor (var prop in LGraph) {\n CoSEGraph[prop] = LGraph[prop];\n}\n\nmodule.exports = CoSEGraph;\n\n/***/ }),\n\n/***/ 578:\n/***/ ((module, __unused_webpack_exports, __webpack_require__) => {\n\n\n\nvar LGraphManager = __webpack_require__(551).LGraphManager;\n\nfunction CoSEGraphManager(layout) {\n LGraphManager.call(this, layout);\n}\n\nCoSEGraphManager.prototype = Object.create(LGraphManager.prototype);\nfor (var prop in LGraphManager) {\n CoSEGraphManager[prop] = LGraphManager[prop];\n}\n\nmodule.exports = CoSEGraphManager;\n\n/***/ }),\n\n/***/ 765:\n/***/ ((module, __unused_webpack_exports, __webpack_require__) => {\n\n\n\nvar FDLayout = __webpack_require__(551).FDLayout;\nvar CoSEGraphManager = __webpack_require__(578);\nvar CoSEGraph = __webpack_require__(880);\nvar CoSENode = __webpack_require__(991);\nvar CoSEEdge = __webpack_require__(767);\nvar CoSEConstants = __webpack_require__(806);\nvar ConstraintHandler = __webpack_require__(902);\nvar FDLayoutConstants = __webpack_require__(551).FDLayoutConstants;\nvar LayoutConstants = __webpack_require__(551).LayoutConstants;\nvar Point = __webpack_require__(551).Point;\nvar PointD = __webpack_require__(551).PointD;\nvar DimensionD = __webpack_require__(551).DimensionD;\nvar Layout = __webpack_require__(551).Layout;\nvar Integer = __webpack_require__(551).Integer;\nvar IGeometry = __webpack_require__(551).IGeometry;\nvar LGraph = __webpack_require__(551).LGraph;\nvar Transform = __webpack_require__(551).Transform;\nvar LinkedList = __webpack_require__(551).LinkedList;\n\nfunction CoSELayout() {\n FDLayout.call(this);\n\n this.toBeTiled = {}; // Memorize if a node is to be tiled or is tiled\n this.constraints = {}; // keep layout constraints\n}\n\nCoSELayout.prototype = Object.create(FDLayout.prototype);\n\nfor (var prop in FDLayout) {\n CoSELayout[prop] = FDLayout[prop];\n}\n\nCoSELayout.prototype.newGraphManager = function () {\n var gm = new CoSEGraphManager(this);\n this.graphManager = gm;\n return gm;\n};\n\nCoSELayout.prototype.newGraph = function (vGraph) {\n return new CoSEGraph(null, this.graphManager, vGraph);\n};\n\nCoSELayout.prototype.newNode = function (vNode) {\n return new CoSENode(this.graphManager, vNode);\n};\n\nCoSELayout.prototype.newEdge = function (vEdge) {\n return new CoSEEdge(null, null, vEdge);\n};\n\nCoSELayout.prototype.initParameters = function () {\n FDLayout.prototype.initParameters.call(this, arguments);\n if (!this.isSubLayout) {\n if (CoSEConstants.DEFAULT_EDGE_LENGTH < 10) {\n this.idealEdgeLength = 10;\n } else {\n this.idealEdgeLength = CoSEConstants.DEFAULT_EDGE_LENGTH;\n }\n\n this.useSmartIdealEdgeLengthCalculation = CoSEConstants.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION;\n this.gravityConstant = FDLayoutConstants.DEFAULT_GRAVITY_STRENGTH;\n this.compoundGravityConstant = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH;\n this.gravityRangeFactor = FDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR;\n this.compoundGravityRangeFactor = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR;\n\n // variables for tree reduction support\n this.prunedNodesAll = [];\n this.growTreeIterations = 0;\n this.afterGrowthIterations = 0;\n this.isTreeGrowing = false;\n this.isGrowthFinished = false;\n }\n};\n\n// This method is used to set CoSE related parameters used by spring embedder.\nCoSELayout.prototype.initSpringEmbedder = function () {\n FDLayout.prototype.initSpringEmbedder.call(this);\n\n // variables for cooling\n this.coolingCycle = 0;\n this.maxCoolingCycle = this.maxIterations / FDLayoutConstants.CONVERGENCE_CHECK_PERIOD;\n this.finalTemperature = 0.04;\n this.coolingAdjuster = 1;\n};\n\nCoSELayout.prototype.layout = function () {\n var createBendsAsNeeded = LayoutConstants.DEFAULT_CREATE_BENDS_AS_NEEDED;\n if (createBendsAsNeeded) {\n this.createBendpoints();\n this.graphManager.resetAllEdges();\n }\n\n this.level = 0;\n return this.classicLayout();\n};\n\nCoSELayout.prototype.classicLayout = function () {\n this.nodesWithGravity = this.calculateNodesToApplyGravitationTo();\n this.graphManager.setAllNodesToApplyGravitation(this.nodesWithGravity);\n this.calcNoOfChildrenForAllNodes();\n this.graphManager.calcLowestCommonAncestors();\n this.graphManager.calcInclusionTreeDepths();\n this.graphManager.getRoot().calcEstimatedSize();\n this.calcIdealEdgeLengths();\n\n if (!this.incremental) {\n var forest = this.getFlatForest();\n\n // The graph associated with this layout is flat and a forest\n if (forest.length > 0) {\n this.positionNodesRadially(forest);\n }\n // The graph associated with this layout is not flat or a forest\n else {\n // Reduce the trees when incremental mode is not enabled and graph is not a forest \n this.reduceTrees();\n // Update nodes that gravity will be applied\n this.graphManager.resetAllNodesToApplyGravitation();\n var allNodes = new Set(this.getAllNodes());\n var intersection = this.nodesWithGravity.filter(function (x) {\n return allNodes.has(x);\n });\n this.graphManager.setAllNodesToApplyGravitation(intersection);\n\n this.positionNodesRandomly();\n }\n } else {\n if (CoSEConstants.TREE_REDUCTION_ON_INCREMENTAL) {\n // Reduce the trees in incremental mode if only this constant is set to true \n this.reduceTrees();\n // Update nodes that gravity will be applied\n this.graphManager.resetAllNodesToApplyGravitation();\n var allNodes = new Set(this.getAllNodes());\n var intersection = this.nodesWithGravity.filter(function (x) {\n return allNodes.has(x);\n });\n this.graphManager.setAllNodesToApplyGravitation(intersection);\n }\n }\n\n if (Object.keys(this.constraints).length > 0) {\n ConstraintHandler.handleConstraints(this);\n this.initConstraintVariables();\n }\n\n this.initSpringEmbedder();\n if (CoSEConstants.APPLY_LAYOUT) {\n this.runSpringEmbedder();\n }\n\n return true;\n};\n\nCoSELayout.prototype.tick = function () {\n this.totalIterations++;\n\n if (this.totalIterations === this.maxIterations && !this.isTreeGrowing && !this.isGrowthFinished) {\n if (this.prunedNodesAll.length > 0) {\n this.isTreeGrowing = true;\n } else {\n return true;\n }\n }\n\n if (this.totalIterations % FDLayoutConstants.CONVERGENCE_CHECK_PERIOD == 0 && !this.isTreeGrowing && !this.isGrowthFinished) {\n if (this.isConverged()) {\n if (this.prunedNodesAll.length > 0) {\n this.isTreeGrowing = true;\n } else {\n return true;\n }\n }\n\n this.coolingCycle++;\n\n if (this.layoutQuality == 0) {\n // quality - \"draft\"\n this.coolingAdjuster = this.coolingCycle;\n } else if (this.layoutQuality == 1) {\n // quality - \"default\"\n this.coolingAdjuster = this.coolingCycle / 3;\n }\n\n // cooling schedule is based on http://www.btluke.com/simanf1.html -> cooling schedule 3\n this.coolingFactor = Math.max(this.initialCoolingFactor - Math.pow(this.coolingCycle, Math.log(100 * (this.initialCoolingFactor - this.finalTemperature)) / Math.log(this.maxCoolingCycle)) / 100 * this.coolingAdjuster, this.finalTemperature);\n this.animationPeriod = Math.ceil(this.initialAnimationPeriod * Math.sqrt(this.coolingFactor));\n }\n // Operations while tree is growing again \n if (this.isTreeGrowing) {\n if (this.growTreeIterations % 10 == 0) {\n if (this.prunedNodesAll.length > 0) {\n this.graphManager.updateBounds();\n this.updateGrid();\n this.growTree(this.prunedNodesAll);\n // Update nodes that gravity will be applied\n this.graphManager.resetAllNodesToApplyGravitation();\n var allNodes = new Set(this.getAllNodes());\n var intersection = this.nodesWithGravity.filter(function (x) {\n return allNodes.has(x);\n });\n this.graphManager.setAllNodesToApplyGravitation(intersection);\n\n this.graphManager.updateBounds();\n this.updateGrid();\n if (CoSEConstants.PURE_INCREMENTAL) this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL / 2;else this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL;\n } else {\n this.isTreeGrowing = false;\n this.isGrowthFinished = true;\n }\n }\n this.growTreeIterations++;\n }\n // Operations after growth is finished\n if (this.isGrowthFinished) {\n if (this.isConverged()) {\n return true;\n }\n if (this.afterGrowthIterations % 10 == 0) {\n this.graphManager.updateBounds();\n this.updateGrid();\n }\n if (CoSEConstants.PURE_INCREMENTAL) this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL / 2 * ((100 - this.afterGrowthIterations) / 100);else this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL * ((100 - this.afterGrowthIterations) / 100);\n this.afterGrowthIterations++;\n }\n\n var gridUpdateAllowed = !this.isTreeGrowing && !this.isGrowthFinished;\n var forceToNodeSurroundingUpdate = this.growTreeIterations % 10 == 1 && this.isTreeGrowing || this.afterGrowthIterations % 10 == 1 && this.isGrowthFinished;\n\n this.totalDisplacement = 0;\n this.graphManager.updateBounds();\n this.calcSpringForces();\n this.calcRepulsionForces(gridUpdateAllowed, forceToNodeSurroundingUpdate);\n this.calcGravitationalForces();\n this.moveNodes();\n this.animate();\n\n return false; // Layout is not ended yet return false\n};\n\nCoSELayout.prototype.getPositionsData = function () {\n var allNodes = this.graphManager.getAllNodes();\n var pData = {};\n for (var i = 0; i < allNodes.length; i++) {\n var rect = allNodes[i].rect;\n var id = allNodes[i].id;\n pData[id] = {\n id: id,\n x: rect.getCenterX(),\n y: rect.getCenterY(),\n w: rect.width,\n h: rect.height\n };\n }\n\n return pData;\n};\n\nCoSELayout.prototype.runSpringEmbedder = function () {\n this.initialAnimationPeriod = 25;\n this.animationPeriod = this.initialAnimationPeriod;\n var layoutEnded = false;\n\n // If aminate option is 'during' signal that layout is supposed to start iterating\n if (FDLayoutConstants.ANIMATE === 'during') {\n this.emit('layoutstarted');\n } else {\n // If aminate option is 'during' tick() function will be called on index.js\n while (!layoutEnded) {\n layoutEnded = this.tick();\n }\n\n this.graphManager.updateBounds();\n }\n};\n\n// overrides moveNodes method in FDLayout\nCoSELayout.prototype.moveNodes = function () {\n var lNodes = this.getAllNodes();\n var node;\n\n // calculate displacement for each node \n for (var i = 0; i < lNodes.length; i++) {\n node = lNodes[i];\n node.calculateDisplacement();\n }\n\n if (Object.keys(this.constraints).length > 0) {\n this.updateDisplacements();\n }\n\n // move each node\n for (var i = 0; i < lNodes.length; i++) {\n node = lNodes[i];\n node.move();\n }\n};\n\n// constraint related methods: initConstraintVariables and updateDisplacements\n\n// initialize constraint related variables\nCoSELayout.prototype.initConstraintVariables = function () {\n var self = this;\n this.idToNodeMap = new Map();\n this.fixedNodeSet = new Set();\n\n var allNodes = this.graphManager.getAllNodes();\n\n // fill idToNodeMap\n for (var i = 0; i < allNodes.length; i++) {\n var node = allNodes[i];\n this.idToNodeMap.set(node.id, node);\n }\n\n // calculate fixed node weight for given compound node\n var calculateCompoundWeight = function calculateCompoundWeight(compoundNode) {\n var nodes = compoundNode.getChild().getNodes();\n var node;\n var fixedNodeWeight = 0;\n for (var i = 0; i < nodes.length; i++) {\n node = nodes[i];\n if (node.getChild() == null) {\n if (self.fixedNodeSet.has(node.id)) {\n fixedNodeWeight += 100;\n }\n } else {\n fixedNodeWeight += calculateCompoundWeight(node);\n }\n }\n return fixedNodeWeight;\n };\n\n if (this.constraints.fixedNodeConstraint) {\n // fill fixedNodeSet\n this.constraints.fixedNodeConstraint.forEach(function (nodeData) {\n self.fixedNodeSet.add(nodeData.nodeId);\n });\n\n // assign fixed node weights to compounds if they contain fixed nodes\n var allNodes = this.graphManager.getAllNodes();\n var node;\n\n for (var i = 0; i < allNodes.length; i++) {\n node = allNodes[i];\n if (node.getChild() != null) {\n var fixedNodeWeight = calculateCompoundWeight(node);\n if (fixedNodeWeight > 0) {\n node.fixedNodeWeight = fixedNodeWeight;\n }\n }\n }\n }\n\n if (this.constraints.relativePlacementConstraint) {\n var nodeToDummyForVerticalAlignment = new Map();\n var nodeToDummyForHorizontalAlignment = new Map();\n this.dummyToNodeForVerticalAlignment = new Map();\n this.dummyToNodeForHorizontalAlignment = new Map();\n this.fixedNodesOnHorizontal = new Set();\n this.fixedNodesOnVertical = new Set();\n\n // fill maps and sets\n this.fixedNodeSet.forEach(function (nodeId) {\n self.fixedNodesOnHorizontal.add(nodeId);\n self.fixedNodesOnVertical.add(nodeId);\n });\n\n if (this.constraints.alignmentConstraint) {\n if (this.constraints.alignmentConstraint.vertical) {\n var verticalAlignment = this.constraints.alignmentConstraint.vertical;\n for (var i = 0; i < verticalAlignment.length; i++) {\n this.dummyToNodeForVerticalAlignment.set(\"dummy\" + i, []);\n verticalAlignment[i].forEach(function (nodeId) {\n nodeToDummyForVerticalAlignment.set(nodeId, \"dummy\" + i);\n self.dummyToNodeForVerticalAlignment.get(\"dummy\" + i).push(nodeId);\n if (self.fixedNodeSet.has(nodeId)) {\n self.fixedNodesOnHorizontal.add(\"dummy\" + i);\n }\n });\n }\n }\n if (this.constraints.alignmentConstraint.horizontal) {\n var horizontalAlignment = this.constraints.alignmentConstraint.horizontal;\n for (var i = 0; i < horizontalAlignment.length; i++) {\n this.dummyToNodeForHorizontalAlignment.set(\"dummy\" + i, []);\n horizontalAlignment[i].forEach(function (nodeId) {\n nodeToDummyForHorizontalAlignment.set(nodeId, \"dummy\" + i);\n self.dummyToNodeForHorizontalAlignment.get(\"dummy\" + i).push(nodeId);\n if (self.fixedNodeSet.has(nodeId)) {\n self.fixedNodesOnVertical.add(\"dummy\" + i);\n }\n });\n }\n }\n }\n\n if (CoSEConstants.RELAX_MOVEMENT_ON_CONSTRAINTS) {\n\n this.shuffle = function (array) {\n var j, x, i;\n for (i = array.length - 1; i >= 2 * array.length / 3; i--) {\n j = Math.floor(Math.random() * (i + 1));\n x = array[i];\n array[i] = array[j];\n array[j] = x;\n }\n return array;\n };\n\n this.nodesInRelativeHorizontal = [];\n this.nodesInRelativeVertical = [];\n this.nodeToRelativeConstraintMapHorizontal = new Map();\n this.nodeToRelativeConstraintMapVertical = new Map();\n this.nodeToTempPositionMapHorizontal = new Map();\n this.nodeToTempPositionMapVertical = new Map();\n\n // fill arrays and maps\n this.constraints.relativePlacementConstraint.forEach(function (constraint) {\n if (constraint.left) {\n var nodeIdLeft = nodeToDummyForVerticalAlignment.has(constraint.left) ? nodeToDummyForVerticalAlignment.get(constraint.left) : constraint.left;\n var nodeIdRight = nodeToDummyForVerticalAlignment.has(constraint.right) ? nodeToDummyForVerticalAlignment.get(constraint.right) : constraint.right;\n\n if (!self.nodesInRelativeHorizontal.includes(nodeIdLeft)) {\n self.nodesInRelativeHorizontal.push(nodeIdLeft);\n self.nodeToRelativeConstraintMapHorizontal.set(nodeIdLeft, []);\n if (self.dummyToNodeForVerticalAlignment.has(nodeIdLeft)) {\n self.nodeToTempPositionMapHorizontal.set(nodeIdLeft, self.idToNodeMap.get(self.dummyToNodeForVerticalAlignment.get(nodeIdLeft)[0]).getCenterX());\n } else {\n self.nodeToTempPositionMapHorizontal.set(nodeIdLeft, self.idToNodeMap.get(nodeIdLeft).getCenterX());\n }\n }\n if (!self.nodesInRelativeHorizontal.includes(nodeIdRight)) {\n self.nodesInRelativeHorizontal.push(nodeIdRight);\n self.nodeToRelativeConstraintMapHorizontal.set(nodeIdRight, []);\n if (self.dummyToNodeForVerticalAlignment.has(nodeIdRight)) {\n self.nodeToTempPositionMapHorizontal.set(nodeIdRight, self.idToNodeMap.get(self.dummyToNodeForVerticalAlignment.get(nodeIdRight)[0]).getCenterX());\n } else {\n self.nodeToTempPositionMapHorizontal.set(nodeIdRight, self.idToNodeMap.get(nodeIdRight).getCenterX());\n }\n }\n\n self.nodeToRelativeConstraintMapHorizontal.get(nodeIdLeft).push({ right: nodeIdRight, gap: constraint.gap });\n self.nodeToRelativeConstraintMapHorizontal.get(nodeIdRight).push({ left: nodeIdLeft, gap: constraint.gap });\n } else {\n var nodeIdTop = nodeToDummyForHorizontalAlignment.has(constraint.top) ? nodeToDummyForHorizontalAlignment.get(constraint.top) : constraint.top;\n var nodeIdBottom = nodeToDummyForHorizontalAlignment.has(constraint.bottom) ? nodeToDummyForHorizontalAlignment.get(constraint.bottom) : constraint.bottom;\n\n if (!self.nodesInRelativeVertical.includes(nodeIdTop)) {\n self.nodesInRelativeVertical.push(nodeIdTop);\n self.nodeToRelativeConstraintMapVertical.set(nodeIdTop, []);\n if (self.dummyToNodeForHorizontalAlignment.has(nodeIdTop)) {\n self.nodeToTempPositionMapVertical.set(nodeIdTop, self.idToNodeMap.get(self.dummyToNodeForHorizontalAlignment.get(nodeIdTop)[0]).getCenterY());\n } else {\n self.nodeToTempPositionMapVertical.set(nodeIdTop, self.idToNodeMap.get(nodeIdTop).getCenterY());\n }\n }\n if (!self.nodesInRelativeVertical.includes(nodeIdBottom)) {\n self.nodesInRelativeVertical.push(nodeIdBottom);\n self.nodeToRelativeConstraintMapVertical.set(nodeIdBottom, []);\n if (self.dummyToNodeForHorizontalAlignment.has(nodeIdBottom)) {\n self.nodeToTempPositionMapVertical.set(nodeIdBottom, self.idToNodeMap.get(self.dummyToNodeForHorizontalAlignment.get(nodeIdBottom)[0]).getCenterY());\n } else {\n self.nodeToTempPositionMapVertical.set(nodeIdBottom, self.idToNodeMap.get(nodeIdBottom).getCenterY());\n }\n }\n self.nodeToRelativeConstraintMapVertical.get(nodeIdTop).push({ bottom: nodeIdBottom, gap: constraint.gap });\n self.nodeToRelativeConstraintMapVertical.get(nodeIdBottom).push({ top: nodeIdTop, gap: constraint.gap });\n }\n });\n } else {\n var subGraphOnHorizontal = new Map(); // subgraph from vertical RP constraints\n var subGraphOnVertical = new Map(); // subgraph from vertical RP constraints\n\n // construct subgraphs from relative placement constraints \n this.constraints.relativePlacementConstraint.forEach(function (constraint) {\n if (constraint.left) {\n var left = nodeToDummyForVerticalAlignment.has(constraint.left) ? nodeToDummyForVerticalAlignment.get(constraint.left) : constraint.left;\n var right = nodeToDummyForVerticalAlignment.has(constraint.right) ? nodeToDummyForVerticalAlignment.get(constraint.right) : constraint.right;\n if (subGraphOnHorizontal.has(left)) {\n subGraphOnHorizontal.get(left).push(right);\n } else {\n subGraphOnHorizontal.set(left, [right]);\n }\n if (subGraphOnHorizontal.has(right)) {\n subGraphOnHorizontal.get(right).push(left);\n } else {\n subGraphOnHorizontal.set(right, [left]);\n }\n } else {\n var top = nodeToDummyForHorizontalAlignment.has(constraint.top) ? nodeToDummyForHorizontalAlignment.get(constraint.top) : constraint.top;\n var bottom = nodeToDummyForHorizontalAlignment.has(constraint.bottom) ? nodeToDummyForHorizontalAlignment.get(constraint.bottom) : constraint.bottom;\n if (subGraphOnVertical.has(top)) {\n subGraphOnVertical.get(top).push(bottom);\n } else {\n subGraphOnVertical.set(top, [bottom]);\n }\n if (subGraphOnVertical.has(bottom)) {\n subGraphOnVertical.get(bottom).push(top);\n } else {\n subGraphOnVertical.set(bottom, [top]);\n }\n }\n });\n\n // function to construct components from a given graph \n // also returns an array that keeps whether each component contains fixed node\n var constructComponents = function constructComponents(graph, fixedNodes) {\n var components = [];\n var isFixed = [];\n var queue = new LinkedList();\n var visited = new Set();\n var count = 0;\n\n graph.forEach(function (value, key) {\n if (!visited.has(key)) {\n components[count] = [];\n isFixed[count] = false;\n var currentNode = key;\n queue.push(currentNode);\n visited.add(currentNode);\n components[count].push(currentNode);\n\n while (queue.length != 0) {\n currentNode = queue.shift();\n if (fixedNodes.has(currentNode)) {\n isFixed[count] = true;\n }\n var neighbors = graph.get(currentNode);\n neighbors.forEach(function (neighbor) {\n if (!visited.has(neighbor)) {\n queue.push(neighbor);\n visited.add(neighbor);\n components[count].push(neighbor);\n }\n });\n }\n count++;\n }\n });\n\n return { components: components, isFixed: isFixed };\n };\n\n var resultOnHorizontal = constructComponents(subGraphOnHorizontal, self.fixedNodesOnHorizontal);\n this.componentsOnHorizontal = resultOnHorizontal.components;\n this.fixedComponentsOnHorizontal = resultOnHorizontal.isFixed;\n var resultOnVertical = constructComponents(subGraphOnVertical, self.fixedNodesOnVertical);\n this.componentsOnVertical = resultOnVertical.components;\n this.fixedComponentsOnVertical = resultOnVertical.isFixed;\n }\n }\n};\n\n// updates node displacements based on constraints\nCoSELayout.prototype.updateDisplacements = function () {\n var self = this;\n if (this.constraints.fixedNodeConstraint) {\n this.constraints.fixedNodeConstraint.forEach(function (nodeData) {\n var fixedNode = self.idToNodeMap.get(nodeData.nodeId);\n fixedNode.displacementX = 0;\n fixedNode.displacementY = 0;\n });\n }\n\n if (this.constraints.alignmentConstraint) {\n if (this.constraints.alignmentConstraint.vertical) {\n var allVerticalAlignments = this.constraints.alignmentConstraint.vertical;\n for (var i = 0; i < allVerticalAlignments.length; i++) {\n var totalDisplacementX = 0;\n for (var j = 0; j < allVerticalAlignments[i].length; j++) {\n if (this.fixedNodeSet.has(allVerticalAlignments[i][j])) {\n totalDisplacementX = 0;\n break;\n }\n totalDisplacementX += this.idToNodeMap.get(allVerticalAlignments[i][j]).displacementX;\n }\n var averageDisplacementX = totalDisplacementX / allVerticalAlignments[i].length;\n for (var j = 0; j < allVerticalAlignments[i].length; j++) {\n this.idToNodeMap.get(allVerticalAlignments[i][j]).displacementX = averageDisplacementX;\n }\n }\n }\n if (this.constraints.alignmentConstraint.horizontal) {\n var allHorizontalAlignments = this.constraints.alignmentConstraint.horizontal;\n for (var i = 0; i < allHorizontalAlignments.length; i++) {\n var totalDisplacementY = 0;\n for (var j = 0; j < allHorizontalAlignments[i].length; j++) {\n if (this.fixedNodeSet.has(allHorizontalAlignments[i][j])) {\n totalDisplacementY = 0;\n break;\n }\n totalDisplacementY += this.idToNodeMap.get(allHorizontalAlignments[i][j]).displacementY;\n }\n var averageDisplacementY = totalDisplacementY / allHorizontalAlignments[i].length;\n for (var j = 0; j < allHorizontalAlignments[i].length; j++) {\n this.idToNodeMap.get(allHorizontalAlignments[i][j]).displacementY = averageDisplacementY;\n }\n }\n }\n }\n\n if (this.constraints.relativePlacementConstraint) {\n\n if (CoSEConstants.RELAX_MOVEMENT_ON_CONSTRAINTS) {\n // shuffle array to randomize node processing order\n if (this.totalIterations % 10 == 0) {\n this.shuffle(this.nodesInRelativeHorizontal);\n this.shuffle(this.nodesInRelativeVertical);\n }\n\n this.nodesInRelativeHorizontal.forEach(function (nodeId) {\n if (!self.fixedNodesOnHorizontal.has(nodeId)) {\n var displacement = 0;\n if (self.dummyToNodeForVerticalAlignment.has(nodeId)) {\n displacement = self.idToNodeMap.get(self.dummyToNodeForVerticalAlignment.get(nodeId)[0]).displacementX;\n } else {\n displacement = self.idToNodeMap.get(nodeId).displacementX;\n }\n self.nodeToRelativeConstraintMapHorizontal.get(nodeId).forEach(function (constraint) {\n if (constraint.right) {\n var diff = self.nodeToTempPositionMapHorizontal.get(constraint.right) - self.nodeToTempPositionMapHorizontal.get(nodeId) - displacement;\n if (diff < constraint.gap) {\n displacement -= constraint.gap - diff;\n }\n } else {\n var diff = self.nodeToTempPositionMapHorizontal.get(nodeId) - self.nodeToTempPositionMapHorizontal.get(constraint.left) + displacement;\n if (diff < constraint.gap) {\n displacement += constraint.gap - diff;\n }\n }\n });\n self.nodeToTempPositionMapHorizontal.set(nodeId, self.nodeToTempPositionMapHorizontal.get(nodeId) + displacement);\n if (self.dummyToNodeForVerticalAlignment.has(nodeId)) {\n self.dummyToNodeForVerticalAlignment.get(nodeId).forEach(function (nodeId) {\n self.idToNodeMap.get(nodeId).displacementX = displacement;\n });\n } else {\n self.idToNodeMap.get(nodeId).displacementX = displacement;\n }\n }\n });\n\n this.nodesInRelativeVertical.forEach(function (nodeId) {\n if (!self.fixedNodesOnHorizontal.has(nodeId)) {\n var displacement = 0;\n if (self.dummyToNodeForHorizontalAlignment.has(nodeId)) {\n displacement = self.idToNodeMap.get(self.dummyToNodeForHorizontalAlignment.get(nodeId)[0]).displacementY;\n } else {\n displacement = self.idToNodeMap.get(nodeId).displacementY;\n }\n self.nodeToRelativeConstraintMapVertical.get(nodeId).forEach(function (constraint) {\n if (constraint.bottom) {\n var diff = self.nodeToTempPositionMapVertical.get(constraint.bottom) - self.nodeToTempPositionMapVertical.get(nodeId) - displacement;\n if (diff < constraint.gap) {\n displacement -= constraint.gap - diff;\n }\n } else {\n var diff = self.nodeToTempPositionMapVertical.get(nodeId) - self.nodeToTempPositionMapVertical.get(constraint.top) + displacement;\n if (diff < constraint.gap) {\n displacement += constraint.gap - diff;\n }\n }\n });\n self.nodeToTempPositionMapVertical.set(nodeId, self.nodeToTempPositionMapVertical.get(nodeId) + displacement);\n if (self.dummyToNodeForHorizontalAlignment.has(nodeId)) {\n self.dummyToNodeForHorizontalAlignment.get(nodeId).forEach(function (nodeId) {\n self.idToNodeMap.get(nodeId).displacementY = displacement;\n });\n } else {\n self.idToNodeMap.get(nodeId).displacementY = displacement;\n }\n }\n });\n } else {\n for (var i = 0; i < this.componentsOnHorizontal.length; i++) {\n var component = this.componentsOnHorizontal[i];\n if (this.fixedComponentsOnHorizontal[i]) {\n for (var j = 0; j < component.length; j++) {\n if (this.dummyToNodeForVerticalAlignment.has(component[j])) {\n this.dummyToNodeForVerticalAlignment.get(component[j]).forEach(function (nodeId) {\n self.idToNodeMap.get(nodeId).displacementX = 0;\n });\n } else {\n this.idToNodeMap.get(component[j]).displacementX = 0;\n }\n }\n } else {\n var sum = 0;\n var count = 0;\n for (var j = 0; j < component.length; j++) {\n if (this.dummyToNodeForVerticalAlignment.has(component[j])) {\n var actualNodes = this.dummyToNodeForVerticalAlignment.get(component[j]);\n sum += actualNodes.length * this.idToNodeMap.get(actualNodes[0]).displacementX;\n count += actualNodes.length;\n } else {\n sum += this.idToNodeMap.get(component[j]).displacementX;\n count++;\n }\n }\n var averageDisplacement = sum / count;\n for (var j = 0; j < component.length; j++) {\n if (this.dummyToNodeForVerticalAlignment.has(component[j])) {\n this.dummyToNodeForVerticalAlignment.get(component[j]).forEach(function (nodeId) {\n self.idToNodeMap.get(nodeId).displacementX = averageDisplacement;\n });\n } else {\n this.idToNodeMap.get(component[j]).displacementX = averageDisplacement;\n }\n }\n }\n }\n\n for (var i = 0; i < this.componentsOnVertical.length; i++) {\n var component = this.componentsOnVertical[i];\n if (this.fixedComponentsOnVertical[i]) {\n for (var j = 0; j < component.length; j++) {\n if (this.dummyToNodeForHorizontalAlignment.has(component[j])) {\n this.dummyToNodeForHorizontalAlignment.get(component[j]).forEach(function (nodeId) {\n self.idToNodeMap.get(nodeId).displacementY = 0;\n });\n } else {\n this.idToNodeMap.get(component[j]).displacementY = 0;\n }\n }\n } else {\n var sum = 0;\n var count = 0;\n for (var j = 0; j < component.length; j++) {\n if (this.dummyToNodeForHorizontalAlignment.has(component[j])) {\n var actualNodes = this.dummyToNodeForHorizontalAlignment.get(component[j]);\n sum += actualNodes.length * this.idToNodeMap.get(actualNodes[0]).displacementY;\n count += actualNodes.length;\n } else {\n sum += this.idToNodeMap.get(component[j]).displacementY;\n count++;\n }\n }\n var averageDisplacement = sum / count;\n for (var j = 0; j < component.length; j++) {\n if (this.dummyToNodeForHorizontalAlignment.has(component[j])) {\n this.dummyToNodeForHorizontalAlignment.get(component[j]).forEach(function (nodeId) {\n self.idToNodeMap.get(nodeId).displacementY = averageDisplacement;\n });\n } else {\n this.idToNodeMap.get(component[j]).displacementY = averageDisplacement;\n }\n }\n }\n }\n }\n }\n};\n\nCoSELayout.prototype.calculateNodesToApplyGravitationTo = function () {\n var nodeList = [];\n var graph;\n\n var graphs = this.graphManager.getGraphs();\n var size = graphs.length;\n var i;\n for (i = 0; i < size; i++) {\n graph = graphs[i];\n\n graph.updateConnected();\n\n if (!graph.isConnected) {\n nodeList = nodeList.concat(graph.getNodes());\n }\n }\n\n return nodeList;\n};\n\nCoSELayout.prototype.createBendpoints = function () {\n var edges = [];\n edges = edges.concat(this.graphManager.getAllEdges());\n var visited = new Set();\n var i;\n for (i = 0; i < edges.length; i++) {\n var edge = edges[i];\n\n if (!visited.has(edge)) {\n var source = edge.getSource();\n var target = edge.getTarget();\n\n if (source == target) {\n edge.getBendpoints().push(new PointD());\n edge.getBendpoints().push(new PointD());\n this.createDummyNodesForBendpoints(edge);\n visited.add(edge);\n } else {\n var edgeList = [];\n\n edgeList = edgeList.concat(source.getEdgeListToNode(target));\n edgeList = edgeList.concat(target.getEdgeListToNode(source));\n\n if (!visited.has(edgeList[0])) {\n if (edgeList.length > 1) {\n var k;\n for (k = 0; k < edgeList.length; k++) {\n var multiEdge = edgeList[k];\n multiEdge.getBendpoints().push(new PointD());\n this.createDummyNodesForBendpoints(multiEdge);\n }\n }\n edgeList.forEach(function (edge) {\n visited.add(edge);\n });\n }\n }\n }\n\n if (visited.size == edges.length) {\n break;\n }\n }\n};\n\nCoSELayout.prototype.positionNodesRadially = function (forest) {\n // We tile the trees to a grid row by row; first tree starts at (0,0)\n var currentStartingPoint = new Point(0, 0);\n var numberOfColumns = Math.ceil(Math.sqrt(forest.length));\n var height = 0;\n var currentY = 0;\n var currentX = 0;\n var point = new PointD(0, 0);\n\n for (var i = 0; i < forest.length; i++) {\n if (i % numberOfColumns == 0) {\n // Start of a new row, make the x coordinate 0, increment the\n // y coordinate with the max height of the previous row\n currentX = 0;\n currentY = height;\n\n if (i != 0) {\n currentY += CoSEConstants.DEFAULT_COMPONENT_SEPERATION;\n }\n\n height = 0;\n }\n\n var tree = forest[i];\n\n // Find the center of the tree\n var centerNode = Layout.findCenterOfTree(tree);\n\n // Set the staring point of the next tree\n currentStartingPoint.x = currentX;\n currentStartingPoint.y = currentY;\n\n // Do a radial layout starting with the center\n point = CoSELayout.radialLayout(tree, centerNode, currentStartingPoint);\n\n if (point.y > height) {\n height = Math.floor(point.y);\n }\n\n currentX = Math.floor(point.x + CoSEConstants.DEFAULT_COMPONENT_SEPERATION);\n }\n\n this.transform(new PointD(LayoutConstants.WORLD_CENTER_X - point.x / 2, LayoutConstants.WORLD_CENTER_Y - point.y / 2));\n};\n\nCoSELayout.radialLayout = function (tree, centerNode, startingPoint) {\n var radialSep = Math.max(this.maxDiagonalInTree(tree), CoSEConstants.DEFAULT_RADIAL_SEPARATION);\n CoSELayout.branchRadialLayout(centerNode, null, 0, 359, 0, radialSep);\n var bounds = LGraph.calculateBounds(tree);\n\n var transform = new Transform();\n transform.setDeviceOrgX(bounds.getMinX());\n transform.setDeviceOrgY(bounds.getMinY());\n transform.setWorldOrgX(startingPoint.x);\n transform.setWorldOrgY(startingPoint.y);\n\n for (var i = 0; i < tree.length; i++) {\n var node = tree[i];\n node.transform(transform);\n }\n\n var bottomRight = new PointD(bounds.getMaxX(), bounds.getMaxY());\n\n return transform.inverseTransformPoint(bottomRight);\n};\n\nCoSELayout.branchRadialLayout = function (node, parentOfNode, startAngle, endAngle, distance, radialSeparation) {\n // First, position this node by finding its angle.\n var halfInterval = (endAngle - startAngle + 1) / 2;\n\n if (halfInterval < 0) {\n halfInterval += 180;\n }\n\n var nodeAngle = (halfInterval + startAngle) % 360;\n var teta = nodeAngle * IGeometry.TWO_PI / 360;\n\n // Make polar to java cordinate conversion.\n var cos_teta = Math.cos(teta);\n var x_ = distance * Math.cos(teta);\n var y_ = distance * Math.sin(teta);\n\n node.setCenter(x_, y_);\n\n // Traverse all neighbors of this node and recursively call this\n // function.\n var neighborEdges = [];\n neighborEdges = neighborEdges.concat(node.getEdges());\n var childCount = neighborEdges.length;\n\n if (parentOfNode != null) {\n childCount--;\n }\n\n var branchCount = 0;\n\n var incEdgesCount = neighborEdges.length;\n var startIndex;\n\n var edges = node.getEdgesBetween(parentOfNode);\n\n // If there are multiple edges, prune them until there remains only one\n // edge.\n while (edges.length > 1) {\n //neighborEdges.remove(edges.remove(0));\n var temp = edges[0];\n edges.splice(0, 1);\n var index = neighborEdges.indexOf(temp);\n if (index >= 0) {\n neighborEdges.splice(index, 1);\n }\n incEdgesCount--;\n childCount--;\n }\n\n if (parentOfNode != null) {\n //assert edges.length == 1;\n startIndex = (neighborEdges.indexOf(edges[0]) + 1) % incEdgesCount;\n } else {\n startIndex = 0;\n }\n\n var stepAngle = Math.abs(endAngle - startAngle) / childCount;\n\n for (var i = startIndex; branchCount != childCount; i = ++i % incEdgesCount) {\n var currentNeighbor = neighborEdges[i].getOtherEnd(node);\n\n // Don't back traverse to root node in current tree.\n if (currentNeighbor == parentOfNode) {\n continue;\n }\n\n var childStartAngle = (startAngle + branchCount * stepAngle) % 360;\n var childEndAngle = (childStartAngle + stepAngle) % 360;\n\n CoSELayout.branchRadialLayout(currentNeighbor, node, childStartAngle, childEndAngle, distance + radialSeparation, radialSeparation);\n\n branchCount++;\n }\n};\n\nCoSELayout.maxDiagonalInTree = function (tree) {\n var maxDiagonal = Integer.MIN_VALUE;\n\n for (var i = 0; i < tree.length; i++) {\n var node = tree[i];\n var diagonal = node.getDiagonal();\n\n if (diagonal > maxDiagonal) {\n maxDiagonal = diagonal;\n }\n }\n\n return maxDiagonal;\n};\n\nCoSELayout.prototype.calcRepulsionRange = function () {\n // formula is 2 x (level + 1) x idealEdgeLength\n return 2 * (this.level + 1) * this.idealEdgeLength;\n};\n\n// Tiling methods\n\n// Group zero degree members whose parents are not to be tiled, create dummy parents where needed and fill memberGroups by their dummp parent id's\nCoSELayout.prototype.groupZeroDegreeMembers = function () {\n var self = this;\n // array of [parent_id x oneDegreeNode_id]\n var tempMemberGroups = {}; // A temporary map of parent node and its zero degree members\n this.memberGroups = {}; // A map of dummy parent node and its zero degree members whose parents are not to be tiled\n this.idToDummyNode = {}; // A map of id to dummy node \n\n var zeroDegree = []; // List of zero degree nodes whose parents are not to be tiled\n var allNodes = this.graphManager.getAllNodes();\n\n // Fill zero degree list\n for (var i = 0; i < allNodes.length; i++) {\n var node = allNodes[i];\n var parent = node.getParent();\n // If a node has zero degree and its parent is not to be tiled if exists add that node to zeroDegres list\n if (this.getNodeDegreeWithChildren(node) === 0 && (parent.id == undefined || !this.getToBeTiled(parent))) {\n zeroDegree.push(node);\n }\n }\n\n // Create a map of parent node and its zero degree members\n for (var i = 0; i < zeroDegree.length; i++) {\n var node = zeroDegree[i]; // Zero degree node itself\n var p_id = node.getParent().id; // Parent id\n\n if (typeof tempMemberGroups[p_id] === \"undefined\") tempMemberGroups[p_id] = [];\n\n tempMemberGroups[p_id] = tempMemberGroups[p_id].concat(node); // Push node to the list belongs to its parent in tempMemberGroups\n }\n\n // If there are at least two nodes at a level, create a dummy compound for them\n Object.keys(tempMemberGroups).forEach(function (p_id) {\n if (tempMemberGroups[p_id].length > 1) {\n var dummyCompoundId = \"DummyCompound_\" + p_id; // The id of dummy compound which will be created soon\n self.memberGroups[dummyCompoundId] = tempMemberGroups[p_id]; // Add dummy compound to memberGroups\n\n var parent = tempMemberGroups[p_id][0].getParent(); // The parent of zero degree nodes will be the parent of new dummy compound\n\n // Create a dummy compound with calculated id\n var dummyCompound = new CoSENode(self.graphManager);\n dummyCompound.id = dummyCompoundId;\n dummyCompound.paddingLeft = parent.paddingLeft || 0;\n dummyCompound.paddingRight = parent.paddingRight || 0;\n dummyCompound.paddingBottom = parent.paddingBottom || 0;\n dummyCompound.paddingTop = parent.paddingTop || 0;\n\n self.idToDummyNode[dummyCompoundId] = dummyCompound;\n\n var dummyParentGraph = self.getGraphManager().add(self.newGraph(), dummyCompound);\n var parentGraph = parent.getChild();\n\n // Add dummy compound to parent the graph\n parentGraph.add(dummyCompound);\n\n // For each zero degree node in this level remove it from its parent graph and add it to the graph of dummy parent\n for (var i = 0; i < tempMemberGroups[p_id].length; i++) {\n var node = tempMemberGroups[p_id][i];\n\n parentGraph.remove(node);\n dummyParentGraph.add(node);\n }\n }\n });\n};\n\nCoSELayout.prototype.clearCompounds = function () {\n var childGraphMap = {};\n var idToNode = {};\n\n // Get compound ordering by finding the inner one first\n this.performDFSOnCompounds();\n\n for (var i = 0; i < this.compoundOrder.length; i++) {\n\n idToNode[this.compoundOrder[i].id] = this.compoundOrder[i];\n childGraphMap[this.compoundOrder[i].id] = [].concat(this.compoundOrder[i].getChild().getNodes());\n\n // Remove children of compounds\n this.graphManager.remove(this.compoundOrder[i].getChild());\n this.compoundOrder[i].child = null;\n }\n\n this.graphManager.resetAllNodes();\n\n // Tile the removed children\n this.tileCompoundMembers(childGraphMap, idToNode);\n};\n\nCoSELayout.prototype.clearZeroDegreeMembers = function () {\n var self = this;\n var tiledZeroDegreePack = this.tiledZeroDegreePack = [];\n\n Object.keys(this.memberGroups).forEach(function (id) {\n var compoundNode = self.idToDummyNode[id]; // Get the dummy compound\n\n tiledZeroDegreePack[id] = self.tileNodes(self.memberGroups[id], compoundNode.paddingLeft + compoundNode.paddingRight);\n\n // Set the width and height of the dummy compound as calculated\n compoundNode.rect.width = tiledZeroDegreePack[id].width;\n compoundNode.rect.height = tiledZeroDegreePack[id].height;\n compoundNode.setCenter(tiledZeroDegreePack[id].centerX, tiledZeroDegreePack[id].centerY);\n\n // compound left and top margings for labels\n // when node labels are included, these values may be set to different values below and are used in tilingPostLayout,\n // otherwise they stay as zero\n compoundNode.labelMarginLeft = 0;\n compoundNode.labelMarginTop = 0;\n\n // Update compound bounds considering its label properties and set label margins for left and top\n if (CoSEConstants.NODE_DIMENSIONS_INCLUDE_LABELS) {\n\n var width = compoundNode.rect.width;\n var height = compoundNode.rect.height;\n\n if (compoundNode.labelWidth) {\n if (compoundNode.labelPosHorizontal == \"left\") {\n compoundNode.rect.x -= compoundNode.labelWidth;\n compoundNode.setWidth(width + compoundNode.labelWidth);\n compoundNode.labelMarginLeft = compoundNode.labelWidth;\n } else if (compoundNode.labelPosHorizontal == \"center\" && compoundNode.labelWidth > width) {\n compoundNode.rect.x -= (compoundNode.labelWidth - width) / 2;\n compoundNode.setWidth(compoundNode.labelWidth);\n compoundNode.labelMarginLeft = (compoundNode.labelWidth - width) / 2;\n } else if (compoundNode.labelPosHorizontal == \"right\") {\n compoundNode.setWidth(width + compoundNode.labelWidth);\n }\n }\n\n if (compoundNode.labelHeight) {\n if (compoundNode.labelPosVertical == \"top\") {\n compoundNode.rect.y -= compoundNode.labelHeight;\n compoundNode.setHeight(height + compoundNode.labelHeight);\n compoundNode.labelMarginTop = compoundNode.labelHeight;\n } else if (compoundNode.labelPosVertical == \"center\" && compoundNode.labelHeight > height) {\n compoundNode.rect.y -= (compoundNode.labelHeight - height) / 2;\n compoundNode.setHeight(compoundNode.labelHeight);\n compoundNode.labelMarginTop = (compoundNode.labelHeight - height) / 2;\n } else if (compoundNode.labelPosVertical == \"bottom\") {\n compoundNode.setHeight(height + compoundNode.labelHeight);\n }\n }\n }\n });\n};\n\nCoSELayout.prototype.repopulateCompounds = function () {\n for (var i = this.compoundOrder.length - 1; i >= 0; i--) {\n var lCompoundNode = this.compoundOrder[i];\n var id = lCompoundNode.id;\n var horizontalMargin = lCompoundNode.paddingLeft;\n var verticalMargin = lCompoundNode.paddingTop;\n var labelMarginLeft = lCompoundNode.labelMarginLeft;\n var labelMarginTop = lCompoundNode.labelMarginTop;\n\n this.adjustLocations(this.tiledMemberPack[id], lCompoundNode.rect.x, lCompoundNode.rect.y, horizontalMargin, verticalMargin, labelMarginLeft, labelMarginTop);\n }\n};\n\nCoSELayout.prototype.repopulateZeroDegreeMembers = function () {\n var self = this;\n var tiledPack = this.tiledZeroDegreePack;\n\n Object.keys(tiledPack).forEach(function (id) {\n var compoundNode = self.idToDummyNode[id]; // Get the dummy compound by its id\n var horizontalMargin = compoundNode.paddingLeft;\n var verticalMargin = compoundNode.paddingTop;\n var labelMarginLeft = compoundNode.labelMarginLeft;\n var labelMarginTop = compoundNode.labelMarginTop;\n\n // Adjust the positions of nodes wrt its compound\n self.adjustLocations(tiledPack[id], compoundNode.rect.x, compoundNode.rect.y, horizontalMargin, verticalMargin, labelMarginLeft, labelMarginTop);\n });\n};\n\nCoSELayout.prototype.getToBeTiled = function (node) {\n var id = node.id;\n //firstly check the previous results\n if (this.toBeTiled[id] != null) {\n return this.toBeTiled[id];\n }\n\n //only compound nodes are to be tiled\n var childGraph = node.getChild();\n if (childGraph == null) {\n this.toBeTiled[id] = false;\n return false;\n }\n\n var children = childGraph.getNodes(); // Get the children nodes\n\n //a compound node is not to be tiled if all of its compound children are not to be tiled\n for (var i = 0; i < children.length; i++) {\n var theChild = children[i];\n\n if (this.getNodeDegree(theChild) > 0) {\n this.toBeTiled[id] = false;\n return false;\n }\n\n //pass the children not having the compound structure\n if (theChild.getChild() == null) {\n this.toBeTiled[theChild.id] = false;\n continue;\n }\n\n if (!this.getToBeTiled(theChild)) {\n this.toBeTiled[id] = false;\n return false;\n }\n }\n this.toBeTiled[id] = true;\n return true;\n};\n\n// Get degree of a node depending of its edges and independent of its children\nCoSELayout.prototype.getNodeDegree = function (node) {\n var id = node.id;\n var edges = node.getEdges();\n var degree = 0;\n\n // For the edges connected\n for (var i = 0; i < edges.length; i++) {\n var edge = edges[i];\n if (edge.getSource().id !== edge.getTarget().id) {\n degree = degree + 1;\n }\n }\n return degree;\n};\n\n// Get degree of a node with its children\nCoSELayout.prototype.getNodeDegreeWithChildren = function (node) {\n var degree = this.getNodeDegree(node);\n if (node.getChild() == null) {\n return degree;\n }\n var children = node.getChild().getNodes();\n for (var i = 0; i < children.length; i++) {\n var child = children[i];\n degree += this.getNodeDegreeWithChildren(child);\n }\n return degree;\n};\n\nCoSELayout.prototype.performDFSOnCompounds = function () {\n this.compoundOrder = [];\n this.fillCompexOrderByDFS(this.graphManager.getRoot().getNodes());\n};\n\nCoSELayout.prototype.fillCompexOrderByDFS = function (children) {\n for (var i = 0; i < children.length; i++) {\n var child = children[i];\n if (child.getChild() != null) {\n this.fillCompexOrderByDFS(child.getChild().getNodes());\n }\n if (this.getToBeTiled(child)) {\n this.compoundOrder.push(child);\n }\n }\n};\n\n/**\n* This method places each zero degree member wrt given (x,y) coordinates (top left).\n*/\nCoSELayout.prototype.adjustLocations = function (organization, x, y, compoundHorizontalMargin, compoundVerticalMargin, compoundLabelMarginLeft, compoundLabelMarginTop) {\n x += compoundHorizontalMargin + compoundLabelMarginLeft;\n y += compoundVerticalMargin + compoundLabelMarginTop;\n\n var left = x;\n\n for (var i = 0; i < organization.rows.length; i++) {\n var row = organization.rows[i];\n x = left;\n var maxHeight = 0;\n\n for (var j = 0; j < row.length; j++) {\n var lnode = row[j];\n\n lnode.rect.x = x; // + lnode.rect.width / 2;\n lnode.rect.y = y; // + lnode.rect.height / 2;\n\n x += lnode.rect.width + organization.horizontalPadding;\n\n if (lnode.rect.height > maxHeight) maxHeight = lnode.rect.height;\n }\n\n y += maxHeight + organization.verticalPadding;\n }\n};\n\nCoSELayout.prototype.tileCompoundMembers = function (childGraphMap, idToNode) {\n var self = this;\n this.tiledMemberPack = [];\n\n Object.keys(childGraphMap).forEach(function (id) {\n // Get the compound node\n var compoundNode = idToNode[id];\n\n self.tiledMemberPack[id] = self.tileNodes(childGraphMap[id], compoundNode.paddingLeft + compoundNode.paddingRight);\n\n compoundNode.rect.width = self.tiledMemberPack[id].width;\n compoundNode.rect.height = self.tiledMemberPack[id].height;\n compoundNode.setCenter(self.tiledMemberPack[id].centerX, self.tiledMemberPack[id].centerY);\n\n // compound left and top margings for labels\n // when node labels are included, these values may be set to different values below and are used in tilingPostLayout,\n // otherwise they stay as zero\n compoundNode.labelMarginLeft = 0;\n compoundNode.labelMarginTop = 0;\n\n // Update compound bounds considering its label properties and set label margins for left and top\n if (CoSEConstants.NODE_DIMENSIONS_INCLUDE_LABELS) {\n\n var width = compoundNode.rect.width;\n var height = compoundNode.rect.height;\n\n if (compoundNode.labelWidth) {\n if (compoundNode.labelPosHorizontal == \"left\") {\n compoundNode.rect.x -= compoundNode.labelWidth;\n compoundNode.setWidth(width + compoundNode.labelWidth);\n compoundNode.labelMarginLeft = compoundNode.labelWidth;\n } else if (compoundNode.labelPosHorizontal == \"center\" && compoundNode.labelWidth > width) {\n compoundNode.rect.x -= (compoundNode.labelWidth - width) / 2;\n compoundNode.setWidth(compoundNode.labelWidth);\n compoundNode.labelMarginLeft = (compoundNode.labelWidth - width) / 2;\n } else if (compoundNode.labelPosHorizontal == \"right\") {\n compoundNode.setWidth(width + compoundNode.labelWidth);\n }\n }\n\n if (compoundNode.labelHeight) {\n if (compoundNode.labelPosVertical == \"top\") {\n compoundNode.rect.y -= compoundNode.labelHeight;\n compoundNode.setHeight(height + compoundNode.labelHeight);\n compoundNode.labelMarginTop = compoundNode.labelHeight;\n } else if (compoundNode.labelPosVertical == \"center\" && compoundNode.labelHeight > height) {\n compoundNode.rect.y -= (compoundNode.labelHeight - height) / 2;\n compoundNode.setHeight(compoundNode.labelHeight);\n compoundNode.labelMarginTop = (compoundNode.labelHeight - height) / 2;\n } else if (compoundNode.labelPosVertical == \"bottom\") {\n compoundNode.setHeight(height + compoundNode.labelHeight);\n }\n }\n }\n });\n};\n\nCoSELayout.prototype.tileNodes = function (nodes, minWidth) {\n var horizontalOrg = this.tileNodesByFavoringDim(nodes, minWidth, true);\n var verticalOrg = this.tileNodesByFavoringDim(nodes, minWidth, false);\n\n var horizontalRatio = this.getOrgRatio(horizontalOrg);\n var verticalRatio = this.getOrgRatio(verticalOrg);\n var bestOrg;\n\n // the best ratio is the one that is closer to 1 since the ratios are already normalized\n // and the best organization is the one that has the best ratio\n if (verticalRatio < horizontalRatio) {\n bestOrg = verticalOrg;\n } else {\n bestOrg = horizontalOrg;\n }\n\n return bestOrg;\n};\n\n// get the width/height ratio of the organization that is normalized so that it will not be less than 1\nCoSELayout.prototype.getOrgRatio = function (organization) {\n // get dimensions and calculate the initial ratio\n var width = organization.width;\n var height = organization.height;\n var ratio = width / height;\n\n // if the initial ratio is less then 1 then inverse it\n if (ratio < 1) {\n ratio = 1 / ratio;\n }\n\n // return the normalized ratio\n return ratio;\n};\n\n/*\n * Calculates the ideal width for the rows. This method assumes that\n * each node has the same sizes and calculates the ideal row width that\n * approximates a square shaped complex accordingly. However, since nodes would\n * have different sizes some rows would have different sizes and the resulting\n * shape would not be an exact square.\n */\nCoSELayout.prototype.calcIdealRowWidth = function (members, favorHorizontalDim) {\n // To approximate a square shaped complex we need to make complex width equal to complex height.\n // To achieve this we need to solve the following equation system for hc:\n // (x + bx) * hc - bx = (y + by) * vc - by, hc * vc = n\n // where x is the avarage width of the nodes, y is the avarage height of nodes\n // bx and by are the buffer sizes in horizontal and vertical dimensions accordingly,\n // hc and vc are the number of rows in horizontal and vertical dimensions\n // n is number of members.\n\n var verticalPadding = CoSEConstants.TILING_PADDING_VERTICAL;\n var horizontalPadding = CoSEConstants.TILING_PADDING_HORIZONTAL;\n\n // number of members\n var membersSize = members.length;\n\n // sum of the width of all members\n var totalWidth = 0;\n\n // sum of the height of all members\n var totalHeight = 0;\n\n var maxWidth = 0;\n\n // traverse all members to calculate total width and total height and get the maximum members width\n members.forEach(function (node) {\n totalWidth += node.getWidth();\n totalHeight += node.getHeight();\n\n if (node.getWidth() > maxWidth) {\n maxWidth = node.getWidth();\n }\n });\n\n // average width of the members\n var averageWidth = totalWidth / membersSize;\n\n // average height of the members\n var averageHeight = totalHeight / membersSize;\n\n // solving the initial equation system for the hc yields the following second degree equation:\n // hc^2 * (x+bx) + hc * (by - bx) - n * (y + by) = 0\n\n // the delta value to solve the equation above for hc\n var delta = Math.pow(verticalPadding - horizontalPadding, 2) + 4 * (averageWidth + horizontalPadding) * (averageHeight + verticalPadding) * membersSize;\n\n // solve the equation using delta value to calculate the horizontal count\n // that represents the number of nodes in an ideal row\n var horizontalCountDouble = (horizontalPadding - verticalPadding + Math.sqrt(delta)) / (2 * (averageWidth + horizontalPadding));\n // round the calculated horizontal count up or down according to the favored dimension\n var horizontalCount;\n\n if (favorHorizontalDim) {\n horizontalCount = Math.ceil(horizontalCountDouble);\n // if horizontalCount count is not a float value then both of rounding to floor and ceil\n // will yield the same values. Instead of repeating the same calculation try going up\n // while favoring horizontal dimension in such cases\n if (horizontalCount == horizontalCountDouble) {\n horizontalCount++;\n }\n } else {\n horizontalCount = Math.floor(horizontalCountDouble);\n }\n\n // ideal width to be calculated\n var idealWidth = horizontalCount * (averageWidth + horizontalPadding) - horizontalPadding;\n\n // if max width is bigger than calculated ideal width reset ideal width to it\n if (maxWidth > idealWidth) {\n idealWidth = maxWidth;\n }\n\n // add the left-right margins to the ideal row width\n idealWidth += horizontalPadding * 2;\n\n // return the ideal row width1\n return idealWidth;\n};\n\nCoSELayout.prototype.tileNodesByFavoringDim = function (nodes, minWidth, favorHorizontalDim) {\n var verticalPadding = CoSEConstants.TILING_PADDING_VERTICAL;\n var horizontalPadding = CoSEConstants.TILING_PADDING_HORIZONTAL;\n var tilingCompareBy = CoSEConstants.TILING_COMPARE_BY;\n var organization = {\n rows: [],\n rowWidth: [],\n rowHeight: [],\n width: 0,\n height: minWidth, // assume minHeight equals to minWidth\n verticalPadding: verticalPadding,\n horizontalPadding: horizontalPadding,\n centerX: 0,\n centerY: 0\n };\n\n if (tilingCompareBy) {\n organization.idealRowWidth = this.calcIdealRowWidth(nodes, favorHorizontalDim);\n }\n\n var getNodeArea = function getNodeArea(n) {\n return n.rect.width * n.rect.height;\n };\n\n var areaCompareFcn = function areaCompareFcn(n1, n2) {\n return getNodeArea(n2) - getNodeArea(n1);\n };\n\n // Sort the nodes in descending order of their areas\n nodes.sort(function (n1, n2) {\n var cmpBy = areaCompareFcn;\n if (organization.idealRowWidth) {\n cmpBy = tilingCompareBy;\n return cmpBy(n1.id, n2.id);\n }\n return cmpBy(n1, n2);\n });\n\n // Create the organization -> calculate compound center\n var sumCenterX = 0;\n var sumCenterY = 0;\n for (var i = 0; i < nodes.length; i++) {\n var lNode = nodes[i];\n\n sumCenterX += lNode.getCenterX();\n sumCenterY += lNode.getCenterY();\n }\n\n organization.centerX = sumCenterX / nodes.length;\n organization.centerY = sumCenterY / nodes.length;\n\n // Create the organization -> tile members\n for (var i = 0; i < nodes.length; i++) {\n var lNode = nodes[i];\n\n if (organization.rows.length == 0) {\n this.insertNodeToRow(organization, lNode, 0, minWidth);\n } else if (this.canAddHorizontal(organization, lNode.rect.width, lNode.rect.height)) {\n var rowIndex = organization.rows.length - 1;\n if (!organization.idealRowWidth) {\n rowIndex = this.getShortestRowIndex(organization);\n }\n this.insertNodeToRow(organization, lNode, rowIndex, minWidth);\n } else {\n this.insertNodeToRow(organization, lNode, organization.rows.length, minWidth);\n }\n\n this.shiftToLastRow(organization);\n }\n\n return organization;\n};\n\nCoSELayout.prototype.insertNodeToRow = function (organization, node, rowIndex, minWidth) {\n var minCompoundSize = minWidth;\n\n // Add new row if needed\n if (rowIndex == organization.rows.length) {\n var secondDimension = [];\n\n organization.rows.push(secondDimension);\n organization.rowWidth.push(minCompoundSize);\n organization.rowHeight.push(0);\n }\n\n // Update row width\n var w = organization.rowWidth[rowIndex] + node.rect.width;\n\n if (organization.rows[rowIndex].length > 0) {\n w += organization.horizontalPadding;\n }\n\n organization.rowWidth[rowIndex] = w;\n // Update compound width\n if (organization.width < w) {\n organization.width = w;\n }\n\n // Update height\n var h = node.rect.height;\n if (rowIndex > 0) h += organization.verticalPadding;\n\n var extraHeight = 0;\n if (h > organization.rowHeight[rowIndex]) {\n extraHeight = organization.rowHeight[rowIndex];\n organization.rowHeight[rowIndex] = h;\n extraHeight = organization.rowHeight[rowIndex] - extraHeight;\n }\n\n organization.height += extraHeight;\n\n // Insert node\n organization.rows[rowIndex].push(node);\n};\n\n//Scans the rows of an organization and returns the one with the min width\nCoSELayout.prototype.getShortestRowIndex = function (organization) {\n var r = -1;\n var min = Number.MAX_VALUE;\n\n for (var i = 0; i < organization.rows.length; i++) {\n if (organization.rowWidth[i] < min) {\n r = i;\n min = organization.rowWidth[i];\n }\n }\n return r;\n};\n\n//Scans the rows of an organization and returns the one with the max width\nCoSELayout.prototype.getLongestRowIndex = function (organization) {\n var r = -1;\n var max = Number.MIN_VALUE;\n\n for (var i = 0; i < organization.rows.length; i++) {\n\n if (organization.rowWidth[i] > max) {\n r = i;\n max = organization.rowWidth[i];\n }\n }\n\n return r;\n};\n\n/**\n* This method checks whether adding extra width to the organization violates\n* the aspect ratio(1) or not.\n*/\nCoSELayout.prototype.canAddHorizontal = function (organization, extraWidth, extraHeight) {\n\n // if there is an ideal row width specified use it instead of checking the aspect ratio\n if (organization.idealRowWidth) {\n var lastRowIndex = organization.rows.length - 1;\n var lastRowWidth = organization.rowWidth[lastRowIndex];\n\n // check and return if ideal row width will be exceed if the node is added to the row\n return lastRowWidth + extraWidth + organization.horizontalPadding <= organization.idealRowWidth;\n }\n\n var sri = this.getShortestRowIndex(organization);\n\n if (sri < 0) {\n return true;\n }\n\n var min = organization.rowWidth[sri];\n\n if (min + organization.horizontalPadding + extraWidth <= organization.width) return true;\n\n var hDiff = 0;\n\n // Adding to an existing row\n if (organization.rowHeight[sri] < extraHeight) {\n if (sri > 0) hDiff = extraHeight + organization.verticalPadding - organization.rowHeight[sri];\n }\n\n var add_to_row_ratio;\n if (organization.width - min >= extraWidth + organization.horizontalPadding) {\n add_to_row_ratio = (organization.height + hDiff) / (min + extraWidth + organization.horizontalPadding);\n } else {\n add_to_row_ratio = (organization.height + hDiff) / organization.width;\n }\n\n // Adding a new row for this node\n hDiff = extraHeight + organization.verticalPadding;\n var add_new_row_ratio;\n if (organization.width < extraWidth) {\n add_new_row_ratio = (organization.height + hDiff) / extraWidth;\n } else {\n add_new_row_ratio = (organization.height + hDiff) / organization.width;\n }\n\n if (add_new_row_ratio < 1) add_new_row_ratio = 1 / add_new_row_ratio;\n\n if (add_to_row_ratio < 1) add_to_row_ratio = 1 / add_to_row_ratio;\n\n return add_to_row_ratio < add_new_row_ratio;\n};\n\n//If moving the last node from the longest row and adding it to the last\n//row makes the bounding box smaller, do it.\nCoSELayout.prototype.shiftToLastRow = function (organization) {\n var longest = this.getLongestRowIndex(organization);\n var last = organization.rowWidth.length - 1;\n var row = organization.rows[longest];\n var node = row[row.length - 1];\n\n var diff = node.width + organization.horizontalPadding;\n\n // Check if there is enough space on the last row\n if (organization.width - organization.rowWidth[last] > diff && longest != last) {\n // Remove the last element of the longest row\n row.splice(-1, 1);\n\n // Push it to the last row\n organization.rows[last].push(node);\n\n organization.rowWidth[longest] = organization.rowWidth[longest] - diff;\n organization.rowWidth[last] = organization.rowWidth[last] + diff;\n organization.width = organization.rowWidth[instance.getLongestRowIndex(organization)];\n\n // Update heights of the organization\n var maxHeight = Number.MIN_VALUE;\n for (var i = 0; i < row.length; i++) {\n if (row[i].height > maxHeight) maxHeight = row[i].height;\n }\n if (longest > 0) maxHeight += organization.verticalPadding;\n\n var prevTotal = organization.rowHeight[longest] + organization.rowHeight[last];\n\n organization.rowHeight[longest] = maxHeight;\n if (organization.rowHeight[last] < node.height + organization.verticalPadding) organization.rowHeight[last] = node.height + organization.verticalPadding;\n\n var finalTotal = organization.rowHeight[longest] + organization.rowHeight[last];\n organization.height += finalTotal - prevTotal;\n\n this.shiftToLastRow(organization);\n }\n};\n\nCoSELayout.prototype.tilingPreLayout = function () {\n if (CoSEConstants.TILE) {\n // Find zero degree nodes and create a compound for each level\n this.groupZeroDegreeMembers();\n // Tile and clear children of each compound\n this.clearCompounds();\n // Separately tile and clear zero degree nodes for each level\n this.clearZeroDegreeMembers();\n }\n};\n\nCoSELayout.prototype.tilingPostLayout = function () {\n if (CoSEConstants.TILE) {\n this.repopulateZeroDegreeMembers();\n this.repopulateCompounds();\n }\n};\n\n// -----------------------------------------------------------------------------\n// Section: Tree Reduction methods\n// -----------------------------------------------------------------------------\n// Reduce trees \nCoSELayout.prototype.reduceTrees = function () {\n var prunedNodesAll = [];\n var containsLeaf = true;\n var node;\n\n while (containsLeaf) {\n var allNodes = this.graphManager.getAllNodes();\n var prunedNodesInStepTemp = [];\n containsLeaf = false;\n\n for (var i = 0; i < allNodes.length; i++) {\n node = allNodes[i];\n if (node.getEdges().length == 1 && !node.getEdges()[0].isInterGraph && node.getChild() == null) {\n if (CoSEConstants.PURE_INCREMENTAL) {\n var otherEnd = node.getEdges()[0].getOtherEnd(node);\n var relativePosition = new DimensionD(node.getCenterX() - otherEnd.getCenterX(), node.getCenterY() - otherEnd.getCenterY());\n prunedNodesInStepTemp.push([node, node.getEdges()[0], node.getOwner(), relativePosition]);\n } else {\n prunedNodesInStepTemp.push([node, node.getEdges()[0], node.getOwner()]);\n }\n containsLeaf = true;\n }\n }\n if (containsLeaf == true) {\n var prunedNodesInStep = [];\n for (var j = 0; j < prunedNodesInStepTemp.length; j++) {\n if (prunedNodesInStepTemp[j][0].getEdges().length == 1) {\n prunedNodesInStep.push(prunedNodesInStepTemp[j]);\n prunedNodesInStepTemp[j][0].getOwner().remove(prunedNodesInStepTemp[j][0]);\n }\n }\n prunedNodesAll.push(prunedNodesInStep);\n this.graphManager.resetAllNodes();\n this.graphManager.resetAllEdges();\n }\n }\n this.prunedNodesAll = prunedNodesAll;\n};\n\n// Grow tree one step \nCoSELayout.prototype.growTree = function (prunedNodesAll) {\n var lengthOfPrunedNodesInStep = prunedNodesAll.length;\n var prunedNodesInStep = prunedNodesAll[lengthOfPrunedNodesInStep - 1];\n\n var nodeData;\n for (var i = 0; i < prunedNodesInStep.length; i++) {\n nodeData = prunedNodesInStep[i];\n\n this.findPlaceforPrunedNode(nodeData);\n\n nodeData[2].add(nodeData[0]);\n nodeData[2].add(nodeData[1], nodeData[1].source, nodeData[1].target);\n }\n\n prunedNodesAll.splice(prunedNodesAll.length - 1, 1);\n this.graphManager.resetAllNodes();\n this.graphManager.resetAllEdges();\n};\n\n// Find an appropriate position to replace pruned node, this method can be improved\nCoSELayout.prototype.findPlaceforPrunedNode = function (nodeData) {\n\n var gridForPrunedNode;\n var nodeToConnect;\n var prunedNode = nodeData[0];\n if (prunedNode == nodeData[1].source) {\n nodeToConnect = nodeData[1].target;\n } else {\n nodeToConnect = nodeData[1].source;\n }\n\n if (CoSEConstants.PURE_INCREMENTAL) {\n prunedNode.setCenter(nodeToConnect.getCenterX() + nodeData[3].getWidth(), nodeToConnect.getCenterY() + nodeData[3].getHeight());\n } else {\n var startGridX = nodeToConnect.startX;\n var finishGridX = nodeToConnect.finishX;\n var startGridY = nodeToConnect.startY;\n var finishGridY = nodeToConnect.finishY;\n\n var upNodeCount = 0;\n var downNodeCount = 0;\n var rightNodeCount = 0;\n var leftNodeCount = 0;\n var controlRegions = [upNodeCount, rightNodeCount, downNodeCount, leftNodeCount];\n\n if (startGridY > 0) {\n for (var i = startGridX; i <= finishGridX; i++) {\n controlRegions[0] += this.grid[i][startGridY - 1].length + this.grid[i][startGridY].length - 1;\n }\n }\n if (finishGridX < this.grid.length - 1) {\n for (var i = startGridY; i <= finishGridY; i++) {\n controlRegions[1] += this.grid[finishGridX + 1][i].length + this.grid[finishGridX][i].length - 1;\n }\n }\n if (finishGridY < this.grid[0].length - 1) {\n for (var i = startGridX; i <= finishGridX; i++) {\n controlRegions[2] += this.grid[i][finishGridY + 1].length + this.grid[i][finishGridY].length - 1;\n }\n }\n if (startGridX > 0) {\n for (var i = startGridY; i <= finishGridY; i++) {\n controlRegions[3] += this.grid[startGridX - 1][i].length + this.grid[startGridX][i].length - 1;\n }\n }\n var min = Integer.MAX_VALUE;\n var minCount;\n var minIndex;\n for (var j = 0; j < controlRegions.length; j++) {\n if (controlRegions[j] < min) {\n min = controlRegions[j];\n minCount = 1;\n minIndex = j;\n } else if (controlRegions[j] == min) {\n minCount++;\n }\n }\n\n if (minCount == 3 && min == 0) {\n if (controlRegions[0] == 0 && controlRegions[1] == 0 && controlRegions[2] == 0) {\n gridForPrunedNode = 1;\n } else if (controlRegions[0] == 0 && controlRegions[1] == 0 && controlRegions[3] == 0) {\n gridForPrunedNode = 0;\n } else if (controlRegions[0] == 0 && controlRegions[2] == 0 && controlRegions[3] == 0) {\n gridForPrunedNode = 3;\n } else if (controlRegions[1] == 0 && controlRegions[2] == 0 && controlRegions[3] == 0) {\n gridForPrunedNode = 2;\n }\n } else if (minCount == 2 && min == 0) {\n var random = Math.floor(Math.random() * 2);\n if (controlRegions[0] == 0 && controlRegions[1] == 0) {\n ;\n if (random == 0) {\n gridForPrunedNode = 0;\n } else {\n gridForPrunedNode = 1;\n }\n } else if (controlRegions[0] == 0 && controlRegions[2] == 0) {\n if (random == 0) {\n gridForPrunedNode = 0;\n } else {\n gridForPrunedNode = 2;\n }\n } else if (controlRegions[0] == 0 && controlRegions[3] == 0) {\n if (random == 0) {\n gridForPrunedNode = 0;\n } else {\n gridForPrunedNode = 3;\n }\n } else if (controlRegions[1] == 0 && controlRegions[2] == 0) {\n if (random == 0) {\n gridForPrunedNode = 1;\n } else {\n gridForPrunedNode = 2;\n }\n } else if (controlRegions[1] == 0 && controlRegions[3] == 0) {\n if (random == 0) {\n gridForPrunedNode = 1;\n } else {\n gridForPrunedNode = 3;\n }\n } else {\n if (random == 0) {\n gridForPrunedNode = 2;\n } else {\n gridForPrunedNode = 3;\n }\n }\n } else if (minCount == 4 && min == 0) {\n var random = Math.floor(Math.random() * 4);\n gridForPrunedNode = random;\n } else {\n gridForPrunedNode = minIndex;\n }\n\n if (gridForPrunedNode == 0) {\n prunedNode.setCenter(nodeToConnect.getCenterX(), nodeToConnect.getCenterY() - nodeToConnect.getHeight() / 2 - FDLayoutConstants.DEFAULT_EDGE_LENGTH - prunedNode.getHeight() / 2);\n } else if (gridForPrunedNode == 1) {\n prunedNode.setCenter(nodeToConnect.getCenterX() + nodeToConnect.getWidth() / 2 + FDLayoutConstants.DEFAULT_EDGE_LENGTH + prunedNode.getWidth() / 2, nodeToConnect.getCenterY());\n } else if (gridForPrunedNode == 2) {\n prunedNode.setCenter(nodeToConnect.getCenterX(), nodeToConnect.getCenterY() + nodeToConnect.getHeight() / 2 + FDLayoutConstants.DEFAULT_EDGE_LENGTH + prunedNode.getHeight() / 2);\n } else {\n prunedNode.setCenter(nodeToConnect.getCenterX() - nodeToConnect.getWidth() / 2 - FDLayoutConstants.DEFAULT_EDGE_LENGTH - prunedNode.getWidth() / 2, nodeToConnect.getCenterY());\n }\n }\n};\n\nmodule.exports = CoSELayout;\n\n/***/ }),\n\n/***/ 991:\n/***/ ((module, __unused_webpack_exports, __webpack_require__) => {\n\n\n\nvar FDLayoutNode = __webpack_require__(551).FDLayoutNode;\nvar IMath = __webpack_require__(551).IMath;\n\nfunction CoSENode(gm, loc, size, vNode) {\n FDLayoutNode.call(this, gm, loc, size, vNode);\n}\n\nCoSENode.prototype = Object.create(FDLayoutNode.prototype);\nfor (var prop in FDLayoutNode) {\n CoSENode[prop] = FDLayoutNode[prop];\n}\n\nCoSENode.prototype.calculateDisplacement = function () {\n var layout = this.graphManager.getLayout();\n // this check is for compound nodes that contain fixed nodes\n if (this.getChild() != null && this.fixedNodeWeight) {\n this.displacementX += layout.coolingFactor * (this.springForceX + this.repulsionForceX + this.gravitationForceX) / this.fixedNodeWeight;\n this.displacementY += layout.coolingFactor * (this.springForceY + this.repulsionForceY + this.gravitationForceY) / this.fixedNodeWeight;\n } else {\n this.displacementX += layout.coolingFactor * (this.springForceX + this.repulsionForceX + this.gravitationForceX) / this.noOfChildren;\n this.displacementY += layout.coolingFactor * (this.springForceY + this.repulsionForceY + this.gravitationForceY) / this.noOfChildren;\n }\n\n if (Math.abs(this.displacementX) > layout.coolingFactor * layout.maxNodeDisplacement) {\n this.displacementX = layout.coolingFactor * layout.maxNodeDisplacement * IMath.sign(this.displacementX);\n }\n\n if (Math.abs(this.displacementY) > layout.coolingFactor * layout.maxNodeDisplacement) {\n this.displacementY = layout.coolingFactor * layout.maxNodeDisplacement * IMath.sign(this.displacementY);\n }\n\n // non-empty compound node, propogate movement to children as well\n if (this.child && this.child.getNodes().length > 0) {\n this.propogateDisplacementToChildren(this.displacementX, this.displacementY);\n }\n};\n\nCoSENode.prototype.propogateDisplacementToChildren = function (dX, dY) {\n var nodes = this.getChild().getNodes();\n var node;\n for (var i = 0; i < nodes.length; i++) {\n node = nodes[i];\n if (node.getChild() == null) {\n node.displacementX += dX;\n node.displacementY += dY;\n } else {\n node.propogateDisplacementToChildren(dX, dY);\n }\n }\n};\n\nCoSENode.prototype.move = function () {\n var layout = this.graphManager.getLayout();\n\n // a simple node or an empty compound node, move it\n if (this.child == null || this.child.getNodes().length == 0) {\n this.moveBy(this.displacementX, this.displacementY);\n\n layout.totalDisplacement += Math.abs(this.displacementX) + Math.abs(this.displacementY);\n }\n\n this.springForceX = 0;\n this.springForceY = 0;\n this.repulsionForceX = 0;\n this.repulsionForceY = 0;\n this.gravitationForceX = 0;\n this.gravitationForceY = 0;\n this.displacementX = 0;\n this.displacementY = 0;\n};\n\nCoSENode.prototype.setPred1 = function (pred1) {\n this.pred1 = pred1;\n};\n\nCoSENode.prototype.getPred1 = function () {\n return pred1;\n};\n\nCoSENode.prototype.getPred2 = function () {\n return pred2;\n};\n\nCoSENode.prototype.setNext = function (next) {\n this.next = next;\n};\n\nCoSENode.prototype.getNext = function () {\n return next;\n};\n\nCoSENode.prototype.setProcessed = function (processed) {\n this.processed = processed;\n};\n\nCoSENode.prototype.isProcessed = function () {\n return processed;\n};\n\nmodule.exports = CoSENode;\n\n/***/ }),\n\n/***/ 902:\n/***/ ((module, __unused_webpack_exports, __webpack_require__) => {\n\n\n\nfunction _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }\n\nvar CoSEConstants = __webpack_require__(806);\nvar LinkedList = __webpack_require__(551).LinkedList;\nvar Matrix = __webpack_require__(551).Matrix;\nvar SVD = __webpack_require__(551).SVD;\n\nfunction ConstraintHandler() {}\n\nConstraintHandler.handleConstraints = function (layout) {\n // let layout = this.graphManager.getLayout();\n\n // get constraints from layout\n var constraints = {};\n constraints.fixedNodeConstraint = layout.constraints.fixedNodeConstraint;\n constraints.alignmentConstraint = layout.constraints.alignmentConstraint;\n constraints.relativePlacementConstraint = layout.constraints.relativePlacementConstraint;\n\n var idToNodeMap = new Map();\n var nodeIndexes = new Map();\n var xCoords = [];\n var yCoords = [];\n\n var allNodes = layout.getAllNodes();\n var index = 0;\n // fill index map and coordinates\n for (var i = 0; i < allNodes.length; i++) {\n var node = allNodes[i];\n if (node.getChild() == null) {\n nodeIndexes.set(node.id, index++);\n xCoords.push(node.getCenterX());\n yCoords.push(node.getCenterY());\n idToNodeMap.set(node.id, node);\n }\n }\n\n // if there exists relative placement constraint without gap value, set it to default \n if (constraints.relativePlacementConstraint) {\n constraints.relativePlacementConstraint.forEach(function (constraint) {\n if (!constraint.gap && constraint.gap != 0) {\n if (constraint.left) {\n constraint.gap = CoSEConstants.DEFAULT_EDGE_LENGTH + idToNodeMap.get(constraint.left).getWidth() / 2 + idToNodeMap.get(constraint.right).getWidth() / 2;\n } else {\n constraint.gap = CoSEConstants.DEFAULT_EDGE_LENGTH + idToNodeMap.get(constraint.top).getHeight() / 2 + idToNodeMap.get(constraint.bottom).getHeight() / 2;\n }\n }\n });\n }\n\n /* auxiliary functions */\n\n // calculate difference between two position objects\n var calculatePositionDiff = function calculatePositionDiff(pos1, pos2) {\n return { x: pos1.x - pos2.x, y: pos1.y - pos2.y };\n };\n\n // calculate average position of the nodes\n var calculateAvgPosition = function calculateAvgPosition(nodeIdSet) {\n var xPosSum = 0;\n var yPosSum = 0;\n nodeIdSet.forEach(function (nodeId) {\n xPosSum += xCoords[nodeIndexes.get(nodeId)];\n yPosSum += yCoords[nodeIndexes.get(nodeId)];\n });\n\n return { x: xPosSum / nodeIdSet.size, y: yPosSum / nodeIdSet.size };\n };\n\n // find an appropriate positioning for the nodes in a given graph according to relative placement constraints\n // this function also takes the fixed nodes and alignment constraints into account\n // graph: dag to be evaluated, direction: \"horizontal\" or \"vertical\", \n // fixedNodes: set of fixed nodes to consider during evaluation, dummyPositions: appropriate coordinates of the dummy nodes \n var findAppropriatePositionForRelativePlacement = function findAppropriatePositionForRelativePlacement(graph, direction, fixedNodes, dummyPositions, componentSources) {\n\n // find union of two sets\n function setUnion(setA, setB) {\n var union = new Set(setA);\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = setB[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var elem = _step.value;\n\n union.add(elem);\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n return union;\n }\n\n // find indegree count for each node\n var inDegrees = new Map();\n\n graph.forEach(function (value, key) {\n inDegrees.set(key, 0);\n });\n graph.forEach(function (value, key) {\n value.forEach(function (adjacent) {\n inDegrees.set(adjacent.id, inDegrees.get(adjacent.id) + 1);\n });\n });\n\n var positionMap = new Map(); // keeps the position for each node\n var pastMap = new Map(); // keeps the predecessors(past) of a node\n var queue = new LinkedList();\n inDegrees.forEach(function (value, key) {\n if (value == 0) {\n queue.push(key);\n if (!fixedNodes) {\n if (direction == \"horizontal\") {\n positionMap.set(key, nodeIndexes.has(key) ? xCoords[nodeIndexes.get(key)] : dummyPositions.get(key));\n } else {\n positionMap.set(key, nodeIndexes.has(key) ? yCoords[nodeIndexes.get(key)] : dummyPositions.get(key));\n }\n }\n } else {\n positionMap.set(key, Number.NEGATIVE_INFINITY);\n }\n if (fixedNodes) {\n pastMap.set(key, new Set([key]));\n }\n });\n\n // align sources of each component in enforcement phase\n if (fixedNodes) {\n componentSources.forEach(function (component) {\n var fixedIds = [];\n component.forEach(function (nodeId) {\n if (fixedNodes.has(nodeId)) {\n fixedIds.push(nodeId);\n }\n });\n if (fixedIds.length > 0) {\n var position = 0;\n fixedIds.forEach(function (fixedId) {\n if (direction == \"horizontal\") {\n positionMap.set(fixedId, nodeIndexes.has(fixedId) ? xCoords[nodeIndexes.get(fixedId)] : dummyPositions.get(fixedId));\n position += positionMap.get(fixedId);\n } else {\n positionMap.set(fixedId, nodeIndexes.has(fixedId) ? yCoords[nodeIndexes.get(fixedId)] : dummyPositions.get(fixedId));\n position += positionMap.get(fixedId);\n }\n });\n position = position / fixedIds.length;\n component.forEach(function (nodeId) {\n if (!fixedNodes.has(nodeId)) {\n positionMap.set(nodeId, position);\n }\n });\n } else {\n var _position = 0;\n component.forEach(function (nodeId) {\n if (direction == \"horizontal\") {\n _position += nodeIndexes.has(nodeId) ? xCoords[nodeIndexes.get(nodeId)] : dummyPositions.get(nodeId);\n } else {\n _position += nodeIndexes.has(nodeId) ? yCoords[nodeIndexes.get(nodeId)] : dummyPositions.get(nodeId);\n }\n });\n _position = _position / component.length;\n component.forEach(function (nodeId) {\n positionMap.set(nodeId, _position);\n });\n }\n });\n }\n\n // calculate positions of the nodes\n\n var _loop = function _loop() {\n var currentNode = queue.shift();\n var neighbors = graph.get(currentNode);\n neighbors.forEach(function (neighbor) {\n if (positionMap.get(neighbor.id) < positionMap.get(currentNode) + neighbor.gap) {\n if (fixedNodes && fixedNodes.has(neighbor.id)) {\n var fixedPosition = void 0;\n if (direction == \"horizontal\") {\n fixedPosition = nodeIndexes.has(neighbor.id) ? xCoords[nodeIndexes.get(neighbor.id)] : dummyPositions.get(neighbor.id);\n } else {\n fixedPosition = nodeIndexes.has(neighbor.id) ? yCoords[nodeIndexes.get(neighbor.id)] : dummyPositions.get(neighbor.id);\n }\n positionMap.set(neighbor.id, fixedPosition); // TODO: may do unnecessary work\n if (fixedPosition < positionMap.get(currentNode) + neighbor.gap) {\n var diff = positionMap.get(currentNode) + neighbor.gap - fixedPosition;\n pastMap.get(currentNode).forEach(function (nodeId) {\n positionMap.set(nodeId, positionMap.get(nodeId) - diff);\n });\n }\n } else {\n positionMap.set(neighbor.id, positionMap.get(currentNode) + neighbor.gap);\n }\n }\n inDegrees.set(neighbor.id, inDegrees.get(neighbor.id) - 1);\n if (inDegrees.get(neighbor.id) == 0) {\n queue.push(neighbor.id);\n }\n if (fixedNodes) {\n pastMap.set(neighbor.id, setUnion(pastMap.get(currentNode), pastMap.get(neighbor.id)));\n }\n });\n };\n\n while (queue.length != 0) {\n _loop();\n }\n\n // readjust position of the nodes after enforcement\n if (fixedNodes) {\n // find indegree count for each node\n var sinkNodes = new Set();\n\n graph.forEach(function (value, key) {\n if (value.length == 0) {\n sinkNodes.add(key);\n }\n });\n\n var _components = [];\n pastMap.forEach(function (value, key) {\n if (sinkNodes.has(key)) {\n var isFixedComponent = false;\n var _iteratorNormalCompletion2 = true;\n var _didIteratorError2 = false;\n var _iteratorError2 = undefined;\n\n try {\n for (var _iterator2 = value[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n var nodeId = _step2.value;\n\n if (fixedNodes.has(nodeId)) {\n isFixedComponent = true;\n }\n }\n } catch (err) {\n _didIteratorError2 = true;\n _iteratorError2 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion2 && _iterator2.return) {\n _iterator2.return();\n }\n } finally {\n if (_didIteratorError2) {\n throw _iteratorError2;\n }\n }\n }\n\n if (!isFixedComponent) {\n var isExist = false;\n var existAt = void 0;\n _components.forEach(function (component, index) {\n if (component.has([].concat(_toConsumableArray(value))[0])) {\n isExist = true;\n existAt = index;\n }\n });\n if (!isExist) {\n _components.push(new Set(value));\n } else {\n value.forEach(function (ele) {\n _components[existAt].add(ele);\n });\n }\n }\n }\n });\n\n _components.forEach(function (component, index) {\n var minBefore = Number.POSITIVE_INFINITY;\n var minAfter = Number.POSITIVE_INFINITY;\n var maxBefore = Number.NEGATIVE_INFINITY;\n var maxAfter = Number.NEGATIVE_INFINITY;\n\n var _iteratorNormalCompletion3 = true;\n var _didIteratorError3 = false;\n var _iteratorError3 = undefined;\n\n try {\n for (var _iterator3 = component[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {\n var nodeId = _step3.value;\n\n var posBefore = void 0;\n if (direction == \"horizontal\") {\n posBefore = nodeIndexes.has(nodeId) ? xCoords[nodeIndexes.get(nodeId)] : dummyPositions.get(nodeId);\n } else {\n posBefore = nodeIndexes.has(nodeId) ? yCoords[nodeIndexes.get(nodeId)] : dummyPositions.get(nodeId);\n }\n var posAfter = positionMap.get(nodeId);\n if (posBefore < minBefore) {\n minBefore = posBefore;\n }\n if (posBefore > maxBefore) {\n maxBefore = posBefore;\n }\n if (posAfter < minAfter) {\n minAfter = posAfter;\n }\n if (posAfter > maxAfter) {\n maxAfter = posAfter;\n }\n }\n } catch (err) {\n _didIteratorError3 = true;\n _iteratorError3 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion3 && _iterator3.return) {\n _iterator3.return();\n }\n } finally {\n if (_didIteratorError3) {\n throw _iteratorError3;\n }\n }\n }\n\n var diff = (minBefore + maxBefore) / 2 - (minAfter + maxAfter) / 2;\n\n var _iteratorNormalCompletion4 = true;\n var _didIteratorError4 = false;\n var _iteratorError4 = undefined;\n\n try {\n for (var _iterator4 = component[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {\n var _nodeId = _step4.value;\n\n positionMap.set(_nodeId, positionMap.get(_nodeId) + diff);\n }\n } catch (err) {\n _didIteratorError4 = true;\n _iteratorError4 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion4 && _iterator4.return) {\n _iterator4.return();\n }\n } finally {\n if (_didIteratorError4) {\n throw _iteratorError4;\n }\n }\n }\n });\n }\n\n return positionMap;\n };\n\n // find transformation based on rel. placement constraints if there are both alignment and rel. placement constraints\n // or if there are only rel. placement contraints where the largest component isn't sufficiently large\n var applyReflectionForRelativePlacement = function applyReflectionForRelativePlacement(relativePlacementConstraints) {\n // variables to count votes\n var reflectOnY = 0,\n notReflectOnY = 0;\n var reflectOnX = 0,\n notReflectOnX = 0;\n\n relativePlacementConstraints.forEach(function (constraint) {\n if (constraint.left) {\n xCoords[nodeIndexes.get(constraint.left)] - xCoords[nodeIndexes.get(constraint.right)] >= 0 ? reflectOnY++ : notReflectOnY++;\n } else {\n yCoords[nodeIndexes.get(constraint.top)] - yCoords[nodeIndexes.get(constraint.bottom)] >= 0 ? reflectOnX++ : notReflectOnX++;\n }\n });\n\n if (reflectOnY > notReflectOnY && reflectOnX > notReflectOnX) {\n for (var _i = 0; _i < nodeIndexes.size; _i++) {\n xCoords[_i] = -1 * xCoords[_i];\n yCoords[_i] = -1 * yCoords[_i];\n }\n } else if (reflectOnY > notReflectOnY) {\n for (var _i2 = 0; _i2 < nodeIndexes.size; _i2++) {\n xCoords[_i2] = -1 * xCoords[_i2];\n }\n } else if (reflectOnX > notReflectOnX) {\n for (var _i3 = 0; _i3 < nodeIndexes.size; _i3++) {\n yCoords[_i3] = -1 * yCoords[_i3];\n }\n }\n };\n\n // find weakly connected components in undirected graph\n var findComponents = function findComponents(graph) {\n // find weakly connected components in dag\n var components = [];\n var queue = new LinkedList();\n var visited = new Set();\n var count = 0;\n\n graph.forEach(function (value, key) {\n if (!visited.has(key)) {\n components[count] = [];\n var _currentNode = key;\n queue.push(_currentNode);\n visited.add(_currentNode);\n components[count].push(_currentNode);\n\n while (queue.length != 0) {\n _currentNode = queue.shift();\n var neighbors = graph.get(_currentNode);\n neighbors.forEach(function (neighbor) {\n if (!visited.has(neighbor.id)) {\n queue.push(neighbor.id);\n visited.add(neighbor.id);\n components[count].push(neighbor.id);\n }\n });\n }\n count++;\n }\n });\n return components;\n };\n\n // return undirected version of given dag\n var dagToUndirected = function dagToUndirected(dag) {\n var undirected = new Map();\n\n dag.forEach(function (value, key) {\n undirected.set(key, []);\n });\n\n dag.forEach(function (value, key) {\n value.forEach(function (adjacent) {\n undirected.get(key).push(adjacent);\n undirected.get(adjacent.id).push({ id: key, gap: adjacent.gap, direction: adjacent.direction });\n });\n });\n\n return undirected;\n };\n\n // return reversed (directions inverted) version of given dag\n var dagToReversed = function dagToReversed(dag) {\n var reversed = new Map();\n\n dag.forEach(function (value, key) {\n reversed.set(key, []);\n });\n\n dag.forEach(function (value, key) {\n value.forEach(function (adjacent) {\n reversed.get(adjacent.id).push({ id: key, gap: adjacent.gap, direction: adjacent.direction });\n });\n });\n\n return reversed;\n };\n\n /**** apply transformation to the initial draft layout to better align with constrained nodes ****/\n // solve the Orthogonal Procrustean Problem to rotate and/or reflect initial draft layout\n // here we follow the solution in Chapter 20.2 of Borg, I. & Groenen, P. (2005) Modern Multidimensional Scaling: Theory and Applications \n\n /* construct source and target configurations */\n\n var targetMatrix = []; // A - target configuration\n var sourceMatrix = []; // B - source configuration \n var standardTransformation = false; // false for no transformation, true for standart (Procrustes) transformation (rotation and/or reflection)\n var reflectionType = false; // false/true for reflection check, 'reflectOnX', 'reflectOnY' or 'reflectOnBoth' for reflection type if necessary\n var fixedNodes = new Set();\n var dag = new Map(); // adjacency list to keep directed acyclic graph (dag) that consists of relative placement constraints\n var dagUndirected = new Map(); // undirected version of the dag\n var components = []; // weakly connected components\n\n // fill fixedNodes collection to use later\n if (constraints.fixedNodeConstraint) {\n constraints.fixedNodeConstraint.forEach(function (nodeData) {\n fixedNodes.add(nodeData.nodeId);\n });\n }\n\n // construct dag from relative placement constraints \n if (constraints.relativePlacementConstraint) {\n // construct both directed and undirected version of the dag\n constraints.relativePlacementConstraint.forEach(function (constraint) {\n if (constraint.left) {\n if (dag.has(constraint.left)) {\n dag.get(constraint.left).push({ id: constraint.right, gap: constraint.gap, direction: \"horizontal\" });\n } else {\n dag.set(constraint.left, [{ id: constraint.right, gap: constraint.gap, direction: \"horizontal\" }]);\n }\n if (!dag.has(constraint.right)) {\n dag.set(constraint.right, []);\n }\n } else {\n if (dag.has(constraint.top)) {\n dag.get(constraint.top).push({ id: constraint.bottom, gap: constraint.gap, direction: \"vertical\" });\n } else {\n dag.set(constraint.top, [{ id: constraint.bottom, gap: constraint.gap, direction: \"vertical\" }]);\n }\n if (!dag.has(constraint.bottom)) {\n dag.set(constraint.bottom, []);\n }\n }\n });\n\n dagUndirected = dagToUndirected(dag);\n components = findComponents(dagUndirected);\n }\n\n if (CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING) {\n // first check fixed node constraint\n if (constraints.fixedNodeConstraint && constraints.fixedNodeConstraint.length > 1) {\n constraints.fixedNodeConstraint.forEach(function (nodeData, i) {\n targetMatrix[i] = [nodeData.position.x, nodeData.position.y];\n sourceMatrix[i] = [xCoords[nodeIndexes.get(nodeData.nodeId)], yCoords[nodeIndexes.get(nodeData.nodeId)]];\n });\n standardTransformation = true;\n } else if (constraints.alignmentConstraint) {\n (function () {\n // then check alignment constraint\n var count = 0;\n if (constraints.alignmentConstraint.vertical) {\n var verticalAlign = constraints.alignmentConstraint.vertical;\n\n var _loop2 = function _loop2(_i4) {\n var alignmentSet = new Set();\n verticalAlign[_i4].forEach(function (nodeId) {\n alignmentSet.add(nodeId);\n });\n var intersection = new Set([].concat(_toConsumableArray(alignmentSet)).filter(function (x) {\n return fixedNodes.has(x);\n }));\n var xPos = void 0;\n if (intersection.size > 0) xPos = xCoords[nodeIndexes.get(intersection.values().next().value)];else xPos = calculateAvgPosition(alignmentSet).x;\n\n verticalAlign[_i4].forEach(function (nodeId) {\n targetMatrix[count] = [xPos, yCoords[nodeIndexes.get(nodeId)]];\n sourceMatrix[count] = [xCoords[nodeIndexes.get(nodeId)], yCoords[nodeIndexes.get(nodeId)]];\n count++;\n });\n };\n\n for (var _i4 = 0; _i4 < verticalAlign.length; _i4++) {\n _loop2(_i4);\n }\n standardTransformation = true;\n }\n if (constraints.alignmentConstraint.horizontal) {\n var horizontalAlign = constraints.alignmentConstraint.horizontal;\n\n var _loop3 = function _loop3(_i5) {\n var alignmentSet = new Set();\n horizontalAlign[_i5].forEach(function (nodeId) {\n alignmentSet.add(nodeId);\n });\n var intersection = new Set([].concat(_toConsumableArray(alignmentSet)).filter(function (x) {\n return fixedNodes.has(x);\n }));\n var yPos = void 0;\n if (intersection.size > 0) yPos = xCoords[nodeIndexes.get(intersection.values().next().value)];else yPos = calculateAvgPosition(alignmentSet).y;\n\n horizontalAlign[_i5].forEach(function (nodeId) {\n targetMatrix[count] = [xCoords[nodeIndexes.get(nodeId)], yPos];\n sourceMatrix[count] = [xCoords[nodeIndexes.get(nodeId)], yCoords[nodeIndexes.get(nodeId)]];\n count++;\n });\n };\n\n for (var _i5 = 0; _i5 < horizontalAlign.length; _i5++) {\n _loop3(_i5);\n }\n standardTransformation = true;\n }\n if (constraints.relativePlacementConstraint) {\n reflectionType = true;\n }\n })();\n } else if (constraints.relativePlacementConstraint) {\n // finally check relative placement constraint\n // find largest component in dag\n var largestComponentSize = 0;\n var largestComponentIndex = 0;\n for (var _i6 = 0; _i6 < components.length; _i6++) {\n if (components[_i6].length > largestComponentSize) {\n largestComponentSize = components[_i6].length;\n largestComponentIndex = _i6;\n }\n }\n // if largest component isn't dominant, then take the votes for reflection\n if (largestComponentSize < dagUndirected.size / 2) {\n applyReflectionForRelativePlacement(constraints.relativePlacementConstraint);\n standardTransformation = false;\n reflectionType = false;\n } else {\n // use largest component for transformation\n // construct horizontal and vertical subgraphs in the largest component\n var subGraphOnHorizontal = new Map();\n var subGraphOnVertical = new Map();\n var constraintsInlargestComponent = [];\n\n components[largestComponentIndex].forEach(function (nodeId) {\n dag.get(nodeId).forEach(function (adjacent) {\n if (adjacent.direction == \"horizontal\") {\n if (subGraphOnHorizontal.has(nodeId)) {\n subGraphOnHorizontal.get(nodeId).push(adjacent);\n } else {\n subGraphOnHorizontal.set(nodeId, [adjacent]);\n }\n if (!subGraphOnHorizontal.has(adjacent.id)) {\n subGraphOnHorizontal.set(adjacent.id, []);\n }\n constraintsInlargestComponent.push({ left: nodeId, right: adjacent.id });\n } else {\n if (subGraphOnVertical.has(nodeId)) {\n subGraphOnVertical.get(nodeId).push(adjacent);\n } else {\n subGraphOnVertical.set(nodeId, [adjacent]);\n }\n if (!subGraphOnVertical.has(adjacent.id)) {\n subGraphOnVertical.set(adjacent.id, []);\n }\n constraintsInlargestComponent.push({ top: nodeId, bottom: adjacent.id });\n }\n });\n });\n\n applyReflectionForRelativePlacement(constraintsInlargestComponent);\n reflectionType = false;\n\n // calculate appropriate positioning for subgraphs\n var positionMapHorizontal = findAppropriatePositionForRelativePlacement(subGraphOnHorizontal, \"horizontal\");\n var positionMapVertical = findAppropriatePositionForRelativePlacement(subGraphOnVertical, \"vertical\");\n\n // construct source and target configuration\n components[largestComponentIndex].forEach(function (nodeId, i) {\n sourceMatrix[i] = [xCoords[nodeIndexes.get(nodeId)], yCoords[nodeIndexes.get(nodeId)]];\n targetMatrix[i] = [];\n if (positionMapHorizontal.has(nodeId)) {\n targetMatrix[i][0] = positionMapHorizontal.get(nodeId);\n } else {\n targetMatrix[i][0] = xCoords[nodeIndexes.get(nodeId)];\n }\n if (positionMapVertical.has(nodeId)) {\n targetMatrix[i][1] = positionMapVertical.get(nodeId);\n } else {\n targetMatrix[i][1] = yCoords[nodeIndexes.get(nodeId)];\n }\n });\n\n standardTransformation = true;\n }\n }\n\n // if transformation is required, then calculate and apply transformation matrix\n if (standardTransformation) {\n /* calculate transformation matrix */\n var transformationMatrix = void 0;\n var targetMatrixTranspose = Matrix.transpose(targetMatrix); // A'\n var sourceMatrixTranspose = Matrix.transpose(sourceMatrix); // B'\n\n // centralize transpose matrices\n for (var _i7 = 0; _i7 < targetMatrixTranspose.length; _i7++) {\n targetMatrixTranspose[_i7] = Matrix.multGamma(targetMatrixTranspose[_i7]);\n sourceMatrixTranspose[_i7] = Matrix.multGamma(sourceMatrixTranspose[_i7]);\n }\n\n // do actual calculation for transformation matrix\n var tempMatrix = Matrix.multMat(targetMatrixTranspose, Matrix.transpose(sourceMatrixTranspose)); // tempMatrix = A'B\n var SVDResult = SVD.svd(tempMatrix); // SVD(A'B) = USV', svd function returns U, S and V \n transformationMatrix = Matrix.multMat(SVDResult.V, Matrix.transpose(SVDResult.U)); // transformationMatrix = T = VU'\n\n /* apply found transformation matrix to obtain final draft layout */\n for (var _i8 = 0; _i8 < nodeIndexes.size; _i8++) {\n var temp1 = [xCoords[_i8], yCoords[_i8]];\n var temp2 = [transformationMatrix[0][0], transformationMatrix[1][0]];\n var temp3 = [transformationMatrix[0][1], transformationMatrix[1][1]];\n xCoords[_i8] = Matrix.dotProduct(temp1, temp2);\n yCoords[_i8] = Matrix.dotProduct(temp1, temp3);\n }\n\n // applied only both alignment and rel. placement constraints exist\n if (reflectionType) {\n applyReflectionForRelativePlacement(constraints.relativePlacementConstraint);\n }\n }\n }\n\n if (CoSEConstants.ENFORCE_CONSTRAINTS) {\n /**** enforce constraints on the transformed draft layout ****/\n\n /* first enforce fixed node constraint */\n\n if (constraints.fixedNodeConstraint && constraints.fixedNodeConstraint.length > 0) {\n var translationAmount = { x: 0, y: 0 };\n constraints.fixedNodeConstraint.forEach(function (nodeData, i) {\n var posInTheory = { x: xCoords[nodeIndexes.get(nodeData.nodeId)], y: yCoords[nodeIndexes.get(nodeData.nodeId)] };\n var posDesired = nodeData.position;\n var posDiff = calculatePositionDiff(posDesired, posInTheory);\n translationAmount.x += posDiff.x;\n translationAmount.y += posDiff.y;\n });\n translationAmount.x /= constraints.fixedNodeConstraint.length;\n translationAmount.y /= constraints.fixedNodeConstraint.length;\n\n xCoords.forEach(function (value, i) {\n xCoords[i] += translationAmount.x;\n });\n\n yCoords.forEach(function (value, i) {\n yCoords[i] += translationAmount.y;\n });\n\n constraints.fixedNodeConstraint.forEach(function (nodeData) {\n xCoords[nodeIndexes.get(nodeData.nodeId)] = nodeData.position.x;\n yCoords[nodeIndexes.get(nodeData.nodeId)] = nodeData.position.y;\n });\n }\n\n /* then enforce alignment constraint */\n\n if (constraints.alignmentConstraint) {\n if (constraints.alignmentConstraint.vertical) {\n var xAlign = constraints.alignmentConstraint.vertical;\n\n var _loop4 = function _loop4(_i9) {\n var alignmentSet = new Set();\n xAlign[_i9].forEach(function (nodeId) {\n alignmentSet.add(nodeId);\n });\n var intersection = new Set([].concat(_toConsumableArray(alignmentSet)).filter(function (x) {\n return fixedNodes.has(x);\n }));\n var xPos = void 0;\n if (intersection.size > 0) xPos = xCoords[nodeIndexes.get(intersection.values().next().value)];else xPos = calculateAvgPosition(alignmentSet).x;\n\n alignmentSet.forEach(function (nodeId) {\n if (!fixedNodes.has(nodeId)) xCoords[nodeIndexes.get(nodeId)] = xPos;\n });\n };\n\n for (var _i9 = 0; _i9 < xAlign.length; _i9++) {\n _loop4(_i9);\n }\n }\n if (constraints.alignmentConstraint.horizontal) {\n var yAlign = constraints.alignmentConstraint.horizontal;\n\n var _loop5 = function _loop5(_i10) {\n var alignmentSet = new Set();\n yAlign[_i10].forEach(function (nodeId) {\n alignmentSet.add(nodeId);\n });\n var intersection = new Set([].concat(_toConsumableArray(alignmentSet)).filter(function (x) {\n return fixedNodes.has(x);\n }));\n var yPos = void 0;\n if (intersection.size > 0) yPos = yCoords[nodeIndexes.get(intersection.values().next().value)];else yPos = calculateAvgPosition(alignmentSet).y;\n\n alignmentSet.forEach(function (nodeId) {\n if (!fixedNodes.has(nodeId)) yCoords[nodeIndexes.get(nodeId)] = yPos;\n });\n };\n\n for (var _i10 = 0; _i10 < yAlign.length; _i10++) {\n _loop5(_i10);\n }\n }\n }\n\n /* finally enforce relative placement constraint */\n\n if (constraints.relativePlacementConstraint) {\n (function () {\n var nodeToDummyForVerticalAlignment = new Map();\n var nodeToDummyForHorizontalAlignment = new Map();\n var dummyToNodeForVerticalAlignment = new Map();\n var dummyToNodeForHorizontalAlignment = new Map();\n var dummyPositionsForVerticalAlignment = new Map();\n var dummyPositionsForHorizontalAlignment = new Map();\n var fixedNodesOnHorizontal = new Set();\n var fixedNodesOnVertical = new Set();\n\n // fill maps and sets \n fixedNodes.forEach(function (nodeId) {\n fixedNodesOnHorizontal.add(nodeId);\n fixedNodesOnVertical.add(nodeId);\n });\n\n if (constraints.alignmentConstraint) {\n if (constraints.alignmentConstraint.vertical) {\n var verticalAlignment = constraints.alignmentConstraint.vertical;\n\n var _loop6 = function _loop6(_i11) {\n dummyToNodeForVerticalAlignment.set(\"dummy\" + _i11, []);\n verticalAlignment[_i11].forEach(function (nodeId) {\n nodeToDummyForVerticalAlignment.set(nodeId, \"dummy\" + _i11);\n dummyToNodeForVerticalAlignment.get(\"dummy\" + _i11).push(nodeId);\n if (fixedNodes.has(nodeId)) {\n fixedNodesOnHorizontal.add(\"dummy\" + _i11);\n }\n });\n dummyPositionsForVerticalAlignment.set(\"dummy\" + _i11, xCoords[nodeIndexes.get(verticalAlignment[_i11][0])]);\n };\n\n for (var _i11 = 0; _i11 < verticalAlignment.length; _i11++) {\n _loop6(_i11);\n }\n }\n if (constraints.alignmentConstraint.horizontal) {\n var horizontalAlignment = constraints.alignmentConstraint.horizontal;\n\n var _loop7 = function _loop7(_i12) {\n dummyToNodeForHorizontalAlignment.set(\"dummy\" + _i12, []);\n horizontalAlignment[_i12].forEach(function (nodeId) {\n nodeToDummyForHorizontalAlignment.set(nodeId, \"dummy\" + _i12);\n dummyToNodeForHorizontalAlignment.get(\"dummy\" + _i12).push(nodeId);\n if (fixedNodes.has(nodeId)) {\n fixedNodesOnVertical.add(\"dummy\" + _i12);\n }\n });\n dummyPositionsForHorizontalAlignment.set(\"dummy\" + _i12, yCoords[nodeIndexes.get(horizontalAlignment[_i12][0])]);\n };\n\n for (var _i12 = 0; _i12 < horizontalAlignment.length; _i12++) {\n _loop7(_i12);\n }\n }\n }\n\n // construct horizontal and vertical dags (subgraphs) from overall dag\n var dagOnHorizontal = new Map();\n var dagOnVertical = new Map();\n\n var _loop8 = function _loop8(nodeId) {\n dag.get(nodeId).forEach(function (adjacent) {\n var sourceId = void 0;\n var targetNode = void 0;\n if (adjacent[\"direction\"] == \"horizontal\") {\n sourceId = nodeToDummyForVerticalAlignment.get(nodeId) ? nodeToDummyForVerticalAlignment.get(nodeId) : nodeId;\n if (nodeToDummyForVerticalAlignment.get(adjacent.id)) {\n targetNode = { id: nodeToDummyForVerticalAlignment.get(adjacent.id), gap: adjacent.gap, direction: adjacent.direction };\n } else {\n targetNode = adjacent;\n }\n if (dagOnHorizontal.has(sourceId)) {\n dagOnHorizontal.get(sourceId).push(targetNode);\n } else {\n dagOnHorizontal.set(sourceId, [targetNode]);\n }\n if (!dagOnHorizontal.has(targetNode.id)) {\n dagOnHorizontal.set(targetNode.id, []);\n }\n } else {\n sourceId = nodeToDummyForHorizontalAlignment.get(nodeId) ? nodeToDummyForHorizontalAlignment.get(nodeId) : nodeId;\n if (nodeToDummyForHorizontalAlignment.get(adjacent.id)) {\n targetNode = { id: nodeToDummyForHorizontalAlignment.get(adjacent.id), gap: adjacent.gap, direction: adjacent.direction };\n } else {\n targetNode = adjacent;\n }\n if (dagOnVertical.has(sourceId)) {\n dagOnVertical.get(sourceId).push(targetNode);\n } else {\n dagOnVertical.set(sourceId, [targetNode]);\n }\n if (!dagOnVertical.has(targetNode.id)) {\n dagOnVertical.set(targetNode.id, []);\n }\n }\n });\n };\n\n var _iteratorNormalCompletion5 = true;\n var _didIteratorError5 = false;\n var _iteratorError5 = undefined;\n\n try {\n for (var _iterator5 = dag.keys()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {\n var nodeId = _step5.value;\n\n _loop8(nodeId);\n }\n\n // find source nodes of each component in horizontal and vertical dags\n } catch (err) {\n _didIteratorError5 = true;\n _iteratorError5 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion5 && _iterator5.return) {\n _iterator5.return();\n }\n } finally {\n if (_didIteratorError5) {\n throw _iteratorError5;\n }\n }\n }\n\n var undirectedOnHorizontal = dagToUndirected(dagOnHorizontal);\n var undirectedOnVertical = dagToUndirected(dagOnVertical);\n var componentsOnHorizontal = findComponents(undirectedOnHorizontal);\n var componentsOnVertical = findComponents(undirectedOnVertical);\n var reversedDagOnHorizontal = dagToReversed(dagOnHorizontal);\n var reversedDagOnVertical = dagToReversed(dagOnVertical);\n var componentSourcesOnHorizontal = [];\n var componentSourcesOnVertical = [];\n\n componentsOnHorizontal.forEach(function (component, index) {\n componentSourcesOnHorizontal[index] = [];\n component.forEach(function (nodeId) {\n if (reversedDagOnHorizontal.get(nodeId).length == 0) {\n componentSourcesOnHorizontal[index].push(nodeId);\n }\n });\n });\n\n componentsOnVertical.forEach(function (component, index) {\n componentSourcesOnVertical[index] = [];\n component.forEach(function (nodeId) {\n if (reversedDagOnVertical.get(nodeId).length == 0) {\n componentSourcesOnVertical[index].push(nodeId);\n }\n });\n });\n\n // calculate appropriate positioning for subgraphs\n var positionMapHorizontal = findAppropriatePositionForRelativePlacement(dagOnHorizontal, \"horizontal\", fixedNodesOnHorizontal, dummyPositionsForVerticalAlignment, componentSourcesOnHorizontal);\n var positionMapVertical = findAppropriatePositionForRelativePlacement(dagOnVertical, \"vertical\", fixedNodesOnVertical, dummyPositionsForHorizontalAlignment, componentSourcesOnVertical);\n\n // update positions of the nodes based on relative placement constraints\n\n var _loop9 = function _loop9(key) {\n if (dummyToNodeForVerticalAlignment.get(key)) {\n dummyToNodeForVerticalAlignment.get(key).forEach(function (nodeId) {\n xCoords[nodeIndexes.get(nodeId)] = positionMapHorizontal.get(key);\n });\n } else {\n xCoords[nodeIndexes.get(key)] = positionMapHorizontal.get(key);\n }\n };\n\n var _iteratorNormalCompletion6 = true;\n var _didIteratorError6 = false;\n var _iteratorError6 = undefined;\n\n try {\n for (var _iterator6 = positionMapHorizontal.keys()[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {\n var key = _step6.value;\n\n _loop9(key);\n }\n } catch (err) {\n _didIteratorError6 = true;\n _iteratorError6 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion6 && _iterator6.return) {\n _iterator6.return();\n }\n } finally {\n if (_didIteratorError6) {\n throw _iteratorError6;\n }\n }\n }\n\n var _loop10 = function _loop10(key) {\n if (dummyToNodeForHorizontalAlignment.get(key)) {\n dummyToNodeForHorizontalAlignment.get(key).forEach(function (nodeId) {\n yCoords[nodeIndexes.get(nodeId)] = positionMapVertical.get(key);\n });\n } else {\n yCoords[nodeIndexes.get(key)] = positionMapVertical.get(key);\n }\n };\n\n var _iteratorNormalCompletion7 = true;\n var _didIteratorError7 = false;\n var _iteratorError7 = undefined;\n\n try {\n for (var _iterator7 = positionMapVertical.keys()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {\n var key = _step7.value;\n\n _loop10(key);\n }\n } catch (err) {\n _didIteratorError7 = true;\n _iteratorError7 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion7 && _iterator7.return) {\n _iterator7.return();\n }\n } finally {\n if (_didIteratorError7) {\n throw _iteratorError7;\n }\n }\n }\n })();\n }\n }\n\n // assign new coordinates to nodes after constraint handling\n for (var _i13 = 0; _i13 < allNodes.length; _i13++) {\n var _node = allNodes[_i13];\n if (_node.getChild() == null) {\n _node.setCenter(xCoords[nodeIndexes.get(_node.id)], yCoords[nodeIndexes.get(_node.id)]);\n }\n }\n};\n\nmodule.exports = ConstraintHandler;\n\n/***/ }),\n\n/***/ 551:\n/***/ ((module) => {\n\nmodule.exports = __WEBPACK_EXTERNAL_MODULE__551__;\n\n/***/ })\n\n/******/ \t});\n/************************************************************************/\n/******/ \t// The module cache\n/******/ \tvar __webpack_module_cache__ = {};\n/******/ \t\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/ \t\t// Check if module is in cache\n/******/ \t\tvar cachedModule = __webpack_module_cache__[moduleId];\n/******/ \t\tif (cachedModule !== undefined) {\n/******/ \t\t\treturn cachedModule.exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = __webpack_module_cache__[moduleId] = {\n/******/ \t\t\t// no module.id needed\n/******/ \t\t\t// no module.loaded needed\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/ \t\n/******/ \t\t// Execute the module function\n/******/ \t\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n/******/ \t\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/ \t\n/************************************************************************/\n/******/ \t\n/******/ \t// startup\n/******/ \t// Load entry module and return exports\n/******/ \t// This entry module is referenced by other modules so it can't be inlined\n/******/ \tvar __webpack_exports__ = __webpack_require__(45);\n/******/ \t\n/******/ \treturn __webpack_exports__;\n/******/ })()\n;\n});", "(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"cose-base\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"cose-base\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"cytoscapeFcose\"] = factory(require(\"cose-base\"));\n\telse\n\t\troot[\"cytoscapeFcose\"] = factory(root[\"coseBase\"]);\n})(this, function(__WEBPACK_EXTERNAL_MODULE__140__) {\nreturn /******/ (() => { // webpackBootstrap\n/******/ \t\"use strict\";\n/******/ \tvar __webpack_modules__ = ({\n\n/***/ 658:\n/***/ ((module) => {\n\n\n\n// Simple, internal Object.assign() polyfill for options objects etc.\n\nmodule.exports = Object.assign != null ? Object.assign.bind(Object) : function (tgt) {\n for (var _len = arguments.length, srcs = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n srcs[_key - 1] = arguments[_key];\n }\n\n srcs.forEach(function (src) {\n Object.keys(src).forEach(function (k) {\n return tgt[k] = src[k];\n });\n });\n\n return tgt;\n};\n\n/***/ }),\n\n/***/ 548:\n/***/ ((module, __unused_webpack_exports, __webpack_require__) => {\n\n\n\nvar _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"]) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); } }; }();\n\n/*\n * Auxiliary functions\n */\n\nvar LinkedList = __webpack_require__(140).layoutBase.LinkedList;\n\nvar auxiliary = {};\n\n// get the top most nodes\nauxiliary.getTopMostNodes = function (nodes) {\n var nodesMap = {};\n for (var i = 0; i < nodes.length; i++) {\n nodesMap[nodes[i].id()] = true;\n }\n var roots = nodes.filter(function (ele, i) {\n if (typeof ele === \"number\") {\n ele = i;\n }\n var parent = ele.parent()[0];\n while (parent != null) {\n if (nodesMap[parent.id()]) {\n return false;\n }\n parent = parent.parent()[0];\n }\n return true;\n });\n\n return roots;\n};\n\n// find disconnected components and create dummy nodes that connect them\nauxiliary.connectComponents = function (cy, eles, topMostNodes, dummyNodes) {\n var queue = new LinkedList();\n var visited = new Set();\n var visitedTopMostNodes = [];\n var currentNeighbor = void 0;\n var minDegreeNode = void 0;\n var minDegree = void 0;\n\n var isConnected = false;\n var count = 1;\n var nodesConnectedToDummy = [];\n var components = [];\n\n var _loop = function _loop() {\n var cmpt = cy.collection();\n components.push(cmpt);\n\n var currentNode = topMostNodes[0];\n var childrenOfCurrentNode = cy.collection();\n childrenOfCurrentNode.merge(currentNode).merge(currentNode.descendants().intersection(eles));\n visitedTopMostNodes.push(currentNode);\n\n childrenOfCurrentNode.forEach(function (node) {\n queue.push(node);\n visited.add(node);\n cmpt.merge(node);\n });\n\n var _loop2 = function _loop2() {\n currentNode = queue.shift();\n\n // Traverse all neighbors of this node\n var neighborNodes = cy.collection();\n currentNode.neighborhood().nodes().forEach(function (node) {\n if (eles.intersection(currentNode.edgesWith(node)).length > 0) {\n neighborNodes.merge(node);\n }\n });\n\n for (var i = 0; i < neighborNodes.length; i++) {\n var neighborNode = neighborNodes[i];\n currentNeighbor = topMostNodes.intersection(neighborNode.union(neighborNode.ancestors()));\n if (currentNeighbor != null && !visited.has(currentNeighbor[0])) {\n var childrenOfNeighbor = currentNeighbor.union(currentNeighbor.descendants());\n\n childrenOfNeighbor.forEach(function (node) {\n queue.push(node);\n visited.add(node);\n cmpt.merge(node);\n if (topMostNodes.has(node)) {\n visitedTopMostNodes.push(node);\n }\n });\n }\n }\n };\n\n while (queue.length != 0) {\n _loop2();\n }\n\n cmpt.forEach(function (node) {\n eles.intersection(node.connectedEdges()).forEach(function (e) {\n // connectedEdges() usually cached\n if (cmpt.has(e.source()) && cmpt.has(e.target())) {\n // has() is cheap\n cmpt.merge(e);\n }\n });\n });\n\n if (visitedTopMostNodes.length == topMostNodes.length) {\n isConnected = true;\n }\n\n if (!isConnected || isConnected && count > 1) {\n minDegreeNode = visitedTopMostNodes[0];\n minDegree = minDegreeNode.connectedEdges().length;\n visitedTopMostNodes.forEach(function (node) {\n if (node.connectedEdges().length < minDegree) {\n minDegree = node.connectedEdges().length;\n minDegreeNode = node;\n }\n });\n nodesConnectedToDummy.push(minDegreeNode.id());\n // TO DO: Check efficiency of this part\n var temp = cy.collection();\n temp.merge(visitedTopMostNodes[0]);\n visitedTopMostNodes.forEach(function (node) {\n temp.merge(node);\n });\n visitedTopMostNodes = [];\n topMostNodes = topMostNodes.difference(temp);\n count++;\n }\n };\n\n do {\n _loop();\n } while (!isConnected);\n\n if (dummyNodes) {\n if (nodesConnectedToDummy.length > 0) {\n dummyNodes.set('dummy' + (dummyNodes.size + 1), nodesConnectedToDummy);\n }\n }\n return components;\n};\n\n// relocates componentResult to originalCenter if there is no fixedNodeConstraint\nauxiliary.relocateComponent = function (originalCenter, componentResult, options) {\n if (!options.fixedNodeConstraint) {\n var minXCoord = Number.POSITIVE_INFINITY;\n var maxXCoord = Number.NEGATIVE_INFINITY;\n var minYCoord = Number.POSITIVE_INFINITY;\n var maxYCoord = Number.NEGATIVE_INFINITY;\n if (options.quality == \"draft\") {\n // calculate current bounding box\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = componentResult.nodeIndexes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var _ref = _step.value;\n\n var _ref2 = _slicedToArray(_ref, 2);\n\n var key = _ref2[0];\n var value = _ref2[1];\n\n var cyNode = options.cy.getElementById(key);\n if (cyNode) {\n var nodeBB = cyNode.boundingBox();\n var leftX = componentResult.xCoords[value] - nodeBB.w / 2;\n var rightX = componentResult.xCoords[value] + nodeBB.w / 2;\n var topY = componentResult.yCoords[value] - nodeBB.h / 2;\n var bottomY = componentResult.yCoords[value] + nodeBB.h / 2;\n\n if (leftX < minXCoord) minXCoord = leftX;\n if (rightX > maxXCoord) maxXCoord = rightX;\n if (topY < minYCoord) minYCoord = topY;\n if (bottomY > maxYCoord) maxYCoord = bottomY;\n }\n }\n // find difference between current and original center\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n var diffOnX = originalCenter.x - (maxXCoord + minXCoord) / 2;\n var diffOnY = originalCenter.y - (maxYCoord + minYCoord) / 2;\n // move component to original center\n componentResult.xCoords = componentResult.xCoords.map(function (x) {\n return x + diffOnX;\n });\n componentResult.yCoords = componentResult.yCoords.map(function (y) {\n return y + diffOnY;\n });\n } else {\n // calculate current bounding box\n Object.keys(componentResult).forEach(function (item) {\n var node = componentResult[item];\n var leftX = node.getRect().x;\n var rightX = node.getRect().x + node.getRect().width;\n var topY = node.getRect().y;\n var bottomY = node.getRect().y + node.getRect().height;\n\n if (leftX < minXCoord) minXCoord = leftX;\n if (rightX > maxXCoord) maxXCoord = rightX;\n if (topY < minYCoord) minYCoord = topY;\n if (bottomY > maxYCoord) maxYCoord = bottomY;\n });\n // find difference between current and original center\n var _diffOnX = originalCenter.x - (maxXCoord + minXCoord) / 2;\n var _diffOnY = originalCenter.y - (maxYCoord + minYCoord) / 2;\n // move component to original center\n Object.keys(componentResult).forEach(function (item) {\n var node = componentResult[item];\n node.setCenter(node.getCenterX() + _diffOnX, node.getCenterY() + _diffOnY);\n });\n }\n }\n};\n\nauxiliary.calcBoundingBox = function (parentNode, xCoords, yCoords, nodeIndexes) {\n // calculate bounds\n var left = Number.MAX_SAFE_INTEGER;\n var right = Number.MIN_SAFE_INTEGER;\n var top = Number.MAX_SAFE_INTEGER;\n var bottom = Number.MIN_SAFE_INTEGER;\n var nodeLeft = void 0;\n var nodeRight = void 0;\n var nodeTop = void 0;\n var nodeBottom = void 0;\n\n var nodes = parentNode.descendants().not(\":parent\");\n var s = nodes.length;\n for (var i = 0; i < s; i++) {\n var node = nodes[i];\n\n nodeLeft = xCoords[nodeIndexes.get(node.id())] - node.width() / 2;\n nodeRight = xCoords[nodeIndexes.get(node.id())] + node.width() / 2;\n nodeTop = yCoords[nodeIndexes.get(node.id())] - node.height() / 2;\n nodeBottom = yCoords[nodeIndexes.get(node.id())] + node.height() / 2;\n\n if (left > nodeLeft) {\n left = nodeLeft;\n }\n\n if (right < nodeRight) {\n right = nodeRight;\n }\n\n if (top > nodeTop) {\n top = nodeTop;\n }\n\n if (bottom < nodeBottom) {\n bottom = nodeBottom;\n }\n }\n\n var boundingBox = {};\n boundingBox.topLeftX = left;\n boundingBox.topLeftY = top;\n boundingBox.width = right - left;\n boundingBox.height = bottom - top;\n return boundingBox;\n};\n\n// This function finds and returns parent nodes whose all children are hidden\nauxiliary.calcParentsWithoutChildren = function (cy, eles) {\n var parentsWithoutChildren = cy.collection();\n eles.nodes(':parent').forEach(function (parent) {\n var check = false;\n parent.children().forEach(function (child) {\n if (child.css('display') != 'none') {\n check = true;\n }\n });\n if (!check) {\n parentsWithoutChildren.merge(parent);\n }\n });\n\n return parentsWithoutChildren;\n};\n\nmodule.exports = auxiliary;\n\n/***/ }),\n\n/***/ 816:\n/***/ ((module, __unused_webpack_exports, __webpack_require__) => {\n\n\n\n/**\n The implementation of the postprocessing part that applies CoSE layout over the spectral layout\n*/\n\nvar aux = __webpack_require__(548);\nvar CoSELayout = __webpack_require__(140).CoSELayout;\nvar CoSENode = __webpack_require__(140).CoSENode;\nvar PointD = __webpack_require__(140).layoutBase.PointD;\nvar DimensionD = __webpack_require__(140).layoutBase.DimensionD;\nvar LayoutConstants = __webpack_require__(140).layoutBase.LayoutConstants;\nvar FDLayoutConstants = __webpack_require__(140).layoutBase.FDLayoutConstants;\nvar CoSEConstants = __webpack_require__(140).CoSEConstants;\n\n// main function that cose layout is processed\nvar coseLayout = function coseLayout(options, spectralResult) {\n\n var cy = options.cy;\n var eles = options.eles;\n var nodes = eles.nodes();\n var edges = eles.edges();\n\n var nodeIndexes = void 0;\n var xCoords = void 0;\n var yCoords = void 0;\n var idToLNode = {};\n\n if (options.randomize) {\n nodeIndexes = spectralResult[\"nodeIndexes\"];\n xCoords = spectralResult[\"xCoords\"];\n yCoords = spectralResult[\"yCoords\"];\n }\n\n var isFn = function isFn(fn) {\n return typeof fn === 'function';\n };\n\n var optFn = function optFn(opt, ele) {\n if (isFn(opt)) {\n return opt(ele);\n } else {\n return opt;\n }\n };\n\n /**** Postprocessing functions ****/\n\n var parentsWithoutChildren = aux.calcParentsWithoutChildren(cy, eles);\n\n // transfer cytoscape nodes to cose nodes\n var processChildrenList = function processChildrenList(parent, children, layout, options) {\n var size = children.length;\n for (var i = 0; i < size; i++) {\n var theChild = children[i];\n var children_of_children = null;\n if (theChild.intersection(parentsWithoutChildren).length == 0) {\n children_of_children = theChild.children();\n }\n var theNode = void 0;\n\n var dimensions = theChild.layoutDimensions({\n nodeDimensionsIncludeLabels: options.nodeDimensionsIncludeLabels\n });\n\n if (theChild.outerWidth() != null && theChild.outerHeight() != null) {\n if (options.randomize) {\n if (!theChild.isParent()) {\n theNode = parent.add(new CoSENode(layout.graphManager, new PointD(xCoords[nodeIndexes.get(theChild.id())] - dimensions.w / 2, yCoords[nodeIndexes.get(theChild.id())] - dimensions.h / 2), new DimensionD(parseFloat(dimensions.w), parseFloat(dimensions.h))));\n } else {\n var parentInfo = aux.calcBoundingBox(theChild, xCoords, yCoords, nodeIndexes);\n if (theChild.intersection(parentsWithoutChildren).length == 0) {\n theNode = parent.add(new CoSENode(layout.graphManager, new PointD(parentInfo.topLeftX, parentInfo.topLeftY), new DimensionD(parentInfo.width, parentInfo.height)));\n } else {\n // for the parentsWithoutChildren\n theNode = parent.add(new CoSENode(layout.graphManager, new PointD(parentInfo.topLeftX, parentInfo.topLeftY), new DimensionD(parseFloat(dimensions.w), parseFloat(dimensions.h))));\n }\n }\n } else {\n theNode = parent.add(new CoSENode(layout.graphManager, new PointD(theChild.position('x') - dimensions.w / 2, theChild.position('y') - dimensions.h / 2), new DimensionD(parseFloat(dimensions.w), parseFloat(dimensions.h))));\n }\n } else {\n theNode = parent.add(new CoSENode(this.graphManager));\n }\n // Attach id to the layout node and repulsion value\n theNode.id = theChild.data(\"id\");\n theNode.nodeRepulsion = optFn(options.nodeRepulsion, theChild);\n // Attach the paddings of cy node to layout node\n theNode.paddingLeft = parseInt(theChild.css('padding'));\n theNode.paddingTop = parseInt(theChild.css('padding'));\n theNode.paddingRight = parseInt(theChild.css('padding'));\n theNode.paddingBottom = parseInt(theChild.css('padding'));\n\n //Attach the label properties to both compound and simple nodes if labels will be included in node dimensions\n //These properties will be used while updating bounds of compounds during iterations or tiling\n //and will be used for simple nodes while transferring final positions to cytoscape\n if (options.nodeDimensionsIncludeLabels) {\n theNode.labelWidth = theChild.boundingBox({ includeLabels: true, includeNodes: false, includeOverlays: false }).w;\n theNode.labelHeight = theChild.boundingBox({ includeLabels: true, includeNodes: false, includeOverlays: false }).h;\n theNode.labelPosVertical = theChild.css(\"text-valign\");\n theNode.labelPosHorizontal = theChild.css(\"text-halign\");\n }\n\n // Map the layout node\n idToLNode[theChild.data(\"id\")] = theNode;\n\n if (isNaN(theNode.rect.x)) {\n theNode.rect.x = 0;\n }\n\n if (isNaN(theNode.rect.y)) {\n theNode.rect.y = 0;\n }\n\n if (children_of_children != null && children_of_children.length > 0) {\n var theNewGraph = void 0;\n theNewGraph = layout.getGraphManager().add(layout.newGraph(), theNode);\n processChildrenList(theNewGraph, children_of_children, layout, options);\n }\n }\n };\n\n // transfer cytoscape edges to cose edges\n var processEdges = function processEdges(layout, gm, edges) {\n var idealLengthTotal = 0;\n var edgeCount = 0;\n for (var i = 0; i < edges.length; i++) {\n var edge = edges[i];\n var sourceNode = idToLNode[edge.data(\"source\")];\n var targetNode = idToLNode[edge.data(\"target\")];\n if (sourceNode && targetNode && sourceNode !== targetNode && sourceNode.getEdgesBetween(targetNode).length == 0) {\n var e1 = gm.add(layout.newEdge(), sourceNode, targetNode);\n e1.id = edge.id();\n e1.idealLength = optFn(options.idealEdgeLength, edge);\n e1.edgeElasticity = optFn(options.edgeElasticity, edge);\n idealLengthTotal += e1.idealLength;\n edgeCount++;\n }\n }\n // we need to update the ideal edge length constant with the avg. ideal length value after processing edges\n // in case there is no edge, use other options\n if (options.idealEdgeLength != null) {\n if (edgeCount > 0) CoSEConstants.DEFAULT_EDGE_LENGTH = FDLayoutConstants.DEFAULT_EDGE_LENGTH = idealLengthTotal / edgeCount;else if (!isFn(options.idealEdgeLength)) // in case there is no edge, but option gives a value to use\n CoSEConstants.DEFAULT_EDGE_LENGTH = FDLayoutConstants.DEFAULT_EDGE_LENGTH = options.idealEdgeLength;else // in case there is no edge and we cannot get a value from option (because it's a function)\n CoSEConstants.DEFAULT_EDGE_LENGTH = FDLayoutConstants.DEFAULT_EDGE_LENGTH = 50;\n // we need to update these constant values based on the ideal edge length constant\n CoSEConstants.MIN_REPULSION_DIST = FDLayoutConstants.MIN_REPULSION_DIST = FDLayoutConstants.DEFAULT_EDGE_LENGTH / 10.0;\n CoSEConstants.DEFAULT_RADIAL_SEPARATION = FDLayoutConstants.DEFAULT_EDGE_LENGTH;\n }\n };\n\n // transfer cytoscape constraints to cose layout\n var processConstraints = function processConstraints(layout, options) {\n // get nodes to be fixed\n if (options.fixedNodeConstraint) {\n layout.constraints[\"fixedNodeConstraint\"] = options.fixedNodeConstraint;\n }\n // get nodes to be aligned\n if (options.alignmentConstraint) {\n layout.constraints[\"alignmentConstraint\"] = options.alignmentConstraint;\n }\n // get nodes to be relatively placed\n if (options.relativePlacementConstraint) {\n layout.constraints[\"relativePlacementConstraint\"] = options.relativePlacementConstraint;\n }\n };\n\n /**** Apply postprocessing ****/\n if (options.nestingFactor != null) CoSEConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR = FDLayoutConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR = options.nestingFactor;\n if (options.gravity != null) CoSEConstants.DEFAULT_GRAVITY_STRENGTH = FDLayoutConstants.DEFAULT_GRAVITY_STRENGTH = options.gravity;\n if (options.numIter != null) CoSEConstants.MAX_ITERATIONS = FDLayoutConstants.MAX_ITERATIONS = options.numIter;\n if (options.gravityRange != null) CoSEConstants.DEFAULT_GRAVITY_RANGE_FACTOR = FDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR = options.gravityRange;\n if (options.gravityCompound != null) CoSEConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH = options.gravityCompound;\n if (options.gravityRangeCompound != null) CoSEConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR = options.gravityRangeCompound;\n if (options.initialEnergyOnIncremental != null) CoSEConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL = options.initialEnergyOnIncremental;\n\n if (options.tilingCompareBy != null) CoSEConstants.TILING_COMPARE_BY = options.tilingCompareBy;\n\n if (options.quality == 'proof') LayoutConstants.QUALITY = 2;else LayoutConstants.QUALITY = 0;\n\n CoSEConstants.NODE_DIMENSIONS_INCLUDE_LABELS = FDLayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS = LayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS = options.nodeDimensionsIncludeLabels;\n CoSEConstants.DEFAULT_INCREMENTAL = FDLayoutConstants.DEFAULT_INCREMENTAL = LayoutConstants.DEFAULT_INCREMENTAL = !options.randomize;\n CoSEConstants.ANIMATE = FDLayoutConstants.ANIMATE = LayoutConstants.ANIMATE = options.animate;\n CoSEConstants.TILE = options.tile;\n CoSEConstants.TILING_PADDING_VERTICAL = typeof options.tilingPaddingVertical === 'function' ? options.tilingPaddingVertical.call() : options.tilingPaddingVertical;\n CoSEConstants.TILING_PADDING_HORIZONTAL = typeof options.tilingPaddingHorizontal === 'function' ? options.tilingPaddingHorizontal.call() : options.tilingPaddingHorizontal;\n\n CoSEConstants.DEFAULT_INCREMENTAL = FDLayoutConstants.DEFAULT_INCREMENTAL = LayoutConstants.DEFAULT_INCREMENTAL = true;\n CoSEConstants.PURE_INCREMENTAL = !options.randomize;\n LayoutConstants.DEFAULT_UNIFORM_LEAF_NODE_SIZES = options.uniformNodeDimensions;\n\n // This part is for debug/demo purpose\n if (options.step == \"transformed\") {\n CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = true;\n CoSEConstants.ENFORCE_CONSTRAINTS = false;\n CoSEConstants.APPLY_LAYOUT = false;\n }\n if (options.step == \"enforced\") {\n CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = false;\n CoSEConstants.ENFORCE_CONSTRAINTS = true;\n CoSEConstants.APPLY_LAYOUT = false;\n }\n if (options.step == \"cose\") {\n CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = false;\n CoSEConstants.ENFORCE_CONSTRAINTS = false;\n CoSEConstants.APPLY_LAYOUT = true;\n }\n if (options.step == \"all\") {\n if (options.randomize) CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = true;else CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = false;\n CoSEConstants.ENFORCE_CONSTRAINTS = true;\n CoSEConstants.APPLY_LAYOUT = true;\n }\n\n if (options.fixedNodeConstraint || options.alignmentConstraint || options.relativePlacementConstraint) {\n CoSEConstants.TREE_REDUCTION_ON_INCREMENTAL = false;\n } else {\n CoSEConstants.TREE_REDUCTION_ON_INCREMENTAL = true;\n }\n\n var coseLayout = new CoSELayout();\n var gm = coseLayout.newGraphManager();\n\n processChildrenList(gm.addRoot(), aux.getTopMostNodes(nodes), coseLayout, options);\n processEdges(coseLayout, gm, edges);\n processConstraints(coseLayout, options);\n\n coseLayout.runLayout();\n\n return idToLNode;\n};\n\nmodule.exports = { coseLayout: coseLayout };\n\n/***/ }),\n\n/***/ 212:\n/***/ ((module, __unused_webpack_exports, __webpack_require__) => {\n\n\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n The implementation of the fcose layout algorithm\n*/\n\nvar assign = __webpack_require__(658);\nvar aux = __webpack_require__(548);\n\nvar _require = __webpack_require__(657),\n spectralLayout = _require.spectralLayout;\n\nvar _require2 = __webpack_require__(816),\n coseLayout = _require2.coseLayout;\n\nvar defaults = Object.freeze({\n\n // 'draft', 'default' or 'proof' \n // - 'draft' only applies spectral layout \n // - 'default' improves the quality with subsequent CoSE layout (fast cooling rate)\n // - 'proof' improves the quality with subsequent CoSE layout (slow cooling rate) \n quality: \"default\",\n // Use random node positions at beginning of layout\n // if this is set to false, then quality option must be \"proof\"\n randomize: true,\n // Whether or not to animate the layout\n animate: true,\n // Duration of animation in ms, if enabled\n animationDuration: 1000,\n // Easing of animation, if enabled\n animationEasing: undefined,\n // Fit the viewport to the repositioned nodes\n fit: true,\n // Padding around layout\n padding: 30,\n // Whether to include labels in node dimensions. Valid in \"proof\" quality\n nodeDimensionsIncludeLabels: false,\n // Whether or not simple nodes (non-compound nodes) are of uniform dimensions\n uniformNodeDimensions: false,\n // Whether to pack disconnected components - valid only if randomize: true\n packComponents: true,\n // Layout step - all, transformed, enforced, cose - for debug purpose only\n step: \"all\",\n\n /* spectral layout options */\n\n // False for random, true for greedy\n samplingType: true,\n // Sample size to construct distance matrix\n sampleSize: 25,\n // Separation amount between nodes\n nodeSeparation: 75,\n // Power iteration tolerance\n piTol: 0.0000001,\n\n /* CoSE layout options */\n\n // Node repulsion (non overlapping) multiplier\n nodeRepulsion: function nodeRepulsion(node) {\n return 4500;\n },\n // Ideal edge (non nested) length\n idealEdgeLength: function idealEdgeLength(edge) {\n return 50;\n },\n // Divisor to compute edge forces\n edgeElasticity: function edgeElasticity(edge) {\n return 0.45;\n },\n // Nesting factor (multiplier) to compute ideal edge length for nested edges\n nestingFactor: 0.1,\n // Gravity force (constant)\n gravity: 0.25,\n // Maximum number of iterations to perform\n numIter: 2500,\n // For enabling tiling\n tile: true,\n // The function that specifies the criteria for comparing nodes while sorting them during tiling operation.\n // Takes the node id as a parameter and the default tiling operation is perfomed when this option is not set.\n tilingCompareBy: undefined,\n // Represents the amount of the vertical space to put between the zero degree members during the tiling operation(can also be a function)\n tilingPaddingVertical: 10,\n // Represents the amount of the horizontal space to put between the zero degree members during the tiling operation(can also be a function)\n tilingPaddingHorizontal: 10,\n // Gravity range (constant) for compounds\n gravityRangeCompound: 1.5,\n // Gravity force (constant) for compounds\n gravityCompound: 1.0,\n // Gravity range (constant)\n gravityRange: 3.8,\n // Initial cooling factor for incremental layout \n initialEnergyOnIncremental: 0.3,\n\n /* constraint options */\n\n // Fix required nodes to predefined positions\n // [{nodeId: 'n1', position: {x: 100, y: 200}, {...}]\n fixedNodeConstraint: undefined,\n // Align required nodes in vertical/horizontal direction\n // {vertical: [['n1', 'n2')], ['n3', 'n4']], horizontal: ['n2', 'n4']}\n alignmentConstraint: undefined,\n // Place two nodes relatively in vertical/horizontal direction \n // [{top: 'n1', bottom: 'n2', gap: 100}, {left: 'n3', right: 'n4', gap: 75}]\n relativePlacementConstraint: undefined,\n\n /* layout event callbacks */\n ready: function ready() {}, // on layoutready\n stop: function stop() {} // on layoutstop\n});\n\nvar Layout = function () {\n function Layout(options) {\n _classCallCheck(this, Layout);\n\n this.options = assign({}, defaults, options);\n }\n\n _createClass(Layout, [{\n key: 'run',\n value: function run() {\n var layout = this;\n var options = this.options;\n var cy = options.cy;\n var eles = options.eles;\n\n var spectralResult = [];\n var xCoords = void 0;\n var yCoords = void 0;\n var coseResult = [];\n var components = void 0;\n var componentCenters = [];\n\n // basic validity check for constraint inputs \n if (options.fixedNodeConstraint && (!Array.isArray(options.fixedNodeConstraint) || options.fixedNodeConstraint.length == 0)) {\n options.fixedNodeConstraint = undefined;\n }\n\n if (options.alignmentConstraint) {\n if (options.alignmentConstraint.vertical && (!Array.isArray(options.alignmentConstraint.vertical) || options.alignmentConstraint.vertical.length == 0)) {\n options.alignmentConstraint.vertical = undefined;\n }\n if (options.alignmentConstraint.horizontal && (!Array.isArray(options.alignmentConstraint.horizontal) || options.alignmentConstraint.horizontal.length == 0)) {\n options.alignmentConstraint.horizontal = undefined;\n }\n }\n\n if (options.relativePlacementConstraint && (!Array.isArray(options.relativePlacementConstraint) || options.relativePlacementConstraint.length == 0)) {\n options.relativePlacementConstraint = undefined;\n }\n\n // if any constraint exists, set some options\n var constraintExist = options.fixedNodeConstraint || options.alignmentConstraint || options.relativePlacementConstraint;\n if (constraintExist) {\n // constraints work with these options\n options.tile = false;\n options.packComponents = false;\n }\n\n // decide component packing is enabled or not\n var layUtil = void 0;\n var packingEnabled = false;\n if (cy.layoutUtilities && options.packComponents) {\n layUtil = cy.layoutUtilities(\"get\");\n if (!layUtil) layUtil = cy.layoutUtilities();\n packingEnabled = true;\n }\n\n if (eles.nodes().length > 0) {\n // if packing is not enabled, perform layout on the whole graph\n if (!packingEnabled) {\n // store component center\n var boundingBox = options.eles.boundingBox();\n componentCenters.push({ x: boundingBox.x1 + boundingBox.w / 2, y: boundingBox.y1 + boundingBox.h / 2 });\n // apply spectral layout\n if (options.randomize) {\n var result = spectralLayout(options);\n spectralResult.push(result);\n }\n // apply cose layout as postprocessing\n if (options.quality == \"default\" || options.quality == \"proof\") {\n coseResult.push(coseLayout(options, spectralResult[0]));\n aux.relocateComponent(componentCenters[0], coseResult[0], options); // relocate center to original position\n } else {\n aux.relocateComponent(componentCenters[0], spectralResult[0], options); // relocate center to original position\n }\n } else {\n // packing is enabled\n var topMostNodes = aux.getTopMostNodes(options.eles.nodes());\n components = aux.connectComponents(cy, options.eles, topMostNodes);\n // store component centers\n components.forEach(function (component) {\n var boundingBox = component.boundingBox();\n componentCenters.push({ x: boundingBox.x1 + boundingBox.w / 2, y: boundingBox.y1 + boundingBox.h / 2 });\n });\n\n //send each component to spectral layout if randomized\n if (options.randomize) {\n components.forEach(function (component) {\n options.eles = component;\n spectralResult.push(spectralLayout(options));\n });\n }\n\n if (options.quality == \"default\" || options.quality == \"proof\") {\n var toBeTiledNodes = cy.collection();\n if (options.tile) {\n // behave nodes to be tiled as one component\n var nodeIndexes = new Map();\n var _xCoords = [];\n var _yCoords = [];\n var count = 0;\n var tempSpectralResult = { nodeIndexes: nodeIndexes, xCoords: _xCoords, yCoords: _yCoords };\n var indexesToBeDeleted = [];\n components.forEach(function (component, index) {\n if (component.edges().length == 0) {\n component.nodes().forEach(function (node, i) {\n toBeTiledNodes.merge(component.nodes()[i]);\n if (!node.isParent()) {\n tempSpectralResult.nodeIndexes.set(component.nodes()[i].id(), count++);\n tempSpectralResult.xCoords.push(component.nodes()[0].position().x);\n tempSpectralResult.yCoords.push(component.nodes()[0].position().y);\n }\n });\n indexesToBeDeleted.push(index);\n }\n });\n if (toBeTiledNodes.length > 1) {\n var _boundingBox = toBeTiledNodes.boundingBox();\n componentCenters.push({ x: _boundingBox.x1 + _boundingBox.w / 2, y: _boundingBox.y1 + _boundingBox.h / 2 });\n components.push(toBeTiledNodes);\n spectralResult.push(tempSpectralResult);\n for (var i = indexesToBeDeleted.length - 1; i >= 0; i--) {\n components.splice(indexesToBeDeleted[i], 1);\n spectralResult.splice(indexesToBeDeleted[i], 1);\n componentCenters.splice(indexesToBeDeleted[i], 1);\n };\n }\n }\n components.forEach(function (component, index) {\n // send each component to cose layout\n options.eles = component;\n coseResult.push(coseLayout(options, spectralResult[index]));\n aux.relocateComponent(componentCenters[index], coseResult[index], options); // relocate center to original position\n });\n } else {\n components.forEach(function (component, index) {\n aux.relocateComponent(componentCenters[index], spectralResult[index], options); // relocate center to original position\n });\n }\n\n // packing\n var componentsEvaluated = new Set();\n if (components.length > 1) {\n var subgraphs = [];\n var hiddenEles = eles.filter(function (ele) {\n return ele.css('display') == 'none';\n });\n components.forEach(function (component, index) {\n var nodeIndexes = void 0;\n if (options.quality == \"draft\") {\n nodeIndexes = spectralResult[index].nodeIndexes;\n }\n\n if (component.nodes().not(hiddenEles).length > 0) {\n var subgraph = {};\n subgraph.edges = [];\n subgraph.nodes = [];\n var nodeIndex = void 0;\n component.nodes().not(hiddenEles).forEach(function (node) {\n if (options.quality == \"draft\") {\n if (!node.isParent()) {\n nodeIndex = nodeIndexes.get(node.id());\n subgraph.nodes.push({ x: spectralResult[index].xCoords[nodeIndex] - node.boundingbox().w / 2, y: spectralResult[index].yCoords[nodeIndex] - node.boundingbox().h / 2, width: node.boundingbox().w, height: node.boundingbox().h });\n } else {\n var parentInfo = aux.calcBoundingBox(node, spectralResult[index].xCoords, spectralResult[index].yCoords, nodeIndexes);\n subgraph.nodes.push({ x: parentInfo.topLeftX, y: parentInfo.topLeftY, width: parentInfo.width, height: parentInfo.height });\n }\n } else {\n if (coseResult[index][node.id()]) {\n subgraph.nodes.push({ x: coseResult[index][node.id()].getLeft(), y: coseResult[index][node.id()].getTop(), width: coseResult[index][node.id()].getWidth(), height: coseResult[index][node.id()].getHeight() });\n }\n }\n });\n component.edges().forEach(function (edge) {\n var source = edge.source();\n var target = edge.target();\n if (source.css(\"display\") != \"none\" && target.css(\"display\") != \"none\") {\n if (options.quality == \"draft\") {\n var sourceNodeIndex = nodeIndexes.get(source.id());\n var targetNodeIndex = nodeIndexes.get(target.id());\n var sourceCenter = [];\n var targetCenter = [];\n if (source.isParent()) {\n var parentInfo = aux.calcBoundingBox(source, spectralResult[index].xCoords, spectralResult[index].yCoords, nodeIndexes);\n sourceCenter.push(parentInfo.topLeftX + parentInfo.width / 2);\n sourceCenter.push(parentInfo.topLeftY + parentInfo.height / 2);\n } else {\n sourceCenter.push(spectralResult[index].xCoords[sourceNodeIndex]);\n sourceCenter.push(spectralResult[index].yCoords[sourceNodeIndex]);\n }\n if (target.isParent()) {\n var _parentInfo = aux.calcBoundingBox(target, spectralResult[index].xCoords, spectralResult[index].yCoords, nodeIndexes);\n targetCenter.push(_parentInfo.topLeftX + _parentInfo.width / 2);\n targetCenter.push(_parentInfo.topLeftY + _parentInfo.height / 2);\n } else {\n targetCenter.push(spectralResult[index].xCoords[targetNodeIndex]);\n targetCenter.push(spectralResult[index].yCoords[targetNodeIndex]);\n }\n subgraph.edges.push({ startX: sourceCenter[0], startY: sourceCenter[1], endX: targetCenter[0], endY: targetCenter[1] });\n } else {\n if (coseResult[index][source.id()] && coseResult[index][target.id()]) {\n subgraph.edges.push({ startX: coseResult[index][source.id()].getCenterX(), startY: coseResult[index][source.id()].getCenterY(), endX: coseResult[index][target.id()].getCenterX(), endY: coseResult[index][target.id()].getCenterY() });\n }\n }\n }\n });\n if (subgraph.nodes.length > 0) {\n subgraphs.push(subgraph);\n componentsEvaluated.add(index);\n }\n }\n });\n var shiftResult = layUtil.packComponents(subgraphs, options.randomize).shifts;\n if (options.quality == \"draft\") {\n spectralResult.forEach(function (result, index) {\n var newXCoords = result.xCoords.map(function (x) {\n return x + shiftResult[index].dx;\n });\n var newYCoords = result.yCoords.map(function (y) {\n return y + shiftResult[index].dy;\n });\n result.xCoords = newXCoords;\n result.yCoords = newYCoords;\n });\n } else {\n var _count = 0;\n componentsEvaluated.forEach(function (index) {\n Object.keys(coseResult[index]).forEach(function (item) {\n var nodeRectangle = coseResult[index][item];\n nodeRectangle.setCenter(nodeRectangle.getCenterX() + shiftResult[_count].dx, nodeRectangle.getCenterY() + shiftResult[_count].dy);\n });\n _count++;\n });\n }\n }\n }\n }\n\n // get each element's calculated position\n var getPositions = function getPositions(ele, i) {\n if (options.quality == \"default\" || options.quality == \"proof\") {\n if (typeof ele === \"number\") {\n ele = i;\n }\n var pos = void 0;\n var node = void 0;\n var theId = ele.data('id');\n coseResult.forEach(function (result) {\n if (theId in result) {\n pos = { x: result[theId].getRect().getCenterX(), y: result[theId].getRect().getCenterY() };\n node = result[theId];\n }\n });\n if (options.nodeDimensionsIncludeLabels) {\n if (node.labelWidth) {\n if (node.labelPosHorizontal == \"left\") {\n pos.x += node.labelWidth / 2;\n } else if (node.labelPosHorizontal == \"right\") {\n pos.x -= node.labelWidth / 2;\n }\n }\n if (node.labelHeight) {\n if (node.labelPosVertical == \"top\") {\n pos.y += node.labelHeight / 2;\n } else if (node.labelPosVertical == \"bottom\") {\n pos.y -= node.labelHeight / 2;\n }\n }\n }\n if (pos == undefined) pos = { x: ele.position(\"x\"), y: ele.position(\"y\") };\n return {\n x: pos.x,\n y: pos.y\n };\n } else {\n var _pos = void 0;\n spectralResult.forEach(function (result) {\n var index = result.nodeIndexes.get(ele.id());\n if (index != undefined) {\n _pos = { x: result.xCoords[index], y: result.yCoords[index] };\n }\n });\n if (_pos == undefined) _pos = { x: ele.position(\"x\"), y: ele.position(\"y\") };\n return {\n x: _pos.x,\n y: _pos.y\n };\n }\n };\n\n // quality = \"draft\" and randomize = false are contradictive so in that case positions don't change\n if (options.quality == \"default\" || options.quality == \"proof\" || options.randomize) {\n // transfer calculated positions to nodes (positions of only simple nodes are evaluated, compounds are positioned automatically)\n var parentsWithoutChildren = aux.calcParentsWithoutChildren(cy, eles);\n var _hiddenEles = eles.filter(function (ele) {\n return ele.css('display') == 'none';\n });\n options.eles = eles.not(_hiddenEles);\n\n eles.nodes().not(\":parent\").not(_hiddenEles).layoutPositions(layout, options, getPositions);\n\n if (parentsWithoutChildren.length > 0) {\n parentsWithoutChildren.forEach(function (ele) {\n ele.position(getPositions(ele));\n });\n }\n } else {\n console.log(\"If randomize option is set to false, then quality option must be 'default' or 'proof'.\");\n }\n }\n }]);\n\n return Layout;\n}();\n\nmodule.exports = Layout;\n\n/***/ }),\n\n/***/ 657:\n/***/ ((module, __unused_webpack_exports, __webpack_require__) => {\n\n\n\n/**\n The implementation of the spectral layout that is the first part of the fcose layout algorithm\n*/\n\nvar aux = __webpack_require__(548);\nvar Matrix = __webpack_require__(140).layoutBase.Matrix;\nvar SVD = __webpack_require__(140).layoutBase.SVD;\n\n// main function that spectral layout is processed\nvar spectralLayout = function spectralLayout(options) {\n\n var cy = options.cy;\n var eles = options.eles;\n var nodes = eles.nodes();\n var parentNodes = eles.nodes(\":parent\");\n\n var dummyNodes = new Map(); // map to keep dummy nodes and their neighbors\n var nodeIndexes = new Map(); // map to keep indexes to nodes\n var parentChildMap = new Map(); // mapping btw. compound and its representative node \n var allNodesNeighborhood = []; // array to keep neighborhood of all nodes\n var xCoords = [];\n var yCoords = [];\n\n var samplesColumn = []; // sampled vertices\n var minDistancesColumn = [];\n var C = []; // column sampling matrix\n var PHI = []; // intersection of column and row sampling matrices \n var INV = []; // inverse of PHI \n\n var firstSample = void 0; // the first sampled node\n var nodeSize = void 0;\n\n var infinity = 100000000;\n var small = 0.000000001;\n\n var piTol = options.piTol;\n var samplingType = options.samplingType; // false for random, true for greedy\n var nodeSeparation = options.nodeSeparation;\n var sampleSize = void 0;\n\n /**** Spectral-preprocessing functions ****/\n\n /**** Spectral layout functions ****/\n\n // determine which columns to be sampled\n var randomSampleCR = function randomSampleCR() {\n var sample = 0;\n var count = 0;\n var flag = false;\n\n while (count < sampleSize) {\n sample = Math.floor(Math.random() * nodeSize);\n\n flag = false;\n for (var i = 0; i < count; i++) {\n if (samplesColumn[i] == sample) {\n flag = true;\n break;\n }\n }\n\n if (!flag) {\n samplesColumn[count] = sample;\n count++;\n } else {\n continue;\n }\n }\n };\n\n // takes the index of the node(pivot) to initiate BFS as a parameter\n var BFS = function BFS(pivot, index, samplingMethod) {\n var path = []; // the front of the path\n var front = 0; // the back of the path\n var back = 0;\n var current = 0;\n var temp = void 0;\n var distance = [];\n\n var max_dist = 0; // the furthest node to be returned\n var max_ind = 1;\n\n for (var i = 0; i < nodeSize; i++) {\n distance[i] = infinity;\n }\n\n path[back] = pivot;\n distance[pivot] = 0;\n\n while (back >= front) {\n current = path[front++];\n var neighbors = allNodesNeighborhood[current];\n for (var _i = 0; _i < neighbors.length; _i++) {\n temp = nodeIndexes.get(neighbors[_i]);\n if (distance[temp] == infinity) {\n distance[temp] = distance[current] + 1;\n path[++back] = temp;\n }\n }\n C[current][index] = distance[current] * nodeSeparation;\n }\n\n if (samplingMethod) {\n for (var _i2 = 0; _i2 < nodeSize; _i2++) {\n if (C[_i2][index] < minDistancesColumn[_i2]) minDistancesColumn[_i2] = C[_i2][index];\n }\n\n for (var _i3 = 0; _i3 < nodeSize; _i3++) {\n if (minDistancesColumn[_i3] > max_dist) {\n max_dist = minDistancesColumn[_i3];\n max_ind = _i3;\n }\n }\n }\n return max_ind;\n };\n\n // apply BFS to all nodes or selected samples\n var allBFS = function allBFS(samplingMethod) {\n\n var sample = void 0;\n\n if (!samplingMethod) {\n randomSampleCR();\n\n // call BFS\n for (var i = 0; i < sampleSize; i++) {\n BFS(samplesColumn[i], i, samplingMethod, false);\n }\n } else {\n sample = Math.floor(Math.random() * nodeSize);\n firstSample = sample;\n\n for (var _i4 = 0; _i4 < nodeSize; _i4++) {\n minDistancesColumn[_i4] = infinity;\n }\n\n for (var _i5 = 0; _i5 < sampleSize; _i5++) {\n samplesColumn[_i5] = sample;\n sample = BFS(sample, _i5, samplingMethod);\n }\n }\n\n // form the squared distances for C\n for (var _i6 = 0; _i6 < nodeSize; _i6++) {\n for (var j = 0; j < sampleSize; j++) {\n C[_i6][j] *= C[_i6][j];\n }\n }\n\n // form PHI\n for (var _i7 = 0; _i7 < sampleSize; _i7++) {\n PHI[_i7] = [];\n }\n\n for (var _i8 = 0; _i8 < sampleSize; _i8++) {\n for (var _j = 0; _j < sampleSize; _j++) {\n PHI[_i8][_j] = C[samplesColumn[_j]][_i8];\n }\n }\n };\n\n // perform the SVD algorithm and apply a regularization step\n var sample = function sample() {\n\n var SVDResult = SVD.svd(PHI);\n\n var a_q = SVDResult.S;\n var a_u = SVDResult.U;\n var a_v = SVDResult.V;\n\n var max_s = a_q[0] * a_q[0] * a_q[0];\n\n var a_Sig = [];\n\n // regularization\n for (var i = 0; i < sampleSize; i++) {\n a_Sig[i] = [];\n for (var j = 0; j < sampleSize; j++) {\n a_Sig[i][j] = 0;\n if (i == j) {\n a_Sig[i][j] = a_q[i] / (a_q[i] * a_q[i] + max_s / (a_q[i] * a_q[i]));\n }\n }\n }\n\n INV = Matrix.multMat(Matrix.multMat(a_v, a_Sig), Matrix.transpose(a_u));\n };\n\n // calculate final coordinates \n var powerIteration = function powerIteration() {\n // two largest eigenvalues\n var theta1 = void 0;\n var theta2 = void 0;\n\n // initial guesses for eigenvectors\n var Y1 = [];\n var Y2 = [];\n\n var V1 = [];\n var V2 = [];\n\n for (var i = 0; i < nodeSize; i++) {\n Y1[i] = Math.random();\n Y2[i] = Math.random();\n }\n\n Y1 = Matrix.normalize(Y1);\n Y2 = Matrix.normalize(Y2);\n\n var count = 0;\n // to keep track of the improvement ratio in power iteration\n var current = small;\n var previous = small;\n\n var temp = void 0;\n\n while (true) {\n count++;\n\n for (var _i9 = 0; _i9 < nodeSize; _i9++) {\n V1[_i9] = Y1[_i9];\n }\n\n Y1 = Matrix.multGamma(Matrix.multL(Matrix.multGamma(V1), C, INV));\n theta1 = Matrix.dotProduct(V1, Y1);\n Y1 = Matrix.normalize(Y1);\n\n current = Matrix.dotProduct(V1, Y1);\n\n temp = Math.abs(current / previous);\n\n if (temp <= 1 + piTol && temp >= 1) {\n break;\n }\n\n previous = current;\n }\n\n for (var _i10 = 0; _i10 < nodeSize; _i10++) {\n V1[_i10] = Y1[_i10];\n }\n\n count = 0;\n previous = small;\n while (true) {\n count++;\n\n for (var _i11 = 0; _i11 < nodeSize; _i11++) {\n V2[_i11] = Y2[_i11];\n }\n\n V2 = Matrix.minusOp(V2, Matrix.multCons(V1, Matrix.dotProduct(V1, V2)));\n Y2 = Matrix.multGamma(Matrix.multL(Matrix.multGamma(V2), C, INV));\n theta2 = Matrix.dotProduct(V2, Y2);\n Y2 = Matrix.normalize(Y2);\n\n current = Matrix.dotProduct(V2, Y2);\n\n temp = Math.abs(current / previous);\n\n if (temp <= 1 + piTol && temp >= 1) {\n break;\n }\n\n previous = current;\n }\n\n for (var _i12 = 0; _i12 < nodeSize; _i12++) {\n V2[_i12] = Y2[_i12];\n }\n\n // theta1 now contains dominant eigenvalue\n // theta2 now contains the second-largest eigenvalue\n // V1 now contains theta1's eigenvector\n // V2 now contains theta2's eigenvector\n\n //populate the two vectors\n xCoords = Matrix.multCons(V1, Math.sqrt(Math.abs(theta1)));\n yCoords = Matrix.multCons(V2, Math.sqrt(Math.abs(theta2)));\n };\n\n /**** Preparation for spectral layout (Preprocessing) ****/\n\n // connect disconnected components (first top level, then inside of each compound node)\n aux.connectComponents(cy, eles, aux.getTopMostNodes(nodes), dummyNodes);\n\n parentNodes.forEach(function (ele) {\n aux.connectComponents(cy, eles, aux.getTopMostNodes(ele.descendants().intersection(eles)), dummyNodes);\n });\n\n // assign indexes to nodes (first real, then dummy nodes)\n var index = 0;\n for (var i = 0; i < nodes.length; i++) {\n if (!nodes[i].isParent()) {\n nodeIndexes.set(nodes[i].id(), index++);\n }\n }\n\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = dummyNodes.keys()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var key = _step.value;\n\n nodeIndexes.set(key, index++);\n }\n\n // instantiate the neighborhood matrix\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n for (var _i13 = 0; _i13 < nodeIndexes.size; _i13++) {\n allNodesNeighborhood[_i13] = [];\n }\n\n // form a parent-child map to keep representative node of each compound node \n parentNodes.forEach(function (ele) {\n var children = ele.children().intersection(eles);\n\n // let random = 0;\n while (children.nodes(\":childless\").length == 0) {\n // random = Math.floor(Math.random() * children.nodes().length); // if all children are compound then proceed randomly\n children = children.nodes()[0].children().intersection(eles);\n }\n // select the representative node - we can apply different methods here\n // random = Math.floor(Math.random() * children.nodes(\":childless\").length);\n var index = 0;\n var min = children.nodes(\":childless\")[0].connectedEdges().length;\n children.nodes(\":childless\").forEach(function (ele2, i) {\n if (ele2.connectedEdges().length < min) {\n min = ele2.connectedEdges().length;\n index = i;\n }\n });\n parentChildMap.set(ele.id(), children.nodes(\":childless\")[index].id());\n });\n\n // add neighborhood relations (first real, then dummy nodes)\n nodes.forEach(function (ele) {\n var eleIndex = void 0;\n\n if (ele.isParent()) eleIndex = nodeIndexes.get(parentChildMap.get(ele.id()));else eleIndex = nodeIndexes.get(ele.id());\n\n ele.neighborhood().nodes().forEach(function (node) {\n if (eles.intersection(ele.edgesWith(node)).length > 0) {\n if (node.isParent()) allNodesNeighborhood[eleIndex].push(parentChildMap.get(node.id()));else allNodesNeighborhood[eleIndex].push(node.id());\n }\n });\n });\n\n var _loop = function _loop(_key) {\n var eleIndex = nodeIndexes.get(_key);\n var disconnectedId = void 0;\n dummyNodes.get(_key).forEach(function (id) {\n if (cy.getElementById(id).isParent()) disconnectedId = parentChildMap.get(id);else disconnectedId = id;\n\n allNodesNeighborhood[eleIndex].push(disconnectedId);\n allNodesNeighborhood[nodeIndexes.get(disconnectedId)].push(_key);\n });\n };\n\n var _iteratorNormalCompletion2 = true;\n var _didIteratorError2 = false;\n var _iteratorError2 = undefined;\n\n try {\n for (var _iterator2 = dummyNodes.keys()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n var _key = _step2.value;\n\n _loop(_key);\n }\n\n // nodeSize now only considers the size of transformed graph\n } catch (err) {\n _didIteratorError2 = true;\n _iteratorError2 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion2 && _iterator2.return) {\n _iterator2.return();\n }\n } finally {\n if (_didIteratorError2) {\n throw _iteratorError2;\n }\n }\n }\n\n nodeSize = nodeIndexes.size;\n\n var spectralResult = void 0;\n\n // If number of nodes in transformed graph is 1 or 2, either SVD or powerIteration causes problem\n // So skip spectral and layout the graph with cose\n if (nodeSize > 2) {\n // if # of nodes in transformed graph is smaller than sample size,\n // then use # of nodes as sample size\n sampleSize = nodeSize < options.sampleSize ? nodeSize : options.sampleSize;\n\n // instantiates the partial matrices that will be used in spectral layout\n for (var _i14 = 0; _i14 < nodeSize; _i14++) {\n C[_i14] = [];\n }\n for (var _i15 = 0; _i15 < sampleSize; _i15++) {\n INV[_i15] = [];\n }\n\n /**** Apply spectral layout ****/\n\n if (options.quality == \"draft\" || options.step == \"all\") {\n allBFS(samplingType);\n sample();\n powerIteration();\n\n spectralResult = { nodeIndexes: nodeIndexes, xCoords: xCoords, yCoords: yCoords };\n } else {\n nodeIndexes.forEach(function (value, key) {\n xCoords.push(cy.getElementById(key).position(\"x\"));\n yCoords.push(cy.getElementById(key).position(\"y\"));\n });\n spectralResult = { nodeIndexes: nodeIndexes, xCoords: xCoords, yCoords: yCoords };\n }\n return spectralResult;\n } else {\n var iterator = nodeIndexes.keys();\n var firstNode = cy.getElementById(iterator.next().value);\n var firstNodePos = firstNode.position();\n var firstNodeWidth = firstNode.outerWidth();\n xCoords.push(firstNodePos.x);\n yCoords.push(firstNodePos.y);\n if (nodeSize == 2) {\n var secondNode = cy.getElementById(iterator.next().value);\n var secondNodeWidth = secondNode.outerWidth();\n xCoords.push(firstNodePos.x + firstNodeWidth / 2 + secondNodeWidth / 2 + options.idealEdgeLength);\n yCoords.push(firstNodePos.y);\n }\n\n spectralResult = { nodeIndexes: nodeIndexes, xCoords: xCoords, yCoords: yCoords };\n return spectralResult;\n }\n};\n\nmodule.exports = { spectralLayout: spectralLayout };\n\n/***/ }),\n\n/***/ 579:\n/***/ ((module, __unused_webpack_exports, __webpack_require__) => {\n\n\n\nvar impl = __webpack_require__(212);\n\n// registers the extension on a cytoscape lib ref\nvar register = function register(cytoscape) {\n if (!cytoscape) {\n return;\n } // can't register if cytoscape unspecified\n\n cytoscape('layout', 'fcose', impl); // register with cytoscape.js\n};\n\nif (typeof cytoscape !== 'undefined') {\n // expose to global cytoscape (i.e. window.cytoscape)\n register(cytoscape);\n}\n\nmodule.exports = register;\n\n/***/ }),\n\n/***/ 140:\n/***/ ((module) => {\n\nmodule.exports = __WEBPACK_EXTERNAL_MODULE__140__;\n\n/***/ })\n\n/******/ \t});\n/************************************************************************/\n/******/ \t// The module cache\n/******/ \tvar __webpack_module_cache__ = {};\n/******/ \t\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/ \t\t// Check if module is in cache\n/******/ \t\tvar cachedModule = __webpack_module_cache__[moduleId];\n/******/ \t\tif (cachedModule !== undefined) {\n/******/ \t\t\treturn cachedModule.exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = __webpack_module_cache__[moduleId] = {\n/******/ \t\t\t// no module.id needed\n/******/ \t\t\t// no module.loaded needed\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/ \t\n/******/ \t\t// Execute the module function\n/******/ \t\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n/******/ \t\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/ \t\n/************************************************************************/\n/******/ \t\n/******/ \t// startup\n/******/ \t// Load entry module and return exports\n/******/ \t// This entry module is referenced by other modules so it can't be inlined\n/******/ \tvar __webpack_exports__ = __webpack_require__(579);\n/******/ \t\n/******/ \treturn __webpack_exports__;\n/******/ })()\n;\n});", "import {\n selectSvgElement\n} from \"./chunk-EXTU4WIE.mjs\";\nimport {\n createText,\n getIconSVG,\n registerIconPacks,\n unknownIcon\n} from \"./chunk-JA3XYJ7Z.mjs\";\nimport {\n populateCommonDb\n} from \"./chunk-4BX2VUAB.mjs\";\nimport {\n cleanAndMerge,\n getEdgeId\n} from \"./chunk-S3R3BYOJ.mjs\";\nimport {\n clear,\n defaultConfig_default,\n getAccDescription,\n getAccTitle,\n getConfig,\n getConfig2,\n getDiagramTitle,\n sanitizeText,\n setAccDescription,\n setAccTitle,\n setDiagramTitle,\n setupGraphViewbox\n} from \"./chunk-ABZYJK2D.mjs\";\nimport {\n __name,\n log\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/diagrams/architecture/architectureParser.ts\nimport { parse } from \"@mermaid-js/parser\";\n\n// src/diagrams/architecture/architectureTypes.ts\nvar ArchitectureDirectionName = {\n L: \"left\",\n R: \"right\",\n T: \"top\",\n B: \"bottom\"\n};\nvar ArchitectureDirectionArrow = {\n L: /* @__PURE__ */ __name((scale) => `${scale},${scale / 2} 0,${scale} 0,0`, \"L\"),\n R: /* @__PURE__ */ __name((scale) => `0,${scale / 2} ${scale},0 ${scale},${scale}`, \"R\"),\n T: /* @__PURE__ */ __name((scale) => `0,0 ${scale},0 ${scale / 2},${scale}`, \"T\"),\n B: /* @__PURE__ */ __name((scale) => `${scale / 2},0 ${scale},${scale} 0,${scale}`, \"B\")\n};\nvar ArchitectureDirectionArrowShift = {\n L: /* @__PURE__ */ __name((orig, arrowSize) => orig - arrowSize + 2, \"L\"),\n R: /* @__PURE__ */ __name((orig, _arrowSize) => orig - 2, \"R\"),\n T: /* @__PURE__ */ __name((orig, arrowSize) => orig - arrowSize + 2, \"T\"),\n B: /* @__PURE__ */ __name((orig, _arrowSize) => orig - 2, \"B\")\n};\nvar getOppositeArchitectureDirection = /* @__PURE__ */ __name(function(x) {\n if (isArchitectureDirectionX(x)) {\n return x === \"L\" ? \"R\" : \"L\";\n } else {\n return x === \"T\" ? \"B\" : \"T\";\n }\n}, \"getOppositeArchitectureDirection\");\nvar isArchitectureDirection = /* @__PURE__ */ __name(function(x) {\n const temp = x;\n return temp === \"L\" || temp === \"R\" || temp === \"T\" || temp === \"B\";\n}, \"isArchitectureDirection\");\nvar isArchitectureDirectionX = /* @__PURE__ */ __name(function(x) {\n const temp = x;\n return temp === \"L\" || temp === \"R\";\n}, \"isArchitectureDirectionX\");\nvar isArchitectureDirectionY = /* @__PURE__ */ __name(function(x) {\n const temp = x;\n return temp === \"T\" || temp === \"B\";\n}, \"isArchitectureDirectionY\");\nvar isArchitectureDirectionXY = /* @__PURE__ */ __name(function(a, b) {\n const aX_bY = isArchitectureDirectionX(a) && isArchitectureDirectionY(b);\n const aY_bX = isArchitectureDirectionY(a) && isArchitectureDirectionX(b);\n return aX_bY || aY_bX;\n}, \"isArchitectureDirectionXY\");\nvar isArchitecturePairXY = /* @__PURE__ */ __name(function(pair) {\n const lhs = pair[0];\n const rhs = pair[1];\n const aX_bY = isArchitectureDirectionX(lhs) && isArchitectureDirectionY(rhs);\n const aY_bX = isArchitectureDirectionY(lhs) && isArchitectureDirectionX(rhs);\n return aX_bY || aY_bX;\n}, \"isArchitecturePairXY\");\nvar isValidArchitectureDirectionPair = /* @__PURE__ */ __name(function(x) {\n return x !== \"LL\" && x !== \"RR\" && x !== \"TT\" && x !== \"BB\";\n}, \"isValidArchitectureDirectionPair\");\nvar getArchitectureDirectionPair = /* @__PURE__ */ __name(function(sourceDir, targetDir) {\n const pair = `${sourceDir}${targetDir}`;\n return isValidArchitectureDirectionPair(pair) ? pair : void 0;\n}, \"getArchitectureDirectionPair\");\nvar shiftPositionByArchitectureDirectionPair = /* @__PURE__ */ __name(function([x, y], pair) {\n const lhs = pair[0];\n const rhs = pair[1];\n if (isArchitectureDirectionX(lhs)) {\n if (isArchitectureDirectionY(rhs)) {\n return [x + (lhs === \"L\" ? -1 : 1), y + (rhs === \"T\" ? 1 : -1)];\n } else {\n return [x + (lhs === \"L\" ? -1 : 1), y];\n }\n } else {\n if (isArchitectureDirectionX(rhs)) {\n return [x + (rhs === \"L\" ? 1 : -1), y + (lhs === \"T\" ? 1 : -1)];\n } else {\n return [x, y + (lhs === \"T\" ? 1 : -1)];\n }\n }\n}, \"shiftPositionByArchitectureDirectionPair\");\nvar getArchitectureDirectionXYFactors = /* @__PURE__ */ __name(function(pair) {\n if (pair === \"LT\" || pair === \"TL\") {\n return [1, 1];\n } else if (pair === \"BL\" || pair === \"LB\") {\n return [1, -1];\n } else if (pair === \"BR\" || pair === \"RB\") {\n return [-1, -1];\n } else {\n return [-1, 1];\n }\n}, \"getArchitectureDirectionXYFactors\");\nvar getArchitectureDirectionAlignment = /* @__PURE__ */ __name(function(a, b) {\n if (isArchitectureDirectionXY(a, b)) {\n return \"bend\";\n } else if (isArchitectureDirectionX(a)) {\n return \"horizontal\";\n }\n return \"vertical\";\n}, \"getArchitectureDirectionAlignment\");\nvar isArchitectureService = /* @__PURE__ */ __name(function(x) {\n const temp = x;\n return temp.type === \"service\";\n}, \"isArchitectureService\");\nvar isArchitectureJunction = /* @__PURE__ */ __name(function(x) {\n const temp = x;\n return temp.type === \"junction\";\n}, \"isArchitectureJunction\");\nvar edgeData = /* @__PURE__ */ __name((edge) => {\n return edge.data();\n}, \"edgeData\");\nvar nodeData = /* @__PURE__ */ __name((node) => {\n return node.data();\n}, \"nodeData\");\n\n// src/diagrams/architecture/architectureDb.ts\nvar DEFAULT_ARCHITECTURE_CONFIG = defaultConfig_default.architecture;\nvar ArchitectureDB = class {\n constructor() {\n this.nodes = {};\n this.groups = {};\n this.edges = [];\n this.registeredIds = {};\n this.elements = {};\n this.setAccTitle = setAccTitle;\n this.getAccTitle = getAccTitle;\n this.setDiagramTitle = setDiagramTitle;\n this.getDiagramTitle = getDiagramTitle;\n this.getAccDescription = getAccDescription;\n this.setAccDescription = setAccDescription;\n this.clear();\n }\n static {\n __name(this, \"ArchitectureDB\");\n }\n clear() {\n this.nodes = {};\n this.groups = {};\n this.edges = [];\n this.registeredIds = {};\n this.dataStructures = void 0;\n this.elements = {};\n clear();\n }\n addService({\n id,\n icon,\n in: parent,\n title,\n iconText\n }) {\n if (this.registeredIds[id] !== void 0) {\n throw new Error(\n `The service id [${id}] is already in use by another ${this.registeredIds[id]}`\n );\n }\n if (parent !== void 0) {\n if (id === parent) {\n throw new Error(`The service [${id}] cannot be placed within itself`);\n }\n if (this.registeredIds[parent] === void 0) {\n throw new Error(\n `The service [${id}]'s parent does not exist. Please make sure the parent is created before this service`\n );\n }\n if (this.registeredIds[parent] === \"node\") {\n throw new Error(`The service [${id}]'s parent is not a group`);\n }\n }\n this.registeredIds[id] = \"node\";\n this.nodes[id] = {\n id,\n type: \"service\",\n icon,\n iconText,\n title,\n edges: [],\n in: parent\n };\n }\n getServices() {\n return Object.values(this.nodes).filter(isArchitectureService);\n }\n addJunction({ id, in: parent }) {\n this.registeredIds[id] = \"node\";\n this.nodes[id] = {\n id,\n type: \"junction\",\n edges: [],\n in: parent\n };\n }\n getJunctions() {\n return Object.values(this.nodes).filter(isArchitectureJunction);\n }\n getNodes() {\n return Object.values(this.nodes);\n }\n getNode(id) {\n return this.nodes[id] ?? null;\n }\n addGroup({ id, icon, in: parent, title }) {\n if (this.registeredIds?.[id] !== void 0) {\n throw new Error(\n `The group id [${id}] is already in use by another ${this.registeredIds[id]}`\n );\n }\n if (parent !== void 0) {\n if (id === parent) {\n throw new Error(`The group [${id}] cannot be placed within itself`);\n }\n if (this.registeredIds?.[parent] === void 0) {\n throw new Error(\n `The group [${id}]'s parent does not exist. Please make sure the parent is created before this group`\n );\n }\n if (this.registeredIds?.[parent] === \"node\") {\n throw new Error(`The group [${id}]'s parent is not a group`);\n }\n }\n this.registeredIds[id] = \"group\";\n this.groups[id] = {\n id,\n icon,\n title,\n in: parent\n };\n }\n getGroups() {\n return Object.values(this.groups);\n }\n addEdge({\n lhsId,\n rhsId,\n lhsDir,\n rhsDir,\n lhsInto,\n rhsInto,\n lhsGroup,\n rhsGroup,\n title\n }) {\n if (!isArchitectureDirection(lhsDir)) {\n throw new Error(\n `Invalid direction given for left hand side of edge ${lhsId}--${rhsId}. Expected (L,R,T,B) got ${String(lhsDir)}`\n );\n }\n if (!isArchitectureDirection(rhsDir)) {\n throw new Error(\n `Invalid direction given for right hand side of edge ${lhsId}--${rhsId}. Expected (L,R,T,B) got ${String(rhsDir)}`\n );\n }\n if (this.nodes[lhsId] === void 0 && this.groups[lhsId] === void 0) {\n throw new Error(\n `The left-hand id [${lhsId}] does not yet exist. Please create the service/group before declaring an edge to it.`\n );\n }\n if (this.nodes[rhsId] === void 0 && this.groups[rhsId] === void 0) {\n throw new Error(\n `The right-hand id [${rhsId}] does not yet exist. Please create the service/group before declaring an edge to it.`\n );\n }\n const lhsGroupId = this.nodes[lhsId].in;\n const rhsGroupId = this.nodes[rhsId].in;\n if (lhsGroup && lhsGroupId && rhsGroupId && lhsGroupId == rhsGroupId) {\n throw new Error(\n `The left-hand id [${lhsId}] is modified to traverse the group boundary, but the edge does not pass through two groups.`\n );\n }\n if (rhsGroup && lhsGroupId && rhsGroupId && lhsGroupId == rhsGroupId) {\n throw new Error(\n `The right-hand id [${rhsId}] is modified to traverse the group boundary, but the edge does not pass through two groups.`\n );\n }\n const edge = {\n lhsId,\n lhsDir,\n lhsInto,\n lhsGroup,\n rhsId,\n rhsDir,\n rhsInto,\n rhsGroup,\n title\n };\n this.edges.push(edge);\n if (this.nodes[lhsId] && this.nodes[rhsId]) {\n this.nodes[lhsId].edges.push(this.edges[this.edges.length - 1]);\n this.nodes[rhsId].edges.push(this.edges[this.edges.length - 1]);\n }\n }\n getEdges() {\n return this.edges;\n }\n /**\n * Returns the current diagram's adjacency list, spatial map, & group alignments.\n * If they have not been created, run the algorithms to generate them.\n * @returns\n */\n getDataStructures() {\n if (this.dataStructures === void 0) {\n const groupAlignments = {};\n const adjList = Object.entries(this.nodes).reduce((prevOuter, [id, service]) => {\n prevOuter[id] = service.edges.reduce((prevInner, edge) => {\n const lhsGroupId = this.getNode(edge.lhsId)?.in;\n const rhsGroupId = this.getNode(edge.rhsId)?.in;\n if (lhsGroupId && rhsGroupId && lhsGroupId !== rhsGroupId) {\n const alignment = getArchitectureDirectionAlignment(edge.lhsDir, edge.rhsDir);\n if (alignment !== \"bend\") {\n groupAlignments[lhsGroupId] ??= {};\n groupAlignments[lhsGroupId][rhsGroupId] = alignment;\n groupAlignments[rhsGroupId] ??= {};\n groupAlignments[rhsGroupId][lhsGroupId] = alignment;\n }\n }\n if (edge.lhsId === id) {\n const pair = getArchitectureDirectionPair(edge.lhsDir, edge.rhsDir);\n if (pair) {\n prevInner[pair] = edge.rhsId;\n }\n } else {\n const pair = getArchitectureDirectionPair(edge.rhsDir, edge.lhsDir);\n if (pair) {\n prevInner[pair] = edge.lhsId;\n }\n }\n return prevInner;\n }, {});\n return prevOuter;\n }, {});\n const firstId = Object.keys(adjList)[0];\n const visited = { [firstId]: 1 };\n const notVisited = Object.keys(adjList).reduce(\n (prev, id) => id === firstId ? prev : { ...prev, [id]: 1 },\n {}\n );\n const BFS = /* @__PURE__ */ __name((startingId) => {\n const spatialMap = { [startingId]: [0, 0] };\n const queue = [startingId];\n while (queue.length > 0) {\n const id = queue.shift();\n if (id) {\n visited[id] = 1;\n delete notVisited[id];\n const adj = adjList[id];\n const [posX, posY] = spatialMap[id];\n Object.entries(adj).forEach(([dir, rhsId]) => {\n if (!visited[rhsId]) {\n spatialMap[rhsId] = shiftPositionByArchitectureDirectionPair(\n [posX, posY],\n dir\n );\n queue.push(rhsId);\n }\n });\n }\n }\n return spatialMap;\n }, \"BFS\");\n const spatialMaps = [BFS(firstId)];\n while (Object.keys(notVisited).length > 0) {\n spatialMaps.push(BFS(Object.keys(notVisited)[0]));\n }\n this.dataStructures = {\n adjList,\n spatialMaps,\n groupAlignments\n };\n }\n return this.dataStructures;\n }\n setElementForId(id, element) {\n this.elements[id] = element;\n }\n getElementById(id) {\n return this.elements[id];\n }\n getConfig() {\n return cleanAndMerge({\n ...DEFAULT_ARCHITECTURE_CONFIG,\n ...getConfig().architecture\n });\n }\n getConfigField(field) {\n return this.getConfig()[field];\n }\n};\n\n// src/diagrams/architecture/architectureParser.ts\nvar populateDb = /* @__PURE__ */ __name((ast, db) => {\n populateCommonDb(ast, db);\n ast.groups.map((group) => db.addGroup(group));\n ast.services.map((service) => db.addService({ ...service, type: \"service\" }));\n ast.junctions.map((service) => db.addJunction({ ...service, type: \"junction\" }));\n ast.edges.map((edge) => db.addEdge(edge));\n}, \"populateDb\");\nvar parser = {\n parser: {\n // @ts-expect-error - ArchitectureDB is not assignable to DiagramDB\n yy: void 0\n },\n parse: /* @__PURE__ */ __name(async (input) => {\n const ast = await parse(\"architecture\", input);\n log.debug(ast);\n const db = parser.parser?.yy;\n if (!(db instanceof ArchitectureDB)) {\n throw new Error(\n \"parser.parser?.yy was not a ArchitectureDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.\"\n );\n }\n populateDb(ast, db);\n }, \"parse\")\n};\n\n// src/diagrams/architecture/architectureStyles.ts\nvar getStyles = /* @__PURE__ */ __name((options) => `\n .edge {\n stroke-width: ${options.archEdgeWidth};\n stroke: ${options.archEdgeColor};\n fill: none;\n }\n\n .arrow {\n fill: ${options.archEdgeArrowColor};\n }\n\n .node-bkg {\n fill: none;\n stroke: ${options.archGroupBorderColor};\n stroke-width: ${options.archGroupBorderWidth};\n stroke-dasharray: 8;\n }\n .node-icon-text {\n display: flex; \n align-items: center;\n }\n \n .node-icon-text > div {\n color: #fff;\n margin: 1px;\n height: fit-content;\n text-align: center;\n overflow: hidden;\n display: -webkit-box;\n -webkit-box-orient: vertical;\n }\n`, \"getStyles\");\nvar architectureStyles_default = getStyles;\n\n// src/diagrams/architecture/architectureRenderer.ts\nimport cytoscape from \"cytoscape\";\nimport fcose from \"cytoscape-fcose\";\nimport { select } from \"d3\";\n\n// src/diagrams/architecture/architectureIcons.ts\nvar wrapIcon = /* @__PURE__ */ __name((icon) => {\n return `${icon}`;\n}, \"wrapIcon\");\nvar architectureIcons = {\n prefix: \"mermaid-architecture\",\n height: 80,\n width: 80,\n icons: {\n database: {\n body: wrapIcon(\n ''\n )\n },\n server: {\n body: wrapIcon(\n ''\n )\n },\n disk: {\n body: wrapIcon(\n ''\n )\n },\n internet: {\n body: wrapIcon(\n ''\n )\n },\n cloud: {\n body: wrapIcon(\n ''\n )\n },\n unknown: unknownIcon,\n blank: {\n body: wrapIcon(\"\")\n }\n }\n};\n\n// src/diagrams/architecture/svgDraw.ts\nvar drawEdges = /* @__PURE__ */ __name(async function(edgesEl, cy, db) {\n const padding = db.getConfigField(\"padding\");\n const iconSize = db.getConfigField(\"iconSize\");\n const halfIconSize = iconSize / 2;\n const arrowSize = iconSize / 6;\n const halfArrowSize = arrowSize / 2;\n await Promise.all(\n cy.edges().map(async (edge) => {\n const {\n source,\n sourceDir,\n sourceArrow,\n sourceGroup,\n target,\n targetDir,\n targetArrow,\n targetGroup,\n label\n } = edgeData(edge);\n let { x: startX, y: startY } = edge[0].sourceEndpoint();\n const { x: midX, y: midY } = edge[0].midpoint();\n let { x: endX, y: endY } = edge[0].targetEndpoint();\n const groupEdgeShift = padding + 4;\n if (sourceGroup) {\n if (isArchitectureDirectionX(sourceDir)) {\n startX += sourceDir === \"L\" ? -groupEdgeShift : groupEdgeShift;\n } else {\n startY += sourceDir === \"T\" ? -groupEdgeShift : groupEdgeShift + 18;\n }\n }\n if (targetGroup) {\n if (isArchitectureDirectionX(targetDir)) {\n endX += targetDir === \"L\" ? -groupEdgeShift : groupEdgeShift;\n } else {\n endY += targetDir === \"T\" ? -groupEdgeShift : groupEdgeShift + 18;\n }\n }\n if (!sourceGroup && db.getNode(source)?.type === \"junction\") {\n if (isArchitectureDirectionX(sourceDir)) {\n startX += sourceDir === \"L\" ? halfIconSize : -halfIconSize;\n } else {\n startY += sourceDir === \"T\" ? halfIconSize : -halfIconSize;\n }\n }\n if (!targetGroup && db.getNode(target)?.type === \"junction\") {\n if (isArchitectureDirectionX(targetDir)) {\n endX += targetDir === \"L\" ? halfIconSize : -halfIconSize;\n } else {\n endY += targetDir === \"T\" ? halfIconSize : -halfIconSize;\n }\n }\n if (edge[0]._private.rscratch) {\n const g = edgesEl.insert(\"g\");\n g.insert(\"path\").attr(\"d\", `M ${startX},${startY} L ${midX},${midY} L${endX},${endY} `).attr(\"class\", \"edge\").attr(\"id\", getEdgeId(source, target, { prefix: \"L\" }));\n if (sourceArrow) {\n const xShift = isArchitectureDirectionX(sourceDir) ? ArchitectureDirectionArrowShift[sourceDir](startX, arrowSize) : startX - halfArrowSize;\n const yShift = isArchitectureDirectionY(sourceDir) ? ArchitectureDirectionArrowShift[sourceDir](startY, arrowSize) : startY - halfArrowSize;\n g.insert(\"polygon\").attr(\"points\", ArchitectureDirectionArrow[sourceDir](arrowSize)).attr(\"transform\", `translate(${xShift},${yShift})`).attr(\"class\", \"arrow\");\n }\n if (targetArrow) {\n const xShift = isArchitectureDirectionX(targetDir) ? ArchitectureDirectionArrowShift[targetDir](endX, arrowSize) : endX - halfArrowSize;\n const yShift = isArchitectureDirectionY(targetDir) ? ArchitectureDirectionArrowShift[targetDir](endY, arrowSize) : endY - halfArrowSize;\n g.insert(\"polygon\").attr(\"points\", ArchitectureDirectionArrow[targetDir](arrowSize)).attr(\"transform\", `translate(${xShift},${yShift})`).attr(\"class\", \"arrow\");\n }\n if (label) {\n const axis = !isArchitectureDirectionXY(sourceDir, targetDir) ? isArchitectureDirectionX(sourceDir) ? \"X\" : \"Y\" : \"XY\";\n let width = 0;\n if (axis === \"X\") {\n width = Math.abs(startX - endX);\n } else if (axis === \"Y\") {\n width = Math.abs(startY - endY) / 1.5;\n } else {\n width = Math.abs(startX - endX) / 2;\n }\n const textElem = g.append(\"g\");\n await createText(\n textElem,\n label,\n {\n useHtmlLabels: false,\n width,\n classes: \"architecture-service-label\"\n },\n getConfig2()\n );\n textElem.attr(\"dy\", \"1em\").attr(\"alignment-baseline\", \"middle\").attr(\"dominant-baseline\", \"middle\").attr(\"text-anchor\", \"middle\");\n if (axis === \"X\") {\n textElem.attr(\"transform\", \"translate(\" + midX + \", \" + midY + \")\");\n } else if (axis === \"Y\") {\n textElem.attr(\"transform\", \"translate(\" + midX + \", \" + midY + \") rotate(-90)\");\n } else if (axis === \"XY\") {\n const pair = getArchitectureDirectionPair(sourceDir, targetDir);\n if (pair && isArchitecturePairXY(pair)) {\n const bboxOrig = textElem.node().getBoundingClientRect();\n const [x, y] = getArchitectureDirectionXYFactors(pair);\n textElem.attr(\"dominant-baseline\", \"auto\").attr(\"transform\", `rotate(${-1 * x * y * 45})`);\n const bboxNew = textElem.node().getBoundingClientRect();\n textElem.attr(\n \"transform\",\n `\n translate(${midX}, ${midY - bboxOrig.height / 2})\n translate(${x * bboxNew.width / 2}, ${y * bboxNew.height / 2})\n rotate(${-1 * x * y * 45}, 0, ${bboxOrig.height / 2})\n `\n );\n }\n }\n }\n }\n })\n );\n}, \"drawEdges\");\nvar drawGroups = /* @__PURE__ */ __name(async function(groupsEl, cy, db) {\n const padding = db.getConfigField(\"padding\");\n const groupIconSize = padding * 0.75;\n const fontSize = db.getConfigField(\"fontSize\");\n const iconSize = db.getConfigField(\"iconSize\");\n const halfIconSize = iconSize / 2;\n await Promise.all(\n cy.nodes().map(async (node) => {\n const data = nodeData(node);\n if (data.type === \"group\") {\n const { h, w, x1, y1 } = node.boundingBox();\n const groupsNode = groupsEl.append(\"rect\");\n groupsNode.attr(\"id\", `group-${data.id}`).attr(\"x\", x1 + halfIconSize).attr(\"y\", y1 + halfIconSize).attr(\"width\", w).attr(\"height\", h).attr(\"class\", \"node-bkg\");\n const groupLabelContainer = groupsEl.append(\"g\");\n let shiftedX1 = x1;\n let shiftedY1 = y1;\n if (data.icon) {\n const bkgElem = groupLabelContainer.append(\"g\");\n bkgElem.html(\n `${await getIconSVG(data.icon, { height: groupIconSize, width: groupIconSize, fallbackPrefix: architectureIcons.prefix })}`\n );\n bkgElem.attr(\n \"transform\",\n \"translate(\" + (shiftedX1 + halfIconSize + 1) + \", \" + (shiftedY1 + halfIconSize + 1) + \")\"\n );\n shiftedX1 += groupIconSize;\n shiftedY1 += fontSize / 2 - 1 - 2;\n }\n if (data.label) {\n const textElem = groupLabelContainer.append(\"g\");\n await createText(\n textElem,\n data.label,\n {\n useHtmlLabels: false,\n width: w,\n classes: \"architecture-service-label\"\n },\n getConfig2()\n );\n textElem.attr(\"dy\", \"1em\").attr(\"alignment-baseline\", \"middle\").attr(\"dominant-baseline\", \"start\").attr(\"text-anchor\", \"start\");\n textElem.attr(\n \"transform\",\n \"translate(\" + (shiftedX1 + halfIconSize + 4) + \", \" + (shiftedY1 + halfIconSize + 2) + \")\"\n );\n }\n db.setElementForId(data.id, groupsNode);\n }\n })\n );\n}, \"drawGroups\");\nvar drawServices = /* @__PURE__ */ __name(async function(db, elem, services) {\n const config = getConfig2();\n for (const service of services) {\n const serviceElem = elem.append(\"g\");\n const iconSize = db.getConfigField(\"iconSize\");\n if (service.title) {\n const textElem = serviceElem.append(\"g\");\n await createText(\n textElem,\n service.title,\n {\n useHtmlLabels: false,\n width: iconSize * 1.5,\n classes: \"architecture-service-label\"\n },\n config\n );\n textElem.attr(\"dy\", \"1em\").attr(\"alignment-baseline\", \"middle\").attr(\"dominant-baseline\", \"middle\").attr(\"text-anchor\", \"middle\");\n textElem.attr(\"transform\", \"translate(\" + iconSize / 2 + \", \" + iconSize + \")\");\n }\n const bkgElem = serviceElem.append(\"g\");\n if (service.icon) {\n bkgElem.html(\n `${await getIconSVG(service.icon, { height: iconSize, width: iconSize, fallbackPrefix: architectureIcons.prefix })}`\n );\n } else if (service.iconText) {\n bkgElem.html(\n `${await getIconSVG(\"blank\", { height: iconSize, width: iconSize, fallbackPrefix: architectureIcons.prefix })}`\n );\n const textElemContainer = bkgElem.append(\"g\");\n const fo = textElemContainer.append(\"foreignObject\").attr(\"width\", iconSize).attr(\"height\", iconSize);\n const divElem = fo.append(\"div\").attr(\"class\", \"node-icon-text\").attr(\"style\", `height: ${iconSize}px;`).append(\"div\").html(sanitizeText(service.iconText, config));\n const fontSize = parseInt(\n window.getComputedStyle(divElem.node(), null).getPropertyValue(\"font-size\").replace(/\\D/g, \"\")\n ) ?? 16;\n divElem.attr(\"style\", `-webkit-line-clamp: ${Math.floor((iconSize - 2) / fontSize)};`);\n } else {\n bkgElem.append(\"path\").attr(\"class\", \"node-bkg\").attr(\"id\", \"node-\" + service.id).attr(\n \"d\",\n `M0 ${iconSize} v${-iconSize} q0,-5 5,-5 h${iconSize} q5,0 5,5 v${iconSize} H0 Z`\n );\n }\n serviceElem.attr(\"id\", `service-${service.id}`).attr(\"class\", \"architecture-service\");\n const { width, height } = serviceElem.node().getBBox();\n service.width = width;\n service.height = height;\n db.setElementForId(service.id, serviceElem);\n }\n return 0;\n}, \"drawServices\");\nvar drawJunctions = /* @__PURE__ */ __name(function(db, elem, junctions) {\n junctions.forEach((junction) => {\n const junctionElem = elem.append(\"g\");\n const iconSize = db.getConfigField(\"iconSize\");\n const bkgElem = junctionElem.append(\"g\");\n bkgElem.append(\"rect\").attr(\"id\", \"node-\" + junction.id).attr(\"fill-opacity\", \"0\").attr(\"width\", iconSize).attr(\"height\", iconSize);\n junctionElem.attr(\"class\", \"architecture-junction\");\n const { width, height } = junctionElem._groups[0][0].getBBox();\n junctionElem.width = width;\n junctionElem.height = height;\n db.setElementForId(junction.id, junctionElem);\n });\n}, \"drawJunctions\");\n\n// src/diagrams/architecture/architectureRenderer.ts\nregisterIconPacks([\n {\n name: architectureIcons.prefix,\n icons: architectureIcons\n }\n]);\ncytoscape.use(fcose);\nfunction addServices(services, cy, db) {\n services.forEach((service) => {\n cy.add({\n group: \"nodes\",\n data: {\n type: \"service\",\n id: service.id,\n icon: service.icon,\n label: service.title,\n parent: service.in,\n width: db.getConfigField(\"iconSize\"),\n height: db.getConfigField(\"iconSize\")\n },\n classes: \"node-service\"\n });\n });\n}\n__name(addServices, \"addServices\");\nfunction addJunctions(junctions, cy, db) {\n junctions.forEach((junction) => {\n cy.add({\n group: \"nodes\",\n data: {\n type: \"junction\",\n id: junction.id,\n parent: junction.in,\n width: db.getConfigField(\"iconSize\"),\n height: db.getConfigField(\"iconSize\")\n },\n classes: \"node-junction\"\n });\n });\n}\n__name(addJunctions, \"addJunctions\");\nfunction positionNodes(db, cy) {\n cy.nodes().map((node) => {\n const data = nodeData(node);\n if (data.type === \"group\") {\n return;\n }\n data.x = node.position().x;\n data.y = node.position().y;\n const nodeElem = db.getElementById(data.id);\n nodeElem.attr(\"transform\", \"translate(\" + (data.x || 0) + \",\" + (data.y || 0) + \")\");\n });\n}\n__name(positionNodes, \"positionNodes\");\nfunction addGroups(groups, cy) {\n groups.forEach((group) => {\n cy.add({\n group: \"nodes\",\n data: {\n type: \"group\",\n id: group.id,\n icon: group.icon,\n label: group.title,\n parent: group.in\n },\n classes: \"node-group\"\n });\n });\n}\n__name(addGroups, \"addGroups\");\nfunction addEdges(edges, cy) {\n edges.forEach((parsedEdge) => {\n const { lhsId, rhsId, lhsInto, lhsGroup, rhsInto, lhsDir, rhsDir, rhsGroup, title } = parsedEdge;\n const edgeType = isArchitectureDirectionXY(parsedEdge.lhsDir, parsedEdge.rhsDir) ? \"segments\" : \"straight\";\n const edge = {\n id: `${lhsId}-${rhsId}`,\n label: title,\n source: lhsId,\n sourceDir: lhsDir,\n sourceArrow: lhsInto,\n sourceGroup: lhsGroup,\n sourceEndpoint: lhsDir === \"L\" ? \"0 50%\" : lhsDir === \"R\" ? \"100% 50%\" : lhsDir === \"T\" ? \"50% 0\" : \"50% 100%\",\n target: rhsId,\n targetDir: rhsDir,\n targetArrow: rhsInto,\n targetGroup: rhsGroup,\n targetEndpoint: rhsDir === \"L\" ? \"0 50%\" : rhsDir === \"R\" ? \"100% 50%\" : rhsDir === \"T\" ? \"50% 0\" : \"50% 100%\"\n };\n cy.add({\n group: \"edges\",\n data: edge,\n classes: edgeType\n });\n });\n}\n__name(addEdges, \"addEdges\");\nfunction getAlignments(db, spatialMaps, groupAlignments) {\n const flattenAlignments = /* @__PURE__ */ __name((alignmentObj, alignmentDir) => {\n return Object.entries(alignmentObj).reduce(\n (prev, [dir, alignments2]) => {\n let cnt = 0;\n const arr = Object.entries(alignments2);\n if (arr.length === 1) {\n prev[dir] = arr[0][1];\n return prev;\n }\n for (let i = 0; i < arr.length - 1; i++) {\n for (let j = i + 1; j < arr.length; j++) {\n const [aGroupId, aNodeIds] = arr[i];\n const [bGroupId, bNodeIds] = arr[j];\n const alignment = groupAlignments[aGroupId]?.[bGroupId];\n if (alignment === alignmentDir) {\n prev[dir] ??= [];\n prev[dir] = [...prev[dir], ...aNodeIds, ...bNodeIds];\n } else if (aGroupId === \"default\" || bGroupId === \"default\") {\n prev[dir] ??= [];\n prev[dir] = [...prev[dir], ...aNodeIds, ...bNodeIds];\n } else {\n const keyA = `${dir}-${cnt++}`;\n prev[keyA] = aNodeIds;\n const keyB = `${dir}-${cnt++}`;\n prev[keyB] = bNodeIds;\n }\n }\n }\n return prev;\n },\n {}\n );\n }, \"flattenAlignments\");\n const alignments = spatialMaps.map((spatialMap) => {\n const horizontalAlignments = {};\n const verticalAlignments = {};\n Object.entries(spatialMap).forEach(([id, [x, y]]) => {\n const nodeGroup = db.getNode(id)?.in ?? \"default\";\n horizontalAlignments[y] ??= {};\n horizontalAlignments[y][nodeGroup] ??= [];\n horizontalAlignments[y][nodeGroup].push(id);\n verticalAlignments[x] ??= {};\n verticalAlignments[x][nodeGroup] ??= [];\n verticalAlignments[x][nodeGroup].push(id);\n });\n return {\n horiz: Object.values(flattenAlignments(horizontalAlignments, \"horizontal\")).filter(\n (arr) => arr.length > 1\n ),\n vert: Object.values(flattenAlignments(verticalAlignments, \"vertical\")).filter(\n (arr) => arr.length > 1\n )\n };\n });\n const [horizontal, vertical] = alignments.reduce(\n ([prevHoriz, prevVert], { horiz, vert }) => {\n return [\n [...prevHoriz, ...horiz],\n [...prevVert, ...vert]\n ];\n },\n [[], []]\n );\n return {\n horizontal,\n vertical\n };\n}\n__name(getAlignments, \"getAlignments\");\nfunction getRelativeConstraints(spatialMaps, db) {\n const relativeConstraints = [];\n const posToStr = /* @__PURE__ */ __name((pos) => `${pos[0]},${pos[1]}`, \"posToStr\");\n const strToPos = /* @__PURE__ */ __name((pos) => pos.split(\",\").map((p) => parseInt(p)), \"strToPos\");\n spatialMaps.forEach((spatialMap) => {\n const invSpatialMap = Object.fromEntries(\n Object.entries(spatialMap).map(([id, pos]) => [posToStr(pos), id])\n );\n const queue = [posToStr([0, 0])];\n const visited = {};\n const directions = {\n L: [-1, 0],\n R: [1, 0],\n T: [0, 1],\n B: [0, -1]\n };\n while (queue.length > 0) {\n const curr = queue.shift();\n if (curr) {\n visited[curr] = 1;\n const currId = invSpatialMap[curr];\n if (currId) {\n const currPos = strToPos(curr);\n Object.entries(directions).forEach(([dir, shift]) => {\n const newPos = posToStr([currPos[0] + shift[0], currPos[1] + shift[1]]);\n const newId = invSpatialMap[newPos];\n if (newId && !visited[newPos]) {\n queue.push(newPos);\n relativeConstraints.push({\n [ArchitectureDirectionName[dir]]: newId,\n [ArchitectureDirectionName[getOppositeArchitectureDirection(dir)]]: currId,\n gap: 1.5 * db.getConfigField(\"iconSize\")\n });\n }\n });\n }\n }\n }\n });\n return relativeConstraints;\n}\n__name(getRelativeConstraints, \"getRelativeConstraints\");\nfunction layoutArchitecture(services, junctions, groups, edges, db, { spatialMaps, groupAlignments }) {\n return new Promise((resolve) => {\n const renderEl = select(\"body\").append(\"div\").attr(\"id\", \"cy\").attr(\"style\", \"display:none\");\n const cy = cytoscape({\n container: document.getElementById(\"cy\"),\n style: [\n {\n selector: \"edge\",\n style: {\n \"curve-style\": \"straight\",\n label: \"data(label)\",\n \"source-endpoint\": \"data(sourceEndpoint)\",\n \"target-endpoint\": \"data(targetEndpoint)\"\n }\n },\n {\n selector: \"edge.segments\",\n style: {\n \"curve-style\": \"segments\",\n \"segment-weights\": \"0\",\n \"segment-distances\": [0.5],\n // @ts-ignore Incorrect library types\n \"edge-distances\": \"endpoints\",\n \"source-endpoint\": \"data(sourceEndpoint)\",\n \"target-endpoint\": \"data(targetEndpoint)\"\n }\n },\n {\n selector: \"node\",\n style: {\n // @ts-ignore Incorrect library types\n \"compound-sizing-wrt-labels\": \"include\"\n }\n },\n {\n selector: \"node[label]\",\n style: {\n \"text-valign\": \"bottom\",\n \"text-halign\": \"center\",\n \"font-size\": `${db.getConfigField(\"fontSize\")}px`\n }\n },\n {\n selector: \".node-service\",\n style: {\n label: \"data(label)\",\n width: \"data(width)\",\n height: \"data(height)\"\n }\n },\n {\n selector: \".node-junction\",\n style: {\n width: \"data(width)\",\n height: \"data(height)\"\n }\n },\n {\n selector: \".node-group\",\n style: {\n // @ts-ignore Incorrect library types\n padding: `${db.getConfigField(\"padding\")}px`\n }\n }\n ],\n layout: {\n name: \"grid\",\n boundingBox: {\n x1: 0,\n x2: 100,\n y1: 0,\n y2: 100\n }\n }\n });\n renderEl.remove();\n addGroups(groups, cy);\n addServices(services, cy, db);\n addJunctions(junctions, cy, db);\n addEdges(edges, cy);\n const alignmentConstraint = getAlignments(db, spatialMaps, groupAlignments);\n const relativePlacementConstraint = getRelativeConstraints(spatialMaps, db);\n const layout = cy.layout({\n name: \"fcose\",\n quality: \"proof\",\n styleEnabled: false,\n animate: false,\n nodeDimensionsIncludeLabels: false,\n // Adjust the edge parameters if it passes through the border of a group\n // Hacky fix for: https://github.com/iVis-at-Bilkent/cytoscape.js-fcose/issues/67\n idealEdgeLength(edge) {\n const [nodeA, nodeB] = edge.connectedNodes();\n const { parent: parentA } = nodeData(nodeA);\n const { parent: parentB } = nodeData(nodeB);\n const elasticity = parentA === parentB ? 1.5 * db.getConfigField(\"iconSize\") : 0.5 * db.getConfigField(\"iconSize\");\n return elasticity;\n },\n edgeElasticity(edge) {\n const [nodeA, nodeB] = edge.connectedNodes();\n const { parent: parentA } = nodeData(nodeA);\n const { parent: parentB } = nodeData(nodeB);\n const elasticity = parentA === parentB ? 0.45 : 1e-3;\n return elasticity;\n },\n alignmentConstraint,\n relativePlacementConstraint\n });\n layout.one(\"layoutstop\", () => {\n function getSegmentWeights(source, target, pointX, pointY) {\n let W, D;\n const { x: sX, y: sY } = source;\n const { x: tX, y: tY } = target;\n D = (pointY - sY + (sX - pointX) * (sY - tY) / (sX - tX)) / Math.sqrt(1 + Math.pow((sY - tY) / (sX - tX), 2));\n W = Math.sqrt(Math.pow(pointY - sY, 2) + Math.pow(pointX - sX, 2) - Math.pow(D, 2));\n const distAB = Math.sqrt(Math.pow(tX - sX, 2) + Math.pow(tY - sY, 2));\n W = W / distAB;\n let delta1 = (tX - sX) * (pointY - sY) - (tY - sY) * (pointX - sX);\n switch (true) {\n case delta1 >= 0:\n delta1 = 1;\n break;\n case delta1 < 0:\n delta1 = -1;\n break;\n }\n let delta2 = (tX - sX) * (pointX - sX) + (tY - sY) * (pointY - sY);\n switch (true) {\n case delta2 >= 0:\n delta2 = 1;\n break;\n case delta2 < 0:\n delta2 = -1;\n break;\n }\n D = Math.abs(D) * delta1;\n W = W * delta2;\n return {\n distances: D,\n weights: W\n };\n }\n __name(getSegmentWeights, \"getSegmentWeights\");\n cy.startBatch();\n for (const edge of Object.values(cy.edges())) {\n if (edge.data?.()) {\n const { x: sX, y: sY } = edge.source().position();\n const { x: tX, y: tY } = edge.target().position();\n if (sX !== tX && sY !== tY) {\n const sEP = edge.sourceEndpoint();\n const tEP = edge.targetEndpoint();\n const { sourceDir } = edgeData(edge);\n const [pointX, pointY] = isArchitectureDirectionY(sourceDir) ? [sEP.x, tEP.y] : [tEP.x, sEP.y];\n const { weights, distances } = getSegmentWeights(sEP, tEP, pointX, pointY);\n edge.style(\"segment-distances\", distances);\n edge.style(\"segment-weights\", weights);\n }\n }\n }\n cy.endBatch();\n layout.run();\n });\n layout.run();\n cy.ready((e) => {\n log.info(\"Ready\", e);\n resolve(cy);\n });\n });\n}\n__name(layoutArchitecture, \"layoutArchitecture\");\nvar draw = /* @__PURE__ */ __name(async (text, id, _version, diagObj) => {\n const db = diagObj.db;\n const services = db.getServices();\n const junctions = db.getJunctions();\n const groups = db.getGroups();\n const edges = db.getEdges();\n const ds = db.getDataStructures();\n const svg = selectSvgElement(id);\n const edgesElem = svg.append(\"g\");\n edgesElem.attr(\"class\", \"architecture-edges\");\n const servicesElem = svg.append(\"g\");\n servicesElem.attr(\"class\", \"architecture-services\");\n const groupElem = svg.append(\"g\");\n groupElem.attr(\"class\", \"architecture-groups\");\n await drawServices(db, servicesElem, services);\n drawJunctions(db, servicesElem, junctions);\n const cy = await layoutArchitecture(services, junctions, groups, edges, db, ds);\n await drawEdges(edgesElem, cy, db);\n await drawGroups(groupElem, cy, db);\n positionNodes(db, cy);\n setupGraphViewbox(void 0, svg, db.getConfigField(\"padding\"), db.getConfigField(\"useMaxWidth\"));\n}, \"draw\");\nvar renderer = { draw };\n\n// src/diagrams/architecture/architectureDiagram.ts\nvar diagram = {\n parser,\n get db() {\n return new ArchitectureDB();\n },\n renderer,\n styles: architectureStyles_default\n};\nexport {\n diagram\n};\n"], + "mappings": "q6BAAA,IAAAA,GAAAC,G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AClD,IAAMC,EAAYJ,EAAI,OAAO,GAAG,EAChCI,EAAU,KAAK,QAAS,qBAAqB,EAC7C,MAAMpG,GAAa5D,EAAI+J,EAAcjG,CAAQ,EAC7CM,GAAcpE,EAAI+J,EAAc1F,CAAS,EACzC,IAAMtD,EAAK,MAAM4G,GAAmB7D,EAAUO,EAAWU,EAAQE,EAAOjF,EAAI2J,CAAE,EAC9E,MAAM9I,GAAUiJ,EAAW/I,EAAIf,CAAE,EACjC,MAAM6C,GAAWmH,EAAWjJ,EAAIf,CAAE,EAClC6E,GAAc7E,EAAIe,CAAE,EACpBkJ,GAAkB,OAAQL,EAAK5J,EAAG,eAAe,SAAS,EAAGA,EAAG,eAAe,aAAa,CAAC,CAC/F,EAAG,MAAM,EACLkK,GAAW,CAAE,KAAAX,EAAK,EAGlBY,GAAU,CACZ,OAAAhK,GACA,IAAI,IAAK,CACP,OAAO,IAAInD,EACb,EACA,SAAAkN,GACA,OAAQzJ,EACV", + "names": ["require_layout_base", "__commonJSMin", "exports", "module", "root", "factory", "modules", "installedModules", "__webpack_require__", "moduleId", "value", "name", "getter", "object", "property", "LayoutConstants", "LGraphObject", "IGeometry", "IMath", "LEdge", "source", "target", "vEdge", "prop", "node", "graph", "otherEnd", "clipPointCoordinates", "vGraphObject", "Integer", "RectangleD", "RandomSeed", "PointD", "LNode", "gm", "loc", "size", "vNode", "width", "height", "upperLeft", "dimension", "cx", "cy", "x", "y", "dx", "dy", "to", "edgeList", "edge", "self", "other", "neighbors", "withNeighborsList", "childNode", "children", "nodes", "i", "noOfChildren", "randomCenterX", "randomCenterY", "minX", "maxX", "minY", "maxY", "childGraph", "trans", "left", "top", "leftTop", "vLeftTop", "FDLayoutConstants", "pt", "dim", "LGraphManager", "Point", "LinkedList", "LGraph", "parent", "obj2", "vGraph", "obj1", "sourceNode", "targetNode", "newNode", "newEdge", "obj", "edgesToBeRemoved", "s", "index", "sourceIndex", "targetIndex", "nodeTop", "nodeLeft", "margin", "lNode", "recursive", "right", "bottom", "nodeRight", "nodeBottom", "boundingRect", "queue", "visited", "currentNode", "neighborEdges", "currentNeighbor", "childrenOfNode", "neighborEdge", "childrenOfNeighbor", "noOfVisitedInThisGraph", "visitedNode", "layout", "ngraph", "nnode", "newGraph", "parentNode", "sourceGraph", "targetGraph", "lObj", "nodesToBeRemoved", "nodeList", "graphs", "firstNode", "secondNode", "ownerGraph", "sourceAncestorGraph", "targetAncestorGraph", "edges", "firstOwnerGraph", "secondOwnerGraph", "depth", "edgesToRemove", "rectA", "rectB", "overlapAmount", "separationBuffer", "directions", "slope", "moveByY", "moveByX", "result", "p1x", "p1y", "p2x", "p2y", "topLeftAx", "topLeftAy", "topRightAx", "bottomLeftAx", "bottomLeftAy", "bottomRightAx", "halfWidthA", "halfHeightA", "topLeftBx", "topLeftBy", "topRightBx", "bottomLeftBx", "bottomLeftBy", "bottomRightBx", "halfWidthB", "halfHeightB", "clipPointAFound", "clipPointBFound", "slopeA", "slopeB", "slopePrime", "cardinalDirectionA", "cardinalDirectionB", "tempPointAx", "tempPointAy", "tempPointBx", "tempPointBy", "line", "s1", "s2", "f1", "f2", "x1", "y1", "x2", "y2", "x3", "y3", "x4", "y4", "a1", "a2", "b1", "b2", "c1", "c2", "denom", "Cx", "Cy", "Nx", "Ny", "C_angle", "p1", "p2", "p3", "p4", "a", "b", "c", "d", "p", "q", "r", "det", "lambda", "gamma", "Ex", "Ey", "Lx", "Ly", "disc", "t1", "t2", "intersections", "_createClass", "defineProperties", "props", "descriptor", "Constructor", "protoProps", "staticProps", "_classCallCheck", "instance", "nodeFrom", "add", "prev", "next", "list", "_remove", "vals", "_this", "v", "val", "otherNode", "current", "_typeof", "UniqueIDGeneretor", "id", "arg", "type", "_toConsumableArray", "arr", "arr2", "Transform", "Emitter", "Layout", "isRemoteUse", "isLayoutSuccessfull", "allEdges", "newLeftTop", "flatForest", "isForest", "allNodes", "isFlat", "toBeVisited", "parents", "unProcessedNodes", "temp", "dummyNodes", "dummyNode", "dummyEdge", "k", "lEdge", "path", "ebp", "sliderValue", "defaultValue", "minDiv", "maxMul", "minValue", "maxValue", "removedNodes", "remainingDegrees", "foundCenter", "centerNode", "degree", "tempList", "tempList2", "neighbours", "neighbour", "otherDegree", "newDegree", "wox", "woy", "wex", "wey", "dox", "doy", "dex", "dey", "xDevice", "worldExtX", "yDevice", "worldExtY", "xWorld", "deviceExtX", "yWorld", "deviceExtY", "inPoint", "outPoint", "FDLayout", "originalIdealLength", "lcaDepth", "sizeOfSourceInLca", "sizeOfTargetInLca", "lEdges", "gridUpdateAllowed", "forceToNodeSurroundingUpdate", "j", "nodeA", "nodeB", "lNodes", "processedNodeSet", "idealLength", "length", "springForce", "springForceX", "springForceY", "clipPoints", "distanceX", "distanceY", "distanceSquared", "distance", "repulsionForce", "repulsionForceX", "repulsionForceY", "childrenConstant", "ownerCenterX", "ownerCenterY", "absDistanceX", "absDistanceY", "estimatedSize", "converged", "oscilating", "sizeX", "sizeY", "grid", "startX", "finishX", "startY", "finishY", "surrounding", "FDLayoutEdge", "FDLayoutNode", "_startX", "_finishX", "_startY", "_finishY", "DimensionD", "HashMap", "key", "theId", "HashSet", "keys", "Matrix", "array1", "array2", "array", "constant", "product", "magnitude", "sum", "_i", "C", "INV", "temp1", "temp2", "_i2", "_sum", "_j", "_i3", "_sum2", "_j2", "Quicksort", "A", "compareFunction", "SVD", "nu", "dims", "allocate", "work", "wantu", "wantv", "nct", "nrt", "lhs", "rhs", "t", "_i4", "_i5", "_i6", "_i7", "_i8", "_t", "_i9", "_i10", "_j3", "_i11", "_k", "_j4", "_t2", "_i12", "_i13", "_i14", "_i15", "_i16", "_k2", "_j5", "_t3", "_i17", "_i18", "_i19", "pp", "iter", "eps", "tiny", "_k3", "kase", "ks", "_t4", "f", "_j6", "_t5", "cs", "sn", "_i20", "_f", "_j7", "_t6", "_cs", "_sn", "_i21", "scale", "sp", "spm1", "epm1", "sk", "ek", "shift", "_f2", "g", "_j8", "_t7", "_cs2", "_sn2", "_i22", "_i23", "_i24", "_t8", "_i25", "_i26", "NeedlemanWunsch", "sequence1", "sequence2", "match_score", "mismatch_penalty", "gap_penalty", "diag", "up", "maxOf", "indices", "inProcessAlignments", "indexes", "layoutBase", "event", "callback", "l", "data", "require_cose_base", "__commonJSMin", "exports", "module", "root", "factory", "__WEBPACK_EXTERNAL_MODULE__551__", "__webpack_modules__", "__unused_webpack_exports", "__webpack_require__", "coseBase", "FDLayoutConstants", "CoSEConstants", "prop", "FDLayoutEdge", "CoSEEdge", "source", "target", "vEdge", "LGraph", "CoSEGraph", "parent", "graphMgr", "vGraph", "LGraphManager", "CoSEGraphManager", "layout", "FDLayout", "CoSENode", "ConstraintHandler", "LayoutConstants", "Point", "PointD", "DimensionD", "Layout", "Integer", "IGeometry", "Transform", "LinkedList", "CoSELayout", "gm", "vNode", "createBendsAsNeeded", "allNodes", "intersection", "x", "forest", "gridUpdateAllowed", "forceToNodeSurroundingUpdate", "pData", "i", "rect", "id", "layoutEnded", "lNodes", "node", "self", "calculateCompoundWeight", "compoundNode", "nodes", "fixedNodeWeight", "nodeData", "nodeToDummyForVerticalAlignment", "nodeToDummyForHorizontalAlignment", "nodeId", "verticalAlignment", "horizontalAlignment", "array", "j", "constraint", "nodeIdLeft", "nodeIdRight", "nodeIdTop", "nodeIdBottom", "subGraphOnHorizontal", "subGraphOnVertical", "left", "right", "top", "bottom", "constructComponents", "graph", "fixedNodes", "components", "isFixed", "queue", "visited", "count", "value", "key", "currentNode", "neighbors", "neighbor", "resultOnHorizontal", "resultOnVertical", "fixedNode", "allVerticalAlignments", "totalDisplacementX", "averageDisplacementX", "allHorizontalAlignments", "totalDisplacementY", "averageDisplacementY", "displacement", "diff", "component", "sum", "actualNodes", "averageDisplacement", "nodeList", "graphs", "size", "edges", "edge", "edgeList", "k", "multiEdge", "currentStartingPoint", "numberOfColumns", "height", "currentY", "currentX", "point", "tree", "centerNode", "startingPoint", "radialSep", "bounds", "transform", "bottomRight", "parentOfNode", "startAngle", "endAngle", "distance", "radialSeparation", "halfInterval", "nodeAngle", "teta", "cos_teta", "x_", "y_", "neighborEdges", "childCount", "branchCount", "incEdgesCount", "startIndex", "temp", "index", "stepAngle", "currentNeighbor", "childStartAngle", "childEndAngle", "maxDiagonal", "diagonal", "tempMemberGroups", "zeroDegree", "p_id", "dummyCompoundId", "dummyCompound", "dummyParentGraph", "parentGraph", "childGraphMap", "idToNode", "tiledZeroDegreePack", "width", "lCompoundNode", "horizontalMargin", "verticalMargin", "labelMarginLeft", "labelMarginTop", "tiledPack", "childGraph", "children", "theChild", "degree", "child", "organization", "y", "compoundHorizontalMargin", "compoundVerticalMargin", "compoundLabelMarginLeft", "compoundLabelMarginTop", "row", "maxHeight", "lnode", "minWidth", "horizontalOrg", "verticalOrg", "horizontalRatio", "verticalRatio", "bestOrg", "ratio", "members", "favorHorizontalDim", "verticalPadding", "horizontalPadding", "membersSize", "totalWidth", "totalHeight", "maxWidth", "averageWidth", "averageHeight", "delta", "horizontalCountDouble", "horizontalCount", "idealWidth", "tilingCompareBy", "getNodeArea", "n", "areaCompareFcn", "n1", "n2", "cmpBy", "sumCenterX", "sumCenterY", "lNode", "rowIndex", "minCompoundSize", "secondDimension", "w", "h", "extraHeight", "r", "min", "max", "extraWidth", "lastRowIndex", "lastRowWidth", "sri", "hDiff", "add_to_row_ratio", "add_new_row_ratio", "longest", "last", "prevTotal", "finalTotal", "prunedNodesAll", "containsLeaf", "prunedNodesInStepTemp", "otherEnd", "relativePosition", "prunedNodesInStep", "lengthOfPrunedNodesInStep", "gridForPrunedNode", "nodeToConnect", "prunedNode", "startGridX", "finishGridX", "startGridY", "finishGridY", "upNodeCount", "downNodeCount", "rightNodeCount", "leftNodeCount", "controlRegions", "minCount", "minIndex", "random", "FDLayoutNode", "IMath", "loc", "dX", "dY", "pred1", "next", "processed", "_toConsumableArray", "arr", "arr2", "Matrix", "SVD", "constraints", "idToNodeMap", "nodeIndexes", "xCoords", "yCoords", "calculatePositionDiff", "pos1", "pos2", "calculateAvgPosition", "nodeIdSet", "xPosSum", "yPosSum", "findAppropriatePositionForRelativePlacement", "direction", "dummyPositions", "componentSources", "setUnion", "setA", "setB", "union", "_iteratorNormalCompletion", "_didIteratorError", "_iteratorError", "_iterator", "_step", "elem", "err", "inDegrees", "adjacent", "positionMap", "pastMap", "fixedIds", "position", "fixedId", "_position", "_loop", "fixedPosition", "sinkNodes", "_components", "isFixedComponent", "_iteratorNormalCompletion2", "_didIteratorError2", "_iteratorError2", "_iterator2", "_step2", "isExist", "existAt", "ele", "minBefore", "minAfter", "maxBefore", "maxAfter", "_iteratorNormalCompletion3", "_didIteratorError3", "_iteratorError3", "_iterator3", "_step3", "posBefore", "posAfter", "_iteratorNormalCompletion4", "_didIteratorError4", "_iteratorError4", "_iterator4", "_step4", "_nodeId", "applyReflectionForRelativePlacement", "relativePlacementConstraints", "reflectOnY", "notReflectOnY", "reflectOnX", "notReflectOnX", "_i", "_i2", "_i3", "findComponents", "_currentNode", "dagToUndirected", "dag", "undirected", "dagToReversed", "reversed", "targetMatrix", "sourceMatrix", "standardTransformation", "reflectionType", "dagUndirected", "verticalAlign", "_loop2", "_i4", "alignmentSet", "xPos", "horizontalAlign", "_loop3", "_i5", "yPos", "largestComponentSize", "largestComponentIndex", "_i6", "constraintsInlargestComponent", "positionMapHorizontal", "positionMapVertical", "transformationMatrix", "targetMatrixTranspose", "sourceMatrixTranspose", "_i7", "tempMatrix", "SVDResult", "_i8", "temp1", "temp2", "temp3", "translationAmount", "posInTheory", "posDesired", "posDiff", "xAlign", "_loop4", "_i9", "yAlign", "_loop5", "_i10", "dummyToNodeForVerticalAlignment", "dummyToNodeForHorizontalAlignment", "dummyPositionsForVerticalAlignment", "dummyPositionsForHorizontalAlignment", "fixedNodesOnHorizontal", "fixedNodesOnVertical", "_loop6", "_i11", "_loop7", "_i12", "dagOnHorizontal", "dagOnVertical", "_loop8", "sourceId", "targetNode", "_iteratorNormalCompletion5", "_didIteratorError5", "_iteratorError5", "_iterator5", "_step5", "undirectedOnHorizontal", "undirectedOnVertical", "componentsOnHorizontal", "componentsOnVertical", "reversedDagOnHorizontal", "reversedDagOnVertical", "componentSourcesOnHorizontal", "componentSourcesOnVertical", "_loop9", "_iteratorNormalCompletion6", "_didIteratorError6", "_iteratorError6", "_iterator6", "_step6", "_loop10", "_iteratorNormalCompletion7", "_didIteratorError7", "_iteratorError7", "_iterator7", "_step7", "_i13", "_node", "__webpack_module_cache__", "moduleId", "cachedModule", "__webpack_exports__", "require_cytoscape_fcose", "__commonJSMin", "exports", "module", "root", "factory", "__WEBPACK_EXTERNAL_MODULE__140__", "__webpack_modules__", "tgt", "_len", "srcs", "_key", "src", "k", "__unused_webpack_exports", "__webpack_require__", "_slicedToArray", "sliceIterator", "arr", "i", "_arr", "_n", "_d", "_e", "_i", "_s", "err", "LinkedList", "auxiliary", "nodes", "nodesMap", "roots", "ele", "parent", "cy", "eles", "topMostNodes", "dummyNodes", "queue", "visited", "visitedTopMostNodes", "currentNeighbor", "minDegreeNode", "minDegree", "isConnected", "count", "nodesConnectedToDummy", "components", "_loop", "cmpt", "currentNode", "childrenOfCurrentNode", "node", "_loop2", "neighborNodes", "neighborNode", "childrenOfNeighbor", "e", "temp", "originalCenter", "componentResult", "options", "minXCoord", "maxXCoord", "minYCoord", "maxYCoord", "_iteratorNormalCompletion", "_didIteratorError", "_iteratorError", "_iterator", "_step", "_ref", "_ref2", "key", "value", "cyNode", "nodeBB", "leftX", "rightX", "topY", "bottomY", "diffOnX", "diffOnY", "x", "y", "item", "_diffOnX", "_diffOnY", "parentNode", "xCoords", "yCoords", "nodeIndexes", "left", "right", "top", "bottom", "nodeLeft", "nodeRight", "nodeTop", "nodeBottom", "s", "boundingBox", "parentsWithoutChildren", "check", "child", "aux", "CoSELayout", "CoSENode", "PointD", "DimensionD", "LayoutConstants", "FDLayoutConstants", "CoSEConstants", "coseLayout", "spectralResult", "edges", "idToLNode", "isFn", "fn", "optFn", "opt", "processChildrenList", "children", "layout", "size", "theChild", "children_of_children", "theNode", "dimensions", "parentInfo", "theNewGraph", "processEdges", "gm", "idealLengthTotal", "edgeCount", "edge", "sourceNode", "targetNode", "e1", "processConstraints", "_createClass", "defineProperties", "target", "props", "descriptor", "Constructor", "protoProps", "staticProps", "_classCallCheck", "instance", "assign", "_require", "spectralLayout", "_require2", "defaults", "Layout", "coseResult", "componentCenters", "constraintExist", "layUtil", "packingEnabled", "component", "toBeTiledNodes", "_xCoords", "_yCoords", "tempSpectralResult", "indexesToBeDeleted", "index", "_boundingBox", "componentsEvaluated", "subgraphs", "hiddenEles", "subgraph", "nodeIndex", "source", "sourceNodeIndex", "targetNodeIndex", "sourceCenter", "targetCenter", "_parentInfo", "shiftResult", "result", "newXCoords", "newYCoords", "_count", "nodeRectangle", "getPositions", "pos", "theId", "_pos", "_hiddenEles", "Matrix", "SVD", "parentNodes", "parentChildMap", "allNodesNeighborhood", "samplesColumn", "minDistancesColumn", "C", "PHI", "INV", "firstSample", "nodeSize", "infinity", "small", "piTol", "samplingType", "nodeSeparation", "sampleSize", "randomSampleCR", "sample", "flag", "BFS", "pivot", "samplingMethod", "path", "front", "back", "current", "distance", "max_dist", "max_ind", "neighbors", "_i2", "_i3", "allBFS", "_i4", "_i5", "_i6", "j", "_i7", "_i8", "_j", "SVDResult", "a_q", "a_u", "a_v", "max_s", "a_Sig", "powerIteration", "theta1", "theta2", "Y1", "Y2", "V1", "V2", "previous", "_i9", "_i10", "_i11", "_i12", "_i13", "min", "ele2", "eleIndex", "disconnectedId", "id", "_iteratorNormalCompletion2", "_didIteratorError2", "_iteratorError2", "_iterator2", "_step2", "_i14", "_i15", "iterator", "firstNode", "firstNodePos", "firstNodeWidth", "secondNode", "secondNodeWidth", "impl", "register", "cytoscape", "__webpack_module_cache__", "moduleId", "cachedModule", "__webpack_exports__", "import_cytoscape_fcose", "ArchitectureDirectionName", "ArchitectureDirectionArrow", "__name", "scale", "ArchitectureDirectionArrowShift", "orig", "arrowSize", "_arrowSize", "getOppositeArchitectureDirection", "x", "isArchitectureDirectionX", "isArchitectureDirection", "temp", "isArchitectureDirectionY", "isArchitectureDirectionXY", "a", "b", "aX_bY", "aY_bX", "isArchitecturePairXY", "pair", "lhs", "rhs", "isValidArchitectureDirectionPair", "getArchitectureDirectionPair", "sourceDir", "targetDir", "shiftPositionByArchitectureDirectionPair", "y", "getArchitectureDirectionXYFactors", "getArchitectureDirectionAlignment", "isArchitectureService", "isArchitectureJunction", "edgeData", "edge", "nodeData", "node", "DEFAULT_ARCHITECTURE_CONFIG", "defaultConfig_default", "ArchitectureDB", "setAccTitle", "getAccTitle", "setDiagramTitle", "getDiagramTitle", "getAccDescription", "setAccDescription", "clear", "id", "icon", "parent", "title", "iconText", "lhsId", "rhsId", "lhsDir", "rhsDir", "lhsInto", "rhsInto", "lhsGroup", "rhsGroup", "lhsGroupId", "rhsGroupId", "groupAlignments", "adjList", "prevOuter", "service", "prevInner", "alignment", "firstId", "visited", "notVisited", "prev", "BFS", "startingId", "spatialMap", "queue", "adj", "posX", "posY", "dir", "spatialMaps", "element", "cleanAndMerge", "getConfig", "field", "populateDb", "ast", "db", "populateCommonDb", "group", "parser", "input", "parse", "log", "getStyles", "options", "architectureStyles_default", "wrapIcon", "architectureIcons", "unknownIcon", "drawEdges", "edgesEl", "cy", "padding", "iconSize", "halfIconSize", "halfArrowSize", "source", "sourceArrow", "sourceGroup", "target", "targetArrow", "targetGroup", "label", "startX", "startY", "midX", "midY", "endX", "endY", "groupEdgeShift", "g", "getEdgeId", "xShift", "yShift", "axis", "width", "textElem", "createText", "getConfig2", "bboxOrig", "bboxNew", "drawGroups", "groupsEl", "groupIconSize", "fontSize", "data", "h", "w", "x1", "y1", "groupsNode", "groupLabelContainer", "shiftedX1", "shiftedY1", "bkgElem", "getIconSVG", "drawServices", "elem", "services", "config", "serviceElem", "divElem", "sanitizeText", "height", "drawJunctions", "junctions", "junction", "junctionElem", "registerIconPacks", "cytoscape", "fcose", "addServices", "addJunctions", "positionNodes", "addGroups", "groups", "addEdges", "edges", "parsedEdge", "edgeType", "getAlignments", "flattenAlignments", "alignmentObj", "alignmentDir", "alignments2", "cnt", "arr", "i", "j", "aGroupId", "aNodeIds", "bGroupId", "bNodeIds", "keyA", "keyB", "alignments", "horizontalAlignments", "verticalAlignments", "nodeGroup", "horizontal", "vertical", "prevHoriz", "prevVert", "horiz", "vert", "getRelativeConstraints", "relativeConstraints", "posToStr", "pos", "strToPos", "p", "invSpatialMap", "directions", "curr", "currId", "currPos", "shift", "newPos", "newId", "layoutArchitecture", "resolve", "renderEl", "select_default", "alignmentConstraint", "relativePlacementConstraint", "layout", "nodeA", "nodeB", "parentA", "parentB", "getSegmentWeights", "pointX", "pointY", "W", "D", "sX", "sY", "tX", "tY", "distAB", "delta1", "delta2", "sEP", "tEP", "weights", "distances", "e", "draw", "text", "_version", "diagObj", "ds", "svg", "selectSvgElement", "edgesElem", "servicesElem", "groupElem", "setupGraphViewbox", "renderer", "diagram"] +} diff --git a/docs/website/public/blockDiagram-VD42YOAC-VWWETFZB.min.js b/docs/website/public/blockDiagram-VD42YOAC-VWWETFZB.min.js new file mode 100644 index 000000000..e87114362 --- /dev/null +++ b/docs/website/public/blockDiagram-VD42YOAC-VWWETFZB.min.js @@ -0,0 +1,123 @@ +import{a as Vt}from"./chunk-PPPUQLJ3.min.js";import{a as jt}from"./chunk-VUATWGGE.min.js";import{c as Yt}from"./chunk-77XMBG7U.min.js";import{a as Ht}from"./chunk-ANLQN3B7.min.js";import{f as Xt,g as mt}from"./chunk-XCAVDAZC.min.js";import{e as Ut}from"./chunk-R5JLOOQ4.min.js";import"./chunk-PTL4EUOE.min.js";import{d as Kt,m as tt,o as lt}from"./chunk-QZZKR5JD.min.js";import"./chunk-CM5D5KZN.min.js";import{D as nt,E as zt,F as X,K as At,L as Mt,P as Ft,W as I,a as Ot,b as Rt,y as $}from"./chunk-3EE2TK35.min.js";import"./chunk-E5F23VE2.min.js";import{J as Wt,N as Pt,b as d,d as w,j as N}from"./chunk-6TVUEPFY.min.js";import"./chunk-OSRY5VT3.min.js";var wt=(function(){var e=d(function(D,x,g,f){for(g=g||{},f=D.length;f--;g[D[f]]=x);return g},"o"),t=[1,15],a=[1,7],i=[1,13],l=[1,14],s=[1,19],r=[1,16],n=[1,17],c=[1,18],u=[8,30],o=[8,10,21,28,29,30,31,39,43,46],b=[1,23],m=[1,24],y=[8,10,15,16,21,28,29,30,31,39,43,46],L=[8,10,15,16,21,27,28,29,30,31,39,43,46],E=[1,49],S={trace:d(function(){},"trace"),yy:{},symbols_:{error:2,spaceLines:3,SPACELINE:4,NL:5,separator:6,SPACE:7,EOF:8,start:9,BLOCK_DIAGRAM_KEY:10,document:11,stop:12,statement:13,link:14,LINK:15,START_LINK:16,LINK_LABEL:17,STR:18,nodeStatement:19,columnsStatement:20,SPACE_BLOCK:21,blockStatement:22,classDefStatement:23,cssClassStatement:24,styleStatement:25,node:26,SIZE:27,COLUMNS:28,"id-block":29,end:30,NODE_ID:31,nodeShapeNLabel:32,dirList:33,DIR:34,NODE_DSTART:35,NODE_DEND:36,BLOCK_ARROW_START:37,BLOCK_ARROW_END:38,classDef:39,CLASSDEF_ID:40,CLASSDEF_STYLEOPTS:41,DEFAULT:42,class:43,CLASSENTITY_IDS:44,STYLECLASS:45,style:46,STYLE_ENTITY_IDS:47,STYLE_DEFINITION_DATA:48,$accept:0,$end:1},terminals_:{2:"error",4:"SPACELINE",5:"NL",7:"SPACE",8:"EOF",10:"BLOCK_DIAGRAM_KEY",15:"LINK",16:"START_LINK",17:"LINK_LABEL",18:"STR",21:"SPACE_BLOCK",27:"SIZE",28:"COLUMNS",29:"id-block",30:"end",31:"NODE_ID",34:"DIR",35:"NODE_DSTART",36:"NODE_DEND",37:"BLOCK_ARROW_START",38:"BLOCK_ARROW_END",39:"classDef",40:"CLASSDEF_ID",41:"CLASSDEF_STYLEOPTS",42:"DEFAULT",43:"class",44:"CLASSENTITY_IDS",45:"STYLECLASS",46:"style",47:"STYLE_ENTITY_IDS",48:"STYLE_DEFINITION_DATA"},productions_:[0,[3,1],[3,2],[3,2],[6,1],[6,1],[6,1],[9,3],[12,1],[12,1],[12,2],[12,2],[11,1],[11,2],[14,1],[14,4],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[19,3],[19,2],[19,1],[20,1],[22,4],[22,3],[26,1],[26,2],[33,1],[33,2],[32,3],[32,4],[23,3],[23,3],[24,3],[25,3]],performAction:d(function(x,g,f,k,v,h,W){var p=h.length-1;switch(v){case 4:k.getLogger().debug("Rule: separator (NL) ");break;case 5:k.getLogger().debug("Rule: separator (Space) ");break;case 6:k.getLogger().debug("Rule: separator (EOF) ");break;case 7:k.getLogger().debug("Rule: hierarchy: ",h[p-1]),k.setHierarchy(h[p-1]);break;case 8:k.getLogger().debug("Stop NL ");break;case 9:k.getLogger().debug("Stop EOF ");break;case 10:k.getLogger().debug("Stop NL2 ");break;case 11:k.getLogger().debug("Stop EOF2 ");break;case 12:k.getLogger().debug("Rule: statement: ",h[p]),typeof h[p].length=="number"?this.$=h[p]:this.$=[h[p]];break;case 13:k.getLogger().debug("Rule: statement #2: ",h[p-1]),this.$=[h[p-1]].concat(h[p]);break;case 14:k.getLogger().debug("Rule: link: ",h[p],x),this.$={edgeTypeStr:h[p],label:""};break;case 15:k.getLogger().debug("Rule: LABEL link: ",h[p-3],h[p-1],h[p]),this.$={edgeTypeStr:h[p],label:h[p-1]};break;case 18:let R=parseInt(h[p]),G=k.generateId();this.$={id:G,type:"space",label:"",width:R,children:[]};break;case 23:k.getLogger().debug("Rule: (nodeStatement link node) ",h[p-2],h[p-1],h[p]," typestr: ",h[p-1].edgeTypeStr);let V=k.edgeStrToEdgeData(h[p-1].edgeTypeStr);this.$=[{id:h[p-2].id,label:h[p-2].label,type:h[p-2].type,directions:h[p-2].directions},{id:h[p-2].id+"-"+h[p].id,start:h[p-2].id,end:h[p].id,label:h[p-1].label,type:"edge",directions:h[p].directions,arrowTypeEnd:V,arrowTypeStart:"arrow_open"},{id:h[p].id,label:h[p].label,type:k.typeStr2Type(h[p].typeStr),directions:h[p].directions}];break;case 24:k.getLogger().debug("Rule: nodeStatement (abc88 node size) ",h[p-1],h[p]),this.$={id:h[p-1].id,label:h[p-1].label,type:k.typeStr2Type(h[p-1].typeStr),directions:h[p-1].directions,widthInColumns:parseInt(h[p],10)};break;case 25:k.getLogger().debug("Rule: nodeStatement (node) ",h[p]),this.$={id:h[p].id,label:h[p].label,type:k.typeStr2Type(h[p].typeStr),directions:h[p].directions,widthInColumns:1};break;case 26:k.getLogger().debug("APA123",this?this:"na"),k.getLogger().debug("COLUMNS: ",h[p]),this.$={type:"column-setting",columns:h[p]==="auto"?-1:parseInt(h[p])};break;case 27:k.getLogger().debug("Rule: id-block statement : ",h[p-2],h[p-1]);let Bt=k.generateId();this.$={...h[p-2],type:"composite",children:h[p-1]};break;case 28:k.getLogger().debug("Rule: blockStatement : ",h[p-2],h[p-1],h[p]);let at=k.generateId();this.$={id:at,type:"composite",label:"",children:h[p-1]};break;case 29:k.getLogger().debug("Rule: node (NODE_ID separator): ",h[p]),this.$={id:h[p]};break;case 30:k.getLogger().debug("Rule: node (NODE_ID nodeShapeNLabel separator): ",h[p-1],h[p]),this.$={id:h[p-1],label:h[p].label,typeStr:h[p].typeStr,directions:h[p].directions};break;case 31:k.getLogger().debug("Rule: dirList: ",h[p]),this.$=[h[p]];break;case 32:k.getLogger().debug("Rule: dirList: ",h[p-1],h[p]),this.$=[h[p-1]].concat(h[p]);break;case 33:k.getLogger().debug("Rule: nodeShapeNLabel: ",h[p-2],h[p-1],h[p]),this.$={typeStr:h[p-2]+h[p],label:h[p-1]};break;case 34:k.getLogger().debug("Rule: BLOCK_ARROW nodeShapeNLabel: ",h[p-3],h[p-2]," #3:",h[p-1],h[p]),this.$={typeStr:h[p-3]+h[p],label:h[p-2],directions:h[p-1]};break;case 35:case 36:this.$={type:"classDef",id:h[p-1].trim(),css:h[p].trim()};break;case 37:this.$={type:"applyClass",id:h[p-1].trim(),styleClass:h[p].trim()};break;case 38:this.$={type:"applyStyles",id:h[p-1].trim(),stylesStr:h[p].trim()};break}},"anonymous"),table:[{9:1,10:[1,2]},{1:[3]},{10:t,11:3,13:4,19:5,20:6,21:a,22:8,23:9,24:10,25:11,26:12,28:i,29:l,31:s,39:r,43:n,46:c},{8:[1,20]},e(u,[2,12],{13:4,19:5,20:6,22:8,23:9,24:10,25:11,26:12,11:21,10:t,21:a,28:i,29:l,31:s,39:r,43:n,46:c}),e(o,[2,16],{14:22,15:b,16:m}),e(o,[2,17]),e(o,[2,18]),e(o,[2,19]),e(o,[2,20]),e(o,[2,21]),e(o,[2,22]),e(y,[2,25],{27:[1,25]}),e(o,[2,26]),{19:26,26:12,31:s},{10:t,11:27,13:4,19:5,20:6,21:a,22:8,23:9,24:10,25:11,26:12,28:i,29:l,31:s,39:r,43:n,46:c},{40:[1,28],42:[1,29]},{44:[1,30]},{47:[1,31]},e(L,[2,29],{32:32,35:[1,33],37:[1,34]}),{1:[2,7]},e(u,[2,13]),{26:35,31:s},{31:[2,14]},{17:[1,36]},e(y,[2,24]),{10:t,11:37,13:4,14:22,15:b,16:m,19:5,20:6,21:a,22:8,23:9,24:10,25:11,26:12,28:i,29:l,31:s,39:r,43:n,46:c},{30:[1,38]},{41:[1,39]},{41:[1,40]},{45:[1,41]},{48:[1,42]},e(L,[2,30]),{18:[1,43]},{18:[1,44]},e(y,[2,23]),{18:[1,45]},{30:[1,46]},e(o,[2,28]),e(o,[2,35]),e(o,[2,36]),e(o,[2,37]),e(o,[2,38]),{36:[1,47]},{33:48,34:E},{15:[1,50]},e(o,[2,27]),e(L,[2,33]),{38:[1,51]},{33:52,34:E,38:[2,31]},{31:[2,15]},e(L,[2,34]),{38:[2,32]}],defaultActions:{20:[2,7],23:[2,14],50:[2,15],52:[2,32]},parseError:d(function(x,g){if(g.recoverable)this.trace(x);else{var f=new Error(x);throw f.hash=g,f}},"parseError"),parse:d(function(x){var g=this,f=[0],k=[],v=[null],h=[],W=this.table,p="",R=0,G=0,V=0,Bt=2,at=1,Se=h.slice.call(arguments,1),z=Object.create(this.lexer),q={yy:{}};for(var pt in this.yy)Object.prototype.hasOwnProperty.call(this.yy,pt)&&(q.yy[pt]=this.yy[pt]);z.setInput(x,q.yy),q.yy.lexer=z,q.yy.parser=this,typeof z.yylloc>"u"&&(z.yylloc={});var ft=z.yylloc;h.push(ft);var ve=z.options&&z.options.ranges;typeof q.yy.parseError=="function"?this.parseError=q.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function Ee(P){f.length=f.length-2*P,v.length=v.length-P,h.length=h.length-P}d(Ee,"popStack");function Ct(){var P;return P=k.pop()||z.lex()||at,typeof P!="number"&&(P instanceof Array&&(k=P,P=k.pop()),P=g.symbols_[P]||P),P}d(Ct,"lex");for(var F,bt,J,H,qr,xt,Q={},st,Z,It,it;;){if(J=f[f.length-1],this.defaultActions[J]?H=this.defaultActions[J]:((F===null||typeof F>"u")&&(F=Ct()),H=W[J]&&W[J][F]),typeof H>"u"||!H.length||!H[0]){var yt="";it=[];for(st in W[J])this.terminals_[st]&&st>Bt&&it.push("'"+this.terminals_[st]+"'");z.showPosition?yt="Parse error on line "+(R+1)+`: +`+z.showPosition()+` +Expecting `+it.join(", ")+", got '"+(this.terminals_[F]||F)+"'":yt="Parse error on line "+(R+1)+": Unexpected "+(F==at?"end of input":"'"+(this.terminals_[F]||F)+"'"),this.parseError(yt,{text:z.match,token:this.terminals_[F]||F,line:z.yylineno,loc:ft,expected:it})}if(H[0]instanceof Array&&H.length>1)throw new Error("Parse Error: multiple actions possible at state: "+J+", token: "+F);switch(H[0]){case 1:f.push(F),v.push(z.yytext),h.push(z.yylloc),f.push(H[1]),F=null,bt?(F=bt,bt=null):(G=z.yyleng,p=z.yytext,R=z.yylineno,ft=z.yylloc,V>0&&V--);break;case 2:if(Z=this.productions_[H[1]][1],Q.$=v[v.length-Z],Q._$={first_line:h[h.length-(Z||1)].first_line,last_line:h[h.length-1].last_line,first_column:h[h.length-(Z||1)].first_column,last_column:h[h.length-1].last_column},ve&&(Q._$.range=[h[h.length-(Z||1)].range[0],h[h.length-1].range[1]]),xt=this.performAction.apply(Q,[p,G,R,q.yy,H[1],v,h].concat(Se)),typeof xt<"u")return xt;Z&&(f=f.slice(0,-1*Z*2),v=v.slice(0,-1*Z),h=h.slice(0,-1*Z)),f.push(this.productions_[H[1]][0]),v.push(Q.$),h.push(Q._$),It=W[f[f.length-2]][f[f.length-1]],f.push(It);break;case 3:return!0}}return!0},"parse")},C=(function(){var D={EOF:1,parseError:d(function(g,f){if(this.yy.parser)this.yy.parser.parseError(g,f);else throw new Error(g)},"parseError"),setInput:d(function(x,g){return this.yy=g||this.yy||{},this._input=x,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:d(function(){var x=this._input[0];this.yytext+=x,this.yyleng++,this.offset++,this.match+=x,this.matched+=x;var g=x.match(/(?:\r\n?|\n).*/g);return g?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),x},"input"),unput:d(function(x){var g=x.length,f=x.split(/(?:\r\n?|\n)/g);this._input=x+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-g),this.offset-=g;var k=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),f.length-1&&(this.yylineno-=f.length-1);var v=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:f?(f.length===k.length?this.yylloc.first_column:0)+k[k.length-f.length].length-f[0].length:this.yylloc.first_column-g},this.options.ranges&&(this.yylloc.range=[v[0],v[0]+this.yyleng-g]),this.yyleng=this.yytext.length,this},"unput"),more:d(function(){return this._more=!0,this},"more"),reject:d(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:d(function(x){this.unput(this.match.slice(x))},"less"),pastInput:d(function(){var x=this.matched.substr(0,this.matched.length-this.match.length);return(x.length>20?"...":"")+x.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:d(function(){var x=this.match;return x.length<20&&(x+=this._input.substr(0,20-x.length)),(x.substr(0,20)+(x.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:d(function(){var x=this.pastInput(),g=new Array(x.length+1).join("-");return x+this.upcomingInput()+` +`+g+"^"},"showPosition"),test_match:d(function(x,g){var f,k,v;if(this.options.backtrack_lexer&&(v={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(v.yylloc.range=this.yylloc.range.slice(0))),k=x[0].match(/(?:\r\n?|\n).*/g),k&&(this.yylineno+=k.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:k?k[k.length-1].length-k[k.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+x[0].length},this.yytext+=x[0],this.match+=x[0],this.matches=x,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(x[0].length),this.matched+=x[0],f=this.performAction.call(this,this.yy,this,g,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),f)return f;if(this._backtrack){for(var h in v)this[h]=v[h];return!1}return!1},"test_match"),next:d(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var x,g,f,k;this._more||(this.yytext="",this.match="");for(var v=this._currentRules(),h=0;hg[0].length)){if(g=f,k=h,this.options.backtrack_lexer){if(x=this.test_match(f,v[h]),x!==!1)return x;if(this._backtrack){g=!1;continue}else return!1}else if(!this.options.flex)break}return g?(x=this.test_match(g,v[k]),x!==!1?x:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:d(function(){var g=this.next();return g||this.lex()},"lex"),begin:d(function(g){this.conditionStack.push(g)},"begin"),popState:d(function(){var g=this.conditionStack.length-1;return g>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:d(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:d(function(g){return g=this.conditionStack.length-1-Math.abs(g||0),g>=0?this.conditionStack[g]:"INITIAL"},"topState"),pushState:d(function(g){this.begin(g)},"pushState"),stateStackSize:d(function(){return this.conditionStack.length},"stateStackSize"),options:{},performAction:d(function(g,f,k,v){var h=v;switch(k){case 0:return g.getLogger().debug("Found block-beta"),10;break;case 1:return g.getLogger().debug("Found id-block"),29;break;case 2:return g.getLogger().debug("Found block"),10;break;case 3:g.getLogger().debug(".",f.yytext);break;case 4:g.getLogger().debug("_",f.yytext);break;case 5:return 5;case 6:return f.yytext=-1,28;break;case 7:return f.yytext=f.yytext.replace(/columns\s+/,""),g.getLogger().debug("COLUMNS (LEX)",f.yytext),28;break;case 8:this.pushState("md_string");break;case 9:return"MD_STR";case 10:this.popState();break;case 11:this.pushState("string");break;case 12:g.getLogger().debug("LEX: POPPING STR:",f.yytext),this.popState();break;case 13:return g.getLogger().debug("LEX: STR end:",f.yytext),"STR";break;case 14:return f.yytext=f.yytext.replace(/space\:/,""),g.getLogger().debug("SPACE NUM (LEX)",f.yytext),21;break;case 15:return f.yytext="1",g.getLogger().debug("COLUMNS (LEX)",f.yytext),21;break;case 16:return 42;case 17:return"LINKSTYLE";case 18:return"INTERPOLATE";case 19:return this.pushState("CLASSDEF"),39;break;case 20:return this.popState(),this.pushState("CLASSDEFID"),"DEFAULT_CLASSDEF_ID";break;case 21:return this.popState(),this.pushState("CLASSDEFID"),40;break;case 22:return this.popState(),41;break;case 23:return this.pushState("CLASS"),43;break;case 24:return this.popState(),this.pushState("CLASS_STYLE"),44;break;case 25:return this.popState(),45;break;case 26:return this.pushState("STYLE_STMNT"),46;break;case 27:return this.popState(),this.pushState("STYLE_DEFINITION"),47;break;case 28:return this.popState(),48;break;case 29:return this.pushState("acc_title"),"acc_title";break;case 30:return this.popState(),"acc_title_value";break;case 31:return this.pushState("acc_descr"),"acc_descr";break;case 32:return this.popState(),"acc_descr_value";break;case 33:this.pushState("acc_descr_multiline");break;case 34:this.popState();break;case 35:return"acc_descr_multiline_value";case 36:return 30;case 37:return this.popState(),g.getLogger().debug("Lex: (("),"NODE_DEND";break;case 38:return this.popState(),g.getLogger().debug("Lex: (("),"NODE_DEND";break;case 39:return this.popState(),g.getLogger().debug("Lex: ))"),"NODE_DEND";break;case 40:return this.popState(),g.getLogger().debug("Lex: (("),"NODE_DEND";break;case 41:return this.popState(),g.getLogger().debug("Lex: (("),"NODE_DEND";break;case 42:return this.popState(),g.getLogger().debug("Lex: (-"),"NODE_DEND";break;case 43:return this.popState(),g.getLogger().debug("Lex: -)"),"NODE_DEND";break;case 44:return this.popState(),g.getLogger().debug("Lex: (("),"NODE_DEND";break;case 45:return this.popState(),g.getLogger().debug("Lex: ]]"),"NODE_DEND";break;case 46:return this.popState(),g.getLogger().debug("Lex: ("),"NODE_DEND";break;case 47:return this.popState(),g.getLogger().debug("Lex: ])"),"NODE_DEND";break;case 48:return this.popState(),g.getLogger().debug("Lex: /]"),"NODE_DEND";break;case 49:return this.popState(),g.getLogger().debug("Lex: /]"),"NODE_DEND";break;case 50:return this.popState(),g.getLogger().debug("Lex: )]"),"NODE_DEND";break;case 51:return this.popState(),g.getLogger().debug("Lex: )"),"NODE_DEND";break;case 52:return this.popState(),g.getLogger().debug("Lex: ]>"),"NODE_DEND";break;case 53:return this.popState(),g.getLogger().debug("Lex: ]"),"NODE_DEND";break;case 54:return g.getLogger().debug("Lexa: -)"),this.pushState("NODE"),35;break;case 55:return g.getLogger().debug("Lexa: (-"),this.pushState("NODE"),35;break;case 56:return g.getLogger().debug("Lexa: ))"),this.pushState("NODE"),35;break;case 57:return g.getLogger().debug("Lexa: )"),this.pushState("NODE"),35;break;case 58:return g.getLogger().debug("Lex: ((("),this.pushState("NODE"),35;break;case 59:return g.getLogger().debug("Lexa: )"),this.pushState("NODE"),35;break;case 60:return g.getLogger().debug("Lexa: )"),this.pushState("NODE"),35;break;case 61:return g.getLogger().debug("Lexa: )"),this.pushState("NODE"),35;break;case 62:return g.getLogger().debug("Lexc: >"),this.pushState("NODE"),35;break;case 63:return g.getLogger().debug("Lexa: (["),this.pushState("NODE"),35;break;case 64:return g.getLogger().debug("Lexa: )"),this.pushState("NODE"),35;break;case 65:return this.pushState("NODE"),35;break;case 66:return this.pushState("NODE"),35;break;case 67:return this.pushState("NODE"),35;break;case 68:return this.pushState("NODE"),35;break;case 69:return this.pushState("NODE"),35;break;case 70:return this.pushState("NODE"),35;break;case 71:return this.pushState("NODE"),35;break;case 72:return g.getLogger().debug("Lexa: ["),this.pushState("NODE"),35;break;case 73:return this.pushState("BLOCK_ARROW"),g.getLogger().debug("LEX ARR START"),37;break;case 74:return g.getLogger().debug("Lex: NODE_ID",f.yytext),31;break;case 75:return g.getLogger().debug("Lex: EOF",f.yytext),8;break;case 76:this.pushState("md_string");break;case 77:this.pushState("md_string");break;case 78:return"NODE_DESCR";case 79:this.popState();break;case 80:g.getLogger().debug("Lex: Starting string"),this.pushState("string");break;case 81:g.getLogger().debug("LEX ARR: Starting string"),this.pushState("string");break;case 82:return g.getLogger().debug("LEX: NODE_DESCR:",f.yytext),"NODE_DESCR";break;case 83:g.getLogger().debug("LEX POPPING"),this.popState();break;case 84:g.getLogger().debug("Lex: =>BAE"),this.pushState("ARROW_DIR");break;case 85:return f.yytext=f.yytext.replace(/^,\s*/,""),g.getLogger().debug("Lex (right): dir:",f.yytext),"DIR";break;case 86:return f.yytext=f.yytext.replace(/^,\s*/,""),g.getLogger().debug("Lex (left):",f.yytext),"DIR";break;case 87:return f.yytext=f.yytext.replace(/^,\s*/,""),g.getLogger().debug("Lex (x):",f.yytext),"DIR";break;case 88:return f.yytext=f.yytext.replace(/^,\s*/,""),g.getLogger().debug("Lex (y):",f.yytext),"DIR";break;case 89:return f.yytext=f.yytext.replace(/^,\s*/,""),g.getLogger().debug("Lex (up):",f.yytext),"DIR";break;case 90:return f.yytext=f.yytext.replace(/^,\s*/,""),g.getLogger().debug("Lex (down):",f.yytext),"DIR";break;case 91:return f.yytext="]>",g.getLogger().debug("Lex (ARROW_DIR end):",f.yytext),this.popState(),this.popState(),"BLOCK_ARROW_END";break;case 92:return g.getLogger().debug("Lex: LINK","#"+f.yytext+"#"),15;break;case 93:return g.getLogger().debug("Lex: LINK",f.yytext),15;break;case 94:return g.getLogger().debug("Lex: LINK",f.yytext),15;break;case 95:return g.getLogger().debug("Lex: LINK",f.yytext),15;break;case 96:return g.getLogger().debug("Lex: START_LINK",f.yytext),this.pushState("LLABEL"),16;break;case 97:return g.getLogger().debug("Lex: START_LINK",f.yytext),this.pushState("LLABEL"),16;break;case 98:return g.getLogger().debug("Lex: START_LINK",f.yytext),this.pushState("LLABEL"),16;break;case 99:this.pushState("md_string");break;case 100:return g.getLogger().debug("Lex: Starting string"),this.pushState("string"),"LINK_LABEL";break;case 101:return this.popState(),g.getLogger().debug("Lex: LINK","#"+f.yytext+"#"),15;break;case 102:return this.popState(),g.getLogger().debug("Lex: LINK",f.yytext),15;break;case 103:return this.popState(),g.getLogger().debug("Lex: LINK",f.yytext),15;break;case 104:return g.getLogger().debug("Lex: COLON",f.yytext),f.yytext=f.yytext.slice(1),27;break}},"anonymous"),rules:[/^(?:block-beta\b)/,/^(?:block:)/,/^(?:block\b)/,/^(?:[\s]+)/,/^(?:[\n]+)/,/^(?:((\u000D\u000A)|(\u000A)))/,/^(?:columns\s+auto\b)/,/^(?:columns\s+[\d]+)/,/^(?:["][`])/,/^(?:[^`"]+)/,/^(?:[`]["])/,/^(?:["])/,/^(?:["])/,/^(?:[^"]*)/,/^(?:space[:]\d+)/,/^(?:space\b)/,/^(?:default\b)/,/^(?:linkStyle\b)/,/^(?:interpolate\b)/,/^(?:classDef\s+)/,/^(?:DEFAULT\s+)/,/^(?:\w+\s+)/,/^(?:[^\n]*)/,/^(?:class\s+)/,/^(?:(\w+)+((,\s*\w+)*))/,/^(?:[^\n]*)/,/^(?:style\s+)/,/^(?:(\w+)+((,\s*\w+)*))/,/^(?:[^\n]*)/,/^(?:accTitle\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*\{\s*)/,/^(?:[\}])/,/^(?:[^\}]*)/,/^(?:end\b\s*)/,/^(?:\(\(\()/,/^(?:\)\)\))/,/^(?:[\)]\))/,/^(?:\}\})/,/^(?:\})/,/^(?:\(-)/,/^(?:-\))/,/^(?:\(\()/,/^(?:\]\])/,/^(?:\()/,/^(?:\]\))/,/^(?:\\\])/,/^(?:\/\])/,/^(?:\)\])/,/^(?:[\)])/,/^(?:\]>)/,/^(?:[\]])/,/^(?:-\))/,/^(?:\(-)/,/^(?:\)\))/,/^(?:\))/,/^(?:\(\(\()/,/^(?:\(\()/,/^(?:\{\{)/,/^(?:\{)/,/^(?:>)/,/^(?:\(\[)/,/^(?:\()/,/^(?:\[\[)/,/^(?:\[\|)/,/^(?:\[\()/,/^(?:\)\)\))/,/^(?:\[\\)/,/^(?:\[\/)/,/^(?:\[\\)/,/^(?:\[)/,/^(?:<\[)/,/^(?:[^\(\[\n\-\)\{\}\s\<\>:]+)/,/^(?:$)/,/^(?:["][`])/,/^(?:["][`])/,/^(?:[^`"]+)/,/^(?:[`]["])/,/^(?:["])/,/^(?:["])/,/^(?:[^"]+)/,/^(?:["])/,/^(?:\]>\s*\()/,/^(?:,?\s*right\s*)/,/^(?:,?\s*left\s*)/,/^(?:,?\s*x\s*)/,/^(?:,?\s*y\s*)/,/^(?:,?\s*up\s*)/,/^(?:,?\s*down\s*)/,/^(?:\)\s*)/,/^(?:\s*[xo<]?--+[-xo>]\s*)/,/^(?:\s*[xo<]?==+[=xo>]\s*)/,/^(?:\s*[xo<]?-?\.+-[xo>]?\s*)/,/^(?:\s*~~[\~]+\s*)/,/^(?:\s*[xo<]?--\s*)/,/^(?:\s*[xo<]?==\s*)/,/^(?:\s*[xo<]?-\.\s*)/,/^(?:["][`])/,/^(?:["])/,/^(?:\s*[xo<]?--+[-xo>]\s*)/,/^(?:\s*[xo<]?==+[=xo>]\s*)/,/^(?:\s*[xo<]?-?\.+-[xo>]?\s*)/,/^(?::\d+)/],conditions:{STYLE_DEFINITION:{rules:[28],inclusive:!1},STYLE_STMNT:{rules:[27],inclusive:!1},CLASSDEFID:{rules:[22],inclusive:!1},CLASSDEF:{rules:[20,21],inclusive:!1},CLASS_STYLE:{rules:[25],inclusive:!1},CLASS:{rules:[24],inclusive:!1},LLABEL:{rules:[99,100,101,102,103],inclusive:!1},ARROW_DIR:{rules:[85,86,87,88,89,90,91],inclusive:!1},BLOCK_ARROW:{rules:[76,81,84],inclusive:!1},NODE:{rules:[37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,77,80],inclusive:!1},md_string:{rules:[9,10,78,79],inclusive:!1},space:{rules:[],inclusive:!1},string:{rules:[12,13,82,83],inclusive:!1},acc_descr_multiline:{rules:[34,35],inclusive:!1},acc_descr:{rules:[32],inclusive:!1},acc_title:{rules:[30],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,7,8,11,14,15,16,17,18,19,23,26,29,31,33,36,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,92,93,94,95,96,97,98,104],inclusive:!0}}};return D})();S.lexer=C;function _(){this.yy={}}return d(_,"Parser"),_.prototype=S,S.Parser=_,new _})();wt.parser=wt;var _e=wt,U=new Map,Et=[],kt=new Map,Zt="color",Gt="fill",De="bgFill",ae=",",Ne=I(),ht=new Map,Te=d(e=>At.sanitizeText(e,Ne),"sanitizeText"),Be=d(function(e,t=""){let a=ht.get(e);a||(a={id:e,styles:[],textStyles:[]},ht.set(e,a)),t?.split(ae).forEach(i=>{let l=i.replace(/([^;]*);/,"$1").trim();if(RegExp(Zt).exec(i)){let r=l.replace(Gt,De).replace(Zt,Gt);a.textStyles.push(r)}a.styles.push(l)})},"addStyleClass"),Ce=d(function(e,t=""){let a=U.get(e);t!=null&&(a.styles=t.split(ae))},"addStyle2Node"),Ie=d(function(e,t){e.split(",").forEach(function(a){let i=U.get(a);if(i===void 0){let l=a.trim();i={id:l,type:"na",children:[]},U.set(l,i)}i.classes||(i.classes=[]),i.classes.push(t)})},"setCssClass"),se=d((e,t)=>{let a=e.flat(),i=[],s=a.find(r=>r?.type==="column-setting")?.columns??-1;for(let r of a){if(typeof s=="number"&&s>0&&r.type!=="column-setting"&&typeof r.widthInColumns=="number"&&r.widthInColumns>s&&w.warn(`Block ${r.id} width ${r.widthInColumns} exceeds configured column width ${s}`),r.label&&(r.label=Te(r.label)),r.type==="classDef"){Be(r.id,r.css);continue}if(r.type==="applyClass"){Ie(r.id,r?.styleClass??"");continue}if(r.type==="applyStyles"){r?.stylesStr&&Ce(r.id,r?.stylesStr);continue}if(r.type==="column-setting")t.columns=r.columns??-1;else if(r.type==="edge"){let n=(kt.get(r.id)??0)+1;kt.set(r.id,n),r.id=n+"-"+r.id,Et.push(r)}else{r.label||(r.type==="composite"?r.label="":r.label=r.id);let n=U.get(r.id);if(n===void 0?U.set(r.id,r):(r.type!=="na"&&(n.type=r.type),r.label!==r.id&&(n.label=r.label)),r.children&&se(r.children,r),r.type==="space"){let c=r.width??1;for(let u=0;u{w.debug("Clear called"),Ft(),rt={id:"root",type:"composite",children:[],columns:-1},U=new Map([["root",rt]]),_t=[],ht=new Map,Et=[],kt=new Map},"clear");function ie(e){switch(w.debug("typeStr2Type",e),e){case"[]":return"square";case"()":return w.debug("we have a round"),"round";case"(())":return"circle";case">]":return"rect_left_inv_arrow";case"{}":return"diamond";case"{{}}":return"hexagon";case"([])":return"stadium";case"[[]]":return"subroutine";case"[()]":return"cylinder";case"((()))":return"doublecircle";case"[//]":return"lean_right";case"[\\\\]":return"lean_left";case"[/\\]":return"trapezoid";case"[\\/]":return"inv_trapezoid";case"<[]>":return"block_arrow";default:return"na"}}d(ie,"typeStr2Type");function ne(e){switch(w.debug("typeStr2Type",e),e){case"==":return"thick";default:return"normal"}}d(ne,"edgeTypeStr2Type");function le(e){switch(e.replace(/^[\s-]+|[\s-]+$/g,"")){case"x":return"arrow_cross";case"o":return"arrow_circle";case">":return"arrow_point";default:return""}}d(le,"edgeStrToEdgeData");var qt=0,Re=d(()=>(qt++,"id-"+Math.random().toString(36).substr(2,12)+"-"+qt),"generateId"),ze=d(e=>{rt.children=e,se(e,rt),_t=rt.children},"setHierarchy"),Ae=d(e=>{let t=U.get(e);return t?t.columns?t.columns:t.children?t.children.length:-1:-1},"getColumns"),Me=d(()=>[...U.values()],"getBlocksFlat"),Fe=d(()=>_t||[],"getBlocks"),We=d(()=>Et,"getEdges"),Pe=d(e=>U.get(e),"getBlock"),Ye=d(e=>{U.set(e.id,e)},"setBlock"),He=d(()=>w,"getLogger"),Ke=d(function(){return ht},"getClasses"),Xe={getConfig:d(()=>$().block,"getConfig"),typeStr2Type:ie,edgeTypeStr2Type:ne,edgeStrToEdgeData:le,getLogger:He,getBlocksFlat:Me,getBlocks:Fe,getEdges:We,setHierarchy:ze,getBlock:Pe,setBlock:Ye,getColumns:Ae,getClasses:Ke,clear:Oe,generateId:Re},Ue=Xe,ct=d((e,t)=>{let a=Rt,i=a(e,"r"),l=a(e,"g"),s=a(e,"b");return Ot(i,l,s,t)},"fade"),je=d(e=>`.label { + font-family: ${e.fontFamily}; + color: ${e.nodeTextColor||e.textColor}; + } + .cluster-label text { + fill: ${e.titleColor}; + } + .cluster-label span,p { + color: ${e.titleColor}; + } + + + + .label text,span,p { + fill: ${e.nodeTextColor||e.textColor}; + color: ${e.nodeTextColor||e.textColor}; + } + + .node rect, + .node circle, + .node ellipse, + .node polygon, + .node path { + fill: ${e.mainBkg}; + stroke: ${e.nodeBorder}; + stroke-width: 1px; + } + .flowchart-label text { + text-anchor: middle; + } + // .flowchart-label .text-outer-tspan { + // text-anchor: middle; + // } + // .flowchart-label .text-inner-tspan { + // text-anchor: start; + // } + + .node .label { + text-align: center; + } + .node.clickable { + cursor: pointer; + } + + .arrowheadPath { + fill: ${e.arrowheadColor}; + } + + .edgePath .path { + stroke: ${e.lineColor}; + stroke-width: 2.0px; + } + + .flowchart-link { + stroke: ${e.lineColor}; + fill: none; + } + + .edgeLabel { + background-color: ${e.edgeLabelBackground}; + rect { + opacity: 0.5; + background-color: ${e.edgeLabelBackground}; + fill: ${e.edgeLabelBackground}; + } + text-align: center; + } + + /* For html labels only */ + .labelBkg { + background-color: ${ct(e.edgeLabelBackground,.5)}; + // background-color: + } + + .node .cluster { + // fill: ${ct(e.mainBkg,.5)}; + fill: ${ct(e.clusterBkg,.5)}; + stroke: ${ct(e.clusterBorder,.2)}; + box-shadow: rgba(50, 50, 93, 0.25) 0px 13px 27px -5px, rgba(0, 0, 0, 0.3) 0px 8px 16px -8px; + stroke-width: 1px; + } + + .cluster text { + fill: ${e.titleColor}; + } + + .cluster span,p { + color: ${e.titleColor}; + } + /* .cluster div { + color: ${e.titleColor}; + } */ + + div.mermaidTooltip { + position: absolute; + text-align: center; + max-width: 200px; + padding: 2px; + font-family: ${e.fontFamily}; + font-size: 12px; + background: ${e.tertiaryColor}; + border: 1px solid ${e.border2}; + border-radius: 2px; + pointer-events: none; + z-index: 100; + } + + .flowchartTitleText { + text-anchor: middle; + font-size: 18px; + fill: ${e.textColor}; + } + ${Vt()} +`,"getStyles"),Ve=je,Ze=d((e,t,a,i)=>{t.forEach(l=>{sr[l](e,a,i)})},"insertMarkers"),Ge=d((e,t,a)=>{w.trace("Making markers for ",a),e.append("defs").append("marker").attr("id",a+"_"+t+"-extensionStart").attr("class","marker extension "+t).attr("refX",18).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 1,7 L18,13 V 1 Z"),e.append("defs").append("marker").attr("id",a+"_"+t+"-extensionEnd").attr("class","marker extension "+t).attr("refX",1).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 1,1 V 13 L18,7 Z")},"extension"),qe=d((e,t,a)=>{e.append("defs").append("marker").attr("id",a+"_"+t+"-compositionStart").attr("class","marker composition "+t).attr("refX",18).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),e.append("defs").append("marker").attr("id",a+"_"+t+"-compositionEnd").attr("class","marker composition "+t).attr("refX",1).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z")},"composition"),Je=d((e,t,a)=>{e.append("defs").append("marker").attr("id",a+"_"+t+"-aggregationStart").attr("class","marker aggregation "+t).attr("refX",18).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),e.append("defs").append("marker").attr("id",a+"_"+t+"-aggregationEnd").attr("class","marker aggregation "+t).attr("refX",1).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z")},"aggregation"),Qe=d((e,t,a)=>{e.append("defs").append("marker").attr("id",a+"_"+t+"-dependencyStart").attr("class","marker dependency "+t).attr("refX",6).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 5,7 L9,13 L1,7 L9,1 Z"),e.append("defs").append("marker").attr("id",a+"_"+t+"-dependencyEnd").attr("class","marker dependency "+t).attr("refX",13).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L14,7 L9,1 Z")},"dependency"),$e=d((e,t,a)=>{e.append("defs").append("marker").attr("id",a+"_"+t+"-lollipopStart").attr("class","marker lollipop "+t).attr("refX",13).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("circle").attr("stroke","black").attr("fill","transparent").attr("cx",7).attr("cy",7).attr("r",6),e.append("defs").append("marker").attr("id",a+"_"+t+"-lollipopEnd").attr("class","marker lollipop "+t).attr("refX",1).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("circle").attr("stroke","black").attr("fill","transparent").attr("cx",7).attr("cy",7).attr("r",6)},"lollipop"),tr=d((e,t,a)=>{e.append("marker").attr("id",a+"_"+t+"-pointEnd").attr("class","marker "+t).attr("viewBox","0 0 10 10").attr("refX",6).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",12).attr("markerHeight",12).attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 z").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0"),e.append("marker").attr("id",a+"_"+t+"-pointStart").attr("class","marker "+t).attr("viewBox","0 0 10 10").attr("refX",4.5).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",12).attr("markerHeight",12).attr("orient","auto").append("path").attr("d","M 0 5 L 10 10 L 10 0 z").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0")},"point"),er=d((e,t,a)=>{e.append("marker").attr("id",a+"_"+t+"-circleEnd").attr("class","marker "+t).attr("viewBox","0 0 10 10").attr("refX",11).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("circle").attr("cx","5").attr("cy","5").attr("r","5").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0"),e.append("marker").attr("id",a+"_"+t+"-circleStart").attr("class","marker "+t).attr("viewBox","0 0 10 10").attr("refX",-1).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("circle").attr("cx","5").attr("cy","5").attr("r","5").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0")},"circle"),rr=d((e,t,a)=>{e.append("marker").attr("id",a+"_"+t+"-crossEnd").attr("class","marker cross "+t).attr("viewBox","0 0 11 11").attr("refX",12).attr("refY",5.2).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("path").attr("d","M 1,1 l 9,9 M 10,1 l -9,9").attr("class","arrowMarkerPath").style("stroke-width",2).style("stroke-dasharray","1,0"),e.append("marker").attr("id",a+"_"+t+"-crossStart").attr("class","marker cross "+t).attr("viewBox","0 0 11 11").attr("refX",-1).attr("refY",5.2).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("path").attr("d","M 1,1 l 9,9 M 10,1 l -9,9").attr("class","arrowMarkerPath").style("stroke-width",2).style("stroke-dasharray","1,0")},"cross"),ar=d((e,t,a)=>{e.append("defs").append("marker").attr("id",a+"_"+t+"-barbEnd").attr("refX",19).attr("refY",7).attr("markerWidth",20).attr("markerHeight",14).attr("markerUnits","strokeWidth").attr("orient","auto").append("path").attr("d","M 19,7 L9,13 L14,7 L9,1 Z")},"barb"),sr={extension:Ge,composition:qe,aggregation:Je,dependency:Qe,lollipop:$e,point:tr,circle:er,cross:rr,barb:ar},ir=Ze,O=I()?.block?.padding??8;function ce(e,t){if(e===0||!Number.isInteger(e))throw new Error("Columns must be an integer !== 0.");if(t<0||!Number.isInteger(t))throw new Error("Position must be a non-negative integer."+t);if(e<0)return{px:t,py:0};if(e===1)return{px:0,py:t};let a=t%e,i=Math.floor(t/e);return{px:a,py:i}}d(ce,"calculateBlockPosition");var nr=d(e=>{let t=0,a=0;for(let i of e.children){let{width:l,height:s,x:r,y:n}=i.size??{width:0,height:0,x:0,y:0};w.debug("getMaxChildSize abc95 child:",i.id,"width:",l,"height:",s,"x:",r,"y:",n,i.type),i.type!=="space"&&(l>t&&(t=l/(e.widthInColumns??1)),s>a&&(a=s))}return{width:t,height:a}},"getMaxChildSize");function dt(e,t,a=0,i=0){w.debug("setBlockSizes abc95 (start)",e.id,e?.size?.x,"block width =",e?.size,"siblingWidth",a),e?.size?.width||(e.size={width:a,height:i,x:0,y:0});let l=0,s=0;if(e.children?.length>0){for(let y of e.children)dt(y,t);let r=nr(e);l=r.width,s=r.height,w.debug("setBlockSizes abc95 maxWidth of",e.id,":s children is ",l,s);for(let y of e.children)y.size&&(w.debug(`abc95 Setting size of children of ${e.id} id=${y.id} ${l} ${s} ${JSON.stringify(y.size)}`),y.size.width=l*(y.widthInColumns??1)+O*((y.widthInColumns??1)-1),y.size.height=s,y.size.x=0,y.size.y=0,w.debug(`abc95 updating size of ${e.id} children child:${y.id} maxWidth:${l} maxHeight:${s}`));for(let y of e.children)dt(y,t,l,s);let n=e.columns??-1,c=0;for(let y of e.children)c+=y.widthInColumns??1;let u=e.children.length;n>0&&n0?Math.min(e.children.length,n):e.children.length;if(y>0){let L=(b-y*O-O)/y;w.debug("abc95 (growing to fit) width",e.id,b,e.size?.width,L);for(let E of e.children)E.size&&(E.size.width=L)}}e.size={width:b,height:m,x:0,y:0}}w.debug("setBlockSizes abc94 (done)",e.id,e?.size?.x,e?.size?.width,e?.size?.y,e?.size?.height)}d(dt,"setBlockSizes");function Dt(e,t){w.debug(`abc85 layout blocks (=>layoutBlocks) ${e.id} x: ${e?.size?.x} y: ${e?.size?.y} width: ${e?.size?.width}`);let a=e.columns??-1;if(w.debug("layoutBlocks columns abc95",e.id,"=>",a,e),e.children&&e.children.length>0){let i=e?.children[0]?.size?.width??0,l=e.children.length*i+(e.children.length-1)*O;w.debug("widthOfChildren 88",l,"posX");let s=0;w.debug("abc91 block?.size?.x",e.id,e?.size?.x);let r=e?.size?.x?e?.size?.x+(-e?.size?.width/2||0):-O,n=0;for(let c of e.children){let u=e;if(!c.size)continue;let{width:o,height:b}=c.size,{px:m,py:y}=ce(a,s);if(y!=n&&(n=y,r=e?.size?.x?e?.size?.x+(-e?.size?.width/2||0):-O,w.debug("New row in layout for block",e.id," and child ",c.id,n)),w.debug(`abc89 layout blocks (child) id: ${c.id} Pos: ${s} (px, py) ${m},${y} (${u?.size?.x},${u?.size?.y}) parent: ${u.id} width: ${o}${O}`),u.size){let E=o/2;c.size.x=r+O+E,w.debug(`abc91 layout blocks (calc) px, pyid:${c.id} startingPos=X${r} new startingPosX${c.size.x} ${E} padding=${O} width=${o} halfWidth=${E} => x:${c.size.x} y:${c.size.y} ${c.widthInColumns} (width * (child?.w || 1)) / 2 ${o*(c?.widthInColumns??1)/2}`),r=c.size.x+E,c.size.y=u.size.y-u.size.height/2+y*(b+O)+b/2+O,w.debug(`abc88 layout blocks (calc) px, pyid:${c.id}startingPosX${r}${O}${E}=>x:${c.size.x}y:${c.size.y}${c.widthInColumns}(width * (child?.w || 1)) / 2${o*(c?.widthInColumns??1)/2}`)}c.children&&Dt(c,t);let L=c?.widthInColumns??1;a>0&&(L=Math.min(L,a-s%a)),s+=L,w.debug("abc88 columnsPos",c,s)}}w.debug(`layout blocks (<==layoutBlocks) ${e.id} x: ${e?.size?.x} y: ${e?.size?.y} width: ${e?.size?.width}`)}d(Dt,"layoutBlocks");function Nt(e,{minX:t,minY:a,maxX:i,maxY:l}={minX:0,minY:0,maxX:0,maxY:0}){if(e.size&&e.id!=="root"){let{x:s,y:r,width:n,height:c}=e.size;s-n/2i&&(i=s+n/2),r+c/2>l&&(l=r+c/2)}if(e.children)for(let s of e.children)({minX:t,minY:a,maxX:i,maxY:l}=Nt(s,{minX:t,minY:a,maxX:i,maxY:l}));return{minX:t,minY:a,maxX:i,maxY:l}}d(Nt,"findBounds");function oe(e){let t=e.getBlock("root");if(!t)return;dt(t,e,0,0),Dt(t,e),w.debug("getBlocks",JSON.stringify(t,null,2));let{minX:a,minY:i,maxX:l,maxY:s}=Nt(t),r=s-i,n=l-a;return{x:a,y:i,width:n,height:r}}d(oe,"layout");function Lt(e,t){t&&e.attr("style",t)}d(Lt,"applyStyle");function he(e,t){let a=N(document.createElementNS("http://www.w3.org/2000/svg","foreignObject")),i=a.append("xhtml:div"),l=e.label,s=e.isNode?"nodeLabel":"edgeLabel",r=i.append("span");return r.html(nt(l,t)),Lt(r,e.labelStyle),r.attr("class",s),Lt(i,e.labelStyle),i.style("display","inline-block"),i.style("white-space","nowrap"),i.attr("xmlns","http://www.w3.org/1999/xhtml"),a.node()}d(he,"addHtmlLabel");var lr=d(async(e,t,a,i)=>{let l=e||"";typeof l=="object"&&(l=l[0]);let s=I();if(X(s.flowchart.htmlLabels)){l=l.replace(/\\n|\n/g,"
"),w.debug("vertexText"+l);let r=await Xt(lt(l)),n={isNode:i,label:r,labelStyle:t.replace("fill:","color:")};return he(n,s)}else{let r=document.createElementNS("http://www.w3.org/2000/svg","text");r.setAttribute("style",t.replace("color:","fill:"));let n=[];typeof l=="string"?n=l.split(/\\n|\n|/gi):Array.isArray(l)?n=l:n=[];for(let c of n){let u=document.createElementNS("http://www.w3.org/2000/svg","tspan");u.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve"),u.setAttribute("dy","1em"),u.setAttribute("x","0"),a?u.setAttribute("class","title-row"):u.setAttribute("class","row"),u.textContent=c.trim(),r.appendChild(u)}return r}},"createLabel"),K=lr,cr=d((e,t,a,i,l)=>{t.arrowTypeStart&&Jt(e,"start",t.arrowTypeStart,a,i,l),t.arrowTypeEnd&&Jt(e,"end",t.arrowTypeEnd,a,i,l)},"addEdgeMarkers"),or={arrow_cross:"cross",arrow_point:"point",arrow_barb:"barb",arrow_circle:"circle",aggregation:"aggregation",extension:"extension",composition:"composition",dependency:"dependency",lollipop:"lollipop"},Jt=d((e,t,a,i,l,s)=>{let r=or[a];if(!r){w.warn(`Unknown arrow type: ${a}`);return}let n=t==="start"?"Start":"End";e.attr(`marker-${t}`,`url(${i}#${l}_${s}-${r}${n})`)},"addEdgeMarker"),St={},M={},hr=d(async(e,t)=>{let a=I(),i=X(a.flowchart.htmlLabels),l=t.labelType==="markdown"?mt(e,t.label,{style:t.labelStyle,useHtmlLabels:i,addSvgBackground:!0},a):await K(t.label,t.labelStyle),s=e.insert("g").attr("class","edgeLabel"),r=s.insert("g").attr("class","label");r.node().appendChild(l);let n=l.getBBox();if(i){let u=l.children[0],o=N(l);n=u.getBoundingClientRect(),o.attr("width",n.width),o.attr("height",n.height)}r.attr("transform","translate("+-n.width/2+", "+-n.height/2+")"),St[t.id]=s,t.width=n.width,t.height=n.height;let c;if(t.startLabelLeft){let u=await K(t.startLabelLeft,t.labelStyle),o=e.insert("g").attr("class","edgeTerminals"),b=o.insert("g").attr("class","inner");c=b.node().appendChild(u);let m=u.getBBox();b.attr("transform","translate("+-m.width/2+", "+-m.height/2+")"),M[t.id]||(M[t.id]={}),M[t.id].startLeft=o,et(c,t.startLabelLeft)}if(t.startLabelRight){let u=await K(t.startLabelRight,t.labelStyle),o=e.insert("g").attr("class","edgeTerminals"),b=o.insert("g").attr("class","inner");c=o.node().appendChild(u),b.node().appendChild(u);let m=u.getBBox();b.attr("transform","translate("+-m.width/2+", "+-m.height/2+")"),M[t.id]||(M[t.id]={}),M[t.id].startRight=o,et(c,t.startLabelRight)}if(t.endLabelLeft){let u=await K(t.endLabelLeft,t.labelStyle),o=e.insert("g").attr("class","edgeTerminals"),b=o.insert("g").attr("class","inner");c=b.node().appendChild(u);let m=u.getBBox();b.attr("transform","translate("+-m.width/2+", "+-m.height/2+")"),o.node().appendChild(u),M[t.id]||(M[t.id]={}),M[t.id].endLeft=o,et(c,t.endLabelLeft)}if(t.endLabelRight){let u=await K(t.endLabelRight,t.labelStyle),o=e.insert("g").attr("class","edgeTerminals"),b=o.insert("g").attr("class","inner");c=b.node().appendChild(u);let m=u.getBBox();b.attr("transform","translate("+-m.width/2+", "+-m.height/2+")"),o.node().appendChild(u),M[t.id]||(M[t.id]={}),M[t.id].endRight=o,et(c,t.endLabelRight)}return l},"insertEdgeLabel");function et(e,t){I().flowchart.htmlLabels&&e&&(e.style.width=t.length*9+"px",e.style.height="12px")}d(et,"setTerminalWidth");var dr=d((e,t)=>{w.debug("Moving label abc88 ",e.id,e.label,St[e.id],t);let a=t.updatedPath?t.updatedPath:t.originalPath,i=I(),{subGraphTitleTotalMargin:l}=Ht(i);if(e.label){let s=St[e.id],r=e.x,n=e.y;if(a){let c=tt.calcLabelPosition(a);w.debug("Moving label "+e.label+" from (",r,",",n,") to (",c.x,",",c.y,") abc88"),t.updatedPath&&(r=c.x,n=c.y)}s.attr("transform",`translate(${r}, ${n+l/2})`)}if(e.startLabelLeft){let s=M[e.id].startLeft,r=e.x,n=e.y;if(a){let c=tt.calcTerminalLabelPosition(e.arrowTypeStart?10:0,"start_left",a);r=c.x,n=c.y}s.attr("transform",`translate(${r}, ${n})`)}if(e.startLabelRight){let s=M[e.id].startRight,r=e.x,n=e.y;if(a){let c=tt.calcTerminalLabelPosition(e.arrowTypeStart?10:0,"start_right",a);r=c.x,n=c.y}s.attr("transform",`translate(${r}, ${n})`)}if(e.endLabelLeft){let s=M[e.id].endLeft,r=e.x,n=e.y;if(a){let c=tt.calcTerminalLabelPosition(e.arrowTypeEnd?10:0,"end_left",a);r=c.x,n=c.y}s.attr("transform",`translate(${r}, ${n})`)}if(e.endLabelRight){let s=M[e.id].endRight,r=e.x,n=e.y;if(a){let c=tt.calcTerminalLabelPosition(e.arrowTypeEnd?10:0,"end_right",a);r=c.x,n=c.y}s.attr("transform",`translate(${r}, ${n})`)}},"positionEdgeLabel"),gr=d((e,t)=>{let a=e.x,i=e.y,l=Math.abs(t.x-a),s=Math.abs(t.y-i),r=e.width/2,n=e.height/2;return l>=r||s>=n},"outsideNode"),ur=d((e,t,a)=>{w.debug(`intersection calc abc89: + outsidePoint: ${JSON.stringify(t)} + insidePoint : ${JSON.stringify(a)} + node : x:${e.x} y:${e.y} w:${e.width} h:${e.height}`);let i=e.x,l=e.y,s=Math.abs(i-a.x),r=e.width/2,n=a.xMath.abs(i-t.x)*c){let b=a.y{w.debug("abc88 cutPathAtIntersect",e,t);let a=[],i=e[0],l=!1;return e.forEach(s=>{if(!gr(t,s)&&!l){let r=ur(t,i,s),n=!1;a.forEach(c=>{n=n||c.x===r.x&&c.y===r.y}),a.some(c=>c.x===r.x&&c.y===r.y)||a.push(r),l=!0}else i=s,l||a.push(s)}),a},"cutPathAtIntersect"),pr=d(function(e,t,a,i,l,s,r){let n=a.points;w.debug("abc88 InsertEdge: edge=",a,"e=",t);let c=!1,u=s.node(t.v);var o=s.node(t.w);o?.intersect&&u?.intersect&&(n=n.slice(1,a.points.length-1),n.unshift(u.intersect(n[0])),n.push(o.intersect(n[n.length-1]))),a.toCluster&&(w.debug("to cluster abc88",i[a.toCluster]),n=Qt(a.points,i[a.toCluster].node),c=!0),a.fromCluster&&(w.debug("from cluster abc88",i[a.fromCluster]),n=Qt(n.reverse(),i[a.fromCluster].node).reverse(),c=!0);let b=n.filter(x=>!Number.isNaN(x.y)),m=Pt;a.curve&&(l==="graph"||l==="flowchart")&&(m=a.curve);let{x:y,y:L}=Yt(a),E=Wt().x(y).y(L).curve(m),S;switch(a.thickness){case"normal":S="edge-thickness-normal";break;case"thick":S="edge-thickness-thick";break;case"invisible":S="edge-thickness-thick";break;default:S=""}switch(a.pattern){case"solid":S+=" edge-pattern-solid";break;case"dotted":S+=" edge-pattern-dotted";break;case"dashed":S+=" edge-pattern-dashed";break}let C=e.append("path").attr("d",E(b)).attr("id",a.id).attr("class"," "+S+(a.classes?" "+a.classes:"")).attr("style",a.style),_="";(I().flowchart.arrowMarkerAbsolute||I().state.arrowMarkerAbsolute)&&(_=zt(!0)),cr(C,a,_,r,l);let D={};return c&&(D.updatedPath=n),D.originalPath=a.points,D},"insertEdge"),fr=d(e=>{let t=new Set;for(let a of e)switch(a){case"x":t.add("right"),t.add("left");break;case"y":t.add("up"),t.add("down");break;default:t.add(a);break}return t},"expandAndDeduplicateDirections"),br=d((e,t,a)=>{let i=fr(e),l=2,s=t.height+2*a.padding,r=s/l,n=t.width+2*r+a.padding,c=a.padding/2;return i.has("right")&&i.has("left")&&i.has("up")&&i.has("down")?[{x:0,y:0},{x:r,y:0},{x:n/2,y:2*c},{x:n-r,y:0},{x:n,y:0},{x:n,y:-s/3},{x:n+2*c,y:-s/2},{x:n,y:-2*s/3},{x:n,y:-s},{x:n-r,y:-s},{x:n/2,y:-s-2*c},{x:r,y:-s},{x:0,y:-s},{x:0,y:-2*s/3},{x:-2*c,y:-s/2},{x:0,y:-s/3}]:i.has("right")&&i.has("left")&&i.has("up")?[{x:r,y:0},{x:n-r,y:0},{x:n,y:-s/2},{x:n-r,y:-s},{x:r,y:-s},{x:0,y:-s/2}]:i.has("right")&&i.has("left")&&i.has("down")?[{x:0,y:0},{x:r,y:-s},{x:n-r,y:-s},{x:n,y:0}]:i.has("right")&&i.has("up")&&i.has("down")?[{x:0,y:0},{x:n,y:-r},{x:n,y:-s+r},{x:0,y:-s}]:i.has("left")&&i.has("up")&&i.has("down")?[{x:n,y:0},{x:0,y:-r},{x:0,y:-s+r},{x:n,y:-s}]:i.has("right")&&i.has("left")?[{x:r,y:0},{x:r,y:-c},{x:n-r,y:-c},{x:n-r,y:0},{x:n,y:-s/2},{x:n-r,y:-s},{x:n-r,y:-s+c},{x:r,y:-s+c},{x:r,y:-s},{x:0,y:-s/2}]:i.has("up")&&i.has("down")?[{x:n/2,y:0},{x:0,y:-c},{x:r,y:-c},{x:r,y:-s+c},{x:0,y:-s+c},{x:n/2,y:-s},{x:n,y:-s+c},{x:n-r,y:-s+c},{x:n-r,y:-c},{x:n,y:-c}]:i.has("right")&&i.has("up")?[{x:0,y:0},{x:n,y:-r},{x:0,y:-s}]:i.has("right")&&i.has("down")?[{x:0,y:0},{x:n,y:0},{x:0,y:-s}]:i.has("left")&&i.has("up")?[{x:n,y:0},{x:0,y:-r},{x:n,y:-s}]:i.has("left")&&i.has("down")?[{x:n,y:0},{x:0,y:0},{x:n,y:-s}]:i.has("right")?[{x:r,y:-c},{x:r,y:-c},{x:n-r,y:-c},{x:n-r,y:0},{x:n,y:-s/2},{x:n-r,y:-s},{x:n-r,y:-s+c},{x:r,y:-s+c},{x:r,y:-s+c}]:i.has("left")?[{x:r,y:0},{x:r,y:-c},{x:n-r,y:-c},{x:n-r,y:-s+c},{x:r,y:-s+c},{x:r,y:-s},{x:0,y:-s/2}]:i.has("up")?[{x:r,y:-c},{x:r,y:-s+c},{x:0,y:-s+c},{x:n/2,y:-s},{x:n,y:-s+c},{x:n-r,y:-s+c},{x:n-r,y:-c}]:i.has("down")?[{x:n/2,y:0},{x:0,y:-c},{x:r,y:-c},{x:r,y:-s+c},{x:n-r,y:-s+c},{x:n-r,y:-c},{x:n,y:-c}]:[{x:0,y:0}]},"getArrowPoints");function de(e,t){return e.intersect(t)}d(de,"intersectNode");var xr=de;function ge(e,t,a,i){var l=e.x,s=e.y,r=l-i.x,n=s-i.y,c=Math.sqrt(t*t*n*n+a*a*r*r),u=Math.abs(t*a*r/c);i.x0}d(vt,"sameSign");var mr=fe,wr=be;function be(e,t,a){var i=e.x,l=e.y,s=[],r=Number.POSITIVE_INFINITY,n=Number.POSITIVE_INFINITY;typeof t.forEach=="function"?t.forEach(function(L){r=Math.min(r,L.x),n=Math.min(n,L.y)}):(r=Math.min(r,t.x),n=Math.min(n,t.y));for(var c=i-e.width/2-r,u=l-e.height/2-n,o=0;o1&&s.sort(function(L,E){var S=L.x-a.x,C=L.y-a.y,_=Math.sqrt(S*S+C*C),D=E.x-a.x,x=E.y-a.y,g=Math.sqrt(D*D+x*x);return _{var a=e.x,i=e.y,l=t.x-a,s=t.y-i,r=e.width/2,n=e.height/2,c,u;return Math.abs(s)*r>Math.abs(l)*n?(s<0&&(n=-n),c=s===0?0:n*l/s,u=n):(l<0&&(r=-r),c=r,u=l===0?0:r*s/l),{x:a+c,y:i+u}},"intersectRect"),Lr=kr,T={node:xr,circle:yr,ellipse:ue,polygon:wr,rect:Lr},A=d(async(e,t,a,i)=>{let l=I(),s,r=t.useHtmlLabels||X(l.flowchart.htmlLabels);a?s=a:s="node default";let n=e.insert("g").attr("class",s).attr("id",t.domId||t.id),c=n.insert("g").attr("class","label").attr("style",t.labelStyle),u;t.labelText===void 0?u="":u=typeof t.labelText=="string"?t.labelText:t.labelText[0];let o=c.node(),b;t.labelType==="markdown"?b=mt(c,nt(lt(u),l),{useHtmlLabels:r,width:t.width||l.flowchart.wrappingWidth,classes:"markdown-node-label"},l):b=o.appendChild(await K(nt(lt(u),l),t.labelStyle,!1,i));let m=b.getBBox(),y=t.padding/2;if(X(l.flowchart.htmlLabels)){let L=b.children[0],E=N(b),S=L.getElementsByTagName("img");if(S){let C=u.replace(/]*>/g,"").trim()==="";await Promise.all([...S].map(_=>new Promise(D=>{function x(){if(_.style.display="flex",_.style.flexDirection="column",C){let g=l.fontSize?l.fontSize:window.getComputedStyle(document.body).fontSize,k=parseInt(g,10)*5+"px";_.style.minWidth=k,_.style.maxWidth=k}else _.style.width="100%";D(_)}d(x,"setupImage"),setTimeout(()=>{_.complete&&x()}),_.addEventListener("error",x),_.addEventListener("load",x)})))}m=L.getBoundingClientRect(),E.attr("width",m.width),E.attr("height",m.height)}return r?c.attr("transform","translate("+-m.width/2+", "+-m.height/2+")"):c.attr("transform","translate(0, "+-m.height/2+")"),t.centerLabel&&c.attr("transform","translate("+-m.width/2+", "+-m.height/2+")"),c.insert("rect",":first-child"),{shapeSvg:n,bbox:m,halfPadding:y,label:c}},"labelHelper"),B=d((e,t)=>{let a=t.node().getBBox();e.width=a.width,e.height=a.height},"updateNodeBounds");function j(e,t,a,i){return e.insert("polygon",":first-child").attr("points",i.map(function(l){return l.x+","+l.y}).join(" ")).attr("class","label-container").attr("transform","translate("+-t/2+","+a/2+")")}d(j,"insertPolygonShape");var Sr=d(async(e,t)=>{t.useHtmlLabels||I().flowchart.htmlLabels||(t.centerLabel=!0);let{shapeSvg:i,bbox:l,halfPadding:s}=await A(e,t,"node "+t.classes,!0);w.info("Classes = ",t.classes);let r=i.insert("rect",":first-child");return r.attr("rx",t.rx).attr("ry",t.ry).attr("x",-l.width/2-s).attr("y",-l.height/2-s).attr("width",l.width+t.padding).attr("height",l.height+t.padding),B(t,r),t.intersect=function(n){return T.rect(t,n)},i},"note"),vr=Sr,$t=d(e=>e?" "+e:"","formatClass"),Y=d((e,t)=>`${t||"node default"}${$t(e.classes)} ${$t(e.class)}`,"getClassesFromNode"),te=d(async(e,t)=>{let{shapeSvg:a,bbox:i}=await A(e,t,Y(t,void 0),!0),l=i.width+t.padding,s=i.height+t.padding,r=l+s,n=[{x:r/2,y:0},{x:r,y:-r/2},{x:r/2,y:-r},{x:0,y:-r/2}];w.info("Question main (Circle)");let c=j(a,r,r,n);return c.attr("style",t.style),B(t,c),t.intersect=function(u){return w.warn("Intersect called"),T.polygon(t,n,u)},a},"question"),Er=d((e,t)=>{let a=e.insert("g").attr("class","node default").attr("id",t.domId||t.id),i=28,l=[{x:0,y:i/2},{x:i/2,y:0},{x:0,y:-i/2},{x:-i/2,y:0}];return a.insert("polygon",":first-child").attr("points",l.map(function(r){return r.x+","+r.y}).join(" ")).attr("class","state-start").attr("r",7).attr("width",28).attr("height",28),t.width=28,t.height=28,t.intersect=function(r){return T.circle(t,14,r)},a},"choice"),_r=d(async(e,t)=>{let{shapeSvg:a,bbox:i}=await A(e,t,Y(t,void 0),!0),l=4,s=i.height+t.padding,r=s/l,n=i.width+2*r+t.padding,c=[{x:r,y:0},{x:n-r,y:0},{x:n,y:-s/2},{x:n-r,y:-s},{x:r,y:-s},{x:0,y:-s/2}],u=j(a,n,s,c);return u.attr("style",t.style),B(t,u),t.intersect=function(o){return T.polygon(t,c,o)},a},"hexagon"),Dr=d(async(e,t)=>{let{shapeSvg:a,bbox:i}=await A(e,t,void 0,!0),l=2,s=i.height+2*t.padding,r=s/l,n=i.width+2*r+t.padding,c=br(t.directions,i,t),u=j(a,n,s,c);return u.attr("style",t.style),B(t,u),t.intersect=function(o){return T.polygon(t,c,o)},a},"block_arrow"),Nr=d(async(e,t)=>{let{shapeSvg:a,bbox:i}=await A(e,t,Y(t,void 0),!0),l=i.width+t.padding,s=i.height+t.padding,r=[{x:-s/2,y:0},{x:l,y:0},{x:l,y:-s},{x:-s/2,y:-s},{x:0,y:-s/2}];return j(a,l,s,r).attr("style",t.style),t.width=l+s,t.height=s,t.intersect=function(c){return T.polygon(t,r,c)},a},"rect_left_inv_arrow"),Tr=d(async(e,t)=>{let{shapeSvg:a,bbox:i}=await A(e,t,Y(t),!0),l=i.width+t.padding,s=i.height+t.padding,r=[{x:-2*s/6,y:0},{x:l-s/6,y:0},{x:l+2*s/6,y:-s},{x:s/6,y:-s}],n=j(a,l,s,r);return n.attr("style",t.style),B(t,n),t.intersect=function(c){return T.polygon(t,r,c)},a},"lean_right"),Br=d(async(e,t)=>{let{shapeSvg:a,bbox:i}=await A(e,t,Y(t,void 0),!0),l=i.width+t.padding,s=i.height+t.padding,r=[{x:2*s/6,y:0},{x:l+s/6,y:0},{x:l-2*s/6,y:-s},{x:-s/6,y:-s}],n=j(a,l,s,r);return n.attr("style",t.style),B(t,n),t.intersect=function(c){return T.polygon(t,r,c)},a},"lean_left"),Cr=d(async(e,t)=>{let{shapeSvg:a,bbox:i}=await A(e,t,Y(t,void 0),!0),l=i.width+t.padding,s=i.height+t.padding,r=[{x:-2*s/6,y:0},{x:l+2*s/6,y:0},{x:l-s/6,y:-s},{x:s/6,y:-s}],n=j(a,l,s,r);return n.attr("style",t.style),B(t,n),t.intersect=function(c){return T.polygon(t,r,c)},a},"trapezoid"),Ir=d(async(e,t)=>{let{shapeSvg:a,bbox:i}=await A(e,t,Y(t,void 0),!0),l=i.width+t.padding,s=i.height+t.padding,r=[{x:s/6,y:0},{x:l-s/6,y:0},{x:l+2*s/6,y:-s},{x:-2*s/6,y:-s}],n=j(a,l,s,r);return n.attr("style",t.style),B(t,n),t.intersect=function(c){return T.polygon(t,r,c)},a},"inv_trapezoid"),Or=d(async(e,t)=>{let{shapeSvg:a,bbox:i}=await A(e,t,Y(t,void 0),!0),l=i.width+t.padding,s=i.height+t.padding,r=[{x:0,y:0},{x:l+s/2,y:0},{x:l,y:-s/2},{x:l+s/2,y:-s},{x:0,y:-s}],n=j(a,l,s,r);return n.attr("style",t.style),B(t,n),t.intersect=function(c){return T.polygon(t,r,c)},a},"rect_right_inv_arrow"),Rr=d(async(e,t)=>{let{shapeSvg:a,bbox:i}=await A(e,t,Y(t,void 0),!0),l=i.width+t.padding,s=l/2,r=s/(2.5+l/50),n=i.height+r+t.padding,c="M 0,"+r+" a "+s+","+r+" 0,0,0 "+l+" 0 a "+s+","+r+" 0,0,0 "+-l+" 0 l 0,"+n+" a "+s+","+r+" 0,0,0 "+l+" 0 l 0,"+-n,u=a.attr("label-offset-y",r).insert("path",":first-child").attr("style",t.style).attr("d",c).attr("transform","translate("+-l/2+","+-(n/2+r)+")");return B(t,u),t.intersect=function(o){let b=T.rect(t,o),m=b.x-t.x;if(s!=0&&(Math.abs(m)t.height/2-r)){let y=r*r*(1-m*m/(s*s));y!=0&&(y=Math.sqrt(y)),y=r-y,o.y-t.y>0&&(y=-y),b.y+=y}return b},a},"cylinder"),zr=d(async(e,t)=>{let{shapeSvg:a,bbox:i,halfPadding:l}=await A(e,t,"node "+t.classes+" "+t.class,!0),s=a.insert("rect",":first-child"),r=t.positioned?t.width:i.width+t.padding,n=t.positioned?t.height:i.height+t.padding,c=t.positioned?-r/2:-i.width/2-l,u=t.positioned?-n/2:-i.height/2-l;if(s.attr("class","basic label-container").attr("style",t.style).attr("rx",t.rx).attr("ry",t.ry).attr("x",c).attr("y",u).attr("width",r).attr("height",n),t.props){let o=new Set(Object.keys(t.props));t.props.borders&&(gt(s,t.props.borders,r,n),o.delete("borders")),o.forEach(b=>{w.warn(`Unknown node property ${b}`)})}return B(t,s),t.intersect=function(o){return T.rect(t,o)},a},"rect"),Ar=d(async(e,t)=>{let{shapeSvg:a,bbox:i,halfPadding:l}=await A(e,t,"node "+t.classes,!0),s=a.insert("rect",":first-child"),r=t.positioned?t.width:i.width+t.padding,n=t.positioned?t.height:i.height+t.padding,c=t.positioned?-r/2:-i.width/2-l,u=t.positioned?-n/2:-i.height/2-l;if(s.attr("class","basic cluster composite label-container").attr("style",t.style).attr("rx",t.rx).attr("ry",t.ry).attr("x",c).attr("y",u).attr("width",r).attr("height",n),t.props){let o=new Set(Object.keys(t.props));t.props.borders&&(gt(s,t.props.borders,r,n),o.delete("borders")),o.forEach(b=>{w.warn(`Unknown node property ${b}`)})}return B(t,s),t.intersect=function(o){return T.rect(t,o)},a},"composite"),Mr=d(async(e,t)=>{let{shapeSvg:a}=await A(e,t,"label",!0);w.trace("Classes = ",t.class);let i=a.insert("rect",":first-child"),l=0,s=0;if(i.attr("width",l).attr("height",s),a.attr("class","label edgeLabel"),t.props){let r=new Set(Object.keys(t.props));t.props.borders&&(gt(i,t.props.borders,l,s),r.delete("borders")),r.forEach(n=>{w.warn(`Unknown node property ${n}`)})}return B(t,i),t.intersect=function(r){return T.rect(t,r)},a},"labelRect");function gt(e,t,a,i){let l=[],s=d(n=>{l.push(n,0)},"addBorder"),r=d(n=>{l.push(0,n)},"skipBorder");t.includes("t")?(w.debug("add top border"),s(a)):r(a),t.includes("r")?(w.debug("add right border"),s(i)):r(i),t.includes("b")?(w.debug("add bottom border"),s(a)):r(a),t.includes("l")?(w.debug("add left border"),s(i)):r(i),e.attr("stroke-dasharray",l.join(" "))}d(gt,"applyNodePropertyBorders");var Fr=d(async(e,t)=>{let a;t.classes?a="node "+t.classes:a="node default";let i=e.insert("g").attr("class",a).attr("id",t.domId||t.id),l=i.insert("rect",":first-child"),s=i.insert("line"),r=i.insert("g").attr("class","label"),n=t.labelText.flat?t.labelText.flat():t.labelText,c="";typeof n=="object"?c=n[0]:c=n,w.info("Label text abc79",c,n,typeof n=="object");let u=r.node().appendChild(await K(c,t.labelStyle,!0,!0)),o={width:0,height:0};if(X(I().flowchart.htmlLabels)){let E=u.children[0],S=N(u);o=E.getBoundingClientRect(),S.attr("width",o.width),S.attr("height",o.height)}w.info("Text 2",n);let b=n.slice(1,n.length),m=u.getBBox(),y=r.node().appendChild(await K(b.join?b.join("
"):b,t.labelStyle,!0,!0));if(X(I().flowchart.htmlLabels)){let E=y.children[0],S=N(y);o=E.getBoundingClientRect(),S.attr("width",o.width),S.attr("height",o.height)}let L=t.padding/2;return N(y).attr("transform","translate( "+(o.width>m.width?0:(m.width-o.width)/2)+", "+(m.height+L+5)+")"),N(u).attr("transform","translate( "+(o.width{let{shapeSvg:a,bbox:i}=await A(e,t,Y(t,void 0),!0),l=i.height+t.padding,s=i.width+l/4+t.padding,r=a.insert("rect",":first-child").attr("style",t.style).attr("rx",l/2).attr("ry",l/2).attr("x",-s/2).attr("y",-l/2).attr("width",s).attr("height",l);return B(t,r),t.intersect=function(n){return T.rect(t,n)},a},"stadium"),Pr=d(async(e,t)=>{let{shapeSvg:a,bbox:i,halfPadding:l}=await A(e,t,Y(t,void 0),!0),s=a.insert("circle",":first-child");return s.attr("style",t.style).attr("rx",t.rx).attr("ry",t.ry).attr("r",i.width/2+l).attr("width",i.width+t.padding).attr("height",i.height+t.padding),w.info("Circle main"),B(t,s),t.intersect=function(r){return w.info("Circle intersect",t,i.width/2+l,r),T.circle(t,i.width/2+l,r)},a},"circle"),Yr=d(async(e,t)=>{let{shapeSvg:a,bbox:i,halfPadding:l}=await A(e,t,Y(t,void 0),!0),s=5,r=a.insert("g",":first-child"),n=r.insert("circle"),c=r.insert("circle");return r.attr("class",t.class),n.attr("style",t.style).attr("rx",t.rx).attr("ry",t.ry).attr("r",i.width/2+l+s).attr("width",i.width+t.padding+s*2).attr("height",i.height+t.padding+s*2),c.attr("style",t.style).attr("rx",t.rx).attr("ry",t.ry).attr("r",i.width/2+l).attr("width",i.width+t.padding).attr("height",i.height+t.padding),w.info("DoubleCircle main"),B(t,n),t.intersect=function(u){return w.info("DoubleCircle intersect",t,i.width/2+l+s,u),T.circle(t,i.width/2+l+s,u)},a},"doublecircle"),Hr=d(async(e,t)=>{let{shapeSvg:a,bbox:i}=await A(e,t,Y(t,void 0),!0),l=i.width+t.padding,s=i.height+t.padding,r=[{x:0,y:0},{x:l,y:0},{x:l,y:-s},{x:0,y:-s},{x:0,y:0},{x:-8,y:0},{x:l+8,y:0},{x:l+8,y:-s},{x:-8,y:-s},{x:-8,y:0}],n=j(a,l,s,r);return n.attr("style",t.style),B(t,n),t.intersect=function(c){return T.polygon(t,r,c)},a},"subroutine"),Kr=d((e,t)=>{let a=e.insert("g").attr("class","node default").attr("id",t.domId||t.id),i=a.insert("circle",":first-child");return i.attr("class","state-start").attr("r",7).attr("width",14).attr("height",14),B(t,i),t.intersect=function(l){return T.circle(t,7,l)},a},"start"),ee=d((e,t,a)=>{let i=e.insert("g").attr("class","node default").attr("id",t.domId||t.id),l=70,s=10;a==="LR"&&(l=10,s=70);let r=i.append("rect").attr("x",-1*l/2).attr("y",-1*s/2).attr("width",l).attr("height",s).attr("class","fork-join");return B(t,r),t.height=t.height+t.padding/2,t.width=t.width+t.padding/2,t.intersect=function(n){return T.rect(t,n)},i},"forkJoin"),Xr=d((e,t)=>{let a=e.insert("g").attr("class","node default").attr("id",t.domId||t.id),i=a.insert("circle",":first-child"),l=a.insert("circle",":first-child");return l.attr("class","state-start").attr("r",7).attr("width",14).attr("height",14),i.attr("class","state-end").attr("r",5).attr("width",10).attr("height",10),B(t,l),t.intersect=function(s){return T.circle(t,7,s)},a},"end"),Ur=d(async(e,t)=>{let a=t.padding/2,i=4,l=8,s;t.classes?s="node "+t.classes:s="node default";let r=e.insert("g").attr("class",s).attr("id",t.domId||t.id),n=r.insert("rect",":first-child"),c=r.insert("line"),u=r.insert("line"),o=0,b=i,m=r.insert("g").attr("class","label"),y=0,L=t.classData.annotations?.[0],E=t.classData.annotations[0]?"\xAB"+t.classData.annotations[0]+"\xBB":"",S=m.node().appendChild(await K(E,t.labelStyle,!0,!0)),C=S.getBBox();if(X(I().flowchart.htmlLabels)){let v=S.children[0],h=N(S);C=v.getBoundingClientRect(),h.attr("width",C.width),h.attr("height",C.height)}t.classData.annotations[0]&&(b+=C.height+i,o+=C.width);let _=t.classData.label;t.classData.type!==void 0&&t.classData.type!==""&&(I().flowchart.htmlLabels?_+="<"+t.classData.type+">":_+="<"+t.classData.type+">");let D=m.node().appendChild(await K(_,t.labelStyle,!0,!0));N(D).attr("class","classTitle");let x=D.getBBox();if(X(I().flowchart.htmlLabels)){let v=D.children[0],h=N(D);x=v.getBoundingClientRect(),h.attr("width",x.width),h.attr("height",x.height)}b+=x.height+i,x.width>o&&(o=x.width);let g=[];t.classData.members.forEach(async v=>{let h=v.getDisplayDetails(),W=h.displayText;I().flowchart.htmlLabels&&(W=W.replace(//g,">"));let p=m.node().appendChild(await K(W,h.cssStyle?h.cssStyle:t.labelStyle,!0,!0)),R=p.getBBox();if(X(I().flowchart.htmlLabels)){let G=p.children[0],V=N(p);R=G.getBoundingClientRect(),V.attr("width",R.width),V.attr("height",R.height)}R.width>o&&(o=R.width),b+=R.height+i,g.push(p)}),b+=l;let f=[];if(t.classData.methods.forEach(async v=>{let h=v.getDisplayDetails(),W=h.displayText;I().flowchart.htmlLabels&&(W=W.replace(//g,">"));let p=m.node().appendChild(await K(W,h.cssStyle?h.cssStyle:t.labelStyle,!0,!0)),R=p.getBBox();if(X(I().flowchart.htmlLabels)){let G=p.children[0],V=N(p);R=G.getBoundingClientRect(),V.attr("width",R.width),V.attr("height",R.height)}R.width>o&&(o=R.width),b+=R.height+i,f.push(p)}),b+=l,L){let v=(o-C.width)/2;N(S).attr("transform","translate( "+(-1*o/2+v)+", "+-1*b/2+")"),y=C.height+i}let k=(o-x.width)/2;return N(D).attr("transform","translate( "+(-1*o/2+k)+", "+(-1*b/2+y)+")"),y+=x.height+i,c.attr("class","divider").attr("x1",-o/2-a).attr("x2",o/2+a).attr("y1",-b/2-a+l+y).attr("y2",-b/2-a+l+y),y+=l,g.forEach(v=>{N(v).attr("transform","translate( "+-o/2+", "+(-1*b/2+y+l/2)+")");let h=v?.getBBox();y+=(h?.height??0)+i}),y+=l,u.attr("class","divider").attr("x1",-o/2-a).attr("x2",o/2+a).attr("y1",-b/2-a+l+y).attr("y2",-b/2-a+l+y),y+=l,f.forEach(v=>{N(v).attr("transform","translate( "+-o/2+", "+(-1*b/2+y)+")");let h=v?.getBBox();y+=(h?.height??0)+i}),n.attr("style",t.style).attr("class","outer title-state").attr("x",-o/2-a).attr("y",-(b/2)-a).attr("width",o+t.padding).attr("height",b+t.padding),B(t,n),t.intersect=function(v){return T.rect(t,v)},r},"class_box"),re={rhombus:te,composite:Ar,question:te,rect:zr,labelRect:Mr,rectWithTitle:Fr,choice:Er,circle:Pr,doublecircle:Yr,stadium:Wr,hexagon:_r,block_arrow:Dr,rect_left_inv_arrow:Nr,lean_right:Tr,lean_left:Br,trapezoid:Cr,inv_trapezoid:Ir,rect_right_inv_arrow:Or,cylinder:Rr,start:Kr,end:Xr,note:vr,subroutine:Hr,fork:ee,join:ee,class_box:Ur},ot={},xe=d(async(e,t,a)=>{let i,l;if(t.link){let s;I().securityLevel==="sandbox"?s="_top":t.linkTarget&&(s=t.linkTarget||"_blank"),i=e.insert("svg:a").attr("xlink:href",t.link).attr("target",s),l=await re[t.shape](i,t,a)}else l=await re[t.shape](e,t,a),i=l;return t.tooltip&&l.attr("title",t.tooltip),t.class&&l.attr("class","node default "+t.class),ot[t.id]=i,t.haveCallback&&ot[t.id].attr("class",ot[t.id].attr("class")+" clickable"),i},"insertNode"),jr=d(e=>{let t=ot[e.id];w.trace("Transforming node",e.diff,e,"translate("+(e.x-e.width/2-5)+", "+e.width/2+")");let a=8,i=e.diff||0;return e.clusterNode?t.attr("transform","translate("+(e.x+i-e.width/2)+", "+(e.y-e.height/2-a)+")"):t.attr("transform","translate("+e.x+", "+e.y+")"),i},"positionNode");function Tt(e,t,a=!1){let i=e,l="default";(i?.classes?.length||0)>0&&(l=(i?.classes??[]).join(" ")),l=l+" flowchart-label";let s=0,r="",n;switch(i.type){case"round":s=5,r="rect";break;case"composite":s=0,r="composite",n=0;break;case"square":r="rect";break;case"diamond":r="question";break;case"hexagon":r="hexagon";break;case"block_arrow":r="block_arrow";break;case"odd":r="rect_left_inv_arrow";break;case"lean_right":r="lean_right";break;case"lean_left":r="lean_left";break;case"trapezoid":r="trapezoid";break;case"inv_trapezoid":r="inv_trapezoid";break;case"rect_left_inv_arrow":r="rect_left_inv_arrow";break;case"circle":r="circle";break;case"ellipse":r="ellipse";break;case"stadium":r="stadium";break;case"subroutine":r="subroutine";break;case"cylinder":r="cylinder";break;case"group":r="rect";break;case"doublecircle":r="doublecircle";break;default:r="rect"}let c=Kt(i?.styles??[]),u=i.label,o=i.size??{width:0,height:0,x:0,y:0};return{labelStyle:c.labelStyle,shape:r,labelText:u,rx:s,ry:s,class:l,style:c.style,id:i.id,directions:i.directions,width:o.width,height:o.height,x:o.x,y:o.y,positioned:a,intersect:void 0,type:i.type,padding:n??$()?.block?.padding??0}}d(Tt,"getNodeFromBlock");async function ye(e,t,a){let i=Tt(t,a,!1);if(i.type==="group")return;let l=$(),s=await xe(e,i,{config:l}),r=s.node().getBBox(),n=a.getBlock(i.id);n.size={width:r.width,height:r.height,x:0,y:0,node:s},a.setBlock(n),s.remove()}d(ye,"calculateBlockSize");async function me(e,t,a){let i=Tt(t,a,!0);if(a.getBlock(i.id).type!=="space"){let s=$();await xe(e,i,{config:s}),t.intersect=i?.intersect,jr(i)}}d(me,"insertBlockPositioned");async function ut(e,t,a,i){for(let l of t)await i(e,l,a),l.children&&await ut(e,l.children,a,i)}d(ut,"performOperations");async function we(e,t,a){await ut(e,t,a,ye)}d(we,"calculateBlockSizes");async function ke(e,t,a){await ut(e,t,a,me)}d(ke,"insertBlocks");async function Le(e,t,a,i,l){let s=new jt({multigraph:!0,compound:!0});s.setGraph({rankdir:"TB",nodesep:10,ranksep:10,marginx:8,marginy:8});for(let r of a)r.size&&s.setNode(r.id,{width:r.size.width,height:r.size.height,intersect:r.intersect});for(let r of t)if(r.start&&r.end){let n=i.getBlock(r.start),c=i.getBlock(r.end);if(n?.size&&c?.size){let u=n.size,o=c.size,b=[{x:u.x,y:u.y},{x:u.x+(o.x-u.x)/2,y:u.y+(o.y-u.y)/2},{x:o.x,y:o.y}];pr(e,{v:r.start,w:r.end,name:r.id},{...r,arrowTypeEnd:r.arrowTypeEnd,arrowTypeStart:r.arrowTypeStart,points:b,classes:"edge-thickness-normal edge-pattern-solid flowchart-link LS-a1 LE-b1"},void 0,"block",s,l),r.label&&(await hr(e,{...r,label:r.label,labelStyle:"stroke: #333; stroke-width: 1.5px;fill:none;",arrowTypeEnd:r.arrowTypeEnd,arrowTypeStart:r.arrowTypeStart,points:b,classes:"edge-thickness-normal edge-pattern-solid flowchart-link LS-a1 LE-b1"}),dr({...r,x:b[1].x,y:b[1].y},{originalPath:b}))}}}d(Le,"insertEdges");var Vr=d(function(e,t){return t.db.getClasses()},"getClasses"),Zr=d(async function(e,t,a,i){let{securityLevel:l,block:s}=$(),r=i.db,n;l==="sandbox"&&(n=N("#i"+t));let c=l==="sandbox"?N(n.nodes()[0].contentDocument.body):N("body"),u=l==="sandbox"?c.select(`[id="${t}"]`):N(`[id="${t}"]`);ir(u,["point","circle","cross"],i.type,t);let b=r.getBlocks(),m=r.getBlocksFlat(),y=r.getEdges(),L=u.insert("g").attr("class","block");await we(L,b,r);let E=oe(r);if(await ke(L,b,r),await Le(L,y,m,r,t),E){let S=E,C=Math.max(1,Math.round(.125*(S.width/S.height))),_=S.height+C+10,D=S.width+10,{useMaxWidth:x}=s;Mt(u,_,D,!!x),w.debug("Here Bounds",E,S),u.attr("viewBox",`${S.x-5} ${S.y-5} ${S.width+10} ${S.height+10}`)}},"draw"),Gr={draw:Zr,getClasses:Vr},ga={parser:_e,db:Ue,renderer:Gr,styles:Ve};export{ga as diagram}; +//# sourceMappingURL=blockDiagram-VD42YOAC-VWWETFZB.min.js.map diff --git a/docs/website/public/blockDiagram-VD42YOAC-VWWETFZB.min.js.map b/docs/website/public/blockDiagram-VD42YOAC-VWWETFZB.min.js.map new file mode 100644 index 000000000..974b81245 --- /dev/null +++ b/docs/website/public/blockDiagram-VD42YOAC-VWWETFZB.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/mermaid/dist/chunks/mermaid.core/blockDiagram-VD42YOAC.mjs"], + "sourcesContent": ["import {\n getIconStyles\n} from \"./chunk-FMBD7UC4.mjs\";\nimport {\n getLineFunctionsWithOffset\n} from \"./chunk-HN2XXSSU.mjs\";\nimport {\n getSubGraphTitleMargins\n} from \"./chunk-CVBHYZKI.mjs\";\nimport {\n createText,\n replaceIconSubstring\n} from \"./chunk-JA3XYJ7Z.mjs\";\nimport {\n decodeEntities,\n getStylesFromArray,\n utils_default\n} from \"./chunk-S3R3BYOJ.mjs\";\nimport {\n clear,\n common_default,\n configureSvgSize,\n evaluate,\n getConfig,\n getConfig2,\n getUrl,\n sanitizeText\n} from \"./chunk-ABZYJK2D.mjs\";\nimport {\n __name,\n log\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/diagrams/block/parser/block.jison\nvar parser = (function() {\n var o = /* @__PURE__ */ __name(function(k, v, o2, l) {\n for (o2 = o2 || {}, l = k.length; l--; o2[k[l]] = v) ;\n return o2;\n }, \"o\"), $V0 = [1, 15], $V1 = [1, 7], $V2 = [1, 13], $V3 = [1, 14], $V4 = [1, 19], $V5 = [1, 16], $V6 = [1, 17], $V7 = [1, 18], $V8 = [8, 30], $V9 = [8, 10, 21, 28, 29, 30, 31, 39, 43, 46], $Va = [1, 23], $Vb = [1, 24], $Vc = [8, 10, 15, 16, 21, 28, 29, 30, 31, 39, 43, 46], $Vd = [8, 10, 15, 16, 21, 27, 28, 29, 30, 31, 39, 43, 46], $Ve = [1, 49];\n var parser2 = {\n trace: /* @__PURE__ */ __name(function trace() {\n }, \"trace\"),\n yy: {},\n symbols_: { \"error\": 2, \"spaceLines\": 3, \"SPACELINE\": 4, \"NL\": 5, \"separator\": 6, \"SPACE\": 7, \"EOF\": 8, \"start\": 9, \"BLOCK_DIAGRAM_KEY\": 10, \"document\": 11, \"stop\": 12, \"statement\": 13, \"link\": 14, \"LINK\": 15, \"START_LINK\": 16, \"LINK_LABEL\": 17, \"STR\": 18, \"nodeStatement\": 19, \"columnsStatement\": 20, \"SPACE_BLOCK\": 21, \"blockStatement\": 22, \"classDefStatement\": 23, \"cssClassStatement\": 24, \"styleStatement\": 25, \"node\": 26, \"SIZE\": 27, \"COLUMNS\": 28, \"id-block\": 29, \"end\": 30, \"NODE_ID\": 31, \"nodeShapeNLabel\": 32, \"dirList\": 33, \"DIR\": 34, \"NODE_DSTART\": 35, \"NODE_DEND\": 36, \"BLOCK_ARROW_START\": 37, \"BLOCK_ARROW_END\": 38, \"classDef\": 39, \"CLASSDEF_ID\": 40, \"CLASSDEF_STYLEOPTS\": 41, \"DEFAULT\": 42, \"class\": 43, \"CLASSENTITY_IDS\": 44, \"STYLECLASS\": 45, \"style\": 46, \"STYLE_ENTITY_IDS\": 47, \"STYLE_DEFINITION_DATA\": 48, \"$accept\": 0, \"$end\": 1 },\n terminals_: { 2: \"error\", 4: \"SPACELINE\", 5: \"NL\", 7: \"SPACE\", 8: \"EOF\", 10: \"BLOCK_DIAGRAM_KEY\", 15: \"LINK\", 16: \"START_LINK\", 17: \"LINK_LABEL\", 18: \"STR\", 21: \"SPACE_BLOCK\", 27: \"SIZE\", 28: \"COLUMNS\", 29: \"id-block\", 30: \"end\", 31: \"NODE_ID\", 34: \"DIR\", 35: \"NODE_DSTART\", 36: \"NODE_DEND\", 37: \"BLOCK_ARROW_START\", 38: \"BLOCK_ARROW_END\", 39: \"classDef\", 40: \"CLASSDEF_ID\", 41: \"CLASSDEF_STYLEOPTS\", 42: \"DEFAULT\", 43: \"class\", 44: \"CLASSENTITY_IDS\", 45: \"STYLECLASS\", 46: \"style\", 47: \"STYLE_ENTITY_IDS\", 48: \"STYLE_DEFINITION_DATA\" },\n productions_: [0, [3, 1], [3, 2], [3, 2], [6, 1], [6, 1], [6, 1], [9, 3], [12, 1], [12, 1], [12, 2], [12, 2], [11, 1], [11, 2], [14, 1], [14, 4], [13, 1], [13, 1], [13, 1], [13, 1], [13, 1], [13, 1], [13, 1], [19, 3], [19, 2], [19, 1], [20, 1], [22, 4], [22, 3], [26, 1], [26, 2], [33, 1], [33, 2], [32, 3], [32, 4], [23, 3], [23, 3], [24, 3], [25, 3]],\n performAction: /* @__PURE__ */ __name(function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$) {\n var $0 = $$.length - 1;\n switch (yystate) {\n case 4:\n yy.getLogger().debug(\"Rule: separator (NL) \");\n break;\n case 5:\n yy.getLogger().debug(\"Rule: separator (Space) \");\n break;\n case 6:\n yy.getLogger().debug(\"Rule: separator (EOF) \");\n break;\n case 7:\n yy.getLogger().debug(\"Rule: hierarchy: \", $$[$0 - 1]);\n yy.setHierarchy($$[$0 - 1]);\n break;\n case 8:\n yy.getLogger().debug(\"Stop NL \");\n break;\n case 9:\n yy.getLogger().debug(\"Stop EOF \");\n break;\n case 10:\n yy.getLogger().debug(\"Stop NL2 \");\n break;\n case 11:\n yy.getLogger().debug(\"Stop EOF2 \");\n break;\n case 12:\n yy.getLogger().debug(\"Rule: statement: \", $$[$0]);\n typeof $$[$0].length === \"number\" ? this.$ = $$[$0] : this.$ = [$$[$0]];\n break;\n case 13:\n yy.getLogger().debug(\"Rule: statement #2: \", $$[$0 - 1]);\n this.$ = [$$[$0 - 1]].concat($$[$0]);\n break;\n case 14:\n yy.getLogger().debug(\"Rule: link: \", $$[$0], yytext);\n this.$ = { edgeTypeStr: $$[$0], label: \"\" };\n break;\n case 15:\n yy.getLogger().debug(\"Rule: LABEL link: \", $$[$0 - 3], $$[$0 - 1], $$[$0]);\n this.$ = { edgeTypeStr: $$[$0], label: $$[$0 - 1] };\n break;\n case 18:\n const num = parseInt($$[$0]);\n const spaceId = yy.generateId();\n this.$ = { id: spaceId, type: \"space\", label: \"\", width: num, children: [] };\n break;\n case 23:\n yy.getLogger().debug(\"Rule: (nodeStatement link node) \", $$[$0 - 2], $$[$0 - 1], $$[$0], \" typestr: \", $$[$0 - 1].edgeTypeStr);\n const edgeData = yy.edgeStrToEdgeData($$[$0 - 1].edgeTypeStr);\n this.$ = [\n { id: $$[$0 - 2].id, label: $$[$0 - 2].label, type: $$[$0 - 2].type, directions: $$[$0 - 2].directions },\n { id: $$[$0 - 2].id + \"-\" + $$[$0].id, start: $$[$0 - 2].id, end: $$[$0].id, label: $$[$0 - 1].label, type: \"edge\", directions: $$[$0].directions, arrowTypeEnd: edgeData, arrowTypeStart: \"arrow_open\" },\n { id: $$[$0].id, label: $$[$0].label, type: yy.typeStr2Type($$[$0].typeStr), directions: $$[$0].directions }\n ];\n break;\n case 24:\n yy.getLogger().debug(\"Rule: nodeStatement (abc88 node size) \", $$[$0 - 1], $$[$0]);\n this.$ = { id: $$[$0 - 1].id, label: $$[$0 - 1].label, type: yy.typeStr2Type($$[$0 - 1].typeStr), directions: $$[$0 - 1].directions, widthInColumns: parseInt($$[$0], 10) };\n break;\n case 25:\n yy.getLogger().debug(\"Rule: nodeStatement (node) \", $$[$0]);\n this.$ = { id: $$[$0].id, label: $$[$0].label, type: yy.typeStr2Type($$[$0].typeStr), directions: $$[$0].directions, widthInColumns: 1 };\n break;\n case 26:\n yy.getLogger().debug(\"APA123\", this ? this : \"na\");\n yy.getLogger().debug(\"COLUMNS: \", $$[$0]);\n this.$ = { type: \"column-setting\", columns: $$[$0] === \"auto\" ? -1 : parseInt($$[$0]) };\n break;\n case 27:\n yy.getLogger().debug(\"Rule: id-block statement : \", $$[$0 - 2], $$[$0 - 1]);\n const id2 = yy.generateId();\n this.$ = { ...$$[$0 - 2], type: \"composite\", children: $$[$0 - 1] };\n break;\n case 28:\n yy.getLogger().debug(\"Rule: blockStatement : \", $$[$0 - 2], $$[$0 - 1], $$[$0]);\n const id = yy.generateId();\n this.$ = { id, type: \"composite\", label: \"\", children: $$[$0 - 1] };\n break;\n case 29:\n yy.getLogger().debug(\"Rule: node (NODE_ID separator): \", $$[$0]);\n this.$ = { id: $$[$0] };\n break;\n case 30:\n yy.getLogger().debug(\"Rule: node (NODE_ID nodeShapeNLabel separator): \", $$[$0 - 1], $$[$0]);\n this.$ = { id: $$[$0 - 1], label: $$[$0].label, typeStr: $$[$0].typeStr, directions: $$[$0].directions };\n break;\n case 31:\n yy.getLogger().debug(\"Rule: dirList: \", $$[$0]);\n this.$ = [$$[$0]];\n break;\n case 32:\n yy.getLogger().debug(\"Rule: dirList: \", $$[$0 - 1], $$[$0]);\n this.$ = [$$[$0 - 1]].concat($$[$0]);\n break;\n case 33:\n yy.getLogger().debug(\"Rule: nodeShapeNLabel: \", $$[$0 - 2], $$[$0 - 1], $$[$0]);\n this.$ = { typeStr: $$[$0 - 2] + $$[$0], label: $$[$0 - 1] };\n break;\n case 34:\n yy.getLogger().debug(\"Rule: BLOCK_ARROW nodeShapeNLabel: \", $$[$0 - 3], $$[$0 - 2], \" #3:\", $$[$0 - 1], $$[$0]);\n this.$ = { typeStr: $$[$0 - 3] + $$[$0], label: $$[$0 - 2], directions: $$[$0 - 1] };\n break;\n case 35:\n case 36:\n this.$ = { type: \"classDef\", id: $$[$0 - 1].trim(), css: $$[$0].trim() };\n break;\n case 37:\n this.$ = { type: \"applyClass\", id: $$[$0 - 1].trim(), styleClass: $$[$0].trim() };\n break;\n case 38:\n this.$ = { type: \"applyStyles\", id: $$[$0 - 1].trim(), stylesStr: $$[$0].trim() };\n break;\n }\n }, \"anonymous\"),\n table: [{ 9: 1, 10: [1, 2] }, { 1: [3] }, { 10: $V0, 11: 3, 13: 4, 19: 5, 20: 6, 21: $V1, 22: 8, 23: 9, 24: 10, 25: 11, 26: 12, 28: $V2, 29: $V3, 31: $V4, 39: $V5, 43: $V6, 46: $V7 }, { 8: [1, 20] }, o($V8, [2, 12], { 13: 4, 19: 5, 20: 6, 22: 8, 23: 9, 24: 10, 25: 11, 26: 12, 11: 21, 10: $V0, 21: $V1, 28: $V2, 29: $V3, 31: $V4, 39: $V5, 43: $V6, 46: $V7 }), o($V9, [2, 16], { 14: 22, 15: $Va, 16: $Vb }), o($V9, [2, 17]), o($V9, [2, 18]), o($V9, [2, 19]), o($V9, [2, 20]), o($V9, [2, 21]), o($V9, [2, 22]), o($Vc, [2, 25], { 27: [1, 25] }), o($V9, [2, 26]), { 19: 26, 26: 12, 31: $V4 }, { 10: $V0, 11: 27, 13: 4, 19: 5, 20: 6, 21: $V1, 22: 8, 23: 9, 24: 10, 25: 11, 26: 12, 28: $V2, 29: $V3, 31: $V4, 39: $V5, 43: $V6, 46: $V7 }, { 40: [1, 28], 42: [1, 29] }, { 44: [1, 30] }, { 47: [1, 31] }, o($Vd, [2, 29], { 32: 32, 35: [1, 33], 37: [1, 34] }), { 1: [2, 7] }, o($V8, [2, 13]), { 26: 35, 31: $V4 }, { 31: [2, 14] }, { 17: [1, 36] }, o($Vc, [2, 24]), { 10: $V0, 11: 37, 13: 4, 14: 22, 15: $Va, 16: $Vb, 19: 5, 20: 6, 21: $V1, 22: 8, 23: 9, 24: 10, 25: 11, 26: 12, 28: $V2, 29: $V3, 31: $V4, 39: $V5, 43: $V6, 46: $V7 }, { 30: [1, 38] }, { 41: [1, 39] }, { 41: [1, 40] }, { 45: [1, 41] }, { 48: [1, 42] }, o($Vd, [2, 30]), { 18: [1, 43] }, { 18: [1, 44] }, o($Vc, [2, 23]), { 18: [1, 45] }, { 30: [1, 46] }, o($V9, [2, 28]), o($V9, [2, 35]), o($V9, [2, 36]), o($V9, [2, 37]), o($V9, [2, 38]), { 36: [1, 47] }, { 33: 48, 34: $Ve }, { 15: [1, 50] }, o($V9, [2, 27]), o($Vd, [2, 33]), { 38: [1, 51] }, { 33: 52, 34: $Ve, 38: [2, 31] }, { 31: [2, 15] }, o($Vd, [2, 34]), { 38: [2, 32] }],\n defaultActions: { 20: [2, 7], 23: [2, 14], 50: [2, 15], 52: [2, 32] },\n parseError: /* @__PURE__ */ __name(function parseError(str, hash) {\n if (hash.recoverable) {\n this.trace(str);\n } else {\n var error = new Error(str);\n error.hash = hash;\n throw error;\n }\n }, \"parseError\"),\n parse: /* @__PURE__ */ __name(function parse(input) {\n var self = this, stack = [0], tstack = [], vstack = [null], lstack = [], table = this.table, yytext = \"\", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;\n var args = lstack.slice.call(arguments, 1);\n var lexer2 = Object.create(this.lexer);\n var sharedState = { yy: {} };\n for (var k in this.yy) {\n if (Object.prototype.hasOwnProperty.call(this.yy, k)) {\n sharedState.yy[k] = this.yy[k];\n }\n }\n lexer2.setInput(input, sharedState.yy);\n sharedState.yy.lexer = lexer2;\n sharedState.yy.parser = this;\n if (typeof lexer2.yylloc == \"undefined\") {\n lexer2.yylloc = {};\n }\n var yyloc = lexer2.yylloc;\n lstack.push(yyloc);\n var ranges = lexer2.options && lexer2.options.ranges;\n if (typeof sharedState.yy.parseError === \"function\") {\n this.parseError = sharedState.yy.parseError;\n } else {\n this.parseError = Object.getPrototypeOf(this).parseError;\n }\n function popStack(n) {\n stack.length = stack.length - 2 * n;\n vstack.length = vstack.length - n;\n lstack.length = lstack.length - n;\n }\n __name(popStack, \"popStack\");\n function lex() {\n var token;\n token = tstack.pop() || lexer2.lex() || EOF;\n if (typeof token !== \"number\") {\n if (token instanceof Array) {\n tstack = token;\n token = tstack.pop();\n }\n token = self.symbols_[token] || token;\n }\n return token;\n }\n __name(lex, \"lex\");\n var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;\n while (true) {\n state = stack[stack.length - 1];\n if (this.defaultActions[state]) {\n action = this.defaultActions[state];\n } else {\n if (symbol === null || typeof symbol == \"undefined\") {\n symbol = lex();\n }\n action = table[state] && table[state][symbol];\n }\n if (typeof action === \"undefined\" || !action.length || !action[0]) {\n var errStr = \"\";\n expected = [];\n for (p in table[state]) {\n if (this.terminals_[p] && p > TERROR) {\n expected.push(\"'\" + this.terminals_[p] + \"'\");\n }\n }\n if (lexer2.showPosition) {\n errStr = \"Parse error on line \" + (yylineno + 1) + \":\\n\" + lexer2.showPosition() + \"\\nExpecting \" + expected.join(\", \") + \", got '\" + (this.terminals_[symbol] || symbol) + \"'\";\n } else {\n errStr = \"Parse error on line \" + (yylineno + 1) + \": Unexpected \" + (symbol == EOF ? \"end of input\" : \"'\" + (this.terminals_[symbol] || symbol) + \"'\");\n }\n this.parseError(errStr, {\n text: lexer2.match,\n token: this.terminals_[symbol] || symbol,\n line: lexer2.yylineno,\n loc: yyloc,\n expected\n });\n }\n if (action[0] instanceof Array && action.length > 1) {\n throw new Error(\"Parse Error: multiple actions possible at state: \" + state + \", token: \" + symbol);\n }\n switch (action[0]) {\n case 1:\n stack.push(symbol);\n vstack.push(lexer2.yytext);\n lstack.push(lexer2.yylloc);\n stack.push(action[1]);\n symbol = null;\n if (!preErrorSymbol) {\n yyleng = lexer2.yyleng;\n yytext = lexer2.yytext;\n yylineno = lexer2.yylineno;\n yyloc = lexer2.yylloc;\n if (recovering > 0) {\n recovering--;\n }\n } else {\n symbol = preErrorSymbol;\n preErrorSymbol = null;\n }\n break;\n case 2:\n len = this.productions_[action[1]][1];\n yyval.$ = vstack[vstack.length - len];\n yyval._$ = {\n first_line: lstack[lstack.length - (len || 1)].first_line,\n last_line: lstack[lstack.length - 1].last_line,\n first_column: lstack[lstack.length - (len || 1)].first_column,\n last_column: lstack[lstack.length - 1].last_column\n };\n if (ranges) {\n yyval._$.range = [\n lstack[lstack.length - (len || 1)].range[0],\n lstack[lstack.length - 1].range[1]\n ];\n }\n r = this.performAction.apply(yyval, [\n yytext,\n yyleng,\n yylineno,\n sharedState.yy,\n action[1],\n vstack,\n lstack\n ].concat(args));\n if (typeof r !== \"undefined\") {\n return r;\n }\n if (len) {\n stack = stack.slice(0, -1 * len * 2);\n vstack = vstack.slice(0, -1 * len);\n lstack = lstack.slice(0, -1 * len);\n }\n stack.push(this.productions_[action[1]][0]);\n vstack.push(yyval.$);\n lstack.push(yyval._$);\n newState = table[stack[stack.length - 2]][stack[stack.length - 1]];\n stack.push(newState);\n break;\n case 3:\n return true;\n }\n }\n return true;\n }, \"parse\")\n };\n var lexer = /* @__PURE__ */ (function() {\n var lexer2 = {\n EOF: 1,\n parseError: /* @__PURE__ */ __name(function parseError(str, hash) {\n if (this.yy.parser) {\n this.yy.parser.parseError(str, hash);\n } else {\n throw new Error(str);\n }\n }, \"parseError\"),\n // resets the lexer, sets new input\n setInput: /* @__PURE__ */ __name(function(input, yy) {\n this.yy = yy || this.yy || {};\n this._input = input;\n this._more = this._backtrack = this.done = false;\n this.yylineno = this.yyleng = 0;\n this.yytext = this.matched = this.match = \"\";\n this.conditionStack = [\"INITIAL\"];\n this.yylloc = {\n first_line: 1,\n first_column: 0,\n last_line: 1,\n last_column: 0\n };\n if (this.options.ranges) {\n this.yylloc.range = [0, 0];\n }\n this.offset = 0;\n return this;\n }, \"setInput\"),\n // consumes and returns one char from the input\n input: /* @__PURE__ */ __name(function() {\n var ch = this._input[0];\n this.yytext += ch;\n this.yyleng++;\n this.offset++;\n this.match += ch;\n this.matched += ch;\n var lines = ch.match(/(?:\\r\\n?|\\n).*/g);\n if (lines) {\n this.yylineno++;\n this.yylloc.last_line++;\n } else {\n this.yylloc.last_column++;\n }\n if (this.options.ranges) {\n this.yylloc.range[1]++;\n }\n this._input = this._input.slice(1);\n return ch;\n }, \"input\"),\n // unshifts one char (or a string) into the input\n unput: /* @__PURE__ */ __name(function(ch) {\n var len = ch.length;\n var lines = ch.split(/(?:\\r\\n?|\\n)/g);\n this._input = ch + this._input;\n this.yytext = this.yytext.substr(0, this.yytext.length - len);\n this.offset -= len;\n var oldLines = this.match.split(/(?:\\r\\n?|\\n)/g);\n this.match = this.match.substr(0, this.match.length - 1);\n this.matched = this.matched.substr(0, this.matched.length - 1);\n if (lines.length - 1) {\n this.yylineno -= lines.length - 1;\n }\n var r = this.yylloc.range;\n this.yylloc = {\n first_line: this.yylloc.first_line,\n last_line: this.yylineno + 1,\n first_column: this.yylloc.first_column,\n last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len\n };\n if (this.options.ranges) {\n this.yylloc.range = [r[0], r[0] + this.yyleng - len];\n }\n this.yyleng = this.yytext.length;\n return this;\n }, \"unput\"),\n // When called from action, caches matched text and appends it on next action\n more: /* @__PURE__ */ __name(function() {\n this._more = true;\n return this;\n }, \"more\"),\n // When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead.\n reject: /* @__PURE__ */ __name(function() {\n if (this.options.backtrack_lexer) {\n this._backtrack = true;\n } else {\n return this.parseError(\"Lexical error on line \" + (this.yylineno + 1) + \". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\\n\" + this.showPosition(), {\n text: \"\",\n token: null,\n line: this.yylineno\n });\n }\n return this;\n }, \"reject\"),\n // retain first n characters of the match\n less: /* @__PURE__ */ __name(function(n) {\n this.unput(this.match.slice(n));\n }, \"less\"),\n // displays already matched input, i.e. for error messages\n pastInput: /* @__PURE__ */ __name(function() {\n var past = this.matched.substr(0, this.matched.length - this.match.length);\n return (past.length > 20 ? \"...\" : \"\") + past.substr(-20).replace(/\\n/g, \"\");\n }, \"pastInput\"),\n // displays upcoming input, i.e. for error messages\n upcomingInput: /* @__PURE__ */ __name(function() {\n var next = this.match;\n if (next.length < 20) {\n next += this._input.substr(0, 20 - next.length);\n }\n return (next.substr(0, 20) + (next.length > 20 ? \"...\" : \"\")).replace(/\\n/g, \"\");\n }, \"upcomingInput\"),\n // displays the character position where the lexing error occurred, i.e. for error messages\n showPosition: /* @__PURE__ */ __name(function() {\n var pre = this.pastInput();\n var c = new Array(pre.length + 1).join(\"-\");\n return pre + this.upcomingInput() + \"\\n\" + c + \"^\";\n }, \"showPosition\"),\n // test the lexed token: return FALSE when not a match, otherwise return token\n test_match: /* @__PURE__ */ __name(function(match, indexed_rule) {\n var token, lines, backup;\n if (this.options.backtrack_lexer) {\n backup = {\n yylineno: this.yylineno,\n yylloc: {\n first_line: this.yylloc.first_line,\n last_line: this.last_line,\n first_column: this.yylloc.first_column,\n last_column: this.yylloc.last_column\n },\n yytext: this.yytext,\n match: this.match,\n matches: this.matches,\n matched: this.matched,\n yyleng: this.yyleng,\n offset: this.offset,\n _more: this._more,\n _input: this._input,\n yy: this.yy,\n conditionStack: this.conditionStack.slice(0),\n done: this.done\n };\n if (this.options.ranges) {\n backup.yylloc.range = this.yylloc.range.slice(0);\n }\n }\n lines = match[0].match(/(?:\\r\\n?|\\n).*/g);\n if (lines) {\n this.yylineno += lines.length;\n }\n this.yylloc = {\n first_line: this.yylloc.last_line,\n last_line: this.yylineno + 1,\n first_column: this.yylloc.last_column,\n last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\\r?\\n?/)[0].length : this.yylloc.last_column + match[0].length\n };\n this.yytext += match[0];\n this.match += match[0];\n this.matches = match;\n this.yyleng = this.yytext.length;\n if (this.options.ranges) {\n this.yylloc.range = [this.offset, this.offset += this.yyleng];\n }\n this._more = false;\n this._backtrack = false;\n this._input = this._input.slice(match[0].length);\n this.matched += match[0];\n token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]);\n if (this.done && this._input) {\n this.done = false;\n }\n if (token) {\n return token;\n } else if (this._backtrack) {\n for (var k in backup) {\n this[k] = backup[k];\n }\n return false;\n }\n return false;\n }, \"test_match\"),\n // return next match in input\n next: /* @__PURE__ */ __name(function() {\n if (this.done) {\n return this.EOF;\n }\n if (!this._input) {\n this.done = true;\n }\n var token, match, tempMatch, index;\n if (!this._more) {\n this.yytext = \"\";\n this.match = \"\";\n }\n var rules = this._currentRules();\n for (var i = 0; i < rules.length; i++) {\n tempMatch = this._input.match(this.rules[rules[i]]);\n if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {\n match = tempMatch;\n index = i;\n if (this.options.backtrack_lexer) {\n token = this.test_match(tempMatch, rules[i]);\n if (token !== false) {\n return token;\n } else if (this._backtrack) {\n match = false;\n continue;\n } else {\n return false;\n }\n } else if (!this.options.flex) {\n break;\n }\n }\n }\n if (match) {\n token = this.test_match(match, rules[index]);\n if (token !== false) {\n return token;\n }\n return false;\n }\n if (this._input === \"\") {\n return this.EOF;\n } else {\n return this.parseError(\"Lexical error on line \" + (this.yylineno + 1) + \". Unrecognized text.\\n\" + this.showPosition(), {\n text: \"\",\n token: null,\n line: this.yylineno\n });\n }\n }, \"next\"),\n // return next match that has a token\n lex: /* @__PURE__ */ __name(function lex() {\n var r = this.next();\n if (r) {\n return r;\n } else {\n return this.lex();\n }\n }, \"lex\"),\n // activates a new lexer condition state (pushes the new lexer condition state onto the condition stack)\n begin: /* @__PURE__ */ __name(function begin(condition) {\n this.conditionStack.push(condition);\n }, \"begin\"),\n // pop the previously active lexer condition state off the condition stack\n popState: /* @__PURE__ */ __name(function popState() {\n var n = this.conditionStack.length - 1;\n if (n > 0) {\n return this.conditionStack.pop();\n } else {\n return this.conditionStack[0];\n }\n }, \"popState\"),\n // produce the lexer rule set which is active for the currently active lexer condition state\n _currentRules: /* @__PURE__ */ __name(function _currentRules() {\n if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) {\n return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;\n } else {\n return this.conditions[\"INITIAL\"].rules;\n }\n }, \"_currentRules\"),\n // return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available\n topState: /* @__PURE__ */ __name(function topState(n) {\n n = this.conditionStack.length - 1 - Math.abs(n || 0);\n if (n >= 0) {\n return this.conditionStack[n];\n } else {\n return \"INITIAL\";\n }\n }, \"topState\"),\n // alias for begin(condition)\n pushState: /* @__PURE__ */ __name(function pushState(condition) {\n this.begin(condition);\n }, \"pushState\"),\n // return the number of states currently on the stack\n stateStackSize: /* @__PURE__ */ __name(function stateStackSize() {\n return this.conditionStack.length;\n }, \"stateStackSize\"),\n options: {},\n performAction: /* @__PURE__ */ __name(function anonymous(yy, yy_, $avoiding_name_collisions, YY_START) {\n var YYSTATE = YY_START;\n switch ($avoiding_name_collisions) {\n case 0:\n yy.getLogger().debug(\"Found block-beta\");\n return 10;\n break;\n case 1:\n yy.getLogger().debug(\"Found id-block\");\n return 29;\n break;\n case 2:\n yy.getLogger().debug(\"Found block\");\n return 10;\n break;\n case 3:\n yy.getLogger().debug(\".\", yy_.yytext);\n break;\n case 4:\n yy.getLogger().debug(\"_\", yy_.yytext);\n break;\n case 5:\n return 5;\n break;\n case 6:\n yy_.yytext = -1;\n return 28;\n break;\n case 7:\n yy_.yytext = yy_.yytext.replace(/columns\\s+/, \"\");\n yy.getLogger().debug(\"COLUMNS (LEX)\", yy_.yytext);\n return 28;\n break;\n case 8:\n this.pushState(\"md_string\");\n break;\n case 9:\n return \"MD_STR\";\n break;\n case 10:\n this.popState();\n break;\n case 11:\n this.pushState(\"string\");\n break;\n case 12:\n yy.getLogger().debug(\"LEX: POPPING STR:\", yy_.yytext);\n this.popState();\n break;\n case 13:\n yy.getLogger().debug(\"LEX: STR end:\", yy_.yytext);\n return \"STR\";\n break;\n case 14:\n yy_.yytext = yy_.yytext.replace(/space\\:/, \"\");\n yy.getLogger().debug(\"SPACE NUM (LEX)\", yy_.yytext);\n return 21;\n break;\n case 15:\n yy_.yytext = \"1\";\n yy.getLogger().debug(\"COLUMNS (LEX)\", yy_.yytext);\n return 21;\n break;\n case 16:\n return 42;\n break;\n case 17:\n return \"LINKSTYLE\";\n break;\n case 18:\n return \"INTERPOLATE\";\n break;\n case 19:\n this.pushState(\"CLASSDEF\");\n return 39;\n break;\n case 20:\n this.popState();\n this.pushState(\"CLASSDEFID\");\n return \"DEFAULT_CLASSDEF_ID\";\n break;\n case 21:\n this.popState();\n this.pushState(\"CLASSDEFID\");\n return 40;\n break;\n case 22:\n this.popState();\n return 41;\n break;\n case 23:\n this.pushState(\"CLASS\");\n return 43;\n break;\n case 24:\n this.popState();\n this.pushState(\"CLASS_STYLE\");\n return 44;\n break;\n case 25:\n this.popState();\n return 45;\n break;\n case 26:\n this.pushState(\"STYLE_STMNT\");\n return 46;\n break;\n case 27:\n this.popState();\n this.pushState(\"STYLE_DEFINITION\");\n return 47;\n break;\n case 28:\n this.popState();\n return 48;\n break;\n case 29:\n this.pushState(\"acc_title\");\n return \"acc_title\";\n break;\n case 30:\n this.popState();\n return \"acc_title_value\";\n break;\n case 31:\n this.pushState(\"acc_descr\");\n return \"acc_descr\";\n break;\n case 32:\n this.popState();\n return \"acc_descr_value\";\n break;\n case 33:\n this.pushState(\"acc_descr_multiline\");\n break;\n case 34:\n this.popState();\n break;\n case 35:\n return \"acc_descr_multiline_value\";\n break;\n case 36:\n return 30;\n break;\n case 37:\n this.popState();\n yy.getLogger().debug(\"Lex: ((\");\n return \"NODE_DEND\";\n break;\n case 38:\n this.popState();\n yy.getLogger().debug(\"Lex: ((\");\n return \"NODE_DEND\";\n break;\n case 39:\n this.popState();\n yy.getLogger().debug(\"Lex: ))\");\n return \"NODE_DEND\";\n break;\n case 40:\n this.popState();\n yy.getLogger().debug(\"Lex: ((\");\n return \"NODE_DEND\";\n break;\n case 41:\n this.popState();\n yy.getLogger().debug(\"Lex: ((\");\n return \"NODE_DEND\";\n break;\n case 42:\n this.popState();\n yy.getLogger().debug(\"Lex: (-\");\n return \"NODE_DEND\";\n break;\n case 43:\n this.popState();\n yy.getLogger().debug(\"Lex: -)\");\n return \"NODE_DEND\";\n break;\n case 44:\n this.popState();\n yy.getLogger().debug(\"Lex: ((\");\n return \"NODE_DEND\";\n break;\n case 45:\n this.popState();\n yy.getLogger().debug(\"Lex: ]]\");\n return \"NODE_DEND\";\n break;\n case 46:\n this.popState();\n yy.getLogger().debug(\"Lex: (\");\n return \"NODE_DEND\";\n break;\n case 47:\n this.popState();\n yy.getLogger().debug(\"Lex: ])\");\n return \"NODE_DEND\";\n break;\n case 48:\n this.popState();\n yy.getLogger().debug(\"Lex: /]\");\n return \"NODE_DEND\";\n break;\n case 49:\n this.popState();\n yy.getLogger().debug(\"Lex: /]\");\n return \"NODE_DEND\";\n break;\n case 50:\n this.popState();\n yy.getLogger().debug(\"Lex: )]\");\n return \"NODE_DEND\";\n break;\n case 51:\n this.popState();\n yy.getLogger().debug(\"Lex: )\");\n return \"NODE_DEND\";\n break;\n case 52:\n this.popState();\n yy.getLogger().debug(\"Lex: ]>\");\n return \"NODE_DEND\";\n break;\n case 53:\n this.popState();\n yy.getLogger().debug(\"Lex: ]\");\n return \"NODE_DEND\";\n break;\n case 54:\n yy.getLogger().debug(\"Lexa: -)\");\n this.pushState(\"NODE\");\n return 35;\n break;\n case 55:\n yy.getLogger().debug(\"Lexa: (-\");\n this.pushState(\"NODE\");\n return 35;\n break;\n case 56:\n yy.getLogger().debug(\"Lexa: ))\");\n this.pushState(\"NODE\");\n return 35;\n break;\n case 57:\n yy.getLogger().debug(\"Lexa: )\");\n this.pushState(\"NODE\");\n return 35;\n break;\n case 58:\n yy.getLogger().debug(\"Lex: (((\");\n this.pushState(\"NODE\");\n return 35;\n break;\n case 59:\n yy.getLogger().debug(\"Lexa: )\");\n this.pushState(\"NODE\");\n return 35;\n break;\n case 60:\n yy.getLogger().debug(\"Lexa: )\");\n this.pushState(\"NODE\");\n return 35;\n break;\n case 61:\n yy.getLogger().debug(\"Lexa: )\");\n this.pushState(\"NODE\");\n return 35;\n break;\n case 62:\n yy.getLogger().debug(\"Lexc: >\");\n this.pushState(\"NODE\");\n return 35;\n break;\n case 63:\n yy.getLogger().debug(\"Lexa: ([\");\n this.pushState(\"NODE\");\n return 35;\n break;\n case 64:\n yy.getLogger().debug(\"Lexa: )\");\n this.pushState(\"NODE\");\n return 35;\n break;\n case 65:\n this.pushState(\"NODE\");\n return 35;\n break;\n case 66:\n this.pushState(\"NODE\");\n return 35;\n break;\n case 67:\n this.pushState(\"NODE\");\n return 35;\n break;\n case 68:\n this.pushState(\"NODE\");\n return 35;\n break;\n case 69:\n this.pushState(\"NODE\");\n return 35;\n break;\n case 70:\n this.pushState(\"NODE\");\n return 35;\n break;\n case 71:\n this.pushState(\"NODE\");\n return 35;\n break;\n case 72:\n yy.getLogger().debug(\"Lexa: [\");\n this.pushState(\"NODE\");\n return 35;\n break;\n case 73:\n this.pushState(\"BLOCK_ARROW\");\n yy.getLogger().debug(\"LEX ARR START\");\n return 37;\n break;\n case 74:\n yy.getLogger().debug(\"Lex: NODE_ID\", yy_.yytext);\n return 31;\n break;\n case 75:\n yy.getLogger().debug(\"Lex: EOF\", yy_.yytext);\n return 8;\n break;\n case 76:\n this.pushState(\"md_string\");\n break;\n case 77:\n this.pushState(\"md_string\");\n break;\n case 78:\n return \"NODE_DESCR\";\n break;\n case 79:\n this.popState();\n break;\n case 80:\n yy.getLogger().debug(\"Lex: Starting string\");\n this.pushState(\"string\");\n break;\n case 81:\n yy.getLogger().debug(\"LEX ARR: Starting string\");\n this.pushState(\"string\");\n break;\n case 82:\n yy.getLogger().debug(\"LEX: NODE_DESCR:\", yy_.yytext);\n return \"NODE_DESCR\";\n break;\n case 83:\n yy.getLogger().debug(\"LEX POPPING\");\n this.popState();\n break;\n case 84:\n yy.getLogger().debug(\"Lex: =>BAE\");\n this.pushState(\"ARROW_DIR\");\n break;\n case 85:\n yy_.yytext = yy_.yytext.replace(/^,\\s*/, \"\");\n yy.getLogger().debug(\"Lex (right): dir:\", yy_.yytext);\n return \"DIR\";\n break;\n case 86:\n yy_.yytext = yy_.yytext.replace(/^,\\s*/, \"\");\n yy.getLogger().debug(\"Lex (left):\", yy_.yytext);\n return \"DIR\";\n break;\n case 87:\n yy_.yytext = yy_.yytext.replace(/^,\\s*/, \"\");\n yy.getLogger().debug(\"Lex (x):\", yy_.yytext);\n return \"DIR\";\n break;\n case 88:\n yy_.yytext = yy_.yytext.replace(/^,\\s*/, \"\");\n yy.getLogger().debug(\"Lex (y):\", yy_.yytext);\n return \"DIR\";\n break;\n case 89:\n yy_.yytext = yy_.yytext.replace(/^,\\s*/, \"\");\n yy.getLogger().debug(\"Lex (up):\", yy_.yytext);\n return \"DIR\";\n break;\n case 90:\n yy_.yytext = yy_.yytext.replace(/^,\\s*/, \"\");\n yy.getLogger().debug(\"Lex (down):\", yy_.yytext);\n return \"DIR\";\n break;\n case 91:\n yy_.yytext = \"]>\";\n yy.getLogger().debug(\"Lex (ARROW_DIR end):\", yy_.yytext);\n this.popState();\n this.popState();\n return \"BLOCK_ARROW_END\";\n break;\n case 92:\n yy.getLogger().debug(\"Lex: LINK\", \"#\" + yy_.yytext + \"#\");\n return 15;\n break;\n case 93:\n yy.getLogger().debug(\"Lex: LINK\", yy_.yytext);\n return 15;\n break;\n case 94:\n yy.getLogger().debug(\"Lex: LINK\", yy_.yytext);\n return 15;\n break;\n case 95:\n yy.getLogger().debug(\"Lex: LINK\", yy_.yytext);\n return 15;\n break;\n case 96:\n yy.getLogger().debug(\"Lex: START_LINK\", yy_.yytext);\n this.pushState(\"LLABEL\");\n return 16;\n break;\n case 97:\n yy.getLogger().debug(\"Lex: START_LINK\", yy_.yytext);\n this.pushState(\"LLABEL\");\n return 16;\n break;\n case 98:\n yy.getLogger().debug(\"Lex: START_LINK\", yy_.yytext);\n this.pushState(\"LLABEL\");\n return 16;\n break;\n case 99:\n this.pushState(\"md_string\");\n break;\n case 100:\n yy.getLogger().debug(\"Lex: Starting string\");\n this.pushState(\"string\");\n return \"LINK_LABEL\";\n break;\n case 101:\n this.popState();\n yy.getLogger().debug(\"Lex: LINK\", \"#\" + yy_.yytext + \"#\");\n return 15;\n break;\n case 102:\n this.popState();\n yy.getLogger().debug(\"Lex: LINK\", yy_.yytext);\n return 15;\n break;\n case 103:\n this.popState();\n yy.getLogger().debug(\"Lex: LINK\", yy_.yytext);\n return 15;\n break;\n case 104:\n yy.getLogger().debug(\"Lex: COLON\", yy_.yytext);\n yy_.yytext = yy_.yytext.slice(1);\n return 27;\n break;\n }\n }, \"anonymous\"),\n rules: [/^(?:block-beta\\b)/, /^(?:block:)/, /^(?:block\\b)/, /^(?:[\\s]+)/, /^(?:[\\n]+)/, /^(?:((\\u000D\\u000A)|(\\u000A)))/, /^(?:columns\\s+auto\\b)/, /^(?:columns\\s+[\\d]+)/, /^(?:[\"][`])/, /^(?:[^`\"]+)/, /^(?:[`][\"])/, /^(?:[\"])/, /^(?:[\"])/, /^(?:[^\"]*)/, /^(?:space[:]\\d+)/, /^(?:space\\b)/, /^(?:default\\b)/, /^(?:linkStyle\\b)/, /^(?:interpolate\\b)/, /^(?:classDef\\s+)/, /^(?:DEFAULT\\s+)/, /^(?:\\w+\\s+)/, /^(?:[^\\n]*)/, /^(?:class\\s+)/, /^(?:(\\w+)+((,\\s*\\w+)*))/, /^(?:[^\\n]*)/, /^(?:style\\s+)/, /^(?:(\\w+)+((,\\s*\\w+)*))/, /^(?:[^\\n]*)/, /^(?:accTitle\\s*:\\s*)/, /^(?:(?!\\n||)*[^\\n]*)/, /^(?:accDescr\\s*:\\s*)/, /^(?:(?!\\n||)*[^\\n]*)/, /^(?:accDescr\\s*\\{\\s*)/, /^(?:[\\}])/, /^(?:[^\\}]*)/, /^(?:end\\b\\s*)/, /^(?:\\(\\(\\()/, /^(?:\\)\\)\\))/, /^(?:[\\)]\\))/, /^(?:\\}\\})/, /^(?:\\})/, /^(?:\\(-)/, /^(?:-\\))/, /^(?:\\(\\()/, /^(?:\\]\\])/, /^(?:\\()/, /^(?:\\]\\))/, /^(?:\\\\\\])/, /^(?:\\/\\])/, /^(?:\\)\\])/, /^(?:[\\)])/, /^(?:\\]>)/, /^(?:[\\]])/, /^(?:-\\))/, /^(?:\\(-)/, /^(?:\\)\\))/, /^(?:\\))/, /^(?:\\(\\(\\()/, /^(?:\\(\\()/, /^(?:\\{\\{)/, /^(?:\\{)/, /^(?:>)/, /^(?:\\(\\[)/, /^(?:\\()/, /^(?:\\[\\[)/, /^(?:\\[\\|)/, /^(?:\\[\\()/, /^(?:\\)\\)\\))/, /^(?:\\[\\\\)/, /^(?:\\[\\/)/, /^(?:\\[\\\\)/, /^(?:\\[)/, /^(?:<\\[)/, /^(?:[^\\(\\[\\n\\-\\)\\{\\}\\s\\<\\>:]+)/, /^(?:$)/, /^(?:[\"][`])/, /^(?:[\"][`])/, /^(?:[^`\"]+)/, /^(?:[`][\"])/, /^(?:[\"])/, /^(?:[\"])/, /^(?:[^\"]+)/, /^(?:[\"])/, /^(?:\\]>\\s*\\()/, /^(?:,?\\s*right\\s*)/, /^(?:,?\\s*left\\s*)/, /^(?:,?\\s*x\\s*)/, /^(?:,?\\s*y\\s*)/, /^(?:,?\\s*up\\s*)/, /^(?:,?\\s*down\\s*)/, /^(?:\\)\\s*)/, /^(?:\\s*[xo<]?--+[-xo>]\\s*)/, /^(?:\\s*[xo<]?==+[=xo>]\\s*)/, /^(?:\\s*[xo<]?-?\\.+-[xo>]?\\s*)/, /^(?:\\s*~~[\\~]+\\s*)/, /^(?:\\s*[xo<]?--\\s*)/, /^(?:\\s*[xo<]?==\\s*)/, /^(?:\\s*[xo<]?-\\.\\s*)/, /^(?:[\"][`])/, /^(?:[\"])/, /^(?:\\s*[xo<]?--+[-xo>]\\s*)/, /^(?:\\s*[xo<]?==+[=xo>]\\s*)/, /^(?:\\s*[xo<]?-?\\.+-[xo>]?\\s*)/, /^(?::\\d+)/],\n conditions: { \"STYLE_DEFINITION\": { \"rules\": [28], \"inclusive\": false }, \"STYLE_STMNT\": { \"rules\": [27], \"inclusive\": false }, \"CLASSDEFID\": { \"rules\": [22], \"inclusive\": false }, \"CLASSDEF\": { \"rules\": [20, 21], \"inclusive\": false }, \"CLASS_STYLE\": { \"rules\": [25], \"inclusive\": false }, \"CLASS\": { \"rules\": [24], \"inclusive\": false }, \"LLABEL\": { \"rules\": [99, 100, 101, 102, 103], \"inclusive\": false }, \"ARROW_DIR\": { \"rules\": [85, 86, 87, 88, 89, 90, 91], \"inclusive\": false }, \"BLOCK_ARROW\": { \"rules\": [76, 81, 84], \"inclusive\": false }, \"NODE\": { \"rules\": [37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 77, 80], \"inclusive\": false }, \"md_string\": { \"rules\": [9, 10, 78, 79], \"inclusive\": false }, \"space\": { \"rules\": [], \"inclusive\": false }, \"string\": { \"rules\": [12, 13, 82, 83], \"inclusive\": false }, \"acc_descr_multiline\": { \"rules\": [34, 35], \"inclusive\": false }, \"acc_descr\": { \"rules\": [32], \"inclusive\": false }, \"acc_title\": { \"rules\": [30], \"inclusive\": false }, \"INITIAL\": { \"rules\": [0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 14, 15, 16, 17, 18, 19, 23, 26, 29, 31, 33, 36, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 92, 93, 94, 95, 96, 97, 98, 104], \"inclusive\": true } }\n };\n return lexer2;\n })();\n parser2.lexer = lexer;\n function Parser() {\n this.yy = {};\n }\n __name(Parser, \"Parser\");\n Parser.prototype = parser2;\n parser2.Parser = Parser;\n return new Parser();\n})();\nparser.parser = parser;\nvar block_default = parser;\n\n// src/diagrams/block/blockDB.ts\nimport clone from \"lodash-es/clone.js\";\nvar blockDatabase = /* @__PURE__ */ new Map();\nvar edgeList = [];\nvar edgeCount = /* @__PURE__ */ new Map();\nvar COLOR_KEYWORD = \"color\";\nvar FILL_KEYWORD = \"fill\";\nvar BG_FILL = \"bgFill\";\nvar STYLECLASS_SEP = \",\";\nvar config = getConfig2();\nvar classes = /* @__PURE__ */ new Map();\nvar sanitizeText2 = /* @__PURE__ */ __name((txt) => common_default.sanitizeText(txt, config), \"sanitizeText\");\nvar addStyleClass = /* @__PURE__ */ __name(function(id, styleAttributes = \"\") {\n let foundClass = classes.get(id);\n if (!foundClass) {\n foundClass = { id, styles: [], textStyles: [] };\n classes.set(id, foundClass);\n }\n if (styleAttributes !== void 0 && styleAttributes !== null) {\n styleAttributes.split(STYLECLASS_SEP).forEach((attrib) => {\n const fixedAttrib = attrib.replace(/([^;]*);/, \"$1\").trim();\n if (RegExp(COLOR_KEYWORD).exec(attrib)) {\n const newStyle1 = fixedAttrib.replace(FILL_KEYWORD, BG_FILL);\n const newStyle2 = newStyle1.replace(COLOR_KEYWORD, FILL_KEYWORD);\n foundClass.textStyles.push(newStyle2);\n }\n foundClass.styles.push(fixedAttrib);\n });\n }\n}, \"addStyleClass\");\nvar addStyle2Node = /* @__PURE__ */ __name(function(id, styles = \"\") {\n const foundBlock = blockDatabase.get(id);\n if (styles !== void 0 && styles !== null) {\n foundBlock.styles = styles.split(STYLECLASS_SEP);\n }\n}, \"addStyle2Node\");\nvar setCssClass = /* @__PURE__ */ __name(function(itemIds, cssClassName) {\n itemIds.split(\",\").forEach(function(id) {\n let foundBlock = blockDatabase.get(id);\n if (foundBlock === void 0) {\n const trimmedId = id.trim();\n foundBlock = { id: trimmedId, type: \"na\", children: [] };\n blockDatabase.set(trimmedId, foundBlock);\n }\n if (!foundBlock.classes) {\n foundBlock.classes = [];\n }\n foundBlock.classes.push(cssClassName);\n });\n}, \"setCssClass\");\nvar populateBlockDatabase = /* @__PURE__ */ __name((_blockList, parent) => {\n const blockList = _blockList.flat();\n const children = [];\n const columnSettingBlock = blockList.find((b) => b?.type === \"column-setting\");\n const column = columnSettingBlock?.columns ?? -1;\n for (const block of blockList) {\n if (typeof column === \"number\" && column > 0 && block.type !== \"column-setting\" && typeof block.widthInColumns === \"number\" && block.widthInColumns > column) {\n log.warn(\n `Block ${block.id} width ${block.widthInColumns} exceeds configured column width ${column}`\n );\n }\n if (block.label) {\n block.label = sanitizeText2(block.label);\n }\n if (block.type === \"classDef\") {\n addStyleClass(block.id, block.css);\n continue;\n }\n if (block.type === \"applyClass\") {\n setCssClass(block.id, block?.styleClass ?? \"\");\n continue;\n }\n if (block.type === \"applyStyles\") {\n if (block?.stylesStr) {\n addStyle2Node(block.id, block?.stylesStr);\n }\n continue;\n }\n if (block.type === \"column-setting\") {\n parent.columns = block.columns ?? -1;\n } else if (block.type === \"edge\") {\n const count = (edgeCount.get(block.id) ?? 0) + 1;\n edgeCount.set(block.id, count);\n block.id = count + \"-\" + block.id;\n edgeList.push(block);\n } else {\n if (!block.label) {\n if (block.type === \"composite\") {\n block.label = \"\";\n } else {\n block.label = block.id;\n }\n }\n const existingBlock = blockDatabase.get(block.id);\n if (existingBlock === void 0) {\n blockDatabase.set(block.id, block);\n } else {\n if (block.type !== \"na\") {\n existingBlock.type = block.type;\n }\n if (block.label !== block.id) {\n existingBlock.label = block.label;\n }\n }\n if (block.children) {\n populateBlockDatabase(block.children, block);\n }\n if (block.type === \"space\") {\n const w = block.width ?? 1;\n for (let j = 0; j < w; j++) {\n const newBlock = clone(block);\n newBlock.id = newBlock.id + \"-\" + j;\n blockDatabase.set(newBlock.id, newBlock);\n children.push(newBlock);\n }\n } else if (existingBlock === void 0) {\n children.push(block);\n }\n }\n }\n parent.children = children;\n}, \"populateBlockDatabase\");\nvar blocks = [];\nvar rootBlock = { id: \"root\", type: \"composite\", children: [], columns: -1 };\nvar clear2 = /* @__PURE__ */ __name(() => {\n log.debug(\"Clear called\");\n clear();\n rootBlock = { id: \"root\", type: \"composite\", children: [], columns: -1 };\n blockDatabase = /* @__PURE__ */ new Map([[\"root\", rootBlock]]);\n blocks = [];\n classes = /* @__PURE__ */ new Map();\n edgeList = [];\n edgeCount = /* @__PURE__ */ new Map();\n}, \"clear\");\nfunction typeStr2Type(typeStr) {\n log.debug(\"typeStr2Type\", typeStr);\n switch (typeStr) {\n case \"[]\":\n return \"square\";\n case \"()\":\n log.debug(\"we have a round\");\n return \"round\";\n case \"(())\":\n return \"circle\";\n case \">]\":\n return \"rect_left_inv_arrow\";\n case \"{}\":\n return \"diamond\";\n case \"{{}}\":\n return \"hexagon\";\n case \"([])\":\n return \"stadium\";\n case \"[[]]\":\n return \"subroutine\";\n case \"[()]\":\n return \"cylinder\";\n case \"((()))\":\n return \"doublecircle\";\n case \"[//]\":\n return \"lean_right\";\n case \"[\\\\\\\\]\":\n return \"lean_left\";\n case \"[/\\\\]\":\n return \"trapezoid\";\n case \"[\\\\/]\":\n return \"inv_trapezoid\";\n case \"<[]>\":\n return \"block_arrow\";\n default:\n return \"na\";\n }\n}\n__name(typeStr2Type, \"typeStr2Type\");\nfunction edgeTypeStr2Type(typeStr) {\n log.debug(\"typeStr2Type\", typeStr);\n switch (typeStr) {\n case \"==\":\n return \"thick\";\n default:\n return \"normal\";\n }\n}\n__name(edgeTypeStr2Type, \"edgeTypeStr2Type\");\nfunction edgeStrToEdgeData(typeStr) {\n switch (typeStr.replace(/^[\\s-]+|[\\s-]+$/g, \"\")) {\n case \"x\":\n return \"arrow_cross\";\n case \"o\":\n return \"arrow_circle\";\n case \">\":\n return \"arrow_point\";\n default:\n return \"\";\n }\n}\n__name(edgeStrToEdgeData, \"edgeStrToEdgeData\");\nvar cnt = 0;\nvar generateId = /* @__PURE__ */ __name(() => {\n cnt++;\n return \"id-\" + Math.random().toString(36).substr(2, 12) + \"-\" + cnt;\n}, \"generateId\");\nvar setHierarchy = /* @__PURE__ */ __name((block) => {\n rootBlock.children = block;\n populateBlockDatabase(block, rootBlock);\n blocks = rootBlock.children;\n}, \"setHierarchy\");\nvar getColumns = /* @__PURE__ */ __name((blockId) => {\n const block = blockDatabase.get(blockId);\n if (!block) {\n return -1;\n }\n if (block.columns) {\n return block.columns;\n }\n if (!block.children) {\n return -1;\n }\n return block.children.length;\n}, \"getColumns\");\nvar getBlocksFlat = /* @__PURE__ */ __name(() => {\n return [...blockDatabase.values()];\n}, \"getBlocksFlat\");\nvar getBlocks = /* @__PURE__ */ __name(() => {\n return blocks || [];\n}, \"getBlocks\");\nvar getEdges = /* @__PURE__ */ __name(() => {\n return edgeList;\n}, \"getEdges\");\nvar getBlock = /* @__PURE__ */ __name((id) => {\n return blockDatabase.get(id);\n}, \"getBlock\");\nvar setBlock = /* @__PURE__ */ __name((block) => {\n blockDatabase.set(block.id, block);\n}, \"setBlock\");\nvar getLogger = /* @__PURE__ */ __name(() => log, \"getLogger\");\nvar getClasses = /* @__PURE__ */ __name(function() {\n return classes;\n}, \"getClasses\");\nvar db = {\n getConfig: /* @__PURE__ */ __name(() => getConfig().block, \"getConfig\"),\n typeStr2Type,\n edgeTypeStr2Type,\n edgeStrToEdgeData,\n getLogger,\n getBlocksFlat,\n getBlocks,\n getEdges,\n setHierarchy,\n getBlock,\n setBlock,\n getColumns,\n getClasses,\n clear: clear2,\n generateId\n};\nvar blockDB_default = db;\n\n// src/diagrams/block/styles.ts\nimport * as khroma from \"khroma\";\nvar fade = /* @__PURE__ */ __name((color, opacity) => {\n const channel2 = khroma.channel;\n const r = channel2(color, \"r\");\n const g = channel2(color, \"g\");\n const b = channel2(color, \"b\");\n return khroma.rgba(r, g, b, opacity);\n}, \"fade\");\nvar getStyles = /* @__PURE__ */ __name((options) => `.label {\n font-family: ${options.fontFamily};\n color: ${options.nodeTextColor || options.textColor};\n }\n .cluster-label text {\n fill: ${options.titleColor};\n }\n .cluster-label span,p {\n color: ${options.titleColor};\n }\n\n\n\n .label text,span,p {\n fill: ${options.nodeTextColor || options.textColor};\n color: ${options.nodeTextColor || options.textColor};\n }\n\n .node rect,\n .node circle,\n .node ellipse,\n .node polygon,\n .node path {\n fill: ${options.mainBkg};\n stroke: ${options.nodeBorder};\n stroke-width: 1px;\n }\n .flowchart-label text {\n text-anchor: middle;\n }\n // .flowchart-label .text-outer-tspan {\n // text-anchor: middle;\n // }\n // .flowchart-label .text-inner-tspan {\n // text-anchor: start;\n // }\n\n .node .label {\n text-align: center;\n }\n .node.clickable {\n cursor: pointer;\n }\n\n .arrowheadPath {\n fill: ${options.arrowheadColor};\n }\n\n .edgePath .path {\n stroke: ${options.lineColor};\n stroke-width: 2.0px;\n }\n\n .flowchart-link {\n stroke: ${options.lineColor};\n fill: none;\n }\n\n .edgeLabel {\n background-color: ${options.edgeLabelBackground};\n rect {\n opacity: 0.5;\n background-color: ${options.edgeLabelBackground};\n fill: ${options.edgeLabelBackground};\n }\n text-align: center;\n }\n\n /* For html labels only */\n .labelBkg {\n background-color: ${fade(options.edgeLabelBackground, 0.5)};\n // background-color:\n }\n\n .node .cluster {\n // fill: ${fade(options.mainBkg, 0.5)};\n fill: ${fade(options.clusterBkg, 0.5)};\n stroke: ${fade(options.clusterBorder, 0.2)};\n box-shadow: rgba(50, 50, 93, 0.25) 0px 13px 27px -5px, rgba(0, 0, 0, 0.3) 0px 8px 16px -8px;\n stroke-width: 1px;\n }\n\n .cluster text {\n fill: ${options.titleColor};\n }\n\n .cluster span,p {\n color: ${options.titleColor};\n }\n /* .cluster div {\n color: ${options.titleColor};\n } */\n\n div.mermaidTooltip {\n position: absolute;\n text-align: center;\n max-width: 200px;\n padding: 2px;\n font-family: ${options.fontFamily};\n font-size: 12px;\n background: ${options.tertiaryColor};\n border: 1px solid ${options.border2};\n border-radius: 2px;\n pointer-events: none;\n z-index: 100;\n }\n\n .flowchartTitleText {\n text-anchor: middle;\n font-size: 18px;\n fill: ${options.textColor};\n }\n ${getIconStyles()}\n`, \"getStyles\");\nvar styles_default = getStyles;\n\n// src/diagrams/block/blockRenderer.ts\nimport { select as d3select } from \"d3\";\n\n// src/dagre-wrapper/markers.js\nvar insertMarkers = /* @__PURE__ */ __name((elem, markerArray, type, id) => {\n markerArray.forEach((markerName) => {\n markers[markerName](elem, type, id);\n });\n}, \"insertMarkers\");\nvar extension = /* @__PURE__ */ __name((elem, type, id) => {\n log.trace(\"Making markers for \", id);\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-extensionStart\").attr(\"class\", \"marker extension \" + type).attr(\"refX\", 18).attr(\"refY\", 7).attr(\"markerWidth\", 190).attr(\"markerHeight\", 240).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 1,7 L18,13 V 1 Z\");\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-extensionEnd\").attr(\"class\", \"marker extension \" + type).attr(\"refX\", 1).attr(\"refY\", 7).attr(\"markerWidth\", 20).attr(\"markerHeight\", 28).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 1,1 V 13 L18,7 Z\");\n}, \"extension\");\nvar composition = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-compositionStart\").attr(\"class\", \"marker composition \" + type).attr(\"refX\", 18).attr(\"refY\", 7).attr(\"markerWidth\", 190).attr(\"markerHeight\", 240).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 18,7 L9,13 L1,7 L9,1 Z\");\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-compositionEnd\").attr(\"class\", \"marker composition \" + type).attr(\"refX\", 1).attr(\"refY\", 7).attr(\"markerWidth\", 20).attr(\"markerHeight\", 28).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 18,7 L9,13 L1,7 L9,1 Z\");\n}, \"composition\");\nvar aggregation = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-aggregationStart\").attr(\"class\", \"marker aggregation \" + type).attr(\"refX\", 18).attr(\"refY\", 7).attr(\"markerWidth\", 190).attr(\"markerHeight\", 240).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 18,7 L9,13 L1,7 L9,1 Z\");\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-aggregationEnd\").attr(\"class\", \"marker aggregation \" + type).attr(\"refX\", 1).attr(\"refY\", 7).attr(\"markerWidth\", 20).attr(\"markerHeight\", 28).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 18,7 L9,13 L1,7 L9,1 Z\");\n}, \"aggregation\");\nvar dependency = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-dependencyStart\").attr(\"class\", \"marker dependency \" + type).attr(\"refX\", 6).attr(\"refY\", 7).attr(\"markerWidth\", 190).attr(\"markerHeight\", 240).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 5,7 L9,13 L1,7 L9,1 Z\");\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-dependencyEnd\").attr(\"class\", \"marker dependency \" + type).attr(\"refX\", 13).attr(\"refY\", 7).attr(\"markerWidth\", 20).attr(\"markerHeight\", 28).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 18,7 L9,13 L14,7 L9,1 Z\");\n}, \"dependency\");\nvar lollipop = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-lollipopStart\").attr(\"class\", \"marker lollipop \" + type).attr(\"refX\", 13).attr(\"refY\", 7).attr(\"markerWidth\", 190).attr(\"markerHeight\", 240).attr(\"orient\", \"auto\").append(\"circle\").attr(\"stroke\", \"black\").attr(\"fill\", \"transparent\").attr(\"cx\", 7).attr(\"cy\", 7).attr(\"r\", 6);\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-lollipopEnd\").attr(\"class\", \"marker lollipop \" + type).attr(\"refX\", 1).attr(\"refY\", 7).attr(\"markerWidth\", 190).attr(\"markerHeight\", 240).attr(\"orient\", \"auto\").append(\"circle\").attr(\"stroke\", \"black\").attr(\"fill\", \"transparent\").attr(\"cx\", 7).attr(\"cy\", 7).attr(\"r\", 6);\n}, \"lollipop\");\nvar point = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"marker\").attr(\"id\", id + \"_\" + type + \"-pointEnd\").attr(\"class\", \"marker \" + type).attr(\"viewBox\", \"0 0 10 10\").attr(\"refX\", 6).attr(\"refY\", 5).attr(\"markerUnits\", \"userSpaceOnUse\").attr(\"markerWidth\", 12).attr(\"markerHeight\", 12).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 0 0 L 10 5 L 0 10 z\").attr(\"class\", \"arrowMarkerPath\").style(\"stroke-width\", 1).style(\"stroke-dasharray\", \"1,0\");\n elem.append(\"marker\").attr(\"id\", id + \"_\" + type + \"-pointStart\").attr(\"class\", \"marker \" + type).attr(\"viewBox\", \"0 0 10 10\").attr(\"refX\", 4.5).attr(\"refY\", 5).attr(\"markerUnits\", \"userSpaceOnUse\").attr(\"markerWidth\", 12).attr(\"markerHeight\", 12).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 0 5 L 10 10 L 10 0 z\").attr(\"class\", \"arrowMarkerPath\").style(\"stroke-width\", 1).style(\"stroke-dasharray\", \"1,0\");\n}, \"point\");\nvar circle = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"marker\").attr(\"id\", id + \"_\" + type + \"-circleEnd\").attr(\"class\", \"marker \" + type).attr(\"viewBox\", \"0 0 10 10\").attr(\"refX\", 11).attr(\"refY\", 5).attr(\"markerUnits\", \"userSpaceOnUse\").attr(\"markerWidth\", 11).attr(\"markerHeight\", 11).attr(\"orient\", \"auto\").append(\"circle\").attr(\"cx\", \"5\").attr(\"cy\", \"5\").attr(\"r\", \"5\").attr(\"class\", \"arrowMarkerPath\").style(\"stroke-width\", 1).style(\"stroke-dasharray\", \"1,0\");\n elem.append(\"marker\").attr(\"id\", id + \"_\" + type + \"-circleStart\").attr(\"class\", \"marker \" + type).attr(\"viewBox\", \"0 0 10 10\").attr(\"refX\", -1).attr(\"refY\", 5).attr(\"markerUnits\", \"userSpaceOnUse\").attr(\"markerWidth\", 11).attr(\"markerHeight\", 11).attr(\"orient\", \"auto\").append(\"circle\").attr(\"cx\", \"5\").attr(\"cy\", \"5\").attr(\"r\", \"5\").attr(\"class\", \"arrowMarkerPath\").style(\"stroke-width\", 1).style(\"stroke-dasharray\", \"1,0\");\n}, \"circle\");\nvar cross = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"marker\").attr(\"id\", id + \"_\" + type + \"-crossEnd\").attr(\"class\", \"marker cross \" + type).attr(\"viewBox\", \"0 0 11 11\").attr(\"refX\", 12).attr(\"refY\", 5.2).attr(\"markerUnits\", \"userSpaceOnUse\").attr(\"markerWidth\", 11).attr(\"markerHeight\", 11).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 1,1 l 9,9 M 10,1 l -9,9\").attr(\"class\", \"arrowMarkerPath\").style(\"stroke-width\", 2).style(\"stroke-dasharray\", \"1,0\");\n elem.append(\"marker\").attr(\"id\", id + \"_\" + type + \"-crossStart\").attr(\"class\", \"marker cross \" + type).attr(\"viewBox\", \"0 0 11 11\").attr(\"refX\", -1).attr(\"refY\", 5.2).attr(\"markerUnits\", \"userSpaceOnUse\").attr(\"markerWidth\", 11).attr(\"markerHeight\", 11).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 1,1 l 9,9 M 10,1 l -9,9\").attr(\"class\", \"arrowMarkerPath\").style(\"stroke-width\", 2).style(\"stroke-dasharray\", \"1,0\");\n}, \"cross\");\nvar barb = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-barbEnd\").attr(\"refX\", 19).attr(\"refY\", 7).attr(\"markerWidth\", 20).attr(\"markerHeight\", 14).attr(\"markerUnits\", \"strokeWidth\").attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 19,7 L9,13 L14,7 L9,1 Z\");\n}, \"barb\");\nvar markers = {\n extension,\n composition,\n aggregation,\n dependency,\n lollipop,\n point,\n circle,\n cross,\n barb\n};\nvar markers_default = insertMarkers;\n\n// src/diagrams/block/layout.ts\nvar padding = getConfig2()?.block?.padding ?? 8;\nfunction calculateBlockPosition(columns, position) {\n if (columns === 0 || !Number.isInteger(columns)) {\n throw new Error(\"Columns must be an integer !== 0.\");\n }\n if (position < 0 || !Number.isInteger(position)) {\n throw new Error(\"Position must be a non-negative integer.\" + position);\n }\n if (columns < 0) {\n return { px: position, py: 0 };\n }\n if (columns === 1) {\n return { px: 0, py: position };\n }\n const px = position % columns;\n const py = Math.floor(position / columns);\n return { px, py };\n}\n__name(calculateBlockPosition, \"calculateBlockPosition\");\nvar getMaxChildSize = /* @__PURE__ */ __name((block) => {\n let maxWidth = 0;\n let maxHeight = 0;\n for (const child of block.children) {\n const { width, height, x, y } = child.size ?? { width: 0, height: 0, x: 0, y: 0 };\n log.debug(\n \"getMaxChildSize abc95 child:\",\n child.id,\n \"width:\",\n width,\n \"height:\",\n height,\n \"x:\",\n x,\n \"y:\",\n y,\n child.type\n );\n if (child.type === \"space\") {\n continue;\n }\n if (width > maxWidth) {\n maxWidth = width / (block.widthInColumns ?? 1);\n }\n if (height > maxHeight) {\n maxHeight = height;\n }\n }\n return { width: maxWidth, height: maxHeight };\n}, \"getMaxChildSize\");\nfunction setBlockSizes(block, db2, siblingWidth = 0, siblingHeight = 0) {\n log.debug(\n \"setBlockSizes abc95 (start)\",\n block.id,\n block?.size?.x,\n \"block width =\",\n block?.size,\n \"siblingWidth\",\n siblingWidth\n );\n if (!block?.size?.width) {\n block.size = {\n width: siblingWidth,\n height: siblingHeight,\n x: 0,\n y: 0\n };\n }\n let maxWidth = 0;\n let maxHeight = 0;\n if (block.children?.length > 0) {\n for (const child of block.children) {\n setBlockSizes(child, db2);\n }\n const childSize = getMaxChildSize(block);\n maxWidth = childSize.width;\n maxHeight = childSize.height;\n log.debug(\"setBlockSizes abc95 maxWidth of\", block.id, \":s children is \", maxWidth, maxHeight);\n for (const child of block.children) {\n if (child.size) {\n log.debug(\n `abc95 Setting size of children of ${block.id} id=${child.id} ${maxWidth} ${maxHeight} ${JSON.stringify(child.size)}`\n );\n child.size.width = maxWidth * (child.widthInColumns ?? 1) + padding * ((child.widthInColumns ?? 1) - 1);\n child.size.height = maxHeight;\n child.size.x = 0;\n child.size.y = 0;\n log.debug(\n `abc95 updating size of ${block.id} children child:${child.id} maxWidth:${maxWidth} maxHeight:${maxHeight}`\n );\n }\n }\n for (const child of block.children) {\n setBlockSizes(child, db2, maxWidth, maxHeight);\n }\n const columns = block.columns ?? -1;\n let numItems = 0;\n for (const child of block.children) {\n numItems += child.widthInColumns ?? 1;\n }\n let xSize = block.children.length;\n if (columns > 0 && columns < numItems) {\n xSize = columns;\n }\n const ySize = Math.ceil(numItems / xSize);\n let width = xSize * (maxWidth + padding) + padding;\n let height = ySize * (maxHeight + padding) + padding;\n if (width < siblingWidth) {\n log.debug(\n `Detected to small sibling: abc95 ${block.id} siblingWidth ${siblingWidth} siblingHeight ${siblingHeight} width ${width}`\n );\n width = siblingWidth;\n height = siblingHeight;\n const childWidth = (siblingWidth - xSize * padding - padding) / xSize;\n const childHeight = (siblingHeight - ySize * padding - padding) / ySize;\n log.debug(\"Size indata abc88\", block.id, \"childWidth\", childWidth, \"maxWidth\", maxWidth);\n log.debug(\"Size indata abc88\", block.id, \"childHeight\", childHeight, \"maxHeight\", maxHeight);\n log.debug(\"Size indata abc88 xSize\", xSize, \"padding\", padding);\n for (const child of block.children) {\n if (child.size) {\n child.size.width = childWidth;\n child.size.height = childHeight;\n child.size.x = 0;\n child.size.y = 0;\n }\n }\n }\n log.debug(\n `abc95 (finale calc) ${block.id} xSize ${xSize} ySize ${ySize} columns ${columns}${block.children.length} width=${Math.max(width, block.size?.width || 0)}`\n );\n if (width < (block?.size?.width || 0)) {\n width = block?.size?.width || 0;\n const num = columns > 0 ? Math.min(block.children.length, columns) : block.children.length;\n if (num > 0) {\n const childWidth = (width - num * padding - padding) / num;\n log.debug(\"abc95 (growing to fit) width\", block.id, width, block.size?.width, childWidth);\n for (const child of block.children) {\n if (child.size) {\n child.size.width = childWidth;\n }\n }\n }\n }\n block.size = {\n width,\n height,\n x: 0,\n y: 0\n };\n }\n log.debug(\n \"setBlockSizes abc94 (done)\",\n block.id,\n block?.size?.x,\n block?.size?.width,\n block?.size?.y,\n block?.size?.height\n );\n}\n__name(setBlockSizes, \"setBlockSizes\");\nfunction layoutBlocks(block, db2) {\n log.debug(\n `abc85 layout blocks (=>layoutBlocks) ${block.id} x: ${block?.size?.x} y: ${block?.size?.y} width: ${block?.size?.width}`\n );\n const columns = block.columns ?? -1;\n log.debug(\"layoutBlocks columns abc95\", block.id, \"=>\", columns, block);\n if (block.children && // find max width of children\n block.children.length > 0) {\n const width = block?.children[0]?.size?.width ?? 0;\n const widthOfChildren = block.children.length * width + (block.children.length - 1) * padding;\n log.debug(\"widthOfChildren 88\", widthOfChildren, \"posX\");\n let columnPos = 0;\n log.debug(\"abc91 block?.size?.x\", block.id, block?.size?.x);\n let startingPosX = block?.size?.x ? block?.size?.x + (-block?.size?.width / 2 || 0) : -padding;\n let rowPos = 0;\n for (const child of block.children) {\n const parent = block;\n if (!child.size) {\n continue;\n }\n const { width: width2, height } = child.size;\n const { px, py } = calculateBlockPosition(columns, columnPos);\n if (py != rowPos) {\n rowPos = py;\n startingPosX = block?.size?.x ? block?.size?.x + (-block?.size?.width / 2 || 0) : -padding;\n log.debug(\"New row in layout for block\", block.id, \" and child \", child.id, rowPos);\n }\n log.debug(\n `abc89 layout blocks (child) id: ${child.id} Pos: ${columnPos} (px, py) ${px},${py} (${parent?.size?.x},${parent?.size?.y}) parent: ${parent.id} width: ${width2}${padding}`\n );\n if (parent.size) {\n const halfWidth = width2 / 2;\n child.size.x = startingPosX + padding + halfWidth;\n log.debug(\n `abc91 layout blocks (calc) px, pyid:${child.id} startingPos=X${startingPosX} new startingPosX${child.size.x} ${halfWidth} padding=${padding} width=${width2} halfWidth=${halfWidth} => x:${child.size.x} y:${child.size.y} ${child.widthInColumns} (width * (child?.w || 1)) / 2 ${width2 * (child?.widthInColumns ?? 1) / 2}`\n );\n startingPosX = child.size.x + halfWidth;\n child.size.y = parent.size.y - parent.size.height / 2 + py * (height + padding) + height / 2 + padding;\n log.debug(\n `abc88 layout blocks (calc) px, pyid:${child.id}startingPosX${startingPosX}${padding}${halfWidth}=>x:${child.size.x}y:${child.size.y}${child.widthInColumns}(width * (child?.w || 1)) / 2${width2 * (child?.widthInColumns ?? 1) / 2}`\n );\n }\n if (child.children) {\n layoutBlocks(child, db2);\n }\n let columnsFilled = child?.widthInColumns ?? 1;\n if (columns > 0) {\n columnsFilled = Math.min(columnsFilled, columns - columnPos % columns);\n }\n columnPos += columnsFilled;\n log.debug(\"abc88 columnsPos\", child, columnPos);\n }\n }\n log.debug(\n `layout blocks (<==layoutBlocks) ${block.id} x: ${block?.size?.x} y: ${block?.size?.y} width: ${block?.size?.width}`\n );\n}\n__name(layoutBlocks, \"layoutBlocks\");\nfunction findBounds(block, { minX, minY, maxX, maxY } = { minX: 0, minY: 0, maxX: 0, maxY: 0 }) {\n if (block.size && block.id !== \"root\") {\n const { x, y, width, height } = block.size;\n if (x - width / 2 < minX) {\n minX = x - width / 2;\n }\n if (y - height / 2 < minY) {\n minY = y - height / 2;\n }\n if (x + width / 2 > maxX) {\n maxX = x + width / 2;\n }\n if (y + height / 2 > maxY) {\n maxY = y + height / 2;\n }\n }\n if (block.children) {\n for (const child of block.children) {\n ({ minX, minY, maxX, maxY } = findBounds(child, { minX, minY, maxX, maxY }));\n }\n }\n return { minX, minY, maxX, maxY };\n}\n__name(findBounds, \"findBounds\");\nfunction layout(db2) {\n const root = db2.getBlock(\"root\");\n if (!root) {\n return;\n }\n setBlockSizes(root, db2, 0, 0);\n layoutBlocks(root, db2);\n log.debug(\"getBlocks\", JSON.stringify(root, null, 2));\n const { minX, minY, maxX, maxY } = findBounds(root);\n const height = maxY - minY;\n const width = maxX - minX;\n return { x: minX, y: minY, width, height };\n}\n__name(layout, \"layout\");\n\n// src/diagrams/block/renderHelpers.ts\nimport * as graphlib from \"dagre-d3-es/src/graphlib/index.js\";\n\n// src/dagre-wrapper/createLabel.js\nimport { select } from \"d3\";\nfunction applyStyle(dom, styleFn) {\n if (styleFn) {\n dom.attr(\"style\", styleFn);\n }\n}\n__name(applyStyle, \"applyStyle\");\nfunction addHtmlLabel(node, config2) {\n const fo = select(document.createElementNS(\"http://www.w3.org/2000/svg\", \"foreignObject\"));\n const div = fo.append(\"xhtml:div\");\n const label = node.label;\n const labelClass = node.isNode ? \"nodeLabel\" : \"edgeLabel\";\n const span = div.append(\"span\");\n span.html(sanitizeText(label, config2));\n applyStyle(span, node.labelStyle);\n span.attr(\"class\", labelClass);\n applyStyle(div, node.labelStyle);\n div.style(\"display\", \"inline-block\");\n div.style(\"white-space\", \"nowrap\");\n div.attr(\"xmlns\", \"http://www.w3.org/1999/xhtml\");\n return fo.node();\n}\n__name(addHtmlLabel, \"addHtmlLabel\");\nvar createLabel = /* @__PURE__ */ __name(async (_vertexText, style, isTitle, isNode) => {\n let vertexText = _vertexText || \"\";\n if (typeof vertexText === \"object\") {\n vertexText = vertexText[0];\n }\n const config2 = getConfig2();\n if (evaluate(config2.flowchart.htmlLabels)) {\n vertexText = vertexText.replace(/\\\\n|\\n/g, \"
\");\n log.debug(\"vertexText\" + vertexText);\n const label = await replaceIconSubstring(decodeEntities(vertexText));\n const node = {\n isNode,\n label,\n labelStyle: style.replace(\"fill:\", \"color:\")\n };\n let vertexNode = addHtmlLabel(node, config2);\n return vertexNode;\n } else {\n const svgLabel = document.createElementNS(\"http://www.w3.org/2000/svg\", \"text\");\n svgLabel.setAttribute(\"style\", style.replace(\"color:\", \"fill:\"));\n let rows = [];\n if (typeof vertexText === \"string\") {\n rows = vertexText.split(/\\\\n|\\n|/gi);\n } else if (Array.isArray(vertexText)) {\n rows = vertexText;\n } else {\n rows = [];\n }\n for (const row of rows) {\n const tspan = document.createElementNS(\"http://www.w3.org/2000/svg\", \"tspan\");\n tspan.setAttributeNS(\"http://www.w3.org/XML/1998/namespace\", \"xml:space\", \"preserve\");\n tspan.setAttribute(\"dy\", \"1em\");\n tspan.setAttribute(\"x\", \"0\");\n if (isTitle) {\n tspan.setAttribute(\"class\", \"title-row\");\n } else {\n tspan.setAttribute(\"class\", \"row\");\n }\n tspan.textContent = row.trim();\n svgLabel.appendChild(tspan);\n }\n return svgLabel;\n }\n}, \"createLabel\");\nvar createLabel_default = createLabel;\n\n// src/dagre-wrapper/edges.js\nimport { line, curveBasis, select as select2 } from \"d3\";\n\n// src/dagre-wrapper/edgeMarker.ts\nvar addEdgeMarkers = /* @__PURE__ */ __name((svgPath, edge, url, id, diagramType) => {\n if (edge.arrowTypeStart) {\n addEdgeMarker(svgPath, \"start\", edge.arrowTypeStart, url, id, diagramType);\n }\n if (edge.arrowTypeEnd) {\n addEdgeMarker(svgPath, \"end\", edge.arrowTypeEnd, url, id, diagramType);\n }\n}, \"addEdgeMarkers\");\nvar arrowTypesMap = {\n arrow_cross: \"cross\",\n arrow_point: \"point\",\n arrow_barb: \"barb\",\n arrow_circle: \"circle\",\n aggregation: \"aggregation\",\n extension: \"extension\",\n composition: \"composition\",\n dependency: \"dependency\",\n lollipop: \"lollipop\"\n};\nvar addEdgeMarker = /* @__PURE__ */ __name((svgPath, position, arrowType, url, id, diagramType) => {\n const endMarkerType = arrowTypesMap[arrowType];\n if (!endMarkerType) {\n log.warn(`Unknown arrow type: ${arrowType}`);\n return;\n }\n const suffix = position === \"start\" ? \"Start\" : \"End\";\n svgPath.attr(`marker-${position}`, `url(${url}#${id}_${diagramType}-${endMarkerType}${suffix})`);\n}, \"addEdgeMarker\");\n\n// src/dagre-wrapper/edges.js\nvar edgeLabels = {};\nvar terminalLabels = {};\nvar insertEdgeLabel = /* @__PURE__ */ __name(async (elem, edge) => {\n const config2 = getConfig2();\n const useHtmlLabels = evaluate(config2.flowchart.htmlLabels);\n const labelElement = edge.labelType === \"markdown\" ? createText(\n elem,\n edge.label,\n {\n style: edge.labelStyle,\n useHtmlLabels,\n addSvgBackground: true\n },\n config2\n ) : await createLabel_default(edge.label, edge.labelStyle);\n const edgeLabel = elem.insert(\"g\").attr(\"class\", \"edgeLabel\");\n const label = edgeLabel.insert(\"g\").attr(\"class\", \"label\");\n label.node().appendChild(labelElement);\n let bbox = labelElement.getBBox();\n if (useHtmlLabels) {\n const div = labelElement.children[0];\n const dv = select2(labelElement);\n bbox = div.getBoundingClientRect();\n dv.attr(\"width\", bbox.width);\n dv.attr(\"height\", bbox.height);\n }\n label.attr(\"transform\", \"translate(\" + -bbox.width / 2 + \", \" + -bbox.height / 2 + \")\");\n edgeLabels[edge.id] = edgeLabel;\n edge.width = bbox.width;\n edge.height = bbox.height;\n let fo;\n if (edge.startLabelLeft) {\n const startLabelElement = await createLabel_default(edge.startLabelLeft, edge.labelStyle);\n const startEdgeLabelLeft = elem.insert(\"g\").attr(\"class\", \"edgeTerminals\");\n const inner = startEdgeLabelLeft.insert(\"g\").attr(\"class\", \"inner\");\n fo = inner.node().appendChild(startLabelElement);\n const slBox = startLabelElement.getBBox();\n inner.attr(\"transform\", \"translate(\" + -slBox.width / 2 + \", \" + -slBox.height / 2 + \")\");\n if (!terminalLabels[edge.id]) {\n terminalLabels[edge.id] = {};\n }\n terminalLabels[edge.id].startLeft = startEdgeLabelLeft;\n setTerminalWidth(fo, edge.startLabelLeft);\n }\n if (edge.startLabelRight) {\n const startLabelElement = await createLabel_default(edge.startLabelRight, edge.labelStyle);\n const startEdgeLabelRight = elem.insert(\"g\").attr(\"class\", \"edgeTerminals\");\n const inner = startEdgeLabelRight.insert(\"g\").attr(\"class\", \"inner\");\n fo = startEdgeLabelRight.node().appendChild(startLabelElement);\n inner.node().appendChild(startLabelElement);\n const slBox = startLabelElement.getBBox();\n inner.attr(\"transform\", \"translate(\" + -slBox.width / 2 + \", \" + -slBox.height / 2 + \")\");\n if (!terminalLabels[edge.id]) {\n terminalLabels[edge.id] = {};\n }\n terminalLabels[edge.id].startRight = startEdgeLabelRight;\n setTerminalWidth(fo, edge.startLabelRight);\n }\n if (edge.endLabelLeft) {\n const endLabelElement = await createLabel_default(edge.endLabelLeft, edge.labelStyle);\n const endEdgeLabelLeft = elem.insert(\"g\").attr(\"class\", \"edgeTerminals\");\n const inner = endEdgeLabelLeft.insert(\"g\").attr(\"class\", \"inner\");\n fo = inner.node().appendChild(endLabelElement);\n const slBox = endLabelElement.getBBox();\n inner.attr(\"transform\", \"translate(\" + -slBox.width / 2 + \", \" + -slBox.height / 2 + \")\");\n endEdgeLabelLeft.node().appendChild(endLabelElement);\n if (!terminalLabels[edge.id]) {\n terminalLabels[edge.id] = {};\n }\n terminalLabels[edge.id].endLeft = endEdgeLabelLeft;\n setTerminalWidth(fo, edge.endLabelLeft);\n }\n if (edge.endLabelRight) {\n const endLabelElement = await createLabel_default(edge.endLabelRight, edge.labelStyle);\n const endEdgeLabelRight = elem.insert(\"g\").attr(\"class\", \"edgeTerminals\");\n const inner = endEdgeLabelRight.insert(\"g\").attr(\"class\", \"inner\");\n fo = inner.node().appendChild(endLabelElement);\n const slBox = endLabelElement.getBBox();\n inner.attr(\"transform\", \"translate(\" + -slBox.width / 2 + \", \" + -slBox.height / 2 + \")\");\n endEdgeLabelRight.node().appendChild(endLabelElement);\n if (!terminalLabels[edge.id]) {\n terminalLabels[edge.id] = {};\n }\n terminalLabels[edge.id].endRight = endEdgeLabelRight;\n setTerminalWidth(fo, edge.endLabelRight);\n }\n return labelElement;\n}, \"insertEdgeLabel\");\nfunction setTerminalWidth(fo, value) {\n if (getConfig2().flowchart.htmlLabels && fo) {\n fo.style.width = value.length * 9 + \"px\";\n fo.style.height = \"12px\";\n }\n}\n__name(setTerminalWidth, \"setTerminalWidth\");\nvar positionEdgeLabel = /* @__PURE__ */ __name((edge, paths) => {\n log.debug(\"Moving label abc88 \", edge.id, edge.label, edgeLabels[edge.id], paths);\n let path = paths.updatedPath ? paths.updatedPath : paths.originalPath;\n const siteConfig = getConfig2();\n const { subGraphTitleTotalMargin } = getSubGraphTitleMargins(siteConfig);\n if (edge.label) {\n const el = edgeLabels[edge.id];\n let x = edge.x;\n let y = edge.y;\n if (path) {\n const pos = utils_default.calcLabelPosition(path);\n log.debug(\n \"Moving label \" + edge.label + \" from (\",\n x,\n \",\",\n y,\n \") to (\",\n pos.x,\n \",\",\n pos.y,\n \") abc88\"\n );\n if (paths.updatedPath) {\n x = pos.x;\n y = pos.y;\n }\n }\n el.attr(\"transform\", `translate(${x}, ${y + subGraphTitleTotalMargin / 2})`);\n }\n if (edge.startLabelLeft) {\n const el = terminalLabels[edge.id].startLeft;\n let x = edge.x;\n let y = edge.y;\n if (path) {\n const pos = utils_default.calcTerminalLabelPosition(edge.arrowTypeStart ? 10 : 0, \"start_left\", path);\n x = pos.x;\n y = pos.y;\n }\n el.attr(\"transform\", `translate(${x}, ${y})`);\n }\n if (edge.startLabelRight) {\n const el = terminalLabels[edge.id].startRight;\n let x = edge.x;\n let y = edge.y;\n if (path) {\n const pos = utils_default.calcTerminalLabelPosition(\n edge.arrowTypeStart ? 10 : 0,\n \"start_right\",\n path\n );\n x = pos.x;\n y = pos.y;\n }\n el.attr(\"transform\", `translate(${x}, ${y})`);\n }\n if (edge.endLabelLeft) {\n const el = terminalLabels[edge.id].endLeft;\n let x = edge.x;\n let y = edge.y;\n if (path) {\n const pos = utils_default.calcTerminalLabelPosition(edge.arrowTypeEnd ? 10 : 0, \"end_left\", path);\n x = pos.x;\n y = pos.y;\n }\n el.attr(\"transform\", `translate(${x}, ${y})`);\n }\n if (edge.endLabelRight) {\n const el = terminalLabels[edge.id].endRight;\n let x = edge.x;\n let y = edge.y;\n if (path) {\n const pos = utils_default.calcTerminalLabelPosition(edge.arrowTypeEnd ? 10 : 0, \"end_right\", path);\n x = pos.x;\n y = pos.y;\n }\n el.attr(\"transform\", `translate(${x}, ${y})`);\n }\n}, \"positionEdgeLabel\");\nvar outsideNode = /* @__PURE__ */ __name((node, point2) => {\n const x = node.x;\n const y = node.y;\n const dx = Math.abs(point2.x - x);\n const dy = Math.abs(point2.y - y);\n const w = node.width / 2;\n const h = node.height / 2;\n if (dx >= w || dy >= h) {\n return true;\n }\n return false;\n}, \"outsideNode\");\nvar intersection = /* @__PURE__ */ __name((node, outsidePoint, insidePoint) => {\n log.debug(`intersection calc abc89:\n outsidePoint: ${JSON.stringify(outsidePoint)}\n insidePoint : ${JSON.stringify(insidePoint)}\n node : x:${node.x} y:${node.y} w:${node.width} h:${node.height}`);\n const x = node.x;\n const y = node.y;\n const dx = Math.abs(x - insidePoint.x);\n const w = node.width / 2;\n let r = insidePoint.x < outsidePoint.x ? w - dx : w + dx;\n const h = node.height / 2;\n const Q = Math.abs(outsidePoint.y - insidePoint.y);\n const R = Math.abs(outsidePoint.x - insidePoint.x);\n if (Math.abs(y - outsidePoint.y) * w > Math.abs(x - outsidePoint.x) * h) {\n let q = insidePoint.y < outsidePoint.y ? outsidePoint.y - h - y : y - h - outsidePoint.y;\n r = R * q / Q;\n const res = {\n x: insidePoint.x < outsidePoint.x ? insidePoint.x + r : insidePoint.x - R + r,\n y: insidePoint.y < outsidePoint.y ? insidePoint.y + Q - q : insidePoint.y - Q + q\n };\n if (r === 0) {\n res.x = outsidePoint.x;\n res.y = outsidePoint.y;\n }\n if (R === 0) {\n res.x = outsidePoint.x;\n }\n if (Q === 0) {\n res.y = outsidePoint.y;\n }\n log.debug(`abc89 topp/bott calc, Q ${Q}, q ${q}, R ${R}, r ${r}`, res);\n return res;\n } else {\n if (insidePoint.x < outsidePoint.x) {\n r = outsidePoint.x - w - x;\n } else {\n r = x - w - outsidePoint.x;\n }\n let q = Q * r / R;\n let _x = insidePoint.x < outsidePoint.x ? insidePoint.x + R - r : insidePoint.x - R + r;\n let _y = insidePoint.y < outsidePoint.y ? insidePoint.y + q : insidePoint.y - q;\n log.debug(`sides calc abc89, Q ${Q}, q ${q}, R ${R}, r ${r}`, { _x, _y });\n if (r === 0) {\n _x = outsidePoint.x;\n _y = outsidePoint.y;\n }\n if (R === 0) {\n _x = outsidePoint.x;\n }\n if (Q === 0) {\n _y = outsidePoint.y;\n }\n return { x: _x, y: _y };\n }\n}, \"intersection\");\nvar cutPathAtIntersect = /* @__PURE__ */ __name((_points, boundaryNode) => {\n log.debug(\"abc88 cutPathAtIntersect\", _points, boundaryNode);\n let points = [];\n let lastPointOutside = _points[0];\n let isInside = false;\n _points.forEach((point2) => {\n if (!outsideNode(boundaryNode, point2) && !isInside) {\n const inter = intersection(boundaryNode, lastPointOutside, point2);\n let pointPresent = false;\n points.forEach((p) => {\n pointPresent = pointPresent || p.x === inter.x && p.y === inter.y;\n });\n if (!points.some((e) => e.x === inter.x && e.y === inter.y)) {\n points.push(inter);\n }\n isInside = true;\n } else {\n lastPointOutside = point2;\n if (!isInside) {\n points.push(point2);\n }\n }\n });\n return points;\n}, \"cutPathAtIntersect\");\nvar insertEdge = /* @__PURE__ */ __name(function(elem, e, edge, clusterDb, diagramType, graph, id) {\n let points = edge.points;\n log.debug(\"abc88 InsertEdge: edge=\", edge, \"e=\", e);\n let pointsHasChanged = false;\n const tail = graph.node(e.v);\n var head = graph.node(e.w);\n if (head?.intersect && tail?.intersect) {\n points = points.slice(1, edge.points.length - 1);\n points.unshift(tail.intersect(points[0]));\n points.push(head.intersect(points[points.length - 1]));\n }\n if (edge.toCluster) {\n log.debug(\"to cluster abc88\", clusterDb[edge.toCluster]);\n points = cutPathAtIntersect(edge.points, clusterDb[edge.toCluster].node);\n pointsHasChanged = true;\n }\n if (edge.fromCluster) {\n log.debug(\"from cluster abc88\", clusterDb[edge.fromCluster]);\n points = cutPathAtIntersect(points.reverse(), clusterDb[edge.fromCluster].node).reverse();\n pointsHasChanged = true;\n }\n const lineData = points.filter((p) => !Number.isNaN(p.y));\n let curve = curveBasis;\n if (edge.curve && (diagramType === \"graph\" || diagramType === \"flowchart\")) {\n curve = edge.curve;\n }\n const { x, y } = getLineFunctionsWithOffset(edge);\n const lineFunction = line().x(x).y(y).curve(curve);\n let strokeClasses;\n switch (edge.thickness) {\n case \"normal\":\n strokeClasses = \"edge-thickness-normal\";\n break;\n case \"thick\":\n strokeClasses = \"edge-thickness-thick\";\n break;\n case \"invisible\":\n strokeClasses = \"edge-thickness-thick\";\n break;\n default:\n strokeClasses = \"\";\n }\n switch (edge.pattern) {\n case \"solid\":\n strokeClasses += \" edge-pattern-solid\";\n break;\n case \"dotted\":\n strokeClasses += \" edge-pattern-dotted\";\n break;\n case \"dashed\":\n strokeClasses += \" edge-pattern-dashed\";\n break;\n }\n const svgPath = elem.append(\"path\").attr(\"d\", lineFunction(lineData)).attr(\"id\", edge.id).attr(\"class\", \" \" + strokeClasses + (edge.classes ? \" \" + edge.classes : \"\")).attr(\"style\", edge.style);\n let url = \"\";\n if (getConfig2().flowchart.arrowMarkerAbsolute || getConfig2().state.arrowMarkerAbsolute) {\n url = getUrl(true);\n }\n addEdgeMarkers(svgPath, edge, url, id, diagramType);\n let paths = {};\n if (pointsHasChanged) {\n paths.updatedPath = points;\n }\n paths.originalPath = edge.points;\n return paths;\n}, \"insertEdge\");\n\n// src/dagre-wrapper/nodes.js\nimport { select as select4 } from \"d3\";\n\n// src/dagre-wrapper/blockArrowHelper.ts\nvar expandAndDeduplicateDirections = /* @__PURE__ */ __name((directions) => {\n const uniqueDirections = /* @__PURE__ */ new Set();\n for (const direction of directions) {\n switch (direction) {\n case \"x\":\n uniqueDirections.add(\"right\");\n uniqueDirections.add(\"left\");\n break;\n case \"y\":\n uniqueDirections.add(\"up\");\n uniqueDirections.add(\"down\");\n break;\n default:\n uniqueDirections.add(direction);\n break;\n }\n }\n return uniqueDirections;\n}, \"expandAndDeduplicateDirections\");\nvar getArrowPoints = /* @__PURE__ */ __name((duplicatedDirections, bbox, node) => {\n const directions = expandAndDeduplicateDirections(duplicatedDirections);\n const f = 2;\n const height = bbox.height + 2 * node.padding;\n const midpoint = height / f;\n const width = bbox.width + 2 * midpoint + node.padding;\n const padding2 = node.padding / 2;\n if (directions.has(\"right\") && directions.has(\"left\") && directions.has(\"up\") && directions.has(\"down\")) {\n return [\n // Bottom\n { x: 0, y: 0 },\n { x: midpoint, y: 0 },\n { x: width / 2, y: 2 * padding2 },\n { x: width - midpoint, y: 0 },\n { x: width, y: 0 },\n // Right\n { x: width, y: -height / 3 },\n { x: width + 2 * padding2, y: -height / 2 },\n { x: width, y: -2 * height / 3 },\n { x: width, y: -height },\n // Top\n { x: width - midpoint, y: -height },\n { x: width / 2, y: -height - 2 * padding2 },\n { x: midpoint, y: -height },\n // Left\n { x: 0, y: -height },\n { x: 0, y: -2 * height / 3 },\n { x: -2 * padding2, y: -height / 2 },\n { x: 0, y: -height / 3 }\n ];\n }\n if (directions.has(\"right\") && directions.has(\"left\") && directions.has(\"up\")) {\n return [\n { x: midpoint, y: 0 },\n { x: width - midpoint, y: 0 },\n { x: width, y: -height / 2 },\n { x: width - midpoint, y: -height },\n { x: midpoint, y: -height },\n { x: 0, y: -height / 2 }\n ];\n }\n if (directions.has(\"right\") && directions.has(\"left\") && directions.has(\"down\")) {\n return [\n { x: 0, y: 0 },\n { x: midpoint, y: -height },\n { x: width - midpoint, y: -height },\n { x: width, y: 0 }\n ];\n }\n if (directions.has(\"right\") && directions.has(\"up\") && directions.has(\"down\")) {\n return [\n { x: 0, y: 0 },\n { x: width, y: -midpoint },\n { x: width, y: -height + midpoint },\n { x: 0, y: -height }\n ];\n }\n if (directions.has(\"left\") && directions.has(\"up\") && directions.has(\"down\")) {\n return [\n { x: width, y: 0 },\n { x: 0, y: -midpoint },\n { x: 0, y: -height + midpoint },\n { x: width, y: -height }\n ];\n }\n if (directions.has(\"right\") && directions.has(\"left\")) {\n return [\n { x: midpoint, y: 0 },\n { x: midpoint, y: -padding2 },\n { x: width - midpoint, y: -padding2 },\n { x: width - midpoint, y: 0 },\n { x: width, y: -height / 2 },\n { x: width - midpoint, y: -height },\n { x: width - midpoint, y: -height + padding2 },\n { x: midpoint, y: -height + padding2 },\n { x: midpoint, y: -height },\n { x: 0, y: -height / 2 }\n ];\n }\n if (directions.has(\"up\") && directions.has(\"down\")) {\n return [\n // Bottom center\n { x: width / 2, y: 0 },\n // Left pont of bottom arrow\n { x: 0, y: -padding2 },\n { x: midpoint, y: -padding2 },\n // Left top over vertical section\n { x: midpoint, y: -height + padding2 },\n { x: 0, y: -height + padding2 },\n // Top of arrow\n { x: width / 2, y: -height },\n { x: width, y: -height + padding2 },\n // Top of right vertical bar\n { x: width - midpoint, y: -height + padding2 },\n { x: width - midpoint, y: -padding2 },\n { x: width, y: -padding2 }\n ];\n }\n if (directions.has(\"right\") && directions.has(\"up\")) {\n return [\n { x: 0, y: 0 },\n { x: width, y: -midpoint },\n { x: 0, y: -height }\n ];\n }\n if (directions.has(\"right\") && directions.has(\"down\")) {\n return [\n { x: 0, y: 0 },\n { x: width, y: 0 },\n { x: 0, y: -height }\n ];\n }\n if (directions.has(\"left\") && directions.has(\"up\")) {\n return [\n { x: width, y: 0 },\n { x: 0, y: -midpoint },\n { x: width, y: -height }\n ];\n }\n if (directions.has(\"left\") && directions.has(\"down\")) {\n return [\n { x: width, y: 0 },\n { x: 0, y: 0 },\n { x: width, y: -height }\n ];\n }\n if (directions.has(\"right\")) {\n return [\n { x: midpoint, y: -padding2 },\n { x: midpoint, y: -padding2 },\n { x: width - midpoint, y: -padding2 },\n { x: width - midpoint, y: 0 },\n { x: width, y: -height / 2 },\n { x: width - midpoint, y: -height },\n { x: width - midpoint, y: -height + padding2 },\n // top left corner of arrow\n { x: midpoint, y: -height + padding2 },\n { x: midpoint, y: -height + padding2 }\n ];\n }\n if (directions.has(\"left\")) {\n return [\n { x: midpoint, y: 0 },\n { x: midpoint, y: -padding2 },\n // Two points, the right corners\n { x: width - midpoint, y: -padding2 },\n { x: width - midpoint, y: -height + padding2 },\n { x: midpoint, y: -height + padding2 },\n { x: midpoint, y: -height },\n { x: 0, y: -height / 2 }\n ];\n }\n if (directions.has(\"up\")) {\n return [\n // Bottom center\n { x: midpoint, y: -padding2 },\n // Left top over vertical section\n { x: midpoint, y: -height + padding2 },\n { x: 0, y: -height + padding2 },\n // Top of arrow\n { x: width / 2, y: -height },\n { x: width, y: -height + padding2 },\n // Top of right vertical bar\n { x: width - midpoint, y: -height + padding2 },\n { x: width - midpoint, y: -padding2 }\n ];\n }\n if (directions.has(\"down\")) {\n return [\n // Bottom center\n { x: width / 2, y: 0 },\n // Left pont of bottom arrow\n { x: 0, y: -padding2 },\n { x: midpoint, y: -padding2 },\n // Left top over vertical section\n { x: midpoint, y: -height + padding2 },\n { x: width - midpoint, y: -height + padding2 },\n { x: width - midpoint, y: -padding2 },\n { x: width, y: -padding2 }\n ];\n }\n return [{ x: 0, y: 0 }];\n}, \"getArrowPoints\");\n\n// src/dagre-wrapper/intersect/intersect-node.js\nfunction intersectNode(node, point2) {\n return node.intersect(point2);\n}\n__name(intersectNode, \"intersectNode\");\nvar intersect_node_default = intersectNode;\n\n// src/dagre-wrapper/intersect/intersect-ellipse.js\nfunction intersectEllipse(node, rx, ry, point2) {\n var cx = node.x;\n var cy = node.y;\n var px = cx - point2.x;\n var py = cy - point2.y;\n var det = Math.sqrt(rx * rx * py * py + ry * ry * px * px);\n var dx = Math.abs(rx * ry * px / det);\n if (point2.x < cx) {\n dx = -dx;\n }\n var dy = Math.abs(rx * ry * py / det);\n if (point2.y < cy) {\n dy = -dy;\n }\n return { x: cx + dx, y: cy + dy };\n}\n__name(intersectEllipse, \"intersectEllipse\");\nvar intersect_ellipse_default = intersectEllipse;\n\n// src/dagre-wrapper/intersect/intersect-circle.js\nfunction intersectCircle(node, rx, point2) {\n return intersect_ellipse_default(node, rx, rx, point2);\n}\n__name(intersectCircle, \"intersectCircle\");\nvar intersect_circle_default = intersectCircle;\n\n// src/dagre-wrapper/intersect/intersect-line.js\nfunction intersectLine(p1, p2, q1, q2) {\n var a1, a2, b1, b2, c1, c2;\n var r1, r2, r3, r4;\n var denom, offset, num;\n var x, y;\n a1 = p2.y - p1.y;\n b1 = p1.x - p2.x;\n c1 = p2.x * p1.y - p1.x * p2.y;\n r3 = a1 * q1.x + b1 * q1.y + c1;\n r4 = a1 * q2.x + b1 * q2.y + c1;\n if (r3 !== 0 && r4 !== 0 && sameSign(r3, r4)) {\n return;\n }\n a2 = q2.y - q1.y;\n b2 = q1.x - q2.x;\n c2 = q2.x * q1.y - q1.x * q2.y;\n r1 = a2 * p1.x + b2 * p1.y + c2;\n r2 = a2 * p2.x + b2 * p2.y + c2;\n if (r1 !== 0 && r2 !== 0 && sameSign(r1, r2)) {\n return;\n }\n denom = a1 * b2 - a2 * b1;\n if (denom === 0) {\n return;\n }\n offset = Math.abs(denom / 2);\n num = b1 * c2 - b2 * c1;\n x = num < 0 ? (num - offset) / denom : (num + offset) / denom;\n num = a2 * c1 - a1 * c2;\n y = num < 0 ? (num - offset) / denom : (num + offset) / denom;\n return { x, y };\n}\n__name(intersectLine, \"intersectLine\");\nfunction sameSign(r1, r2) {\n return r1 * r2 > 0;\n}\n__name(sameSign, \"sameSign\");\nvar intersect_line_default = intersectLine;\n\n// src/dagre-wrapper/intersect/intersect-polygon.js\nvar intersect_polygon_default = intersectPolygon;\nfunction intersectPolygon(node, polyPoints, point2) {\n var x1 = node.x;\n var y1 = node.y;\n var intersections = [];\n var minX = Number.POSITIVE_INFINITY;\n var minY = Number.POSITIVE_INFINITY;\n if (typeof polyPoints.forEach === \"function\") {\n polyPoints.forEach(function(entry) {\n minX = Math.min(minX, entry.x);\n minY = Math.min(minY, entry.y);\n });\n } else {\n minX = Math.min(minX, polyPoints.x);\n minY = Math.min(minY, polyPoints.y);\n }\n var left = x1 - node.width / 2 - minX;\n var top = y1 - node.height / 2 - minY;\n for (var i = 0; i < polyPoints.length; i++) {\n var p1 = polyPoints[i];\n var p2 = polyPoints[i < polyPoints.length - 1 ? i + 1 : 0];\n var intersect = intersect_line_default(\n node,\n point2,\n { x: left + p1.x, y: top + p1.y },\n { x: left + p2.x, y: top + p2.y }\n );\n if (intersect) {\n intersections.push(intersect);\n }\n }\n if (!intersections.length) {\n return node;\n }\n if (intersections.length > 1) {\n intersections.sort(function(p, q) {\n var pdx = p.x - point2.x;\n var pdy = p.y - point2.y;\n var distp = Math.sqrt(pdx * pdx + pdy * pdy);\n var qdx = q.x - point2.x;\n var qdy = q.y - point2.y;\n var distq = Math.sqrt(qdx * qdx + qdy * qdy);\n return distp < distq ? -1 : distp === distq ? 0 : 1;\n });\n }\n return intersections[0];\n}\n__name(intersectPolygon, \"intersectPolygon\");\n\n// src/dagre-wrapper/intersect/intersect-rect.js\nvar intersectRect = /* @__PURE__ */ __name((node, point2) => {\n var x = node.x;\n var y = node.y;\n var dx = point2.x - x;\n var dy = point2.y - y;\n var w = node.width / 2;\n var h = node.height / 2;\n var sx, sy;\n if (Math.abs(dy) * w > Math.abs(dx) * h) {\n if (dy < 0) {\n h = -h;\n }\n sx = dy === 0 ? 0 : h * dx / dy;\n sy = h;\n } else {\n if (dx < 0) {\n w = -w;\n }\n sx = w;\n sy = dx === 0 ? 0 : w * dy / dx;\n }\n return { x: x + sx, y: y + sy };\n}, \"intersectRect\");\nvar intersect_rect_default = intersectRect;\n\n// src/dagre-wrapper/intersect/index.js\nvar intersect_default = {\n node: intersect_node_default,\n circle: intersect_circle_default,\n ellipse: intersect_ellipse_default,\n polygon: intersect_polygon_default,\n rect: intersect_rect_default\n};\n\n// src/dagre-wrapper/shapes/util.js\nimport { select as select3 } from \"d3\";\nvar labelHelper = /* @__PURE__ */ __name(async (parent, node, _classes, isNode) => {\n const config2 = getConfig2();\n let classes2;\n const useHtmlLabels = node.useHtmlLabels || evaluate(config2.flowchart.htmlLabels);\n if (!_classes) {\n classes2 = \"node default\";\n } else {\n classes2 = _classes;\n }\n const shapeSvg = parent.insert(\"g\").attr(\"class\", classes2).attr(\"id\", node.domId || node.id);\n const label = shapeSvg.insert(\"g\").attr(\"class\", \"label\").attr(\"style\", node.labelStyle);\n let labelText;\n if (node.labelText === void 0) {\n labelText = \"\";\n } else {\n labelText = typeof node.labelText === \"string\" ? node.labelText : node.labelText[0];\n }\n const textNode = label.node();\n let text;\n if (node.labelType === \"markdown\") {\n text = createText(\n label,\n sanitizeText(decodeEntities(labelText), config2),\n {\n useHtmlLabels,\n width: node.width || config2.flowchart.wrappingWidth,\n classes: \"markdown-node-label\"\n },\n config2\n );\n } else {\n text = textNode.appendChild(\n await createLabel_default(\n sanitizeText(decodeEntities(labelText), config2),\n node.labelStyle,\n false,\n isNode\n )\n );\n }\n let bbox = text.getBBox();\n const halfPadding = node.padding / 2;\n if (evaluate(config2.flowchart.htmlLabels)) {\n const div = text.children[0];\n const dv = select3(text);\n const images = div.getElementsByTagName(\"img\");\n if (images) {\n const noImgText = labelText.replace(/]*>/g, \"\").trim() === \"\";\n await Promise.all(\n [...images].map(\n (img) => new Promise((res) => {\n function setupImage() {\n img.style.display = \"flex\";\n img.style.flexDirection = \"column\";\n if (noImgText) {\n const bodyFontSize = config2.fontSize ? config2.fontSize : window.getComputedStyle(document.body).fontSize;\n const enlargingFactor = 5;\n const width = parseInt(bodyFontSize, 10) * enlargingFactor + \"px\";\n img.style.minWidth = width;\n img.style.maxWidth = width;\n } else {\n img.style.width = \"100%\";\n }\n res(img);\n }\n __name(setupImage, \"setupImage\");\n setTimeout(() => {\n if (img.complete) {\n setupImage();\n }\n });\n img.addEventListener(\"error\", setupImage);\n img.addEventListener(\"load\", setupImage);\n })\n )\n );\n }\n bbox = div.getBoundingClientRect();\n dv.attr(\"width\", bbox.width);\n dv.attr(\"height\", bbox.height);\n }\n if (useHtmlLabels) {\n label.attr(\"transform\", \"translate(\" + -bbox.width / 2 + \", \" + -bbox.height / 2 + \")\");\n } else {\n label.attr(\"transform\", \"translate(0, \" + -bbox.height / 2 + \")\");\n }\n if (node.centerLabel) {\n label.attr(\"transform\", \"translate(\" + -bbox.width / 2 + \", \" + -bbox.height / 2 + \")\");\n }\n label.insert(\"rect\", \":first-child\");\n return { shapeSvg, bbox, halfPadding, label };\n}, \"labelHelper\");\nvar updateNodeBounds = /* @__PURE__ */ __name((node, element) => {\n const bbox = element.node().getBBox();\n node.width = bbox.width;\n node.height = bbox.height;\n}, \"updateNodeBounds\");\nfunction insertPolygonShape(parent, w, h, points) {\n return parent.insert(\"polygon\", \":first-child\").attr(\n \"points\",\n points.map(function(d) {\n return d.x + \",\" + d.y;\n }).join(\" \")\n ).attr(\"class\", \"label-container\").attr(\"transform\", \"translate(\" + -w / 2 + \",\" + h / 2 + \")\");\n}\n__name(insertPolygonShape, \"insertPolygonShape\");\n\n// src/dagre-wrapper/shapes/note.js\nvar note = /* @__PURE__ */ __name(async (parent, node) => {\n const useHtmlLabels = node.useHtmlLabels || getConfig2().flowchart.htmlLabels;\n if (!useHtmlLabels) {\n node.centerLabel = true;\n }\n const { shapeSvg, bbox, halfPadding } = await labelHelper(\n parent,\n node,\n \"node \" + node.classes,\n true\n );\n log.info(\"Classes = \", node.classes);\n const rect2 = shapeSvg.insert(\"rect\", \":first-child\");\n rect2.attr(\"rx\", node.rx).attr(\"ry\", node.ry).attr(\"x\", -bbox.width / 2 - halfPadding).attr(\"y\", -bbox.height / 2 - halfPadding).attr(\"width\", bbox.width + node.padding).attr(\"height\", bbox.height + node.padding);\n updateNodeBounds(node, rect2);\n node.intersect = function(point2) {\n return intersect_default.rect(node, point2);\n };\n return shapeSvg;\n}, \"note\");\nvar note_default = note;\n\n// src/dagre-wrapper/nodes.js\nvar formatClass = /* @__PURE__ */ __name((str) => {\n if (str) {\n return \" \" + str;\n }\n return \"\";\n}, \"formatClass\");\nvar getClassesFromNode = /* @__PURE__ */ __name((node, otherClasses) => {\n return `${otherClasses ? otherClasses : \"node default\"}${formatClass(node.classes)} ${formatClass(\n node.class\n )}`;\n}, \"getClassesFromNode\");\nvar question = /* @__PURE__ */ __name(async (parent, node) => {\n const { shapeSvg, bbox } = await labelHelper(\n parent,\n node,\n getClassesFromNode(node, void 0),\n true\n );\n const w = bbox.width + node.padding;\n const h = bbox.height + node.padding;\n const s = w + h;\n const points = [\n { x: s / 2, y: 0 },\n { x: s, y: -s / 2 },\n { x: s / 2, y: -s },\n { x: 0, y: -s / 2 }\n ];\n log.info(\"Question main (Circle)\");\n const questionElem = insertPolygonShape(shapeSvg, s, s, points);\n questionElem.attr(\"style\", node.style);\n updateNodeBounds(node, questionElem);\n node.intersect = function(point2) {\n log.warn(\"Intersect called\");\n return intersect_default.polygon(node, points, point2);\n };\n return shapeSvg;\n}, \"question\");\nvar choice = /* @__PURE__ */ __name((parent, node) => {\n const shapeSvg = parent.insert(\"g\").attr(\"class\", \"node default\").attr(\"id\", node.domId || node.id);\n const s = 28;\n const points = [\n { x: 0, y: s / 2 },\n { x: s / 2, y: 0 },\n { x: 0, y: -s / 2 },\n { x: -s / 2, y: 0 }\n ];\n const choice2 = shapeSvg.insert(\"polygon\", \":first-child\").attr(\n \"points\",\n points.map(function(d) {\n return d.x + \",\" + d.y;\n }).join(\" \")\n );\n choice2.attr(\"class\", \"state-start\").attr(\"r\", 7).attr(\"width\", 28).attr(\"height\", 28);\n node.width = 28;\n node.height = 28;\n node.intersect = function(point2) {\n return intersect_default.circle(node, 14, point2);\n };\n return shapeSvg;\n}, \"choice\");\nvar hexagon = /* @__PURE__ */ __name(async (parent, node) => {\n const { shapeSvg, bbox } = await labelHelper(\n parent,\n node,\n getClassesFromNode(node, void 0),\n true\n );\n const f = 4;\n const h = bbox.height + node.padding;\n const m = h / f;\n const w = bbox.width + 2 * m + node.padding;\n const points = [\n { x: m, y: 0 },\n { x: w - m, y: 0 },\n { x: w, y: -h / 2 },\n { x: w - m, y: -h },\n { x: m, y: -h },\n { x: 0, y: -h / 2 }\n ];\n const hex = insertPolygonShape(shapeSvg, w, h, points);\n hex.attr(\"style\", node.style);\n updateNodeBounds(node, hex);\n node.intersect = function(point2) {\n return intersect_default.polygon(node, points, point2);\n };\n return shapeSvg;\n}, \"hexagon\");\nvar block_arrow = /* @__PURE__ */ __name(async (parent, node) => {\n const { shapeSvg, bbox } = await labelHelper(parent, node, void 0, true);\n const f = 2;\n const h = bbox.height + 2 * node.padding;\n const m = h / f;\n const w = bbox.width + 2 * m + node.padding;\n const points = getArrowPoints(node.directions, bbox, node);\n const blockArrow = insertPolygonShape(shapeSvg, w, h, points);\n blockArrow.attr(\"style\", node.style);\n updateNodeBounds(node, blockArrow);\n node.intersect = function(point2) {\n return intersect_default.polygon(node, points, point2);\n };\n return shapeSvg;\n}, \"block_arrow\");\nvar rect_left_inv_arrow = /* @__PURE__ */ __name(async (parent, node) => {\n const { shapeSvg, bbox } = await labelHelper(\n parent,\n node,\n getClassesFromNode(node, void 0),\n true\n );\n const w = bbox.width + node.padding;\n const h = bbox.height + node.padding;\n const points = [\n { x: -h / 2, y: 0 },\n { x: w, y: 0 },\n { x: w, y: -h },\n { x: -h / 2, y: -h },\n { x: 0, y: -h / 2 }\n ];\n const el = insertPolygonShape(shapeSvg, w, h, points);\n el.attr(\"style\", node.style);\n node.width = w + h;\n node.height = h;\n node.intersect = function(point2) {\n return intersect_default.polygon(node, points, point2);\n };\n return shapeSvg;\n}, \"rect_left_inv_arrow\");\nvar lean_right = /* @__PURE__ */ __name(async (parent, node) => {\n const { shapeSvg, bbox } = await labelHelper(parent, node, getClassesFromNode(node), true);\n const w = bbox.width + node.padding;\n const h = bbox.height + node.padding;\n const points = [\n { x: -2 * h / 6, y: 0 },\n { x: w - h / 6, y: 0 },\n { x: w + 2 * h / 6, y: -h },\n { x: h / 6, y: -h }\n ];\n const el = insertPolygonShape(shapeSvg, w, h, points);\n el.attr(\"style\", node.style);\n updateNodeBounds(node, el);\n node.intersect = function(point2) {\n return intersect_default.polygon(node, points, point2);\n };\n return shapeSvg;\n}, \"lean_right\");\nvar lean_left = /* @__PURE__ */ __name(async (parent, node) => {\n const { shapeSvg, bbox } = await labelHelper(\n parent,\n node,\n getClassesFromNode(node, void 0),\n true\n );\n const w = bbox.width + node.padding;\n const h = bbox.height + node.padding;\n const points = [\n { x: 2 * h / 6, y: 0 },\n { x: w + h / 6, y: 0 },\n { x: w - 2 * h / 6, y: -h },\n { x: -h / 6, y: -h }\n ];\n const el = insertPolygonShape(shapeSvg, w, h, points);\n el.attr(\"style\", node.style);\n updateNodeBounds(node, el);\n node.intersect = function(point2) {\n return intersect_default.polygon(node, points, point2);\n };\n return shapeSvg;\n}, \"lean_left\");\nvar trapezoid = /* @__PURE__ */ __name(async (parent, node) => {\n const { shapeSvg, bbox } = await labelHelper(\n parent,\n node,\n getClassesFromNode(node, void 0),\n true\n );\n const w = bbox.width + node.padding;\n const h = bbox.height + node.padding;\n const points = [\n { x: -2 * h / 6, y: 0 },\n { x: w + 2 * h / 6, y: 0 },\n { x: w - h / 6, y: -h },\n { x: h / 6, y: -h }\n ];\n const el = insertPolygonShape(shapeSvg, w, h, points);\n el.attr(\"style\", node.style);\n updateNodeBounds(node, el);\n node.intersect = function(point2) {\n return intersect_default.polygon(node, points, point2);\n };\n return shapeSvg;\n}, \"trapezoid\");\nvar inv_trapezoid = /* @__PURE__ */ __name(async (parent, node) => {\n const { shapeSvg, bbox } = await labelHelper(\n parent,\n node,\n getClassesFromNode(node, void 0),\n true\n );\n const w = bbox.width + node.padding;\n const h = bbox.height + node.padding;\n const points = [\n { x: h / 6, y: 0 },\n { x: w - h / 6, y: 0 },\n { x: w + 2 * h / 6, y: -h },\n { x: -2 * h / 6, y: -h }\n ];\n const el = insertPolygonShape(shapeSvg, w, h, points);\n el.attr(\"style\", node.style);\n updateNodeBounds(node, el);\n node.intersect = function(point2) {\n return intersect_default.polygon(node, points, point2);\n };\n return shapeSvg;\n}, \"inv_trapezoid\");\nvar rect_right_inv_arrow = /* @__PURE__ */ __name(async (parent, node) => {\n const { shapeSvg, bbox } = await labelHelper(\n parent,\n node,\n getClassesFromNode(node, void 0),\n true\n );\n const w = bbox.width + node.padding;\n const h = bbox.height + node.padding;\n const points = [\n { x: 0, y: 0 },\n { x: w + h / 2, y: 0 },\n { x: w, y: -h / 2 },\n { x: w + h / 2, y: -h },\n { x: 0, y: -h }\n ];\n const el = insertPolygonShape(shapeSvg, w, h, points);\n el.attr(\"style\", node.style);\n updateNodeBounds(node, el);\n node.intersect = function(point2) {\n return intersect_default.polygon(node, points, point2);\n };\n return shapeSvg;\n}, \"rect_right_inv_arrow\");\nvar cylinder = /* @__PURE__ */ __name(async (parent, node) => {\n const { shapeSvg, bbox } = await labelHelper(\n parent,\n node,\n getClassesFromNode(node, void 0),\n true\n );\n const w = bbox.width + node.padding;\n const rx = w / 2;\n const ry = rx / (2.5 + w / 50);\n const h = bbox.height + ry + node.padding;\n const shape = \"M 0,\" + ry + \" a \" + rx + \",\" + ry + \" 0,0,0 \" + w + \" 0 a \" + rx + \",\" + ry + \" 0,0,0 \" + -w + \" 0 l 0,\" + h + \" a \" + rx + \",\" + ry + \" 0,0,0 \" + w + \" 0 l 0,\" + -h;\n const el = shapeSvg.attr(\"label-offset-y\", ry).insert(\"path\", \":first-child\").attr(\"style\", node.style).attr(\"d\", shape).attr(\"transform\", \"translate(\" + -w / 2 + \",\" + -(h / 2 + ry) + \")\");\n updateNodeBounds(node, el);\n node.intersect = function(point2) {\n const pos = intersect_default.rect(node, point2);\n const x = pos.x - node.x;\n if (rx != 0 && (Math.abs(x) < node.width / 2 || Math.abs(x) == node.width / 2 && Math.abs(pos.y - node.y) > node.height / 2 - ry)) {\n let y = ry * ry * (1 - x * x / (rx * rx));\n if (y != 0) {\n y = Math.sqrt(y);\n }\n y = ry - y;\n if (point2.y - node.y > 0) {\n y = -y;\n }\n pos.y += y;\n }\n return pos;\n };\n return shapeSvg;\n}, \"cylinder\");\nvar rect = /* @__PURE__ */ __name(async (parent, node) => {\n const { shapeSvg, bbox, halfPadding } = await labelHelper(\n parent,\n node,\n \"node \" + node.classes + \" \" + node.class,\n true\n );\n const rect2 = shapeSvg.insert(\"rect\", \":first-child\");\n const totalWidth = node.positioned ? node.width : bbox.width + node.padding;\n const totalHeight = node.positioned ? node.height : bbox.height + node.padding;\n const x = node.positioned ? -totalWidth / 2 : -bbox.width / 2 - halfPadding;\n const y = node.positioned ? -totalHeight / 2 : -bbox.height / 2 - halfPadding;\n rect2.attr(\"class\", \"basic label-container\").attr(\"style\", node.style).attr(\"rx\", node.rx).attr(\"ry\", node.ry).attr(\"x\", x).attr(\"y\", y).attr(\"width\", totalWidth).attr(\"height\", totalHeight);\n if (node.props) {\n const propKeys = new Set(Object.keys(node.props));\n if (node.props.borders) {\n applyNodePropertyBorders(rect2, node.props.borders, totalWidth, totalHeight);\n propKeys.delete(\"borders\");\n }\n propKeys.forEach((propKey) => {\n log.warn(`Unknown node property ${propKey}`);\n });\n }\n updateNodeBounds(node, rect2);\n node.intersect = function(point2) {\n return intersect_default.rect(node, point2);\n };\n return shapeSvg;\n}, \"rect\");\nvar composite = /* @__PURE__ */ __name(async (parent, node) => {\n const { shapeSvg, bbox, halfPadding } = await labelHelper(\n parent,\n node,\n \"node \" + node.classes,\n true\n );\n const rect2 = shapeSvg.insert(\"rect\", \":first-child\");\n const totalWidth = node.positioned ? node.width : bbox.width + node.padding;\n const totalHeight = node.positioned ? node.height : bbox.height + node.padding;\n const x = node.positioned ? -totalWidth / 2 : -bbox.width / 2 - halfPadding;\n const y = node.positioned ? -totalHeight / 2 : -bbox.height / 2 - halfPadding;\n rect2.attr(\"class\", \"basic cluster composite label-container\").attr(\"style\", node.style).attr(\"rx\", node.rx).attr(\"ry\", node.ry).attr(\"x\", x).attr(\"y\", y).attr(\"width\", totalWidth).attr(\"height\", totalHeight);\n if (node.props) {\n const propKeys = new Set(Object.keys(node.props));\n if (node.props.borders) {\n applyNodePropertyBorders(rect2, node.props.borders, totalWidth, totalHeight);\n propKeys.delete(\"borders\");\n }\n propKeys.forEach((propKey) => {\n log.warn(`Unknown node property ${propKey}`);\n });\n }\n updateNodeBounds(node, rect2);\n node.intersect = function(point2) {\n return intersect_default.rect(node, point2);\n };\n return shapeSvg;\n}, \"composite\");\nvar labelRect = /* @__PURE__ */ __name(async (parent, node) => {\n const { shapeSvg } = await labelHelper(parent, node, \"label\", true);\n log.trace(\"Classes = \", node.class);\n const rect2 = shapeSvg.insert(\"rect\", \":first-child\");\n const totalWidth = 0;\n const totalHeight = 0;\n rect2.attr(\"width\", totalWidth).attr(\"height\", totalHeight);\n shapeSvg.attr(\"class\", \"label edgeLabel\");\n if (node.props) {\n const propKeys = new Set(Object.keys(node.props));\n if (node.props.borders) {\n applyNodePropertyBorders(rect2, node.props.borders, totalWidth, totalHeight);\n propKeys.delete(\"borders\");\n }\n propKeys.forEach((propKey) => {\n log.warn(`Unknown node property ${propKey}`);\n });\n }\n updateNodeBounds(node, rect2);\n node.intersect = function(point2) {\n return intersect_default.rect(node, point2);\n };\n return shapeSvg;\n}, \"labelRect\");\nfunction applyNodePropertyBorders(rect2, borders, totalWidth, totalHeight) {\n const strokeDashArray = [];\n const addBorder = /* @__PURE__ */ __name((length) => {\n strokeDashArray.push(length, 0);\n }, \"addBorder\");\n const skipBorder = /* @__PURE__ */ __name((length) => {\n strokeDashArray.push(0, length);\n }, \"skipBorder\");\n if (borders.includes(\"t\")) {\n log.debug(\"add top border\");\n addBorder(totalWidth);\n } else {\n skipBorder(totalWidth);\n }\n if (borders.includes(\"r\")) {\n log.debug(\"add right border\");\n addBorder(totalHeight);\n } else {\n skipBorder(totalHeight);\n }\n if (borders.includes(\"b\")) {\n log.debug(\"add bottom border\");\n addBorder(totalWidth);\n } else {\n skipBorder(totalWidth);\n }\n if (borders.includes(\"l\")) {\n log.debug(\"add left border\");\n addBorder(totalHeight);\n } else {\n skipBorder(totalHeight);\n }\n rect2.attr(\"stroke-dasharray\", strokeDashArray.join(\" \"));\n}\n__name(applyNodePropertyBorders, \"applyNodePropertyBorders\");\nvar rectWithTitle = /* @__PURE__ */ __name(async (parent, node) => {\n let classes2;\n if (!node.classes) {\n classes2 = \"node default\";\n } else {\n classes2 = \"node \" + node.classes;\n }\n const shapeSvg = parent.insert(\"g\").attr(\"class\", classes2).attr(\"id\", node.domId || node.id);\n const rect2 = shapeSvg.insert(\"rect\", \":first-child\");\n const innerLine = shapeSvg.insert(\"line\");\n const label = shapeSvg.insert(\"g\").attr(\"class\", \"label\");\n const text2 = node.labelText.flat ? node.labelText.flat() : node.labelText;\n let title = \"\";\n if (typeof text2 === \"object\") {\n title = text2[0];\n } else {\n title = text2;\n }\n log.info(\"Label text abc79\", title, text2, typeof text2 === \"object\");\n const text = label.node().appendChild(await createLabel_default(title, node.labelStyle, true, true));\n let bbox = { width: 0, height: 0 };\n if (evaluate(getConfig2().flowchart.htmlLabels)) {\n const div = text.children[0];\n const dv = select4(text);\n bbox = div.getBoundingClientRect();\n dv.attr(\"width\", bbox.width);\n dv.attr(\"height\", bbox.height);\n }\n log.info(\"Text 2\", text2);\n const textRows = text2.slice(1, text2.length);\n let titleBox = text.getBBox();\n const descr = label.node().appendChild(\n await createLabel_default(\n textRows.join ? textRows.join(\"
\") : textRows,\n node.labelStyle,\n true,\n true\n )\n );\n if (evaluate(getConfig2().flowchart.htmlLabels)) {\n const div = descr.children[0];\n const dv = select4(descr);\n bbox = div.getBoundingClientRect();\n dv.attr(\"width\", bbox.width);\n dv.attr(\"height\", bbox.height);\n }\n const halfPadding = node.padding / 2;\n select4(descr).attr(\n \"transform\",\n \"translate( \" + // (titleBox.width - bbox.width) / 2 +\n (bbox.width > titleBox.width ? 0 : (titleBox.width - bbox.width) / 2) + \", \" + (titleBox.height + halfPadding + 5) + \")\"\n );\n select4(text).attr(\n \"transform\",\n \"translate( \" + // (titleBox.width - bbox.width) / 2 +\n (bbox.width < titleBox.width ? 0 : -(titleBox.width - bbox.width) / 2) + \", 0)\"\n );\n bbox = label.node().getBBox();\n label.attr(\n \"transform\",\n \"translate(\" + -bbox.width / 2 + \", \" + (-bbox.height / 2 - halfPadding + 3) + \")\"\n );\n rect2.attr(\"class\", \"outer title-state\").attr(\"x\", -bbox.width / 2 - halfPadding).attr(\"y\", -bbox.height / 2 - halfPadding).attr(\"width\", bbox.width + node.padding).attr(\"height\", bbox.height + node.padding);\n innerLine.attr(\"class\", \"divider\").attr(\"x1\", -bbox.width / 2 - halfPadding).attr(\"x2\", bbox.width / 2 + halfPadding).attr(\"y1\", -bbox.height / 2 - halfPadding + titleBox.height + halfPadding).attr(\"y2\", -bbox.height / 2 - halfPadding + titleBox.height + halfPadding);\n updateNodeBounds(node, rect2);\n node.intersect = function(point2) {\n return intersect_default.rect(node, point2);\n };\n return shapeSvg;\n}, \"rectWithTitle\");\nvar stadium = /* @__PURE__ */ __name(async (parent, node) => {\n const { shapeSvg, bbox } = await labelHelper(\n parent,\n node,\n getClassesFromNode(node, void 0),\n true\n );\n const h = bbox.height + node.padding;\n const w = bbox.width + h / 4 + node.padding;\n const rect2 = shapeSvg.insert(\"rect\", \":first-child\").attr(\"style\", node.style).attr(\"rx\", h / 2).attr(\"ry\", h / 2).attr(\"x\", -w / 2).attr(\"y\", -h / 2).attr(\"width\", w).attr(\"height\", h);\n updateNodeBounds(node, rect2);\n node.intersect = function(point2) {\n return intersect_default.rect(node, point2);\n };\n return shapeSvg;\n}, \"stadium\");\nvar circle2 = /* @__PURE__ */ __name(async (parent, node) => {\n const { shapeSvg, bbox, halfPadding } = await labelHelper(\n parent,\n node,\n getClassesFromNode(node, void 0),\n true\n );\n const circle3 = shapeSvg.insert(\"circle\", \":first-child\");\n circle3.attr(\"style\", node.style).attr(\"rx\", node.rx).attr(\"ry\", node.ry).attr(\"r\", bbox.width / 2 + halfPadding).attr(\"width\", bbox.width + node.padding).attr(\"height\", bbox.height + node.padding);\n log.info(\"Circle main\");\n updateNodeBounds(node, circle3);\n node.intersect = function(point2) {\n log.info(\"Circle intersect\", node, bbox.width / 2 + halfPadding, point2);\n return intersect_default.circle(node, bbox.width / 2 + halfPadding, point2);\n };\n return shapeSvg;\n}, \"circle\");\nvar doublecircle = /* @__PURE__ */ __name(async (parent, node) => {\n const { shapeSvg, bbox, halfPadding } = await labelHelper(\n parent,\n node,\n getClassesFromNode(node, void 0),\n true\n );\n const gap = 5;\n const circleGroup = shapeSvg.insert(\"g\", \":first-child\");\n const outerCircle = circleGroup.insert(\"circle\");\n const innerCircle = circleGroup.insert(\"circle\");\n circleGroup.attr(\"class\", node.class);\n outerCircle.attr(\"style\", node.style).attr(\"rx\", node.rx).attr(\"ry\", node.ry).attr(\"r\", bbox.width / 2 + halfPadding + gap).attr(\"width\", bbox.width + node.padding + gap * 2).attr(\"height\", bbox.height + node.padding + gap * 2);\n innerCircle.attr(\"style\", node.style).attr(\"rx\", node.rx).attr(\"ry\", node.ry).attr(\"r\", bbox.width / 2 + halfPadding).attr(\"width\", bbox.width + node.padding).attr(\"height\", bbox.height + node.padding);\n log.info(\"DoubleCircle main\");\n updateNodeBounds(node, outerCircle);\n node.intersect = function(point2) {\n log.info(\"DoubleCircle intersect\", node, bbox.width / 2 + halfPadding + gap, point2);\n return intersect_default.circle(node, bbox.width / 2 + halfPadding + gap, point2);\n };\n return shapeSvg;\n}, \"doublecircle\");\nvar subroutine = /* @__PURE__ */ __name(async (parent, node) => {\n const { shapeSvg, bbox } = await labelHelper(\n parent,\n node,\n getClassesFromNode(node, void 0),\n true\n );\n const w = bbox.width + node.padding;\n const h = bbox.height + node.padding;\n const points = [\n { x: 0, y: 0 },\n { x: w, y: 0 },\n { x: w, y: -h },\n { x: 0, y: -h },\n { x: 0, y: 0 },\n { x: -8, y: 0 },\n { x: w + 8, y: 0 },\n { x: w + 8, y: -h },\n { x: -8, y: -h },\n { x: -8, y: 0 }\n ];\n const el = insertPolygonShape(shapeSvg, w, h, points);\n el.attr(\"style\", node.style);\n updateNodeBounds(node, el);\n node.intersect = function(point2) {\n return intersect_default.polygon(node, points, point2);\n };\n return shapeSvg;\n}, \"subroutine\");\nvar start = /* @__PURE__ */ __name((parent, node) => {\n const shapeSvg = parent.insert(\"g\").attr(\"class\", \"node default\").attr(\"id\", node.domId || node.id);\n const circle3 = shapeSvg.insert(\"circle\", \":first-child\");\n circle3.attr(\"class\", \"state-start\").attr(\"r\", 7).attr(\"width\", 14).attr(\"height\", 14);\n updateNodeBounds(node, circle3);\n node.intersect = function(point2) {\n return intersect_default.circle(node, 7, point2);\n };\n return shapeSvg;\n}, \"start\");\nvar forkJoin = /* @__PURE__ */ __name((parent, node, dir) => {\n const shapeSvg = parent.insert(\"g\").attr(\"class\", \"node default\").attr(\"id\", node.domId || node.id);\n let width = 70;\n let height = 10;\n if (dir === \"LR\") {\n width = 10;\n height = 70;\n }\n const shape = shapeSvg.append(\"rect\").attr(\"x\", -1 * width / 2).attr(\"y\", -1 * height / 2).attr(\"width\", width).attr(\"height\", height).attr(\"class\", \"fork-join\");\n updateNodeBounds(node, shape);\n node.height = node.height + node.padding / 2;\n node.width = node.width + node.padding / 2;\n node.intersect = function(point2) {\n return intersect_default.rect(node, point2);\n };\n return shapeSvg;\n}, \"forkJoin\");\nvar end = /* @__PURE__ */ __name((parent, node) => {\n const shapeSvg = parent.insert(\"g\").attr(\"class\", \"node default\").attr(\"id\", node.domId || node.id);\n const innerCircle = shapeSvg.insert(\"circle\", \":first-child\");\n const circle3 = shapeSvg.insert(\"circle\", \":first-child\");\n circle3.attr(\"class\", \"state-start\").attr(\"r\", 7).attr(\"width\", 14).attr(\"height\", 14);\n innerCircle.attr(\"class\", \"state-end\").attr(\"r\", 5).attr(\"width\", 10).attr(\"height\", 10);\n updateNodeBounds(node, circle3);\n node.intersect = function(point2) {\n return intersect_default.circle(node, 7, point2);\n };\n return shapeSvg;\n}, \"end\");\nvar class_box = /* @__PURE__ */ __name(async (parent, node) => {\n const halfPadding = node.padding / 2;\n const rowPadding = 4;\n const lineHeight = 8;\n let classes2;\n if (!node.classes) {\n classes2 = \"node default\";\n } else {\n classes2 = \"node \" + node.classes;\n }\n const shapeSvg = parent.insert(\"g\").attr(\"class\", classes2).attr(\"id\", node.domId || node.id);\n const rect2 = shapeSvg.insert(\"rect\", \":first-child\");\n const topLine = shapeSvg.insert(\"line\");\n const bottomLine = shapeSvg.insert(\"line\");\n let maxWidth = 0;\n let maxHeight = rowPadding;\n const labelContainer = shapeSvg.insert(\"g\").attr(\"class\", \"label\");\n let verticalPos = 0;\n const hasInterface = node.classData.annotations?.[0];\n const interfaceLabelText = node.classData.annotations[0] ? \"\\xAB\" + node.classData.annotations[0] + \"\\xBB\" : \"\";\n const interfaceLabel = labelContainer.node().appendChild(await createLabel_default(interfaceLabelText, node.labelStyle, true, true));\n let interfaceBBox = interfaceLabel.getBBox();\n if (evaluate(getConfig2().flowchart.htmlLabels)) {\n const div = interfaceLabel.children[0];\n const dv = select4(interfaceLabel);\n interfaceBBox = div.getBoundingClientRect();\n dv.attr(\"width\", interfaceBBox.width);\n dv.attr(\"height\", interfaceBBox.height);\n }\n if (node.classData.annotations[0]) {\n maxHeight += interfaceBBox.height + rowPadding;\n maxWidth += interfaceBBox.width;\n }\n let classTitleString = node.classData.label;\n if (node.classData.type !== void 0 && node.classData.type !== \"\") {\n if (getConfig2().flowchart.htmlLabels) {\n classTitleString += \"<\" + node.classData.type + \">\";\n } else {\n classTitleString += \"<\" + node.classData.type + \">\";\n }\n }\n const classTitleLabel = labelContainer.node().appendChild(await createLabel_default(classTitleString, node.labelStyle, true, true));\n select4(classTitleLabel).attr(\"class\", \"classTitle\");\n let classTitleBBox = classTitleLabel.getBBox();\n if (evaluate(getConfig2().flowchart.htmlLabels)) {\n const div = classTitleLabel.children[0];\n const dv = select4(classTitleLabel);\n classTitleBBox = div.getBoundingClientRect();\n dv.attr(\"width\", classTitleBBox.width);\n dv.attr(\"height\", classTitleBBox.height);\n }\n maxHeight += classTitleBBox.height + rowPadding;\n if (classTitleBBox.width > maxWidth) {\n maxWidth = classTitleBBox.width;\n }\n const classAttributes = [];\n node.classData.members.forEach(async (member) => {\n const parsedInfo = member.getDisplayDetails();\n let parsedText = parsedInfo.displayText;\n if (getConfig2().flowchart.htmlLabels) {\n parsedText = parsedText.replace(//g, \">\");\n }\n const lbl = labelContainer.node().appendChild(\n await createLabel_default(\n parsedText,\n parsedInfo.cssStyle ? parsedInfo.cssStyle : node.labelStyle,\n true,\n true\n )\n );\n let bbox = lbl.getBBox();\n if (evaluate(getConfig2().flowchart.htmlLabels)) {\n const div = lbl.children[0];\n const dv = select4(lbl);\n bbox = div.getBoundingClientRect();\n dv.attr(\"width\", bbox.width);\n dv.attr(\"height\", bbox.height);\n }\n if (bbox.width > maxWidth) {\n maxWidth = bbox.width;\n }\n maxHeight += bbox.height + rowPadding;\n classAttributes.push(lbl);\n });\n maxHeight += lineHeight;\n const classMethods = [];\n node.classData.methods.forEach(async (member) => {\n const parsedInfo = member.getDisplayDetails();\n let displayText = parsedInfo.displayText;\n if (getConfig2().flowchart.htmlLabels) {\n displayText = displayText.replace(//g, \">\");\n }\n const lbl = labelContainer.node().appendChild(\n await createLabel_default(\n displayText,\n parsedInfo.cssStyle ? parsedInfo.cssStyle : node.labelStyle,\n true,\n true\n )\n );\n let bbox = lbl.getBBox();\n if (evaluate(getConfig2().flowchart.htmlLabels)) {\n const div = lbl.children[0];\n const dv = select4(lbl);\n bbox = div.getBoundingClientRect();\n dv.attr(\"width\", bbox.width);\n dv.attr(\"height\", bbox.height);\n }\n if (bbox.width > maxWidth) {\n maxWidth = bbox.width;\n }\n maxHeight += bbox.height + rowPadding;\n classMethods.push(lbl);\n });\n maxHeight += lineHeight;\n if (hasInterface) {\n let diffX2 = (maxWidth - interfaceBBox.width) / 2;\n select4(interfaceLabel).attr(\n \"transform\",\n \"translate( \" + (-1 * maxWidth / 2 + diffX2) + \", \" + -1 * maxHeight / 2 + \")\"\n );\n verticalPos = interfaceBBox.height + rowPadding;\n }\n let diffX = (maxWidth - classTitleBBox.width) / 2;\n select4(classTitleLabel).attr(\n \"transform\",\n \"translate( \" + (-1 * maxWidth / 2 + diffX) + \", \" + (-1 * maxHeight / 2 + verticalPos) + \")\"\n );\n verticalPos += classTitleBBox.height + rowPadding;\n topLine.attr(\"class\", \"divider\").attr(\"x1\", -maxWidth / 2 - halfPadding).attr(\"x2\", maxWidth / 2 + halfPadding).attr(\"y1\", -maxHeight / 2 - halfPadding + lineHeight + verticalPos).attr(\"y2\", -maxHeight / 2 - halfPadding + lineHeight + verticalPos);\n verticalPos += lineHeight;\n classAttributes.forEach((lbl) => {\n select4(lbl).attr(\n \"transform\",\n \"translate( \" + -maxWidth / 2 + \", \" + (-1 * maxHeight / 2 + verticalPos + lineHeight / 2) + \")\"\n );\n const memberBBox = lbl?.getBBox();\n verticalPos += (memberBBox?.height ?? 0) + rowPadding;\n });\n verticalPos += lineHeight;\n bottomLine.attr(\"class\", \"divider\").attr(\"x1\", -maxWidth / 2 - halfPadding).attr(\"x2\", maxWidth / 2 + halfPadding).attr(\"y1\", -maxHeight / 2 - halfPadding + lineHeight + verticalPos).attr(\"y2\", -maxHeight / 2 - halfPadding + lineHeight + verticalPos);\n verticalPos += lineHeight;\n classMethods.forEach((lbl) => {\n select4(lbl).attr(\n \"transform\",\n \"translate( \" + -maxWidth / 2 + \", \" + (-1 * maxHeight / 2 + verticalPos) + \")\"\n );\n const memberBBox = lbl?.getBBox();\n verticalPos += (memberBBox?.height ?? 0) + rowPadding;\n });\n rect2.attr(\"style\", node.style).attr(\"class\", \"outer title-state\").attr(\"x\", -maxWidth / 2 - halfPadding).attr(\"y\", -(maxHeight / 2) - halfPadding).attr(\"width\", maxWidth + node.padding).attr(\"height\", maxHeight + node.padding);\n updateNodeBounds(node, rect2);\n node.intersect = function(point2) {\n return intersect_default.rect(node, point2);\n };\n return shapeSvg;\n}, \"class_box\");\nvar shapes = {\n rhombus: question,\n composite,\n question,\n rect,\n labelRect,\n rectWithTitle,\n choice,\n circle: circle2,\n doublecircle,\n stadium,\n hexagon,\n block_arrow,\n rect_left_inv_arrow,\n lean_right,\n lean_left,\n trapezoid,\n inv_trapezoid,\n rect_right_inv_arrow,\n cylinder,\n start,\n end,\n note: note_default,\n subroutine,\n fork: forkJoin,\n join: forkJoin,\n class_box\n};\nvar nodeElems = {};\nvar insertNode = /* @__PURE__ */ __name(async (elem, node, renderOptions) => {\n let newEl;\n let el;\n if (node.link) {\n let target;\n if (getConfig2().securityLevel === \"sandbox\") {\n target = \"_top\";\n } else if (node.linkTarget) {\n target = node.linkTarget || \"_blank\";\n }\n newEl = elem.insert(\"svg:a\").attr(\"xlink:href\", node.link).attr(\"target\", target);\n el = await shapes[node.shape](newEl, node, renderOptions);\n } else {\n el = await shapes[node.shape](elem, node, renderOptions);\n newEl = el;\n }\n if (node.tooltip) {\n el.attr(\"title\", node.tooltip);\n }\n if (node.class) {\n el.attr(\"class\", \"node default \" + node.class);\n }\n nodeElems[node.id] = newEl;\n if (node.haveCallback) {\n nodeElems[node.id].attr(\"class\", nodeElems[node.id].attr(\"class\") + \" clickable\");\n }\n return newEl;\n}, \"insertNode\");\nvar positionNode = /* @__PURE__ */ __name((node) => {\n const el = nodeElems[node.id];\n log.trace(\n \"Transforming node\",\n node.diff,\n node,\n \"translate(\" + (node.x - node.width / 2 - 5) + \", \" + node.width / 2 + \")\"\n );\n const padding2 = 8;\n const diff = node.diff || 0;\n if (node.clusterNode) {\n el.attr(\n \"transform\",\n \"translate(\" + (node.x + diff - node.width / 2) + \", \" + (node.y - node.height / 2 - padding2) + \")\"\n );\n } else {\n el.attr(\"transform\", \"translate(\" + node.x + \", \" + node.y + \")\");\n }\n return diff;\n}, \"positionNode\");\n\n// src/diagrams/block/renderHelpers.ts\nfunction getNodeFromBlock(block, db2, positioned = false) {\n const vertex = block;\n let classStr = \"default\";\n if ((vertex?.classes?.length || 0) > 0) {\n classStr = (vertex?.classes ?? []).join(\" \");\n }\n classStr = classStr + \" flowchart-label\";\n let radius = 0;\n let shape = \"\";\n let padding2;\n switch (vertex.type) {\n case \"round\":\n radius = 5;\n shape = \"rect\";\n break;\n case \"composite\":\n radius = 0;\n shape = \"composite\";\n padding2 = 0;\n break;\n case \"square\":\n shape = \"rect\";\n break;\n case \"diamond\":\n shape = \"question\";\n break;\n case \"hexagon\":\n shape = \"hexagon\";\n break;\n case \"block_arrow\":\n shape = \"block_arrow\";\n break;\n case \"odd\":\n shape = \"rect_left_inv_arrow\";\n break;\n case \"lean_right\":\n shape = \"lean_right\";\n break;\n case \"lean_left\":\n shape = \"lean_left\";\n break;\n case \"trapezoid\":\n shape = \"trapezoid\";\n break;\n case \"inv_trapezoid\":\n shape = \"inv_trapezoid\";\n break;\n case \"rect_left_inv_arrow\":\n shape = \"rect_left_inv_arrow\";\n break;\n case \"circle\":\n shape = \"circle\";\n break;\n case \"ellipse\":\n shape = \"ellipse\";\n break;\n case \"stadium\":\n shape = \"stadium\";\n break;\n case \"subroutine\":\n shape = \"subroutine\";\n break;\n case \"cylinder\":\n shape = \"cylinder\";\n break;\n case \"group\":\n shape = \"rect\";\n break;\n case \"doublecircle\":\n shape = \"doublecircle\";\n break;\n default:\n shape = \"rect\";\n }\n const styles = getStylesFromArray(vertex?.styles ?? []);\n const vertexText = vertex.label;\n const bounds = vertex.size ?? { width: 0, height: 0, x: 0, y: 0 };\n const node = {\n labelStyle: styles.labelStyle,\n shape,\n labelText: vertexText,\n rx: radius,\n ry: radius,\n class: classStr,\n style: styles.style,\n id: vertex.id,\n directions: vertex.directions,\n width: bounds.width,\n height: bounds.height,\n x: bounds.x,\n y: bounds.y,\n positioned,\n intersect: void 0,\n type: vertex.type,\n padding: padding2 ?? getConfig()?.block?.padding ?? 0\n };\n return node;\n}\n__name(getNodeFromBlock, \"getNodeFromBlock\");\nasync function calculateBlockSize(elem, block, db2) {\n const node = getNodeFromBlock(block, db2, false);\n if (node.type === \"group\") {\n return;\n }\n const config2 = getConfig();\n const nodeEl = await insertNode(elem, node, { config: config2 });\n const boundingBox = nodeEl.node().getBBox();\n const obj = db2.getBlock(node.id);\n obj.size = { width: boundingBox.width, height: boundingBox.height, x: 0, y: 0, node: nodeEl };\n db2.setBlock(obj);\n nodeEl.remove();\n}\n__name(calculateBlockSize, \"calculateBlockSize\");\nasync function insertBlockPositioned(elem, block, db2) {\n const node = getNodeFromBlock(block, db2, true);\n const obj = db2.getBlock(node.id);\n if (obj.type !== \"space\") {\n const config2 = getConfig();\n await insertNode(elem, node, { config: config2 });\n block.intersect = node?.intersect;\n positionNode(node);\n }\n}\n__name(insertBlockPositioned, \"insertBlockPositioned\");\nasync function performOperations(elem, blocks2, db2, operation) {\n for (const block of blocks2) {\n await operation(elem, block, db2);\n if (block.children) {\n await performOperations(elem, block.children, db2, operation);\n }\n }\n}\n__name(performOperations, \"performOperations\");\nasync function calculateBlockSizes(elem, blocks2, db2) {\n await performOperations(elem, blocks2, db2, calculateBlockSize);\n}\n__name(calculateBlockSizes, \"calculateBlockSizes\");\nasync function insertBlocks(elem, blocks2, db2) {\n await performOperations(elem, blocks2, db2, insertBlockPositioned);\n}\n__name(insertBlocks, \"insertBlocks\");\nasync function insertEdges(elem, edges, blocks2, db2, id) {\n const g = new graphlib.Graph({\n multigraph: true,\n compound: true\n });\n g.setGraph({\n rankdir: \"TB\",\n nodesep: 10,\n ranksep: 10,\n marginx: 8,\n marginy: 8\n });\n for (const block of blocks2) {\n if (block.size) {\n g.setNode(block.id, {\n width: block.size.width,\n height: block.size.height,\n intersect: block.intersect\n });\n }\n }\n for (const edge of edges) {\n if (edge.start && edge.end) {\n const startBlock = db2.getBlock(edge.start);\n const endBlock = db2.getBlock(edge.end);\n if (startBlock?.size && endBlock?.size) {\n const start2 = startBlock.size;\n const end2 = endBlock.size;\n const points = [\n { x: start2.x, y: start2.y },\n { x: start2.x + (end2.x - start2.x) / 2, y: start2.y + (end2.y - start2.y) / 2 },\n { x: end2.x, y: end2.y }\n ];\n insertEdge(\n elem,\n { v: edge.start, w: edge.end, name: edge.id },\n {\n ...edge,\n arrowTypeEnd: edge.arrowTypeEnd,\n arrowTypeStart: edge.arrowTypeStart,\n points,\n classes: \"edge-thickness-normal edge-pattern-solid flowchart-link LS-a1 LE-b1\"\n },\n void 0,\n \"block\",\n g,\n id\n );\n if (edge.label) {\n await insertEdgeLabel(elem, {\n ...edge,\n label: edge.label,\n labelStyle: \"stroke: #333; stroke-width: 1.5px;fill:none;\",\n arrowTypeEnd: edge.arrowTypeEnd,\n arrowTypeStart: edge.arrowTypeStart,\n points,\n classes: \"edge-thickness-normal edge-pattern-solid flowchart-link LS-a1 LE-b1\"\n });\n positionEdgeLabel(\n { ...edge, x: points[1].x, y: points[1].y },\n {\n originalPath: points\n }\n );\n }\n }\n }\n }\n}\n__name(insertEdges, \"insertEdges\");\n\n// src/diagrams/block/blockRenderer.ts\nvar getClasses2 = /* @__PURE__ */ __name(function(text, diagObj) {\n return diagObj.db.getClasses();\n}, \"getClasses\");\nvar draw = /* @__PURE__ */ __name(async function(text, id, _version, diagObj) {\n const { securityLevel, block: conf } = getConfig();\n const db2 = diagObj.db;\n let sandboxElement;\n if (securityLevel === \"sandbox\") {\n sandboxElement = d3select(\"#i\" + id);\n }\n const root = securityLevel === \"sandbox\" ? d3select(sandboxElement.nodes()[0].contentDocument.body) : d3select(\"body\");\n const svg = securityLevel === \"sandbox\" ? root.select(`[id=\"${id}\"]`) : d3select(`[id=\"${id}\"]`);\n const markers2 = [\"point\", \"circle\", \"cross\"];\n markers_default(svg, markers2, diagObj.type, id);\n const bl = db2.getBlocks();\n const blArr = db2.getBlocksFlat();\n const edges = db2.getEdges();\n const nodes = svg.insert(\"g\").attr(\"class\", \"block\");\n await calculateBlockSizes(nodes, bl, db2);\n const bounds = layout(db2);\n await insertBlocks(nodes, bl, db2);\n await insertEdges(nodes, edges, blArr, db2, id);\n if (bounds) {\n const bounds2 = bounds;\n const magicFactor = Math.max(1, Math.round(0.125 * (bounds2.width / bounds2.height)));\n const height = bounds2.height + magicFactor + 10;\n const width = bounds2.width + 10;\n const { useMaxWidth } = conf;\n configureSvgSize(svg, height, width, !!useMaxWidth);\n log.debug(\"Here Bounds\", bounds, bounds2);\n svg.attr(\n \"viewBox\",\n `${bounds2.x - 5} ${bounds2.y - 5} ${bounds2.width + 10} ${bounds2.height + 10}`\n );\n }\n}, \"draw\");\nvar blockRenderer_default = {\n draw,\n getClasses: getClasses2\n};\n\n// src/diagrams/block/blockDiagram.ts\nvar diagram = {\n parser: block_default,\n db: blockDB_default,\n renderer: blockRenderer_default,\n styles: styles_default\n};\nexport {\n diagram\n};\n"], + "mappings": "+oBAkCA,IAAIA,IAAU,UAAW,CACvB,IAAIC,EAAoBC,EAAO,SAASC,EAAGC,EAAGC,EAAIC,EAAG,CACnD,IAAKD,EAAKA,GAAM,CAAC,EAAGC,EAAIH,EAAE,OAAQG,IAAKD,EAAGF,EAAEG,CAAC,CAAC,EAA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$V9", "$Va", "$Vb", "$Vc", "$Vd", "$Ve", "parser2", "yytext", "yyleng", "yylineno", "yy", "yystate", "$$", "_$", "$0", "num", "spaceId", "edgeData", "id2", "id", "str", "hash", "error", "input", "self", "stack", "tstack", "vstack", "lstack", "table", "recovering", "TERROR", "EOF", "args", "lexer2", "sharedState", "yyloc", "ranges", "popStack", "n", "lex", "token", "symbol", "preErrorSymbol", "state", "action", "a", "r", "yyval", "p", "len", "newState", "expected", "errStr", "lexer", "ch", "lines", "oldLines", "past", "next", "pre", "c", "match", "indexed_rule", "backup", "tempMatch", "index", "rules", "i", "condition", "yy_", "$avoiding_name_collisions", "YY_START", "YYSTATE", "Parser", "block_default", "blockDatabase", "edgeList", "edgeCount", "COLOR_KEYWORD", "FILL_KEYWORD", "BG_FILL", "STYLECLASS_SEP", "config", "getConfig2", "classes", "sanitizeText2", "txt", "common_default", "addStyleClass", "styleAttributes", "foundClass", "attrib", "fixedAttrib", "newStyle2", "addStyle2Node", "styles", "foundBlock", "setCssClass", "itemIds", "cssClassName", "trimmedId", "populateBlockDatabase", "_blockList", "parent", "blockList", "children", "column", "b", "block", "log", "count", "existingBlock", "w", "j", "newBlock", "clone_default", "blocks", "rootBlock", "clear2", "clear", "typeStr2Type", "typeStr", "edgeTypeStr2Type", "edgeStrToEdgeData", "cnt", "generateId", "setHierarchy", "getColumns", "blockId", "getBlocksFlat", "getBlocks", "getEdges", "getBlock", "setBlock", "getLogger", "getClasses", "db", "getConfig", "blockDB_default", "fade", "color", "opacity", "channel2", "channel_default", "g", "rgba_default", "getStyles", "options", "getIconStyles", "styles_default", "insertMarkers", "elem", "markerArray", "type", "markerName", "markers", "extension", "composition", "aggregation", "dependency", "lollipop", "point", "circle", "cross", "barb", "markers_default", "padding", "calculateBlockPosition", "columns", "position", "px", "py", "getMaxChildSize", "maxWidth", "maxHeight", "child", "width", "height", "x", "y", "setBlockSizes", "db2", "siblingWidth", "siblingHeight", "childSize", "numItems", "xSize", "ySize", "childWidth", "childHeight", "layoutBlocks", "widthOfChildren", "columnPos", "startingPosX", "rowPos", "width2", "halfWidth", "columnsFilled", "findBounds", "minX", "minY", "maxX", "maxY", "layout", "root", "applyStyle", "dom", "styleFn", "addHtmlLabel", "node", "config2", "fo", "select_default", "div", "label", "labelClass", "span", "sanitizeText", "createLabel", "_vertexText", "style", "isTitle", "isNode", "vertexText", "evaluate", "replaceIconSubstring", "decodeEntities", "svgLabel", "rows", "row", "tspan", "createLabel_default", "addEdgeMarkers", "svgPath", "edge", "url", "diagramType", "addEdgeMarker", "arrowTypesMap", "arrowType", "endMarkerType", "suffix", "edgeLabels", "terminalLabels", "insertEdgeLabel", "useHtmlLabels", "labelElement", "createText", "edgeLabel", "bbox", "dv", "startLabelElement", "startEdgeLabelLeft", "inner", "slBox", "setTerminalWidth", "startEdgeLabelRight", "endLabelElement", "endEdgeLabelLeft", "endEdgeLabelRight", "value", "positionEdgeLabel", "paths", "path", "siteConfig", "subGraphTitleTotalMargin", "getSubGraphTitleMargins", "el", "pos", "utils_default", "outsideNode", "point2", "dx", "dy", "h", "intersection", "outsidePoint", "insidePoint", "Q", "R", "q", "res", "_x", "_y", "cutPathAtIntersect", "_points", "boundaryNode", "points", "lastPointOutside", "isInside", "inter", "pointPresent", "e", "insertEdge", "clusterDb", "graph", "pointsHasChanged", "tail", "head", "lineData", "curve", "basis_default", "getLineFunctionsWithOffset", "lineFunction", "line_default", "strokeClasses", "getUrl", "expandAndDeduplicateDirections", "directions", "uniqueDirections", "direction", "getArrowPoints", "duplicatedDirections", "f", "midpoint", "padding2", "intersectNode", "intersect_node_default", "intersectEllipse", "rx", "ry", "cx", "cy", "det", "intersect_ellipse_default", "intersectCircle", "intersect_circle_default", "intersectLine", "p1", "p2", "q1", "q2", "a1", "a2", "b1", "b2", "c1", "c2", "r1", "r2", "r3", "r4", "denom", "offset", "sameSign", "intersect_line_default", "intersect_polygon_default", "intersectPolygon", "polyPoints", "x1", "y1", "intersections", "entry", "left", "top", "intersect", "pdx", "pdy", "distp", "qdx", "qdy", "distq", "intersectRect", "sx", "sy", "intersect_rect_default", "intersect_default", "labelHelper", "_classes", "classes2", "shapeSvg", "labelText", "textNode", "text", "halfPadding", "images", "noImgText", "img", "setupImage", "bodyFontSize", "updateNodeBounds", "element", "insertPolygonShape", "d", "note", "rect2", "note_default", "formatClass", "getClassesFromNode", "otherClasses", "question", "s", "questionElem", "choice", "hexagon", "m", "hex", "block_arrow", "blockArrow", "rect_left_inv_arrow", "lean_right", "lean_left", "trapezoid", "inv_trapezoid", "rect_right_inv_arrow", "cylinder", "shape", "rect", "totalWidth", "totalHeight", "propKeys", "applyNodePropertyBorders", "propKey", "composite", "labelRect", "borders", "strokeDashArray", "addBorder", "length", "skipBorder", "rectWithTitle", "innerLine", "text2", "title", "textRows", "titleBox", "descr", "stadium", "circle2", "circle3", "doublecircle", "gap", "circleGroup", "outerCircle", "innerCircle", "subroutine", "start", "forkJoin", "dir", "end", "class_box", "rowPadding", "lineHeight", "topLine", "bottomLine", "labelContainer", "verticalPos", "hasInterface", "interfaceLabelText", "interfaceLabel", "interfaceBBox", "classTitleString", "classTitleLabel", "classTitleBBox", "classAttributes", "member", "parsedInfo", "parsedText", "lbl", "classMethods", "displayText", "diffX2", "diffX", "memberBBox", "shapes", "nodeElems", "insertNode", "renderOptions", "newEl", "target", "positionNode", "diff", "getNodeFromBlock", "positioned", "vertex", "classStr", "radius", "getStylesFromArray", "bounds", "calculateBlockSize", "nodeEl", "boundingBox", "obj", "insertBlockPositioned", "performOperations", "blocks2", "operation", "calculateBlockSizes", "insertBlocks", "insertEdges", "edges", "Graph", "startBlock", "endBlock", "start2", "end2", "getClasses2", "diagObj", "draw", "_version", "securityLevel", "conf", "sandboxElement", "svg", "bl", "blArr", "nodes", "bounds2", "magicFactor", "useMaxWidth", "configureSvgSize", "blockRenderer_default", "diagram"] +} diff --git a/docs/website/public/bootstrap-icons-CVBWLLHT.woff2 b/docs/website/public/bootstrap-icons-CVBWLLHT.woff2 new file mode 100644 index 000000000..4d8c490e1 Binary files /dev/null and b/docs/website/public/bootstrap-icons-CVBWLLHT.woff2 differ diff --git a/docs/website/public/bootstrap-icons-VQNJTM6Q.woff b/docs/website/public/bootstrap-icons-VQNJTM6Q.woff new file mode 100644 index 000000000..a4fa4f024 Binary files /dev/null and b/docs/website/public/bootstrap-icons-VQNJTM6Q.woff differ diff --git a/docs/website/public/c4Diagram-YG6GDRKO-6JHP5GV7.min.js b/docs/website/public/c4Diagram-YG6GDRKO-6JHP5GV7.min.js new file mode 100644 index 000000000..fb3a3f45e --- /dev/null +++ b/docs/website/public/c4Diagram-YG6GDRKO-6JHP5GV7.min.js @@ -0,0 +1,11 @@ +import{a as ke,f as Ee}from"./chunk-ZTFIXIRW.min.js";import{g as ve,h as ee,i as Ct}from"./chunk-QZZKR5JD.min.js";import{a as Fe}from"./chunk-CM5D5KZN.min.js";import{D as te,K as Yt,L as be,Q as ge,R as _e,S as xe,T as me,W as Ot,n as ye}from"./chunk-3EE2TK35.min.js";import"./chunk-E5F23VE2.min.js";import{b,d as $t,j as Dt}from"./chunk-6TVUEPFY.min.js";import{d as Ue}from"./chunk-OSRY5VT3.min.js";var Re=Ue(Fe(),1),Ut=(function(){var e=b(function(_t,x,m,v){for(m=m||{},v=_t.length;v--;m[_t[v]]=x);return m},"o"),t=[1,24],s=[1,25],o=[1,26],l=[1,27],a=[1,28],n=[1,63],r=[1,64],i=[1,65],u=[1,66],d=[1,67],y=[1,68],p=[1,69],k=[1,29],O=[1,30],S=[1,31],P=[1,32],M=[1,33],U=[1,34],H=[1,35],q=[1,36],G=[1,37],K=[1,38],J=[1,39],Z=[1,40],$=[1,41],tt=[1,42],et=[1,43],at=[1,44],it=[1,45],rt=[1,46],nt=[1,47],st=[1,48],lt=[1,50],ot=[1,51],ct=[1,52],ht=[1,53],ut=[1,54],dt=[1,55],ft=[1,56],pt=[1,57],yt=[1,58],bt=[1,59],gt=[1,60],wt=[14,42],Wt=[14,34,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],Rt=[12,14,34,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],E=[1,82],A=[1,83],C=[1,84],w=[1,85],T=[12,14,42],ce=[12,14,33,42],It=[12,14,33,42,76,77,79,80],vt=[12,33],Qt=[34,36,37,38,39,40,41,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],Ht={trace:b(function(){},"trace"),yy:{},symbols_:{error:2,start:3,mermaidDoc:4,direction:5,direction_tb:6,direction_bt:7,direction_rl:8,direction_lr:9,graphConfig:10,C4_CONTEXT:11,NEWLINE:12,statements:13,EOF:14,C4_CONTAINER:15,C4_COMPONENT:16,C4_DYNAMIC:17,C4_DEPLOYMENT:18,otherStatements:19,diagramStatements:20,otherStatement:21,title:22,accDescription:23,acc_title:24,acc_title_value:25,acc_descr:26,acc_descr_value:27,acc_descr_multiline_value:28,boundaryStatement:29,boundaryStartStatement:30,boundaryStopStatement:31,boundaryStart:32,LBRACE:33,ENTERPRISE_BOUNDARY:34,attributes:35,SYSTEM_BOUNDARY:36,BOUNDARY:37,CONTAINER_BOUNDARY:38,NODE:39,NODE_L:40,NODE_R:41,RBRACE:42,diagramStatement:43,PERSON:44,PERSON_EXT:45,SYSTEM:46,SYSTEM_DB:47,SYSTEM_QUEUE:48,SYSTEM_EXT:49,SYSTEM_EXT_DB:50,SYSTEM_EXT_QUEUE:51,CONTAINER:52,CONTAINER_DB:53,CONTAINER_QUEUE:54,CONTAINER_EXT:55,CONTAINER_EXT_DB:56,CONTAINER_EXT_QUEUE:57,COMPONENT:58,COMPONENT_DB:59,COMPONENT_QUEUE:60,COMPONENT_EXT:61,COMPONENT_EXT_DB:62,COMPONENT_EXT_QUEUE:63,REL:64,BIREL:65,REL_U:66,REL_D:67,REL_L:68,REL_R:69,REL_B:70,REL_INDEX:71,UPDATE_EL_STYLE:72,UPDATE_REL_STYLE:73,UPDATE_LAYOUT_CONFIG:74,attribute:75,STR:76,STR_KEY:77,STR_VALUE:78,ATTRIBUTE:79,ATTRIBUTE_EMPTY:80,$accept:0,$end:1},terminals_:{2:"error",6:"direction_tb",7:"direction_bt",8:"direction_rl",9:"direction_lr",11:"C4_CONTEXT",12:"NEWLINE",14:"EOF",15:"C4_CONTAINER",16:"C4_COMPONENT",17:"C4_DYNAMIC",18:"C4_DEPLOYMENT",22:"title",23:"accDescription",24:"acc_title",25:"acc_title_value",26:"acc_descr",27:"acc_descr_value",28:"acc_descr_multiline_value",33:"LBRACE",34:"ENTERPRISE_BOUNDARY",36:"SYSTEM_BOUNDARY",37:"BOUNDARY",38:"CONTAINER_BOUNDARY",39:"NODE",40:"NODE_L",41:"NODE_R",42:"RBRACE",44:"PERSON",45:"PERSON_EXT",46:"SYSTEM",47:"SYSTEM_DB",48:"SYSTEM_QUEUE",49:"SYSTEM_EXT",50:"SYSTEM_EXT_DB",51:"SYSTEM_EXT_QUEUE",52:"CONTAINER",53:"CONTAINER_DB",54:"CONTAINER_QUEUE",55:"CONTAINER_EXT",56:"CONTAINER_EXT_DB",57:"CONTAINER_EXT_QUEUE",58:"COMPONENT",59:"COMPONENT_DB",60:"COMPONENT_QUEUE",61:"COMPONENT_EXT",62:"COMPONENT_EXT_DB",63:"COMPONENT_EXT_QUEUE",64:"REL",65:"BIREL",66:"REL_U",67:"REL_D",68:"REL_L",69:"REL_R",70:"REL_B",71:"REL_INDEX",72:"UPDATE_EL_STYLE",73:"UPDATE_REL_STYLE",74:"UPDATE_LAYOUT_CONFIG",76:"STR",77:"STR_KEY",78:"STR_VALUE",79:"ATTRIBUTE",80:"ATTRIBUTE_EMPTY"},productions_:[0,[3,1],[3,1],[5,1],[5,1],[5,1],[5,1],[4,1],[10,4],[10,4],[10,4],[10,4],[10,4],[13,1],[13,1],[13,2],[19,1],[19,2],[19,3],[21,1],[21,1],[21,2],[21,2],[21,1],[29,3],[30,3],[30,3],[30,4],[32,2],[32,2],[32,2],[32,2],[32,2],[32,2],[32,2],[31,1],[20,1],[20,2],[20,3],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,1],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[35,1],[35,2],[75,1],[75,2],[75,1],[75,1]],performAction:b(function(x,m,v,g,R,h,St){var f=h.length-1;switch(R){case 3:g.setDirection("TB");break;case 4:g.setDirection("BT");break;case 5:g.setDirection("RL");break;case 6:g.setDirection("LR");break;case 8:case 9:case 10:case 11:case 12:g.setC4Type(h[f-3]);break;case 19:g.setTitle(h[f].substring(6)),this.$=h[f].substring(6);break;case 20:g.setAccDescription(h[f].substring(15)),this.$=h[f].substring(15);break;case 21:this.$=h[f].trim(),g.setTitle(this.$);break;case 22:case 23:this.$=h[f].trim(),g.setAccDescription(this.$);break;case 28:h[f].splice(2,0,"ENTERPRISE"),g.addPersonOrSystemBoundary(...h[f]),this.$=h[f];break;case 29:h[f].splice(2,0,"SYSTEM"),g.addPersonOrSystemBoundary(...h[f]),this.$=h[f];break;case 30:g.addPersonOrSystemBoundary(...h[f]),this.$=h[f];break;case 31:h[f].splice(2,0,"CONTAINER"),g.addContainerBoundary(...h[f]),this.$=h[f];break;case 32:g.addDeploymentNode("node",...h[f]),this.$=h[f];break;case 33:g.addDeploymentNode("nodeL",...h[f]),this.$=h[f];break;case 34:g.addDeploymentNode("nodeR",...h[f]),this.$=h[f];break;case 35:g.popBoundaryParseStack();break;case 39:g.addPersonOrSystem("person",...h[f]),this.$=h[f];break;case 40:g.addPersonOrSystem("external_person",...h[f]),this.$=h[f];break;case 41:g.addPersonOrSystem("system",...h[f]),this.$=h[f];break;case 42:g.addPersonOrSystem("system_db",...h[f]),this.$=h[f];break;case 43:g.addPersonOrSystem("system_queue",...h[f]),this.$=h[f];break;case 44:g.addPersonOrSystem("external_system",...h[f]),this.$=h[f];break;case 45:g.addPersonOrSystem("external_system_db",...h[f]),this.$=h[f];break;case 46:g.addPersonOrSystem("external_system_queue",...h[f]),this.$=h[f];break;case 47:g.addContainer("container",...h[f]),this.$=h[f];break;case 48:g.addContainer("container_db",...h[f]),this.$=h[f];break;case 49:g.addContainer("container_queue",...h[f]),this.$=h[f];break;case 50:g.addContainer("external_container",...h[f]),this.$=h[f];break;case 51:g.addContainer("external_container_db",...h[f]),this.$=h[f];break;case 52:g.addContainer("external_container_queue",...h[f]),this.$=h[f];break;case 53:g.addComponent("component",...h[f]),this.$=h[f];break;case 54:g.addComponent("component_db",...h[f]),this.$=h[f];break;case 55:g.addComponent("component_queue",...h[f]),this.$=h[f];break;case 56:g.addComponent("external_component",...h[f]),this.$=h[f];break;case 57:g.addComponent("external_component_db",...h[f]),this.$=h[f];break;case 58:g.addComponent("external_component_queue",...h[f]),this.$=h[f];break;case 60:g.addRel("rel",...h[f]),this.$=h[f];break;case 61:g.addRel("birel",...h[f]),this.$=h[f];break;case 62:g.addRel("rel_u",...h[f]),this.$=h[f];break;case 63:g.addRel("rel_d",...h[f]),this.$=h[f];break;case 64:g.addRel("rel_l",...h[f]),this.$=h[f];break;case 65:g.addRel("rel_r",...h[f]),this.$=h[f];break;case 66:g.addRel("rel_b",...h[f]),this.$=h[f];break;case 67:h[f].splice(0,1),g.addRel("rel",...h[f]),this.$=h[f];break;case 68:g.updateElStyle("update_el_style",...h[f]),this.$=h[f];break;case 69:g.updateRelStyle("update_rel_style",...h[f]),this.$=h[f];break;case 70:g.updateLayoutConfig("update_layout_config",...h[f]),this.$=h[f];break;case 71:this.$=[h[f]];break;case 72:h[f].unshift(h[f-1]),this.$=h[f];break;case 73:case 75:this.$=h[f].trim();break;case 74:let kt={};kt[h[f-1].trim()]=h[f].trim(),this.$=kt;break;case 76:this.$="";break}},"anonymous"),table:[{3:1,4:2,5:3,6:[1,5],7:[1,6],8:[1,7],9:[1,8],10:4,11:[1,9],15:[1,10],16:[1,11],17:[1,12],18:[1,13]},{1:[3]},{1:[2,1]},{1:[2,2]},{1:[2,7]},{1:[2,3]},{1:[2,4]},{1:[2,5]},{1:[2,6]},{12:[1,14]},{12:[1,15]},{12:[1,16]},{12:[1,17]},{12:[1,18]},{13:19,19:20,20:21,21:22,22:t,23:s,24:o,26:l,28:a,29:49,30:61,32:62,34:n,36:r,37:i,38:u,39:d,40:y,41:p,43:23,44:k,45:O,46:S,47:P,48:M,49:U,50:H,51:q,52:G,53:K,54:J,55:Z,56:$,57:tt,58:et,59:at,60:it,61:rt,62:nt,63:st,64:lt,65:ot,66:ct,67:ht,68:ut,69:dt,70:ft,71:pt,72:yt,73:bt,74:gt},{13:70,19:20,20:21,21:22,22:t,23:s,24:o,26:l,28:a,29:49,30:61,32:62,34:n,36:r,37:i,38:u,39:d,40:y,41:p,43:23,44:k,45:O,46:S,47:P,48:M,49:U,50:H,51:q,52:G,53:K,54:J,55:Z,56:$,57:tt,58:et,59:at,60:it,61:rt,62:nt,63:st,64:lt,65:ot,66:ct,67:ht,68:ut,69:dt,70:ft,71:pt,72:yt,73:bt,74:gt},{13:71,19:20,20:21,21:22,22:t,23:s,24:o,26:l,28:a,29:49,30:61,32:62,34:n,36:r,37:i,38:u,39:d,40:y,41:p,43:23,44:k,45:O,46:S,47:P,48:M,49:U,50:H,51:q,52:G,53:K,54:J,55:Z,56:$,57:tt,58:et,59:at,60:it,61:rt,62:nt,63:st,64:lt,65:ot,66:ct,67:ht,68:ut,69:dt,70:ft,71:pt,72:yt,73:bt,74:gt},{13:72,19:20,20:21,21:22,22:t,23:s,24:o,26:l,28:a,29:49,30:61,32:62,34:n,36:r,37:i,38:u,39:d,40:y,41:p,43:23,44:k,45:O,46:S,47:P,48:M,49:U,50:H,51:q,52:G,53:K,54:J,55:Z,56:$,57:tt,58:et,59:at,60:it,61:rt,62:nt,63:st,64:lt,65:ot,66:ct,67:ht,68:ut,69:dt,70:ft,71:pt,72:yt,73:bt,74:gt},{13:73,19:20,20:21,21:22,22:t,23:s,24:o,26:l,28:a,29:49,30:61,32:62,34:n,36:r,37:i,38:u,39:d,40:y,41:p,43:23,44:k,45:O,46:S,47:P,48:M,49:U,50:H,51:q,52:G,53:K,54:J,55:Z,56:$,57:tt,58:et,59:at,60:it,61:rt,62:nt,63:st,64:lt,65:ot,66:ct,67:ht,68:ut,69:dt,70:ft,71:pt,72:yt,73:bt,74:gt},{14:[1,74]},e(wt,[2,13],{43:23,29:49,30:61,32:62,20:75,34:n,36:r,37:i,38:u,39:d,40:y,41:p,44:k,45:O,46:S,47:P,48:M,49:U,50:H,51:q,52:G,53:K,54:J,55:Z,56:$,57:tt,58:et,59:at,60:it,61:rt,62:nt,63:st,64:lt,65:ot,66:ct,67:ht,68:ut,69:dt,70:ft,71:pt,72:yt,73:bt,74:gt}),e(wt,[2,14]),e(Wt,[2,16],{12:[1,76]}),e(wt,[2,36],{12:[1,77]}),e(Rt,[2,19]),e(Rt,[2,20]),{25:[1,78]},{27:[1,79]},e(Rt,[2,23]),{35:80,75:81,76:E,77:A,79:C,80:w},{35:86,75:81,76:E,77:A,79:C,80:w},{35:87,75:81,76:E,77:A,79:C,80:w},{35:88,75:81,76:E,77:A,79:C,80:w},{35:89,75:81,76:E,77:A,79:C,80:w},{35:90,75:81,76:E,77:A,79:C,80:w},{35:91,75:81,76:E,77:A,79:C,80:w},{35:92,75:81,76:E,77:A,79:C,80:w},{35:93,75:81,76:E,77:A,79:C,80:w},{35:94,75:81,76:E,77:A,79:C,80:w},{35:95,75:81,76:E,77:A,79:C,80:w},{35:96,75:81,76:E,77:A,79:C,80:w},{35:97,75:81,76:E,77:A,79:C,80:w},{35:98,75:81,76:E,77:A,79:C,80:w},{35:99,75:81,76:E,77:A,79:C,80:w},{35:100,75:81,76:E,77:A,79:C,80:w},{35:101,75:81,76:E,77:A,79:C,80:w},{35:102,75:81,76:E,77:A,79:C,80:w},{35:103,75:81,76:E,77:A,79:C,80:w},{35:104,75:81,76:E,77:A,79:C,80:w},e(T,[2,59]),{35:105,75:81,76:E,77:A,79:C,80:w},{35:106,75:81,76:E,77:A,79:C,80:w},{35:107,75:81,76:E,77:A,79:C,80:w},{35:108,75:81,76:E,77:A,79:C,80:w},{35:109,75:81,76:E,77:A,79:C,80:w},{35:110,75:81,76:E,77:A,79:C,80:w},{35:111,75:81,76:E,77:A,79:C,80:w},{35:112,75:81,76:E,77:A,79:C,80:w},{35:113,75:81,76:E,77:A,79:C,80:w},{35:114,75:81,76:E,77:A,79:C,80:w},{35:115,75:81,76:E,77:A,79:C,80:w},{20:116,29:49,30:61,32:62,34:n,36:r,37:i,38:u,39:d,40:y,41:p,43:23,44:k,45:O,46:S,47:P,48:M,49:U,50:H,51:q,52:G,53:K,54:J,55:Z,56:$,57:tt,58:et,59:at,60:it,61:rt,62:nt,63:st,64:lt,65:ot,66:ct,67:ht,68:ut,69:dt,70:ft,71:pt,72:yt,73:bt,74:gt},{12:[1,118],33:[1,117]},{35:119,75:81,76:E,77:A,79:C,80:w},{35:120,75:81,76:E,77:A,79:C,80:w},{35:121,75:81,76:E,77:A,79:C,80:w},{35:122,75:81,76:E,77:A,79:C,80:w},{35:123,75:81,76:E,77:A,79:C,80:w},{35:124,75:81,76:E,77:A,79:C,80:w},{35:125,75:81,76:E,77:A,79:C,80:w},{14:[1,126]},{14:[1,127]},{14:[1,128]},{14:[1,129]},{1:[2,8]},e(wt,[2,15]),e(Wt,[2,17],{21:22,19:130,22:t,23:s,24:o,26:l,28:a}),e(wt,[2,37],{19:20,20:21,21:22,43:23,29:49,30:61,32:62,13:131,22:t,23:s,24:o,26:l,28:a,34:n,36:r,37:i,38:u,39:d,40:y,41:p,44:k,45:O,46:S,47:P,48:M,49:U,50:H,51:q,52:G,53:K,54:J,55:Z,56:$,57:tt,58:et,59:at,60:it,61:rt,62:nt,63:st,64:lt,65:ot,66:ct,67:ht,68:ut,69:dt,70:ft,71:pt,72:yt,73:bt,74:gt}),e(Rt,[2,21]),e(Rt,[2,22]),e(T,[2,39]),e(ce,[2,71],{75:81,35:132,76:E,77:A,79:C,80:w}),e(It,[2,73]),{78:[1,133]},e(It,[2,75]),e(It,[2,76]),e(T,[2,40]),e(T,[2,41]),e(T,[2,42]),e(T,[2,43]),e(T,[2,44]),e(T,[2,45]),e(T,[2,46]),e(T,[2,47]),e(T,[2,48]),e(T,[2,49]),e(T,[2,50]),e(T,[2,51]),e(T,[2,52]),e(T,[2,53]),e(T,[2,54]),e(T,[2,55]),e(T,[2,56]),e(T,[2,57]),e(T,[2,58]),e(T,[2,60]),e(T,[2,61]),e(T,[2,62]),e(T,[2,63]),e(T,[2,64]),e(T,[2,65]),e(T,[2,66]),e(T,[2,67]),e(T,[2,68]),e(T,[2,69]),e(T,[2,70]),{31:134,42:[1,135]},{12:[1,136]},{33:[1,137]},e(vt,[2,28]),e(vt,[2,29]),e(vt,[2,30]),e(vt,[2,31]),e(vt,[2,32]),e(vt,[2,33]),e(vt,[2,34]),{1:[2,9]},{1:[2,10]},{1:[2,11]},{1:[2,12]},e(Wt,[2,18]),e(wt,[2,38]),e(ce,[2,72]),e(It,[2,74]),e(T,[2,24]),e(T,[2,35]),e(Qt,[2,25]),e(Qt,[2,26],{12:[1,138]}),e(Qt,[2,27])],defaultActions:{2:[2,1],3:[2,2],4:[2,7],5:[2,3],6:[2,4],7:[2,5],8:[2,6],74:[2,8],126:[2,9],127:[2,10],128:[2,11],129:[2,12]},parseError:b(function(x,m){if(m.recoverable)this.trace(x);else{var v=new Error(x);throw v.hash=m,v}},"parseError"),parse:b(function(x){var m=this,v=[0],g=[],R=[null],h=[],St=this.table,f="",kt=0,he=0,ue=0,Le=2,de=1,Ne=h.slice.call(arguments,1),D=Object.create(this.lexer),Et={yy:{}};for(var qt in this.yy)Object.prototype.hasOwnProperty.call(this.yy,qt)&&(Et.yy[qt]=this.yy[qt]);D.setInput(x,Et.yy),Et.yy.lexer=D,Et.yy.parser=this,typeof D.yylloc>"u"&&(D.yylloc={});var Gt=D.yylloc;h.push(Gt);var Ye=D.options&&D.options.ranges;typeof Et.yy.parseError=="function"?this.parseError=Et.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function je(L){v.length=v.length-2*L,R.length=R.length-L,h.length=h.length-L}b(je,"popStack");function fe(){var L;return L=g.pop()||D.lex()||de,typeof L!="number"&&(L instanceof Array&&(g=L,L=g.pop()),L=m.symbols_[L]||L),L}b(fe,"lex");for(var B,Kt,At,N,M0,Jt,Tt={},Lt,W,pe,Nt;;){if(At=v[v.length-1],this.defaultActions[At]?N=this.defaultActions[At]:((B===null||typeof B>"u")&&(B=fe()),N=St[At]&&St[At][B]),typeof N>"u"||!N.length||!N[0]){var Zt="";Nt=[];for(Lt in St[At])this.terminals_[Lt]&&Lt>Le&&Nt.push("'"+this.terminals_[Lt]+"'");D.showPosition?Zt="Parse error on line "+(kt+1)+`: +`+D.showPosition()+` +Expecting `+Nt.join(", ")+", got '"+(this.terminals_[B]||B)+"'":Zt="Parse error on line "+(kt+1)+": Unexpected "+(B==de?"end of input":"'"+(this.terminals_[B]||B)+"'"),this.parseError(Zt,{text:D.match,token:this.terminals_[B]||B,line:D.yylineno,loc:Gt,expected:Nt})}if(N[0]instanceof Array&&N.length>1)throw new Error("Parse Error: multiple actions possible at state: "+At+", token: "+B);switch(N[0]){case 1:v.push(B),R.push(D.yytext),h.push(D.yylloc),v.push(N[1]),B=null,Kt?(B=Kt,Kt=null):(he=D.yyleng,f=D.yytext,kt=D.yylineno,Gt=D.yylloc,ue>0&&ue--);break;case 2:if(W=this.productions_[N[1]][1],Tt.$=R[R.length-W],Tt._$={first_line:h[h.length-(W||1)].first_line,last_line:h[h.length-1].last_line,first_column:h[h.length-(W||1)].first_column,last_column:h[h.length-1].last_column},Ye&&(Tt._$.range=[h[h.length-(W||1)].range[0],h[h.length-1].range[1]]),Jt=this.performAction.apply(Tt,[f,he,kt,Et.yy,N[1],R,h].concat(Ne)),typeof Jt<"u")return Jt;W&&(v=v.slice(0,-1*W*2),R=R.slice(0,-1*W),h=h.slice(0,-1*W)),v.push(this.productions_[N[1]][0]),R.push(Tt.$),h.push(Tt._$),pe=St[v[v.length-2]][v[v.length-1]],v.push(pe);break;case 3:return!0}}return!0},"parse")},Me=(function(){var _t={EOF:1,parseError:b(function(m,v){if(this.yy.parser)this.yy.parser.parseError(m,v);else throw new Error(m)},"parseError"),setInput:b(function(x,m){return this.yy=m||this.yy||{},this._input=x,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:b(function(){var x=this._input[0];this.yytext+=x,this.yyleng++,this.offset++,this.match+=x,this.matched+=x;var m=x.match(/(?:\r\n?|\n).*/g);return m?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),x},"input"),unput:b(function(x){var m=x.length,v=x.split(/(?:\r\n?|\n)/g);this._input=x+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-m),this.offset-=m;var g=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),v.length-1&&(this.yylineno-=v.length-1);var R=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:v?(v.length===g.length?this.yylloc.first_column:0)+g[g.length-v.length].length-v[0].length:this.yylloc.first_column-m},this.options.ranges&&(this.yylloc.range=[R[0],R[0]+this.yyleng-m]),this.yyleng=this.yytext.length,this},"unput"),more:b(function(){return this._more=!0,this},"more"),reject:b(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:b(function(x){this.unput(this.match.slice(x))},"less"),pastInput:b(function(){var x=this.matched.substr(0,this.matched.length-this.match.length);return(x.length>20?"...":"")+x.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:b(function(){var x=this.match;return x.length<20&&(x+=this._input.substr(0,20-x.length)),(x.substr(0,20)+(x.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:b(function(){var x=this.pastInput(),m=new Array(x.length+1).join("-");return x+this.upcomingInput()+` +`+m+"^"},"showPosition"),test_match:b(function(x,m){var v,g,R;if(this.options.backtrack_lexer&&(R={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(R.yylloc.range=this.yylloc.range.slice(0))),g=x[0].match(/(?:\r\n?|\n).*/g),g&&(this.yylineno+=g.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:g?g[g.length-1].length-g[g.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+x[0].length},this.yytext+=x[0],this.match+=x[0],this.matches=x,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(x[0].length),this.matched+=x[0],v=this.performAction.call(this,this.yy,this,m,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),v)return v;if(this._backtrack){for(var h in R)this[h]=R[h];return!1}return!1},"test_match"),next:b(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var x,m,v,g;this._more||(this.yytext="",this.match="");for(var R=this._currentRules(),h=0;hm[0].length)){if(m=v,g=h,this.options.backtrack_lexer){if(x=this.test_match(v,R[h]),x!==!1)return x;if(this._backtrack){m=!1;continue}else return!1}else if(!this.options.flex)break}return m?(x=this.test_match(m,R[g]),x!==!1?x:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:b(function(){var m=this.next();return m||this.lex()},"lex"),begin:b(function(m){this.conditionStack.push(m)},"begin"),popState:b(function(){var m=this.conditionStack.length-1;return m>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:b(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:b(function(m){return m=this.conditionStack.length-1-Math.abs(m||0),m>=0?this.conditionStack[m]:"INITIAL"},"topState"),pushState:b(function(m){this.begin(m)},"pushState"),stateStackSize:b(function(){return this.conditionStack.length},"stateStackSize"),options:{},performAction:b(function(m,v,g,R){var h=R;switch(g){case 0:return 6;case 1:return 7;case 2:return 8;case 3:return 9;case 4:return 22;case 5:return 23;case 6:return this.begin("acc_title"),24;break;case 7:return this.popState(),"acc_title_value";break;case 8:return this.begin("acc_descr"),26;break;case 9:return this.popState(),"acc_descr_value";break;case 10:this.begin("acc_descr_multiline");break;case 11:this.popState();break;case 12:return"acc_descr_multiline_value";case 13:break;case 14:c;break;case 15:return 12;case 16:break;case 17:return 11;case 18:return 15;case 19:return 16;case 20:return 17;case 21:return 18;case 22:return this.begin("person_ext"),45;break;case 23:return this.begin("person"),44;break;case 24:return this.begin("system_ext_queue"),51;break;case 25:return this.begin("system_ext_db"),50;break;case 26:return this.begin("system_ext"),49;break;case 27:return this.begin("system_queue"),48;break;case 28:return this.begin("system_db"),47;break;case 29:return this.begin("system"),46;break;case 30:return this.begin("boundary"),37;break;case 31:return this.begin("enterprise_boundary"),34;break;case 32:return this.begin("system_boundary"),36;break;case 33:return this.begin("container_ext_queue"),57;break;case 34:return this.begin("container_ext_db"),56;break;case 35:return this.begin("container_ext"),55;break;case 36:return this.begin("container_queue"),54;break;case 37:return this.begin("container_db"),53;break;case 38:return this.begin("container"),52;break;case 39:return this.begin("container_boundary"),38;break;case 40:return this.begin("component_ext_queue"),63;break;case 41:return this.begin("component_ext_db"),62;break;case 42:return this.begin("component_ext"),61;break;case 43:return this.begin("component_queue"),60;break;case 44:return this.begin("component_db"),59;break;case 45:return this.begin("component"),58;break;case 46:return this.begin("node"),39;break;case 47:return this.begin("node"),39;break;case 48:return this.begin("node_l"),40;break;case 49:return this.begin("node_r"),41;break;case 50:return this.begin("rel"),64;break;case 51:return this.begin("birel"),65;break;case 52:return this.begin("rel_u"),66;break;case 53:return this.begin("rel_u"),66;break;case 54:return this.begin("rel_d"),67;break;case 55:return this.begin("rel_d"),67;break;case 56:return this.begin("rel_l"),68;break;case 57:return this.begin("rel_l"),68;break;case 58:return this.begin("rel_r"),69;break;case 59:return this.begin("rel_r"),69;break;case 60:return this.begin("rel_b"),70;break;case 61:return this.begin("rel_index"),71;break;case 62:return this.begin("update_el_style"),72;break;case 63:return this.begin("update_rel_style"),73;break;case 64:return this.begin("update_layout_config"),74;break;case 65:return"EOF_IN_STRUCT";case 66:return this.begin("attribute"),"ATTRIBUTE_EMPTY";break;case 67:this.begin("attribute");break;case 68:this.popState(),this.popState();break;case 69:return 80;case 70:break;case 71:return 80;case 72:this.begin("string");break;case 73:this.popState();break;case 74:return"STR";case 75:this.begin("string_kv");break;case 76:return this.begin("string_kv_key"),"STR_KEY";break;case 77:this.popState(),this.begin("string_kv_value");break;case 78:return"STR_VALUE";case 79:this.popState(),this.popState();break;case 80:return"STR";case 81:return"LBRACE";case 82:return"RBRACE";case 83:return"SPACE";case 84:return"EOL";case 85:return 14}},"anonymous"),rules:[/^(?:.*direction\s+TB[^\n]*)/,/^(?:.*direction\s+BT[^\n]*)/,/^(?:.*direction\s+RL[^\n]*)/,/^(?:.*direction\s+LR[^\n]*)/,/^(?:title\s[^#\n;]+)/,/^(?:accDescription\s[^#\n;]+)/,/^(?:accTitle\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*\{\s*)/,/^(?:[\}])/,/^(?:[^\}]*)/,/^(?:%%(?!\{)*[^\n]*(\r?\n?)+)/,/^(?:%%[^\n]*(\r?\n)*)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:C4Context\b)/,/^(?:C4Container\b)/,/^(?:C4Component\b)/,/^(?:C4Dynamic\b)/,/^(?:C4Deployment\b)/,/^(?:Person_Ext\b)/,/^(?:Person\b)/,/^(?:SystemQueue_Ext\b)/,/^(?:SystemDb_Ext\b)/,/^(?:System_Ext\b)/,/^(?:SystemQueue\b)/,/^(?:SystemDb\b)/,/^(?:System\b)/,/^(?:Boundary\b)/,/^(?:Enterprise_Boundary\b)/,/^(?:System_Boundary\b)/,/^(?:ContainerQueue_Ext\b)/,/^(?:ContainerDb_Ext\b)/,/^(?:Container_Ext\b)/,/^(?:ContainerQueue\b)/,/^(?:ContainerDb\b)/,/^(?:Container\b)/,/^(?:Container_Boundary\b)/,/^(?:ComponentQueue_Ext\b)/,/^(?:ComponentDb_Ext\b)/,/^(?:Component_Ext\b)/,/^(?:ComponentQueue\b)/,/^(?:ComponentDb\b)/,/^(?:Component\b)/,/^(?:Deployment_Node\b)/,/^(?:Node\b)/,/^(?:Node_L\b)/,/^(?:Node_R\b)/,/^(?:Rel\b)/,/^(?:BiRel\b)/,/^(?:Rel_Up\b)/,/^(?:Rel_U\b)/,/^(?:Rel_Down\b)/,/^(?:Rel_D\b)/,/^(?:Rel_Left\b)/,/^(?:Rel_L\b)/,/^(?:Rel_Right\b)/,/^(?:Rel_R\b)/,/^(?:Rel_Back\b)/,/^(?:RelIndex\b)/,/^(?:UpdateElementStyle\b)/,/^(?:UpdateRelStyle\b)/,/^(?:UpdateLayoutConfig\b)/,/^(?:$)/,/^(?:[(][ ]*[,])/,/^(?:[(])/,/^(?:[)])/,/^(?:,,)/,/^(?:,)/,/^(?:[ ]*["]["])/,/^(?:[ ]*["])/,/^(?:["])/,/^(?:[^"]*)/,/^(?:[ ]*[\$])/,/^(?:[^=]*)/,/^(?:[=][ ]*["])/,/^(?:[^"]+)/,/^(?:["])/,/^(?:[^,]+)/,/^(?:\{)/,/^(?:\})/,/^(?:[\s]+)/,/^(?:[\n\r]+)/,/^(?:$)/],conditions:{acc_descr_multiline:{rules:[11,12],inclusive:!1},acc_descr:{rules:[9],inclusive:!1},acc_title:{rules:[7],inclusive:!1},string_kv_value:{rules:[78,79],inclusive:!1},string_kv_key:{rules:[77],inclusive:!1},string_kv:{rules:[76],inclusive:!1},string:{rules:[73,74],inclusive:!1},attribute:{rules:[68,69,70,71,72,75,80],inclusive:!1},update_layout_config:{rules:[65,66,67,68],inclusive:!1},update_rel_style:{rules:[65,66,67,68],inclusive:!1},update_el_style:{rules:[65,66,67,68],inclusive:!1},rel_b:{rules:[65,66,67,68],inclusive:!1},rel_r:{rules:[65,66,67,68],inclusive:!1},rel_l:{rules:[65,66,67,68],inclusive:!1},rel_d:{rules:[65,66,67,68],inclusive:!1},rel_u:{rules:[65,66,67,68],inclusive:!1},rel_bi:{rules:[],inclusive:!1},rel:{rules:[65,66,67,68],inclusive:!1},node_r:{rules:[65,66,67,68],inclusive:!1},node_l:{rules:[65,66,67,68],inclusive:!1},node:{rules:[65,66,67,68],inclusive:!1},index:{rules:[],inclusive:!1},rel_index:{rules:[65,66,67,68],inclusive:!1},component_ext_queue:{rules:[],inclusive:!1},component_ext_db:{rules:[65,66,67,68],inclusive:!1},component_ext:{rules:[65,66,67,68],inclusive:!1},component_queue:{rules:[65,66,67,68],inclusive:!1},component_db:{rules:[65,66,67,68],inclusive:!1},component:{rules:[65,66,67,68],inclusive:!1},container_boundary:{rules:[65,66,67,68],inclusive:!1},container_ext_queue:{rules:[65,66,67,68],inclusive:!1},container_ext_db:{rules:[65,66,67,68],inclusive:!1},container_ext:{rules:[65,66,67,68],inclusive:!1},container_queue:{rules:[65,66,67,68],inclusive:!1},container_db:{rules:[65,66,67,68],inclusive:!1},container:{rules:[65,66,67,68],inclusive:!1},birel:{rules:[65,66,67,68],inclusive:!1},system_boundary:{rules:[65,66,67,68],inclusive:!1},enterprise_boundary:{rules:[65,66,67,68],inclusive:!1},boundary:{rules:[65,66,67,68],inclusive:!1},system_ext_queue:{rules:[65,66,67,68],inclusive:!1},system_ext_db:{rules:[65,66,67,68],inclusive:!1},system_ext:{rules:[65,66,67,68],inclusive:!1},system_queue:{rules:[65,66,67,68],inclusive:!1},system_db:{rules:[65,66,67,68],inclusive:!1},system:{rules:[65,66,67,68],inclusive:!1},person_ext:{rules:[65,66,67,68],inclusive:!1},person:{rules:[65,66,67,68],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,8,10,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,81,82,83,84,85],inclusive:!0}}};return _t})();Ht.lexer=Me;function Mt(){this.yy={}}return b(Mt,"Parser"),Mt.prototype=Ht,Ht.Parser=Mt,new Mt})();Ut.parser=Ut;var Ve=Ut,V=[],xt=[""],I="global",F="",X=[{alias:"global",label:{text:"global"},type:{text:"global"},tags:null,link:null,parentBoundary:""}],Bt=[],ne="",se=!1,Ft=4,Vt=2,we,ze=b(function(){return we},"getC4Type"),Xe=b(function(e){we=te(e,Ot())},"setC4Type"),We=b(function(e,t,s,o,l,a,n,r,i){if(e==null||t===void 0||t===null||s===void 0||s===null||o===void 0||o===null)return;let u={},d=Bt.find(y=>y.from===t&&y.to===s);if(d?u=d:Bt.push(u),u.type=e,u.from=t,u.to=s,u.label={text:o},l==null)u.techn={text:""};else if(typeof l=="object"){let[y,p]=Object.entries(l)[0];u[y]={text:p}}else u.techn={text:l};if(a==null)u.descr={text:""};else if(typeof a=="object"){let[y,p]=Object.entries(a)[0];u[y]={text:p}}else u.descr={text:a};if(typeof n=="object"){let[y,p]=Object.entries(n)[0];u[y]=p}else u.sprite=n;if(typeof r=="object"){let[y,p]=Object.entries(r)[0];u[y]=p}else u.tags=r;if(typeof i=="object"){let[y,p]=Object.entries(i)[0];u[y]=p}else u.link=i;u.wrap=mt()},"addRel"),Qe=b(function(e,t,s,o,l,a,n){if(t===null||s===null)return;let r={},i=V.find(u=>u.alias===t);if(i&&t===i.alias?r=i:(r.alias=t,V.push(r)),s==null?r.label={text:""}:r.label={text:s},o==null)r.descr={text:""};else if(typeof o=="object"){let[u,d]=Object.entries(o)[0];r[u]={text:d}}else r.descr={text:o};if(typeof l=="object"){let[u,d]=Object.entries(l)[0];r[u]=d}else r.sprite=l;if(typeof a=="object"){let[u,d]=Object.entries(a)[0];r[u]=d}else r.tags=a;if(typeof n=="object"){let[u,d]=Object.entries(n)[0];r[u]=d}else r.link=n;r.typeC4Shape={text:e},r.parentBoundary=I,r.wrap=mt()},"addPersonOrSystem"),He=b(function(e,t,s,o,l,a,n,r){if(t===null||s===null)return;let i={},u=V.find(d=>d.alias===t);if(u&&t===u.alias?i=u:(i.alias=t,V.push(i)),s==null?i.label={text:""}:i.label={text:s},o==null)i.techn={text:""};else if(typeof o=="object"){let[d,y]=Object.entries(o)[0];i[d]={text:y}}else i.techn={text:o};if(l==null)i.descr={text:""};else if(typeof l=="object"){let[d,y]=Object.entries(l)[0];i[d]={text:y}}else i.descr={text:l};if(typeof a=="object"){let[d,y]=Object.entries(a)[0];i[d]=y}else i.sprite=a;if(typeof n=="object"){let[d,y]=Object.entries(n)[0];i[d]=y}else i.tags=n;if(typeof r=="object"){let[d,y]=Object.entries(r)[0];i[d]=y}else i.link=r;i.wrap=mt(),i.typeC4Shape={text:e},i.parentBoundary=I},"addContainer"),qe=b(function(e,t,s,o,l,a,n,r){if(t===null||s===null)return;let i={},u=V.find(d=>d.alias===t);if(u&&t===u.alias?i=u:(i.alias=t,V.push(i)),s==null?i.label={text:""}:i.label={text:s},o==null)i.techn={text:""};else if(typeof o=="object"){let[d,y]=Object.entries(o)[0];i[d]={text:y}}else i.techn={text:o};if(l==null)i.descr={text:""};else if(typeof l=="object"){let[d,y]=Object.entries(l)[0];i[d]={text:y}}else i.descr={text:l};if(typeof a=="object"){let[d,y]=Object.entries(a)[0];i[d]=y}else i.sprite=a;if(typeof n=="object"){let[d,y]=Object.entries(n)[0];i[d]=y}else i.tags=n;if(typeof r=="object"){let[d,y]=Object.entries(r)[0];i[d]=y}else i.link=r;i.wrap=mt(),i.typeC4Shape={text:e},i.parentBoundary=I},"addComponent"),Ge=b(function(e,t,s,o,l){if(e===null||t===null)return;let a={},n=X.find(r=>r.alias===e);if(n&&e===n.alias?a=n:(a.alias=e,X.push(a)),t==null?a.label={text:""}:a.label={text:t},s==null)a.type={text:"system"};else if(typeof s=="object"){let[r,i]=Object.entries(s)[0];a[r]={text:i}}else a.type={text:s};if(typeof o=="object"){let[r,i]=Object.entries(o)[0];a[r]=i}else a.tags=o;if(typeof l=="object"){let[r,i]=Object.entries(l)[0];a[r]=i}else a.link=l;a.parentBoundary=I,a.wrap=mt(),F=I,I=e,xt.push(F)},"addPersonOrSystemBoundary"),Ke=b(function(e,t,s,o,l){if(e===null||t===null)return;let a={},n=X.find(r=>r.alias===e);if(n&&e===n.alias?a=n:(a.alias=e,X.push(a)),t==null?a.label={text:""}:a.label={text:t},s==null)a.type={text:"container"};else if(typeof s=="object"){let[r,i]=Object.entries(s)[0];a[r]={text:i}}else a.type={text:s};if(typeof o=="object"){let[r,i]=Object.entries(o)[0];a[r]=i}else a.tags=o;if(typeof l=="object"){let[r,i]=Object.entries(l)[0];a[r]=i}else a.link=l;a.parentBoundary=I,a.wrap=mt(),F=I,I=e,xt.push(F)},"addContainerBoundary"),Je=b(function(e,t,s,o,l,a,n,r){if(t===null||s===null)return;let i={},u=X.find(d=>d.alias===t);if(u&&t===u.alias?i=u:(i.alias=t,X.push(i)),s==null?i.label={text:""}:i.label={text:s},o==null)i.type={text:"node"};else if(typeof o=="object"){let[d,y]=Object.entries(o)[0];i[d]={text:y}}else i.type={text:o};if(l==null)i.descr={text:""};else if(typeof l=="object"){let[d,y]=Object.entries(l)[0];i[d]={text:y}}else i.descr={text:l};if(typeof n=="object"){let[d,y]=Object.entries(n)[0];i[d]=y}else i.tags=n;if(typeof r=="object"){let[d,y]=Object.entries(r)[0];i[d]=y}else i.link=r;i.nodeType=e,i.parentBoundary=I,i.wrap=mt(),F=I,I=t,xt.push(F)},"addDeploymentNode"),Ze=b(function(){I=F,xt.pop(),F=xt.pop(),xt.push(F)},"popBoundaryParseStack"),$e=b(function(e,t,s,o,l,a,n,r,i,u,d){let y=V.find(p=>p.alias===t);if(!(y===void 0&&(y=X.find(p=>p.alias===t),y===void 0))){if(s!=null)if(typeof s=="object"){let[p,k]=Object.entries(s)[0];y[p]=k}else y.bgColor=s;if(o!=null)if(typeof o=="object"){let[p,k]=Object.entries(o)[0];y[p]=k}else y.fontColor=o;if(l!=null)if(typeof l=="object"){let[p,k]=Object.entries(l)[0];y[p]=k}else y.borderColor=l;if(a!=null)if(typeof a=="object"){let[p,k]=Object.entries(a)[0];y[p]=k}else y.shadowing=a;if(n!=null)if(typeof n=="object"){let[p,k]=Object.entries(n)[0];y[p]=k}else y.shape=n;if(r!=null)if(typeof r=="object"){let[p,k]=Object.entries(r)[0];y[p]=k}else y.sprite=r;if(i!=null)if(typeof i=="object"){let[p,k]=Object.entries(i)[0];y[p]=k}else y.techn=i;if(u!=null)if(typeof u=="object"){let[p,k]=Object.entries(u)[0];y[p]=k}else y.legendText=u;if(d!=null)if(typeof d=="object"){let[p,k]=Object.entries(d)[0];y[p]=k}else y.legendSprite=d}},"updateElStyle"),t0=b(function(e,t,s,o,l,a,n){let r=Bt.find(i=>i.from===t&&i.to===s);if(r!==void 0){if(o!=null)if(typeof o=="object"){let[i,u]=Object.entries(o)[0];r[i]=u}else r.textColor=o;if(l!=null)if(typeof l=="object"){let[i,u]=Object.entries(l)[0];r[i]=u}else r.lineColor=l;if(a!=null)if(typeof a=="object"){let[i,u]=Object.entries(a)[0];r[i]=parseInt(u)}else r.offsetX=parseInt(a);if(n!=null)if(typeof n=="object"){let[i,u]=Object.entries(n)[0];r[i]=parseInt(u)}else r.offsetY=parseInt(n)}},"updateRelStyle"),e0=b(function(e,t,s){let o=Ft,l=Vt;if(typeof t=="object"){let a=Object.values(t)[0];o=parseInt(a)}else o=parseInt(t);if(typeof s=="object"){let a=Object.values(s)[0];l=parseInt(a)}else l=parseInt(s);o>=1&&(Ft=o),l>=1&&(Vt=l)},"updateLayoutConfig"),a0=b(function(){return Ft},"getC4ShapeInRow"),i0=b(function(){return Vt},"getC4BoundaryInRow"),r0=b(function(){return I},"getCurrentBoundaryParse"),n0=b(function(){return F},"getParentBoundaryParse"),Te=b(function(e){return e==null?V:V.filter(t=>t.parentBoundary===e)},"getC4ShapeArray"),s0=b(function(e){return V.find(t=>t.alias===e)},"getC4Shape"),l0=b(function(e){return Object.keys(Te(e))},"getC4ShapeKeys"),Oe=b(function(e){return e==null?X:X.filter(t=>t.parentBoundary===e)},"getBoundaries"),o0=Oe,c0=b(function(){return Bt},"getRels"),h0=b(function(){return ne},"getTitle"),u0=b(function(e){se=e},"setWrap"),mt=b(function(){return se},"autoWrap"),d0=b(function(){V=[],X=[{alias:"global",label:{text:"global"},type:{text:"global"},tags:null,link:null,parentBoundary:""}],F="",I="global",xt=[""],Bt=[],xt=[""],ne="",se=!1,Ft=4,Vt=2},"clear"),f0={SOLID:0,DOTTED:1,NOTE:2,SOLID_CROSS:3,DOTTED_CROSS:4,SOLID_OPEN:5,DOTTED_OPEN:6,LOOP_START:10,LOOP_END:11,ALT_START:12,ALT_ELSE:13,ALT_END:14,OPT_START:15,OPT_END:16,ACTIVE_START:17,ACTIVE_END:18,PAR_START:19,PAR_AND:20,PAR_END:21,RECT_START:22,RECT_END:23,SOLID_POINT:24,DOTTED_POINT:25},p0={FILLED:0,OPEN:1},y0={LEFTOF:0,RIGHTOF:1,OVER:2},b0=b(function(e){ne=te(e,Ot())},"setTitle"),ae={addPersonOrSystem:Qe,addPersonOrSystemBoundary:Ge,addContainer:He,addContainerBoundary:Ke,addComponent:qe,addDeploymentNode:Je,popBoundaryParseStack:Ze,addRel:We,updateElStyle:$e,updateRelStyle:t0,updateLayoutConfig:e0,autoWrap:mt,setWrap:u0,getC4ShapeArray:Te,getC4Shape:s0,getC4ShapeKeys:l0,getBoundaries:Oe,getBoundarys:o0,getCurrentBoundaryParse:r0,getParentBoundaryParse:n0,getRels:c0,getTitle:h0,getC4Type:ze,getC4ShapeInRow:a0,getC4BoundaryInRow:i0,setAccTitle:ge,getAccTitle:_e,getAccDescription:me,setAccDescription:xe,getConfig:b(()=>Ot().c4,"getConfig"),clear:d0,LINETYPE:f0,ARROWTYPE:p0,PLACEMENT:y0,setTitle:b0,setC4Type:Xe},le=b(function(e,t){return ke(e,t)},"drawRect"),Se=b(function(e,t,s,o,l,a){let n=e.append("image");n.attr("width",t),n.attr("height",s),n.attr("x",o),n.attr("y",l);let r=a.startsWith("data:image/png;base64")?a:(0,Re.sanitizeUrl)(a);n.attr("xlink:href",r)},"drawImage"),g0=b((e,t,s)=>{let o=e.append("g"),l=0;for(let a of t){let n=a.textColor?a.textColor:"#444444",r=a.lineColor?a.lineColor:"#444444",i=a.offsetX?parseInt(a.offsetX):0,u=a.offsetY?parseInt(a.offsetY):0,d="";if(l===0){let p=o.append("line");p.attr("x1",a.startPoint.x),p.attr("y1",a.startPoint.y),p.attr("x2",a.endPoint.x),p.attr("y2",a.endPoint.y),p.attr("stroke-width","1"),p.attr("stroke",r),p.style("fill","none"),a.type!=="rel_b"&&p.attr("marker-end","url("+d+"#arrowhead)"),(a.type==="birel"||a.type==="rel_b")&&p.attr("marker-start","url("+d+"#arrowend)"),l=-1}else{let p=o.append("path");p.attr("fill","none").attr("stroke-width","1").attr("stroke",r).attr("d","Mstartx,starty Qcontrolx,controly stopx,stopy ".replaceAll("startx",a.startPoint.x).replaceAll("starty",a.startPoint.y).replaceAll("controlx",a.startPoint.x+(a.endPoint.x-a.startPoint.x)/2-(a.endPoint.x-a.startPoint.x)/4).replaceAll("controly",a.startPoint.y+(a.endPoint.y-a.startPoint.y)/2).replaceAll("stopx",a.endPoint.x).replaceAll("stopy",a.endPoint.y)),a.type!=="rel_b"&&p.attr("marker-end","url("+d+"#arrowhead)"),(a.type==="birel"||a.type==="rel_b")&&p.attr("marker-start","url("+d+"#arrowend)")}let y=s.messageFont();Q(s)(a.label.text,o,Math.min(a.startPoint.x,a.endPoint.x)+Math.abs(a.endPoint.x-a.startPoint.x)/2+i,Math.min(a.startPoint.y,a.endPoint.y)+Math.abs(a.endPoint.y-a.startPoint.y)/2+u,a.label.width,a.label.height,{fill:n},y),a.techn&&a.techn.text!==""&&(y=s.messageFont(),Q(s)("["+a.techn.text+"]",o,Math.min(a.startPoint.x,a.endPoint.x)+Math.abs(a.endPoint.x-a.startPoint.x)/2+i,Math.min(a.startPoint.y,a.endPoint.y)+Math.abs(a.endPoint.y-a.startPoint.y)/2+s.messageFontSize+5+u,Math.max(a.label.width,a.techn.width),a.techn.height,{fill:n,"font-style":"italic"},y))}},"drawRels"),_0=b(function(e,t,s){let o=e.append("g"),l=t.bgColor?t.bgColor:"none",a=t.borderColor?t.borderColor:"#444444",n=t.fontColor?t.fontColor:"black",r={"stroke-width":1,"stroke-dasharray":"7.0,7.0"};t.nodeType&&(r={"stroke-width":1});let i={x:t.x,y:t.y,fill:l,stroke:a,width:t.width,height:t.height,rx:2.5,ry:2.5,attrs:r};le(o,i);let u=s.boundaryFont();u.fontWeight="bold",u.fontSize=u.fontSize+2,u.fontColor=n,Q(s)(t.label.text,o,t.x,t.y+t.label.Y,t.width,t.height,{fill:"#444444"},u),t.type&&t.type.text!==""&&(u=s.boundaryFont(),u.fontColor=n,Q(s)(t.type.text,o,t.x,t.y+t.type.Y,t.width,t.height,{fill:"#444444"},u)),t.descr&&t.descr.text!==""&&(u=s.boundaryFont(),u.fontSize=u.fontSize-2,u.fontColor=n,Q(s)(t.descr.text,o,t.x,t.y+t.descr.Y,t.width,t.height,{fill:"#444444"},u))},"drawBoundary"),x0=b(function(e,t,s){let o=t.bgColor?t.bgColor:s[t.typeC4Shape.text+"_bg_color"],l=t.borderColor?t.borderColor:s[t.typeC4Shape.text+"_border_color"],a=t.fontColor?t.fontColor:"#FFFFFF",n="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAIAAADYYG7QAAACD0lEQVR4Xu2YoU4EMRCGT+4j8Ai8AhaH4QHgAUjQuFMECUgMIUgwJAgMhgQsAYUiJCiQIBBY+EITsjfTdme6V24v4c8vyGbb+ZjOtN0bNcvjQXmkH83WvYBWto6PLm6v7p7uH1/w2fXD+PBycX1Pv2l3IdDm/vn7x+dXQiAubRzoURa7gRZWd0iGRIiJbOnhnfYBQZNJjNbuyY2eJG8fkDE3bbG4ep6MHUAsgYxmE3nVs6VsBWJSGccsOlFPmLIViMzLOB7pCVO2AtHJMohH7Fh6zqitQK7m0rJvAVYgGcEpe//PLdDz65sM4pF9N7ICcXDKIB5Nv6j7tD0NoSdM2QrU9Gg0ewE1LqBhHR3BBdvj2vapnidjHxD/q6vd7Pvhr31AwcY8eXMTXAKECZZJFXuEq27aLgQK5uLMohCenGGuGewOxSjBvYBqeG6B+Nqiblggdjnc+ZXDy+FNFpFzw76O3UBAROuXh6FoiAcf5g9eTvUgzy0nWg6I8cXHRUpg5bOVBCo+KDpFajOf23GgPme7RSQ+lacIENUgJ6gg1k6HjgOlqnLqip4tEuhv0hNEMXUD0clyXE3p6pZA0S2nnvTlXwLJEZWlb7cTQH1+USgTN4VhAenm/wea1OCAOmqo6fE1WCb9WSKBah+rbUWPWAmE2Rvk0ApiB45eOyNAzU8xcTvj8KvkKEoOaIYeHNA3ZuygAvFMUO0AAAAASUVORK5CYII=";switch(t.typeC4Shape.text){case"person":n="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAIAAADYYG7QAAACD0lEQVR4Xu2YoU4EMRCGT+4j8Ai8AhaH4QHgAUjQuFMECUgMIUgwJAgMhgQsAYUiJCiQIBBY+EITsjfTdme6V24v4c8vyGbb+ZjOtN0bNcvjQXmkH83WvYBWto6PLm6v7p7uH1/w2fXD+PBycX1Pv2l3IdDm/vn7x+dXQiAubRzoURa7gRZWd0iGRIiJbOnhnfYBQZNJjNbuyY2eJG8fkDE3bbG4ep6MHUAsgYxmE3nVs6VsBWJSGccsOlFPmLIViMzLOB7pCVO2AtHJMohH7Fh6zqitQK7m0rJvAVYgGcEpe//PLdDz65sM4pF9N7ICcXDKIB5Nv6j7tD0NoSdM2QrU9Gg0ewE1LqBhHR3BBdvj2vapnidjHxD/q6vd7Pvhr31AwcY8eXMTXAKECZZJFXuEq27aLgQK5uLMohCenGGuGewOxSjBvYBqeG6B+Nqiblggdjnc+ZXDy+FNFpFzw76O3UBAROuXh6FoiAcf5g9eTvUgzy0nWg6I8cXHRUpg5bOVBCo+KDpFajOf23GgPme7RSQ+lacIENUgJ6gg1k6HjgOlqnLqip4tEuhv0hNEMXUD0clyXE3p6pZA0S2nnvTlXwLJEZWlb7cTQH1+USgTN4VhAenm/wea1OCAOmqo6fE1WCb9WSKBah+rbUWPWAmE2Rvk0ApiB45eOyNAzU8xcTvj8KvkKEoOaIYeHNA3ZuygAvFMUO0AAAAASUVORK5CYII=";break;case"external_person":n="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAIAAADYYG7QAAAB6ElEQVR4Xu2YLY+EMBCG9+dWr0aj0Wg0Go1Go0+j8Xdv2uTCvv1gpt0ebHKPuhDaeW4605Z9mJvx4AdXUyTUdd08z+u6flmWZRnHsWkafk9DptAwDPu+f0eAYtu2PEaGWuj5fCIZrBAC2eLBAnRCsEkkxmeaJp7iDJ2QMDdHsLg8SxKFEJaAo8lAXnmuOFIhTMpxxKATebo4UiFknuNo4OniSIXQyRxEA3YsnjGCVEjVXD7yLUAqxBGUyPv/Y4W2beMgGuS7kVQIBycH0fD+oi5pezQETxdHKmQKGk1eQEYldK+jw5GxPfZ9z7Mk0Qnhf1W1m3w//EUn5BDmSZsbR44QQLBEqrBHqOrmSKaQAxdnLArCrxZcM7A7ZKs4ioRq8LFC+NpC3WCBJsvpVw5edm9iEXFuyNfxXAgSwfrFQ1c0iNda8AdejvUgnktOtJQQxmcfFzGglc5WVCj7oDgFqU18boeFSs52CUh8LE8BIVQDT1ABrB0HtgSEYlX5doJnCwv9TXocKCaKbnwhdDKPq4lf3SwU3HLq4V/+WYhHVMa/3b4IlfyikAduCkcBc7mQ3/z/Qq/cTuikhkzB12Ae/mcJC9U+Vo8Ej1gWAtgbeGgFsAMHr50BIWOLCbezvhpBFUdY6EJuJ/QDW0XoMX60zZ0AAAAASUVORK5CYII=";break}let r=e.append("g");r.attr("class","person-man");let i=Ee();switch(t.typeC4Shape.text){case"person":case"external_person":case"system":case"external_system":case"container":case"external_container":case"component":case"external_component":i.x=t.x,i.y=t.y,i.fill=o,i.width=t.width,i.height=t.height,i.stroke=l,i.rx=2.5,i.ry=2.5,i.attrs={"stroke-width":.5},le(r,i);break;case"system_db":case"external_system_db":case"container_db":case"external_container_db":case"component_db":case"external_component_db":r.append("path").attr("fill",o).attr("stroke-width","0.5").attr("stroke",l).attr("d","Mstartx,startyc0,-10 half,-10 half,-10c0,0 half,0 half,10l0,heightc0,10 -half,10 -half,10c0,0 -half,0 -half,-10l0,-height".replaceAll("startx",t.x).replaceAll("starty",t.y).replaceAll("half",t.width/2).replaceAll("height",t.height)),r.append("path").attr("fill","none").attr("stroke-width","0.5").attr("stroke",l).attr("d","Mstartx,startyc0,10 half,10 half,10c0,0 half,0 half,-10".replaceAll("startx",t.x).replaceAll("starty",t.y).replaceAll("half",t.width/2));break;case"system_queue":case"external_system_queue":case"container_queue":case"external_container_queue":case"component_queue":case"external_component_queue":r.append("path").attr("fill",o).attr("stroke-width","0.5").attr("stroke",l).attr("d","Mstartx,startylwidth,0c5,0 5,half 5,halfc0,0 0,half -5,halfl-width,0c-5,0 -5,-half -5,-halfc0,0 0,-half 5,-half".replaceAll("startx",t.x).replaceAll("starty",t.y).replaceAll("width",t.width).replaceAll("half",t.height/2)),r.append("path").attr("fill","none").attr("stroke-width","0.5").attr("stroke",l).attr("d","Mstartx,startyc-5,0 -5,half -5,halfc0,half 5,half 5,half".replaceAll("startx",t.x+t.width).replaceAll("starty",t.y).replaceAll("half",t.height/2));break}let u=O0(s,t.typeC4Shape.text);switch(r.append("text").attr("fill",a).attr("font-family",u.fontFamily).attr("font-size",u.fontSize-2).attr("font-style","italic").attr("lengthAdjust","spacing").attr("textLength",t.typeC4Shape.width).attr("x",t.x+t.width/2-t.typeC4Shape.width/2).attr("y",t.y+t.typeC4Shape.Y).text("<<"+t.typeC4Shape.text+">>"),t.typeC4Shape.text){case"person":case"external_person":Se(r,48,48,t.x+t.width/2-24,t.y+t.image.Y,n);break}let d=s[t.typeC4Shape.text+"Font"]();return d.fontWeight="bold",d.fontSize=d.fontSize+2,d.fontColor=a,Q(s)(t.label.text,r,t.x,t.y+t.label.Y,t.width,t.height,{fill:a},d),d=s[t.typeC4Shape.text+"Font"](),d.fontColor=a,t.techn&&t.techn?.text!==""?Q(s)(t.techn.text,r,t.x,t.y+t.techn.Y,t.width,t.height,{fill:a,"font-style":"italic"},d):t.type&&t.type.text!==""&&Q(s)(t.type.text,r,t.x,t.y+t.type.Y,t.width,t.height,{fill:a,"font-style":"italic"},d),t.descr&&t.descr.text!==""&&(d=s.personFont(),d.fontColor=a,Q(s)(t.descr.text,r,t.x,t.y+t.descr.Y,t.width,t.height,{fill:a},d)),t.height},"drawC4Shape"),m0=b(function(e){e.append("defs").append("symbol").attr("id","database").attr("fill-rule","evenodd").attr("clip-rule","evenodd").append("path").attr("transform","scale(.5)").attr("d","M12.258.001l.256.004.255.005.253.008.251.01.249.012.247.015.246.016.242.019.241.02.239.023.236.024.233.027.231.028.229.031.225.032.223.034.22.036.217.038.214.04.211.041.208.043.205.045.201.046.198.048.194.05.191.051.187.053.183.054.18.056.175.057.172.059.168.06.163.061.16.063.155.064.15.066.074.033.073.033.071.034.07.034.069.035.068.035.067.035.066.035.064.036.064.036.062.036.06.036.06.037.058.037.058.037.055.038.055.038.053.038.052.038.051.039.05.039.048.039.047.039.045.04.044.04.043.04.041.04.04.041.039.041.037.041.036.041.034.041.033.042.032.042.03.042.029.042.027.042.026.043.024.043.023.043.021.043.02.043.018.044.017.043.015.044.013.044.012.044.011.045.009.044.007.045.006.045.004.045.002.045.001.045v17l-.001.045-.002.045-.004.045-.006.045-.007.045-.009.044-.011.045-.012.044-.013.044-.015.044-.017.043-.018.044-.02.043-.021.043-.023.043-.024.043-.026.043-.027.042-.029.042-.03.042-.032.042-.033.042-.034.041-.036.041-.037.041-.039.041-.04.041-.041.04-.043.04-.044.04-.045.04-.047.039-.048.039-.05.039-.051.039-.052.038-.053.038-.055.038-.055.038-.058.037-.058.037-.06.037-.06.036-.062.036-.064.036-.064.036-.066.035-.067.035-.068.035-.069.035-.07.034-.071.034-.073.033-.074.033-.15.066-.155.064-.16.063-.163.061-.168.06-.172.059-.175.057-.18.056-.183.054-.187.053-.191.051-.194.05-.198.048-.201.046-.205.045-.208.043-.211.041-.214.04-.217.038-.22.036-.223.034-.225.032-.229.031-.231.028-.233.027-.236.024-.239.023-.241.02-.242.019-.246.016-.247.015-.249.012-.251.01-.253.008-.255.005-.256.004-.258.001-.258-.001-.256-.004-.255-.005-.253-.008-.251-.01-.249-.012-.247-.015-.245-.016-.243-.019-.241-.02-.238-.023-.236-.024-.234-.027-.231-.028-.228-.031-.226-.032-.223-.034-.22-.036-.217-.038-.214-.04-.211-.041-.208-.043-.204-.045-.201-.046-.198-.048-.195-.05-.19-.051-.187-.053-.184-.054-.179-.056-.176-.057-.172-.059-.167-.06-.164-.061-.159-.063-.155-.064-.151-.066-.074-.033-.072-.033-.072-.034-.07-.034-.069-.035-.068-.035-.067-.035-.066-.035-.064-.036-.063-.036-.062-.036-.061-.036-.06-.037-.058-.037-.057-.037-.056-.038-.055-.038-.053-.038-.052-.038-.051-.039-.049-.039-.049-.039-.046-.039-.046-.04-.044-.04-.043-.04-.041-.04-.04-.041-.039-.041-.037-.041-.036-.041-.034-.041-.033-.042-.032-.042-.03-.042-.029-.042-.027-.042-.026-.043-.024-.043-.023-.043-.021-.043-.02-.043-.018-.044-.017-.043-.015-.044-.013-.044-.012-.044-.011-.045-.009-.044-.007-.045-.006-.045-.004-.045-.002-.045-.001-.045v-17l.001-.045.002-.045.004-.045.006-.045.007-.045.009-.044.011-.045.012-.044.013-.044.015-.044.017-.043.018-.044.02-.043.021-.043.023-.043.024-.043.026-.043.027-.042.029-.042.03-.042.032-.042.033-.042.034-.041.036-.041.037-.041.039-.041.04-.041.041-.04.043-.04.044-.04.046-.04.046-.039.049-.039.049-.039.051-.039.052-.038.053-.038.055-.038.056-.038.057-.037.058-.037.06-.037.061-.036.062-.036.063-.036.064-.036.066-.035.067-.035.068-.035.069-.035.07-.034.072-.034.072-.033.074-.033.151-.066.155-.064.159-.063.164-.061.167-.06.172-.059.176-.057.179-.056.184-.054.187-.053.19-.051.195-.05.198-.048.201-.046.204-.045.208-.043.211-.041.214-.04.217-.038.22-.036.223-.034.226-.032.228-.031.231-.028.234-.027.236-.024.238-.023.241-.02.243-.019.245-.016.247-.015.249-.012.251-.01.253-.008.255-.005.256-.004.258-.001.258.001zm-9.258 20.499v.01l.001.021.003.021.004.022.005.021.006.022.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.023.018.024.019.024.021.024.022.025.023.024.024.025.052.049.056.05.061.051.066.051.07.051.075.051.079.052.084.052.088.052.092.052.097.052.102.051.105.052.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.048.144.049.147.047.152.047.155.047.16.045.163.045.167.043.171.043.176.041.178.041.183.039.187.039.19.037.194.035.197.035.202.033.204.031.209.03.212.029.216.027.219.025.222.024.226.021.23.02.233.018.236.016.24.015.243.012.246.01.249.008.253.005.256.004.259.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.021.224-.024.22-.026.216-.027.212-.028.21-.031.205-.031.202-.034.198-.034.194-.036.191-.037.187-.039.183-.04.179-.04.175-.042.172-.043.168-.044.163-.045.16-.046.155-.046.152-.047.148-.048.143-.049.139-.049.136-.05.131-.05.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.053.083-.051.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.05.023-.024.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.023.01-.022.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.127l-.077.055-.08.053-.083.054-.085.053-.087.052-.09.052-.093.051-.095.05-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.045-.118.044-.12.043-.122.042-.124.042-.126.041-.128.04-.13.04-.132.038-.134.038-.135.037-.138.037-.139.035-.142.035-.143.034-.144.033-.147.032-.148.031-.15.03-.151.03-.153.029-.154.027-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.01-.179.008-.179.008-.181.006-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.006-.179-.008-.179-.008-.178-.01-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.027-.153-.029-.151-.03-.15-.03-.148-.031-.146-.032-.145-.033-.143-.034-.141-.035-.14-.035-.137-.037-.136-.037-.134-.038-.132-.038-.13-.04-.128-.04-.126-.041-.124-.042-.122-.042-.12-.044-.117-.043-.116-.045-.113-.045-.112-.046-.109-.047-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.05-.093-.052-.09-.051-.087-.052-.085-.053-.083-.054-.08-.054-.077-.054v4.127zm0-5.654v.011l.001.021.003.021.004.021.005.022.006.022.007.022.009.022.01.022.011.023.012.023.013.023.015.024.016.023.017.024.018.024.019.024.021.024.022.024.023.025.024.024.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.052.11.051.114.051.119.052.123.05.127.051.131.05.135.049.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.044.171.042.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.022.23.02.233.018.236.016.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.012.241-.015.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.048.139-.05.136-.049.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.051.051-.049.023-.025.023-.024.021-.025.02-.024.019-.024.018-.024.017-.024.015-.023.014-.023.013-.024.012-.022.01-.023.01-.023.008-.022.006-.022.006-.022.004-.021.004-.022.001-.021.001-.021v-4.139l-.077.054-.08.054-.083.054-.085.052-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.044-.118.044-.12.044-.122.042-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.035-.143.033-.144.033-.147.033-.148.031-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.009-.179.009-.179.007-.181.007-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.007-.179-.007-.179-.009-.178-.009-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.031-.146-.033-.145-.033-.143-.033-.141-.035-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.04-.126-.041-.124-.042-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.051-.093-.051-.09-.051-.087-.053-.085-.052-.083-.054-.08-.054-.077-.054v4.139zm0-5.666v.011l.001.02.003.022.004.021.005.022.006.021.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.024.018.023.019.024.021.025.022.024.023.024.024.025.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.051.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.043.171.043.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.021.23.02.233.018.236.017.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.013.241-.014.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.049.139-.049.136-.049.131-.051.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.049.023-.025.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.022.01-.023.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.153l-.077.054-.08.054-.083.053-.085.053-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.048-.105.048-.106.048-.109.046-.111.046-.114.046-.115.044-.118.044-.12.043-.122.043-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.034-.143.034-.144.033-.147.032-.148.032-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.024-.161.024-.162.023-.163.023-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.01-.178.01-.179.009-.179.007-.181.006-.182.006-.182.004-.184.003-.184.001-.185.001-.185-.001-.184-.001-.184-.003-.182-.004-.182-.006-.181-.006-.179-.007-.179-.009-.178-.01-.176-.01-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.023-.162-.023-.161-.024-.159-.024-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.032-.146-.032-.145-.033-.143-.034-.141-.034-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.041-.126-.041-.124-.041-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.048-.105-.048-.102-.048-.1-.05-.097-.049-.095-.051-.093-.051-.09-.052-.087-.052-.085-.053-.083-.053-.08-.054-.077-.054v4.153zm8.74-8.179l-.257.004-.254.005-.25.008-.247.011-.244.012-.241.014-.237.016-.233.018-.231.021-.226.022-.224.023-.22.026-.216.027-.212.028-.21.031-.205.032-.202.033-.198.034-.194.036-.191.038-.187.038-.183.04-.179.041-.175.042-.172.043-.168.043-.163.045-.16.046-.155.046-.152.048-.148.048-.143.048-.139.049-.136.05-.131.05-.126.051-.123.051-.118.051-.114.052-.11.052-.106.052-.101.052-.096.052-.092.052-.088.052-.083.052-.079.052-.074.051-.07.052-.065.051-.06.05-.056.05-.051.05-.023.025-.023.024-.021.024-.02.025-.019.024-.018.024-.017.023-.015.024-.014.023-.013.023-.012.023-.01.023-.01.022-.008.022-.006.023-.006.021-.004.022-.004.021-.001.021-.001.021.001.021.001.021.004.021.004.022.006.021.006.023.008.022.01.022.01.023.012.023.013.023.014.023.015.024.017.023.018.024.019.024.02.025.021.024.023.024.023.025.051.05.056.05.06.05.065.051.07.052.074.051.079.052.083.052.088.052.092.052.096.052.101.052.106.052.11.052.114.052.118.051.123.051.126.051.131.05.136.05.139.049.143.048.148.048.152.048.155.046.16.046.163.045.168.043.172.043.175.042.179.041.183.04.187.038.191.038.194.036.198.034.202.033.205.032.21.031.212.028.216.027.22.026.224.023.226.022.231.021.233.018.237.016.241.014.244.012.247.011.25.008.254.005.257.004.26.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.022.224-.023.22-.026.216-.027.212-.028.21-.031.205-.032.202-.033.198-.034.194-.036.191-.038.187-.038.183-.04.179-.041.175-.042.172-.043.168-.043.163-.045.16-.046.155-.046.152-.048.148-.048.143-.048.139-.049.136-.05.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.05.051-.05.023-.025.023-.024.021-.024.02-.025.019-.024.018-.024.017-.023.015-.024.014-.023.013-.023.012-.023.01-.023.01-.022.008-.022.006-.023.006-.021.004-.022.004-.021.001-.021.001-.021-.001-.021-.001-.021-.004-.021-.004-.022-.006-.021-.006-.023-.008-.022-.01-.022-.01-.023-.012-.023-.013-.023-.014-.023-.015-.024-.017-.023-.018-.024-.019-.024-.02-.025-.021-.024-.023-.024-.023-.025-.051-.05-.056-.05-.06-.05-.065-.051-.07-.052-.074-.051-.079-.052-.083-.052-.088-.052-.092-.052-.096-.052-.101-.052-.106-.052-.11-.052-.114-.052-.118-.051-.123-.051-.126-.051-.131-.05-.136-.05-.139-.049-.143-.048-.148-.048-.152-.048-.155-.046-.16-.046-.163-.045-.168-.043-.172-.043-.175-.042-.179-.041-.183-.04-.187-.038-.191-.038-.194-.036-.198-.034-.202-.033-.205-.032-.21-.031-.212-.028-.216-.027-.22-.026-.224-.023-.226-.022-.231-.021-.233-.018-.237-.016-.241-.014-.244-.012-.247-.011-.25-.008-.254-.005-.257-.004-.26-.001-.26.001z")},"insertDatabaseIcon"),v0=b(function(e){e.append("defs").append("symbol").attr("id","computer").attr("width","24").attr("height","24").append("path").attr("transform","scale(.5)").attr("d","M2 2v13h20v-13h-20zm18 11h-16v-9h16v9zm-10.228 6l.466-1h3.524l.467 1h-4.457zm14.228 3h-24l2-6h2.104l-1.33 4h18.45l-1.297-4h2.073l2 6zm-5-10h-14v-7h14v7z")},"insertComputerIcon"),k0=b(function(e){e.append("defs").append("symbol").attr("id","clock").attr("width","24").attr("height","24").append("path").attr("transform","scale(.5)").attr("d","M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm5.848 12.459c.202.038.202.333.001.372-1.907.361-6.045 1.111-6.547 1.111-.719 0-1.301-.582-1.301-1.301 0-.512.77-5.447 1.125-7.445.034-.192.312-.181.343.014l.985 6.238 5.394 1.011z")},"insertClockIcon"),E0=b(function(e){e.append("defs").append("marker").attr("id","arrowhead").attr("refX",9).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",12).attr("markerHeight",12).attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 z")},"insertArrowHead"),A0=b(function(e){e.append("defs").append("marker").attr("id","arrowend").attr("refX",1).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",12).attr("markerHeight",12).attr("orient","auto").append("path").attr("d","M 10 0 L 0 5 L 10 10 z")},"insertArrowEnd"),C0=b(function(e){e.append("defs").append("marker").attr("id","filled-head").attr("refX",18).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L14,7 L9,1 Z")},"insertArrowFilledHead"),w0=b(function(e){e.append("defs").append("marker").attr("id","sequencenumber").attr("refX",15).attr("refY",15).attr("markerWidth",60).attr("markerHeight",40).attr("orient","auto").append("circle").attr("cx",15).attr("cy",15).attr("r",6)},"insertDynamicNumber"),T0=b(function(e){let s=e.append("defs").append("marker").attr("id","crosshead").attr("markerWidth",15).attr("markerHeight",8).attr("orient","auto").attr("refX",16).attr("refY",4);s.append("path").attr("fill","black").attr("stroke","#000000").style("stroke-dasharray","0, 0").attr("stroke-width","1px").attr("d","M 9,2 V 6 L16,4 Z"),s.append("path").attr("fill","none").attr("stroke","#000000").style("stroke-dasharray","0, 0").attr("stroke-width","1px").attr("d","M 0,1 L 6,7 M 6,1 L 0,7")},"insertArrowCrossHead"),O0=b((e,t)=>({fontFamily:e[t+"FontFamily"],fontSize:e[t+"FontSize"],fontWeight:e[t+"FontWeight"]}),"getC4ShapeFont"),Q=(function(){function e(l,a,n,r,i,u,d){let y=a.append("text").attr("x",n+i/2).attr("y",r+u/2+5).style("text-anchor","middle").text(l);o(y,d)}b(e,"byText");function t(l,a,n,r,i,u,d,y){let{fontSize:p,fontFamily:k,fontWeight:O}=y,S=l.split(Yt.lineBreakRegex);for(let P=0;P=this.data.widthLimit||s>=this.data.widthLimit||this.nextData.cnt>De)&&(t=this.nextData.startx+e.margin+_.nextLinePaddingX,o=this.nextData.stopy+e.margin*2,this.nextData.stopx=s=t+e.width,this.nextData.starty=this.nextData.stopy,this.nextData.stopy=l=o+e.height,this.nextData.cnt=1),e.x=t,e.y=o,this.updateVal(this.data,"startx",t,Math.min),this.updateVal(this.data,"starty",o,Math.min),this.updateVal(this.data,"stopx",s,Math.max),this.updateVal(this.data,"stopy",l,Math.max),this.updateVal(this.nextData,"startx",t,Math.min),this.updateVal(this.nextData,"starty",o,Math.min),this.updateVal(this.nextData,"stopx",s,Math.max),this.updateVal(this.nextData,"stopy",l,Math.max)}init(e){this.name="",this.data={startx:void 0,stopx:void 0,starty:void 0,stopy:void 0,widthLimit:void 0},this.nextData={startx:void 0,stopx:void 0,starty:void 0,stopy:void 0,cnt:0},re(e.db.getConfig())}bumpLastMargin(e){this.data.stopx+=e,this.data.stopy+=e}},re=b(function(e){ye(_,e),e.fontFamily&&(_.personFontFamily=_.systemFontFamily=_.messageFontFamily=e.fontFamily),e.fontSize&&(_.personFontSize=_.systemFontSize=_.messageFontSize=e.fontSize),e.fontWeight&&(_.personFontWeight=_.systemFontWeight=_.messageFontWeight=e.fontWeight)},"setConf"),Pt=b((e,t)=>({fontFamily:e[t+"FontFamily"],fontSize:e[t+"FontSize"],fontWeight:e[t+"FontWeight"]}),"c4ShapeFont"),jt=b(e=>({fontFamily:e.boundaryFontFamily,fontSize:e.boundaryFontSize,fontWeight:e.boundaryFontWeight}),"boundaryFont"),R0=b(e=>({fontFamily:e.messageFontFamily,fontSize:e.messageFontSize,fontWeight:e.messageFontWeight}),"messageFont");function j(e,t,s,o,l){if(!t[e].width)if(s)t[e].text=ve(t[e].text,l,o),t[e].textLines=t[e].text.split(Yt.lineBreakRegex).length,t[e].width=l,t[e].height=ee(t[e].text,o);else{let a=t[e].text.split(Yt.lineBreakRegex);t[e].textLines=a.length;let n=0;t[e].height=0,t[e].width=0;for(let r of a)t[e].width=Math.max(Ct(r,o),t[e].width),n=ee(r,o),t[e].height=t[e].height+n}}b(j,"calcC4ShapeTextWH");var Be=b(function(e,t,s){t.x=s.data.startx,t.y=s.data.starty,t.width=s.data.stopx-s.data.startx,t.height=s.data.stopy-s.data.starty,t.label.y=_.c4ShapeMargin-35;let o=t.wrap&&_.wrap,l=jt(_);l.fontSize=l.fontSize+2,l.fontWeight="bold";let a=Ct(t.label.text,l);j("label",t,o,l,a),z.drawBoundary(e,t,_)},"drawBoundary"),Ie=b(function(e,t,s,o){let l=0;for(let a of o){l=0;let n=s[a],r=Pt(_,n.typeC4Shape.text);switch(r.fontSize=r.fontSize-2,n.typeC4Shape.width=Ct("\xAB"+n.typeC4Shape.text+"\xBB",r),n.typeC4Shape.height=r.fontSize+2,n.typeC4Shape.Y=_.c4ShapePadding,l=n.typeC4Shape.Y+n.typeC4Shape.height-4,n.image={width:0,height:0,Y:0},n.typeC4Shape.text){case"person":case"external_person":n.image.width=48,n.image.height=48,n.image.Y=l,l=n.image.Y+n.image.height;break}n.sprite&&(n.image.width=48,n.image.height=48,n.image.Y=l,l=n.image.Y+n.image.height);let i=n.wrap&&_.wrap,u=_.width-_.c4ShapePadding*2,d=Pt(_,n.typeC4Shape.text);if(d.fontSize=d.fontSize+2,d.fontWeight="bold",j("label",n,i,d,u),n.label.Y=l+8,l=n.label.Y+n.label.height,n.type&&n.type.text!==""){n.type.text="["+n.type.text+"]";let k=Pt(_,n.typeC4Shape.text);j("type",n,i,k,u),n.type.Y=l+5,l=n.type.Y+n.type.height}else if(n.techn&&n.techn.text!==""){n.techn.text="["+n.techn.text+"]";let k=Pt(_,n.techn.text);j("techn",n,i,k,u),n.techn.Y=l+5,l=n.techn.Y+n.techn.height}let y=l,p=n.label.width;if(n.descr&&n.descr.text!==""){let k=Pt(_,n.typeC4Shape.text);j("descr",n,i,k,u),n.descr.Y=l+20,l=n.descr.Y+n.descr.height,p=Math.max(n.label.width,n.descr.width),y=l-n.descr.textLines*5}p=p+_.c4ShapePadding,n.width=Math.max(n.width||_.width,p,_.width),n.height=Math.max(n.height||_.height,y,_.height),n.margin=n.margin||_.c4ShapeMargin,e.insert(n),z.drawC4Shape(t,n,_)}e.bumpLastMargin(_.c4ShapeMargin)},"drawC4ShapeArray"),Y=class{static{b(this,"Point")}constructor(e,t){this.x=e,this.y=t}},Ae=b(function(e,t){let s=e.x,o=e.y,l=t.x,a=t.y,n=s+e.width/2,r=o+e.height/2,i=Math.abs(s-l),u=Math.abs(o-a),d=u/i,y=e.height/e.width,p=null;return o==a&&sl?p=new Y(s,r):s==l&&oa&&(p=new Y(n,o)),s>l&&o=d?p=new Y(s,r+d*e.width/2):p=new Y(n-i/u*e.height/2,o+e.height):s=d?p=new Y(s+e.width,r+d*e.width/2):p=new Y(n+i/u*e.height/2,o+e.height):sa?y>=d?p=new Y(s+e.width,r-d*e.width/2):p=new Y(n+e.height/2*i/u,o):s>l&&o>a&&(y>=d?p=new Y(s,r-e.width/2*d):p=new Y(n-e.height/2*i/u,o)),p},"getIntersectPoint"),S0=b(function(e,t){let s={x:0,y:0};s.x=t.x+t.width/2,s.y=t.y+t.height/2;let o=Ae(e,s);s.x=e.x+e.width/2,s.y=e.y+e.height/2;let l=Ae(t,s);return{startPoint:o,endPoint:l}},"getIntersectPoints"),D0=b(function(e,t,s,o){let l=0;for(let a of t){l=l+1;let n=a.wrap&&_.wrap,r=R0(_);o.db.getC4Type()==="C4Dynamic"&&(a.label.text=l+": "+a.label.text);let u=Ct(a.label.text,r);j("label",a,n,r,u),a.techn&&a.techn.text!==""&&(u=Ct(a.techn.text,r),j("techn",a,n,r,u)),a.descr&&a.descr.text!==""&&(u=Ct(a.descr.text,r),j("descr",a,n,r,u));let d=s(a.from),y=s(a.to),p=S0(d,y);a.startPoint=p.startPoint,a.endPoint=p.endPoint}z.drawRels(e,t,_)},"drawRels");function oe(e,t,s,o,l){let a=new Pe(l);a.data.widthLimit=s.data.widthLimit/Math.min(ie,o.length);for(let[n,r]of o.entries()){let i=0;r.image={width:0,height:0,Y:0},r.sprite&&(r.image.width=48,r.image.height=48,r.image.Y=i,i=r.image.Y+r.image.height);let u=r.wrap&&_.wrap,d=jt(_);if(d.fontSize=d.fontSize+2,d.fontWeight="bold",j("label",r,u,d,a.data.widthLimit),r.label.Y=i+8,i=r.label.Y+r.label.height,r.type&&r.type.text!==""){r.type.text="["+r.type.text+"]";let O=jt(_);j("type",r,u,O,a.data.widthLimit),r.type.Y=i+5,i=r.type.Y+r.type.height}if(r.descr&&r.descr.text!==""){let O=jt(_);O.fontSize=O.fontSize-2,j("descr",r,u,O,a.data.widthLimit),r.descr.Y=i+20,i=r.descr.Y+r.descr.height}if(n==0||n%ie===0){let O=s.data.startx+_.diagramMarginX,S=s.data.stopy+_.diagramMarginY+i;a.setData(O,O,S,S)}else{let O=a.data.stopx!==a.data.startx?a.data.stopx+_.diagramMarginX:a.data.startx,S=a.data.starty;a.setData(O,O,S,S)}a.name=r.alias;let y=l.db.getC4ShapeArray(r.alias),p=l.db.getC4ShapeKeys(r.alias);p.length>0&&Ie(a,e,y,p),t=r.alias;let k=l.db.getBoundaries(t);k.length>0&&oe(e,t,a,k,l),r.alias!=="global"&&Be(e,r,a),s.data.stopy=Math.max(a.data.stopy+_.c4ShapeMargin,s.data.stopy),s.data.stopx=Math.max(a.data.stopx+_.c4ShapeMargin,s.data.stopx),zt=Math.max(zt,s.data.stopx),Xt=Math.max(Xt,s.data.stopy)}}b(oe,"drawInsideBoundary");var P0=b(function(e,t,s,o){_=Ot().c4;let l=Ot().securityLevel,a;l==="sandbox"&&(a=Dt("#i"+t));let n=l==="sandbox"?Dt(a.nodes()[0].contentDocument.body):Dt("body"),r=o.db;o.db.setWrap(_.wrap),De=r.getC4ShapeInRow(),ie=r.getC4BoundaryInRow(),$t.debug(`C:${JSON.stringify(_,null,2)}`);let i=l==="sandbox"?n.select(`[id="${t}"]`):Dt(`[id="${t}"]`);z.insertComputerIcon(i),z.insertDatabaseIcon(i),z.insertClockIcon(i);let u=new Pe(o);u.setData(_.diagramMarginX,_.diagramMarginX,_.diagramMarginY,_.diagramMarginY),u.data.widthLimit=screen.availWidth,zt=_.diagramMarginX,Xt=_.diagramMarginY;let d=o.db.getTitle(),y=o.db.getBoundaries("");oe(i,"",u,y,o),z.insertArrowHead(i),z.insertArrowEnd(i),z.insertArrowCrossHead(i),z.insertArrowFilledHead(i),D0(i,o.db.getRels(),o.db.getC4Shape,o),u.data.stopx=zt,u.data.stopy=Xt;let p=u.data,O=p.stopy-p.starty+2*_.diagramMarginY,P=p.stopx-p.startx+2*_.diagramMarginX;d&&i.append("text").text(d).attr("x",(p.stopx-p.startx)/2-4*_.diagramMarginX).attr("y",p.starty+_.diagramMarginY),be(i,O,P,_.useMaxWidth);let M=d?60:0;i.attr("viewBox",p.startx-_.diagramMarginX+" -"+(_.diagramMarginY+M)+" "+P+" "+(O+M)),$t.debug("models:",p)},"draw"),Ce={drawPersonOrSystemArray:Ie,drawBoundary:Be,setConf:re,draw:P0},B0=b(e=>`.person { + stroke: ${e.personBorder}; + fill: ${e.personBkg}; + } +`,"getStyles"),I0=B0,F0={parser:Ve,db:ae,renderer:Ce,styles:I0,init:b(({c4:e,wrap:t})=>{Ce.setConf(e),ae.setWrap(t)},"init")};export{F0 as diagram}; +//# sourceMappingURL=c4Diagram-YG6GDRKO-6JHP5GV7.min.js.map diff --git a/docs/website/public/c4Diagram-YG6GDRKO-6JHP5GV7.min.js.map b/docs/website/public/c4Diagram-YG6GDRKO-6JHP5GV7.min.js.map new file mode 100644 index 000000000..5a6eba950 --- /dev/null +++ b/docs/website/public/c4Diagram-YG6GDRKO-6JHP5GV7.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/mermaid/dist/chunks/mermaid.core/c4Diagram-YG6GDRKO.mjs"], + "sourcesContent": ["import {\n drawRect,\n getNoteRect\n} from \"./chunk-TZMSLE5B.mjs\";\nimport {\n calculateTextHeight,\n calculateTextWidth,\n wrapLabel\n} from \"./chunk-S3R3BYOJ.mjs\";\nimport {\n assignWithDepth_default,\n common_default,\n configureSvgSize,\n getAccDescription,\n getAccTitle,\n getConfig2 as getConfig,\n sanitizeText,\n setAccDescription,\n setAccTitle\n} from \"./chunk-ABZYJK2D.mjs\";\nimport {\n __name,\n log\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/diagrams/c4/parser/c4Diagram.jison\nvar parser = (function() {\n var o = /* @__PURE__ */ __name(function(k, v, o2, l) {\n for (o2 = o2 || {}, l = k.length; l--; o2[k[l]] = v) ;\n return o2;\n }, \"o\"), $V0 = [1, 24], $V1 = [1, 25], $V2 = [1, 26], $V3 = [1, 27], $V4 = [1, 28], $V5 = [1, 63], $V6 = [1, 64], $V7 = [1, 65], $V8 = [1, 66], $V9 = [1, 67], $Va = [1, 68], $Vb = [1, 69], $Vc = [1, 29], $Vd = [1, 30], $Ve = [1, 31], $Vf = [1, 32], $Vg = [1, 33], $Vh = [1, 34], $Vi = [1, 35], $Vj = [1, 36], $Vk = [1, 37], $Vl = [1, 38], $Vm = [1, 39], $Vn = [1, 40], $Vo = [1, 41], $Vp = [1, 42], $Vq = [1, 43], $Vr = [1, 44], $Vs = [1, 45], $Vt = [1, 46], $Vu = [1, 47], $Vv = [1, 48], $Vw = [1, 50], $Vx = [1, 51], $Vy = [1, 52], $Vz = [1, 53], $VA = [1, 54], $VB = [1, 55], $VC = [1, 56], $VD = [1, 57], $VE = [1, 58], $VF = [1, 59], $VG = [1, 60], $VH = [14, 42], $VI = [14, 34, 36, 37, 38, 39, 40, 41, 42, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74], $VJ = [12, 14, 34, 36, 37, 38, 39, 40, 41, 42, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74], $VK = [1, 82], $VL = [1, 83], $VM = [1, 84], $VN = [1, 85], $VO = [12, 14, 42], $VP = [12, 14, 33, 42], $VQ = [12, 14, 33, 42, 76, 77, 79, 80], $VR = [12, 33], $VS = [34, 36, 37, 38, 39, 40, 41, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74];\n var parser2 = {\n trace: /* @__PURE__ */ __name(function trace() {\n }, \"trace\"),\n yy: {},\n symbols_: { \"error\": 2, \"start\": 3, \"mermaidDoc\": 4, \"direction\": 5, \"direction_tb\": 6, \"direction_bt\": 7, \"direction_rl\": 8, \"direction_lr\": 9, \"graphConfig\": 10, \"C4_CONTEXT\": 11, \"NEWLINE\": 12, \"statements\": 13, \"EOF\": 14, \"C4_CONTAINER\": 15, \"C4_COMPONENT\": 16, \"C4_DYNAMIC\": 17, \"C4_DEPLOYMENT\": 18, \"otherStatements\": 19, \"diagramStatements\": 20, \"otherStatement\": 21, \"title\": 22, \"accDescription\": 23, \"acc_title\": 24, \"acc_title_value\": 25, \"acc_descr\": 26, \"acc_descr_value\": 27, \"acc_descr_multiline_value\": 28, \"boundaryStatement\": 29, \"boundaryStartStatement\": 30, \"boundaryStopStatement\": 31, \"boundaryStart\": 32, \"LBRACE\": 33, \"ENTERPRISE_BOUNDARY\": 34, \"attributes\": 35, \"SYSTEM_BOUNDARY\": 36, \"BOUNDARY\": 37, \"CONTAINER_BOUNDARY\": 38, \"NODE\": 39, \"NODE_L\": 40, \"NODE_R\": 41, \"RBRACE\": 42, \"diagramStatement\": 43, \"PERSON\": 44, \"PERSON_EXT\": 45, \"SYSTEM\": 46, \"SYSTEM_DB\": 47, \"SYSTEM_QUEUE\": 48, \"SYSTEM_EXT\": 49, \"SYSTEM_EXT_DB\": 50, \"SYSTEM_EXT_QUEUE\": 51, \"CONTAINER\": 52, \"CONTAINER_DB\": 53, \"CONTAINER_QUEUE\": 54, \"CONTAINER_EXT\": 55, \"CONTAINER_EXT_DB\": 56, \"CONTAINER_EXT_QUEUE\": 57, \"COMPONENT\": 58, \"COMPONENT_DB\": 59, \"COMPONENT_QUEUE\": 60, \"COMPONENT_EXT\": 61, \"COMPONENT_EXT_DB\": 62, \"COMPONENT_EXT_QUEUE\": 63, \"REL\": 64, \"BIREL\": 65, \"REL_U\": 66, \"REL_D\": 67, \"REL_L\": 68, \"REL_R\": 69, \"REL_B\": 70, \"REL_INDEX\": 71, \"UPDATE_EL_STYLE\": 72, \"UPDATE_REL_STYLE\": 73, \"UPDATE_LAYOUT_CONFIG\": 74, \"attribute\": 75, \"STR\": 76, \"STR_KEY\": 77, \"STR_VALUE\": 78, \"ATTRIBUTE\": 79, \"ATTRIBUTE_EMPTY\": 80, \"$accept\": 0, \"$end\": 1 },\n terminals_: { 2: \"error\", 6: \"direction_tb\", 7: \"direction_bt\", 8: \"direction_rl\", 9: \"direction_lr\", 11: \"C4_CONTEXT\", 12: \"NEWLINE\", 14: \"EOF\", 15: \"C4_CONTAINER\", 16: \"C4_COMPONENT\", 17: \"C4_DYNAMIC\", 18: \"C4_DEPLOYMENT\", 22: \"title\", 23: \"accDescription\", 24: \"acc_title\", 25: \"acc_title_value\", 26: \"acc_descr\", 27: \"acc_descr_value\", 28: \"acc_descr_multiline_value\", 33: \"LBRACE\", 34: \"ENTERPRISE_BOUNDARY\", 36: \"SYSTEM_BOUNDARY\", 37: \"BOUNDARY\", 38: \"CONTAINER_BOUNDARY\", 39: \"NODE\", 40: \"NODE_L\", 41: \"NODE_R\", 42: \"RBRACE\", 44: \"PERSON\", 45: \"PERSON_EXT\", 46: \"SYSTEM\", 47: \"SYSTEM_DB\", 48: \"SYSTEM_QUEUE\", 49: \"SYSTEM_EXT\", 50: \"SYSTEM_EXT_DB\", 51: \"SYSTEM_EXT_QUEUE\", 52: \"CONTAINER\", 53: \"CONTAINER_DB\", 54: \"CONTAINER_QUEUE\", 55: \"CONTAINER_EXT\", 56: \"CONTAINER_EXT_DB\", 57: \"CONTAINER_EXT_QUEUE\", 58: \"COMPONENT\", 59: \"COMPONENT_DB\", 60: \"COMPONENT_QUEUE\", 61: \"COMPONENT_EXT\", 62: \"COMPONENT_EXT_DB\", 63: \"COMPONENT_EXT_QUEUE\", 64: \"REL\", 65: \"BIREL\", 66: \"REL_U\", 67: \"REL_D\", 68: \"REL_L\", 69: \"REL_R\", 70: \"REL_B\", 71: \"REL_INDEX\", 72: \"UPDATE_EL_STYLE\", 73: \"UPDATE_REL_STYLE\", 74: \"UPDATE_LAYOUT_CONFIG\", 76: \"STR\", 77: \"STR_KEY\", 78: \"STR_VALUE\", 79: \"ATTRIBUTE\", 80: \"ATTRIBUTE_EMPTY\" },\n productions_: [0, [3, 1], [3, 1], [5, 1], [5, 1], [5, 1], [5, 1], [4, 1], [10, 4], [10, 4], [10, 4], [10, 4], [10, 4], [13, 1], [13, 1], [13, 2], [19, 1], [19, 2], [19, 3], [21, 1], [21, 1], [21, 2], [21, 2], [21, 1], [29, 3], [30, 3], [30, 3], [30, 4], [32, 2], [32, 2], [32, 2], [32, 2], [32, 2], [32, 2], [32, 2], [31, 1], [20, 1], [20, 2], [20, 3], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 1], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [43, 2], [35, 1], [35, 2], [75, 1], [75, 2], [75, 1], [75, 1]],\n performAction: /* @__PURE__ */ __name(function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$) {\n var $0 = $$.length - 1;\n switch (yystate) {\n case 3:\n yy.setDirection(\"TB\");\n break;\n case 4:\n yy.setDirection(\"BT\");\n break;\n case 5:\n yy.setDirection(\"RL\");\n break;\n case 6:\n yy.setDirection(\"LR\");\n break;\n case 8:\n case 9:\n case 10:\n case 11:\n case 12:\n yy.setC4Type($$[$0 - 3]);\n break;\n case 19:\n yy.setTitle($$[$0].substring(6));\n this.$ = $$[$0].substring(6);\n break;\n case 20:\n yy.setAccDescription($$[$0].substring(15));\n this.$ = $$[$0].substring(15);\n break;\n case 21:\n this.$ = $$[$0].trim();\n yy.setTitle(this.$);\n break;\n case 22:\n case 23:\n this.$ = $$[$0].trim();\n yy.setAccDescription(this.$);\n break;\n case 28:\n $$[$0].splice(2, 0, \"ENTERPRISE\");\n yy.addPersonOrSystemBoundary(...$$[$0]);\n this.$ = $$[$0];\n break;\n case 29:\n $$[$0].splice(2, 0, \"SYSTEM\");\n yy.addPersonOrSystemBoundary(...$$[$0]);\n this.$ = $$[$0];\n break;\n case 30:\n yy.addPersonOrSystemBoundary(...$$[$0]);\n this.$ = $$[$0];\n break;\n case 31:\n $$[$0].splice(2, 0, \"CONTAINER\");\n yy.addContainerBoundary(...$$[$0]);\n this.$ = $$[$0];\n break;\n case 32:\n yy.addDeploymentNode(\"node\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 33:\n yy.addDeploymentNode(\"nodeL\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 34:\n yy.addDeploymentNode(\"nodeR\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 35:\n yy.popBoundaryParseStack();\n break;\n case 39:\n yy.addPersonOrSystem(\"person\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 40:\n yy.addPersonOrSystem(\"external_person\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 41:\n yy.addPersonOrSystem(\"system\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 42:\n yy.addPersonOrSystem(\"system_db\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 43:\n yy.addPersonOrSystem(\"system_queue\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 44:\n yy.addPersonOrSystem(\"external_system\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 45:\n yy.addPersonOrSystem(\"external_system_db\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 46:\n yy.addPersonOrSystem(\"external_system_queue\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 47:\n yy.addContainer(\"container\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 48:\n yy.addContainer(\"container_db\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 49:\n yy.addContainer(\"container_queue\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 50:\n yy.addContainer(\"external_container\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 51:\n yy.addContainer(\"external_container_db\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 52:\n yy.addContainer(\"external_container_queue\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 53:\n yy.addComponent(\"component\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 54:\n yy.addComponent(\"component_db\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 55:\n yy.addComponent(\"component_queue\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 56:\n yy.addComponent(\"external_component\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 57:\n yy.addComponent(\"external_component_db\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 58:\n yy.addComponent(\"external_component_queue\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 60:\n yy.addRel(\"rel\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 61:\n yy.addRel(\"birel\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 62:\n yy.addRel(\"rel_u\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 63:\n yy.addRel(\"rel_d\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 64:\n yy.addRel(\"rel_l\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 65:\n yy.addRel(\"rel_r\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 66:\n yy.addRel(\"rel_b\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 67:\n $$[$0].splice(0, 1);\n yy.addRel(\"rel\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 68:\n yy.updateElStyle(\"update_el_style\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 69:\n yy.updateRelStyle(\"update_rel_style\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 70:\n yy.updateLayoutConfig(\"update_layout_config\", ...$$[$0]);\n this.$ = $$[$0];\n break;\n case 71:\n this.$ = [$$[$0]];\n break;\n case 72:\n $$[$0].unshift($$[$0 - 1]);\n this.$ = $$[$0];\n break;\n case 73:\n case 75:\n this.$ = $$[$0].trim();\n break;\n case 74:\n let kv = {};\n kv[$$[$0 - 1].trim()] = $$[$0].trim();\n this.$ = kv;\n break;\n case 76:\n this.$ = \"\";\n break;\n }\n }, \"anonymous\"),\n table: [{ 3: 1, 4: 2, 5: 3, 6: [1, 5], 7: [1, 6], 8: [1, 7], 9: [1, 8], 10: 4, 11: [1, 9], 15: [1, 10], 16: [1, 11], 17: [1, 12], 18: [1, 13] }, { 1: [3] }, { 1: [2, 1] }, { 1: [2, 2] }, { 1: [2, 7] }, { 1: [2, 3] }, { 1: [2, 4] }, { 1: [2, 5] }, { 1: [2, 6] }, { 12: [1, 14] }, { 12: [1, 15] }, { 12: [1, 16] }, { 12: [1, 17] }, { 12: [1, 18] }, { 13: 19, 19: 20, 20: 21, 21: 22, 22: $V0, 23: $V1, 24: $V2, 26: $V3, 28: $V4, 29: 49, 30: 61, 32: 62, 34: $V5, 36: $V6, 37: $V7, 38: $V8, 39: $V9, 40: $Va, 41: $Vb, 43: 23, 44: $Vc, 45: $Vd, 46: $Ve, 47: $Vf, 48: $Vg, 49: $Vh, 50: $Vi, 51: $Vj, 52: $Vk, 53: $Vl, 54: $Vm, 55: $Vn, 56: $Vo, 57: $Vp, 58: $Vq, 59: $Vr, 60: $Vs, 61: $Vt, 62: $Vu, 63: $Vv, 64: $Vw, 65: $Vx, 66: $Vy, 67: $Vz, 68: $VA, 69: $VB, 70: $VC, 71: $VD, 72: $VE, 73: $VF, 74: $VG }, { 13: 70, 19: 20, 20: 21, 21: 22, 22: $V0, 23: $V1, 24: $V2, 26: $V3, 28: $V4, 29: 49, 30: 61, 32: 62, 34: $V5, 36: $V6, 37: $V7, 38: $V8, 39: $V9, 40: $Va, 41: $Vb, 43: 23, 44: $Vc, 45: $Vd, 46: $Ve, 47: $Vf, 48: $Vg, 49: $Vh, 50: $Vi, 51: $Vj, 52: $Vk, 53: $Vl, 54: $Vm, 55: $Vn, 56: $Vo, 57: $Vp, 58: $Vq, 59: $Vr, 60: $Vs, 61: $Vt, 62: $Vu, 63: $Vv, 64: $Vw, 65: $Vx, 66: $Vy, 67: $Vz, 68: $VA, 69: $VB, 70: $VC, 71: $VD, 72: $VE, 73: $VF, 74: $VG }, { 13: 71, 19: 20, 20: 21, 21: 22, 22: $V0, 23: $V1, 24: $V2, 26: $V3, 28: $V4, 29: 49, 30: 61, 32: 62, 34: $V5, 36: $V6, 37: $V7, 38: $V8, 39: $V9, 40: $Va, 41: $Vb, 43: 23, 44: $Vc, 45: $Vd, 46: $Ve, 47: $Vf, 48: $Vg, 49: $Vh, 50: $Vi, 51: $Vj, 52: $Vk, 53: $Vl, 54: $Vm, 55: $Vn, 56: $Vo, 57: $Vp, 58: $Vq, 59: $Vr, 60: $Vs, 61: $Vt, 62: $Vu, 63: $Vv, 64: $Vw, 65: $Vx, 66: $Vy, 67: $Vz, 68: $VA, 69: $VB, 70: $VC, 71: $VD, 72: $VE, 73: $VF, 74: $VG }, { 13: 72, 19: 20, 20: 21, 21: 22, 22: $V0, 23: $V1, 24: $V2, 26: $V3, 28: $V4, 29: 49, 30: 61, 32: 62, 34: $V5, 36: $V6, 37: $V7, 38: $V8, 39: $V9, 40: $Va, 41: $Vb, 43: 23, 44: $Vc, 45: $Vd, 46: $Ve, 47: $Vf, 48: $Vg, 49: $Vh, 50: $Vi, 51: $Vj, 52: $Vk, 53: $Vl, 54: $Vm, 55: $Vn, 56: $Vo, 57: $Vp, 58: $Vq, 59: $Vr, 60: $Vs, 61: $Vt, 62: $Vu, 63: $Vv, 64: $Vw, 65: $Vx, 66: $Vy, 67: $Vz, 68: $VA, 69: $VB, 70: $VC, 71: $VD, 72: $VE, 73: $VF, 74: $VG }, { 13: 73, 19: 20, 20: 21, 21: 22, 22: $V0, 23: $V1, 24: $V2, 26: $V3, 28: $V4, 29: 49, 30: 61, 32: 62, 34: $V5, 36: $V6, 37: $V7, 38: $V8, 39: $V9, 40: $Va, 41: $Vb, 43: 23, 44: $Vc, 45: $Vd, 46: $Ve, 47: $Vf, 48: $Vg, 49: $Vh, 50: $Vi, 51: $Vj, 52: $Vk, 53: $Vl, 54: $Vm, 55: $Vn, 56: $Vo, 57: $Vp, 58: $Vq, 59: $Vr, 60: $Vs, 61: $Vt, 62: $Vu, 63: $Vv, 64: $Vw, 65: $Vx, 66: $Vy, 67: $Vz, 68: $VA, 69: $VB, 70: $VC, 71: $VD, 72: $VE, 73: $VF, 74: $VG }, { 14: [1, 74] }, o($VH, [2, 13], { 43: 23, 29: 49, 30: 61, 32: 62, 20: 75, 34: $V5, 36: $V6, 37: $V7, 38: $V8, 39: $V9, 40: $Va, 41: $Vb, 44: $Vc, 45: $Vd, 46: $Ve, 47: $Vf, 48: $Vg, 49: $Vh, 50: $Vi, 51: $Vj, 52: $Vk, 53: $Vl, 54: $Vm, 55: $Vn, 56: $Vo, 57: $Vp, 58: $Vq, 59: $Vr, 60: $Vs, 61: $Vt, 62: $Vu, 63: $Vv, 64: $Vw, 65: $Vx, 66: $Vy, 67: $Vz, 68: $VA, 69: $VB, 70: $VC, 71: $VD, 72: $VE, 73: $VF, 74: $VG }), o($VH, [2, 14]), o($VI, [2, 16], { 12: [1, 76] }), o($VH, [2, 36], { 12: [1, 77] }), o($VJ, [2, 19]), o($VJ, [2, 20]), { 25: [1, 78] }, { 27: [1, 79] }, o($VJ, [2, 23]), { 35: 80, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 86, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 87, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 88, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 89, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 90, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 91, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 92, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 93, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 94, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 95, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 96, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 97, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 98, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 99, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 100, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 101, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 102, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 103, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 104, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, o($VO, [2, 59]), { 35: 105, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 106, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 107, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 108, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 109, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 110, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 111, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 112, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 113, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 114, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 115, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 20: 116, 29: 49, 30: 61, 32: 62, 34: $V5, 36: $V6, 37: $V7, 38: $V8, 39: $V9, 40: $Va, 41: $Vb, 43: 23, 44: $Vc, 45: $Vd, 46: $Ve, 47: $Vf, 48: $Vg, 49: $Vh, 50: $Vi, 51: $Vj, 52: $Vk, 53: $Vl, 54: $Vm, 55: $Vn, 56: $Vo, 57: $Vp, 58: $Vq, 59: $Vr, 60: $Vs, 61: $Vt, 62: $Vu, 63: $Vv, 64: $Vw, 65: $Vx, 66: $Vy, 67: $Vz, 68: $VA, 69: $VB, 70: $VC, 71: $VD, 72: $VE, 73: $VF, 74: $VG }, { 12: [1, 118], 33: [1, 117] }, { 35: 119, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 120, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 121, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 122, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 123, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 124, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 35: 125, 75: 81, 76: $VK, 77: $VL, 79: $VM, 80: $VN }, { 14: [1, 126] }, { 14: [1, 127] }, { 14: [1, 128] }, { 14: [1, 129] }, { 1: [2, 8] }, o($VH, [2, 15]), o($VI, [2, 17], { 21: 22, 19: 130, 22: $V0, 23: $V1, 24: $V2, 26: $V3, 28: $V4 }), o($VH, [2, 37], { 19: 20, 20: 21, 21: 22, 43: 23, 29: 49, 30: 61, 32: 62, 13: 131, 22: $V0, 23: $V1, 24: $V2, 26: $V3, 28: $V4, 34: $V5, 36: $V6, 37: $V7, 38: $V8, 39: $V9, 40: $Va, 41: $Vb, 44: $Vc, 45: $Vd, 46: $Ve, 47: $Vf, 48: $Vg, 49: $Vh, 50: $Vi, 51: $Vj, 52: $Vk, 53: $Vl, 54: $Vm, 55: $Vn, 56: $Vo, 57: $Vp, 58: $Vq, 59: $Vr, 60: $Vs, 61: $Vt, 62: $Vu, 63: $Vv, 64: $Vw, 65: $Vx, 66: $Vy, 67: $Vz, 68: $VA, 69: $VB, 70: $VC, 71: $VD, 72: $VE, 73: $VF, 74: $VG }), o($VJ, [2, 21]), o($VJ, [2, 22]), o($VO, [2, 39]), o($VP, [2, 71], { 75: 81, 35: 132, 76: $VK, 77: $VL, 79: $VM, 80: $VN }), o($VQ, [2, 73]), { 78: [1, 133] }, o($VQ, [2, 75]), o($VQ, [2, 76]), o($VO, [2, 40]), o($VO, [2, 41]), o($VO, [2, 42]), o($VO, [2, 43]), o($VO, [2, 44]), o($VO, [2, 45]), o($VO, [2, 46]), o($VO, [2, 47]), o($VO, [2, 48]), o($VO, [2, 49]), o($VO, [2, 50]), o($VO, [2, 51]), o($VO, [2, 52]), o($VO, [2, 53]), o($VO, [2, 54]), o($VO, [2, 55]), o($VO, [2, 56]), o($VO, [2, 57]), o($VO, [2, 58]), o($VO, [2, 60]), o($VO, [2, 61]), o($VO, [2, 62]), o($VO, [2, 63]), o($VO, [2, 64]), o($VO, [2, 65]), o($VO, [2, 66]), o($VO, [2, 67]), o($VO, [2, 68]), o($VO, [2, 69]), o($VO, [2, 70]), { 31: 134, 42: [1, 135] }, { 12: [1, 136] }, { 33: [1, 137] }, o($VR, [2, 28]), o($VR, [2, 29]), o($VR, [2, 30]), o($VR, [2, 31]), o($VR, [2, 32]), o($VR, [2, 33]), o($VR, [2, 34]), { 1: [2, 9] }, { 1: [2, 10] }, { 1: [2, 11] }, { 1: [2, 12] }, o($VI, [2, 18]), o($VH, [2, 38]), o($VP, [2, 72]), o($VQ, [2, 74]), o($VO, [2, 24]), o($VO, [2, 35]), o($VS, [2, 25]), o($VS, [2, 26], { 12: [1, 138] }), o($VS, [2, 27])],\n defaultActions: { 2: [2, 1], 3: [2, 2], 4: [2, 7], 5: [2, 3], 6: [2, 4], 7: [2, 5], 8: [2, 6], 74: [2, 8], 126: [2, 9], 127: [2, 10], 128: [2, 11], 129: [2, 12] },\n parseError: /* @__PURE__ */ __name(function parseError(str, hash) {\n if (hash.recoverable) {\n this.trace(str);\n } else {\n var error = new Error(str);\n error.hash = hash;\n throw error;\n }\n }, \"parseError\"),\n parse: /* @__PURE__ */ __name(function parse(input) {\n var self = this, stack = [0], tstack = [], vstack = [null], lstack = [], table = this.table, yytext = \"\", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;\n var args = lstack.slice.call(arguments, 1);\n var lexer2 = Object.create(this.lexer);\n var sharedState = { yy: {} };\n for (var k in this.yy) {\n if (Object.prototype.hasOwnProperty.call(this.yy, k)) {\n sharedState.yy[k] = this.yy[k];\n }\n }\n lexer2.setInput(input, sharedState.yy);\n sharedState.yy.lexer = lexer2;\n sharedState.yy.parser = this;\n if (typeof lexer2.yylloc == \"undefined\") {\n lexer2.yylloc = {};\n }\n var yyloc = lexer2.yylloc;\n lstack.push(yyloc);\n var ranges = lexer2.options && lexer2.options.ranges;\n if (typeof sharedState.yy.parseError === \"function\") {\n this.parseError = sharedState.yy.parseError;\n } else {\n this.parseError = Object.getPrototypeOf(this).parseError;\n }\n function popStack(n) {\n stack.length = stack.length - 2 * n;\n vstack.length = vstack.length - n;\n lstack.length = lstack.length - n;\n }\n __name(popStack, \"popStack\");\n function lex() {\n var token;\n token = tstack.pop() || lexer2.lex() || EOF;\n if (typeof token !== \"number\") {\n if (token instanceof Array) {\n tstack = token;\n token = tstack.pop();\n }\n token = self.symbols_[token] || token;\n }\n return token;\n }\n __name(lex, \"lex\");\n var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;\n while (true) {\n state = stack[stack.length - 1];\n if (this.defaultActions[state]) {\n action = this.defaultActions[state];\n } else {\n if (symbol === null || typeof symbol == \"undefined\") {\n symbol = lex();\n }\n action = table[state] && table[state][symbol];\n }\n if (typeof action === \"undefined\" || !action.length || !action[0]) {\n var errStr = \"\";\n expected = [];\n for (p in table[state]) {\n if (this.terminals_[p] && p > TERROR) {\n expected.push(\"'\" + this.terminals_[p] + \"'\");\n }\n }\n if (lexer2.showPosition) {\n errStr = \"Parse error on line \" + (yylineno + 1) + \":\\n\" + lexer2.showPosition() + \"\\nExpecting \" + expected.join(\", \") + \", got '\" + (this.terminals_[symbol] || symbol) + \"'\";\n } else {\n errStr = \"Parse error on line \" + (yylineno + 1) + \": Unexpected \" + (symbol == EOF ? \"end of input\" : \"'\" + (this.terminals_[symbol] || symbol) + \"'\");\n }\n this.parseError(errStr, {\n text: lexer2.match,\n token: this.terminals_[symbol] || symbol,\n line: lexer2.yylineno,\n loc: yyloc,\n expected\n });\n }\n if (action[0] instanceof Array && action.length > 1) {\n throw new Error(\"Parse Error: multiple actions possible at state: \" + state + \", token: \" + symbol);\n }\n switch (action[0]) {\n case 1:\n stack.push(symbol);\n vstack.push(lexer2.yytext);\n lstack.push(lexer2.yylloc);\n stack.push(action[1]);\n symbol = null;\n if (!preErrorSymbol) {\n yyleng = lexer2.yyleng;\n yytext = lexer2.yytext;\n yylineno = lexer2.yylineno;\n yyloc = lexer2.yylloc;\n if (recovering > 0) {\n recovering--;\n }\n } else {\n symbol = preErrorSymbol;\n preErrorSymbol = null;\n }\n break;\n case 2:\n len = this.productions_[action[1]][1];\n yyval.$ = vstack[vstack.length - len];\n yyval._$ = {\n first_line: lstack[lstack.length - (len || 1)].first_line,\n last_line: lstack[lstack.length - 1].last_line,\n first_column: lstack[lstack.length - (len || 1)].first_column,\n last_column: lstack[lstack.length - 1].last_column\n };\n if (ranges) {\n yyval._$.range = [\n lstack[lstack.length - (len || 1)].range[0],\n lstack[lstack.length - 1].range[1]\n ];\n }\n r = this.performAction.apply(yyval, [\n yytext,\n yyleng,\n yylineno,\n sharedState.yy,\n action[1],\n vstack,\n lstack\n ].concat(args));\n if (typeof r !== \"undefined\") {\n return r;\n }\n if (len) {\n stack = stack.slice(0, -1 * len * 2);\n vstack = vstack.slice(0, -1 * len);\n lstack = lstack.slice(0, -1 * len);\n }\n stack.push(this.productions_[action[1]][0]);\n vstack.push(yyval.$);\n lstack.push(yyval._$);\n newState = table[stack[stack.length - 2]][stack[stack.length - 1]];\n stack.push(newState);\n break;\n case 3:\n return true;\n }\n }\n return true;\n }, \"parse\")\n };\n var lexer = /* @__PURE__ */ (function() {\n var lexer2 = {\n EOF: 1,\n parseError: /* @__PURE__ */ __name(function parseError(str, hash) {\n if (this.yy.parser) {\n this.yy.parser.parseError(str, hash);\n } else {\n throw new Error(str);\n }\n }, \"parseError\"),\n // resets the lexer, sets new input\n setInput: /* @__PURE__ */ __name(function(input, yy) {\n this.yy = yy || this.yy || {};\n this._input = input;\n this._more = this._backtrack = this.done = false;\n this.yylineno = this.yyleng = 0;\n this.yytext = this.matched = this.match = \"\";\n this.conditionStack = [\"INITIAL\"];\n this.yylloc = {\n first_line: 1,\n first_column: 0,\n last_line: 1,\n last_column: 0\n };\n if (this.options.ranges) {\n this.yylloc.range = [0, 0];\n }\n this.offset = 0;\n return this;\n }, \"setInput\"),\n // consumes and returns one char from the input\n input: /* @__PURE__ */ __name(function() {\n var ch = this._input[0];\n this.yytext += ch;\n this.yyleng++;\n this.offset++;\n this.match += ch;\n this.matched += ch;\n var lines = ch.match(/(?:\\r\\n?|\\n).*/g);\n if (lines) {\n this.yylineno++;\n this.yylloc.last_line++;\n } else {\n this.yylloc.last_column++;\n }\n if (this.options.ranges) {\n this.yylloc.range[1]++;\n }\n this._input = this._input.slice(1);\n return ch;\n }, \"input\"),\n // unshifts one char (or a string) into the input\n unput: /* @__PURE__ */ __name(function(ch) {\n var len = ch.length;\n var lines = ch.split(/(?:\\r\\n?|\\n)/g);\n this._input = ch + this._input;\n this.yytext = this.yytext.substr(0, this.yytext.length - len);\n this.offset -= len;\n var oldLines = this.match.split(/(?:\\r\\n?|\\n)/g);\n this.match = this.match.substr(0, this.match.length - 1);\n this.matched = this.matched.substr(0, this.matched.length - 1);\n if (lines.length - 1) {\n this.yylineno -= lines.length - 1;\n }\n var r = this.yylloc.range;\n this.yylloc = {\n first_line: this.yylloc.first_line,\n last_line: this.yylineno + 1,\n first_column: this.yylloc.first_column,\n last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len\n };\n if (this.options.ranges) {\n this.yylloc.range = [r[0], r[0] + this.yyleng - len];\n }\n this.yyleng = this.yytext.length;\n return this;\n }, \"unput\"),\n // When called from action, caches matched text and appends it on next action\n more: /* @__PURE__ */ __name(function() {\n this._more = true;\n return this;\n }, \"more\"),\n // When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead.\n reject: /* @__PURE__ */ __name(function() {\n if (this.options.backtrack_lexer) {\n this._backtrack = true;\n } else {\n return this.parseError(\"Lexical error on line \" + (this.yylineno + 1) + \". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\\n\" + this.showPosition(), {\n text: \"\",\n token: null,\n line: this.yylineno\n });\n }\n return this;\n }, \"reject\"),\n // retain first n characters of the match\n less: /* @__PURE__ */ __name(function(n) {\n this.unput(this.match.slice(n));\n }, \"less\"),\n // displays already matched input, i.e. for error messages\n pastInput: /* @__PURE__ */ __name(function() {\n var past = this.matched.substr(0, this.matched.length - this.match.length);\n return (past.length > 20 ? \"...\" : \"\") + past.substr(-20).replace(/\\n/g, \"\");\n }, \"pastInput\"),\n // displays upcoming input, i.e. for error messages\n upcomingInput: /* @__PURE__ */ __name(function() {\n var next = this.match;\n if (next.length < 20) {\n next += this._input.substr(0, 20 - next.length);\n }\n return (next.substr(0, 20) + (next.length > 20 ? \"...\" : \"\")).replace(/\\n/g, \"\");\n }, \"upcomingInput\"),\n // displays the character position where the lexing error occurred, i.e. for error messages\n showPosition: /* @__PURE__ */ __name(function() {\n var pre = this.pastInput();\n var c2 = new Array(pre.length + 1).join(\"-\");\n return pre + this.upcomingInput() + \"\\n\" + c2 + \"^\";\n }, \"showPosition\"),\n // test the lexed token: return FALSE when not a match, otherwise return token\n test_match: /* @__PURE__ */ __name(function(match, indexed_rule) {\n var token, lines, backup;\n if (this.options.backtrack_lexer) {\n backup = {\n yylineno: this.yylineno,\n yylloc: {\n first_line: this.yylloc.first_line,\n last_line: this.last_line,\n first_column: this.yylloc.first_column,\n last_column: this.yylloc.last_column\n },\n yytext: this.yytext,\n match: this.match,\n matches: this.matches,\n matched: this.matched,\n yyleng: this.yyleng,\n offset: this.offset,\n _more: this._more,\n _input: this._input,\n yy: this.yy,\n conditionStack: this.conditionStack.slice(0),\n done: this.done\n };\n if (this.options.ranges) {\n backup.yylloc.range = this.yylloc.range.slice(0);\n }\n }\n lines = match[0].match(/(?:\\r\\n?|\\n).*/g);\n if (lines) {\n this.yylineno += lines.length;\n }\n this.yylloc = {\n first_line: this.yylloc.last_line,\n last_line: this.yylineno + 1,\n first_column: this.yylloc.last_column,\n last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\\r?\\n?/)[0].length : this.yylloc.last_column + match[0].length\n };\n this.yytext += match[0];\n this.match += match[0];\n this.matches = match;\n this.yyleng = this.yytext.length;\n if (this.options.ranges) {\n this.yylloc.range = [this.offset, this.offset += this.yyleng];\n }\n this._more = false;\n this._backtrack = false;\n this._input = this._input.slice(match[0].length);\n this.matched += match[0];\n token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]);\n if (this.done && this._input) {\n this.done = false;\n }\n if (token) {\n return token;\n } else if (this._backtrack) {\n for (var k in backup) {\n this[k] = backup[k];\n }\n return false;\n }\n return false;\n }, \"test_match\"),\n // return next match in input\n next: /* @__PURE__ */ __name(function() {\n if (this.done) {\n return this.EOF;\n }\n if (!this._input) {\n this.done = true;\n }\n var token, match, tempMatch, index;\n if (!this._more) {\n this.yytext = \"\";\n this.match = \"\";\n }\n var rules = this._currentRules();\n for (var i = 0; i < rules.length; i++) {\n tempMatch = this._input.match(this.rules[rules[i]]);\n if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {\n match = tempMatch;\n index = i;\n if (this.options.backtrack_lexer) {\n token = this.test_match(tempMatch, rules[i]);\n if (token !== false) {\n return token;\n } else if (this._backtrack) {\n match = false;\n continue;\n } else {\n return false;\n }\n } else if (!this.options.flex) {\n break;\n }\n }\n }\n if (match) {\n token = this.test_match(match, rules[index]);\n if (token !== false) {\n return token;\n }\n return false;\n }\n if (this._input === \"\") {\n return this.EOF;\n } else {\n return this.parseError(\"Lexical error on line \" + (this.yylineno + 1) + \". Unrecognized text.\\n\" + this.showPosition(), {\n text: \"\",\n token: null,\n line: this.yylineno\n });\n }\n }, \"next\"),\n // return next match that has a token\n lex: /* @__PURE__ */ __name(function lex() {\n var r = this.next();\n if (r) {\n return r;\n } else {\n return this.lex();\n }\n }, \"lex\"),\n // activates a new lexer condition state (pushes the new lexer condition state onto the condition stack)\n begin: /* @__PURE__ */ __name(function begin(condition) {\n this.conditionStack.push(condition);\n }, \"begin\"),\n // pop the previously active lexer condition state off the condition stack\n popState: /* @__PURE__ */ __name(function popState() {\n var n = this.conditionStack.length - 1;\n if (n > 0) {\n return this.conditionStack.pop();\n } else {\n return this.conditionStack[0];\n }\n }, \"popState\"),\n // produce the lexer rule set which is active for the currently active lexer condition state\n _currentRules: /* @__PURE__ */ __name(function _currentRules() {\n if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) {\n return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;\n } else {\n return this.conditions[\"INITIAL\"].rules;\n }\n }, \"_currentRules\"),\n // return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available\n topState: /* @__PURE__ */ __name(function topState(n) {\n n = this.conditionStack.length - 1 - Math.abs(n || 0);\n if (n >= 0) {\n return this.conditionStack[n];\n } else {\n return \"INITIAL\";\n }\n }, \"topState\"),\n // alias for begin(condition)\n pushState: /* @__PURE__ */ __name(function pushState(condition) {\n this.begin(condition);\n }, \"pushState\"),\n // return the number of states currently on the stack\n stateStackSize: /* @__PURE__ */ __name(function stateStackSize() {\n return this.conditionStack.length;\n }, \"stateStackSize\"),\n options: {},\n performAction: /* @__PURE__ */ __name(function anonymous(yy, yy_, $avoiding_name_collisions, YY_START) {\n var YYSTATE = YY_START;\n switch ($avoiding_name_collisions) {\n case 0:\n return 6;\n break;\n case 1:\n return 7;\n break;\n case 2:\n return 8;\n break;\n case 3:\n return 9;\n break;\n case 4:\n return 22;\n break;\n case 5:\n return 23;\n break;\n case 6:\n this.begin(\"acc_title\");\n return 24;\n break;\n case 7:\n this.popState();\n return \"acc_title_value\";\n break;\n case 8:\n this.begin(\"acc_descr\");\n return 26;\n break;\n case 9:\n this.popState();\n return \"acc_descr_value\";\n break;\n case 10:\n this.begin(\"acc_descr_multiline\");\n break;\n case 11:\n this.popState();\n break;\n case 12:\n return \"acc_descr_multiline_value\";\n break;\n case 13:\n break;\n case 14:\n c;\n break;\n case 15:\n return 12;\n break;\n case 16:\n break;\n case 17:\n return 11;\n break;\n case 18:\n return 15;\n break;\n case 19:\n return 16;\n break;\n case 20:\n return 17;\n break;\n case 21:\n return 18;\n break;\n case 22:\n this.begin(\"person_ext\");\n return 45;\n break;\n case 23:\n this.begin(\"person\");\n return 44;\n break;\n case 24:\n this.begin(\"system_ext_queue\");\n return 51;\n break;\n case 25:\n this.begin(\"system_ext_db\");\n return 50;\n break;\n case 26:\n this.begin(\"system_ext\");\n return 49;\n break;\n case 27:\n this.begin(\"system_queue\");\n return 48;\n break;\n case 28:\n this.begin(\"system_db\");\n return 47;\n break;\n case 29:\n this.begin(\"system\");\n return 46;\n break;\n case 30:\n this.begin(\"boundary\");\n return 37;\n break;\n case 31:\n this.begin(\"enterprise_boundary\");\n return 34;\n break;\n case 32:\n this.begin(\"system_boundary\");\n return 36;\n break;\n case 33:\n this.begin(\"container_ext_queue\");\n return 57;\n break;\n case 34:\n this.begin(\"container_ext_db\");\n return 56;\n break;\n case 35:\n this.begin(\"container_ext\");\n return 55;\n break;\n case 36:\n this.begin(\"container_queue\");\n return 54;\n break;\n case 37:\n this.begin(\"container_db\");\n return 53;\n break;\n case 38:\n this.begin(\"container\");\n return 52;\n break;\n case 39:\n this.begin(\"container_boundary\");\n return 38;\n break;\n case 40:\n this.begin(\"component_ext_queue\");\n return 63;\n break;\n case 41:\n this.begin(\"component_ext_db\");\n return 62;\n break;\n case 42:\n this.begin(\"component_ext\");\n return 61;\n break;\n case 43:\n this.begin(\"component_queue\");\n return 60;\n break;\n case 44:\n this.begin(\"component_db\");\n return 59;\n break;\n case 45:\n this.begin(\"component\");\n return 58;\n break;\n case 46:\n this.begin(\"node\");\n return 39;\n break;\n case 47:\n this.begin(\"node\");\n return 39;\n break;\n case 48:\n this.begin(\"node_l\");\n return 40;\n break;\n case 49:\n this.begin(\"node_r\");\n return 41;\n break;\n case 50:\n this.begin(\"rel\");\n return 64;\n break;\n case 51:\n this.begin(\"birel\");\n return 65;\n break;\n case 52:\n this.begin(\"rel_u\");\n return 66;\n break;\n case 53:\n this.begin(\"rel_u\");\n return 66;\n break;\n case 54:\n this.begin(\"rel_d\");\n return 67;\n break;\n case 55:\n this.begin(\"rel_d\");\n return 67;\n break;\n case 56:\n this.begin(\"rel_l\");\n return 68;\n break;\n case 57:\n this.begin(\"rel_l\");\n return 68;\n break;\n case 58:\n this.begin(\"rel_r\");\n return 69;\n break;\n case 59:\n this.begin(\"rel_r\");\n return 69;\n break;\n case 60:\n this.begin(\"rel_b\");\n return 70;\n break;\n case 61:\n this.begin(\"rel_index\");\n return 71;\n break;\n case 62:\n this.begin(\"update_el_style\");\n return 72;\n break;\n case 63:\n this.begin(\"update_rel_style\");\n return 73;\n break;\n case 64:\n this.begin(\"update_layout_config\");\n return 74;\n break;\n case 65:\n return \"EOF_IN_STRUCT\";\n break;\n case 66:\n this.begin(\"attribute\");\n return \"ATTRIBUTE_EMPTY\";\n break;\n case 67:\n this.begin(\"attribute\");\n break;\n case 68:\n this.popState();\n this.popState();\n break;\n case 69:\n return 80;\n break;\n case 70:\n break;\n case 71:\n return 80;\n break;\n case 72:\n this.begin(\"string\");\n break;\n case 73:\n this.popState();\n break;\n case 74:\n return \"STR\";\n break;\n case 75:\n this.begin(\"string_kv\");\n break;\n case 76:\n this.begin(\"string_kv_key\");\n return \"STR_KEY\";\n break;\n case 77:\n this.popState();\n this.begin(\"string_kv_value\");\n break;\n case 78:\n return \"STR_VALUE\";\n break;\n case 79:\n this.popState();\n this.popState();\n break;\n case 80:\n return \"STR\";\n break;\n case 81:\n return \"LBRACE\";\n break;\n case 82:\n return \"RBRACE\";\n break;\n case 83:\n return \"SPACE\";\n break;\n case 84:\n return \"EOL\";\n break;\n case 85:\n return 14;\n break;\n }\n }, \"anonymous\"),\n rules: [/^(?:.*direction\\s+TB[^\\n]*)/, /^(?:.*direction\\s+BT[^\\n]*)/, /^(?:.*direction\\s+RL[^\\n]*)/, /^(?:.*direction\\s+LR[^\\n]*)/, /^(?:title\\s[^#\\n;]+)/, /^(?:accDescription\\s[^#\\n;]+)/, /^(?:accTitle\\s*:\\s*)/, /^(?:(?!\\n||)*[^\\n]*)/, /^(?:accDescr\\s*:\\s*)/, /^(?:(?!\\n||)*[^\\n]*)/, /^(?:accDescr\\s*\\{\\s*)/, /^(?:[\\}])/, /^(?:[^\\}]*)/, /^(?:%%(?!\\{)*[^\\n]*(\\r?\\n?)+)/, /^(?:%%[^\\n]*(\\r?\\n)*)/, /^(?:\\s*(\\r?\\n)+)/, /^(?:\\s+)/, /^(?:C4Context\\b)/, /^(?:C4Container\\b)/, /^(?:C4Component\\b)/, /^(?:C4Dynamic\\b)/, /^(?:C4Deployment\\b)/, /^(?:Person_Ext\\b)/, /^(?:Person\\b)/, /^(?:SystemQueue_Ext\\b)/, /^(?:SystemDb_Ext\\b)/, /^(?:System_Ext\\b)/, /^(?:SystemQueue\\b)/, /^(?:SystemDb\\b)/, /^(?:System\\b)/, /^(?:Boundary\\b)/, /^(?:Enterprise_Boundary\\b)/, /^(?:System_Boundary\\b)/, /^(?:ContainerQueue_Ext\\b)/, /^(?:ContainerDb_Ext\\b)/, /^(?:Container_Ext\\b)/, /^(?:ContainerQueue\\b)/, /^(?:ContainerDb\\b)/, /^(?:Container\\b)/, /^(?:Container_Boundary\\b)/, /^(?:ComponentQueue_Ext\\b)/, /^(?:ComponentDb_Ext\\b)/, /^(?:Component_Ext\\b)/, /^(?:ComponentQueue\\b)/, /^(?:ComponentDb\\b)/, /^(?:Component\\b)/, /^(?:Deployment_Node\\b)/, /^(?:Node\\b)/, /^(?:Node_L\\b)/, /^(?:Node_R\\b)/, /^(?:Rel\\b)/, /^(?:BiRel\\b)/, /^(?:Rel_Up\\b)/, /^(?:Rel_U\\b)/, /^(?:Rel_Down\\b)/, /^(?:Rel_D\\b)/, /^(?:Rel_Left\\b)/, /^(?:Rel_L\\b)/, /^(?:Rel_Right\\b)/, /^(?:Rel_R\\b)/, /^(?:Rel_Back\\b)/, /^(?:RelIndex\\b)/, /^(?:UpdateElementStyle\\b)/, /^(?:UpdateRelStyle\\b)/, /^(?:UpdateLayoutConfig\\b)/, /^(?:$)/, /^(?:[(][ ]*[,])/, /^(?:[(])/, /^(?:[)])/, /^(?:,,)/, /^(?:,)/, /^(?:[ ]*[\"][\"])/, /^(?:[ ]*[\"])/, /^(?:[\"])/, /^(?:[^\"]*)/, /^(?:[ ]*[\\$])/, /^(?:[^=]*)/, /^(?:[=][ ]*[\"])/, /^(?:[^\"]+)/, /^(?:[\"])/, /^(?:[^,]+)/, /^(?:\\{)/, /^(?:\\})/, /^(?:[\\s]+)/, /^(?:[\\n\\r]+)/, /^(?:$)/],\n conditions: { \"acc_descr_multiline\": { \"rules\": [11, 12], \"inclusive\": false }, \"acc_descr\": { \"rules\": [9], \"inclusive\": false }, \"acc_title\": { \"rules\": [7], \"inclusive\": false }, \"string_kv_value\": { \"rules\": [78, 79], \"inclusive\": false }, \"string_kv_key\": { \"rules\": [77], \"inclusive\": false }, \"string_kv\": { \"rules\": [76], \"inclusive\": false }, \"string\": { \"rules\": [73, 74], \"inclusive\": false }, \"attribute\": { \"rules\": [68, 69, 70, 71, 72, 75, 80], \"inclusive\": false }, \"update_layout_config\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"update_rel_style\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"update_el_style\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"rel_b\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"rel_r\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"rel_l\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"rel_d\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"rel_u\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"rel_bi\": { \"rules\": [], \"inclusive\": false }, \"rel\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"node_r\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"node_l\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"node\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"index\": { \"rules\": [], \"inclusive\": false }, \"rel_index\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"component_ext_queue\": { \"rules\": [], \"inclusive\": false }, \"component_ext_db\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"component_ext\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"component_queue\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"component_db\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"component\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"container_boundary\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"container_ext_queue\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"container_ext_db\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"container_ext\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"container_queue\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"container_db\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"container\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"birel\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"system_boundary\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"enterprise_boundary\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"boundary\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"system_ext_queue\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"system_ext_db\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"system_ext\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"system_queue\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"system_db\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"system\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"person_ext\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"person\": { \"rules\": [65, 66, 67, 68], \"inclusive\": false }, \"INITIAL\": { \"rules\": [0, 1, 2, 3, 4, 5, 6, 8, 10, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 81, 82, 83, 84, 85], \"inclusive\": true } }\n };\n return lexer2;\n })();\n parser2.lexer = lexer;\n function Parser() {\n this.yy = {};\n }\n __name(Parser, \"Parser\");\n Parser.prototype = parser2;\n parser2.Parser = Parser;\n return new Parser();\n})();\nparser.parser = parser;\nvar c4Diagram_default = parser;\n\n// src/diagrams/c4/c4Db.js\nvar c4ShapeArray = [];\nvar boundaryParseStack = [\"\"];\nvar currentBoundaryParse = \"global\";\nvar parentBoundaryParse = \"\";\nvar boundaries = [\n {\n alias: \"global\",\n label: { text: \"global\" },\n type: { text: \"global\" },\n tags: null,\n link: null,\n parentBoundary: \"\"\n }\n];\nvar rels = [];\nvar title = \"\";\nvar wrapEnabled = false;\nvar c4ShapeInRow = 4;\nvar c4BoundaryInRow = 2;\nvar c4Type;\nvar getC4Type = /* @__PURE__ */ __name(function() {\n return c4Type;\n}, \"getC4Type\");\nvar setC4Type = /* @__PURE__ */ __name(function(c4TypeParam) {\n let sanitizedText = sanitizeText(c4TypeParam, getConfig());\n c4Type = sanitizedText;\n}, \"setC4Type\");\nvar addRel = /* @__PURE__ */ __name(function(type, from, to, label, techn, descr, sprite, tags, link) {\n if (type === void 0 || type === null || from === void 0 || from === null || to === void 0 || to === null || label === void 0 || label === null) {\n return;\n }\n let rel = {};\n const old = rels.find((rel2) => rel2.from === from && rel2.to === to);\n if (old) {\n rel = old;\n } else {\n rels.push(rel);\n }\n rel.type = type;\n rel.from = from;\n rel.to = to;\n rel.label = { text: label };\n if (techn === void 0 || techn === null) {\n rel.techn = { text: \"\" };\n } else {\n if (typeof techn === \"object\") {\n let [key, value] = Object.entries(techn)[0];\n rel[key] = { text: value };\n } else {\n rel.techn = { text: techn };\n }\n }\n if (descr === void 0 || descr === null) {\n rel.descr = { text: \"\" };\n } else {\n if (typeof descr === \"object\") {\n let [key, value] = Object.entries(descr)[0];\n rel[key] = { text: value };\n } else {\n rel.descr = { text: descr };\n }\n }\n if (typeof sprite === \"object\") {\n let [key, value] = Object.entries(sprite)[0];\n rel[key] = value;\n } else {\n rel.sprite = sprite;\n }\n if (typeof tags === \"object\") {\n let [key, value] = Object.entries(tags)[0];\n rel[key] = value;\n } else {\n rel.tags = tags;\n }\n if (typeof link === \"object\") {\n let [key, value] = Object.entries(link)[0];\n rel[key] = value;\n } else {\n rel.link = link;\n }\n rel.wrap = autoWrap();\n}, \"addRel\");\nvar addPersonOrSystem = /* @__PURE__ */ __name(function(typeC4Shape, alias, label, descr, sprite, tags, link) {\n if (alias === null || label === null) {\n return;\n }\n let personOrSystem = {};\n const old = c4ShapeArray.find((personOrSystem2) => personOrSystem2.alias === alias);\n if (old && alias === old.alias) {\n personOrSystem = old;\n } else {\n personOrSystem.alias = alias;\n c4ShapeArray.push(personOrSystem);\n }\n if (label === void 0 || label === null) {\n personOrSystem.label = { text: \"\" };\n } else {\n personOrSystem.label = { text: label };\n }\n if (descr === void 0 || descr === null) {\n personOrSystem.descr = { text: \"\" };\n } else {\n if (typeof descr === \"object\") {\n let [key, value] = Object.entries(descr)[0];\n personOrSystem[key] = { text: value };\n } else {\n personOrSystem.descr = { text: descr };\n }\n }\n if (typeof sprite === \"object\") {\n let [key, value] = Object.entries(sprite)[0];\n personOrSystem[key] = value;\n } else {\n personOrSystem.sprite = sprite;\n }\n if (typeof tags === \"object\") {\n let [key, value] = Object.entries(tags)[0];\n personOrSystem[key] = value;\n } else {\n personOrSystem.tags = tags;\n }\n if (typeof link === \"object\") {\n let [key, value] = Object.entries(link)[0];\n personOrSystem[key] = value;\n } else {\n personOrSystem.link = link;\n }\n personOrSystem.typeC4Shape = { text: typeC4Shape };\n personOrSystem.parentBoundary = currentBoundaryParse;\n personOrSystem.wrap = autoWrap();\n}, \"addPersonOrSystem\");\nvar addContainer = /* @__PURE__ */ __name(function(typeC4Shape, alias, label, techn, descr, sprite, tags, link) {\n if (alias === null || label === null) {\n return;\n }\n let container = {};\n const old = c4ShapeArray.find((container2) => container2.alias === alias);\n if (old && alias === old.alias) {\n container = old;\n } else {\n container.alias = alias;\n c4ShapeArray.push(container);\n }\n if (label === void 0 || label === null) {\n container.label = { text: \"\" };\n } else {\n container.label = { text: label };\n }\n if (techn === void 0 || techn === null) {\n container.techn = { text: \"\" };\n } else {\n if (typeof techn === \"object\") {\n let [key, value] = Object.entries(techn)[0];\n container[key] = { text: value };\n } else {\n container.techn = { text: techn };\n }\n }\n if (descr === void 0 || descr === null) {\n container.descr = { text: \"\" };\n } else {\n if (typeof descr === \"object\") {\n let [key, value] = Object.entries(descr)[0];\n container[key] = { text: value };\n } else {\n container.descr = { text: descr };\n }\n }\n if (typeof sprite === \"object\") {\n let [key, value] = Object.entries(sprite)[0];\n container[key] = value;\n } else {\n container.sprite = sprite;\n }\n if (typeof tags === \"object\") {\n let [key, value] = Object.entries(tags)[0];\n container[key] = value;\n } else {\n container.tags = tags;\n }\n if (typeof link === \"object\") {\n let [key, value] = Object.entries(link)[0];\n container[key] = value;\n } else {\n container.link = link;\n }\n container.wrap = autoWrap();\n container.typeC4Shape = { text: typeC4Shape };\n container.parentBoundary = currentBoundaryParse;\n}, \"addContainer\");\nvar addComponent = /* @__PURE__ */ __name(function(typeC4Shape, alias, label, techn, descr, sprite, tags, link) {\n if (alias === null || label === null) {\n return;\n }\n let component = {};\n const old = c4ShapeArray.find((component2) => component2.alias === alias);\n if (old && alias === old.alias) {\n component = old;\n } else {\n component.alias = alias;\n c4ShapeArray.push(component);\n }\n if (label === void 0 || label === null) {\n component.label = { text: \"\" };\n } else {\n component.label = { text: label };\n }\n if (techn === void 0 || techn === null) {\n component.techn = { text: \"\" };\n } else {\n if (typeof techn === \"object\") {\n let [key, value] = Object.entries(techn)[0];\n component[key] = { text: value };\n } else {\n component.techn = { text: techn };\n }\n }\n if (descr === void 0 || descr === null) {\n component.descr = { text: \"\" };\n } else {\n if (typeof descr === \"object\") {\n let [key, value] = Object.entries(descr)[0];\n component[key] = { text: value };\n } else {\n component.descr = { text: descr };\n }\n }\n if (typeof sprite === \"object\") {\n let [key, value] = Object.entries(sprite)[0];\n component[key] = value;\n } else {\n component.sprite = sprite;\n }\n if (typeof tags === \"object\") {\n let [key, value] = Object.entries(tags)[0];\n component[key] = value;\n } else {\n component.tags = tags;\n }\n if (typeof link === \"object\") {\n let [key, value] = Object.entries(link)[0];\n component[key] = value;\n } else {\n component.link = link;\n }\n component.wrap = autoWrap();\n component.typeC4Shape = { text: typeC4Shape };\n component.parentBoundary = currentBoundaryParse;\n}, \"addComponent\");\nvar addPersonOrSystemBoundary = /* @__PURE__ */ __name(function(alias, label, type, tags, link) {\n if (alias === null || label === null) {\n return;\n }\n let boundary = {};\n const old = boundaries.find((boundary2) => boundary2.alias === alias);\n if (old && alias === old.alias) {\n boundary = old;\n } else {\n boundary.alias = alias;\n boundaries.push(boundary);\n }\n if (label === void 0 || label === null) {\n boundary.label = { text: \"\" };\n } else {\n boundary.label = { text: label };\n }\n if (type === void 0 || type === null) {\n boundary.type = { text: \"system\" };\n } else {\n if (typeof type === \"object\") {\n let [key, value] = Object.entries(type)[0];\n boundary[key] = { text: value };\n } else {\n boundary.type = { text: type };\n }\n }\n if (typeof tags === \"object\") {\n let [key, value] = Object.entries(tags)[0];\n boundary[key] = value;\n } else {\n boundary.tags = tags;\n }\n if (typeof link === \"object\") {\n let [key, value] = Object.entries(link)[0];\n boundary[key] = value;\n } else {\n boundary.link = link;\n }\n boundary.parentBoundary = currentBoundaryParse;\n boundary.wrap = autoWrap();\n parentBoundaryParse = currentBoundaryParse;\n currentBoundaryParse = alias;\n boundaryParseStack.push(parentBoundaryParse);\n}, \"addPersonOrSystemBoundary\");\nvar addContainerBoundary = /* @__PURE__ */ __name(function(alias, label, type, tags, link) {\n if (alias === null || label === null) {\n return;\n }\n let boundary = {};\n const old = boundaries.find((boundary2) => boundary2.alias === alias);\n if (old && alias === old.alias) {\n boundary = old;\n } else {\n boundary.alias = alias;\n boundaries.push(boundary);\n }\n if (label === void 0 || label === null) {\n boundary.label = { text: \"\" };\n } else {\n boundary.label = { text: label };\n }\n if (type === void 0 || type === null) {\n boundary.type = { text: \"container\" };\n } else {\n if (typeof type === \"object\") {\n let [key, value] = Object.entries(type)[0];\n boundary[key] = { text: value };\n } else {\n boundary.type = { text: type };\n }\n }\n if (typeof tags === \"object\") {\n let [key, value] = Object.entries(tags)[0];\n boundary[key] = value;\n } else {\n boundary.tags = tags;\n }\n if (typeof link === \"object\") {\n let [key, value] = Object.entries(link)[0];\n boundary[key] = value;\n } else {\n boundary.link = link;\n }\n boundary.parentBoundary = currentBoundaryParse;\n boundary.wrap = autoWrap();\n parentBoundaryParse = currentBoundaryParse;\n currentBoundaryParse = alias;\n boundaryParseStack.push(parentBoundaryParse);\n}, \"addContainerBoundary\");\nvar addDeploymentNode = /* @__PURE__ */ __name(function(nodeType, alias, label, type, descr, sprite, tags, link) {\n if (alias === null || label === null) {\n return;\n }\n let boundary = {};\n const old = boundaries.find((boundary2) => boundary2.alias === alias);\n if (old && alias === old.alias) {\n boundary = old;\n } else {\n boundary.alias = alias;\n boundaries.push(boundary);\n }\n if (label === void 0 || label === null) {\n boundary.label = { text: \"\" };\n } else {\n boundary.label = { text: label };\n }\n if (type === void 0 || type === null) {\n boundary.type = { text: \"node\" };\n } else {\n if (typeof type === \"object\") {\n let [key, value] = Object.entries(type)[0];\n boundary[key] = { text: value };\n } else {\n boundary.type = { text: type };\n }\n }\n if (descr === void 0 || descr === null) {\n boundary.descr = { text: \"\" };\n } else {\n if (typeof descr === \"object\") {\n let [key, value] = Object.entries(descr)[0];\n boundary[key] = { text: value };\n } else {\n boundary.descr = { text: descr };\n }\n }\n if (typeof tags === \"object\") {\n let [key, value] = Object.entries(tags)[0];\n boundary[key] = value;\n } else {\n boundary.tags = tags;\n }\n if (typeof link === \"object\") {\n let [key, value] = Object.entries(link)[0];\n boundary[key] = value;\n } else {\n boundary.link = link;\n }\n boundary.nodeType = nodeType;\n boundary.parentBoundary = currentBoundaryParse;\n boundary.wrap = autoWrap();\n parentBoundaryParse = currentBoundaryParse;\n currentBoundaryParse = alias;\n boundaryParseStack.push(parentBoundaryParse);\n}, \"addDeploymentNode\");\nvar popBoundaryParseStack = /* @__PURE__ */ __name(function() {\n currentBoundaryParse = parentBoundaryParse;\n boundaryParseStack.pop();\n parentBoundaryParse = boundaryParseStack.pop();\n boundaryParseStack.push(parentBoundaryParse);\n}, \"popBoundaryParseStack\");\nvar updateElStyle = /* @__PURE__ */ __name(function(typeC4Shape, elementName, bgColor, fontColor, borderColor, shadowing, shape, sprite, techn, legendText, legendSprite) {\n let old = c4ShapeArray.find((element) => element.alias === elementName);\n if (old === void 0) {\n old = boundaries.find((element) => element.alias === elementName);\n if (old === void 0) {\n return;\n }\n }\n if (bgColor !== void 0 && bgColor !== null) {\n if (typeof bgColor === \"object\") {\n let [key, value] = Object.entries(bgColor)[0];\n old[key] = value;\n } else {\n old.bgColor = bgColor;\n }\n }\n if (fontColor !== void 0 && fontColor !== null) {\n if (typeof fontColor === \"object\") {\n let [key, value] = Object.entries(fontColor)[0];\n old[key] = value;\n } else {\n old.fontColor = fontColor;\n }\n }\n if (borderColor !== void 0 && borderColor !== null) {\n if (typeof borderColor === \"object\") {\n let [key, value] = Object.entries(borderColor)[0];\n old[key] = value;\n } else {\n old.borderColor = borderColor;\n }\n }\n if (shadowing !== void 0 && shadowing !== null) {\n if (typeof shadowing === \"object\") {\n let [key, value] = Object.entries(shadowing)[0];\n old[key] = value;\n } else {\n old.shadowing = shadowing;\n }\n }\n if (shape !== void 0 && shape !== null) {\n if (typeof shape === \"object\") {\n let [key, value] = Object.entries(shape)[0];\n old[key] = value;\n } else {\n old.shape = shape;\n }\n }\n if (sprite !== void 0 && sprite !== null) {\n if (typeof sprite === \"object\") {\n let [key, value] = Object.entries(sprite)[0];\n old[key] = value;\n } else {\n old.sprite = sprite;\n }\n }\n if (techn !== void 0 && techn !== null) {\n if (typeof techn === \"object\") {\n let [key, value] = Object.entries(techn)[0];\n old[key] = value;\n } else {\n old.techn = techn;\n }\n }\n if (legendText !== void 0 && legendText !== null) {\n if (typeof legendText === \"object\") {\n let [key, value] = Object.entries(legendText)[0];\n old[key] = value;\n } else {\n old.legendText = legendText;\n }\n }\n if (legendSprite !== void 0 && legendSprite !== null) {\n if (typeof legendSprite === \"object\") {\n let [key, value] = Object.entries(legendSprite)[0];\n old[key] = value;\n } else {\n old.legendSprite = legendSprite;\n }\n }\n}, \"updateElStyle\");\nvar updateRelStyle = /* @__PURE__ */ __name(function(typeC4Shape, from, to, textColor, lineColor, offsetX, offsetY) {\n const old = rels.find((rel) => rel.from === from && rel.to === to);\n if (old === void 0) {\n return;\n }\n if (textColor !== void 0 && textColor !== null) {\n if (typeof textColor === \"object\") {\n let [key, value] = Object.entries(textColor)[0];\n old[key] = value;\n } else {\n old.textColor = textColor;\n }\n }\n if (lineColor !== void 0 && lineColor !== null) {\n if (typeof lineColor === \"object\") {\n let [key, value] = Object.entries(lineColor)[0];\n old[key] = value;\n } else {\n old.lineColor = lineColor;\n }\n }\n if (offsetX !== void 0 && offsetX !== null) {\n if (typeof offsetX === \"object\") {\n let [key, value] = Object.entries(offsetX)[0];\n old[key] = parseInt(value);\n } else {\n old.offsetX = parseInt(offsetX);\n }\n }\n if (offsetY !== void 0 && offsetY !== null) {\n if (typeof offsetY === \"object\") {\n let [key, value] = Object.entries(offsetY)[0];\n old[key] = parseInt(value);\n } else {\n old.offsetY = parseInt(offsetY);\n }\n }\n}, \"updateRelStyle\");\nvar updateLayoutConfig = /* @__PURE__ */ __name(function(typeC4Shape, c4ShapeInRowParam, c4BoundaryInRowParam) {\n let c4ShapeInRowValue = c4ShapeInRow;\n let c4BoundaryInRowValue = c4BoundaryInRow;\n if (typeof c4ShapeInRowParam === \"object\") {\n const value = Object.values(c4ShapeInRowParam)[0];\n c4ShapeInRowValue = parseInt(value);\n } else {\n c4ShapeInRowValue = parseInt(c4ShapeInRowParam);\n }\n if (typeof c4BoundaryInRowParam === \"object\") {\n const value = Object.values(c4BoundaryInRowParam)[0];\n c4BoundaryInRowValue = parseInt(value);\n } else {\n c4BoundaryInRowValue = parseInt(c4BoundaryInRowParam);\n }\n if (c4ShapeInRowValue >= 1) {\n c4ShapeInRow = c4ShapeInRowValue;\n }\n if (c4BoundaryInRowValue >= 1) {\n c4BoundaryInRow = c4BoundaryInRowValue;\n }\n}, \"updateLayoutConfig\");\nvar getC4ShapeInRow = /* @__PURE__ */ __name(function() {\n return c4ShapeInRow;\n}, \"getC4ShapeInRow\");\nvar getC4BoundaryInRow = /* @__PURE__ */ __name(function() {\n return c4BoundaryInRow;\n}, \"getC4BoundaryInRow\");\nvar getCurrentBoundaryParse = /* @__PURE__ */ __name(function() {\n return currentBoundaryParse;\n}, \"getCurrentBoundaryParse\");\nvar getParentBoundaryParse = /* @__PURE__ */ __name(function() {\n return parentBoundaryParse;\n}, \"getParentBoundaryParse\");\nvar getC4ShapeArray = /* @__PURE__ */ __name(function(parentBoundary) {\n if (parentBoundary === void 0 || parentBoundary === null) {\n return c4ShapeArray;\n } else {\n return c4ShapeArray.filter((personOrSystem) => {\n return personOrSystem.parentBoundary === parentBoundary;\n });\n }\n}, \"getC4ShapeArray\");\nvar getC4Shape = /* @__PURE__ */ __name(function(alias) {\n return c4ShapeArray.find((personOrSystem) => personOrSystem.alias === alias);\n}, \"getC4Shape\");\nvar getC4ShapeKeys = /* @__PURE__ */ __name(function(parentBoundary) {\n return Object.keys(getC4ShapeArray(parentBoundary));\n}, \"getC4ShapeKeys\");\nvar getBoundaries = /* @__PURE__ */ __name(function(parentBoundary) {\n if (parentBoundary === void 0 || parentBoundary === null) {\n return boundaries;\n } else {\n return boundaries.filter((boundary) => boundary.parentBoundary === parentBoundary);\n }\n}, \"getBoundaries\");\nvar getBoundarys = getBoundaries;\nvar getRels = /* @__PURE__ */ __name(function() {\n return rels;\n}, \"getRels\");\nvar getTitle = /* @__PURE__ */ __name(function() {\n return title;\n}, \"getTitle\");\nvar setWrap = /* @__PURE__ */ __name(function(wrapSetting) {\n wrapEnabled = wrapSetting;\n}, \"setWrap\");\nvar autoWrap = /* @__PURE__ */ __name(function() {\n return wrapEnabled;\n}, \"autoWrap\");\nvar clear = /* @__PURE__ */ __name(function() {\n c4ShapeArray = [];\n boundaries = [\n {\n alias: \"global\",\n label: { text: \"global\" },\n type: { text: \"global\" },\n tags: null,\n link: null,\n parentBoundary: \"\"\n }\n ];\n parentBoundaryParse = \"\";\n currentBoundaryParse = \"global\";\n boundaryParseStack = [\"\"];\n rels = [];\n boundaryParseStack = [\"\"];\n title = \"\";\n wrapEnabled = false;\n c4ShapeInRow = 4;\n c4BoundaryInRow = 2;\n}, \"clear\");\nvar LINETYPE = {\n SOLID: 0,\n DOTTED: 1,\n NOTE: 2,\n SOLID_CROSS: 3,\n DOTTED_CROSS: 4,\n SOLID_OPEN: 5,\n DOTTED_OPEN: 6,\n LOOP_START: 10,\n LOOP_END: 11,\n ALT_START: 12,\n ALT_ELSE: 13,\n ALT_END: 14,\n OPT_START: 15,\n OPT_END: 16,\n ACTIVE_START: 17,\n ACTIVE_END: 18,\n PAR_START: 19,\n PAR_AND: 20,\n PAR_END: 21,\n RECT_START: 22,\n RECT_END: 23,\n SOLID_POINT: 24,\n DOTTED_POINT: 25\n};\nvar ARROWTYPE = {\n FILLED: 0,\n OPEN: 1\n};\nvar PLACEMENT = {\n LEFTOF: 0,\n RIGHTOF: 1,\n OVER: 2\n};\nvar setTitle = /* @__PURE__ */ __name(function(txt) {\n let sanitizedText = sanitizeText(txt, getConfig());\n title = sanitizedText;\n}, \"setTitle\");\nvar c4Db_default = {\n addPersonOrSystem,\n addPersonOrSystemBoundary,\n addContainer,\n addContainerBoundary,\n addComponent,\n addDeploymentNode,\n popBoundaryParseStack,\n addRel,\n updateElStyle,\n updateRelStyle,\n updateLayoutConfig,\n autoWrap,\n setWrap,\n getC4ShapeArray,\n getC4Shape,\n getC4ShapeKeys,\n getBoundaries,\n getBoundarys,\n getCurrentBoundaryParse,\n getParentBoundaryParse,\n getRels,\n getTitle,\n getC4Type,\n getC4ShapeInRow,\n getC4BoundaryInRow,\n setAccTitle,\n getAccTitle,\n getAccDescription,\n setAccDescription,\n getConfig: /* @__PURE__ */ __name(() => getConfig().c4, \"getConfig\"),\n clear,\n LINETYPE,\n ARROWTYPE,\n PLACEMENT,\n setTitle,\n setC4Type\n // apply,\n};\n\n// src/diagrams/c4/c4Renderer.js\nimport { select } from \"d3\";\n\n// src/diagrams/c4/svgDraw.js\nimport { sanitizeUrl } from \"@braintree/sanitize-url\";\nvar drawRect2 = /* @__PURE__ */ __name(function(elem, rectData) {\n return drawRect(elem, rectData);\n}, \"drawRect\");\nvar drawImage = /* @__PURE__ */ __name(function(elem, width, height, x, y, link) {\n const imageElem = elem.append(\"image\");\n imageElem.attr(\"width\", width);\n imageElem.attr(\"height\", height);\n imageElem.attr(\"x\", x);\n imageElem.attr(\"y\", y);\n let sanitizedLink = link.startsWith(\"data:image/png;base64\") ? link : sanitizeUrl(link);\n imageElem.attr(\"xlink:href\", sanitizedLink);\n}, \"drawImage\");\nvar drawRels = /* @__PURE__ */ __name((elem, rels2, conf2) => {\n const relsElem = elem.append(\"g\");\n let i = 0;\n for (let rel of rels2) {\n let textColor = rel.textColor ? rel.textColor : \"#444444\";\n let strokeColor = rel.lineColor ? rel.lineColor : \"#444444\";\n let offsetX = rel.offsetX ? parseInt(rel.offsetX) : 0;\n let offsetY = rel.offsetY ? parseInt(rel.offsetY) : 0;\n let url = \"\";\n if (i === 0) {\n let line = relsElem.append(\"line\");\n line.attr(\"x1\", rel.startPoint.x);\n line.attr(\"y1\", rel.startPoint.y);\n line.attr(\"x2\", rel.endPoint.x);\n line.attr(\"y2\", rel.endPoint.y);\n line.attr(\"stroke-width\", \"1\");\n line.attr(\"stroke\", strokeColor);\n line.style(\"fill\", \"none\");\n if (rel.type !== \"rel_b\") {\n line.attr(\"marker-end\", \"url(\" + url + \"#arrowhead)\");\n }\n if (rel.type === \"birel\" || rel.type === \"rel_b\") {\n line.attr(\"marker-start\", \"url(\" + url + \"#arrowend)\");\n }\n i = -1;\n } else {\n let line = relsElem.append(\"path\");\n line.attr(\"fill\", \"none\").attr(\"stroke-width\", \"1\").attr(\"stroke\", strokeColor).attr(\n \"d\",\n \"Mstartx,starty Qcontrolx,controly stopx,stopy \".replaceAll(\"startx\", rel.startPoint.x).replaceAll(\"starty\", rel.startPoint.y).replaceAll(\n \"controlx\",\n rel.startPoint.x + (rel.endPoint.x - rel.startPoint.x) / 2 - (rel.endPoint.x - rel.startPoint.x) / 4\n ).replaceAll(\"controly\", rel.startPoint.y + (rel.endPoint.y - rel.startPoint.y) / 2).replaceAll(\"stopx\", rel.endPoint.x).replaceAll(\"stopy\", rel.endPoint.y)\n );\n if (rel.type !== \"rel_b\") {\n line.attr(\"marker-end\", \"url(\" + url + \"#arrowhead)\");\n }\n if (rel.type === \"birel\" || rel.type === \"rel_b\") {\n line.attr(\"marker-start\", \"url(\" + url + \"#arrowend)\");\n }\n }\n let messageConf = conf2.messageFont();\n _drawTextCandidateFunc(conf2)(\n rel.label.text,\n relsElem,\n Math.min(rel.startPoint.x, rel.endPoint.x) + Math.abs(rel.endPoint.x - rel.startPoint.x) / 2 + offsetX,\n Math.min(rel.startPoint.y, rel.endPoint.y) + Math.abs(rel.endPoint.y - rel.startPoint.y) / 2 + offsetY,\n rel.label.width,\n rel.label.height,\n { fill: textColor },\n messageConf\n );\n if (rel.techn && rel.techn.text !== \"\") {\n messageConf = conf2.messageFont();\n _drawTextCandidateFunc(conf2)(\n \"[\" + rel.techn.text + \"]\",\n relsElem,\n Math.min(rel.startPoint.x, rel.endPoint.x) + Math.abs(rel.endPoint.x - rel.startPoint.x) / 2 + offsetX,\n Math.min(rel.startPoint.y, rel.endPoint.y) + Math.abs(rel.endPoint.y - rel.startPoint.y) / 2 + conf2.messageFontSize + 5 + offsetY,\n Math.max(rel.label.width, rel.techn.width),\n rel.techn.height,\n { fill: textColor, \"font-style\": \"italic\" },\n messageConf\n );\n }\n }\n}, \"drawRels\");\nvar drawBoundary = /* @__PURE__ */ __name(function(elem, boundary, conf2) {\n const boundaryElem = elem.append(\"g\");\n let fillColor = boundary.bgColor ? boundary.bgColor : \"none\";\n let strokeColor = boundary.borderColor ? boundary.borderColor : \"#444444\";\n let fontColor = boundary.fontColor ? boundary.fontColor : \"black\";\n let attrsValue = { \"stroke-width\": 1, \"stroke-dasharray\": \"7.0,7.0\" };\n if (boundary.nodeType) {\n attrsValue = { \"stroke-width\": 1 };\n }\n let rectData = {\n x: boundary.x,\n y: boundary.y,\n fill: fillColor,\n stroke: strokeColor,\n width: boundary.width,\n height: boundary.height,\n rx: 2.5,\n ry: 2.5,\n attrs: attrsValue\n };\n drawRect2(boundaryElem, rectData);\n let boundaryConf = conf2.boundaryFont();\n boundaryConf.fontWeight = \"bold\";\n boundaryConf.fontSize = boundaryConf.fontSize + 2;\n boundaryConf.fontColor = fontColor;\n _drawTextCandidateFunc(conf2)(\n boundary.label.text,\n boundaryElem,\n boundary.x,\n boundary.y + boundary.label.Y,\n boundary.width,\n boundary.height,\n { fill: \"#444444\" },\n boundaryConf\n );\n if (boundary.type && boundary.type.text !== \"\") {\n boundaryConf = conf2.boundaryFont();\n boundaryConf.fontColor = fontColor;\n _drawTextCandidateFunc(conf2)(\n boundary.type.text,\n boundaryElem,\n boundary.x,\n boundary.y + boundary.type.Y,\n boundary.width,\n boundary.height,\n { fill: \"#444444\" },\n boundaryConf\n );\n }\n if (boundary.descr && boundary.descr.text !== \"\") {\n boundaryConf = conf2.boundaryFont();\n boundaryConf.fontSize = boundaryConf.fontSize - 2;\n boundaryConf.fontColor = fontColor;\n _drawTextCandidateFunc(conf2)(\n boundary.descr.text,\n boundaryElem,\n boundary.x,\n boundary.y + boundary.descr.Y,\n boundary.width,\n boundary.height,\n { fill: \"#444444\" },\n boundaryConf\n );\n }\n}, \"drawBoundary\");\nvar drawC4Shape = /* @__PURE__ */ __name(function(elem, c4Shape, conf2) {\n let fillColor = c4Shape.bgColor ? c4Shape.bgColor : conf2[c4Shape.typeC4Shape.text + \"_bg_color\"];\n let strokeColor = c4Shape.borderColor ? c4Shape.borderColor : conf2[c4Shape.typeC4Shape.text + \"_border_color\"];\n let fontColor = c4Shape.fontColor ? c4Shape.fontColor : \"#FFFFFF\";\n let personImg = \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAIAAADYYG7QAAACD0lEQVR4Xu2YoU4EMRCGT+4j8Ai8AhaH4QHgAUjQuFMECUgMIUgwJAgMhgQsAYUiJCiQIBBY+EITsjfTdme6V24v4c8vyGbb+ZjOtN0bNcvjQXmkH83WvYBWto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ej1gWAtgbeGgFsAMHr50BIWOLCbezvhpBFUdY6EJuJ/QDW0XoMX60zZ0AAAAASUVORK5CYII=\";\n break;\n }\n const c4ShapeElem = elem.append(\"g\");\n c4ShapeElem.attr(\"class\", \"person-man\");\n const rect = getNoteRect();\n switch (c4Shape.typeC4Shape.text) {\n case \"person\":\n case \"external_person\":\n case \"system\":\n case \"external_system\":\n case \"container\":\n case \"external_container\":\n case \"component\":\n case \"external_component\":\n rect.x = c4Shape.x;\n rect.y = c4Shape.y;\n rect.fill = fillColor;\n rect.width = c4Shape.width;\n rect.height = c4Shape.height;\n rect.stroke = strokeColor;\n rect.rx = 2.5;\n rect.ry = 2.5;\n rect.attrs = { \"stroke-width\": 0.5 };\n drawRect2(c4ShapeElem, rect);\n break;\n case \"system_db\":\n case \"external_system_db\":\n case \"container_db\":\n case \"external_container_db\":\n case \"component_db\":\n case \"external_component_db\":\n c4ShapeElem.append(\"path\").attr(\"fill\", fillColor).attr(\"stroke-width\", \"0.5\").attr(\"stroke\", strokeColor).attr(\n \"d\",\n \"Mstartx,startyc0,-10 half,-10 half,-10c0,0 half,0 half,10l0,heightc0,10 -half,10 -half,10c0,0 -half,0 -half,-10l0,-height\".replaceAll(\"startx\", c4Shape.x).replaceAll(\"starty\", c4Shape.y).replaceAll(\"half\", c4Shape.width / 2).replaceAll(\"height\", c4Shape.height)\n );\n c4ShapeElem.append(\"path\").attr(\"fill\", \"none\").attr(\"stroke-width\", \"0.5\").attr(\"stroke\", strokeColor).attr(\n \"d\",\n \"Mstartx,startyc0,10 half,10 half,10c0,0 half,0 half,-10\".replaceAll(\"startx\", c4Shape.x).replaceAll(\"starty\", c4Shape.y).replaceAll(\"half\", c4Shape.width / 2)\n );\n break;\n case \"system_queue\":\n case \"external_system_queue\":\n case \"container_queue\":\n case \"external_container_queue\":\n case \"component_queue\":\n case \"external_component_queue\":\n c4ShapeElem.append(\"path\").attr(\"fill\", fillColor).attr(\"stroke-width\", \"0.5\").attr(\"stroke\", strokeColor).attr(\n \"d\",\n \"Mstartx,startylwidth,0c5,0 5,half 5,halfc0,0 0,half -5,halfl-width,0c-5,0 -5,-half -5,-halfc0,0 0,-half 5,-half\".replaceAll(\"startx\", c4Shape.x).replaceAll(\"starty\", c4Shape.y).replaceAll(\"width\", c4Shape.width).replaceAll(\"half\", c4Shape.height / 2)\n );\n c4ShapeElem.append(\"path\").attr(\"fill\", \"none\").attr(\"stroke-width\", \"0.5\").attr(\"stroke\", strokeColor).attr(\n \"d\",\n \"Mstartx,startyc-5,0 -5,half -5,halfc0,half 5,half 5,half\".replaceAll(\"startx\", c4Shape.x + c4Shape.width).replaceAll(\"starty\", c4Shape.y).replaceAll(\"half\", c4Shape.height / 2)\n );\n break;\n }\n let c4ShapeFontConf = getC4ShapeFont(conf2, c4Shape.typeC4Shape.text);\n c4ShapeElem.append(\"text\").attr(\"fill\", fontColor).attr(\"font-family\", c4ShapeFontConf.fontFamily).attr(\"font-size\", c4ShapeFontConf.fontSize - 2).attr(\"font-style\", \"italic\").attr(\"lengthAdjust\", \"spacing\").attr(\"textLength\", c4Shape.typeC4Shape.width).attr(\"x\", c4Shape.x + c4Shape.width / 2 - c4Shape.typeC4Shape.width / 2).attr(\"y\", c4Shape.y + c4Shape.typeC4Shape.Y).text(\"<<\" + c4Shape.typeC4Shape.text + \">>\");\n switch (c4Shape.typeC4Shape.text) {\n case \"person\":\n case \"external_person\":\n drawImage(\n c4ShapeElem,\n 48,\n 48,\n c4Shape.x + c4Shape.width / 2 - 24,\n c4Shape.y + c4Shape.image.Y,\n personImg\n );\n break;\n }\n let textFontConf = conf2[c4Shape.typeC4Shape.text + \"Font\"]();\n textFontConf.fontWeight = \"bold\";\n textFontConf.fontSize = textFontConf.fontSize + 2;\n textFontConf.fontColor = fontColor;\n _drawTextCandidateFunc(conf2)(\n c4Shape.label.text,\n c4ShapeElem,\n c4Shape.x,\n c4Shape.y + c4Shape.label.Y,\n c4Shape.width,\n c4Shape.height,\n { fill: fontColor },\n textFontConf\n );\n textFontConf = conf2[c4Shape.typeC4Shape.text + \"Font\"]();\n textFontConf.fontColor = fontColor;\n if (c4Shape.techn && c4Shape.techn?.text !== \"\") {\n _drawTextCandidateFunc(conf2)(\n c4Shape.techn.text,\n c4ShapeElem,\n c4Shape.x,\n c4Shape.y + c4Shape.techn.Y,\n c4Shape.width,\n c4Shape.height,\n { fill: fontColor, \"font-style\": \"italic\" },\n textFontConf\n );\n } else if (c4Shape.type && c4Shape.type.text !== \"\") {\n _drawTextCandidateFunc(conf2)(\n c4Shape.type.text,\n c4ShapeElem,\n c4Shape.x,\n c4Shape.y + c4Shape.type.Y,\n c4Shape.width,\n c4Shape.height,\n { fill: fontColor, \"font-style\": \"italic\" },\n textFontConf\n );\n }\n if (c4Shape.descr && c4Shape.descr.text !== \"\") {\n textFontConf = conf2.personFont();\n textFontConf.fontColor = fontColor;\n _drawTextCandidateFunc(conf2)(\n c4Shape.descr.text,\n c4ShapeElem,\n c4Shape.x,\n c4Shape.y + c4Shape.descr.Y,\n c4Shape.width,\n c4Shape.height,\n { fill: fontColor },\n textFontConf\n );\n }\n return c4Shape.height;\n}, \"drawC4Shape\");\nvar insertDatabaseIcon = /* @__PURE__ */ __name(function(elem) {\n elem.append(\"defs\").append(\"symbol\").attr(\"id\", \"database\").attr(\"fill-rule\", \"evenodd\").attr(\"clip-rule\", \"evenodd\").append(\"path\").attr(\"transform\", \"scale(.5)\").attr(\n \"d\",\n \"M12.258.001l.256.004.255.005.253.008.251.01.249.012.247.015.246.016.242.019.241.02.239.023.236.024.233.027.231.028.229.031.225.032.223.034.22.036.217.038.214.04.211.041.208.043.205.045.201.046.198.048.194.05.191.051.187.053.183.054.18.056.175.057.172.059.168.06.163.061.16.063.155.064.15.066.074.033.073.033.071.034.07.034.069.035.068.035.067.035.066.035.064.036.064.036.062.036.06.036.06.037.058.037.058.037.055.038.055.038.053.038.052.038.051.039.05.039.048.039.047.039.045.04.044.04.043.04.041.04.04.041.039.041.037.041.036.041.034.041.033.042.032.042.03.042.029.042.027.042.026.043.024.043.023.043.021.043.02.043.018.044.017.043.015.044.013.044.012.044.011.045.009.044.007.045.006.045.004.045.002.045.001.045v17l-.001.045-.002.045-.004.045-.006.045-.007.045-.009.044-.011.045-.012.044-.013.044-.015.044-.017.043-.018.044-.02.043-.021.043-.023.043-.024.043-.026.043-.027.042-.029.042-.03.042-.032.042-.033.042-.034.041-.036.041-.037.041-.039.041-.04.041-.041.04-.043.04-.044.04-.045.04-.047.039-.048.039-.05.039-.051.039-.052.038-.053.038-.055.038-.055.038-.058.037-.058.037-.06.037-.06.036-.062.036-.064.036-.064.036-.066.035-.067.035-.068.035-.069.035-.07.034-.071.034-.073.033-.074.033-.15.066-.155.064-.16.063-.163.061-.168.06-.172.059-.175.057-.18.056-.183.054-.187.053-.191.051-.194.05-.198.048-.201.046-.205.045-.208.043-.211.041-.214.04-.217.038-.22.036-.223.034-.225.032-.229.031-.231.028-.233.027-.236.024-.239.023-.241.02-.242.019-.246.016-.247.015-.249.012-.251.01-.253.008-.255.005-.256.004-.258.001-.258-.001-.256-.004-.255-.005-.253-.008-.251-.01-.249-.012-.247-.015-.245-.016-.243-.019-.241-.02-.238-.023-.236-.024-.234-.027-.231-.028-.228-.031-.226-.032-.223-.034-.22-.036-.217-.038-.214-.04-.211-.041-.208-.043-.204-.045-.201-.046-.198-.048-.195-.05-.19-.051-.187-.053-.184-.054-.179-.056-.176-.057-.172-.059-.167-.06-.164-.061-.159-.063-.155-.064-.151-.066-.074-.033-.072-.033-.072-.034-.07-.034-.069-.035-.068-.035-.067-.035-.066-.035-.064-.036-.063-.036-.062-.036-.061-.036-.06-.037-.058-.037-.057-.037-.056-.038-.055-.038-.053-.038-.052-.038-.051-.039-.049-.039-.049-.039-.046-.039-.046-.04-.044-.04-.043-.04-.041-.04-.04-.041-.039-.041-.037-.041-.036-.041-.034-.041-.033-.042-.032-.042-.03-.042-.029-.042-.027-.042-.026-.043-.024-.043-.023-.043-.021-.043-.02-.043-.018-.044-.017-.043-.015-.044-.013-.044-.012-.044-.011-.045-.009-.044-.007-.045-.006-.045-.004-.045-.002-.045-.001-.045v-17l.001-.045.002-.045.004-.045.006-.045.007-.045.009-.044.011-.045.012-.044.013-.044.015-.044.017-.043.018-.044.02-.043.021-.043.023-.043.024-.043.026-.043.027-.042.029-.042.03-.042.032-.042.033-.042.034-.041.036-.041.037-.041.039-.041.04-.041.041-.04.043-.04.044-.04.046-.04.046-.039.049-.039.049-.039.051-.039.052-.038.053-.038.055-.038.056-.038.057-.037.058-.037.06-.037.061-.036.062-.036.063-.036.064-.036.066-.035.067-.035.068-.035.069-.035.07-.034.072-.034.072-.033.074-.033.151-.066.155-.064.159-.063.164-.061.167-.06.172-.059.176-.057.179-.056.184-.054.187-.053.19-.051.195-.05.198-.048.201-.046.204-.045.208-.043.211-.041.214-.04.217-.038.22-.036.223-.034.226-.032.228-.031.231-.028.234-.027.236-.024.238-.023.241-.02.243-.019.245-.016.247-.015.249-.012.251-.01.253-.008.255-.005.256-.004.258-.001.258.001zm-9.258 20.499v.01l.001.021.003.021.004.022.005.021.006.022.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.023.018.024.019.024.021.024.022.025.023.024.024.025.052.049.056.05.061.051.066.051.07.051.075.051.079.052.084.052.088.052.092.052.097.052.102.051.105.052.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.048.144.049.147.047.152.047.155.047.16.045.163.045.167.043.171.043.176.041.178.041.183.039.187.039.19.037.194.035.197.035.202.033.204.031.209.03.212.029.216.027.219.025.222.024.226.021.23.02.233.018.236.016.24.015.243.012.246.01.249.008.253.005.256.004.259.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.021.224-.024.22-.026.216-.027.212-.028.21-.031.205-.031.202-.034.198-.034.194-.036.191-.037.187-.039.183-.04.179-.04.175-.042.172-.043.168-.044.163-.045.16-.046.155-.046.152-.047.148-.048.143-.049.139-.049.136-.05.131-.05.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.053.083-.051.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.05.023-.024.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.023.01-.022.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.127l-.077.055-.08.053-.083.054-.085.053-.087.052-.09.052-.093.051-.095.05-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.045-.118.044-.12.043-.122.042-.124.042-.126.041-.128.04-.13.04-.132.038-.134.038-.135.037-.138.037-.139.035-.142.035-.143.034-.144.033-.147.032-.148.031-.15.03-.151.03-.153.029-.154.027-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.01-.179.008-.179.008-.181.006-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.006-.179-.008-.179-.008-.178-.01-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.027-.153-.029-.151-.03-.15-.03-.148-.031-.146-.032-.145-.033-.143-.034-.141-.035-.14-.035-.137-.037-.136-.037-.134-.038-.132-.038-.13-.04-.128-.04-.126-.041-.124-.042-.122-.042-.12-.044-.117-.043-.116-.045-.113-.045-.112-.046-.109-.047-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.05-.093-.052-.09-.051-.087-.052-.085-.053-.083-.054-.08-.054-.077-.054v4.127zm0-5.654v.011l.001.021.003.021.004.021.005.022.006.022.007.022.009.022.01.022.011.023.012.023.013.023.015.024.016.023.017.024.018.024.019.024.021.024.022.024.023.025.024.024.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.052.11.051.114.051.119.052.123.05.127.051.131.05.135.049.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.044.171.042.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.022.23.02.233.018.236.016.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.012.241-.015.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.048.139-.05.136-.049.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.051.051-.049.023-.025.023-.024.021-.025.02-.024.019-.024.018-.024.017-.024.015-.023.014-.023.013-.024.012-.022.01-.023.01-.023.008-.022.006-.022.006-.022.004-.021.004-.022.001-.021.001-.021v-4.139l-.077.054-.08.054-.083.054-.085.052-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.044-.118.044-.12.044-.122.042-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.035-.143.033-.144.033-.147.033-.148.031-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.009-.179.009-.179.007-.181.007-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.007-.179-.007-.179-.009-.178-.009-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.031-.146-.033-.145-.033-.143-.033-.141-.035-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.04-.126-.041-.124-.042-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.051-.093-.051-.09-.051-.087-.053-.085-.052-.083-.054-.08-.054-.077-.054v4.139zm0-5.666v.011l.001.02.003.022.004.021.005.022.006.021.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.024.018.023.019.024.021.025.022.024.023.024.024.025.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.051.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.043.171.043.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.021.23.02.233.018.236.017.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.013.241-.014.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.049.139-.049.136-.049.131-.051.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.049.023-.025.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.022.01-.023.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.153l-.077.054-.08.054-.083.053-.085.053-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.048-.105.048-.106.048-.109.046-.111.046-.114.046-.115.044-.118.044-.12.043-.122.043-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.034-.143.034-.144.033-.147.032-.148.032-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.024-.161.024-.162.023-.163.023-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.01-.178.01-.179.009-.179.007-.181.006-.182.006-.182.004-.184.003-.184.001-.185.001-.185-.001-.184-.001-.184-.003-.182-.004-.182-.006-.181-.006-.179-.007-.179-.009-.178-.01-.176-.01-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.023-.162-.023-.161-.024-.159-.024-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.032-.146-.032-.145-.033-.143-.034-.141-.034-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.041-.126-.041-.124-.041-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.048-.105-.048-.102-.048-.1-.05-.097-.049-.095-.051-.093-.051-.09-.052-.087-.052-.085-.053-.083-.053-.08-.054-.077-.054v4.153zm8.74-8.179l-.257.004-.254.005-.25.008-.247.011-.244.012-.241.014-.237.016-.233.018-.231.021-.226.022-.224.023-.22.026-.216.027-.212.028-.21.031-.205.032-.202.033-.198.034-.194.036-.191.038-.187.038-.183.04-.179.041-.175.042-.172.043-.168.043-.163.045-.16.046-.155.046-.152.048-.148.048-.143.048-.139.049-.136.05-.131.05-.126.051-.123.051-.118.051-.114.052-.11.052-.106.052-.101.052-.096.052-.092.052-.088.052-.083.052-.079.052-.074.051-.07.052-.065.051-.06.05-.056.05-.051.05-.023.025-.023.024-.021.024-.02.025-.019.024-.018.024-.017.023-.015.024-.014.023-.013.023-.012.023-.01.023-.01.022-.008.022-.006.023-.006.021-.004.022-.004.021-.001.021-.001.021.001.021.001.021.004.021.004.022.006.021.006.023.008.022.01.022.01.023.012.023.013.023.014.023.015.024.017.023.018.024.019.024.02.025.021.024.023.024.023.025.051.05.056.05.06.05.065.051.07.052.074.051.079.052.083.052.088.052.092.052.096.052.101.052.106.052.11.052.114.052.118.051.123.051.126.051.131.05.136.05.139.049.143.048.148.048.152.048.155.046.16.046.163.045.168.043.172.043.175.042.179.041.183.04.187.038.191.038.194.036.198.034.202.033.205.032.21.031.212.028.216.027.22.026.224.023.226.022.231.021.233.018.237.016.241.014.244.012.247.011.25.008.254.005.257.004.26.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.022.224-.023.22-.026.216-.027.212-.028.21-.031.205-.032.202-.033.198-.034.194-.036.191-.038.187-.038.183-.04.179-.041.175-.042.172-.043.168-.043.163-.045.16-.046.155-.046.152-.048.148-.048.143-.048.139-.049.136-.05.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.05.051-.05.023-.025.023-.024.021-.024.02-.025.019-.024.018-.024.017-.023.015-.024.014-.023.013-.023.012-.023.01-.023.01-.022.008-.022.006-.023.006-.021.004-.022.004-.021.001-.021.001-.021-.001-.021-.001-.021-.004-.021-.004-.022-.006-.021-.006-.023-.008-.022-.01-.022-.01-.023-.012-.023-.013-.023-.014-.023-.015-.024-.017-.023-.018-.024-.019-.024-.02-.025-.021-.024-.023-.024-.023-.025-.051-.05-.056-.05-.06-.05-.065-.051-.07-.052-.074-.051-.079-.052-.083-.052-.088-.052-.092-.052-.096-.052-.101-.052-.106-.052-.11-.052-.114-.052-.118-.051-.123-.051-.126-.051-.131-.05-.136-.05-.139-.049-.143-.048-.148-.048-.152-.048-.155-.046-.16-.046-.163-.045-.168-.043-.172-.043-.175-.042-.179-.041-.183-.04-.187-.038-.191-.038-.194-.036-.198-.034-.202-.033-.205-.032-.21-.031-.212-.028-.216-.027-.22-.026-.224-.023-.226-.022-.231-.021-.233-.018-.237-.016-.241-.014-.244-.012-.247-.011-.25-.008-.254-.005-.257-.004-.26-.001-.26.001z\"\n );\n}, \"insertDatabaseIcon\");\nvar insertComputerIcon = /* @__PURE__ */ __name(function(elem) {\n elem.append(\"defs\").append(\"symbol\").attr(\"id\", \"computer\").attr(\"width\", \"24\").attr(\"height\", \"24\").append(\"path\").attr(\"transform\", \"scale(.5)\").attr(\n \"d\",\n \"M2 2v13h20v-13h-20zm18 11h-16v-9h16v9zm-10.228 6l.466-1h3.524l.467 1h-4.457zm14.228 3h-24l2-6h2.104l-1.33 4h18.45l-1.297-4h2.073l2 6zm-5-10h-14v-7h14v7z\"\n );\n}, \"insertComputerIcon\");\nvar insertClockIcon = /* @__PURE__ */ __name(function(elem) {\n elem.append(\"defs\").append(\"symbol\").attr(\"id\", \"clock\").attr(\"width\", \"24\").attr(\"height\", \"24\").append(\"path\").attr(\"transform\", \"scale(.5)\").attr(\n \"d\",\n \"M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm5.848 12.459c.202.038.202.333.001.372-1.907.361-6.045 1.111-6.547 1.111-.719 0-1.301-.582-1.301-1.301 0-.512.77-5.447 1.125-7.445.034-.192.312-.181.343.014l.985 6.238 5.394 1.011z\"\n );\n}, \"insertClockIcon\");\nvar insertArrowHead = /* @__PURE__ */ __name(function(elem) {\n elem.append(\"defs\").append(\"marker\").attr(\"id\", \"arrowhead\").attr(\"refX\", 9).attr(\"refY\", 5).attr(\"markerUnits\", \"userSpaceOnUse\").attr(\"markerWidth\", 12).attr(\"markerHeight\", 12).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 0 0 L 10 5 L 0 10 z\");\n}, \"insertArrowHead\");\nvar insertArrowEnd = /* @__PURE__ */ __name(function(elem) {\n elem.append(\"defs\").append(\"marker\").attr(\"id\", \"arrowend\").attr(\"refX\", 1).attr(\"refY\", 5).attr(\"markerUnits\", \"userSpaceOnUse\").attr(\"markerWidth\", 12).attr(\"markerHeight\", 12).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 10 0 L 0 5 L 10 10 z\");\n}, \"insertArrowEnd\");\nvar insertArrowFilledHead = /* @__PURE__ */ __name(function(elem) {\n elem.append(\"defs\").append(\"marker\").attr(\"id\", \"filled-head\").attr(\"refX\", 18).attr(\"refY\", 7).attr(\"markerWidth\", 20).attr(\"markerHeight\", 28).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 18,7 L9,13 L14,7 L9,1 Z\");\n}, \"insertArrowFilledHead\");\nvar insertDynamicNumber = /* @__PURE__ */ __name(function(elem) {\n elem.append(\"defs\").append(\"marker\").attr(\"id\", \"sequencenumber\").attr(\"refX\", 15).attr(\"refY\", 15).attr(\"markerWidth\", 60).attr(\"markerHeight\", 40).attr(\"orient\", \"auto\").append(\"circle\").attr(\"cx\", 15).attr(\"cy\", 15).attr(\"r\", 6);\n}, \"insertDynamicNumber\");\nvar insertArrowCrossHead = /* @__PURE__ */ __name(function(elem) {\n const defs = elem.append(\"defs\");\n const marker = defs.append(\"marker\").attr(\"id\", \"crosshead\").attr(\"markerWidth\", 15).attr(\"markerHeight\", 8).attr(\"orient\", \"auto\").attr(\"refX\", 16).attr(\"refY\", 4);\n marker.append(\"path\").attr(\"fill\", \"black\").attr(\"stroke\", \"#000000\").style(\"stroke-dasharray\", \"0, 0\").attr(\"stroke-width\", \"1px\").attr(\"d\", \"M 9,2 V 6 L16,4 Z\");\n marker.append(\"path\").attr(\"fill\", \"none\").attr(\"stroke\", \"#000000\").style(\"stroke-dasharray\", \"0, 0\").attr(\"stroke-width\", \"1px\").attr(\"d\", \"M 0,1 L 6,7 M 6,1 L 0,7\");\n}, \"insertArrowCrossHead\");\nvar getC4ShapeFont = /* @__PURE__ */ __name((cnf, typeC4Shape) => {\n return {\n fontFamily: cnf[typeC4Shape + \"FontFamily\"],\n fontSize: cnf[typeC4Shape + \"FontSize\"],\n fontWeight: cnf[typeC4Shape + \"FontWeight\"]\n };\n}, \"getC4ShapeFont\");\nvar _drawTextCandidateFunc = /* @__PURE__ */ (function() {\n function byText(content, g, x, y, width, height, textAttrs) {\n const text = g.append(\"text\").attr(\"x\", x + width / 2).attr(\"y\", y + height / 2 + 5).style(\"text-anchor\", \"middle\").text(content);\n _setTextAttrs(text, textAttrs);\n }\n __name(byText, \"byText\");\n function byTspan(content, g, x, y, width, height, textAttrs, conf2) {\n const { fontSize, fontFamily, fontWeight } = conf2;\n const lines = content.split(common_default.lineBreakRegex);\n for (let i = 0; i < lines.length; i++) {\n const dy = i * fontSize - fontSize * (lines.length - 1) / 2;\n const text = g.append(\"text\").attr(\"x\", x + width / 2).attr(\"y\", y).style(\"text-anchor\", \"middle\").attr(\"dominant-baseline\", \"middle\").style(\"font-size\", fontSize).style(\"font-weight\", fontWeight).style(\"font-family\", fontFamily);\n text.append(\"tspan\").attr(\"dy\", dy).text(lines[i]).attr(\"alignment-baseline\", \"mathematical\");\n _setTextAttrs(text, textAttrs);\n }\n }\n __name(byTspan, \"byTspan\");\n function byFo(content, g, x, y, width, height, textAttrs, conf2) {\n const s = g.append(\"switch\");\n const f = s.append(\"foreignObject\").attr(\"x\", x).attr(\"y\", y).attr(\"width\", width).attr(\"height\", height);\n const text = f.append(\"xhtml:div\").style(\"display\", \"table\").style(\"height\", \"100%\").style(\"width\", \"100%\");\n text.append(\"div\").style(\"display\", \"table-cell\").style(\"text-align\", \"center\").style(\"vertical-align\", \"middle\").text(content);\n byTspan(content, s, x, y, width, height, textAttrs, conf2);\n _setTextAttrs(text, textAttrs);\n }\n __name(byFo, \"byFo\");\n function _setTextAttrs(toText, fromTextAttrsDict) {\n for (const key in fromTextAttrsDict) {\n if (fromTextAttrsDict.hasOwnProperty(key)) {\n toText.attr(key, fromTextAttrsDict[key]);\n }\n }\n }\n __name(_setTextAttrs, \"_setTextAttrs\");\n return function(conf2) {\n return conf2.textPlacement === \"fo\" ? byFo : conf2.textPlacement === \"old\" ? byText : byTspan;\n };\n})();\nvar svgDraw_default = {\n drawRect: drawRect2,\n drawBoundary,\n drawC4Shape,\n drawRels,\n drawImage,\n insertArrowHead,\n insertArrowEnd,\n insertArrowFilledHead,\n insertDynamicNumber,\n insertArrowCrossHead,\n insertDatabaseIcon,\n insertComputerIcon,\n insertClockIcon\n};\n\n// src/diagrams/c4/c4Renderer.js\nvar globalBoundaryMaxX = 0;\nvar globalBoundaryMaxY = 0;\nvar c4ShapeInRow2 = 4;\nvar c4BoundaryInRow2 = 2;\nparser.yy = c4Db_default;\nvar conf = {};\nvar Bounds = class {\n static {\n __name(this, \"Bounds\");\n }\n constructor(diagObj) {\n this.name = \"\";\n this.data = {};\n this.data.startx = void 0;\n this.data.stopx = void 0;\n this.data.starty = void 0;\n this.data.stopy = void 0;\n this.data.widthLimit = void 0;\n this.nextData = {};\n this.nextData.startx = void 0;\n this.nextData.stopx = void 0;\n this.nextData.starty = void 0;\n this.nextData.stopy = void 0;\n this.nextData.cnt = 0;\n setConf(diagObj.db.getConfig());\n }\n setData(startx, stopx, starty, stopy) {\n this.nextData.startx = this.data.startx = startx;\n this.nextData.stopx = this.data.stopx = stopx;\n this.nextData.starty = this.data.starty = starty;\n this.nextData.stopy = this.data.stopy = stopy;\n }\n updateVal(obj, key, val, fun) {\n if (obj[key] === void 0) {\n obj[key] = val;\n } else {\n obj[key] = fun(val, obj[key]);\n }\n }\n insert(c4Shape) {\n this.nextData.cnt = this.nextData.cnt + 1;\n let _startx = this.nextData.startx === this.nextData.stopx ? this.nextData.stopx + c4Shape.margin : this.nextData.stopx + c4Shape.margin * 2;\n let _stopx = _startx + c4Shape.width;\n let _starty = this.nextData.starty + c4Shape.margin * 2;\n let _stopy = _starty + c4Shape.height;\n if (_startx >= this.data.widthLimit || _stopx >= this.data.widthLimit || this.nextData.cnt > c4ShapeInRow2) {\n _startx = this.nextData.startx + c4Shape.margin + conf.nextLinePaddingX;\n _starty = this.nextData.stopy + c4Shape.margin * 2;\n this.nextData.stopx = _stopx = _startx + c4Shape.width;\n this.nextData.starty = this.nextData.stopy;\n this.nextData.stopy = _stopy = _starty + c4Shape.height;\n this.nextData.cnt = 1;\n }\n c4Shape.x = _startx;\n c4Shape.y = _starty;\n this.updateVal(this.data, \"startx\", _startx, Math.min);\n this.updateVal(this.data, \"starty\", _starty, Math.min);\n this.updateVal(this.data, \"stopx\", _stopx, Math.max);\n this.updateVal(this.data, \"stopy\", _stopy, Math.max);\n this.updateVal(this.nextData, \"startx\", _startx, Math.min);\n this.updateVal(this.nextData, \"starty\", _starty, Math.min);\n this.updateVal(this.nextData, \"stopx\", _stopx, Math.max);\n this.updateVal(this.nextData, \"stopy\", _stopy, Math.max);\n }\n init(diagObj) {\n this.name = \"\";\n this.data = {\n startx: void 0,\n stopx: void 0,\n starty: void 0,\n stopy: void 0,\n widthLimit: void 0\n };\n this.nextData = {\n startx: void 0,\n stopx: void 0,\n starty: void 0,\n stopy: void 0,\n cnt: 0\n };\n setConf(diagObj.db.getConfig());\n }\n bumpLastMargin(margin) {\n this.data.stopx += margin;\n this.data.stopy += margin;\n }\n};\nvar setConf = /* @__PURE__ */ __name(function(cnf) {\n assignWithDepth_default(conf, cnf);\n if (cnf.fontFamily) {\n conf.personFontFamily = conf.systemFontFamily = conf.messageFontFamily = cnf.fontFamily;\n }\n if (cnf.fontSize) {\n conf.personFontSize = conf.systemFontSize = conf.messageFontSize = cnf.fontSize;\n }\n if (cnf.fontWeight) {\n conf.personFontWeight = conf.systemFontWeight = conf.messageFontWeight = cnf.fontWeight;\n }\n}, \"setConf\");\nvar c4ShapeFont = /* @__PURE__ */ __name((cnf, typeC4Shape) => {\n return {\n fontFamily: cnf[typeC4Shape + \"FontFamily\"],\n fontSize: cnf[typeC4Shape + \"FontSize\"],\n fontWeight: cnf[typeC4Shape + \"FontWeight\"]\n };\n}, \"c4ShapeFont\");\nvar boundaryFont = /* @__PURE__ */ __name((cnf) => {\n return {\n fontFamily: cnf.boundaryFontFamily,\n fontSize: cnf.boundaryFontSize,\n fontWeight: cnf.boundaryFontWeight\n };\n}, \"boundaryFont\");\nvar messageFont = /* @__PURE__ */ __name((cnf) => {\n return {\n fontFamily: cnf.messageFontFamily,\n fontSize: cnf.messageFontSize,\n fontWeight: cnf.messageFontWeight\n };\n}, \"messageFont\");\nfunction calcC4ShapeTextWH(textType, c4Shape, c4ShapeTextWrap, textConf, textLimitWidth) {\n if (!c4Shape[textType].width) {\n if (c4ShapeTextWrap) {\n c4Shape[textType].text = wrapLabel(c4Shape[textType].text, textLimitWidth, textConf);\n c4Shape[textType].textLines = c4Shape[textType].text.split(common_default.lineBreakRegex).length;\n c4Shape[textType].width = textLimitWidth;\n c4Shape[textType].height = calculateTextHeight(c4Shape[textType].text, textConf);\n } else {\n let lines = c4Shape[textType].text.split(common_default.lineBreakRegex);\n c4Shape[textType].textLines = lines.length;\n let lineHeight = 0;\n c4Shape[textType].height = 0;\n c4Shape[textType].width = 0;\n for (const line of lines) {\n c4Shape[textType].width = Math.max(\n calculateTextWidth(line, textConf),\n c4Shape[textType].width\n );\n lineHeight = calculateTextHeight(line, textConf);\n c4Shape[textType].height = c4Shape[textType].height + lineHeight;\n }\n }\n }\n}\n__name(calcC4ShapeTextWH, \"calcC4ShapeTextWH\");\nvar drawBoundary2 = /* @__PURE__ */ __name(function(diagram2, boundary, bounds) {\n boundary.x = bounds.data.startx;\n boundary.y = bounds.data.starty;\n boundary.width = bounds.data.stopx - bounds.data.startx;\n boundary.height = bounds.data.stopy - bounds.data.starty;\n boundary.label.y = conf.c4ShapeMargin - 35;\n let boundaryTextWrap = boundary.wrap && conf.wrap;\n let boundaryLabelConf = boundaryFont(conf);\n boundaryLabelConf.fontSize = boundaryLabelConf.fontSize + 2;\n boundaryLabelConf.fontWeight = \"bold\";\n let textLimitWidth = calculateTextWidth(boundary.label.text, boundaryLabelConf);\n calcC4ShapeTextWH(\"label\", boundary, boundaryTextWrap, boundaryLabelConf, textLimitWidth);\n svgDraw_default.drawBoundary(diagram2, boundary, conf);\n}, \"drawBoundary\");\nvar drawC4ShapeArray = /* @__PURE__ */ __name(function(currentBounds, diagram2, c4ShapeArray2, c4ShapeKeys) {\n let Y = 0;\n for (const c4ShapeKey of c4ShapeKeys) {\n Y = 0;\n const c4Shape = c4ShapeArray2[c4ShapeKey];\n let c4ShapeTypeConf = c4ShapeFont(conf, c4Shape.typeC4Shape.text);\n c4ShapeTypeConf.fontSize = c4ShapeTypeConf.fontSize - 2;\n c4Shape.typeC4Shape.width = calculateTextWidth(\n \"\\xAB\" + c4Shape.typeC4Shape.text + \"\\xBB\",\n c4ShapeTypeConf\n );\n c4Shape.typeC4Shape.height = c4ShapeTypeConf.fontSize + 2;\n c4Shape.typeC4Shape.Y = conf.c4ShapePadding;\n Y = c4Shape.typeC4Shape.Y + c4Shape.typeC4Shape.height - 4;\n c4Shape.image = { width: 0, height: 0, Y: 0 };\n switch (c4Shape.typeC4Shape.text) {\n case \"person\":\n case \"external_person\":\n c4Shape.image.width = 48;\n c4Shape.image.height = 48;\n c4Shape.image.Y = Y;\n Y = c4Shape.image.Y + c4Shape.image.height;\n break;\n }\n if (c4Shape.sprite) {\n c4Shape.image.width = 48;\n c4Shape.image.height = 48;\n c4Shape.image.Y = Y;\n Y = c4Shape.image.Y + c4Shape.image.height;\n }\n let c4ShapeTextWrap = c4Shape.wrap && conf.wrap;\n let textLimitWidth = conf.width - conf.c4ShapePadding * 2;\n let c4ShapeLabelConf = c4ShapeFont(conf, c4Shape.typeC4Shape.text);\n c4ShapeLabelConf.fontSize = c4ShapeLabelConf.fontSize + 2;\n c4ShapeLabelConf.fontWeight = \"bold\";\n calcC4ShapeTextWH(\"label\", c4Shape, c4ShapeTextWrap, c4ShapeLabelConf, textLimitWidth);\n c4Shape.label.Y = Y + 8;\n Y = c4Shape.label.Y + c4Shape.label.height;\n if (c4Shape.type && c4Shape.type.text !== \"\") {\n c4Shape.type.text = \"[\" + c4Shape.type.text + \"]\";\n let c4ShapeTypeConf2 = c4ShapeFont(conf, c4Shape.typeC4Shape.text);\n calcC4ShapeTextWH(\"type\", c4Shape, c4ShapeTextWrap, c4ShapeTypeConf2, textLimitWidth);\n c4Shape.type.Y = Y + 5;\n Y = c4Shape.type.Y + c4Shape.type.height;\n } else if (c4Shape.techn && c4Shape.techn.text !== \"\") {\n c4Shape.techn.text = \"[\" + c4Shape.techn.text + \"]\";\n let c4ShapeTechnConf = c4ShapeFont(conf, c4Shape.techn.text);\n calcC4ShapeTextWH(\"techn\", c4Shape, c4ShapeTextWrap, c4ShapeTechnConf, textLimitWidth);\n c4Shape.techn.Y = Y + 5;\n Y = c4Shape.techn.Y + c4Shape.techn.height;\n }\n let rectHeight = Y;\n let rectWidth = c4Shape.label.width;\n if (c4Shape.descr && c4Shape.descr.text !== \"\") {\n let c4ShapeDescrConf = c4ShapeFont(conf, c4Shape.typeC4Shape.text);\n calcC4ShapeTextWH(\"descr\", c4Shape, c4ShapeTextWrap, c4ShapeDescrConf, textLimitWidth);\n c4Shape.descr.Y = Y + 20;\n Y = c4Shape.descr.Y + c4Shape.descr.height;\n rectWidth = Math.max(c4Shape.label.width, c4Shape.descr.width);\n rectHeight = Y - c4Shape.descr.textLines * 5;\n }\n rectWidth = rectWidth + conf.c4ShapePadding;\n c4Shape.width = Math.max(c4Shape.width || conf.width, rectWidth, conf.width);\n c4Shape.height = Math.max(c4Shape.height || conf.height, rectHeight, conf.height);\n c4Shape.margin = c4Shape.margin || conf.c4ShapeMargin;\n currentBounds.insert(c4Shape);\n svgDraw_default.drawC4Shape(diagram2, c4Shape, conf);\n }\n currentBounds.bumpLastMargin(conf.c4ShapeMargin);\n}, \"drawC4ShapeArray\");\nvar Point = class {\n static {\n __name(this, \"Point\");\n }\n constructor(x, y) {\n this.x = x;\n this.y = y;\n }\n};\nvar getIntersectPoint = /* @__PURE__ */ __name(function(fromNode, endPoint) {\n let x1 = fromNode.x;\n let y1 = fromNode.y;\n let x2 = endPoint.x;\n let y2 = endPoint.y;\n let fromCenterX = x1 + fromNode.width / 2;\n let fromCenterY = y1 + fromNode.height / 2;\n let dx = Math.abs(x1 - x2);\n let dy = Math.abs(y1 - y2);\n let tanDYX = dy / dx;\n let fromDYX = fromNode.height / fromNode.width;\n let returnPoint = null;\n if (y1 == y2 && x1 < x2) {\n returnPoint = new Point(x1 + fromNode.width, fromCenterY);\n } else if (y1 == y2 && x1 > x2) {\n returnPoint = new Point(x1, fromCenterY);\n } else if (x1 == x2 && y1 < y2) {\n returnPoint = new Point(fromCenterX, y1 + fromNode.height);\n } else if (x1 == x2 && y1 > y2) {\n returnPoint = new Point(fromCenterX, y1);\n }\n if (x1 > x2 && y1 < y2) {\n if (fromDYX >= tanDYX) {\n returnPoint = new Point(x1, fromCenterY + tanDYX * fromNode.width / 2);\n } else {\n returnPoint = new Point(\n fromCenterX - dx / dy * fromNode.height / 2,\n y1 + fromNode.height\n );\n }\n } else if (x1 < x2 && y1 < y2) {\n if (fromDYX >= tanDYX) {\n returnPoint = new Point(x1 + fromNode.width, fromCenterY + tanDYX * fromNode.width / 2);\n } else {\n returnPoint = new Point(\n fromCenterX + dx / dy * fromNode.height / 2,\n y1 + fromNode.height\n );\n }\n } else if (x1 < x2 && y1 > y2) {\n if (fromDYX >= tanDYX) {\n returnPoint = new Point(x1 + fromNode.width, fromCenterY - tanDYX * fromNode.width / 2);\n } else {\n returnPoint = new Point(fromCenterX + fromNode.height / 2 * dx / dy, y1);\n }\n } else if (x1 > x2 && y1 > y2) {\n if (fromDYX >= tanDYX) {\n returnPoint = new Point(x1, fromCenterY - fromNode.width / 2 * tanDYX);\n } else {\n returnPoint = new Point(fromCenterX - fromNode.height / 2 * dx / dy, y1);\n }\n }\n return returnPoint;\n}, \"getIntersectPoint\");\nvar getIntersectPoints = /* @__PURE__ */ __name(function(fromNode, endNode) {\n let endIntersectPoint = { x: 0, y: 0 };\n endIntersectPoint.x = endNode.x + endNode.width / 2;\n endIntersectPoint.y = endNode.y + endNode.height / 2;\n let startPoint = getIntersectPoint(fromNode, endIntersectPoint);\n endIntersectPoint.x = fromNode.x + fromNode.width / 2;\n endIntersectPoint.y = fromNode.y + fromNode.height / 2;\n let endPoint = getIntersectPoint(endNode, endIntersectPoint);\n return { startPoint, endPoint };\n}, \"getIntersectPoints\");\nvar drawRels2 = /* @__PURE__ */ __name(function(diagram2, rels2, getC4ShapeObj, diagObj) {\n let i = 0;\n for (let rel of rels2) {\n i = i + 1;\n let relTextWrap = rel.wrap && conf.wrap;\n let relConf = messageFont(conf);\n let diagramType = diagObj.db.getC4Type();\n if (diagramType === \"C4Dynamic\") {\n rel.label.text = i + \": \" + rel.label.text;\n }\n let textLimitWidth = calculateTextWidth(rel.label.text, relConf);\n calcC4ShapeTextWH(\"label\", rel, relTextWrap, relConf, textLimitWidth);\n if (rel.techn && rel.techn.text !== \"\") {\n textLimitWidth = calculateTextWidth(rel.techn.text, relConf);\n calcC4ShapeTextWH(\"techn\", rel, relTextWrap, relConf, textLimitWidth);\n }\n if (rel.descr && rel.descr.text !== \"\") {\n textLimitWidth = calculateTextWidth(rel.descr.text, relConf);\n calcC4ShapeTextWH(\"descr\", rel, relTextWrap, relConf, textLimitWidth);\n }\n let fromNode = getC4ShapeObj(rel.from);\n let endNode = getC4ShapeObj(rel.to);\n let points = getIntersectPoints(fromNode, endNode);\n rel.startPoint = points.startPoint;\n rel.endPoint = points.endPoint;\n }\n svgDraw_default.drawRels(diagram2, rels2, conf);\n}, \"drawRels\");\nfunction drawInsideBoundary(diagram2, parentBoundaryAlias, parentBounds, currentBoundaries, diagObj) {\n let currentBounds = new Bounds(diagObj);\n currentBounds.data.widthLimit = parentBounds.data.widthLimit / Math.min(c4BoundaryInRow2, currentBoundaries.length);\n for (let [i, currentBoundary] of currentBoundaries.entries()) {\n let Y = 0;\n currentBoundary.image = { width: 0, height: 0, Y: 0 };\n if (currentBoundary.sprite) {\n currentBoundary.image.width = 48;\n currentBoundary.image.height = 48;\n currentBoundary.image.Y = Y;\n Y = currentBoundary.image.Y + currentBoundary.image.height;\n }\n let currentBoundaryTextWrap = currentBoundary.wrap && conf.wrap;\n let currentBoundaryLabelConf = boundaryFont(conf);\n currentBoundaryLabelConf.fontSize = currentBoundaryLabelConf.fontSize + 2;\n currentBoundaryLabelConf.fontWeight = \"bold\";\n calcC4ShapeTextWH(\n \"label\",\n currentBoundary,\n currentBoundaryTextWrap,\n currentBoundaryLabelConf,\n currentBounds.data.widthLimit\n );\n currentBoundary.label.Y = Y + 8;\n Y = currentBoundary.label.Y + currentBoundary.label.height;\n if (currentBoundary.type && currentBoundary.type.text !== \"\") {\n currentBoundary.type.text = \"[\" + currentBoundary.type.text + \"]\";\n let currentBoundaryTypeConf = boundaryFont(conf);\n calcC4ShapeTextWH(\n \"type\",\n currentBoundary,\n currentBoundaryTextWrap,\n currentBoundaryTypeConf,\n currentBounds.data.widthLimit\n );\n currentBoundary.type.Y = Y + 5;\n Y = currentBoundary.type.Y + currentBoundary.type.height;\n }\n if (currentBoundary.descr && currentBoundary.descr.text !== \"\") {\n let currentBoundaryDescrConf = boundaryFont(conf);\n currentBoundaryDescrConf.fontSize = currentBoundaryDescrConf.fontSize - 2;\n calcC4ShapeTextWH(\n \"descr\",\n currentBoundary,\n currentBoundaryTextWrap,\n currentBoundaryDescrConf,\n currentBounds.data.widthLimit\n );\n currentBoundary.descr.Y = Y + 20;\n Y = currentBoundary.descr.Y + currentBoundary.descr.height;\n }\n if (i == 0 || i % c4BoundaryInRow2 === 0) {\n let _x = parentBounds.data.startx + conf.diagramMarginX;\n let _y = parentBounds.data.stopy + conf.diagramMarginY + Y;\n currentBounds.setData(_x, _x, _y, _y);\n } else {\n let _x = currentBounds.data.stopx !== currentBounds.data.startx ? currentBounds.data.stopx + conf.diagramMarginX : currentBounds.data.startx;\n let _y = currentBounds.data.starty;\n currentBounds.setData(_x, _x, _y, _y);\n }\n currentBounds.name = currentBoundary.alias;\n let currentPersonOrSystemArray = diagObj.db.getC4ShapeArray(currentBoundary.alias);\n let currentPersonOrSystemKeys = diagObj.db.getC4ShapeKeys(currentBoundary.alias);\n if (currentPersonOrSystemKeys.length > 0) {\n drawC4ShapeArray(\n currentBounds,\n diagram2,\n currentPersonOrSystemArray,\n currentPersonOrSystemKeys\n );\n }\n parentBoundaryAlias = currentBoundary.alias;\n let nextCurrentBoundaries = diagObj.db.getBoundaries(parentBoundaryAlias);\n if (nextCurrentBoundaries.length > 0) {\n drawInsideBoundary(\n diagram2,\n parentBoundaryAlias,\n currentBounds,\n nextCurrentBoundaries,\n diagObj\n );\n }\n if (currentBoundary.alias !== \"global\") {\n drawBoundary2(diagram2, currentBoundary, currentBounds);\n }\n parentBounds.data.stopy = Math.max(\n currentBounds.data.stopy + conf.c4ShapeMargin,\n parentBounds.data.stopy\n );\n parentBounds.data.stopx = Math.max(\n currentBounds.data.stopx + conf.c4ShapeMargin,\n parentBounds.data.stopx\n );\n globalBoundaryMaxX = Math.max(globalBoundaryMaxX, parentBounds.data.stopx);\n globalBoundaryMaxY = Math.max(globalBoundaryMaxY, parentBounds.data.stopy);\n }\n}\n__name(drawInsideBoundary, \"drawInsideBoundary\");\nvar draw = /* @__PURE__ */ __name(function(_text, id, _version, diagObj) {\n conf = getConfig().c4;\n const securityLevel = getConfig().securityLevel;\n let sandboxElement;\n if (securityLevel === \"sandbox\") {\n sandboxElement = select(\"#i\" + id);\n }\n const root = securityLevel === \"sandbox\" ? select(sandboxElement.nodes()[0].contentDocument.body) : select(\"body\");\n let db = diagObj.db;\n diagObj.db.setWrap(conf.wrap);\n c4ShapeInRow2 = db.getC4ShapeInRow();\n c4BoundaryInRow2 = db.getC4BoundaryInRow();\n log.debug(`C:${JSON.stringify(conf, null, 2)}`);\n const diagram2 = securityLevel === \"sandbox\" ? root.select(`[id=\"${id}\"]`) : select(`[id=\"${id}\"]`);\n svgDraw_default.insertComputerIcon(diagram2);\n svgDraw_default.insertDatabaseIcon(diagram2);\n svgDraw_default.insertClockIcon(diagram2);\n let screenBounds = new Bounds(diagObj);\n screenBounds.setData(\n conf.diagramMarginX,\n conf.diagramMarginX,\n conf.diagramMarginY,\n conf.diagramMarginY\n );\n screenBounds.data.widthLimit = screen.availWidth;\n globalBoundaryMaxX = conf.diagramMarginX;\n globalBoundaryMaxY = conf.diagramMarginY;\n const title2 = diagObj.db.getTitle();\n let currentBoundaries = diagObj.db.getBoundaries(\"\");\n drawInsideBoundary(diagram2, \"\", screenBounds, currentBoundaries, diagObj);\n svgDraw_default.insertArrowHead(diagram2);\n svgDraw_default.insertArrowEnd(diagram2);\n svgDraw_default.insertArrowCrossHead(diagram2);\n svgDraw_default.insertArrowFilledHead(diagram2);\n drawRels2(diagram2, diagObj.db.getRels(), diagObj.db.getC4Shape, diagObj);\n screenBounds.data.stopx = globalBoundaryMaxX;\n screenBounds.data.stopy = globalBoundaryMaxY;\n const box = screenBounds.data;\n let boxHeight = box.stopy - box.starty;\n let height = boxHeight + 2 * conf.diagramMarginY;\n let boxWidth = box.stopx - box.startx;\n const width = boxWidth + 2 * conf.diagramMarginX;\n if (title2) {\n diagram2.append(\"text\").text(title2).attr(\"x\", (box.stopx - box.startx) / 2 - 4 * conf.diagramMarginX).attr(\"y\", box.starty + conf.diagramMarginY);\n }\n configureSvgSize(diagram2, height, width, conf.useMaxWidth);\n const extraVertForTitle = title2 ? 60 : 0;\n diagram2.attr(\n \"viewBox\",\n box.startx - conf.diagramMarginX + \" -\" + (conf.diagramMarginY + extraVertForTitle) + \" \" + width + \" \" + (height + extraVertForTitle)\n );\n log.debug(`models:`, box);\n}, \"draw\");\nvar c4Renderer_default = {\n drawPersonOrSystemArray: drawC4ShapeArray,\n drawBoundary: drawBoundary2,\n setConf,\n draw\n};\n\n// src/diagrams/c4/styles.js\nvar getStyles = /* @__PURE__ */ __name((options) => `.person {\n stroke: ${options.personBorder};\n fill: ${options.personBkg};\n }\n`, \"getStyles\");\nvar styles_default = getStyles;\n\n// src/diagrams/c4/c4Diagram.ts\nvar diagram = {\n parser: c4Diagram_default,\n db: c4Db_default,\n renderer: c4Renderer_default,\n styles: styles_default,\n init: /* @__PURE__ */ __name(({ c4, wrap }) => {\n c4Renderer_default.setConf(c4);\n c4Db_default.setWrap(wrap);\n }, \"init\")\n};\nexport {\n diagram\n};\n"], + "mappings": "gZAkrDA,IAAAA,GAA4B,WAxpDxBC,IAAU,UAAW,CACvB,IAAIC,EAAoBC,EAAO,SAASC,GAAGC,EAAGC,EAAIC,EAAG,CACnD,IAAKD,EAAKA,GAAM,CAAC,EAAGC,EAAIH,GAAE,OAAQG,IAAKD,EAAGF,GAAEG,CAAC,CAAC,EAAIF,EAAG,CACrD,OAAOC,CACT,EAAG,GAAG,EAAGE,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,GAAM,CAAC,EAAG,EAAE,EAAGC,GAAM,CAAC,EAAG,EAAE,E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AO,IAET,IAAK,IACH,MAAO,IAET,IAAK,IACH,YAAK,MAAM,YAAY,EAChB,GACP,MACF,IAAK,IACH,YAAK,MAAM,QAAQ,EACZ,GACP,MACF,IAAK,IACH,YAAK,MAAM,kBAAkB,EACtB,GACP,MACF,IAAK,IACH,YAAK,MAAM,eAAe,EACnB,GACP,MACF,IAAK,IACH,YAAK,MAAM,YAAY,EAChB,GACP,MACF,IAAK,IACH,YAAK,MAAM,cAAc,EAClB,GACP,MACF,IAAK,IACH,YAAK,MAAM,WAAW,EACf,GACP,MACF,IAAK,IACH,YAAK,MAAM,QAAQ,EACZ,GACP,MACF,IAAK,IACH,YAAK,MAAM,UAAU,EACd,GACP,MACF,IAAK,IACH,YAAK,MAAM,qBAAqB,EACzB,GACP,MACF,IAAK,IACH,YAAK,MAAM,iBAAiB,EACrB,GACP,MACF,IAAK,IACH,YAAK,MAAM,qBAAqB,EACzB,GACP,MACF,IAAK,IACH,YAAK,MAAM,kBAAkB,EACtB,GACP,MACF,IAAK,IACH,YAAK,MAAM,eAAe,EACnB,GACP,MACF,IAAK,IACH,YAAK,MAAM,iBAAiB,EACrB,GACP,MACF,IAAK,IACH,YAAK,MAAM,cAAc,EAClB,GACP,MACF,IAAK,IACH,YAAK,MAAM,WAAW,EACf,GACP,MACF,IAAK,IACH,YAAK,MAAM,oBAAoB,EACxB,GACP,MACF,IAAK,IACH,YAAK,MAAM,qBAAqB,EACzB,GACP,MACF,IAAK,IACH,YAAK,MAAM,kBAAkB,EACtB,GACP,MACF,IAAK,IACH,YAAK,MAAM,eAAe,EACnB,GACP,MACF,IAAK,IACH,YAAK,MAAM,iBAAiB,EACrB,GACP,MACF,IAAK,IACH,YAAK,MAAM,cAAc,EAClB,GACP,MACF,IAAK,IACH,YAAK,MAAM,WAAW,EACf,GACP,MACF,IAAK,IACH,YAAK,MAAM,MAAM,EACV,GACP,MACF,IAAK,IACH,YAAK,MAAM,MAAM,EACV,GACP,MACF,IAAK,IACH,YAAK,MAAM,QA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AG,MAAM,EACLG,GAAqB,CACvB,wBAAyBjE,GACzB,aAAcL,GACd,QAAA1B,GACA,KAAAiF,EACF,EAGIgB,GAA4BlY,EAAQmY,GAAY;AAAA,cACtCA,EAAQ,YAAY;AAAA,YACtBA,EAAQ,SAAS;AAAA;AAAA,EAE1B,WAAW,EACVC,GAAiBF,GAGjBG,GAAU,CACZ,OAAQxQ,GACR,GAAI2F,GACJ,SAAUyK,GACV,OAAQG,GACR,KAAsBpY,EAAO,CAAC,CAAE,GAAAsY,EAAI,KAAAC,CAAK,IAAM,CAC7CN,GAAmB,QAAQK,CAAE,EAC7B9K,GAAa,QAAQ+K,CAAI,CAC3B,EAAG,MAAM,CACX", + "names": ["import_sanitize_url", "parser", "o", "__name", "k", "v", "o2", "l", "$V0", "$V1", "$V2", "$V3", "$V4", "$V5", "$V6", "$V7", "$V8", "$V9", "$Va", "$Vb", "$Vc", "$Vd", "$Ve", "$Vf", "$Vg", "$Vh", "$Vi", "$Vj", "$Vk", "$Vl", "$Vm", "$Vn", "$Vo", "$Vp", "$Vq", "$Vr", "$Vs", "$Vt", "$Vu", "$Vv", "$Vw", "$Vx", "$Vy", "$Vz", "$VA", "$VB", "$VC", "$VD", "$VE", "$VF", "$VG", "$VH", "$VI", "$VJ", "$VK", "$VL", "$VM", "$VN", "$VO", "$VP", "$VQ", "$VR", "$VS", "parser2", "yytext", "yyleng", "yylineno", "yy", "yystate", "$$", "_$", "$0", "kv", "str", "hash", "error", "input", "self", "stack", "tstack", "vstack", "lstack", "table", "recovering", "TERROR", "EOF", "args", "lexer2", "sharedState", "yyloc", "ranges", "popStack", "n", "lex", "token", "symbol", "preErrorSymbol", "state", "action", "a", "r", "yyval", "p", "len", "newState", "expected", "errStr", "lexer", "ch", "lines", "oldLines", "past", "next", "pre", "c2", "match", "indexed_rule", "backup", "tempMatch", "index", "rules", "i", "condition", "yy_", "$avoiding_name_collisions", "YY_START", "YYSTATE", "Parser", "c4Diagram_default", "c4ShapeArray", "boundaryParseStack", "currentBoundaryParse", "parentBoundaryParse", "boundaries", "rels", "title", "wrapEnabled", "c4ShapeInRow", "c4BoundaryInRow", "c4Type", "getC4Type", "setC4Type", "c4TypeParam", "sanitizeText", "getConfig2", "addRel", "type", "from", "to", "label", "techn", "descr", "sprite", "tags", "link", "rel", "old", "rel2", "key", "value", "autoWrap", "addPersonOrSystem", "typeC4Shape", "alias", "personOrSystem", "personOrSystem2", "addContainer", "container", "container2", "addComponent", "component", "component2", "addPersonOrSystemBoundary", "boundary", "boundary2", "addContainerBoundary", "addDeploymentNode", "nodeType", "popBoundaryParseStack", "updateElStyle", "elementName", "bgColor", "fontColor", "borderColor", "shadowing", "shape", "legendText", "legendSprite", "element", "updateRelStyle", "textColor", "lineColor", "offsetX", "offsetY", "updateLayoutConfig", "c4ShapeInRowParam", "c4BoundaryInRowParam", "c4ShapeInRowValue", "c4BoundaryInRowValue", "getC4ShapeInRow", "getC4BoundaryInRow", "getCurrentBoundaryParse", "getParentBoundaryParse", "getC4ShapeArray", "parentBoundary", "getC4Shape", "getC4ShapeKeys", "getBoundaries", "getBoundarys", "getRels", "getTitle", "setWrap", "wrapSetting", "clear", "LINETYPE", "ARROWTYPE", "PLACEMENT", "setTitle", "txt", "c4Db_default", "setAccTitle", "getAccTitle", "getAccDescription", "setAccDescription", "drawRect2", "elem", "rectData", "drawRect", "drawImage", "width", "height", "x", "y", "imageElem", "sanitizedLink", "drawRels", "rels2", "conf2", "relsElem", "strokeColor", "url", "line", "messageConf", "_drawTextCandidateFunc", "drawBoundary", "boundaryElem", "fillColor", "attrsValue", "boundaryConf", "drawC4Shape", "c4Shape", "personImg", "c4ShapeElem", "rect", "getNoteRect", "c4ShapeFontConf", "getC4ShapeFont", "textFontConf", "insertDatabaseIcon", "insertComputerIcon", "insertClockIcon", "insertArrowHead", "insertArrowEnd", "insertArrowFilledHead", "insertDynamicNumber", "insertArrowCrossHead", "marker", "cnf", "byText", "content", "g", "textAttrs", "text", "_setTextAttrs", "byTspan", "fontSize", "fontFamily", "fontWeight", "common_default", "dy", "byFo", "s", "toText", "fromTextAttrsDict", "svgDraw_default", "globalBoundaryMaxX", "globalBoundaryMaxY", "c4ShapeInRow2", "c4BoundaryInRow2", "conf", "Bounds", "diagObj", "setConf", "startx", "stopx", "starty", "stopy", "obj", "val", "fun", "_startx", "_stopx", "_starty", "_stopy", "margin", "assignWithDepth_default", "c4ShapeFont", "boundaryFont", "messageFont", "calcC4ShapeTextWH", "textType", "c4ShapeTextWrap", "textConf", "textLimitWidth", "wrapLabel", "calculateTextHeight", "lineHeight", "calculateTextWidth", "drawBoundary2", "diagram2", "bounds", "boundaryTextWrap", "boundaryLabelConf", "drawC4ShapeArray", "currentBounds", "c4ShapeArray2", "c4ShapeKeys", "Y", "c4ShapeKey", "c4ShapeTypeConf", "c4ShapeLabelConf", "c4ShapeTypeConf2", "c4ShapeTechnConf", "rectHeight", "rectWidth", "c4ShapeDescrConf", "Point", "getIntersectPoint", "fromNode", "endPoint", "x1", "y1", "x2", "y2", "fromCenterX", "fromCenterY", "dx", "tanDYX", "fromDYX", "returnPoint", "getIntersectPoints", "endNode", "endIntersectPoint", "startPoint", "drawRels2", "getC4ShapeObj", "relTextWrap", "relConf", "points", "drawInsideBoundary", "parentBoundaryAlias", "parentBounds", "currentBoundaries", "currentBoundary", "currentBoundaryTextWrap", "currentBoundaryLabelConf", "currentBoundaryTypeConf", "currentBoundaryDescrConf", "_x", "_y", "currentPersonOrSystemArray", "currentPersonOrSystemKeys", "nextCurrentBoundaries", "draw", "_text", "id", "_version", "securityLevel", "sandboxElement", "select_default", "root", "db", "log", "screenBounds", "title2", "box", "configureSvgSize", "extraVertForTitle", "c4Renderer_default", "getStyles", "options", "styles_default", "diagram", "c4", "wrap"] +} diff --git a/docs/website/public/chunk-3EE2TK35.min.js b/docs/website/public/chunk-3EE2TK35.min.js new file mode 100644 index 000000000..71bee5918 --- /dev/null +++ b/docs/website/public/chunk-3EE2TK35.min.js @@ -0,0 +1,86 @@ +import{b as l,c as di,d as M,e as ui}from"./chunk-6TVUEPFY.min.js";var Nt={min:{r:0,g:0,b:0,s:0,l:0,a:0},max:{r:255,g:255,b:255,h:360,s:100,l:100,a:1},clamp:{r:t=>t>=255?255:t<0?0:t,g:t=>t>=255?255:t<0?0:t,b:t=>t>=255?255:t<0?0:t,h:t=>t%360,s:t=>t>=100?100:t<0?0:t,l:t=>t>=100?100:t<0?0:t,a:t=>t>=1?1:t<0?0:t},toLinear:t=>{let e=t/255;return t>.03928?Math.pow((e+.055)/1.055,2.4):e/12.92},hue2rgb:(t,e,i)=>(i<0&&(i+=1),i>1&&(i-=1),i<.16666666666666666?t+(e-t)*6*i:i<.5?e:i<.6666666666666666?t+(e-t)*(.6666666666666666-i)*6:t),hsl2rgb:({h:t,s:e,l:i},a)=>{if(!e)return i*2.55;t/=360,e/=100,i/=100;let s=i<.5?i*(1+e):i+e-i*e,c=2*i-s;switch(a){case"r":return Nt.hue2rgb(c,s,t+.3333333333333333)*255;case"g":return Nt.hue2rgb(c,s,t)*255;case"b":return Nt.hue2rgb(c,s,t-.3333333333333333)*255}},rgb2hsl:({r:t,g:e,b:i},a)=>{t/=255,e/=255,i/=255;let s=Math.max(t,e,i),c=Math.min(t,e,i),f=(s+c)/2;if(a==="l")return f*100;if(s===c)return 0;let x=s-c,_=f>.5?x/(2-s-c):x/(s+c);if(a==="s")return _*100;switch(s){case t:return((e-i)/x+(ee>i?Math.min(e,Math.max(i,t)):Math.min(i,Math.max(e,t)),round:t=>Math.round(t*1e10)/1e10},Ci=gr;var Cr={dec2hex:t=>{let e=Math.round(t).toString(16);return e.length>1?e:`0${e}`}},mi=Cr;var mr={channel:gi,lang:Ci,unit:mi},C=mr;var K={};for(let t=0;t<=255;t++)K[t]=C.unit.dec2hex(t);var k={ALL:0,RGB:1,HSL:2};var Te=class{constructor(){this.type=k.ALL}get(){return this.type}set(e){if(this.type&&this.type!==e)throw new Error("Cannot change both RGB and HSL channels at the same time");this.type=e}reset(){this.type=k.ALL}is(e){return this.type===e}},pi=Te;var ke=class{constructor(e,i){this.color=i,this.changed=!1,this.data=e,this.type=new pi}set(e,i){return this.color=i,this.changed=!1,this.data=e,this.type.type=k.ALL,this}_ensureHSL(){let e=this.data,{h:i,s:a,l:s}=e;i===void 0&&(e.h=C.channel.rgb2hsl(e,"h")),a===void 0&&(e.s=C.channel.rgb2hsl(e,"s")),s===void 0&&(e.l=C.channel.rgb2hsl(e,"l"))}_ensureRGB(){let e=this.data,{r:i,g:a,b:s}=e;i===void 0&&(e.r=C.channel.hsl2rgb(e,"r")),a===void 0&&(e.g=C.channel.hsl2rgb(e,"g")),s===void 0&&(e.b=C.channel.hsl2rgb(e,"b"))}get r(){let e=this.data,i=e.r;return!this.type.is(k.HSL)&&i!==void 0?i:(this._ensureHSL(),C.channel.hsl2rgb(e,"r"))}get g(){let e=this.data,i=e.g;return!this.type.is(k.HSL)&&i!==void 0?i:(this._ensureHSL(),C.channel.hsl2rgb(e,"g"))}get b(){let e=this.data,i=e.b;return!this.type.is(k.HSL)&&i!==void 0?i:(this._ensureHSL(),C.channel.hsl2rgb(e,"b"))}get h(){let e=this.data,i=e.h;return!this.type.is(k.RGB)&&i!==void 0?i:(this._ensureRGB(),C.channel.rgb2hsl(e,"h"))}get s(){let e=this.data,i=e.s;return!this.type.is(k.RGB)&&i!==void 0?i:(this._ensureRGB(),C.channel.rgb2hsl(e,"s"))}get l(){let e=this.data,i=e.l;return!this.type.is(k.RGB)&&i!==void 0?i:(this._ensureRGB(),C.channel.rgb2hsl(e,"l"))}get a(){return this.data.a}set r(e){this.type.set(k.RGB),this.changed=!0,this.data.r=e}set g(e){this.type.set(k.RGB),this.changed=!0,this.data.g=e}set b(e){this.type.set(k.RGB),this.changed=!0,this.data.b=e}set h(e){this.type.set(k.HSL),this.changed=!0,this.data.h=e}set s(e){this.type.set(k.HSL),this.changed=!0,this.data.s=e}set l(e){this.type.set(k.HSL),this.changed=!0,this.data.l=e}set a(e){this.changed=!0,this.data.a=e}},fi=ke;var pr=new fi({r:0,g:0,b:0,a:0},"transparent"),tt=pr;var xi={re:/^#((?:[a-f0-9]{2}){2,4}|[a-f0-9]{3})$/i,parse:t=>{if(t.charCodeAt(0)!==35)return;let e=t.match(xi.re);if(!e)return;let i=e[1],a=parseInt(i,16),s=i.length,c=s%4===0,f=s>4,x=f?1:17,_=f?8:4,L=c?0:-1,H=f?255:15;return tt.set({r:(a>>_*(L+3)&H)*x,g:(a>>_*(L+2)&H)*x,b:(a>>_*(L+1)&H)*x,a:c?(a&H)*x/255:1},t)},stringify:t=>{let{r:e,g:i,b:a,a:s}=t;return s<1?`#${K[Math.round(e)]}${K[Math.round(i)]}${K[Math.round(a)]}${K[Math.round(s*255)]}`:`#${K[Math.round(e)]}${K[Math.round(i)]}${K[Math.round(a)]}`}},rt=xi;var Ht={re:/^hsla?\(\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?(?:deg|grad|rad|turn)?)\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?%)\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?%)(?:\s*?(?:,|\/)\s*?\+?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?(%)?))?\s*?\)$/i,hueRe:/^(.+?)(deg|grad|rad|turn)$/i,_hue2deg:t=>{let e=t.match(Ht.hueRe);if(e){let[,i,a]=e;switch(a){case"grad":return C.channel.clamp.h(parseFloat(i)*.9);case"rad":return C.channel.clamp.h(parseFloat(i)*180/Math.PI);case"turn":return C.channel.clamp.h(parseFloat(i)*360)}}return C.channel.clamp.h(parseFloat(t))},parse:t=>{let e=t.charCodeAt(0);if(e!==104&&e!==72)return;let i=t.match(Ht.re);if(!i)return;let[,a,s,c,f,x]=i;return tt.set({h:Ht._hue2deg(a),s:C.channel.clamp.s(parseFloat(s)),l:C.channel.clamp.l(parseFloat(c)),a:f?C.channel.clamp.a(x?parseFloat(f)/100:parseFloat(f)):1},t)},stringify:t=>{let{h:e,s:i,l:a,a:s}=t;return s<1?`hsla(${C.lang.round(e)}, ${C.lang.round(i)}%, ${C.lang.round(a)}%, ${s})`:`hsl(${C.lang.round(e)}, ${C.lang.round(i)}%, ${C.lang.round(a)}%)`}},Ft=Ht;var Ut={colors:{aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyanaqua:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",transparent:"#00000000",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},parse:t=>{t=t.toLowerCase();let e=Ut.colors[t];if(e)return rt.parse(e)},stringify:t=>{let e=rt.stringify(t);for(let i in Ut.colors)if(Ut.colors[i]===e)return i}},Be=Ut;var yi={re:/^rgba?\(\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))(?:\s*?(?:,|\/)\s*?\+?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?)))?\s*?\)$/i,parse:t=>{let e=t.charCodeAt(0);if(e!==114&&e!==82)return;let i=t.match(yi.re);if(!i)return;let[,a,s,c,f,x,_,L,H]=i;return tt.set({r:C.channel.clamp.r(s?parseFloat(a)*2.55:parseFloat(a)),g:C.channel.clamp.g(f?parseFloat(c)*2.55:parseFloat(c)),b:C.channel.clamp.b(_?parseFloat(x)*2.55:parseFloat(x)),a:L?C.channel.clamp.a(H?parseFloat(L)/100:parseFloat(L)):1},t)},stringify:t=>{let{r:e,g:i,b:a,a:s}=t;return s<1?`rgba(${C.lang.round(e)}, ${C.lang.round(i)}, ${C.lang.round(a)}, ${C.lang.round(s)})`:`rgb(${C.lang.round(e)}, ${C.lang.round(i)}, ${C.lang.round(a)})`}},_t=yi;var fr={format:{keyword:Be,hex:rt,rgb:_t,rgba:_t,hsl:Ft,hsla:Ft},parse:t=>{if(typeof t!="string")return t;let e=rt.parse(t)||_t.parse(t)||Ft.parse(t)||Be.parse(t);if(e)return e;throw new Error(`Unsupported color format: "${t}"`)},stringify:t=>!t.changed&&t.color?t.color:t.type.is(k.HSL)||t.data.r===void 0?Ft.stringify(t):t.a<1||!Number.isInteger(t.r)||!Number.isInteger(t.g)||!Number.isInteger(t.b)?_t.stringify(t):rt.stringify(t)},B=fr;var xr=(t,e)=>{let i=B.parse(t);for(let a in e)i[a]=C.channel.clamp[a](e[a]);return B.stringify(i)},Gt=xr;var yr=(t,e,i=0,a=1)=>{if(typeof t!="number")return Gt(t,{a:e});let s=tt.set({r:C.channel.clamp.r(t),g:C.channel.clamp.g(e),b:C.channel.clamp.b(i),a:C.channel.clamp.a(a)});return B.stringify(s)},Z=yr;var br=(t,e)=>C.lang.round(B.parse(t)[e]),Tr=br;var kr=t=>{let{r:e,g:i,b:a}=B.parse(t),s=.2126*C.channel.toLinear(e)+.7152*C.channel.toLinear(i)+.0722*C.channel.toLinear(a);return C.lang.round(s)},bi=kr;var Br=t=>bi(t)>=.5,Ti=Br;var Sr=t=>!Ti(t),U=Sr;var Fr=(t,e,i)=>{let a=B.parse(t),s=a[e],c=C.channel.clamp[e](s+i);return s!==c&&(a[e]=c),B.stringify(a)},$t=Fr;var _r=(t,e)=>$t(t,"l",e),d=_r;var Lr=(t,e)=>$t(t,"l",-e),u=Lr;var Ar=(t,e)=>{let i=B.parse(t),a={};for(let s in e)e[s]&&(a[s]=i[s]+e[s]);return Gt(t,a)},o=Ar;var Er=(t,e,i=50)=>{let{r:a,g:s,b:c,a:f}=B.parse(t),{r:x,g:_,b:L,a:H}=B.parse(e),yt=i/100,at=yt*2-1,Q=f-H,lt=((at*Q===-1?at:(at+Q)/(1+at*Q))+1)/2,bt=1-lt,oe=a*lt+x*bt,ae=s*lt+_*bt,nt=c*lt+L*bt,A=f*yt+H*(1-yt);return Z(oe,ae,nt,A)},ki=Er;var vr=(t,e=100)=>{let i=B.parse(t);return i.r=255-i.r,i.g=255-i.g,i.b=255-i.b,ki(i,t,e)},h=vr;var{entries:Oi,setPrototypeOf:Bi,isFrozen:Or,getPrototypeOf:Mr,getOwnPropertyDescriptor:wr}=Object,{freeze:z,seal:N,create:Mi}=Object,{apply:ve,construct:Oe}=typeof Reflect<"u"&&Reflect;z||(z=function(e){return e});N||(N=function(e){return e});ve||(ve=function(e,i){for(var a=arguments.length,s=new Array(a>2?a-2:0),c=2;c1?i-1:0),s=1;s1?i-1:0),s=1;s2&&arguments[2]!==void 0?arguments[2]:Yt;Bi&&Bi(t,null);let a=e.length;for(;a--;){let s=e[a];if(typeof s=="string"){let c=i(s);c!==s&&(Or(e)||(e[a]=c),s=c)}t[s]=!0}return t}function Wr(t){for(let e=0;e/gm),Gr=N(/\$\{[\w\W]*/gm),$r=N(/^data-[\-\w.\u00B7-\uFFFF]+$/),jr=N(/^aria-[\-\w]+$/),wi=N(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Vr=N(/^(?:\w+script|data):/i),Yr=N(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Di=N(/^html$/i),Xr=N(/^[a-z][.\w]*(-[.\w]+)+$/i),Ei=Object.freeze({__proto__:null,ARIA_ATTR:jr,ATTR_WHITESPACE:Yr,CUSTOM_ELEMENT:Xr,DATA_ATTR:$r,DOCTYPE_NAME:Di,ERB_EXPR:Ur,IS_ALLOWED_URI:wi,IS_SCRIPT_OR_DATA:Vr,MUSTACHE_EXPR:Hr,TMPLIT_EXPR:Gr}),Ot={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Kr=function(){return typeof window>"u"?null:window},Zr=function(e,i){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let a=null,s="data-tt-policy-suffix";i&&i.hasAttribute(s)&&(a=i.getAttribute(s));let c="dompurify"+(a?"#"+a:"");try{return e.createPolicy(c,{createHTML(f){return f},createScriptURL(f){return f}})}catch{return console.warn("TrustedTypes policy "+c+" could not be created."),null}},vi=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Ii(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Kr(),e=m=>Ii(m);if(e.version="3.2.7",e.removed=[],!t||!t.document||t.document.nodeType!==Ot.document||!t.Element)return e.isSupported=!1,e;let{document:i}=t,a=i,s=a.currentScript,{DocumentFragment:c,HTMLTemplateElement:f,Node:x,Element:_,NodeFilter:L,NamedNodeMap:H=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:yt,DOMParser:at,trustedTypes:Q}=t,st=_.prototype,lt=vt(st,"cloneNode"),bt=vt(st,"remove"),oe=vt(st,"nextSibling"),ae=vt(st,"childNodes"),nt=vt(st,"parentNode");if(typeof f=="function"){let m=i.createElement("template");m.content&&m.content.ownerDocument&&(i=m.content.ownerDocument)}let A,Tt="",{implementation:se,createNodeIterator:Zi,createDocumentFragment:Ji,getElementsByTagName:Qi}=i,{importNode:tr}=a,D=vi();e.isSupported=typeof Oi=="function"&&typeof nt=="function"&&se&&se.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:le,ERB_EXPR:ne,TMPLIT_EXPR:he,DATA_ATTR:er,ARIA_ATTR:ir,IS_SCRIPT_OR_DATA:rr,ATTR_WHITESPACE:Pe,CUSTOM_ELEMENT:or}=Ei,{IS_ALLOWED_URI:Ne}=Ei,S=null,He=p({},[...Fi,..._e,...Le,...Ae,..._i]),E=null,Ue=p({},[...Li,...Ee,...Ai,...Vt]),b=Object.seal(Mi(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),kt=null,ce=null,Ge=!0,de=!0,$e=!1,je=!0,ht=!1,Dt=!0,et=!1,ue=!1,ge=!1,ct=!1,It=!1,zt=!1,Ve=!0,Ye=!1,ar="user-content-",Ce=!0,Bt=!1,dt={},ut=null,Xe=p({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),Ke=null,Ze=p({},["audio","video","img","source","image","track"]),me=null,Je=p({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),qt="http://www.w3.org/1998/Math/MathML",Rt="http://www.w3.org/2000/svg",V="http://www.w3.org/1999/xhtml",gt=V,pe=!1,fe=null,sr=p({},[qt,Rt,V],Se),Wt=p({},["mi","mo","mn","ms","mtext"]),Pt=p({},["annotation-xml"]),lr=p({},["title","style","font","a","script"]),St=null,nr=["application/xhtml+xml","text/html"],hr="text/html",F=null,Ct=null,cr=i.createElement("form"),Qe=function(r){return r instanceof RegExp||r instanceof Function},xe=function(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Ct&&Ct===r)){if((!r||typeof r!="object")&&(r={}),r=J(r),St=nr.indexOf(r.PARSER_MEDIA_TYPE)===-1?hr:r.PARSER_MEDIA_TYPE,F=St==="application/xhtml+xml"?Se:Yt,S=G(r,"ALLOWED_TAGS")?p({},r.ALLOWED_TAGS,F):He,E=G(r,"ALLOWED_ATTR")?p({},r.ALLOWED_ATTR,F):Ue,fe=G(r,"ALLOWED_NAMESPACES")?p({},r.ALLOWED_NAMESPACES,Se):sr,me=G(r,"ADD_URI_SAFE_ATTR")?p(J(Je),r.ADD_URI_SAFE_ATTR,F):Je,Ke=G(r,"ADD_DATA_URI_TAGS")?p(J(Ze),r.ADD_DATA_URI_TAGS,F):Ze,ut=G(r,"FORBID_CONTENTS")?p({},r.FORBID_CONTENTS,F):Xe,kt=G(r,"FORBID_TAGS")?p({},r.FORBID_TAGS,F):J({}),ce=G(r,"FORBID_ATTR")?p({},r.FORBID_ATTR,F):J({}),dt=G(r,"USE_PROFILES")?r.USE_PROFILES:!1,Ge=r.ALLOW_ARIA_ATTR!==!1,de=r.ALLOW_DATA_ATTR!==!1,$e=r.ALLOW_UNKNOWN_PROTOCOLS||!1,je=r.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ht=r.SAFE_FOR_TEMPLATES||!1,Dt=r.SAFE_FOR_XML!==!1,et=r.WHOLE_DOCUMENT||!1,ct=r.RETURN_DOM||!1,It=r.RETURN_DOM_FRAGMENT||!1,zt=r.RETURN_TRUSTED_TYPE||!1,ge=r.FORCE_BODY||!1,Ve=r.SANITIZE_DOM!==!1,Ye=r.SANITIZE_NAMED_PROPS||!1,Ce=r.KEEP_CONTENT!==!1,Bt=r.IN_PLACE||!1,Ne=r.ALLOWED_URI_REGEXP||wi,gt=r.NAMESPACE||V,Wt=r.MATHML_TEXT_INTEGRATION_POINTS||Wt,Pt=r.HTML_INTEGRATION_POINTS||Pt,b=r.CUSTOM_ELEMENT_HANDLING||{},r.CUSTOM_ELEMENT_HANDLING&&Qe(r.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(b.tagNameCheck=r.CUSTOM_ELEMENT_HANDLING.tagNameCheck),r.CUSTOM_ELEMENT_HANDLING&&Qe(r.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(b.attributeNameCheck=r.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),r.CUSTOM_ELEMENT_HANDLING&&typeof r.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(b.allowCustomizedBuiltInElements=r.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ht&&(de=!1),It&&(ct=!0),dt&&(S=p({},_i),E=[],dt.html===!0&&(p(S,Fi),p(E,Li)),dt.svg===!0&&(p(S,_e),p(E,Ee),p(E,Vt)),dt.svgFilters===!0&&(p(S,Le),p(E,Ee),p(E,Vt)),dt.mathMl===!0&&(p(S,Ae),p(E,Ai),p(E,Vt))),r.ADD_TAGS&&(S===He&&(S=J(S)),p(S,r.ADD_TAGS,F)),r.ADD_ATTR&&(E===Ue&&(E=J(E)),p(E,r.ADD_ATTR,F)),r.ADD_URI_SAFE_ATTR&&p(me,r.ADD_URI_SAFE_ATTR,F),r.FORBID_CONTENTS&&(ut===Xe&&(ut=J(ut)),p(ut,r.FORBID_CONTENTS,F)),Ce&&(S["#text"]=!0),et&&p(S,["html","head","body"]),S.table&&(p(S,["tbody"]),delete kt.tbody),r.TRUSTED_TYPES_POLICY){if(typeof r.TRUSTED_TYPES_POLICY.createHTML!="function")throw Et('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof r.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Et('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');A=r.TRUSTED_TYPES_POLICY,Tt=A.createHTML("")}else A===void 0&&(A=Zr(Q,s)),A!==null&&typeof Tt=="string"&&(Tt=A.createHTML(""));z&&z(r),Ct=r}},ti=p({},[..._e,...Le,...Pr]),ei=p({},[...Ae,...Nr]),dr=function(r){let n=nt(r);(!n||!n.tagName)&&(n={namespaceURI:gt,tagName:"template"});let g=Yt(r.tagName),y=Yt(n.tagName);return fe[r.namespaceURI]?r.namespaceURI===Rt?n.namespaceURI===V?g==="svg":n.namespaceURI===qt?g==="svg"&&(y==="annotation-xml"||Wt[y]):!!ti[g]:r.namespaceURI===qt?n.namespaceURI===V?g==="math":n.namespaceURI===Rt?g==="math"&&Pt[y]:!!ei[g]:r.namespaceURI===V?n.namespaceURI===Rt&&!Pt[y]||n.namespaceURI===qt&&!Wt[y]?!1:!ei[g]&&(lr[g]||!ti[g]):!!(St==="application/xhtml+xml"&&fe[r.namespaceURI]):!1},$=function(r){Lt(e.removed,{element:r});try{nt(r).removeChild(r)}catch{bt(r)}},it=function(r,n){try{Lt(e.removed,{attribute:n.getAttributeNode(r),from:n})}catch{Lt(e.removed,{attribute:null,from:n})}if(n.removeAttribute(r),r==="is")if(ct||It)try{$(n)}catch{}else try{n.setAttribute(r,"")}catch{}},ii=function(r){let n=null,g=null;if(ge)r=""+r;else{let T=Fe(r,/^[\r\n\t ]+/);g=T&&T[0]}St==="application/xhtml+xml"&>===V&&(r=''+r+"");let y=A?A.createHTML(r):r;if(gt===V)try{n=new at().parseFromString(y,St)}catch{}if(!n||!n.documentElement){n=se.createDocument(gt,"template",null);try{n.documentElement.innerHTML=pe?Tt:y}catch{}}let O=n.body||n.documentElement;return r&&g&&O.insertBefore(i.createTextNode(g),O.childNodes[0]||null),gt===V?Qi.call(n,et?"html":"body")[0]:et?n.documentElement:O},ri=function(r){return Zi.call(r.ownerDocument||r,r,L.SHOW_ELEMENT|L.SHOW_COMMENT|L.SHOW_TEXT|L.SHOW_PROCESSING_INSTRUCTION|L.SHOW_CDATA_SECTION,null)},ye=function(r){return r instanceof yt&&(typeof r.nodeName!="string"||typeof r.textContent!="string"||typeof r.removeChild!="function"||!(r.attributes instanceof H)||typeof r.removeAttribute!="function"||typeof r.setAttribute!="function"||typeof r.namespaceURI!="string"||typeof r.insertBefore!="function"||typeof r.hasChildNodes!="function")},oi=function(r){return typeof x=="function"&&r instanceof x};function Y(m,r,n){jt(m,g=>{g.call(e,r,n,Ct)})}let ai=function(r){let n=null;if(Y(D.beforeSanitizeElements,r,null),ye(r))return $(r),!0;let g=F(r.nodeName);if(Y(D.uponSanitizeElement,r,{tagName:g,allowedTags:S}),Dt&&r.hasChildNodes()&&!oi(r.firstElementChild)&&I(/<[/\w!]/g,r.innerHTML)&&I(/<[/\w!]/g,r.textContent)||r.nodeType===Ot.progressingInstruction||Dt&&r.nodeType===Ot.comment&&I(/<[/\w]/g,r.data))return $(r),!0;if(!S[g]||kt[g]){if(!kt[g]&&li(g)&&(b.tagNameCheck instanceof RegExp&&I(b.tagNameCheck,g)||b.tagNameCheck instanceof Function&&b.tagNameCheck(g)))return!1;if(Ce&&!ut[g]){let y=nt(r)||r.parentNode,O=ae(r)||r.childNodes;if(O&&y){let T=O.length;for(let W=T-1;W>=0;--W){let X=lt(O[W],!0);X.__removalCount=(r.__removalCount||0)+1,y.insertBefore(X,oe(r))}}}return $(r),!0}return r instanceof _&&!dr(r)||(g==="noscript"||g==="noembed"||g==="noframes")&&I(/<\/no(script|embed|frames)/i,r.innerHTML)?($(r),!0):(ht&&r.nodeType===Ot.text&&(n=r.textContent,jt([le,ne,he],y=>{n=At(n,y," ")}),r.textContent!==n&&(Lt(e.removed,{element:r.cloneNode()}),r.textContent=n)),Y(D.afterSanitizeElements,r,null),!1)},si=function(r,n,g){if(Ve&&(n==="id"||n==="name")&&(g in i||g in cr))return!1;if(!(de&&!ce[n]&&I(er,n))){if(!(Ge&&I(ir,n))){if(!E[n]||ce[n]){if(!(li(r)&&(b.tagNameCheck instanceof RegExp&&I(b.tagNameCheck,r)||b.tagNameCheck instanceof Function&&b.tagNameCheck(r))&&(b.attributeNameCheck instanceof RegExp&&I(b.attributeNameCheck,n)||b.attributeNameCheck instanceof Function&&b.attributeNameCheck(n,r))||n==="is"&&b.allowCustomizedBuiltInElements&&(b.tagNameCheck instanceof RegExp&&I(b.tagNameCheck,g)||b.tagNameCheck instanceof Function&&b.tagNameCheck(g))))return!1}else if(!me[n]){if(!I(Ne,At(g,Pe,""))){if(!((n==="src"||n==="xlink:href"||n==="href")&&r!=="script"&&zr(g,"data:")===0&&Ke[r])){if(!($e&&!I(rr,At(g,Pe,"")))){if(g)return!1}}}}}}return!0},li=function(r){return r!=="annotation-xml"&&Fe(r,or)},ni=function(r){Y(D.beforeSanitizeAttributes,r,null);let{attributes:n}=r;if(!n||ye(r))return;let g={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:E,forceKeepAttr:void 0},y=n.length;for(;y--;){let O=n[y],{name:T,namespaceURI:W,value:X}=O,mt=F(T),be=X,v=T==="value"?be:qr(be);if(g.attrName=mt,g.attrValue=v,g.keepAttr=!0,g.forceKeepAttr=void 0,Y(D.uponSanitizeAttribute,r,g),v=g.attrValue,Ye&&(mt==="id"||mt==="name")&&(it(T,r),v=ar+v),Dt&&I(/((--!?|])>)|<\/(style|title|textarea)/i,v)){it(T,r);continue}if(mt==="attributename"&&Fe(v,"href")){it(T,r);continue}if(g.forceKeepAttr)continue;if(!g.keepAttr){it(T,r);continue}if(!je&&I(/\/>/i,v)){it(T,r);continue}ht&&jt([le,ne,he],ci=>{v=At(v,ci," ")});let hi=F(r.nodeName);if(!si(hi,mt,v)){it(T,r);continue}if(A&&typeof Q=="object"&&typeof Q.getAttributeType=="function"&&!W)switch(Q.getAttributeType(hi,mt)){case"TrustedHTML":{v=A.createHTML(v);break}case"TrustedScriptURL":{v=A.createScriptURL(v);break}}if(v!==be)try{W?r.setAttributeNS(W,T,v):r.setAttribute(T,v),ye(r)?$(r):Si(e.removed)}catch{it(T,r)}}Y(D.afterSanitizeAttributes,r,null)},ur=function m(r){let n=null,g=ri(r);for(Y(D.beforeSanitizeShadowDOM,r,null);n=g.nextNode();)Y(D.uponSanitizeShadowNode,n,null),ai(n),ni(n),n.content instanceof c&&m(n.content);Y(D.afterSanitizeShadowDOM,r,null)};return e.sanitize=function(m){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=null,g=null,y=null,O=null;if(pe=!m,pe&&(m=""),typeof m!="string"&&!oi(m))if(typeof m.toString=="function"){if(m=m.toString(),typeof m!="string")throw Et("dirty is not a string, aborting")}else throw Et("toString is not a function");if(!e.isSupported)return m;if(ue||xe(r),e.removed=[],typeof m=="string"&&(Bt=!1),Bt){if(m.nodeName){let X=F(m.nodeName);if(!S[X]||kt[X])throw Et("root node is forbidden and cannot be sanitized in-place")}}else if(m instanceof x)n=ii(""),g=n.ownerDocument.importNode(m,!0),g.nodeType===Ot.element&&g.nodeName==="BODY"||g.nodeName==="HTML"?n=g:n.appendChild(g);else{if(!ct&&!ht&&!et&&m.indexOf("<")===-1)return A&&zt?A.createHTML(m):m;if(n=ii(m),!n)return ct?null:zt?Tt:""}n&&ge&&$(n.firstChild);let T=ri(Bt?m:n);for(;y=T.nextNode();)ai(y),ni(y),y.content instanceof c&&ur(y.content);if(Bt)return m;if(ct){if(It)for(O=Ji.call(n.ownerDocument);n.firstChild;)O.appendChild(n.firstChild);else O=n;return(E.shadowroot||E.shadowrootmode)&&(O=tr.call(a,O,!0)),O}let W=et?n.outerHTML:n.innerHTML;return et&&S["!doctype"]&&n.ownerDocument&&n.ownerDocument.doctype&&n.ownerDocument.doctype.name&&I(Di,n.ownerDocument.doctype.name)&&(W=" +`+W),ht&&jt([le,ne,he],X=>{W=At(W,X," ")}),A&&zt?A.createHTML(W):W},e.setConfig=function(){let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};xe(m),ue=!0},e.clearConfig=function(){Ct=null,ue=!1},e.isValidAttribute=function(m,r,n){Ct||xe({});let g=F(m),y=F(r);return si(g,y,n)},e.addHook=function(m,r){typeof r=="function"&&Lt(D[m],r)},e.removeHook=function(m,r){if(r!==void 0){let n=Dr(D[m],r);return n===-1?void 0:Ir(D[m],n,1)[0]}return Si(D[m])},e.removeHooks=function(m){D[m]=[]},e.removeAllHooks=function(){D=vi()},e}var pt=Ii();var Jr=/^-{3}\s*[\n\r](.*?)[\n\r]-{3}\s*[\n\r]+/s,Qr=/%{2}{\s*(?:(\w+)\s*:|(\w+))\s*(?:(\w+)|((?:(?!}%{2}).|\r?\n)*))?\s*(?:}%{2})?/gi,to=/\s*%%.*\n/gm,eo=class extends Error{static{l(this,"UnknownDiagramError")}constructor(t){super(t),this.name="UnknownDiagramError"}},Zt={},Ts=l(function(t,e){t=t.replace(Jr,"").replace(Qr,"").replace(to,` +`);for(let[i,{detector:a}]of Object.entries(Zt))if(a(t,e))return i;throw new eo(`No diagram type detected matching given configuration for text: ${t}`)},"detectType"),ks=l((...t)=>{for(let{id:e,detector:i,loader:a}of t)Ni(e,i,a)},"registerLazyLoadedDiagrams"),Ni=l((t,e,i)=>{Zt[t]&&M.warn(`Detector with key ${t} already exists. Overwriting.`),Zt[t]={detector:e,loader:i},M.debug(`Detector with key ${t} added${i?" with loader":""}`)},"addDetector"),Bs=l(t=>Zt[t].loader,"getDiagramLoader"),Me=l((t,e,{depth:i=2,clobber:a=!1}={})=>{let s={depth:i,clobber:a};return Array.isArray(e)&&!Array.isArray(t)?(e.forEach(c=>Me(t,c,s)),t):Array.isArray(e)&&Array.isArray(t)?(e.forEach(c=>{t.includes(c)||t.push(c)}),t):t===void 0||i<=0?t!=null&&typeof t=="object"&&typeof e=="object"?Object.assign(t,e):e:(e!==void 0&&typeof t=="object"&&typeof e=="object"&&Object.keys(e).forEach(c=>{typeof e[c]=="object"&&(t[c]===void 0||typeof t[c]=="object")?(t[c]===void 0&&(t[c]=Array.isArray(e[c])?[]:{}),t[c]=Me(t[c],e[c],{depth:i-1,clobber:a})):(a||typeof t[c]!="object"&&typeof e[c]!="object")&&(t[c]=e[c])}),t)},"assignWithDepth"),w=Me,te="#ffffff",ee="#f2f2f2",R=l((t,e)=>e?o(t,{s:-40,l:10}):o(t,{s:-40,l:-10}),"mkBorder"),io=class{static{l(this,"Theme")}constructor(){this.background="#f4f4f4",this.primaryColor="#fff4dd",this.noteBkgColor="#fff5ad",this.noteTextColor="#333",this.THEME_COLOR_LIMIT=12,this.fontFamily='"trebuchet ms", verdana, arial, sans-serif',this.fontSize="16px"}updateColors(){if(this.primaryTextColor=this.primaryTextColor||(this.darkMode?"#eee":"#333"),this.secondaryColor=this.secondaryColor||o(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||o(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||R(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||R(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||R(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||R(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||"#fff5ad",this.noteTextColor=this.noteTextColor||"#333",this.secondaryTextColor=this.secondaryTextColor||h(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||h(this.tertiaryColor),this.lineColor=this.lineColor||h(this.background),this.arrowheadColor=this.arrowheadColor||h(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.primaryBorderColor,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?u(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||u(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||h(this.lineColor),this.sectionBkgColor=this.sectionBkgColor||this.tertiaryColor,this.altSectionBkgColor=this.altSectionBkgColor||"white",this.sectionBkgColor=this.sectionBkgColor||this.secondaryColor,this.sectionBkgColor2=this.sectionBkgColor2||this.primaryColor,this.excludeBkgColor=this.excludeBkgColor||"#eeeeee",this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||this.primaryColor,this.activeTaskBorderColor=this.activeTaskBorderColor||this.primaryColor,this.activeTaskBkgColor=this.activeTaskBkgColor||d(this.primaryColor,23),this.gridColor=this.gridColor||"lightgrey",this.doneTaskBkgColor=this.doneTaskBkgColor||"lightgrey",this.doneTaskBorderColor=this.doneTaskBorderColor||"grey",this.critBorderColor=this.critBorderColor||"#ff8888",this.critBkgColor=this.critBkgColor||"red",this.todayLineColor=this.todayLineColor||"red",this.vertLineColor=this.vertLineColor||"navy",this.taskTextColor=this.taskTextColor||this.textColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||"#003163",this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.darkMode?(this.rowOdd=this.rowOdd||u(this.mainBkg,5)||"#ffffff",this.rowEven=this.rowEven||u(this.mainBkg,10)):(this.rowOdd=this.rowOdd||d(this.mainBkg,75)||"#ffffff",this.rowEven=this.rowEven||d(this.mainBkg,5)),this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||this.tertiaryColor,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||o(this.primaryColor,{h:30}),this.cScale4=this.cScale4||o(this.primaryColor,{h:60}),this.cScale5=this.cScale5||o(this.primaryColor,{h:90}),this.cScale6=this.cScale6||o(this.primaryColor,{h:120}),this.cScale7=this.cScale7||o(this.primaryColor,{h:150}),this.cScale8=this.cScale8||o(this.primaryColor,{h:210,l:150}),this.cScale9=this.cScale9||o(this.primaryColor,{h:270}),this.cScale10=this.cScale10||o(this.primaryColor,{h:300}),this.cScale11=this.cScale11||o(this.primaryColor,{h:330}),this.darkMode)for(let e=0;e{this[i]=t[i]}),this.updateColors(),e.forEach(i=>{this[i]=t[i]})}},ro=l(t=>{let e=new io;return e.calculate(t),e},"getThemeVariables"),oo=class{static{l(this,"Theme")}constructor(){this.background="#333",this.primaryColor="#1f2020",this.secondaryColor=d(this.primaryColor,16),this.tertiaryColor=o(this.primaryColor,{h:-160}),this.primaryBorderColor=h(this.background),this.secondaryBorderColor=R(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=R(this.tertiaryColor,this.darkMode),this.primaryTextColor=h(this.primaryColor),this.secondaryTextColor=h(this.secondaryColor),this.tertiaryTextColor=h(this.tertiaryColor),this.lineColor=h(this.background),this.textColor=h(this.background),this.mainBkg="#1f2020",this.secondBkg="calculated",this.mainContrastColor="lightgrey",this.darkTextColor=d(h("#323D47"),10),this.lineColor="calculated",this.border1="#ccc",this.border2=Z(255,255,255,.25),this.arrowheadColor="calculated",this.fontFamily='"trebuchet ms", verdana, arial, sans-serif',this.fontSize="16px",this.labelBackground="#181818",this.textColor="#ccc",this.THEME_COLOR_LIMIT=12,this.nodeBkg="calculated",this.nodeBorder="calculated",this.clusterBkg="calculated",this.clusterBorder="calculated",this.defaultLinkColor="calculated",this.titleColor="#F9FFFE",this.edgeLabelBackground="calculated",this.actorBorder="calculated",this.actorBkg="calculated",this.actorTextColor="calculated",this.actorLineColor="calculated",this.signalColor="calculated",this.signalTextColor="calculated",this.labelBoxBkgColor="calculated",this.labelBoxBorderColor="calculated",this.labelTextColor="calculated",this.loopTextColor="calculated",this.noteBorderColor="calculated",this.noteBkgColor="#fff5ad",this.noteTextColor="calculated",this.activationBorderColor="calculated",this.activationBkgColor="calculated",this.sequenceNumberColor="black",this.sectionBkgColor=u("#EAE8D9",30),this.altSectionBkgColor="calculated",this.sectionBkgColor2="#EAE8D9",this.excludeBkgColor=u(this.sectionBkgColor,10),this.taskBorderColor=Z(255,255,255,70),this.taskBkgColor="calculated",this.taskTextColor="calculated",this.taskTextLightColor="calculated",this.taskTextOutsideColor="calculated",this.taskTextClickableColor="#003163",this.activeTaskBorderColor=Z(255,255,255,50),this.activeTaskBkgColor="#81B1DB",this.gridColor="calculated",this.doneTaskBkgColor="calculated",this.doneTaskBorderColor="grey",this.critBorderColor="#E83737",this.critBkgColor="#E83737",this.taskTextDarkColor="calculated",this.todayLineColor="#DB5757",this.vertLineColor="#00BFFF",this.personBorder=this.primaryBorderColor,this.personBkg=this.mainBkg,this.archEdgeColor="calculated",this.archEdgeArrowColor="calculated",this.archEdgeWidth="3",this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth="2px",this.rowOdd=this.rowOdd||d(this.mainBkg,5)||"#ffffff",this.rowEven=this.rowEven||u(this.mainBkg,10),this.labelColor="calculated",this.errorBkgColor="#a44141",this.errorTextColor="#ddd"}updateColors(){this.secondBkg=d(this.mainBkg,16),this.lineColor=this.mainContrastColor,this.arrowheadColor=this.mainContrastColor,this.nodeBkg=this.mainBkg,this.nodeBorder=this.border1,this.clusterBkg=this.secondBkg,this.clusterBorder=this.border2,this.defaultLinkColor=this.lineColor,this.edgeLabelBackground=d(this.labelBackground,25),this.actorBorder=this.border1,this.actorBkg=this.mainBkg,this.actorTextColor=this.mainContrastColor,this.actorLineColor=this.actorBorder,this.signalColor=this.mainContrastColor,this.signalTextColor=this.mainContrastColor,this.labelBoxBkgColor=this.actorBkg,this.labelBoxBorderColor=this.actorBorder,this.labelTextColor=this.mainContrastColor,this.loopTextColor=this.mainContrastColor,this.noteBorderColor=this.secondaryBorderColor,this.noteBkgColor=this.secondBkg,this.noteTextColor=this.secondaryTextColor,this.activationBorderColor=this.border1,this.activationBkgColor=this.secondBkg,this.altSectionBkgColor=this.background,this.taskBkgColor=d(this.mainBkg,23),this.taskTextColor=this.darkTextColor,this.taskTextLightColor=this.mainContrastColor,this.taskTextOutsideColor=this.taskTextLightColor,this.gridColor=this.mainContrastColor,this.doneTaskBkgColor=this.mainContrastColor,this.taskTextDarkColor=this.darkTextColor,this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||"#555",this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.primaryBorderColor,this.specialStateColor="#f4f4f4",this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.fillType0=this.primaryColor,this.fillType1=this.secondaryColor,this.fillType2=o(this.primaryColor,{h:64}),this.fillType3=o(this.secondaryColor,{h:64}),this.fillType4=o(this.primaryColor,{h:-64}),this.fillType5=o(this.secondaryColor,{h:-64}),this.fillType6=o(this.primaryColor,{h:128}),this.fillType7=o(this.secondaryColor,{h:128}),this.cScale1=this.cScale1||"#0b0000",this.cScale2=this.cScale2||"#4d1037",this.cScale3=this.cScale3||"#3f5258",this.cScale4=this.cScale4||"#4f2f1b",this.cScale5=this.cScale5||"#6e0a0a",this.cScale6=this.cScale6||"#3b0048",this.cScale7=this.cScale7||"#995a01",this.cScale8=this.cScale8||"#154706",this.cScale9=this.cScale9||"#161722",this.cScale10=this.cScale10||"#00296f",this.cScale11=this.cScale11||"#01629c",this.cScale12=this.cScale12||"#010029",this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||o(this.primaryColor,{h:30}),this.cScale4=this.cScale4||o(this.primaryColor,{h:60}),this.cScale5=this.cScale5||o(this.primaryColor,{h:90}),this.cScale6=this.cScale6||o(this.primaryColor,{h:120}),this.cScale7=this.cScale7||o(this.primaryColor,{h:150}),this.cScale8=this.cScale8||o(this.primaryColor,{h:210}),this.cScale9=this.cScale9||o(this.primaryColor,{h:270}),this.cScale10=this.cScale10||o(this.primaryColor,{h:300}),this.cScale11=this.cScale11||o(this.primaryColor,{h:330});for(let t=0;t{this[i]=t[i]}),this.updateColors(),e.forEach(i=>{this[i]=t[i]})}},ao=l(t=>{let e=new oo;return e.calculate(t),e},"getThemeVariables"),so=class{static{l(this,"Theme")}constructor(){this.background="#f4f4f4",this.primaryColor="#ECECFF",this.secondaryColor=o(this.primaryColor,{h:120}),this.secondaryColor="#ffffde",this.tertiaryColor=o(this.primaryColor,{h:-160}),this.primaryBorderColor=R(this.primaryColor,this.darkMode),this.secondaryBorderColor=R(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=R(this.tertiaryColor,this.darkMode),this.primaryTextColor=h(this.primaryColor),this.secondaryTextColor=h(this.secondaryColor),this.tertiaryTextColor=h(this.tertiaryColor),this.lineColor=h(this.background),this.textColor=h(this.background),this.background="white",this.mainBkg="#ECECFF",this.secondBkg="#ffffde",this.lineColor="#333333",this.border1="#9370DB",this.border2="#aaaa33",this.arrowheadColor="#333333",this.fontFamily='"trebuchet ms", verdana, arial, sans-serif',this.fontSize="16px",this.labelBackground="rgba(232,232,232, 0.8)",this.textColor="#333",this.THEME_COLOR_LIMIT=12,this.nodeBkg="calculated",this.nodeBorder="calculated",this.clusterBkg="calculated",this.clusterBorder="calculated",this.defaultLinkColor="calculated",this.titleColor="calculated",this.edgeLabelBackground="calculated",this.actorBorder="calculated",this.actorBkg="calculated",this.actorTextColor="black",this.actorLineColor="calculated",this.signalColor="calculated",this.signalTextColor="calculated",this.labelBoxBkgColor="calculated",this.labelBoxBorderColor="calculated",this.labelTextColor="calculated",this.loopTextColor="calculated",this.noteBorderColor="calculated",this.noteBkgColor="#fff5ad",this.noteTextColor="calculated",this.activationBorderColor="#666",this.activationBkgColor="#f4f4f4",this.sequenceNumberColor="white",this.sectionBkgColor="calculated",this.altSectionBkgColor="calculated",this.sectionBkgColor2="calculated",this.excludeBkgColor="#eeeeee",this.taskBorderColor="calculated",this.taskBkgColor="calculated",this.taskTextLightColor="calculated",this.taskTextColor=this.taskTextLightColor,this.taskTextDarkColor="calculated",this.taskTextOutsideColor=this.taskTextDarkColor,this.taskTextClickableColor="calculated",this.activeTaskBorderColor="calculated",this.activeTaskBkgColor="calculated",this.gridColor="calculated",this.doneTaskBkgColor="calculated",this.doneTaskBorderColor="calculated",this.critBorderColor="calculated",this.critBkgColor="calculated",this.todayLineColor="calculated",this.vertLineColor="calculated",this.sectionBkgColor=Z(102,102,255,.49),this.altSectionBkgColor="white",this.sectionBkgColor2="#fff400",this.taskBorderColor="#534fbc",this.taskBkgColor="#8a90dd",this.taskTextLightColor="white",this.taskTextColor="calculated",this.taskTextDarkColor="black",this.taskTextOutsideColor="calculated",this.taskTextClickableColor="#003163",this.activeTaskBorderColor="#534fbc",this.activeTaskBkgColor="#bfc7ff",this.gridColor="lightgrey",this.doneTaskBkgColor="lightgrey",this.doneTaskBorderColor="grey",this.critBorderColor="#ff8888",this.critBkgColor="red",this.todayLineColor="red",this.vertLineColor="navy",this.personBorder=this.primaryBorderColor,this.personBkg=this.mainBkg,this.archEdgeColor="calculated",this.archEdgeArrowColor="calculated",this.archEdgeWidth="3",this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth="2px",this.rowOdd="calculated",this.rowEven="calculated",this.labelColor="black",this.errorBkgColor="#552222",this.errorTextColor="#552222",this.updateColors()}updateColors(){this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||o(this.primaryColor,{h:30}),this.cScale4=this.cScale4||o(this.primaryColor,{h:60}),this.cScale5=this.cScale5||o(this.primaryColor,{h:90}),this.cScale6=this.cScale6||o(this.primaryColor,{h:120}),this.cScale7=this.cScale7||o(this.primaryColor,{h:150}),this.cScale8=this.cScale8||o(this.primaryColor,{h:210}),this.cScale9=this.cScale9||o(this.primaryColor,{h:270}),this.cScale10=this.cScale10||o(this.primaryColor,{h:300}),this.cScale11=this.cScale11||o(this.primaryColor,{h:330}),this.cScalePeer1=this.cScalePeer1||u(this.secondaryColor,45),this.cScalePeer2=this.cScalePeer2||u(this.tertiaryColor,40);for(let t=0;t{this[i]==="calculated"&&(this[i]=void 0)}),typeof t!="object"){this.updateColors();return}let e=Object.keys(t);e.forEach(i=>{this[i]=t[i]}),this.updateColors(),e.forEach(i=>{this[i]=t[i]})}},lo=l(t=>{let e=new so;return e.calculate(t),e},"getThemeVariables"),no=class{static{l(this,"Theme")}constructor(){this.background="#f4f4f4",this.primaryColor="#cde498",this.secondaryColor="#cdffb2",this.background="white",this.mainBkg="#cde498",this.secondBkg="#cdffb2",this.lineColor="green",this.border1="#13540c",this.border2="#6eaa49",this.arrowheadColor="green",this.fontFamily='"trebuchet ms", verdana, arial, sans-serif',this.fontSize="16px",this.tertiaryColor=d("#cde498",10),this.primaryBorderColor=R(this.primaryColor,this.darkMode),this.secondaryBorderColor=R(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=R(this.tertiaryColor,this.darkMode),this.primaryTextColor=h(this.primaryColor),this.secondaryTextColor=h(this.secondaryColor),this.tertiaryTextColor=h(this.primaryColor),this.lineColor=h(this.background),this.textColor=h(this.background),this.THEME_COLOR_LIMIT=12,this.nodeBkg="calculated",this.nodeBorder="calculated",this.clusterBkg="calculated",this.clusterBorder="calculated",this.defaultLinkColor="calculated",this.titleColor="#333",this.edgeLabelBackground="#e8e8e8",this.actorBorder="calculated",this.actorBkg="calculated",this.actorTextColor="black",this.actorLineColor="calculated",this.signalColor="#333",this.signalTextColor="#333",this.labelBoxBkgColor="calculated",this.labelBoxBorderColor="#326932",this.labelTextColor="calculated",this.loopTextColor="calculated",this.noteBorderColor="calculated",this.noteBkgColor="#fff5ad",this.noteTextColor="calculated",this.activationBorderColor="#666",this.activationBkgColor="#f4f4f4",this.sequenceNumberColor="white",this.sectionBkgColor="#6eaa49",this.altSectionBkgColor="white",this.sectionBkgColor2="#6eaa49",this.excludeBkgColor="#eeeeee",this.taskBorderColor="calculated",this.taskBkgColor="#487e3a",this.taskTextLightColor="white",this.taskTextColor="calculated",this.taskTextDarkColor="black",this.taskTextOutsideColor="calculated",this.taskTextClickableColor="#003163",this.activeTaskBorderColor="calculated",this.activeTaskBkgColor="calculated",this.gridColor="lightgrey",this.doneTaskBkgColor="lightgrey",this.doneTaskBorderColor="grey",this.critBorderColor="#ff8888",this.critBkgColor="red",this.todayLineColor="red",this.vertLineColor="#00BFFF",this.personBorder=this.primaryBorderColor,this.personBkg=this.mainBkg,this.archEdgeColor="calculated",this.archEdgeArrowColor="calculated",this.archEdgeWidth="3",this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth="2px",this.labelColor="black",this.errorBkgColor="#552222",this.errorTextColor="#552222"}updateColors(){this.actorBorder=u(this.mainBkg,20),this.actorBkg=this.mainBkg,this.labelBoxBkgColor=this.actorBkg,this.labelTextColor=this.actorTextColor,this.loopTextColor=this.actorTextColor,this.noteBorderColor=this.border2,this.noteTextColor=this.actorTextColor,this.actorLineColor=this.actorBorder,this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||o(this.primaryColor,{h:30}),this.cScale4=this.cScale4||o(this.primaryColor,{h:60}),this.cScale5=this.cScale5||o(this.primaryColor,{h:90}),this.cScale6=this.cScale6||o(this.primaryColor,{h:120}),this.cScale7=this.cScale7||o(this.primaryColor,{h:150}),this.cScale8=this.cScale8||o(this.primaryColor,{h:210}),this.cScale9=this.cScale9||o(this.primaryColor,{h:270}),this.cScale10=this.cScale10||o(this.primaryColor,{h:300}),this.cScale11=this.cScale11||o(this.primaryColor,{h:330}),this.cScalePeer1=this.cScalePeer1||u(this.secondaryColor,45),this.cScalePeer2=this.cScalePeer2||u(this.tertiaryColor,40);for(let t=0;t{this[i]=t[i]}),this.updateColors(),e.forEach(i=>{this[i]=t[i]})}},ho=l(t=>{let e=new no;return e.calculate(t),e},"getThemeVariables"),co=class{static{l(this,"Theme")}constructor(){this.primaryColor="#eee",this.contrast="#707070",this.secondaryColor=d(this.contrast,55),this.background="#ffffff",this.tertiaryColor=o(this.primaryColor,{h:-160}),this.primaryBorderColor=R(this.primaryColor,this.darkMode),this.secondaryBorderColor=R(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=R(this.tertiaryColor,this.darkMode),this.primaryTextColor=h(this.primaryColor),this.secondaryTextColor=h(this.secondaryColor),this.tertiaryTextColor=h(this.tertiaryColor),this.lineColor=h(this.background),this.textColor=h(this.background),this.mainBkg="#eee",this.secondBkg="calculated",this.lineColor="#666",this.border1="#999",this.border2="calculated",this.note="#ffa",this.text="#333",this.critical="#d42",this.done="#bbb",this.arrowheadColor="#333333",this.fontFamily='"trebuchet ms", verdana, arial, sans-serif',this.fontSize="16px",this.THEME_COLOR_LIMIT=12,this.nodeBkg="calculated",this.nodeBorder="calculated",this.clusterBkg="calculated",this.clusterBorder="calculated",this.defaultLinkColor="calculated",this.titleColor="calculated",this.edgeLabelBackground="white",this.actorBorder="calculated",this.actorBkg="calculated",this.actorTextColor="calculated",this.actorLineColor=this.actorBorder,this.signalColor="calculated",this.signalTextColor="calculated",this.labelBoxBkgColor="calculated",this.labelBoxBorderColor="calculated",this.labelTextColor="calculated",this.loopTextColor="calculated",this.noteBorderColor="calculated",this.noteBkgColor="calculated",this.noteTextColor="calculated",this.activationBorderColor="#666",this.activationBkgColor="#f4f4f4",this.sequenceNumberColor="white",this.sectionBkgColor="calculated",this.altSectionBkgColor="white",this.sectionBkgColor2="calculated",this.excludeBkgColor="#eeeeee",this.taskBorderColor="calculated",this.taskBkgColor="calculated",this.taskTextLightColor="white",this.taskTextColor="calculated",this.taskTextDarkColor="calculated",this.taskTextOutsideColor="calculated",this.taskTextClickableColor="#003163",this.activeTaskBorderColor="calculated",this.activeTaskBkgColor="calculated",this.gridColor="calculated",this.doneTaskBkgColor="calculated",this.doneTaskBorderColor="calculated",this.critBkgColor="calculated",this.critBorderColor="calculated",this.todayLineColor="calculated",this.vertLineColor="calculated",this.personBorder=this.primaryBorderColor,this.personBkg=this.mainBkg,this.archEdgeColor="calculated",this.archEdgeArrowColor="calculated",this.archEdgeWidth="3",this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth="2px",this.rowOdd=this.rowOdd||d(this.mainBkg,75)||"#ffffff",this.rowEven=this.rowEven||"#f4f4f4",this.labelColor="black",this.errorBkgColor="#552222",this.errorTextColor="#552222"}updateColors(){this.secondBkg=d(this.contrast,55),this.border2=this.contrast,this.actorBorder=d(this.border1,23),this.actorBkg=this.mainBkg,this.actorTextColor=this.text,this.actorLineColor=this.actorBorder,this.signalColor=this.text,this.signalTextColor=this.text,this.labelBoxBkgColor=this.actorBkg,this.labelBoxBorderColor=this.actorBorder,this.labelTextColor=this.text,this.loopTextColor=this.text,this.noteBorderColor="#999",this.noteBkgColor="#666",this.noteTextColor="#fff",this.cScale0=this.cScale0||"#555",this.cScale1=this.cScale1||"#F4F4F4",this.cScale2=this.cScale2||"#555",this.cScale3=this.cScale3||"#BBB",this.cScale4=this.cScale4||"#777",this.cScale5=this.cScale5||"#999",this.cScale6=this.cScale6||"#DDD",this.cScale7=this.cScale7||"#FFF",this.cScale8=this.cScale8||"#DDD",this.cScale9=this.cScale9||"#BBB",this.cScale10=this.cScale10||"#999",this.cScale11=this.cScale11||"#777";for(let t=0;t{this[i]=t[i]}),this.updateColors(),e.forEach(i=>{this[i]=t[i]})}},uo=l(t=>{let e=new co;return e.calculate(t),e},"getThemeVariables"),ft={base:{getThemeVariables:ro},dark:{getThemeVariables:ao},default:{getThemeVariables:lo},forest:{getThemeVariables:ho},neutral:{getThemeVariables:uo}},j={flowchart:{useMaxWidth:!0,titleTopMargin:25,subGraphTitleMargin:{top:0,bottom:0},diagramPadding:8,htmlLabels:!0,nodeSpacing:50,rankSpacing:50,curve:"basis",padding:15,defaultRenderer:"dagre-wrapper",wrappingWidth:200,inheritDir:!1},sequence:{useMaxWidth:!0,hideUnusedParticipants:!1,activationWidth:10,diagramMarginX:50,diagramMarginY:10,actorMargin:50,width:150,height:65,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center",mirrorActors:!0,forceMenus:!1,bottomMarginAdj:1,rightAngles:!1,showSequenceNumbers:!1,actorFontSize:14,actorFontFamily:'"Open Sans", sans-serif',actorFontWeight:400,noteFontSize:14,noteFontFamily:'"trebuchet ms", verdana, arial, sans-serif',noteFontWeight:400,noteAlign:"center",messageFontSize:16,messageFontFamily:'"trebuchet ms", verdana, arial, sans-serif',messageFontWeight:400,wrap:!1,wrapPadding:10,labelBoxWidth:50,labelBoxHeight:20},gantt:{useMaxWidth:!0,titleTopMargin:25,barHeight:20,barGap:4,topPadding:50,rightPadding:75,leftPadding:75,gridLineStartPadding:35,fontSize:11,sectionFontSize:11,numberSectionStyles:4,axisFormat:"%Y-%m-%d",topAxis:!1,displayMode:"",weekday:"sunday"},journey:{useMaxWidth:!0,diagramMarginX:50,diagramMarginY:10,leftMargin:150,maxLabelWidth:360,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center",bottomMarginAdj:1,rightAngles:!1,taskFontSize:14,taskFontFamily:'"Open Sans", sans-serif',taskMargin:50,activationWidth:10,textPlacement:"fo",actorColours:["#8FBC8F","#7CFC00","#00FFFF","#20B2AA","#B0E0E6","#FFFFE0"],sectionFills:["#191970","#8B008B","#4B0082","#2F4F4F","#800000","#8B4513","#00008B"],sectionColours:["#fff"],titleColor:"",titleFontFamily:'"trebuchet ms", verdana, arial, sans-serif',titleFontSize:"4ex"},class:{useMaxWidth:!0,titleTopMargin:25,arrowMarkerAbsolute:!1,dividerMargin:10,padding:5,textHeight:10,defaultRenderer:"dagre-wrapper",htmlLabels:!1,hideEmptyMembersBox:!1},state:{useMaxWidth:!0,titleTopMargin:25,dividerMargin:10,sizeUnit:5,padding:8,textHeight:10,titleShift:-15,noteMargin:10,forkWidth:70,forkHeight:7,miniPadding:2,fontSizeFactor:5.02,fontSize:24,labelHeight:16,edgeLengthFactor:"20",compositTitleSize:35,radius:5,defaultRenderer:"dagre-wrapper"},er:{useMaxWidth:!0,titleTopMargin:25,diagramPadding:20,layoutDirection:"TB",minEntityWidth:100,minEntityHeight:75,entityPadding:15,nodeSpacing:140,rankSpacing:80,stroke:"gray",fill:"honeydew",fontSize:12},pie:{useMaxWidth:!0,textPosition:.75},quadrantChart:{useMaxWidth:!0,chartWidth:500,chartHeight:500,titleFontSize:20,titlePadding:10,quadrantPadding:5,xAxisLabelPadding:5,yAxisLabelPadding:5,xAxisLabelFontSize:16,yAxisLabelFontSize:16,quadrantLabelFontSize:16,quadrantTextTopPadding:5,pointTextPadding:5,pointLabelFontSize:12,pointRadius:5,xAxisPosition:"top",yAxisPosition:"left",quadrantInternalBorderStrokeWidth:1,quadrantExternalBorderStrokeWidth:2},xyChart:{useMaxWidth:!0,width:700,height:500,titleFontSize:20,titlePadding:10,showDataLabel:!1,showTitle:!0,xAxis:{$ref:"#/$defs/XYChartAxisConfig",showLabel:!0,labelFontSize:14,labelPadding:5,showTitle:!0,titleFontSize:16,titlePadding:5,showTick:!0,tickLength:5,tickWidth:2,showAxisLine:!0,axisLineWidth:2},yAxis:{$ref:"#/$defs/XYChartAxisConfig",showLabel:!0,labelFontSize:14,labelPadding:5,showTitle:!0,titleFontSize:16,titlePadding:5,showTick:!0,tickLength:5,tickWidth:2,showAxisLine:!0,axisLineWidth:2},chartOrientation:"vertical",plotReservedSpacePercent:50},requirement:{useMaxWidth:!0,rect_fill:"#f9f9f9",text_color:"#333",rect_border_size:"0.5px",rect_border_color:"#bbb",rect_min_width:200,rect_min_height:200,fontSize:14,rect_padding:10,line_height:20},mindmap:{useMaxWidth:!0,padding:10,maxNodeWidth:200,layoutAlgorithm:"cose-bilkent"},kanban:{useMaxWidth:!0,padding:8,sectionWidth:200,ticketBaseUrl:""},timeline:{useMaxWidth:!0,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center",bottomMarginAdj:1,rightAngles:!1,taskFontSize:14,taskFontFamily:'"Open Sans", sans-serif',taskMargin:50,activationWidth:10,textPlacement:"fo",actorColours:["#8FBC8F","#7CFC00","#00FFFF","#20B2AA","#B0E0E6","#FFFFE0"],sectionFills:["#191970","#8B008B","#4B0082","#2F4F4F","#800000","#8B4513","#00008B"],sectionColours:["#fff"],disableMulticolor:!1},gitGraph:{useMaxWidth:!0,titleTopMargin:25,diagramPadding:8,nodeLabel:{width:75,height:100,x:-25,y:0},mainBranchName:"main",mainBranchOrder:0,showCommitLabel:!0,showBranches:!0,rotateCommitLabel:!0,parallelCommits:!1,arrowMarkerAbsolute:!1},c4:{useMaxWidth:!0,diagramMarginX:50,diagramMarginY:10,c4ShapeMargin:50,c4ShapePadding:20,width:216,height:60,boxMargin:10,c4ShapeInRow:4,nextLinePaddingX:0,c4BoundaryInRow:2,personFontSize:14,personFontFamily:'"Open Sans", sans-serif',personFontWeight:"normal",external_personFontSize:14,external_personFontFamily:'"Open Sans", sans-serif',external_personFontWeight:"normal",systemFontSize:14,systemFontFamily:'"Open Sans", sans-serif',systemFontWeight:"normal",external_systemFontSize:14,external_systemFontFamily:'"Open Sans", sans-serif',external_systemFontWeight:"normal",system_dbFontSize:14,system_dbFontFamily:'"Open Sans", sans-serif',system_dbFontWeight:"normal",external_system_dbFontSize:14,external_system_dbFontFamily:'"Open Sans", sans-serif',external_system_dbFontWeight:"normal",system_queueFontSize:14,system_queueFontFamily:'"Open Sans", sans-serif',system_queueFontWeight:"normal",external_system_queueFontSize:14,external_system_queueFontFamily:'"Open Sans", sans-serif',external_system_queueFontWeight:"normal",boundaryFontSize:14,boundaryFontFamily:'"Open Sans", sans-serif',boundaryFontWeight:"normal",messageFontSize:12,messageFontFamily:'"Open Sans", sans-serif',messageFontWeight:"normal",containerFontSize:14,containerFontFamily:'"Open Sans", sans-serif',containerFontWeight:"normal",external_containerFontSize:14,external_containerFontFamily:'"Open Sans", sans-serif',external_containerFontWeight:"normal",container_dbFontSize:14,container_dbFontFamily:'"Open Sans", sans-serif',container_dbFontWeight:"normal",external_container_dbFontSize:14,external_container_dbFontFamily:'"Open Sans", sans-serif',external_container_dbFontWeight:"normal",container_queueFontSize:14,container_queueFontFamily:'"Open Sans", sans-serif',container_queueFontWeight:"normal",external_container_queueFontSize:14,external_container_queueFontFamily:'"Open Sans", sans-serif',external_container_queueFontWeight:"normal",componentFontSize:14,componentFontFamily:'"Open Sans", sans-serif',componentFontWeight:"normal",external_componentFontSize:14,external_componentFontFamily:'"Open Sans", sans-serif',external_componentFontWeight:"normal",component_dbFontSize:14,component_dbFontFamily:'"Open Sans", sans-serif',component_dbFontWeight:"normal",external_component_dbFontSize:14,external_component_dbFontFamily:'"Open Sans", sans-serif',external_component_dbFontWeight:"normal",component_queueFontSize:14,component_queueFontFamily:'"Open Sans", sans-serif',component_queueFontWeight:"normal",external_component_queueFontSize:14,external_component_queueFontFamily:'"Open Sans", sans-serif',external_component_queueFontWeight:"normal",wrap:!0,wrapPadding:10,person_bg_color:"#08427B",person_border_color:"#073B6F",external_person_bg_color:"#686868",external_person_border_color:"#8A8A8A",system_bg_color:"#1168BD",system_border_color:"#3C7FC0",system_db_bg_color:"#1168BD",system_db_border_color:"#3C7FC0",system_queue_bg_color:"#1168BD",system_queue_border_color:"#3C7FC0",external_system_bg_color:"#999999",external_system_border_color:"#8A8A8A",external_system_db_bg_color:"#999999",external_system_db_border_color:"#8A8A8A",external_system_queue_bg_color:"#999999",external_system_queue_border_color:"#8A8A8A",container_bg_color:"#438DD5",container_border_color:"#3C7FC0",container_db_bg_color:"#438DD5",container_db_border_color:"#3C7FC0",container_queue_bg_color:"#438DD5",container_queue_border_color:"#3C7FC0",external_container_bg_color:"#B3B3B3",external_container_border_color:"#A6A6A6",external_container_db_bg_color:"#B3B3B3",external_container_db_border_color:"#A6A6A6",external_container_queue_bg_color:"#B3B3B3",external_container_queue_border_color:"#A6A6A6",component_bg_color:"#85BBF0",component_border_color:"#78A8D8",component_db_bg_color:"#85BBF0",component_db_border_color:"#78A8D8",component_queue_bg_color:"#85BBF0",component_queue_border_color:"#78A8D8",external_component_bg_color:"#CCCCCC",external_component_border_color:"#BFBFBF",external_component_db_bg_color:"#CCCCCC",external_component_db_border_color:"#BFBFBF",external_component_queue_bg_color:"#CCCCCC",external_component_queue_border_color:"#BFBFBF"},sankey:{useMaxWidth:!0,width:600,height:400,linkColor:"gradient",nodeAlignment:"justify",showValues:!0,prefix:"",suffix:""},block:{useMaxWidth:!0,padding:8},packet:{useMaxWidth:!0,rowHeight:32,bitWidth:32,bitsPerRow:32,showBits:!0,paddingX:5,paddingY:5},architecture:{useMaxWidth:!0,padding:40,iconSize:80,fontSize:16},radar:{useMaxWidth:!0,width:600,height:600,marginTop:50,marginRight:50,marginBottom:50,marginLeft:50,axisScaleFactor:1,axisLabelFactor:1.05,curveTension:.17},theme:"default",look:"classic",handDrawnSeed:0,layout:"dagre",maxTextSize:5e4,maxEdges:500,darkMode:!1,fontFamily:'"trebuchet ms", verdana, arial, sans-serif;',logLevel:5,securityLevel:"strict",startOnLoad:!0,arrowMarkerAbsolute:!1,secure:["secure","securityLevel","startOnLoad","maxTextSize","suppressErrorRendering","maxEdges"],legacyMathML:!1,forceLegacyMathML:!1,deterministicIds:!1,fontSize:16,markdownAutoWrap:!0,suppressErrorRendering:!1},Hi={...j,deterministicIDSeed:void 0,elk:{mergeEdges:!1,nodePlacementStrategy:"BRANDES_KOEPF",forceNodeModelOrder:!1,considerModelOrder:"NODES_AND_EDGES"},themeCSS:void 0,themeVariables:ft.default.getThemeVariables(),sequence:{...j.sequence,messageFont:l(function(){return{fontFamily:this.messageFontFamily,fontSize:this.messageFontSize,fontWeight:this.messageFontWeight}},"messageFont"),noteFont:l(function(){return{fontFamily:this.noteFontFamily,fontSize:this.noteFontSize,fontWeight:this.noteFontWeight}},"noteFont"),actorFont:l(function(){return{fontFamily:this.actorFontFamily,fontSize:this.actorFontSize,fontWeight:this.actorFontWeight}},"actorFont")},class:{hideEmptyMembersBox:!1},gantt:{...j.gantt,tickInterval:void 0,useWidth:void 0},c4:{...j.c4,useWidth:void 0,personFont:l(function(){return{fontFamily:this.personFontFamily,fontSize:this.personFontSize,fontWeight:this.personFontWeight}},"personFont"),flowchart:{...j.flowchart,inheritDir:!1},external_personFont:l(function(){return{fontFamily:this.external_personFontFamily,fontSize:this.external_personFontSize,fontWeight:this.external_personFontWeight}},"external_personFont"),systemFont:l(function(){return{fontFamily:this.systemFontFamily,fontSize:this.systemFontSize,fontWeight:this.systemFontWeight}},"systemFont"),external_systemFont:l(function(){return{fontFamily:this.external_systemFontFamily,fontSize:this.external_systemFontSize,fontWeight:this.external_systemFontWeight}},"external_systemFont"),system_dbFont:l(function(){return{fontFamily:this.system_dbFontFamily,fontSize:this.system_dbFontSize,fontWeight:this.system_dbFontWeight}},"system_dbFont"),external_system_dbFont:l(function(){return{fontFamily:this.external_system_dbFontFamily,fontSize:this.external_system_dbFontSize,fontWeight:this.external_system_dbFontWeight}},"external_system_dbFont"),system_queueFont:l(function(){return{fontFamily:this.system_queueFontFamily,fontSize:this.system_queueFontSize,fontWeight:this.system_queueFontWeight}},"system_queueFont"),external_system_queueFont:l(function(){return{fontFamily:this.external_system_queueFontFamily,fontSize:this.external_system_queueFontSize,fontWeight:this.external_system_queueFontWeight}},"external_system_queueFont"),containerFont:l(function(){return{fontFamily:this.containerFontFamily,fontSize:this.containerFontSize,fontWeight:this.containerFontWeight}},"containerFont"),external_containerFont:l(function(){return{fontFamily:this.external_containerFontFamily,fontSize:this.external_containerFontSize,fontWeight:this.external_containerFontWeight}},"external_containerFont"),container_dbFont:l(function(){return{fontFamily:this.container_dbFontFamily,fontSize:this.container_dbFontSize,fontWeight:this.container_dbFontWeight}},"container_dbFont"),external_container_dbFont:l(function(){return{fontFamily:this.external_container_dbFontFamily,fontSize:this.external_container_dbFontSize,fontWeight:this.external_container_dbFontWeight}},"external_container_dbFont"),container_queueFont:l(function(){return{fontFamily:this.container_queueFontFamily,fontSize:this.container_queueFontSize,fontWeight:this.container_queueFontWeight}},"container_queueFont"),external_container_queueFont:l(function(){return{fontFamily:this.external_container_queueFontFamily,fontSize:this.external_container_queueFontSize,fontWeight:this.external_container_queueFontWeight}},"external_container_queueFont"),componentFont:l(function(){return{fontFamily:this.componentFontFamily,fontSize:this.componentFontSize,fontWeight:this.componentFontWeight}},"componentFont"),external_componentFont:l(function(){return{fontFamily:this.external_componentFontFamily,fontSize:this.external_componentFontSize,fontWeight:this.external_componentFontWeight}},"external_componentFont"),component_dbFont:l(function(){return{fontFamily:this.component_dbFontFamily,fontSize:this.component_dbFontSize,fontWeight:this.component_dbFontWeight}},"component_dbFont"),external_component_dbFont:l(function(){return{fontFamily:this.external_component_dbFontFamily,fontSize:this.external_component_dbFontSize,fontWeight:this.external_component_dbFontWeight}},"external_component_dbFont"),component_queueFont:l(function(){return{fontFamily:this.component_queueFontFamily,fontSize:this.component_queueFontSize,fontWeight:this.component_queueFontWeight}},"component_queueFont"),external_component_queueFont:l(function(){return{fontFamily:this.external_component_queueFontFamily,fontSize:this.external_component_queueFontSize,fontWeight:this.external_component_queueFontWeight}},"external_component_queueFont"),boundaryFont:l(function(){return{fontFamily:this.boundaryFontFamily,fontSize:this.boundaryFontSize,fontWeight:this.boundaryFontWeight}},"boundaryFont"),messageFont:l(function(){return{fontFamily:this.messageFontFamily,fontSize:this.messageFontSize,fontWeight:this.messageFontWeight}},"messageFont")},pie:{...j.pie,useWidth:984},xyChart:{...j.xyChart,useWidth:void 0},requirement:{...j.requirement,useWidth:void 0},packet:{...j.packet},radar:{...j.radar},treemap:{useMaxWidth:!0,padding:10,diagramPadding:8,showValues:!0,nodeWidth:100,nodeHeight:40,borderWidth:1,valueFontSize:12,labelFontSize:14,valueFormat:","}},Ui=l((t,e="")=>Object.keys(t).reduce((i,a)=>Array.isArray(t[a])?i:typeof t[a]=="object"&&t[a]!==null?[...i,e+a,...Ui(t[a],"")]:[...i,e+a],[]),"keyify"),go=new Set(Ui(Hi,"")),Co=Hi,we=l(t=>{if(M.debug("sanitizeDirective called with",t),!(typeof t!="object"||t==null)){if(Array.isArray(t)){t.forEach(e=>we(e));return}for(let e of Object.keys(t)){if(M.debug("Checking key",e),e.startsWith("__")||e.includes("proto")||e.includes("constr")||!go.has(e)||t[e]==null){M.debug("sanitize deleting key: ",e),delete t[e];continue}if(typeof t[e]=="object"){M.debug("sanitizing object",e),we(t[e]);continue}let i=["themeCSS","fontFamily","altFontFamily"];for(let a of i)e.includes(a)&&(M.debug("sanitizing css option",e),t[e]=mo(t[e]))}if(t.themeVariables)for(let e of Object.keys(t.themeVariables)){let i=t.themeVariables[e];i?.match&&!i.match(/^[\d "#%(),.;A-Za-z]+$/)&&(t.themeVariables[e]="")}M.debug("After sanitization",t)}},"sanitizeDirective"),mo=l(t=>{let e=0,i=0;for(let a of t){if(e{let i=w({},t),a={};for(let s of e)Gi(s),a=w(a,s);if(i=w(i,a),a.theme&&a.theme in ft){let s=w({},Jt),c=w(s.themeVariables||{},a.themeVariables);i.theme&&i.theme in ft&&(i.themeVariables=ft[i.theme].getThemeVariables(c))}return Mt=i,$i(Mt),Mt},"updateCurrentConfig"),vs=l(t=>(P=w({},ie),P=w(P,t),t.theme&&ft[t.theme]&&(P.themeVariables=ft[t.theme].getThemeVariables(t.themeVariables)),re(P,ot),P),"setSiteConfig"),Os=l(t=>{Jt=w({},t)},"saveConfigFromInitialize"),Ms=l(t=>(P=w(P,t),re(P,ot),P),"updateSiteConfig"),ws=l(()=>w({},P),"getSiteConfig"),po=l(t=>($i(t),w(Mt,t),Ie()),"setConfig"),Ie=l(()=>w({},Mt),"getConfig"),Gi=l(t=>{t&&(["secure",...P.secure??[]].forEach(e=>{Object.hasOwn(t,e)&&(M.debug(`Denied attempt to modify a secure key ${e}`,t[e]),delete t[e])}),Object.keys(t).forEach(e=>{e.startsWith("__")&&delete t[e]}),Object.keys(t).forEach(e=>{typeof t[e]=="string"&&(t[e].includes("<")||t[e].includes(">")||t[e].includes("url(data:"))&&delete t[e],typeof t[e]=="object"&&Gi(t[e])}))},"sanitize"),Ds=l(t=>{we(t),t.fontFamily&&!t.themeVariables?.fontFamily&&(t.themeVariables={...t.themeVariables,fontFamily:t.fontFamily}),ot.push(t),re(P,ot)},"addDirective"),Is=l((t=P)=>{ot=[],re(t,ot)},"reset"),fo={LAZY_LOAD_DEPRECATED:"The configuration options lazyLoadedDiagrams and loadExternalDiagramsAtStartup are deprecated. Please use registerExternalDiagrams instead."},zi={},xo=l(t=>{zi[t]||(M.warn(fo[t]),zi[t]=!0)},"issueWarning"),$i=l(t=>{t&&(t.lazyLoadedDiagrams||t.loadExternalDiagramsAtStartup)&&xo("LAZY_LOAD_DEPRECATED")},"checkConfig"),zs=l(()=>{let t={};Jt&&(t=w(t,Jt));for(let e of ot)t=w(t,e);return t},"getUserDefinedConfig"),wt=//gi,yo=l(t=>t?Yi(t).replace(/\\n/g,"#br#").split("#br#"):[""],"getRows"),bo=(()=>{let t=!1;return()=>{t||(ji(),t=!0)}})();function ji(){let t="data-temp-href-target";pt.addHook("beforeSanitizeAttributes",e=>{e.tagName==="A"&&e.hasAttribute("target")&&e.setAttribute(t,e.getAttribute("target")??"")}),pt.addHook("afterSanitizeAttributes",e=>{e.tagName==="A"&&e.hasAttribute(t)&&(e.setAttribute("target",e.getAttribute(t)??""),e.removeAttribute(t),e.getAttribute("target")==="_blank"&&e.setAttribute("rel","noopener"))})}l(ji,"setupDompurifyHooks");var Vi=l(t=>(bo(),pt.sanitize(t)),"removeScript"),qi=l((t,e)=>{if(e.flowchart?.htmlLabels!==!1){let i=e.securityLevel;i==="antiscript"||i==="strict"?t=Vi(t):i!=="loose"&&(t=Yi(t),t=t.replace(//g,">"),t=t.replace(/=/g,"="),t=So(t))}return t},"sanitizeMore"),xt=l((t,e)=>t&&(e.dompurifyConfig?t=pt.sanitize(qi(t,e),e.dompurifyConfig).toString():t=pt.sanitize(qi(t,e),{FORBID_TAGS:["style"]}).toString(),t),"sanitizeText"),To=l((t,e)=>typeof t=="string"?xt(t,e):t.flat().map(i=>xt(i,e)),"sanitizeTextOrArray"),ko=l(t=>wt.test(t),"hasBreaks"),Bo=l(t=>t.split(wt),"splitBreaks"),So=l(t=>t.replace(/#br#/g,"
"),"placeholderToBreak"),Yi=l(t=>t.replace(wt,"#br#"),"breakToPlaceholder"),Fo=l(t=>{let e="";return t&&(e=window.location.protocol+"//"+window.location.host+window.location.pathname+window.location.search,e=CSS.escape(e)),e},"getUrl"),_o=l(t=>!(t===!1||["false","null","0"].includes(String(t).trim().toLowerCase())),"evaluate"),Lo=l(function(...t){let e=t.filter(i=>!isNaN(i));return Math.max(...e)},"getMax"),Ao=l(function(...t){let e=t.filter(i=>!isNaN(i));return Math.min(...e)},"getMin"),Rs=l(function(t){let e=t.split(/(,)/),i=[];for(let a=0;a0&&a+1Math.max(0,t.split(e).length-1),"countOccurrence"),Eo=l((t,e)=>{let i=De(t,"~"),a=De(e,"~");return i===1&&a===1},"shouldCombineSets"),vo=l(t=>{let e=De(t,"~"),i=!1;if(e<=1)return t;e%2!==0&&t.startsWith("~")&&(t=t.substring(1),i=!0);let a=[...t],s=a.indexOf("~"),c=a.lastIndexOf("~");for(;s!==-1&&c!==-1&&s!==c;)a[s]="<",a[c]=">",s=a.indexOf("~"),c=a.lastIndexOf("~");return i&&a.unshift("~"),a.join("")},"processSet"),Ri=l(()=>window.MathMLElement!==void 0,"isMathMLSupported"),Xt=/\$\$(.*)\$\$/g,Wi=l(t=>(t.match(Xt)?.length??0)>0,"hasKatex"),Ws=l(async(t,e)=>{let i=document.createElement("div");i.innerHTML=await Mo(t,e),i.id="katex-temp",i.style.visibility="hidden",i.style.position="absolute",i.style.top="0",document.querySelector("body")?.insertAdjacentElement("beforeend",i);let s={width:i.clientWidth,height:i.clientHeight};return i.remove(),s},"calculateMathMLDimensions"),Oo=l(async(t,e)=>{if(!Wi(t))return t;if(!(Ri()||e.legacyMathML||e.forceLegacyMathML))return t.replace(Xt,"MathML is unsupported in this environment.");{let{default:i}=await import("./katex-BQXZD77A.min.js"),a=e.forceLegacyMathML||!Ri()&&e.legacyMathML?"htmlAndMathml":"mathml";return t.split(wt).map(s=>Wi(s)?`
${s}
`:`
${s}
`).join("").replace(Xt,(s,c)=>i.renderToString(c,{throwOnError:!0,displayMode:!0,output:a}).replace(/\n/g," ").replace(//g,""))}return t.replace(Xt,"Katex is not supported in @mermaid-js/tiny. Please use the full mermaid library.")},"renderKatexUnsanitized"),Mo=l(async(t,e)=>xt(await Oo(t,e),e),"renderKatexSanitized"),Ps={getRows:yo,sanitizeText:xt,sanitizeTextOrArray:To,hasBreaks:ko,splitBreaks:Bo,lineBreakRegex:wt,removeScript:Vi,getUrl:Fo,evaluate:_o,getMax:Lo,getMin:Ao},wo=l(function(t,e){for(let i of e)t.attr(i[0],i[1])},"d3Attrs"),Do=l(function(t,e,i){let a=new Map;return i?(a.set("width","100%"),a.set("style",`max-width: ${e}px;`)):(a.set("height",t),a.set("width",e)),a},"calculateSvgSizeAttrs"),Io=l(function(t,e,i,a){let s=Do(e,i,a);wo(t,s)},"configureSvgSize"),zo=l(function(t,e,i,a){let s=e.node().getBBox(),c=s.width,f=s.height;M.info(`SVG bounds: ${c}x${f}`,s);let x=0,_=0;M.info(`Graph bounds: ${x}x${_}`,t),x=c+i*2,_=f+i*2,M.info(`Calculated bounds: ${x}x${_}`),Io(e,_,x,a);let L=`${s.x-i} ${s.y-i} ${s.width+2*i} ${s.height+2*i}`;e.attr("viewBox",L)},"setupGraphViewbox"),Kt={},qo=l((t,e,i)=>{let a="";return t in Kt&&Kt[t]?a=Kt[t](i):M.warn(`No theme found for ${t}`),` & { + font-family: ${i.fontFamily}; + font-size: ${i.fontSize}; + fill: ${i.textColor} + } + @keyframes edge-animation-frame { + from { + stroke-dashoffset: 0; + } + } + @keyframes dash { + to { + stroke-dashoffset: 0; + } + } + & .edge-animation-slow { + stroke-dasharray: 9,5 !important; + stroke-dashoffset: 900; + animation: dash 50s linear infinite; + stroke-linecap: round; + } + & .edge-animation-fast { + stroke-dasharray: 9,5 !important; + stroke-dashoffset: 900; + animation: dash 20s linear infinite; + stroke-linecap: round; + } + /* Classes common for multiple diagrams */ + + & .error-icon { + fill: ${i.errorBkgColor}; + } + & .error-text { + fill: ${i.errorTextColor}; + stroke: ${i.errorTextColor}; + } + + & .edge-thickness-normal { + stroke-width: 1px; + } + & .edge-thickness-thick { + stroke-width: 3.5px + } + & .edge-pattern-solid { + stroke-dasharray: 0; + } + & .edge-thickness-invisible { + stroke-width: 0; + fill: none; + } + & .edge-pattern-dashed{ + stroke-dasharray: 3; + } + .edge-pattern-dotted { + stroke-dasharray: 2; + } + + & .marker { + fill: ${i.lineColor}; + stroke: ${i.lineColor}; + } + & .marker.cross { + stroke: ${i.lineColor}; + } + + & svg { + font-family: ${i.fontFamily}; + font-size: ${i.fontSize}; + } + & p { + margin: 0 + } + + ${a} + + ${e} +`},"getStyles"),Ro=l((t,e)=>{e!==void 0&&(Kt[t]=e)},"addStylesForDiagram"),Ns=qo,Xi={};di(Xi,{clear:()=>Wo,getAccDescription:()=>Uo,getAccTitle:()=>No,getDiagramTitle:()=>$o,setAccDescription:()=>Ho,setAccTitle:()=>Po,setDiagramTitle:()=>Go});var ze="",qe="",Re="",We=l(t=>xt(t,Ie()),"sanitizeText"),Wo=l(()=>{ze="",Re="",qe=""},"clear"),Po=l(t=>{ze=We(t).replace(/^\s+/g,"")},"setAccTitle"),No=l(()=>ze,"getAccTitle"),Ho=l(t=>{Re=We(t).replace(/\n\s+/g,` +`)},"setAccDescription"),Uo=l(()=>Re,"getAccDescription"),Go=l(t=>{qe=We(t)},"setDiagramTitle"),$o=l(()=>qe,"getDiagramTitle"),Pi=M,jo=ui,Ki=Ie,Hs=po,Us=ie,Vo=l(t=>xt(t,Ki()),"sanitizeText"),Yo=zo,Xo=l(()=>Xi,"getCommonDb"),Qt={},Gs=l((t,e,i)=>{Qt[t]&&Pi.warn(`Diagram with id ${t} already registered. Overwriting.`),Qt[t]=e,i&&Ni(t,i),Ro(t,e.styles),e.injectUtils?.(Pi,jo,Ki,Vo,Yo,Xo(),()=>{})},"registerDiagram"),$s=l(t=>{if(t in Qt)return Qt[t];throw new Ko(t)},"getDiagram"),Ko=class extends Error{static{l(this,"DiagramNotFoundError")}constructor(t){super(`Diagram ${t} not found.`)}};export{Z as a,Tr as b,U as c,d,u as e,pt as f,Jr as g,Qr as h,eo as i,Zt as j,Ts as k,ks as l,Bs as m,w as n,lo as o,ft as p,Co as q,we as r,ie as s,vs as t,Os as u,Ms as v,ws as w,po as x,Ie as y,Ds as z,Is as A,zs as B,wt as C,xt as D,Fo as E,_o as F,Rs as G,Wi as H,Ws as I,Mo as J,Ps as K,Io as L,zo as M,Ns as N,Xi as O,Wo as P,Po as Q,No as R,Ho as S,Uo as T,Go as U,$o as V,Ki as W,Hs as X,Us as Y,Vo as Z,Yo as _,Gs as $,$s as aa}; +/*! Bundled license information: + +dompurify/dist/purify.es.mjs: + (*! @license DOMPurify 3.2.7 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.7/LICENSE *) +*/ +//# sourceMappingURL=chunk-3EE2TK35.min.js.map diff --git a/docs/website/public/chunk-3EE2TK35.min.js.map b/docs/website/public/chunk-3EE2TK35.min.js.map new file mode 100644 index 000000000..8a96f9a00 --- /dev/null +++ b/docs/website/public/chunk-3EE2TK35.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/khroma/dist/utils/channel.js", "../../node_modules/khroma/dist/utils/lang.js", "../../node_modules/khroma/dist/utils/unit.js", "../../node_modules/khroma/dist/utils/index.js", "../../node_modules/khroma/dist/constants.js", "../../node_modules/khroma/dist/channels/type.js", "../../node_modules/khroma/dist/channels/index.js", "../../node_modules/khroma/dist/channels/reusable.js", "../../node_modules/khroma/dist/color/hex.js", "../../node_modules/khroma/dist/color/hsl.js", "../../node_modules/khroma/dist/color/keyword.js", "../../node_modules/khroma/dist/color/rgb.js", "../../node_modules/khroma/dist/color/index.js", "../../node_modules/khroma/dist/methods/change.js", "../../node_modules/khroma/dist/methods/rgba.js", "../../node_modules/khroma/dist/methods/channel.js", "../../node_modules/khroma/dist/methods/luminance.js", "../../node_modules/khroma/dist/methods/is_light.js", "../../node_modules/khroma/dist/methods/is_dark.js", "../../node_modules/khroma/dist/methods/adjust_channel.js", "../../node_modules/khroma/dist/methods/lighten.js", "../../node_modules/khroma/dist/methods/darken.js", "../../node_modules/khroma/dist/methods/adjust.js", "../../node_modules/khroma/dist/methods/mix.js", "../../node_modules/khroma/dist/methods/invert.js", "../../node_modules/dompurify/src/utils.ts", "../../node_modules/dompurify/src/tags.ts", "../../node_modules/dompurify/src/attrs.ts", "../../node_modules/dompurify/src/regexp.ts", "../../node_modules/dompurify/src/purify.ts", "../../node_modules/mermaid/dist/chunks/mermaid.core/chunk-ABZYJK2D.mjs"], + "sourcesContent": ["/* IMPORT */\n/* MAIN */\nconst Channel = {\n /* CLAMP */\n min: {\n r: 0,\n g: 0,\n b: 0,\n s: 0,\n l: 0,\n a: 0\n },\n max: {\n r: 255,\n g: 255,\n b: 255,\n h: 360,\n s: 100,\n l: 100,\n a: 1\n },\n clamp: {\n r: (r) => r >= 255 ? 255 : (r < 0 ? 0 : r),\n g: (g) => g >= 255 ? 255 : (g < 0 ? 0 : g),\n b: (b) => b >= 255 ? 255 : (b < 0 ? 0 : b),\n h: (h) => h % 360,\n s: (s) => s >= 100 ? 100 : (s < 0 ? 0 : s),\n l: (l) => l >= 100 ? 100 : (l < 0 ? 0 : l),\n a: (a) => a >= 1 ? 1 : (a < 0 ? 0 : a)\n },\n /* CONVERSION */\n //SOURCE: https://planetcalc.com/7779\n toLinear: (c) => {\n const n = c / 255;\n return c > .03928 ? Math.pow(((n + .055) / 1.055), 2.4) : n / 12.92;\n },\n //SOURCE: https://gist.github.com/mjackson/5311256\n hue2rgb: (p, q, t) => {\n if (t < 0)\n t += 1;\n if (t > 1)\n t -= 1;\n if (t < 1 / 6)\n return p + (q - p) * 6 * t;\n if (t < 1 / 2)\n return q;\n if (t < 2 / 3)\n return p + (q - p) * (2 / 3 - t) * 6;\n return p;\n },\n hsl2rgb: ({ h, s, l }, channel) => {\n if (!s)\n return l * 2.55; // Achromatic\n h /= 360;\n s /= 100;\n l /= 100;\n const q = (l < .5) ? l * (1 + s) : (l + s) - (l * s);\n const p = 2 * l - q;\n switch (channel) {\n case 'r': return Channel.hue2rgb(p, q, h + 1 / 3) * 255;\n case 'g': return Channel.hue2rgb(p, q, h) * 255;\n case 'b': return Channel.hue2rgb(p, q, h - 1 / 3) * 255;\n }\n },\n rgb2hsl: ({ r, g, b }, channel) => {\n r /= 255;\n g /= 255;\n b /= 255;\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const l = (max + min) / 2;\n if (channel === 'l')\n return l * 100;\n if (max === min)\n return 0; // Achromatic\n const d = max - min;\n const s = (l > .5) ? d / (2 - max - min) : d / (max + min);\n if (channel === 's')\n return s * 100;\n switch (max) {\n case r: return ((g - b) / d + (g < b ? 6 : 0)) * 60;\n case g: return ((b - r) / d + 2) * 60;\n case b: return ((r - g) / d + 4) * 60;\n default: return -1; //TSC: TypeScript is stupid and complains if there isn't this useless default statement\n }\n }\n};\n/* EXPORT */\nexport default Channel;\n", "/* MAIN */\nconst Lang = {\n /* API */\n clamp: (number, lower, upper) => {\n if (lower > upper)\n return Math.min(lower, Math.max(upper, number));\n return Math.min(upper, Math.max(lower, number));\n },\n round: (number) => {\n return Math.round(number * 10000000000) / 10000000000;\n }\n};\n/* EXPORT */\nexport default Lang;\n", "/* MAIN */\nconst Unit = {\n /* API */\n dec2hex: (dec) => {\n const hex = Math.round(dec).toString(16);\n return hex.length > 1 ? hex : `0${hex}`;\n }\n};\n/* EXPORT */\nexport default Unit;\n", "/* IMPORT */\nimport channel from './channel.js';\nimport lang from './lang.js';\nimport unit from './unit.js';\n/* MAIN */\nconst Utils = {\n channel,\n lang,\n unit\n};\n/* EXPORT */\nexport default Utils;\n", "/* IMPORT */\nimport _ from './utils/index.js';\n/* MAIN */\nconst DEC2HEX = {};\nfor (let i = 0; i <= 255; i++)\n DEC2HEX[i] = _.unit.dec2hex(i); // Populating dynamically, striking a balance between code size and performance\nconst TYPE = {\n ALL: 0,\n RGB: 1,\n HSL: 2\n};\n/* EXPORT */\nexport { DEC2HEX, TYPE };\n", "/* IMPORT */\nimport { TYPE } from '../constants.js';\n/* MAIN */\nclass Type {\n constructor() {\n /* VARIABLES */\n this.type = TYPE.ALL;\n }\n /* API */\n get() {\n return this.type;\n }\n set(type) {\n if (this.type && this.type !== type)\n throw new Error('Cannot change both RGB and HSL channels at the same time');\n this.type = type;\n }\n reset() {\n this.type = TYPE.ALL;\n }\n is(type) {\n return this.type === type;\n }\n}\n/* EXPORT */\nexport default Type;\n", "/* IMPORT */\nimport _ from '../utils/index.js';\nimport Type from './type.js';\nimport { TYPE } from '../constants.js';\n/* MAIN */\nclass Channels {\n /* CONSTRUCTOR */\n constructor(data, color) {\n this.color = color;\n this.changed = false;\n this.data = data; //TSC\n this.type = new Type();\n }\n /* API */\n set(data, color) {\n this.color = color;\n this.changed = false;\n this.data = data; //TSC\n this.type.type = TYPE.ALL;\n return this;\n }\n /* HELPERS */\n _ensureHSL() {\n const data = this.data;\n const { h, s, l } = data;\n if (h === undefined)\n data.h = _.channel.rgb2hsl(data, 'h');\n if (s === undefined)\n data.s = _.channel.rgb2hsl(data, 's');\n if (l === undefined)\n data.l = _.channel.rgb2hsl(data, 'l');\n }\n _ensureRGB() {\n const data = this.data;\n const { r, g, b } = data;\n if (r === undefined)\n data.r = _.channel.hsl2rgb(data, 'r');\n if (g === undefined)\n data.g = _.channel.hsl2rgb(data, 'g');\n if (b === undefined)\n data.b = _.channel.hsl2rgb(data, 'b');\n }\n /* GETTERS */\n get r() {\n const data = this.data;\n const r = data.r;\n if (!this.type.is(TYPE.HSL) && r !== undefined)\n return r;\n this._ensureHSL();\n return _.channel.hsl2rgb(data, 'r');\n }\n get g() {\n const data = this.data;\n const g = data.g;\n if (!this.type.is(TYPE.HSL) && g !== undefined)\n return g;\n this._ensureHSL();\n return _.channel.hsl2rgb(data, 'g');\n }\n get b() {\n const data = this.data;\n const b = data.b;\n if (!this.type.is(TYPE.HSL) && b !== undefined)\n return b;\n this._ensureHSL();\n return _.channel.hsl2rgb(data, 'b');\n }\n get h() {\n const data = this.data;\n const h = data.h;\n if (!this.type.is(TYPE.RGB) && h !== undefined)\n return h;\n this._ensureRGB();\n return _.channel.rgb2hsl(data, 'h');\n }\n get s() {\n const data = this.data;\n const s = data.s;\n if (!this.type.is(TYPE.RGB) && s !== undefined)\n return s;\n this._ensureRGB();\n return _.channel.rgb2hsl(data, 's');\n }\n get l() {\n const data = this.data;\n const l = data.l;\n if (!this.type.is(TYPE.RGB) && l !== undefined)\n return l;\n this._ensureRGB();\n return _.channel.rgb2hsl(data, 'l');\n }\n get a() {\n return this.data.a;\n }\n /* SETTERS */\n set r(r) {\n this.type.set(TYPE.RGB);\n this.changed = true;\n this.data.r = r;\n }\n set g(g) {\n this.type.set(TYPE.RGB);\n this.changed = true;\n this.data.g = g;\n }\n set b(b) {\n this.type.set(TYPE.RGB);\n this.changed = true;\n this.data.b = b;\n }\n set h(h) {\n this.type.set(TYPE.HSL);\n this.changed = true;\n this.data.h = h;\n }\n set s(s) {\n this.type.set(TYPE.HSL);\n this.changed = true;\n this.data.s = s;\n }\n set l(l) {\n this.type.set(TYPE.HSL);\n this.changed = true;\n this.data.l = l;\n }\n set a(a) {\n this.changed = true;\n this.data.a = a;\n }\n}\n/* EXPORT */\nexport default Channels;\n", "/* IMPORT */\nimport Channels from './/index.js';\n/* MAIN */\nconst channels = new Channels({ r: 0, g: 0, b: 0, a: 0 }, 'transparent');\n/* EXPORT */\nexport default channels;\n", "/* IMPORT */\nimport _ from '../utils/index.js';\nimport ChannelsReusable from '../channels/reusable.js';\nimport { DEC2HEX } from '../constants.js';\n/* MAIN */\nconst Hex = {\n /* VARIABLES */\n re: /^#((?:[a-f0-9]{2}){2,4}|[a-f0-9]{3})$/i,\n /* API */\n parse: (color) => {\n if (color.charCodeAt(0) !== 35)\n return; // '#'\n const match = color.match(Hex.re);\n if (!match)\n return;\n const hex = match[1];\n const dec = parseInt(hex, 16);\n const length = hex.length;\n const hasAlpha = length % 4 === 0;\n const isFullLength = length > 4;\n const multiplier = isFullLength ? 1 : 17;\n const bits = isFullLength ? 8 : 4;\n const bitsOffset = hasAlpha ? 0 : -1;\n const mask = isFullLength ? 255 : 15;\n return ChannelsReusable.set({\n r: ((dec >> (bits * (bitsOffset + 3))) & mask) * multiplier,\n g: ((dec >> (bits * (bitsOffset + 2))) & mask) * multiplier,\n b: ((dec >> (bits * (bitsOffset + 1))) & mask) * multiplier,\n a: hasAlpha ? (dec & mask) * multiplier / 255 : 1\n }, color);\n },\n stringify: (channels) => {\n const { r, g, b, a } = channels;\n if (a < 1) { // #RRGGBBAA\n return `#${DEC2HEX[Math.round(r)]}${DEC2HEX[Math.round(g)]}${DEC2HEX[Math.round(b)]}${DEC2HEX[Math.round(a * 255)]}`;\n }\n else { // #RRGGBB\n return `#${DEC2HEX[Math.round(r)]}${DEC2HEX[Math.round(g)]}${DEC2HEX[Math.round(b)]}`;\n }\n }\n};\n/* EXPORT */\nexport default Hex;\n", "/* IMPORT */\nimport _ from '../utils/index.js';\nimport ChannelsReusable from '../channels/reusable.js';\n/* MAIN */\nconst HSL = {\n /* VARIABLES */\n re: /^hsla?\\(\\s*?(-?(?:\\d+(?:\\.\\d+)?|(?:\\.\\d+))(?:e-?\\d+)?(?:deg|grad|rad|turn)?)\\s*?(?:,|\\s)\\s*?(-?(?:\\d+(?:\\.\\d+)?|(?:\\.\\d+))(?:e-?\\d+)?%)\\s*?(?:,|\\s)\\s*?(-?(?:\\d+(?:\\.\\d+)?|(?:\\.\\d+))(?:e-?\\d+)?%)(?:\\s*?(?:,|\\/)\\s*?\\+?(-?(?:\\d+(?:\\.\\d+)?|(?:\\.\\d+))(?:e-?\\d+)?(%)?))?\\s*?\\)$/i,\n hueRe: /^(.+?)(deg|grad|rad|turn)$/i,\n /* HELPERS */\n _hue2deg: (hue) => {\n const match = hue.match(HSL.hueRe);\n if (match) {\n const [, number, unit] = match;\n switch (unit) {\n case 'grad': return _.channel.clamp.h(parseFloat(number) * .9);\n case 'rad': return _.channel.clamp.h(parseFloat(number) * 180 / Math.PI);\n case 'turn': return _.channel.clamp.h(parseFloat(number) * 360);\n }\n }\n return _.channel.clamp.h(parseFloat(hue));\n },\n /* API */\n parse: (color) => {\n const charCode = color.charCodeAt(0);\n if (charCode !== 104 && charCode !== 72)\n return; // 'h'/'H'\n const match = color.match(HSL.re);\n if (!match)\n return;\n const [, h, s, l, a, isAlphaPercentage] = match;\n return ChannelsReusable.set({\n h: HSL._hue2deg(h),\n s: _.channel.clamp.s(parseFloat(s)),\n l: _.channel.clamp.l(parseFloat(l)),\n a: a ? _.channel.clamp.a(isAlphaPercentage ? parseFloat(a) / 100 : parseFloat(a)) : 1\n }, color);\n },\n stringify: (channels) => {\n const { h, s, l, a } = channels;\n if (a < 1) { // HSLA\n return `hsla(${_.lang.round(h)}, ${_.lang.round(s)}%, ${_.lang.round(l)}%, ${a})`;\n }\n else { // HSL\n return `hsl(${_.lang.round(h)}, ${_.lang.round(s)}%, ${_.lang.round(l)}%)`;\n }\n }\n};\n/* EXPORT */\nexport default HSL;\n", "/* IMPORT */\nimport Hex from './hex.js';\n/* MAIN */\nconst Keyword = {\n /* VARIABLES */\n colors: {\n aliceblue: '#f0f8ff',\n antiquewhite: '#faebd7',\n aqua: '#00ffff',\n aquamarine: '#7fffd4',\n azure: '#f0ffff',\n beige: '#f5f5dc',\n bisque: '#ffe4c4',\n black: '#000000',\n blanchedalmond: '#ffebcd',\n blue: '#0000ff',\n blueviolet: '#8a2be2',\n brown: '#a52a2a',\n burlywood: '#deb887',\n cadetblue: '#5f9ea0',\n chartreuse: '#7fff00',\n chocolate: '#d2691e',\n coral: '#ff7f50',\n cornflowerblue: '#6495ed',\n cornsilk: '#fff8dc',\n crimson: '#dc143c',\n cyanaqua: '#00ffff',\n darkblue: '#00008b',\n darkcyan: '#008b8b',\n darkgoldenrod: '#b8860b',\n darkgray: '#a9a9a9',\n darkgreen: '#006400',\n darkgrey: '#a9a9a9',\n darkkhaki: '#bdb76b',\n darkmagenta: '#8b008b',\n darkolivegreen: '#556b2f',\n darkorange: '#ff8c00',\n darkorchid: '#9932cc',\n darkred: '#8b0000',\n darksalmon: '#e9967a',\n darkseagreen: '#8fbc8f',\n darkslateblue: '#483d8b',\n darkslategray: '#2f4f4f',\n darkslategrey: '#2f4f4f',\n darkturquoise: '#00ced1',\n darkviolet: '#9400d3',\n deeppink: '#ff1493',\n deepskyblue: '#00bfff',\n dimgray: '#696969',\n dimgrey: '#696969',\n dodgerblue: '#1e90ff',\n firebrick: '#b22222',\n floralwhite: '#fffaf0',\n forestgreen: '#228b22',\n fuchsia: '#ff00ff',\n gainsboro: '#dcdcdc',\n ghostwhite: '#f8f8ff',\n gold: '#ffd700',\n goldenrod: '#daa520',\n gray: '#808080',\n green: '#008000',\n greenyellow: '#adff2f',\n grey: '#808080',\n honeydew: '#f0fff0',\n hotpink: '#ff69b4',\n indianred: '#cd5c5c',\n indigo: '#4b0082',\n ivory: '#fffff0',\n khaki: '#f0e68c',\n lavender: '#e6e6fa',\n lavenderblush: '#fff0f5',\n lawngreen: '#7cfc00',\n lemonchiffon: '#fffacd',\n lightblue: '#add8e6',\n lightcoral: '#f08080',\n lightcyan: '#e0ffff',\n lightgoldenrodyellow: '#fafad2',\n lightgray: '#d3d3d3',\n lightgreen: '#90ee90',\n lightgrey: '#d3d3d3',\n lightpink: '#ffb6c1',\n lightsalmon: '#ffa07a',\n lightseagreen: '#20b2aa',\n lightskyblue: '#87cefa',\n lightslategray: '#778899',\n lightslategrey: '#778899',\n lightsteelblue: '#b0c4de',\n lightyellow: '#ffffe0',\n lime: '#00ff00',\n limegreen: '#32cd32',\n linen: '#faf0e6',\n magenta: '#ff00ff',\n maroon: '#800000',\n mediumaquamarine: '#66cdaa',\n mediumblue: '#0000cd',\n mediumorchid: '#ba55d3',\n mediumpurple: '#9370db',\n mediumseagreen: '#3cb371',\n mediumslateblue: '#7b68ee',\n mediumspringgreen: '#00fa9a',\n mediumturquoise: '#48d1cc',\n mediumvioletred: '#c71585',\n midnightblue: '#191970',\n mintcream: '#f5fffa',\n mistyrose: '#ffe4e1',\n moccasin: '#ffe4b5',\n navajowhite: '#ffdead',\n navy: '#000080',\n oldlace: '#fdf5e6',\n olive: '#808000',\n olivedrab: '#6b8e23',\n orange: '#ffa500',\n orangered: '#ff4500',\n orchid: '#da70d6',\n palegoldenrod: '#eee8aa',\n palegreen: '#98fb98',\n paleturquoise: '#afeeee',\n palevioletred: '#db7093',\n papayawhip: '#ffefd5',\n peachpuff: '#ffdab9',\n peru: '#cd853f',\n pink: '#ffc0cb',\n plum: '#dda0dd',\n powderblue: '#b0e0e6',\n purple: '#800080',\n rebeccapurple: '#663399',\n red: '#ff0000',\n rosybrown: '#bc8f8f',\n royalblue: '#4169e1',\n saddlebrown: '#8b4513',\n salmon: '#fa8072',\n sandybrown: '#f4a460',\n seagreen: '#2e8b57',\n seashell: '#fff5ee',\n sienna: '#a0522d',\n silver: '#c0c0c0',\n skyblue: '#87ceeb',\n slateblue: '#6a5acd',\n slategray: '#708090',\n slategrey: '#708090',\n snow: '#fffafa',\n springgreen: '#00ff7f',\n tan: '#d2b48c',\n teal: '#008080',\n thistle: '#d8bfd8',\n transparent: '#00000000',\n turquoise: '#40e0d0',\n violet: '#ee82ee',\n wheat: '#f5deb3',\n white: '#ffffff',\n whitesmoke: '#f5f5f5',\n yellow: '#ffff00',\n yellowgreen: '#9acd32'\n },\n /* API */\n parse: (color) => {\n color = color.toLowerCase();\n const hex = Keyword.colors[color];\n if (!hex)\n return;\n return Hex.parse(hex);\n },\n stringify: (channels) => {\n const hex = Hex.stringify(channels);\n for (const name in Keyword.colors) {\n if (Keyword.colors[name] === hex)\n return name;\n }\n return;\n }\n};\n/* EXPORT */\nexport default Keyword;\n", "/* IMPORT */\nimport _ from '../utils/index.js';\nimport ChannelsReusable from '../channels/reusable.js';\n/* MAIN */\nconst RGB = {\n /* VARIABLES */\n re: /^rgba?\\(\\s*?(-?(?:\\d+(?:\\.\\d+)?|(?:\\.\\d+))(?:e\\d+)?(%?))\\s*?(?:,|\\s)\\s*?(-?(?:\\d+(?:\\.\\d+)?|(?:\\.\\d+))(?:e\\d+)?(%?))\\s*?(?:,|\\s)\\s*?(-?(?:\\d+(?:\\.\\d+)?|(?:\\.\\d+))(?:e\\d+)?(%?))(?:\\s*?(?:,|\\/)\\s*?\\+?(-?(?:\\d+(?:\\.\\d+)?|(?:\\.\\d+))(?:e\\d+)?(%?)))?\\s*?\\)$/i,\n /* API */\n parse: (color) => {\n const charCode = color.charCodeAt(0);\n if (charCode !== 114 && charCode !== 82)\n return; // 'r'/'R'\n const match = color.match(RGB.re);\n if (!match)\n return;\n const [, r, isRedPercentage, g, isGreenPercentage, b, isBluePercentage, a, isAlphaPercentage] = match;\n return ChannelsReusable.set({\n r: _.channel.clamp.r(isRedPercentage ? parseFloat(r) * 2.55 : parseFloat(r)),\n g: _.channel.clamp.g(isGreenPercentage ? parseFloat(g) * 2.55 : parseFloat(g)),\n b: _.channel.clamp.b(isBluePercentage ? parseFloat(b) * 2.55 : parseFloat(b)),\n a: a ? _.channel.clamp.a(isAlphaPercentage ? parseFloat(a) / 100 : parseFloat(a)) : 1\n }, color);\n },\n stringify: (channels) => {\n const { r, g, b, a } = channels;\n if (a < 1) { // RGBA\n return `rgba(${_.lang.round(r)}, ${_.lang.round(g)}, ${_.lang.round(b)}, ${_.lang.round(a)})`;\n }\n else { // RGB\n return `rgb(${_.lang.round(r)}, ${_.lang.round(g)}, ${_.lang.round(b)})`;\n }\n }\n};\n/* EXPORT */\nexport default RGB;\n", "/* IMPORT */\nimport _ from '../utils/index.js';\nimport Hex from './hex.js';\nimport HSL from './hsl.js';\nimport Keyword from './keyword.js';\nimport RGB from './rgb.js';\nimport { TYPE } from '../constants.js';\n/* MAIN */\nconst Color = {\n /* VARIABLES */\n format: {\n keyword: Keyword,\n hex: Hex,\n rgb: RGB,\n rgba: RGB,\n hsl: HSL,\n hsla: HSL\n },\n /* API */\n parse: (color) => {\n if (typeof color !== 'string')\n return color;\n const channels = Hex.parse(color) || RGB.parse(color) || HSL.parse(color) || Keyword.parse(color); // Color providers ordered with performance in mind\n if (channels)\n return channels;\n throw new Error(`Unsupported color format: \"${color}\"`);\n },\n stringify: (channels) => {\n // SASS returns a keyword if possible, but we avoid doing that as it's slower and doesn't really add any value\n if (!channels.changed && channels.color)\n return channels.color;\n if (channels.type.is(TYPE.HSL) || channels.data.r === undefined) {\n return HSL.stringify(channels);\n }\n else if (channels.a < 1 || !Number.isInteger(channels.r) || !Number.isInteger(channels.g) || !Number.isInteger(channels.b)) {\n return RGB.stringify(channels);\n }\n else {\n return Hex.stringify(channels);\n }\n }\n};\n/* EXPORT */\nexport default Color;\n", "/* IMPORT */\nimport _ from '../utils/index.js';\nimport Color from '../color/index.js';\n/* MAIN */\nconst change = (color, channels) => {\n const ch = Color.parse(color);\n for (const c in channels) {\n ch[c] = _.channel.clamp[c](channels[c]);\n }\n return Color.stringify(ch);\n};\n/* EXPORT */\nexport default change;\n", "/* IMPORT */\nimport _ from '../utils/index.js';\nimport ChannelsReusable from '../channels/reusable.js';\nimport Color from '../color/index.js';\nimport change from './change.js';\n/* MAIN */\nconst rgba = (r, g, b = 0, a = 1) => {\n if (typeof r !== 'number')\n return change(r, { a: g });\n const channels = ChannelsReusable.set({\n r: _.channel.clamp.r(r),\n g: _.channel.clamp.g(g),\n b: _.channel.clamp.b(b),\n a: _.channel.clamp.a(a)\n });\n return Color.stringify(channels);\n};\n/* EXPORT */\nexport default rgba;\n", "/* IMPORT */\nimport _ from '../utils/index.js';\nimport Color from '../color/index.js';\n/* MAIN */\nconst channel = (color, channel) => {\n return _.lang.round(Color.parse(color)[channel]);\n};\n/* EXPORT */\nexport default channel;\n", "/* IMPORT */\nimport _ from '../utils/index.js';\nimport Color from '../color/index.js';\n/* MAIN */\n//SOURCE: https://planetcalc.com/7779\nconst luminance = (color) => {\n const { r, g, b } = Color.parse(color);\n const luminance = .2126 * _.channel.toLinear(r) + .7152 * _.channel.toLinear(g) + .0722 * _.channel.toLinear(b);\n return _.lang.round(luminance);\n};\n/* EXPORT */\nexport default luminance;\n", "/* IMPORT */\nimport luminance from './luminance.js';\n/* MAIN */\nconst isLight = (color) => {\n return luminance(color) >= .5;\n};\n/* EXPORT */\nexport default isLight;\n", "/* IMPORT */\nimport isLight from './is_light.js';\n/* MAIN */\nconst isDark = (color) => {\n return !isLight(color);\n};\n/* EXPORT */\nexport default isDark;\n", "/* IMPORT */\nimport _ from '../utils/index.js';\nimport Color from '../color/index.js';\n/* MAIN */\nconst adjustChannel = (color, channel, amount) => {\n const channels = Color.parse(color);\n const amountCurrent = channels[channel];\n const amountNext = _.channel.clamp[channel](amountCurrent + amount);\n if (amountCurrent !== amountNext)\n channels[channel] = amountNext;\n return Color.stringify(channels);\n};\n/* EXPORT */\nexport default adjustChannel;\n", "/* IMPORT */\nimport adjustChannel from './adjust_channel.js';\n/* MAIN */\nconst lighten = (color, amount) => {\n return adjustChannel(color, 'l', amount);\n};\n/* EXPORT */\nexport default lighten;\n", "/* IMPORT */\nimport adjustChannel from './adjust_channel.js';\n/* MAIN */\nconst darken = (color, amount) => {\n return adjustChannel(color, 'l', -amount);\n};\n/* EXPORT */\nexport default darken;\n", "/* IMPORT */\nimport Color from '../color/index.js';\nimport change from './change.js';\n/* MAIN */\nconst adjust = (color, channels) => {\n const ch = Color.parse(color);\n const changes = {};\n for (const c in channels) {\n if (!channels[c])\n continue;\n changes[c] = ch[c] + channels[c];\n }\n return change(color, changes);\n};\n/* EXPORT */\nexport default adjust;\n", "/* IMPORT */\nimport Color from '../color/index.js';\nimport rgba from './rgba.js';\n/* MAIN */\n//SOURCE: https://github.com/sass/dart-sass/blob/7457d2e9e7e623d9844ffd037a070cf32d39c348/lib/src/functions/color.dart#L718-L756\nconst mix = (color1, color2, weight = 50) => {\n const { r: r1, g: g1, b: b1, a: a1 } = Color.parse(color1);\n const { r: r2, g: g2, b: b2, a: a2 } = Color.parse(color2);\n const weightScale = weight / 100;\n const weightNormalized = (weightScale * 2) - 1;\n const alphaDelta = a1 - a2;\n const weight1combined = ((weightNormalized * alphaDelta) === -1) ? weightNormalized : (weightNormalized + alphaDelta) / (1 + weightNormalized * alphaDelta);\n const weight1 = (weight1combined + 1) / 2;\n const weight2 = 1 - weight1;\n const r = (r1 * weight1) + (r2 * weight2);\n const g = (g1 * weight1) + (g2 * weight2);\n const b = (b1 * weight1) + (b2 * weight2);\n const a = (a1 * weightScale) + (a2 * (1 - weightScale));\n return rgba(r, g, b, a);\n};\n/* EXPORT */\nexport default mix;\n", "/* IMPORT */\nimport Color from '../color/index.js';\nimport mix from './mix.js';\n/* MAIN */\nconst invert = (color, weight = 100) => {\n const inverse = Color.parse(color);\n inverse.r = 255 - inverse.r;\n inverse.g = 255 - inverse.g;\n inverse.b = 255 - inverse.b;\n return mix(inverse, color, weight);\n};\n/* EXPORT */\nexport default invert;\n", "const {\n entries,\n setPrototypeOf,\n isFrozen,\n getPrototypeOf,\n getOwnPropertyDescriptor,\n} = Object;\n\nlet { freeze, seal, create } = Object; // eslint-disable-line import/no-mutable-exports\nlet { apply, construct } = typeof Reflect !== 'undefined' && Reflect;\n\nif (!freeze) {\n freeze = function (x: T): T {\n return x;\n };\n}\n\nif (!seal) {\n seal = function (x: T): T {\n return x;\n };\n}\n\nif (!apply) {\n apply = function (\n func: (thisArg: any, ...args: any[]) => T,\n thisArg: any,\n ...args: any[]\n ): T {\n return func.apply(thisArg, args);\n };\n}\n\nif (!construct) {\n construct = function (Func: new (...args: any[]) => T, ...args: any[]): T {\n return new Func(...args);\n };\n}\n\nconst arrayForEach = unapply(Array.prototype.forEach);\nconst arrayIndexOf = unapply(Array.prototype.indexOf);\nconst arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);\nconst arrayPop = unapply(Array.prototype.pop);\nconst arrayPush = unapply(Array.prototype.push);\nconst arraySlice = unapply(Array.prototype.slice);\nconst arraySplice = unapply(Array.prototype.splice);\n\nconst stringToLowerCase = unapply(String.prototype.toLowerCase);\nconst stringToString = unapply(String.prototype.toString);\nconst stringMatch = unapply(String.prototype.match);\nconst stringReplace = unapply(String.prototype.replace);\nconst stringIndexOf = unapply(String.prototype.indexOf);\nconst stringTrim = unapply(String.prototype.trim);\n\nconst objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);\n\nconst regExpTest = unapply(RegExp.prototype.test);\n\nconst typeErrorCreate = unconstruct(TypeError);\n\n/**\n * Creates a new function that calls the given function with a specified thisArg and arguments.\n *\n * @param func - The function to be wrapped and called.\n * @returns A new function that calls the given function with a specified thisArg and arguments.\n */\nfunction unapply(\n func: (thisArg: any, ...args: any[]) => T\n): (thisArg: any, ...args: any[]) => T {\n return (thisArg: any, ...args: any[]): T => {\n if (thisArg instanceof RegExp) {\n thisArg.lastIndex = 0;\n }\n\n return apply(func, thisArg, args);\n };\n}\n\n/**\n * Creates a new function that constructs an instance of the given constructor function with the provided arguments.\n *\n * @param func - The constructor function to be wrapped and called.\n * @returns A new function that constructs an instance of the given constructor function with the provided arguments.\n */\nfunction unconstruct(\n Func: new (...args: any[]) => T\n): (...args: any[]) => T {\n return (...args: any[]): T => construct(Func, args);\n}\n\n/**\n * Add properties to a lookup table\n *\n * @param set - The set to which elements will be added.\n * @param array - The array containing elements to be added to the set.\n * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.\n * @returns The modified set with added elements.\n */\nfunction addToSet(\n set: Record,\n array: readonly any[],\n transformCaseFunc: ReturnType> = stringToLowerCase\n): Record {\n if (setPrototypeOf) {\n // Make 'in' and truthy checks like Boolean(set.constructor)\n // independent of any properties defined on Object.prototype.\n // Prevent prototype setters from intercepting set as a this value.\n setPrototypeOf(set, null);\n }\n\n let l = array.length;\n while (l--) {\n let element = array[l];\n if (typeof element === 'string') {\n const lcElement = transformCaseFunc(element);\n if (lcElement !== element) {\n // Config presets (e.g. tags.js, attrs.js) are immutable.\n if (!isFrozen(array)) {\n (array as any[])[l] = lcElement;\n }\n\n element = lcElement;\n }\n }\n\n set[element] = true;\n }\n\n return set;\n}\n\n/**\n * Clean up an array to harden against CSPP\n *\n * @param array - The array to be cleaned.\n * @returns The cleaned version of the array\n */\nfunction cleanArray(array: T[]): Array {\n for (let index = 0; index < array.length; index++) {\n const isPropertyExist = objectHasOwnProperty(array, index);\n\n if (!isPropertyExist) {\n array[index] = null;\n }\n }\n\n return array;\n}\n\n/**\n * Shallow clone an object\n *\n * @param object - The object to be cloned.\n * @returns A new object that copies the original.\n */\nfunction clone>(object: T): T {\n const newObject = create(null);\n\n for (const [property, value] of entries(object)) {\n const isPropertyExist = objectHasOwnProperty(object, property);\n\n if (isPropertyExist) {\n if (Array.isArray(value)) {\n newObject[property] = cleanArray(value);\n } else if (\n value &&\n typeof value === 'object' &&\n value.constructor === Object\n ) {\n newObject[property] = clone(value);\n } else {\n newObject[property] = value;\n }\n }\n }\n\n return newObject;\n}\n\n/**\n * This method automatically checks if the prop is function or getter and behaves accordingly.\n *\n * @param object - The object to look up the getter function in its prototype chain.\n * @param prop - The property name for which to find the getter function.\n * @returns The getter function found in the prototype chain or a fallback function.\n */\nfunction lookupGetter>(\n object: T,\n prop: string\n): ReturnType> | (() => null) {\n while (object !== null) {\n const desc = getOwnPropertyDescriptor(object, prop);\n\n if (desc) {\n if (desc.get) {\n return unapply(desc.get);\n }\n\n if (typeof desc.value === 'function') {\n return unapply(desc.value);\n }\n }\n\n object = getPrototypeOf(object);\n }\n\n function fallbackValue(): null {\n return null;\n }\n\n return fallbackValue;\n}\n\nexport {\n // Array\n arrayForEach,\n arrayIndexOf,\n arrayLastIndexOf,\n arrayPop,\n arrayPush,\n arraySlice,\n arraySplice,\n // Object\n entries,\n freeze,\n getPrototypeOf,\n getOwnPropertyDescriptor,\n isFrozen,\n setPrototypeOf,\n seal,\n clone,\n create,\n objectHasOwnProperty,\n // RegExp\n regExpTest,\n // String\n stringIndexOf,\n stringMatch,\n stringReplace,\n stringToLowerCase,\n stringToString,\n stringTrim,\n // Errors\n typeErrorCreate,\n // Other\n lookupGetter,\n addToSet,\n // Reflect\n unapply,\n unconstruct,\n};\n", "import { freeze } from './utils.js';\n\nexport const html = freeze([\n 'a',\n 'abbr',\n 'acronym',\n 'address',\n 'area',\n 'article',\n 'aside',\n 'audio',\n 'b',\n 'bdi',\n 'bdo',\n 'big',\n 'blink',\n 'blockquote',\n 'body',\n 'br',\n 'button',\n 'canvas',\n 'caption',\n 'center',\n 'cite',\n 'code',\n 'col',\n 'colgroup',\n 'content',\n 'data',\n 'datalist',\n 'dd',\n 'decorator',\n 'del',\n 'details',\n 'dfn',\n 'dialog',\n 'dir',\n 'div',\n 'dl',\n 'dt',\n 'element',\n 'em',\n 'fieldset',\n 'figcaption',\n 'figure',\n 'font',\n 'footer',\n 'form',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'head',\n 'header',\n 'hgroup',\n 'hr',\n 'html',\n 'i',\n 'img',\n 'input',\n 'ins',\n 'kbd',\n 'label',\n 'legend',\n 'li',\n 'main',\n 'map',\n 'mark',\n 'marquee',\n 'menu',\n 'menuitem',\n 'meter',\n 'nav',\n 'nobr',\n 'ol',\n 'optgroup',\n 'option',\n 'output',\n 'p',\n 'picture',\n 'pre',\n 'progress',\n 'q',\n 'rp',\n 'rt',\n 'ruby',\n 's',\n 'samp',\n 'search',\n 'section',\n 'select',\n 'shadow',\n 'slot',\n 'small',\n 'source',\n 'spacer',\n 'span',\n 'strike',\n 'strong',\n 'style',\n 'sub',\n 'summary',\n 'sup',\n 'table',\n 'tbody',\n 'td',\n 'template',\n 'textarea',\n 'tfoot',\n 'th',\n 'thead',\n 'time',\n 'tr',\n 'track',\n 'tt',\n 'u',\n 'ul',\n 'var',\n 'video',\n 'wbr',\n] as const);\n\nexport const svg = freeze([\n 'svg',\n 'a',\n 'altglyph',\n 'altglyphdef',\n 'altglyphitem',\n 'animatecolor',\n 'animatemotion',\n 'animatetransform',\n 'circle',\n 'clippath',\n 'defs',\n 'desc',\n 'ellipse',\n 'enterkeyhint',\n 'exportparts',\n 'filter',\n 'font',\n 'g',\n 'glyph',\n 'glyphref',\n 'hkern',\n 'image',\n 'inputmode',\n 'line',\n 'lineargradient',\n 'marker',\n 'mask',\n 'metadata',\n 'mpath',\n 'part',\n 'path',\n 'pattern',\n 'polygon',\n 'polyline',\n 'radialgradient',\n 'rect',\n 'slot',\n 'stop',\n 'style',\n 'switch',\n 'symbol',\n 'text',\n 'textpath',\n 'title',\n 'tref',\n 'tspan',\n 'view',\n 'vkern',\n] as const);\n\nexport const svgFilters = freeze([\n 'feBlend',\n 'feColorMatrix',\n 'feComponentTransfer',\n 'feComposite',\n 'feConvolveMatrix',\n 'feDiffuseLighting',\n 'feDisplacementMap',\n 'feDistantLight',\n 'feDropShadow',\n 'feFlood',\n 'feFuncA',\n 'feFuncB',\n 'feFuncG',\n 'feFuncR',\n 'feGaussianBlur',\n 'feImage',\n 'feMerge',\n 'feMergeNode',\n 'feMorphology',\n 'feOffset',\n 'fePointLight',\n 'feSpecularLighting',\n 'feSpotLight',\n 'feTile',\n 'feTurbulence',\n] as const);\n\n// List of SVG elements that are disallowed by default.\n// We still need to know them so that we can do namespace\n// checks properly in case one wants to add them to\n// allow-list.\nexport const svgDisallowed = freeze([\n 'animate',\n 'color-profile',\n 'cursor',\n 'discard',\n 'font-face',\n 'font-face-format',\n 'font-face-name',\n 'font-face-src',\n 'font-face-uri',\n 'foreignobject',\n 'hatch',\n 'hatchpath',\n 'mesh',\n 'meshgradient',\n 'meshpatch',\n 'meshrow',\n 'missing-glyph',\n 'script',\n 'set',\n 'solidcolor',\n 'unknown',\n 'use',\n] as const);\n\nexport const mathMl = freeze([\n 'math',\n 'menclose',\n 'merror',\n 'mfenced',\n 'mfrac',\n 'mglyph',\n 'mi',\n 'mlabeledtr',\n 'mmultiscripts',\n 'mn',\n 'mo',\n 'mover',\n 'mpadded',\n 'mphantom',\n 'mroot',\n 'mrow',\n 'ms',\n 'mspace',\n 'msqrt',\n 'mstyle',\n 'msub',\n 'msup',\n 'msubsup',\n 'mtable',\n 'mtd',\n 'mtext',\n 'mtr',\n 'munder',\n 'munderover',\n 'mprescripts',\n] as const);\n\n// Similarly to SVG, we want to know all MathML elements,\n// even those that we disallow by default.\nexport const mathMlDisallowed = freeze([\n 'maction',\n 'maligngroup',\n 'malignmark',\n 'mlongdiv',\n 'mscarries',\n 'mscarry',\n 'msgroup',\n 'mstack',\n 'msline',\n 'msrow',\n 'semantics',\n 'annotation',\n 'annotation-xml',\n 'mprescripts',\n 'none',\n] as const);\n\nexport const text = freeze(['#text'] as const);\n", "import { freeze } from './utils.js';\n\nexport const html = freeze([\n 'accept',\n 'action',\n 'align',\n 'alt',\n 'autocapitalize',\n 'autocomplete',\n 'autopictureinpicture',\n 'autoplay',\n 'background',\n 'bgcolor',\n 'border',\n 'capture',\n 'cellpadding',\n 'cellspacing',\n 'checked',\n 'cite',\n 'class',\n 'clear',\n 'color',\n 'cols',\n 'colspan',\n 'controls',\n 'controlslist',\n 'coords',\n 'crossorigin',\n 'datetime',\n 'decoding',\n 'default',\n 'dir',\n 'disabled',\n 'disablepictureinpicture',\n 'disableremoteplayback',\n 'download',\n 'draggable',\n 'enctype',\n 'enterkeyhint',\n 'exportparts',\n 'face',\n 'for',\n 'headers',\n 'height',\n 'hidden',\n 'high',\n 'href',\n 'hreflang',\n 'id',\n 'inert',\n 'inputmode',\n 'integrity',\n 'ismap',\n 'kind',\n 'label',\n 'lang',\n 'list',\n 'loading',\n 'loop',\n 'low',\n 'max',\n 'maxlength',\n 'media',\n 'method',\n 'min',\n 'minlength',\n 'multiple',\n 'muted',\n 'name',\n 'nonce',\n 'noshade',\n 'novalidate',\n 'nowrap',\n 'open',\n 'optimum',\n 'part',\n 'pattern',\n 'placeholder',\n 'playsinline',\n 'popover',\n 'popovertarget',\n 'popovertargetaction',\n 'poster',\n 'preload',\n 'pubdate',\n 'radiogroup',\n 'readonly',\n 'rel',\n 'required',\n 'rev',\n 'reversed',\n 'role',\n 'rows',\n 'rowspan',\n 'spellcheck',\n 'scope',\n 'selected',\n 'shape',\n 'size',\n 'sizes',\n 'slot',\n 'span',\n 'srclang',\n 'start',\n 'src',\n 'srcset',\n 'step',\n 'style',\n 'summary',\n 'tabindex',\n 'title',\n 'translate',\n 'type',\n 'usemap',\n 'valign',\n 'value',\n 'width',\n 'wrap',\n 'xmlns',\n 'slot',\n] as const);\n\nexport const svg = freeze([\n 'accent-height',\n 'accumulate',\n 'additive',\n 'alignment-baseline',\n 'amplitude',\n 'ascent',\n 'attributename',\n 'attributetype',\n 'azimuth',\n 'basefrequency',\n 'baseline-shift',\n 'begin',\n 'bias',\n 'by',\n 'class',\n 'clip',\n 'clippathunits',\n 'clip-path',\n 'clip-rule',\n 'color',\n 'color-interpolation',\n 'color-interpolation-filters',\n 'color-profile',\n 'color-rendering',\n 'cx',\n 'cy',\n 'd',\n 'dx',\n 'dy',\n 'diffuseconstant',\n 'direction',\n 'display',\n 'divisor',\n 'dur',\n 'edgemode',\n 'elevation',\n 'end',\n 'exponent',\n 'fill',\n 'fill-opacity',\n 'fill-rule',\n 'filter',\n 'filterunits',\n 'flood-color',\n 'flood-opacity',\n 'font-family',\n 'font-size',\n 'font-size-adjust',\n 'font-stretch',\n 'font-style',\n 'font-variant',\n 'font-weight',\n 'fx',\n 'fy',\n 'g1',\n 'g2',\n 'glyph-name',\n 'glyphref',\n 'gradientunits',\n 'gradienttransform',\n 'height',\n 'href',\n 'id',\n 'image-rendering',\n 'in',\n 'in2',\n 'intercept',\n 'k',\n 'k1',\n 'k2',\n 'k3',\n 'k4',\n 'kerning',\n 'keypoints',\n 'keysplines',\n 'keytimes',\n 'lang',\n 'lengthadjust',\n 'letter-spacing',\n 'kernelmatrix',\n 'kernelunitlength',\n 'lighting-color',\n 'local',\n 'marker-end',\n 'marker-mid',\n 'marker-start',\n 'markerheight',\n 'markerunits',\n 'markerwidth',\n 'maskcontentunits',\n 'maskunits',\n 'max',\n 'mask',\n 'media',\n 'method',\n 'mode',\n 'min',\n 'name',\n 'numoctaves',\n 'offset',\n 'operator',\n 'opacity',\n 'order',\n 'orient',\n 'orientation',\n 'origin',\n 'overflow',\n 'paint-order',\n 'path',\n 'pathlength',\n 'patterncontentunits',\n 'patterntransform',\n 'patternunits',\n 'points',\n 'preservealpha',\n 'preserveaspectratio',\n 'primitiveunits',\n 'r',\n 'rx',\n 'ry',\n 'radius',\n 'refx',\n 'refy',\n 'repeatcount',\n 'repeatdur',\n 'restart',\n 'result',\n 'rotate',\n 'scale',\n 'seed',\n 'shape-rendering',\n 'slope',\n 'specularconstant',\n 'specularexponent',\n 'spreadmethod',\n 'startoffset',\n 'stddeviation',\n 'stitchtiles',\n 'stop-color',\n 'stop-opacity',\n 'stroke-dasharray',\n 'stroke-dashoffset',\n 'stroke-linecap',\n 'stroke-linejoin',\n 'stroke-miterlimit',\n 'stroke-opacity',\n 'stroke',\n 'stroke-width',\n 'style',\n 'surfacescale',\n 'systemlanguage',\n 'tabindex',\n 'tablevalues',\n 'targetx',\n 'targety',\n 'transform',\n 'transform-origin',\n 'text-anchor',\n 'text-decoration',\n 'text-rendering',\n 'textlength',\n 'type',\n 'u1',\n 'u2',\n 'unicode',\n 'values',\n 'viewbox',\n 'visibility',\n 'version',\n 'vert-adv-y',\n 'vert-origin-x',\n 'vert-origin-y',\n 'width',\n 'word-spacing',\n 'wrap',\n 'writing-mode',\n 'xchannelselector',\n 'ychannelselector',\n 'x',\n 'x1',\n 'x2',\n 'xmlns',\n 'y',\n 'y1',\n 'y2',\n 'z',\n 'zoomandpan',\n] as const);\n\nexport const mathMl = freeze([\n 'accent',\n 'accentunder',\n 'align',\n 'bevelled',\n 'close',\n 'columnsalign',\n 'columnlines',\n 'columnspan',\n 'denomalign',\n 'depth',\n 'dir',\n 'display',\n 'displaystyle',\n 'encoding',\n 'fence',\n 'frame',\n 'height',\n 'href',\n 'id',\n 'largeop',\n 'length',\n 'linethickness',\n 'lspace',\n 'lquote',\n 'mathbackground',\n 'mathcolor',\n 'mathsize',\n 'mathvariant',\n 'maxsize',\n 'minsize',\n 'movablelimits',\n 'notation',\n 'numalign',\n 'open',\n 'rowalign',\n 'rowlines',\n 'rowspacing',\n 'rowspan',\n 'rspace',\n 'rquote',\n 'scriptlevel',\n 'scriptminsize',\n 'scriptsizemultiplier',\n 'selection',\n 'separator',\n 'separators',\n 'stretchy',\n 'subscriptshift',\n 'supscriptshift',\n 'symmetric',\n 'voffset',\n 'width',\n 'xmlns',\n]);\n\nexport const xml = freeze([\n 'xlink:href',\n 'xml:id',\n 'xlink:title',\n 'xml:space',\n 'xmlns:xlink',\n] as const);\n", "import { seal } from './utils.js';\n\n// eslint-disable-next-line unicorn/better-regex\nexport const MUSTACHE_EXPR = seal(/\\{\\{[\\w\\W]*|[\\w\\W]*\\}\\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode\nexport const ERB_EXPR = seal(/<%[\\w\\W]*|[\\w\\W]*%>/gm);\nexport const TMPLIT_EXPR = seal(/\\$\\{[\\w\\W]*/gm); // eslint-disable-line unicorn/better-regex\nexport const DATA_ATTR = seal(/^data-[\\-\\w.\\u00B7-\\uFFFF]+$/); // eslint-disable-line no-useless-escape\nexport const ARIA_ATTR = seal(/^aria-[\\-\\w]+$/); // eslint-disable-line no-useless-escape\nexport const IS_ALLOWED_URI = seal(\n /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i // eslint-disable-line no-useless-escape\n);\nexport const IS_SCRIPT_OR_DATA = seal(/^(?:\\w+script|data):/i);\nexport const ATTR_WHITESPACE = seal(\n /[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]/g // eslint-disable-line no-control-regex\n);\nexport const DOCTYPE_NAME = seal(/^html$/i);\nexport const CUSTOM_ELEMENT = seal(/^[a-z][.\\w]*(-[.\\w]+)+$/i);\n", "/* eslint-disable @typescript-eslint/indent */\n\nimport type { TrustedHTML, TrustedTypesWindow } from 'trusted-types/lib';\nimport type { Config, UseProfilesConfig } from './config';\nimport * as TAGS from './tags.js';\nimport * as ATTRS from './attrs.js';\nimport * as EXPRESSIONS from './regexp.js';\nimport {\n addToSet,\n clone,\n entries,\n freeze,\n arrayForEach,\n arrayLastIndexOf,\n arrayPop,\n arrayPush,\n arraySplice,\n stringMatch,\n stringReplace,\n stringToLowerCase,\n stringToString,\n stringIndexOf,\n stringTrim,\n regExpTest,\n typeErrorCreate,\n lookupGetter,\n create,\n objectHasOwnProperty,\n} from './utils.js';\n\nexport type { Config } from './config';\n\ndeclare const VERSION: string;\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType\nconst NODE_TYPE = {\n element: 1,\n attribute: 2,\n text: 3,\n cdataSection: 4,\n entityReference: 5, // Deprecated\n entityNode: 6, // Deprecated\n progressingInstruction: 7,\n comment: 8,\n document: 9,\n documentType: 10,\n documentFragment: 11,\n notation: 12, // Deprecated\n};\n\nconst getGlobal = function (): WindowLike {\n return typeof window === 'undefined' ? null : window;\n};\n\n/**\n * Creates a no-op policy for internal use only.\n * Don't export this function outside this module!\n * @param trustedTypes The policy factory.\n * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).\n * @return The policy created (or null, if Trusted Types\n * are not supported or creating the policy failed).\n */\nconst _createTrustedTypesPolicy = function (\n trustedTypes: TrustedTypePolicyFactory,\n purifyHostElement: HTMLScriptElement\n) {\n if (\n typeof trustedTypes !== 'object' ||\n typeof trustedTypes.createPolicy !== 'function'\n ) {\n return null;\n }\n\n // Allow the callers to control the unique policy name\n // by adding a data-tt-policy-suffix to the script element with the DOMPurify.\n // Policy creation with duplicate names throws in Trusted Types.\n let suffix = null;\n const ATTR_NAME = 'data-tt-policy-suffix';\n if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {\n suffix = purifyHostElement.getAttribute(ATTR_NAME);\n }\n\n const policyName = 'dompurify' + (suffix ? '#' + suffix : '');\n\n try {\n return trustedTypes.createPolicy(policyName, {\n createHTML(html) {\n return html;\n },\n createScriptURL(scriptUrl) {\n return scriptUrl;\n },\n });\n } catch (_) {\n // Policy creation failed (most likely another DOMPurify script has\n // already run). Skip creating the policy, as this will only cause errors\n // if TT are enforced.\n console.warn(\n 'TrustedTypes policy ' + policyName + ' could not be created.'\n );\n return null;\n }\n};\n\nconst _createHooksMap = function (): HooksMap {\n return {\n afterSanitizeAttributes: [],\n afterSanitizeElements: [],\n afterSanitizeShadowDOM: [],\n beforeSanitizeAttributes: [],\n beforeSanitizeElements: [],\n beforeSanitizeShadowDOM: [],\n uponSanitizeAttribute: [],\n uponSanitizeElement: [],\n uponSanitizeShadowNode: [],\n };\n};\n\nfunction createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {\n const DOMPurify: DOMPurify = (root: WindowLike) => createDOMPurify(root);\n\n DOMPurify.version = VERSION;\n\n DOMPurify.removed = [];\n\n if (\n !window ||\n !window.document ||\n window.document.nodeType !== NODE_TYPE.document ||\n !window.Element\n ) {\n // Not running in a browser, provide a factory function\n // so that you can pass your own Window\n DOMPurify.isSupported = false;\n\n return DOMPurify;\n }\n\n let { document } = window;\n\n const originalDocument = document;\n const currentScript: HTMLScriptElement =\n originalDocument.currentScript as HTMLScriptElement;\n const {\n DocumentFragment,\n HTMLTemplateElement,\n Node,\n Element,\n NodeFilter,\n NamedNodeMap = window.NamedNodeMap || (window as any).MozNamedAttrMap,\n HTMLFormElement,\n DOMParser,\n trustedTypes,\n } = window;\n\n const ElementPrototype = Element.prototype;\n\n const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');\n const remove = lookupGetter(ElementPrototype, 'remove');\n const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');\n const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');\n const getParentNode = lookupGetter(ElementPrototype, 'parentNode');\n\n // As per issue #47, the web-components registry is inherited by a\n // new document created via createHTMLDocument. As per the spec\n // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)\n // a new empty registry is used when creating a template contents owner\n // document, so we use that as our parent document to ensure nothing\n // is inherited.\n if (typeof HTMLTemplateElement === 'function') {\n const template = document.createElement('template');\n if (template.content && template.content.ownerDocument) {\n document = template.content.ownerDocument;\n }\n }\n\n let trustedTypesPolicy;\n let emptyHTML = '';\n\n const {\n implementation,\n createNodeIterator,\n createDocumentFragment,\n getElementsByTagName,\n } = document;\n const { importNode } = originalDocument;\n\n let hooks = _createHooksMap();\n\n /**\n * Expose whether this browser supports running the full DOMPurify.\n */\n DOMPurify.isSupported =\n typeof entries === 'function' &&\n typeof getParentNode === 'function' &&\n implementation &&\n implementation.createHTMLDocument !== undefined;\n\n const {\n MUSTACHE_EXPR,\n ERB_EXPR,\n TMPLIT_EXPR,\n DATA_ATTR,\n ARIA_ATTR,\n IS_SCRIPT_OR_DATA,\n ATTR_WHITESPACE,\n CUSTOM_ELEMENT,\n } = EXPRESSIONS;\n\n let { IS_ALLOWED_URI } = EXPRESSIONS;\n\n /**\n * We consider the elements and attributes below to be safe. Ideally\n * don't add any new ones but feel free to remove unwanted ones.\n */\n\n /* allowed element names */\n let ALLOWED_TAGS = null;\n const DEFAULT_ALLOWED_TAGS = addToSet({}, [\n ...TAGS.html,\n ...TAGS.svg,\n ...TAGS.svgFilters,\n ...TAGS.mathMl,\n ...TAGS.text,\n ]);\n\n /* Allowed attribute names */\n let ALLOWED_ATTR = null;\n const DEFAULT_ALLOWED_ATTR = addToSet({}, [\n ...ATTRS.html,\n ...ATTRS.svg,\n ...ATTRS.mathMl,\n ...ATTRS.xml,\n ]);\n\n /*\n * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.\n * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)\n * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)\n * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.\n */\n let CUSTOM_ELEMENT_HANDLING = Object.seal(\n create(null, {\n tagNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null,\n },\n attributeNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null,\n },\n allowCustomizedBuiltInElements: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: false,\n },\n })\n );\n\n /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */\n let FORBID_TAGS = null;\n\n /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */\n let FORBID_ATTR = null;\n\n /* Decide if ARIA attributes are okay */\n let ALLOW_ARIA_ATTR = true;\n\n /* Decide if custom data attributes are okay */\n let ALLOW_DATA_ATTR = true;\n\n /* Decide if unknown protocols are okay */\n let ALLOW_UNKNOWN_PROTOCOLS = false;\n\n /* Decide if self-closing tags in attributes are allowed.\n * Usually removed due to a mXSS issue in jQuery 3.0 */\n let ALLOW_SELF_CLOSE_IN_ATTR = true;\n\n /* Output should be safe for common template engines.\n * This means, DOMPurify removes data attributes, mustaches and ERB\n */\n let SAFE_FOR_TEMPLATES = false;\n\n /* Output should be safe even for XML used within HTML and alike.\n * This means, DOMPurify removes comments when containing risky content.\n */\n let SAFE_FOR_XML = true;\n\n /* Decide if document with ... should be returned */\n let WHOLE_DOCUMENT = false;\n\n /* Track whether config is already set on this instance of DOMPurify. */\n let SET_CONFIG = false;\n\n /* Decide if all elements (e.g. style, script) must be children of\n * document.body. By default, browsers might move them to document.head */\n let FORCE_BODY = false;\n\n /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported).\n * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead\n */\n let RETURN_DOM = false;\n\n /* Decide if a DOM `DocumentFragment` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported) */\n let RETURN_DOM_FRAGMENT = false;\n\n /* Try to return a Trusted Type object instead of a string, return a string in\n * case Trusted Types are not supported */\n let RETURN_TRUSTED_TYPE = false;\n\n /* Output should be free from DOM clobbering attacks?\n * This sanitizes markups named with colliding, clobberable built-in DOM APIs.\n */\n let SANITIZE_DOM = true;\n\n /* Achieve full DOM Clobbering protection by isolating the namespace of named\n * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.\n *\n * HTML/DOM spec rules that enable DOM Clobbering:\n * - Named Access on Window (§7.3.3)\n * - DOM Tree Accessors (§3.1.5)\n * - Form Element Parent-Child Relations (§4.10.3)\n * - Iframe srcdoc / Nested WindowProxies (§4.8.5)\n * - HTMLCollection (§4.2.10.2)\n *\n * Namespace isolation is implemented by prefixing `id` and `name` attributes\n * with a constant string, i.e., `user-content-`\n */\n let SANITIZE_NAMED_PROPS = false;\n const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';\n\n /* Keep element content when removing element? */\n let KEEP_CONTENT = true;\n\n /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead\n * of importing it into a new Document and returning a sanitized copy */\n let IN_PLACE = false;\n\n /* Allow usage of profiles like html, svg and mathMl */\n let USE_PROFILES: UseProfilesConfig | false = {};\n\n /* Tags to ignore content of when KEEP_CONTENT is true */\n let FORBID_CONTENTS = null;\n const DEFAULT_FORBID_CONTENTS = addToSet({}, [\n 'annotation-xml',\n 'audio',\n 'colgroup',\n 'desc',\n 'foreignobject',\n 'head',\n 'iframe',\n 'math',\n 'mi',\n 'mn',\n 'mo',\n 'ms',\n 'mtext',\n 'noembed',\n 'noframes',\n 'noscript',\n 'plaintext',\n 'script',\n 'style',\n 'svg',\n 'template',\n 'thead',\n 'title',\n 'video',\n 'xmp',\n ]);\n\n /* Tags that are safe for data: URIs */\n let DATA_URI_TAGS = null;\n const DEFAULT_DATA_URI_TAGS = addToSet({}, [\n 'audio',\n 'video',\n 'img',\n 'source',\n 'image',\n 'track',\n ]);\n\n /* Attributes safe for values like \"javascript:\" */\n let URI_SAFE_ATTRIBUTES = null;\n const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, [\n 'alt',\n 'class',\n 'for',\n 'id',\n 'label',\n 'name',\n 'pattern',\n 'placeholder',\n 'role',\n 'summary',\n 'title',\n 'value',\n 'style',\n 'xmlns',\n ]);\n\n const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\n /* Document namespace */\n let NAMESPACE = HTML_NAMESPACE;\n let IS_EMPTY_INPUT = false;\n\n /* Allowed XHTML+XML namespaces */\n let ALLOWED_NAMESPACES = null;\n const DEFAULT_ALLOWED_NAMESPACES = addToSet(\n {},\n [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE],\n stringToString\n );\n\n let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, [\n 'mi',\n 'mo',\n 'mn',\n 'ms',\n 'mtext',\n ]);\n\n let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);\n\n // Certain elements are allowed in both SVG and HTML\n // namespace. We need to specify them explicitly\n // so that they don't get erroneously deleted from\n // HTML namespace.\n const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, [\n 'title',\n 'style',\n 'font',\n 'a',\n 'script',\n ]);\n\n /* Parsing of strict XHTML documents */\n let PARSER_MEDIA_TYPE: null | DOMParserSupportedType = null;\n const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];\n const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';\n let transformCaseFunc: null | Parameters[2] = null;\n\n /* Keep a reference to config to pass to hooks */\n let CONFIG: Config | null = null;\n\n /* Ideally, do not touch anything below this line */\n /* ______________________________________________ */\n\n const formElement = document.createElement('form');\n\n const isRegexOrFunction = function (\n testValue: unknown\n ): testValue is Function | RegExp {\n return testValue instanceof RegExp || testValue instanceof Function;\n };\n\n /**\n * _parseConfig\n *\n * @param cfg optional config literal\n */\n // eslint-disable-next-line complexity\n const _parseConfig = function (cfg: Config = {}): void {\n if (CONFIG && CONFIG === cfg) {\n return;\n }\n\n /* Shield configuration object from tampering */\n if (!cfg || typeof cfg !== 'object') {\n cfg = {};\n }\n\n /* Shield configuration object from prototype pollution */\n cfg = clone(cfg);\n\n PARSER_MEDIA_TYPE =\n // eslint-disable-next-line unicorn/prefer-includes\n SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1\n ? DEFAULT_PARSER_MEDIA_TYPE\n : cfg.PARSER_MEDIA_TYPE;\n\n // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.\n transformCaseFunc =\n PARSER_MEDIA_TYPE === 'application/xhtml+xml'\n ? stringToString\n : stringToLowerCase;\n\n /* Set configuration parameters */\n ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS')\n ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc)\n : DEFAULT_ALLOWED_TAGS;\n ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR')\n ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc)\n : DEFAULT_ALLOWED_ATTR;\n ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES')\n ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString)\n : DEFAULT_ALLOWED_NAMESPACES;\n URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR')\n ? addToSet(\n clone(DEFAULT_URI_SAFE_ATTRIBUTES),\n cfg.ADD_URI_SAFE_ATTR,\n transformCaseFunc\n )\n : DEFAULT_URI_SAFE_ATTRIBUTES;\n DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS')\n ? addToSet(\n clone(DEFAULT_DATA_URI_TAGS),\n cfg.ADD_DATA_URI_TAGS,\n transformCaseFunc\n )\n : DEFAULT_DATA_URI_TAGS;\n FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS')\n ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc)\n : DEFAULT_FORBID_CONTENTS;\n FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS')\n ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc)\n : clone({});\n FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR')\n ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc)\n : clone({});\n USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES')\n ? cfg.USE_PROFILES\n : false;\n ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true\n ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true\n ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false\n ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true\n SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false\n SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true\n WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false\n RETURN_DOM = cfg.RETURN_DOM || false; // Default false\n RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false\n RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false\n FORCE_BODY = cfg.FORCE_BODY || false; // Default false\n SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true\n SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false\n KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true\n IN_PLACE = cfg.IN_PLACE || false; // Default false\n IS_ALLOWED_URI = cfg.ALLOWED_URI_REGEXP || EXPRESSIONS.IS_ALLOWED_URI;\n NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;\n MATHML_TEXT_INTEGRATION_POINTS =\n cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;\n HTML_INTEGRATION_POINTS =\n cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;\n\n CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};\n if (\n cfg.CUSTOM_ELEMENT_HANDLING &&\n isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)\n ) {\n CUSTOM_ELEMENT_HANDLING.tagNameCheck =\n cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;\n }\n\n if (\n cfg.CUSTOM_ELEMENT_HANDLING &&\n isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)\n ) {\n CUSTOM_ELEMENT_HANDLING.attributeNameCheck =\n cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;\n }\n\n if (\n cfg.CUSTOM_ELEMENT_HANDLING &&\n typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements ===\n 'boolean'\n ) {\n CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements =\n cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;\n }\n\n if (SAFE_FOR_TEMPLATES) {\n ALLOW_DATA_ATTR = false;\n }\n\n if (RETURN_DOM_FRAGMENT) {\n RETURN_DOM = true;\n }\n\n /* Parse profile info */\n if (USE_PROFILES) {\n ALLOWED_TAGS = addToSet({}, TAGS.text);\n ALLOWED_ATTR = [];\n if (USE_PROFILES.html === true) {\n addToSet(ALLOWED_TAGS, TAGS.html);\n addToSet(ALLOWED_ATTR, ATTRS.html);\n }\n\n if (USE_PROFILES.svg === true) {\n addToSet(ALLOWED_TAGS, TAGS.svg);\n addToSet(ALLOWED_ATTR, ATTRS.svg);\n addToSet(ALLOWED_ATTR, ATTRS.xml);\n }\n\n if (USE_PROFILES.svgFilters === true) {\n addToSet(ALLOWED_TAGS, TAGS.svgFilters);\n addToSet(ALLOWED_ATTR, ATTRS.svg);\n addToSet(ALLOWED_ATTR, ATTRS.xml);\n }\n\n if (USE_PROFILES.mathMl === true) {\n addToSet(ALLOWED_TAGS, TAGS.mathMl);\n addToSet(ALLOWED_ATTR, ATTRS.mathMl);\n addToSet(ALLOWED_ATTR, ATTRS.xml);\n }\n }\n\n /* Merge configuration parameters */\n if (cfg.ADD_TAGS) {\n if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n\n addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);\n }\n\n if (cfg.ADD_ATTR) {\n if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n\n addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);\n }\n\n if (cfg.ADD_URI_SAFE_ATTR) {\n addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);\n }\n\n if (cfg.FORBID_CONTENTS) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n\n addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);\n }\n\n /* Add #text in case KEEP_CONTENT is set to true */\n if (KEEP_CONTENT) {\n ALLOWED_TAGS['#text'] = true;\n }\n\n /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */\n if (WHOLE_DOCUMENT) {\n addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);\n }\n\n /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */\n if (ALLOWED_TAGS.table) {\n addToSet(ALLOWED_TAGS, ['tbody']);\n delete FORBID_TAGS.tbody;\n }\n\n if (cfg.TRUSTED_TYPES_POLICY) {\n if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {\n throw typeErrorCreate(\n 'TRUSTED_TYPES_POLICY configuration option must provide a \"createHTML\" hook.'\n );\n }\n\n if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {\n throw typeErrorCreate(\n 'TRUSTED_TYPES_POLICY configuration option must provide a \"createScriptURL\" hook.'\n );\n }\n\n // Overwrite existing TrustedTypes policy.\n trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;\n\n // Sign local variables required by `sanitize`.\n emptyHTML = trustedTypesPolicy.createHTML('');\n } else {\n // Uninitialized policy, attempt to initialize the internal dompurify policy.\n if (trustedTypesPolicy === undefined) {\n trustedTypesPolicy = _createTrustedTypesPolicy(\n trustedTypes,\n currentScript\n );\n }\n\n // If creating the internal policy succeeded sign internal variables.\n if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {\n emptyHTML = trustedTypesPolicy.createHTML('');\n }\n }\n\n // Prevent further manipulation of configuration.\n // Not available in IE8, Safari 5, etc.\n if (freeze) {\n freeze(cfg);\n }\n\n CONFIG = cfg;\n };\n\n /* Keep track of all possible SVG and MathML tags\n * so that we can perform the namespace checks\n * correctly. */\n const ALL_SVG_TAGS = addToSet({}, [\n ...TAGS.svg,\n ...TAGS.svgFilters,\n ...TAGS.svgDisallowed,\n ]);\n const ALL_MATHML_TAGS = addToSet({}, [\n ...TAGS.mathMl,\n ...TAGS.mathMlDisallowed,\n ]);\n\n /**\n * @param element a DOM element whose namespace is being checked\n * @returns Return false if the element has a\n * namespace that a spec-compliant parser would never\n * return. Return true otherwise.\n */\n const _checkValidNamespace = function (element: Element): boolean {\n let parent = getParentNode(element);\n\n // In JSDOM, if we're inside shadow DOM, then parentNode\n // can be null. We just simulate parent in this case.\n if (!parent || !parent.tagName) {\n parent = {\n namespaceURI: NAMESPACE,\n tagName: 'template',\n };\n }\n\n const tagName = stringToLowerCase(element.tagName);\n const parentTagName = stringToLowerCase(parent.tagName);\n\n if (!ALLOWED_NAMESPACES[element.namespaceURI]) {\n return false;\n }\n\n if (element.namespaceURI === SVG_NAMESPACE) {\n // The only way to switch from HTML namespace to SVG\n // is via . If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'svg';\n }\n\n // The only way to switch from MathML to SVG is via`\n // svg if parent is either or MathML\n // text integration points.\n if (parent.namespaceURI === MATHML_NAMESPACE) {\n return (\n tagName === 'svg' &&\n (parentTagName === 'annotation-xml' ||\n MATHML_TEXT_INTEGRATION_POINTS[parentTagName])\n );\n }\n\n // We only allow elements that are defined in SVG\n // spec. All others are disallowed in SVG namespace.\n return Boolean(ALL_SVG_TAGS[tagName]);\n }\n\n if (element.namespaceURI === MATHML_NAMESPACE) {\n // The only way to switch from HTML namespace to MathML\n // is via . If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'math';\n }\n\n // The only way to switch from SVG to MathML is via\n // and HTML integration points\n if (parent.namespaceURI === SVG_NAMESPACE) {\n return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];\n }\n\n // We only allow elements that are defined in MathML\n // spec. All others are disallowed in MathML namespace.\n return Boolean(ALL_MATHML_TAGS[tagName]);\n }\n\n if (element.namespaceURI === HTML_NAMESPACE) {\n // The only way to switch from SVG to HTML is via\n // HTML integration points, and from MathML to HTML\n // is via MathML text integration points\n if (\n parent.namespaceURI === SVG_NAMESPACE &&\n !HTML_INTEGRATION_POINTS[parentTagName]\n ) {\n return false;\n }\n\n if (\n parent.namespaceURI === MATHML_NAMESPACE &&\n !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]\n ) {\n return false;\n }\n\n // We disallow tags that are specific for MathML\n // or SVG and should never appear in HTML namespace\n return (\n !ALL_MATHML_TAGS[tagName] &&\n (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName])\n );\n }\n\n // For XHTML and XML documents that support custom namespaces\n if (\n PARSER_MEDIA_TYPE === 'application/xhtml+xml' &&\n ALLOWED_NAMESPACES[element.namespaceURI]\n ) {\n return true;\n }\n\n // The code should never reach this place (this means\n // that the element somehow got namespace that is not\n // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).\n // Return false just in case.\n return false;\n };\n\n /**\n * _forceRemove\n *\n * @param node a DOM node\n */\n const _forceRemove = function (node: Node): void {\n arrayPush(DOMPurify.removed, { element: node });\n\n try {\n // eslint-disable-next-line unicorn/prefer-dom-node-remove\n getParentNode(node).removeChild(node);\n } catch (_) {\n remove(node);\n }\n };\n\n /**\n * _removeAttribute\n *\n * @param name an Attribute name\n * @param element a DOM node\n */\n const _removeAttribute = function (name: string, element: Element): void {\n try {\n arrayPush(DOMPurify.removed, {\n attribute: element.getAttributeNode(name),\n from: element,\n });\n } catch (_) {\n arrayPush(DOMPurify.removed, {\n attribute: null,\n from: element,\n });\n }\n\n element.removeAttribute(name);\n\n // We void attribute values for unremovable \"is\" attributes\n if (name === 'is') {\n if (RETURN_DOM || RETURN_DOM_FRAGMENT) {\n try {\n _forceRemove(element);\n } catch (_) {}\n } else {\n try {\n element.setAttribute(name, '');\n } catch (_) {}\n }\n }\n };\n\n /**\n * _initDocument\n *\n * @param dirty - a string of dirty markup\n * @return a DOM, filled with the dirty markup\n */\n const _initDocument = function (dirty: string): Document {\n /* Create a HTML document */\n let doc = null;\n let leadingWhitespace = null;\n\n if (FORCE_BODY) {\n dirty = '' + dirty;\n } else {\n /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */\n const matches = stringMatch(dirty, /^[\\r\\n\\t ]+/);\n leadingWhitespace = matches && matches[0];\n }\n\n if (\n PARSER_MEDIA_TYPE === 'application/xhtml+xml' &&\n NAMESPACE === HTML_NAMESPACE\n ) {\n // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)\n dirty =\n '' +\n dirty +\n '';\n }\n\n const dirtyPayload = trustedTypesPolicy\n ? trustedTypesPolicy.createHTML(dirty)\n : dirty;\n /*\n * Use the DOMParser API by default, fallback later if needs be\n * DOMParser not work for svg when has multiple root element.\n */\n if (NAMESPACE === HTML_NAMESPACE) {\n try {\n doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);\n } catch (_) {}\n }\n\n /* Use createHTMLDocument in case DOMParser is not available */\n if (!doc || !doc.documentElement) {\n doc = implementation.createDocument(NAMESPACE, 'template', null);\n try {\n doc.documentElement.innerHTML = IS_EMPTY_INPUT\n ? emptyHTML\n : dirtyPayload;\n } catch (_) {\n // Syntax error if dirtyPayload is invalid xml\n }\n }\n\n const body = doc.body || doc.documentElement;\n\n if (dirty && leadingWhitespace) {\n body.insertBefore(\n document.createTextNode(leadingWhitespace),\n body.childNodes[0] || null\n );\n }\n\n /* Work on whole document or just its body */\n if (NAMESPACE === HTML_NAMESPACE) {\n return getElementsByTagName.call(\n doc,\n WHOLE_DOCUMENT ? 'html' : 'body'\n )[0];\n }\n\n return WHOLE_DOCUMENT ? doc.documentElement : body;\n };\n\n /**\n * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.\n *\n * @param root The root element or node to start traversing on.\n * @return The created NodeIterator\n */\n const _createNodeIterator = function (root: Node): NodeIterator {\n return createNodeIterator.call(\n root.ownerDocument || root,\n root,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_ELEMENT |\n NodeFilter.SHOW_COMMENT |\n NodeFilter.SHOW_TEXT |\n NodeFilter.SHOW_PROCESSING_INSTRUCTION |\n NodeFilter.SHOW_CDATA_SECTION,\n null\n );\n };\n\n /**\n * _isClobbered\n *\n * @param element element to check for clobbering attacks\n * @return true if clobbered, false if safe\n */\n const _isClobbered = function (element: Element): boolean {\n return (\n element instanceof HTMLFormElement &&\n (typeof element.nodeName !== 'string' ||\n typeof element.textContent !== 'string' ||\n typeof element.removeChild !== 'function' ||\n !(element.attributes instanceof NamedNodeMap) ||\n typeof element.removeAttribute !== 'function' ||\n typeof element.setAttribute !== 'function' ||\n typeof element.namespaceURI !== 'string' ||\n typeof element.insertBefore !== 'function' ||\n typeof element.hasChildNodes !== 'function')\n );\n };\n\n /**\n * Checks whether the given object is a DOM node.\n *\n * @param value object to check whether it's a DOM node\n * @return true is object is a DOM node\n */\n const _isNode = function (value: unknown): value is Node {\n return typeof Node === 'function' && value instanceof Node;\n };\n\n function _executeHooks(\n hooks: HookFunction[],\n currentNode: Parameters[0],\n data: Parameters[1]\n ): void {\n arrayForEach(hooks, (hook: T) => {\n hook.call(DOMPurify, currentNode, data, CONFIG);\n });\n }\n\n /**\n * _sanitizeElements\n *\n * @protect nodeName\n * @protect textContent\n * @protect removeChild\n * @param currentNode to check for permission to exist\n * @return true if node was killed, false if left alive\n */\n const _sanitizeElements = function (currentNode: any): boolean {\n let content = null;\n\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeElements, currentNode, null);\n\n /* Check if element is clobbered or can clobber */\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Now let's check the element's type and name */\n const tagName = transformCaseFunc(currentNode.nodeName);\n\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeElement, currentNode, {\n tagName,\n allowedTags: ALLOWED_TAGS,\n });\n\n /* Detect mXSS attempts abusing namespace confusion */\n if (\n SAFE_FOR_XML &&\n currentNode.hasChildNodes() &&\n !_isNode(currentNode.firstElementChild) &&\n regExpTest(/<[/\\w!]/g, currentNode.innerHTML) &&\n regExpTest(/<[/\\w!]/g, currentNode.textContent)\n ) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Remove any occurrence of processing instructions */\n if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Remove any kind of possibly harmful comments */\n if (\n SAFE_FOR_XML &&\n currentNode.nodeType === NODE_TYPE.comment &&\n regExpTest(/<[/\\w]/g, currentNode.data)\n ) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Remove element if anything forbids its presence */\n if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {\n /* Check if we have a custom element to handle */\n if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {\n if (\n CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp &&\n regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)\n ) {\n return false;\n }\n\n if (\n CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function &&\n CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)\n ) {\n return false;\n }\n }\n\n /* Keep content except for bad-listed elements */\n if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {\n const parentNode = getParentNode(currentNode) || currentNode.parentNode;\n const childNodes = getChildNodes(currentNode) || currentNode.childNodes;\n\n if (childNodes && parentNode) {\n const childCount = childNodes.length;\n\n for (let i = childCount - 1; i >= 0; --i) {\n const childClone = cloneNode(childNodes[i], true);\n childClone.__removalCount = (currentNode.__removalCount || 0) + 1;\n parentNode.insertBefore(childClone, getNextSibling(currentNode));\n }\n }\n }\n\n _forceRemove(currentNode);\n return true;\n }\n\n /* Check whether element has a valid namespace */\n if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Make sure that older browsers don't get fallback-tag mXSS */\n if (\n (tagName === 'noscript' ||\n tagName === 'noembed' ||\n tagName === 'noframes') &&\n regExpTest(/<\\/no(script|embed|frames)/i, currentNode.innerHTML)\n ) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Sanitize element content to be template-safe */\n if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {\n /* Get the element's text content */\n content = currentNode.textContent;\n\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], (expr: RegExp) => {\n content = stringReplace(content, expr, ' ');\n });\n\n if (currentNode.textContent !== content) {\n arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });\n currentNode.textContent = content;\n }\n }\n\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n\n return false;\n };\n\n /**\n * _isValidAttribute\n *\n * @param lcTag Lowercase tag name of containing element.\n * @param lcName Lowercase attribute name.\n * @param value Attribute value.\n * @return Returns true if `value` is valid, otherwise false.\n */\n // eslint-disable-next-line complexity\n const _isValidAttribute = function (\n lcTag: string,\n lcName: string,\n value: string\n ): boolean {\n /* Make sure attribute cannot clobber */\n if (\n SANITIZE_DOM &&\n (lcName === 'id' || lcName === 'name') &&\n (value in document || value in formElement)\n ) {\n return false;\n }\n\n /* Allow valid data-* attributes: At least one character after \"-\"\n (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)\n XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)\n We don't need to check the value; it's always URI safe. */\n if (\n ALLOW_DATA_ATTR &&\n !FORBID_ATTR[lcName] &&\n regExpTest(DATA_ATTR, lcName)\n ) {\n // This attribute is safe\n } else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) {\n // This attribute is safe\n /* Otherwise, check the name is permitted */\n } else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {\n if (\n // First condition does a very basic check if a) it's basically a valid custom element tagname AND\n // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck\n (_isBasicCustomElement(lcTag) &&\n ((CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp &&\n regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag)) ||\n (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function &&\n CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag))) &&\n ((CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp &&\n regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName)) ||\n (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function &&\n CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)))) ||\n // Alternative, second condition checks if it's an `is`-attribute, AND\n // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n (lcName === 'is' &&\n CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements &&\n ((CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp &&\n regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value)) ||\n (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function &&\n CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))))\n ) {\n // If user has supplied a regexp or function in CUSTOM_ELEMENT_HANDLING.tagNameCheck, we need to also allow derived custom elements using the same tagName test.\n // Additionally, we need to allow attributes passing the CUSTOM_ELEMENT_HANDLING.attributeNameCheck user has configured, as custom elements can define these at their own discretion.\n } else {\n return false;\n }\n /* Check value is safe. First, is attr inert? If so, is safe */\n } else if (URI_SAFE_ATTRIBUTES[lcName]) {\n // This attribute is safe\n /* Check no script, data or unknown possibly unsafe URI\n unless we know URI values are safe for that attribute */\n } else if (\n regExpTest(IS_ALLOWED_URI, stringReplace(value, ATTR_WHITESPACE, ''))\n ) {\n // This attribute is safe\n /* Keep image data URIs alive if src/xlink:href is allowed */\n /* Further prevent gadget XSS for dynamically built script tags */\n } else if (\n (lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') &&\n lcTag !== 'script' &&\n stringIndexOf(value, 'data:') === 0 &&\n DATA_URI_TAGS[lcTag]\n ) {\n // This attribute is safe\n /* Allow unknown protocols: This provides support for links that\n are handled by protocol handlers which may be unknown ahead of\n time, e.g. fb:, spotify: */\n } else if (\n ALLOW_UNKNOWN_PROTOCOLS &&\n !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))\n ) {\n // This attribute is safe\n /* Check for binary attributes */\n } else if (value) {\n return false;\n } else {\n // Binary attributes are safe at this point\n /* Anything else, presume unsafe, do not add it back */\n }\n\n return true;\n };\n\n /**\n * _isBasicCustomElement\n * checks if at least one dash is included in tagName, and it's not the first char\n * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name\n *\n * @param tagName name of the tag of the node to sanitize\n * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.\n */\n const _isBasicCustomElement = function (tagName: string): RegExpMatchArray {\n return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);\n };\n\n /**\n * _sanitizeAttributes\n *\n * @protect attributes\n * @protect nodeName\n * @protect removeAttribute\n * @protect setAttribute\n *\n * @param currentNode to sanitize\n */\n const _sanitizeAttributes = function (currentNode: Element): void {\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);\n\n const { attributes } = currentNode;\n\n /* Check if we have attributes; if not we might have a text node */\n if (!attributes || _isClobbered(currentNode)) {\n return;\n }\n\n const hookEvent = {\n attrName: '',\n attrValue: '',\n keepAttr: true,\n allowedAttributes: ALLOWED_ATTR,\n forceKeepAttr: undefined,\n };\n let l = attributes.length;\n\n /* Go backwards over all attributes; safely remove bad ones */\n while (l--) {\n const attr = attributes[l];\n const { name, namespaceURI, value: attrValue } = attr;\n const lcName = transformCaseFunc(name);\n\n const initValue = attrValue;\n let value = name === 'value' ? initValue : stringTrim(initValue);\n\n /* Execute a hook if present */\n hookEvent.attrName = lcName;\n hookEvent.attrValue = value;\n hookEvent.keepAttr = true;\n hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set\n _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);\n value = hookEvent.attrValue;\n\n /* Full DOM Clobbering protection via namespace isolation,\n * Prefix id and name attributes with `user-content-`\n */\n if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {\n // Remove the attribute with this value\n _removeAttribute(name, currentNode);\n\n // Prefix the value and later re-create the attribute with the sanitized value\n value = SANITIZE_NAMED_PROPS_PREFIX + value;\n }\n\n /* Work around a security issue with comments inside attributes */\n if (\n SAFE_FOR_XML &&\n regExpTest(/((--!?|])>)|<\\/(style|title|textarea)/i, value)\n ) {\n _removeAttribute(name, currentNode);\n continue;\n }\n\n /* Make sure we cannot easily use animated hrefs, even if animations are allowed */\n if (lcName === 'attributename' && stringMatch(value, 'href')) {\n _removeAttribute(name, currentNode);\n continue;\n }\n\n /* Did the hooks approve of the attribute? */\n if (hookEvent.forceKeepAttr) {\n continue;\n }\n\n /* Did the hooks approve of the attribute? */\n if (!hookEvent.keepAttr) {\n _removeAttribute(name, currentNode);\n continue;\n }\n\n /* Work around a security issue in jQuery 3.0 */\n if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\\/>/i, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n\n /* Sanitize attribute content to be template-safe */\n if (SAFE_FOR_TEMPLATES) {\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], (expr: RegExp) => {\n value = stringReplace(value, expr, ' ');\n });\n }\n\n /* Is `value` valid for this attribute? */\n const lcTag = transformCaseFunc(currentNode.nodeName);\n if (!_isValidAttribute(lcTag, lcName, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n\n /* Handle attributes that require Trusted Types */\n if (\n trustedTypesPolicy &&\n typeof trustedTypes === 'object' &&\n typeof trustedTypes.getAttributeType === 'function'\n ) {\n if (namespaceURI) {\n /* Namespaces are not yet supported, see https://bugs.chromium.org/p/chromium/issues/detail?id=1305293 */\n } else {\n switch (trustedTypes.getAttributeType(lcTag, lcName)) {\n case 'TrustedHTML': {\n value = trustedTypesPolicy.createHTML(value);\n break;\n }\n\n case 'TrustedScriptURL': {\n value = trustedTypesPolicy.createScriptURL(value);\n break;\n }\n\n default: {\n break;\n }\n }\n }\n }\n\n /* Handle invalid data-* attribute set by try-catching it */\n if (value !== initValue) {\n try {\n if (namespaceURI) {\n currentNode.setAttributeNS(namespaceURI, name, value);\n } else {\n /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. \"x-schema\". */\n currentNode.setAttribute(name, value);\n }\n\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n } else {\n arrayPop(DOMPurify.removed);\n }\n } catch (_) {\n _removeAttribute(name, currentNode);\n }\n }\n }\n\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);\n };\n\n /**\n * _sanitizeShadowDOM\n *\n * @param fragment to iterate over recursively\n */\n const _sanitizeShadowDOM = function (fragment: DocumentFragment): void {\n let shadowNode = null;\n const shadowIterator = _createNodeIterator(fragment);\n\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);\n\n while ((shadowNode = shadowIterator.nextNode())) {\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);\n\n /* Sanitize tags and elements */\n _sanitizeElements(shadowNode);\n\n /* Check attributes next */\n _sanitizeAttributes(shadowNode);\n\n /* Deep shadow DOM detected */\n if (shadowNode.content instanceof DocumentFragment) {\n _sanitizeShadowDOM(shadowNode.content);\n }\n }\n\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);\n };\n\n // eslint-disable-next-line complexity\n DOMPurify.sanitize = function (dirty, cfg = {}) {\n let body = null;\n let importedNode = null;\n let currentNode = null;\n let returnNode = null;\n /* Make sure we have a string to sanitize.\n DO NOT return early, as this will return the wrong type if\n the user has requested a DOM object rather than a string */\n IS_EMPTY_INPUT = !dirty;\n if (IS_EMPTY_INPUT) {\n dirty = '';\n }\n\n /* Stringify, in case dirty is an object */\n if (typeof dirty !== 'string' && !_isNode(dirty)) {\n if (typeof dirty.toString === 'function') {\n dirty = dirty.toString();\n if (typeof dirty !== 'string') {\n throw typeErrorCreate('dirty is not a string, aborting');\n }\n } else {\n throw typeErrorCreate('toString is not a function');\n }\n }\n\n /* Return dirty HTML if DOMPurify cannot run */\n if (!DOMPurify.isSupported) {\n return dirty;\n }\n\n /* Assign config vars */\n if (!SET_CONFIG) {\n _parseConfig(cfg);\n }\n\n /* Clean up removed elements */\n DOMPurify.removed = [];\n\n /* Check if dirty is correctly typed for IN_PLACE */\n if (typeof dirty === 'string') {\n IN_PLACE = false;\n }\n\n if (IN_PLACE) {\n /* Do some early pre-sanitization to avoid unsafe root nodes */\n if ((dirty as Node).nodeName) {\n const tagName = transformCaseFunc((dirty as Node).nodeName);\n if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {\n throw typeErrorCreate(\n 'root node is forbidden and cannot be sanitized in-place'\n );\n }\n }\n } else if (dirty instanceof Node) {\n /* If dirty is a DOM element, append to an empty document to avoid\n elements being stripped by the parser */\n body = _initDocument('');\n importedNode = body.ownerDocument.importNode(dirty, true);\n if (\n importedNode.nodeType === NODE_TYPE.element &&\n importedNode.nodeName === 'BODY'\n ) {\n /* Node is already a body, use as is */\n body = importedNode;\n } else if (importedNode.nodeName === 'HTML') {\n body = importedNode;\n } else {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n body.appendChild(importedNode);\n }\n } else {\n /* Exit directly if we have nothing to do */\n if (\n !RETURN_DOM &&\n !SAFE_FOR_TEMPLATES &&\n !WHOLE_DOCUMENT &&\n // eslint-disable-next-line unicorn/prefer-includes\n dirty.indexOf('<') === -1\n ) {\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE\n ? trustedTypesPolicy.createHTML(dirty)\n : dirty;\n }\n\n /* Initialize the document to work on */\n body = _initDocument(dirty);\n\n /* Check we have a DOM node from the data */\n if (!body) {\n return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';\n }\n }\n\n /* Remove first element node (ours) if FORCE_BODY is set */\n if (body && FORCE_BODY) {\n _forceRemove(body.firstChild);\n }\n\n /* Get node iterator */\n const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);\n\n /* Now start iterating over the created document */\n while ((currentNode = nodeIterator.nextNode())) {\n /* Sanitize tags and elements */\n _sanitizeElements(currentNode);\n\n /* Check attributes next */\n _sanitizeAttributes(currentNode);\n\n /* Shadow DOM detected, sanitize it */\n if (currentNode.content instanceof DocumentFragment) {\n _sanitizeShadowDOM(currentNode.content);\n }\n }\n\n /* If we sanitized `dirty` in-place, return it. */\n if (IN_PLACE) {\n return dirty;\n }\n\n /* Return sanitized string or DOM */\n if (RETURN_DOM) {\n if (RETURN_DOM_FRAGMENT) {\n returnNode = createDocumentFragment.call(body.ownerDocument);\n\n while (body.firstChild) {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n returnNode.appendChild(body.firstChild);\n }\n } else {\n returnNode = body;\n }\n\n if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {\n /*\n AdoptNode() is not used because internal state is not reset\n (e.g. the past names map of a HTMLFormElement), this is safe\n in theory but we would rather not risk another attack vector.\n The state that is cloned by importNode() is explicitly defined\n by the specs.\n */\n returnNode = importNode.call(originalDocument, returnNode, true);\n }\n\n return returnNode;\n }\n\n let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;\n\n /* Serialize doctype if allowed */\n if (\n WHOLE_DOCUMENT &&\n ALLOWED_TAGS['!doctype'] &&\n body.ownerDocument &&\n body.ownerDocument.doctype &&\n body.ownerDocument.doctype.name &&\n regExpTest(EXPRESSIONS.DOCTYPE_NAME, body.ownerDocument.doctype.name)\n ) {\n serializedHTML =\n '\\n' + serializedHTML;\n }\n\n /* Sanitize final string template-safe */\n if (SAFE_FOR_TEMPLATES) {\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], (expr: RegExp) => {\n serializedHTML = stringReplace(serializedHTML, expr, ' ');\n });\n }\n\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE\n ? trustedTypesPolicy.createHTML(serializedHTML)\n : serializedHTML;\n };\n\n DOMPurify.setConfig = function (cfg = {}) {\n _parseConfig(cfg);\n SET_CONFIG = true;\n };\n\n DOMPurify.clearConfig = function () {\n CONFIG = null;\n SET_CONFIG = false;\n };\n\n DOMPurify.isValidAttribute = function (tag, attr, value) {\n /* Initialize shared config vars if necessary. */\n if (!CONFIG) {\n _parseConfig({});\n }\n\n const lcTag = transformCaseFunc(tag);\n const lcName = transformCaseFunc(attr);\n return _isValidAttribute(lcTag, lcName, value);\n };\n\n DOMPurify.addHook = function (\n entryPoint: keyof HooksMap,\n hookFunction: HookFunction\n ) {\n if (typeof hookFunction !== 'function') {\n return;\n }\n\n arrayPush(hooks[entryPoint], hookFunction);\n };\n\n DOMPurify.removeHook = function (\n entryPoint: keyof HooksMap,\n hookFunction: HookFunction\n ) {\n if (hookFunction !== undefined) {\n const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);\n\n return index === -1\n ? undefined\n : arraySplice(hooks[entryPoint], index, 1)[0];\n }\n\n return arrayPop(hooks[entryPoint]);\n };\n\n DOMPurify.removeHooks = function (entryPoint: keyof HooksMap) {\n hooks[entryPoint] = [];\n };\n\n DOMPurify.removeAllHooks = function () {\n hooks = _createHooksMap();\n };\n\n return DOMPurify;\n}\n\nexport default createDOMPurify();\n\nexport interface DOMPurify {\n /**\n * Creates a DOMPurify instance using the given window-like object. Defaults to `window`.\n */\n (root?: WindowLike): DOMPurify;\n\n /**\n * Version label, exposed for easier checks\n * if DOMPurify is up to date or not\n */\n version: string;\n\n /**\n * Array of elements that DOMPurify removed during sanitation.\n * Empty if nothing was removed.\n */\n removed: Array;\n\n /**\n * Expose whether this browser supports running the full DOMPurify.\n */\n isSupported: boolean;\n\n /**\n * Set the configuration once.\n *\n * @param cfg configuration object\n */\n setConfig(cfg?: Config): void;\n\n /**\n * Removes the configuration.\n */\n clearConfig(): void;\n\n /**\n * Provides core sanitation functionality.\n *\n * @param dirty string or DOM node\n * @param cfg object\n * @returns Sanitized TrustedHTML.\n */\n sanitize(\n dirty: string | Node,\n cfg: Config & { RETURN_TRUSTED_TYPE: true }\n ): TrustedHTML;\n\n /**\n * Provides core sanitation functionality.\n *\n * @param dirty DOM node\n * @param cfg object\n * @returns Sanitized DOM node.\n */\n sanitize(dirty: Node, cfg: Config & { IN_PLACE: true }): Node;\n\n /**\n * Provides core sanitation functionality.\n *\n * @param dirty string or DOM node\n * @param cfg object\n * @returns Sanitized DOM node.\n */\n sanitize(dirty: string | Node, cfg: Config & { RETURN_DOM: true }): Node;\n\n /**\n * Provides core sanitation functionality.\n *\n * @param dirty string or DOM node\n * @param cfg object\n * @returns Sanitized document fragment.\n */\n sanitize(\n dirty: string | Node,\n cfg: Config & { RETURN_DOM_FRAGMENT: true }\n ): DocumentFragment;\n\n /**\n * Provides core sanitation functionality.\n *\n * @param dirty string or DOM node\n * @param cfg object\n * @returns Sanitized string.\n */\n sanitize(dirty: string | Node, cfg?: Config): string;\n\n /**\n * Checks if an attribute value is valid.\n * Uses last set config, if any. Otherwise, uses config defaults.\n *\n * @param tag Tag name of containing element.\n * @param attr Attribute name.\n * @param value Attribute value.\n * @returns Returns true if `value` is valid. Otherwise, returns false.\n */\n isValidAttribute(tag: string, attr: string, value: string): boolean;\n\n /**\n * Adds a DOMPurify hook.\n *\n * @param entryPoint entry point for the hook to add\n * @param hookFunction function to execute\n */\n addHook(entryPoint: BasicHookName, hookFunction: NodeHook): void;\n\n /**\n * Adds a DOMPurify hook.\n *\n * @param entryPoint entry point for the hook to add\n * @param hookFunction function to execute\n */\n addHook(entryPoint: ElementHookName, hookFunction: ElementHook): void;\n\n /**\n * Adds a DOMPurify hook.\n *\n * @param entryPoint entry point for the hook to add\n * @param hookFunction function to execute\n */\n addHook(\n entryPoint: DocumentFragmentHookName,\n hookFunction: DocumentFragmentHook\n ): void;\n\n /**\n * Adds a DOMPurify hook.\n *\n * @param entryPoint entry point for the hook to add\n * @param hookFunction function to execute\n */\n addHook(\n entryPoint: 'uponSanitizeElement',\n hookFunction: UponSanitizeElementHook\n ): void;\n\n /**\n * Adds a DOMPurify hook.\n *\n * @param entryPoint entry point for the hook to add\n * @param hookFunction function to execute\n */\n addHook(\n entryPoint: 'uponSanitizeAttribute',\n hookFunction: UponSanitizeAttributeHook\n ): void;\n\n /**\n * Remove a DOMPurify hook at a given entryPoint\n * (pops it from the stack of hooks if hook not specified)\n *\n * @param entryPoint entry point for the hook to remove\n * @param hookFunction optional specific hook to remove\n * @returns removed hook\n */\n removeHook(\n entryPoint: BasicHookName,\n hookFunction?: NodeHook\n ): NodeHook | undefined;\n\n /**\n * Remove a DOMPurify hook at a given entryPoint\n * (pops it from the stack of hooks if hook not specified)\n *\n * @param entryPoint entry point for the hook to remove\n * @param hookFunction optional specific hook to remove\n * @returns removed hook\n */\n removeHook(\n entryPoint: ElementHookName,\n hookFunction?: ElementHook\n ): ElementHook | undefined;\n\n /**\n * Remove a DOMPurify hook at a given entryPoint\n * (pops it from the stack of hooks if hook not specified)\n *\n * @param entryPoint entry point for the hook to remove\n * @param hookFunction optional specific hook to remove\n * @returns removed hook\n */\n removeHook(\n entryPoint: DocumentFragmentHookName,\n hookFunction?: DocumentFragmentHook\n ): DocumentFragmentHook | undefined;\n\n /**\n * Remove a DOMPurify hook at a given entryPoint\n * (pops it from the stack of hooks if hook not specified)\n *\n * @param entryPoint entry point for the hook to remove\n * @param hookFunction optional specific hook to remove\n * @returns removed hook\n */\n removeHook(\n entryPoint: 'uponSanitizeElement',\n hookFunction?: UponSanitizeElementHook\n ): UponSanitizeElementHook | undefined;\n\n /**\n * Remove a DOMPurify hook at a given entryPoint\n * (pops it from the stack of hooks if hook not specified)\n *\n * @param entryPoint entry point for the hook to remove\n * @param hookFunction optional specific hook to remove\n * @returns removed hook\n */\n removeHook(\n entryPoint: 'uponSanitizeAttribute',\n hookFunction?: UponSanitizeAttributeHook\n ): UponSanitizeAttributeHook | undefined;\n\n /**\n * Removes all DOMPurify hooks at a given entryPoint\n *\n * @param entryPoint entry point for the hooks to remove\n */\n removeHooks(entryPoint: HookName): void;\n\n /**\n * Removes all DOMPurify hooks.\n */\n removeAllHooks(): void;\n}\n\n/**\n * An element removed by DOMPurify.\n */\nexport interface RemovedElement {\n /**\n * The element that was removed.\n */\n element: Node;\n}\n\n/**\n * An element removed by DOMPurify.\n */\nexport interface RemovedAttribute {\n /**\n * The attribute that was removed.\n */\n attribute: Attr | null;\n\n /**\n * The element that the attribute was removed.\n */\n from: Node;\n}\n\ntype BasicHookName =\n | 'beforeSanitizeElements'\n | 'afterSanitizeElements'\n | 'uponSanitizeShadowNode';\ntype ElementHookName = 'beforeSanitizeAttributes' | 'afterSanitizeAttributes';\ntype DocumentFragmentHookName =\n | 'beforeSanitizeShadowDOM'\n | 'afterSanitizeShadowDOM';\ntype UponSanitizeElementHookName = 'uponSanitizeElement';\ntype UponSanitizeAttributeHookName = 'uponSanitizeAttribute';\n\ninterface HooksMap {\n beforeSanitizeElements: NodeHook[];\n afterSanitizeElements: NodeHook[];\n beforeSanitizeShadowDOM: DocumentFragmentHook[];\n uponSanitizeShadowNode: NodeHook[];\n afterSanitizeShadowDOM: DocumentFragmentHook[];\n beforeSanitizeAttributes: ElementHook[];\n afterSanitizeAttributes: ElementHook[];\n uponSanitizeElement: UponSanitizeElementHook[];\n uponSanitizeAttribute: UponSanitizeAttributeHook[];\n}\n\ntype ArrayElement = T extends Array ? U : never;\n\ntype HookFunction = ArrayElement;\n\nexport type HookName =\n | BasicHookName\n | ElementHookName\n | DocumentFragmentHookName\n | UponSanitizeElementHookName\n | UponSanitizeAttributeHookName;\n\nexport type NodeHook = (\n this: DOMPurify,\n currentNode: Node,\n hookEvent: null,\n config: Config\n) => void;\n\nexport type ElementHook = (\n this: DOMPurify,\n currentNode: Element,\n hookEvent: null,\n config: Config\n) => void;\n\nexport type DocumentFragmentHook = (\n this: DOMPurify,\n currentNode: DocumentFragment,\n hookEvent: null,\n config: Config\n) => void;\n\nexport type UponSanitizeElementHook = (\n this: DOMPurify,\n currentNode: Node,\n hookEvent: UponSanitizeElementHookEvent,\n config: Config\n) => void;\n\nexport type UponSanitizeAttributeHook = (\n this: DOMPurify,\n currentNode: Element,\n hookEvent: UponSanitizeAttributeHookEvent,\n config: Config\n) => void;\n\nexport interface UponSanitizeElementHookEvent {\n tagName: string;\n allowedTags: Record;\n}\n\nexport interface UponSanitizeAttributeHookEvent {\n attrName: string;\n attrValue: string;\n keepAttr: boolean;\n allowedAttributes: Record;\n forceKeepAttr: boolean | undefined;\n}\n\n/**\n * A `Window`-like object containing the properties and types that DOMPurify requires.\n */\nexport type WindowLike = Pick<\n typeof globalThis,\n | 'DocumentFragment'\n | 'HTMLTemplateElement'\n | 'Node'\n | 'Element'\n | 'NodeFilter'\n | 'NamedNodeMap'\n | 'HTMLFormElement'\n | 'DOMParser'\n> & {\n document?: Document;\n MozNamedAttrMap?: typeof window.NamedNodeMap;\n} & Pick;\n", "import {\n __export,\n __name,\n log,\n setLogLevel\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/diagram-api/regexes.ts\nvar frontMatterRegex = /^-{3}\\s*[\\n\\r](.*?)[\\n\\r]-{3}\\s*[\\n\\r]+/s;\nvar directiveRegex = /%{2}{\\s*(?:(\\w+)\\s*:|(\\w+))\\s*(?:(\\w+)|((?:(?!}%{2}).|\\r?\\n)*))?\\s*(?:}%{2})?/gi;\nvar anyCommentRegex = /\\s*%%.*\\n/gm;\n\n// src/errors.ts\nvar UnknownDiagramError = class extends Error {\n static {\n __name(this, \"UnknownDiagramError\");\n }\n constructor(message) {\n super(message);\n this.name = \"UnknownDiagramError\";\n }\n};\n\n// src/diagram-api/detectType.ts\nvar detectors = {};\nvar detectType = /* @__PURE__ */ __name(function(text, config2) {\n text = text.replace(frontMatterRegex, \"\").replace(directiveRegex, \"\").replace(anyCommentRegex, \"\\n\");\n for (const [key, { detector }] of Object.entries(detectors)) {\n const diagram = detector(text, config2);\n if (diagram) {\n return key;\n }\n }\n throw new UnknownDiagramError(\n `No diagram type detected matching given configuration for text: ${text}`\n );\n}, \"detectType\");\nvar registerLazyLoadedDiagrams = /* @__PURE__ */ __name((...diagrams2) => {\n for (const { id, detector, loader } of diagrams2) {\n addDetector(id, detector, loader);\n }\n}, \"registerLazyLoadedDiagrams\");\nvar addDetector = /* @__PURE__ */ __name((key, detector, loader) => {\n if (detectors[key]) {\n log.warn(`Detector with key ${key} already exists. Overwriting.`);\n }\n detectors[key] = { detector, loader };\n log.debug(`Detector with key ${key} added${loader ? \" with loader\" : \"\"}`);\n}, \"addDetector\");\nvar getDiagramLoader = /* @__PURE__ */ __name((key) => {\n return detectors[key].loader;\n}, \"getDiagramLoader\");\n\n// src/assignWithDepth.ts\nvar assignWithDepth = /* @__PURE__ */ __name((dst, src, { depth = 2, clobber = false } = {}) => {\n const config2 = { depth, clobber };\n if (Array.isArray(src) && !Array.isArray(dst)) {\n src.forEach((s) => assignWithDepth(dst, s, config2));\n return dst;\n } else if (Array.isArray(src) && Array.isArray(dst)) {\n src.forEach((s) => {\n if (!dst.includes(s)) {\n dst.push(s);\n }\n });\n return dst;\n }\n if (dst === void 0 || depth <= 0) {\n if (dst !== void 0 && dst !== null && typeof dst === \"object\" && typeof src === \"object\") {\n return Object.assign(dst, src);\n } else {\n return src;\n }\n }\n if (src !== void 0 && typeof dst === \"object\" && typeof src === \"object\") {\n Object.keys(src).forEach((key) => {\n if (typeof src[key] === \"object\" && (dst[key] === void 0 || typeof dst[key] === \"object\")) {\n if (dst[key] === void 0) {\n dst[key] = Array.isArray(src[key]) ? [] : {};\n }\n dst[key] = assignWithDepth(dst[key], src[key], { depth: depth - 1, clobber });\n } else if (clobber || typeof dst[key] !== \"object\" && typeof src[key] !== \"object\") {\n dst[key] = src[key];\n }\n });\n }\n return dst;\n}, \"assignWithDepth\");\nvar assignWithDepth_default = assignWithDepth;\n\n// src/themes/theme-base.js\nimport { adjust as adjust2, darken, invert, isDark, lighten } from \"khroma\";\n\n// src/themes/erDiagram-oldHardcodedValues.ts\nvar oldAttributeBackgroundColorOdd = \"#ffffff\";\nvar oldAttributeBackgroundColorEven = \"#f2f2f2\";\n\n// src/themes/theme-helpers.js\nimport { adjust } from \"khroma\";\nvar mkBorder = /* @__PURE__ */ __name((col, darkMode) => darkMode ? adjust(col, { s: -40, l: 10 }) : adjust(col, { s: -40, l: -10 }), \"mkBorder\");\n\n// src/themes/theme-base.js\nvar Theme = class {\n static {\n __name(this, \"Theme\");\n }\n constructor() {\n this.background = \"#f4f4f4\";\n this.primaryColor = \"#fff4dd\";\n this.noteBkgColor = \"#fff5ad\";\n this.noteTextColor = \"#333\";\n this.THEME_COLOR_LIMIT = 12;\n this.fontFamily = '\"trebuchet ms\", verdana, arial, sans-serif';\n this.fontSize = \"16px\";\n }\n updateColors() {\n this.primaryTextColor = this.primaryTextColor || (this.darkMode ? \"#eee\" : \"#333\");\n this.secondaryColor = this.secondaryColor || adjust2(this.primaryColor, { h: -120 });\n this.tertiaryColor = this.tertiaryColor || adjust2(this.primaryColor, { h: 180, l: 5 });\n this.primaryBorderColor = this.primaryBorderColor || mkBorder(this.primaryColor, this.darkMode);\n this.secondaryBorderColor = this.secondaryBorderColor || mkBorder(this.secondaryColor, this.darkMode);\n this.tertiaryBorderColor = this.tertiaryBorderColor || mkBorder(this.tertiaryColor, this.darkMode);\n this.noteBorderColor = this.noteBorderColor || mkBorder(this.noteBkgColor, this.darkMode);\n this.noteBkgColor = this.noteBkgColor || \"#fff5ad\";\n this.noteTextColor = this.noteTextColor || \"#333\";\n this.secondaryTextColor = this.secondaryTextColor || invert(this.secondaryColor);\n this.tertiaryTextColor = this.tertiaryTextColor || invert(this.tertiaryColor);\n this.lineColor = this.lineColor || invert(this.background);\n this.arrowheadColor = this.arrowheadColor || invert(this.background);\n this.textColor = this.textColor || this.primaryTextColor;\n this.border2 = this.border2 || this.tertiaryBorderColor;\n this.nodeBkg = this.nodeBkg || this.primaryColor;\n this.mainBkg = this.mainBkg || this.primaryColor;\n this.nodeBorder = this.nodeBorder || this.primaryBorderColor;\n this.clusterBkg = this.clusterBkg || this.tertiaryColor;\n this.clusterBorder = this.clusterBorder || this.tertiaryBorderColor;\n this.defaultLinkColor = this.defaultLinkColor || this.lineColor;\n this.titleColor = this.titleColor || this.tertiaryTextColor;\n this.edgeLabelBackground = this.edgeLabelBackground || (this.darkMode ? darken(this.secondaryColor, 30) : this.secondaryColor);\n this.nodeTextColor = this.nodeTextColor || this.primaryTextColor;\n this.actorBorder = this.actorBorder || this.primaryBorderColor;\n this.actorBkg = this.actorBkg || this.mainBkg;\n this.actorTextColor = this.actorTextColor || this.primaryTextColor;\n this.actorLineColor = this.actorLineColor || this.actorBorder;\n this.labelBoxBkgColor = this.labelBoxBkgColor || this.actorBkg;\n this.signalColor = this.signalColor || this.textColor;\n this.signalTextColor = this.signalTextColor || this.textColor;\n this.labelBoxBorderColor = this.labelBoxBorderColor || this.actorBorder;\n this.labelTextColor = this.labelTextColor || this.actorTextColor;\n this.loopTextColor = this.loopTextColor || this.actorTextColor;\n this.activationBorderColor = this.activationBorderColor || darken(this.secondaryColor, 10);\n this.activationBkgColor = this.activationBkgColor || this.secondaryColor;\n this.sequenceNumberColor = this.sequenceNumberColor || invert(this.lineColor);\n this.sectionBkgColor = this.sectionBkgColor || this.tertiaryColor;\n this.altSectionBkgColor = this.altSectionBkgColor || \"white\";\n this.sectionBkgColor = this.sectionBkgColor || this.secondaryColor;\n this.sectionBkgColor2 = this.sectionBkgColor2 || this.primaryColor;\n this.excludeBkgColor = this.excludeBkgColor || \"#eeeeee\";\n this.taskBorderColor = this.taskBorderColor || this.primaryBorderColor;\n this.taskBkgColor = this.taskBkgColor || this.primaryColor;\n this.activeTaskBorderColor = this.activeTaskBorderColor || this.primaryColor;\n this.activeTaskBkgColor = this.activeTaskBkgColor || lighten(this.primaryColor, 23);\n this.gridColor = this.gridColor || \"lightgrey\";\n this.doneTaskBkgColor = this.doneTaskBkgColor || \"lightgrey\";\n this.doneTaskBorderColor = this.doneTaskBorderColor || \"grey\";\n this.critBorderColor = this.critBorderColor || \"#ff8888\";\n this.critBkgColor = this.critBkgColor || \"red\";\n this.todayLineColor = this.todayLineColor || \"red\";\n this.vertLineColor = this.vertLineColor || \"navy\";\n this.taskTextColor = this.taskTextColor || this.textColor;\n this.taskTextOutsideColor = this.taskTextOutsideColor || this.textColor;\n this.taskTextLightColor = this.taskTextLightColor || this.textColor;\n this.taskTextColor = this.taskTextColor || this.primaryTextColor;\n this.taskTextDarkColor = this.taskTextDarkColor || this.textColor;\n this.taskTextClickableColor = this.taskTextClickableColor || \"#003163\";\n this.personBorder = this.personBorder || this.primaryBorderColor;\n this.personBkg = this.personBkg || this.mainBkg;\n if (this.darkMode) {\n this.rowOdd = this.rowOdd || darken(this.mainBkg, 5) || \"#ffffff\";\n this.rowEven = this.rowEven || darken(this.mainBkg, 10);\n } else {\n this.rowOdd = this.rowOdd || lighten(this.mainBkg, 75) || \"#ffffff\";\n this.rowEven = this.rowEven || lighten(this.mainBkg, 5);\n }\n this.transitionColor = this.transitionColor || this.lineColor;\n this.transitionLabelColor = this.transitionLabelColor || this.textColor;\n this.stateLabelColor = this.stateLabelColor || this.stateBkg || this.primaryTextColor;\n this.stateBkg = this.stateBkg || this.mainBkg;\n this.labelBackgroundColor = this.labelBackgroundColor || this.stateBkg;\n this.compositeBackground = this.compositeBackground || this.background || this.tertiaryColor;\n this.altBackground = this.altBackground || this.tertiaryColor;\n this.compositeTitleBackground = this.compositeTitleBackground || this.mainBkg;\n this.compositeBorder = this.compositeBorder || this.nodeBorder;\n this.innerEndBackground = this.nodeBorder;\n this.errorBkgColor = this.errorBkgColor || this.tertiaryColor;\n this.errorTextColor = this.errorTextColor || this.tertiaryTextColor;\n this.transitionColor = this.transitionColor || this.lineColor;\n this.specialStateColor = this.lineColor;\n this.cScale0 = this.cScale0 || this.primaryColor;\n this.cScale1 = this.cScale1 || this.secondaryColor;\n this.cScale2 = this.cScale2 || this.tertiaryColor;\n this.cScale3 = this.cScale3 || adjust2(this.primaryColor, { h: 30 });\n this.cScale4 = this.cScale4 || adjust2(this.primaryColor, { h: 60 });\n this.cScale5 = this.cScale5 || adjust2(this.primaryColor, { h: 90 });\n this.cScale6 = this.cScale6 || adjust2(this.primaryColor, { h: 120 });\n this.cScale7 = this.cScale7 || adjust2(this.primaryColor, { h: 150 });\n this.cScale8 = this.cScale8 || adjust2(this.primaryColor, { h: 210, l: 150 });\n this.cScale9 = this.cScale9 || adjust2(this.primaryColor, { h: 270 });\n this.cScale10 = this.cScale10 || adjust2(this.primaryColor, { h: 300 });\n this.cScale11 = this.cScale11 || adjust2(this.primaryColor, { h: 330 });\n if (this.darkMode) {\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n this[\"cScale\" + i] = darken(this[\"cScale\" + i], 75);\n }\n } else {\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n this[\"cScale\" + i] = darken(this[\"cScale\" + i], 25);\n }\n }\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n this[\"cScaleInv\" + i] = this[\"cScaleInv\" + i] || invert(this[\"cScale\" + i]);\n }\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n if (this.darkMode) {\n this[\"cScalePeer\" + i] = this[\"cScalePeer\" + i] || lighten(this[\"cScale\" + i], 10);\n } else {\n this[\"cScalePeer\" + i] = this[\"cScalePeer\" + i] || darken(this[\"cScale\" + i], 10);\n }\n }\n this.scaleLabelColor = this.scaleLabelColor || this.labelTextColor;\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n this[\"cScaleLabel\" + i] = this[\"cScaleLabel\" + i] || this.scaleLabelColor;\n }\n const multiplier = this.darkMode ? -4 : -1;\n for (let i = 0; i < 5; i++) {\n this[\"surface\" + i] = this[\"surface\" + i] || adjust2(this.mainBkg, { h: 180, s: -15, l: multiplier * (5 + i * 3) });\n this[\"surfacePeer\" + i] = this[\"surfacePeer\" + i] || adjust2(this.mainBkg, { h: 180, s: -15, l: multiplier * (8 + i * 3) });\n }\n this.classText = this.classText || this.textColor;\n this.fillType0 = this.fillType0 || this.primaryColor;\n this.fillType1 = this.fillType1 || this.secondaryColor;\n this.fillType2 = this.fillType2 || adjust2(this.primaryColor, { h: 64 });\n this.fillType3 = this.fillType3 || adjust2(this.secondaryColor, { h: 64 });\n this.fillType4 = this.fillType4 || adjust2(this.primaryColor, { h: -64 });\n this.fillType5 = this.fillType5 || adjust2(this.secondaryColor, { h: -64 });\n this.fillType6 = this.fillType6 || adjust2(this.primaryColor, { h: 128 });\n this.fillType7 = this.fillType7 || adjust2(this.secondaryColor, { h: 128 });\n this.pie1 = this.pie1 || this.primaryColor;\n this.pie2 = this.pie2 || this.secondaryColor;\n this.pie3 = this.pie3 || this.tertiaryColor;\n this.pie4 = this.pie4 || adjust2(this.primaryColor, { l: -10 });\n this.pie5 = this.pie5 || adjust2(this.secondaryColor, { l: -10 });\n this.pie6 = this.pie6 || adjust2(this.tertiaryColor, { l: -10 });\n this.pie7 = this.pie7 || adjust2(this.primaryColor, { h: 60, l: -10 });\n this.pie8 = this.pie8 || adjust2(this.primaryColor, { h: -60, l: -10 });\n this.pie9 = this.pie9 || adjust2(this.primaryColor, { h: 120, l: 0 });\n this.pie10 = this.pie10 || adjust2(this.primaryColor, { h: 60, l: -20 });\n this.pie11 = this.pie11 || adjust2(this.primaryColor, { h: -60, l: -20 });\n this.pie12 = this.pie12 || adjust2(this.primaryColor, { h: 120, l: -10 });\n this.pieTitleTextSize = this.pieTitleTextSize || \"25px\";\n this.pieTitleTextColor = this.pieTitleTextColor || this.taskTextDarkColor;\n this.pieSectionTextSize = this.pieSectionTextSize || \"17px\";\n this.pieSectionTextColor = this.pieSectionTextColor || this.textColor;\n this.pieLegendTextSize = this.pieLegendTextSize || \"17px\";\n this.pieLegendTextColor = this.pieLegendTextColor || this.taskTextDarkColor;\n this.pieStrokeColor = this.pieStrokeColor || \"black\";\n this.pieStrokeWidth = this.pieStrokeWidth || \"2px\";\n this.pieOuterStrokeWidth = this.pieOuterStrokeWidth || \"2px\";\n this.pieOuterStrokeColor = this.pieOuterStrokeColor || \"black\";\n this.pieOpacity = this.pieOpacity || \"0.7\";\n this.radar = {\n axisColor: this.radar?.axisColor || this.lineColor,\n axisStrokeWidth: this.radar?.axisStrokeWidth || 2,\n axisLabelFontSize: this.radar?.axisLabelFontSize || 12,\n curveOpacity: this.radar?.curveOpacity || 0.5,\n curveStrokeWidth: this.radar?.curveStrokeWidth || 2,\n graticuleColor: this.radar?.graticuleColor || \"#DEDEDE\",\n graticuleStrokeWidth: this.radar?.graticuleStrokeWidth || 1,\n graticuleOpacity: this.radar?.graticuleOpacity || 0.3,\n legendBoxSize: this.radar?.legendBoxSize || 12,\n legendFontSize: this.radar?.legendFontSize || 12\n };\n this.archEdgeColor = this.archEdgeColor || \"#777\";\n this.archEdgeArrowColor = this.archEdgeArrowColor || \"#777\";\n this.archEdgeWidth = this.archEdgeWidth || \"3\";\n this.archGroupBorderColor = this.archGroupBorderColor || \"#000\";\n this.archGroupBorderWidth = this.archGroupBorderWidth || \"2px\";\n this.quadrant1Fill = this.quadrant1Fill || this.primaryColor;\n this.quadrant2Fill = this.quadrant2Fill || adjust2(this.primaryColor, { r: 5, g: 5, b: 5 });\n this.quadrant3Fill = this.quadrant3Fill || adjust2(this.primaryColor, { r: 10, g: 10, b: 10 });\n this.quadrant4Fill = this.quadrant4Fill || adjust2(this.primaryColor, { r: 15, g: 15, b: 15 });\n this.quadrant1TextFill = this.quadrant1TextFill || this.primaryTextColor;\n this.quadrant2TextFill = this.quadrant2TextFill || adjust2(this.primaryTextColor, { r: -5, g: -5, b: -5 });\n this.quadrant3TextFill = this.quadrant3TextFill || adjust2(this.primaryTextColor, { r: -10, g: -10, b: -10 });\n this.quadrant4TextFill = this.quadrant4TextFill || adjust2(this.primaryTextColor, { r: -15, g: -15, b: -15 });\n this.quadrantPointFill = this.quadrantPointFill || isDark(this.quadrant1Fill) ? lighten(this.quadrant1Fill) : darken(this.quadrant1Fill);\n this.quadrantPointTextFill = this.quadrantPointTextFill || this.primaryTextColor;\n this.quadrantXAxisTextFill = this.quadrantXAxisTextFill || this.primaryTextColor;\n this.quadrantYAxisTextFill = this.quadrantYAxisTextFill || this.primaryTextColor;\n this.quadrantInternalBorderStrokeFill = this.quadrantInternalBorderStrokeFill || this.primaryBorderColor;\n this.quadrantExternalBorderStrokeFill = this.quadrantExternalBorderStrokeFill || this.primaryBorderColor;\n this.quadrantTitleFill = this.quadrantTitleFill || this.primaryTextColor;\n this.xyChart = {\n backgroundColor: this.xyChart?.backgroundColor || this.background,\n titleColor: this.xyChart?.titleColor || this.primaryTextColor,\n xAxisTitleColor: this.xyChart?.xAxisTitleColor || this.primaryTextColor,\n xAxisLabelColor: this.xyChart?.xAxisLabelColor || this.primaryTextColor,\n xAxisTickColor: this.xyChart?.xAxisTickColor || this.primaryTextColor,\n xAxisLineColor: this.xyChart?.xAxisLineColor || this.primaryTextColor,\n yAxisTitleColor: this.xyChart?.yAxisTitleColor || this.primaryTextColor,\n yAxisLabelColor: this.xyChart?.yAxisLabelColor || this.primaryTextColor,\n yAxisTickColor: this.xyChart?.yAxisTickColor || this.primaryTextColor,\n yAxisLineColor: this.xyChart?.yAxisLineColor || this.primaryTextColor,\n plotColorPalette: this.xyChart?.plotColorPalette || \"#FFF4DD,#FFD8B1,#FFA07A,#ECEFF1,#D6DBDF,#C3E0A8,#FFB6A4,#FFD74D,#738FA7,#FFFFF0\"\n };\n this.requirementBackground = this.requirementBackground || this.primaryColor;\n this.requirementBorderColor = this.requirementBorderColor || this.primaryBorderColor;\n this.requirementBorderSize = this.requirementBorderSize || \"1\";\n this.requirementTextColor = this.requirementTextColor || this.primaryTextColor;\n this.relationColor = this.relationColor || this.lineColor;\n this.relationLabelBackground = this.relationLabelBackground || (this.darkMode ? darken(this.secondaryColor, 30) : this.secondaryColor);\n this.relationLabelColor = this.relationLabelColor || this.actorTextColor;\n this.git0 = this.git0 || this.primaryColor;\n this.git1 = this.git1 || this.secondaryColor;\n this.git2 = this.git2 || this.tertiaryColor;\n this.git3 = this.git3 || adjust2(this.primaryColor, { h: -30 });\n this.git4 = this.git4 || adjust2(this.primaryColor, { h: -60 });\n this.git5 = this.git5 || adjust2(this.primaryColor, { h: -90 });\n this.git6 = this.git6 || adjust2(this.primaryColor, { h: 60 });\n this.git7 = this.git7 || adjust2(this.primaryColor, { h: 120 });\n if (this.darkMode) {\n this.git0 = lighten(this.git0, 25);\n this.git1 = lighten(this.git1, 25);\n this.git2 = lighten(this.git2, 25);\n this.git3 = lighten(this.git3, 25);\n this.git4 = lighten(this.git4, 25);\n this.git5 = lighten(this.git5, 25);\n this.git6 = lighten(this.git6, 25);\n this.git7 = lighten(this.git7, 25);\n } else {\n this.git0 = darken(this.git0, 25);\n this.git1 = darken(this.git1, 25);\n this.git2 = darken(this.git2, 25);\n this.git3 = darken(this.git3, 25);\n this.git4 = darken(this.git4, 25);\n this.git5 = darken(this.git5, 25);\n this.git6 = darken(this.git6, 25);\n this.git7 = darken(this.git7, 25);\n }\n this.gitInv0 = this.gitInv0 || invert(this.git0);\n this.gitInv1 = this.gitInv1 || invert(this.git1);\n this.gitInv2 = this.gitInv2 || invert(this.git2);\n this.gitInv3 = this.gitInv3 || invert(this.git3);\n this.gitInv4 = this.gitInv4 || invert(this.git4);\n this.gitInv5 = this.gitInv5 || invert(this.git5);\n this.gitInv6 = this.gitInv6 || invert(this.git6);\n this.gitInv7 = this.gitInv7 || invert(this.git7);\n this.branchLabelColor = this.branchLabelColor || (this.darkMode ? \"black\" : this.labelTextColor);\n this.gitBranchLabel0 = this.gitBranchLabel0 || this.branchLabelColor;\n this.gitBranchLabel1 = this.gitBranchLabel1 || this.branchLabelColor;\n this.gitBranchLabel2 = this.gitBranchLabel2 || this.branchLabelColor;\n this.gitBranchLabel3 = this.gitBranchLabel3 || this.branchLabelColor;\n this.gitBranchLabel4 = this.gitBranchLabel4 || this.branchLabelColor;\n this.gitBranchLabel5 = this.gitBranchLabel5 || this.branchLabelColor;\n this.gitBranchLabel6 = this.gitBranchLabel6 || this.branchLabelColor;\n this.gitBranchLabel7 = this.gitBranchLabel7 || this.branchLabelColor;\n this.tagLabelColor = this.tagLabelColor || this.primaryTextColor;\n this.tagLabelBackground = this.tagLabelBackground || this.primaryColor;\n this.tagLabelBorder = this.tagBorder || this.primaryBorderColor;\n this.tagLabelFontSize = this.tagLabelFontSize || \"10px\";\n this.commitLabelColor = this.commitLabelColor || this.secondaryTextColor;\n this.commitLabelBackground = this.commitLabelBackground || this.secondaryColor;\n this.commitLabelFontSize = this.commitLabelFontSize || \"10px\";\n this.attributeBackgroundColorOdd = this.attributeBackgroundColorOdd || oldAttributeBackgroundColorOdd;\n this.attributeBackgroundColorEven = this.attributeBackgroundColorEven || oldAttributeBackgroundColorEven;\n }\n calculate(overrides) {\n if (typeof overrides !== \"object\") {\n this.updateColors();\n return;\n }\n const keys = Object.keys(overrides);\n keys.forEach((k) => {\n this[k] = overrides[k];\n });\n this.updateColors();\n keys.forEach((k) => {\n this[k] = overrides[k];\n });\n }\n};\nvar getThemeVariables = /* @__PURE__ */ __name((userOverrides) => {\n const theme = new Theme();\n theme.calculate(userOverrides);\n return theme;\n}, \"getThemeVariables\");\n\n// src/themes/theme-dark.js\nimport { adjust as adjust3, darken as darken2, invert as invert2, isDark as isDark2, lighten as lighten2, rgba } from \"khroma\";\nvar Theme2 = class {\n static {\n __name(this, \"Theme\");\n }\n constructor() {\n this.background = \"#333\";\n this.primaryColor = \"#1f2020\";\n this.secondaryColor = lighten2(this.primaryColor, 16);\n this.tertiaryColor = adjust3(this.primaryColor, { h: -160 });\n this.primaryBorderColor = invert2(this.background);\n this.secondaryBorderColor = mkBorder(this.secondaryColor, this.darkMode);\n this.tertiaryBorderColor = mkBorder(this.tertiaryColor, this.darkMode);\n this.primaryTextColor = invert2(this.primaryColor);\n this.secondaryTextColor = invert2(this.secondaryColor);\n this.tertiaryTextColor = invert2(this.tertiaryColor);\n this.lineColor = invert2(this.background);\n this.textColor = invert2(this.background);\n this.mainBkg = \"#1f2020\";\n this.secondBkg = \"calculated\";\n this.mainContrastColor = \"lightgrey\";\n this.darkTextColor = lighten2(invert2(\"#323D47\"), 10);\n this.lineColor = \"calculated\";\n this.border1 = \"#ccc\";\n this.border2 = rgba(255, 255, 255, 0.25);\n this.arrowheadColor = \"calculated\";\n this.fontFamily = '\"trebuchet ms\", verdana, arial, sans-serif';\n this.fontSize = \"16px\";\n this.labelBackground = \"#181818\";\n this.textColor = \"#ccc\";\n this.THEME_COLOR_LIMIT = 12;\n this.nodeBkg = \"calculated\";\n this.nodeBorder = \"calculated\";\n this.clusterBkg = \"calculated\";\n this.clusterBorder = \"calculated\";\n this.defaultLinkColor = \"calculated\";\n this.titleColor = \"#F9FFFE\";\n this.edgeLabelBackground = \"calculated\";\n this.actorBorder = \"calculated\";\n this.actorBkg = \"calculated\";\n this.actorTextColor = \"calculated\";\n this.actorLineColor = \"calculated\";\n this.signalColor = \"calculated\";\n this.signalTextColor = \"calculated\";\n this.labelBoxBkgColor = \"calculated\";\n this.labelBoxBorderColor = \"calculated\";\n this.labelTextColor = \"calculated\";\n this.loopTextColor = \"calculated\";\n this.noteBorderColor = \"calculated\";\n this.noteBkgColor = \"#fff5ad\";\n this.noteTextColor = \"calculated\";\n this.activationBorderColor = \"calculated\";\n this.activationBkgColor = \"calculated\";\n this.sequenceNumberColor = \"black\";\n this.sectionBkgColor = darken2(\"#EAE8D9\", 30);\n this.altSectionBkgColor = \"calculated\";\n this.sectionBkgColor2 = \"#EAE8D9\";\n this.excludeBkgColor = darken2(this.sectionBkgColor, 10);\n this.taskBorderColor = rgba(255, 255, 255, 70);\n this.taskBkgColor = \"calculated\";\n this.taskTextColor = \"calculated\";\n this.taskTextLightColor = \"calculated\";\n this.taskTextOutsideColor = \"calculated\";\n this.taskTextClickableColor = \"#003163\";\n this.activeTaskBorderColor = rgba(255, 255, 255, 50);\n this.activeTaskBkgColor = \"#81B1DB\";\n this.gridColor = \"calculated\";\n this.doneTaskBkgColor = \"calculated\";\n this.doneTaskBorderColor = \"grey\";\n this.critBorderColor = \"#E83737\";\n this.critBkgColor = \"#E83737\";\n this.taskTextDarkColor = \"calculated\";\n this.todayLineColor = \"#DB5757\";\n this.vertLineColor = \"#00BFFF\";\n this.personBorder = this.primaryBorderColor;\n this.personBkg = this.mainBkg;\n this.archEdgeColor = \"calculated\";\n this.archEdgeArrowColor = \"calculated\";\n this.archEdgeWidth = \"3\";\n this.archGroupBorderColor = this.primaryBorderColor;\n this.archGroupBorderWidth = \"2px\";\n this.rowOdd = this.rowOdd || lighten2(this.mainBkg, 5) || \"#ffffff\";\n this.rowEven = this.rowEven || darken2(this.mainBkg, 10);\n this.labelColor = \"calculated\";\n this.errorBkgColor = \"#a44141\";\n this.errorTextColor = \"#ddd\";\n }\n updateColors() {\n this.secondBkg = lighten2(this.mainBkg, 16);\n this.lineColor = this.mainContrastColor;\n this.arrowheadColor = this.mainContrastColor;\n this.nodeBkg = this.mainBkg;\n this.nodeBorder = this.border1;\n this.clusterBkg = this.secondBkg;\n this.clusterBorder = this.border2;\n this.defaultLinkColor = this.lineColor;\n this.edgeLabelBackground = lighten2(this.labelBackground, 25);\n this.actorBorder = this.border1;\n this.actorBkg = this.mainBkg;\n this.actorTextColor = this.mainContrastColor;\n this.actorLineColor = this.actorBorder;\n this.signalColor = this.mainContrastColor;\n this.signalTextColor = this.mainContrastColor;\n this.labelBoxBkgColor = this.actorBkg;\n this.labelBoxBorderColor = this.actorBorder;\n this.labelTextColor = this.mainContrastColor;\n this.loopTextColor = this.mainContrastColor;\n this.noteBorderColor = this.secondaryBorderColor;\n this.noteBkgColor = this.secondBkg;\n this.noteTextColor = this.secondaryTextColor;\n this.activationBorderColor = this.border1;\n this.activationBkgColor = this.secondBkg;\n this.altSectionBkgColor = this.background;\n this.taskBkgColor = lighten2(this.mainBkg, 23);\n this.taskTextColor = this.darkTextColor;\n this.taskTextLightColor = this.mainContrastColor;\n this.taskTextOutsideColor = this.taskTextLightColor;\n this.gridColor = this.mainContrastColor;\n this.doneTaskBkgColor = this.mainContrastColor;\n this.taskTextDarkColor = this.darkTextColor;\n this.archEdgeColor = this.lineColor;\n this.archEdgeArrowColor = this.lineColor;\n this.transitionColor = this.transitionColor || this.lineColor;\n this.transitionLabelColor = this.transitionLabelColor || this.textColor;\n this.stateLabelColor = this.stateLabelColor || this.stateBkg || this.primaryTextColor;\n this.stateBkg = this.stateBkg || this.mainBkg;\n this.labelBackgroundColor = this.labelBackgroundColor || this.stateBkg;\n this.compositeBackground = this.compositeBackground || this.background || this.tertiaryColor;\n this.altBackground = this.altBackground || \"#555\";\n this.compositeTitleBackground = this.compositeTitleBackground || this.mainBkg;\n this.compositeBorder = this.compositeBorder || this.nodeBorder;\n this.innerEndBackground = this.primaryBorderColor;\n this.specialStateColor = \"#f4f4f4\";\n this.errorBkgColor = this.errorBkgColor || this.tertiaryColor;\n this.errorTextColor = this.errorTextColor || this.tertiaryTextColor;\n this.fillType0 = this.primaryColor;\n this.fillType1 = this.secondaryColor;\n this.fillType2 = adjust3(this.primaryColor, { h: 64 });\n this.fillType3 = adjust3(this.secondaryColor, { h: 64 });\n this.fillType4 = adjust3(this.primaryColor, { h: -64 });\n this.fillType5 = adjust3(this.secondaryColor, { h: -64 });\n this.fillType6 = adjust3(this.primaryColor, { h: 128 });\n this.fillType7 = adjust3(this.secondaryColor, { h: 128 });\n this.cScale1 = this.cScale1 || \"#0b0000\";\n this.cScale2 = this.cScale2 || \"#4d1037\";\n this.cScale3 = this.cScale3 || \"#3f5258\";\n this.cScale4 = this.cScale4 || \"#4f2f1b\";\n this.cScale5 = this.cScale5 || \"#6e0a0a\";\n this.cScale6 = this.cScale6 || \"#3b0048\";\n this.cScale7 = this.cScale7 || \"#995a01\";\n this.cScale8 = this.cScale8 || \"#154706\";\n this.cScale9 = this.cScale9 || \"#161722\";\n this.cScale10 = this.cScale10 || \"#00296f\";\n this.cScale11 = this.cScale11 || \"#01629c\";\n this.cScale12 = this.cScale12 || \"#010029\";\n this.cScale0 = this.cScale0 || this.primaryColor;\n this.cScale1 = this.cScale1 || this.secondaryColor;\n this.cScale2 = this.cScale2 || this.tertiaryColor;\n this.cScale3 = this.cScale3 || adjust3(this.primaryColor, { h: 30 });\n this.cScale4 = this.cScale4 || adjust3(this.primaryColor, { h: 60 });\n this.cScale5 = this.cScale5 || adjust3(this.primaryColor, { h: 90 });\n this.cScale6 = this.cScale6 || adjust3(this.primaryColor, { h: 120 });\n this.cScale7 = this.cScale7 || adjust3(this.primaryColor, { h: 150 });\n this.cScale8 = this.cScale8 || adjust3(this.primaryColor, { h: 210 });\n this.cScale9 = this.cScale9 || adjust3(this.primaryColor, { h: 270 });\n this.cScale10 = this.cScale10 || adjust3(this.primaryColor, { h: 300 });\n this.cScale11 = this.cScale11 || adjust3(this.primaryColor, { h: 330 });\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n this[\"cScaleInv\" + i] = this[\"cScaleInv\" + i] || invert2(this[\"cScale\" + i]);\n }\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n this[\"cScalePeer\" + i] = this[\"cScalePeer\" + i] || lighten2(this[\"cScale\" + i], 10);\n }\n for (let i = 0; i < 5; i++) {\n this[\"surface\" + i] = this[\"surface\" + i] || adjust3(this.mainBkg, { h: 30, s: -30, l: -(-10 + i * 4) });\n this[\"surfacePeer\" + i] = this[\"surfacePeer\" + i] || adjust3(this.mainBkg, { h: 30, s: -30, l: -(-7 + i * 4) });\n }\n this.scaleLabelColor = this.scaleLabelColor || (this.darkMode ? \"black\" : this.labelTextColor);\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n this[\"cScaleLabel\" + i] = this[\"cScaleLabel\" + i] || this.scaleLabelColor;\n }\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n this[\"pie\" + i] = this[\"cScale\" + i];\n }\n this.pieTitleTextSize = this.pieTitleTextSize || \"25px\";\n this.pieTitleTextColor = this.pieTitleTextColor || this.taskTextDarkColor;\n this.pieSectionTextSize = this.pieSectionTextSize || \"17px\";\n this.pieSectionTextColor = this.pieSectionTextColor || this.textColor;\n this.pieLegendTextSize = this.pieLegendTextSize || \"17px\";\n this.pieLegendTextColor = this.pieLegendTextColor || this.taskTextDarkColor;\n this.pieStrokeColor = this.pieStrokeColor || \"black\";\n this.pieStrokeWidth = this.pieStrokeWidth || \"2px\";\n this.pieOuterStrokeWidth = this.pieOuterStrokeWidth || \"2px\";\n this.pieOuterStrokeColor = this.pieOuterStrokeColor || \"black\";\n this.pieOpacity = this.pieOpacity || \"0.7\";\n this.quadrant1Fill = this.quadrant1Fill || this.primaryColor;\n this.quadrant2Fill = this.quadrant2Fill || adjust3(this.primaryColor, { r: 5, g: 5, b: 5 });\n this.quadrant3Fill = this.quadrant3Fill || adjust3(this.primaryColor, { r: 10, g: 10, b: 10 });\n this.quadrant4Fill = this.quadrant4Fill || adjust3(this.primaryColor, { r: 15, g: 15, b: 15 });\n this.quadrant1TextFill = this.quadrant1TextFill || this.primaryTextColor;\n this.quadrant2TextFill = this.quadrant2TextFill || adjust3(this.primaryTextColor, { r: -5, g: -5, b: -5 });\n this.quadrant3TextFill = this.quadrant3TextFill || adjust3(this.primaryTextColor, { r: -10, g: -10, b: -10 });\n this.quadrant4TextFill = this.quadrant4TextFill || adjust3(this.primaryTextColor, { r: -15, g: -15, b: -15 });\n this.quadrantPointFill = this.quadrantPointFill || isDark2(this.quadrant1Fill) ? lighten2(this.quadrant1Fill) : darken2(this.quadrant1Fill);\n this.quadrantPointTextFill = this.quadrantPointTextFill || this.primaryTextColor;\n this.quadrantXAxisTextFill = this.quadrantXAxisTextFill || this.primaryTextColor;\n this.quadrantYAxisTextFill = this.quadrantYAxisTextFill || this.primaryTextColor;\n this.quadrantInternalBorderStrokeFill = this.quadrantInternalBorderStrokeFill || this.primaryBorderColor;\n this.quadrantExternalBorderStrokeFill = this.quadrantExternalBorderStrokeFill || this.primaryBorderColor;\n this.quadrantTitleFill = this.quadrantTitleFill || this.primaryTextColor;\n this.xyChart = {\n backgroundColor: this.xyChart?.backgroundColor || this.background,\n titleColor: this.xyChart?.titleColor || this.primaryTextColor,\n xAxisTitleColor: this.xyChart?.xAxisTitleColor || this.primaryTextColor,\n xAxisLabelColor: this.xyChart?.xAxisLabelColor || this.primaryTextColor,\n xAxisTickColor: this.xyChart?.xAxisTickColor || this.primaryTextColor,\n xAxisLineColor: this.xyChart?.xAxisLineColor || this.primaryTextColor,\n yAxisTitleColor: this.xyChart?.yAxisTitleColor || this.primaryTextColor,\n yAxisLabelColor: this.xyChart?.yAxisLabelColor || this.primaryTextColor,\n yAxisTickColor: this.xyChart?.yAxisTickColor || this.primaryTextColor,\n yAxisLineColor: this.xyChart?.yAxisLineColor || this.primaryTextColor,\n plotColorPalette: this.xyChart?.plotColorPalette || \"#3498db,#2ecc71,#e74c3c,#f1c40f,#bdc3c7,#ffffff,#34495e,#9b59b6,#1abc9c,#e67e22\"\n };\n this.packet = {\n startByteColor: this.primaryTextColor,\n endByteColor: this.primaryTextColor,\n labelColor: this.primaryTextColor,\n titleColor: this.primaryTextColor,\n blockStrokeColor: this.primaryTextColor,\n blockFillColor: this.background\n };\n this.radar = {\n axisColor: this.radar?.axisColor || this.lineColor,\n axisStrokeWidth: this.radar?.axisStrokeWidth || 2,\n axisLabelFontSize: this.radar?.axisLabelFontSize || 12,\n curveOpacity: this.radar?.curveOpacity || 0.5,\n curveStrokeWidth: this.radar?.curveStrokeWidth || 2,\n graticuleColor: this.radar?.graticuleColor || \"#DEDEDE\",\n graticuleStrokeWidth: this.radar?.graticuleStrokeWidth || 1,\n graticuleOpacity: this.radar?.graticuleOpacity || 0.3,\n legendBoxSize: this.radar?.legendBoxSize || 12,\n legendFontSize: this.radar?.legendFontSize || 12\n };\n this.classText = this.primaryTextColor;\n this.requirementBackground = this.requirementBackground || this.primaryColor;\n this.requirementBorderColor = this.requirementBorderColor || this.primaryBorderColor;\n this.requirementBorderSize = this.requirementBorderSize || \"1\";\n this.requirementTextColor = this.requirementTextColor || this.primaryTextColor;\n this.relationColor = this.relationColor || this.lineColor;\n this.relationLabelBackground = this.relationLabelBackground || (this.darkMode ? darken2(this.secondaryColor, 30) : this.secondaryColor);\n this.relationLabelColor = this.relationLabelColor || this.actorTextColor;\n this.git0 = lighten2(this.secondaryColor, 20);\n this.git1 = lighten2(this.pie2 || this.secondaryColor, 20);\n this.git2 = lighten2(this.pie3 || this.tertiaryColor, 20);\n this.git3 = lighten2(this.pie4 || adjust3(this.primaryColor, { h: -30 }), 20);\n this.git4 = lighten2(this.pie5 || adjust3(this.primaryColor, { h: -60 }), 20);\n this.git5 = lighten2(this.pie6 || adjust3(this.primaryColor, { h: -90 }), 10);\n this.git6 = lighten2(this.pie7 || adjust3(this.primaryColor, { h: 60 }), 10);\n this.git7 = lighten2(this.pie8 || adjust3(this.primaryColor, { h: 120 }), 20);\n this.gitInv0 = this.gitInv0 || invert2(this.git0);\n this.gitInv1 = this.gitInv1 || invert2(this.git1);\n this.gitInv2 = this.gitInv2 || invert2(this.git2);\n this.gitInv3 = this.gitInv3 || invert2(this.git3);\n this.gitInv4 = this.gitInv4 || invert2(this.git4);\n this.gitInv5 = this.gitInv5 || invert2(this.git5);\n this.gitInv6 = this.gitInv6 || invert2(this.git6);\n this.gitInv7 = this.gitInv7 || invert2(this.git7);\n this.gitBranchLabel0 = this.gitBranchLabel0 || invert2(this.labelTextColor);\n this.gitBranchLabel1 = this.gitBranchLabel1 || this.labelTextColor;\n this.gitBranchLabel2 = this.gitBranchLabel2 || this.labelTextColor;\n this.gitBranchLabel3 = this.gitBranchLabel3 || invert2(this.labelTextColor);\n this.gitBranchLabel4 = this.gitBranchLabel4 || this.labelTextColor;\n this.gitBranchLabel5 = this.gitBranchLabel5 || this.labelTextColor;\n this.gitBranchLabel6 = this.gitBranchLabel6 || this.labelTextColor;\n this.gitBranchLabel7 = this.gitBranchLabel7 || this.labelTextColor;\n this.tagLabelColor = this.tagLabelColor || this.primaryTextColor;\n this.tagLabelBackground = this.tagLabelBackground || this.primaryColor;\n this.tagLabelBorder = this.tagBorder || this.primaryBorderColor;\n this.tagLabelFontSize = this.tagLabelFontSize || \"10px\";\n this.commitLabelColor = this.commitLabelColor || this.secondaryTextColor;\n this.commitLabelBackground = this.commitLabelBackground || this.secondaryColor;\n this.commitLabelFontSize = this.commitLabelFontSize || \"10px\";\n this.attributeBackgroundColorOdd = this.attributeBackgroundColorOdd || lighten2(this.background, 12);\n this.attributeBackgroundColorEven = this.attributeBackgroundColorEven || lighten2(this.background, 2);\n this.nodeBorder = this.nodeBorder || \"#999\";\n }\n calculate(overrides) {\n if (typeof overrides !== \"object\") {\n this.updateColors();\n return;\n }\n const keys = Object.keys(overrides);\n keys.forEach((k) => {\n this[k] = overrides[k];\n });\n this.updateColors();\n keys.forEach((k) => {\n this[k] = overrides[k];\n });\n }\n};\nvar getThemeVariables2 = /* @__PURE__ */ __name((userOverrides) => {\n const theme = new Theme2();\n theme.calculate(userOverrides);\n return theme;\n}, \"getThemeVariables\");\n\n// src/themes/theme-default.js\nimport { invert as invert3, lighten as lighten3, rgba as rgba2, adjust as adjust4, darken as darken3, isDark as isDark3 } from \"khroma\";\nvar Theme3 = class {\n static {\n __name(this, \"Theme\");\n }\n constructor() {\n this.background = \"#f4f4f4\";\n this.primaryColor = \"#ECECFF\";\n this.secondaryColor = adjust4(this.primaryColor, { h: 120 });\n this.secondaryColor = \"#ffffde\";\n this.tertiaryColor = adjust4(this.primaryColor, { h: -160 });\n this.primaryBorderColor = mkBorder(this.primaryColor, this.darkMode);\n this.secondaryBorderColor = mkBorder(this.secondaryColor, this.darkMode);\n this.tertiaryBorderColor = mkBorder(this.tertiaryColor, this.darkMode);\n this.primaryTextColor = invert3(this.primaryColor);\n this.secondaryTextColor = invert3(this.secondaryColor);\n this.tertiaryTextColor = invert3(this.tertiaryColor);\n this.lineColor = invert3(this.background);\n this.textColor = invert3(this.background);\n this.background = \"white\";\n this.mainBkg = \"#ECECFF\";\n this.secondBkg = \"#ffffde\";\n this.lineColor = \"#333333\";\n this.border1 = \"#9370DB\";\n this.border2 = \"#aaaa33\";\n this.arrowheadColor = \"#333333\";\n this.fontFamily = '\"trebuchet ms\", verdana, arial, sans-serif';\n this.fontSize = \"16px\";\n this.labelBackground = \"rgba(232,232,232, 0.8)\";\n this.textColor = \"#333\";\n this.THEME_COLOR_LIMIT = 12;\n this.nodeBkg = \"calculated\";\n this.nodeBorder = \"calculated\";\n this.clusterBkg = \"calculated\";\n this.clusterBorder = \"calculated\";\n this.defaultLinkColor = \"calculated\";\n this.titleColor = \"calculated\";\n this.edgeLabelBackground = \"calculated\";\n this.actorBorder = \"calculated\";\n this.actorBkg = \"calculated\";\n this.actorTextColor = \"black\";\n this.actorLineColor = \"calculated\";\n this.signalColor = \"calculated\";\n this.signalTextColor = \"calculated\";\n this.labelBoxBkgColor = \"calculated\";\n this.labelBoxBorderColor = \"calculated\";\n this.labelTextColor = \"calculated\";\n this.loopTextColor = \"calculated\";\n this.noteBorderColor = \"calculated\";\n this.noteBkgColor = \"#fff5ad\";\n this.noteTextColor = \"calculated\";\n this.activationBorderColor = \"#666\";\n this.activationBkgColor = \"#f4f4f4\";\n this.sequenceNumberColor = \"white\";\n this.sectionBkgColor = \"calculated\";\n this.altSectionBkgColor = \"calculated\";\n this.sectionBkgColor2 = \"calculated\";\n this.excludeBkgColor = \"#eeeeee\";\n this.taskBorderColor = \"calculated\";\n this.taskBkgColor = \"calculated\";\n this.taskTextLightColor = \"calculated\";\n this.taskTextColor = this.taskTextLightColor;\n this.taskTextDarkColor = \"calculated\";\n this.taskTextOutsideColor = this.taskTextDarkColor;\n this.taskTextClickableColor = \"calculated\";\n this.activeTaskBorderColor = \"calculated\";\n this.activeTaskBkgColor = \"calculated\";\n this.gridColor = \"calculated\";\n this.doneTaskBkgColor = \"calculated\";\n this.doneTaskBorderColor = \"calculated\";\n this.critBorderColor = \"calculated\";\n this.critBkgColor = \"calculated\";\n this.todayLineColor = \"calculated\";\n this.vertLineColor = \"calculated\";\n this.sectionBkgColor = rgba2(102, 102, 255, 0.49);\n this.altSectionBkgColor = \"white\";\n this.sectionBkgColor2 = \"#fff400\";\n this.taskBorderColor = \"#534fbc\";\n this.taskBkgColor = \"#8a90dd\";\n this.taskTextLightColor = \"white\";\n this.taskTextColor = \"calculated\";\n this.taskTextDarkColor = \"black\";\n this.taskTextOutsideColor = \"calculated\";\n this.taskTextClickableColor = \"#003163\";\n this.activeTaskBorderColor = \"#534fbc\";\n this.activeTaskBkgColor = \"#bfc7ff\";\n this.gridColor = \"lightgrey\";\n this.doneTaskBkgColor = \"lightgrey\";\n this.doneTaskBorderColor = \"grey\";\n this.critBorderColor = \"#ff8888\";\n this.critBkgColor = \"red\";\n this.todayLineColor = \"red\";\n this.vertLineColor = \"navy\";\n this.personBorder = this.primaryBorderColor;\n this.personBkg = this.mainBkg;\n this.archEdgeColor = \"calculated\";\n this.archEdgeArrowColor = \"calculated\";\n this.archEdgeWidth = \"3\";\n this.archGroupBorderColor = this.primaryBorderColor;\n this.archGroupBorderWidth = \"2px\";\n this.rowOdd = \"calculated\";\n this.rowEven = \"calculated\";\n this.labelColor = \"black\";\n this.errorBkgColor = \"#552222\";\n this.errorTextColor = \"#552222\";\n this.updateColors();\n }\n updateColors() {\n this.cScale0 = this.cScale0 || this.primaryColor;\n this.cScale1 = this.cScale1 || this.secondaryColor;\n this.cScale2 = this.cScale2 || this.tertiaryColor;\n this.cScale3 = this.cScale3 || adjust4(this.primaryColor, { h: 30 });\n this.cScale4 = this.cScale4 || adjust4(this.primaryColor, { h: 60 });\n this.cScale5 = this.cScale5 || adjust4(this.primaryColor, { h: 90 });\n this.cScale6 = this.cScale6 || adjust4(this.primaryColor, { h: 120 });\n this.cScale7 = this.cScale7 || adjust4(this.primaryColor, { h: 150 });\n this.cScale8 = this.cScale8 || adjust4(this.primaryColor, { h: 210 });\n this.cScale9 = this.cScale9 || adjust4(this.primaryColor, { h: 270 });\n this.cScale10 = this.cScale10 || adjust4(this.primaryColor, { h: 300 });\n this.cScale11 = this.cScale11 || adjust4(this.primaryColor, { h: 330 });\n this[\"cScalePeer1\"] = this[\"cScalePeer1\"] || darken3(this.secondaryColor, 45);\n this[\"cScalePeer2\"] = this[\"cScalePeer2\"] || darken3(this.tertiaryColor, 40);\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n this[\"cScale\" + i] = darken3(this[\"cScale\" + i], 10);\n this[\"cScalePeer\" + i] = this[\"cScalePeer\" + i] || darken3(this[\"cScale\" + i], 25);\n }\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n this[\"cScaleInv\" + i] = this[\"cScaleInv\" + i] || adjust4(this[\"cScale\" + i], { h: 180 });\n }\n for (let i = 0; i < 5; i++) {\n this[\"surface\" + i] = this[\"surface\" + i] || adjust4(this.mainBkg, { h: 30, l: -(5 + i * 5) });\n this[\"surfacePeer\" + i] = this[\"surfacePeer\" + i] || adjust4(this.mainBkg, { h: 30, l: -(7 + i * 5) });\n }\n this.scaleLabelColor = this.scaleLabelColor !== \"calculated\" && this.scaleLabelColor ? this.scaleLabelColor : this.labelTextColor;\n if (this.labelTextColor !== \"calculated\") {\n this.cScaleLabel0 = this.cScaleLabel0 || invert3(this.labelTextColor);\n this.cScaleLabel3 = this.cScaleLabel3 || invert3(this.labelTextColor);\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n this[\"cScaleLabel\" + i] = this[\"cScaleLabel\" + i] || this.labelTextColor;\n }\n }\n this.nodeBkg = this.mainBkg;\n this.nodeBorder = this.border1;\n this.clusterBkg = this.secondBkg;\n this.clusterBorder = this.border2;\n this.defaultLinkColor = this.lineColor;\n this.titleColor = this.textColor;\n this.edgeLabelBackground = this.labelBackground;\n this.actorBorder = lighten3(this.border1, 23);\n this.actorBkg = this.mainBkg;\n this.labelBoxBkgColor = this.actorBkg;\n this.signalColor = this.textColor;\n this.signalTextColor = this.textColor;\n this.labelBoxBorderColor = this.actorBorder;\n this.labelTextColor = this.actorTextColor;\n this.loopTextColor = this.actorTextColor;\n this.noteBorderColor = this.border2;\n this.noteTextColor = this.actorTextColor;\n this.actorLineColor = this.actorBorder;\n this.taskTextColor = this.taskTextLightColor;\n this.taskTextOutsideColor = this.taskTextDarkColor;\n this.archEdgeColor = this.lineColor;\n this.archEdgeArrowColor = this.lineColor;\n this.rowOdd = this.rowOdd || lighten3(this.primaryColor, 75) || \"#ffffff\";\n this.rowEven = this.rowEven || lighten3(this.primaryColor, 1);\n this.transitionColor = this.transitionColor || this.lineColor;\n this.transitionLabelColor = this.transitionLabelColor || this.textColor;\n this.stateLabelColor = this.stateLabelColor || this.stateBkg || this.primaryTextColor;\n this.stateBkg = this.stateBkg || this.mainBkg;\n this.labelBackgroundColor = this.labelBackgroundColor || this.stateBkg;\n this.compositeBackground = this.compositeBackground || this.background || this.tertiaryColor;\n this.altBackground = this.altBackground || \"#f0f0f0\";\n this.compositeTitleBackground = this.compositeTitleBackground || this.mainBkg;\n this.compositeBorder = this.compositeBorder || this.nodeBorder;\n this.innerEndBackground = this.nodeBorder;\n this.specialStateColor = this.lineColor;\n this.errorBkgColor = this.errorBkgColor || this.tertiaryColor;\n this.errorTextColor = this.errorTextColor || this.tertiaryTextColor;\n this.transitionColor = this.transitionColor || this.lineColor;\n this.classText = this.primaryTextColor;\n this.fillType0 = this.primaryColor;\n this.fillType1 = this.secondaryColor;\n this.fillType2 = adjust4(this.primaryColor, { h: 64 });\n this.fillType3 = adjust4(this.secondaryColor, { h: 64 });\n this.fillType4 = adjust4(this.primaryColor, { h: -64 });\n this.fillType5 = adjust4(this.secondaryColor, { h: -64 });\n this.fillType6 = adjust4(this.primaryColor, { h: 128 });\n this.fillType7 = adjust4(this.secondaryColor, { h: 128 });\n this.pie1 = this.pie1 || this.primaryColor;\n this.pie2 = this.pie2 || this.secondaryColor;\n this.pie3 = this.pie3 || adjust4(this.tertiaryColor, { l: -40 });\n this.pie4 = this.pie4 || adjust4(this.primaryColor, { l: -10 });\n this.pie5 = this.pie5 || adjust4(this.secondaryColor, { l: -30 });\n this.pie6 = this.pie6 || adjust4(this.tertiaryColor, { l: -20 });\n this.pie7 = this.pie7 || adjust4(this.primaryColor, { h: 60, l: -20 });\n this.pie8 = this.pie8 || adjust4(this.primaryColor, { h: -60, l: -40 });\n this.pie9 = this.pie9 || adjust4(this.primaryColor, { h: 120, l: -40 });\n this.pie10 = this.pie10 || adjust4(this.primaryColor, { h: 60, l: -40 });\n this.pie11 = this.pie11 || adjust4(this.primaryColor, { h: -90, l: -40 });\n this.pie12 = this.pie12 || adjust4(this.primaryColor, { h: 120, l: -30 });\n this.pieTitleTextSize = this.pieTitleTextSize || \"25px\";\n this.pieTitleTextColor = this.pieTitleTextColor || this.taskTextDarkColor;\n this.pieSectionTextSize = this.pieSectionTextSize || \"17px\";\n this.pieSectionTextColor = this.pieSectionTextColor || this.textColor;\n this.pieLegendTextSize = this.pieLegendTextSize || \"17px\";\n this.pieLegendTextColor = this.pieLegendTextColor || this.taskTextDarkColor;\n this.pieStrokeColor = this.pieStrokeColor || \"black\";\n this.pieStrokeWidth = this.pieStrokeWidth || \"2px\";\n this.pieOuterStrokeWidth = this.pieOuterStrokeWidth || \"2px\";\n this.pieOuterStrokeColor = this.pieOuterStrokeColor || \"black\";\n this.pieOpacity = this.pieOpacity || \"0.7\";\n this.quadrant1Fill = this.quadrant1Fill || this.primaryColor;\n this.quadrant2Fill = this.quadrant2Fill || adjust4(this.primaryColor, { r: 5, g: 5, b: 5 });\n this.quadrant3Fill = this.quadrant3Fill || adjust4(this.primaryColor, { r: 10, g: 10, b: 10 });\n this.quadrant4Fill = this.quadrant4Fill || adjust4(this.primaryColor, { r: 15, g: 15, b: 15 });\n this.quadrant1TextFill = this.quadrant1TextFill || this.primaryTextColor;\n this.quadrant2TextFill = this.quadrant2TextFill || adjust4(this.primaryTextColor, { r: -5, g: -5, b: -5 });\n this.quadrant3TextFill = this.quadrant3TextFill || adjust4(this.primaryTextColor, { r: -10, g: -10, b: -10 });\n this.quadrant4TextFill = this.quadrant4TextFill || adjust4(this.primaryTextColor, { r: -15, g: -15, b: -15 });\n this.quadrantPointFill = this.quadrantPointFill || isDark3(this.quadrant1Fill) ? lighten3(this.quadrant1Fill) : darken3(this.quadrant1Fill);\n this.quadrantPointTextFill = this.quadrantPointTextFill || this.primaryTextColor;\n this.quadrantXAxisTextFill = this.quadrantXAxisTextFill || this.primaryTextColor;\n this.quadrantYAxisTextFill = this.quadrantYAxisTextFill || this.primaryTextColor;\n this.quadrantInternalBorderStrokeFill = this.quadrantInternalBorderStrokeFill || this.primaryBorderColor;\n this.quadrantExternalBorderStrokeFill = this.quadrantExternalBorderStrokeFill || this.primaryBorderColor;\n this.quadrantTitleFill = this.quadrantTitleFill || this.primaryTextColor;\n this.radar = {\n axisColor: this.radar?.axisColor || this.lineColor,\n axisStrokeWidth: this.radar?.axisStrokeWidth || 2,\n axisLabelFontSize: this.radar?.axisLabelFontSize || 12,\n curveOpacity: this.radar?.curveOpacity || 0.5,\n curveStrokeWidth: this.radar?.curveStrokeWidth || 2,\n graticuleColor: this.radar?.graticuleColor || \"#DEDEDE\",\n graticuleStrokeWidth: this.radar?.graticuleStrokeWidth || 1,\n graticuleOpacity: this.radar?.graticuleOpacity || 0.3,\n legendBoxSize: this.radar?.legendBoxSize || 12,\n legendFontSize: this.radar?.legendFontSize || 12\n };\n this.xyChart = {\n backgroundColor: this.xyChart?.backgroundColor || this.background,\n titleColor: this.xyChart?.titleColor || this.primaryTextColor,\n xAxisTitleColor: this.xyChart?.xAxisTitleColor || this.primaryTextColor,\n xAxisLabelColor: this.xyChart?.xAxisLabelColor || this.primaryTextColor,\n xAxisTickColor: this.xyChart?.xAxisTickColor || this.primaryTextColor,\n xAxisLineColor: this.xyChart?.xAxisLineColor || this.primaryTextColor,\n yAxisTitleColor: this.xyChart?.yAxisTitleColor || this.primaryTextColor,\n yAxisLabelColor: this.xyChart?.yAxisLabelColor || this.primaryTextColor,\n yAxisTickColor: this.xyChart?.yAxisTickColor || this.primaryTextColor,\n yAxisLineColor: this.xyChart?.yAxisLineColor || this.primaryTextColor,\n plotColorPalette: this.xyChart?.plotColorPalette || \"#ECECFF,#8493A6,#FFC3A0,#DCDDE1,#B8E994,#D1A36F,#C3CDE6,#FFB6C1,#496078,#F8F3E3\"\n };\n this.requirementBackground = this.requirementBackground || this.primaryColor;\n this.requirementBorderColor = this.requirementBorderColor || this.primaryBorderColor;\n this.requirementBorderSize = this.requirementBorderSize || \"1\";\n this.requirementTextColor = this.requirementTextColor || this.primaryTextColor;\n this.relationColor = this.relationColor || this.lineColor;\n this.relationLabelBackground = this.relationLabelBackground || this.labelBackground;\n this.relationLabelColor = this.relationLabelColor || this.actorTextColor;\n this.git0 = this.git0 || this.primaryColor;\n this.git1 = this.git1 || this.secondaryColor;\n this.git2 = this.git2 || this.tertiaryColor;\n this.git3 = this.git3 || adjust4(this.primaryColor, { h: -30 });\n this.git4 = this.git4 || adjust4(this.primaryColor, { h: -60 });\n this.git5 = this.git5 || adjust4(this.primaryColor, { h: -90 });\n this.git6 = this.git6 || adjust4(this.primaryColor, { h: 60 });\n this.git7 = this.git7 || adjust4(this.primaryColor, { h: 120 });\n if (this.darkMode) {\n this.git0 = lighten3(this.git0, 25);\n this.git1 = lighten3(this.git1, 25);\n this.git2 = lighten3(this.git2, 25);\n this.git3 = lighten3(this.git3, 25);\n this.git4 = lighten3(this.git4, 25);\n this.git5 = lighten3(this.git5, 25);\n this.git6 = lighten3(this.git6, 25);\n this.git7 = lighten3(this.git7, 25);\n } else {\n this.git0 = darken3(this.git0, 25);\n this.git1 = darken3(this.git1, 25);\n this.git2 = darken3(this.git2, 25);\n this.git3 = darken3(this.git3, 25);\n this.git4 = darken3(this.git4, 25);\n this.git5 = darken3(this.git5, 25);\n this.git6 = darken3(this.git6, 25);\n this.git7 = darken3(this.git7, 25);\n }\n this.gitInv0 = this.gitInv0 || darken3(invert3(this.git0), 25);\n this.gitInv1 = this.gitInv1 || invert3(this.git1);\n this.gitInv2 = this.gitInv2 || invert3(this.git2);\n this.gitInv3 = this.gitInv3 || invert3(this.git3);\n this.gitInv4 = this.gitInv4 || invert3(this.git4);\n this.gitInv5 = this.gitInv5 || invert3(this.git5);\n this.gitInv6 = this.gitInv6 || invert3(this.git6);\n this.gitInv7 = this.gitInv7 || invert3(this.git7);\n this.gitBranchLabel0 = this.gitBranchLabel0 || invert3(this.labelTextColor);\n this.gitBranchLabel1 = this.gitBranchLabel1 || this.labelTextColor;\n this.gitBranchLabel2 = this.gitBranchLabel2 || this.labelTextColor;\n this.gitBranchLabel3 = this.gitBranchLabel3 || invert3(this.labelTextColor);\n this.gitBranchLabel4 = this.gitBranchLabel4 || this.labelTextColor;\n this.gitBranchLabel5 = this.gitBranchLabel5 || this.labelTextColor;\n this.gitBranchLabel6 = this.gitBranchLabel6 || this.labelTextColor;\n this.gitBranchLabel7 = this.gitBranchLabel7 || this.labelTextColor;\n this.tagLabelColor = this.tagLabelColor || this.primaryTextColor;\n this.tagLabelBackground = this.tagLabelBackground || this.primaryColor;\n this.tagLabelBorder = this.tagBorder || this.primaryBorderColor;\n this.tagLabelFontSize = this.tagLabelFontSize || \"10px\";\n this.commitLabelColor = this.commitLabelColor || this.secondaryTextColor;\n this.commitLabelBackground = this.commitLabelBackground || this.secondaryColor;\n this.commitLabelFontSize = this.commitLabelFontSize || \"10px\";\n this.attributeBackgroundColorOdd = this.attributeBackgroundColorOdd || oldAttributeBackgroundColorOdd;\n this.attributeBackgroundColorEven = this.attributeBackgroundColorEven || oldAttributeBackgroundColorEven;\n }\n calculate(overrides) {\n Object.keys(this).forEach((k) => {\n if (this[k] === \"calculated\") {\n this[k] = void 0;\n }\n });\n if (typeof overrides !== \"object\") {\n this.updateColors();\n return;\n }\n const keys = Object.keys(overrides);\n keys.forEach((k) => {\n this[k] = overrides[k];\n });\n this.updateColors();\n keys.forEach((k) => {\n this[k] = overrides[k];\n });\n }\n};\nvar getThemeVariables3 = /* @__PURE__ */ __name((userOverrides) => {\n const theme = new Theme3();\n theme.calculate(userOverrides);\n return theme;\n}, \"getThemeVariables\");\n\n// src/themes/theme-forest.js\nimport { adjust as adjust5, darken as darken4, invert as invert4, isDark as isDark4, lighten as lighten4 } from \"khroma\";\nvar Theme4 = class {\n static {\n __name(this, \"Theme\");\n }\n constructor() {\n this.background = \"#f4f4f4\";\n this.primaryColor = \"#cde498\";\n this.secondaryColor = \"#cdffb2\";\n this.background = \"white\";\n this.mainBkg = \"#cde498\";\n this.secondBkg = \"#cdffb2\";\n this.lineColor = \"green\";\n this.border1 = \"#13540c\";\n this.border2 = \"#6eaa49\";\n this.arrowheadColor = \"green\";\n this.fontFamily = '\"trebuchet ms\", verdana, arial, sans-serif';\n this.fontSize = \"16px\";\n this.tertiaryColor = lighten4(\"#cde498\", 10);\n this.primaryBorderColor = mkBorder(this.primaryColor, this.darkMode);\n this.secondaryBorderColor = mkBorder(this.secondaryColor, this.darkMode);\n this.tertiaryBorderColor = mkBorder(this.tertiaryColor, this.darkMode);\n this.primaryTextColor = invert4(this.primaryColor);\n this.secondaryTextColor = invert4(this.secondaryColor);\n this.tertiaryTextColor = invert4(this.primaryColor);\n this.lineColor = invert4(this.background);\n this.textColor = invert4(this.background);\n this.THEME_COLOR_LIMIT = 12;\n this.nodeBkg = \"calculated\";\n this.nodeBorder = \"calculated\";\n this.clusterBkg = \"calculated\";\n this.clusterBorder = \"calculated\";\n this.defaultLinkColor = \"calculated\";\n this.titleColor = \"#333\";\n this.edgeLabelBackground = \"#e8e8e8\";\n this.actorBorder = \"calculated\";\n this.actorBkg = \"calculated\";\n this.actorTextColor = \"black\";\n this.actorLineColor = \"calculated\";\n this.signalColor = \"#333\";\n this.signalTextColor = \"#333\";\n this.labelBoxBkgColor = \"calculated\";\n this.labelBoxBorderColor = \"#326932\";\n this.labelTextColor = \"calculated\";\n this.loopTextColor = \"calculated\";\n this.noteBorderColor = \"calculated\";\n this.noteBkgColor = \"#fff5ad\";\n this.noteTextColor = \"calculated\";\n this.activationBorderColor = \"#666\";\n this.activationBkgColor = \"#f4f4f4\";\n this.sequenceNumberColor = \"white\";\n this.sectionBkgColor = \"#6eaa49\";\n this.altSectionBkgColor = \"white\";\n this.sectionBkgColor2 = \"#6eaa49\";\n this.excludeBkgColor = \"#eeeeee\";\n this.taskBorderColor = \"calculated\";\n this.taskBkgColor = \"#487e3a\";\n this.taskTextLightColor = \"white\";\n this.taskTextColor = \"calculated\";\n this.taskTextDarkColor = \"black\";\n this.taskTextOutsideColor = \"calculated\";\n this.taskTextClickableColor = \"#003163\";\n this.activeTaskBorderColor = \"calculated\";\n this.activeTaskBkgColor = \"calculated\";\n this.gridColor = \"lightgrey\";\n this.doneTaskBkgColor = \"lightgrey\";\n this.doneTaskBorderColor = \"grey\";\n this.critBorderColor = \"#ff8888\";\n this.critBkgColor = \"red\";\n this.todayLineColor = \"red\";\n this.vertLineColor = \"#00BFFF\";\n this.personBorder = this.primaryBorderColor;\n this.personBkg = this.mainBkg;\n this.archEdgeColor = \"calculated\";\n this.archEdgeArrowColor = \"calculated\";\n this.archEdgeWidth = \"3\";\n this.archGroupBorderColor = this.primaryBorderColor;\n this.archGroupBorderWidth = \"2px\";\n this.labelColor = \"black\";\n this.errorBkgColor = \"#552222\";\n this.errorTextColor = \"#552222\";\n }\n updateColors() {\n this.actorBorder = darken4(this.mainBkg, 20);\n this.actorBkg = this.mainBkg;\n this.labelBoxBkgColor = this.actorBkg;\n this.labelTextColor = this.actorTextColor;\n this.loopTextColor = this.actorTextColor;\n this.noteBorderColor = this.border2;\n this.noteTextColor = this.actorTextColor;\n this.actorLineColor = this.actorBorder;\n this.cScale0 = this.cScale0 || this.primaryColor;\n this.cScale1 = this.cScale1 || this.secondaryColor;\n this.cScale2 = this.cScale2 || this.tertiaryColor;\n this.cScale3 = this.cScale3 || adjust5(this.primaryColor, { h: 30 });\n this.cScale4 = this.cScale4 || adjust5(this.primaryColor, { h: 60 });\n this.cScale5 = this.cScale5 || adjust5(this.primaryColor, { h: 90 });\n this.cScale6 = this.cScale6 || adjust5(this.primaryColor, { h: 120 });\n this.cScale7 = this.cScale7 || adjust5(this.primaryColor, { h: 150 });\n this.cScale8 = this.cScale8 || adjust5(this.primaryColor, { h: 210 });\n this.cScale9 = this.cScale9 || adjust5(this.primaryColor, { h: 270 });\n this.cScale10 = this.cScale10 || adjust5(this.primaryColor, { h: 300 });\n this.cScale11 = this.cScale11 || adjust5(this.primaryColor, { h: 330 });\n this[\"cScalePeer1\"] = this[\"cScalePeer1\"] || darken4(this.secondaryColor, 45);\n this[\"cScalePeer2\"] = this[\"cScalePeer2\"] || darken4(this.tertiaryColor, 40);\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n this[\"cScale\" + i] = darken4(this[\"cScale\" + i], 10);\n this[\"cScalePeer\" + i] = this[\"cScalePeer\" + i] || darken4(this[\"cScale\" + i], 25);\n }\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n this[\"cScaleInv\" + i] = this[\"cScaleInv\" + i] || adjust5(this[\"cScale\" + i], { h: 180 });\n }\n this.scaleLabelColor = this.scaleLabelColor !== \"calculated\" && this.scaleLabelColor ? this.scaleLabelColor : this.labelTextColor;\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n this[\"cScaleLabel\" + i] = this[\"cScaleLabel\" + i] || this.scaleLabelColor;\n }\n for (let i = 0; i < 5; i++) {\n this[\"surface\" + i] = this[\"surface\" + i] || adjust5(this.mainBkg, { h: 30, s: -30, l: -(5 + i * 5) });\n this[\"surfacePeer\" + i] = this[\"surfacePeer\" + i] || adjust5(this.mainBkg, { h: 30, s: -30, l: -(8 + i * 5) });\n }\n this.nodeBkg = this.mainBkg;\n this.nodeBorder = this.border1;\n this.clusterBkg = this.secondBkg;\n this.clusterBorder = this.border2;\n this.defaultLinkColor = this.lineColor;\n this.taskBorderColor = this.border1;\n this.taskTextColor = this.taskTextLightColor;\n this.taskTextOutsideColor = this.taskTextDarkColor;\n this.activeTaskBorderColor = this.taskBorderColor;\n this.activeTaskBkgColor = this.mainBkg;\n this.archEdgeColor = this.lineColor;\n this.archEdgeArrowColor = this.lineColor;\n this.rowOdd = this.rowOdd || lighten4(this.mainBkg, 75) || \"#ffffff\";\n this.rowEven = this.rowEven || lighten4(this.mainBkg, 20);\n this.transitionColor = this.transitionColor || this.lineColor;\n this.transitionLabelColor = this.transitionLabelColor || this.textColor;\n this.stateLabelColor = this.stateLabelColor || this.stateBkg || this.primaryTextColor;\n this.stateBkg = this.stateBkg || this.mainBkg;\n this.labelBackgroundColor = this.labelBackgroundColor || this.stateBkg;\n this.compositeBackground = this.compositeBackground || this.background || this.tertiaryColor;\n this.altBackground = this.altBackground || \"#f0f0f0\";\n this.compositeTitleBackground = this.compositeTitleBackground || this.mainBkg;\n this.compositeBorder = this.compositeBorder || this.nodeBorder;\n this.innerEndBackground = this.primaryBorderColor;\n this.specialStateColor = this.lineColor;\n this.errorBkgColor = this.errorBkgColor || this.tertiaryColor;\n this.errorTextColor = this.errorTextColor || this.tertiaryTextColor;\n this.transitionColor = this.transitionColor || this.lineColor;\n this.classText = this.primaryTextColor;\n this.fillType0 = this.primaryColor;\n this.fillType1 = this.secondaryColor;\n this.fillType2 = adjust5(this.primaryColor, { h: 64 });\n this.fillType3 = adjust5(this.secondaryColor, { h: 64 });\n this.fillType4 = adjust5(this.primaryColor, { h: -64 });\n this.fillType5 = adjust5(this.secondaryColor, { h: -64 });\n this.fillType6 = adjust5(this.primaryColor, { h: 128 });\n this.fillType7 = adjust5(this.secondaryColor, { h: 128 });\n this.pie1 = this.pie1 || this.primaryColor;\n this.pie2 = this.pie2 || this.secondaryColor;\n this.pie3 = this.pie3 || this.tertiaryColor;\n this.pie4 = this.pie4 || adjust5(this.primaryColor, { l: -30 });\n this.pie5 = this.pie5 || adjust5(this.secondaryColor, { l: -30 });\n this.pie6 = this.pie6 || adjust5(this.tertiaryColor, { h: 40, l: -40 });\n this.pie7 = this.pie7 || adjust5(this.primaryColor, { h: 60, l: -10 });\n this.pie8 = this.pie8 || adjust5(this.primaryColor, { h: -60, l: -10 });\n this.pie9 = this.pie9 || adjust5(this.primaryColor, { h: 120, l: 0 });\n this.pie10 = this.pie10 || adjust5(this.primaryColor, { h: 60, l: -50 });\n this.pie11 = this.pie11 || adjust5(this.primaryColor, { h: -60, l: -50 });\n this.pie12 = this.pie12 || adjust5(this.primaryColor, { h: 120, l: -50 });\n this.pieTitleTextSize = this.pieTitleTextSize || \"25px\";\n this.pieTitleTextColor = this.pieTitleTextColor || this.taskTextDarkColor;\n this.pieSectionTextSize = this.pieSectionTextSize || \"17px\";\n this.pieSectionTextColor = this.pieSectionTextColor || this.textColor;\n this.pieLegendTextSize = this.pieLegendTextSize || \"17px\";\n this.pieLegendTextColor = this.pieLegendTextColor || this.taskTextDarkColor;\n this.pieStrokeColor = this.pieStrokeColor || \"black\";\n this.pieStrokeWidth = this.pieStrokeWidth || \"2px\";\n this.pieOuterStrokeWidth = this.pieOuterStrokeWidth || \"2px\";\n this.pieOuterStrokeColor = this.pieOuterStrokeColor || \"black\";\n this.pieOpacity = this.pieOpacity || \"0.7\";\n this.quadrant1Fill = this.quadrant1Fill || this.primaryColor;\n this.quadrant2Fill = this.quadrant2Fill || adjust5(this.primaryColor, { r: 5, g: 5, b: 5 });\n this.quadrant3Fill = this.quadrant3Fill || adjust5(this.primaryColor, { r: 10, g: 10, b: 10 });\n this.quadrant4Fill = this.quadrant4Fill || adjust5(this.primaryColor, { r: 15, g: 15, b: 15 });\n this.quadrant1TextFill = this.quadrant1TextFill || this.primaryTextColor;\n this.quadrant2TextFill = this.quadrant2TextFill || adjust5(this.primaryTextColor, { r: -5, g: -5, b: -5 });\n this.quadrant3TextFill = this.quadrant3TextFill || adjust5(this.primaryTextColor, { r: -10, g: -10, b: -10 });\n this.quadrant4TextFill = this.quadrant4TextFill || adjust5(this.primaryTextColor, { r: -15, g: -15, b: -15 });\n this.quadrantPointFill = this.quadrantPointFill || isDark4(this.quadrant1Fill) ? lighten4(this.quadrant1Fill) : darken4(this.quadrant1Fill);\n this.quadrantPointTextFill = this.quadrantPointTextFill || this.primaryTextColor;\n this.quadrantXAxisTextFill = this.quadrantXAxisTextFill || this.primaryTextColor;\n this.quadrantYAxisTextFill = this.quadrantYAxisTextFill || this.primaryTextColor;\n this.quadrantInternalBorderStrokeFill = this.quadrantInternalBorderStrokeFill || this.primaryBorderColor;\n this.quadrantExternalBorderStrokeFill = this.quadrantExternalBorderStrokeFill || this.primaryBorderColor;\n this.quadrantTitleFill = this.quadrantTitleFill || this.primaryTextColor;\n this.packet = {\n startByteColor: this.primaryTextColor,\n endByteColor: this.primaryTextColor,\n labelColor: this.primaryTextColor,\n titleColor: this.primaryTextColor,\n blockStrokeColor: this.primaryTextColor,\n blockFillColor: this.mainBkg\n };\n this.radar = {\n axisColor: this.radar?.axisColor || this.lineColor,\n axisStrokeWidth: this.radar?.axisStrokeWidth || 2,\n axisLabelFontSize: this.radar?.axisLabelFontSize || 12,\n curveOpacity: this.radar?.curveOpacity || 0.5,\n curveStrokeWidth: this.radar?.curveStrokeWidth || 2,\n graticuleColor: this.radar?.graticuleColor || \"#DEDEDE\",\n graticuleStrokeWidth: this.radar?.graticuleStrokeWidth || 1,\n graticuleOpacity: this.radar?.graticuleOpacity || 0.3,\n legendBoxSize: this.radar?.legendBoxSize || 12,\n legendFontSize: this.radar?.legendFontSize || 12\n };\n this.xyChart = {\n backgroundColor: this.xyChart?.backgroundColor || this.background,\n titleColor: this.xyChart?.titleColor || this.primaryTextColor,\n xAxisTitleColor: this.xyChart?.xAxisTitleColor || this.primaryTextColor,\n xAxisLabelColor: this.xyChart?.xAxisLabelColor || this.primaryTextColor,\n xAxisTickColor: this.xyChart?.xAxisTickColor || this.primaryTextColor,\n xAxisLineColor: this.xyChart?.xAxisLineColor || this.primaryTextColor,\n yAxisTitleColor: this.xyChart?.yAxisTitleColor || this.primaryTextColor,\n yAxisLabelColor: this.xyChart?.yAxisLabelColor || this.primaryTextColor,\n yAxisTickColor: this.xyChart?.yAxisTickColor || this.primaryTextColor,\n yAxisLineColor: this.xyChart?.yAxisLineColor || this.primaryTextColor,\n plotColorPalette: this.xyChart?.plotColorPalette || \"#CDE498,#FF6B6B,#A0D2DB,#D7BDE2,#F0F0F0,#FFC3A0,#7FD8BE,#FF9A8B,#FAF3E0,#FFF176\"\n };\n this.requirementBackground = this.requirementBackground || this.primaryColor;\n this.requirementBorderColor = this.requirementBorderColor || this.primaryBorderColor;\n this.requirementBorderSize = this.requirementBorderSize || \"1\";\n this.requirementTextColor = this.requirementTextColor || this.primaryTextColor;\n this.relationColor = this.relationColor || this.lineColor;\n this.relationLabelBackground = this.relationLabelBackground || this.edgeLabelBackground;\n this.relationLabelColor = this.relationLabelColor || this.actorTextColor;\n this.git0 = this.git0 || this.primaryColor;\n this.git1 = this.git1 || this.secondaryColor;\n this.git2 = this.git2 || this.tertiaryColor;\n this.git3 = this.git3 || adjust5(this.primaryColor, { h: -30 });\n this.git4 = this.git4 || adjust5(this.primaryColor, { h: -60 });\n this.git5 = this.git5 || adjust5(this.primaryColor, { h: -90 });\n this.git6 = this.git6 || adjust5(this.primaryColor, { h: 60 });\n this.git7 = this.git7 || adjust5(this.primaryColor, { h: 120 });\n if (this.darkMode) {\n this.git0 = lighten4(this.git0, 25);\n this.git1 = lighten4(this.git1, 25);\n this.git2 = lighten4(this.git2, 25);\n this.git3 = lighten4(this.git3, 25);\n this.git4 = lighten4(this.git4, 25);\n this.git5 = lighten4(this.git5, 25);\n this.git6 = lighten4(this.git6, 25);\n this.git7 = lighten4(this.git7, 25);\n } else {\n this.git0 = darken4(this.git0, 25);\n this.git1 = darken4(this.git1, 25);\n this.git2 = darken4(this.git2, 25);\n this.git3 = darken4(this.git3, 25);\n this.git4 = darken4(this.git4, 25);\n this.git5 = darken4(this.git5, 25);\n this.git6 = darken4(this.git6, 25);\n this.git7 = darken4(this.git7, 25);\n }\n this.gitInv0 = this.gitInv0 || invert4(this.git0);\n this.gitInv1 = this.gitInv1 || invert4(this.git1);\n this.gitInv2 = this.gitInv2 || invert4(this.git2);\n this.gitInv3 = this.gitInv3 || invert4(this.git3);\n this.gitInv4 = this.gitInv4 || invert4(this.git4);\n this.gitInv5 = this.gitInv5 || invert4(this.git5);\n this.gitInv6 = this.gitInv6 || invert4(this.git6);\n this.gitInv7 = this.gitInv7 || invert4(this.git7);\n this.gitBranchLabel0 = this.gitBranchLabel0 || invert4(this.labelTextColor);\n this.gitBranchLabel1 = this.gitBranchLabel1 || this.labelTextColor;\n this.gitBranchLabel2 = this.gitBranchLabel2 || this.labelTextColor;\n this.gitBranchLabel3 = this.gitBranchLabel3 || invert4(this.labelTextColor);\n this.gitBranchLabel4 = this.gitBranchLabel4 || this.labelTextColor;\n this.gitBranchLabel5 = this.gitBranchLabel5 || this.labelTextColor;\n this.gitBranchLabel6 = this.gitBranchLabel6 || this.labelTextColor;\n this.gitBranchLabel7 = this.gitBranchLabel7 || this.labelTextColor;\n this.tagLabelColor = this.tagLabelColor || this.primaryTextColor;\n this.tagLabelBackground = this.tagLabelBackground || this.primaryColor;\n this.tagLabelBorder = this.tagBorder || this.primaryBorderColor;\n this.tagLabelFontSize = this.tagLabelFontSize || \"10px\";\n this.commitLabelColor = this.commitLabelColor || this.secondaryTextColor;\n this.commitLabelBackground = this.commitLabelBackground || this.secondaryColor;\n this.commitLabelFontSize = this.commitLabelFontSize || \"10px\";\n this.attributeBackgroundColorOdd = this.attributeBackgroundColorOdd || oldAttributeBackgroundColorOdd;\n this.attributeBackgroundColorEven = this.attributeBackgroundColorEven || oldAttributeBackgroundColorEven;\n }\n calculate(overrides) {\n if (typeof overrides !== \"object\") {\n this.updateColors();\n return;\n }\n const keys = Object.keys(overrides);\n keys.forEach((k) => {\n this[k] = overrides[k];\n });\n this.updateColors();\n keys.forEach((k) => {\n this[k] = overrides[k];\n });\n }\n};\nvar getThemeVariables4 = /* @__PURE__ */ __name((userOverrides) => {\n const theme = new Theme4();\n theme.calculate(userOverrides);\n return theme;\n}, \"getThemeVariables\");\n\n// src/themes/theme-neutral.js\nimport { invert as invert5, darken as darken5, lighten as lighten5, adjust as adjust6, isDark as isDark5 } from \"khroma\";\nvar Theme5 = class {\n static {\n __name(this, \"Theme\");\n }\n constructor() {\n this.primaryColor = \"#eee\";\n this.contrast = \"#707070\";\n this.secondaryColor = lighten5(this.contrast, 55);\n this.background = \"#ffffff\";\n this.tertiaryColor = adjust6(this.primaryColor, { h: -160 });\n this.primaryBorderColor = mkBorder(this.primaryColor, this.darkMode);\n this.secondaryBorderColor = mkBorder(this.secondaryColor, this.darkMode);\n this.tertiaryBorderColor = mkBorder(this.tertiaryColor, this.darkMode);\n this.primaryTextColor = invert5(this.primaryColor);\n this.secondaryTextColor = invert5(this.secondaryColor);\n this.tertiaryTextColor = invert5(this.tertiaryColor);\n this.lineColor = invert5(this.background);\n this.textColor = invert5(this.background);\n this.mainBkg = \"#eee\";\n this.secondBkg = \"calculated\";\n this.lineColor = \"#666\";\n this.border1 = \"#999\";\n this.border2 = \"calculated\";\n this.note = \"#ffa\";\n this.text = \"#333\";\n this.critical = \"#d42\";\n this.done = \"#bbb\";\n this.arrowheadColor = \"#333333\";\n this.fontFamily = '\"trebuchet ms\", verdana, arial, sans-serif';\n this.fontSize = \"16px\";\n this.THEME_COLOR_LIMIT = 12;\n this.nodeBkg = \"calculated\";\n this.nodeBorder = \"calculated\";\n this.clusterBkg = \"calculated\";\n this.clusterBorder = \"calculated\";\n this.defaultLinkColor = \"calculated\";\n this.titleColor = \"calculated\";\n this.edgeLabelBackground = \"white\";\n this.actorBorder = \"calculated\";\n this.actorBkg = \"calculated\";\n this.actorTextColor = \"calculated\";\n this.actorLineColor = this.actorBorder;\n this.signalColor = \"calculated\";\n this.signalTextColor = \"calculated\";\n this.labelBoxBkgColor = \"calculated\";\n this.labelBoxBorderColor = \"calculated\";\n this.labelTextColor = \"calculated\";\n this.loopTextColor = \"calculated\";\n this.noteBorderColor = \"calculated\";\n this.noteBkgColor = \"calculated\";\n this.noteTextColor = \"calculated\";\n this.activationBorderColor = \"#666\";\n this.activationBkgColor = \"#f4f4f4\";\n this.sequenceNumberColor = \"white\";\n this.sectionBkgColor = \"calculated\";\n this.altSectionBkgColor = \"white\";\n this.sectionBkgColor2 = \"calculated\";\n this.excludeBkgColor = \"#eeeeee\";\n this.taskBorderColor = \"calculated\";\n this.taskBkgColor = \"calculated\";\n this.taskTextLightColor = \"white\";\n this.taskTextColor = \"calculated\";\n this.taskTextDarkColor = \"calculated\";\n this.taskTextOutsideColor = \"calculated\";\n this.taskTextClickableColor = \"#003163\";\n this.activeTaskBorderColor = \"calculated\";\n this.activeTaskBkgColor = \"calculated\";\n this.gridColor = \"calculated\";\n this.doneTaskBkgColor = \"calculated\";\n this.doneTaskBorderColor = \"calculated\";\n this.critBkgColor = \"calculated\";\n this.critBorderColor = \"calculated\";\n this.todayLineColor = \"calculated\";\n this.vertLineColor = \"calculated\";\n this.personBorder = this.primaryBorderColor;\n this.personBkg = this.mainBkg;\n this.archEdgeColor = \"calculated\";\n this.archEdgeArrowColor = \"calculated\";\n this.archEdgeWidth = \"3\";\n this.archGroupBorderColor = this.primaryBorderColor;\n this.archGroupBorderWidth = \"2px\";\n this.rowOdd = this.rowOdd || lighten5(this.mainBkg, 75) || \"#ffffff\";\n this.rowEven = this.rowEven || \"#f4f4f4\";\n this.labelColor = \"black\";\n this.errorBkgColor = \"#552222\";\n this.errorTextColor = \"#552222\";\n }\n updateColors() {\n this.secondBkg = lighten5(this.contrast, 55);\n this.border2 = this.contrast;\n this.actorBorder = lighten5(this.border1, 23);\n this.actorBkg = this.mainBkg;\n this.actorTextColor = this.text;\n this.actorLineColor = this.actorBorder;\n this.signalColor = this.text;\n this.signalTextColor = this.text;\n this.labelBoxBkgColor = this.actorBkg;\n this.labelBoxBorderColor = this.actorBorder;\n this.labelTextColor = this.text;\n this.loopTextColor = this.text;\n this.noteBorderColor = \"#999\";\n this.noteBkgColor = \"#666\";\n this.noteTextColor = \"#fff\";\n this.cScale0 = this.cScale0 || \"#555\";\n this.cScale1 = this.cScale1 || \"#F4F4F4\";\n this.cScale2 = this.cScale2 || \"#555\";\n this.cScale3 = this.cScale3 || \"#BBB\";\n this.cScale4 = this.cScale4 || \"#777\";\n this.cScale5 = this.cScale5 || \"#999\";\n this.cScale6 = this.cScale6 || \"#DDD\";\n this.cScale7 = this.cScale7 || \"#FFF\";\n this.cScale8 = this.cScale8 || \"#DDD\";\n this.cScale9 = this.cScale9 || \"#BBB\";\n this.cScale10 = this.cScale10 || \"#999\";\n this.cScale11 = this.cScale11 || \"#777\";\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n this[\"cScaleInv\" + i] = this[\"cScaleInv\" + i] || invert5(this[\"cScale\" + i]);\n }\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n if (this.darkMode) {\n this[\"cScalePeer\" + i] = this[\"cScalePeer\" + i] || lighten5(this[\"cScale\" + i], 10);\n } else {\n this[\"cScalePeer\" + i] = this[\"cScalePeer\" + i] || darken5(this[\"cScale\" + i], 10);\n }\n }\n this.scaleLabelColor = this.scaleLabelColor || (this.darkMode ? \"black\" : this.labelTextColor);\n this.cScaleLabel0 = this.cScaleLabel0 || this.cScale1;\n this.cScaleLabel2 = this.cScaleLabel2 || this.cScale1;\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n this[\"cScaleLabel\" + i] = this[\"cScaleLabel\" + i] || this.scaleLabelColor;\n }\n for (let i = 0; i < 5; i++) {\n this[\"surface\" + i] = this[\"surface\" + i] || adjust6(this.mainBkg, { l: -(5 + i * 5) });\n this[\"surfacePeer\" + i] = this[\"surfacePeer\" + i] || adjust6(this.mainBkg, { l: -(8 + i * 5) });\n }\n this.nodeBkg = this.mainBkg;\n this.nodeBorder = this.border1;\n this.clusterBkg = this.secondBkg;\n this.clusterBorder = this.border2;\n this.defaultLinkColor = this.lineColor;\n this.titleColor = this.text;\n this.sectionBkgColor = lighten5(this.contrast, 30);\n this.sectionBkgColor2 = lighten5(this.contrast, 30);\n this.taskBorderColor = darken5(this.contrast, 10);\n this.taskBkgColor = this.contrast;\n this.taskTextColor = this.taskTextLightColor;\n this.taskTextDarkColor = this.text;\n this.taskTextOutsideColor = this.taskTextDarkColor;\n this.activeTaskBorderColor = this.taskBorderColor;\n this.activeTaskBkgColor = this.mainBkg;\n this.gridColor = lighten5(this.border1, 30);\n this.doneTaskBkgColor = this.done;\n this.doneTaskBorderColor = this.lineColor;\n this.critBkgColor = this.critical;\n this.critBorderColor = darken5(this.critBkgColor, 10);\n this.todayLineColor = this.critBkgColor;\n this.vertLineColor = this.critBkgColor;\n this.archEdgeColor = this.lineColor;\n this.archEdgeArrowColor = this.lineColor;\n this.transitionColor = this.transitionColor || \"#000\";\n this.transitionLabelColor = this.transitionLabelColor || this.textColor;\n this.stateLabelColor = this.stateLabelColor || this.stateBkg || this.primaryTextColor;\n this.stateBkg = this.stateBkg || this.mainBkg;\n this.labelBackgroundColor = this.labelBackgroundColor || this.stateBkg;\n this.compositeBackground = this.compositeBackground || this.background || this.tertiaryColor;\n this.altBackground = this.altBackground || \"#f4f4f4\";\n this.compositeTitleBackground = this.compositeTitleBackground || this.mainBkg;\n this.stateBorder = this.stateBorder || \"#000\";\n this.innerEndBackground = this.primaryBorderColor;\n this.specialStateColor = \"#222\";\n this.errorBkgColor = this.errorBkgColor || this.tertiaryColor;\n this.errorTextColor = this.errorTextColor || this.tertiaryTextColor;\n this.classText = this.primaryTextColor;\n this.fillType0 = this.primaryColor;\n this.fillType1 = this.secondaryColor;\n this.fillType2 = adjust6(this.primaryColor, { h: 64 });\n this.fillType3 = adjust6(this.secondaryColor, { h: 64 });\n this.fillType4 = adjust6(this.primaryColor, { h: -64 });\n this.fillType5 = adjust6(this.secondaryColor, { h: -64 });\n this.fillType6 = adjust6(this.primaryColor, { h: 128 });\n this.fillType7 = adjust6(this.secondaryColor, { h: 128 });\n for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {\n this[\"pie\" + i] = this[\"cScale\" + i];\n }\n this.pie12 = this.pie0;\n this.pieTitleTextSize = this.pieTitleTextSize || \"25px\";\n this.pieTitleTextColor = this.pieTitleTextColor || this.taskTextDarkColor;\n this.pieSectionTextSize = this.pieSectionTextSize || \"17px\";\n this.pieSectionTextColor = this.pieSectionTextColor || this.textColor;\n this.pieLegendTextSize = this.pieLegendTextSize || \"17px\";\n this.pieLegendTextColor = this.pieLegendTextColor || this.taskTextDarkColor;\n this.pieStrokeColor = this.pieStrokeColor || \"black\";\n this.pieStrokeWidth = this.pieStrokeWidth || \"2px\";\n this.pieOuterStrokeWidth = this.pieOuterStrokeWidth || \"2px\";\n this.pieOuterStrokeColor = this.pieOuterStrokeColor || \"black\";\n this.pieOpacity = this.pieOpacity || \"0.7\";\n this.quadrant1Fill = this.quadrant1Fill || this.primaryColor;\n this.quadrant2Fill = this.quadrant2Fill || adjust6(this.primaryColor, { r: 5, g: 5, b: 5 });\n this.quadrant3Fill = this.quadrant3Fill || adjust6(this.primaryColor, { r: 10, g: 10, b: 10 });\n this.quadrant4Fill = this.quadrant4Fill || adjust6(this.primaryColor, { r: 15, g: 15, b: 15 });\n this.quadrant1TextFill = this.quadrant1TextFill || this.primaryTextColor;\n this.quadrant2TextFill = this.quadrant2TextFill || adjust6(this.primaryTextColor, { r: -5, g: -5, b: -5 });\n this.quadrant3TextFill = this.quadrant3TextFill || adjust6(this.primaryTextColor, { r: -10, g: -10, b: -10 });\n this.quadrant4TextFill = this.quadrant4TextFill || adjust6(this.primaryTextColor, { r: -15, g: -15, b: -15 });\n this.quadrantPointFill = this.quadrantPointFill || isDark5(this.quadrant1Fill) ? lighten5(this.quadrant1Fill) : darken5(this.quadrant1Fill);\n this.quadrantPointTextFill = this.quadrantPointTextFill || this.primaryTextColor;\n this.quadrantXAxisTextFill = this.quadrantXAxisTextFill || this.primaryTextColor;\n this.quadrantYAxisTextFill = this.quadrantYAxisTextFill || this.primaryTextColor;\n this.quadrantInternalBorderStrokeFill = this.quadrantInternalBorderStrokeFill || this.primaryBorderColor;\n this.quadrantExternalBorderStrokeFill = this.quadrantExternalBorderStrokeFill || this.primaryBorderColor;\n this.quadrantTitleFill = this.quadrantTitleFill || this.primaryTextColor;\n this.xyChart = {\n backgroundColor: this.xyChart?.backgroundColor || this.background,\n titleColor: this.xyChart?.titleColor || this.primaryTextColor,\n xAxisTitleColor: this.xyChart?.xAxisTitleColor || this.primaryTextColor,\n xAxisLabelColor: this.xyChart?.xAxisLabelColor || this.primaryTextColor,\n xAxisTickColor: this.xyChart?.xAxisTickColor || this.primaryTextColor,\n xAxisLineColor: this.xyChart?.xAxisLineColor || this.primaryTextColor,\n yAxisTitleColor: this.xyChart?.yAxisTitleColor || this.primaryTextColor,\n yAxisLabelColor: this.xyChart?.yAxisLabelColor || this.primaryTextColor,\n yAxisTickColor: this.xyChart?.yAxisTickColor || this.primaryTextColor,\n yAxisLineColor: this.xyChart?.yAxisLineColor || this.primaryTextColor,\n plotColorPalette: this.xyChart?.plotColorPalette || \"#EEE,#6BB8E4,#8ACB88,#C7ACD6,#E8DCC2,#FFB2A8,#FFF380,#7E8D91,#FFD8B1,#FAF3E0\"\n };\n this.radar = {\n axisColor: this.radar?.axisColor || this.lineColor,\n axisStrokeWidth: this.radar?.axisStrokeWidth || 2,\n axisLabelFontSize: this.radar?.axisLabelFontSize || 12,\n curveOpacity: this.radar?.curveOpacity || 0.5,\n curveStrokeWidth: this.radar?.curveStrokeWidth || 2,\n graticuleColor: this.radar?.graticuleColor || \"#DEDEDE\",\n graticuleStrokeWidth: this.radar?.graticuleStrokeWidth || 1,\n graticuleOpacity: this.radar?.graticuleOpacity || 0.3,\n legendBoxSize: this.radar?.legendBoxSize || 12,\n legendFontSize: this.radar?.legendFontSize || 12\n };\n this.requirementBackground = this.requirementBackground || this.primaryColor;\n this.requirementBorderColor = this.requirementBorderColor || this.primaryBorderColor;\n this.requirementBorderSize = this.requirementBorderSize || \"1\";\n this.requirementTextColor = this.requirementTextColor || this.primaryTextColor;\n this.relationColor = this.relationColor || this.lineColor;\n this.relationLabelBackground = this.relationLabelBackground || this.edgeLabelBackground;\n this.relationLabelColor = this.relationLabelColor || this.actorTextColor;\n this.git0 = darken5(this.pie1, 25) || this.primaryColor;\n this.git1 = this.pie2 || this.secondaryColor;\n this.git2 = this.pie3 || this.tertiaryColor;\n this.git3 = this.pie4 || adjust6(this.primaryColor, { h: -30 });\n this.git4 = this.pie5 || adjust6(this.primaryColor, { h: -60 });\n this.git5 = this.pie6 || adjust6(this.primaryColor, { h: -90 });\n this.git6 = this.pie7 || adjust6(this.primaryColor, { h: 60 });\n this.git7 = this.pie8 || adjust6(this.primaryColor, { h: 120 });\n this.gitInv0 = this.gitInv0 || invert5(this.git0);\n this.gitInv1 = this.gitInv1 || invert5(this.git1);\n this.gitInv2 = this.gitInv2 || invert5(this.git2);\n this.gitInv3 = this.gitInv3 || invert5(this.git3);\n this.gitInv4 = this.gitInv4 || invert5(this.git4);\n this.gitInv5 = this.gitInv5 || invert5(this.git5);\n this.gitInv6 = this.gitInv6 || invert5(this.git6);\n this.gitInv7 = this.gitInv7 || invert5(this.git7);\n this.branchLabelColor = this.branchLabelColor || this.labelTextColor;\n this.gitBranchLabel0 = this.branchLabelColor;\n this.gitBranchLabel1 = \"white\";\n this.gitBranchLabel2 = this.branchLabelColor;\n this.gitBranchLabel3 = \"white\";\n this.gitBranchLabel4 = this.branchLabelColor;\n this.gitBranchLabel5 = this.branchLabelColor;\n this.gitBranchLabel6 = this.branchLabelColor;\n this.gitBranchLabel7 = this.branchLabelColor;\n this.tagLabelColor = this.tagLabelColor || this.primaryTextColor;\n this.tagLabelBackground = this.tagLabelBackground || this.primaryColor;\n this.tagLabelBorder = this.tagBorder || this.primaryBorderColor;\n this.tagLabelFontSize = this.tagLabelFontSize || \"10px\";\n this.commitLabelColor = this.commitLabelColor || this.secondaryTextColor;\n this.commitLabelBackground = this.commitLabelBackground || this.secondaryColor;\n this.commitLabelFontSize = this.commitLabelFontSize || \"10px\";\n this.attributeBackgroundColorOdd = this.attributeBackgroundColorOdd || oldAttributeBackgroundColorOdd;\n this.attributeBackgroundColorEven = this.attributeBackgroundColorEven || oldAttributeBackgroundColorEven;\n }\n calculate(overrides) {\n if (typeof overrides !== \"object\") {\n this.updateColors();\n return;\n }\n const keys = Object.keys(overrides);\n keys.forEach((k) => {\n this[k] = overrides[k];\n });\n this.updateColors();\n keys.forEach((k) => {\n this[k] = overrides[k];\n });\n }\n};\nvar getThemeVariables5 = /* @__PURE__ */ __name((userOverrides) => {\n const theme = new Theme5();\n theme.calculate(userOverrides);\n return theme;\n}, \"getThemeVariables\");\n\n// src/themes/index.js\nvar themes_default = {\n base: {\n getThemeVariables\n },\n dark: {\n getThemeVariables: getThemeVariables2\n },\n default: {\n getThemeVariables: getThemeVariables3\n },\n forest: {\n getThemeVariables: getThemeVariables4\n },\n neutral: {\n getThemeVariables: getThemeVariables5\n }\n};\n\n// src/schemas/config.schema.yaml?only-defaults=true\nvar config_schema_default = {\n \"flowchart\": {\n \"useMaxWidth\": true,\n \"titleTopMargin\": 25,\n \"subGraphTitleMargin\": {\n \"top\": 0,\n \"bottom\": 0\n },\n \"diagramPadding\": 8,\n \"htmlLabels\": true,\n \"nodeSpacing\": 50,\n \"rankSpacing\": 50,\n \"curve\": \"basis\",\n \"padding\": 15,\n \"defaultRenderer\": \"dagre-wrapper\",\n \"wrappingWidth\": 200,\n \"inheritDir\": false\n },\n \"sequence\": {\n \"useMaxWidth\": true,\n \"hideUnusedParticipants\": false,\n \"activationWidth\": 10,\n \"diagramMarginX\": 50,\n \"diagramMarginY\": 10,\n \"actorMargin\": 50,\n \"width\": 150,\n \"height\": 65,\n \"boxMargin\": 10,\n \"boxTextMargin\": 5,\n \"noteMargin\": 10,\n \"messageMargin\": 35,\n \"messageAlign\": \"center\",\n \"mirrorActors\": true,\n \"forceMenus\": false,\n \"bottomMarginAdj\": 1,\n \"rightAngles\": false,\n \"showSequenceNumbers\": false,\n \"actorFontSize\": 14,\n \"actorFontFamily\": '\"Open Sans\", sans-serif',\n \"actorFontWeight\": 400,\n \"noteFontSize\": 14,\n \"noteFontFamily\": '\"trebuchet ms\", verdana, arial, sans-serif',\n \"noteFontWeight\": 400,\n \"noteAlign\": \"center\",\n \"messageFontSize\": 16,\n \"messageFontFamily\": '\"trebuchet ms\", verdana, arial, sans-serif',\n \"messageFontWeight\": 400,\n \"wrap\": false,\n \"wrapPadding\": 10,\n \"labelBoxWidth\": 50,\n \"labelBoxHeight\": 20\n },\n \"gantt\": {\n \"useMaxWidth\": true,\n \"titleTopMargin\": 25,\n \"barHeight\": 20,\n \"barGap\": 4,\n \"topPadding\": 50,\n \"rightPadding\": 75,\n \"leftPadding\": 75,\n \"gridLineStartPadding\": 35,\n \"fontSize\": 11,\n \"sectionFontSize\": 11,\n \"numberSectionStyles\": 4,\n \"axisFormat\": \"%Y-%m-%d\",\n \"topAxis\": false,\n \"displayMode\": \"\",\n \"weekday\": \"sunday\"\n },\n \"journey\": {\n \"useMaxWidth\": true,\n \"diagramMarginX\": 50,\n \"diagramMarginY\": 10,\n \"leftMargin\": 150,\n \"maxLabelWidth\": 360,\n \"width\": 150,\n \"height\": 50,\n \"boxMargin\": 10,\n \"boxTextMargin\": 5,\n \"noteMargin\": 10,\n \"messageMargin\": 35,\n \"messageAlign\": \"center\",\n \"bottomMarginAdj\": 1,\n \"rightAngles\": false,\n \"taskFontSize\": 14,\n \"taskFontFamily\": '\"Open Sans\", sans-serif',\n \"taskMargin\": 50,\n \"activationWidth\": 10,\n \"textPlacement\": \"fo\",\n \"actorColours\": [\n \"#8FBC8F\",\n \"#7CFC00\",\n \"#00FFFF\",\n \"#20B2AA\",\n \"#B0E0E6\",\n \"#FFFFE0\"\n ],\n \"sectionFills\": [\n \"#191970\",\n \"#8B008B\",\n \"#4B0082\",\n \"#2F4F4F\",\n \"#800000\",\n \"#8B4513\",\n \"#00008B\"\n ],\n \"sectionColours\": [\n \"#fff\"\n ],\n \"titleColor\": \"\",\n \"titleFontFamily\": '\"trebuchet ms\", verdana, arial, sans-serif',\n \"titleFontSize\": \"4ex\"\n },\n \"class\": {\n \"useMaxWidth\": true,\n \"titleTopMargin\": 25,\n \"arrowMarkerAbsolute\": false,\n \"dividerMargin\": 10,\n \"padding\": 5,\n \"textHeight\": 10,\n \"defaultRenderer\": \"dagre-wrapper\",\n \"htmlLabels\": false,\n \"hideEmptyMembersBox\": false\n },\n \"state\": {\n \"useMaxWidth\": true,\n \"titleTopMargin\": 25,\n \"dividerMargin\": 10,\n \"sizeUnit\": 5,\n \"padding\": 8,\n \"textHeight\": 10,\n \"titleShift\": -15,\n \"noteMargin\": 10,\n \"forkWidth\": 70,\n \"forkHeight\": 7,\n \"miniPadding\": 2,\n \"fontSizeFactor\": 5.02,\n \"fontSize\": 24,\n \"labelHeight\": 16,\n \"edgeLengthFactor\": \"20\",\n \"compositTitleSize\": 35,\n \"radius\": 5,\n \"defaultRenderer\": \"dagre-wrapper\"\n },\n \"er\": {\n \"useMaxWidth\": true,\n \"titleTopMargin\": 25,\n \"diagramPadding\": 20,\n \"layoutDirection\": \"TB\",\n \"minEntityWidth\": 100,\n \"minEntityHeight\": 75,\n \"entityPadding\": 15,\n \"nodeSpacing\": 140,\n \"rankSpacing\": 80,\n \"stroke\": \"gray\",\n \"fill\": \"honeydew\",\n \"fontSize\": 12\n },\n \"pie\": {\n \"useMaxWidth\": true,\n \"textPosition\": 0.75\n },\n \"quadrantChart\": {\n \"useMaxWidth\": true,\n \"chartWidth\": 500,\n \"chartHeight\": 500,\n \"titleFontSize\": 20,\n \"titlePadding\": 10,\n \"quadrantPadding\": 5,\n \"xAxisLabelPadding\": 5,\n \"yAxisLabelPadding\": 5,\n \"xAxisLabelFontSize\": 16,\n \"yAxisLabelFontSize\": 16,\n \"quadrantLabelFontSize\": 16,\n \"quadrantTextTopPadding\": 5,\n \"pointTextPadding\": 5,\n \"pointLabelFontSize\": 12,\n \"pointRadius\": 5,\n \"xAxisPosition\": \"top\",\n \"yAxisPosition\": \"left\",\n \"quadrantInternalBorderStrokeWidth\": 1,\n \"quadrantExternalBorderStrokeWidth\": 2\n },\n \"xyChart\": {\n \"useMaxWidth\": true,\n \"width\": 700,\n \"height\": 500,\n \"titleFontSize\": 20,\n \"titlePadding\": 10,\n \"showDataLabel\": false,\n \"showTitle\": true,\n \"xAxis\": {\n \"$ref\": \"#/$defs/XYChartAxisConfig\",\n \"showLabel\": true,\n \"labelFontSize\": 14,\n \"labelPadding\": 5,\n \"showTitle\": true,\n \"titleFontSize\": 16,\n \"titlePadding\": 5,\n \"showTick\": true,\n \"tickLength\": 5,\n \"tickWidth\": 2,\n \"showAxisLine\": true,\n \"axisLineWidth\": 2\n },\n \"yAxis\": {\n \"$ref\": \"#/$defs/XYChartAxisConfig\",\n \"showLabel\": true,\n \"labelFontSize\": 14,\n \"labelPadding\": 5,\n \"showTitle\": true,\n \"titleFontSize\": 16,\n \"titlePadding\": 5,\n \"showTick\": true,\n \"tickLength\": 5,\n \"tickWidth\": 2,\n \"showAxisLine\": true,\n \"axisLineWidth\": 2\n },\n \"chartOrientation\": \"vertical\",\n \"plotReservedSpacePercent\": 50\n },\n \"requirement\": {\n \"useMaxWidth\": true,\n \"rect_fill\": \"#f9f9f9\",\n \"text_color\": \"#333\",\n \"rect_border_size\": \"0.5px\",\n \"rect_border_color\": \"#bbb\",\n \"rect_min_width\": 200,\n \"rect_min_height\": 200,\n \"fontSize\": 14,\n \"rect_padding\": 10,\n \"line_height\": 20\n },\n \"mindmap\": {\n \"useMaxWidth\": true,\n \"padding\": 10,\n \"maxNodeWidth\": 200,\n \"layoutAlgorithm\": \"cose-bilkent\"\n },\n \"kanban\": {\n \"useMaxWidth\": true,\n \"padding\": 8,\n \"sectionWidth\": 200,\n \"ticketBaseUrl\": \"\"\n },\n \"timeline\": {\n \"useMaxWidth\": true,\n \"diagramMarginX\": 50,\n \"diagramMarginY\": 10,\n \"leftMargin\": 150,\n \"width\": 150,\n \"height\": 50,\n \"boxMargin\": 10,\n \"boxTextMargin\": 5,\n \"noteMargin\": 10,\n \"messageMargin\": 35,\n \"messageAlign\": \"center\",\n \"bottomMarginAdj\": 1,\n \"rightAngles\": false,\n \"taskFontSize\": 14,\n \"taskFontFamily\": '\"Open Sans\", sans-serif',\n \"taskMargin\": 50,\n \"activationWidth\": 10,\n \"textPlacement\": \"fo\",\n \"actorColours\": [\n \"#8FBC8F\",\n \"#7CFC00\",\n \"#00FFFF\",\n \"#20B2AA\",\n \"#B0E0E6\",\n \"#FFFFE0\"\n ],\n \"sectionFills\": [\n \"#191970\",\n \"#8B008B\",\n \"#4B0082\",\n \"#2F4F4F\",\n \"#800000\",\n \"#8B4513\",\n \"#00008B\"\n ],\n \"sectionColours\": [\n \"#fff\"\n ],\n \"disableMulticolor\": false\n },\n \"gitGraph\": {\n \"useMaxWidth\": true,\n \"titleTopMargin\": 25,\n \"diagramPadding\": 8,\n \"nodeLabel\": {\n \"width\": 75,\n \"height\": 100,\n \"x\": -25,\n \"y\": 0\n },\n \"mainBranchName\": \"main\",\n \"mainBranchOrder\": 0,\n \"showCommitLabel\": true,\n \"showBranches\": true,\n \"rotateCommitLabel\": true,\n \"parallelCommits\": false,\n \"arrowMarkerAbsolute\": false\n },\n \"c4\": {\n \"useMaxWidth\": true,\n \"diagramMarginX\": 50,\n \"diagramMarginY\": 10,\n \"c4ShapeMargin\": 50,\n \"c4ShapePadding\": 20,\n \"width\": 216,\n \"height\": 60,\n \"boxMargin\": 10,\n \"c4ShapeInRow\": 4,\n \"nextLinePaddingX\": 0,\n \"c4BoundaryInRow\": 2,\n \"personFontSize\": 14,\n \"personFontFamily\": '\"Open Sans\", sans-serif',\n \"personFontWeight\": \"normal\",\n \"external_personFontSize\": 14,\n \"external_personFontFamily\": '\"Open Sans\", sans-serif',\n \"external_personFontWeight\": \"normal\",\n \"systemFontSize\": 14,\n \"systemFontFamily\": '\"Open Sans\", sans-serif',\n \"systemFontWeight\": \"normal\",\n \"external_systemFontSize\": 14,\n \"external_systemFontFamily\": '\"Open Sans\", sans-serif',\n \"external_systemFontWeight\": \"normal\",\n \"system_dbFontSize\": 14,\n \"system_dbFontFamily\": '\"Open Sans\", sans-serif',\n \"system_dbFontWeight\": \"normal\",\n \"external_system_dbFontSize\": 14,\n \"external_system_dbFontFamily\": '\"Open Sans\", sans-serif',\n \"external_system_dbFontWeight\": \"normal\",\n \"system_queueFontSize\": 14,\n \"system_queueFontFamily\": '\"Open Sans\", sans-serif',\n \"system_queueFontWeight\": \"normal\",\n \"external_system_queueFontSize\": 14,\n \"external_system_queueFontFamily\": '\"Open Sans\", sans-serif',\n \"external_system_queueFontWeight\": \"normal\",\n \"boundaryFontSize\": 14,\n \"boundaryFontFamily\": '\"Open Sans\", sans-serif',\n \"boundaryFontWeight\": \"normal\",\n \"messageFontSize\": 12,\n \"messageFontFamily\": '\"Open Sans\", sans-serif',\n \"messageFontWeight\": \"normal\",\n \"containerFontSize\": 14,\n \"containerFontFamily\": '\"Open Sans\", sans-serif',\n \"containerFontWeight\": \"normal\",\n \"external_containerFontSize\": 14,\n \"external_containerFontFamily\": '\"Open Sans\", sans-serif',\n \"external_containerFontWeight\": \"normal\",\n \"container_dbFontSize\": 14,\n \"container_dbFontFamily\": '\"Open Sans\", sans-serif',\n \"container_dbFontWeight\": \"normal\",\n \"external_container_dbFontSize\": 14,\n \"external_container_dbFontFamily\": '\"Open Sans\", sans-serif',\n \"external_container_dbFontWeight\": \"normal\",\n \"container_queueFontSize\": 14,\n \"container_queueFontFamily\": '\"Open Sans\", sans-serif',\n \"container_queueFontWeight\": \"normal\",\n \"external_container_queueFontSize\": 14,\n \"external_container_queueFontFamily\": '\"Open Sans\", sans-serif',\n \"external_container_queueFontWeight\": \"normal\",\n \"componentFontSize\": 14,\n \"componentFontFamily\": '\"Open Sans\", sans-serif',\n \"componentFontWeight\": \"normal\",\n \"external_componentFontSize\": 14,\n \"external_componentFontFamily\": '\"Open Sans\", sans-serif',\n \"external_componentFontWeight\": \"normal\",\n \"component_dbFontSize\": 14,\n \"component_dbFontFamily\": '\"Open Sans\", sans-serif',\n \"component_dbFontWeight\": \"normal\",\n \"external_component_dbFontSize\": 14,\n \"external_component_dbFontFamily\": '\"Open Sans\", sans-serif',\n \"external_component_dbFontWeight\": \"normal\",\n \"component_queueFontSize\": 14,\n \"component_queueFontFamily\": '\"Open Sans\", sans-serif',\n \"component_queueFontWeight\": \"normal\",\n \"external_component_queueFontSize\": 14,\n \"external_component_queueFontFamily\": '\"Open Sans\", sans-serif',\n \"external_component_queueFontWeight\": \"normal\",\n \"wrap\": true,\n \"wrapPadding\": 10,\n \"person_bg_color\": \"#08427B\",\n \"person_border_color\": \"#073B6F\",\n \"external_person_bg_color\": \"#686868\",\n \"external_person_border_color\": \"#8A8A8A\",\n \"system_bg_color\": \"#1168BD\",\n \"system_border_color\": \"#3C7FC0\",\n \"system_db_bg_color\": \"#1168BD\",\n \"system_db_border_color\": \"#3C7FC0\",\n \"system_queue_bg_color\": \"#1168BD\",\n \"system_queue_border_color\": \"#3C7FC0\",\n \"external_system_bg_color\": \"#999999\",\n \"external_system_border_color\": \"#8A8A8A\",\n \"external_system_db_bg_color\": \"#999999\",\n \"external_system_db_border_color\": \"#8A8A8A\",\n \"external_system_queue_bg_color\": \"#999999\",\n \"external_system_queue_border_color\": \"#8A8A8A\",\n \"container_bg_color\": \"#438DD5\",\n \"container_border_color\": \"#3C7FC0\",\n \"container_db_bg_color\": \"#438DD5\",\n \"container_db_border_color\": \"#3C7FC0\",\n \"container_queue_bg_color\": \"#438DD5\",\n \"container_queue_border_color\": \"#3C7FC0\",\n \"external_container_bg_color\": \"#B3B3B3\",\n \"external_container_border_color\": \"#A6A6A6\",\n \"external_container_db_bg_color\": \"#B3B3B3\",\n \"external_container_db_border_color\": \"#A6A6A6\",\n \"external_container_queue_bg_color\": \"#B3B3B3\",\n \"external_container_queue_border_color\": \"#A6A6A6\",\n \"component_bg_color\": \"#85BBF0\",\n \"component_border_color\": \"#78A8D8\",\n \"component_db_bg_color\": \"#85BBF0\",\n \"component_db_border_color\": \"#78A8D8\",\n \"component_queue_bg_color\": \"#85BBF0\",\n \"component_queue_border_color\": \"#78A8D8\",\n \"external_component_bg_color\": \"#CCCCCC\",\n \"external_component_border_color\": \"#BFBFBF\",\n \"external_component_db_bg_color\": \"#CCCCCC\",\n \"external_component_db_border_color\": \"#BFBFBF\",\n \"external_component_queue_bg_color\": \"#CCCCCC\",\n \"external_component_queue_border_color\": \"#BFBFBF\"\n },\n \"sankey\": {\n \"useMaxWidth\": true,\n \"width\": 600,\n \"height\": 400,\n \"linkColor\": \"gradient\",\n \"nodeAlignment\": \"justify\",\n \"showValues\": true,\n \"prefix\": \"\",\n \"suffix\": \"\"\n },\n \"block\": {\n \"useMaxWidth\": true,\n \"padding\": 8\n },\n \"packet\": {\n \"useMaxWidth\": true,\n \"rowHeight\": 32,\n \"bitWidth\": 32,\n \"bitsPerRow\": 32,\n \"showBits\": true,\n \"paddingX\": 5,\n \"paddingY\": 5\n },\n \"architecture\": {\n \"useMaxWidth\": true,\n \"padding\": 40,\n \"iconSize\": 80,\n \"fontSize\": 16\n },\n \"radar\": {\n \"useMaxWidth\": true,\n \"width\": 600,\n \"height\": 600,\n \"marginTop\": 50,\n \"marginRight\": 50,\n \"marginBottom\": 50,\n \"marginLeft\": 50,\n \"axisScaleFactor\": 1,\n \"axisLabelFactor\": 1.05,\n \"curveTension\": 0.17\n },\n \"theme\": \"default\",\n \"look\": \"classic\",\n \"handDrawnSeed\": 0,\n \"layout\": \"dagre\",\n \"maxTextSize\": 5e4,\n \"maxEdges\": 500,\n \"darkMode\": false,\n \"fontFamily\": '\"trebuchet ms\", verdana, arial, sans-serif;',\n \"logLevel\": 5,\n \"securityLevel\": \"strict\",\n \"startOnLoad\": true,\n \"arrowMarkerAbsolute\": false,\n \"secure\": [\n \"secure\",\n \"securityLevel\",\n \"startOnLoad\",\n \"maxTextSize\",\n \"suppressErrorRendering\",\n \"maxEdges\"\n ],\n \"legacyMathML\": false,\n \"forceLegacyMathML\": false,\n \"deterministicIds\": false,\n \"fontSize\": 16,\n \"markdownAutoWrap\": true,\n \"suppressErrorRendering\": false\n};\n\n// src/defaultConfig.ts\nvar config = {\n ...config_schema_default,\n // Set, even though they're `undefined` so that `configKeys` finds these keys\n // TODO: Should we replace these with `null` so that they can go in the JSON Schema?\n deterministicIDSeed: void 0,\n elk: {\n // mergeEdges is needed here to be considered\n mergeEdges: false,\n nodePlacementStrategy: \"BRANDES_KOEPF\",\n forceNodeModelOrder: false,\n considerModelOrder: \"NODES_AND_EDGES\"\n },\n themeCSS: void 0,\n // add non-JSON default config values\n themeVariables: themes_default.default.getThemeVariables(),\n sequence: {\n ...config_schema_default.sequence,\n messageFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.messageFontFamily,\n fontSize: this.messageFontSize,\n fontWeight: this.messageFontWeight\n };\n }, \"messageFont\"),\n noteFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.noteFontFamily,\n fontSize: this.noteFontSize,\n fontWeight: this.noteFontWeight\n };\n }, \"noteFont\"),\n actorFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.actorFontFamily,\n fontSize: this.actorFontSize,\n fontWeight: this.actorFontWeight\n };\n }, \"actorFont\")\n },\n class: {\n hideEmptyMembersBox: false\n },\n gantt: {\n ...config_schema_default.gantt,\n tickInterval: void 0,\n useWidth: void 0\n // can probably be removed since `configKeys` already includes this\n },\n c4: {\n ...config_schema_default.c4,\n useWidth: void 0,\n personFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.personFontFamily,\n fontSize: this.personFontSize,\n fontWeight: this.personFontWeight\n };\n }, \"personFont\"),\n flowchart: {\n ...config_schema_default.flowchart,\n inheritDir: false\n // default to legacy behavior\n },\n external_personFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.external_personFontFamily,\n fontSize: this.external_personFontSize,\n fontWeight: this.external_personFontWeight\n };\n }, \"external_personFont\"),\n systemFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.systemFontFamily,\n fontSize: this.systemFontSize,\n fontWeight: this.systemFontWeight\n };\n }, \"systemFont\"),\n external_systemFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.external_systemFontFamily,\n fontSize: this.external_systemFontSize,\n fontWeight: this.external_systemFontWeight\n };\n }, \"external_systemFont\"),\n system_dbFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.system_dbFontFamily,\n fontSize: this.system_dbFontSize,\n fontWeight: this.system_dbFontWeight\n };\n }, \"system_dbFont\"),\n external_system_dbFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.external_system_dbFontFamily,\n fontSize: this.external_system_dbFontSize,\n fontWeight: this.external_system_dbFontWeight\n };\n }, \"external_system_dbFont\"),\n system_queueFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.system_queueFontFamily,\n fontSize: this.system_queueFontSize,\n fontWeight: this.system_queueFontWeight\n };\n }, \"system_queueFont\"),\n external_system_queueFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.external_system_queueFontFamily,\n fontSize: this.external_system_queueFontSize,\n fontWeight: this.external_system_queueFontWeight\n };\n }, \"external_system_queueFont\"),\n containerFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.containerFontFamily,\n fontSize: this.containerFontSize,\n fontWeight: this.containerFontWeight\n };\n }, \"containerFont\"),\n external_containerFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.external_containerFontFamily,\n fontSize: this.external_containerFontSize,\n fontWeight: this.external_containerFontWeight\n };\n }, \"external_containerFont\"),\n container_dbFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.container_dbFontFamily,\n fontSize: this.container_dbFontSize,\n fontWeight: this.container_dbFontWeight\n };\n }, \"container_dbFont\"),\n external_container_dbFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.external_container_dbFontFamily,\n fontSize: this.external_container_dbFontSize,\n fontWeight: this.external_container_dbFontWeight\n };\n }, \"external_container_dbFont\"),\n container_queueFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.container_queueFontFamily,\n fontSize: this.container_queueFontSize,\n fontWeight: this.container_queueFontWeight\n };\n }, \"container_queueFont\"),\n external_container_queueFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.external_container_queueFontFamily,\n fontSize: this.external_container_queueFontSize,\n fontWeight: this.external_container_queueFontWeight\n };\n }, \"external_container_queueFont\"),\n componentFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.componentFontFamily,\n fontSize: this.componentFontSize,\n fontWeight: this.componentFontWeight\n };\n }, \"componentFont\"),\n external_componentFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.external_componentFontFamily,\n fontSize: this.external_componentFontSize,\n fontWeight: this.external_componentFontWeight\n };\n }, \"external_componentFont\"),\n component_dbFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.component_dbFontFamily,\n fontSize: this.component_dbFontSize,\n fontWeight: this.component_dbFontWeight\n };\n }, \"component_dbFont\"),\n external_component_dbFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.external_component_dbFontFamily,\n fontSize: this.external_component_dbFontSize,\n fontWeight: this.external_component_dbFontWeight\n };\n }, \"external_component_dbFont\"),\n component_queueFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.component_queueFontFamily,\n fontSize: this.component_queueFontSize,\n fontWeight: this.component_queueFontWeight\n };\n }, \"component_queueFont\"),\n external_component_queueFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.external_component_queueFontFamily,\n fontSize: this.external_component_queueFontSize,\n fontWeight: this.external_component_queueFontWeight\n };\n }, \"external_component_queueFont\"),\n boundaryFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.boundaryFontFamily,\n fontSize: this.boundaryFontSize,\n fontWeight: this.boundaryFontWeight\n };\n }, \"boundaryFont\"),\n messageFont: /* @__PURE__ */ __name(function() {\n return {\n fontFamily: this.messageFontFamily,\n fontSize: this.messageFontSize,\n fontWeight: this.messageFontWeight\n };\n }, \"messageFont\")\n },\n pie: {\n ...config_schema_default.pie,\n useWidth: 984\n },\n xyChart: {\n ...config_schema_default.xyChart,\n useWidth: void 0\n },\n requirement: {\n ...config_schema_default.requirement,\n useWidth: void 0\n },\n packet: {\n ...config_schema_default.packet\n },\n radar: {\n ...config_schema_default.radar\n },\n treemap: {\n useMaxWidth: true,\n padding: 10,\n diagramPadding: 8,\n showValues: true,\n nodeWidth: 100,\n nodeHeight: 40,\n borderWidth: 1,\n valueFontSize: 12,\n labelFontSize: 14,\n valueFormat: \",\"\n }\n};\nvar keyify = /* @__PURE__ */ __name((obj, prefix = \"\") => Object.keys(obj).reduce((res, el) => {\n if (Array.isArray(obj[el])) {\n return res;\n } else if (typeof obj[el] === \"object\" && obj[el] !== null) {\n return [...res, prefix + el, ...keyify(obj[el], \"\")];\n }\n return [...res, prefix + el];\n}, []), \"keyify\");\nvar configKeys = new Set(keyify(config, \"\"));\nvar defaultConfig_default = config;\n\n// src/utils/sanitizeDirective.ts\nvar sanitizeDirective = /* @__PURE__ */ __name((args) => {\n log.debug(\"sanitizeDirective called with\", args);\n if (typeof args !== \"object\" || args == null) {\n return;\n }\n if (Array.isArray(args)) {\n args.forEach((arg) => sanitizeDirective(arg));\n return;\n }\n for (const key of Object.keys(args)) {\n log.debug(\"Checking key\", key);\n if (key.startsWith(\"__\") || key.includes(\"proto\") || key.includes(\"constr\") || !configKeys.has(key) || args[key] == null) {\n log.debug(\"sanitize deleting key: \", key);\n delete args[key];\n continue;\n }\n if (typeof args[key] === \"object\") {\n log.debug(\"sanitizing object\", key);\n sanitizeDirective(args[key]);\n continue;\n }\n const cssMatchers = [\"themeCSS\", \"fontFamily\", \"altFontFamily\"];\n for (const cssKey of cssMatchers) {\n if (key.includes(cssKey)) {\n log.debug(\"sanitizing css option\", key);\n args[key] = sanitizeCss(args[key]);\n }\n }\n }\n if (args.themeVariables) {\n for (const k of Object.keys(args.themeVariables)) {\n const val = args.themeVariables[k];\n if (val?.match && !val.match(/^[\\d \"#%(),.;A-Za-z]+$/)) {\n args.themeVariables[k] = \"\";\n }\n }\n }\n log.debug(\"After sanitization\", args);\n}, \"sanitizeDirective\");\nvar sanitizeCss = /* @__PURE__ */ __name((str) => {\n let startCnt = 0;\n let endCnt = 0;\n for (const element of str) {\n if (startCnt < endCnt) {\n return \"{ /* ERROR: Unbalanced CSS */ }\";\n }\n if (element === \"{\") {\n startCnt++;\n } else if (element === \"}\") {\n endCnt++;\n }\n }\n if (startCnt !== endCnt) {\n return \"{ /* ERROR: Unbalanced CSS */ }\";\n }\n return str;\n}, \"sanitizeCss\");\n\n// src/config.ts\nvar defaultConfig = Object.freeze(defaultConfig_default);\nvar siteConfig = assignWithDepth_default({}, defaultConfig);\nvar configFromInitialize;\nvar directives = [];\nvar currentConfig = assignWithDepth_default({}, defaultConfig);\nvar updateCurrentConfig = /* @__PURE__ */ __name((siteCfg, _directives) => {\n let cfg = assignWithDepth_default({}, siteCfg);\n let sumOfDirectives = {};\n for (const d of _directives) {\n sanitize(d);\n sumOfDirectives = assignWithDepth_default(sumOfDirectives, d);\n }\n cfg = assignWithDepth_default(cfg, sumOfDirectives);\n if (sumOfDirectives.theme && sumOfDirectives.theme in themes_default) {\n const tmpConfigFromInitialize = assignWithDepth_default({}, configFromInitialize);\n const themeVariables = assignWithDepth_default(\n tmpConfigFromInitialize.themeVariables || {},\n sumOfDirectives.themeVariables\n );\n if (cfg.theme && cfg.theme in themes_default) {\n cfg.themeVariables = themes_default[cfg.theme].getThemeVariables(themeVariables);\n }\n }\n currentConfig = cfg;\n checkConfig(currentConfig);\n return currentConfig;\n}, \"updateCurrentConfig\");\nvar setSiteConfig = /* @__PURE__ */ __name((conf) => {\n siteConfig = assignWithDepth_default({}, defaultConfig);\n siteConfig = assignWithDepth_default(siteConfig, conf);\n if (conf.theme && themes_default[conf.theme]) {\n siteConfig.themeVariables = themes_default[conf.theme].getThemeVariables(conf.themeVariables);\n }\n updateCurrentConfig(siteConfig, directives);\n return siteConfig;\n}, \"setSiteConfig\");\nvar saveConfigFromInitialize = /* @__PURE__ */ __name((conf) => {\n configFromInitialize = assignWithDepth_default({}, conf);\n}, \"saveConfigFromInitialize\");\nvar updateSiteConfig = /* @__PURE__ */ __name((conf) => {\n siteConfig = assignWithDepth_default(siteConfig, conf);\n updateCurrentConfig(siteConfig, directives);\n return siteConfig;\n}, \"updateSiteConfig\");\nvar getSiteConfig = /* @__PURE__ */ __name(() => {\n return assignWithDepth_default({}, siteConfig);\n}, \"getSiteConfig\");\nvar setConfig = /* @__PURE__ */ __name((conf) => {\n checkConfig(conf);\n assignWithDepth_default(currentConfig, conf);\n return getConfig();\n}, \"setConfig\");\nvar getConfig = /* @__PURE__ */ __name(() => {\n return assignWithDepth_default({}, currentConfig);\n}, \"getConfig\");\nvar sanitize = /* @__PURE__ */ __name((options) => {\n if (!options) {\n return;\n }\n [\"secure\", ...siteConfig.secure ?? []].forEach((key) => {\n if (Object.hasOwn(options, key)) {\n log.debug(`Denied attempt to modify a secure key ${key}`, options[key]);\n delete options[key];\n }\n });\n Object.keys(options).forEach((key) => {\n if (key.startsWith(\"__\")) {\n delete options[key];\n }\n });\n Object.keys(options).forEach((key) => {\n if (typeof options[key] === \"string\" && (options[key].includes(\"<\") || options[key].includes(\">\") || options[key].includes(\"url(data:\"))) {\n delete options[key];\n }\n if (typeof options[key] === \"object\") {\n sanitize(options[key]);\n }\n });\n}, \"sanitize\");\nvar addDirective = /* @__PURE__ */ __name((directive) => {\n sanitizeDirective(directive);\n if (directive.fontFamily && !directive.themeVariables?.fontFamily) {\n directive.themeVariables = {\n ...directive.themeVariables,\n fontFamily: directive.fontFamily\n };\n }\n directives.push(directive);\n updateCurrentConfig(siteConfig, directives);\n}, \"addDirective\");\nvar reset = /* @__PURE__ */ __name((config2 = siteConfig) => {\n directives = [];\n updateCurrentConfig(config2, directives);\n}, \"reset\");\nvar ConfigWarning = {\n LAZY_LOAD_DEPRECATED: \"The configuration options lazyLoadedDiagrams and loadExternalDiagramsAtStartup are deprecated. Please use registerExternalDiagrams instead.\"\n};\nvar issuedWarnings = {};\nvar issueWarning = /* @__PURE__ */ __name((warning) => {\n if (issuedWarnings[warning]) {\n return;\n }\n log.warn(ConfigWarning[warning]);\n issuedWarnings[warning] = true;\n}, \"issueWarning\");\nvar checkConfig = /* @__PURE__ */ __name((config2) => {\n if (!config2) {\n return;\n }\n if (config2.lazyLoadedDiagrams || config2.loadExternalDiagramsAtStartup) {\n issueWarning(\"LAZY_LOAD_DEPRECATED\");\n }\n}, \"checkConfig\");\nvar getUserDefinedConfig = /* @__PURE__ */ __name(() => {\n let userConfig = {};\n if (configFromInitialize) {\n userConfig = assignWithDepth_default(userConfig, configFromInitialize);\n }\n for (const d of directives) {\n userConfig = assignWithDepth_default(userConfig, d);\n }\n return userConfig;\n}, \"getUserDefinedConfig\");\n\n// src/diagrams/common/common.ts\nimport DOMPurify from \"dompurify\";\nvar lineBreakRegex = //gi;\nvar getRows = /* @__PURE__ */ __name((s) => {\n if (!s) {\n return [\"\"];\n }\n const str = breakToPlaceholder(s).replace(/\\\\n/g, \"#br#\");\n return str.split(\"#br#\");\n}, \"getRows\");\nvar setupDompurifyHooksIfNotSetup = /* @__PURE__ */ (() => {\n let setup = false;\n return () => {\n if (!setup) {\n setupDompurifyHooks();\n setup = true;\n }\n };\n})();\nfunction setupDompurifyHooks() {\n const TEMPORARY_ATTRIBUTE = \"data-temp-href-target\";\n DOMPurify.addHook(\"beforeSanitizeAttributes\", (node) => {\n if (node.tagName === \"A\" && node.hasAttribute(\"target\")) {\n node.setAttribute(TEMPORARY_ATTRIBUTE, node.getAttribute(\"target\") ?? \"\");\n }\n });\n DOMPurify.addHook(\"afterSanitizeAttributes\", (node) => {\n if (node.tagName === \"A\" && node.hasAttribute(TEMPORARY_ATTRIBUTE)) {\n node.setAttribute(\"target\", node.getAttribute(TEMPORARY_ATTRIBUTE) ?? \"\");\n node.removeAttribute(TEMPORARY_ATTRIBUTE);\n if (node.getAttribute(\"target\") === \"_blank\") {\n node.setAttribute(\"rel\", \"noopener\");\n }\n }\n });\n}\n__name(setupDompurifyHooks, \"setupDompurifyHooks\");\nvar removeScript = /* @__PURE__ */ __name((txt) => {\n setupDompurifyHooksIfNotSetup();\n const sanitizedText = DOMPurify.sanitize(txt);\n return sanitizedText;\n}, \"removeScript\");\nvar sanitizeMore = /* @__PURE__ */ __name((text, config2) => {\n if (config2.flowchart?.htmlLabels !== false) {\n const level = config2.securityLevel;\n if (level === \"antiscript\" || level === \"strict\") {\n text = removeScript(text);\n } else if (level !== \"loose\") {\n text = breakToPlaceholder(text);\n text = text.replace(//g, \">\");\n text = text.replace(/=/g, \"=\");\n text = placeholderToBreak(text);\n }\n }\n return text;\n}, \"sanitizeMore\");\nvar sanitizeText = /* @__PURE__ */ __name((text, config2) => {\n if (!text) {\n return text;\n }\n if (config2.dompurifyConfig) {\n text = DOMPurify.sanitize(sanitizeMore(text, config2), config2.dompurifyConfig).toString();\n } else {\n text = DOMPurify.sanitize(sanitizeMore(text, config2), {\n FORBID_TAGS: [\"style\"]\n }).toString();\n }\n return text;\n}, \"sanitizeText\");\nvar sanitizeTextOrArray = /* @__PURE__ */ __name((a, config2) => {\n if (typeof a === \"string\") {\n return sanitizeText(a, config2);\n }\n return a.flat().map((x) => sanitizeText(x, config2));\n}, \"sanitizeTextOrArray\");\nvar hasBreaks = /* @__PURE__ */ __name((text) => {\n return lineBreakRegex.test(text);\n}, \"hasBreaks\");\nvar splitBreaks = /* @__PURE__ */ __name((text) => {\n return text.split(lineBreakRegex);\n}, \"splitBreaks\");\nvar placeholderToBreak = /* @__PURE__ */ __name((s) => {\n return s.replace(/#br#/g, \"
\");\n}, \"placeholderToBreak\");\nvar breakToPlaceholder = /* @__PURE__ */ __name((s) => {\n return s.replace(lineBreakRegex, \"#br#\");\n}, \"breakToPlaceholder\");\nvar getUrl = /* @__PURE__ */ __name((useAbsolute) => {\n let url = \"\";\n if (useAbsolute) {\n url = window.location.protocol + \"//\" + window.location.host + window.location.pathname + window.location.search;\n url = CSS.escape(url);\n }\n return url;\n}, \"getUrl\");\nvar evaluate = /* @__PURE__ */ __name((val) => val === false || [\"false\", \"null\", \"0\"].includes(String(val).trim().toLowerCase()) ? false : true, \"evaluate\");\nvar getMax = /* @__PURE__ */ __name(function(...values) {\n const newValues = values.filter((value) => {\n return !isNaN(value);\n });\n return Math.max(...newValues);\n}, \"getMax\");\nvar getMin = /* @__PURE__ */ __name(function(...values) {\n const newValues = values.filter((value) => {\n return !isNaN(value);\n });\n return Math.min(...newValues);\n}, \"getMin\");\nvar parseGenericTypes = /* @__PURE__ */ __name(function(input) {\n const inputSets = input.split(/(,)/);\n const output = [];\n for (let i = 0; i < inputSets.length; i++) {\n let thisSet = inputSets[i];\n if (thisSet === \",\" && i > 0 && i + 1 < inputSets.length) {\n const previousSet = inputSets[i - 1];\n const nextSet = inputSets[i + 1];\n if (shouldCombineSets(previousSet, nextSet)) {\n thisSet = previousSet + \",\" + nextSet;\n i++;\n output.pop();\n }\n }\n output.push(processSet(thisSet));\n }\n return output.join(\"\");\n}, \"parseGenericTypes\");\nvar countOccurrence = /* @__PURE__ */ __name((string, substring) => {\n return Math.max(0, string.split(substring).length - 1);\n}, \"countOccurrence\");\nvar shouldCombineSets = /* @__PURE__ */ __name((previousSet, nextSet) => {\n const prevCount = countOccurrence(previousSet, \"~\");\n const nextCount = countOccurrence(nextSet, \"~\");\n return prevCount === 1 && nextCount === 1;\n}, \"shouldCombineSets\");\nvar processSet = /* @__PURE__ */ __name((input) => {\n const tildeCount = countOccurrence(input, \"~\");\n let hasStartingTilde = false;\n if (tildeCount <= 1) {\n return input;\n }\n if (tildeCount % 2 !== 0 && input.startsWith(\"~\")) {\n input = input.substring(1);\n hasStartingTilde = true;\n }\n const chars = [...input];\n let first = chars.indexOf(\"~\");\n let last = chars.lastIndexOf(\"~\");\n while (first !== -1 && last !== -1 && first !== last) {\n chars[first] = \"<\";\n chars[last] = \">\";\n first = chars.indexOf(\"~\");\n last = chars.lastIndexOf(\"~\");\n }\n if (hasStartingTilde) {\n chars.unshift(\"~\");\n }\n return chars.join(\"\");\n}, \"processSet\");\nvar isMathMLSupported = /* @__PURE__ */ __name(() => window.MathMLElement !== void 0, \"isMathMLSupported\");\nvar katexRegex = /\\$\\$(.*)\\$\\$/g;\nvar hasKatex = /* @__PURE__ */ __name((text) => (text.match(katexRegex)?.length ?? 0) > 0, \"hasKatex\");\nvar calculateMathMLDimensions = /* @__PURE__ */ __name(async (text, config2) => {\n const divElem = document.createElement(\"div\");\n divElem.innerHTML = await renderKatexSanitized(text, config2);\n divElem.id = \"katex-temp\";\n divElem.style.visibility = \"hidden\";\n divElem.style.position = \"absolute\";\n divElem.style.top = \"0\";\n const body = document.querySelector(\"body\");\n body?.insertAdjacentElement(\"beforeend\", divElem);\n const dim = { width: divElem.clientWidth, height: divElem.clientHeight };\n divElem.remove();\n return dim;\n}, \"calculateMathMLDimensions\");\nvar renderKatexUnsanitized = /* @__PURE__ */ __name(async (text, config2) => {\n if (!hasKatex(text)) {\n return text;\n }\n if (!(isMathMLSupported() || config2.legacyMathML || config2.forceLegacyMathML)) {\n return text.replace(katexRegex, \"MathML is unsupported in this environment.\");\n }\n if (true) {\n const { default: katex } = await import(\"katex\");\n const outputMode = config2.forceLegacyMathML || !isMathMLSupported() && config2.legacyMathML ? \"htmlAndMathml\" : \"mathml\";\n return text.split(lineBreakRegex).map(\n (line) => hasKatex(line) ? `
${line}
` : `
${line}
`\n ).join(\"\").replace(\n katexRegex,\n (_, c) => katex.renderToString(c, {\n throwOnError: true,\n displayMode: true,\n output: outputMode\n }).replace(/\\n/g, \" \").replace(//g, \"\")\n );\n }\n return text.replace(\n katexRegex,\n \"Katex is not supported in @mermaid-js/tiny. Please use the full mermaid library.\"\n );\n}, \"renderKatexUnsanitized\");\nvar renderKatexSanitized = /* @__PURE__ */ __name(async (text, config2) => {\n return sanitizeText(await renderKatexUnsanitized(text, config2), config2);\n}, \"renderKatexSanitized\");\nvar common_default = {\n getRows,\n sanitizeText,\n sanitizeTextOrArray,\n hasBreaks,\n splitBreaks,\n lineBreakRegex,\n removeScript,\n getUrl,\n evaluate,\n getMax,\n getMin\n};\n\n// src/setupGraphViewbox.js\nvar d3Attrs = /* @__PURE__ */ __name(function(d3Elem, attrs) {\n for (let attr of attrs) {\n d3Elem.attr(attr[0], attr[1]);\n }\n}, \"d3Attrs\");\nvar calculateSvgSizeAttrs = /* @__PURE__ */ __name(function(height, width, useMaxWidth) {\n let attrs = /* @__PURE__ */ new Map();\n if (useMaxWidth) {\n attrs.set(\"width\", \"100%\");\n attrs.set(\"style\", `max-width: ${width}px;`);\n } else {\n attrs.set(\"height\", height);\n attrs.set(\"width\", width);\n }\n return attrs;\n}, \"calculateSvgSizeAttrs\");\nvar configureSvgSize = /* @__PURE__ */ __name(function(svgElem, height, width, useMaxWidth) {\n const attrs = calculateSvgSizeAttrs(height, width, useMaxWidth);\n d3Attrs(svgElem, attrs);\n}, \"configureSvgSize\");\nvar setupGraphViewbox = /* @__PURE__ */ __name(function(graph, svgElem, padding, useMaxWidth) {\n const svgBounds = svgElem.node().getBBox();\n const sWidth = svgBounds.width;\n const sHeight = svgBounds.height;\n log.info(`SVG bounds: ${sWidth}x${sHeight}`, svgBounds);\n let width = 0;\n let height = 0;\n log.info(`Graph bounds: ${width}x${height}`, graph);\n width = sWidth + padding * 2;\n height = sHeight + padding * 2;\n log.info(`Calculated bounds: ${width}x${height}`);\n configureSvgSize(svgElem, height, width, useMaxWidth);\n const vBox = `${svgBounds.x - padding} ${svgBounds.y - padding} ${svgBounds.width + 2 * padding} ${svgBounds.height + 2 * padding}`;\n svgElem.attr(\"viewBox\", vBox);\n}, \"setupGraphViewbox\");\n\n// src/styles.ts\nvar themes = {};\nvar getStyles = /* @__PURE__ */ __name((type, userStyles, options) => {\n let diagramStyles = \"\";\n if (type in themes && themes[type]) {\n diagramStyles = themes[type](options);\n } else {\n log.warn(`No theme found for ${type}`);\n }\n return ` & {\n font-family: ${options.fontFamily};\n font-size: ${options.fontSize};\n fill: ${options.textColor}\n }\n @keyframes edge-animation-frame {\n from {\n stroke-dashoffset: 0;\n }\n }\n @keyframes dash {\n to {\n stroke-dashoffset: 0;\n }\n }\n & .edge-animation-slow {\n stroke-dasharray: 9,5 !important;\n stroke-dashoffset: 900;\n animation: dash 50s linear infinite;\n stroke-linecap: round;\n }\n & .edge-animation-fast {\n stroke-dasharray: 9,5 !important;\n stroke-dashoffset: 900;\n animation: dash 20s linear infinite;\n stroke-linecap: round;\n }\n /* Classes common for multiple diagrams */\n\n & .error-icon {\n fill: ${options.errorBkgColor};\n }\n & .error-text {\n fill: ${options.errorTextColor};\n stroke: ${options.errorTextColor};\n }\n\n & .edge-thickness-normal {\n stroke-width: 1px;\n }\n & .edge-thickness-thick {\n stroke-width: 3.5px\n }\n & .edge-pattern-solid {\n stroke-dasharray: 0;\n }\n & .edge-thickness-invisible {\n stroke-width: 0;\n fill: none;\n }\n & .edge-pattern-dashed{\n stroke-dasharray: 3;\n }\n .edge-pattern-dotted {\n stroke-dasharray: 2;\n }\n\n & .marker {\n fill: ${options.lineColor};\n stroke: ${options.lineColor};\n }\n & .marker.cross {\n stroke: ${options.lineColor};\n }\n\n & svg {\n font-family: ${options.fontFamily};\n font-size: ${options.fontSize};\n }\n & p {\n margin: 0\n }\n\n ${diagramStyles}\n\n ${userStyles}\n`;\n}, \"getStyles\");\nvar addStylesForDiagram = /* @__PURE__ */ __name((type, diagramTheme) => {\n if (diagramTheme !== void 0) {\n themes[type] = diagramTheme;\n }\n}, \"addStylesForDiagram\");\nvar styles_default = getStyles;\n\n// src/diagrams/common/commonDb.ts\nvar commonDb_exports = {};\n__export(commonDb_exports, {\n clear: () => clear,\n getAccDescription: () => getAccDescription,\n getAccTitle: () => getAccTitle,\n getDiagramTitle: () => getDiagramTitle,\n setAccDescription: () => setAccDescription,\n setAccTitle: () => setAccTitle,\n setDiagramTitle: () => setDiagramTitle\n});\nvar accTitle = \"\";\nvar diagramTitle = \"\";\nvar accDescription = \"\";\nvar sanitizeText2 = /* @__PURE__ */ __name((txt) => sanitizeText(txt, getConfig()), \"sanitizeText\");\nvar clear = /* @__PURE__ */ __name(() => {\n accTitle = \"\";\n accDescription = \"\";\n diagramTitle = \"\";\n}, \"clear\");\nvar setAccTitle = /* @__PURE__ */ __name((txt) => {\n accTitle = sanitizeText2(txt).replace(/^\\s+/g, \"\");\n}, \"setAccTitle\");\nvar getAccTitle = /* @__PURE__ */ __name(() => accTitle, \"getAccTitle\");\nvar setAccDescription = /* @__PURE__ */ __name((txt) => {\n accDescription = sanitizeText2(txt).replace(/\\n\\s+/g, \"\\n\");\n}, \"setAccDescription\");\nvar getAccDescription = /* @__PURE__ */ __name(() => accDescription, \"getAccDescription\");\nvar setDiagramTitle = /* @__PURE__ */ __name((txt) => {\n diagramTitle = sanitizeText2(txt);\n}, \"setDiagramTitle\");\nvar getDiagramTitle = /* @__PURE__ */ __name(() => diagramTitle, \"getDiagramTitle\");\n\n// src/diagram-api/diagramAPI.ts\nvar log2 = log;\nvar setLogLevel2 = setLogLevel;\nvar getConfig2 = getConfig;\nvar setConfig2 = setConfig;\nvar defaultConfig2 = defaultConfig;\nvar sanitizeText3 = /* @__PURE__ */ __name((text) => sanitizeText(text, getConfig2()), \"sanitizeText\");\nvar setupGraphViewbox2 = setupGraphViewbox;\nvar getCommonDb = /* @__PURE__ */ __name(() => {\n return commonDb_exports;\n}, \"getCommonDb\");\nvar diagrams = {};\nvar registerDiagram = /* @__PURE__ */ __name((id, diagram, detector) => {\n if (diagrams[id]) {\n log2.warn(`Diagram with id ${id} already registered. Overwriting.`);\n }\n diagrams[id] = diagram;\n if (detector) {\n addDetector(id, detector);\n }\n addStylesForDiagram(id, diagram.styles);\n diagram.injectUtils?.(\n log2,\n setLogLevel2,\n getConfig2,\n sanitizeText3,\n setupGraphViewbox2,\n getCommonDb(),\n () => {\n }\n );\n}, \"registerDiagram\");\nvar getDiagram = /* @__PURE__ */ __name((name) => {\n if (name in diagrams) {\n return diagrams[name];\n }\n throw new DiagramNotFoundError(name);\n}, \"getDiagram\");\nvar DiagramNotFoundError = class extends Error {\n static {\n __name(this, \"DiagramNotFoundError\");\n }\n constructor(name) {\n super(`Diagram ${name} not found.`);\n }\n};\n\nexport {\n assignWithDepth_default,\n getThemeVariables3 as getThemeVariables,\n themes_default,\n defaultConfig_default,\n sanitizeDirective,\n defaultConfig,\n setSiteConfig,\n saveConfigFromInitialize,\n updateSiteConfig,\n getSiteConfig,\n setConfig,\n getConfig,\n addDirective,\n reset,\n getUserDefinedConfig,\n lineBreakRegex,\n sanitizeText,\n getUrl,\n evaluate,\n parseGenericTypes,\n hasKatex,\n calculateMathMLDimensions,\n renderKatexSanitized,\n common_default,\n frontMatterRegex,\n directiveRegex,\n UnknownDiagramError,\n detectors,\n detectType,\n registerLazyLoadedDiagrams,\n getDiagramLoader,\n configureSvgSize,\n setupGraphViewbox,\n styles_default,\n clear,\n setAccTitle,\n getAccTitle,\n setAccDescription,\n getAccDescription,\n setDiagramTitle,\n getDiagramTitle,\n commonDb_exports,\n getConfig2,\n setConfig2,\n defaultConfig2,\n sanitizeText3 as sanitizeText2,\n setupGraphViewbox2,\n registerDiagram,\n getDiagram\n};\n"], + "mappings": "mEAEA,IAAMA,GAAU,CAEZ,IAAK,CACD,EAAG,EACH,EAAG,EACH,EAAG,EACH,EAAG,EACH,EAAG,EACH,EAAG,CACP,EACA,IAAK,CACD,EAA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,IAAMC,GAAO7E,EAAO,CACzB,IACA,OACA,UACA,UACA,OACA,UACA,QACA,QACA,IACA,MACA,MACA,MACA,QACA,aACA,OACA,KACA,SACA,SACA,UACA,SACA,OACA,OACA,MACA,WACA,UACA,OACA,WACA,KACA,YACA,MACA,UACA,MACA,SACA,MACA,MACA,KACA,KACA,UACA,KACA,WACA,aACA,SACA,OACA,SACA,OACA,KACA,KACA,KACA,KACA,KACA,KACA,OACA,SACA,SACA,KACA,OACA,IACA,MACA,QACA,MACA,MACA,QACA,SACA,KACA,OACA,MACA,OACA,UACA,OACA,WACA,QACA,MACA,OACA,KACA,WACA,SACA,SACA,IACA,UACA,MACA,WACA,IACA,KACA,KACA,OACA,IACA,OACA,SACA,UACA,SACA,SACA,OACA,QACA,SACA,SACA,OACA,SACA,SACA,QACA,MACA,UACA,MACA,QACA,QACA,KACA,WACA,WACA,QACA,KACA,QACA,OACA,KACA,QACA,KACA,IACA,KACA,MACA,QACA,KAAK,CACG,EAEG8E,GAAM9E,EAAO,CACxB,MACA,IACA,WACA,cACA,eACA,eACA,gBACA,mBACA,SACA,WACA,OACA,OACA,UACA,eACA,cACA,SACA,OACA,IACA,QACA,WACA,QACA,QACA,YACA,OACA,iBACA,SACA,OACA,WACA,QACA,OACA,OACA,UACA,UACA,WACA,iBACA,OACA,OACA,OACA,QACA,SACA,SACA,OACA,WACA,QACA,OACA,QACA,OACA,OAAO,CACC,EAEG+E,GAAa/E,EAAO,CAC/B,UACA,gBACA,sBACA,cACA,mBACA,oBACA,oBACA,iBACA,eACA,UACA,UACA,UACA,UACA,UACA,iBACA,UACA,UACA,cACA,eACA,WACA,eACA,qBACA,cACA,SACA,cAAc,CACN,EAMGgF,GAAgBhF,EAAO,CAClC,UACA,gBACA,SACA,UACA,YACA,mBACA,iBACA,gBACA,gBACA,gBACA,QACA,YACA,OACA,eACA,YACA,UACA,gBACA,SACA,MACA,aACA,UACA,KAAK,CACG,EAEGiF,GAASjF,EAAO,CAC3B,OACA,WACA,SACA,UACA,QACA,SACA,KACA,aACA,gBACA,KACA,KACA,QACA,UACA,WACA,QACA,OACA,KACA,SACA,QACA,SACA,OACA,OACA,UACA,SACA,MACA,QACA,MACA,SACA,aACA,aAAa,CACL,EAIGkF,GAAmBlF,EAAO,CACrC,UACA,cACA,aACA,WACA,YACA,UACA,UACA,SACA,SACA,QACA,YACA,aACA,iBACA,cACA,MAAM,CACE,EAEGmF,GAAOnF,EAAO,CAAC,OAAO,CAAU,EC3RhC6E,GAAO7E,EAAO,CACzB,SACA,SACA,QACA,MACA,iBACA,eACA,uBACA,WACA,aACA,UACA,SACA,UACA,cACA,cACA,UACA,OACA,QACA,QACA,QACA,OACA,UACA,WACA,eACA,SACA,cACA,WACA,WACA,UACA,MACA,WACA,0BACA,wBACA,WACA,YACA,UACA,eACA,cACA,OACA,MACA,UACA,SACA,SACA,OACA,OACA,WACA,KACA,QACA,YACA,YACA,QACA,OACA,QACA,OACA,OACA,UACA,OACA,MACA,MACA,YACA,QACA,SACA,MACA,YACA,WACA,QACA,OACA,QACA,UACA,aACA,SACA,OACA,UACA,OACA,UACA,cACA,cACA,UACA,gBACA,sBACA,SACA,UACA,UACA,aACA,WACA,MACA,WACA,MACA,WACA,OACA,OACA,UACA,aACA,QACA,WACA,QACA,OACA,QACA,OACA,OACA,UACA,QACA,MACA,SACA,OACA,QACA,UACA,WACA,QACA,YACA,OACA,SACA,SACA,QACA,QACA,OACA,QACA,MAAM,CACE,EAEG8E,GAAM9E,EAAO,CACxB,gBACA,aACA,WACA,qBACA,YACA,SACA,gBACA,gBACA,UACA,gBACA,iBACA,QACA,OACA,KACA,QACA,OACA,gBACA,YACA,YACA,QACA,sBACA,8BACA,gBACA,kBACA,KACA,KACA,IACA,KACA,KACA,kBACA,YACA,UACA,UACA,MACA,WACA,YACA,MACA,WACA,OACA,eACA,YACA,SACA,cACA,cACA,gBACA,cACA,YACA,mBACA,eACA,aACA,eACA,cACA,KACA,KACA,KACA,KACA,aACA,WACA,gBACA,oBACA,SACA,OACA,KACA,kBACA,KACA,MACA,YACA,IACA,KACA,KACA,KACA,KACA,UACA,YACA,aACA,WACA,OACA,eACA,iBACA,eACA,mBACA,iBACA,QACA,aACA,aACA,eACA,eACA,cACA,cACA,mBACA,YACA,MACA,OACA,QACA,SACA,OACA,MACA,OACA,aACA,SACA,WACA,UACA,QACA,SACA,cACA,SACA,WACA,cACA,OACA,aACA,sBACA,mBACA,eACA,SACA,gBACA,sBACA,iBACA,IACA,KACA,KACA,SACA,OACA,OACA,cACA,YACA,UACA,SACA,SACA,QACA,OACA,kBACA,QACA,mBACA,mBACA,eACA,cACA,eACA,cACA,aACA,eACA,mBACA,oBACA,iBACA,kBACA,oBACA,iBACA,SACA,eACA,QACA,eACA,iBACA,WACA,cACA,UACA,UACA,YACA,mBACA,cACA,kBACA,iBACA,aACA,OACA,KACA,KACA,UACA,SACA,UACA,aACA,UACA,aACA,gBACA,gBACA,QACA,eACA,OACA,eACA,mBACA,mBACA,IACA,KACA,KACA,QACA,IACA,KACA,KACA,IACA,YAAY,CACJ,EAEGiF,GAASjF,EAAO,CAC3B,SACA,cACA,QACA,WACA,QACA,eACA,cACA,aACA,aACA,QACA,MACA,UACA,eACA,WACA,QACA,QACA,SACA,OACA,KACA,UACA,SACA,gBACA,SACA,SACA,iBACA,YACA,WACA,cACA,UACA,UACA,gBACA,WACA,WACA,OACA,WACA,WACA,aACA,UACA,SACA,SACA,cACA,gBACA,uBACA,YACA,YACA,aACA,WACA,iBACA,iBACA,YACA,UACA,QACA,OAAO,CACR,EAEYoF,GAAMpF,EAAO,CACxB,aACA,SACA,cACA,YACA,aAAa,CACL,ECnXGqF,GAAgBpF,EAAK,2BAA2B,EAChDqF,GAAWrF,EAAK,uBAAuB,EACvCsF,GAActF,EAAK,eAAe,EAClCuF,GAAYvF,EAAK,8BAA8B,EAC/CwF,GAAYxF,EAAK,gBAAgB,EACjCyF,GAAiBzF,EAC5B,oGAEW0F,GAAoB1F,EAAK,uBAAuB,EACh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AwB,GACxB,SAAY,GACZ,gBAAmB,GACnB,oBAAuB,EACvB,WAAc,WACd,QAAW,GACX,YAAe,GACf,QAAW,QACb,EACA,QAAW,CACT,YAAe,GACf,eAAkB,GAClB,eAAkB,GAClB,WAAc,IACd,cAAiB,IACjB,MAAS,IACT,OAAU,GACV,UAAa,GACb,cAAiB,EACjB,WAAc,GACd,cAAiB,GACjB,aAAgB,SAChB,gBAAmB,EACnB,YAAe,GACf,aAAgB,GAChB,eAAkB,0BAClB,WAAc,GACd,gBAAmB,GACnB,cAAiB,KACjB,aAAgB,CACd,UACA,UACA,UACA,UACA,UACA,SACF,EACA,aAAgB,CACd,UACA,UACA,UACA,UACA,UACA,UACA,SACF,EACA,eAAkB,CAChB,MACF,EACA,WAAc,GACd,gBAAmB,6CACnB,cAAiB,KACnB,EACA,MAAS,CACP,YAAe,GACf,eAAkB,GAClB,oBAAuB,GACvB,cAAiB,GACjB,QAAW,EACX,WAAc,GACd,gBAAmB,gBACnB,WAAc,GACd,oBAAuB,EACzB,EACA,MAAS,CACP,YAAe,GACf,eAAkB,GAClB,cAAiB,GACjB,SAAY,EACZ,QAAW,EACX,WAAc,GACd,WAAc,IACd,WAAc,GACd,UAAa,GACb,WAAc,EACd,YAAe,EACf,eAAkB,KAClB,SAAY,GACZ,YAAe,GACf,iBAAoB,KACpB,kBAAqB,GACrB,OAAU,EACV,gBAAmB,eACrB,EACA,GAAM,CACJ,YAAe,GACf,eAAkB,GAClB,eAAkB,GAClB,gBAAmB,KACnB,eAAkB,IAClB,gBAAmB,GACnB,cAAiB,GACjB,YAAe,IACf,YAAe,GACf,OAAU,OACV,KAAQ,WACR,SAAY,EACd,EACA,IAAO,CACL,YAAe,GACf,aAAgB,GAClB,EACA,cAAiB,CACf,YAAe,GACf,WAAc,IACd,YAAe,IACf,cAAiB,GACjB,aAAgB,GAChB,gBAAmB,EACnB,kBAAqB,EACrB,kBAAqB,EACrB,mBAAsB,GACtB,mBAAsB,GACtB,sBAAyB,GACzB,uBAA0B,EAC1B,iBAAoB,EACpB,mBAAsB,GACtB,YAAe,EACf,cAAiB,MACjB,cAAiB,OACjB,kCAAqC,EACrC,kCAAqC,CACvC,EACA,QAAW,CACT,YAAe,GACf,MAAS,IACT,OAAU,IACV,cAAiB,GACjB,aAAgB,GAChB,cAAiB,GACjB,UAAa,GACb,MAAS,CACP,KAAQ,4BACR,UAAa,GACb,cAAiB,GACjB,aAAgB,EAChB,UAAa,GACb,cAAiB,GACjB,aAAgB,EAChB,SAAY,GACZ,WAAc,EACd,UAAa,EACb,aAAgB,GAChB,cAAiB,CACnB,EACA,MAAS,CACP,KAAQ,4BACR,UAAa,GACb,cAAiB,GACjB,aAAgB,EAChB,UAAa,GACb,cAAiB,GACjB,aAAgB,EAChB,SAAY,GACZ,WAAc,EACd,UAAa,EACb,aAAgB,GAChB,cAAiB,CACnB,EACA,iBAAoB,WACpB,yBAA4B,EAC9B,EACA,YAAe,CACb,YAAe,GACf,UAAa,UACb,WAAc,OACd,iBAAoB,QACpB,kBAAqB,OACrB,eAAkB,IAClB,gBAAmB,IACnB,SAAY,GACZ,aAAgB,GAChB,YAAe,EACjB,EACA,QAAW,CACT,YAAe,GACf,QAAW,GACX,aAAgB,IAChB,gBAAmB,cACrB,EACA,OAAU,CACR,YAAe,GACf,QAAW,EACX,aAAgB,IAChB,cAAiB,EACnB,EACA,SAAY,CACV,YAAe,GACf,eAAkB,GAClB,eAAkB,GAClB,WAAc,IACd,MAAS,IACT,OAAU,GACV,UAAa,GACb,cAAiB,EACjB,WAAc,GACd,cAAiB,GACjB,aAAgB,SAChB,gBAAmB,EACnB,YAAe,GACf,aAAgB,GAChB,eAAkB,0BAClB,WAAc,GACd,gBAAmB,GACnB,cAAiB,KACjB,aAAgB,CACd,UACA,UACA,UACA,UACA,UACA,SACF,EACA,aAAgB,CACd,UACA,UACA,UACA,UACA,UACA,UACA,SACF,EACA,eAAkB,CAChB,MACF,EACA,kBAAqB,EACvB,EACA,SAAY,CACV,YAAe,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GAAQ,CACpDsF,GAAeE,GAAcxF,CAAG,CAClC,EAAG,iBAAiB,EAChBiF,GAAkClM,EAAO,IAAMuM,GAAc,iBAAiB,EAG9EG,GAAO7L,EACP8L,GAAeC,GACfC,GAAajH,GACbkH,GAAanH,GACboH,GAAiBxI,GACjByI,GAAgChN,EAAQI,GAASiH,GAAajH,EAAMyM,GAAW,CAAC,EAAG,cAAc,EACjGI,GAAqBnC,GACrBoC,GAA8BlN,EAAO,IAChC6L,GACN,aAAa,EACZsB,GAAW,CAAC,EACZC,GAAkCpN,EAAO,CAACU,EAAI2M,EAAS9M,IAAa,CAClE4M,GAASzM,CAAE,GACbgM,GAAK,KAAK,mBAAmBhM,CAAE,mCAAmC,EAEpEyM,GAASzM,CAAE,EAAI2M,EACX9M,GACFK,GAAYF,EAAIH,CAAQ,EAE1BmL,GAAoBhL,EAAI2M,EAAQ,MAAM,EACtCA,EAAQ,cACNX,GACAC,GACAE,GACAG,GACAC,GACAC,GAAY,EACZ,IAAM,CACN,CACF,CACF,EAAG,iBAAiB,EAChBI,GAA6BtN,EAAQuN,GAAS,CAChD,GAAIA,KAAQJ,GACV,OAAOA,GAASI,CAAI,EAEtB,MAAM,IAAIC,GAAqBD,CAAI,CACrC,EAAG,YAAY,EACXC,GAAuB,cAAc,KAAM,CAC7C,MAAO,CACLxN,EAAO,KAAM,sBAAsB,CACrC,CACA,YAAYuN,EAAM,CAChB,MAAM,WAAWA,CAAI,aAAa,CACpC,CACF", + "names": ["Channel", "r", "g", "b", "h", "s", "l", "a", "c", "n", "p", "q", "t", "channel", "max", "min", "d", "channel_default", "Lang", "number", "lower", "upper", "lang_default", "Unit", "dec", "hex", "unit_default", "Utils", "channel_default", "lang_default", "unit_default", "utils_default", "DEC2HEX", "i", "utils_default", "TYPE", "Type", "TYPE", "type", "type_default", "Channels", "data", "color", "type_default", "TYPE", "h", "s", "l", "utils_default", "r", "g", "b", "a", "channels_default", "channels", "channels_default", "reusable_default", "Hex", "color", "match", "hex", "dec", "length", "hasAlpha", "isFullLength", "multiplier", "bits", "bitsOffset", "mask", "reusable_default", "channels", "r", "g", "b", "a", "DEC2HEX", "hex_default", "HSL", "hue", "match", "number", "unit", "utils_default", "color", "charCode", "h", "l", "a", "isAlphaPercentage", "reusable_default", "channels", "s", "hsl_default", "Keyword", "color", "hex", "hex_default", "channels", "name", "keyword_default", "RGB", "color", "charCode", "match", "r", "isRedPercentage", "g", "isGreenPercentage", "b", "isBluePercentage", "a", "isAlphaPercentage", "reusable_default", "utils_default", "channels", "rgb_default", "Color", "keyword_default", "hex_default", "rgb_default", "hsl_default", "color", "channels", "TYPE", "color_default", "change", "color", "channels", "ch", "color_default", "c", "utils_default", "change_default", "rgba", "r", "g", "b", "change_default", "channels", "reusable_default", "utils_default", "color_default", "rgba_default", "channel", "color", "utils_default", "color_default", "channel_default", "luminance", "color", "r", "g", "b", "color_default", "utils_default", "luminance_default", "isLight", "color", "luminance_default", "is_light_default", "isDark", "color", "is_light_default", "is_dark_default", "adjustChannel", "color", "channel", "amount", "channels", "color_default", "amountCurrent", "amountNext", "utils_default", "adjust_channel_default", "lighten", "color", "amount", "adjust_channel_default", "lighten_default", "darken", "color", "amount", "adjust_channel_default", "darken_default", "adjust", "color", "channels", "ch", "color_default", "changes", "c", "change_default", "adjust_default", "mix", "color1", "color2", "weight", "r1", "g1", "b1", "a1", "color_default", "r2", "g2", "b2", "a2", "weightScale", "weightNormalized", "alphaDelta", "weight1", "weight2", "r", "g", "b", "a", "rgba_default", "mix_default", "invert", "color", "weight", "inverse", "color_default", "mix_default", "invert_default", "entries", "setPrototypeOf", "isFrozen", "getPrototypeOf", "getOwnPropertyDescriptor", "Object", "freeze", "seal", "create", "apply", "construct", "Reflect", "x", "func", "thisArg", "_len", "arguments", "length", "args", "Array", "_key", "Func", "_len2", "_key2", "arrayForEach", "unapply", "prototype", "forEach", "arrayLastIndexOf", "lastIndexOf", "arrayPop", "pop", "arrayPush", "push", "arraySplice", "splice", "stringToLowerCase", "String", "toLowerCase", "stringToString", "toString", "stringMatch", "match", "stringReplace", "replace", "stringIndexOf", "indexOf", "stringTrim", "trim", "objectHasOwnProperty", "hasOwnProperty", "regExpTest", "RegExp", "test", "typeErrorCreate", "unconstruct", "TypeError", "lastIndex", "_len3", "_key3", "_len4", "_key4", "addToSet", "set", "array", "transformCaseFunc", "l", "element", "lcElement", "cleanArray", "index", "clone", "object", "newObject", "property", "value", "isArray", "constructor", "lookupGetter", "prop", "desc", "get", "fallbackValue", "html", "svg", "svgFilters", "svgDisallowed", "mathMl", "mathMlDisallowed", "text", "xml", "MUSTACHE_EXPR", "ERB_EXPR", "TMPLIT_EXPR", "DATA_ATTR", "ARIA_ATTR", "IS_ALLOWED_URI", "IS_SCRIPT_OR_DATA", "ATTR_WHITESPACE", "DOCTYPE_NAME", "CUSTOM_ELEMENT", "NODE_TYPE", "attribute", "cdataSection", "entityReference", "entityNode", "progressingInstruction", "comment", "document", "documentType", "documentFragment", "notation", "getGlobal", "window", "_createTrustedTypesPolicy", "trustedTypes", "purifyHostElement", "createPolicy", "suffix", "ATTR_NAME", "hasAttribute", "getAttribute", "policyName", "createHTML", "createScriptURL", "scriptUrl", "console", "warn", "_createHooksMap", "afterSanitizeAttributes", "afterSanitizeElements", "afterSanitizeShadowDOM", "beforeSanitizeAttributes", "beforeSanitizeElements", "beforeSanitizeShadowDOM", "uponSanitizeAttribute", "uponSanitizeElement", "uponSanitizeShadowNode", "createDOMPurify", "undefined", "DOMPurify", "root", "version", "VERSION", "removed", "nodeType", "Element", "isSupported", "originalDocument", "currentScript", "DocumentFragment", "HTMLTemplateElement", "Node", "NodeFilter", "NamedNodeMap", "MozNamedAttrMap", "HTMLFormElement", "DOMParser", "ElementPrototype", "cloneNode", "remove", "getNextSibling", "getChildNodes", "getParentNode", "template", "createElement", "content", "ownerDocument", "trustedTypesPolicy", "emptyHTML", "implementation", "createNodeIterator", "createDocumentFragment", "getElementsByTagName", "importNode", "hooks", "createHTMLDocument", "EXPRESSIONS", "ALLOWED_TAGS", "DEFAULT_ALLOWED_TAGS", "TAGS", "ALLOWED_ATTR", "DEFAULT_ALLOWED_ATTR", "ATTRS", "CUSTOM_ELEMENT_HANDLING", "tagNameCheck", "writable", "configurable", "enumerable", "attributeNameCheck", "allowCustomizedBuiltInElements", "FORBID_TAGS", "FORBID_ATTR", "ALLOW_ARIA_ATTR", "ALLOW_DATA_ATTR", "ALLOW_UNKNOWN_PROTOCOLS", "ALLOW_SELF_CLOSE_IN_ATTR", "SAFE_FOR_TEMPLATES", "SAFE_FOR_XML", "WHOLE_DOCUMENT", "SET_CONFIG", "FORCE_BODY", "RETURN_DOM", "RETURN_DOM_FRAGMENT", "RETURN_TRUSTED_TYPE", "SANITIZE_DOM", "SANITIZE_NAMED_PROPS", "SANITIZE_NAMED_PROPS_PREFIX", "KEEP_CONTENT", "IN_PLACE", "USE_PROFILES", "FORBID_CONTENTS", "DEFAULT_FORBID_CONTENTS", "DATA_URI_TAGS", "DEFAULT_DATA_URI_TAGS", "URI_SAFE_ATTRIBUTES", "DEFAULT_URI_SAFE_ATTRIBUTES", "MATHML_NAMESPACE", "SVG_NAMESPACE", "HTML_NAMESPACE", "NAMESPACE", "IS_EMPTY_INPUT", "ALLOWED_NAMESPACES", "DEFAULT_ALLOWED_NAMESPACES", "MATHML_TEXT_INTEGRATION_POINTS", "HTML_INTEGRATION_POINTS", "COMMON_SVG_AND_HTML_ELEMENTS", "PARSER_MEDIA_TYPE", "SUPPORTED_PARSER_MEDIA_TYPES", "DEFAULT_PARSER_MEDIA_TYPE", "CONFIG", "formElement", "isRegexOrFunction", "testValue", "Function", "_parseConfig", "cfg", "ADD_URI_SAFE_ATTR", "ADD_DATA_URI_TAGS", "ALLOWED_URI_REGEXP", "ADD_TAGS", "ADD_ATTR", "table", "tbody", "TRUSTED_TYPES_POLICY", "ALL_SVG_TAGS", "ALL_MATHML_TAGS", "_checkValidNamespace", "parent", "tagName", "namespaceURI", "parentTagName", "Boolean", "_forceRemove", "node", "removeChild", "_removeAttribute", "name", "getAttributeNode", "from", "removeAttribute", "setAttribute", "_initDocument", "dirty", "doc", "leadingWhitespace", "matches", "dirtyPayload", "parseFromString", "documentElement", "createDocument", "innerHTML", "body", "insertBefore", "createTextNode", "childNodes", "call", "_createNodeIterator", "SHOW_ELEMENT", "SHOW_COMMENT", "SHOW_TEXT", "SHOW_PROCESSING_INSTRUCTION", "SHOW_CDATA_SECTION", "_isClobbered", "nodeName", "textContent", "attributes", "hasChildNodes", "_isNode", "_executeHooks", "currentNode", "data", "hook", "_sanitizeElements", "allowedTags", "firstElementChild", "_isBasicCustomElement", "parentNode", "childCount", "i", "childClone", "__removalCount", "expr", "_isValidAttribute", "lcTag", "lcName", "_sanitizeAttributes", "hookEvent", "attrName", "attrValue", "keepAttr", "allowedAttributes", "forceKeepAttr", "attr", "initValue", "getAttributeType", "setAttributeNS", "_sanitizeShadowDOM", "fragment", "shadowNode", "shadowIterator", "nextNode", "sanitize", "importedNode", "returnNode", "appendChild", "firstChild", "nodeIterator", "shadowroot", "shadowrootmode", "serializedHTML", "outerHTML", "doctype", "setConfig", "clearConfig", "isValidAttribute", "tag", "addHook", "entryPoint", "hookFunction", "removeHook", "removeHooks", "removeAllHooks", "purify", "frontMatterRegex", "directiveRegex", "anyCommentRegex", "UnknownDiagramError", "__name", "message", "detectors", "detectType", "text", "config2", "key", "detector", "registerLazyLoadedDiagrams", "diagrams2", "id", "loader", "addDetector", "log", "getDiagramLoader", "assignWithDepth", "dst", "src", "depth", "clobber", "s", "assignWithDepth_default", "oldAttributeBackgroundColorOdd", "oldAttributeBackgroundColorEven", "mkBorder", "col", "darkMode", "adjust_default", "Theme", "invert_default", "darken_default", "lighten_default", "i", "multiplier", "is_dark_default", "overrides", "keys", "k", "getThemeVariables", "userOverrides", "theme", "Theme2", "rgba_default", "getThemeVariables2", "Theme3", "getThemeVariables3", "Theme4", "getThemeVariables4", "Theme5", "getThemeVariables5", "themes_default", "config_schema_default", "config", "keyify", "obj", "prefix", "res", "el", "configKeys", "defaultConfig_default", "sanitizeDirective", "args", "arg", "cssMatchers", "cssKey", "sanitizeCss", "val", "str", "startCnt", "endCnt", "element", "defaultConfig", "siteConfig", "configFromInitialize", "directives", "currentConfig", "updateCurrentConfig", "siteCfg", "_directives", "cfg", "sumOfDirectives", "d", "sanitize", "tmpConfigFromInitialize", "themeVariables", "checkConfig", "setSiteConfig", "conf", "saveConfigFromInitialize", "updateSiteConfig", "getSiteConfig", "setConfig", "getConfig", "options", "addDirective", "directive", "reset", "ConfigWarning", "issuedWarnings", "issueWarning", "warning", "getUserDefinedConfig", "userConfig", "lineBreakRegex", "getRows", "breakToPlaceholder", "setupDompurifyHooksIfNotSetup", "setup", "setupDompurifyHooks", "TEMPORARY_ATTRIBUTE", "purify", "node", "removeScript", "txt", "sanitizeMore", "level", "placeholderToBreak", "sanitizeText", "sanitizeTextOrArray", "a", "x", "hasBreaks", "splitBreaks", "getUrl", "useAbsolute", "url", "evaluate", "getMax", "values", "newValues", "value", "getMin", "parseGenericTypes", "input", "inputSets", "output", "thisSet", "previousSet", "nextSet", "shouldCombineSets", "processSet", "countOccurrence", "string", "substring", "prevCount", "nextCount", "tildeCount", "hasStartingTilde", "chars", "first", "last", "isMathMLSupported", "katexRegex", "hasKatex", "calculateMathMLDimensions", "divElem", "renderKatexSanitized", "dim", "renderKatexUnsanitized", "katex", "outputMode", "line", "_", "common_default", "d3Attrs", "d3Elem", "attrs", "attr", "calculateSvgSizeAttrs", "height", "width", "useMaxWidth", "configureSvgSize", "svgElem", "setupGraphViewbox", "graph", "padding", "svgBounds", "sWidth", "sHeight", "vBox", "themes", "getStyles", "type", "userStyles", "diagramStyles", "addStylesForDiagram", "diagramTheme", "styles_default", "commonDb_exports", "__export", "clear", "getAccDescription", "getAccTitle", "getDiagramTitle", "setAccDescription", "setAccTitle", "setDiagramTitle", "accTitle", "diagramTitle", "accDescription", "sanitizeText2", "log2", "setLogLevel2", "setLogLevel", "getConfig2", "setConfig2", "defaultConfig2", "sanitizeText3", "setupGraphViewbox2", "getCommonDb", "diagrams", "registerDiagram", "diagram", "getDiagram", "name", "DiagramNotFoundError"] +} diff --git a/docs/website/public/chunk-6B6J5Z6Z.min.js b/docs/website/public/chunk-6B6J5Z6Z.min.js new file mode 100644 index 000000000..a25506fc5 --- /dev/null +++ b/docs/website/public/chunk-6B6J5Z6Z.min.js @@ -0,0 +1,2 @@ +import{a as i,b as u,c as a,d as n,e as m,f as r,g as o,k as s,o as l,q as d}from"./chunk-LBFZT66H.min.js";var h=class extends d{static{r(this,"ArchitectureTokenBuilder")}constructor(){super(["architecture"])}},A=class extends l{static{r(this,"ArchitectureValueConverter")}runCustomConverter(t,e,c){if(t.name==="ARCH_ICON")return e.replace(/[()]/g,"").trim();if(t.name==="ARCH_TEXT_ICON")return e.replace(/["()]/g,"");if(t.name==="ARCH_TITLE")return e.replace(/[[\]]/g,"").trim()}},C={parser:{TokenBuilder:r(()=>new h,"TokenBuilder"),ValueConverter:r(()=>new A,"ValueConverter")}};function v(t=n){let e=a(u(t),o),c=a(i({shared:e}),s,C);return e.ServiceRegistry.register(c),{shared:e,Architecture:c}}r(v,"createArchitectureServices");export{C as a,v as b}; +//# sourceMappingURL=chunk-6B6J5Z6Z.min.js.map diff --git a/docs/website/public/chunk-6B6J5Z6Z.min.js.map b/docs/website/public/chunk-6B6J5Z6Z.min.js.map new file mode 100644 index 000000000..3bc41d27f --- /dev/null +++ b/docs/website/public/chunk-6B6J5Z6Z.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/@mermaid-js/parser/dist/chunks/mermaid-parser.core/chunk-JEIROHC2.mjs"], + "sourcesContent": ["import {\n AbstractMermaidTokenBuilder,\n AbstractMermaidValueConverter,\n ArchitectureGeneratedModule,\n MermaidGeneratedSharedModule,\n __name\n} from \"./chunk-4KMFLZZN.mjs\";\n\n// src/language/architecture/module.ts\nimport {\n EmptyFileSystem,\n createDefaultCoreModule,\n createDefaultSharedCoreModule,\n inject\n} from \"langium\";\n\n// src/language/architecture/tokenBuilder.ts\nvar ArchitectureTokenBuilder = class extends AbstractMermaidTokenBuilder {\n static {\n __name(this, \"ArchitectureTokenBuilder\");\n }\n constructor() {\n super([\"architecture\"]);\n }\n};\n\n// src/language/architecture/valueConverter.ts\nvar ArchitectureValueConverter = class extends AbstractMermaidValueConverter {\n static {\n __name(this, \"ArchitectureValueConverter\");\n }\n runCustomConverter(rule, input, _cstNode) {\n if (rule.name === \"ARCH_ICON\") {\n return input.replace(/[()]/g, \"\").trim();\n } else if (rule.name === \"ARCH_TEXT_ICON\") {\n return input.replace(/[\"()]/g, \"\");\n } else if (rule.name === \"ARCH_TITLE\") {\n return input.replace(/[[\\]]/g, \"\").trim();\n }\n return void 0;\n }\n};\n\n// src/language/architecture/module.ts\nvar ArchitectureModule = {\n parser: {\n TokenBuilder: /* @__PURE__ */ __name(() => new ArchitectureTokenBuilder(), \"TokenBuilder\"),\n ValueConverter: /* @__PURE__ */ __name(() => new ArchitectureValueConverter(), \"ValueConverter\")\n }\n};\nfunction createArchitectureServices(context = EmptyFileSystem) {\n const shared = inject(\n createDefaultSharedCoreModule(context),\n MermaidGeneratedSharedModule\n );\n const Architecture = inject(\n createDefaultCoreModule({ shared }),\n ArchitectureGeneratedModule,\n ArchitectureModule\n );\n shared.ServiceRegistry.register(Architecture);\n return { shared, Architecture };\n}\n__name(createArchitectureServices, \"createArchitectureServices\");\n\nexport {\n ArchitectureModule,\n createArchitectureServices\n};\n"], + "mappings": "2GAiBA,IAAIA,EAA2B,cAAcC,CAA4B,CACvE,MAAO,CACLC,EAAO,KAAM,0BAA0B,CACzC,CACA,aAAc,CACZ,MAAM,CAAC,cAAc,CAAC,CACxB,CACF,EAGIC,EAA6B,cAAcC,CAA8B,CAC3E,MAAO,CACLF,EAAO,KAAM,4BAA4B,CAC3C,CACA,mBAAmBG,EAAMC,EAAOC,EAAU,CACxC,GAAIF,EAAK,OAAS,YAChB,OAAOC,EAAM,QAAQ,QAAS,EAAE,EAAE,KAAK,EAClC,GAAID,EAAK,OAAS,iBACvB,OAAOC,EAAM,QAAQ,SAAU,EAAE,EAC5B,GAAID,EAAK,OAAS,aACvB,OAAOC,EAAM,QAAQ,SAAU,EAAE,EAAE,KAAK,CAG5C,CACF,EAGIE,EAAqB,CACvB,OAAQ,CACN,aAA8BN,EAAO,IAAM,IAAIF,EAA4B,cAAc,EACzF,eAAgCE,EAAO,IAAM,IAAIC,EAA8B,gBAAgB,CACjG,CACF,EACA,SAASM,EAA2BC,EAAUC,EAAiB,CAC7D,IAAMC,EAASC,EACbC,EAA8BJ,CAAO,EACrCK,CACF,EACMC,EAAeH,EACnBI,EAAwB,CAAE,OAAAL,CAAO,CAAC,EAClCM,EACAV,CACF,EACA,OAAAI,EAAO,gBAAgB,SAASI,CAAY,EACrC,CAAE,OAAAJ,EAAQ,aAAAI,CAAa,CAChC,CACAd,EAAOO,EAA4B,4BAA4B", + "names": ["ArchitectureTokenBuilder", "AbstractMermaidTokenBuilder", "__name", "ArchitectureValueConverter", "AbstractMermaidValueConverter", "rule", "input", "_cstNode", "ArchitectureModule", "createArchitectureServices", "context", "EmptyFileSystem", "shared", "inject", "createDefaultSharedCoreModule", "MermaidGeneratedSharedModule", "Architecture", "createDefaultCoreModule", "ArchitectureGeneratedModule"] +} diff --git a/docs/website/public/chunk-6RTTMAJH.min.js b/docs/website/public/chunk-6RTTMAJH.min.js new file mode 100644 index 000000000..b49c27e64 --- /dev/null +++ b/docs/website/public/chunk-6RTTMAJH.min.js @@ -0,0 +1,2 @@ +import{a as t,b as a,c as o,d as i,e as f,f as e,g as u,h as d,p as s,q as l}from"./chunk-LBFZT66H.min.js";var m=class extends l{static{e(this,"InfoTokenBuilder")}constructor(){super(["info","showInfo"])}},v={parser:{TokenBuilder:e(()=>new m,"TokenBuilder"),ValueConverter:e(()=>new s,"ValueConverter")}};function I(c=i){let r=o(a(c),u),n=o(t({shared:r}),d,v);return r.ServiceRegistry.register(n),{shared:r,Info:n}}e(I,"createInfoServices");export{v as a,I as b}; +//# sourceMappingURL=chunk-6RTTMAJH.min.js.map diff --git a/docs/website/public/chunk-6RTTMAJH.min.js.map b/docs/website/public/chunk-6RTTMAJH.min.js.map new file mode 100644 index 000000000..8117a485d --- /dev/null +++ b/docs/website/public/chunk-6RTTMAJH.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/@mermaid-js/parser/dist/chunks/mermaid-parser.core/chunk-T44TD3VJ.mjs"], + "sourcesContent": ["import {\n AbstractMermaidTokenBuilder,\n CommonValueConverter,\n InfoGeneratedModule,\n MermaidGeneratedSharedModule,\n __name\n} from \"./chunk-4KMFLZZN.mjs\";\n\n// src/language/info/module.ts\nimport {\n EmptyFileSystem,\n createDefaultCoreModule,\n createDefaultSharedCoreModule,\n inject\n} from \"langium\";\n\n// src/language/info/tokenBuilder.ts\nvar InfoTokenBuilder = class extends AbstractMermaidTokenBuilder {\n static {\n __name(this, \"InfoTokenBuilder\");\n }\n constructor() {\n super([\"info\", \"showInfo\"]);\n }\n};\n\n// src/language/info/module.ts\nvar InfoModule = {\n parser: {\n TokenBuilder: /* @__PURE__ */ __name(() => new InfoTokenBuilder(), \"TokenBuilder\"),\n ValueConverter: /* @__PURE__ */ __name(() => new CommonValueConverter(), \"ValueConverter\")\n }\n};\nfunction createInfoServices(context = EmptyFileSystem) {\n const shared = inject(\n createDefaultSharedCoreModule(context),\n MermaidGeneratedSharedModule\n );\n const Info = inject(\n createDefaultCoreModule({ shared }),\n InfoGeneratedModule,\n InfoModule\n );\n shared.ServiceRegistry.register(Info);\n return { shared, Info };\n}\n__name(createInfoServices, \"createInfoServices\");\n\nexport {\n InfoModule,\n createInfoServices\n};\n"], + "mappings": "2GAiBA,IAAIA,EAAmB,cAAcC,CAA4B,CAC/D,MAAO,CACLC,EAAO,KAAM,kBAAkB,CACjC,CACA,aAAc,CACZ,MAAM,CAAC,OAAQ,UAAU,CAAC,CAC5B,CACF,EAGIC,EAAa,CACf,OAAQ,CACN,aAA8BD,EAAO,IAAM,IAAIF,EAAoB,cAAc,EACjF,eAAgCE,EAAO,IAAM,IAAIE,EAAwB,gBAAgB,CAC3F,CACF,EACA,SAASC,EAAmBC,EAAUC,EAAiB,CACrD,IAAMC,EAASC,EACbC,EAA8BJ,CAAO,EACrCK,CACF,EACMC,EAAOH,EACXI,EAAwB,CAAE,OAAAL,CAAO,CAAC,EAClCM,EACAX,CACF,EACA,OAAAK,EAAO,gBAAgB,SAASI,CAAI,EAC7B,CAAE,OAAAJ,EAAQ,KAAAI,CAAK,CACxB,CACAV,EAAOG,EAAoB,oBAAoB", + "names": ["InfoTokenBuilder", "AbstractMermaidTokenBuilder", "__name", "InfoModule", "CommonValueConverter", "createInfoServices", "context", "EmptyFileSystem", "shared", "inject", "createDefaultSharedCoreModule", "MermaidGeneratedSharedModule", "Info", "createDefaultCoreModule", "InfoGeneratedModule"] +} diff --git a/docs/website/public/chunk-6TVUEPFY.min.js b/docs/website/public/chunk-6TVUEPFY.min.js new file mode 100644 index 000000000..2ae70950f --- /dev/null +++ b/docs/website/public/chunk-6TVUEPFY.min.js @@ -0,0 +1,2 @@ +import{a as js,d as tu}from"./chunk-OSRY5VT3.min.js";var ui=js((er,nr)=>{(function(t,e){typeof er=="object"&&typeof nr<"u"?nr.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs=e()})(er,(function(){"use strict";var t=1e3,e=6e4,n=36e5,r="millisecond",i="second",o="minute",a="hour",s="day",f="week",u="month",c="quarter",h="year",l="date",p="Invalid Date",x=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,b=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(y){var m=["th","st","nd","rd"],d=y%100;return"["+y+(m[(d-20)%10]||m[d]||m[0])+"]"}},T=function(y,m,d){var k=String(y);return!k||k.length>=m?y:""+Array(m+1-k.length).join(d)+y},I={s:T,z:function(y){var m=-y.utcOffset(),d=Math.abs(m),k=Math.floor(d/60),g=d%60;return(m<=0?"+":"-")+T(k,2,"0")+":"+T(g,2,"0")},m:function y(m,d){if(m.date()1)return y(D[0])}else{var R=m.name;N[R]=m,g=R}return!k&&g&&(S=g),g||!k&&S},F=function(y,m){if(v(y))return y.clone();var d=typeof m=="object"?m:{};return d.date=y,d.args=arguments,new H(d)},O=I;O.l=P,O.i=v,O.w=function(y,m){return F(y,{locale:m.$L,utc:m.$u,x:m.$x,$offset:m.$offset})};var H=(function(){function y(d){this.$L=P(d.locale,null,!0),this.parse(d),this.$x=this.$x||d.x||{},this[$]=!0}var m=y.prototype;return m.parse=function(d){this.$d=(function(k){var g=k.date,A=k.utc;if(g===null)return new Date(NaN);if(O.u(g))return new Date;if(g instanceof Date)return new Date(g);if(typeof g=="string"&&!/Z$/i.test(g)){var D=g.match(x);if(D){var R=D[2]-1||0,z=(D[7]||"0").substring(0,3);return A?new Date(Date.UTC(D[1],R,D[3]||1,D[4]||0,D[5]||0,D[6]||0,z)):new Date(D[1],R,D[3]||1,D[4]||0,D[5]||0,D[6]||0,z)}}return new Date(g)})(d),this.init()},m.init=function(){var d=this.$d;this.$y=d.getFullYear(),this.$M=d.getMonth(),this.$D=d.getDate(),this.$W=d.getDay(),this.$H=d.getHours(),this.$m=d.getMinutes(),this.$s=d.getSeconds(),this.$ms=d.getMilliseconds()},m.$utils=function(){return O},m.isValid=function(){return this.$d.toString()!==p},m.isSame=function(d,k){var g=F(d);return this.startOf(k)<=g&&g<=this.endOf(k)},m.isAfter=function(d,k){return F(d)fi(t,"name",{value:e,configurable:!0}),Wh=(t,e)=>{for(var n in e)fi(t,n,{get:e[n],enumerable:!0})},Tt={trace:0,debug:1,info:2,warn:3,error:4,fatal:5},ct={trace:Ot((...t)=>{},"trace"),debug:Ot((...t)=>{},"debug"),info:Ot((...t)=>{},"info"),warn:Ot((...t)=>{},"warn"),error:Ot((...t)=>{},"error"),fatal:Ot((...t)=>{},"fatal")},Vh=Ot(function(t="fatal"){let e=Tt.fatal;typeof t=="string"?t.toLowerCase()in Tt&&(e=Tt[t]):typeof t=="number"&&(e=t),ct.trace=()=>{},ct.debug=()=>{},ct.info=()=>{},ct.warn=()=>{},ct.error=()=>{},ct.fatal=()=>{},e<=Tt.fatal&&(ct.fatal=console.error?console.error.bind(console,ht("FATAL"),"color: orange"):console.log.bind(console,"\x1B[35m",ht("FATAL"))),e<=Tt.error&&(ct.error=console.error?console.error.bind(console,ht("ERROR"),"color: orange"):console.log.bind(console,"\x1B[31m",ht("ERROR"))),e<=Tt.warn&&(ct.warn=console.warn?console.warn.bind(console,ht("WARN"),"color: orange"):console.log.bind(console,"\x1B[33m",ht("WARN"))),e<=Tt.info&&(ct.info=console.info?console.info.bind(console,ht("INFO"),"color: lightblue"):console.log.bind(console,"\x1B[34m",ht("INFO"))),e<=Tt.debug&&(ct.debug=console.debug?console.debug.bind(console,ht("DEBUG"),"color: lightgreen"):console.log.bind(console,"\x1B[32m",ht("DEBUG"))),e<=Tt.trace&&(ct.trace=console.debug?console.debug.bind(console,ht("TRACE"),"color: lightgreen"):console.log.bind(console,"\x1B[32m",ht("TRACE")))},"setLogLevel"),ht=Ot(t=>`%c${(0,li.default)().format("ss.SSS")} : ${t} : `,"format");function ci(t,e){let n;if(e===void 0)for(let r of t)r!=null&&(n=r)&&(n=r);else{let r=-1;for(let i of t)(i=e(i,++r,t))!=null&&(n=i)&&(n=i)}return n}function hi(t,e){let n;if(e===void 0)for(let r of t)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);else{let r=-1;for(let i of t)(i=e(i,++r,t))!=null&&(n>i||n===void 0&&i>=i)&&(n=i)}return n}function Bt(t,e){return t==null||e==null?NaN:te?1:t>=e?0:NaN}function rr(t,e){return t==null||e==null?NaN:et?1:e>=t?0:NaN}function qt(t){let e,n,r;t.length!==2?(e=Bt,n=(s,f)=>Bt(t(s),f),r=(s,f)=>t(s)-f):(e=t===Bt||t===rr?t:eu,n=t,r=t);function i(s,f,u=0,c=s.length){if(u>>1;n(s[h],f)<0?u=h+1:c=h}while(u>>1;n(s[h],f)<=0?u=h+1:c=h}while(uu&&r(s[h-1],f)>-r(s[h],f)?h-1:h}return{left:i,center:a,right:o}}function eu(){return 0}function ir(t){return t===null?NaN:+t}var pi=qt(Bt),mi=pi.right,nu=pi.left,ru=qt(ir).center,or=mi;var ue=class extends Map{constructor(e,n=au){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),e!=null)for(let[r,i]of e)this.set(r,i)}get(e){return super.get(di(this,e))}has(e){return super.has(di(this,e))}set(e,n){return super.set(iu(this,e),n)}delete(e){return super.delete(ou(this,e))}};function di({_intern:t,_key:e},n){let r=e(n);return t.has(r)?t.get(r):n}function iu({_intern:t,_key:e},n){let r=e(n);return t.has(r)?t.get(r):(t.set(r,n),n)}function ou({_intern:t,_key:e},n){let r=e(n);return t.has(r)&&(n=t.get(r),t.delete(r)),n}function au(t){return t!==null&&typeof t=="object"?t.valueOf():t}var su=Math.sqrt(50),uu=Math.sqrt(10),fu=Math.sqrt(2);function rn(t,e,n){let r=(e-t)/Math.max(0,n),i=Math.floor(Math.log10(r)),o=r/Math.pow(10,i),a=o>=su?10:o>=uu?5:o>=fu?2:1,s,f,u;return i<0?(u=Math.pow(10,-i)/a,s=Math.round(t*u),f=Math.round(e*u),s/ue&&--f,u=-u):(u=Math.pow(10,i)*a,s=Math.round(t/u),f=Math.round(e/u),s*ue&&--f),f0))return[];if(t===e)return[t];let r=e=i))return[];let s=o-i+1,f=new Array(s);if(r)if(a<0)for(let u=0;u+t(e)}function pu(t,e){return e=Math.max(0,t.bandwidth()-e*2)/2,t.round()&&(e=Math.round(e)),n=>+t(n)+e}function mu(){return!this.__axis}function gi(t,e){var n=[],r=null,i=null,o=6,a=6,s=3,f=typeof window<"u"&&window.devicePixelRatio>1?0:.5,u=t===un||t===sn?-1:1,c=t===sn||t===ar?"x":"y",h=t===un||t===sr?lu:cu;function l(p){var x=r??(e.ticks?e.ticks.apply(e,n):e.domain()),b=i??(e.tickFormat?e.tickFormat.apply(e,n):xi),M=Math.max(o,0)+s,T=e.range(),I=+T[0]+f,S=+T[T.length-1]+f,N=(e.bandwidth?pu:hu)(e.copy(),f),$=p.selection?p.selection():p,v=$.selectAll(".domain").data([null]),P=$.selectAll(".tick").data(x,e).order(),F=P.exit(),O=P.enter().append("g").attr("class","tick"),H=P.select("line"),C=P.select("text");v=v.merge(v.enter().insert("path",".tick").attr("class","domain").attr("stroke","currentColor")),P=P.merge(O),H=H.merge(O.append("line").attr("stroke","currentColor").attr(c+"2",u*o)),C=C.merge(O.append("text").attr("fill","currentColor").attr(c,u*M).attr("dy",t===un?"0em":t===sr?"0.71em":"0.32em")),p!==$&&(v=v.transition(p),P=P.transition(p),H=H.transition(p),C=C.transition(p),F=F.transition(p).attr("opacity",_i).attr("transform",function(y){return isFinite(y=N(y))?h(y+f):this.getAttribute("transform")}),O.attr("opacity",_i).attr("transform",function(y){var m=this.parentNode.__axis;return h((m&&isFinite(m=m(y))?m:N(y))+f)})),F.remove(),v.attr("d",t===sn||t===ar?a?"M"+u*a+","+I+"H"+f+"V"+S+"H"+u*a:"M"+f+","+I+"V"+S:a?"M"+I+","+u*a+"V"+f+"H"+S+"V"+u*a:"M"+I+","+f+"H"+S),P.attr("opacity",1).attr("transform",function(y){return h(N(y)+f)}),H.attr(c+"2",u*o),C.attr(c,u*M).text(b),$.filter(mu).attr("fill","none").attr("font-size",10).attr("font-family","sans-serif").attr("text-anchor",t===ar?"start":t===sn?"end":"middle"),$.each(function(){this.__axis=N})}return l.scale=function(p){return arguments.length?(e=p,l):e},l.ticks=function(){return n=Array.from(arguments),l},l.tickArguments=function(p){return arguments.length?(n=p==null?[]:Array.from(p),l):n.slice()},l.tickValues=function(p){return arguments.length?(r=p==null?null:Array.from(p),l):r&&r.slice()},l.tickFormat=function(p){return arguments.length?(i=p,l):i},l.tickSize=function(p){return arguments.length?(o=a=+p,l):o},l.tickSizeInner=function(p){return arguments.length?(o=+p,l):o},l.tickSizeOuter=function(p){return arguments.length?(a=+p,l):a},l.tickPadding=function(p){return arguments.length?(s=+p,l):s},l.offset=function(p){return arguments.length?(f=+p,l):f},l}function du(t){return gi(un,t)}function xu(t){return gi(sr,t)}function _u(){}function Wt(t){return t==null?_u:function(){return this.querySelector(t)}}function yi(t){typeof t!="function"&&(t=Wt(t));for(var e=this._groups,n=e.length,r=new Array(n),i=0;i=S&&(S=I+1);!($=M[S])&&++S=0;)(a=r[i])&&(o&&a.compareDocumentPosition(o)^4&&o.parentNode.insertBefore(a,o),o=a);return this}function $i(t){t||(t=Du);function e(h,l){return h&&l?t(h.__data__,l.__data__):!h-!l}for(var n=this._groups,r=n.length,i=new Array(r),o=0;oe?1:t>=e?0:NaN}function Oi(){var t=arguments[0];return arguments[0]=this,t.apply(null,arguments),this}function Ii(){return Array.from(this)}function Ei(){for(var t=this._groups,e=0,n=t.length;e=0&&(e=t.slice(0,n))!=="xmlns"&&(t=t.slice(n+1)),fr.hasOwnProperty(e)?{space:fr[e],local:t}:t}function $u(t){return function(){this.removeAttribute(t)}}function Ou(t){return function(){this.removeAttributeNS(t.space,t.local)}}function Iu(t,e){return function(){this.setAttribute(t,e)}}function Eu(t,e){return function(){this.setAttributeNS(t.space,t.local,e)}}function Ru(t,e){return function(){var n=e.apply(this,arguments);n==null?this.removeAttribute(t):this.setAttribute(t,n)}}function Pu(t,e){return function(){var n=e.apply(this,arguments);n==null?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,n)}}function Fi(t,e){var n=kt(t);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((e==null?n.local?Ou:$u:typeof e=="function"?n.local?Pu:Ru:n.local?Eu:Iu)(n,e))}function hn(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function Yu(t){return function(){this.style.removeProperty(t)}}function Fu(t,e,n){return function(){this.style.setProperty(t,e,n)}}function Uu(t,e,n){return function(){var r=e.apply(this,arguments);r==null?this.style.removeProperty(t):this.style.setProperty(t,r,n)}}function Ui(t,e,n){return arguments.length>1?this.each((e==null?Yu:typeof e=="function"?Uu:Fu)(t,e,n??"")):It(this.node(),t)}function It(t,e){return t.style.getPropertyValue(e)||hn(t).getComputedStyle(t,null).getPropertyValue(e)}function zu(t){return function(){delete this[t]}}function Lu(t,e){return function(){this[t]=e}}function Hu(t,e){return function(){var n=e.apply(this,arguments);n==null?delete this[t]:this[t]=n}}function zi(t,e){return arguments.length>1?this.each((e==null?zu:typeof e=="function"?Hu:Lu)(t,e)):this.node()[t]}function Li(t){return t.trim().split(/^|\s+/)}function lr(t){return t.classList||new Hi(t)}function Hi(t){this._node=t,this._names=Li(t.getAttribute("class")||"")}Hi.prototype={add:function(t){var e=this._names.indexOf(t);e<0&&(this._names.push(t),this._node.setAttribute("class",this._names.join(" ")))},remove:function(t){var e=this._names.indexOf(t);e>=0&&(this._names.splice(e,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};function Bi(t,e){for(var n=lr(t),r=-1,i=e.length;++r=0&&(n=e.slice(r+1),e=e.slice(0,r)),{type:e,name:n}})}function ff(t){return function(){var e=this.__on;if(e){for(var n=0,r=-1,i=e.length,o;n>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):n===8?mn(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):n===4?mn(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|e&240,((e&15)<<4|e&15)/255):null):(e=xf.exec(t))?new tt(e[1],e[2],e[3],1):(e=_f.exec(t))?new tt(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=gf.exec(t))?mn(e[1],e[2],e[3],e[4]):(e=yf.exec(t))?mn(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=vf.exec(t))?ho(e[1],e[2]/100,e[3]/100,1):(e=wf.exec(t))?ho(e[1],e[2]/100,e[3]/100,e[4]):ao.hasOwnProperty(t)?fo(ao[t]):t==="transparent"?new tt(NaN,NaN,NaN,0):null}function fo(t){return new tt(t>>16&255,t>>8&255,t&255,1)}function mn(t,e,n,r){return r<=0&&(t=e=n=NaN),new tt(t,e,n,r)}function pr(t){return t instanceof Et||(t=xt(t)),t?(t=t.rgb(),new tt(t.r,t.g,t.b,t.opacity)):new tt}function he(t,e,n,r){return arguments.length===1?pr(t):new tt(t,e,n,r??1)}function tt(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}Vt(tt,he,le(Et,{brighter(t){return t=t==null?xn:Math.pow(xn,t),new tt(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?Ee:Math.pow(Ee,t),new tt(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new tt(Gt(this.r),Gt(this.g),Gt(this.b),_n(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:lo,formatHex:lo,formatHex8:Tf,formatRgb:co,toString:co}));function lo(){return`#${Xt(this.r)}${Xt(this.g)}${Xt(this.b)}`}function Tf(){return`#${Xt(this.r)}${Xt(this.g)}${Xt(this.b)}${Xt((isNaN(this.opacity)?1:this.opacity)*255)}`}function co(){let t=_n(this.opacity);return`${t===1?"rgb(":"rgba("}${Gt(this.r)}, ${Gt(this.g)}, ${Gt(this.b)}${t===1?")":`, ${t})`}`}function _n(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function Gt(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function Xt(t){return t=Gt(t),(t<16?"0":"")+t.toString(16)}function ho(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new dt(t,e,n,r)}function mo(t){if(t instanceof dt)return new dt(t.h,t.s,t.l,t.opacity);if(t instanceof Et||(t=xt(t)),!t)return new dt;if(t instanceof dt)return t;t=t.rgb();var e=t.r/255,n=t.g/255,r=t.b/255,i=Math.min(e,n,r),o=Math.max(e,n,r),a=NaN,s=o-i,f=(o+i)/2;return s?(e===o?a=(n-r)/s+(n0&&f<1?0:a,new dt(a,s,f,t.opacity)}function xo(t,e,n,r){return arguments.length===1?mo(t):new dt(t,e,n,r??1)}function dt(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}Vt(dt,xo,le(Et,{brighter(t){return t=t==null?xn:Math.pow(xn,t),new dt(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?Ee:Math.pow(Ee,t),new dt(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+(this.h<0)*360,e=isNaN(t)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*e,i=2*n-r;return new tt(hr(t>=240?t-240:t+120,i,r),hr(t,i,r),hr(t<120?t+240:t-120,i,r),this.opacity)},clamp(){return new dt(po(this.h),dn(this.s),dn(this.l),_n(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let t=_n(this.opacity);return`${t===1?"hsl(":"hsla("}${po(this.h)}, ${dn(this.s)*100}%, ${dn(this.l)*100}%${t===1?")":`, ${t})`}`}}));function po(t){return t=(t||0)%360,t<0?t+360:t}function dn(t){return Math.max(0,Math.min(1,t||0))}function hr(t,e,n){return(t<60?e+(n-e)*t/60:t<180?n:t<240?e+(n-e)*(240-t)/60:e)*255}var _o=Math.PI/180,go=180/Math.PI;var gn=18,yo=.96422,vo=1,wo=.82521,bo=4/29,pe=6/29,Mo=3*pe*pe,kf=pe*pe*pe;function To(t){if(t instanceof vt)return new vt(t.l,t.a,t.b,t.opacity);if(t instanceof Ct)return ko(t);t instanceof tt||(t=pr(t));var e=_r(t.r),n=_r(t.g),r=_r(t.b),i=mr((.2225045*e+.7168786*n+.0606169*r)/vo),o,a;return e===n&&n===r?o=a=i:(o=mr((.4360747*e+.3850649*n+.1430804*r)/yo),a=mr((.0139322*e+.0971045*n+.7141733*r)/wo)),new vt(116*i-16,500*(o-i),200*(i-a),t.opacity)}function gr(t,e,n,r){return arguments.length===1?To(t):new vt(t,e,n,r??1)}function vt(t,e,n,r){this.l=+t,this.a=+e,this.b=+n,this.opacity=+r}Vt(vt,gr,le(Et,{brighter(t){return new vt(this.l+gn*(t??1),this.a,this.b,this.opacity)},darker(t){return new vt(this.l-gn*(t??1),this.a,this.b,this.opacity)},rgb(){var t=(this.l+16)/116,e=isNaN(this.a)?t:t+this.a/500,n=isNaN(this.b)?t:t-this.b/200;return e=yo*dr(e),t=vo*dr(t),n=wo*dr(n),new tt(xr(3.1338561*e-1.6168667*t-.4906146*n),xr(-.9787684*e+1.9161415*t+.033454*n),xr(.0719453*e-.2289914*t+1.4052427*n),this.opacity)}}));function mr(t){return t>kf?Math.pow(t,1/3):t/Mo+bo}function dr(t){return t>pe?t*t*t:Mo*(t-bo)}function xr(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function _r(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Sf(t){if(t instanceof Ct)return new Ct(t.h,t.c,t.l,t.opacity);if(t instanceof vt||(t=To(t)),t.a===0&&t.b===0)return new Ct(NaN,0()=>t;function So(t,e){return function(n){return t+n*e}}function Cf(t,e,n){return t=Math.pow(t,n),e=Math.pow(e,n)-t,n=1/n,function(r){return Math.pow(t+r*e,n)}}function Co(t,e){var n=e-t;return n?So(t,n>180||n<-180?n-360*Math.round(n/360):n):me(isNaN(t)?e:t)}function No(t){return(t=+t)==1?Nt:function(e,n){return n-e?Cf(e,n,t):me(isNaN(e)?n:e)}}function Nt(t,e){var n=e-t;return n?So(t,n):me(isNaN(t)?e:t)}function Ao(t){return function(e,n){var r=t((e=Pe(e)).h,(n=Pe(n)).h),i=Nt(e.c,n.c),o=Nt(e.l,n.l),a=Nt(e.opacity,n.opacity);return function(s){return e.h=r(s),e.c=i(s),e.l=o(s),e.opacity=a(s),e+""}}}var Nf=Ao(Co),Af=Ao(Nt);function yr(t,e,n,r,i){var o=t*t,a=o*t;return((1-3*t+3*o-a)*e+(4-6*o+3*a)*n+(1+3*t+3*o-3*a)*r+a*i)/6}function Do(t){var e=t.length-1;return function(n){var r=n<=0?n=0:n>=1?(n=1,e-1):Math.floor(n*e),i=t[r],o=t[r+1],a=r>0?t[r-1]:2*i-o,s=rn&&(o=e.slice(n,o),s[a]?s[a]+=o:s[++a]=o),(r=r[0])===(i=i[0])?s[a]?s[a]+=i:s[++a]=i:(s[++a]=null,f.push({i:a,x:et(r,i)})),n=vr.lastIndex;return n180?c+=360:c-u>180&&(u+=360),l.push({i:h.push(i(h)+"rotate(",null,r)-2,x:et(u,c)})):c&&h.push(i(h)+"rotate("+c+r)}function s(u,c,h,l){u!==c?l.push({i:h.push(i(h)+"skewX(",null,r)-2,x:et(u,c)}):c&&h.push(i(h)+"skewX("+c+r)}function f(u,c,h,l,p,x){if(u!==h||c!==l){var b=p.push(i(p)+"scale(",null,",",null,")");x.push({i:b-4,x:et(u,h)},{i:b-2,x:et(c,l)})}else(h!==1||l!==1)&&p.push(i(p)+"scale("+h+","+l+")")}return function(u,c){var h=[],l=[];return u=t(u),c=t(c),o(u.translateX,u.translateY,c.translateX,c.translateY,h,l),a(u.rotate,c.rotate,h,l),s(u.skewX,c.skewX,h,l),f(u.scaleX,u.scaleY,c.scaleX,c.scaleY,h,l),u=c=null,function(p){for(var x=-1,b=l.length,M;++x=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function Kt(t,e){if((n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var n,r=t.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+t.slice(n+1)]}function wt(t){return t=Kt(Math.abs(t)),t?t[1]:NaN}function Bo(t,e){return function(n,r){for(var i=n.length,o=[],a=0,s=t[0],f=0;i>0&&s>0&&(f+s+1>r&&(s=Math.max(1,r-f)),o.push(n.substring(i-=s,i+s)),!((f+=s+1)>r));)s=t[a=(a+1)%t.length];return o.reverse().join(e)}}function qo(t){return function(e){return e.replace(/[0-9]/g,function(n){return t[+n]})}}var Ef=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Rt(t){if(!(e=Ef.exec(t)))throw new Error("invalid format: "+t);var e;return new wn({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}Rt.prototype=wn.prototype;function wn(t){this.fill=t.fill===void 0?" ":t.fill+"",this.align=t.align===void 0?">":t.align+"",this.sign=t.sign===void 0?"-":t.sign+"",this.symbol=t.symbol===void 0?"":t.symbol+"",this.zero=!!t.zero,this.width=t.width===void 0?void 0:+t.width,this.comma=!!t.comma,this.precision=t.precision===void 0?void 0:+t.precision,this.trim=!!t.trim,this.type=t.type===void 0?"":t.type+""}wn.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function Wo(t){t:for(var e=t.length,n=1,r=-1,i;n0&&(r=0);break}return r>0?t.slice(0,r)+t.slice(i+1):t}var Sr;function Vo(t,e){var n=Kt(t,e);if(!n)return t+"";var r=n[0],i=n[1],o=i-(Sr=Math.max(-8,Math.min(8,Math.floor(i/3)))*3)+1,a=r.length;return o===a?r:o>a?r+new Array(o-a+1).join("0"):o>0?r.slice(0,o)+"."+r.slice(o):"0."+new Array(1-o).join("0")+Kt(t,Math.max(0,e+o-1))[0]}function Cr(t,e){var n=Kt(t,e);if(!n)return t+"";var r=n[0],i=n[1];return i<0?"0."+new Array(-i).join("0")+r:r.length>i+1?r.slice(0,i+1)+"."+r.slice(i+1):r+new Array(i-r.length+2).join("0")}var Nr={"%":(t,e)=>(t*100).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:Ho,e:(t,e)=>t.toExponential(e),f:(t,e)=>t.toFixed(e),g:(t,e)=>t.toPrecision(e),o:t=>Math.round(t).toString(8),p:(t,e)=>Cr(t*100,e),r:Cr,s:Vo,X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function Ar(t){return t}var Xo=Array.prototype.map,Go=["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"];function Zo(t){var e=t.grouping===void 0||t.thousands===void 0?Ar:Bo(Xo.call(t.grouping,Number),t.thousands+""),n=t.currency===void 0?"":t.currency[0]+"",r=t.currency===void 0?"":t.currency[1]+"",i=t.decimal===void 0?".":t.decimal+"",o=t.numerals===void 0?Ar:qo(Xo.call(t.numerals,String)),a=t.percent===void 0?"%":t.percent+"",s=t.minus===void 0?"\u2212":t.minus+"",f=t.nan===void 0?"NaN":t.nan+"";function u(h){h=Rt(h);var l=h.fill,p=h.align,x=h.sign,b=h.symbol,M=h.zero,T=h.width,I=h.comma,S=h.precision,N=h.trim,$=h.type;$==="n"?(I=!0,$="g"):Nr[$]||(S===void 0&&(S=12),N=!0,$="g"),(M||l==="0"&&p==="=")&&(M=!0,l="0",p="=");var v=b==="$"?n:b==="#"&&/[boxX]/.test($)?"0"+$.toLowerCase():"",P=b==="$"?r:/[%p]/.test($)?a:"",F=Nr[$],O=/[defgprs%]/.test($);S=S===void 0?6:/[gprs]/.test($)?Math.max(1,Math.min(21,S)):Math.max(0,Math.min(20,S));function H(C){var y=v,m=P,d,k,g;if($==="c")m=F(C)+m,C="";else{C=+C;var A=C<0||1/C<0;if(C=isNaN(C)?f:F(Math.abs(C),S),N&&(C=Wo(C)),A&&+C==0&&x!=="+"&&(A=!1),y=(A?x==="("?x:s:x==="-"||x==="("?"":x)+y,m=($==="s"?Go[8+Sr/3]:"")+m+(A&&x==="("?")":""),O){for(d=-1,k=C.length;++dg||g>57){m=(g===46?i+C.slice(d+1):C.slice(d))+m,C=C.slice(0,d);break}}}I&&!M&&(C=e(C,1/0));var D=y.length+C.length+m.length,R=D>1)+y+C+m+R.slice(D);break;default:C=R+y+C+m;break}return o(C)}return H.toString=function(){return h+""},H}function c(h,l){var p=u((h=Rt(h),h.type="f",h)),x=Math.max(-8,Math.min(8,Math.floor(wt(l)/3)))*3,b=Math.pow(10,-x),M=Go[8+x/3];return function(T){return p(b*T)+M}}return{format:u,formatPrefix:c}}var bn,Mn,Tn;Dr({thousands:",",grouping:[3],currency:["$",""]});function Dr(t){return bn=Zo(t),Mn=bn.format,Tn=bn.formatPrefix,bn}function $r(t){return Math.max(0,-wt(Math.abs(t)))}function Or(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(wt(e)/3)))*3-wt(Math.abs(t)))}function Ir(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,wt(e)-wt(t))+1}function Rf(t){var e=0,n=t.children,r=n&&n.length;if(!r)e=1;else for(;--r>=0;)e+=n[r].value;t.value=e}function Qo(){return this.eachAfter(Rf)}function Ko(t,e){let n=-1;for(let r of this)t.call(e,r,++n,this);return this}function Jo(t,e){for(var n=this,r=[n],i,o,a=-1;n=r.pop();)if(t.call(e,n,++a,this),i=n.children)for(o=i.length-1;o>=0;--o)r.push(i[o]);return this}function jo(t,e){for(var n=this,r=[n],i=[],o,a,s,f=-1;n=r.pop();)if(i.push(n),o=n.children)for(a=0,s=o.length;a=0;)n+=r[i].value;e.value=n})}function na(t){return this.eachBefore(function(e){e.children&&e.children.sort(t)})}function ra(t){for(var e=this,n=Pf(e,t),r=[e];e!==n;)e=e.parent,r.push(e);for(var i=r.length;t!==n;)r.splice(i,0,t),t=t.parent;return r}function Pf(t,e){if(t===e)return t;var n=t.ancestors(),r=e.ancestors(),i=null;for(t=n.pop(),e=r.pop();t===e;)i=t,t=n.pop(),e=r.pop();return i}function ia(){for(var t=this,e=[t];t=t.parent;)e.push(t);return e}function oa(){return Array.from(this)}function aa(){var t=[];return this.eachBefore(function(e){e.children||t.push(e)}),t}function sa(){var t=this,e=[];return t.each(function(n){n!==t&&e.push({source:n.parent,target:n})}),e}function*ua(){var t=this,e,n=[t],r,i,o;do for(e=n.reverse(),n=[];t=e.pop();)if(yield t,r=t.children)for(i=0,o=r.length;i=0;--s)i.push(o=a[s]=new Fe(a[s])),o.parent=r,o.depth=r.depth+1;return n.eachBefore(Lf)}function Yf(){return kn(this).eachBefore(zf)}function Ff(t){return t.children}function Uf(t){return Array.isArray(t)?t[1]:null}function zf(t){t.data.value!==void 0&&(t.value=t.data.value),t.data=t.data.data}function Lf(t){var e=0;do t.height=e;while((t=t.parent)&&t.height<++e)}function Fe(t){this.data=t,this.depth=this.height=0,this.parent=null}Fe.prototype=kn.prototype={constructor:Fe,count:Qo,each:Ko,eachAfter:jo,eachBefore:Jo,find:ta,sum:ea,sort:na,path:ra,ancestors:ia,descendants:oa,leaves:aa,links:sa,copy:Yf,[Symbol.iterator]:ua};function fa(t){t.x0=Math.round(t.x0),t.y0=Math.round(t.y0),t.x1=Math.round(t.x1),t.y1=Math.round(t.y1)}function la(t,e,n,r,i){for(var o=t.children,a,s=-1,f=o.length,u=t.value&&(r-e)/t.value;++sI&&(I=u),v=M*M*$,S=Math.max(I/v,v/T),S>N){M-=u;break}N=S}a.push(f={value:M,dice:p1?r:1)},n})(Hf);function pa(t){if(typeof t!="function")throw new Error;return t}function de(){return 0}function xe(t){return function(){return t}}function qf(){var t=ha,e=!1,n=1,r=1,i=[0],o=de,a=de,s=de,f=de,u=de;function c(l){return l.x0=l.y0=0,l.x1=n,l.y1=r,l.eachBefore(h),i=[0],e&&l.eachBefore(fa),l}function h(l){var p=i[l.depth],x=l.x0+p,b=l.y0+p,M=l.x1-p,T=l.y1-p;Me&&(n=t,t=e,e=n),function(r){return Math.max(t,Math.min(e,r))}}function Vf(t,e,n){var r=t[0],i=t[1],o=e[0],a=e[1];return i2?Xf:Vf,f=u=null,h}function h(l){return l==null||isNaN(l=+l)?o:(f||(f=s(t.map(r),e,n)))(r(a(l)))}return h.invert=function(l){return a(i((u||(u=s(e,t.map(r),et)))(l)))},h.domain=function(l){return arguments.length?(t=Array.from(l,Yr),c()):t.slice()},h.range=function(l){return arguments.length?(e=Array.from(l),c()):e.slice()},h.rangeRound=function(l){return e=Array.from(l),n=br,c()},h.clamp=function(l){return arguments.length?(a=l?!0:_e,c()):a!==_e},h.interpolate=function(l){return arguments.length?(n=l,c()):n},h.unknown=function(l){return arguments.length?(o=l,h):o},function(l,p){return r=l,i=p,c()}}function ze(){return Gf()(_e,_e)}function Ur(t,e,n,r){var i=fe(t,e,n),o;switch(r=Rt(r??",f"),r.type){case"s":{var a=Math.max(Math.abs(t),Math.abs(e));return r.precision==null&&!isNaN(o=Or(i,a))&&(r.precision=o),Tn(r,a)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(o=Ir(i,Math.max(Math.abs(t),Math.abs(e))))&&(r.precision=o-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(o=$r(i))&&(r.precision=o-(r.type==="%")*2);break}}return Mn(r)}function Zf(t){var e=t.domain;return t.ticks=function(n){var r=e();return on(r[0],r[r.length-1],n??10)},t.tickFormat=function(n,r){var i=e();return Ur(i[0],i[i.length-1],n??10,r)},t.nice=function(n){n==null&&(n=10);var r=e(),i=0,o=r.length-1,a=r[i],s=r[o],f,u,c=10;for(s0;){if(u=De(a,s,n),u===f)return r[i]=a,r[o]=s,e(r);if(u>0)a=Math.floor(a/u)*u,s=Math.ceil(s/u)*u;else if(u<0)a=Math.ceil(a*u)/u,s=Math.floor(s*u)/u;else break;f=u}return t},t}function zr(){var t=ze();return t.copy=function(){return Sn(t,zr())},Pt.apply(t,arguments),Zf(t)}var Lr=new Date,Hr=new Date;function L(t,e,n,r){function i(o){return t(o=arguments.length===0?new Date:new Date(+o)),o}return i.floor=o=>(t(o=new Date(+o)),o),i.ceil=o=>(t(o=new Date(o-1)),e(o,1),t(o),o),i.round=o=>{let a=i(o),s=i.ceil(o);return o-a(e(o=new Date(+o),a==null?1:Math.floor(a)),o),i.range=(o,a,s)=>{let f=[];if(o=i.ceil(o),s=s==null?1:Math.floor(s),!(o0))return f;let u;do f.push(u=new Date(+o)),e(o,s),t(o);while(uL(a=>{if(a>=a)for(;t(a),!o(a);)a.setTime(a-1)},(a,s)=>{if(a>=a)if(s<0)for(;++s<=0;)for(;e(a,-1),!o(a););else for(;--s>=0;)for(;e(a,1),!o(a););}),n&&(i.count=(o,a)=>(Lr.setTime(+o),Hr.setTime(+a),t(Lr),t(Hr),Math.floor(n(Lr,Hr))),i.every=o=>(o=Math.floor(o),!isFinite(o)||!(o>0)?null:o>1?i.filter(r?a=>r(a)%o===0:a=>i.count(0,a)%o===0):i)),i}var Jt=L(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);Jt.every=t=>(t=Math.floor(t),!isFinite(t)||!(t>0)?null:t>1?L(e=>{e.setTime(Math.floor(e/t)*t)},(e,n)=>{e.setTime(+e+n*t)},(e,n)=>(n-e)/t):Jt);var da=Jt.range;var bt=L(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*1e3)},(t,e)=>(e-t)/1e3,t=>t.getUTCSeconds()),xa=bt.range;var ge=L(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*1e3)},(t,e)=>{t.setTime(+t+e*6e4)},(t,e)=>(e-t)/6e4,t=>t.getMinutes()),Qf=ge.range,Cn=L(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*6e4)},(t,e)=>(e-t)/6e4,t=>t.getUTCMinutes()),Kf=Cn.range;var ye=L(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*1e3-t.getMinutes()*6e4)},(t,e)=>{t.setTime(+t+e*36e5)},(t,e)=>(e-t)/36e5,t=>t.getHours()),Jf=ye.range,Nn=L(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*36e5)},(t,e)=>(e-t)/36e5,t=>t.getUTCHours()),jf=Nn.range;var At=L(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*6e4)/864e5,t=>t.getDate()-1),tl=At.range,He=L(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/864e5,t=>t.getUTCDate()-1),el=He.range,An=L(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/864e5,t=>Math.floor(t/864e5)),nl=An.range;function ee(t){return L(e=>{e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)},(e,n)=>{e.setDate(e.getDate()+n*7)},(e,n)=>(n-e-(n.getTimezoneOffset()-e.getTimezoneOffset())*6e4)/6048e5)}var Dt=ee(0),ve=ee(1),ga=ee(2),ya=ee(3),Yt=ee(4),va=ee(5),wa=ee(6),ba=Dt.range,rl=ve.range,il=ga.range,ol=ya.range,al=Yt.range,sl=va.range,ul=wa.range;function ne(t){return L(e=>{e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)},(e,n)=>{e.setUTCDate(e.getUTCDate()+n*7)},(e,n)=>(n-e)/6048e5)}var re=ne(0),we=ne(1),Ma=ne(2),Ta=ne(3),Ft=ne(4),ka=ne(5),Sa=ne(6),Ca=re.range,fl=we.range,ll=Ma.range,cl=Ta.range,hl=Ft.range,pl=ka.range,ml=Sa.range;var be=L(t=>{t.setDate(1),t.setHours(0,0,0,0)},(t,e)=>{t.setMonth(t.getMonth()+e)},(t,e)=>e.getMonth()-t.getMonth()+(e.getFullYear()-t.getFullYear())*12,t=>t.getMonth()),dl=be.range,Dn=L(t=>{t.setUTCDate(1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCMonth(t.getUTCMonth()+e)},(t,e)=>e.getUTCMonth()-t.getUTCMonth()+(e.getUTCFullYear()-t.getUTCFullYear())*12,t=>t.getUTCMonth()),xl=Dn.range;var ft=L(t=>{t.setMonth(0,1),t.setHours(0,0,0,0)},(t,e)=>{t.setFullYear(t.getFullYear()+e)},(t,e)=>e.getFullYear()-t.getFullYear(),t=>t.getFullYear());ft.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:L(e=>{e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)},(e,n)=>{e.setFullYear(e.getFullYear()+n*t)});var _l=ft.range,_t=L(t=>{t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCFullYear(t.getUTCFullYear()+e)},(t,e)=>e.getUTCFullYear()-t.getUTCFullYear(),t=>t.getUTCFullYear());_t.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:L(e=>{e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,n)=>{e.setUTCFullYear(e.getUTCFullYear()+n*t)});var gl=_t.range;function Aa(t,e,n,r,i,o){let a=[[bt,1,1e3],[bt,5,5*1e3],[bt,15,15*1e3],[bt,30,30*1e3],[o,1,6e4],[o,5,5*6e4],[o,15,15*6e4],[o,30,30*6e4],[i,1,36e5],[i,3,3*36e5],[i,6,6*36e5],[i,12,12*36e5],[r,1,864e5],[r,2,2*864e5],[n,1,6048e5],[e,1,2592e6],[e,3,3*2592e6],[t,1,31536e6]];function s(u,c,h){let l=cM).right(a,l);if(p===a.length)return t.every(fe(u/31536e6,c/31536e6,h));if(p===0)return Jt.every(Math.max(fe(u,c,h),1));let[x,b]=a[l/a[p-1][2]53)return null;"w"in _||(_.w=1),"Z"in _?(B=Vr(Be(_.y,0,1)),st=B.getUTCDay(),B=st>4||st===0?we.ceil(B):we(B),B=He.offset(B,(_.V-1)*7),_.y=B.getUTCFullYear(),_.m=B.getUTCMonth(),_.d=B.getUTCDate()+(_.w+6)%7):(B=Wr(Be(_.y,0,1)),st=B.getDay(),B=st>4||st===0?ve.ceil(B):ve(B),B=At.offset(B,(_.V-1)*7),_.y=B.getFullYear(),_.m=B.getMonth(),_.d=B.getDate()+(_.w+6)%7)}else("W"in _||"U"in _)&&("w"in _||(_.w="u"in _?_.u%7:"W"in _?1:0),st="Z"in _?Vr(Be(_.y,0,1)).getUTCDay():Wr(Be(_.y,0,1)).getDay(),_.m=0,_.d="W"in _?(_.w+6)%7+_.W*7-(st+5)%7:_.w+_.U*7-(st+6)%7);return"Z"in _?(_.H+=_.Z/100|0,_.M+=_.Z%100,Vr(_)):Wr(_)}}function F(w,E,Y,_){for(var ot=0,B=E.length,st=Y.length,ut,Ht;ot=st)return-1;if(ut=E.charCodeAt(ot++),ut===37){if(ut=E.charAt(ot++),Ht=$[ut in Da?E.charAt(ot++):ut],!Ht||(_=Ht(w,Y,_))<0)return-1}else if(ut!=Y.charCodeAt(_++))return-1}return _}function O(w,E,Y){var _=u.exec(E.slice(Y));return _?(w.p=c.get(_[0].toLowerCase()),Y+_[0].length):-1}function H(w,E,Y){var _=p.exec(E.slice(Y));return _?(w.w=x.get(_[0].toLowerCase()),Y+_[0].length):-1}function C(w,E,Y){var _=h.exec(E.slice(Y));return _?(w.w=l.get(_[0].toLowerCase()),Y+_[0].length):-1}function y(w,E,Y){var _=T.exec(E.slice(Y));return _?(w.m=I.get(_[0].toLowerCase()),Y+_[0].length):-1}function m(w,E,Y){var _=b.exec(E.slice(Y));return _?(w.m=M.get(_[0].toLowerCase()),Y+_[0].length):-1}function d(w,E,Y){return F(w,e,E,Y)}function k(w,E,Y){return F(w,n,E,Y)}function g(w,E,Y){return F(w,r,E,Y)}function A(w){return a[w.getDay()]}function D(w){return o[w.getDay()]}function R(w){return f[w.getMonth()]}function z(w){return s[w.getMonth()]}function q(w){return i[+(w.getHours()>=12)]}function V(w){return 1+~~(w.getMonth()/3)}function K(w){return a[w.getUTCDay()]}function lt(w){return o[w.getUTCDay()]}function Z(w){return f[w.getUTCMonth()]}function mt(w){return s[w.getUTCMonth()]}function at(w){return i[+(w.getUTCHours()>=12)]}function G(w){return 1+~~(w.getUTCMonth()/3)}return{format:function(w){var E=v(w+="",S);return E.toString=function(){return w},E},parse:function(w){var E=P(w+="",!1);return E.toString=function(){return w},E},utcFormat:function(w){var E=v(w+="",N);return E.toString=function(){return w},E},utcParse:function(w){var E=P(w+="",!0);return E.toString=function(){return w},E}}}var Da={"-":"",_:" ",0:"0"},J=/^\s*\d+/,bl=/^%/,Ml=/[\\^$*+?|[\]().{}]/g;function U(t,e,n){var r=t<0?"-":"",i=(r?-t:t)+"",o=i.length;return r+(o[e.toLowerCase(),n]))}function kl(t,e,n){var r=J.exec(e.slice(n,n+1));return r?(t.w=+r[0],n+r[0].length):-1}function Sl(t,e,n){var r=J.exec(e.slice(n,n+1));return r?(t.u=+r[0],n+r[0].length):-1}function Cl(t,e,n){var r=J.exec(e.slice(n,n+2));return r?(t.U=+r[0],n+r[0].length):-1}function Nl(t,e,n){var r=J.exec(e.slice(n,n+2));return r?(t.V=+r[0],n+r[0].length):-1}function Al(t,e,n){var r=J.exec(e.slice(n,n+2));return r?(t.W=+r[0],n+r[0].length):-1}function $a(t,e,n){var r=J.exec(e.slice(n,n+4));return r?(t.y=+r[0],n+r[0].length):-1}function Oa(t,e,n){var r=J.exec(e.slice(n,n+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function Dl(t,e,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(n,n+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function $l(t,e,n){var r=J.exec(e.slice(n,n+1));return r?(t.q=r[0]*3-3,n+r[0].length):-1}function Ol(t,e,n){var r=J.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function Ia(t,e,n){var r=J.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function Il(t,e,n){var r=J.exec(e.slice(n,n+3));return r?(t.m=0,t.d=+r[0],n+r[0].length):-1}function Ea(t,e,n){var r=J.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function El(t,e,n){var r=J.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function Rl(t,e,n){var r=J.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function Pl(t,e,n){var r=J.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function Yl(t,e,n){var r=J.exec(e.slice(n,n+6));return r?(t.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function Fl(t,e,n){var r=bl.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function Ul(t,e,n){var r=J.exec(e.slice(n));return r?(t.Q=+r[0],n+r[0].length):-1}function zl(t,e,n){var r=J.exec(e.slice(n));return r?(t.s=+r[0],n+r[0].length):-1}function Ra(t,e){return U(t.getDate(),e,2)}function Ll(t,e){return U(t.getHours(),e,2)}function Hl(t,e){return U(t.getHours()%12||12,e,2)}function Bl(t,e){return U(1+At.count(ft(t),t),e,3)}function za(t,e){return U(t.getMilliseconds(),e,3)}function ql(t,e){return za(t,e)+"000"}function Wl(t,e){return U(t.getMonth()+1,e,2)}function Vl(t,e){return U(t.getMinutes(),e,2)}function Xl(t,e){return U(t.getSeconds(),e,2)}function Gl(t){var e=t.getDay();return e===0?7:e}function Zl(t,e){return U(Dt.count(ft(t)-1,t),e,2)}function La(t){var e=t.getDay();return e>=4||e===0?Yt(t):Yt.ceil(t)}function Ql(t,e){return t=La(t),U(Yt.count(ft(t),t)+(ft(t).getDay()===4),e,2)}function Kl(t){return t.getDay()}function Jl(t,e){return U(ve.count(ft(t)-1,t),e,2)}function jl(t,e){return U(t.getFullYear()%100,e,2)}function tc(t,e){return t=La(t),U(t.getFullYear()%100,e,2)}function ec(t,e){return U(t.getFullYear()%1e4,e,4)}function nc(t,e){var n=t.getDay();return t=n>=4||n===0?Yt(t):Yt.ceil(t),U(t.getFullYear()%1e4,e,4)}function rc(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+U(e/60|0,"0",2)+U(e%60,"0",2)}function Pa(t,e){return U(t.getUTCDate(),e,2)}function ic(t,e){return U(t.getUTCHours(),e,2)}function oc(t,e){return U(t.getUTCHours()%12||12,e,2)}function ac(t,e){return U(1+He.count(_t(t),t),e,3)}function Ha(t,e){return U(t.getUTCMilliseconds(),e,3)}function sc(t,e){return Ha(t,e)+"000"}function uc(t,e){return U(t.getUTCMonth()+1,e,2)}function fc(t,e){return U(t.getUTCMinutes(),e,2)}function lc(t,e){return U(t.getUTCSeconds(),e,2)}function cc(t){var e=t.getUTCDay();return e===0?7:e}function hc(t,e){return U(re.count(_t(t)-1,t),e,2)}function Ba(t){var e=t.getUTCDay();return e>=4||e===0?Ft(t):Ft.ceil(t)}function pc(t,e){return t=Ba(t),U(Ft.count(_t(t),t)+(_t(t).getUTCDay()===4),e,2)}function mc(t){return t.getUTCDay()}function dc(t,e){return U(we.count(_t(t)-1,t),e,2)}function xc(t,e){return U(t.getUTCFullYear()%100,e,2)}function _c(t,e){return t=Ba(t),U(t.getUTCFullYear()%100,e,2)}function gc(t,e){return U(t.getUTCFullYear()%1e4,e,4)}function yc(t,e){var n=t.getUTCDay();return t=n>=4||n===0?Ft(t):Ft.ceil(t),U(t.getUTCFullYear()%1e4,e,4)}function vc(){return"+0000"}function Ya(){return"%"}function Fa(t){return+t}function Ua(t){return Math.floor(+t/1e3)}var Me,$n,qa,Wa,Va;Gr({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function Gr(t){return Me=Xr(t),$n=Me.format,qa=Me.parse,Wa=Me.utcFormat,Va=Me.utcParse,Me}function Zr(t,e){t=t.slice();var n=0,r=t.length-1,i=t[n],o=t[r],a;return o1?0:t<-1?Te:Math.acos(t)}function Kr(t){return t>=1?Ve:t<=-1?-Ve:Math.asin(t)}var Jr=Math.PI,jr=2*Jr,oe=1e-6,Tc=jr-oe;function Ja(t){this._+=t[0];for(let e=1,n=t.length;e=0))throw new Error(`invalid digits: ${t}`);if(e>15)return Ja;let n=10**e;return function(r){this._+=r[0];for(let i=1,o=r.length;ioe)if(!(Math.abs(h*f-u*c)>oe)||!o)this._append`L${this._x1=e},${this._y1=n}`;else{let p=r-a,x=i-s,b=f*f+u*u,M=p*p+x*x,T=Math.sqrt(b),I=Math.sqrt(l),S=o*Math.tan((Jr-Math.acos((b+l-M)/(2*T*I)))/2),N=S/I,$=S/T;Math.abs(N-1)>oe&&this._append`L${e+N*c},${n+N*h}`,this._append`A${o},${o},0,0,${+(h*p>c*x)},${this._x1=e+$*f},${this._y1=n+$*u}`}}arc(e,n,r,i,o,a){if(e=+e,n=+n,r=+r,a=!!a,r<0)throw new Error(`negative radius: ${r}`);let s=r*Math.cos(i),f=r*Math.sin(i),u=e+s,c=n+f,h=1^a,l=a?i-o:o-i;this._x1===null?this._append`M${u},${c}`:(Math.abs(this._x1-u)>oe||Math.abs(this._y1-c)>oe)&&this._append`L${u},${c}`,r&&(l<0&&(l=l%jr+jr),l>Tc?this._append`A${r},${r},0,1,${h},${e-s},${n-f}A${r},${r},0,1,${h},${this._x1=u},${this._y1=c}`:l>oe&&this._append`A${r},${r},0,${+(l>=Jr)},${h},${this._x1=e+r*Math.cos(o)},${this._y1=n+r*Math.sin(o)}`)}rect(e,n,r,i){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+n}h${r=+r}v${+i}h${-r}Z`}toString(){return this._}};function ja(){return new ae}ja.prototype=ae.prototype;function In(t){let e=3;return t.digits=function(n){if(!arguments.length)return e;if(n==null)e=null;else{let r=Math.floor(n);if(!(r>=0))throw new RangeError(`invalid digits: ${n}`);e=r}return t},()=>new ae(e)}function Sc(t){return t.innerRadius}function Cc(t){return t.outerRadius}function Nc(t){return t.startAngle}function Ac(t){return t.endAngle}function Dc(t){return t&&t.padAngle}function $c(t,e,n,r,i,o,a,s){var f=n-t,u=r-e,c=a-i,h=s-o,l=h*f-c*u;if(!(l*ld*d+k*k&&(F=H,O=C),{cx:F,cy:O,x01:-c,y01:-h,x11:F*(i/$-1),y11:O*(i/$-1)}}function Oc(){var t=Sc,e=Cc,n=W(0),r=null,i=Nc,o=Ac,a=Dc,s=null,f=In(u);function u(){var c,h,l=+t.apply(this,arguments),p=+e.apply(this,arguments),x=i.apply(this,arguments)-Ve,b=o.apply(this,arguments)-Ve,M=Qr(b-x),T=b>x;if(s||(s=c=f()),pj))s.moveTo(0,0);else if(M>ke-j)s.moveTo(p*Ut(x),p*gt(x)),s.arc(0,0,p,x,b,!T),l>j&&(s.moveTo(l*Ut(b),l*gt(b)),s.arc(0,0,l,b,x,T));else{var I=x,S=b,N=x,$=b,v=M,P=M,F=a.apply(this,arguments)/2,O=F>j&&(r?+r.apply(this,arguments):ie(l*l+p*p)),H=On(Qr(p-l)/2,+n.apply(this,arguments)),C=H,y=H,m,d;if(O>j){var k=Kr(O/l*gt(F)),g=Kr(O/p*gt(F));(v-=k*2)>j?(k*=T?1:-1,N+=k,$-=k):(v=0,N=$=(x+b)/2),(P-=g*2)>j?(g*=T?1:-1,I+=g,S-=g):(P=0,I=S=(x+b)/2)}var A=p*Ut(I),D=p*gt(I),R=l*Ut($),z=l*gt($);if(H>j){var q=p*Ut(S),V=p*gt(S),K=l*Ut(N),lt=l*gt(N),Z;if(Mj?y>j?(m=En(K,lt,A,D,p,y,T),d=En(q,V,R,z,p,y,T),s.moveTo(m.cx+m.x01,m.cy+m.y01),yj)||!(v>j)?s.lineTo(R,z):C>j?(m=En(R,z,q,V,l,-C,T),d=En(A,D,K,lt,l,-C,T),s.lineTo(m.cx+m.x01,m.cy+m.y01),Ct?1:e>=t?0:NaN}function is(t){return t}function Ec(){var t=is,e=rs,n=null,r=W(0),i=W(ke),o=W(0);function a(s){var f,u=(s=Rn(s)).length,c,h,l=0,p=new Array(u),x=new Array(u),b=+r.apply(this,arguments),M=Math.min(ke,Math.max(-ke,i.apply(this,arguments)-b)),T,I=Math.min(Math.abs(M)/u,o.apply(this,arguments)),S=I*(M<0?-1:1),N;for(f=0;f0&&(l+=N);for(e!=null?p.sort(function($,v){return e(x[$],x[v])}):n!=null&&p.sort(function($,v){return n(s[$],s[v])}),f=0,h=l?(M-u*S)/l:0;f0?N*h:0)+S,x[c]={data:s[c],index:f,value:N,startAngle:b,endAngle:T,padAngle:I};return x}return a.value=function(s){return arguments.length?(t=typeof s=="function"?s:W(+s),a):t},a.sortValues=function(s){return arguments.length?(e=s,n=null,a):e},a.sort=function(s){return arguments.length?(n=s,e=null,a):n},a.startAngle=function(s){return arguments.length?(r=typeof s=="function"?s:W(+s),a):r},a.endAngle=function(s){return arguments.length?(i=typeof s=="function"?s:W(+s),a):i},a.padAngle=function(s){return arguments.length?(o=typeof s=="function"?s:W(+s),a):o},a}function Se(t,e,n){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+n)/6)}function Xe(t){this._context=t}Xe.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:Se(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:Se(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function Rc(t){return new Xe(t)}var Pn=class{constructor(e,n){this._context=e,this._x=n}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(e,n){switch(e=+e,n=+n,this._point){case 0:{this._point=1,this._line?this._context.lineTo(e,n):this._context.moveTo(e,n);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+e)/2,this._y0,this._x0,n,e,n):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+n)/2,e,this._y0,e,n);break}}this._x0=e,this._y0=n}};function Pc(t){return new Pn(t,!0)}function Yc(t){return new Pn(t,!1)}function pt(){}function os(t){this._context=t}os.prototype={areaStart:pt,areaEnd:pt,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:Se(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function Fc(t){return new os(t)}function as(t){this._context=t}as.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+t)/6,r=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:Se(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function Uc(t){return new as(t)}function ss(t,e){this._basis=new Xe(t),this._beta=e}ss.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var t=this._x,e=this._y,n=t.length-1;if(n>0)for(var r=t[0],i=e[0],o=t[n]-r,a=e[n]-i,s=-1,f;++s<=n;)f=s/n,this._basis.point(this._beta*t[s]+(1-this._beta)*(r+f*o),this._beta*e[s]+(1-this._beta)*(i+f*a));this._x=this._y=null,this._basis.lineEnd()},point:function(t,e){this._x.push(+t),this._y.push(+e)}};var zc=(function t(e){function n(r){return e===1?new Xe(r):new ss(r,e)}return n.beta=function(r){return t(+r)},n})(.85);function Ce(t,e,n){t._context.bezierCurveTo(t._x1+t._k*(t._x2-t._x0),t._y1+t._k*(t._y2-t._y0),t._x2+t._k*(t._x1-e),t._y2+t._k*(t._y1-n),t._x2,t._y2)}function Yn(t,e){this._context=t,this._k=(1-e)/6}Yn.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:Ce(this,this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2,this._x1=t,this._y1=e;break;case 2:this._point=3;default:Ce(this,t,e);break}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};var Lc=(function t(e){function n(r){return new Yn(r,e)}return n.tension=function(r){return t(+r)},n})(0);function Fn(t,e){this._context=t,this._k=(1-e)/6}Fn.prototype={areaStart:pt,areaEnd:pt,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x3,this._y3),this._context.closePath();break}case 2:{this._context.lineTo(this._x3,this._y3),this._context.closePath();break}case 3:{this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:Ce(this,t,e);break}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};var Hc=(function t(e){function n(r){return new Fn(r,e)}return n.tension=function(r){return t(+r)},n})(0);function Un(t,e){this._context=t,this._k=(1-e)/6}Un.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:Ce(this,t,e);break}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};var Bc=(function t(e){function n(r){return new Un(r,e)}return n.tension=function(r){return t(+r)},n})(0);function Ge(t,e,n){var r=t._x1,i=t._y1,o=t._x2,a=t._y2;if(t._l01_a>j){var s=2*t._l01_2a+3*t._l01_a*t._l12_a+t._l12_2a,f=3*t._l01_a*(t._l01_a+t._l12_a);r=(r*s-t._x0*t._l12_2a+t._x2*t._l01_2a)/f,i=(i*s-t._y0*t._l12_2a+t._y2*t._l01_2a)/f}if(t._l23_a>j){var u=2*t._l23_2a+3*t._l23_a*t._l12_a+t._l12_2a,c=3*t._l23_a*(t._l23_a+t._l12_a);o=(o*u+t._x1*t._l23_2a-e*t._l12_2a)/c,a=(a*u+t._y1*t._l23_2a-n*t._l12_2a)/c}t._context.bezierCurveTo(r,i,o,a,t._x2,t._y2)}function us(t,e){this._context=t,this._alpha=e}us.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3;default:Ge(this,t,e);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};var qc=(function t(e){function n(r){return e?new us(r,e):new Yn(r,0)}return n.alpha=function(r){return t(+r)},n})(.5);function fs(t,e){this._context=t,this._alpha=e}fs.prototype={areaStart:pt,areaEnd:pt,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x3,this._y3),this._context.closePath();break}case 2:{this._context.lineTo(this._x3,this._y3),this._context.closePath();break}case 3:{this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}}},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:Ge(this,t,e);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};var Wc=(function t(e){function n(r){return e?new fs(r,e):new Fn(r,0)}return n.alpha=function(r){return t(+r)},n})(.5);function ls(t,e){this._context=t,this._alpha=e}ls.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:Ge(this,t,e);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};var Vc=(function t(e){function n(r){return e?new ls(r,e):new Un(r,0)}return n.alpha=function(r){return t(+r)},n})(.5);function cs(t){this._context=t}cs.prototype={areaStart:pt,areaEnd:pt,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(t,e){t=+t,e=+e,this._point?this._context.lineTo(t,e):(this._point=1,this._context.moveTo(t,e))}};function Xc(t){return new cs(t)}function hs(t){return t<0?-1:1}function ps(t,e,n){var r=t._x1-t._x0,i=e-t._x1,o=(t._y1-t._y0)/(r||i<0&&-0),a=(n-t._y1)/(i||r<0&&-0),s=(o*i+a*r)/(r+i);return(hs(o)+hs(a))*Math.min(Math.abs(o),Math.abs(a),.5*Math.abs(s))||0}function ms(t,e){var n=t._x1-t._x0;return n?(3*(t._y1-t._y0)/n-e)/2:e}function ei(t,e,n){var r=t._x0,i=t._y0,o=t._x1,a=t._y1,s=(o-r)/3;t._context.bezierCurveTo(r+s,i+s*e,o-s,a-s*n,o,a)}function zn(t){this._context=t}zn.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:ei(this,this._t0,ms(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){var n=NaN;if(t=+t,e=+e,!(t===this._x1&&e===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,ei(this,ms(this,n=ps(this,t,e)),n);break;default:ei(this,this._t0,n=ps(this,t,e));break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=n}}};function ds(t){this._context=new xs(t)}(ds.prototype=Object.create(zn.prototype)).point=function(t,e){zn.prototype.point.call(this,e,t)};function xs(t){this._context=t}xs.prototype={moveTo:function(t,e){this._context.moveTo(e,t)},closePath:function(){this._context.closePath()},lineTo:function(t,e){this._context.lineTo(e,t)},bezierCurveTo:function(t,e,n,r,i,o){this._context.bezierCurveTo(e,t,r,n,o,i)}};function Gc(t){return new zn(t)}function Zc(t){return new ds(t)}function gs(t){this._context=t}gs.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var t=this._x,e=this._y,n=t.length;if(n)if(this._line?this._context.lineTo(t[0],e[0]):this._context.moveTo(t[0],e[0]),n===2)this._context.lineTo(t[1],e[1]);else for(var r=_s(t),i=_s(e),o=0,a=1;a=0;--e)i[e]=(a[e]-i[e+1])/o[e];for(o[n-1]=(t[n]+i[n-1])/2,e=0;e=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var n=this._x*(1-this._t)+t*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,e)}break}}this._x=t,this._y=e}};function Kc(t){return new Ln(t,.5)}function Jc(t){return new Ln(t,0)}function jc(t){return new Ln(t,1)}var th={value:()=>{}};function vs(){for(var t=0,e=arguments.length,n={},r;t=0&&(r=n.slice(i+1),n=n.slice(0,i)),n&&!e.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}Hn.prototype=vs.prototype={constructor:Hn,on:function(t,e){var n=this._,r=eh(t+"",n),i,o=-1,a=r.length;if(arguments.length<2){for(;++o0)for(var n=new Array(i),r=0,i,o;r=0&&t._call.call(void 0,e),t=t._next;--Ne}function ws(){se=(qn=Je.now())+Wn,Ne=Qe=0;try{Ts()}finally{Ne=0,oh(),se=0}}function ih(){var t=Je.now(),e=t-qn;e>bs&&(Wn-=e,qn=t)}function oh(){for(var t,e=Bn,n,r=1/0;e;)e._call?(r>e._time&&(r=e._time),t=e,e=e._next):(n=e._next,e._next=null,e=t?t._next=n:Bn=n);Ke=t,ri(r)}function ri(t){if(!Ne){Qe&&(Qe=clearTimeout(Qe));var e=t-se;e>24?(t<1/0&&(Qe=setTimeout(ws,t-Je.now()-Wn)),Ze&&(Ze=clearInterval(Ze))):(Ze||(qn=Je.now(),Ze=setInterval(ih,bs)),Ne=1,Ms(ws))}}function Xn(t,e,n){var r=new je;return e=e==null?0:+e,r.restart(i=>{r.stop(),t(i+e)},e,n),r}var ah=ni("start","end","cancel","interrupt"),sh=[],Cs=0,ks=1,Zn=2,Gn=3,Ss=4,Qn=5,en=6;function zt(t,e,n,r,i,o){var a=t.__transition;if(!a)t.__transition={};else if(n in a)return;uh(t,n,{name:e,index:r,group:i,on:ah,tween:sh,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:Cs})}function nn(t,e){var n=Q(t,e);if(n.state>Cs)throw new Error("too late; already scheduled");return n}function rt(t,e){var n=Q(t,e);if(n.state>Gn)throw new Error("too late; already running");return n}function Q(t,e){var n=t.__transition;if(!n||!(n=n[e]))throw new Error("transition not found");return n}function uh(t,e,n){var r=t.__transition,i;r[e]=n,n.timer=Vn(o,0,n.time);function o(u){n.state=ks,n.timer.restart(a,n.delay,n.time),n.delay<=u&&a(u-n.delay)}function a(u){var c,h,l,p;if(n.state!==ks)return f();for(c in r)if(p=r[c],p.name===n.name){if(p.state===Gn)return Xn(a);p.state===Ss?(p.state=en,p.timer.stop(),p.on.call("interrupt",t,t.__data__,p.index,p.group),delete r[c]):+cZn&&r.state=0&&(e=e.slice(0,n)),!e||e==="start"})}function Nh(t,e,n){var r,i,o=Ch(e)?nn:rt;return function(){var a=o(this,t),s=a.on;s!==r&&(i=(r=s).copy()).on(e,n),a.on=i}}function Fs(t,e){var n=this._id;return arguments.length<2?Q(this.node(),n).on.on(t):this.each(Nh(n,t,e))}function Ah(t){return function(){var e=this.parentNode;for(var n in this.__transition)if(+n!==t)return;e&&e.removeChild(this)}}function Us(){return this.on("end.remove",Ah(this._id))}function zs(t){var e=this._name,n=this._id;typeof t!="function"&&(t=Wt(t));for(var r=this._groups,i=r.length,o=new Array(i),a=0;a=e?t:\"\"+Array(e+1-r.length).join(n)+t},v={s:m,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return(e<=0?\"+\":\"-\")+m(r,2,\"0\")+\":\"+m(i,2,\"0\")},m:function t(e,n){if(e.date()1)return t(u[0])}else{var a=e.name;D[a]=e,i=a}return!r&&i&&(g=i),i||!r&&g},O=function(t,e){if(S(t))return t.clone();var n=\"object\"==typeof e?e:{};return n.date=t,n.args=arguments,new _(n)},b=v;b.l=w,b.i=S,b.w=function(t,e){return O(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var _=function(){function M(t){this.$L=w(t.locale,null,!0),this.parse(t),this.$x=this.$x||t.x||{},this[p]=!0}var m=M.prototype;return m.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(b.u(e))return new Date;if(e instanceof Date)return new Date(e);if(\"string\"==typeof e&&!/Z$/i.test(e)){var r=e.match($);if(r){var i=r[2]-1||0,s=(r[7]||\"0\").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.init()},m.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds()},m.$utils=function(){return b},m.isValid=function(){return!(this.$d.toString()===l)},m.isSame=function(t,e){var n=O(t);return this.startOf(e)<=n&&n<=this.endOf(e)},m.isAfter=function(t,e){return O(t) __defProp(target, \"name\", { value, configurable: true });\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\n\n// src/logger.ts\nimport dayjs from \"dayjs\";\nvar LEVELS = {\n trace: 0,\n debug: 1,\n info: 2,\n warn: 3,\n error: 4,\n fatal: 5\n};\nvar log = {\n trace: /* @__PURE__ */ __name((..._args) => {\n }, \"trace\"),\n debug: /* @__PURE__ */ __name((..._args) => {\n }, \"debug\"),\n info: /* @__PURE__ */ __name((..._args) => {\n }, \"info\"),\n warn: /* @__PURE__ */ __name((..._args) => {\n }, \"warn\"),\n error: /* @__PURE__ */ __name((..._args) => {\n }, \"error\"),\n fatal: /* @__PURE__ */ __name((..._args) => {\n }, \"fatal\")\n};\nvar setLogLevel = /* @__PURE__ */ __name(function(level = \"fatal\") {\n let numericLevel = LEVELS.fatal;\n if (typeof level === \"string\") {\n if (level.toLowerCase() in LEVELS) {\n numericLevel = LEVELS[level];\n }\n } else if (typeof level === \"number\") {\n numericLevel = level;\n }\n log.trace = () => {\n };\n log.debug = () => {\n };\n log.info = () => {\n };\n log.warn = () => {\n };\n log.error = () => {\n };\n log.fatal = () => {\n };\n if (numericLevel <= LEVELS.fatal) {\n log.fatal = console.error ? console.error.bind(console, format(\"FATAL\"), \"color: orange\") : console.log.bind(console, \"\\x1B[35m\", format(\"FATAL\"));\n }\n if (numericLevel <= LEVELS.error) {\n log.error = console.error ? console.error.bind(console, format(\"ERROR\"), \"color: orange\") : console.log.bind(console, \"\\x1B[31m\", format(\"ERROR\"));\n }\n if (numericLevel <= LEVELS.warn) {\n log.warn = console.warn ? console.warn.bind(console, format(\"WARN\"), \"color: orange\") : console.log.bind(console, `\\x1B[33m`, format(\"WARN\"));\n }\n if (numericLevel <= LEVELS.info) {\n log.info = console.info ? console.info.bind(console, format(\"INFO\"), \"color: lightblue\") : console.log.bind(console, \"\\x1B[34m\", format(\"INFO\"));\n }\n if (numericLevel <= LEVELS.debug) {\n log.debug = console.debug ? console.debug.bind(console, format(\"DEBUG\"), \"color: lightgreen\") : console.log.bind(console, \"\\x1B[32m\", format(\"DEBUG\"));\n }\n if (numericLevel <= LEVELS.trace) {\n log.trace = console.debug ? console.debug.bind(console, format(\"TRACE\"), \"color: lightgreen\") : console.log.bind(console, \"\\x1B[32m\", format(\"TRACE\"));\n }\n}, \"setLogLevel\");\nvar format = /* @__PURE__ */ __name((level) => {\n const time = dayjs().format(\"ss.SSS\");\n return `%c${time} : ${level} : `;\n}, \"format\");\n\nexport {\n __name,\n __export,\n log,\n setLogLevel\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 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 ascending(a, b) {\n return a == null || b == null ? NaN : a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;\n}\n", "export default function descending(a, b) {\n return a == null || b == null ? NaN\n : b < a ? -1\n : b > a ? 1\n : b >= a ? 0\n : NaN;\n}\n", "import ascending from \"./ascending.js\";\nimport descending from \"./descending.js\";\n\nexport default function bisector(f) {\n let compare1, compare2, delta;\n\n // If an accessor is specified, promote it to a comparator. In this case we\n // can test whether the search value is (self-) comparable. We can\u2019t do this\n // for a comparator (except for specific, known comparators) because we can\u2019t\n // tell if the comparator is symmetric, and an asymmetric comparator can\u2019t be\n // used to test whether a single value is comparable.\n if (f.length !== 2) {\n compare1 = ascending;\n compare2 = (d, x) => ascending(f(d), x);\n delta = (d, x) => f(d) - x;\n } else {\n compare1 = f === ascending || f === descending ? f : zero;\n compare2 = f;\n delta = f;\n }\n\n function left(a, x, lo = 0, hi = a.length) {\n if (lo < hi) {\n if (compare1(x, x) !== 0) return hi;\n do {\n const mid = (lo + hi) >>> 1;\n if (compare2(a[mid], x) < 0) lo = mid + 1;\n else hi = mid;\n } while (lo < hi);\n }\n return lo;\n }\n\n function right(a, x, lo = 0, hi = a.length) {\n if (lo < hi) {\n if (compare1(x, x) !== 0) return hi;\n do {\n const mid = (lo + hi) >>> 1;\n if (compare2(a[mid], x) <= 0) lo = mid + 1;\n else hi = mid;\n } while (lo < hi);\n }\n return lo;\n }\n\n function center(a, x, lo = 0, 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 zero() {\n return 0;\n}\n", "export default function number(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", "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", "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(key);\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 e10 = Math.sqrt(50),\n e5 = Math.sqrt(10),\n e2 = Math.sqrt(2);\n\nfunction tickSpec(start, stop, count) {\n const step = (stop - start) / Math.max(0, count),\n power = Math.floor(Math.log10(step)),\n error = step / Math.pow(10, power),\n factor = error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1;\n let i1, i2, inc;\n if (power < 0) {\n inc = Math.pow(10, -power) / factor;\n i1 = Math.round(start * inc);\n i2 = Math.round(stop * inc);\n if (i1 / inc < start) ++i1;\n if (i2 / inc > stop) --i2;\n inc = -inc;\n } else {\n inc = Math.pow(10, power) * factor;\n i1 = Math.round(start / inc);\n i2 = Math.round(stop / inc);\n if (i1 * inc < start) ++i1;\n if (i2 * inc > stop) --i2;\n }\n if (i2 < i1 && 0.5 <= count && count < 2) return tickSpec(start, stop, count * 2);\n return [i1, i2, inc];\n}\n\nexport default function ticks(start, stop, count) {\n stop = +stop, start = +start, count = +count;\n if (!(count > 0)) return [];\n if (start === stop) return [start];\n const reverse = stop < start, [i1, i2, inc] = reverse ? tickSpec(stop, start, count) : tickSpec(start, stop, count);\n if (!(i2 >= i1)) return [];\n const n = i2 - i1 + 1, ticks = new Array(n);\n if (reverse) {\n if (inc < 0) for (let i = 0; i < n; ++i) ticks[i] = (i2 - i) / -inc;\n else for (let i = 0; i < n; ++i) ticks[i] = (i2 - i) * inc;\n } else {\n if (inc < 0) for (let i = 0; i < n; ++i) ticks[i] = (i1 + i) / -inc;\n else for (let i = 0; i < n; ++i) ticks[i] = (i1 + i) * inc;\n }\n return ticks;\n}\n\nexport function tickIncrement(start, stop, count) {\n stop = +stop, start = +start, count = +count;\n return tickSpec(start, stop, count)[2];\n}\n\nexport function tickStep(start, stop, count) {\n stop = +stop, start = +start, count = +count;\n const reverse = stop < start, inc = reverse ? tickIncrement(stop, start, count) : tickIncrement(start, stop, count);\n return (reverse ? -1 : 1) * (inc < 0 ? 1 / -inc : inc);\n}\n", "export default function range(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(x) {\n return x;\n}\n", "import identity from \"./identity.js\";\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)\";\n}\n\nfunction translateY(y) {\n return \"translate(0,\" + y + \")\";\n}\n\nfunction number(scale) {\n return d => +scale(d);\n}\n\nfunction center(scale, offset) {\n offset = Math.max(0, scale.bandwidth() - offset * 2) / 2;\n if (scale.round()) offset = Math.round(offset);\n return d => +scale(d) + offset;\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 offset = typeof window !== \"undefined\" && window.devicePixelRatio > 1 ? 0 : 0.5,\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] + offset,\n range1 = +range[range.length - 1] + offset,\n position = (scale.bandwidth ? center : number)(scale.copy(), offset),\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 + offset) : 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)) + offset); });\n }\n\n tickExit.remove();\n\n path\n .attr(\"d\", orient === left || orient === right\n ? (tickSizeOuter ? \"M\" + k * tickSizeOuter + \",\" + range0 + \"H\" + offset + \"V\" + range1 + \"H\" + k * tickSizeOuter : \"M\" + offset + \",\" + range0 + \"V\" + range1)\n : (tickSizeOuter ? \"M\" + range0 + \",\" + k * tickSizeOuter + \"V\" + offset + \"H\" + range1 + \"V\" + k * tickSizeOuter : \"M\" + range0 + \",\" + offset + \"H\" + range1));\n\n tick\n .attr(\"opacity\", 1)\n .attr(\"transform\", function(d) { return transform(position(d) + offset); });\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 = Array.from(arguments), axis;\n };\n\n axis.tickArguments = function(_) {\n return arguments.length ? (tickArguments = _ == null ? [] : Array.from(_), axis) : tickArguments.slice();\n };\n\n axis.tickValues = function(_) {\n return arguments.length ? (tickValues = _ == null ? null : Array.from(_), 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 axis.offset = function(_) {\n return arguments.length ? (offset = +_, axis) : offset;\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", "function none() {}\n\nexport default function(selector) {\n return selector == null ? none : function() {\n return this.querySelector(selector);\n };\n}\n", "import {Selection} from \"./index.js\";\nimport selector from \"../selector.js\";\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", "// Given something array like (or null), returns something that is strictly an\n// array. This is used to ensure that array-like objects passed to d3.selectAll\n// or selection.selectAll are converted into proper arrays when creating a\n// selection; we don\u2019t ever want to create a selection backed by a live\n// HTMLCollection or NodeList. However, note that selection.selectAll will use a\n// static NodeList as a group, since it safely derived from querySelectorAll.\nexport default function array(x) {\n return x == null ? [] : Array.isArray(x) ? x : Array.from(x);\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 {Selection} from \"./index.js\";\nimport array from \"../array.js\";\nimport selectorAll from \"../selectorAll.js\";\n\nfunction arrayAll(select) {\n return function() {\n return array(select.apply(this, arguments));\n };\n}\n\nexport default function(select) {\n if (typeof select === \"function\") select = arrayAll(select);\n else 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(selector) {\n return function() {\n return this.matches(selector);\n };\n}\n\nexport function childMatcher(selector) {\n return function(node) {\n return node.matches(selector);\n };\n}\n\n", "import {childMatcher} from \"../matcher.js\";\n\nvar find = Array.prototype.find;\n\nfunction childFind(match) {\n return function() {\n return find.call(this.children, match);\n };\n}\n\nfunction childFirst() {\n return this.firstElementChild;\n}\n\nexport default function(match) {\n return this.select(match == null ? childFirst\n : childFind(typeof match === \"function\" ? match : childMatcher(match)));\n}\n", "import {childMatcher} from \"../matcher.js\";\n\nvar filter = Array.prototype.filter;\n\nfunction children() {\n return Array.from(this.children);\n}\n\nfunction childrenFilter(match) {\n return function() {\n return filter.call(this.children, match);\n };\n}\n\nexport default function(match) {\n return this.selectAll(match == null ? children\n : childrenFilter(typeof match === \"function\" ? match : childMatcher(match)));\n}\n", "import {Selection} from \"./index.js\";\nimport matcher from \"../matcher.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 Selection(subgroups, this._parents);\n}\n", "export default function(update) {\n return new Array(update.length);\n}\n", "import sparse from \"./sparse.js\";\nimport {Selection} from \"./index.js\";\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", "export default function(x) {\n return function() {\n return x;\n };\n}\n", "import {Selection} from \"./index.js\";\nimport {EnterNode} from \"./enter.js\";\nimport constant from \"../constant.js\";\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\u2019t 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 = new Map,\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 = key.call(node, node.__data__, i, group) + \"\";\n if (nodeByKeyValue.has(keyValue)) {\n exit[i] = node;\n } else {\n nodeByKeyValue.set(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 = key.call(parent, data[i], i, data) + \"\";\n if (node = nodeByKeyValue.get(keyValue)) {\n update[i] = node;\n node.__data__ = data[i];\n nodeByKeyValue.delete(keyValue);\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.get(keyValues[i]) === node)) {\n exit[i] = node;\n }\n }\n}\n\nfunction datum(node) {\n return node.__data__;\n}\n\nexport default function(value, key) {\n if (!arguments.length) return Array.from(this, datum);\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 = arraylike(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\n// Given some data, this returns an array-like view of it: an object that\n// exposes a length property and allows numeric indexing. Note that unlike\n// selectAll, this isn\u2019t worried about \u201Clive\u201D collections because the resulting\n// array will only be used briefly while data is being bound. (It is possible to\n// cause the data to change while iterating by using a key function, but please\n// don\u2019t; we\u2019d rather avoid a gratuitous copy.)\nfunction arraylike(data) {\n return typeof data === \"object\" && \"length\" in data\n ? data // Array, TypedArray, NodeList, array-like\n : Array.from(data); // Map, Set, iterable, string, or anything else\n}\n", "import sparse from \"./sparse.js\";\nimport {Selection} from \"./index.js\";\n\nexport default function() {\n return new Selection(this._exit || this._groups.map(sparse), this._parents);\n}\n", "export default function(onenter, onupdate, onexit) {\n var enter = this.enter(), update = this, exit = this.exit();\n if (typeof onenter === \"function\") {\n enter = onenter(enter);\n if (enter) enter = enter.selection();\n } else {\n enter = enter.append(onenter + \"\");\n }\n if (onupdate != null) {\n update = onupdate(update);\n if (update) update = update.selection();\n }\n if (onexit == null) exit.remove(); else onexit(exit);\n return enter && update ? enter.merge(update).order() : update;\n}\n", "import {Selection} from \"./index.js\";\n\nexport default function(context) {\n var selection = context.selection ? context.selection() : context;\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 = -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", "import {Selection} from \"./index.js\";\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() {\n var callback = arguments[0];\n arguments[0] = this;\n callback.apply(null, arguments);\n return this;\n}\n", "export default function() {\n return Array.from(this);\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 let size = 0;\n for (const node of this) ++size; // eslint-disable-line no-unused-vars\n return size;\n}\n", "export default function() {\n return !this.node();\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 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", "import namespaces from \"./namespaces.js\";\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; // eslint-disable-line no-prototype-builtins\n}\n", "import namespace from \"../namespace.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, 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(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 defaultView from \"../window.js\";\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 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 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 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 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", "function raise() {\n if (this.nextSibling) this.parentNode.appendChild(this);\n}\n\nexport default function() {\n return this.each(raise);\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 namespace from \"./namespace.js\";\nimport {xhtml} from \"./namespaces.js\";\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", "import creator from \"../creator.js\";\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 creator from \"../creator.js\";\nimport selector from \"../selector.js\";\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", "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", "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", "export default function(value) {\n return arguments.length\n ? this.property(\"__data__\", value)\n : this.node().__data__;\n}\n", "function contextListener(listener) {\n return function(event) {\n listener.call(this, event, this.__data__);\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.options);\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, options) {\n return function() {\n var on = this.__on, o, listener = contextListener(value);\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.options);\n this.addEventListener(o.type, o.listener = listener, o.options = options);\n o.value = value;\n return;\n }\n }\n this.addEventListener(typename.type, listener, options);\n o = {type: typename.type, name: typename.name, value: value, listener: listener, options: options};\n if (!on) this.__on = [o];\n else on.push(o);\n };\n}\n\nexport default function(typename, value, options) {\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 for (i = 0; i < n; ++i) this.each(on(typenames[i], value, options));\n return this;\n}\n", "import defaultView from \"../window.js\";\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*() {\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]) yield node;\n }\n }\n}\n", "import selection_select from \"./select.js\";\nimport selection_selectAll from \"./selectAll.js\";\nimport selection_selectChild from \"./selectChild.js\";\nimport selection_selectChildren from \"./selectChildren.js\";\nimport selection_filter from \"./filter.js\";\nimport selection_data from \"./data.js\";\nimport selection_enter from \"./enter.js\";\nimport selection_exit from \"./exit.js\";\nimport selection_join from \"./join.js\";\nimport selection_merge from \"./merge.js\";\nimport selection_order from \"./order.js\";\nimport selection_sort from \"./sort.js\";\nimport selection_call from \"./call.js\";\nimport selection_nodes from \"./nodes.js\";\nimport selection_node from \"./node.js\";\nimport selection_size from \"./size.js\";\nimport selection_empty from \"./empty.js\";\nimport selection_each from \"./each.js\";\nimport selection_attr from \"./attr.js\";\nimport selection_style from \"./style.js\";\nimport selection_property from \"./property.js\";\nimport selection_classed from \"./classed.js\";\nimport selection_text from \"./text.js\";\nimport selection_html from \"./html.js\";\nimport selection_raise from \"./raise.js\";\nimport selection_lower from \"./lower.js\";\nimport selection_append from \"./append.js\";\nimport selection_insert from \"./insert.js\";\nimport selection_remove from \"./remove.js\";\nimport selection_clone from \"./clone.js\";\nimport selection_datum from \"./datum.js\";\nimport selection_on from \"./on.js\";\nimport selection_dispatch from \"./dispatch.js\";\nimport selection_iterator from \"./iterator.js\";\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\nfunction selection_selection() {\n return this;\n}\n\nSelection.prototype = selection.prototype = {\n constructor: Selection,\n select: selection_select,\n selectAll: selection_selectAll,\n selectChild: selection_selectChild,\n selectChildren: selection_selectChildren,\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 selection: selection_selection,\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 [Symbol.iterator]: selection_iterator\n};\n\nexport default selection;\n", "import {Selection, root} from \"./selection/index.js\";\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", "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", "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(channels) {\n return Object.assign(new this.constructor, this, channels);\n },\n displayable() {\n return this.rgb().displayable();\n },\n hex: color_formatHex, // Deprecated! Use color.formatHex.\n formatHex: color_formatHex,\n formatHex8: color_formatHex8,\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_formatHex8() {\n return this.rgb().formatHex8();\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(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(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() {\n return this;\n },\n clamp() {\n return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity));\n },\n displayable() {\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 formatHex8: rgb_formatHex8,\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_formatHex8() {\n return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;\n}\n\nfunction rgb_formatRgb() {\n const a = clampa(this.opacity);\n return `${a === 1 ? \"rgb(\" : \"rgba(\"}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? \")\" : `, ${a})`}`;\n}\n\nfunction clampa(opacity) {\n return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity));\n}\n\nfunction clampi(value) {\n return Math.max(0, Math.min(255, Math.round(value) || 0));\n}\n\nfunction hex(value) {\n value = clampi(value);\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(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(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() {\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 clamp() {\n return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity));\n },\n displayable() {\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() {\n const a = clampa(this.opacity);\n return `${a === 1 ? \"hsl(\" : \"hsla(\"}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? \")\" : `, ${a})`}`;\n }\n}));\n\nfunction clamph(value) {\n value = (value || 0) % 360;\n return value < 0 ? value + 360 : value;\n}\n\nfunction clampt(value) {\n return Math.max(0, Math.min(1, value || 0));\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", "export const radians = Math.PI / 180;\nexport const degrees = 180 / Math.PI;\n", "import define, {extend} from \"./define.js\";\nimport {Color, rgbConvert, Rgb} from \"./color.js\";\nimport {degrees, radians} from \"./math.js\";\n\n// https://observablehq.com/@mbostock/lab-and-rgb\nconst 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(k) {\n return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);\n },\n darker(k) {\n return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);\n },\n rgb() {\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) * degrees;\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 * radians;\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(k) {\n return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);\n },\n darker(k) {\n return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);\n },\n rgb() {\n return hcl2lab(this).rgb();\n }\n}));\n", "export default x => () => x;\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", "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", "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 {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 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\";\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 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(a, b) {\n return a = +a, b = +b, function(t) {\n return a * (1 - t) + b * t;\n };\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", "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", "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", "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", "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 decompose, {identity} from \"./decompose.js\";\n\nvar svgNode;\n\n/* eslint-disable no-undef */\nexport function parseCss(value) {\n const m = new (typeof DOMMatrix === \"function\" ? DOMMatrix : WebKitCSSMatrix)(value + \"\");\n return m.isIdentity ? identity : decompose(m.a, m.b, m.c, m.d, m.e, m.f);\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 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", "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, \u00B1Infinity\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", "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(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", "// [[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 {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", "import formatDecimal from \"./formatDecimal.js\";\nimport formatPrefixAuto from \"./formatPrefixAuto.js\";\nimport formatRounded from \"./formatRounded.js\";\n\nexport default {\n \"%\": (x, p) => (x * 100).toFixed(p),\n \"b\": (x) => Math.round(x).toString(2),\n \"c\": (x) => x + \"\",\n \"d\": formatDecimal,\n \"e\": (x, p) => x.toExponential(p),\n \"f\": (x, p) => x.toFixed(p),\n \"g\": (x, p) => x.toPrecision(p),\n \"o\": (x) => Math.round(x).toString(8),\n \"p\": (x, p) => formatRounded(x * 100, p),\n \"r\": formatRounded,\n \"s\": formatPrefixAuto,\n \"X\": (x) => Math.round(x).toString(16).toUpperCase(),\n \"x\": (x) => Math.round(x).toString(16)\n};\n", "export default function(x) {\n return x;\n}\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\",\"\u00B5\",\"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 ? \"\u2212\" : 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 \u201Cvalue\u201D part that can be\n // grouped, and fractional or exponential \u201Csuffix\u201D 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 formatLocale from \"./locale.js\";\n\nvar locale;\nexport var format;\nexport var formatPrefix;\n\ndefaultLocale({\n thousands: \",\",\n grouping: [3],\n currency: [\"$\", \"\"]\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 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", "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(callback, that) {\n let index = -1;\n for (const node of this) {\n callback.call(that, node, ++index, this);\n }\n return this;\n}\n", "export default function(callback, that) {\n var node = this, nodes = [node], children, i, index = -1;\n while (node = nodes.pop()) {\n callback.call(that, node, ++index, this);\n if (children = node.children) {\n for (i = children.length - 1; i >= 0; --i) {\n nodes.push(children[i]);\n }\n }\n }\n return this;\n}\n", "export default function(callback, that) {\n var node = this, nodes = [node], next = [], children, i, n, index = -1;\n while (node = nodes.pop()) {\n next.push(node);\n if (children = node.children) {\n for (i = 0, n = children.length; i < n; ++i) {\n nodes.push(children[i]);\n }\n }\n }\n while (node = next.pop()) {\n callback.call(that, node, ++index, this);\n }\n return this;\n}\n", "export default function(callback, that) {\n let index = -1;\n for (const node of this) {\n if (callback.call(that, node, ++index, this)) {\n return node;\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 function(compare) {\n return this.eachBefore(function(node) {\n if (node.children) {\n node.children.sort(compare);\n }\n });\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() {\n var node = this, nodes = [node];\n while (node = node.parent) {\n nodes.push(node);\n }\n return nodes;\n}\n", "export default function() {\n return Array.from(this);\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\u2019t include the root\u2019s parent, if any.\n links.push({source: node.parent, target: node});\n }\n });\n return links;\n}\n", "export default function*() {\n var node = this, current, next = [node], children, i, n;\n do {\n current = next.reverse(), next = [];\n while (node = current.pop()) {\n yield node;\n if (children = node.children) {\n for (i = 0, n = children.length; i < n; ++i) {\n next.push(children[i]);\n }\n }\n }\n } while (next.length);\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_find from \"./find.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\";\nimport node_iterator from \"./iterator.js\";\n\nexport default function hierarchy(data, children) {\n if (data instanceof Map) {\n data = [undefined, data];\n if (children === undefined) children = mapChildren;\n } else if (children === undefined) {\n children = objectChildren;\n }\n\n var root = new Node(data),\n node,\n nodes = [root],\n child,\n childs,\n i,\n n;\n\n while (node = nodes.pop()) {\n if ((childs = children(node.data)) && (n = (childs = Array.from(childs)).length)) {\n node.children = childs;\n for (i = n - 1; i >= 0; --i) {\n nodes.push(child = childs[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 objectChildren(d) {\n return d.children;\n}\n\nfunction mapChildren(d) {\n return Array.isArray(d) ? d[1] : null;\n}\n\nfunction copyData(node) {\n if (node.data.value !== undefined) node.value = node.data.value;\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 find: node_find,\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 [Symbol.iterator]: node_iterator\n};\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 && (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", "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 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", "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 function constantZero() {\n return 0;\n}\n\nexport default function(x) {\n return function() {\n return x;\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", "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: {\n if (typeof domain === \"function\") this.interpolator(domain);\n else this.range(domain);\n break;\n }\n default: {\n this.domain(domain);\n if (typeof interpolator === \"function\") this.interpolator(interpolator);\n else this.range(interpolator);\n break;\n }\n }\n return this;\n}\n", "import {InternMap} from \"d3-array\";\nimport {initRange} from \"./init.js\";\n\nexport const implicit = Symbol(\"implicit\");\n\nexport default function ordinal() {\n var index = new InternMap(),\n domain = [],\n range = [],\n unknown = implicit;\n\n function scale(d) {\n let i = index.get(d);\n if (i === undefined) {\n if (unknown !== implicit) return unknown;\n index.set(d, i = domain.push(d) - 1);\n }\n return range[i % range.length];\n }\n\n scale.domain = function(_) {\n if (!arguments.length) return domain.slice();\n domain = [], index = new InternMap();\n for (const value of _) {\n if (index.has(value)) continue;\n index.set(value, domain.push(value) - 1);\n }\n return scale;\n };\n\n scale.range = function(_) {\n return arguments.length ? (range = Array.from(_), 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 {range as sequence} from \"d3-array\";\nimport {initRange} from \"./init.js\";\nimport ordinal from \"./ordinal.js\";\n\nexport default function band() {\n var scale = ordinal().unknown(undefined),\n domain = scale.domain,\n ordinalRange = scale.range,\n r0 = 0,\n r1 = 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 = r1 < r0,\n start = reverse ? r1 : r0,\n stop = reverse ? r0 : r1;\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 ? ([r0, r1] = _, r0 = +r0, r1 = +r1, rescale()) : [r0, r1];\n };\n\n scale.rangeRound = function(_) {\n return [r0, r1] = _, r0 = +r0, r1 = +r1, 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(), [r0, r1])\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 constants(x) {\n return function() {\n return x;\n };\n}\n", "export default function number(x) {\n return +x;\n}\n", "import {bisect} from \"d3-array\";\nimport {interpolate as interpolateValue, interpolateNumber, interpolateRound} from \"d3-interpolate\";\nimport constant from \"./constant.js\";\nimport number from \"./number.js\";\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(a, b) {\n var 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 var n = Math.min(domain.length, range.length);\n if (clamp !== identity) clamp = clamper(domain[0], domain[n - 1]);\n piecewise = n > 2 ? polymap : bimap;\n output = input = null;\n return scale;\n }\n\n function scale(x) {\n return x == null || 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 = Array.from(_, number), rescale()) : domain.slice();\n };\n\n scale.range = function(_) {\n return arguments.length ? (range = Array.from(_), rescale()) : range.slice();\n };\n\n scale.rangeRound = function(_) {\n return range = Array.from(_), interpolate = interpolateRound, rescale();\n };\n\n scale.clamp = function(_) {\n return arguments.length ? (clamp = _ ? true : identity, rescale()) : 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() {\n return transformer()(identity, identity);\n}\n", "import {tickStep} from \"d3-array\";\nimport {format, formatPrefix, formatSpecifier, precisionFixed, precisionPrefix, precisionRound} from \"d3-format\";\n\nexport default function tickFormat(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 {ticks, tickIncrement} from \"d3-array\";\nimport continuous, {copy} from \"./continuous.js\";\nimport {initRange} from \"./init.js\";\nimport tickFormat from \"./tickFormat.js\";\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 var i0 = 0;\n var i1 = d.length - 1;\n var start = d[i0];\n var stop = d[i1];\n var prestep;\n var step;\n var maxIter = 10;\n\n if (stop < start) {\n step = start, start = stop, stop = step;\n step = i0, i0 = i1, i1 = step;\n }\n \n while (maxIter-- > 0) {\n step = tickIncrement(start, stop, count);\n if (step === prestep) {\n d[i0] = start\n d[i1] = stop\n return domain(d);\n } else if (step > 0) {\n start = Math.floor(start / step) * step;\n stop = Math.ceil(stop / step) * step;\n } else if (step < 0) {\n start = Math.ceil(start * step) / step;\n stop = Math.floor(stop * step) / step;\n } else {\n break;\n }\n prestep = step;\n }\n\n return scale;\n };\n\n return scale;\n}\n\nexport default function linear() {\n var scale = continuous();\n\n scale.copy = function() {\n return copy(scale, linear());\n };\n\n initRange.apply(scale, arguments);\n\n return linearish(scale);\n}\n", "const t0 = new Date, t1 = new Date;\n\nexport function timeInterval(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 = (date) => {\n return floori(date = new Date(+date)), date;\n };\n\n interval.ceil = (date) => {\n return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date;\n };\n\n interval.round = (date) => {\n const d0 = interval(date), d1 = interval.ceil(date);\n return date - d0 < d1 - date ? d0 : d1;\n };\n\n interval.offset = (date, step) => {\n return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date;\n };\n\n interval.range = (start, stop, step) => {\n const range = [];\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 let previous;\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 = (test) => {\n return timeInterval((date) => {\n if (date >= date) while (floori(date), !test(date)) date.setTime(date - 1);\n }, (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 = (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 = (step) => {\n step = Math.floor(step);\n return !isFinite(step) || !(step > 0) ? null\n : !(step > 1) ? interval\n : interval.filter(field\n ? (d) => field(d) % step === 0\n : (d) => interval.count(0, d) % step === 0);\n };\n }\n\n return interval;\n}\n", "import {timeInterval} from \"./interval.js\";\n\nexport const millisecond = timeInterval(() => {\n // noop\n}, (date, step) => {\n date.setTime(+date + step);\n}, (start, end) => {\n return end - start;\n});\n\n// An optimized implementation for this simple case.\nmillisecond.every = (k) => {\n k = Math.floor(k);\n if (!isFinite(k) || !(k > 0)) return null;\n if (!(k > 1)) return millisecond;\n return timeInterval((date) => {\n date.setTime(Math.floor(date / k) * k);\n }, (date, step) => {\n date.setTime(+date + step * k);\n }, (start, end) => {\n return (end - start) / k;\n });\n};\n\nexport const milliseconds = millisecond.range;\n", "import {timeInterval} from \"./interval.js\";\nimport {durationSecond} from \"./duration.js\";\n\nexport const second = timeInterval((date) => {\n date.setTime(date - date.getMilliseconds());\n}, (date, step) => {\n date.setTime(+date + step * durationSecond);\n}, (start, end) => {\n return (end - start) / durationSecond;\n}, (date) => {\n return date.getUTCSeconds();\n});\n\nexport const seconds = second.range;\n", "import {timeInterval} from \"./interval.js\";\nimport {durationMinute, durationSecond} from \"./duration.js\";\n\nexport const timeMinute = timeInterval((date) => {\n date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond);\n}, (date, step) => {\n date.setTime(+date + step * durationMinute);\n}, (start, end) => {\n return (end - start) / durationMinute;\n}, (date) => {\n return date.getMinutes();\n});\n\nexport const timeMinutes = timeMinute.range;\n\nexport const utcMinute = timeInterval((date) => {\n date.setUTCSeconds(0, 0);\n}, (date, step) => {\n date.setTime(+date + step * durationMinute);\n}, (start, end) => {\n return (end - start) / durationMinute;\n}, (date) => {\n return date.getUTCMinutes();\n});\n\nexport const utcMinutes = utcMinute.range;\n", "import {timeInterval} from \"./interval.js\";\nimport {durationHour, durationMinute, durationSecond} from \"./duration.js\";\n\nexport const timeHour = timeInterval((date) => {\n date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond - date.getMinutes() * durationMinute);\n}, (date, step) => {\n date.setTime(+date + step * durationHour);\n}, (start, end) => {\n return (end - start) / durationHour;\n}, (date) => {\n return date.getHours();\n});\n\nexport const timeHours = timeHour.range;\n\nexport const utcHour = timeInterval((date) => {\n date.setUTCMinutes(0, 0, 0);\n}, (date, step) => {\n date.setTime(+date + step * durationHour);\n}, (start, end) => {\n return (end - start) / durationHour;\n}, (date) => {\n return date.getUTCHours();\n});\n\nexport const utcHours = utcHour.range;\n", "import {timeInterval} from \"./interval.js\";\nimport {durationDay, durationMinute} from \"./duration.js\";\n\nexport const timeDay = timeInterval(\n date => date.setHours(0, 0, 0, 0),\n (date, step) => date.setDate(date.getDate() + step),\n (start, end) => (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay,\n date => date.getDate() - 1\n);\n\nexport const timeDays = timeDay.range;\n\nexport const utcDay = timeInterval((date) => {\n date.setUTCHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setUTCDate(date.getUTCDate() + step);\n}, (start, end) => {\n return (end - start) / durationDay;\n}, (date) => {\n return date.getUTCDate() - 1;\n});\n\nexport const utcDays = utcDay.range;\n\nexport const unixDay = timeInterval((date) => {\n date.setUTCHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setUTCDate(date.getUTCDate() + step);\n}, (start, end) => {\n return (end - start) / durationDay;\n}, (date) => {\n return Math.floor(date / durationDay);\n});\n\nexport const unixDays = unixDay.range;\n", "import {timeInterval} from \"./interval.js\";\nimport {durationMinute, durationWeek} from \"./duration.js\";\n\nfunction timeWeekday(i) {\n return timeInterval((date) => {\n date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7);\n date.setHours(0, 0, 0, 0);\n }, (date, step) => {\n date.setDate(date.getDate() + step * 7);\n }, (start, end) => {\n return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek;\n });\n}\n\nexport const timeSunday = timeWeekday(0);\nexport const timeMonday = timeWeekday(1);\nexport const timeTuesday = timeWeekday(2);\nexport const timeWednesday = timeWeekday(3);\nexport const timeThursday = timeWeekday(4);\nexport const timeFriday = timeWeekday(5);\nexport const timeSaturday = timeWeekday(6);\n\nexport const timeSundays = timeSunday.range;\nexport const timeMondays = timeMonday.range;\nexport const timeTuesdays = timeTuesday.range;\nexport const timeWednesdays = timeWednesday.range;\nexport const timeThursdays = timeThursday.range;\nexport const timeFridays = timeFriday.range;\nexport const timeSaturdays = timeSaturday.range;\n\nfunction utcWeekday(i) {\n return timeInterval((date) => {\n date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7);\n date.setUTCHours(0, 0, 0, 0);\n }, (date, step) => {\n date.setUTCDate(date.getUTCDate() + step * 7);\n }, (start, end) => {\n return (end - start) / durationWeek;\n });\n}\n\nexport const utcSunday = utcWeekday(0);\nexport const utcMonday = utcWeekday(1);\nexport const utcTuesday = utcWeekday(2);\nexport const utcWednesday = utcWeekday(3);\nexport const utcThursday = utcWeekday(4);\nexport const utcFriday = utcWeekday(5);\nexport const utcSaturday = utcWeekday(6);\n\nexport const utcSundays = utcSunday.range;\nexport const utcMondays = utcMonday.range;\nexport const utcTuesdays = utcTuesday.range;\nexport const utcWednesdays = utcWednesday.range;\nexport const utcThursdays = utcThursday.range;\nexport const utcFridays = utcFriday.range;\nexport const utcSaturdays = utcSaturday.range;\n", "import {timeInterval} from \"./interval.js\";\n\nexport const timeMonth = timeInterval((date) => {\n date.setDate(1);\n date.setHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setMonth(date.getMonth() + step);\n}, (start, end) => {\n return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;\n}, (date) => {\n return date.getMonth();\n});\n\nexport const timeMonths = timeMonth.range;\n\nexport const utcMonth = timeInterval((date) => {\n date.setUTCDate(1);\n date.setUTCHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setUTCMonth(date.getUTCMonth() + step);\n}, (start, end) => {\n return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;\n}, (date) => {\n return date.getUTCMonth();\n});\n\nexport const utcMonths = utcMonth.range;\n", "import {timeInterval} from \"./interval.js\";\n\nexport const timeYear = timeInterval((date) => {\n date.setMonth(0, 1);\n date.setHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setFullYear(date.getFullYear() + step);\n}, (start, end) => {\n return end.getFullYear() - start.getFullYear();\n}, (date) => {\n return date.getFullYear();\n});\n\n// An optimized implementation for this simple case.\ntimeYear.every = (k) => {\n return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date) => {\n date.setFullYear(Math.floor(date.getFullYear() / k) * k);\n date.setMonth(0, 1);\n date.setHours(0, 0, 0, 0);\n }, (date, step) => {\n date.setFullYear(date.getFullYear() + step * k);\n });\n};\n\nexport const timeYears = timeYear.range;\n\nexport const utcYear = timeInterval((date) => {\n date.setUTCMonth(0, 1);\n date.setUTCHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setUTCFullYear(date.getUTCFullYear() + step);\n}, (start, end) => {\n return end.getUTCFullYear() - start.getUTCFullYear();\n}, (date) => {\n return date.getUTCFullYear();\n});\n\n// An optimized implementation for this simple case.\nutcYear.every = (k) => {\n return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date) => {\n date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k);\n date.setUTCMonth(0, 1);\n date.setUTCHours(0, 0, 0, 0);\n }, (date, step) => {\n date.setUTCFullYear(date.getUTCFullYear() + step * k);\n });\n};\n\nexport const utcYears = utcYear.range;\n", "import {bisector, tickStep} from \"d3-array\";\nimport {durationDay, durationHour, durationMinute, durationMonth, durationSecond, durationWeek, durationYear} from \"./duration.js\";\nimport {millisecond} from \"./millisecond.js\";\nimport {second} from \"./second.js\";\nimport {timeMinute, utcMinute} from \"./minute.js\";\nimport {timeHour, utcHour} from \"./hour.js\";\nimport {timeDay, unixDay} from \"./day.js\";\nimport {timeSunday, utcSunday} from \"./week.js\";\nimport {timeMonth, utcMonth} from \"./month.js\";\nimport {timeYear, utcYear} from \"./year.js\";\n\nfunction ticker(year, month, week, day, hour, minute) {\n\n const 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 ticks(start, stop, count) {\n const reverse = stop < start;\n if (reverse) [start, stop] = [stop, start];\n const interval = count && typeof count.range === \"function\" ? count : tickInterval(start, stop, count);\n const ticks = interval ? interval.range(start, +stop + 1) : []; // inclusive stop\n return reverse ? ticks.reverse() : ticks;\n }\n\n function tickInterval(start, stop, count) {\n const target = Math.abs(stop - start) / count;\n const i = bisector(([,, step]) => step).right(tickIntervals, target);\n if (i === tickIntervals.length) return year.every(tickStep(start / durationYear, stop / durationYear, count));\n if (i === 0) return millisecond.every(Math.max(tickStep(start, stop, count), 1));\n const [t, step] = tickIntervals[target / tickIntervals[i - 1][2] < tickIntervals[i][2] / target ? i - 1 : i];\n return t.every(step);\n }\n\n return [ticks, tickInterval];\n}\n\nconst [utcTicks, utcTickInterval] = ticker(utcYear, utcMonth, utcSunday, unixDay, utcHour, utcMinute);\nconst [timeTicks, timeTickInterval] = ticker(timeYear, timeMonth, timeSunday, timeDay, timeHour, timeMinute);\n\nexport {utcTicks, utcTickInterval, timeTicks, timeTickInterval};\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.get(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.get(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.get(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.get(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.get(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 return new Map(names.map((name, i) => [name.toLowerCase(), i]));\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 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 function nice(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", "import {timeYear, timeMonth, timeWeek, timeDay, timeHour, timeMinute, timeSecond, timeTicks, timeTickInterval} from \"d3-time\";\nimport {timeFormat} from \"d3-time-format\";\nimport continuous, {copy} from \"./continuous.js\";\nimport {initRange} from \"./init.js\";\nimport nice from \"./nice.js\";\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(ticks, tickInterval, year, month, week, day, hour, minute, second, format) {\n var scale = continuous(),\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 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 scale.invert = function(y) {\n return new Date(invert(y));\n };\n\n scale.domain = function(_) {\n return arguments.length ? domain(Array.from(_, number)) : domain().map(date);\n };\n\n scale.ticks = function(interval) {\n var d = domain();\n return ticks(d[0], d[d.length - 1], interval == null ? 10 : interval);\n };\n\n scale.tickFormat = function(count, specifier) {\n return specifier == null ? tickFormat : format(specifier);\n };\n\n scale.nice = function(interval) {\n var d = domain();\n if (!interval || typeof interval.range !== \"function\") interval = tickInterval(d[0], d[d.length - 1], interval == null ? 10 : interval);\n return interval ? domain(nice(d, interval)) : scale;\n };\n\n scale.copy = function() {\n return copy(scale, calendar(ticks, tickInterval, year, month, week, day, hour, minute, second, format));\n };\n\n return scale;\n}\n\nexport default function time() {\n return initRange.apply(calendar(timeTicks, timeTickInterval, timeYear, timeMonth, timeWeek, timeDay, timeHour, timeMinute, timeSecond, timeFormat).domain([new Date(2000, 0, 1), new Date(2000, 0, 2)]), arguments);\n}\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\";\n\nexport default colors(\"4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab\");\n", "export default function(x) {\n return function constant() {\n return x;\n };\n}\n", "export const abs = Math.abs;\nexport const atan2 = Math.atan2;\nexport const cos = Math.cos;\nexport const max = Math.max;\nexport const min = Math.min;\nexport const sin = Math.sin;\nexport const sqrt = Math.sqrt;\n\nexport const epsilon = 1e-12;\nexport const pi = Math.PI;\nexport const halfPi = pi / 2;\nexport const 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", "const pi = Math.PI,\n tau = 2 * pi,\n epsilon = 1e-6,\n tauEpsilon = tau - epsilon;\n\nfunction append(strings) {\n this._ += strings[0];\n for (let i = 1, n = strings.length; i < n; ++i) {\n this._ += arguments[i] + strings[i];\n }\n}\n\nfunction appendRound(digits) {\n let d = Math.floor(digits);\n if (!(d >= 0)) throw new Error(`invalid digits: ${digits}`);\n if (d > 15) return append;\n const k = 10 ** d;\n return function(strings) {\n this._ += strings[0];\n for (let i = 1, n = strings.length; i < n; ++i) {\n this._ += Math.round(arguments[i] * k) / k + strings[i];\n }\n };\n}\n\nexport class Path {\n constructor(digits) {\n this._x0 = this._y0 = // start of current subpath\n this._x1 = this._y1 = null; // end of current subpath\n this._ = \"\";\n this._append = digits == null ? append : appendRound(digits);\n }\n moveTo(x, y) {\n this._append`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._append`Z`;\n }\n }\n lineTo(x, y) {\n this._append`L${this._x1 = +x},${this._y1 = +y}`;\n }\n quadraticCurveTo(x1, y1, x, y) {\n this._append`Q${+x1},${+y1},${this._x1 = +x},${this._y1 = +y}`;\n }\n bezierCurveTo(x1, y1, x2, y2, x, y) {\n this._append`C${+x1},${+y1},${+x2},${+y2},${this._x1 = +x},${this._y1 = +y}`;\n }\n arcTo(x1, y1, x2, y2, r) {\n x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;\n\n // Is the radius negative? Error.\n if (r < 0) throw new Error(`negative radius: ${r}`);\n\n let 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 this path empty? Move to (x1,y1).\n if (this._x1 === null) {\n this._append`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._append`L${this._x1 = x1},${this._y1 = y1}`;\n }\n\n // Otherwise, draw an arc!\n else {\n let 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._append`L${x1 + t01 * x01},${y1 + t01 * y01}`;\n }\n\n this._append`A${r},${r},0,0,${+(y01 * x20 > x01 * y20)},${this._x1 = x1 + t21 * x21},${this._y1 = y1 + t21 * y21}`;\n }\n }\n arc(x, y, r, a0, a1, ccw) {\n x = +x, y = +y, r = +r, ccw = !!ccw;\n\n // Is the radius negative? Error.\n if (r < 0) throw new Error(`negative radius: ${r}`);\n\n let 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 this path empty? Move to (x0,y0).\n if (this._x1 === null) {\n this._append`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._append`L${x0},${y0}`;\n }\n\n // Is this arc empty? We\u2019re 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._append`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._append`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(x, y, w, h) {\n this._append`M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}h${w = +w}v${+h}h${-w}Z`;\n }\n toString() {\n return this._;\n }\n}\n\nexport function path() {\n return new Path;\n}\n\n// Allow instanceof d3.path\npath.prototype = Path.prototype;\n\nexport function pathRound(digits = 3) {\n return new Path(+digits);\n}\n", "import {Path} from \"d3-path\";\n\nexport function withPath(shape) {\n let digits = 3;\n\n shape.digits = function(_) {\n if (!arguments.length) return digits;\n if (_ == null) {\n digits = null;\n } else {\n const d = Math.floor(_);\n if (!(d >= 0)) throw new RangeError(`invalid digits: ${_}`);\n digits = d;\n }\n return shape;\n };\n\n return () => new Path(digits);\n}\n", "import constant from \"./constant.js\";\nimport {abs, acos, asin, atan2, cos, epsilon, halfPi, max, min, pi, sin, sqrt, tau} from \"./math.js\";\nimport {withPath} from \"./path.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 path = withPath(arc);\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 \u2265 r0, da1 \u2265 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. If this\n // intersection fails, it\u2019s probably because the arc is too small, so\n // disable the corner radius entirely.\n if (da < pi) {\n if (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 } else {\n rc0 = rc1 = 0;\n }\n }\n }\n\n // Is the sector collapsed to a line?\n if (!(da1 > epsilon)) context.moveTo(x01, y01);\n\n // Does the sector\u2019s 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\u2019s a circular sector?\n // Or perhaps it\u2019s an annular sector collapsed due to padding?\n if (!(r0 > epsilon) || !(da0 > epsilon)) context.lineTo(x10, y10);\n\n // Does the sector\u2019s 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", "export var slice = Array.prototype.slice;\n\nexport default function(x) {\n return typeof x === \"object\" && \"length\" in x\n ? x // Array, TypedArray, NodeList, array-like\n : Array.from(x); // Map, Set, iterable, string, or anything else\n}\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; // falls through\n default: this._context.lineTo(x, y); break;\n }\n }\n};\n\nexport default function(context) {\n return new Linear(context);\n}\n", "export function x(p) {\n return p[0];\n}\n\nexport function y(p) {\n return p[1];\n}\n", "import array from \"./array.js\";\nimport constant from \"./constant.js\";\nimport curveLinear from \"./curve/linear.js\";\nimport {withPath} from \"./path.js\";\nimport {x as pointX, y as pointY} from \"./point.js\";\n\nexport default function(x, y) {\n var defined = constant(true),\n context = null,\n curve = curveLinear,\n output = null,\n path = withPath(line);\n\n x = typeof x === \"function\" ? x : (x === undefined) ? pointX : constant(x);\n y = typeof y === \"function\" ? y : (y === undefined) ? pointY : constant(y);\n\n function line(data) {\n var i,\n n = (data = array(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", "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", "import array from \"./array.js\";\nimport 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 = array(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 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); // falls through\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); // falls through\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 pointRadial from \"../pointRadial.js\";\n\nclass Bump {\n constructor(context, x) {\n this._context = context;\n this._x = x;\n }\n areaStart() {\n this._line = 0;\n }\n areaEnd() {\n this._line = NaN;\n }\n lineStart() {\n this._point = 0;\n }\n lineEnd() {\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n this._line = 1 - this._line;\n }\n point(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: {\n this._point = 1;\n if (this._line) this._context.lineTo(x, y);\n else this._context.moveTo(x, y);\n break;\n }\n case 1: this._point = 2; // falls through\n default: {\n if (this._x) this._context.bezierCurveTo(this._x0 = (this._x0 + x) / 2, this._y0, this._x0, y, x, y);\n else this._context.bezierCurveTo(this._x0, this._y0 = (this._y0 + y) / 2, x, this._y0, x, y);\n break;\n }\n }\n this._x0 = x, this._y0 = y;\n }\n}\n\nclass BumpRadial {\n constructor(context) {\n this._context = context;\n }\n lineStart() {\n this._point = 0;\n }\n lineEnd() {}\n point(x, y) {\n x = +x, y = +y;\n if (this._point === 0) {\n this._point = 1;\n } else {\n const p0 = pointRadial(this._x0, this._y0);\n const p1 = pointRadial(this._x0, this._y0 = (this._y0 + y) / 2);\n const p2 = pointRadial(x, this._y0);\n const p3 = pointRadial(x, y);\n this._context.moveTo(...p0);\n this._context.bezierCurveTo(...p1, ...p2, ...p3);\n }\n this._x0 = x, this._y0 = y;\n }\n}\n\nexport function bumpX(context) {\n return new Bump(context, true);\n}\n\nexport function bumpY(context) {\n return new Bump(context, false);\n}\n\nexport function bumpRadial(context) {\n return new BumpRadial(context);\n}\n", "export default function() {}\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; // falls through\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; // falls through\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; // falls through\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; // falls through\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; // falls through\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", "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\u00E9zier 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", "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; // falls through\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", "var noop = {value: () => {}};\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", "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\u2019ve set an alarm, if we haven\u2019t already.\n var t = taskHead, e;\n while (t) {\n if ((e = clockNow - t._time) >= 0) t._call.call(undefined, 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 {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(elapsed => {\n t.stop();\n callback(elapsed + delay);\n }, delay, time);\n return t;\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 {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 interrupt from \"../interrupt.js\";\n\nexport default function(name) {\n return this.each(function() {\n interrupt(this, name);\n });\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\u2019re 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\u2019re 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 {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 {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\nfunction easeVarying(id, value) {\n return function() {\n var v = value.apply(this, arguments);\n if (typeof v !== \"function\") throw new Error;\n set(this, id).ease = v;\n };\n}\n\nexport default function(value) {\n if (typeof value !== \"function\") throw new Error;\n return this.each(easeVarying(this._id, value));\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 {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\u2019re 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 {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\u2019re 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 {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\u2019re 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 // The selection was empty, resolve end immediately\n if (size === 0) resolve();\n });\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_easeVarying from \"./easeVarying.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 selectChild: selection_prototype.selectChild,\n selectChildren: selection_prototype.selectChildren,\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 easeVarying: transition_easeVarying,\n end: transition_end,\n [Symbol.iterator]: selection_prototype[Symbol.iterator]\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 {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 throw new Error(`transition ${id} not found`);\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 {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 {dispatch} from \"d3-dispatch\";\nimport {dragDisable, dragEnable} from \"d3-drag\";\nimport {interpolate} from \"d3-interpolate\";\nimport {pointer, 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\nconst {abs, max, min} = Math;\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\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(event) {\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 \u201C__brush\u201D 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, event) {\n if (group.tween) {\n group\n .on(\"start.brush\", function(event) { emitter(this, arguments).beforestart().start(event); })\n .on(\"interrupt.brush end.brush\", function(event) { emitter(this, arguments).end(event); })\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(event).brush(event).end(event);\n });\n }\n };\n\n brush.clear = function(group, event) {\n brush.move(group, null, event);\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(event, mode) {\n if (this.starting) this.starting = false, this.emit(\"start\", event, mode);\n else this.emit(\"brush\", event);\n return this;\n },\n brush: function(event, mode) {\n this.emit(\"brush\", event, mode);\n return this;\n },\n end: function(event, mode) {\n if (--this.active === 0) delete this.state.emitter, this.emit(\"end\", event, mode);\n return this;\n },\n emit: function(type, event, mode) {\n var d = select(this.that).datum();\n listeners.call(\n type,\n this.that,\n new BrushEvent(type, {\n sourceEvent: event,\n target: brush,\n selection: dim.output(this.state.selection),\n mode,\n dispatch: listeners\n }),\n d\n );\n }\n };\n\n function started(event) {\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 points = Array.from(event.touches || [event], t => {\n const i = t.identifier;\n t = pointer(t, that);\n t.point0 = t.slice();\n t.identifier = i;\n return t;\n });\n\n interrupt(that);\n var emit = emitter(that, arguments, true).beforestart();\n\n if (type === \"overlay\") {\n if (selection) moving = true;\n const pts = [points[0], points[1] || points[0]];\n state.selection = selection = [[\n w0 = dim === Y ? W : min(pts[0][0], pts[1][0]),\n n0 = dim === X ? N : min(pts[0][1], pts[1][1])\n ], [\n e0 = dim === Y ? E : max(pts[0][0], pts[1][0]),\n s0 = dim === X ? S : max(pts[0][1], pts[1][1])\n ]];\n if (points.length > 1) move(event);\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 redraw.call(that);\n emit.start(event, mode.name);\n\n function moved(event) {\n for (const p of event.changedTouches || [event]) {\n for (const d of points)\n if (d.identifier === p.identifier) d.cur = pointer(p, that);\n }\n if (shifting && !lockX && !lockY && points.length === 1) {\n const point = points[0];\n if (abs(point.cur[0] - point[0]) > abs(point.cur[1] - point[1]))\n lockY = true;\n else\n lockX = true;\n }\n for (const point of points)\n if (point.cur) point[0] = point.cur[0], point[1] = point.cur[1];\n moving = true;\n noevent(event);\n move(event);\n }\n\n function move(event) {\n const point = points[0], point0 = point.point0;\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 = max(W - w0, min(E - e0, dx)), w1 = w0 + dx, e1 = e0 + dx;\n if (signY) dy = max(N - n0, min(S - s0, dy)), n1 = n0 + dy, s1 = s0 + dy;\n break;\n }\n case MODE_HANDLE: {\n if (points[1]) {\n if (signX) w1 = max(W, min(E, points[0][0])), e1 = max(W, min(E, points[1][0])), signX = 1;\n if (signY) n1 = max(N, min(S, points[0][1])), s1 = max(N, min(S, points[1][1])), signY = 1;\n } else {\n if (signX < 0) dx = max(W - w0, min(E - w0, dx)), w1 = w0 + dx, e1 = e0;\n else if (signX > 0) dx = max(W - e0, min(E - e0, dx)), w1 = w0, e1 = e0 + dx;\n if (signY < 0) dy = max(N - n0, min(S - n0, dy)), n1 = n0 + dy, s1 = s0;\n else if (signY > 0) dy = max(N - s0, min(S - s0, dy)), n1 = n0, s1 = s0 + dy;\n }\n break;\n }\n case MODE_CENTER: {\n if (signX) w1 = max(W, min(E, w0 - dx * signX)), e1 = max(W, min(E, e0 + dx * signX));\n if (signY) n1 = max(N, min(S, n0 - dy * signY)), s1 = max(N, 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(event, mode.name);\n }\n }\n\n function ended(event) {\n nopropagation(event);\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(event, mode.name);\n }\n\n function keydowned(event) {\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(event);\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(event);\n }\n break;\n }\n default: return;\n }\n noevent(event);\n }\n\n function keyupped(event) {\n switch (event.keyCode) {\n case 16: { // SHIFT\n if (shifting) {\n lockX = lockY = shifting = false;\n move(event);\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(event);\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(event);\n }\n break;\n }\n default: return;\n }\n noevent(event);\n }\n }\n\n function touchmoved(event) {\n emitter(this, arguments).moved(event);\n }\n\n function touchended(event) {\n emitter(this, arguments).ended(event);\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 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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AASD,EAAG,CACpB,OAAOA,EAAE,KAAK,EAAE,OAAOA,EAAE,MAAM,EAAE,IAAI,KAAK,QAAS,IAAI,EAAE,IAAIA,EAAE,OAAQA,CAAC,CAAC,CAC3E,EACA,SAAU,SAASC,EAAG,CACpB,OAAOA,EAAE,KAAK,EAAE,OAAOA,EAAE,MAAM,EAAE,IAAI,KAAK,QAAS,IAAI,EAAE,IAAIA,EAAE,OAAQA,CAAC,CAAC,CAC3E,EACA,SAAU,UAAW,CACnB,MAAO,aAAe,KAAK,EAAI,IAAM,KAAK,EAAI,WAAa,KAAK,EAAI,GACtE,CACF,EAEO,IAAIG,GAAW,IAAIN,GAAU,EAAG,EAAG,CAAC,EAE3CO,GAAU,UAAYP,GAAU,UAEjB,SAARO,GAA2BC,EAAM,CACtC,KAAO,CAACA,EAAK,QAAQ,GAAI,EAAEA,EAAOA,EAAK,YAAa,OAAOF,GAC3D,OAAOE,EAAK,MACd", + "names": ["require_dayjs_min", "__commonJSMin", "exports", "module", "s", "u", "a", "o", "c", "f", "d", "l", "$", "y", "t", "e", "n", "m", "r", "v", "i", "g", "D", "p", "S", "_", "w", "O", "b", "M", "h", "k", "import_dayjs", "__defProp", "__name", "target", "value", "__export", "all", "name", "LEVELS", "log", "_args", "setLogLevel", "level", "numericLevel", "format", "dayjs", "max", "values", "valueof", "value", "index", "min", "values", "valueof", "value", "index", "ascending", "a", "b", "descending", "a", "b", "bisector", "f", "compare1", "compare2", "delta", "ascending", "d", "x", "descending", "zero", "left", "a", "lo", "hi", "mid", "right", "center", "i", "number", "x", "ascendingBisect", "bisector", "ascending", "bisectRight", "bisectLeft", "bisectCenter", "number", "bisect_default", "InternMap", "entries", "key", "keyof", "value", "intern_get", "intern_set", "intern_delete", "intern_get", "_intern", "_key", "value", "key", "intern_set", "intern_delete", "keyof", "e10", "e5", "e2", "tickSpec", "start", "stop", "count", "step", "power", "error", "factor", "i1", "i2", "inc", "ticks", "reverse", "n", "i", "tickIncrement", "tickStep", "range", "start", "stop", "step", "n", "i", "identity_default", "x", "top", "right", "bottom", "left", "epsilon", "translateX", "x", "translateY", "y", "number", "scale", "d", "center", "offset", "entering", "axis", "orient", "tickArguments", "tickValues", "tickFormat", "tickSizeInner", "tickSizeOuter", "tickPadding", "k", "transform", "context", "values", "format", "identity_default", "spacing", "range", "range0", "range1", "position", "selection", "path", "tick", "tickExit", "tickEnter", "line", "text", "p", "_", "axisTop", "axisBottom", "scale", "axis", "bottom", "none", "selector_default", "selector", "select_default", "select", "selector_default", "groups", "m", "subgroups", "j", "group", "n", "subgroup", "node", "subnode", "i", "Selection", "array", "x", "empty", "selectorAll_default", "selector", "arrayAll", "select", "array", "selectAll_default", "selectorAll_default", "groups", "m", "subgroups", "parents", "j", "group", "n", "node", "i", "Selection", "matcher_default", "selector", "childMatcher", "node", "find", "childFind", "match", "childFirst", "selectChild_default", "childMatcher", "filter", "children", "childrenFilter", "match", "selectChildren_default", "childMatcher", "filter_default", "match", "matcher_default", "groups", "m", "subgroups", "j", "group", "n", "subgroup", "node", "i", "Selection", "sparse_default", "update", "enter_default", "Selection", "sparse_default", "EnterNode", "parent", "datum", "child", "next", "selector", "constant_default", "x", "bindIndex", "parent", "group", "enter", "update", "exit", "data", "i", "node", "groupLength", "dataLength", "EnterNode", "bindKey", "key", "nodeByKeyValue", "keyValues", "keyValue", "datum", "data_default", "value", "bind", "parents", "groups", "constant_default", "m", "j", "arraylike", "enterGroup", "updateGroup", "exitGroup", "i0", "i1", "previous", "next", "Selection", "exit_default", "Selection", "sparse_default", "join_default", "onenter", "onupdate", "onexit", "enter", "update", "exit", "merge_default", "context", "selection", "groups0", "groups1", "m0", "m1", "m", "merges", "j", "group0", "group1", "n", "merge", "node", "i", "Selection", "order_default", "groups", "j", "m", "group", "next", "node", "sort_default", "compare", "ascending", "compareNode", "a", "b", "groups", "m", "sortgroups", "j", "group", "n", "sortgroup", "node", "i", "Selection", "call_default", "callback", "nodes_default", "node_default", "groups", "j", "m", "group", "n", "node", "size_default", "size", "node", "empty_default", "each_default", "callback", "groups", "j", "m", "group", "i", "n", "node", "xhtml", "namespaces_default", "namespace_default", "name", "prefix", "i", "namespaces_default", "attrRemove", "name", "attrRemoveNS", "fullname", "attrConstant", "value", "attrConstantNS", "attrFunction", "v", "attrFunctionNS", "attr_default", "namespace_default", "node", "window_default", "node", "styleRemove", "name", "styleConstant", "value", "priority", "styleFunction", "v", "style_default", "styleValue", "node", "window_default", "propertyRemove", "name", "propertyConstant", "value", "propertyFunction", "v", "property_default", "classArray", "string", "classList", "node", "ClassList", "name", "i", "classedAdd", "names", "list", "n", "classedRemove", "classedTrue", "classedFalse", "classedFunction", "value", "classed_default", "textRemove", "textConstant", "value", "textFunction", "v", "text_default", "htmlRemove", "htmlConstant", "value", "htmlFunction", "v", "html_default", "raise", "raise_default", "lower", "lower_default", "creatorInherit", "name", "document", "uri", "xhtml", "creatorFixed", "fullname", "creator_default", "namespace_default", "append_default", "name", "create", "creator_default", "constantNull", "insert_default", "name", "before", "create", "creator_default", "select", "selector_default", "remove", "parent", "remove_default", "selection_cloneShallow", "clone", "parent", "selection_cloneDeep", "clone_default", "deep", "datum_default", "value", "contextListener", "listener", "event", "parseTypenames", "typenames", "t", "name", "i", "onRemove", "typename", "on", "j", "m", "onAdd", "value", "options", "o", "on_default", "n", "dispatchEvent", "node", "type", "params", "window", "window_default", "event", "dispatchConstant", "dispatchFunction", "dispatch_default", "iterator_default", "groups", "j", "m", "group", "n", "node", "root", "Selection", "groups", "parents", "selection", "selection_selection", "select_default", "selectAll_default", "selectChild_default", "selectChildren_default", "filter_default", "data_default", "enter_default", "exit_default", "join_default", "merge_default", "order_default", "sort_default", "call_default", "nodes_default", "node_default", "size_default", "empty_default", "each_default", "attr_default", "style_default", "property_default", "classed_default", "text_default", "html_default", "raise_default", "lower_default", "append_default", "insert_default", "remove_default", "clone_default", "datum_default", "on_default", "dispatch_default", "iterator_default", "selection_default", "select_default", "selector", "Selection", "root", "define_default", "constructor", "factory", "prototype", "extend", "parent", "definition", "key", "Color", "darker", "brighter", "reI", "reN", "reP", "reHex", "reRgbInteger", "reRgbPercent", "reRgbaInteger", "reRgbaPercent", "reHslPercent", "reHslaPercent", "named", "define_default", "color", "channels", "color_formatHex", "color_formatHex8", "color_formatHsl", "color_formatRgb", "hslConvert", "format", "m", "l", "rgbn", "Rgb", "rgba", "hsla", "n", "r", "g", "b", "a", "rgbConvert", "o", "rgb", "opacity", "extend", "k", "clampi", "clampa", "rgb_formatHex", "rgb_formatHex8", "rgb_formatRgb", "hex", "value", "h", "s", "Hsl", "min", "max", "hsl", "m2", "m1", "hsl2rgb", "clamph", "clampt", "radians", "degrees", "K", "Xn", "Yn", "Zn", "t0", "t1", "t2", "t3", "labConvert", "o", "Lab", "Hcl", "hcl2lab", "Rgb", "rgbConvert", "r", "rgb2lrgb", "g", "b", "y", "xyz2lab", "x", "z", "lab", "l", "a", "b", "opacity", "labConvert", "Lab", "define_default", "extend", "Color", "k", "K", "y", "x", "z", "Xn", "lab2xyz", "Yn", "Zn", "Rgb", "lrgb2rgb", "xyz2lab", "t3", "t2", "t0", "t1", "rgb2lrgb", "hclConvert", "o", "Hcl", "h", "degrees", "hcl", "h", "c", "l", "opacity", "hclConvert", "Hcl", "hcl2lab", "o", "Lab", "radians", "define_default", "extend", "Color", "k", "K", "constant_default", "x", "linear", "a", "d", "t", "exponential", "b", "y", "hue", "constant_default", "gamma", "nogamma", "hcl", "hue", "start", "end", "h", "c", "nogamma", "l", "opacity", "t", "hcl_default", "hclLong", "basis", "t1", "v0", "v1", "v2", "v3", "t2", "t3", "basis_default", "values", "n", "t", "i", "basisClosed_default", "values", "n", "t", "i", "v0", "v1", "v2", "v3", "basis", "rgb_default", "rgbGamma", "y", "color", "gamma", "rgb", "start", "end", "r", "g", "b", "opacity", "nogamma", "t", "rgbSpline", "spline", "colors", "i", "rgbBasis", "basis_default", "rgbBasisClosed", "basisClosed_default", "numberArray_default", "a", "b", "c", "t", "isNumberArray", "x", "genericArray", "a", "b", "nb", "na", "x", "c", "i", "value_default", "t", "date_default", "a", "b", "d", "t", "number_default", "a", "b", "t", "object_default", "a", "b", "i", "c", "k", "value_default", "t", "reA", "reB", "zero", "b", "one", "t", "string_default", "a", "bi", "am", "bm", "bs", "i", "q", "number_default", "o", "value_default", "a", "b", "t", "c", "constant_default", "number_default", "color", "rgb_default", "string_default", "date_default", "isNumberArray", "numberArray_default", "genericArray", "object_default", "round_default", "a", "b", "t", "degrees", "identity", "decompose_default", "a", "b", "c", "d", "e", "f", "scaleX", "scaleY", "skewX", "svgNode", "parseCss", "value", "m", "identity", "decompose_default", "parseSvg", "interpolateTransform", "parse", "pxComma", "pxParen", "degParen", "pop", "s", "translate", "xa", "ya", "xb", "yb", "q", "i", "number_default", "rotate", "a", "b", "skewX", "scale", "t", "n", "o", "interpolateTransformCss", "parseCss", "interpolateTransformSvg", "parseSvg", "formatDecimal_default", "x", "formatDecimalParts", "p", "i", "coefficient", "exponent_default", "x", "formatDecimalParts", "formatGroup_default", "grouping", "thousands", "value", "width", "t", "j", "g", "length", "formatNumerals_default", "numerals", "value", "i", "re", "formatSpecifier", "specifier", "match", "FormatSpecifier", "formatTrim_default", "s", "out", "n", "i", "i0", "i1", "prefixExponent", "formatPrefixAuto_default", "x", "p", "d", "formatDecimalParts", "coefficient", "exponent", "i", "n", "formatRounded_default", "x", "p", "d", "formatDecimalParts", "coefficient", "exponent", "formatTypes_default", "x", "p", "formatDecimal_default", "formatRounded_default", "formatPrefixAuto_default", "identity_default", "x", "map", "prefixes", "locale_default", "locale", "group", "identity_default", "formatGroup_default", "currencyPrefix", "currencySuffix", "decimal", "numerals", "formatNumerals_default", "percent", "minus", "nan", "newFormat", "specifier", "formatSpecifier", "fill", "align", "sign", "symbol", "zero", "width", "comma", "precision", "trim", "type", "formatTypes_default", "prefix", "suffix", "formatType", "maybeSuffix", "format", "value", "valuePrefix", "valueSuffix", "i", "n", "c", "valueNegative", "formatTrim_default", "prefixExponent", "length", "padding", "formatPrefix", "f", "e", "exponent_default", "k", "locale", "format", "formatPrefix", "defaultLocale", "definition", "locale_default", "precisionFixed_default", "step", "exponent_default", "precisionPrefix_default", "step", "value", "exponent_default", "precisionRound_default", "step", "max", "exponent_default", "count", "node", "sum", "children", "i", "count_default", "each_default", "callback", "that", "index", "node", "eachBefore_default", "callback", "that", "node", "nodes", "children", "i", "index", "eachAfter_default", "callback", "that", "node", "nodes", "next", "children", "i", "n", "index", "find_default", "callback", "that", "index", "node", "sum_default", "value", "node", "sum", "children", "sort_default", "compare", "node", "path_default", "end", "start", "ancestor", "leastCommonAncestor", "nodes", "k", "a", "b", "aNodes", "bNodes", "c", "ancestors_default", "node", "nodes", "descendants_default", "leaves_default", "leaves", "node", "links_default", "root", "links", "node", "iterator_default", "node", "current", "next", "children", "n", "hierarchy", "data", "children", "mapChildren", "objectChildren", "root", "Node", "node", "nodes", "child", "childs", "i", "n", "computeHeight", "node_copy", "copyData", "d", "height", "count_default", "each_default", "eachAfter_default", "eachBefore_default", "find_default", "sum_default", "sort_default", "path_default", "ancestors_default", "descendants_default", "leaves_default", "links_default", "iterator_default", "round_default", "node", "dice_default", "parent", "x0", "y0", "x1", "y1", "nodes", "node", "i", "n", "k", "slice_default", "parent", "x0", "y0", "x1", "y1", "nodes", "node", "i", "n", "k", "phi", "squarifyRatio", "ratio", "parent", "x0", "y0", "x1", "y1", "rows", "nodes", "row", "nodeValue", "i0", "i1", "n", "dx", "dy", "value", "sumValue", "minValue", "maxValue", "newRatio", "minRatio", "alpha", "beta", "dice_default", "slice_default", "squarify_default", "custom", "squarify", "x", "required", "f", "constantZero", "constant_default", "x", "treemap_default", "tile", "squarify_default", "round", "dx", "dy", "paddingStack", "paddingInner", "constantZero", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft", "treemap", "root", "positionNode", "round_default", "node", "x0", "y0", "x1", "y1", "x", "required", "constant_default", "initRange", "domain", "range", "implicit", "ordinal", "index", "InternMap", "domain", "range", "unknown", "scale", "d", "i", "_", "value", "initRange", "band", "scale", "ordinal", "domain", "ordinalRange", "r0", "r1", "step", "bandwidth", "round", "paddingInner", "paddingOuter", "align", "rescale", "n", "reverse", "start", "stop", "values", "range", "i", "_", "initRange", "constants", "x", "number", "x", "unit", "identity", "x", "normalize", "a", "b", "constants", "clamper", "t", "bimap", "domain", "range", "interpolate", "d0", "d1", "r0", "r1", "polymap", "j", "d", "r", "i", "bisect_default", "copy", "source", "target", "transformer", "value_default", "transform", "untransform", "unknown", "clamp", "piecewise", "output", "input", "rescale", "n", "scale", "y", "number_default", "_", "number", "round_default", "u", "continuous", "tickFormat", "start", "stop", "count", "specifier", "step", "tickStep", "precision", "formatSpecifier", "value", "precisionPrefix_default", "formatPrefix", "precisionRound_default", "precisionFixed_default", "format", "linearish", "scale", "domain", "count", "d", "ticks", "specifier", "tickFormat", "i0", "i1", "start", "stop", "prestep", "step", "maxIter", "tickIncrement", "linear", "continuous", "copy", "initRange", "t0", "t1", "timeInterval", "floori", "offseti", "count", "field", "interval", "date", "d0", "d1", "step", "start", "stop", "range", "previous", "test", "end", "d", "millisecond", "timeInterval", "date", "step", "start", "end", "k", "milliseconds", "second", "timeInterval", "date", "step", "start", "end", "seconds", "timeMinute", "timeInterval", "date", "step", "start", "end", "timeMinutes", "utcMinute", "utcMinutes", "timeHour", "timeInterval", "date", "step", "start", "end", "timeHours", "utcHour", "utcHours", "timeDay", "timeInterval", "date", "step", "start", "end", "timeDays", "utcDay", "utcDays", "unixDay", "unixDays", "timeWeekday", "i", "timeInterval", "date", "step", "start", "end", "timeSunday", "timeMonday", "timeTuesday", "timeWednesday", "timeThursday", "timeFriday", "timeSaturday", "timeSundays", "timeMondays", "timeTuesdays", "timeWednesdays", "timeThursdays", "timeFridays", "timeSaturdays", "utcWeekday", "utcSunday", "utcMonday", "utcTuesday", "utcWednesday", "utcThursday", "utcFriday", "utcSaturday", "utcSundays", "utcMondays", "utcTuesdays", "utcWednesdays", "utcThursdays", "utcFridays", "utcSaturdays", "timeMonth", "timeInterval", "date", "step", "start", "end", "timeMonths", "utcMonth", "utcMonths", "timeYear", "timeInterval", "date", "step", "start", "end", "k", "timeYears", "utcYear", "utcYears", "ticker", "year", "month", "week", "day", "hour", "minute", "tickIntervals", "second", "ticks", "start", "stop", "count", "reverse", "interval", "tickInterval", "target", "i", "bisector", "step", "tickStep", "millisecond", "t", "utcTicks", "utcTickInterval", "utcYear", "utcMonth", "utcSunday", "unixDay", "utcHour", "utcMinute", "timeTicks", "timeTickInterval", "timeYear", "timeMonth", "timeSunday", "timeDay", "timeHour", "timeMinute", "localDate", "d", "date", "utcDate", "newDate", "y", "m", "formatLocale", "locale", "locale_dateTime", "locale_date", "locale_time", "locale_periods", "locale_weekdays", "locale_shortWeekdays", "locale_months", "locale_shortMonths", "periodRe", "formatRe", "periodLookup", "formatLookup", "weekdayRe", "weekdayLookup", "shortWeekdayRe", "shortWeekdayLookup", "monthRe", "monthLookup", "shortMonthRe", "shortMonthLookup", "formats", "formatShortWeekday", "formatWeekday", "formatShortMonth", "formatMonth", "formatDayOfMonth", "formatMicroseconds", "formatYearISO", "formatFullYearISO", "formatHour24", "formatHour12", "formatDayOfYear", "formatMilliseconds", "formatMonthNumber", "formatMinutes", "formatPeriod", "formatQuarter", "formatUnixTimestamp", "formatUnixTimestampSeconds", "formatSeconds", "formatWeekdayNumberMonday", "formatWeekNumberSunday", "formatWeekNumberISO", "formatWeekdayNumberSunday", "formatWeekNumberMonday", "formatYear", "formatFullYear", "formatZone", "formatLiteralPercent", "utcFormats", "formatUTCShortWeekday", "formatUTCWeekday", "formatUTCShortMonth", "formatUTCMonth", "formatUTCDayOfMonth", "formatUTCMicroseconds", "formatUTCYearISO", "formatUTCFullYearISO", "formatUTCHour24", "formatUTCHour12", "formatUTCDayOfYear", "formatUTCMilliseconds", "formatUTCMonthNumber", "formatUTCMinutes", "formatUTCPeriod", "formatUTCQuarter", "formatUTCSeconds", "formatUTCWeekdayNumberMonday", "formatUTCWeekNumberSunday", "formatUTCWeekNumberISO", "formatUTCWeekdayNumberSunday", "formatUTCWeekNumberMonday", "formatUTCYear", "formatUTCFullYear", "formatUTCZone", "parses", "parseShortWeekday", "parseWeekday", "parseShortMonth", "parseMonth", "parseLocaleDateTime", "parseDayOfMonth", "parseMicroseconds", "parseYear", "parseFullYear", "parseHour24", "parseDayOfYear", "parseMilliseconds", "parseMonthNumber", "parseMinutes", "parsePeriod", "parseQuarter", "parseUnixTimestamp", "parseUnixTimestampSeconds", "parseSeconds", "parseWeekdayNumberMonday", "parseWeekNumberSunday", "parseWeekNumberISO", "parseWeekdayNumberSunday", "parseWeekNumberMonday", "parseLocaleDate", "parseLocaleTime", "parseZone", "parseLiteralPercent", "newFormat", "specifier", "string", "i", "j", "n", "c", "pad", "format", "pads", "newParse", "Z", "parseSpecifier", "week", "day", "utcMonday", "utcDay", "timeMonday", "timeDay", "parse", "f", "p", "numberRe", "percentRe", "requoteRe", "value", "fill", "width", "sign", "length", "requote", "s", "names", "name", "timeYear", "timeSunday", "dISO", "timeThursday", "z", "utcYear", "dow", "utcSunday", "UTCdISO", "utcThursday", "locale", "timeFormat", "timeParse", "utcFormat", "utcParse", "defaultLocale", "definition", "formatLocale", "nice", "domain", "interval", "i0", "i1", "x0", "x1", "t", "date", "number", "calendar", "ticks", "tickInterval", "year", "month", "week", "day", "hour", "minute", "second", "format", "scale", "continuous", "invert", "domain", "formatMillisecond", "formatSecond", "formatMinute", "formatHour", "formatDay", "formatWeek", "formatMonth", "formatYear", "tickFormat", "y", "_", "interval", "d", "count", "specifier", "nice", "copy", "time", "initRange", "timeTicks", "timeTickInterval", "timeYear", "timeMonth", "timeSunday", "timeDay", "timeHour", "timeMinute", "timeFormat", "colors_default", "specifier", "n", "colors", "i", "Tableau10_default", "colors_default", "constant_default", "x", "abs", "atan2", "cos", "max", "min", "sin", "sqrt", "epsilon", "pi", "halfPi", "tau", "acos", "x", "asin", "pi", "tau", "epsilon", "tauEpsilon", "append", "strings", "i", "appendRound", "digits", "d", "k", "n", "Path", "x", "y", "x1", "y1", "x2", "y2", "r", "x0", "y0", "x21", "y21", "x01", "y01", "l01_2", "x20", "y20", "l21_2", "l20_2", "l21", "l01", "l", "t01", "t21", "a0", "a1", "ccw", "dx", "dy", "cw", "da", "w", "h", "path", "withPath", "shape", "digits", "_", "d", "Path", "arcInnerRadius", "d", "arcOuterRadius", "arcStartAngle", "arcEndAngle", "arcPadAngle", "intersect", "x0", "y0", "x1", "y1", "x2", "y2", "x3", "y3", "x10", "y10", "x32", "y32", "t", "epsilon", "cornerTangents", "r1", "rc", "cw", "x01", "y01", "lo", "sqrt", "ox", "oy", "x11", "y11", "x00", "y00", "dx", "dy", "d2", "r", "D", "max", "cx0", "cy0", "cx1", "cy1", "dx0", "dy0", "dx1", "dy1", "arc_default", "innerRadius", "outerRadius", "cornerRadius", "constant_default", "padRadius", "startAngle", "endAngle", "padAngle", "context", "path", "withPath", "arc", "buffer", "r0", "a0", "halfPi", "a1", "da", "abs", "tau", "cos", "sin", "a01", "a11", "a00", "a10", "da0", "da1", "ap", "rp", "min", "rc0", "rc1", "t0", "t1", "p0", "asin", "p1", "oc", "pi", "ax", "ay", "bx", "by", "kc", "acos", "lc", "atan2", "a", "_", "slice", "array_default", "x", "Linear", "context", "x", "y", "linear_default", "x", "p", "y", "line_default", "x", "y", "defined", "constant_default", "context", "curve", "linear_default", "output", "path", "withPath", "line", "data", "i", "n", "array_default", "d", "defined0", "buffer", "_", "descending_default", "a", "b", "identity_default", "d", "pie_default", "value", "identity_default", "sortValues", "descending_default", "sort", "startAngle", "constant_default", "endAngle", "tau", "padAngle", "pie", "data", "i", "n", "array_default", "j", "k", "sum", "index", "arcs", "a0", "da", "a1", "p", "pa", "v", "_", "point", "that", "x", "y", "Basis", "context", "basis_default", "Bump", "context", "x", "y", "bumpX", "context", "Bump", "bumpY", "noop_default", "BasisClosed", "context", "noop_default", "x", "y", "point", "basisClosed_default", "BasisOpen", "context", "x", "y", "x0", "y0", "point", "basisOpen_default", "Bundle", "context", "beta", "Basis", "x", "y", "j", "x0", "y0", "dx", "dy", "i", "t", "bundle_default", "custom", "bundle", "point", "that", "x", "y", "Cardinal", "context", "tension", "cardinal_default", "custom", "cardinal", "CardinalClosed", "context", "tension", "noop_default", "x", "y", "point", "cardinalClosed_default", "custom", "cardinal", "CardinalOpen", "context", "tension", "x", "y", "point", "cardinalOpen_default", "custom", "cardinal", "point", "that", "x", "y", "x1", "y1", "x2", "y2", "epsilon", "a", "n", "b", "m", "CatmullRom", "context", "alpha", "x23", "y23", "catmullRom_default", "custom", "catmullRom", "Cardinal", "CatmullRomClosed", "context", "alpha", "noop_default", "x", "y", "x23", "y23", "point", "catmullRomClosed_default", "custom", "catmullRom", "CardinalClosed", "CatmullRomOpen", "context", "alpha", "x", "y", "x23", "y23", "point", "catmullRomOpen_default", "custom", "catmullRom", "CardinalOpen", "LinearClosed", "context", "noop_default", "x", "y", "linearClosed_default", "sign", "x", "slope3", "that", "x2", "y2", "h0", "h1", "s0", "s1", "p", "slope2", "t", "h", "point", "t0", "t1", "x0", "y0", "x1", "y1", "dx", "MonotoneX", "context", "y", "MonotoneY", "ReflectContext", "monotoneX", "monotoneY", "Natural", "context", "x", "y", "px", "controlPoints", "py", "i0", "i1", "i", "m", "a", "b", "r", "natural_default", "Step", "context", "t", "x", "y", "x1", "step_default", "stepBefore", "stepAfter", "noop", "dispatch", "i", "n", "_", "t", "Dispatch", "parseTypenames", "typenames", "types", "name", "typename", "callback", "T", "get", "set", "copy", "type", "that", "args", "c", "dispatch_default", "frame", "timeout", "interval", "pokeDelay", "taskHead", "taskTail", "clockLast", "clockNow", "clockSkew", "clock", "setFrame", "f", "now", "clearNow", "Timer", "timer", "callback", "delay", "time", "sleep", "t", "timerFlush", "wake", "nap", "poke", "t0", "t1", "t2", "timeout_default", "callback", "delay", "time", "t", "Timer", "elapsed", "emptyOn", "dispatch_default", "emptyTween", "CREATED", "SCHEDULED", "STARTING", "STARTED", "RUNNING", "ENDING", "ENDED", "schedule_default", "node", "name", "id", "index", "group", "timing", "schedules", "create", "init", "schedule", "get", "set", "self", "tween", "timer", "elapsed", "start", "i", "j", "n", "o", "stop", "timeout_default", "tick", "t", "interrupt_default", "node", "name", "schedules", "schedule", "active", "empty", "i", "STARTING", "ENDING", "ENDED", "interrupt_default", "name", "tweenRemove", "id", "name", "tween0", "tween1", "schedule", "set", "tween", "i", "n", "tweenFunction", "value", "t", "tween_default", "get", "tweenValue", "transition", "node", "interpolate_default", "a", "b", "c", "number_default", "color", "rgb_default", "string_default", "attrRemove", "name", "attrRemoveNS", "fullname", "attrConstant", "interpolate", "value1", "string00", "string1", "interpolate0", "string0", "attrConstantNS", "attrFunction", "value", "string10", "attrFunctionNS", "attr_default", "namespace_default", "i", "interpolateTransformSvg", "interpolate_default", "tweenValue", "attrInterpolate", "name", "i", "t", "attrInterpolateNS", "fullname", "attrTweenNS", "value", "t0", "i0", "tween", "attrTween", "attrTween_default", "key", "namespace_default", "delayFunction", "id", "value", "init", "delayConstant", "delay_default", "get", "durationFunction", "id", "value", "set", "durationConstant", "duration_default", "get", "easeConstant", "id", "value", "set", "ease_default", "get", "easeVarying", "id", "value", "v", "set", "easeVarying_default", "filter_default", "match", "matcher_default", "groups", "m", "subgroups", "j", "group", "n", "subgroup", "node", "i", "Transition", "merge_default", "transition", "groups0", "groups1", "m0", "m1", "m", "merges", "j", "group0", "group1", "n", "merge", "node", "i", "Transition", "start", "name", "t", "i", "onFunction", "id", "listener", "on0", "on1", "sit", "init", "set", "schedule", "on", "on_default", "get", "removeFunction", "id", "parent", "i", "remove_default", "select_default", "select", "name", "id", "selector_default", "groups", "m", "subgroups", "j", "group", "n", "subgroup", "node", "subnode", "i", "schedule_default", "get", "Transition", "selectAll_default", "select", "name", "id", "selectorAll_default", "groups", "m", "subgroups", "parents", "j", "group", "n", "node", "i", "children", "child", "inherit", "get", "k", "l", "schedule_default", "Transition", "Selection", "selection_default", "styleNull", "name", "interpolate", "string00", "string10", "interpolate0", "string0", "styleValue", "string1", "styleRemove", "styleConstant", "value1", "styleFunction", "value", "styleMaybeRemove", "id", "on0", "on1", "listener0", "key", "event", "remove", "schedule", "set", "on", "listener", "style_default", "priority", "i", "interpolateTransformCss", "interpolate_default", "tweenValue", "styleInterpolate", "name", "i", "priority", "t", "styleTween", "value", "i0", "tween", "styleTween_default", "key", "textConstant", "value", "textFunction", "value1", "text_default", "tweenValue", "textInterpolate", "i", "t", "textTween", "value", "t0", "i0", "tween", "textTween_default", "key", "transition_default", "name", "id0", "id1", "newId", "groups", "m", "j", "group", "n", "node", "i", "inherit", "get", "schedule_default", "Transition", "end_default", "on0", "on1", "that", "id", "size", "resolve", "reject", "cancel", "end", "schedule", "set", "on", "id", "Transition", "groups", "parents", "name", "transition", "selection_default", "newId", "selection_prototype", "select_default", "selectAll_default", "filter_default", "merge_default", "transition_default", "on_default", "attr_default", "attrTween_default", "style_default", "styleTween_default", "text_default", "textTween_default", "remove_default", "tween_default", "delay_default", "duration_default", "ease_default", "easeVarying_default", "end_default", "cubicInOut", "defaultTiming", "cubicInOut", "inherit", "node", "id", "timing", "transition_default", "name", "Transition", "newId", "now", "groups", "m", "j", "group", "n", "i", "schedule_default", "selection_default", "interrupt_default", "transition_default", "abs", "max", "min", "number1", "e", "number2", "X", "type", "x", "xy", "Y", "y", "XY", "type", "Transform", "k", "x", "y", "point", "location", "identity", "transform", "node"] +} diff --git a/docs/website/public/chunk-77XMBG7U.min.js b/docs/website/public/chunk-77XMBG7U.min.js new file mode 100644 index 000000000..753d7ab03 --- /dev/null +++ b/docs/website/public/chunk-77XMBG7U.min.js @@ -0,0 +1,2 @@ +import{b as x}from"./chunk-6TVUEPFY.min.js";var c={aggregation:17.25,extension:17.25,composition:17.25,dependency:6,lollipop:13.5,arrow_point:4},T={arrow_point:9,arrow_cross:12.5,arrow_circle:12.5};function w(n,l){if(n===void 0||l===void 0)return{angle:0,deltaX:0,deltaY:0};n=t(n),l=t(l);let[s,e]=[n.x,n.y],[a,i]=[l.x,l.y],o=a-s,y=i-e;return{angle:Math.atan(y/o),deltaX:o,deltaY:y}}x(w,"calculateDeltaAndAngle");var t=x(n=>Array.isArray(n)?{x:n[0],y:n[1]}:n,"pointTransformer"),M=x(n=>({x:x(function(l,s,e){let a=0,i=t(e[0]).x=0?1:-1)}else if(s===e.length-1&&Object.hasOwn(c,n.arrowTypeEnd)){let{angle:r,deltaX:g}=w(e[e.length-1],e[e.length-2]);a=c[n.arrowTypeEnd]*Math.cos(r)*(g>=0?1:-1)}let o=Math.abs(t(l).x-t(e[e.length-1]).x),y=Math.abs(t(l).y-t(e[e.length-1]).y),f=Math.abs(t(l).x-t(e[0]).x),d=Math.abs(t(l).y-t(e[0]).y),h=c[n.arrowTypeStart],u=c[n.arrowTypeEnd],p=1;if(o0&&y0&&d=0?1:-1)}else if(s===e.length-1&&Object.hasOwn(c,n.arrowTypeEnd)){let{angle:r,deltaY:g}=w(e[e.length-1],e[e.length-2]);a=c[n.arrowTypeEnd]*Math.abs(Math.sin(r))*(g>=0?1:-1)}let o=Math.abs(t(l).y-t(e[e.length-1]).y),y=Math.abs(t(l).x-t(e[e.length-1]).x),f=Math.abs(t(l).y-t(e[0]).y),d=Math.abs(t(l).x-t(e[0]).x),h=c[n.arrowTypeStart],u=c[n.arrowTypeEnd],p=1;if(o0&&y0&&d {\n if (Array.isArray(data)) {\n return { x: data[0], y: data[1] };\n }\n return data;\n}, \"pointTransformer\");\nvar getLineFunctionsWithOffset = /* @__PURE__ */ __name((edge) => {\n return {\n x: /* @__PURE__ */ __name(function(d, i, data) {\n let offset = 0;\n const DIRECTION = pointTransformer(data[0]).x < pointTransformer(data[data.length - 1]).x ? \"left\" : \"right\";\n if (i === 0 && Object.hasOwn(markerOffsets, edge.arrowTypeStart)) {\n const { angle, deltaX } = calculateDeltaAndAngle(data[0], data[1]);\n offset = markerOffsets[edge.arrowTypeStart] * Math.cos(angle) * (deltaX >= 0 ? 1 : -1);\n } else if (i === data.length - 1 && Object.hasOwn(markerOffsets, edge.arrowTypeEnd)) {\n const { angle, deltaX } = calculateDeltaAndAngle(\n data[data.length - 1],\n data[data.length - 2]\n );\n offset = markerOffsets[edge.arrowTypeEnd] * Math.cos(angle) * (deltaX >= 0 ? 1 : -1);\n }\n const differenceToEnd = Math.abs(\n pointTransformer(d).x - pointTransformer(data[data.length - 1]).x\n );\n const differenceInYEnd = Math.abs(\n pointTransformer(d).y - pointTransformer(data[data.length - 1]).y\n );\n const differenceToStart = Math.abs(pointTransformer(d).x - pointTransformer(data[0]).x);\n const differenceInYStart = Math.abs(pointTransformer(d).y - pointTransformer(data[0]).y);\n const startMarkerHeight = markerOffsets[edge.arrowTypeStart];\n const endMarkerHeight = markerOffsets[edge.arrowTypeEnd];\n const extraRoom = 1;\n if (differenceToEnd < endMarkerHeight && differenceToEnd > 0 && differenceInYEnd < endMarkerHeight) {\n let adjustment = endMarkerHeight + extraRoom - differenceToEnd;\n adjustment *= DIRECTION === \"right\" ? -1 : 1;\n offset -= adjustment;\n }\n if (differenceToStart < startMarkerHeight && differenceToStart > 0 && differenceInYStart < startMarkerHeight) {\n let adjustment = startMarkerHeight + extraRoom - differenceToStart;\n adjustment *= DIRECTION === \"right\" ? -1 : 1;\n offset += adjustment;\n }\n return pointTransformer(d).x + offset;\n }, \"x\"),\n y: /* @__PURE__ */ __name(function(d, i, data) {\n let offset = 0;\n const DIRECTION = pointTransformer(data[0]).y < pointTransformer(data[data.length - 1]).y ? \"down\" : \"up\";\n if (i === 0 && Object.hasOwn(markerOffsets, edge.arrowTypeStart)) {\n const { angle, deltaY } = calculateDeltaAndAngle(data[0], data[1]);\n offset = markerOffsets[edge.arrowTypeStart] * Math.abs(Math.sin(angle)) * (deltaY >= 0 ? 1 : -1);\n } else if (i === data.length - 1 && Object.hasOwn(markerOffsets, edge.arrowTypeEnd)) {\n const { angle, deltaY } = calculateDeltaAndAngle(\n data[data.length - 1],\n data[data.length - 2]\n );\n offset = markerOffsets[edge.arrowTypeEnd] * Math.abs(Math.sin(angle)) * (deltaY >= 0 ? 1 : -1);\n }\n const differenceToEnd = Math.abs(\n pointTransformer(d).y - pointTransformer(data[data.length - 1]).y\n );\n const differenceInXEnd = Math.abs(\n pointTransformer(d).x - pointTransformer(data[data.length - 1]).x\n );\n const differenceToStart = Math.abs(pointTransformer(d).y - pointTransformer(data[0]).y);\n const differenceInXStart = Math.abs(pointTransformer(d).x - pointTransformer(data[0]).x);\n const startMarkerHeight = markerOffsets[edge.arrowTypeStart];\n const endMarkerHeight = markerOffsets[edge.arrowTypeEnd];\n const extraRoom = 1;\n if (differenceToEnd < endMarkerHeight && differenceToEnd > 0 && differenceInXEnd < endMarkerHeight) {\n let adjustment = endMarkerHeight + extraRoom - differenceToEnd;\n adjustment *= DIRECTION === \"up\" ? -1 : 1;\n offset -= adjustment;\n }\n if (differenceToStart < startMarkerHeight && differenceToStart > 0 && differenceInXStart < startMarkerHeight) {\n let adjustment = startMarkerHeight + extraRoom - differenceToStart;\n adjustment *= DIRECTION === \"up\" ? -1 : 1;\n offset += adjustment;\n }\n return pointTransformer(d).y + offset;\n }, \"y\")\n };\n}, \"getLineFunctionsWithOffset\");\nif (void 0) {\n const { it, expect, describe } = void 0;\n describe(\"calculateDeltaAndAngle\", () => {\n it(\"should calculate the angle and deltas between two points\", () => {\n expect(calculateDeltaAndAngle([0, 0], [0, 1])).toStrictEqual({\n angle: 1.5707963267948966,\n deltaX: 0,\n deltaY: 1\n });\n expect(calculateDeltaAndAngle([1, 0], [0, -1])).toStrictEqual({\n angle: 0.7853981633974483,\n deltaX: -1,\n deltaY: -1\n });\n expect(calculateDeltaAndAngle({ x: 1, y: 0 }, [0, -1])).toStrictEqual({\n angle: 0.7853981633974483,\n deltaX: -1,\n deltaY: -1\n });\n expect(calculateDeltaAndAngle({ x: 1, y: 0 }, { x: 1, y: 0 })).toStrictEqual({\n angle: NaN,\n deltaX: 0,\n deltaY: 0\n });\n });\n it(\"should calculate the angle and deltas if one point in undefined\", () => {\n expect(calculateDeltaAndAngle(void 0, [0, 1])).toStrictEqual({\n angle: 0,\n deltaX: 0,\n deltaY: 0\n });\n expect(calculateDeltaAndAngle([0, 1], void 0)).toStrictEqual({\n angle: 0,\n deltaX: 0,\n deltaY: 0\n });\n });\n });\n}\n\nexport {\n markerOffsets,\n markerOffsets2,\n getLineFunctionsWithOffset\n};\n"], + "mappings": "4CAKA,IAAIA,EAAgB,CAClB,YAAa,MACb,UAAW,MACX,YAAa,MACb,WAAY,EACZ,SAAU,KACV,YAAa,CAEf,EACIC,EAAiB,CACnB,YAAa,EACb,YAAa,KACb,aAAc,IAChB,EACA,SAASC,EAAuBC,EAAQC,EAAQ,CAC9C,GAAID,IAAW,QAAUC,IAAW,OAClC,MAAO,CAAE,MAAO,EAAG,OAAQ,EAAG,OAAQ,CAAE,EAE1CD,EAASE,EAAiBF,CAAM,EAChCC,EAASC,EAAiBD,CAAM,EAChC,GAAM,CAACE,EAAIC,CAAE,EAAI,CAACJ,EAAO,EAAGA,EAAO,CAAC,EAC9B,CAACK,EAAIC,CAAE,EAAI,CAACL,EAAO,EAAGA,EAAO,CAAC,EAC9BM,EAASF,EAAKF,EACdK,EAASF,EAAKF,EACpB,MAAO,CAAE,MAAO,KAAK,KAAKI,EAASD,CAAM,EAAG,OAAAA,EAAQ,OAAAC,CAAO,CAC7D,CACAC,EAAOV,EAAwB,wBAAwB,EACvD,IAAIG,EAAmCO,EAAQC,GACzC,MAAM,QAAQA,CAAI,EACb,CAAE,EAAGA,EAAK,CAAC,EAAG,EAAGA,EAAK,CAAC,CAAE,EAE3BA,EACN,kBAAkB,EACjBC,EAA6CF,EAAQG,IAChD,CACL,EAAmBH,EAAO,SAASI,EAAGC,EAAGJ,EAAM,CAC7C,IAAIK,EAAS,EACPC,EAAYd,EAAiBQ,EAAK,CAAC,CAAC,EAAE,EAAIR,EAAiBQ,EAAKA,EAAK,OAAS,CAAC,CAAC,EAAE,EAAI,OAAS,QACrG,GAAII,IAAM,GAAK,OAAO,OAAOjB,EAAee,EAAK,cAAc,EAAG,CAChE,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K,CAAC,CAAC,EAAE,CAAC,EACjFY,EAAoBzB,EAAce,EAAK,cAAc,EACrDW,EAAkB1B,EAAce,EAAK,YAAY,EACjDY,EAAY,EAClB,GAAIN,EAAkBK,GAAmBL,EAAkB,GAAKQ,EAAmBH,EAAiB,CAClG,IAAIE,EAAaF,EAAkBC,EAAYN,EAC/CO,GAAcT,IAAc,KAAO,GAAK,EACxCD,GAAUU,CACZ,CACA,GAAIL,EAAoBE,GAAqBF,EAAoB,GAAKO,EAAqBL,EAAmB,CAC5G,IAAIG,EAAaH,EAAoBE,EAAYJ,EACjDK,GAAcT,IAAc,KAAO,GAAK,EACxCD,GAAUU,CACZ,CACA,OAAOvB,EAAiBW,CAAC,EAAE,EAAIE,CACjC,EAAG,GAAG,CACR,GACC,4BAA4B", + "names": ["markerOffsets", "markerOffsets2", "calculateDeltaAndAngle", "point1", "point2", "pointTransformer", "x1", "y1", "x2", "y2", "deltaX", "deltaY", "__name", "data", "getLineFunctionsWithOffset", "edge", "d", "i", "offset", "DIRECTION", "angle", "differenceToEnd", "differenceInYEnd", "differenceToStart", "differenceInYStart", "startMarkerHeight", "endMarkerHeight", "extraRoom", "adjustment", "differenceInXEnd", "differenceInXStart"] +} diff --git a/docs/website/public/chunk-7EBV5LUJ.min.js b/docs/website/public/chunk-7EBV5LUJ.min.js new file mode 100644 index 000000000..a8f9fd97d --- /dev/null +++ b/docs/website/public/chunk-7EBV5LUJ.min.js @@ -0,0 +1,2 @@ +import{W as s}from"./chunk-3EE2TK35.min.js";import{b as n,j as e}from"./chunk-6TVUEPFY.min.js";var a=n(t=>{let{securityLevel:c}=s(),o=e("body");if(c==="sandbox"){let m=e(`#i${t}`).node()?.contentDocument??document;o=e(m.body)}return o.select(`#${t}`)},"selectSvgElement");export{a}; +//# sourceMappingURL=chunk-7EBV5LUJ.min.js.map diff --git a/docs/website/public/chunk-7EBV5LUJ.min.js.map b/docs/website/public/chunk-7EBV5LUJ.min.js.map new file mode 100644 index 000000000..92f285fca --- /dev/null +++ b/docs/website/public/chunk-7EBV5LUJ.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/mermaid/dist/chunks/mermaid.core/chunk-EXTU4WIE.mjs"], + "sourcesContent": ["import {\n getConfig2 as getConfig\n} from \"./chunk-ABZYJK2D.mjs\";\nimport {\n __name\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/rendering-util/selectSvgElement.ts\nimport { select } from \"d3\";\nvar selectSvgElement = /* @__PURE__ */ __name((id) => {\n const { securityLevel } = getConfig();\n let root = select(\"body\");\n if (securityLevel === \"sandbox\") {\n const sandboxElement = select(`#i${id}`);\n const doc = sandboxElement.node()?.contentDocument ?? document;\n root = select(doc.body);\n }\n const svg = root.select(`#${id}`);\n return svg;\n}, \"selectSvgElement\");\n\nexport {\n selectSvgElement\n};\n"], + "mappings": "+FASA,IAAIA,EAAmCC,EAAQC,GAAO,CACpD,GAAM,CAAE,cAAAC,CAAc,EAAIC,EAAU,EAChCC,EAAOC,EAAO,MAAM,EACxB,GAAIH,IAAkB,UAAW,CAE/B,IAAMI,EADiBD,EAAO,KAAKJ,CAAE,EAAE,EACZ,KAAK,GAAG,iBAAmB,SACtDG,EAAOC,EAAOC,EAAI,IAAI,CACxB,CAEA,OADYF,EAAK,OAAO,IAAIH,CAAE,EAAE,CAElC,EAAG,kBAAkB", + "names": ["selectSvgElement", "__name", "id", "securityLevel", "getConfig2", "root", "select_default", "doc"] +} diff --git a/docs/website/public/chunk-ANLQN3B7.min.js b/docs/website/public/chunk-ANLQN3B7.min.js new file mode 100644 index 000000000..55deb6907 --- /dev/null +++ b/docs/website/public/chunk-ANLQN3B7.min.js @@ -0,0 +1,2 @@ +import{b as i}from"./chunk-6TVUEPFY.min.js";var o=i(({flowchart:t})=>{let r=t?.subGraphTitleMargin?.top??0,a=t?.subGraphTitleMargin?.bottom??0,e=r+a;return{subGraphTitleTopMargin:r,subGraphTitleBottomMargin:a,subGraphTitleTotalMargin:e}},"getSubGraphTitleMargins");export{o as a}; +//# sourceMappingURL=chunk-ANLQN3B7.min.js.map diff --git a/docs/website/public/chunk-ANLQN3B7.min.js.map b/docs/website/public/chunk-ANLQN3B7.min.js.map new file mode 100644 index 000000000..2d052cd2b --- /dev/null +++ b/docs/website/public/chunk-ANLQN3B7.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/mermaid/dist/chunks/mermaid.core/chunk-CVBHYZKI.mjs"], + "sourcesContent": ["import {\n __name\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/utils/subGraphTitleMargins.ts\nvar getSubGraphTitleMargins = /* @__PURE__ */ __name(({\n flowchart\n}) => {\n const subGraphTitleTopMargin = flowchart?.subGraphTitleMargin?.top ?? 0;\n const subGraphTitleBottomMargin = flowchart?.subGraphTitleMargin?.bottom ?? 0;\n const subGraphTitleTotalMargin = subGraphTitleTopMargin + subGraphTitleBottomMargin;\n return {\n subGraphTitleTopMargin,\n subGraphTitleBottomMargin,\n subGraphTitleTotalMargin\n };\n}, \"getSubGraphTitleMargins\");\n\nexport {\n getSubGraphTitleMargins\n};\n"], + "mappings": "4CAKA,IAAIA,EAA0CC,EAAO,CAAC,CACpD,UAAAC,CACF,IAAM,CACJ,IAAMC,EAAyBD,GAAW,qBAAqB,KAAO,EAChEE,EAA4BF,GAAW,qBAAqB,QAAU,EACtEG,EAA2BF,EAAyBC,EAC1D,MAAO,CACL,uBAAAD,EACA,0BAAAC,EACA,yBAAAC,CACF,CACF,EAAG,yBAAyB", + "names": ["getSubGraphTitleMargins", "__name", "flowchart", "subGraphTitleTopMargin", "subGraphTitleBottomMargin", "subGraphTitleTotalMargin"] +} diff --git a/docs/website/public/chunk-B46QTP2J.min.js b/docs/website/public/chunk-B46QTP2J.min.js new file mode 100644 index 000000000..feede30cd --- /dev/null +++ b/docs/website/public/chunk-B46QTP2J.min.js @@ -0,0 +1,2 @@ +import{a as b}from"./chunk-VUATWGGE.min.js";import{D as E,E as F,F as y,G as L,H as G,J as V,K as x,L as R,N as Er,P as I,T as B,U as Q,d as g,f as vr,h as K,i as _r,k as j,n as f,p as N,q as Y,s as v,u as wr,v as br,x as W,z as O}from"./chunk-R5JLOOQ4.min.js";import{O as M,T as D,z as mr}from"./chunk-E5F23VE2.min.js";function k(r,e,n,t){var o;do o=B(t);while(r.hasNode(o));return n.dummy=e,r.setNode(o,n),o}function yr(r){var e=new b().setGraph(r.graph());return f(r.nodes(),function(n){e.setNode(n,r.node(n))}),f(r.edges(),function(n){var t=e.edge(n.v,n.w)||{weight:0,minlen:1},o=r.edge(n);e.setEdge(n.v,n.w,{weight:t.weight+o.weight,minlen:Math.max(t.minlen,o.minlen)})}),e}function q(r){var e=new b({multigraph:r.isMultigraph()}).setGraph(r.graph());return f(r.nodes(),function(n){r.children(n).length||e.setNode(n,r.node(n))}),f(r.edges(),function(n){e.setEdge(n,r.edge(n))}),e}function Z(r,e){var n=r.x,t=r.y,o=e.x-n,a=e.y-t,i=r.width/2,s=r.height/2;if(!o&&!a)throw new Error("Not possible to find intersection inside of the rectangle");var u,d;return Math.abs(a)*i>Math.abs(o)*s?(a<0&&(s=-s),u=s*o/a,d=s):(o<0&&(i=-i),u=i,d=i*a/o),{x:n+u,y:t+d}}function P(r){var e=v(x(rr(r)+1),function(){return[]});return f(r.nodes(),function(n){var t=r.node(n),o=t.rank;E(o)||(e[o][t.order]=n)}),e}function xr(r){var e=L(v(r.nodes(),function(n){return r.node(n).rank}));f(r.nodes(),function(n){var t=r.node(n);W(t,"rank")&&(t.rank-=e)})}function kr(r){var e=L(v(r.nodes(),function(a){return r.node(a).rank})),n=[];f(r.nodes(),function(a){var i=r.node(a).rank-e;n[i]||(n[i]=[]),n[i].push(a)});var t=0,o=r.graph().nodeRankFactor;f(n,function(a,i){E(a)&&i%o!==0?--t:t&&f(a,function(s){r.node(s).rank+=t})})}function $(r,e,n,t){var o={width:0,height:0};return arguments.length>=4&&(o.rank=n,o.order=t),k(r,"border",o,e)}function rr(r){return y(v(r.nodes(),function(e){var n=r.node(e).rank;if(!E(n))return n}))}function gr(r,e){var n={lhs:[],rhs:[]};return f(r,function(t){e(t)?n.lhs.push(t):n.rhs.push(t)}),n}function Nr(r,e){var n=K();try{return e()}finally{console.log(r+" time: "+(K()-n)+"ms")}}function Ir(r,e){return e()}function Lr(r){function e(n){var t=r.children(n),o=r.node(n);if(t.length&&f(t,e),Object.prototype.hasOwnProperty.call(o,"minRank")){o.borderLeft=[],o.borderRight=[];for(var a=o.minRank,i=o.maxRank+1;a0;--s)if(i=e[s].dequeue(),i){t=t.concat(tr(r,e,n,i,!0));break}}}return t}function tr(r,e,n,t,o){var a=o?[]:void 0;return f(r.inEdges(t.v),function(i){var s=r.edge(i),u=r.node(i.v);o&&a.push({v:i.v,w:i.w}),u.out-=s,or(e,n,u)}),f(r.outEdges(t.v),function(i){var s=r.edge(i),u=i.w,d=r.node(u);d.in-=s,or(e,n,d)}),r.removeNode(t.v),a}function be(r,e){var n=new b,t=0,o=0;f(r.nodes(),function(s){n.setNode(s,{v:s,in:0,out:0})}),f(r.edges(),function(s){var u=n.edge(s.v,s.w)||0,d=e(s),c=u+d;n.setEdge(s.v,s.w,c),o=Math.max(o,n.node(s.v).out+=d),t=Math.max(t,n.node(s.w).in+=d)});var a=x(o+t+3).map(function(){return new X}),i=t+1;return f(n.nodes(),function(s){or(a,i,n.node(s))}),{graph:n,buckets:a,zeroIdx:i}}function or(r,e,n){n.out?n.in?r[n.out-n.in+e].enqueue(n):r[r.length-1].enqueue(n):r[0].enqueue(n)}function Mr(r){var e=r.graph().acyclicer==="greedy"?Sr(r,n(r)):Ee(r);f(e,function(t){var o=r.edge(t);r.removeEdge(t),o.forwardName=t.name,o.reversed=!0,r.setEdge(t.w,t.v,o,B("rev"))});function n(t){return function(o){return t.edge(o).weight}}}function Ee(r){var e=[],n={},t={};function o(a){Object.prototype.hasOwnProperty.call(t,a)||(t[a]=!0,n[a]=!0,f(r.outEdges(a),function(i){Object.prototype.hasOwnProperty.call(n,i.w)?e.push(i):o(i.w)}),delete n[a])}return f(r.nodes(),o),e}function Fr(r){f(r.edges(),function(e){var n=r.edge(e);if(n.reversed){r.removeEdge(e);var t=n.forwardName;delete n.reversed,delete n.forwardName,r.setEdge(e.w,e.v,n,t)}})}function Vr(r){r.graph().dummyChains=[],f(r.edges(),function(e){ye(r,e)})}function ye(r,e){var n=e.v,t=r.node(n).rank,o=e.w,a=r.node(o).rank,i=e.name,s=r.edge(e),u=s.labelRank;if(a!==t+1){r.removeEdge(e);var d=void 0,c,h;for(h=0,++t;ti.lim&&(s=i,u=!0);var d=N(e.edges(),function(c){return u===Yr(r,r.node(c.v),s)&&u!==Yr(r,r.node(c.w),s)});return G(d,function(c){return S(e,c)})}function Xr(r,e,n,t){var o=n.v,a=n.w;r.removeEdge(o,a),r.setEdge(t.v,t.w,{}),ur(r),fr(r,e),Ce(r,e)}function Ce(r,e){var n=Y(r.nodes(),function(o){return!e.node(o).parent}),t=sr(r,n);t=t.slice(1),f(t,function(o){var a=r.node(o).parent,i=e.edge(o,a),s=!1;i||(i=e.edge(a,o),s=!0),e.node(o).rank=e.node(a).rank+(s?i.minlen:-i.minlen)})}function Te(r,e,n){return r.hasEdge(e,n)}function Yr(r,e,n){return n.low<=e.lim&&e.lim<=n.lim}function dr(r){switch(r.graph().ranker){case"network-simplex":Hr(r);break;case"tight-tree":Re(r);break;case"longest-path":je(r);break;default:Hr(r)}}var je=z;function Re(r){z(r),H(r)}function Hr(r){T(r)}function Jr(r){var e=k(r,"root",{},"_root"),n=Se(r),t=y(O(n))-1,o=2*t+1;r.graph().nestingRoot=e,f(r.edges(),function(i){r.edge(i).minlen*=o});var a=Me(r)+1;f(r.children(),function(i){Kr(r,e,o,a,t,n,i)}),r.graph().nodeRankFactor=o}function Kr(r,e,n,t,o,a,i){var s=r.children(i);if(!s.length){i!==e&&r.setEdge(e,i,{weight:0,minlen:n});return}var u=$(r,"_bt"),d=$(r,"_bb"),c=r.node(i);r.setParent(u,i),c.borderTop=u,r.setParent(d,i),c.borderBottom=d,f(s,function(h){Kr(r,e,n,t,o,a,h);var l=r.node(h),p=l.borderTop?l.borderTop:h,m=l.borderBottom?l.borderBottom:h,w=l.borderTop?t:2*t,A=p!==m?1:o-a[i]+1;r.setEdge(u,p,{weight:w,minlen:A,nestingEdge:!0}),r.setEdge(m,d,{weight:w,minlen:A,nestingEdge:!0})}),r.parent(i)||r.setEdge(e,u,{weight:0,minlen:o+a[i]})}function Se(r){var e={};function n(t,o){var a=r.children(t);a&&a.length&&f(a,function(i){n(i,o+1)}),e[t]=o}return f(r.children(),function(t){n(t,1)}),e}function Me(r){return R(r.edges(),function(e,n){return e+r.edge(n).weight},0)}function Qr(r){var e=r.graph();r.removeNode(e.nestingRoot),delete e.nestingRoot,f(r.edges(),function(n){var t=r.edge(n);t.nestingEdge&&r.removeEdge(n)})}function Zr(r,e,n){var t={},o;f(n,function(a){for(var i=r.parent(a),s,u;i;){if(s=r.parent(i),s?(u=t[s],t[s]=i):(u=o,o=i),u&&u!==i){e.setEdge(u,i);return}i=s}})}function $r(r,e,n){var t=Ge(r),o=new b({compound:!0}).setGraph({root:t}).setDefaultNodeLabel(function(a){return r.node(a)});return f(r.nodes(),function(a){var i=r.node(a),s=r.parent(a);(i.rank===e||i.minRank<=e&&e<=i.maxRank)&&(o.setNode(a),o.setParent(a,s||t),f(r[n](a),function(u){var d=u.v===a?u.w:u.v,c=o.edge(d,a),h=E(c)?0:c.weight;o.setEdge(d,a,{weight:r.edge(u).weight+h})}),Object.prototype.hasOwnProperty.call(i,"minRank")&&o.setNode(a,{borderLeft:i.borderLeft[e],borderRight:i.borderRight[e]}))}),o}function Ge(r){for(var e;r.hasNode(e=B("_root")););return e}function re(r,e){for(var n=0,t=1;t0;)c%2&&(h+=s[c+1]),c=c-1>>1,s[c]+=d.weight;u+=d.weight*h})),u}function ee(r){var e={},n=N(r.nodes(),function(s){return!r.children(s).length}),t=y(v(n,function(s){return r.node(s).rank})),o=v(x(t+1),function(){return[]});function a(s){if(!W(e,s)){e[s]=!0;var u=r.node(s);o[u.rank].push(s),f(r.successors(s),a)}}var i=I(n,function(s){return r.node(s).rank});return f(i,a),o}function ne(r,e){return v(e,function(n){var t=r.inEdges(n);if(t.length){var o=R(t,function(a,i){var s=r.edge(i),u=r.node(i.v);return{sum:a.sum+s.weight*u.order,weight:a.weight+s.weight}},{sum:0,weight:0});return{v:n,barycenter:o.sum/o.weight,weight:o.weight}}else return{v:n}})}function te(r,e){var n={};f(r,function(o,a){var i=n[o.v]={indegree:0,in:[],out:[],vs:[o.v],i:a};E(o.barycenter)||(i.barycenter=o.barycenter,i.weight=o.weight)}),f(e.edges(),function(o){var a=n[o.v],i=n[o.w];!E(a)&&!E(i)&&(i.indegree++,a.out.push(n[o.w]))});var t=N(n,function(o){return!o.indegree});return Be(t)}function Be(r){var e=[];function n(a){return function(i){i.merged||(E(i.barycenter)||E(a.barycenter)||i.barycenter>=a.barycenter)&&Ae(a,i)}}function t(a){return function(i){i.in.push(a),--i.indegree===0&&r.push(i)}}for(;r.length;){var o=r.pop();e.push(o),f(o.in.reverse(),n(o)),f(o.out,t(o))}return v(N(e,function(a){return!a.merged}),function(a){return V(a,["vs","i","barycenter","weight"])})}function Ae(r,e){var n=0,t=0;r.weight&&(n+=r.barycenter*r.weight,t+=r.weight),e.weight&&(n+=e.barycenter*e.weight,t+=e.weight),r.vs=e.vs.concat(r.vs),r.barycenter=n/t,r.weight=t,r.i=Math.min(e.i,r.i),e.merged=!0}function ae(r,e){var n=gr(r,function(c){return Object.prototype.hasOwnProperty.call(c,"barycenter")}),t=n.lhs,o=I(n.rhs,function(c){return-c.i}),a=[],i=0,s=0,u=0;t.sort(De(!!e)),u=oe(a,o,u),f(t,function(c){u+=c.vs.length,a.push(c.vs),i+=c.barycenter*c.weight,s+=c.weight,u=oe(a,o,u)});var d={vs:g(a)};return s&&(d.barycenter=i/s,d.weight=s),d}function oe(r,e,n){for(var t;e.length&&(t=j(e)).i<=n;)e.pop(),r.push(t.vs),n++;return n}function De(r){return function(e,n){return e.barycentern.barycenter?1:r?n.i-e.i:e.i-n.i}}function cr(r,e,n,t){var o=r.children(e),a=r.node(e),i=a?a.borderLeft:void 0,s=a?a.borderRight:void 0,u={};i&&(o=N(o,function(m){return m!==i&&m!==s}));var d=ne(r,o);f(d,function(m){if(r.children(m.v).length){var w=cr(r,m.v,n,t);u[m.v]=w,Object.prototype.hasOwnProperty.call(w,"barycenter")&&ze(m,w)}});var c=te(d,n);Ye(c,u);var h=ae(c,t);if(i&&(h.vs=g([i,h.vs,s]),r.predecessors(i).length)){var l=r.node(r.predecessors(i)[0]),p=r.node(r.predecessors(s)[0]);Object.prototype.hasOwnProperty.call(h,"barycenter")||(h.barycenter=0,h.weight=0),h.barycenter=(h.barycenter*h.weight+l.order+p.order)/(h.weight+2),h.weight+=2}return h}function Ye(r,e){f(r,function(n){n.vs=g(n.vs.map(function(t){return e[t]?e[t].vs:t}))})}function ze(r,e){E(r.barycenter)?(r.barycenter=e.barycenter,r.weight=e.weight):(r.barycenter=(r.barycenter*r.weight+e.barycenter*e.weight)/(r.weight+e.weight),r.weight+=e.weight)}function fe(r){var e=rr(r),n=ie(r,x(1,e+1),"inEdges"),t=ie(r,x(e-1,-1,-1),"outEdges"),o=ee(r);se(r,o);for(var a=Number.POSITIVE_INFINITY,i,s=0,u=0;u<4;++s,++u){Ue(s%2?n:t,s%4>=2),o=P(r);var d=re(r,o);di||s>e[u].lim));for(d=u,u=t;(u=r.parent(u))!==d;)a.push(u);return{path:o.concat(a.reverse()),lca:d}}function qe(r){var e={},n=0;function t(o){var a=n;f(r.children(o),t),e[o]={low:a,lim:n++}}return f(r.children(),t),e}function Xe(r,e){var n={};function t(o,a){var i=0,s=0,u=o.length,d=j(a);return f(a,function(c,h){var l=Je(r,c),p=l?r.node(l).order:u;(l||c===d)&&(f(a.slice(s,h+1),function(m){f(r.predecessors(m),function(w){var A=r.node(w),pr=A.order;(prd)&&de(n,l,c)})})}function o(a,i){var s=-1,u,d=0;return f(i,function(c,h){if(r.node(c).dummy==="border"){var l=r.predecessors(c);l.length&&(u=r.node(l[0]).order,t(i,d,h,s,u),d=h,s=u)}t(i,d,i.length,u,a.length)}),i}return R(e,o),n}function Je(r,e){if(r.node(e).dummy)return Y(r.predecessors(e),function(n){return r.node(n).dummy})}function de(r,e,n){if(e>n){var t=e;e=n,n=t}var o=r[e];o||(r[e]=o={}),o[n]=!0}function Ke(r,e,n){if(e>n){var t=e;e=n,n=t}return!!r[e]&&Object.prototype.hasOwnProperty.call(r[e],n)}function Qe(r,e,n,t){var o={},a={},i={};return f(e,function(s){f(s,function(u,d){o[u]=u,a[u]=u,i[u]=d})}),f(e,function(s){var u=-1;f(s,function(d){var c=t(d);if(c.length){c=I(c,function(w){return i[w]});for(var h=(c.length-1)/2,l=Math.floor(h),p=Math.ceil(h);l<=p;++l){var m=c[l];a[d]===d&&u{var t=n(" buildLayoutGraph",()=>wn(r));n(" runLayout",()=>fn(t,n)),n(" updateInputGraph",()=>un(r,t))})}function fn(r,e){e(" makeSpaceForEdgeLabels",()=>bn(r)),e(" removeSelfEdges",()=>Ln(r)),e(" acyclic",()=>Mr(r)),e(" nestingGraph.run",()=>Jr(r)),e(" rank",()=>dr(q(r))),e(" injectEdgeLabelProxies",()=>En(r)),e(" removeEmptyRanks",()=>kr(r)),e(" nestingGraph.cleanup",()=>Qr(r)),e(" normalizeRanks",()=>xr(r)),e(" assignRankMinMax",()=>yn(r)),e(" removeEdgeLabelProxies",()=>xn(r)),e(" normalize.run",()=>Vr(r)),e(" parentDummyChains",()=>ue(r)),e(" addBorderSegments",()=>Lr(r)),e(" order",()=>fe(r)),e(" insertSelfEdges",()=>Pn(r)),e(" adjustCoordinateSystem",()=>Cr(r)),e(" position",()=>he(r)),e(" positionSelfEdges",()=>Cn(r)),e(" removeBorderNodes",()=>On(r)),e(" normalize.undo",()=>Br(r)),e(" fixupEdgeLabelCoords",()=>Nn(r)),e(" undoCoordinateSystem",()=>Tr(r)),e(" translateGraph",()=>kn(r)),e(" assignNodeIntersects",()=>gn(r)),e(" reversePoints",()=>In(r)),e(" acyclic.undo",()=>Fr(r))}function un(r,e){f(r.nodes(),function(n){var t=r.node(n),o=e.node(n);t&&(t.x=o.x,t.y=o.y,e.children(n).length&&(t.width=o.width,t.height=o.height))}),f(r.edges(),function(n){var t=r.edge(n),o=e.edge(n);t.points=o.points,Object.prototype.hasOwnProperty.call(o,"x")&&(t.x=o.x,t.y=o.y)}),r.graph().width=e.graph().width,r.graph().height=e.graph().height}var dn=["nodesep","edgesep","ranksep","marginx","marginy"],cn={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},hn=["acyclicer","ranker","rankdir","align"],ln=["width","height"],pn={width:0,height:0},mn=["minlen","weight","width","height","labeloffset"],vn={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},_n=["labelpos"];function wn(r){var e=new b({multigraph:!0,compound:!0}),n=lr(r.graph());return e.setGraph(D({},cn,hr(n,dn),V(n,hn))),f(r.nodes(),function(t){var o=lr(r.node(t));e.setNode(t,_r(hr(o,ln),pn)),e.setParent(t,r.parent(t))}),f(r.edges(),function(t){var o=lr(r.edge(t));e.setEdge(t,D({},vn,hr(o,mn),V(o,_n)))}),e}function bn(r){var e=r.graph();e.ranksep/=2,f(r.edges(),function(n){var t=r.edge(n);t.minlen*=2,t.labelpos.toLowerCase()!=="c"&&(e.rankdir==="TB"||e.rankdir==="BT"?t.width+=t.labeloffset:t.height+=t.labeloffset)})}function En(r){f(r.edges(),function(e){var n=r.edge(e);if(n.width&&n.height){var t=r.node(e.v),o=r.node(e.w),a={rank:(o.rank-t.rank)/2+t.rank,e};k(r,"edge-proxy",a,"_ep")}})}function yn(r){var e=0;f(r.nodes(),function(n){var t=r.node(n);t.borderTop&&(t.minRank=r.node(t.borderTop).rank,t.maxRank=r.node(t.borderBottom).rank,e=y(e,t.maxRank))}),r.graph().maxRank=e}function xn(r){f(r.nodes(),function(e){var n=r.node(e);n.dummy==="edge-proxy"&&(r.edge(n.e).labelRank=n.rank,r.removeNode(e))})}function kn(r){var e=Number.POSITIVE_INFINITY,n=0,t=Number.POSITIVE_INFINITY,o=0,a=r.graph(),i=a.marginx||0,s=a.marginy||0;function u(d){var c=d.x,h=d.y,l=d.width,p=d.height;e=Math.min(e,c-l/2),n=Math.max(n,c+l/2),t=Math.min(t,h-p/2),o=Math.max(o,h+p/2)}f(r.nodes(),function(d){u(r.node(d))}),f(r.edges(),function(d){var c=r.edge(d);Object.prototype.hasOwnProperty.call(c,"x")&&u(c)}),e-=i,t-=s,f(r.nodes(),function(d){var c=r.node(d);c.x-=e,c.y-=t}),f(r.edges(),function(d){var c=r.edge(d);f(c.points,function(h){h.x-=e,h.y-=t}),Object.prototype.hasOwnProperty.call(c,"x")&&(c.x-=e),Object.prototype.hasOwnProperty.call(c,"y")&&(c.y-=t)}),a.width=n-e+i,a.height=o-t+s}function gn(r){f(r.edges(),function(e){var n=r.edge(e),t=r.node(e.v),o=r.node(e.w),a,i;n.points?(a=n.points[0],i=n.points[n.points.length-1]):(n.points=[],a=o,i=t),n.points.unshift(Z(t,a)),n.points.push(Z(o,i))})}function Nn(r){f(r.edges(),function(e){var n=r.edge(e);if(Object.prototype.hasOwnProperty.call(n,"x"))switch((n.labelpos==="l"||n.labelpos==="r")&&(n.width-=n.labeloffset),n.labelpos){case"l":n.x-=n.width/2+n.labeloffset;break;case"r":n.x+=n.width/2+n.labeloffset;break}})}function In(r){f(r.edges(),function(e){var n=r.edge(e);n.reversed&&n.points.reverse()})}function On(r){f(r.nodes(),function(e){if(r.children(e).length){var n=r.node(e),t=r.node(n.borderTop),o=r.node(n.borderBottom),a=r.node(j(n.borderLeft)),i=r.node(j(n.borderRight));n.width=Math.abs(i.x-a.x),n.height=Math.abs(o.y-t.y),n.x=a.x+n.width/2,n.y=t.y+n.height/2}}),f(r.nodes(),function(e){r.node(e).dummy==="border"&&r.removeNode(e)})}function Ln(r){f(r.edges(),function(e){if(e.v===e.w){var n=r.node(e.v);n.selfEdges||(n.selfEdges=[]),n.selfEdges.push({e,label:r.edge(e)}),r.removeEdge(e)}})}function Pn(r){var e=P(r);f(e,function(n){var t=0;f(n,function(o,a){var i=r.node(o);i.order=a+t,f(i.selfEdges,function(s){k(r,"selfedge",{width:s.label.width,height:s.label.height,rank:i.rank,order:a+ ++t,e:s.e,label:s.label},"_se")}),delete i.selfEdges})})}function Cn(r){f(r.nodes(),function(e){var n=r.node(e);if(n.dummy==="selfedge"){var t=r.node(n.e.v),o=t.x+t.width/2,a=t.y,i=n.x-o,s=t.height/2;r.setEdge(n.e,n.label),r.removeNode(e),n.label.points=[{x:o+2*i/3,y:a-s},{x:o+5*i/6,y:a-s},{x:o+i,y:a},{x:o+5*i/6,y:a+s},{x:o+2*i/3,y:a+s}],n.label.x=n.x,n.label.y=n.y}})}function hr(r,e){return F(V(r,e),Number)}function lr(r){var e={};return f(r,function(n,t){e[t.toLowerCase()]=n}),e}export{sn as a}; +//# sourceMappingURL=chunk-B46QTP2J.min.js.map diff --git a/docs/website/public/chunk-B46QTP2J.min.js.map b/docs/website/public/chunk-B46QTP2J.min.js.map new file mode 100644 index 000000000..ab7f40545 --- /dev/null +++ b/docs/website/public/chunk-B46QTP2J.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/dagre-d3-es/src/dagre/util.js", "../../node_modules/dagre-d3-es/src/dagre/add-border-segments.js", "../../node_modules/dagre-d3-es/src/dagre/coordinate-system.js", "../../node_modules/dagre-d3-es/src/dagre/data/list.js", "../../node_modules/dagre-d3-es/src/dagre/greedy-fas.js", "../../node_modules/dagre-d3-es/src/dagre/acyclic.js", "../../node_modules/dagre-d3-es/src/dagre/normalize.js", "../../node_modules/dagre-d3-es/src/dagre/rank/util.js", "../../node_modules/dagre-d3-es/src/dagre/rank/feasible-tree.js", "../../node_modules/dagre-d3-es/src/graphlib/alg/dijkstra.js", "../../node_modules/dagre-d3-es/src/graphlib/alg/floyd-warshall.js", "../../node_modules/dagre-d3-es/src/graphlib/alg/topsort.js", "../../node_modules/dagre-d3-es/src/graphlib/alg/dfs.js", "../../node_modules/dagre-d3-es/src/graphlib/alg/postorder.js", "../../node_modules/dagre-d3-es/src/graphlib/alg/preorder.js", "../../node_modules/dagre-d3-es/src/dagre/rank/network-simplex.js", "../../node_modules/dagre-d3-es/src/dagre/rank/index.js", "../../node_modules/dagre-d3-es/src/dagre/nesting-graph.js", "../../node_modules/dagre-d3-es/src/dagre/order/add-subgraph-constraints.js", "../../node_modules/dagre-d3-es/src/dagre/order/build-layer-graph.js", "../../node_modules/dagre-d3-es/src/dagre/order/cross-count.js", "../../node_modules/dagre-d3-es/src/dagre/order/init-order.js", "../../node_modules/dagre-d3-es/src/dagre/order/barycenter.js", "../../node_modules/dagre-d3-es/src/dagre/order/resolve-conflicts.js", "../../node_modules/dagre-d3-es/src/dagre/order/sort.js", "../../node_modules/dagre-d3-es/src/dagre/order/sort-subgraph.js", "../../node_modules/dagre-d3-es/src/dagre/order/index.js", "../../node_modules/dagre-d3-es/src/dagre/parent-dummy-chains.js", "../../node_modules/dagre-d3-es/src/dagre/position/bk.js", "../../node_modules/dagre-d3-es/src/dagre/position/index.js", "../../node_modules/dagre-d3-es/src/dagre/layout.js"], + "sourcesContent": ["import * as _ from 'lodash-es';\nimport { Graph } from '../graphlib/index.js';\n\nexport {\n addDummyNode,\n simplify,\n asNonCompoundGraph,\n successorWeights,\n predecessorWeights,\n intersectRect,\n buildLayerMatrix,\n normalizeRanks,\n removeEmptyRanks,\n addBorderNode,\n maxRank,\n partition,\n time,\n notime,\n};\n\n/*\n * Adds a dummy node to the graph and return v.\n */\nfunction addDummyNode(g, type, attrs, name) {\n var v;\n do {\n v = _.uniqueId(name);\n } while (g.hasNode(v));\n\n attrs.dummy = type;\n g.setNode(v, attrs);\n return v;\n}\n\n/*\n * Returns a new graph with only simple edges. Handles aggregation of data\n * associated with multi-edges.\n */\nfunction simplify(g) {\n var simplified = new Graph().setGraph(g.graph());\n _.forEach(g.nodes(), function (v) {\n simplified.setNode(v, g.node(v));\n });\n _.forEach(g.edges(), function (e) {\n var simpleLabel = simplified.edge(e.v, e.w) || { weight: 0, minlen: 1 };\n var label = g.edge(e);\n simplified.setEdge(e.v, e.w, {\n weight: simpleLabel.weight + label.weight,\n minlen: Math.max(simpleLabel.minlen, label.minlen),\n });\n });\n return simplified;\n}\n\nfunction asNonCompoundGraph(g) {\n var simplified = new Graph({ multigraph: g.isMultigraph() }).setGraph(g.graph());\n _.forEach(g.nodes(), function (v) {\n if (!g.children(v).length) {\n simplified.setNode(v, g.node(v));\n }\n });\n _.forEach(g.edges(), function (e) {\n simplified.setEdge(e, g.edge(e));\n });\n return simplified;\n}\n\nfunction successorWeights(g) {\n var weightMap = _.map(g.nodes(), function (v) {\n var sucs = {};\n _.forEach(g.outEdges(v), function (e) {\n sucs[e.w] = (sucs[e.w] || 0) + g.edge(e).weight;\n });\n return sucs;\n });\n return _.zipObject(g.nodes(), weightMap);\n}\n\nfunction predecessorWeights(g) {\n var weightMap = _.map(g.nodes(), function (v) {\n var preds = {};\n _.forEach(g.inEdges(v), function (e) {\n preds[e.v] = (preds[e.v] || 0) + g.edge(e).weight;\n });\n return preds;\n });\n return _.zipObject(g.nodes(), weightMap);\n}\n\n/*\n * Finds where a line starting at point ({x, y}) would intersect a rectangle\n * ({x, y, width, height}) if it were pointing at the rectangle's center.\n */\nfunction intersectRect(rect, point) {\n var x = rect.x;\n var y = rect.y;\n\n // Rectangle intersection algorithm from:\n // http://math.stackexchange.com/questions/108113/find-edge-between-two-boxes\n var dx = point.x - x;\n var dy = point.y - y;\n var w = rect.width / 2;\n var h = rect.height / 2;\n\n if (!dx && !dy) {\n throw new Error('Not possible to find intersection inside of the rectangle');\n }\n\n var sx, sy;\n if (Math.abs(dy) * w > Math.abs(dx) * h) {\n // Intersection is top or bottom of rect.\n if (dy < 0) {\n h = -h;\n }\n sx = (h * dx) / dy;\n sy = h;\n } else {\n // Intersection is left or right of rect.\n if (dx < 0) {\n w = -w;\n }\n sx = w;\n sy = (w * dy) / dx;\n }\n\n return { x: x + sx, y: y + sy };\n}\n\n/*\n * Given a DAG with each node assigned \"rank\" and \"order\" properties, this\n * function will produce a matrix with the ids of each node.\n */\nfunction buildLayerMatrix(g) {\n var layering = _.map(_.range(maxRank(g) + 1), function () {\n return [];\n });\n _.forEach(g.nodes(), function (v) {\n var node = g.node(v);\n var rank = node.rank;\n if (!_.isUndefined(rank)) {\n layering[rank][node.order] = v;\n }\n });\n return layering;\n}\n\n/*\n * Adjusts the ranks for all nodes in the graph such that all nodes v have\n * rank(v) >= 0 and at least one node w has rank(w) = 0.\n */\nfunction normalizeRanks(g) {\n var min = _.min(\n _.map(g.nodes(), function (v) {\n return g.node(v).rank;\n }),\n );\n _.forEach(g.nodes(), function (v) {\n var node = g.node(v);\n if (_.has(node, 'rank')) {\n node.rank -= min;\n }\n });\n}\n\nfunction removeEmptyRanks(g) {\n // Ranks may not start at 0, so we need to offset them\n var offset = _.min(\n _.map(g.nodes(), function (v) {\n return g.node(v).rank;\n }),\n );\n\n var layers = [];\n _.forEach(g.nodes(), function (v) {\n var rank = g.node(v).rank - offset;\n if (!layers[rank]) {\n layers[rank] = [];\n }\n layers[rank].push(v);\n });\n\n var delta = 0;\n var nodeRankFactor = g.graph().nodeRankFactor;\n _.forEach(layers, function (vs, i) {\n if (_.isUndefined(vs) && i % nodeRankFactor !== 0) {\n --delta;\n } else if (delta) {\n _.forEach(vs, function (v) {\n g.node(v).rank += delta;\n });\n }\n });\n}\n\nfunction addBorderNode(g, prefix, rank, order) {\n var node = {\n width: 0,\n height: 0,\n };\n if (arguments.length >= 4) {\n node.rank = rank;\n node.order = order;\n }\n return addDummyNode(g, 'border', node, prefix);\n}\n\nfunction maxRank(g) {\n return _.max(\n _.map(g.nodes(), function (v) {\n var rank = g.node(v).rank;\n if (!_.isUndefined(rank)) {\n return rank;\n }\n }),\n );\n}\n\n/*\n * Partition a collection into two groups: `lhs` and `rhs`. If the supplied\n * function returns true for an entry it goes into `lhs`. Otherwise it goes\n * into `rhs.\n */\nfunction partition(collection, fn) {\n var result = { lhs: [], rhs: [] };\n _.forEach(collection, function (value) {\n if (fn(value)) {\n result.lhs.push(value);\n } else {\n result.rhs.push(value);\n }\n });\n return result;\n}\n\n/*\n * Returns a new function that wraps `fn` with a timer. The wrapper logs the\n * time it takes to execute the function.\n */\nfunction time(name, fn) {\n var start = _.now();\n try {\n return fn();\n } finally {\n console.log(name + ' time: ' + (_.now() - start) + 'ms');\n }\n}\n\nfunction notime(name, fn) {\n return fn();\n}\n", "import * as _ from 'lodash-es';\nimport * as util from './util.js';\n\nexport { addBorderSegments };\n\nfunction addBorderSegments(g) {\n function dfs(v) {\n var children = g.children(v);\n var node = g.node(v);\n if (children.length) {\n _.forEach(children, dfs);\n }\n\n if (Object.prototype.hasOwnProperty.call(node, 'minRank')) {\n node.borderLeft = [];\n node.borderRight = [];\n for (var rank = node.minRank, maxRank = node.maxRank + 1; rank < maxRank; ++rank) {\n addBorderNode(g, 'borderLeft', '_bl', v, node, rank);\n addBorderNode(g, 'borderRight', '_br', v, node, rank);\n }\n }\n }\n\n _.forEach(g.children(), dfs);\n}\n\nfunction addBorderNode(g, prop, prefix, sg, sgNode, rank) {\n var label = { width: 0, height: 0, rank: rank, borderType: prop };\n var prev = sgNode[prop][rank - 1];\n var curr = util.addDummyNode(g, 'border', label, prefix);\n sgNode[prop][rank] = curr;\n g.setParent(curr, sg);\n if (prev) {\n g.setEdge(prev, curr, { weight: 1 });\n }\n}\n", "import * as _ from 'lodash-es';\n\nexport { adjust, undo };\n\nfunction adjust(g) {\n var rankDir = g.graph().rankdir.toLowerCase();\n if (rankDir === 'lr' || rankDir === 'rl') {\n swapWidthHeight(g);\n }\n}\n\nfunction undo(g) {\n var rankDir = g.graph().rankdir.toLowerCase();\n if (rankDir === 'bt' || rankDir === 'rl') {\n reverseY(g);\n }\n\n if (rankDir === 'lr' || rankDir === 'rl') {\n swapXY(g);\n swapWidthHeight(g);\n }\n}\n\nfunction swapWidthHeight(g) {\n _.forEach(g.nodes(), function (v) {\n swapWidthHeightOne(g.node(v));\n });\n _.forEach(g.edges(), function (e) {\n swapWidthHeightOne(g.edge(e));\n });\n}\n\nfunction swapWidthHeightOne(attrs) {\n var w = attrs.width;\n attrs.width = attrs.height;\n attrs.height = w;\n}\n\nfunction reverseY(g) {\n _.forEach(g.nodes(), function (v) {\n reverseYOne(g.node(v));\n });\n\n _.forEach(g.edges(), function (e) {\n var edge = g.edge(e);\n _.forEach(edge.points, reverseYOne);\n if (Object.prototype.hasOwnProperty.call(edge, 'y')) {\n reverseYOne(edge);\n }\n });\n}\n\nfunction reverseYOne(attrs) {\n attrs.y = -attrs.y;\n}\n\nfunction swapXY(g) {\n _.forEach(g.nodes(), function (v) {\n swapXYOne(g.node(v));\n });\n\n _.forEach(g.edges(), function (e) {\n var edge = g.edge(e);\n _.forEach(edge.points, swapXYOne);\n if (Object.prototype.hasOwnProperty.call(edge, 'x')) {\n swapXYOne(edge);\n }\n });\n}\n\nfunction swapXYOne(attrs) {\n var x = attrs.x;\n attrs.x = attrs.y;\n attrs.y = x;\n}\n", "/*\n * Simple doubly linked list implementation derived from Cormen, et al.,\n * \"Introduction to Algorithms\".\n */\n\nexport { List };\n\nclass List {\n constructor() {\n var sentinel = {};\n sentinel._next = sentinel._prev = sentinel;\n this._sentinel = sentinel;\n }\n dequeue() {\n var sentinel = this._sentinel;\n var entry = sentinel._prev;\n if (entry !== sentinel) {\n unlink(entry);\n return entry;\n }\n }\n enqueue(entry) {\n var sentinel = this._sentinel;\n if (entry._prev && entry._next) {\n unlink(entry);\n }\n entry._next = sentinel._next;\n sentinel._next._prev = entry;\n sentinel._next = entry;\n entry._prev = sentinel;\n }\n toString() {\n var strs = [];\n var sentinel = this._sentinel;\n var curr = sentinel._prev;\n while (curr !== sentinel) {\n strs.push(JSON.stringify(curr, filterOutLinks));\n curr = curr._prev;\n }\n return '[' + strs.join(', ') + ']';\n }\n}\n\nfunction unlink(entry) {\n entry._prev._next = entry._next;\n entry._next._prev = entry._prev;\n delete entry._next;\n delete entry._prev;\n}\n\nfunction filterOutLinks(k, v) {\n if (k !== '_next' && k !== '_prev') {\n return v;\n }\n}\n", "import * as _ from 'lodash-es';\nimport { Graph } from '../graphlib/index.js';\nimport { List } from './data/list.js';\n\n/*\n * A greedy heuristic for finding a feedback arc set for a graph. A feedback\n * arc set is a set of edges that can be removed to make a graph acyclic.\n * The algorithm comes from: P. Eades, X. Lin, and W. F. Smyth, \"A fast and\n * effective heuristic for the feedback arc set problem.\" This implementation\n * adjusts that from the paper to allow for weighted edges.\n */\nexport { greedyFAS };\n\nvar DEFAULT_WEIGHT_FN = _.constant(1);\n\nfunction greedyFAS(g, weightFn) {\n if (g.nodeCount() <= 1) {\n return [];\n }\n var state = buildState(g, weightFn || DEFAULT_WEIGHT_FN);\n var results = doGreedyFAS(state.graph, state.buckets, state.zeroIdx);\n\n // Expand multi-edges\n return _.flatten(\n _.map(results, function (e) {\n return g.outEdges(e.v, e.w);\n }),\n );\n}\n\nfunction doGreedyFAS(g, buckets, zeroIdx) {\n var results = [];\n var sources = buckets[buckets.length - 1];\n var sinks = buckets[0];\n\n var entry;\n while (g.nodeCount()) {\n while ((entry = sinks.dequeue())) {\n removeNode(g, buckets, zeroIdx, entry);\n }\n while ((entry = sources.dequeue())) {\n removeNode(g, buckets, zeroIdx, entry);\n }\n if (g.nodeCount()) {\n for (var i = buckets.length - 2; i > 0; --i) {\n entry = buckets[i].dequeue();\n if (entry) {\n results = results.concat(removeNode(g, buckets, zeroIdx, entry, true));\n break;\n }\n }\n }\n }\n\n return results;\n}\n\nfunction removeNode(g, buckets, zeroIdx, entry, collectPredecessors) {\n var results = collectPredecessors ? [] : undefined;\n\n _.forEach(g.inEdges(entry.v), function (edge) {\n var weight = g.edge(edge);\n var uEntry = g.node(edge.v);\n\n if (collectPredecessors) {\n results.push({ v: edge.v, w: edge.w });\n }\n\n uEntry.out -= weight;\n assignBucket(buckets, zeroIdx, uEntry);\n });\n\n _.forEach(g.outEdges(entry.v), function (edge) {\n var weight = g.edge(edge);\n var w = edge.w;\n var wEntry = g.node(w);\n wEntry['in'] -= weight;\n assignBucket(buckets, zeroIdx, wEntry);\n });\n\n g.removeNode(entry.v);\n\n return results;\n}\n\nfunction buildState(g, weightFn) {\n var fasGraph = new Graph();\n var maxIn = 0;\n var maxOut = 0;\n\n _.forEach(g.nodes(), function (v) {\n fasGraph.setNode(v, { v: v, in: 0, out: 0 });\n });\n\n // Aggregate weights on nodes, but also sum the weights across multi-edges\n // into a single edge for the fasGraph.\n _.forEach(g.edges(), function (e) {\n var prevWeight = fasGraph.edge(e.v, e.w) || 0;\n var weight = weightFn(e);\n var edgeWeight = prevWeight + weight;\n fasGraph.setEdge(e.v, e.w, edgeWeight);\n maxOut = Math.max(maxOut, (fasGraph.node(e.v).out += weight));\n maxIn = Math.max(maxIn, (fasGraph.node(e.w)['in'] += weight));\n });\n\n var buckets = _.range(maxOut + maxIn + 3).map(function () {\n return new List();\n });\n var zeroIdx = maxIn + 1;\n\n _.forEach(fasGraph.nodes(), function (v) {\n assignBucket(buckets, zeroIdx, fasGraph.node(v));\n });\n\n return { graph: fasGraph, buckets: buckets, zeroIdx: zeroIdx };\n}\n\nfunction assignBucket(buckets, zeroIdx, entry) {\n if (!entry.out) {\n buckets[0].enqueue(entry);\n } else if (!entry['in']) {\n buckets[buckets.length - 1].enqueue(entry);\n } else {\n buckets[entry.out - entry['in'] + zeroIdx].enqueue(entry);\n }\n}\n", "import * as _ from 'lodash-es';\nimport { greedyFAS } from './greedy-fas.js';\n\nexport { run, undo };\n\nfunction run(g) {\n var fas = g.graph().acyclicer === 'greedy' ? greedyFAS(g, weightFn(g)) : dfsFAS(g);\n _.forEach(fas, function (e) {\n var label = g.edge(e);\n g.removeEdge(e);\n label.forwardName = e.name;\n label.reversed = true;\n g.setEdge(e.w, e.v, label, _.uniqueId('rev'));\n });\n\n function weightFn(g) {\n return function (e) {\n return g.edge(e).weight;\n };\n }\n}\n\nfunction dfsFAS(g) {\n var fas = [];\n var stack = {};\n var visited = {};\n\n function dfs(v) {\n if (Object.prototype.hasOwnProperty.call(visited, v)) {\n return;\n }\n visited[v] = true;\n stack[v] = true;\n _.forEach(g.outEdges(v), function (e) {\n if (Object.prototype.hasOwnProperty.call(stack, e.w)) {\n fas.push(e);\n } else {\n dfs(e.w);\n }\n });\n delete stack[v];\n }\n\n _.forEach(g.nodes(), dfs);\n return fas;\n}\n\nfunction undo(g) {\n _.forEach(g.edges(), function (e) {\n var label = g.edge(e);\n if (label.reversed) {\n g.removeEdge(e);\n\n var forwardName = label.forwardName;\n delete label.reversed;\n delete label.forwardName;\n g.setEdge(e.w, e.v, label, forwardName);\n }\n });\n}\n", "/**\n * TypeScript type imports:\n *\n * @import { Graph } from '../graphlib/graph.js';\n */\nimport * as _ from 'lodash-es';\nimport * as util from './util.js';\n\nexport { run, undo };\n\n/*\n * Breaks any long edges in the graph into short segments that span 1 layer\n * each. This operation is undoable with the denormalize function.\n *\n * Pre-conditions:\n *\n * 1. The input graph is a DAG.\n * 2. Each node in the graph has a \"rank\" property.\n *\n * Post-condition:\n *\n * 1. All edges in the graph have a length of 1.\n * 2. Dummy nodes are added where edges have been split into segments.\n * 3. The graph is augmented with a \"dummyChains\" attribute which contains\n * the first dummy in each chain of dummy nodes produced.\n */\nfunction run(g) {\n g.graph().dummyChains = [];\n _.forEach(g.edges(), function (edge) {\n normalizeEdge(g, edge);\n });\n}\n\n/**\n * @param {Graph} g\n */\nfunction normalizeEdge(g, e) {\n var v = e.v;\n var vRank = g.node(v).rank;\n var w = e.w;\n var wRank = g.node(w).rank;\n var name = e.name;\n var edgeLabel = g.edge(e);\n var labelRank = edgeLabel.labelRank;\n\n if (wRank === vRank + 1) return;\n\n g.removeEdge(e);\n\n /**\n * @typedef {Object} Attrs\n * @property {number} width\n * @property {number} height\n * @property {ReturnType} edgeLabel\n * @property {any} edgeObj\n * @property {ReturnType[\"rank\"]} rank\n * @property {string} [dummy]\n * @property {ReturnType[\"labelpos\"]} [labelpos]\n */\n\n /** @type {Attrs | undefined} */\n var attrs = undefined;\n var dummy, i;\n for (i = 0, ++vRank; vRank < wRank; ++i, ++vRank) {\n edgeLabel.points = [];\n attrs = {\n width: 0,\n height: 0,\n edgeLabel: edgeLabel,\n edgeObj: e,\n rank: vRank,\n };\n dummy = util.addDummyNode(g, 'edge', attrs, '_d');\n if (vRank === labelRank) {\n attrs.width = edgeLabel.width;\n attrs.height = edgeLabel.height;\n attrs.dummy = 'edge-label';\n attrs.labelpos = edgeLabel.labelpos;\n }\n g.setEdge(v, dummy, { weight: edgeLabel.weight }, name);\n if (i === 0) {\n g.graph().dummyChains.push(dummy);\n }\n v = dummy;\n }\n\n g.setEdge(v, w, { weight: edgeLabel.weight }, name);\n}\n\nfunction undo(g) {\n _.forEach(g.graph().dummyChains, function (v) {\n var node = g.node(v);\n var origLabel = node.edgeLabel;\n var w;\n g.setEdge(node.edgeObj, origLabel);\n while (node.dummy) {\n w = g.successors(v)[0];\n g.removeNode(v);\n origLabel.points.push({ x: node.x, y: node.y });\n if (node.dummy === 'edge-label') {\n origLabel.x = node.x;\n origLabel.y = node.y;\n origLabel.width = node.width;\n origLabel.height = node.height;\n }\n v = w;\n node = g.node(v);\n }\n });\n}\n", "import * as _ from 'lodash-es';\n\nexport { longestPath, slack };\n\n/*\n * Initializes ranks for the input graph using the longest path algorithm. This\n * algorithm scales well and is fast in practice, it yields rather poor\n * solutions. Nodes are pushed to the lowest layer possible, leaving the bottom\n * ranks wide and leaving edges longer than necessary. However, due to its\n * speed, this algorithm is good for getting an initial ranking that can be fed\n * into other algorithms.\n *\n * This algorithm does not normalize layers because it will be used by other\n * algorithms in most cases. If using this algorithm directly, be sure to\n * run normalize at the end.\n *\n * Pre-conditions:\n *\n * 1. Input graph is a DAG.\n * 2. Input graph node labels can be assigned properties.\n *\n * Post-conditions:\n *\n * 1. Each node will be assign an (unnormalized) \"rank\" property.\n */\nfunction longestPath(g) {\n var visited = {};\n\n function dfs(v) {\n var label = g.node(v);\n if (Object.prototype.hasOwnProperty.call(visited, v)) {\n return label.rank;\n }\n visited[v] = true;\n\n var rank = _.min(\n _.map(g.outEdges(v), function (e) {\n return dfs(e.w) - g.edge(e).minlen;\n }),\n );\n\n if (\n rank === Number.POSITIVE_INFINITY || // return value of _.map([]) for Lodash 3\n rank === undefined || // return value of _.map([]) for Lodash 4\n rank === null\n ) {\n // return value of _.map([null])\n rank = 0;\n }\n\n return (label.rank = rank);\n }\n\n _.forEach(g.sources(), dfs);\n}\n\n/*\n * Returns the amount of slack for the given edge. The slack is defined as the\n * difference between the length of the edge and its minimum length.\n */\nfunction slack(g, e) {\n return g.node(e.w).rank - g.node(e.v).rank - g.edge(e).minlen;\n}\n", "import * as _ from 'lodash-es';\nimport { Graph } from '../../graphlib/index.js';\nimport { slack } from './util.js';\n\nexport { feasibleTree };\n\n/*\n * Constructs a spanning tree with tight edges and adjusted the input node's\n * ranks to achieve this. A tight edge is one that is has a length that matches\n * its \"minlen\" attribute.\n *\n * The basic structure for this function is derived from Gansner, et al., \"A\n * Technique for Drawing Directed Graphs.\"\n *\n * Pre-conditions:\n *\n * 1. Graph must be a DAG.\n * 2. Graph must be connected.\n * 3. Graph must have at least one node.\n * 5. Graph nodes must have been previously assigned a \"rank\" property that\n * respects the \"minlen\" property of incident edges.\n * 6. Graph edges must have a \"minlen\" property.\n *\n * Post-conditions:\n *\n * - Graph nodes will have their rank adjusted to ensure that all edges are\n * tight.\n *\n * Returns a tree (undirected graph) that is constructed using only \"tight\"\n * edges.\n */\nfunction feasibleTree(g) {\n var t = new Graph({ directed: false });\n\n // Choose arbitrary node from which to start our tree\n var start = g.nodes()[0];\n var size = g.nodeCount();\n t.setNode(start, {});\n\n var edge, delta;\n while (tightTree(t, g) < size) {\n edge = findMinSlackEdge(t, g);\n delta = t.hasNode(edge.v) ? slack(g, edge) : -slack(g, edge);\n shiftRanks(t, g, delta);\n }\n\n return t;\n}\n\n/*\n * Finds a maximal tree of tight edges and returns the number of nodes in the\n * tree.\n */\nfunction tightTree(t, g) {\n function dfs(v) {\n _.forEach(g.nodeEdges(v), function (e) {\n var edgeV = e.v,\n w = v === edgeV ? e.w : edgeV;\n if (!t.hasNode(w) && !slack(g, e)) {\n t.setNode(w, {});\n t.setEdge(v, w, {});\n dfs(w);\n }\n });\n }\n\n _.forEach(t.nodes(), dfs);\n return t.nodeCount();\n}\n\n/*\n * Finds the edge with the smallest slack that is incident on tree and returns\n * it.\n */\nfunction findMinSlackEdge(t, g) {\n return _.minBy(g.edges(), function (e) {\n if (t.hasNode(e.v) !== t.hasNode(e.w)) {\n return slack(g, e);\n }\n });\n}\n\nfunction shiftRanks(t, g, delta) {\n _.forEach(t.nodes(), function (v) {\n g.node(v).rank += delta;\n });\n}\n", "import * as _ from 'lodash-es';\nimport { PriorityQueue } from '../data/priority-queue.js';\n\nexport { dijkstra };\n\nvar DEFAULT_WEIGHT_FUNC = _.constant(1);\n\nfunction dijkstra(g, source, weightFn, edgeFn) {\n return runDijkstra(\n g,\n String(source),\n weightFn || DEFAULT_WEIGHT_FUNC,\n edgeFn ||\n function (v) {\n return g.outEdges(v);\n },\n );\n}\n\nfunction runDijkstra(g, source, weightFn, edgeFn) {\n var results = {};\n var pq = new PriorityQueue();\n var v, vEntry;\n\n var updateNeighbors = function (edge) {\n var w = edge.v !== v ? edge.v : edge.w;\n var wEntry = results[w];\n var weight = weightFn(edge);\n var distance = vEntry.distance + weight;\n\n if (weight < 0) {\n throw new Error(\n 'dijkstra does not allow negative edge weights. ' +\n 'Bad edge: ' +\n edge +\n ' Weight: ' +\n weight,\n );\n }\n\n if (distance < wEntry.distance) {\n wEntry.distance = distance;\n wEntry.predecessor = v;\n pq.decrease(w, distance);\n }\n };\n\n g.nodes().forEach(function (v) {\n var distance = v === source ? 0 : Number.POSITIVE_INFINITY;\n results[v] = { distance: distance };\n pq.add(v, distance);\n });\n\n while (pq.size() > 0) {\n v = pq.removeMin();\n vEntry = results[v];\n if (vEntry.distance === Number.POSITIVE_INFINITY) {\n break;\n }\n\n edgeFn(v).forEach(updateNeighbors);\n }\n\n return results;\n}\n", "import * as _ from 'lodash-es';\n\nexport { floydWarshall };\n\nvar DEFAULT_WEIGHT_FUNC = _.constant(1);\n\nfunction floydWarshall(g, weightFn, edgeFn) {\n return runFloydWarshall(\n g,\n weightFn || DEFAULT_WEIGHT_FUNC,\n edgeFn ||\n function (v) {\n return g.outEdges(v);\n },\n );\n}\n\nfunction runFloydWarshall(g, weightFn, edgeFn) {\n var results = {};\n var nodes = g.nodes();\n\n nodes.forEach(function (v) {\n results[v] = {};\n results[v][v] = { distance: 0 };\n nodes.forEach(function (w) {\n if (v !== w) {\n results[v][w] = { distance: Number.POSITIVE_INFINITY };\n }\n });\n edgeFn(v).forEach(function (edge) {\n var w = edge.v === v ? edge.w : edge.v;\n var d = weightFn(edge);\n results[v][w] = { distance: d, predecessor: v };\n });\n });\n\n nodes.forEach(function (k) {\n var rowK = results[k];\n nodes.forEach(function (i) {\n var rowI = results[i];\n nodes.forEach(function (j) {\n var ik = rowI[k];\n var kj = rowK[j];\n var ij = rowI[j];\n var altDistance = ik.distance + kj.distance;\n if (altDistance < ij.distance) {\n ij.distance = altDistance;\n ij.predecessor = kj.predecessor;\n }\n });\n });\n });\n\n return results;\n}\n", "import * as _ from 'lodash-es';\n\nexport { topsort, CycleException };\n\ntopsort.CycleException = CycleException;\n\nfunction topsort(g) {\n var visited = {};\n var stack = {};\n var results = [];\n\n function visit(node) {\n if (Object.prototype.hasOwnProperty.call(stack, node)) {\n throw new CycleException();\n }\n\n if (!Object.prototype.hasOwnProperty.call(visited, node)) {\n stack[node] = true;\n visited[node] = true;\n _.each(g.predecessors(node), visit);\n delete stack[node];\n results.push(node);\n }\n }\n\n _.each(g.sinks(), visit);\n\n if (_.size(visited) !== g.nodeCount()) {\n throw new CycleException();\n }\n\n return results;\n}\n\nfunction CycleException() {}\nCycleException.prototype = new Error(); // must be an instance of Error to pass testing\n", "import * as _ from 'lodash-es';\n\nexport { dfs };\n\n/*\n * A helper that preforms a pre- or post-order traversal on the input graph\n * and returns the nodes in the order they were visited. If the graph is\n * undirected then this algorithm will navigate using neighbors. If the graph\n * is directed then this algorithm will navigate using successors.\n *\n * Order must be one of \"pre\" or \"post\".\n */\nfunction dfs(g, vs, order) {\n if (!_.isArray(vs)) {\n vs = [vs];\n }\n\n var navigation = (g.isDirected() ? g.successors : g.neighbors).bind(g);\n\n var acc = [];\n var visited = {};\n _.each(vs, function (v) {\n if (!g.hasNode(v)) {\n throw new Error('Graph does not have node: ' + v);\n }\n\n doDfs(g, v, order === 'post', visited, navigation, acc);\n });\n return acc;\n}\n\nfunction doDfs(g, v, postorder, visited, navigation, acc) {\n if (!Object.prototype.hasOwnProperty.call(visited, v)) {\n visited[v] = true;\n\n if (!postorder) {\n acc.push(v);\n }\n _.each(navigation(v), function (w) {\n doDfs(g, w, postorder, visited, navigation, acc);\n });\n if (postorder) {\n acc.push(v);\n }\n }\n}\n", "import { dfs } from './dfs.js';\n\nexport { postorder };\n\nfunction postorder(g, vs) {\n return dfs(g, vs, 'post');\n}\n", "import { dfs } from './dfs.js';\n\nexport { preorder };\n\nfunction preorder(g, vs) {\n return dfs(g, vs, 'pre');\n}\n", "import * as _ from 'lodash-es';\nimport * as alg from '../../graphlib/alg/index.js';\nimport { simplify } from '../util.js';\nimport { feasibleTree } from './feasible-tree.js';\nimport { longestPath, slack } from './util.js';\n\nexport { networkSimplex };\n\n// Expose some internals for testing purposes\nnetworkSimplex.initLowLimValues = initLowLimValues;\nnetworkSimplex.initCutValues = initCutValues;\nnetworkSimplex.calcCutValue = calcCutValue;\nnetworkSimplex.leaveEdge = leaveEdge;\nnetworkSimplex.enterEdge = enterEdge;\nnetworkSimplex.exchangeEdges = exchangeEdges;\n\n/*\n * The network simplex algorithm assigns ranks to each node in the input graph\n * and iteratively improves the ranking to reduce the length of edges.\n *\n * Preconditions:\n *\n * 1. The input graph must be a DAG.\n * 2. All nodes in the graph must have an object value.\n * 3. All edges in the graph must have \"minlen\" and \"weight\" attributes.\n *\n * Postconditions:\n *\n * 1. All nodes in the graph will have an assigned \"rank\" attribute that has\n * been optimized by the network simplex algorithm. Ranks start at 0.\n *\n *\n * A rough sketch of the algorithm is as follows:\n *\n * 1. Assign initial ranks to each node. We use the longest path algorithm,\n * which assigns ranks to the lowest position possible. In general this\n * leads to very wide bottom ranks and unnecessarily long edges.\n * 2. Construct a feasible tight tree. A tight tree is one such that all\n * edges in the tree have no slack (difference between length of edge\n * and minlen for the edge). This by itself greatly improves the assigned\n * rankings by shorting edges.\n * 3. Iteratively find edges that have negative cut values. Generally a\n * negative cut value indicates that the edge could be removed and a new\n * tree edge could be added to produce a more compact graph.\n *\n * Much of the algorithms here are derived from Gansner, et al., \"A Technique\n * for Drawing Directed Graphs.\" The structure of the file roughly follows the\n * structure of the overall algorithm.\n */\nfunction networkSimplex(g) {\n g = simplify(g);\n longestPath(g);\n var t = feasibleTree(g);\n initLowLimValues(t);\n initCutValues(t, g);\n\n var e, f;\n while ((e = leaveEdge(t))) {\n f = enterEdge(t, g, e);\n exchangeEdges(t, g, e, f);\n }\n}\n\n/*\n * Initializes cut values for all edges in the tree.\n */\nfunction initCutValues(t, g) {\n var vs = alg.postorder(t, t.nodes());\n vs = vs.slice(0, vs.length - 1);\n _.forEach(vs, function (v) {\n assignCutValue(t, g, v);\n });\n}\n\nfunction assignCutValue(t, g, child) {\n var childLab = t.node(child);\n var parent = childLab.parent;\n t.edge(child, parent).cutvalue = calcCutValue(t, g, child);\n}\n\n/*\n * Given the tight tree, its graph, and a child in the graph calculate and\n * return the cut value for the edge between the child and its parent.\n */\nfunction calcCutValue(t, g, child) {\n var childLab = t.node(child);\n var parent = childLab.parent;\n // True if the child is on the tail end of the edge in the directed graph\n var childIsTail = true;\n // The graph's view of the tree edge we're inspecting\n var graphEdge = g.edge(child, parent);\n // The accumulated cut value for the edge between this node and its parent\n var cutValue = 0;\n\n if (!graphEdge) {\n childIsTail = false;\n graphEdge = g.edge(parent, child);\n }\n\n cutValue = graphEdge.weight;\n\n _.forEach(g.nodeEdges(child), function (e) {\n var isOutEdge = e.v === child,\n other = isOutEdge ? e.w : e.v;\n\n if (other !== parent) {\n var pointsToHead = isOutEdge === childIsTail,\n otherWeight = g.edge(e).weight;\n\n cutValue += pointsToHead ? otherWeight : -otherWeight;\n if (isTreeEdge(t, child, other)) {\n var otherCutValue = t.edge(child, other).cutvalue;\n cutValue += pointsToHead ? -otherCutValue : otherCutValue;\n }\n }\n });\n\n return cutValue;\n}\n\nfunction initLowLimValues(tree, root) {\n if (arguments.length < 2) {\n root = tree.nodes()[0];\n }\n dfsAssignLowLim(tree, {}, 1, root);\n}\n\nfunction dfsAssignLowLim(tree, visited, nextLim, v, parent) {\n var low = nextLim;\n var label = tree.node(v);\n\n visited[v] = true;\n _.forEach(tree.neighbors(v), function (w) {\n if (!Object.prototype.hasOwnProperty.call(visited, w)) {\n nextLim = dfsAssignLowLim(tree, visited, nextLim, w, v);\n }\n });\n\n label.low = low;\n label.lim = nextLim++;\n if (parent) {\n label.parent = parent;\n } else {\n // TODO should be able to remove this when we incrementally update low lim\n delete label.parent;\n }\n\n return nextLim;\n}\n\nfunction leaveEdge(tree) {\n return _.find(tree.edges(), function (e) {\n return tree.edge(e).cutvalue < 0;\n });\n}\n\nfunction enterEdge(t, g, edge) {\n var v = edge.v;\n var w = edge.w;\n\n // For the rest of this function we assume that v is the tail and w is the\n // head, so if we don't have this edge in the graph we should flip it to\n // match the correct orientation.\n if (!g.hasEdge(v, w)) {\n v = edge.w;\n w = edge.v;\n }\n\n var vLabel = t.node(v);\n var wLabel = t.node(w);\n var tailLabel = vLabel;\n var flip = false;\n\n // If the root is in the tail of the edge then we need to flip the logic that\n // checks for the head and tail nodes in the candidates function below.\n if (vLabel.lim > wLabel.lim) {\n tailLabel = wLabel;\n flip = true;\n }\n\n var candidates = _.filter(g.edges(), function (edge) {\n return (\n flip === isDescendant(t, t.node(edge.v), tailLabel) &&\n flip !== isDescendant(t, t.node(edge.w), tailLabel)\n );\n });\n\n return _.minBy(candidates, function (edge) {\n return slack(g, edge);\n });\n}\n\nfunction exchangeEdges(t, g, e, f) {\n var v = e.v;\n var w = e.w;\n t.removeEdge(v, w);\n t.setEdge(f.v, f.w, {});\n initLowLimValues(t);\n initCutValues(t, g);\n updateRanks(t, g);\n}\n\nfunction updateRanks(t, g) {\n var root = _.find(t.nodes(), function (v) {\n return !g.node(v).parent;\n });\n var vs = alg.preorder(t, root);\n vs = vs.slice(1);\n _.forEach(vs, function (v) {\n var parent = t.node(v).parent,\n edge = g.edge(v, parent),\n flipped = false;\n\n if (!edge) {\n edge = g.edge(parent, v);\n flipped = true;\n }\n\n g.node(v).rank = g.node(parent).rank + (flipped ? edge.minlen : -edge.minlen);\n });\n}\n\n/*\n * Returns true if the edge is in the tree.\n */\nfunction isTreeEdge(tree, u, v) {\n return tree.hasEdge(u, v);\n}\n\n/*\n * Returns true if the specified node is descendant of the root node per the\n * assigned low and lim attributes in the tree.\n */\nfunction isDescendant(tree, vLabel, rootLabel) {\n return rootLabel.low <= vLabel.lim && vLabel.lim <= rootLabel.lim;\n}\n", "import { feasibleTree } from './feasible-tree.js';\nimport { networkSimplex } from './network-simplex.js';\nimport { longestPath } from './util.js';\n\nexport { rank };\n\n/*\n * Assigns a rank to each node in the input graph that respects the \"minlen\"\n * constraint specified on edges between nodes.\n *\n * This basic structure is derived from Gansner, et al., \"A Technique for\n * Drawing Directed Graphs.\"\n *\n * Pre-conditions:\n *\n * 1. Graph must be a connected DAG\n * 2. Graph nodes must be objects\n * 3. Graph edges must have \"weight\" and \"minlen\" attributes\n *\n * Post-conditions:\n *\n * 1. Graph nodes will have a \"rank\" attribute based on the results of the\n * algorithm. Ranks can start at any index (including negative), we'll\n * fix them up later.\n */\nfunction rank(g) {\n switch (g.graph().ranker) {\n case 'network-simplex':\n networkSimplexRanker(g);\n break;\n case 'tight-tree':\n tightTreeRanker(g);\n break;\n case 'longest-path':\n longestPathRanker(g);\n break;\n default:\n networkSimplexRanker(g);\n }\n}\n\n// A fast and simple ranker, but results are far from optimal.\nvar longestPathRanker = longestPath;\n\nfunction tightTreeRanker(g) {\n longestPath(g);\n feasibleTree(g);\n}\n\nfunction networkSimplexRanker(g) {\n networkSimplex(g);\n}\n", "import * as _ from 'lodash-es';\nimport * as util from './util.js';\n\nexport { run, cleanup };\n\n/*\n * A nesting graph creates dummy nodes for the tops and bottoms of subgraphs,\n * adds appropriate edges to ensure that all cluster nodes are placed between\n * these boundries, and ensures that the graph is connected.\n *\n * In addition we ensure, through the use of the minlen property, that nodes\n * and subgraph border nodes to not end up on the same rank.\n *\n * Preconditions:\n *\n * 1. Input graph is a DAG\n * 2. Nodes in the input graph has a minlen attribute\n *\n * Postconditions:\n *\n * 1. Input graph is connected.\n * 2. Dummy nodes are added for the tops and bottoms of subgraphs.\n * 3. The minlen attribute for nodes is adjusted to ensure nodes do not\n * get placed on the same rank as subgraph border nodes.\n *\n * The nesting graph idea comes from Sander, \"Layout of Compound Directed\n * Graphs.\"\n */\nfunction run(g) {\n var root = util.addDummyNode(g, 'root', {}, '_root');\n var depths = treeDepths(g);\n var height = _.max(_.values(depths)) - 1; // Note: depths is an Object not an array\n var nodeSep = 2 * height + 1;\n\n g.graph().nestingRoot = root;\n\n // Multiply minlen by nodeSep to align nodes on non-border ranks.\n _.forEach(g.edges(), function (e) {\n g.edge(e).minlen *= nodeSep;\n });\n\n // Calculate a weight that is sufficient to keep subgraphs vertically compact\n var weight = sumWeights(g) + 1;\n\n // Create border nodes and link them up\n _.forEach(g.children(), function (child) {\n dfs(g, root, nodeSep, weight, height, depths, child);\n });\n\n // Save the multiplier for node layers for later removal of empty border\n // layers.\n g.graph().nodeRankFactor = nodeSep;\n}\n\nfunction dfs(g, root, nodeSep, weight, height, depths, v) {\n var children = g.children(v);\n if (!children.length) {\n if (v !== root) {\n g.setEdge(root, v, { weight: 0, minlen: nodeSep });\n }\n return;\n }\n\n var top = util.addBorderNode(g, '_bt');\n var bottom = util.addBorderNode(g, '_bb');\n var label = g.node(v);\n\n g.setParent(top, v);\n label.borderTop = top;\n g.setParent(bottom, v);\n label.borderBottom = bottom;\n\n _.forEach(children, function (child) {\n dfs(g, root, nodeSep, weight, height, depths, child);\n\n var childNode = g.node(child);\n var childTop = childNode.borderTop ? childNode.borderTop : child;\n var childBottom = childNode.borderBottom ? childNode.borderBottom : child;\n var thisWeight = childNode.borderTop ? weight : 2 * weight;\n var minlen = childTop !== childBottom ? 1 : height - depths[v] + 1;\n\n g.setEdge(top, childTop, {\n weight: thisWeight,\n minlen: minlen,\n nestingEdge: true,\n });\n\n g.setEdge(childBottom, bottom, {\n weight: thisWeight,\n minlen: minlen,\n nestingEdge: true,\n });\n });\n\n if (!g.parent(v)) {\n g.setEdge(root, top, { weight: 0, minlen: height + depths[v] });\n }\n}\n\nfunction treeDepths(g) {\n var depths = {};\n function dfs(v, depth) {\n var children = g.children(v);\n if (children && children.length) {\n _.forEach(children, function (child) {\n dfs(child, depth + 1);\n });\n }\n depths[v] = depth;\n }\n _.forEach(g.children(), function (v) {\n dfs(v, 1);\n });\n return depths;\n}\n\nfunction sumWeights(g) {\n return _.reduce(\n g.edges(),\n function (acc, e) {\n return acc + g.edge(e).weight;\n },\n 0,\n );\n}\n\nfunction cleanup(g) {\n var graphLabel = g.graph();\n g.removeNode(graphLabel.nestingRoot);\n delete graphLabel.nestingRoot;\n _.forEach(g.edges(), function (e) {\n var edge = g.edge(e);\n if (edge.nestingEdge) {\n g.removeEdge(e);\n }\n });\n}\n", "import * as _ from 'lodash-es';\n\nexport { addSubgraphConstraints };\n\nfunction addSubgraphConstraints(g, cg, vs) {\n var prev = {},\n rootPrev;\n\n _.forEach(vs, function (v) {\n var child = g.parent(v),\n parent,\n prevChild;\n while (child) {\n parent = g.parent(child);\n if (parent) {\n prevChild = prev[parent];\n prev[parent] = child;\n } else {\n prevChild = rootPrev;\n rootPrev = child;\n }\n if (prevChild && prevChild !== child) {\n cg.setEdge(prevChild, child);\n return;\n }\n child = parent;\n }\n });\n\n /*\n function dfs(v) {\n var children = v ? g.children(v) : g.children();\n if (children.length) {\n var min = Number.POSITIVE_INFINITY,\n subgraphs = [];\n _.each(children, function(child) {\n var childMin = dfs(child);\n if (g.children(child).length) {\n subgraphs.push({ v: child, order: childMin });\n }\n min = Math.min(min, childMin);\n });\n _.reduce(_.sortBy(subgraphs, \"order\"), function(prev, curr) {\n cg.setEdge(prev.v, curr.v);\n return curr;\n });\n return min;\n }\n return g.node(v).order;\n }\n dfs(undefined);\n */\n}\n", "import * as _ from 'lodash-es';\nimport { Graph } from '../../graphlib/index.js';\n\nexport { buildLayerGraph };\n\n/*\n * Constructs a graph that can be used to sort a layer of nodes. The graph will\n * contain all base and subgraph nodes from the request layer in their original\n * hierarchy and any edges that are incident on these nodes and are of the type\n * requested by the \"relationship\" parameter.\n *\n * Nodes from the requested rank that do not have parents are assigned a root\n * node in the output graph, which is set in the root graph attribute. This\n * makes it easy to walk the hierarchy of movable nodes during ordering.\n *\n * Pre-conditions:\n *\n * 1. Input graph is a DAG\n * 2. Base nodes in the input graph have a rank attribute\n * 3. Subgraph nodes in the input graph has minRank and maxRank attributes\n * 4. Edges have an assigned weight\n *\n * Post-conditions:\n *\n * 1. Output graph has all nodes in the movable rank with preserved\n * hierarchy.\n * 2. Root nodes in the movable layer are made children of the node\n * indicated by the root attribute of the graph.\n * 3. Non-movable nodes incident on movable nodes, selected by the\n * relationship parameter, are included in the graph (without hierarchy).\n * 4. Edges incident on movable nodes, selected by the relationship\n * parameter, are added to the output graph.\n * 5. The weights for copied edges are aggregated as need, since the output\n * graph is not a multi-graph.\n */\nfunction buildLayerGraph(g, rank, relationship) {\n var root = createRootNode(g),\n result = new Graph({ compound: true })\n .setGraph({ root: root })\n .setDefaultNodeLabel(function (v) {\n return g.node(v);\n });\n\n _.forEach(g.nodes(), function (v) {\n var node = g.node(v),\n parent = g.parent(v);\n\n if (node.rank === rank || (node.minRank <= rank && rank <= node.maxRank)) {\n result.setNode(v);\n result.setParent(v, parent || root);\n\n // This assumes we have only short edges!\n _.forEach(g[relationship](v), function (e) {\n var u = e.v === v ? e.w : e.v,\n edge = result.edge(u, v),\n weight = !_.isUndefined(edge) ? edge.weight : 0;\n result.setEdge(u, v, { weight: g.edge(e).weight + weight });\n });\n\n if (Object.prototype.hasOwnProperty.call(node, 'minRank')) {\n result.setNode(v, {\n borderLeft: node.borderLeft[rank],\n borderRight: node.borderRight[rank],\n });\n }\n }\n });\n\n return result;\n}\n\nfunction createRootNode(g) {\n var v;\n while (g.hasNode((v = _.uniqueId('_root'))));\n return v;\n}\n", "import * as _ from 'lodash-es';\n\nexport { crossCount };\n\n/*\n * A function that takes a layering (an array of layers, each with an array of\n * ordererd nodes) and a graph and returns a weighted crossing count.\n *\n * Pre-conditions:\n *\n * 1. Input graph must be simple (not a multigraph), directed, and include\n * only simple edges.\n * 2. Edges in the input graph must have assigned weights.\n *\n * Post-conditions:\n *\n * 1. The graph and layering matrix are left unchanged.\n *\n * This algorithm is derived from Barth, et al., \"Bilayer Cross Counting.\"\n */\nfunction crossCount(g, layering) {\n var cc = 0;\n for (var i = 1; i < layering.length; ++i) {\n cc += twoLayerCrossCount(g, layering[i - 1], layering[i]);\n }\n return cc;\n}\n\nfunction twoLayerCrossCount(g, northLayer, southLayer) {\n // Sort all of the edges between the north and south layers by their position\n // in the north layer and then the south. Map these edges to the position of\n // their head in the south layer.\n var southPos = _.zipObject(\n southLayer,\n _.map(southLayer, function (v, i) {\n return i;\n }),\n );\n var southEntries = _.flatten(\n _.map(northLayer, function (v) {\n return _.sortBy(\n _.map(g.outEdges(v), function (e) {\n return { pos: southPos[e.w], weight: g.edge(e).weight };\n }),\n 'pos',\n );\n }),\n );\n\n // Build the accumulator tree\n var firstIndex = 1;\n while (firstIndex < southLayer.length) firstIndex <<= 1;\n var treeSize = 2 * firstIndex - 1;\n firstIndex -= 1;\n var tree = _.map(new Array(treeSize), function () {\n return 0;\n });\n\n // Calculate the weighted crossings\n var cc = 0;\n _.forEach(\n // @ts-expect-error\n southEntries.forEach(function (entry) {\n var index = entry.pos + firstIndex;\n tree[index] += entry.weight;\n var weightSum = 0;\n // @ts-expect-error\n while (index > 0) {\n // @ts-expect-error\n if (index % 2) {\n weightSum += tree[index + 1];\n }\n // @ts-expect-error\n index = (index - 1) >> 1;\n tree[index] += entry.weight;\n }\n cc += entry.weight * weightSum;\n }),\n );\n\n return cc;\n}\n", "import * as _ from 'lodash-es';\n\n/*\n * Assigns an initial order value for each node by performing a DFS search\n * starting from nodes in the first rank. Nodes are assigned an order in their\n * rank as they are first visited.\n *\n * This approach comes from Gansner, et al., \"A Technique for Drawing Directed\n * Graphs.\"\n *\n * Returns a layering matrix with an array per layer and each layer sorted by\n * the order of its nodes.\n */\nexport function initOrder(g) {\n var visited = {};\n var simpleNodes = _.filter(g.nodes(), function (v) {\n return !g.children(v).length;\n });\n var maxRank = _.max(\n _.map(simpleNodes, function (v) {\n return g.node(v).rank;\n }),\n );\n var layers = _.map(_.range(maxRank + 1), function () {\n return [];\n });\n\n function dfs(v) {\n if (_.has(visited, v)) return;\n visited[v] = true;\n var node = g.node(v);\n layers[node.rank].push(v);\n _.forEach(g.successors(v), dfs);\n }\n\n var orderedVs = _.sortBy(simpleNodes, function (v) {\n return g.node(v).rank;\n });\n _.forEach(orderedVs, dfs);\n\n return layers;\n}\n", "import * as _ from 'lodash-es';\n\nexport { barycenter };\n\nfunction barycenter(g, movable) {\n return _.map(movable, function (v) {\n var inV = g.inEdges(v);\n if (!inV.length) {\n return { v: v };\n } else {\n var result = _.reduce(\n inV,\n function (acc, e) {\n var edge = g.edge(e),\n nodeU = g.node(e.v);\n return {\n sum: acc.sum + edge.weight * nodeU.order,\n weight: acc.weight + edge.weight,\n };\n },\n { sum: 0, weight: 0 },\n );\n\n return {\n v: v,\n barycenter: result.sum / result.weight,\n weight: result.weight,\n };\n }\n });\n}\n", "import * as _ from 'lodash-es';\n\nexport { resolveConflicts };\n\n/*\n * Given a list of entries of the form {v, barycenter, weight} and a\n * constraint graph this function will resolve any conflicts between the\n * constraint graph and the barycenters for the entries. If the barycenters for\n * an entry would violate a constraint in the constraint graph then we coalesce\n * the nodes in the conflict into a new node that respects the contraint and\n * aggregates barycenter and weight information.\n *\n * This implementation is based on the description in Forster, \"A Fast and\n * Simple Hueristic for Constrained Two-Level Crossing Reduction,\" thought it\n * differs in some specific details.\n *\n * Pre-conditions:\n *\n * 1. Each entry has the form {v, barycenter, weight}, or if the node has\n * no barycenter, then {v}.\n *\n * Returns:\n *\n * A new list of entries of the form {vs, i, barycenter, weight}. The list\n * `vs` may either be a singleton or it may be an aggregation of nodes\n * ordered such that they do not violate constraints from the constraint\n * graph. The property `i` is the lowest original index of any of the\n * elements in `vs`.\n */\nfunction resolveConflicts(entries, cg) {\n var mappedEntries = {};\n _.forEach(entries, function (entry, i) {\n var tmp = (mappedEntries[entry.v] = {\n indegree: 0,\n in: [],\n out: [],\n vs: [entry.v],\n i: i,\n });\n if (!_.isUndefined(entry.barycenter)) {\n // @ts-expect-error\n tmp.barycenter = entry.barycenter;\n // @ts-expect-error\n tmp.weight = entry.weight;\n }\n });\n\n _.forEach(cg.edges(), function (e) {\n var entryV = mappedEntries[e.v];\n var entryW = mappedEntries[e.w];\n if (!_.isUndefined(entryV) && !_.isUndefined(entryW)) {\n entryW.indegree++;\n entryV.out.push(mappedEntries[e.w]);\n }\n });\n\n var sourceSet = _.filter(mappedEntries, function (entry) {\n // @ts-expect-error\n return !entry.indegree;\n });\n\n return doResolveConflicts(sourceSet);\n}\n\nfunction doResolveConflicts(sourceSet) {\n var entries = [];\n\n function handleIn(vEntry) {\n return function (uEntry) {\n if (uEntry.merged) {\n return;\n }\n if (\n _.isUndefined(uEntry.barycenter) ||\n _.isUndefined(vEntry.barycenter) ||\n uEntry.barycenter >= vEntry.barycenter\n ) {\n mergeEntries(vEntry, uEntry);\n }\n };\n }\n\n function handleOut(vEntry) {\n return function (wEntry) {\n wEntry['in'].push(vEntry);\n if (--wEntry.indegree === 0) {\n sourceSet.push(wEntry);\n }\n };\n }\n\n while (sourceSet.length) {\n var entry = sourceSet.pop();\n entries.push(entry);\n _.forEach(entry['in'].reverse(), handleIn(entry));\n _.forEach(entry.out, handleOut(entry));\n }\n\n return _.map(\n _.filter(entries, function (entry) {\n return !entry.merged;\n }),\n function (entry) {\n return _.pick(entry, ['vs', 'i', 'barycenter', 'weight']);\n },\n );\n}\n\nfunction mergeEntries(target, source) {\n var sum = 0;\n var weight = 0;\n\n if (target.weight) {\n sum += target.barycenter * target.weight;\n weight += target.weight;\n }\n\n if (source.weight) {\n sum += source.barycenter * source.weight;\n weight += source.weight;\n }\n\n target.vs = source.vs.concat(target.vs);\n target.barycenter = sum / weight;\n target.weight = weight;\n target.i = Math.min(source.i, target.i);\n source.merged = true;\n}\n", "import * as _ from 'lodash-es';\nimport * as util from '../util.js';\n\nexport { sort };\n\nfunction sort(entries, biasRight) {\n var parts = util.partition(entries, function (entry) {\n return Object.prototype.hasOwnProperty.call(entry, 'barycenter');\n });\n var sortable = parts.lhs,\n unsortable = _.sortBy(parts.rhs, function (entry) {\n return -entry.i;\n }),\n vs = [],\n sum = 0,\n weight = 0,\n vsIndex = 0;\n\n sortable.sort(compareWithBias(!!biasRight));\n\n vsIndex = consumeUnsortable(vs, unsortable, vsIndex);\n\n _.forEach(sortable, function (entry) {\n vsIndex += entry.vs.length;\n vs.push(entry.vs);\n sum += entry.barycenter * entry.weight;\n weight += entry.weight;\n vsIndex = consumeUnsortable(vs, unsortable, vsIndex);\n });\n\n var result = { vs: _.flatten(vs) };\n if (weight) {\n result.barycenter = sum / weight;\n result.weight = weight;\n }\n return result;\n}\n\nfunction consumeUnsortable(vs, unsortable, index) {\n var last;\n while (unsortable.length && (last = _.last(unsortable)).i <= index) {\n unsortable.pop();\n vs.push(last.vs);\n index++;\n }\n return index;\n}\n\nfunction compareWithBias(bias) {\n return function (entryV, entryW) {\n if (entryV.barycenter < entryW.barycenter) {\n return -1;\n } else if (entryV.barycenter > entryW.barycenter) {\n return 1;\n }\n\n return !bias ? entryV.i - entryW.i : entryW.i - entryV.i;\n };\n}\n", "import * as _ from 'lodash-es';\nimport { barycenter } from './barycenter.js';\nimport { resolveConflicts } from './resolve-conflicts.js';\nimport { sort } from './sort.js';\n\nexport { sortSubgraph };\n\nfunction sortSubgraph(g, v, cg, biasRight) {\n var movable = g.children(v);\n var node = g.node(v);\n var bl = node ? node.borderLeft : undefined;\n var br = node ? node.borderRight : undefined;\n var subgraphs = {};\n\n if (bl) {\n movable = _.filter(movable, function (w) {\n return w !== bl && w !== br;\n });\n }\n\n var barycenters = barycenter(g, movable);\n _.forEach(barycenters, function (entry) {\n if (g.children(entry.v).length) {\n var subgraphResult = sortSubgraph(g, entry.v, cg, biasRight);\n subgraphs[entry.v] = subgraphResult;\n if (Object.prototype.hasOwnProperty.call(subgraphResult, 'barycenter')) {\n mergeBarycenters(entry, subgraphResult);\n }\n }\n });\n\n var entries = resolveConflicts(barycenters, cg);\n expandSubgraphs(entries, subgraphs);\n\n var result = sort(entries, biasRight);\n\n if (bl) {\n result.vs = _.flatten([bl, result.vs, br]);\n if (g.predecessors(bl).length) {\n var blPred = g.node(g.predecessors(bl)[0]),\n brPred = g.node(g.predecessors(br)[0]);\n if (!Object.prototype.hasOwnProperty.call(result, 'barycenter')) {\n result.barycenter = 0;\n result.weight = 0;\n }\n result.barycenter =\n (result.barycenter * result.weight + blPred.order + brPred.order) / (result.weight + 2);\n result.weight += 2;\n }\n }\n\n return result;\n}\n\nfunction expandSubgraphs(entries, subgraphs) {\n _.forEach(entries, function (entry) {\n entry.vs = _.flatten(\n entry.vs.map(function (v) {\n if (subgraphs[v]) {\n return subgraphs[v].vs;\n }\n return v;\n }),\n );\n });\n}\n\nfunction mergeBarycenters(target, other) {\n if (!_.isUndefined(target.barycenter)) {\n target.barycenter =\n (target.barycenter * target.weight + other.barycenter * other.weight) /\n (target.weight + other.weight);\n target.weight += other.weight;\n } else {\n target.barycenter = other.barycenter;\n target.weight = other.weight;\n }\n}\n", "import * as _ from 'lodash-es';\nimport { Graph } from '../../graphlib/index.js';\nimport * as util from '../util.js';\nimport { addSubgraphConstraints } from './add-subgraph-constraints.js';\nimport { buildLayerGraph } from './build-layer-graph.js';\nimport { crossCount } from './cross-count.js';\nimport { initOrder } from './init-order.js';\nimport { sortSubgraph } from './sort-subgraph.js';\n\nexport { order };\n\n/*\n * Applies heuristics to minimize edge crossings in the graph and sets the best\n * order solution as an order attribute on each node.\n *\n * Pre-conditions:\n *\n * 1. Graph must be DAG\n * 2. Graph nodes must be objects with a \"rank\" attribute\n * 3. Graph edges must have the \"weight\" attribute\n *\n * Post-conditions:\n *\n * 1. Graph nodes will have an \"order\" attribute based on the results of the\n * algorithm.\n */\nfunction order(g) {\n var maxRank = util.maxRank(g),\n downLayerGraphs = buildLayerGraphs(g, _.range(1, maxRank + 1), 'inEdges'),\n upLayerGraphs = buildLayerGraphs(g, _.range(maxRank - 1, -1, -1), 'outEdges');\n\n var layering = initOrder(g);\n assignOrder(g, layering);\n\n var bestCC = Number.POSITIVE_INFINITY,\n best;\n\n for (var i = 0, lastBest = 0; lastBest < 4; ++i, ++lastBest) {\n sweepLayerGraphs(i % 2 ? downLayerGraphs : upLayerGraphs, i % 4 >= 2);\n\n layering = util.buildLayerMatrix(g);\n var cc = crossCount(g, layering);\n if (cc < bestCC) {\n lastBest = 0;\n best = _.cloneDeep(layering);\n bestCC = cc;\n }\n }\n\n assignOrder(g, best);\n}\n\nfunction buildLayerGraphs(g, ranks, relationship) {\n return _.map(ranks, function (rank) {\n return buildLayerGraph(g, rank, relationship);\n });\n}\n\nfunction sweepLayerGraphs(layerGraphs, biasRight) {\n var cg = new Graph();\n _.forEach(layerGraphs, function (lg) {\n var root = lg.graph().root;\n var sorted = sortSubgraph(lg, root, cg, biasRight);\n _.forEach(sorted.vs, function (v, i) {\n lg.node(v).order = i;\n });\n addSubgraphConstraints(lg, cg, sorted.vs);\n });\n}\n\nfunction assignOrder(g, layering) {\n _.forEach(layering, function (layer) {\n _.forEach(layer, function (v, i) {\n g.node(v).order = i;\n });\n });\n}\n", "import * as _ from 'lodash-es';\n\nexport { parentDummyChains };\n\nfunction parentDummyChains(g) {\n var postorderNums = postorder(g);\n\n _.forEach(g.graph().dummyChains, function (v) {\n var node = g.node(v);\n var edgeObj = node.edgeObj;\n var pathData = findPath(g, postorderNums, edgeObj.v, edgeObj.w);\n var path = pathData.path;\n var lca = pathData.lca;\n var pathIdx = 0;\n var pathV = path[pathIdx];\n var ascending = true;\n\n while (v !== edgeObj.w) {\n node = g.node(v);\n\n if (ascending) {\n while ((pathV = path[pathIdx]) !== lca && g.node(pathV).maxRank < node.rank) {\n pathIdx++;\n }\n\n if (pathV === lca) {\n ascending = false;\n }\n }\n\n if (!ascending) {\n while (\n pathIdx < path.length - 1 &&\n g.node((pathV = path[pathIdx + 1])).minRank <= node.rank\n ) {\n pathIdx++;\n }\n pathV = path[pathIdx];\n }\n\n g.setParent(v, pathV);\n v = g.successors(v)[0];\n }\n });\n}\n\n// Find a path from v to w through the lowest common ancestor (LCA). Return the\n// full path and the LCA.\nfunction findPath(g, postorderNums, v, w) {\n var vPath = [];\n var wPath = [];\n var low = Math.min(postorderNums[v].low, postorderNums[w].low);\n var lim = Math.max(postorderNums[v].lim, postorderNums[w].lim);\n var parent;\n var lca;\n\n // Traverse up from v to find the LCA\n parent = v;\n do {\n parent = g.parent(parent);\n vPath.push(parent);\n } while (parent && (postorderNums[parent].low > low || lim > postorderNums[parent].lim));\n lca = parent;\n\n // Traverse from w to LCA\n parent = w;\n while ((parent = g.parent(parent)) !== lca) {\n wPath.push(parent);\n }\n\n return { path: vPath.concat(wPath.reverse()), lca: lca };\n}\n\nfunction postorder(g) {\n var result = {};\n var lim = 0;\n\n function dfs(v) {\n var low = lim;\n _.forEach(g.children(v), dfs);\n result[v] = { low: low, lim: lim++ };\n }\n _.forEach(g.children(), dfs);\n\n return result;\n}\n", "import * as _ from 'lodash-es';\nimport { Graph } from '../../graphlib/index.js';\nimport * as util from '../util.js';\n\n/*\n * This module provides coordinate assignment based on Brandes and K\u00F6pf, \"Fast\n * and Simple Horizontal Coordinate Assignment.\"\n */\n\nexport {\n positionX,\n findType1Conflicts,\n findType2Conflicts,\n addConflict,\n hasConflict,\n verticalAlignment,\n horizontalCompaction,\n alignCoordinates,\n findSmallestWidthAlignment,\n balance,\n};\n\n/*\n * Marks all edges in the graph with a type-1 conflict with the \"type1Conflict\"\n * property. A type-1 conflict is one where a non-inner segment crosses an\n * inner segment. An inner segment is an edge with both incident nodes marked\n * with the \"dummy\" property.\n *\n * This algorithm scans layer by layer, starting with the second, for type-1\n * conflicts between the current layer and the previous layer. For each layer\n * it scans the nodes from left to right until it reaches one that is incident\n * on an inner segment. It then scans predecessors to determine if they have\n * edges that cross that inner segment. At the end a final scan is done for all\n * nodes on the current rank to see if they cross the last visited inner\n * segment.\n *\n * This algorithm (safely) assumes that a dummy node will only be incident on a\n * single node in the layers being scanned.\n */\nfunction findType1Conflicts(g, layering) {\n var conflicts = {};\n\n function visitLayer(prevLayer, layer) {\n var // last visited node in the previous layer that is incident on an inner\n // segment.\n k0 = 0,\n // Tracks the last node in this layer scanned for crossings with a type-1\n // segment.\n scanPos = 0,\n prevLayerLength = prevLayer.length,\n lastNode = _.last(layer);\n\n _.forEach(layer, function (v, i) {\n var w = findOtherInnerSegmentNode(g, v),\n k1 = w ? g.node(w).order : prevLayerLength;\n\n if (w || v === lastNode) {\n _.forEach(layer.slice(scanPos, i + 1), function (scanNode) {\n _.forEach(g.predecessors(scanNode), function (u) {\n var uLabel = g.node(u),\n uPos = uLabel.order;\n if ((uPos < k0 || k1 < uPos) && !(uLabel.dummy && g.node(scanNode).dummy)) {\n addConflict(conflicts, u, scanNode);\n }\n });\n });\n // @ts-expect-error\n scanPos = i + 1;\n k0 = k1;\n }\n });\n\n return layer;\n }\n\n _.reduce(layering, visitLayer);\n return conflicts;\n}\n\nfunction findType2Conflicts(g, layering) {\n var conflicts = {};\n\n function scan(south, southPos, southEnd, prevNorthBorder, nextNorthBorder) {\n var v;\n _.forEach(_.range(southPos, southEnd), function (i) {\n v = south[i];\n if (g.node(v).dummy) {\n _.forEach(g.predecessors(v), function (u) {\n var uNode = g.node(u);\n if (uNode.dummy && (uNode.order < prevNorthBorder || uNode.order > nextNorthBorder)) {\n addConflict(conflicts, u, v);\n }\n });\n }\n });\n }\n\n function visitLayer(north, south) {\n var prevNorthPos = -1,\n nextNorthPos,\n southPos = 0;\n\n _.forEach(south, function (v, southLookahead) {\n if (g.node(v).dummy === 'border') {\n var predecessors = g.predecessors(v);\n if (predecessors.length) {\n nextNorthPos = g.node(predecessors[0]).order;\n scan(south, southPos, southLookahead, prevNorthPos, nextNorthPos);\n // @ts-expect-error\n southPos = southLookahead;\n prevNorthPos = nextNorthPos;\n }\n }\n scan(south, southPos, south.length, nextNorthPos, north.length);\n });\n\n return south;\n }\n\n _.reduce(layering, visitLayer);\n return conflicts;\n}\n\nfunction findOtherInnerSegmentNode(g, v) {\n if (g.node(v).dummy) {\n return _.find(g.predecessors(v), function (u) {\n return g.node(u).dummy;\n });\n }\n}\n\nfunction addConflict(conflicts, v, w) {\n if (v > w) {\n var tmp = v;\n v = w;\n w = tmp;\n }\n\n var conflictsV = conflicts[v];\n if (!conflictsV) {\n conflicts[v] = conflictsV = {};\n }\n conflictsV[w] = true;\n}\n\nfunction hasConflict(conflicts, v, w) {\n if (v > w) {\n var tmp = v;\n v = w;\n w = tmp;\n }\n return !!conflicts[v] && Object.prototype.hasOwnProperty.call(conflicts[v], w);\n}\n\n/*\n * Try to align nodes into vertical \"blocks\" where possible. This algorithm\n * attempts to align a node with one of its median neighbors. If the edge\n * connecting a neighbor is a type-1 conflict then we ignore that possibility.\n * If a previous node has already formed a block with a node after the node\n * we're trying to form a block with, we also ignore that possibility - our\n * blocks would be split in that scenario.\n */\nfunction verticalAlignment(g, layering, conflicts, neighborFn) {\n var root = {},\n align = {},\n pos = {};\n\n // We cache the position here based on the layering because the graph and\n // layering may be out of sync. The layering matrix is manipulated to\n // generate different extreme alignments.\n _.forEach(layering, function (layer) {\n _.forEach(layer, function (v, order) {\n root[v] = v;\n align[v] = v;\n pos[v] = order;\n });\n });\n\n _.forEach(layering, function (layer) {\n var prevIdx = -1;\n _.forEach(layer, function (v) {\n var ws = neighborFn(v);\n if (ws.length) {\n ws = _.sortBy(ws, function (w) {\n return pos[w];\n });\n var mp = (ws.length - 1) / 2;\n for (var i = Math.floor(mp), il = Math.ceil(mp); i <= il; ++i) {\n var w = ws[i];\n if (align[v] === v && prevIdx < pos[w] && !hasConflict(conflicts, v, w)) {\n align[w] = v;\n align[v] = root[v] = root[w];\n prevIdx = pos[w];\n }\n }\n }\n });\n });\n\n return { root: root, align: align };\n}\n\nfunction horizontalCompaction(g, layering, root, align, reverseSep) {\n // This portion of the algorithm differs from BK due to a number of problems.\n // Instead of their algorithm we construct a new block graph and do two\n // sweeps. The first sweep places blocks with the smallest possible\n // coordinates. The second sweep removes unused space by moving blocks to the\n // greatest coordinates without violating separation.\n var xs = {},\n blockG = buildBlockGraph(g, layering, root, reverseSep),\n borderType = reverseSep ? 'borderLeft' : 'borderRight';\n\n function iterate(setXsFunc, nextNodesFunc) {\n var stack = blockG.nodes();\n var elem = stack.pop();\n var visited = {};\n while (elem) {\n if (visited[elem]) {\n setXsFunc(elem);\n } else {\n visited[elem] = true;\n stack.push(elem);\n stack = stack.concat(nextNodesFunc(elem));\n }\n\n elem = stack.pop();\n }\n }\n\n // First pass, assign smallest coordinates\n function pass1(elem) {\n xs[elem] = blockG.inEdges(elem).reduce(function (acc, e) {\n return Math.max(acc, xs[e.v] + blockG.edge(e));\n }, 0);\n }\n\n // Second pass, assign greatest coordinates\n function pass2(elem) {\n var min = blockG.outEdges(elem).reduce(function (acc, e) {\n return Math.min(acc, xs[e.w] - blockG.edge(e));\n }, Number.POSITIVE_INFINITY);\n\n var node = g.node(elem);\n if (min !== Number.POSITIVE_INFINITY && node.borderType !== borderType) {\n xs[elem] = Math.max(xs[elem], min);\n }\n }\n\n iterate(pass1, blockG.predecessors.bind(blockG));\n iterate(pass2, blockG.successors.bind(blockG));\n\n // Assign x coordinates to all nodes\n _.forEach(align, function (v) {\n xs[v] = xs[root[v]];\n });\n\n return xs;\n}\n\nfunction buildBlockGraph(g, layering, root, reverseSep) {\n var blockGraph = new Graph(),\n graphLabel = g.graph(),\n sepFn = sep(graphLabel.nodesep, graphLabel.edgesep, reverseSep);\n\n _.forEach(layering, function (layer) {\n var u;\n _.forEach(layer, function (v) {\n var vRoot = root[v];\n blockGraph.setNode(vRoot);\n if (u) {\n var uRoot = root[u],\n prevMax = blockGraph.edge(uRoot, vRoot);\n blockGraph.setEdge(uRoot, vRoot, Math.max(sepFn(g, v, u), prevMax || 0));\n }\n u = v;\n });\n });\n\n return blockGraph;\n}\n\n/*\n * Returns the alignment that has the smallest width of the given alignments.\n */\nfunction findSmallestWidthAlignment(g, xss) {\n return _.minBy(_.values(xss), function (xs) {\n var max = Number.NEGATIVE_INFINITY;\n var min = Number.POSITIVE_INFINITY;\n\n _.forIn(xs, function (x, v) {\n var halfWidth = width(g, v) / 2;\n\n max = Math.max(x + halfWidth, max);\n min = Math.min(x - halfWidth, min);\n });\n\n return max - min;\n });\n}\n\n/*\n * Align the coordinates of each of the layout alignments such that\n * left-biased alignments have their minimum coordinate at the same point as\n * the minimum coordinate of the smallest width alignment and right-biased\n * alignments have their maximum coordinate at the same point as the maximum\n * coordinate of the smallest width alignment.\n */\nfunction alignCoordinates(xss, alignTo) {\n var alignToVals = _.values(alignTo),\n alignToMin = _.min(alignToVals),\n alignToMax = _.max(alignToVals);\n\n _.forEach(['u', 'd'], function (vert) {\n _.forEach(['l', 'r'], function (horiz) {\n var alignment = vert + horiz,\n xs = xss[alignment],\n delta;\n if (xs === alignTo) return;\n\n var xsVals = _.values(xs);\n delta = horiz === 'l' ? alignToMin - _.min(xsVals) : alignToMax - _.max(xsVals);\n\n if (delta) {\n xss[alignment] = _.mapValues(xs, function (x) {\n return x + delta;\n });\n }\n });\n });\n}\n\nfunction balance(xss, align) {\n return _.mapValues(xss.ul, function (ignore, v) {\n if (align) {\n return xss[align.toLowerCase()][v];\n } else {\n var xs = _.sortBy(_.map(xss, v));\n return (xs[1] + xs[2]) / 2;\n }\n });\n}\n\nfunction positionX(g) {\n var layering = util.buildLayerMatrix(g);\n var conflicts = _.merge(findType1Conflicts(g, layering), findType2Conflicts(g, layering));\n\n var xss = {};\n var adjustedLayering;\n _.forEach(['u', 'd'], function (vert) {\n adjustedLayering = vert === 'u' ? layering : _.values(layering).reverse();\n _.forEach(['l', 'r'], function (horiz) {\n if (horiz === 'r') {\n adjustedLayering = _.map(adjustedLayering, function (inner) {\n return _.values(inner).reverse();\n });\n }\n\n var neighborFn = (vert === 'u' ? g.predecessors : g.successors).bind(g);\n var align = verticalAlignment(g, adjustedLayering, conflicts, neighborFn);\n var xs = horizontalCompaction(g, adjustedLayering, align.root, align.align, horiz === 'r');\n if (horiz === 'r') {\n xs = _.mapValues(xs, function (x) {\n return -x;\n });\n }\n xss[vert + horiz] = xs;\n });\n });\n\n var smallestWidth = findSmallestWidthAlignment(g, xss);\n alignCoordinates(xss, smallestWidth);\n return balance(xss, g.graph().align);\n}\n\nfunction sep(nodeSep, edgeSep, reverseSep) {\n return function (g, v, w) {\n var vLabel = g.node(v);\n var wLabel = g.node(w);\n var sum = 0;\n var delta;\n\n sum += vLabel.width / 2;\n if (Object.prototype.hasOwnProperty.call(vLabel, 'labelpos')) {\n switch (vLabel.labelpos.toLowerCase()) {\n case 'l':\n delta = -vLabel.width / 2;\n break;\n case 'r':\n delta = vLabel.width / 2;\n break;\n }\n }\n if (delta) {\n sum += reverseSep ? delta : -delta;\n }\n delta = 0;\n\n sum += (vLabel.dummy ? edgeSep : nodeSep) / 2;\n sum += (wLabel.dummy ? edgeSep : nodeSep) / 2;\n\n sum += wLabel.width / 2;\n if (Object.prototype.hasOwnProperty.call(wLabel, 'labelpos')) {\n switch (wLabel.labelpos.toLowerCase()) {\n case 'l':\n delta = wLabel.width / 2;\n break;\n case 'r':\n delta = -wLabel.width / 2;\n break;\n }\n }\n if (delta) {\n sum += reverseSep ? delta : -delta;\n }\n delta = 0;\n\n return sum;\n };\n}\n\nfunction width(g, v) {\n return g.node(v).width;\n}\n", "import * as _ from 'lodash-es';\nimport * as util from '../util.js';\nimport { positionX } from './bk.js';\n\nexport { position };\n\nfunction position(g) {\n g = util.asNonCompoundGraph(g);\n\n positionY(g);\n _.forOwn(positionX(g), function (x, v) {\n g.node(v).x = x;\n });\n}\n\nfunction positionY(g) {\n var layering = util.buildLayerMatrix(g);\n var rankSep = g.graph().ranksep;\n var prevY = 0;\n _.forEach(layering, function (layer) {\n var maxHeight = _.max(\n _.map(layer, function (v) {\n return g.node(v).height;\n }),\n );\n _.forEach(layer, function (v) {\n g.node(v).y = prevY + maxHeight / 2;\n });\n prevY += maxHeight + rankSep;\n });\n}\n", "import * as _ from 'lodash-es';\nimport { Graph } from '../graphlib/index.js';\nimport { addBorderSegments } from './add-border-segments.js';\nimport * as coordinateSystem from './coordinate-system.js';\nimport * as acyclic from './acyclic.js';\nimport * as normalize from './normalize.js';\nimport { rank } from './rank/index.js';\nimport * as nestingGraph from './nesting-graph.js';\nimport { order } from './order/index.js';\nimport { parentDummyChains } from './parent-dummy-chains.js';\nimport { position } from './position/index.js';\nimport * as util from './util.js';\n\nexport { layout };\n\nfunction layout(g, opts) {\n var time = opts && opts.debugTiming ? util.time : util.notime;\n time('layout', () => {\n var layoutGraph = time(' buildLayoutGraph', () => buildLayoutGraph(g));\n time(' runLayout', () => runLayout(layoutGraph, time));\n time(' updateInputGraph', () => updateInputGraph(g, layoutGraph));\n });\n}\n\nfunction runLayout(g, time) {\n time(' makeSpaceForEdgeLabels', () => makeSpaceForEdgeLabels(g));\n time(' removeSelfEdges', () => removeSelfEdges(g));\n time(' acyclic', () => acyclic.run(g));\n time(' nestingGraph.run', () => nestingGraph.run(g));\n time(' rank', () => rank(util.asNonCompoundGraph(g)));\n time(' injectEdgeLabelProxies', () => injectEdgeLabelProxies(g));\n time(' removeEmptyRanks', () => util.removeEmptyRanks(g));\n time(' nestingGraph.cleanup', () => nestingGraph.cleanup(g));\n time(' normalizeRanks', () => util.normalizeRanks(g));\n time(' assignRankMinMax', () => assignRankMinMax(g));\n time(' removeEdgeLabelProxies', () => removeEdgeLabelProxies(g));\n time(' normalize.run', () => normalize.run(g));\n time(' parentDummyChains', () => parentDummyChains(g));\n time(' addBorderSegments', () => addBorderSegments(g));\n time(' order', () => order(g));\n time(' insertSelfEdges', () => insertSelfEdges(g));\n time(' adjustCoordinateSystem', () => coordinateSystem.adjust(g));\n time(' position', () => position(g));\n time(' positionSelfEdges', () => positionSelfEdges(g));\n time(' removeBorderNodes', () => removeBorderNodes(g));\n time(' normalize.undo', () => normalize.undo(g));\n time(' fixupEdgeLabelCoords', () => fixupEdgeLabelCoords(g));\n time(' undoCoordinateSystem', () => coordinateSystem.undo(g));\n time(' translateGraph', () => translateGraph(g));\n time(' assignNodeIntersects', () => assignNodeIntersects(g));\n time(' reversePoints', () => reversePointsForReversedEdges(g));\n time(' acyclic.undo', () => acyclic.undo(g));\n}\n\n/*\n * Copies final layout information from the layout graph back to the input\n * graph. This process only copies whitelisted attributes from the layout graph\n * to the input graph, so it serves as a good place to determine what\n * attributes can influence layout.\n */\nfunction updateInputGraph(inputGraph, layoutGraph) {\n _.forEach(inputGraph.nodes(), function (v) {\n var inputLabel = inputGraph.node(v);\n var layoutLabel = layoutGraph.node(v);\n\n if (inputLabel) {\n inputLabel.x = layoutLabel.x;\n inputLabel.y = layoutLabel.y;\n\n if (layoutGraph.children(v).length) {\n inputLabel.width = layoutLabel.width;\n inputLabel.height = layoutLabel.height;\n }\n }\n });\n\n _.forEach(inputGraph.edges(), function (e) {\n var inputLabel = inputGraph.edge(e);\n var layoutLabel = layoutGraph.edge(e);\n\n inputLabel.points = layoutLabel.points;\n if (Object.prototype.hasOwnProperty.call(layoutLabel, 'x')) {\n inputLabel.x = layoutLabel.x;\n inputLabel.y = layoutLabel.y;\n }\n });\n\n inputGraph.graph().width = layoutGraph.graph().width;\n inputGraph.graph().height = layoutGraph.graph().height;\n}\n\nvar graphNumAttrs = ['nodesep', 'edgesep', 'ranksep', 'marginx', 'marginy'];\nvar graphDefaults = { ranksep: 50, edgesep: 20, nodesep: 50, rankdir: 'tb' };\nvar graphAttrs = ['acyclicer', 'ranker', 'rankdir', 'align'];\nvar nodeNumAttrs = ['width', 'height'];\nvar nodeDefaults = { width: 0, height: 0 };\nvar edgeNumAttrs = ['minlen', 'weight', 'width', 'height', 'labeloffset'];\nvar edgeDefaults = {\n minlen: 1,\n weight: 1,\n width: 0,\n height: 0,\n labeloffset: 10,\n labelpos: 'r',\n};\nvar edgeAttrs = ['labelpos'];\n\n/*\n * Constructs a new graph from the input graph, which can be used for layout.\n * This process copies only whitelisted attributes from the input graph to the\n * layout graph. Thus this function serves as a good place to determine what\n * attributes can influence layout.\n */\nfunction buildLayoutGraph(inputGraph) {\n var g = new Graph({ multigraph: true, compound: true });\n var graph = canonicalize(inputGraph.graph());\n\n g.setGraph(\n _.merge({}, graphDefaults, selectNumberAttrs(graph, graphNumAttrs), _.pick(graph, graphAttrs)),\n );\n\n _.forEach(inputGraph.nodes(), function (v) {\n var node = canonicalize(inputGraph.node(v));\n g.setNode(v, _.defaults(selectNumberAttrs(node, nodeNumAttrs), nodeDefaults));\n g.setParent(v, inputGraph.parent(v));\n });\n\n _.forEach(inputGraph.edges(), function (e) {\n var edge = canonicalize(inputGraph.edge(e));\n g.setEdge(\n e,\n _.merge({}, edgeDefaults, selectNumberAttrs(edge, edgeNumAttrs), _.pick(edge, edgeAttrs)),\n );\n });\n\n return g;\n}\n\n/*\n * This idea comes from the Gansner paper: to account for edge labels in our\n * layout we split each rank in half by doubling minlen and halving ranksep.\n * Then we can place labels at these mid-points between nodes.\n *\n * We also add some minimal padding to the width to push the label for the edge\n * away from the edge itself a bit.\n */\nfunction makeSpaceForEdgeLabels(g) {\n var graph = g.graph();\n graph.ranksep /= 2;\n _.forEach(g.edges(), function (e) {\n var edge = g.edge(e);\n edge.minlen *= 2;\n if (edge.labelpos.toLowerCase() !== 'c') {\n if (graph.rankdir === 'TB' || graph.rankdir === 'BT') {\n edge.width += edge.labeloffset;\n } else {\n edge.height += edge.labeloffset;\n }\n }\n });\n}\n\n/*\n * Creates temporary dummy nodes that capture the rank in which each edge's\n * label is going to, if it has one of non-zero width and height. We do this\n * so that we can safely remove empty ranks while preserving balance for the\n * label's position.\n */\nfunction injectEdgeLabelProxies(g) {\n _.forEach(g.edges(), function (e) {\n var edge = g.edge(e);\n if (edge.width && edge.height) {\n var v = g.node(e.v);\n var w = g.node(e.w);\n var label = { rank: (w.rank - v.rank) / 2 + v.rank, e: e };\n util.addDummyNode(g, 'edge-proxy', label, '_ep');\n }\n });\n}\n\nfunction assignRankMinMax(g) {\n var maxRank = 0;\n _.forEach(g.nodes(), function (v) {\n var node = g.node(v);\n if (node.borderTop) {\n node.minRank = g.node(node.borderTop).rank;\n node.maxRank = g.node(node.borderBottom).rank;\n // @ts-expect-error\n maxRank = _.max(maxRank, node.maxRank);\n }\n });\n g.graph().maxRank = maxRank;\n}\n\nfunction removeEdgeLabelProxies(g) {\n _.forEach(g.nodes(), function (v) {\n var node = g.node(v);\n if (node.dummy === 'edge-proxy') {\n g.edge(node.e).labelRank = node.rank;\n g.removeNode(v);\n }\n });\n}\n\nfunction translateGraph(g) {\n var minX = Number.POSITIVE_INFINITY;\n var maxX = 0;\n var minY = Number.POSITIVE_INFINITY;\n var maxY = 0;\n var graphLabel = g.graph();\n var marginX = graphLabel.marginx || 0;\n var marginY = graphLabel.marginy || 0;\n\n function getExtremes(attrs) {\n var x = attrs.x;\n var y = attrs.y;\n var w = attrs.width;\n var h = attrs.height;\n minX = Math.min(minX, x - w / 2);\n maxX = Math.max(maxX, x + w / 2);\n minY = Math.min(minY, y - h / 2);\n maxY = Math.max(maxY, y + h / 2);\n }\n\n _.forEach(g.nodes(), function (v) {\n getExtremes(g.node(v));\n });\n _.forEach(g.edges(), function (e) {\n var edge = g.edge(e);\n if (Object.prototype.hasOwnProperty.call(edge, 'x')) {\n getExtremes(edge);\n }\n });\n\n minX -= marginX;\n minY -= marginY;\n\n _.forEach(g.nodes(), function (v) {\n var node = g.node(v);\n node.x -= minX;\n node.y -= minY;\n });\n\n _.forEach(g.edges(), function (e) {\n var edge = g.edge(e);\n _.forEach(edge.points, function (p) {\n p.x -= minX;\n p.y -= minY;\n });\n if (Object.prototype.hasOwnProperty.call(edge, 'x')) {\n edge.x -= minX;\n }\n if (Object.prototype.hasOwnProperty.call(edge, 'y')) {\n edge.y -= minY;\n }\n });\n\n graphLabel.width = maxX - minX + marginX;\n graphLabel.height = maxY - minY + marginY;\n}\n\nfunction assignNodeIntersects(g) {\n _.forEach(g.edges(), function (e) {\n var edge = g.edge(e);\n var nodeV = g.node(e.v);\n var nodeW = g.node(e.w);\n var p1, p2;\n if (!edge.points) {\n edge.points = [];\n p1 = nodeW;\n p2 = nodeV;\n } else {\n p1 = edge.points[0];\n p2 = edge.points[edge.points.length - 1];\n }\n edge.points.unshift(util.intersectRect(nodeV, p1));\n edge.points.push(util.intersectRect(nodeW, p2));\n });\n}\n\nfunction fixupEdgeLabelCoords(g) {\n _.forEach(g.edges(), function (e) {\n var edge = g.edge(e);\n if (Object.prototype.hasOwnProperty.call(edge, 'x')) {\n if (edge.labelpos === 'l' || edge.labelpos === 'r') {\n edge.width -= edge.labeloffset;\n }\n switch (edge.labelpos) {\n case 'l':\n edge.x -= edge.width / 2 + edge.labeloffset;\n break;\n case 'r':\n edge.x += edge.width / 2 + edge.labeloffset;\n break;\n }\n }\n });\n}\n\nfunction reversePointsForReversedEdges(g) {\n _.forEach(g.edges(), function (e) {\n var edge = g.edge(e);\n if (edge.reversed) {\n edge.points.reverse();\n }\n });\n}\n\nfunction removeBorderNodes(g) {\n _.forEach(g.nodes(), function (v) {\n if (g.children(v).length) {\n var node = g.node(v);\n var t = g.node(node.borderTop);\n var b = g.node(node.borderBottom);\n var l = g.node(_.last(node.borderLeft));\n var r = g.node(_.last(node.borderRight));\n\n node.width = Math.abs(r.x - l.x);\n node.height = Math.abs(b.y - t.y);\n node.x = l.x + node.width / 2;\n node.y = t.y + node.height / 2;\n }\n });\n\n _.forEach(g.nodes(), function (v) {\n if (g.node(v).dummy === 'border') {\n g.removeNode(v);\n }\n });\n}\n\nfunction removeSelfEdges(g) {\n _.forEach(g.edges(), function (e) {\n if (e.v === e.w) {\n var node = g.node(e.v);\n if (!node.selfEdges) {\n node.selfEdges = [];\n }\n node.selfEdges.push({ e: e, label: g.edge(e) });\n g.removeEdge(e);\n }\n });\n}\n\nfunction insertSelfEdges(g) {\n var layers = util.buildLayerMatrix(g);\n _.forEach(layers, function (layer) {\n var orderShift = 0;\n _.forEach(layer, function (v, i) {\n var node = g.node(v);\n node.order = i + orderShift;\n _.forEach(node.selfEdges, function (selfEdge) {\n util.addDummyNode(\n g,\n 'selfedge',\n {\n width: selfEdge.label.width,\n height: selfEdge.label.height,\n rank: node.rank,\n order: i + ++orderShift,\n e: selfEdge.e,\n label: selfEdge.label,\n },\n '_se',\n );\n });\n delete node.selfEdges;\n });\n });\n}\n\nfunction positionSelfEdges(g) {\n _.forEach(g.nodes(), function (v) {\n var node = g.node(v);\n if (node.dummy === 'selfedge') {\n var selfNode = g.node(node.e.v);\n var x = selfNode.x + selfNode.width / 2;\n var y = selfNode.y;\n var dx = node.x - x;\n var dy = selfNode.height / 2;\n g.setEdge(node.e, node.label);\n g.removeNode(v);\n node.label.points = [\n { x: x + (2 * dx) / 3, y: y - dy },\n { x: x + (5 * dx) / 6, y: y - dy },\n { x: x + dx, y: y },\n { x: x + (5 * dx) / 6, y: y + dy },\n { x: x + (2 * dx) / 3, y: y + dy },\n ];\n node.label.x = node.x;\n node.label.y = node.y;\n }\n });\n}\n\nfunction selectNumberAttrs(obj, attrs) {\n return _.mapValues(_.pick(obj, attrs), Number);\n}\n\nfunction canonicalize(attrs) {\n var newAttrs = {};\n _.forEach(attrs, function (v, k) {\n newAttrs[k.toLowerCase()] = v;\n });\n return newAttrs;\n}\n"], + "mappings": "gUAuBA,SAASA,EAAaC,EAAGC,EAAMC,EAAOC,EAAM,CAC1C,IAAIC,EACJ,GACEA,EAAMC,EAASF,CAAI,QACZH,EAAE,QAAQI,CAAC,GAEpB,OAAAF,EAAM,MAAQD,EACdD,EAAE,QAAQI,EAAGF,CAAK,EACXE,CACT,CAMA,SAASE,GAASN,EAAG,CACnB,IAAIO,EAAa,IAAIC,EAAM,EAAE,SAASR,EAAE,MAAM,CAAC,EAC/C,OAAES,EAAQT,EAAE,MAAM,EAAG,SAAUI,EAAG,CAChCG,EAAW,QAAQH,EAAGJ,EAAE,KAAKI,CAAC,CAAC,CACjC,CAAC,EACCK,EAAQT,EAAE,MAAM,EAAG,SAAUU,EAAG,CAChC,IAAIC,EAAcJ,EAAW,KAAKG,EAAE,EAAGA,EAAE,CAAC,GAAK,CAAE,OAAQ,EAAG,OAAQ,CAAE,EAClEE,EAAQZ,EAAE,KAAKU,CAAC,EACpBH,EAAW,QAAQG,EAAE,EAAGA,EAAE,EAAG,CAC3B,OAAQC,EAAY,OAASC,EAAM,OACnC,OAAQ,KAAK,IAAID,EAAY,OAAQC,EAAM,MAAM,CACnD,CAAC,CACH,CAAC,EACML,CACT,CAEA,SAASM,EAAmBb,EAAG,CAC7B,IAAIO,EAAa,IAAIC,EAAM,CAAE,WAAYR,EAAE,aAAa,CAAE,CAAC,EAAE,SAASA,EAAE,MAAM,CAAC,EAC/E,OAAES,EAAQT,EAAE,MAAM,EAAG,SAAUI,EAAG,CAC3BJ,EAAE,SAASI,CAAC,EAAE,QACjBG,EAAW,QAAQH,EAAGJ,EAAE,KAAKI,CAAC,CAAC,CAEnC,CAAC,EACCK,EAAQT,EAAE,MAAM,EAAG,SAAUU,E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rC,OAASwB,EAAYzC,EAAKwC,EAAKvB,CAAK,EAAG,MAAM,CAC/C,CAEA,SAASpB,GAAaoB,EAAO,CAC3B,IAAIyB,EAAW,CAAC,EAChB,OAAE5D,EAAQmC,EAAO,SAAUlC,EAAG4D,EAAG,CAC/BD,EAASC,EAAE,YAAY,CAAC,EAAI5D,CAC9B,CAAC,EACM2D,CACT", + "names": ["addDummyNode", "g", "type", "attrs", "name", "v", "uniqueId_default", "simplify", "simplified", "Graph", "forEach_default", "e", "simpleLabel", "label", "asNonCompoundGraph", "intersectRect", "rect", "point", "x", "y", "dx", "dy", "w", "h", "sx", "sy", "buildLayerMatrix", "g", "layering", "map_default", "range_default", "maxRank", "forEach_default", "v", "node", "rank", "isUndefined_default", "normalizeRanks", "min", "min_default", "has_default", "removeEmptyRanks", "offset", "layers", "delta", "nodeRankFactor", "vs", "addBorderNode", "prefix", "order", "addDummyNode", "max_default", "partition", "collection", "fn", "result", "value", "time", "name", "start", "now_default", "notime", "addBorderSegments", "g", "dfs", "v", "children", "node", "forEach_default", "rank", "maxRank", "addBorderNode", "prop", "prefix", "sg", "sgNode", "label", "prev", "curr", "addDummyNode", "adjust", "g", "rankDir", "swapWidthHeight", "undo", "reverseY", "swapXY", "forEach_default", "v", "swapWidthHeightOne", "attrs", "w", "reverseYOne", "edge", "swapXYOne", "x", "List", "sentinel", "entry", "unlink", "strs", "curr", "filterOutLinks", "k", "v", "DEFAULT_WEIGHT_FN", "constant_default", "greedyFAS", "g", "weightFn", "state", "buildState", "results", "doGreedyFAS", "flatten_default", "map_default", "e", "buckets", "zeroIdx", "sources", "sinks", "entry", "removeNode", "i", "collectPredecessors", "forEach_default", "edge", "weight", "uEntry", "assignBucket", "w", "wEntry", "fasGraph", "Graph", "maxIn", "maxOut", "v", "prevWeight", "edgeWeight", "range_default", "List", "run", "g", "fas", "greedyFAS", "weightFn", "dfsFAS", "forEach_default", "e", "label", "uniqueId_default", "stack", "visited", "dfs", "v", "undo", "forwardName", "run", "g", "forEach_default", "edge", "normalizeEdge", "v", "vRank", "w", "wRank", "name", "edgeLabel", "labelRank", "attrs", "dummy", "i", "addDummyNode", "undo", "node", "origLabel", "longestPath", "g", "visited", "dfs", "v", "label", "rank", "min_default", "map_default", "e", "forEach_default", "slack", "feasibleTree", "g", "t", "Graph", "start", "size", "edge", "delta", "tightTree", "findMinSlackEdge", "slack", "shiftRanks", "dfs", "v", "forEach_default", "e", "edgeV", "w", "minBy_default", "DEFAULT_WEIGHT_FUNC", "constant_default", "DEFAULT_WEIGHT_FUNC", "constant_default", "topsort", "CycleException", "g", "visited", "stack", "results", "visit", "node", "forEach_default", "size_default", "dfs", "g", "vs", "order", "isArray_default", "navigation", "acc", "visited", "forEach_default", "v", "doDfs", "postorder", "w", "postorder", "g", "vs", "dfs", "preorder", "g", "vs", "dfs", "networkSimplex", "initLowLimValues", "initCutValues", "calcCutValue", "leaveEdge", "enterEdge", "exchangeEdges", "g", "simplify", "longestPath", "t", "feasibleTree", "e", "f", "vs", "postorder", "forEach_default", "v", "assignCutValue", "child", "childLab", "parent", "childIsTail", "graphEdge", "cutValue", "isOutEdge", "other", "pointsToHead", "otherWeight", "isTreeEdge", "otherCutValue", "tree", "root", "dfsAssignLowLim", "visited", "nextLim", "low", "label", "w", "find_default", "edge", "vLabel", "wLabel", "tailLabel", "flip", "candidates", "filter_default", "isDescendant", "minBy_default", "slack", "updateRanks", "preorder", "flipped", "u", "rootLabel", "rank", "g", "networkSimplexRanker", "tightTreeRanker", "longestPathRanker", "longestPath", "feasibleTree", "networkSimplex", "run", "g", "root", "addDummyNode", "depths", "treeDepths", "height", "max_default", "values_default", "nodeSep", "forEach_default", "e", "weight", "sumWeights", "child", "dfs", "v", "children", "top", "addBorderNode", "bottom", "label", "childNode", "childTop", "childBottom", "thisWeight", "minlen", "depth", "reduce_default", "acc", "cleanup", "graphLabel", "edge", "addSubgraphConstraints", "g", "cg", "vs", "prev", "rootPrev", "forEach_default", "v", "child", "parent", "prevChild", "buildLayerGraph", "g", "rank", "relationship", "root", "createRootNode", "result", "Graph", "v", "forEach_default", "node", "parent", "e", "u", "edge", "weight", "isUndefined_default", "uniqueId_default", "crossCount", "g", "layering", "cc", "i", "twoLayerCrossCount", "northLayer", "southLayer", "southPos", "zipObject_default", "map_default", "v", "southEntries", "flatten_default", "sortBy_default", "e", "firstIndex", "treeSize", "tree", "forEach_default", "entry", "index", "weightSum", "initOrder", "g", "visited", "simpleNodes", "filter_default", "v", "maxRank", "max_default", "map_default", "layers", "range_default", "dfs", "has_default", "node", "forEach_default", "orderedVs", "sortBy_default", "barycenter", "g", "movable", "map_default", "v", "inV", "result", "reduce_default", "acc", "e", "edge", "nodeU", "resolveConflicts", "entries", "cg", "mappedEntries", "forEach_default", "entry", "i", "tmp", "isUndefined_default", "e", "entryV", "entryW", "sourceSet", "filter_default", "doResolveConflicts", "handleIn", "vEntry", "uEntry", "mergeEntries", "handleOut", "wEntry", "map_default", "pick_default", "target", "source", "sum", "weight", "sort", "entries", "biasRight", "parts", "partition", "entry", "sortable", "unsortable", "sortBy_default", "vs", "sum", "weight", "vsIndex", "compareWithBias", "consumeUnsortable", "forEach_default", "result", "flatten_default", "index", "last", "last_default", "bias", "entryV", "entryW", "sortSubgraph", "g", "v", "cg", "biasRight", "movable", "node", "bl", "br", "subgraphs", "filter_default", "w", "barycenters", "barycenter", "forEach_default", "entry", "subgraphResult", "mergeBarycenters", "entries", "resolveConflicts", "expandSubgraphs", "result", "sort", "flatten_default", "blPred", "brPred", "target", "other", "isUndefined_default", "order", "g", "maxRank", "downLayerGraphs", "buildLayerGraphs", "range_default", "upLayerGraphs", "layering", "initOrder", "assignOrder", "bestCC", "best", "i", "lastBest", "sweepLayerGraphs", "buildLayerMatrix", "cc", "crossCount", "cloneDeep_default", "ranks", "relationship", "map_default", "rank", "buildLayerGraph", "layerGraphs", "biasRight", "cg", "Graph", "forEach_default", "lg", "root", "sorted", "sortSubgraph", "v", "addSubgraphConstraints", "layer", "parentDummyChains", "g", "postorderNums", "postorder", "forEach_default", "v", "node", "edgeObj", "pathData", "findPath", "path", "lca", "pathIdx", "pathV", "ascending", "w", "vPath", "wPath", "low", "lim", "parent", "result", "dfs", "findType1Conflicts", "g", "layering", "conflicts", "visitLayer", "prevLayer", "layer", "k0", "scanPos", "prevLayerLength", "lastNode", "last_default", "forEach_default", "v", "i", "w", "findOtherInnerSegmentNode", "k1", "scanNode", "u", "uLabel", "uPos", "addConflict", "reduce_default", "findType2Conflicts", "scan", "south", "southPos", "southEnd", "prevNorthBorder", "nextNorthBorder", "range_default", "uNode", "north", "prevNorthPos", "nextNorthPos", "southLookahead", "predecessors", "find_default", "tmp", "conflictsV", "hasConflict", "verticalAlignment", "neighborFn", "root", "align", "pos", "order", "prevIdx", "ws", "sortBy_default", "mp", "il", "horizontalCompaction", "reverseSep", "xs", "blockG", "buildBlockGraph", "borderType", "iterate", "setXsFunc", "nextNodesFunc", "stack", "elem", "visited", "pass1", "acc", "e", "pass2", "min", "node", "blockGraph", "Graph", "graphLabel", "sepFn", "sep", "vRoot", "uRoot", "prevMax", "findSmallestWidthAlignment", "xss", "minBy_default", "values_default", "max", "forIn_default", "x", "halfWidth", "width", "alignCoordinates", "alignTo", "alignToVals", "alignToMin", "min_default", "alignToMax", "max_default", "vert", "horiz", "alignment", "delta", "xsVals", "mapValues_default", "balance", "ignore", "map_default", "positionX", "buildLayerMatrix", "merge_default", "adjustedLayering", "inner", "smallestWidth", "nodeSep", "edgeSep", "vLabel", "wLabel", "sum", "position", "g", "asNonCompoundGraph", "positionY", "forOwn_default", "positionX", "x", "v", "layering", "buildLayerMatrix", "rankSep", "prevY", "forEach_default", "layer", "maxHeight", "max_default", "map_default", "layout", "g", "opts", "time", "notime", "layoutGraph", "buildLayoutGraph", "runLayout", "updateInputGraph", "makeSpaceForEdgeLabels", "removeSelfEdges", "run", "rank", "asNonCompoundGraph", "injectEdgeLabelProxies", "removeEmptyRanks", "cleanup", "normalizeRanks", "assignRankMinMax", "removeEdgeLabelProxies", "parentDummyChains", "addBorderSegments", "order", "insertSelfEdges", "adjust", "position", "positionSelfEdges", "removeBorderNodes", "undo", "fixupEdgeLabelCoords", "translateGraph", "assignNodeIntersects", "reversePointsForReversedEdges", "inputGraph", "forEach_default", "v", "inputLabel", "layoutLabel", "e", "graphNumAttrs", "graphDefaults", "graphAttrs", "nodeNumAttrs", "nodeDefaults", "edgeNumAttrs", "edgeDefaults", "edgeAttrs", "Graph", "graph", "canonicalize", "merge_default", "selectNumberAttrs", "pick_default", "node", "defaults_default", "edge", "w", "label", "addDummyNode", "maxRank", "max_default", "minX", "maxX", "minY", "maxY", "graphLabel", "marginX", "marginY", "getExtremes", "attrs", "x", "y", "h", "p", "nodeV", "nodeW", "p1", "p2", "intersectRect", "b", "l", "last_default", "r", "layers", "buildLayerMatrix", "layer", "orderShift", "i", "selfEdge", "selfNode", "dx", "dy", "obj", "mapValues_default", "newAttrs", "k"] +} diff --git a/docs/website/public/chunk-CM5D5KZN.min.js b/docs/website/public/chunk-CM5D5KZN.min.js new file mode 100644 index 000000000..76e50e8b7 --- /dev/null +++ b/docs/website/public/chunk-CM5D5KZN.min.js @@ -0,0 +1,2 @@ +import{a as m}from"./chunk-OSRY5VT3.min.js";var R=m(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.BLANK_URL=e.relativeFirstCharacters=e.whitespaceEscapeCharsRegex=e.urlSchemeRegex=e.ctrlCharactersRegex=e.htmlCtrlEntityRegex=e.htmlEntitiesRegex=e.invalidProtocolRegex=void 0;e.invalidProtocolRegex=/^([^\w]*)(javascript|data|vbscript)/im;e.htmlEntitiesRegex=/&#(\w+)(^\w|;)?/g;e.htmlCtrlEntityRegex=/&(newline|tab);/gi;e.ctrlCharactersRegex=/[\u0000-\u001F\u007F-\u009F\u2000-\u200D\uFEFF]/gim;e.urlSchemeRegex=/^.+(:|:)/gim;e.whitespaceEscapeCharsRegex=/(\\|%5[cC])((%(6[eE]|72|74))|[nrt])/g;e.relativeFirstCharacters=[".","/"];e.BLANK_URL="about:blank"});var p=m(s=>{"use strict";Object.defineProperty(s,"__esModule",{value:!0});s.sanitizeUrl=void 0;var t=R();function d(r){return t.relativeFirstCharacters.indexOf(r[0])>-1}function v(r){var c=r.replace(t.ctrlCharactersRegex,"");return c.replace(t.htmlEntitiesRegex,function(a,i){return String.fromCharCode(i)})}function x(r){return URL.canParse(r)}function g(r){try{return decodeURIComponent(r)}catch{return r}}function C(r){if(!r)return t.BLANK_URL;var c,a=g(r.trim());do a=v(a).replace(t.htmlCtrlEntityRegex,"").replace(t.ctrlCharactersRegex,"").replace(t.whitespaceEscapeCharsRegex,"").trim(),a=g(a),c=a.match(t.ctrlCharactersRegex)||a.match(t.htmlEntitiesRegex)||a.match(t.htmlCtrlEntityRegex)||a.match(t.whitespaceEscapeCharsRegex);while(c&&c.length>0);var i=a;if(!i)return t.BLANK_URL;if(d(i))return i;var h=i.trimStart(),u=h.match(t.urlSchemeRegex);if(!u)return i;var n=u[0].toLowerCase().trim();if(t.invalidProtocolRegex.test(n))return t.BLANK_URL;var o=h.replace(/\\/g,"/");if(n==="mailto:"||n.includes("://"))return o;if(n==="http:"||n==="https:"){if(!x(o))return t.BLANK_URL;var l=new URL(o);return l.protocol=l.protocol.toLowerCase(),l.hostname=l.hostname.toLowerCase(),l.toString()}return o}s.sanitizeUrl=C});export{p as a}; +//# sourceMappingURL=chunk-CM5D5KZN.min.js.map diff --git a/docs/website/public/chunk-CM5D5KZN.min.js.map b/docs/website/public/chunk-CM5D5KZN.min.js.map new file mode 100644 index 000000000..508e75f6f --- /dev/null +++ b/docs/website/public/chunk-CM5D5KZN.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/@braintree/sanitize-url/dist/constants.js", "../../node_modules/@braintree/sanitize-url/dist/index.js"], + "sourcesContent": ["\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BLANK_URL = exports.relativeFirstCharacters = exports.whitespaceEscapeCharsRegex = exports.urlSchemeRegex = exports.ctrlCharactersRegex = exports.htmlCtrlEntityRegex = exports.htmlEntitiesRegex = exports.invalidProtocolRegex = void 0;\nexports.invalidProtocolRegex = /^([^\\w]*)(javascript|data|vbscript)/im;\nexports.htmlEntitiesRegex = /&#(\\w+)(^\\w|;)?/g;\nexports.htmlCtrlEntityRegex = /&(newline|tab);/gi;\nexports.ctrlCharactersRegex = /[\\u0000-\\u001F\\u007F-\\u009F\\u2000-\\u200D\\uFEFF]/gim;\nexports.urlSchemeRegex = /^.+(:|:)/gim;\nexports.whitespaceEscapeCharsRegex = /(\\\\|%5[cC])((%(6[eE]|72|74))|[nrt])/g;\nexports.relativeFirstCharacters = [\".\", \"/\"];\nexports.BLANK_URL = \"about:blank\";\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.sanitizeUrl = void 0;\nvar constants_1 = require(\"./constants\");\nfunction isRelativeUrlWithoutProtocol(url) {\n return constants_1.relativeFirstCharacters.indexOf(url[0]) > -1;\n}\nfunction decodeHtmlCharacters(str) {\n var removedNullByte = str.replace(constants_1.ctrlCharactersRegex, \"\");\n return removedNullByte.replace(constants_1.htmlEntitiesRegex, function (match, dec) {\n return String.fromCharCode(dec);\n });\n}\nfunction isValidUrl(url) {\n return URL.canParse(url);\n}\nfunction decodeURI(uri) {\n try {\n return decodeURIComponent(uri);\n }\n catch (e) {\n // Ignoring error\n // It is possible that the URI contains a `%` not associated\n // with URI/URL-encoding.\n return uri;\n }\n}\nfunction sanitizeUrl(url) {\n if (!url) {\n return constants_1.BLANK_URL;\n }\n var charsToDecode;\n var decodedUrl = decodeURI(url.trim());\n do {\n decodedUrl = decodeHtmlCharacters(decodedUrl)\n .replace(constants_1.htmlCtrlEntityRegex, \"\")\n .replace(constants_1.ctrlCharactersRegex, \"\")\n .replace(constants_1.whitespaceEscapeCharsRegex, \"\")\n .trim();\n decodedUrl = decodeURI(decodedUrl);\n charsToDecode =\n decodedUrl.match(constants_1.ctrlCharactersRegex) ||\n decodedUrl.match(constants_1.htmlEntitiesRegex) ||\n decodedUrl.match(constants_1.htmlCtrlEntityRegex) ||\n decodedUrl.match(constants_1.whitespaceEscapeCharsRegex);\n } while (charsToDecode && charsToDecode.length > 0);\n var sanitizedUrl = decodedUrl;\n if (!sanitizedUrl) {\n return constants_1.BLANK_URL;\n }\n if (isRelativeUrlWithoutProtocol(sanitizedUrl)) {\n return sanitizedUrl;\n }\n // Remove any leading whitespace before checking the URL scheme\n var trimmedUrl = sanitizedUrl.trimStart();\n var urlSchemeParseResults = trimmedUrl.match(constants_1.urlSchemeRegex);\n if (!urlSchemeParseResults) {\n return sanitizedUrl;\n }\n var urlScheme = urlSchemeParseResults[0].toLowerCase().trim();\n if (constants_1.invalidProtocolRegex.test(urlScheme)) {\n return constants_1.BLANK_URL;\n }\n var backSanitized = trimmedUrl.replace(/\\\\/g, \"/\");\n // Handle special cases for mailto: and custom deep-link protocols\n if (urlScheme === \"mailto:\" || urlScheme.includes(\"://\")) {\n return backSanitized;\n }\n // For http and https URLs, perform additional validation\n if (urlScheme === \"http:\" || urlScheme === \"https:\") {\n if (!isValidUrl(backSanitized)) {\n return constants_1.BLANK_URL;\n }\n var url_1 = new URL(backSanitized);\n url_1.protocol = url_1.protocol.toLowerCase();\n url_1.hostname = url_1.hostname.toLowerCase();\n return url_1.toString();\n }\n return backSanitized;\n}\nexports.sanitizeUrl = sanitizeUrl;\n"], + "mappings": "4CAAA,IAAAA,EAAAC,EAAAC,GAAA,cACA,OAAO,eAAeA,EAAS,aAAc,CAAE,MAAO,EAAK,CAAC,EAC5DA,EAAQ,UAAYA,EAAQ,wBAA0BA,EAAQ,2BAA6BA,EAAQ,eAAiBA,EAAQ,oBAAsBA,EAAQ,oBAAsBA,EAAQ,kBAAoBA,EAAQ,qBAAuB,OAC3OA,EAAQ,qBAAuB,wCAC/BA,EAAQ,kBAAoB,mBAC5BA,EAAQ,oBAAsB,oBAC9BA,EAAQ,oBAAsB,qDAC9BA,EAAQ,eAAiB,o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EAGX,IAAIC,EAAaD,EAAa,UAAU,EACpCE,EAAwBD,EAAW,MAAMf,EAAY,cAAc,EACvE,GAAI,CAACgB,EACD,OAAOF,EAEX,IAAIG,EAAYD,EAAsB,CAAC,EAAE,YAAY,EAAE,KAAK,EAC5D,GAAIhB,EAAY,qBAAqB,KAAKiB,CAAS,EAC/C,OAAOjB,EAAY,UAEvB,IAAIkB,EAAgBH,EAAW,QAAQ,MAAO,GAAG,EAEjD,GAAIE,IAAc,WAAaA,EAAU,SAAS,KAAK,EACnD,OAAOC,EAGX,GAAID,IAAc,SAAWA,IAAc,SAAU,CACjD,GAAI,CAACT,EAAWU,CAAa,EACzB,OAAOlB,EAAY,UAEvB,IAAImB,EAAQ,IAAI,IAAID,CAAa,EACjC,OAAAC,EAAM,SAAWA,EAAM,SAAS,YAAY,EAC5CA,EAAM,SAAWA,EAAM,SAAS,YAAY,EACrCA,EAAM,SAAS,CAC1B,CACA,OAAOD,CACX,CACAnB,EAAQ,YAAcY", + "names": ["require_constants", "__commonJSMin", "exports", "require_dist", "__commonJSMin", "exports", "constants_1", "isRelativeUrlWithoutProtocol", "url", "decodeHtmlCharacters", "str", "removedNullByte", "match", "dec", "isValidUrl", "decodeURI", "uri", "sanitizeUrl", "charsToDecode", "decodedUrl", "sanitizedUrl", "trimmedUrl", "urlSchemeParseResults", "urlScheme", "backSanitized", "url_1"] +} diff --git a/docs/website/public/chunk-CQUFH26W.min.js b/docs/website/public/chunk-CQUFH26W.min.js new file mode 100644 index 000000000..6feafe5cd --- /dev/null +++ b/docs/website/public/chunk-CQUFH26W.min.js @@ -0,0 +1,2 @@ +import{a as o,b as d,c as a,d as n,e as m,f as e,g as i,m as u,p as l,q as s}from"./chunk-LBFZT66H.min.js";var v=class extends s{static{e(this,"RadarTokenBuilder")}constructor(){super(["radar-beta"])}},R={parser:{TokenBuilder:e(()=>new v,"TokenBuilder"),ValueConverter:e(()=>new l,"ValueConverter")}};function M(c=n){let r=a(d(c),i),t=a(o({shared:r}),u,R);return r.ServiceRegistry.register(t),{shared:r,Radar:t}}e(M,"createRadarServices");export{R as a,M as b}; +//# sourceMappingURL=chunk-CQUFH26W.min.js.map diff --git a/docs/website/public/chunk-CQUFH26W.min.js.map b/docs/website/public/chunk-CQUFH26W.min.js.map new file mode 100644 index 000000000..67753fdb6 --- /dev/null +++ b/docs/website/public/chunk-CQUFH26W.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/@mermaid-js/parser/dist/chunks/mermaid-parser.core/chunk-WFRQ32O7.mjs"], + "sourcesContent": ["import {\n AbstractMermaidTokenBuilder,\n CommonValueConverter,\n MermaidGeneratedSharedModule,\n RadarGeneratedModule,\n __name\n} from \"./chunk-4KMFLZZN.mjs\";\n\n// src/language/radar/module.ts\nimport {\n EmptyFileSystem,\n createDefaultCoreModule,\n createDefaultSharedCoreModule,\n inject\n} from \"langium\";\n\n// src/language/radar/tokenBuilder.ts\nvar RadarTokenBuilder = class extends AbstractMermaidTokenBuilder {\n static {\n __name(this, \"RadarTokenBuilder\");\n }\n constructor() {\n super([\"radar-beta\"]);\n }\n};\n\n// src/language/radar/module.ts\nvar RadarModule = {\n parser: {\n TokenBuilder: /* @__PURE__ */ __name(() => new RadarTokenBuilder(), \"TokenBuilder\"),\n ValueConverter: /* @__PURE__ */ __name(() => new CommonValueConverter(), \"ValueConverter\")\n }\n};\nfunction createRadarServices(context = EmptyFileSystem) {\n const shared = inject(\n createDefaultSharedCoreModule(context),\n MermaidGeneratedSharedModule\n );\n const Radar = inject(\n createDefaultCoreModule({ shared }),\n RadarGeneratedModule,\n RadarModule\n );\n shared.ServiceRegistry.register(Radar);\n return { shared, Radar };\n}\n__name(createRadarServices, \"createRadarServices\");\n\nexport {\n RadarModule,\n createRadarServices\n};\n"], + "mappings": "2GAiBA,IAAIA,EAAoB,cAAcC,CAA4B,CAChE,MAAO,CACLC,EAAO,KAAM,mBAAmB,CAClC,CACA,aAAc,CACZ,MAAM,CAAC,YAAY,CAAC,CACtB,CACF,EAGIC,EAAc,CAChB,OAAQ,CACN,aAA8BD,EAAO,IAAM,IAAIF,EAAqB,cAAc,EAClF,eAAgCE,EAAO,IAAM,IAAIE,EAAwB,gBAAgB,CAC3F,CACF,EACA,SAASC,EAAoBC,EAAUC,EAAiB,CACtD,IAAMC,EAASC,EACbC,EAA8BJ,CAAO,EACrCK,CACF,EACMC,EAAQH,EACZI,EAAwB,CAAE,OAAAL,CAAO,CAAC,EAClCM,EACAX,CACF,EACA,OAAAK,EAAO,gBAAgB,SAASI,CAAK,EAC9B,CAAE,OAAAJ,EAAQ,MAAAI,CAAM,CACzB,CACAV,EAAOG,EAAqB,qBAAqB", + "names": ["RadarTokenBuilder", "AbstractMermaidTokenBuilder", "__name", "RadarModule", "CommonValueConverter", "createRadarServices", "context", "EmptyFileSystem", "shared", "inject", "createDefaultSharedCoreModule", "MermaidGeneratedSharedModule", "Radar", "createDefaultCoreModule", "RadarGeneratedModule"] +} diff --git a/docs/website/public/chunk-E5F23VE2.min.js b/docs/website/public/chunk-E5F23VE2.min.js new file mode 100644 index 000000000..064c5d3c5 --- /dev/null +++ b/docs/website/public/chunk-E5F23VE2.min.js @@ -0,0 +1,2 @@ +var Pr=typeof global=="object"&&global&&global.Object===Object&&global,U=Pr;var Sr=typeof self=="object"&&self&&self.Object===Object&&self,Ir=U||Sr||Function("return this")(),c=Ir;var Mr=c.Symbol,_=Mr;var nt=Object.prototype,Er=nt.hasOwnProperty,Fr=nt.toString,E=_?_.toStringTag:void 0;function Lr(t){var r=Er.call(t,E),e=t[E];try{t[E]=void 0;var o=!0}catch{}var a=Fr.call(t);return o&&(r?t[E]=e:delete t[E]),a}var it=Lr;var Dr=Object.prototype,Gr=Dr.toString;function Nr(t){return Gr.call(t)}var ft=Nr;var zr="[object Null]",Ur="[object Undefined]",pt=_?_.toStringTag:void 0;function Rr(t){return t==null?t===void 0?Ur:zr:pt&&pt in Object(t)?it(t):ft(t)}var g=Rr;function Hr(t){var r=typeof t;return t!=null&&(r=="object"||r=="function")}var s=Hr;var Br="[object AsyncFunction]",Vr="[object Function]",Kr="[object GeneratorFunction]",qr="[object Proxy]";function $r(t){if(!s(t))return!1;var r=g(t);return r==Vr||r==Kr||r==Br||r==qr}var O=$r;var Xr=c["__core-js_shared__"],R=Xr;var ut=(function(){var t=/[^.]+$/.exec(R&&R.keys&&R.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})();function Jr(t){return!!ut&&ut in t}var st=Jr;var Wr=Function.prototype,Yr=Wr.toString;function Zr(t){if(t!=null){try{return Yr.call(t)}catch{}try{return t+""}catch{}}return""}var mt=Zr;var Qr=/[\\^$.*+?()[\]{}|]/g,kr=/^\[object .+?Constructor\]$/,te=Function.prototype,re=Object.prototype,ee=te.toString,oe=re.hasOwnProperty,ae=RegExp("^"+ee.call(oe).replace(Qr,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ne(t){if(!s(t)||st(t))return!1;var r=O(t)?ae:kr;return r.test(mt(t))}var lt=ne;function ie(t,r){return t?.[r]}var ct=ie;function fe(t,r){var e=ct(t,r);return lt(e)?e:void 0}var T=fe;var pe=T(Object,"create"),h=pe;function ue(){this.__data__=h?h(null):{},this.size=0}var dt=ue;function se(t){var r=this.has(t)&&delete this.__data__[t];return this.size-=r?1:0,r}var ht=se;var me="__lodash_hash_undefined__",le=Object.prototype,ce=le.hasOwnProperty;function de(t){var r=this.__data__;if(h){var e=r[t];return e===me?void 0:e}return ce.call(r,t)?r[t]:void 0}var gt=de;var he=Object.prototype,ge=he.hasOwnProperty;function ye(t){var r=this.__data__;return h?r[t]!==void 0:ge.call(r,t)}var yt=ye;var be="__lodash_hash_undefined__";function xe(t,r){var e=this.__data__;return this.size+=this.has(t)?0:1,e[t]=h&&r===void 0?be:r,this}var bt=xe;function j(t){var r=-1,e=t==null?0:t.length;for(this.clear();++r-1}var Ot=we;function Pe(t,r){var e=this.__data__,o=b(e,t);return o<0?(++this.size,e.push([t,r])):e[o][1]=r,this}var Tt=Pe;function A(t){var r=-1,e=t==null?0:t.length;for(this.clear();++r-1&&t%1==0&&t<=Xe}var V=Je;function We(t){return t!=null&&V(t.length)&&!O(t)}var w=We;function Ye(){return!1}var Mt=Ye;var Lt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Et=Lt&&typeof module=="object"&&module&&!module.nodeType&&module,Ze=Et&&Et.exports===Lt,Ft=Ze?c.Buffer:void 0,Qe=Ft?Ft.isBuffer:void 0,ke=Qe||Mt,K=ke;var to="[object Arguments]",ro="[object Array]",eo="[object Boolean]",oo="[object Date]",ao="[object Error]",no="[object Function]",io="[object Map]",fo="[object Number]",po="[object Object]",uo="[object RegExp]",so="[object Set]",mo="[object String]",lo="[object WeakMap]",co="[object ArrayBuffer]",ho="[object DataView]",go="[object Float32Array]",yo="[object Float64Array]",bo="[object Int8Array]",xo="[object Int16Array]",vo="[object Int32Array]",_o="[object Uint8Array]",Oo="[object Uint8ClampedArray]",To="[object Uint16Array]",jo="[object Uint32Array]",p={};p[go]=p[yo]=p[bo]=p[xo]=p[vo]=p[_o]=p[Oo]=p[To]=p[jo]=!0;p[to]=p[ro]=p[co]=p[eo]=p[ho]=p[oo]=p[ao]=p[no]=p[io]=p[fo]=p[po]=p[uo]=p[so]=p[mo]=p[lo]=!1;function Ao(t){return d(t)&&V(t.length)&&!!p[g(t)]}var Dt=Ao;function Co(t){return function(r){return t(r)}}var Gt=Co;var Nt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,G=Nt&&typeof module=="object"&&module&&!module.nodeType&&module,wo=G&&G.exports===Nt,rt=wo&&U.process,Po=(function(){try{var t=G&&G.require&&G.require("util").types;return t||rt&&rt.binding&&rt.binding("util")}catch{}})(),et=Po;var zt=et&&et.isTypedArray,So=zt?Gt(zt):Dt,q=So;function Io(t){return function(){return t}}var Ut=Io;function Mo(){this.__data__=new x,this.size=0}var Rt=Mo;function Eo(t){var r=this.__data__,e=r.delete(t);return this.size=r.size,e}var Ht=Eo;function Fo(t){return this.__data__.get(t)}var Bt=Fo;function Lo(t){return this.__data__.has(t)}var Vt=Lo;var Do=200;function Go(t,r){var e=this.__data__;if(e instanceof x){var o=e.__data__;if(!H||o.length-1&&t%1==0&&t0){if(++r>=Pa)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}var Tr=Ma;var Ea=Tr(Or),jr=Ea;function Fa(t,r){return jr(_r(t,r,W),t+"")}var Ar=Fa;function La(t,r,e){if(!s(e))return!1;var o=typeof r;return(o=="number"?w(e)&&X(r,e.length):o=="string"&&r in e)?y(e[r],t):!1}var Cr=La;function Da(t){return Ar(function(r,e){var o=-1,a=e.length,i=a>1?e[a-1]:void 0,f=a>2?e[2]:void 0;for(i=t.length>3&&typeof i=="function"?(a--,i):void 0,f&&Cr(e[0],e[1],f)&&(i=a<3?void 0:i,a=1),r=Object(r);++o true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObject from './isObject.js';\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\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 */\nfunction 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\nexport default isFunction;\n", "import root from './_root.js';\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nexport default coreJsData;\n", "import coreJsData from './_coreJsData.js';\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\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 */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nexport default isMasked;\n", "/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\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 */\nfunction 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\nexport default toSource;\n", "import isFunction from './isFunction.js';\nimport isMasked from './_isMasked.js';\nimport isObject from './isObject.js';\nimport toSource from './_toSource.js';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\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 */\nfunction 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\nexport default baseIsNative;\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 */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n", "import baseIsNative from './_baseIsNative.js';\nimport getValue from './_getValue.js';\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 */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nexport default getNative;\n", "import getNative from './_getNative.js';\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nexport default nativeCreate;\n", "import nativeCreate from './_nativeCreate.js';\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nexport default hashClear;\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 */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\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 */\nfunction 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\nexport default hashGet;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\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 */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nexport default hashHas;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\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 */\nfunction 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\nexport default hashSet;\n", "import hashClear from './_hashClear.js';\nimport hashDelete from './_hashDelete.js';\nimport hashGet from './_hashGet.js';\nimport hashHas from './_hashHas.js';\nimport hashSet from './_hashSet.js';\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction 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// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nexport default Hash;\n", "/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\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 */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n", "import eq from './eq.js';\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 */\nfunction 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\nexport default assocIndexOf;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\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 */\nfunction 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\nexport default listCacheDelete;\n", "import assocIndexOf from './_assocIndexOf.js';\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 */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nexport default listCacheGet;\n", "import assocIndexOf from './_assocIndexOf.js';\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 */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nexport default listCacheHas;\n", "import assocIndexOf from './_assocIndexOf.js';\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 */\nfunction 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\nexport default listCacheSet;\n", "import listCacheClear from './_listCacheClear.js';\nimport listCacheDelete from './_listCacheDelete.js';\nimport listCacheGet from './_listCacheGet.js';\nimport listCacheHas from './_listCacheHas.js';\nimport listCacheSet from './_listCacheSet.js';\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction 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// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nexport default ListCache;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nexport default Map;\n", "import Hash from './_Hash.js';\nimport ListCache from './_ListCache.js';\nimport Map from './_Map.js';\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nexport default mapCacheClear;\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 */\nfunction 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\nexport default isKeyable;\n", "import isKeyable from './_isKeyable.js';\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 */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nexport default getMapData;\n", "import getMapData from './_getMapData.js';\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 */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default mapCacheDelete;\n", "import getMapData from './_getMapData.js';\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 */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nexport default mapCacheGet;\n", "import getMapData from './_getMapData.js';\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 */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nexport default mapCacheHas;\n", "import getMapData from './_getMapData.js';\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 */\nfunction 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\nexport default mapCacheSet;\n", "import mapCacheClear from './_mapCacheClear.js';\nimport mapCacheDelete from './_mapCacheDelete.js';\nimport mapCacheGet from './_mapCacheGet.js';\nimport mapCacheHas from './_mapCacheHas.js';\nimport mapCacheSet from './_mapCacheSet.js';\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 */\nfunction 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// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nexport default MapCache;\n", "import MapCache from './_MapCache.js';\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\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 */\nfunction 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`.\nmemoize.Cache = MapCache;\n\nexport default memoize;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\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 */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\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 */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\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 */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nexport default baseIsArguments;\n", "import baseIsArguments from './_baseIsArguments.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\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 */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nexport default isArguments;\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 */\nvar isArray = Array.isArray;\n\nexport default isArray;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\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 */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n", "import isFunction from './isFunction.js';\nimport isLength from './isLength.js';\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 */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nexport default isArrayLike;\n", "/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n", "import root from './_root.js';\nimport stubFalse from './stubFalse.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\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 */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nexport default isBuffer;\n", "import baseGetTag from './_baseGetTag.js';\nimport isLength from './isLength.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar 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 identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\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 */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nexport default baseIsTypedArray;\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 */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n", "import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar 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\nexport default nodeUtil;\n", "import baseIsTypedArray from './_baseIsTypedArray.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\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 */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nexport default isTypedArray;\n", "/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n", "import ListCache from './_ListCache.js';\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nexport default stackClear;\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 */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\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 */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\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 */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n", "import ListCache from './_ListCache.js';\nimport Map from './_Map.js';\nimport MapCache from './_MapCache.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\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 */\nfunction 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\nexport default stackSet;\n", "import ListCache from './_ListCache.js';\nimport stackClear from './_stackClear.js';\nimport stackDelete from './_stackDelete.js';\nimport stackGet from './_stackGet.js';\nimport stackHas from './_stackHas.js';\nimport stackSet from './_stackSet.js';\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 */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nexport default Stack;\n", "import getNative from './_getNative.js';\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nexport default defineProperty;\n", "import defineProperty from './_defineProperty.js';\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 */\nfunction 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\nexport default baseAssignValue;\n", "import baseAssignValue from './_baseAssignValue.js';\nimport eq from './eq.js';\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 */\nfunction 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\nexport default assignMergeValue;\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 */\nfunction 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\nexport default createBaseFor;\n", "import createBaseFor from './_createBaseFor.js';\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 */\nvar baseFor = createBaseFor();\n\nexport default baseFor;\n", "import root from './_root.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;\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 */\nfunction 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\nexport default cloneBuffer;\n", "import root from './_root.js';\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nexport default Uint8Array;\n", "import Uint8Array from './_Uint8Array.js';\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 */\nfunction cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n}\n\nexport default cloneArrayBuffer;\n", "import cloneArrayBuffer from './_cloneArrayBuffer.js';\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 */\nfunction cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\nexport default cloneTypedArray;\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 */\nfunction 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\nexport default copyArray;\n", "import isObject from './isObject.js';\n\n/** Built-in value references. */\nvar objectCreate = Object.create;\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 */\nvar 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\nexport default baseCreate;\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 */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n", "import overArg from './_overArg.js';\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nexport default getPrototype;\n", "import baseCreate from './_baseCreate.js';\nimport getPrototype from './_getPrototype.js';\nimport isPrototype from './_isPrototype.js';\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 */\nfunction initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n}\n\nexport default initCloneObject;\n", "import isArrayLike from './isArrayLike.js';\nimport isObjectLike from './isObjectLike.js';\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 */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\nexport default isArrayLikeObject;\n", "import baseGetTag from './_baseGetTag.js';\nimport getPrototype from './_getPrototype.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to infer the `Object` constructor. */\nvar objectCtorString = funcToString.call(Object);\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 */\nfunction 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\nexport default isPlainObject;\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 */\nfunction 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\nexport default safeGet;\n", "import baseAssignValue from './_baseAssignValue.js';\nimport eq from './eq.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\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 */\nfunction 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\nexport default assignValue;\n", "import assignValue from './_assignValue.js';\nimport baseAssignValue from './_baseAssignValue.js';\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 */\nfunction 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\nexport default copyObject;\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 */\nfunction 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\nexport default baseTimes;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\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 */\nfunction 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\nexport default isIndex;\n", "import baseTimes from './_baseTimes.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isIndex from './_isIndex.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\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 */\nfunction 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\nexport default arrayLikeKeys;\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 */\nfunction 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\nexport default nativeKeysIn;\n", "import isObject from './isObject.js';\nimport isPrototype from './_isPrototype.js';\nimport nativeKeysIn from './_nativeKeysIn.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\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 */\nfunction 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\nexport default baseKeysIn;\n", "import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeysIn from './_baseKeysIn.js';\nimport isArrayLike from './isArrayLike.js';\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 */\nfunction keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nexport default keysIn;\n", "import copyObject from './_copyObject.js';\nimport keysIn from './keysIn.js';\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 */\nfunction toPlainObject(value) {\n return copyObject(value, keysIn(value));\n}\n\nexport default toPlainObject;\n", "import assignMergeValue from './_assignMergeValue.js';\nimport cloneBuffer from './_cloneBuffer.js';\nimport cloneTypedArray from './_cloneTypedArray.js';\nimport copyArray from './_copyArray.js';\nimport initCloneObject from './_initCloneObject.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isArrayLikeObject from './isArrayLikeObject.js';\nimport isBuffer from './isBuffer.js';\nimport isFunction from './isFunction.js';\nimport isObject from './isObject.js';\nimport isPlainObject from './isPlainObject.js';\nimport isTypedArray from './isTypedArray.js';\nimport safeGet from './_safeGet.js';\nimport toPlainObject from './toPlainObject.js';\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 */\nfunction 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\nexport default baseMergeDeep;\n", "import Stack from './_Stack.js';\nimport assignMergeValue from './_assignMergeValue.js';\nimport baseFor from './_baseFor.js';\nimport baseMergeDeep from './_baseMergeDeep.js';\nimport isObject from './isObject.js';\nimport keysIn from './keysIn.js';\nimport safeGet from './_safeGet.js';\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 */\nfunction 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\nexport default baseMerge;\n", "/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\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 */\nfunction 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\nexport default apply;\n", "import apply from './_apply.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\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 */\nfunction 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\nexport default overRest;\n", "import constant from './constant.js';\nimport defineProperty from './_defineProperty.js';\nimport identity from './identity.js';\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 */\nvar 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\nexport default baseSetToString;\n", "/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\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 */\nfunction 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\nexport default shortOut;\n", "import baseSetToString from './_baseSetToString.js';\nimport shortOut from './_shortOut.js';\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 */\nvar setToString = shortOut(baseSetToString);\n\nexport default setToString;\n", "import identity from './identity.js';\nimport overRest from './_overRest.js';\nimport setToString from './_setToString.js';\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 */\nfunction baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n}\n\nexport default baseRest;\n", "import eq from './eq.js';\nimport isArrayLike from './isArrayLike.js';\nimport isIndex from './_isIndex.js';\nimport isObject from './isObject.js';\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 */\nfunction 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\nexport default isIterateeCall;\n", "import baseRest from './_baseRest.js';\nimport isIterateeCall from './_isIterateeCall.js';\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 */\nfunction 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\nexport default createAssigner;\n", "import baseMerge from './_baseMerge.js';\nimport createAssigner from './_createAssigner.js';\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 */\nvar merge = createAssigner(function(object, source, srcIndex) {\n baseMerge(object, source, srcIndex);\n});\n\nexport default merge;\n"], + "mappings": "AACA,IAAIA,GAAa,OAAO,QAAU,UAAY,QAAU,OAAO,SAAW,QAAU,OAE7EC,EAAQD,GCAf,IAAIE,GAAW,OAAO,MAAQ,UAAY,MAAQ,KAAK,SAAW,QAAU,KAGxEC,GAAOC,GAAcF,IAAY,SAAS,aAAa,EAAE,EAEtDG,EAAQF,GCLf,IAAIG,GAASC,EAAK,OAEXC,EAAQF,GCFf,IAAIG,GAAc,OAAO,UAGrBC,GAAiBD,GAAY,eAO7BE,GAAuBF,GAAY,SAGnCG,EAAiBC,EAASA,EAAO,YAAc,OASnD,SAASC,GAAUC,EAAO,CACxB,IAAIC,EAAQN,GAAe,KAAKK,EAAOH,CAAc,EACjDK,EAAMF,EAAMH,CAAc,EAE9B,GAAI,CACFG,EAAMH,CAAc,EAAI,OACxB,IAAIM,EAAW,EACjB,MAAY,CAAC,CAEb,IAAIC,EAASR,GAAqB,KAAKI,CAAK,EAC5C,OAAIG,IACEF,EACFD,EAAMH,CAAc,EAAIK,EAExB,OAAOF,EAAMH,CAAc,GAGxBO,CACT,CAEA,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C,EAAU,CAChC,OAAOC,GAAS,SAASC,EAAQC,EAAS,CACxC,IAAIC,EAAQ,GACRC,EAASF,EAAQ,OACjBG,EAAaD,EAAS,EAAIF,EAAQE,EAAS,CAAC,EAAI,OAChDE,EAAQF,EAAS,EAAIF,EAAQ,CAAC,EAAI,OAWtC,IATAG,EAAcN,EAAS,OAAS,GAAK,OAAOM,GAAc,YACrDD,IAAUC,GACX,OAEAC,GAASC,GAAeL,EAAQ,CAAC,EAAGA,EAAQ,CAAC,EAAGI,CAAK,IACvDD,EAAaD,EAAS,EAAI,OAAYC,EACtCD,EAAS,GAEXH,EAAS,OAAOA,CAAM,EACf,EAAEE,EAAQC,GAAQ,CACvB,IAAII,EAASN,EAAQC,CAAK,EACtBK,GACFT,EAASE,EAAQO,EAAQL,EAAOE,CAAU,CAE9C,CACA,OAAOJ,CACT,CAAC,CACH,CAEA,IAAOQ,GAAQX,GCFf,IAAIY,GAAQC,GAAe,SAASC,EAAQC,EAAQC,EAAU,CAC5DC,GAAUH,EAAQC,EAAQC,CAAQ,CACpC,CAAC,EAEME,GAAQN", + "names": ["freeGlobal", "freeGlobal_default", "freeSelf", "root", "freeGlobal_default", "root_default", "Symbol", "root_default", "Symbol_default", "objectProto", "hasOwnProperty", "nativeObjectToString", "symToStringTag", "Symbol_default", "getRawTag", "value", "isOwn", "tag", "unmasked", "result", "getRawTag_default", "objectProto", "nativeObjectToString", "objectToString", "value", "objectToString_default", "nullTag", "undefinedTag", "symToStringTag", "Symbol_default", "baseGetTag", "value", "getRawTag_default", "objectToString_default", "baseGetTag_default", "isObject", "value", "type", "isObject_default", "asyncTag", "funcTag", "genTag", "proxyTag", "isFunction", "value", "isObject_default", "tag", "baseGetTag_default", "isFunction_default", "coreJsData", "root_default", "coreJsData_default", "maskSrcKey", "uid", "coreJsData_default", "isMasked", "func", "isMasked_default", "funcProto", "funcToString", "toSource", "func", "toSource_default", "reRegExpChar", "reIsHostCtor", "funcProto", "objectProto", "funcToString", "hasOwnProperty", "reIsNative", "baseIsNative", "value", "isObject_default", "isMasked_default", "pattern", "isFunction_default", "toSource_default", "baseIsNative_default", "getValue", "object", "key", "getValue_default", "getNative", "object", "key", "value", "getValue_default", "baseIsNative_default", "getNative_default", "nativeCreate", "getNative_default", "nativeCreate_default", "hashClear", "nativeCreate_default", "hashClear_default", "hashDelete", "key", "result", "hashDelete_default", "HASH_UNDEFINED", "objectProto", "hasOwnProperty", "hashGet", "key", "data", "nativeCreate_default", "result", "hashGet_default", "objectProto", "hasOwnProperty", "hashHas", "key", "data", "nativeCreate_default", "hashHas_default", "HASH_UNDEFINED", "hashSet", "key", "value", "data", "nativeCreate_default", "hashSet_default", "Hash", "entries", "index", "length", "entry", "hashClear_default", "hashDelete_default", "hashGet_default", "hashHas_default", "hashSet_default", "Hash_default", "listCacheClear", "listCacheClear_default", "eq", "value", "other", "eq_default", "assocIndexOf", "array", "key", "length", "eq_default", "assocIndexOf_default", "arrayProto", "splice", "listCacheDelete", "key", "data", "index", "assocIndexOf_default", "lastIndex", "listCacheDelete_default", "listCacheGet", "key", "data", "index", "assocIndexOf_default", "listCacheGet_default", "listCacheHas", "key", "assocIndexOf_default", "listCacheHas_default", "listCacheSet", "key", "value", "data", "index", "assocIndexOf_default", "listCacheSet_default", "ListCache", "entries", "index", "length", "entry", "listCacheClear_default", "listCacheDelete_default", "listCacheGet_default", "listCacheHas_default", "listCacheSet_default", "ListCache_default", "Map", "getNative_default", "root_default", "Map_default", "mapCacheClear", "Hash_default", "Map_default", "ListCache_default", "mapCacheClear_default", "isKeyable", "value", "type", "isKeyable_default", "getMapData", "map", "key", "data", "isKeyable_default", "getMapData_default", "mapCacheDelete", "key", "result", "getMapData_default", "mapCacheDelete_default", "mapCacheGet", "key", "getMapData_default", "mapCacheGet_default", "mapCacheHas", "key", "getMapData_default", "mapCacheHas_default", "mapCacheSet", "key", "value", "data", "getMapData_default", "size", "mapCacheSet_default", "MapCache", "entries", "index", "length", "entry", "mapCacheClear_default", "mapCacheDelete_default", "mapCacheGet_default", "mapCacheHas_default", "mapCacheSet_default", "MapCache_default", "FUNC_ERROR_TEXT", "memoize", "func", "resolver", "memoized", "args", "key", "cache", "result", "MapCache_default", "memoize_default", "objectProto", "isPrototype", "value", "Ctor", "proto", "isPrototype_default", "isObjectLike", "value", "isObjectLike_default", "argsTag", "baseIsArguments", "value", "isObjectLike_default", "baseGetTag_default", "baseIsArguments_default", "objectProto", "hasOwnProperty", "propertyIsEnumerable", "isArguments", "baseIsArguments_default", "value", "isObjectLike_default", "isArguments_default", "isArray", "isArray_default", "MAX_SAFE_INTEGER", "isLength", "value", "isLength_default", "isArrayLike", "value", "isLength_default", "isFunction_default", "isArrayLike_default", "stubFalse", "stubFalse_default", "freeExports", "freeModule", "moduleExports", "Buffer", "root_default", "nativeIsBuffer", "isBuffer", "stubFalse_default", "isBuffer_default", "argsTag", "arrayTag", "boolTag", "dateTag", "errorTag", "funcTag", "mapTag", "numberTag", "objectTag", "regexpTag", "setTag", "stringTag", "weakMapTag", "arrayBufferTag", "dataViewTag", "float32Tag", "float64Tag", "int8Tag", "int16Tag", "int32Tag", "uint8Tag", "uint8ClampedTag", "uint16Tag", "uint32Tag", "typedArrayTags", "baseIsTypedArray", "value", "isObjectLike_default", "isLength_default", "baseGetTag_default", "baseIsTypedArray_default", "baseUnary", "func", "value", "baseUnary_default", "freeExports", "freeModule", "moduleExports", "freeProcess", "freeGlobal_default", "nodeUtil", "types", "nodeUtil_default", "nodeIsTypedArray", "nodeUtil_default", "isTypedArray", "baseUnary_default", "baseIsTypedArray_default", "isTypedArray_default", "constant", "value", "constant_default", "stackClear", "ListCache_default", "stackClear_default", "stackDelete", "key", "data", "result", "stackDelete_default", "stackGet", "key", "stackGet_default", "stackHas", "key", "stackHas_default", "LARGE_ARRAY_SIZE", "stackSet", "key", "value", "data", "ListCache_default", "pairs", "Map_default", "MapCache_default", "stackSet_default", "Stack", "entries", "data", "ListCache_default", "stackClear_default", "stackDelete_default", "stackGet_default", "stackHas_default", "stackSet_default", "Stack_default", "defineProperty", "func", "getNative_default", "defineProperty_default", "baseAssignValue", "object", "key", "value", "defineProperty_default", "baseAssignValue_default", "assignMergeValue", "object", "key", "value", "eq_default", "baseAssignValue_default", "assignMergeValue_default", "createBaseFor", "fromRight", "object", "iteratee", "keysFunc", "index", "iterable", "props", "length", "key", "createBaseFor_default", "baseFor", "createBaseFor_default", "baseFor_default", "freeExports", "freeModule", "moduleExports", "Buffer", "root_default", "allocUnsafe", "cloneBuffer", "buffer", "isDeep", "length", "result", "cloneBuffer_default", "Uint8Array", "root_default", "Uint8Array_default", "cloneArrayBuffer", "arrayBuffer", "result", "Uint8Array_default", "cloneArrayBuffer_default", "cloneTypedArray", "typedArray", "isDeep", "buffer", "cloneArrayBuffer_default", "cloneTypedArray_default", "copyArray", "source", "array", "index", "length", "copyArray_default", "objectCreate", "baseCreate", "object", "proto", "isObject_default", "result", "baseCreate_default", "overArg", "func", "transform", "arg", "overArg_default", "getPrototype", "overArg_default", "getPrototype_default", "initCloneObject", "object", "isPrototype_default", "baseCreate_default", "getPrototype_default", "initCloneObject_default", "isArrayLikeObject", "value", "isObjectLike_default", "isArrayLike_default", "isArrayLikeObject_default", "objectTag", "funcProto", "objectProto", "funcToString", "hasOwnProperty", "objectCtorString", "isPlainObject", "value", "isObjectLike_default", "baseGetTag_default", "proto", "getPrototype_default", "Ctor", "isPlainObject_default", "safeGet", "object", "key", "safeGet_default", "objectProto", "hasOwnProperty", "assignValue", "object", "key", "value", "objValue", "eq_default", "baseAssignValue_default", "assignValue_default", "copyObject", "source", "props", "object", "customizer", "isNew", "index", "length", "key", "newValue", "baseAssignValue_default", "assignValue_default", "copyObject_default", "baseTimes", "n", "iteratee", "index", "result", "baseTimes_default", "MAX_SAFE_INTEGER", "reIsUint", "isIndex", "value", "length", "type", "isIndex_default", "objectProto", "hasOwnProperty", "arrayLikeKeys", "value", "inherited", "isArr", "isArray_default", "isArg", "isArguments_default", "isBuff", "isBuffer_default", "isType", "isTypedArray_default", "skipIndexes", "result", "baseTimes_default", "length", "key", "isIndex_default", "arrayLikeKeys_default", "nativeKeysIn", "object", "result", "key", "nativeKeysIn_default", "objectProto", "hasOwnProperty", "baseKeysIn", "object", "isObject_default", "nativeKeysIn_default", "isProto", "isPrototype_default", "result", "key", "baseKeysIn_default", "keysIn", "object", "isArrayLike_default", "arrayLikeKeys_default", "baseKeysIn_default", "keysIn_default", "toPlainObject", "value", "copyObject_default", "keysIn_default", "toPlainObject_default", "baseMergeDeep", "object", "source", "key", "srcIndex", "mergeFunc", "customizer", "stack", "objValue", "safeGet_default", "srcValue", "stacked", "assignMergeValue_default", "newValue", "isCommon", "isArr", "isArray_default", "isBuff", "isBuffer_default", "isTyped", "isTypedArray_default", "isArrayLikeObject_default", "copyArray_default", "cloneBuffer_default", "cloneTypedArray_default", "isPlainObject_default", "isArguments_default", "toPlainObject_default", "isObject_default", "isFunction_default", "initCloneObject_default", "baseMergeDeep_default", "baseMerge", "object", "source", "srcIndex", "customizer", "stack", "baseFor_default", "srcValue", "key", "Stack_default", "isObject_default", "baseMergeDeep_default", "newValue", "safeGet_default", "assignMergeValue_default", "keysIn_default", "baseMerge_default", "identity", "value", "identity_default", "apply", "func", "thisArg", "args", "apply_default", "nativeMax", "overRest", "func", "start", "transform", "args", "index", "length", "array", "otherArgs", "apply_default", "overRest_default", "baseSetToString", "defineProperty_default", "func", "string", "constant_default", "identity_default", "baseSetToString_default", "HOT_COUNT", "HOT_SPAN", "nativeNow", "shortOut", "func", "count", "lastCalled", "stamp", "remaining", "shortOut_default", "setToString", "shortOut_default", "baseSetToString_default", "setToString_default", "baseRest", "func", "start", "setToString_default", "overRest_default", "identity_default", "baseRest_default", "isIterateeCall", "value", "index", "object", "isObject_default", "type", "isArrayLike_default", "isIndex_default", "eq_default", "isIterateeCall_default", "createAssigner", "assigner", "baseRest_default", "object", "sources", "index", "length", "customizer", "guard", "isIterateeCall_default", "source", "createAssigner_default", "merge", "createAssigner_default", "object", "source", "srcIndex", "baseMerge_default", "merge_default"] +} diff --git a/docs/website/public/chunk-EU44H33B.min.js b/docs/website/public/chunk-EU44H33B.min.js new file mode 100644 index 000000000..fd352cd6f --- /dev/null +++ b/docs/website/public/chunk-EU44H33B.min.js @@ -0,0 +1,2 @@ +import{a as i,b as o,c as t,d as n,e as c,f as e,g as u,l as d,p as l,q as s}from"./chunk-LBFZT66H.min.js";var p=class extends s{static{e(this,"GitGraphTokenBuilder")}constructor(){super(["gitGraph"])}},h={parser:{TokenBuilder:e(()=>new p,"TokenBuilder"),ValueConverter:e(()=>new l,"ValueConverter")}};function m(G=n){let r=t(o(G),u),a=t(i({shared:r}),d,h);return r.ServiceRegistry.register(a),{shared:r,GitGraph:a}}e(m,"createGitGraphServices");export{h as a,m as b}; +//# sourceMappingURL=chunk-EU44H33B.min.js.map diff --git a/docs/website/public/chunk-EU44H33B.min.js.map b/docs/website/public/chunk-EU44H33B.min.js.map new file mode 100644 index 000000000..0d9e098ff --- /dev/null +++ b/docs/website/public/chunk-EU44H33B.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/@mermaid-js/parser/dist/chunks/mermaid-parser.core/chunk-BN7GFLIU.mjs"], + "sourcesContent": ["import {\n AbstractMermaidTokenBuilder,\n CommonValueConverter,\n GitGraphGeneratedModule,\n MermaidGeneratedSharedModule,\n __name\n} from \"./chunk-4KMFLZZN.mjs\";\n\n// src/language/gitGraph/module.ts\nimport {\n inject,\n createDefaultCoreModule,\n createDefaultSharedCoreModule,\n EmptyFileSystem\n} from \"langium\";\n\n// src/language/gitGraph/tokenBuilder.ts\nvar GitGraphTokenBuilder = class extends AbstractMermaidTokenBuilder {\n static {\n __name(this, \"GitGraphTokenBuilder\");\n }\n constructor() {\n super([\"gitGraph\"]);\n }\n};\n\n// src/language/gitGraph/module.ts\nvar GitGraphModule = {\n parser: {\n TokenBuilder: /* @__PURE__ */ __name(() => new GitGraphTokenBuilder(), \"TokenBuilder\"),\n ValueConverter: /* @__PURE__ */ __name(() => new CommonValueConverter(), \"ValueConverter\")\n }\n};\nfunction createGitGraphServices(context = EmptyFileSystem) {\n const shared = inject(\n createDefaultSharedCoreModule(context),\n MermaidGeneratedSharedModule\n );\n const GitGraph = inject(\n createDefaultCoreModule({ shared }),\n GitGraphGeneratedModule,\n GitGraphModule\n );\n shared.ServiceRegistry.register(GitGraph);\n return { shared, GitGraph };\n}\n__name(createGitGraphServices, \"createGitGraphServices\");\n\nexport {\n GitGraphModule,\n createGitGraphServices\n};\n"], + "mappings": "2GAiBA,IAAIA,EAAuB,cAAcC,CAA4B,CACnE,MAAO,CACLC,EAAO,KAAM,sBAAsB,CACrC,CACA,aAAc,CACZ,MAAM,CAAC,UAAU,CAAC,CACpB,CACF,EAGIC,EAAiB,CACnB,OAAQ,CACN,aAA8BD,EAAO,IAAM,IAAIF,EAAwB,cAAc,EACrF,eAAgCE,EAAO,IAAM,IAAIE,EAAwB,gBAAgB,CAC3F,CACF,EACA,SAASC,EAAuBC,EAAUC,EAAiB,CACzD,IAAMC,EAASC,EACbC,EAA8BJ,CAAO,EACrCK,CACF,EACMC,EAAWH,EACfI,EAAwB,CAAE,OAAAL,CAAO,CAAC,EAClCM,EACAX,CACF,EACA,OAAAK,EAAO,gBAAgB,SAASI,CAAQ,EACjC,CAAE,OAAAJ,EAAQ,SAAAI,CAAS,CAC5B,CACAV,EAAOG,EAAwB,wBAAwB", + "names": ["GitGraphTokenBuilder", "AbstractMermaidTokenBuilder", "__name", "GitGraphModule", "CommonValueConverter", "createGitGraphServices", "context", "EmptyFileSystem", "shared", "inject", "createDefaultSharedCoreModule", "MermaidGeneratedSharedModule", "GitGraph", "createDefaultCoreModule", "GitGraphGeneratedModule"] +} diff --git a/docs/website/public/chunk-FNCPGT3X.min.js b/docs/website/public/chunk-FNCPGT3X.min.js new file mode 100644 index 000000000..7731632c1 --- /dev/null +++ b/docs/website/public/chunk-FNCPGT3X.min.js @@ -0,0 +1,221 @@ +import{a as Vt}from"./chunk-WNTLZBBZ.min.js";import{a as Mt}from"./chunk-ORLGEIQN.min.js";import{b as Bt}from"./chunk-VTDY5BYI.min.js";import{e as Yt,m as Gt}from"./chunk-QZZKR5JD.min.js";import{K as G,P as Ot,Q as Rt,R as Nt,S as wt,T as $t,U as Pt,V as Ft,W as w}from"./chunk-3EE2TK35.min.js";import{b as d,d as b}from"./chunk-6TVUEPFY.min.js";var vt=(function(){var t=d(function(Y,a,c,r){for(c=c||{},r=Y.length;r--;c[Y[r]]=a);return c},"o"),e=[1,2],o=[1,3],s=[1,4],h=[2,4],u=[1,9],S=[1,11],g=[1,16],n=[1,17],T=[1,18],k=[1,19],A=[1,33],x=[1,20],D=[1,21],f=[1,22],m=[1,23],R=[1,24],L=[1,26],$=[1,27],I=[1,28],P=[1,29],et=[1,30],st=[1,31],it=[1,32],rt=[1,35],at=[1,36],nt=[1,37],ot=[1,38],j=[1,34],p=[1,4,5,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],lt=[1,4,5,14,15,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,39,40,41,45,48,51,52,53,54,57],xt=[4,5,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],gt={trace:d(function(){},"trace"),yy:{},symbols_:{error:2,start:3,SPACE:4,NL:5,SD:6,document:7,line:8,statement:9,classDefStatement:10,styleStatement:11,cssClassStatement:12,idStatement:13,DESCR:14,"-->":15,HIDE_EMPTY:16,scale:17,WIDTH:18,COMPOSIT_STATE:19,STRUCT_START:20,STRUCT_STOP:21,STATE_DESCR:22,AS:23,ID:24,FORK:25,JOIN:26,CHOICE:27,CONCURRENT:28,note:29,notePosition:30,NOTE_TEXT:31,direction:32,acc_title:33,acc_title_value:34,acc_descr:35,acc_descr_value:36,acc_descr_multiline_value:37,CLICK:38,STRING:39,HREF:40,classDef:41,CLASSDEF_ID:42,CLASSDEF_STYLEOPTS:43,DEFAULT:44,style:45,STYLE_IDS:46,STYLEDEF_STYLEOPTS:47,class:48,CLASSENTITY_IDS:49,STYLECLASS:50,direction_tb:51,direction_bt:52,direction_rl:53,direction_lr:54,eol:55,";":56,EDGE_STATE:57,STYLE_SEPARATOR:58,left_of:59,right_of:60,$accept:0,$end:1},terminals_:{2:"error",4:"SPACE",5:"NL",6:"SD",14:"DESCR",15:"-->",16:"HIDE_EMPTY",17:"scale",18:"WIDTH",19:"COMPOSIT_STATE",20:"STRUCT_START",21:"STRUCT_STOP",22:"STATE_DESCR",23:"AS",24:"ID",25:"FORK",26:"JOIN",27:"CHOICE",28:"CONCURRENT",29:"note",31:"NOTE_TEXT",33:"acc_title",34:"acc_title_value",35:"acc_descr",36:"acc_descr_value",37:"acc_descr_multiline_value",38:"CLICK",39:"STRING",40:"HREF",41:"classDef",42:"CLASSDEF_ID",43:"CLASSDEF_STYLEOPTS",44:"DEFAULT",45:"style",46:"STYLE_IDS",47:"STYLEDEF_STYLEOPTS",48:"class",49:"CLASSENTITY_IDS",50:"STYLECLASS",51:"direction_tb",52:"direction_bt",53:"direction_rl",54:"direction_lr",56:";",57:"EDGE_STATE",58:"STYLE_SEPARATOR",59:"left_of",60:"right_of"},productions_:[0,[3,2],[3,2],[3,2],[7,0],[7,2],[8,2],[8,1],[8,1],[9,1],[9,1],[9,1],[9,1],[9,2],[9,3],[9,4],[9,1],[9,2],[9,1],[9,4],[9,3],[9,6],[9,1],[9,1],[9,1],[9,1],[9,4],[9,4],[9,1],[9,2],[9,2],[9,1],[9,5],[9,5],[10,3],[10,3],[11,3],[12,3],[32,1],[32,1],[32,1],[32,1],[55,1],[55,1],[13,1],[13,1],[13,3],[13,3],[30,1],[30,1]],performAction:d(function(a,c,r,y,E,i,X){var l=i.length-1;switch(E){case 3:return y.setRootDoc(i[l]),i[l];break;case 4:this.$=[];break;case 5:i[l]!="nl"&&(i[l-1].push(i[l]),this.$=i[l-1]);break;case 6:case 7:this.$=i[l];break;case 8:this.$="nl";break;case 12:this.$=i[l];break;case 13:let ht=i[l-1];ht.description=y.trimColon(i[l]),this.$=ht;break;case 14:this.$={stmt:"relation",state1:i[l-2],state2:i[l]};break;case 15:let ut=y.trimColon(i[l]);this.$={stmt:"relation",state1:i[l-3],state2:i[l-1],description:ut};break;case 19:this.$={stmt:"state",id:i[l-3],type:"default",description:"",doc:i[l-1]};break;case 20:var V=i[l],H=i[l-2].trim();if(i[l].match(":")){var J=i[l].split(":");V=J[0],H=[H,J[1]]}this.$={stmt:"state",id:V,type:"default",description:H};break;case 21:this.$={stmt:"state",id:i[l-3],type:"default",description:i[l-5],doc:i[l-1]};break;case 22:this.$={stmt:"state",id:i[l],type:"fork"};break;case 23:this.$={stmt:"state",id:i[l],type:"join"};break;case 24:this.$={stmt:"state",id:i[l],type:"choice"};break;case 25:this.$={stmt:"state",id:y.getDividerId(),type:"divider"};break;case 26:this.$={stmt:"state",id:i[l-1].trim(),note:{position:i[l-2].trim(),text:i[l].trim()}};break;case 29:this.$=i[l].trim(),y.setAccTitle(this.$);break;case 30:case 31:this.$=i[l].trim(),y.setAccDescription(this.$);break;case 32:this.$={stmt:"click",id:i[l-3],url:i[l-2],tooltip:i[l-1]};break;case 33:this.$={stmt:"click",id:i[l-3],url:i[l-1],tooltip:""};break;case 34:case 35:this.$={stmt:"classDef",id:i[l-1].trim(),classes:i[l].trim()};break;case 36:this.$={stmt:"style",id:i[l-1].trim(),styleClass:i[l].trim()};break;case 37:this.$={stmt:"applyClass",id:i[l-1].trim(),styleClass:i[l].trim()};break;case 38:y.setDirection("TB"),this.$={stmt:"dir",value:"TB"};break;case 39:y.setDirection("BT"),this.$={stmt:"dir",value:"BT"};break;case 40:y.setDirection("RL"),this.$={stmt:"dir",value:"RL"};break;case 41:y.setDirection("LR"),this.$={stmt:"dir",value:"LR"};break;case 44:case 45:this.$={stmt:"state",id:i[l].trim(),type:"default",description:""};break;case 46:this.$={stmt:"state",id:i[l-2].trim(),classes:[i[l].trim()],type:"default",description:""};break;case 47:this.$={stmt:"state",id:i[l-2].trim(),classes:[i[l].trim()],type:"default",description:""};break}},"anonymous"),table:[{3:1,4:e,5:o,6:s},{1:[3]},{3:5,4:e,5:o,6:s},{3:6,4:e,5:o,6:s},t([1,4,5,16,17,19,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],h,{7:7}),{1:[2,1]},{1:[2,2]},{1:[2,3],4:u,5:S,8:8,9:10,10:12,11:13,12:14,13:15,16:g,17:n,19:T,22:k,24:A,25:x,26:D,27:f,28:m,29:R,32:25,33:L,35:$,37:I,38:P,41:et,45:st,48:it,51:rt,52:at,53:nt,54:ot,57:j},t(p,[2,5]),{9:39,10:12,11:13,12:14,13:15,16:g,17:n,19:T,22:k,24:A,25:x,26:D,27:f,28:m,29:R,32:25,33:L,35:$,37:I,38:P,41:et,45:st,48:it,51:rt,52:at,53:nt,54:ot,57:j},t(p,[2,7]),t(p,[2,8]),t(p,[2,9]),t(p,[2,10]),t(p,[2,11]),t(p,[2,12],{14:[1,40],15:[1,41]}),t(p,[2,16]),{18:[1,42]},t(p,[2,18],{20:[1,43]}),{23:[1,44]},t(p,[2,22]),t(p,[2,23]),t(p,[2,24]),t(p,[2,25]),{30:45,31:[1,46],59:[1,47],60:[1,48]},t(p,[2,28]),{34:[1,49]},{36:[1,50]},t(p,[2,31]),{13:51,24:A,57:j},{42:[1,52],44:[1,53]},{46:[1,54]},{49:[1,55]},t(lt,[2,44],{58:[1,56]}),t(lt,[2,45],{58:[1,57]}),t(p,[2,38]),t(p,[2,39]),t(p,[2,40]),t(p,[2,41]),t(p,[2,6]),t(p,[2,13]),{13:58,24:A,57:j},t(p,[2,17]),t(xt,h,{7:59}),{24:[1,60]},{24:[1,61]},{23:[1,62]},{24:[2,48]},{24:[2,49]},t(p,[2,29]),t(p,[2,30]),{39:[1,63],40:[1,64]},{43:[1,65]},{43:[1,66]},{47:[1,67]},{50:[1,68]},{24:[1,69]},{24:[1,70]},t(p,[2,14],{14:[1,71]}),{4:u,5:S,8:8,9:10,10:12,11:13,12:14,13:15,16:g,17:n,19:T,21:[1,72],22:k,24:A,25:x,26:D,27:f,28:m,29:R,32:25,33:L,35:$,37:I,38:P,41:et,45:st,48:it,51:rt,52:at,53:nt,54:ot,57:j},t(p,[2,20],{20:[1,73]}),{31:[1,74]},{24:[1,75]},{39:[1,76]},{39:[1,77]},t(p,[2,34]),t(p,[2,35]),t(p,[2,36]),t(p,[2,37]),t(lt,[2,46]),t(lt,[2,47]),t(p,[2,15]),t(p,[2,19]),t(xt,h,{7:78}),t(p,[2,26]),t(p,[2,27]),{5:[1,79]},{5:[1,80]},{4:u,5:S,8:8,9:10,10:12,11:13,12:14,13:15,16:g,17:n,19:T,21:[1,81],22:k,24:A,25:x,26:D,27:f,28:m,29:R,32:25,33:L,35:$,37:I,38:P,41:et,45:st,48:it,51:rt,52:at,53:nt,54:ot,57:j},t(p,[2,32]),t(p,[2,33]),t(p,[2,21])],defaultActions:{5:[2,1],6:[2,2],47:[2,48],48:[2,49]},parseError:d(function(a,c){if(c.recoverable)this.trace(a);else{var r=new Error(a);throw r.hash=c,r}},"parseError"),parse:d(function(a){var c=this,r=[0],y=[],E=[null],i=[],X=this.table,l="",V=0,H=0,J=0,ht=2,ut=1,he=i.slice.call(arguments,1),_=Object.create(this.lexer),M={yy:{}};for(var Tt in this.yy)Object.prototype.hasOwnProperty.call(this.yy,Tt)&&(M.yy[Tt]=this.yy[Tt]);_.setInput(a,M.yy),M.yy.lexer=_,M.yy.parser=this,typeof _.yylloc>"u"&&(_.yylloc={});var Et=_.yylloc;i.push(Et);var ue=_.options&&_.options.ranges;typeof M.yy.parseError=="function"?this.parseError=M.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function de(O){r.length=r.length-2*O,E.length=E.length-O,i.length=i.length-O}d(de,"popStack");function Lt(){var O;return O=y.pop()||_.lex()||ut,typeof O!="number"&&(O instanceof Array&&(y=O,O=y.pop()),O=c.symbols_[O]||O),O}d(Lt,"lex");for(var v,bt,U,N,Ye,_t,W={},dt,F,It,ft;;){if(U=r[r.length-1],this.defaultActions[U]?N=this.defaultActions[U]:((v===null||typeof v>"u")&&(v=Lt()),N=X[U]&&X[U][v]),typeof N>"u"||!N.length||!N[0]){var kt="";ft=[];for(dt in X[U])this.terminals_[dt]&&dt>ht&&ft.push("'"+this.terminals_[dt]+"'");_.showPosition?kt="Parse error on line "+(V+1)+`: +`+_.showPosition()+` +Expecting `+ft.join(", ")+", got '"+(this.terminals_[v]||v)+"'":kt="Parse error on line "+(V+1)+": Unexpected "+(v==ut?"end of input":"'"+(this.terminals_[v]||v)+"'"),this.parseError(kt,{text:_.match,token:this.terminals_[v]||v,line:_.yylineno,loc:Et,expected:ft})}if(N[0]instanceof Array&&N.length>1)throw new Error("Parse Error: multiple actions possible at state: "+U+", token: "+v);switch(N[0]){case 1:r.push(v),E.push(_.yytext),i.push(_.yylloc),r.push(N[1]),v=null,bt?(v=bt,bt=null):(H=_.yyleng,l=_.yytext,V=_.yylineno,Et=_.yylloc,J>0&&J--);break;case 2:if(F=this.productions_[N[1]][1],W.$=E[E.length-F],W._$={first_line:i[i.length-(F||1)].first_line,last_line:i[i.length-1].last_line,first_column:i[i.length-(F||1)].first_column,last_column:i[i.length-1].last_column},ue&&(W._$.range=[i[i.length-(F||1)].range[0],i[i.length-1].range[1]]),_t=this.performAction.apply(W,[l,H,V,M.yy,N[1],E,i].concat(he)),typeof _t<"u")return _t;F&&(r=r.slice(0,-1*F*2),E=E.slice(0,-1*F),i=i.slice(0,-1*F)),r.push(this.productions_[N[1]][0]),E.push(W.$),i.push(W._$),It=X[r[r.length-2]][r[r.length-1]],r.push(It);break;case 3:return!0}}return!0},"parse")},ce=(function(){var Y={EOF:1,parseError:d(function(c,r){if(this.yy.parser)this.yy.parser.parseError(c,r);else throw new Error(c)},"parseError"),setInput:d(function(a,c){return this.yy=c||this.yy||{},this._input=a,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:d(function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var c=a.match(/(?:\r\n?|\n).*/g);return c?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},"input"),unput:d(function(a){var c=a.length,r=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-c),this.offset-=c;var y=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),r.length-1&&(this.yylineno-=r.length-1);var E=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:r?(r.length===y.length?this.yylloc.first_column:0)+y[y.length-r.length].length-r[0].length:this.yylloc.first_column-c},this.options.ranges&&(this.yylloc.range=[E[0],E[0]+this.yyleng-c]),this.yyleng=this.yytext.length,this},"unput"),more:d(function(){return this._more=!0,this},"more"),reject:d(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:d(function(a){this.unput(this.match.slice(a))},"less"),pastInput:d(function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:d(function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:d(function(){var a=this.pastInput(),c=new Array(a.length+1).join("-");return a+this.upcomingInput()+` +`+c+"^"},"showPosition"),test_match:d(function(a,c){var r,y,E;if(this.options.backtrack_lexer&&(E={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(E.yylloc.range=this.yylloc.range.slice(0))),y=a[0].match(/(?:\r\n?|\n).*/g),y&&(this.yylineno+=y.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:y?y[y.length-1].length-y[y.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+a[0].length},this.yytext+=a[0],this.match+=a[0],this.matches=a,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(a[0].length),this.matched+=a[0],r=this.performAction.call(this,this.yy,this,c,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),r)return r;if(this._backtrack){for(var i in E)this[i]=E[i];return!1}return!1},"test_match"),next:d(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,c,r,y;this._more||(this.yytext="",this.match="");for(var E=this._currentRules(),i=0;ic[0].length)){if(c=r,y=i,this.options.backtrack_lexer){if(a=this.test_match(r,E[i]),a!==!1)return a;if(this._backtrack){c=!1;continue}else return!1}else if(!this.options.flex)break}return c?(a=this.test_match(c,E[y]),a!==!1?a:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:d(function(){var c=this.next();return c||this.lex()},"lex"),begin:d(function(c){this.conditionStack.push(c)},"begin"),popState:d(function(){var c=this.conditionStack.length-1;return c>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:d(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:d(function(c){return c=this.conditionStack.length-1-Math.abs(c||0),c>=0?this.conditionStack[c]:"INITIAL"},"topState"),pushState:d(function(c){this.begin(c)},"pushState"),stateStackSize:d(function(){return this.conditionStack.length},"stateStackSize"),options:{"case-insensitive":!0},performAction:d(function(c,r,y,E){var i=E;switch(y){case 0:return 38;case 1:return 40;case 2:return 39;case 3:return 44;case 4:return 51;case 5:return 52;case 6:return 53;case 7:return 54;case 8:break;case 9:break;case 10:return 5;case 11:break;case 12:break;case 13:break;case 14:break;case 15:return this.pushState("SCALE"),17;break;case 16:return 18;case 17:this.popState();break;case 18:return this.begin("acc_title"),33;break;case 19:return this.popState(),"acc_title_value";break;case 20:return this.begin("acc_descr"),35;break;case 21:return this.popState(),"acc_descr_value";break;case 22:this.begin("acc_descr_multiline");break;case 23:this.popState();break;case 24:return"acc_descr_multiline_value";case 25:return this.pushState("CLASSDEF"),41;break;case 26:return this.popState(),this.pushState("CLASSDEFID"),"DEFAULT_CLASSDEF_ID";break;case 27:return this.popState(),this.pushState("CLASSDEFID"),42;break;case 28:return this.popState(),43;break;case 29:return this.pushState("CLASS"),48;break;case 30:return this.popState(),this.pushState("CLASS_STYLE"),49;break;case 31:return this.popState(),50;break;case 32:return this.pushState("STYLE"),45;break;case 33:return this.popState(),this.pushState("STYLEDEF_STYLES"),46;break;case 34:return this.popState(),47;break;case 35:return this.pushState("SCALE"),17;break;case 36:return 18;case 37:this.popState();break;case 38:this.pushState("STATE");break;case 39:return this.popState(),r.yytext=r.yytext.slice(0,-8).trim(),25;break;case 40:return this.popState(),r.yytext=r.yytext.slice(0,-8).trim(),26;break;case 41:return this.popState(),r.yytext=r.yytext.slice(0,-10).trim(),27;break;case 42:return this.popState(),r.yytext=r.yytext.slice(0,-8).trim(),25;break;case 43:return this.popState(),r.yytext=r.yytext.slice(0,-8).trim(),26;break;case 44:return this.popState(),r.yytext=r.yytext.slice(0,-10).trim(),27;break;case 45:return 51;case 46:return 52;case 47:return 53;case 48:return 54;case 49:this.pushState("STATE_STRING");break;case 50:return this.pushState("STATE_ID"),"AS";break;case 51:return this.popState(),"ID";break;case 52:this.popState();break;case 53:return"STATE_DESCR";case 54:return 19;case 55:this.popState();break;case 56:return this.popState(),this.pushState("struct"),20;break;case 57:break;case 58:return this.popState(),21;break;case 59:break;case 60:return this.begin("NOTE"),29;break;case 61:return this.popState(),this.pushState("NOTE_ID"),59;break;case 62:return this.popState(),this.pushState("NOTE_ID"),60;break;case 63:this.popState(),this.pushState("FLOATING_NOTE");break;case 64:return this.popState(),this.pushState("FLOATING_NOTE_ID"),"AS";break;case 65:break;case 66:return"NOTE_TEXT";case 67:return this.popState(),"ID";break;case 68:return this.popState(),this.pushState("NOTE_TEXT"),24;break;case 69:return this.popState(),r.yytext=r.yytext.substr(2).trim(),31;break;case 70:return this.popState(),r.yytext=r.yytext.slice(0,-8).trim(),31;break;case 71:return 6;case 72:return 6;case 73:return 16;case 74:return 57;case 75:return 24;case 76:return r.yytext=r.yytext.trim(),14;break;case 77:return 15;case 78:return 28;case 79:return 58;case 80:return 5;case 81:return"INVALID"}},"anonymous"),rules:[/^(?:click\b)/i,/^(?:href\b)/i,/^(?:"[^"]*")/i,/^(?:default\b)/i,/^(?:.*direction\s+TB[^\n]*)/i,/^(?:.*direction\s+BT[^\n]*)/i,/^(?:.*direction\s+RL[^\n]*)/i,/^(?:.*direction\s+LR[^\n]*)/i,/^(?:%%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[\n]+)/i,/^(?:[\s]+)/i,/^(?:((?!\n)\s)+)/i,/^(?:#[^\n]*)/i,/^(?:%[^\n]*)/i,/^(?:scale\s+)/i,/^(?:\d+)/i,/^(?:\s+width\b)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:classDef\s+)/i,/^(?:DEFAULT\s+)/i,/^(?:\w+\s+)/i,/^(?:[^\n]*)/i,/^(?:class\s+)/i,/^(?:(\w+)+((,\s*\w+)*))/i,/^(?:[^\n]*)/i,/^(?:style\s+)/i,/^(?:[\w,]+\s+)/i,/^(?:[^\n]*)/i,/^(?:scale\s+)/i,/^(?:\d+)/i,/^(?:\s+width\b)/i,/^(?:state\s+)/i,/^(?:.*<>)/i,/^(?:.*<>)/i,/^(?:.*<>)/i,/^(?:.*\[\[fork\]\])/i,/^(?:.*\[\[join\]\])/i,/^(?:.*\[\[choice\]\])/i,/^(?:.*direction\s+TB[^\n]*)/i,/^(?:.*direction\s+BT[^\n]*)/i,/^(?:.*direction\s+RL[^\n]*)/i,/^(?:.*direction\s+LR[^\n]*)/i,/^(?:["])/i,/^(?:\s*as\s+)/i,/^(?:[^\n\{]*)/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:[^\n\s\{]+)/i,/^(?:\n)/i,/^(?:\{)/i,/^(?:%%(?!\{)[^\n]*)/i,/^(?:\})/i,/^(?:[\n])/i,/^(?:note\s+)/i,/^(?:left of\b)/i,/^(?:right of\b)/i,/^(?:")/i,/^(?:\s*as\s*)/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:[^\n]*)/i,/^(?:\s*[^:\n\s\-]+)/i,/^(?:\s*:[^:\n;]+)/i,/^(?:[\s\S]*?end note\b)/i,/^(?:stateDiagram\s+)/i,/^(?:stateDiagram-v2\s+)/i,/^(?:hide empty description\b)/i,/^(?:\[\*\])/i,/^(?:[^:\n\s\-\{]+)/i,/^(?:\s*:[^:\n;]+)/i,/^(?:-->)/i,/^(?:--)/i,/^(?::::)/i,/^(?:$)/i,/^(?:.)/i],conditions:{LINE:{rules:[12,13],inclusive:!1},struct:{rules:[12,13,25,29,32,38,45,46,47,48,57,58,59,60,74,75,76,77,78],inclusive:!1},FLOATING_NOTE_ID:{rules:[67],inclusive:!1},FLOATING_NOTE:{rules:[64,65,66],inclusive:!1},NOTE_TEXT:{rules:[69,70],inclusive:!1},NOTE_ID:{rules:[68],inclusive:!1},NOTE:{rules:[61,62,63],inclusive:!1},STYLEDEF_STYLEOPTS:{rules:[],inclusive:!1},STYLEDEF_STYLES:{rules:[34],inclusive:!1},STYLE_IDS:{rules:[],inclusive:!1},STYLE:{rules:[33],inclusive:!1},CLASS_STYLE:{rules:[31],inclusive:!1},CLASS:{rules:[30],inclusive:!1},CLASSDEFID:{rules:[28],inclusive:!1},CLASSDEF:{rules:[26,27],inclusive:!1},acc_descr_multiline:{rules:[23,24],inclusive:!1},acc_descr:{rules:[21],inclusive:!1},acc_title:{rules:[19],inclusive:!1},SCALE:{rules:[16,17,36,37],inclusive:!1},ALIAS:{rules:[],inclusive:!1},STATE_ID:{rules:[51],inclusive:!1},STATE_STRING:{rules:[52,53],inclusive:!1},FORK_STATE:{rules:[],inclusive:!1},STATE:{rules:[12,13,39,40,41,42,43,44,49,50,54,55,56],inclusive:!1},ID:{rules:[12,13],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,10,11,13,14,15,18,20,22,25,29,32,35,38,56,60,71,72,73,74,75,76,77,79,80,81],inclusive:!0}}};return Y})();gt.lexer=ce;function ct(){this.yy={}}return d(ct,"Parser"),ct.prototype=gt,gt.Parser=ct,new ct})();vt.parser=vt;var He=vt,fe="TB",Jt="TB",Ut="dir",K="state",z="root",Ct="relation",pe="classDef",Se="style",ye="applyClass",Z="default",qt="divider",Qt="fill:none",Zt="fill: #333",te="c",ee="text",se="normal",mt="rect",Dt="rectWithTitle",ge="stateStart",Te="stateEnd",jt="divider",Ht="roundedWithTitle",Ee="note",be="noteGroup",tt="statediagram",_e="state",ke=`${tt}-${_e}`,ie="transition",me="note",De="note-edge",ve=`${ie} ${De}`,Ce=`${tt}-${me}`,Ae="cluster",xe=`${tt}-${Ae}`,Le="cluster-alt",Ie=`${tt}-${Le}`,re="parent",ae="note",Oe="state",At="----",Re=`${At}${ae}`,Wt=`${At}${re}`,ne=d((t,e=Jt)=>{if(!t.doc)return e;let o=e;for(let s of t.doc)s.stmt==="dir"&&(o=s.value);return o},"getDir"),Ne=d(function(t,e){return e.db.getClasses()},"getClasses"),we=d(async function(t,e,o,s){b.info("REF0:"),b.info("Drawing state diagram (v2)",e);let{securityLevel:h,state:u,layout:S}=w();s.db.extract(s.db.getRootDocV2());let g=s.db.getData(),n=Vt(e,h);g.type=s.type,g.layoutAlgorithm=S,g.nodeSpacing=u?.nodeSpacing||50,g.rankSpacing=u?.rankSpacing||50,g.markers=["barb"],g.diagramId=e,await Bt(g,n);let T=8;try{(typeof s.db.getLinks=="function"?s.db.getLinks():new Map).forEach((A,x)=>{let D=typeof x=="string"?x:typeof x?.id=="string"?x.id:"";if(!D){b.warn("\u26A0\uFE0F Invalid or missing stateId from key:",JSON.stringify(x));return}let f=n.node()?.querySelectorAll("g"),m;if(f?.forEach(I=>{I.textContent?.trim()===D&&(m=I)}),!m){b.warn("\u26A0\uFE0F Could not find node matching text:",D);return}let R=m.parentNode;if(!R){b.warn("\u26A0\uFE0F Node has no parent, cannot wrap:",D);return}let L=document.createElementNS("http://www.w3.org/2000/svg","a"),$=A.url.replace(/^"+|"+$/g,"");if(L.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",$),L.setAttribute("target","_blank"),A.tooltip){let I=A.tooltip.replace(/^"+|"+$/g,"");L.setAttribute("title",I)}R.replaceChild(L,m),L.appendChild(m),b.info("\u{1F517} Wrapped node in tag for:",D,A.url)})}catch(k){b.error("\u274C Error injecting clickable links:",k)}Gt.insertTitle(n,"statediagramTitleText",u?.titleTopMargin??25,s.db.getDiagramTitle()),Mt(n,T,tt,u?.useMaxWidth??!0)},"draw"),We={getClasses:Ne,draw:we,getDir:ne},St=new Map,B=0;function yt(t="",e=0,o="",s=At){let h=o!==null&&o.length>0?`${s}${o}`:"";return`${Oe}-${t}${h}-${e}`}d(yt,"stateDomId");var $e=d((t,e,o,s,h,u,S,g)=>{b.trace("items",e),e.forEach(n=>{switch(n.stmt){case K:Q(t,n,o,s,h,u,S,g);break;case Z:Q(t,n,o,s,h,u,S,g);break;case Ct:{Q(t,n.state1,o,s,h,u,S,g),Q(t,n.state2,o,s,h,u,S,g);let T={id:"edge"+B,start:n.state1.id,end:n.state2.id,arrowhead:"normal",arrowTypeEnd:"arrow_barb",style:Qt,labelStyle:"",label:G.sanitizeText(n.description??"",w()),arrowheadStyle:Zt,labelpos:te,labelType:ee,thickness:se,classes:ie,look:S};h.push(T),B++}break}})},"setupDoc"),zt=d((t,e=Jt)=>{let o=e;if(t.doc)for(let s of t.doc)s.stmt==="dir"&&(o=s.value);return o},"getDir");function q(t,e,o){if(!e.id||e.id===""||e.id==="")return;e.cssClasses&&(Array.isArray(e.cssCompiledStyles)||(e.cssCompiledStyles=[]),e.cssClasses.split(" ").forEach(h=>{let u=o.get(h);u&&(e.cssCompiledStyles=[...e.cssCompiledStyles??[],...u.styles])}));let s=t.find(h=>h.id===e.id);s?Object.assign(s,e):t.push(e)}d(q,"insertOrUpdateNode");function oe(t){return t?.classes?.join(" ")??""}d(oe,"getClassesFromDbInfo");function le(t){return t?.styles??[]}d(le,"getStylesFromDbInfo");var Q=d((t,e,o,s,h,u,S,g)=>{let n=e.id,T=o.get(n),k=oe(T),A=le(T),x=w();if(b.info("dataFetcher parsedItem",e,T,A),n!=="root"){let D=mt;e.start===!0?D=ge:e.start===!1&&(D=Te),e.type!==Z&&(D=e.type),St.get(n)||St.set(n,{id:n,shape:D,description:G.sanitizeText(n,x),cssClasses:`${k} ${ke}`,cssStyles:A});let f=St.get(n);e.description&&(Array.isArray(f.description)?(f.shape=Dt,f.description.push(e.description)):f.description?.length&&f.description.length>0?(f.shape=Dt,f.description===n?f.description=[e.description]:f.description=[f.description,e.description]):(f.shape=mt,f.description=e.description),f.description=G.sanitizeTextOrArray(f.description,x)),f.description?.length===1&&f.shape===Dt&&(f.type==="group"?f.shape=Ht:f.shape=mt),!f.type&&e.doc&&(b.info("Setting cluster for XCX",n,zt(e)),f.type="group",f.isGroup=!0,f.dir=zt(e),f.shape=e.type===qt?jt:Ht,f.cssClasses=`${f.cssClasses} ${xe} ${u?Ie:""}`);let m={labelStyle:"",shape:f.shape,label:f.description,cssClasses:f.cssClasses,cssCompiledStyles:[],cssStyles:f.cssStyles,id:n,dir:f.dir,domId:yt(n,B),type:f.type,isGroup:f.type==="group",padding:8,rx:10,ry:10,look:S};if(m.shape===jt&&(m.label=""),t&&t.id!=="root"&&(b.trace("Setting node ",n," to be child of its parent ",t.id),m.parentId=t.id),m.centerLabel=!0,e.note){let R={labelStyle:"",shape:Ee,label:e.note.text,cssClasses:Ce,cssStyles:[],cssCompiledStyles:[],id:n+Re+"-"+B,domId:yt(n,B,ae),type:f.type,isGroup:f.type==="group",padding:x.flowchart?.padding,look:S,position:e.note.position},L=n+Wt,$={labelStyle:"",shape:be,label:e.note.text,cssClasses:f.cssClasses,cssStyles:[],id:n+Wt,domId:yt(n,B,re),type:"group",isGroup:!0,padding:16,look:S,position:e.note.position};B++,$.id=L,R.parentId=L,q(s,$,g),q(s,R,g),q(s,m,g);let I=n,P=R.id;e.note.position==="left of"&&(I=R.id,P=n),h.push({id:I+"-"+P,start:I,end:P,arrowhead:"none",arrowTypeEnd:"",style:Qt,labelStyle:"",classes:ve,arrowheadStyle:Zt,labelpos:te,labelType:ee,thickness:se,look:S})}else q(s,m,g)}e.doc&&(b.trace("Adding nodes children "),$e(e,e.doc,o,s,h,!u,S,g))},"dataFetcher"),Pe=d(()=>{St.clear(),B=0},"reset"),C={START_NODE:"[*]",START_TYPE:"start",END_NODE:"[*]",END_TYPE:"end",COLOR_KEYWORD:"color",FILL_KEYWORD:"fill",BG_FILL:"bgFill",STYLECLASS_SEP:","},Kt=d(()=>new Map,"newClassesList"),Xt=d(()=>({relations:[],states:new Map,documents:{}}),"newDoc"),pt=d(t=>JSON.parse(JSON.stringify(t)),"clone"),ze=class{constructor(t){this.version=t,this.nodes=[],this.edges=[],this.rootDoc=[],this.classes=Kt(),this.documents={root:Xt()},this.currentDocument=this.documents.root,this.startEndCount=0,this.dividerCnt=0,this.links=new Map,this.getAccTitle=Nt,this.setAccTitle=Rt,this.getAccDescription=$t,this.setAccDescription=wt,this.setDiagramTitle=Pt,this.getDiagramTitle=Ft,this.clear(),this.setRootDoc=this.setRootDoc.bind(this),this.getDividerId=this.getDividerId.bind(this),this.setDirection=this.setDirection.bind(this),this.trimColon=this.trimColon.bind(this)}static{d(this,"StateDB")}static{this.relationType={AGGREGATION:0,EXTENSION:1,COMPOSITION:2,DEPENDENCY:3}}extract(t){this.clear(!0);for(let s of Array.isArray(t)?t:t.doc)switch(s.stmt){case K:this.addState(s.id.trim(),s.type,s.doc,s.description,s.note);break;case Ct:this.addRelation(s.state1,s.state2,s.description);break;case pe:this.addStyleClass(s.id.trim(),s.classes);break;case Se:this.handleStyleDef(s);break;case ye:this.setCssClass(s.id.trim(),s.styleClass);break;case"click":this.addLink(s.id,s.url,s.tooltip);break}let e=this.getStates(),o=w();Pe(),Q(void 0,this.getRootDocV2(),e,this.nodes,this.edges,!0,o.look,this.classes);for(let s of this.nodes)if(Array.isArray(s.label)){if(s.description=s.label.slice(1),s.isGroup&&s.description.length>0)throw new Error(`Group nodes can only have label. Remove the additional description for node [${s.id}]`);s.label=s.label[0]}}handleStyleDef(t){let e=t.id.trim().split(","),o=t.styleClass.split(",");for(let s of e){let h=this.getState(s);if(!h){let u=s.trim();this.addState(u),h=this.getState(u)}h&&(h.styles=o.map(u=>u.replace(/;/g,"")?.trim()))}}setRootDoc(t){b.info("Setting root doc",t),this.rootDoc=t,this.version===1?this.extract(t):this.extract(this.getRootDocV2())}docTranslator(t,e,o){if(e.stmt===Ct){this.docTranslator(t,e.state1,!0),this.docTranslator(t,e.state2,!1);return}if(e.stmt===K&&(e.id===C.START_NODE?(e.id=t.id+(o?"_start":"_end"),e.start=o):e.id=e.id.trim()),e.stmt!==z&&e.stmt!==K||!e.doc)return;let s=[],h=[];for(let u of e.doc)if(u.type===qt){let S=pt(u);S.doc=pt(h),s.push(S),h=[]}else h.push(u);if(s.length>0&&h.length>0){let u={stmt:K,id:Yt(),type:"divider",doc:pt(h)};s.push(pt(u)),e.doc=s}e.doc.forEach(u=>this.docTranslator(e,u,!0))}getRootDocV2(){return this.docTranslator({id:z,stmt:z},{id:z,stmt:z,doc:this.rootDoc},!0),{id:z,doc:this.rootDoc}}addState(t,e=Z,o=void 0,s=void 0,h=void 0,u=void 0,S=void 0,g=void 0){let n=t?.trim();if(!this.currentDocument.states.has(n))b.info("Adding state ",n,s),this.currentDocument.states.set(n,{stmt:K,id:n,descriptions:[],type:e,doc:o,note:h,classes:[],styles:[],textStyles:[]});else{let T=this.currentDocument.states.get(n);if(!T)throw new Error(`State not found: ${n}`);T.doc||(T.doc=o),T.type||(T.type=e)}if(s&&(b.info("Setting state description",n,s),(Array.isArray(s)?s:[s]).forEach(k=>this.addDescription(n,k.trim()))),h){let T=this.currentDocument.states.get(n);if(!T)throw new Error(`State not found: ${n}`);T.note=h,T.note.text=G.sanitizeText(T.note.text,w())}u&&(b.info("Setting state classes",n,u),(Array.isArray(u)?u:[u]).forEach(k=>this.setCssClass(n,k.trim()))),S&&(b.info("Setting state styles",n,S),(Array.isArray(S)?S:[S]).forEach(k=>this.setStyle(n,k.trim()))),g&&(b.info("Setting state styles",n,S),(Array.isArray(g)?g:[g]).forEach(k=>this.setTextStyle(n,k.trim())))}clear(t){this.nodes=[],this.edges=[],this.documents={root:Xt()},this.currentDocument=this.documents.root,this.startEndCount=0,this.classes=Kt(),t||(this.links=new Map,Ot())}getState(t){return this.currentDocument.states.get(t)}getStates(){return this.currentDocument.states}logDocuments(){b.info("Documents = ",this.documents)}getRelations(){return this.currentDocument.relations}addLink(t,e,o){this.links.set(t,{url:e,tooltip:o}),b.warn("Adding link",t,e,o)}getLinks(){return this.links}startIdIfNeeded(t=""){return t===C.START_NODE?(this.startEndCount++,`${C.START_TYPE}${this.startEndCount}`):t}startTypeIfNeeded(t="",e=Z){return t===C.START_NODE?C.START_TYPE:e}endIdIfNeeded(t=""){return t===C.END_NODE?(this.startEndCount++,`${C.END_TYPE}${this.startEndCount}`):t}endTypeIfNeeded(t="",e=Z){return t===C.END_NODE?C.END_TYPE:e}addRelationObjs(t,e,o=""){let s=this.startIdIfNeeded(t.id.trim()),h=this.startTypeIfNeeded(t.id.trim(),t.type),u=this.startIdIfNeeded(e.id.trim()),S=this.startTypeIfNeeded(e.id.trim(),e.type);this.addState(s,h,t.doc,t.description,t.note,t.classes,t.styles,t.textStyles),this.addState(u,S,e.doc,e.description,e.note,e.classes,e.styles,e.textStyles),this.currentDocument.relations.push({id1:s,id2:u,relationTitle:G.sanitizeText(o,w())})}addRelation(t,e,o){if(typeof t=="object"&&typeof e=="object")this.addRelationObjs(t,e,o);else if(typeof t=="string"&&typeof e=="string"){let s=this.startIdIfNeeded(t.trim()),h=this.startTypeIfNeeded(t),u=this.endIdIfNeeded(e.trim()),S=this.endTypeIfNeeded(e);this.addState(s,h),this.addState(u,S),this.currentDocument.relations.push({id1:s,id2:u,relationTitle:o?G.sanitizeText(o,w()):void 0})}}addDescription(t,e){let o=this.currentDocument.states.get(t),s=e.startsWith(":")?e.replace(":","").trim():e;o?.descriptions?.push(G.sanitizeText(s,w()))}cleanupLabel(t){return t.startsWith(":")?t.slice(2).trim():t.trim()}getDividerId(){return this.dividerCnt++,`divider-id-${this.dividerCnt}`}addStyleClass(t,e=""){this.classes.has(t)||this.classes.set(t,{id:t,styles:[],textStyles:[]});let o=this.classes.get(t);e&&o&&e.split(C.STYLECLASS_SEP).forEach(s=>{let h=s.replace(/([^;]*);/,"$1").trim();if(RegExp(C.COLOR_KEYWORD).exec(s)){let S=h.replace(C.FILL_KEYWORD,C.BG_FILL).replace(C.COLOR_KEYWORD,C.FILL_KEYWORD);o.textStyles.push(S)}o.styles.push(h)})}getClasses(){return this.classes}setCssClass(t,e){t.split(",").forEach(o=>{let s=this.getState(o);if(!s){let h=o.trim();this.addState(h),s=this.getState(h)}s?.classes?.push(e)})}setStyle(t,e){this.getState(t)?.styles?.push(e)}setTextStyle(t,e){this.getState(t)?.textStyles?.push(e)}getDirectionStatement(){return this.rootDoc.find(t=>t.stmt===Ut)}getDirection(){return this.getDirectionStatement()?.value??fe}setDirection(t){let e=this.getDirectionStatement();e?e.value=t:this.rootDoc.unshift({stmt:Ut,value:t})}trimColon(t){return t.startsWith(":")?t.slice(1).trim():t.trim()}getData(){let t=w();return{nodes:this.nodes,edges:this.edges,other:{},config:t,direction:ne(this.getRootDocV2())}}getConfig(){return w().state}},Fe=d(t=>` +defs #statediagram-barbEnd { + fill: ${t.transitionColor}; + stroke: ${t.transitionColor}; + } +g.stateGroup text { + fill: ${t.nodeBorder}; + stroke: none; + font-size: 10px; +} +g.stateGroup text { + fill: ${t.textColor}; + stroke: none; + font-size: 10px; + +} +g.stateGroup .state-title { + font-weight: bolder; + fill: ${t.stateLabelColor}; +} + +g.stateGroup rect { + fill: ${t.mainBkg}; + stroke: ${t.nodeBorder}; +} + +g.stateGroup line { + stroke: ${t.lineColor}; + stroke-width: 1; +} + +.transition { + stroke: ${t.transitionColor}; + stroke-width: 1; + fill: none; +} + +.stateGroup .composit { + fill: ${t.background}; + border-bottom: 1px +} + +.stateGroup .alt-composit { + fill: #e0e0e0; + border-bottom: 1px +} + +.state-note { + stroke: ${t.noteBorderColor}; + fill: ${t.noteBkgColor}; + + text { + fill: ${t.noteTextColor}; + stroke: none; + font-size: 10px; + } +} + +.stateLabel .box { + stroke: none; + stroke-width: 0; + fill: ${t.mainBkg}; + opacity: 0.5; +} + +.edgeLabel .label rect { + fill: ${t.labelBackgroundColor}; + opacity: 0.5; +} +.edgeLabel { + background-color: ${t.edgeLabelBackground}; + p { + background-color: ${t.edgeLabelBackground}; + } + rect { + opacity: 0.5; + background-color: ${t.edgeLabelBackground}; + fill: ${t.edgeLabelBackground}; + } + text-align: center; +} +.edgeLabel .label text { + fill: ${t.transitionLabelColor||t.tertiaryTextColor}; +} +.label div .edgeLabel { + color: ${t.transitionLabelColor||t.tertiaryTextColor}; +} + +.stateLabel text { + fill: ${t.stateLabelColor}; + font-size: 10px; + font-weight: bold; +} + +.node circle.state-start { + fill: ${t.specialStateColor}; + stroke: ${t.specialStateColor}; +} + +.node .fork-join { + fill: ${t.specialStateColor}; + stroke: ${t.specialStateColor}; +} + +.node circle.state-end { + fill: ${t.innerEndBackground}; + stroke: ${t.background}; + stroke-width: 1.5 +} +.end-state-inner { + fill: ${t.compositeBackground||t.background}; + // stroke: ${t.background}; + stroke-width: 1.5 +} + +.node rect { + fill: ${t.stateBkg||t.mainBkg}; + stroke: ${t.stateBorder||t.nodeBorder}; + stroke-width: 1px; +} +.node polygon { + fill: ${t.mainBkg}; + stroke: ${t.stateBorder||t.nodeBorder};; + stroke-width: 1px; +} +#statediagram-barbEnd { + fill: ${t.lineColor}; +} + +.statediagram-cluster rect { + fill: ${t.compositeTitleBackground}; + stroke: ${t.stateBorder||t.nodeBorder}; + stroke-width: 1px; +} + +.cluster-label, .nodeLabel { + color: ${t.stateLabelColor}; + // line-height: 1; +} + +.statediagram-cluster rect.outer { + rx: 5px; + ry: 5px; +} +.statediagram-state .divider { + stroke: ${t.stateBorder||t.nodeBorder}; +} + +.statediagram-state .title-state { + rx: 5px; + ry: 5px; +} +.statediagram-cluster.statediagram-cluster .inner { + fill: ${t.compositeBackground||t.background}; +} +.statediagram-cluster.statediagram-cluster-alt .inner { + fill: ${t.altBackground?t.altBackground:"#efefef"}; +} + +.statediagram-cluster .inner { + rx:0; + ry:0; +} + +.statediagram-state rect.basic { + rx: 5px; + ry: 5px; +} +.statediagram-state rect.divider { + stroke-dasharray: 10,10; + fill: ${t.altBackground?t.altBackground:"#efefef"}; +} + +.note-edge { + stroke-dasharray: 5; +} + +.statediagram-note rect { + fill: ${t.noteBkgColor}; + stroke: ${t.noteBorderColor}; + stroke-width: 1px; + rx: 0; + ry: 0; +} +.statediagram-note rect { + fill: ${t.noteBkgColor}; + stroke: ${t.noteBorderColor}; + stroke-width: 1px; + rx: 0; + ry: 0; +} + +.statediagram-note text { + fill: ${t.noteTextColor}; +} + +.statediagram-note .nodeLabel { + color: ${t.noteTextColor}; +} +.statediagram .edgeLabel { + color: red; // ${t.noteTextColor}; +} + +#dependencyStart, #dependencyEnd { + fill: ${t.lineColor}; + stroke: ${t.lineColor}; + stroke-width: 1; +} + +.statediagramTitleText { + text-anchor: middle; + font-size: 18px; + fill: ${t.textColor}; +} +`,"getStyles"),Ke=Fe;export{He as a,We as b,ze as c,Ke as d}; +//# sourceMappingURL=chunk-FNCPGT3X.min.js.map diff --git a/docs/website/public/chunk-FNCPGT3X.min.js.map b/docs/website/public/chunk-FNCPGT3X.min.js.map new file mode 100644 index 000000000..ad352550e --- /dev/null +++ b/docs/website/public/chunk-FNCPGT3X.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/mermaid/dist/chunks/mermaid.core/chunk-DI55MBZ5.mjs"], + "sourcesContent": ["import {\n getDiagramElement\n} from \"./chunk-55IACEB6.mjs\";\nimport {\n setupViewPortForSVG\n} from \"./chunk-QN33PNHL.mjs\";\nimport {\n render\n} from \"./chunk-N4CR4FBY.mjs\";\nimport {\n generateId,\n utils_default\n} from \"./chunk-S3R3BYOJ.mjs\";\nimport {\n clear,\n common_default,\n getAccDescription,\n getAccTitle,\n getConfig2 as getConfig,\n getDiagramTitle,\n setAccDescription,\n setAccTitle,\n setDiagramTitle\n} from \"./chunk-ABZYJK2D.mjs\";\nimport {\n __name,\n log\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/diagrams/state/parser/stateDiagram.jison\nvar parser = (function() {\n var o = /* @__PURE__ */ __name(function(k, v, o2, l) {\n for (o2 = o2 || {}, l = k.length; l--; o2[k[l]] = v) ;\n return o2;\n }, \"o\"), $V0 = [1, 2], $V1 = [1, 3], $V2 = [1, 4], $V3 = [2, 4], $V4 = [1, 9], $V5 = [1, 11], $V6 = [1, 16], $V7 = [1, 17], $V8 = [1, 18], $V9 = [1, 19], $Va = [1, 33], $Vb = [1, 20], $Vc = [1, 21], $Vd = [1, 22], $Ve = [1, 23], $Vf = [1, 24], $Vg = [1, 26], $Vh = [1, 27], $Vi = [1, 28], $Vj = [1, 29], $Vk = [1, 30], $Vl = [1, 31], $Vm = [1, 32], $Vn = [1, 35], $Vo = [1, 36], $Vp = [1, 37], $Vq = [1, 38], $Vr = [1, 34], $Vs = [1, 4, 5, 16, 17, 19, 21, 22, 24, 25, 26, 27, 28, 29, 33, 35, 37, 38, 41, 45, 48, 51, 52, 53, 54, 57], $Vt = [1, 4, 5, 14, 15, 16, 17, 19, 21, 22, 24, 25, 26, 27, 28, 29, 33, 35, 37, 38, 39, 40, 41, 45, 48, 51, 52, 53, 54, 57], $Vu = [4, 5, 16, 17, 19, 21, 22, 24, 25, 26, 27, 28, 29, 33, 35, 37, 38, 41, 45, 48, 51, 52, 53, 54, 57];\n var parser2 = {\n trace: /* @__PURE__ */ __name(function trace() {\n }, \"trace\"),\n yy: {},\n symbols_: { \"error\": 2, \"start\": 3, \"SPACE\": 4, \"NL\": 5, \"SD\": 6, \"document\": 7, \"line\": 8, \"statement\": 9, \"classDefStatement\": 10, \"styleStatement\": 11, \"cssClassStatement\": 12, \"idStatement\": 13, \"DESCR\": 14, \"-->\": 15, \"HIDE_EMPTY\": 16, \"scale\": 17, \"WIDTH\": 18, \"COMPOSIT_STATE\": 19, \"STRUCT_START\": 20, \"STRUCT_STOP\": 21, \"STATE_DESCR\": 22, \"AS\": 23, \"ID\": 24, \"FORK\": 25, \"JOIN\": 26, \"CHOICE\": 27, \"CONCURRENT\": 28, \"note\": 29, \"notePosition\": 30, \"NOTE_TEXT\": 31, \"direction\": 32, \"acc_title\": 33, \"acc_title_value\": 34, \"acc_descr\": 35, \"acc_descr_value\": 36, \"acc_descr_multiline_value\": 37, \"CLICK\": 38, \"STRING\": 39, \"HREF\": 40, \"classDef\": 41, \"CLASSDEF_ID\": 42, \"CLASSDEF_STYLEOPTS\": 43, \"DEFAULT\": 44, \"style\": 45, \"STYLE_IDS\": 46, \"STYLEDEF_STYLEOPTS\": 47, \"class\": 48, \"CLASSENTITY_IDS\": 49, \"STYLECLASS\": 50, \"direction_tb\": 51, \"direction_bt\": 52, \"direction_rl\": 53, \"direction_lr\": 54, \"eol\": 55, \";\": 56, \"EDGE_STATE\": 57, \"STYLE_SEPARATOR\": 58, \"left_of\": 59, \"right_of\": 60, \"$accept\": 0, \"$end\": 1 },\n terminals_: { 2: \"error\", 4: \"SPACE\", 5: \"NL\", 6: \"SD\", 14: \"DESCR\", 15: \"-->\", 16: \"HIDE_EMPTY\", 17: \"scale\", 18: \"WIDTH\", 19: \"COMPOSIT_STATE\", 20: \"STRUCT_START\", 21: \"STRUCT_STOP\", 22: \"STATE_DESCR\", 23: \"AS\", 24: \"ID\", 25: \"FORK\", 26: \"JOIN\", 27: \"CHOICE\", 28: \"CONCURRENT\", 29: \"note\", 31: \"NOTE_TEXT\", 33: \"acc_title\", 34: \"acc_title_value\", 35: \"acc_descr\", 36: \"acc_descr_value\", 37: \"acc_descr_multiline_value\", 38: \"CLICK\", 39: \"STRING\", 40: \"HREF\", 41: \"classDef\", 42: \"CLASSDEF_ID\", 43: \"CLASSDEF_STYLEOPTS\", 44: \"DEFAULT\", 45: \"style\", 46: \"STYLE_IDS\", 47: \"STYLEDEF_STYLEOPTS\", 48: \"class\", 49: \"CLASSENTITY_IDS\", 50: \"STYLECLASS\", 51: \"direction_tb\", 52: \"direction_bt\", 53: \"direction_rl\", 54: \"direction_lr\", 56: \";\", 57: \"EDGE_STATE\", 58: \"STYLE_SEPARATOR\", 59: \"left_of\", 60: \"right_of\" },\n productions_: [0, [3, 2], [3, 2], [3, 2], [7, 0], [7, 2], [8, 2], [8, 1], [8, 1], [9, 1], [9, 1], [9, 1], [9, 1], [9, 2], [9, 3], [9, 4], [9, 1], [9, 2], [9, 1], [9, 4], [9, 3], [9, 6], [9, 1], [9, 1], [9, 1], [9, 1], [9, 4], [9, 4], [9, 1], [9, 2], [9, 2], [9, 1], [9, 5], [9, 5], [10, 3], [10, 3], [11, 3], [12, 3], [32, 1], [32, 1], [32, 1], [32, 1], [55, 1], [55, 1], [13, 1], [13, 1], [13, 3], [13, 3], [30, 1], [30, 1]],\n performAction: /* @__PURE__ */ __name(function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$) {\n var $0 = $$.length - 1;\n switch (yystate) {\n case 3:\n yy.setRootDoc($$[$0]);\n return $$[$0];\n break;\n case 4:\n this.$ = [];\n break;\n case 5:\n if ($$[$0] != \"nl\") {\n $$[$0 - 1].push($$[$0]);\n this.$ = $$[$0 - 1];\n }\n break;\n case 6:\n case 7:\n this.$ = $$[$0];\n break;\n case 8:\n this.$ = \"nl\";\n break;\n case 12:\n this.$ = $$[$0];\n break;\n case 13:\n const stateStmt = $$[$0 - 1];\n stateStmt.description = yy.trimColon($$[$0]);\n this.$ = stateStmt;\n break;\n case 14:\n this.$ = { stmt: \"relation\", state1: $$[$0 - 2], state2: $$[$0] };\n break;\n case 15:\n const relDescription = yy.trimColon($$[$0]);\n this.$ = { stmt: \"relation\", state1: $$[$0 - 3], state2: $$[$0 - 1], description: relDescription };\n break;\n case 19:\n this.$ = { stmt: \"state\", id: $$[$0 - 3], type: \"default\", description: \"\", doc: $$[$0 - 1] };\n break;\n case 20:\n var id = $$[$0];\n var description = $$[$0 - 2].trim();\n if ($$[$0].match(\":\")) {\n var parts = $$[$0].split(\":\");\n id = parts[0];\n description = [description, parts[1]];\n }\n this.$ = { stmt: \"state\", id, type: \"default\", description };\n break;\n case 21:\n this.$ = { stmt: \"state\", id: $$[$0 - 3], type: \"default\", description: $$[$0 - 5], doc: $$[$0 - 1] };\n break;\n case 22:\n this.$ = { stmt: \"state\", id: $$[$0], type: \"fork\" };\n break;\n case 23:\n this.$ = { stmt: \"state\", id: $$[$0], type: \"join\" };\n break;\n case 24:\n this.$ = { stmt: \"state\", id: $$[$0], type: \"choice\" };\n break;\n case 25:\n this.$ = { stmt: \"state\", id: yy.getDividerId(), type: \"divider\" };\n break;\n case 26:\n this.$ = { stmt: \"state\", id: $$[$0 - 1].trim(), note: { position: $$[$0 - 2].trim(), text: $$[$0].trim() } };\n break;\n case 29:\n this.$ = $$[$0].trim();\n yy.setAccTitle(this.$);\n break;\n case 30:\n case 31:\n this.$ = $$[$0].trim();\n yy.setAccDescription(this.$);\n break;\n case 32:\n this.$ = {\n stmt: \"click\",\n id: $$[$0 - 3],\n url: $$[$0 - 2],\n tooltip: $$[$0 - 1]\n };\n break;\n case 33:\n this.$ = {\n stmt: \"click\",\n id: $$[$0 - 3],\n url: $$[$0 - 1],\n tooltip: \"\"\n };\n break;\n case 34:\n case 35:\n this.$ = { stmt: \"classDef\", id: $$[$0 - 1].trim(), classes: $$[$0].trim() };\n break;\n case 36:\n this.$ = { stmt: \"style\", id: $$[$0 - 1].trim(), styleClass: $$[$0].trim() };\n break;\n case 37:\n this.$ = { stmt: \"applyClass\", id: $$[$0 - 1].trim(), styleClass: $$[$0].trim() };\n break;\n case 38:\n yy.setDirection(\"TB\");\n this.$ = { stmt: \"dir\", value: \"TB\" };\n break;\n case 39:\n yy.setDirection(\"BT\");\n this.$ = { stmt: \"dir\", value: \"BT\" };\n break;\n case 40:\n yy.setDirection(\"RL\");\n this.$ = { stmt: \"dir\", value: \"RL\" };\n break;\n case 41:\n yy.setDirection(\"LR\");\n this.$ = { stmt: \"dir\", value: \"LR\" };\n break;\n case 44:\n case 45:\n this.$ = { stmt: \"state\", id: $$[$0].trim(), type: \"default\", description: \"\" };\n break;\n case 46:\n this.$ = { stmt: \"state\", id: $$[$0 - 2].trim(), classes: [$$[$0].trim()], type: \"default\", description: \"\" };\n break;\n case 47:\n this.$ = { stmt: \"state\", id: $$[$0 - 2].trim(), classes: [$$[$0].trim()], type: \"default\", description: \"\" };\n break;\n }\n }, \"anonymous\"),\n table: [{ 3: 1, 4: $V0, 5: $V1, 6: $V2 }, { 1: [3] }, { 3: 5, 4: $V0, 5: $V1, 6: $V2 }, { 3: 6, 4: $V0, 5: $V1, 6: $V2 }, o([1, 4, 5, 16, 17, 19, 22, 24, 25, 26, 27, 28, 29, 33, 35, 37, 38, 41, 45, 48, 51, 52, 53, 54, 57], $V3, { 7: 7 }), { 1: [2, 1] }, { 1: [2, 2] }, { 1: [2, 3], 4: $V4, 5: $V5, 8: 8, 9: 10, 10: 12, 11: 13, 12: 14, 13: 15, 16: $V6, 17: $V7, 19: $V8, 22: $V9, 24: $Va, 25: $Vb, 26: $Vc, 27: $Vd, 28: $Ve, 29: $Vf, 32: 25, 33: $Vg, 35: $Vh, 37: $Vi, 38: $Vj, 41: $Vk, 45: $Vl, 48: $Vm, 51: $Vn, 52: $Vo, 53: $Vp, 54: $Vq, 57: $Vr }, o($Vs, [2, 5]), { 9: 39, 10: 12, 11: 13, 12: 14, 13: 15, 16: $V6, 17: $V7, 19: $V8, 22: $V9, 24: $Va, 25: $Vb, 26: $Vc, 27: $Vd, 28: $Ve, 29: $Vf, 32: 25, 33: $Vg, 35: $Vh, 37: $Vi, 38: $Vj, 41: $Vk, 45: $Vl, 48: $Vm, 51: $Vn, 52: $Vo, 53: $Vp, 54: $Vq, 57: $Vr }, o($Vs, [2, 7]), o($Vs, [2, 8]), o($Vs, [2, 9]), o($Vs, [2, 10]), o($Vs, [2, 11]), o($Vs, [2, 12], { 14: [1, 40], 15: [1, 41] }), o($Vs, [2, 16]), { 18: [1, 42] }, o($Vs, [2, 18], { 20: [1, 43] }), { 23: [1, 44] }, o($Vs, [2, 22]), o($Vs, [2, 23]), o($Vs, [2, 24]), o($Vs, [2, 25]), { 30: 45, 31: [1, 46], 59: [1, 47], 60: [1, 48] }, o($Vs, [2, 28]), { 34: [1, 49] }, { 36: [1, 50] }, o($Vs, [2, 31]), { 13: 51, 24: $Va, 57: $Vr }, { 42: [1, 52], 44: [1, 53] }, { 46: [1, 54] }, { 49: [1, 55] }, o($Vt, [2, 44], { 58: [1, 56] }), o($Vt, [2, 45], { 58: [1, 57] }), o($Vs, [2, 38]), o($Vs, [2, 39]), o($Vs, [2, 40]), o($Vs, [2, 41]), o($Vs, [2, 6]), o($Vs, [2, 13]), { 13: 58, 24: $Va, 57: $Vr }, o($Vs, [2, 17]), o($Vu, $V3, { 7: 59 }), { 24: [1, 60] }, { 24: [1, 61] }, { 23: [1, 62] }, { 24: [2, 48] }, { 24: [2, 49] }, o($Vs, [2, 29]), o($Vs, [2, 30]), { 39: [1, 63], 40: [1, 64] }, { 43: [1, 65] }, { 43: [1, 66] }, { 47: [1, 67] }, { 50: [1, 68] }, { 24: [1, 69] }, { 24: [1, 70] }, o($Vs, [2, 14], { 14: [1, 71] }), { 4: $V4, 5: $V5, 8: 8, 9: 10, 10: 12, 11: 13, 12: 14, 13: 15, 16: $V6, 17: $V7, 19: $V8, 21: [1, 72], 22: $V9, 24: $Va, 25: $Vb, 26: $Vc, 27: $Vd, 28: $Ve, 29: $Vf, 32: 25, 33: $Vg, 35: $Vh, 37: $Vi, 38: $Vj, 41: $Vk, 45: $Vl, 48: $Vm, 51: $Vn, 52: $Vo, 53: $Vp, 54: $Vq, 57: $Vr }, o($Vs, [2, 20], { 20: [1, 73] }), { 31: [1, 74] }, { 24: [1, 75] }, { 39: [1, 76] }, { 39: [1, 77] }, o($Vs, [2, 34]), o($Vs, [2, 35]), o($Vs, [2, 36]), o($Vs, [2, 37]), o($Vt, [2, 46]), o($Vt, [2, 47]), o($Vs, [2, 15]), o($Vs, [2, 19]), o($Vu, $V3, { 7: 78 }), o($Vs, [2, 26]), o($Vs, [2, 27]), { 5: [1, 79] }, { 5: [1, 80] }, { 4: $V4, 5: $V5, 8: 8, 9: 10, 10: 12, 11: 13, 12: 14, 13: 15, 16: $V6, 17: $V7, 19: $V8, 21: [1, 81], 22: $V9, 24: $Va, 25: $Vb, 26: $Vc, 27: $Vd, 28: $Ve, 29: $Vf, 32: 25, 33: $Vg, 35: $Vh, 37: $Vi, 38: $Vj, 41: $Vk, 45: $Vl, 48: $Vm, 51: $Vn, 52: $Vo, 53: $Vp, 54: $Vq, 57: $Vr }, o($Vs, [2, 32]), o($Vs, [2, 33]), o($Vs, [2, 21])],\n defaultActions: { 5: [2, 1], 6: [2, 2], 47: [2, 48], 48: [2, 49] },\n parseError: /* @__PURE__ */ __name(function parseError(str, hash) {\n if (hash.recoverable) {\n this.trace(str);\n } else {\n var error = new Error(str);\n error.hash = hash;\n throw error;\n }\n }, \"parseError\"),\n parse: /* @__PURE__ */ __name(function parse(input) {\n var self = this, stack = [0], tstack = [], vstack = [null], lstack = [], table = this.table, yytext = \"\", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;\n var args = lstack.slice.call(arguments, 1);\n var lexer2 = Object.create(this.lexer);\n var sharedState = { yy: {} };\n for (var k in this.yy) {\n if (Object.prototype.hasOwnProperty.call(this.yy, k)) {\n sharedState.yy[k] = this.yy[k];\n }\n }\n lexer2.setInput(input, sharedState.yy);\n sharedState.yy.lexer = lexer2;\n sharedState.yy.parser = this;\n if (typeof lexer2.yylloc == \"undefined\") {\n lexer2.yylloc = {};\n }\n var yyloc = lexer2.yylloc;\n lstack.push(yyloc);\n var ranges = lexer2.options && lexer2.options.ranges;\n if (typeof sharedState.yy.parseError === \"function\") {\n this.parseError = sharedState.yy.parseError;\n } else {\n this.parseError = Object.getPrototypeOf(this).parseError;\n }\n function popStack(n) {\n stack.length = stack.length - 2 * n;\n vstack.length = vstack.length - n;\n lstack.length = lstack.length - n;\n }\n __name(popStack, \"popStack\");\n function lex() {\n var token;\n token = tstack.pop() || lexer2.lex() || EOF;\n if (typeof token !== \"number\") {\n if (token instanceof Array) {\n tstack = token;\n token = tstack.pop();\n }\n token = self.symbols_[token] || token;\n }\n return token;\n }\n __name(lex, \"lex\");\n var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;\n while (true) {\n state = stack[stack.length - 1];\n if (this.defaultActions[state]) {\n action = this.defaultActions[state];\n } else {\n if (symbol === null || typeof symbol == \"undefined\") {\n symbol = lex();\n }\n action = table[state] && table[state][symbol];\n }\n if (typeof action === \"undefined\" || !action.length || !action[0]) {\n var errStr = \"\";\n expected = [];\n for (p in table[state]) {\n if (this.terminals_[p] && p > TERROR) {\n expected.push(\"'\" + this.terminals_[p] + \"'\");\n }\n }\n if (lexer2.showPosition) {\n errStr = \"Parse error on line \" + (yylineno + 1) + \":\\n\" + lexer2.showPosition() + \"\\nExpecting \" + expected.join(\", \") + \", got '\" + (this.terminals_[symbol] || symbol) + \"'\";\n } else {\n errStr = \"Parse error on line \" + (yylineno + 1) + \": Unexpected \" + (symbol == EOF ? \"end of input\" : \"'\" + (this.terminals_[symbol] || symbol) + \"'\");\n }\n this.parseError(errStr, {\n text: lexer2.match,\n token: this.terminals_[symbol] || symbol,\n line: lexer2.yylineno,\n loc: yyloc,\n expected\n });\n }\n if (action[0] instanceof Array && action.length > 1) {\n throw new Error(\"Parse Error: multiple actions possible at state: \" + state + \", token: \" + symbol);\n }\n switch (action[0]) {\n case 1:\n stack.push(symbol);\n vstack.push(lexer2.yytext);\n lstack.push(lexer2.yylloc);\n stack.push(action[1]);\n symbol = null;\n if (!preErrorSymbol) {\n yyleng = lexer2.yyleng;\n yytext = lexer2.yytext;\n yylineno = lexer2.yylineno;\n yyloc = lexer2.yylloc;\n if (recovering > 0) {\n recovering--;\n }\n } else {\n symbol = preErrorSymbol;\n preErrorSymbol = null;\n }\n break;\n case 2:\n len = this.productions_[action[1]][1];\n yyval.$ = vstack[vstack.length - len];\n yyval._$ = {\n first_line: lstack[lstack.length - (len || 1)].first_line,\n last_line: lstack[lstack.length - 1].last_line,\n first_column: lstack[lstack.length - (len || 1)].first_column,\n last_column: lstack[lstack.length - 1].last_column\n };\n if (ranges) {\n yyval._$.range = [\n lstack[lstack.length - (len || 1)].range[0],\n lstack[lstack.length - 1].range[1]\n ];\n }\n r = this.performAction.apply(yyval, [\n yytext,\n yyleng,\n yylineno,\n sharedState.yy,\n action[1],\n vstack,\n lstack\n ].concat(args));\n if (typeof r !== \"undefined\") {\n return r;\n }\n if (len) {\n stack = stack.slice(0, -1 * len * 2);\n vstack = vstack.slice(0, -1 * len);\n lstack = lstack.slice(0, -1 * len);\n }\n stack.push(this.productions_[action[1]][0]);\n vstack.push(yyval.$);\n lstack.push(yyval._$);\n newState = table[stack[stack.length - 2]][stack[stack.length - 1]];\n stack.push(newState);\n break;\n case 3:\n return true;\n }\n }\n return true;\n }, \"parse\")\n };\n var lexer = /* @__PURE__ */ (function() {\n var lexer2 = {\n EOF: 1,\n parseError: /* @__PURE__ */ __name(function parseError(str, hash) {\n if (this.yy.parser) {\n this.yy.parser.parseError(str, hash);\n } else {\n throw new Error(str);\n }\n }, \"parseError\"),\n // resets the lexer, sets new input\n setInput: /* @__PURE__ */ __name(function(input, yy) {\n this.yy = yy || this.yy || {};\n this._input = input;\n this._more = this._backtrack = this.done = false;\n this.yylineno = this.yyleng = 0;\n this.yytext = this.matched = this.match = \"\";\n this.conditionStack = [\"INITIAL\"];\n this.yylloc = {\n first_line: 1,\n first_column: 0,\n last_line: 1,\n last_column: 0\n };\n if (this.options.ranges) {\n this.yylloc.range = [0, 0];\n }\n this.offset = 0;\n return this;\n }, \"setInput\"),\n // consumes and returns one char from the input\n input: /* @__PURE__ */ __name(function() {\n var ch = this._input[0];\n this.yytext += ch;\n this.yyleng++;\n this.offset++;\n this.match += ch;\n this.matched += ch;\n var lines = ch.match(/(?:\\r\\n?|\\n).*/g);\n if (lines) {\n this.yylineno++;\n this.yylloc.last_line++;\n } else {\n this.yylloc.last_column++;\n }\n if (this.options.ranges) {\n this.yylloc.range[1]++;\n }\n this._input = this._input.slice(1);\n return ch;\n }, \"input\"),\n // unshifts one char (or a string) into the input\n unput: /* @__PURE__ */ __name(function(ch) {\n var len = ch.length;\n var lines = ch.split(/(?:\\r\\n?|\\n)/g);\n this._input = ch + this._input;\n this.yytext = this.yytext.substr(0, this.yytext.length - len);\n this.offset -= len;\n var oldLines = this.match.split(/(?:\\r\\n?|\\n)/g);\n this.match = this.match.substr(0, this.match.length - 1);\n this.matched = this.matched.substr(0, this.matched.length - 1);\n if (lines.length - 1) {\n this.yylineno -= lines.length - 1;\n }\n var r = this.yylloc.range;\n this.yylloc = {\n first_line: this.yylloc.first_line,\n last_line: this.yylineno + 1,\n first_column: this.yylloc.first_column,\n last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len\n };\n if (this.options.ranges) {\n this.yylloc.range = [r[0], r[0] + this.yyleng - len];\n }\n this.yyleng = this.yytext.length;\n return this;\n }, \"unput\"),\n // When called from action, caches matched text and appends it on next action\n more: /* @__PURE__ */ __name(function() {\n this._more = true;\n return this;\n }, \"more\"),\n // When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead.\n reject: /* @__PURE__ */ __name(function() {\n if (this.options.backtrack_lexer) {\n this._backtrack = true;\n } else {\n return this.parseError(\"Lexical error on line \" + (this.yylineno + 1) + \". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\\n\" + this.showPosition(), {\n text: \"\",\n token: null,\n line: this.yylineno\n });\n }\n return this;\n }, \"reject\"),\n // retain first n characters of the match\n less: /* @__PURE__ */ __name(function(n) {\n this.unput(this.match.slice(n));\n }, \"less\"),\n // displays already matched input, i.e. for error messages\n pastInput: /* @__PURE__ */ __name(function() {\n var past = this.matched.substr(0, this.matched.length - this.match.length);\n return (past.length > 20 ? \"...\" : \"\") + past.substr(-20).replace(/\\n/g, \"\");\n }, \"pastInput\"),\n // displays upcoming input, i.e. for error messages\n upcomingInput: /* @__PURE__ */ __name(function() {\n var next = this.match;\n if (next.length < 20) {\n next += this._input.substr(0, 20 - next.length);\n }\n return (next.substr(0, 20) + (next.length > 20 ? \"...\" : \"\")).replace(/\\n/g, \"\");\n }, \"upcomingInput\"),\n // displays the character position where the lexing error occurred, i.e. for error messages\n showPosition: /* @__PURE__ */ __name(function() {\n var pre = this.pastInput();\n var c = new Array(pre.length + 1).join(\"-\");\n return pre + this.upcomingInput() + \"\\n\" + c + \"^\";\n }, \"showPosition\"),\n // test the lexed token: return FALSE when not a match, otherwise return token\n test_match: /* @__PURE__ */ __name(function(match, indexed_rule) {\n var token, lines, backup;\n if (this.options.backtrack_lexer) {\n backup = {\n yylineno: this.yylineno,\n yylloc: {\n first_line: this.yylloc.first_line,\n last_line: this.last_line,\n first_column: this.yylloc.first_column,\n last_column: this.yylloc.last_column\n },\n yytext: this.yytext,\n match: this.match,\n matches: this.matches,\n matched: this.matched,\n yyleng: this.yyleng,\n offset: this.offset,\n _more: this._more,\n _input: this._input,\n yy: this.yy,\n conditionStack: this.conditionStack.slice(0),\n done: this.done\n };\n if (this.options.ranges) {\n backup.yylloc.range = this.yylloc.range.slice(0);\n }\n }\n lines = match[0].match(/(?:\\r\\n?|\\n).*/g);\n if (lines) {\n this.yylineno += lines.length;\n }\n this.yylloc = {\n first_line: this.yylloc.last_line,\n last_line: this.yylineno + 1,\n first_column: this.yylloc.last_column,\n last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\\r?\\n?/)[0].length : this.yylloc.last_column + match[0].length\n };\n this.yytext += match[0];\n this.match += match[0];\n this.matches = match;\n this.yyleng = this.yytext.length;\n if (this.options.ranges) {\n this.yylloc.range = [this.offset, this.offset += this.yyleng];\n }\n this._more = false;\n this._backtrack = false;\n this._input = this._input.slice(match[0].length);\n this.matched += match[0];\n token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]);\n if (this.done && this._input) {\n this.done = false;\n }\n if (token) {\n return token;\n } else if (this._backtrack) {\n for (var k in backup) {\n this[k] = backup[k];\n }\n return false;\n }\n return false;\n }, \"test_match\"),\n // return next match in input\n next: /* @__PURE__ */ __name(function() {\n if (this.done) {\n return this.EOF;\n }\n if (!this._input) {\n this.done = true;\n }\n var token, match, tempMatch, index;\n if (!this._more) {\n this.yytext = \"\";\n this.match = \"\";\n }\n var rules = this._currentRules();\n for (var i = 0; i < rules.length; i++) {\n tempMatch = this._input.match(this.rules[rules[i]]);\n if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {\n match = tempMatch;\n index = i;\n if (this.options.backtrack_lexer) {\n token = this.test_match(tempMatch, rules[i]);\n if (token !== false) {\n return token;\n } else if (this._backtrack) {\n match = false;\n continue;\n } else {\n return false;\n }\n } else if (!this.options.flex) {\n break;\n }\n }\n }\n if (match) {\n token = this.test_match(match, rules[index]);\n if (token !== false) {\n return token;\n }\n return false;\n }\n if (this._input === \"\") {\n return this.EOF;\n } else {\n return this.parseError(\"Lexical error on line \" + (this.yylineno + 1) + \". Unrecognized text.\\n\" + this.showPosition(), {\n text: \"\",\n token: null,\n line: this.yylineno\n });\n }\n }, \"next\"),\n // return next match that has a token\n lex: /* @__PURE__ */ __name(function lex() {\n var r = this.next();\n if (r) {\n return r;\n } else {\n return this.lex();\n }\n }, \"lex\"),\n // activates a new lexer condition state (pushes the new lexer condition state onto the condition stack)\n begin: /* @__PURE__ */ __name(function begin(condition) {\n this.conditionStack.push(condition);\n }, \"begin\"),\n // pop the previously active lexer condition state off the condition stack\n popState: /* @__PURE__ */ __name(function popState() {\n var n = this.conditionStack.length - 1;\n if (n > 0) {\n return this.conditionStack.pop();\n } else {\n return this.conditionStack[0];\n }\n }, \"popState\"),\n // produce the lexer rule set which is active for the currently active lexer condition state\n _currentRules: /* @__PURE__ */ __name(function _currentRules() {\n if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) {\n return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;\n } else {\n return this.conditions[\"INITIAL\"].rules;\n }\n }, \"_currentRules\"),\n // return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available\n topState: /* @__PURE__ */ __name(function topState(n) {\n n = this.conditionStack.length - 1 - Math.abs(n || 0);\n if (n >= 0) {\n return this.conditionStack[n];\n } else {\n return \"INITIAL\";\n }\n }, \"topState\"),\n // alias for begin(condition)\n pushState: /* @__PURE__ */ __name(function pushState(condition) {\n this.begin(condition);\n }, \"pushState\"),\n // return the number of states currently on the stack\n stateStackSize: /* @__PURE__ */ __name(function stateStackSize() {\n return this.conditionStack.length;\n }, \"stateStackSize\"),\n options: { \"case-insensitive\": true },\n performAction: /* @__PURE__ */ __name(function anonymous(yy, yy_, $avoiding_name_collisions, YY_START) {\n var YYSTATE = YY_START;\n switch ($avoiding_name_collisions) {\n case 0:\n return 38;\n break;\n case 1:\n return 40;\n break;\n case 2:\n return 39;\n break;\n case 3:\n return 44;\n break;\n case 4:\n return 51;\n break;\n case 5:\n return 52;\n break;\n case 6:\n return 53;\n break;\n case 7:\n return 54;\n break;\n case 8:\n break;\n case 9:\n {\n }\n break;\n case 10:\n return 5;\n break;\n case 11:\n break;\n case 12:\n break;\n case 13:\n break;\n case 14:\n break;\n case 15:\n this.pushState(\"SCALE\");\n return 17;\n break;\n case 16:\n return 18;\n break;\n case 17:\n this.popState();\n break;\n case 18:\n this.begin(\"acc_title\");\n return 33;\n break;\n case 19:\n this.popState();\n return \"acc_title_value\";\n break;\n case 20:\n this.begin(\"acc_descr\");\n return 35;\n break;\n case 21:\n this.popState();\n return \"acc_descr_value\";\n break;\n case 22:\n this.begin(\"acc_descr_multiline\");\n break;\n case 23:\n this.popState();\n break;\n case 24:\n return \"acc_descr_multiline_value\";\n break;\n case 25:\n this.pushState(\"CLASSDEF\");\n return 41;\n break;\n case 26:\n this.popState();\n this.pushState(\"CLASSDEFID\");\n return \"DEFAULT_CLASSDEF_ID\";\n break;\n case 27:\n this.popState();\n this.pushState(\"CLASSDEFID\");\n return 42;\n break;\n case 28:\n this.popState();\n return 43;\n break;\n case 29:\n this.pushState(\"CLASS\");\n return 48;\n break;\n case 30:\n this.popState();\n this.pushState(\"CLASS_STYLE\");\n return 49;\n break;\n case 31:\n this.popState();\n return 50;\n break;\n case 32:\n this.pushState(\"STYLE\");\n return 45;\n break;\n case 33:\n this.popState();\n this.pushState(\"STYLEDEF_STYLES\");\n return 46;\n break;\n case 34:\n this.popState();\n return 47;\n break;\n case 35:\n this.pushState(\"SCALE\");\n return 17;\n break;\n case 36:\n return 18;\n break;\n case 37:\n this.popState();\n break;\n case 38:\n this.pushState(\"STATE\");\n break;\n case 39:\n this.popState();\n yy_.yytext = yy_.yytext.slice(0, -8).trim();\n return 25;\n break;\n case 40:\n this.popState();\n yy_.yytext = yy_.yytext.slice(0, -8).trim();\n return 26;\n break;\n case 41:\n this.popState();\n yy_.yytext = yy_.yytext.slice(0, -10).trim();\n return 27;\n break;\n case 42:\n this.popState();\n yy_.yytext = yy_.yytext.slice(0, -8).trim();\n return 25;\n break;\n case 43:\n this.popState();\n yy_.yytext = yy_.yytext.slice(0, -8).trim();\n return 26;\n break;\n case 44:\n this.popState();\n yy_.yytext = yy_.yytext.slice(0, -10).trim();\n return 27;\n break;\n case 45:\n return 51;\n break;\n case 46:\n return 52;\n break;\n case 47:\n return 53;\n break;\n case 48:\n return 54;\n break;\n case 49:\n this.pushState(\"STATE_STRING\");\n break;\n case 50:\n this.pushState(\"STATE_ID\");\n return \"AS\";\n break;\n case 51:\n this.popState();\n return \"ID\";\n break;\n case 52:\n this.popState();\n break;\n case 53:\n return \"STATE_DESCR\";\n break;\n case 54:\n return 19;\n break;\n case 55:\n this.popState();\n break;\n case 56:\n this.popState();\n this.pushState(\"struct\");\n return 20;\n break;\n case 57:\n break;\n case 58:\n this.popState();\n return 21;\n break;\n case 59:\n break;\n case 60:\n this.begin(\"NOTE\");\n return 29;\n break;\n case 61:\n this.popState();\n this.pushState(\"NOTE_ID\");\n return 59;\n break;\n case 62:\n this.popState();\n this.pushState(\"NOTE_ID\");\n return 60;\n break;\n case 63:\n this.popState();\n this.pushState(\"FLOATING_NOTE\");\n break;\n case 64:\n this.popState();\n this.pushState(\"FLOATING_NOTE_ID\");\n return \"AS\";\n break;\n case 65:\n break;\n case 66:\n return \"NOTE_TEXT\";\n break;\n case 67:\n this.popState();\n return \"ID\";\n break;\n case 68:\n this.popState();\n this.pushState(\"NOTE_TEXT\");\n return 24;\n break;\n case 69:\n this.popState();\n yy_.yytext = yy_.yytext.substr(2).trim();\n return 31;\n break;\n case 70:\n this.popState();\n yy_.yytext = yy_.yytext.slice(0, -8).trim();\n return 31;\n break;\n case 71:\n return 6;\n break;\n case 72:\n return 6;\n break;\n case 73:\n return 16;\n break;\n case 74:\n return 57;\n break;\n case 75:\n return 24;\n break;\n case 76:\n yy_.yytext = yy_.yytext.trim();\n return 14;\n break;\n case 77:\n return 15;\n break;\n case 78:\n return 28;\n break;\n case 79:\n return 58;\n break;\n case 80:\n return 5;\n break;\n case 81:\n return \"INVALID\";\n break;\n }\n }, \"anonymous\"),\n rules: [/^(?:click\\b)/i, /^(?:href\\b)/i, /^(?:\"[^\"]*\")/i, /^(?:default\\b)/i, /^(?:.*direction\\s+TB[^\\n]*)/i, /^(?:.*direction\\s+BT[^\\n]*)/i, /^(?:.*direction\\s+RL[^\\n]*)/i, /^(?:.*direction\\s+LR[^\\n]*)/i, /^(?:%%(?!\\{)[^\\n]*)/i, /^(?:[^\\}]%%[^\\n]*)/i, /^(?:[\\n]+)/i, /^(?:[\\s]+)/i, /^(?:((?!\\n)\\s)+)/i, /^(?:#[^\\n]*)/i, /^(?:%[^\\n]*)/i, /^(?:scale\\s+)/i, /^(?:\\d+)/i, /^(?:\\s+width\\b)/i, /^(?:accTitle\\s*:\\s*)/i, /^(?:(?!\\n||)*[^\\n]*)/i, /^(?:accDescr\\s*:\\s*)/i, /^(?:(?!\\n||)*[^\\n]*)/i, /^(?:accDescr\\s*\\{\\s*)/i, /^(?:[\\}])/i, /^(?:[^\\}]*)/i, /^(?:classDef\\s+)/i, /^(?:DEFAULT\\s+)/i, /^(?:\\w+\\s+)/i, /^(?:[^\\n]*)/i, /^(?:class\\s+)/i, /^(?:(\\w+)+((,\\s*\\w+)*))/i, /^(?:[^\\n]*)/i, /^(?:style\\s+)/i, /^(?:[\\w,]+\\s+)/i, /^(?:[^\\n]*)/i, /^(?:scale\\s+)/i, /^(?:\\d+)/i, /^(?:\\s+width\\b)/i, /^(?:state\\s+)/i, /^(?:.*<>)/i, /^(?:.*<>)/i, /^(?:.*<>)/i, /^(?:.*\\[\\[fork\\]\\])/i, /^(?:.*\\[\\[join\\]\\])/i, /^(?:.*\\[\\[choice\\]\\])/i, /^(?:.*direction\\s+TB[^\\n]*)/i, /^(?:.*direction\\s+BT[^\\n]*)/i, /^(?:.*direction\\s+RL[^\\n]*)/i, /^(?:.*direction\\s+LR[^\\n]*)/i, /^(?:[\"])/i, /^(?:\\s*as\\s+)/i, /^(?:[^\\n\\{]*)/i, /^(?:[\"])/i, /^(?:[^\"]*)/i, /^(?:[^\\n\\s\\{]+)/i, /^(?:\\n)/i, /^(?:\\{)/i, /^(?:%%(?!\\{)[^\\n]*)/i, /^(?:\\})/i, /^(?:[\\n])/i, /^(?:note\\s+)/i, /^(?:left of\\b)/i, /^(?:right of\\b)/i, /^(?:\")/i, /^(?:\\s*as\\s*)/i, /^(?:[\"])/i, /^(?:[^\"]*)/i, /^(?:[^\\n]*)/i, /^(?:\\s*[^:\\n\\s\\-]+)/i, /^(?:\\s*:[^:\\n;]+)/i, /^(?:[\\s\\S]*?end note\\b)/i, /^(?:stateDiagram\\s+)/i, /^(?:stateDiagram-v2\\s+)/i, /^(?:hide empty description\\b)/i, /^(?:\\[\\*\\])/i, /^(?:[^:\\n\\s\\-\\{]+)/i, /^(?:\\s*:[^:\\n;]+)/i, /^(?:-->)/i, /^(?:--)/i, /^(?::::)/i, /^(?:$)/i, /^(?:.)/i],\n conditions: { \"LINE\": { \"rules\": [12, 13], \"inclusive\": false }, \"struct\": { \"rules\": [12, 13, 25, 29, 32, 38, 45, 46, 47, 48, 57, 58, 59, 60, 74, 75, 76, 77, 78], \"inclusive\": false }, \"FLOATING_NOTE_ID\": { \"rules\": [67], \"inclusive\": false }, \"FLOATING_NOTE\": { \"rules\": [64, 65, 66], \"inclusive\": false }, \"NOTE_TEXT\": { \"rules\": [69, 70], \"inclusive\": false }, \"NOTE_ID\": { \"rules\": [68], \"inclusive\": false }, \"NOTE\": { \"rules\": [61, 62, 63], \"inclusive\": false }, \"STYLEDEF_STYLEOPTS\": { \"rules\": [], \"inclusive\": false }, \"STYLEDEF_STYLES\": { \"rules\": [34], \"inclusive\": false }, \"STYLE_IDS\": { \"rules\": [], \"inclusive\": false }, \"STYLE\": { \"rules\": [33], \"inclusive\": false }, \"CLASS_STYLE\": { \"rules\": [31], \"inclusive\": false }, \"CLASS\": { \"rules\": [30], \"inclusive\": false }, \"CLASSDEFID\": { \"rules\": [28], \"inclusive\": false }, \"CLASSDEF\": { \"rules\": [26, 27], \"inclusive\": false }, \"acc_descr_multiline\": { \"rules\": [23, 24], \"inclusive\": false }, \"acc_descr\": { \"rules\": [21], \"inclusive\": false }, \"acc_title\": { \"rules\": [19], \"inclusive\": false }, \"SCALE\": { \"rules\": [16, 17, 36, 37], \"inclusive\": false }, \"ALIAS\": { \"rules\": [], \"inclusive\": false }, \"STATE_ID\": { \"rules\": [51], \"inclusive\": false }, \"STATE_STRING\": { \"rules\": [52, 53], \"inclusive\": false }, \"FORK_STATE\": { \"rules\": [], \"inclusive\": false }, \"STATE\": { \"rules\": [12, 13, 39, 40, 41, 42, 43, 44, 49, 50, 54, 55, 56], \"inclusive\": false }, \"ID\": { \"rules\": [12, 13], \"inclusive\": false }, \"INITIAL\": { \"rules\": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 18, 20, 22, 25, 29, 32, 35, 38, 56, 60, 71, 72, 73, 74, 75, 76, 77, 79, 80, 81], \"inclusive\": true } }\n };\n return lexer2;\n })();\n parser2.lexer = lexer;\n function Parser() {\n this.yy = {};\n }\n __name(Parser, \"Parser\");\n Parser.prototype = parser2;\n parser2.Parser = Parser;\n return new Parser();\n})();\nparser.parser = parser;\nvar stateDiagram_default = parser;\n\n// src/diagrams/state/stateCommon.ts\nvar DEFAULT_DIAGRAM_DIRECTION = \"TB\";\nvar DEFAULT_NESTED_DOC_DIR = \"TB\";\nvar STMT_DIRECTION = \"dir\";\nvar STMT_STATE = \"state\";\nvar STMT_ROOT = \"root\";\nvar STMT_RELATION = \"relation\";\nvar STMT_CLASSDEF = \"classDef\";\nvar STMT_STYLEDEF = \"style\";\nvar STMT_APPLYCLASS = \"applyClass\";\nvar DEFAULT_STATE_TYPE = \"default\";\nvar DIVIDER_TYPE = \"divider\";\nvar G_EDGE_STYLE = \"fill:none\";\nvar G_EDGE_ARROWHEADSTYLE = \"fill: #333\";\nvar G_EDGE_LABELPOS = \"c\";\nvar G_EDGE_LABELTYPE = \"text\";\nvar G_EDGE_THICKNESS = \"normal\";\nvar SHAPE_STATE = \"rect\";\nvar SHAPE_STATE_WITH_DESC = \"rectWithTitle\";\nvar SHAPE_START = \"stateStart\";\nvar SHAPE_END = \"stateEnd\";\nvar SHAPE_DIVIDER = \"divider\";\nvar SHAPE_GROUP = \"roundedWithTitle\";\nvar SHAPE_NOTE = \"note\";\nvar SHAPE_NOTEGROUP = \"noteGroup\";\nvar CSS_DIAGRAM = \"statediagram\";\nvar CSS_STATE = \"state\";\nvar CSS_DIAGRAM_STATE = `${CSS_DIAGRAM}-${CSS_STATE}`;\nvar CSS_EDGE = \"transition\";\nvar CSS_NOTE = \"note\";\nvar CSS_NOTE_EDGE = \"note-edge\";\nvar CSS_EDGE_NOTE_EDGE = `${CSS_EDGE} ${CSS_NOTE_EDGE}`;\nvar CSS_DIAGRAM_NOTE = `${CSS_DIAGRAM}-${CSS_NOTE}`;\nvar CSS_CLUSTER = \"cluster\";\nvar CSS_DIAGRAM_CLUSTER = `${CSS_DIAGRAM}-${CSS_CLUSTER}`;\nvar CSS_CLUSTER_ALT = \"cluster-alt\";\nvar CSS_DIAGRAM_CLUSTER_ALT = `${CSS_DIAGRAM}-${CSS_CLUSTER_ALT}`;\nvar PARENT = \"parent\";\nvar NOTE = \"note\";\nvar DOMID_STATE = \"state\";\nvar DOMID_TYPE_SPACER = \"----\";\nvar NOTE_ID = `${DOMID_TYPE_SPACER}${NOTE}`;\nvar PARENT_ID = `${DOMID_TYPE_SPACER}${PARENT}`;\n\n// src/diagrams/state/stateRenderer-v3-unified.ts\nvar getDir = /* @__PURE__ */ __name((parsedItem, defaultDir = DEFAULT_NESTED_DOC_DIR) => {\n if (!parsedItem.doc) {\n return defaultDir;\n }\n let dir = defaultDir;\n for (const parsedItemDoc of parsedItem.doc) {\n if (parsedItemDoc.stmt === \"dir\") {\n dir = parsedItemDoc.value;\n }\n }\n return dir;\n}, \"getDir\");\nvar getClasses = /* @__PURE__ */ __name(function(text, diagramObj) {\n return diagramObj.db.getClasses();\n}, \"getClasses\");\nvar draw = /* @__PURE__ */ __name(async function(text, id, _version, diag) {\n log.info(\"REF0:\");\n log.info(\"Drawing state diagram (v2)\", id);\n const { securityLevel, state: conf, layout } = getConfig();\n diag.db.extract(diag.db.getRootDocV2());\n const data4Layout = diag.db.getData();\n const svg = getDiagramElement(id, securityLevel);\n data4Layout.type = diag.type;\n data4Layout.layoutAlgorithm = layout;\n data4Layout.nodeSpacing = conf?.nodeSpacing || 50;\n data4Layout.rankSpacing = conf?.rankSpacing || 50;\n data4Layout.markers = [\"barb\"];\n data4Layout.diagramId = id;\n await render(data4Layout, svg);\n const padding = 8;\n try {\n const links = typeof diag.db.getLinks === \"function\" ? diag.db.getLinks() : /* @__PURE__ */ new Map();\n links.forEach((linkInfo, key) => {\n const stateId = typeof key === \"string\" ? key : typeof key?.id === \"string\" ? key.id : \"\";\n if (!stateId) {\n log.warn(\"\\u26A0\\uFE0F Invalid or missing stateId from key:\", JSON.stringify(key));\n return;\n }\n const allNodes = svg.node()?.querySelectorAll(\"g\");\n let matchedElem;\n allNodes?.forEach((g) => {\n const text2 = g.textContent?.trim();\n if (text2 === stateId) {\n matchedElem = g;\n }\n });\n if (!matchedElem) {\n log.warn(\"\\u26A0\\uFE0F Could not find node matching text:\", stateId);\n return;\n }\n const parent = matchedElem.parentNode;\n if (!parent) {\n log.warn(\"\\u26A0\\uFE0F Node has no parent, cannot wrap:\", stateId);\n return;\n }\n const a = document.createElementNS(\"http://www.w3.org/2000/svg\", \"a\");\n const cleanedUrl = linkInfo.url.replace(/^\"+|\"+$/g, \"\");\n a.setAttributeNS(\"http://www.w3.org/1999/xlink\", \"xlink:href\", cleanedUrl);\n a.setAttribute(\"target\", \"_blank\");\n if (linkInfo.tooltip) {\n const tooltip = linkInfo.tooltip.replace(/^\"+|\"+$/g, \"\");\n a.setAttribute(\"title\", tooltip);\n }\n parent.replaceChild(a, matchedElem);\n a.appendChild(matchedElem);\n log.info(\"\\u{1F517} Wrapped node in tag for:\", stateId, linkInfo.url);\n });\n } catch (err) {\n log.error(\"\\u274C Error injecting clickable links:\", err);\n }\n utils_default.insertTitle(\n svg,\n \"statediagramTitleText\",\n conf?.titleTopMargin ?? 25,\n diag.db.getDiagramTitle()\n );\n setupViewPortForSVG(svg, padding, CSS_DIAGRAM, conf?.useMaxWidth ?? true);\n}, \"draw\");\nvar stateRenderer_v3_unified_default = {\n getClasses,\n draw,\n getDir\n};\n\n// src/diagrams/state/dataFetcher.ts\nvar nodeDb = /* @__PURE__ */ new Map();\nvar graphItemCount = 0;\nfunction stateDomId(itemId = \"\", counter = 0, type = \"\", typeSpacer = DOMID_TYPE_SPACER) {\n const typeStr = type !== null && type.length > 0 ? `${typeSpacer}${type}` : \"\";\n return `${DOMID_STATE}-${itemId}${typeStr}-${counter}`;\n}\n__name(stateDomId, \"stateDomId\");\nvar setupDoc = /* @__PURE__ */ __name((parentParsedItem, doc, diagramStates, nodes, edges, altFlag, look, classes) => {\n log.trace(\"items\", doc);\n doc.forEach((item) => {\n switch (item.stmt) {\n case STMT_STATE:\n dataFetcher(parentParsedItem, item, diagramStates, nodes, edges, altFlag, look, classes);\n break;\n case DEFAULT_STATE_TYPE:\n dataFetcher(parentParsedItem, item, diagramStates, nodes, edges, altFlag, look, classes);\n break;\n case STMT_RELATION:\n {\n dataFetcher(\n parentParsedItem,\n item.state1,\n diagramStates,\n nodes,\n edges,\n altFlag,\n look,\n classes\n );\n dataFetcher(\n parentParsedItem,\n item.state2,\n diagramStates,\n nodes,\n edges,\n altFlag,\n look,\n classes\n );\n const edgeData = {\n id: \"edge\" + graphItemCount,\n start: item.state1.id,\n end: item.state2.id,\n arrowhead: \"normal\",\n arrowTypeEnd: \"arrow_barb\",\n style: G_EDGE_STYLE,\n labelStyle: \"\",\n label: common_default.sanitizeText(item.description ?? \"\", getConfig()),\n arrowheadStyle: G_EDGE_ARROWHEADSTYLE,\n labelpos: G_EDGE_LABELPOS,\n labelType: G_EDGE_LABELTYPE,\n thickness: G_EDGE_THICKNESS,\n classes: CSS_EDGE,\n look\n };\n edges.push(edgeData);\n graphItemCount++;\n }\n break;\n }\n });\n}, \"setupDoc\");\nvar getDir2 = /* @__PURE__ */ __name((parsedItem, defaultDir = DEFAULT_NESTED_DOC_DIR) => {\n let dir = defaultDir;\n if (parsedItem.doc) {\n for (const parsedItemDoc of parsedItem.doc) {\n if (parsedItemDoc.stmt === \"dir\") {\n dir = parsedItemDoc.value;\n }\n }\n }\n return dir;\n}, \"getDir\");\nfunction insertOrUpdateNode(nodes, nodeData, classes) {\n if (!nodeData.id || nodeData.id === \"\" || nodeData.id === \"\") {\n return;\n }\n if (nodeData.cssClasses) {\n if (!Array.isArray(nodeData.cssCompiledStyles)) {\n nodeData.cssCompiledStyles = [];\n }\n nodeData.cssClasses.split(\" \").forEach((cssClass) => {\n const classDef = classes.get(cssClass);\n if (classDef) {\n nodeData.cssCompiledStyles = [...nodeData.cssCompiledStyles ?? [], ...classDef.styles];\n }\n });\n }\n const existingNodeData = nodes.find((node) => node.id === nodeData.id);\n if (existingNodeData) {\n Object.assign(existingNodeData, nodeData);\n } else {\n nodes.push(nodeData);\n }\n}\n__name(insertOrUpdateNode, \"insertOrUpdateNode\");\nfunction getClassesFromDbInfo(dbInfoItem) {\n return dbInfoItem?.classes?.join(\" \") ?? \"\";\n}\n__name(getClassesFromDbInfo, \"getClassesFromDbInfo\");\nfunction getStylesFromDbInfo(dbInfoItem) {\n return dbInfoItem?.styles ?? [];\n}\n__name(getStylesFromDbInfo, \"getStylesFromDbInfo\");\nvar dataFetcher = /* @__PURE__ */ __name((parent, parsedItem, diagramStates, nodes, edges, altFlag, look, classes) => {\n const itemId = parsedItem.id;\n const dbState = diagramStates.get(itemId);\n const classStr = getClassesFromDbInfo(dbState);\n const style = getStylesFromDbInfo(dbState);\n const config = getConfig();\n log.info(\"dataFetcher parsedItem\", parsedItem, dbState, style);\n if (itemId !== \"root\") {\n let shape = SHAPE_STATE;\n if (parsedItem.start === true) {\n shape = SHAPE_START;\n } else if (parsedItem.start === false) {\n shape = SHAPE_END;\n }\n if (parsedItem.type !== DEFAULT_STATE_TYPE) {\n shape = parsedItem.type;\n }\n if (!nodeDb.get(itemId)) {\n nodeDb.set(itemId, {\n id: itemId,\n shape,\n description: common_default.sanitizeText(itemId, config),\n cssClasses: `${classStr} ${CSS_DIAGRAM_STATE}`,\n cssStyles: style\n });\n }\n const newNode = nodeDb.get(itemId);\n if (parsedItem.description) {\n if (Array.isArray(newNode.description)) {\n newNode.shape = SHAPE_STATE_WITH_DESC;\n newNode.description.push(parsedItem.description);\n } else {\n if (newNode.description?.length && newNode.description.length > 0) {\n newNode.shape = SHAPE_STATE_WITH_DESC;\n if (newNode.description === itemId) {\n newNode.description = [parsedItem.description];\n } else {\n newNode.description = [newNode.description, parsedItem.description];\n }\n } else {\n newNode.shape = SHAPE_STATE;\n newNode.description = parsedItem.description;\n }\n }\n newNode.description = common_default.sanitizeTextOrArray(newNode.description, config);\n }\n if (newNode.description?.length === 1 && newNode.shape === SHAPE_STATE_WITH_DESC) {\n if (newNode.type === \"group\") {\n newNode.shape = SHAPE_GROUP;\n } else {\n newNode.shape = SHAPE_STATE;\n }\n }\n if (!newNode.type && parsedItem.doc) {\n log.info(\"Setting cluster for XCX\", itemId, getDir2(parsedItem));\n newNode.type = \"group\";\n newNode.isGroup = true;\n newNode.dir = getDir2(parsedItem);\n newNode.shape = parsedItem.type === DIVIDER_TYPE ? SHAPE_DIVIDER : SHAPE_GROUP;\n newNode.cssClasses = `${newNode.cssClasses} ${CSS_DIAGRAM_CLUSTER} ${altFlag ? CSS_DIAGRAM_CLUSTER_ALT : \"\"}`;\n }\n const nodeData = {\n labelStyle: \"\",\n shape: newNode.shape,\n label: newNode.description,\n cssClasses: newNode.cssClasses,\n cssCompiledStyles: [],\n cssStyles: newNode.cssStyles,\n id: itemId,\n dir: newNode.dir,\n domId: stateDomId(itemId, graphItemCount),\n type: newNode.type,\n isGroup: newNode.type === \"group\",\n padding: 8,\n rx: 10,\n ry: 10,\n look\n };\n if (nodeData.shape === SHAPE_DIVIDER) {\n nodeData.label = \"\";\n }\n if (parent && parent.id !== \"root\") {\n log.trace(\"Setting node \", itemId, \" to be child of its parent \", parent.id);\n nodeData.parentId = parent.id;\n }\n nodeData.centerLabel = true;\n if (parsedItem.note) {\n const noteData = {\n labelStyle: \"\",\n shape: SHAPE_NOTE,\n label: parsedItem.note.text,\n cssClasses: CSS_DIAGRAM_NOTE,\n // useHtmlLabels: false,\n cssStyles: [],\n cssCompiledStyles: [],\n id: itemId + NOTE_ID + \"-\" + graphItemCount,\n domId: stateDomId(itemId, graphItemCount, NOTE),\n type: newNode.type,\n isGroup: newNode.type === \"group\",\n padding: config.flowchart?.padding,\n look,\n position: parsedItem.note.position\n };\n const parentNodeId = itemId + PARENT_ID;\n const groupData = {\n labelStyle: \"\",\n shape: SHAPE_NOTEGROUP,\n label: parsedItem.note.text,\n cssClasses: newNode.cssClasses,\n cssStyles: [],\n id: itemId + PARENT_ID,\n domId: stateDomId(itemId, graphItemCount, PARENT),\n type: \"group\",\n isGroup: true,\n padding: 16,\n //getConfig().flowchart.padding\n look,\n position: parsedItem.note.position\n };\n graphItemCount++;\n groupData.id = parentNodeId;\n noteData.parentId = parentNodeId;\n insertOrUpdateNode(nodes, groupData, classes);\n insertOrUpdateNode(nodes, noteData, classes);\n insertOrUpdateNode(nodes, nodeData, classes);\n let from = itemId;\n let to = noteData.id;\n if (parsedItem.note.position === \"left of\") {\n from = noteData.id;\n to = itemId;\n }\n edges.push({\n id: from + \"-\" + to,\n start: from,\n end: to,\n arrowhead: \"none\",\n arrowTypeEnd: \"\",\n style: G_EDGE_STYLE,\n labelStyle: \"\",\n classes: CSS_EDGE_NOTE_EDGE,\n arrowheadStyle: G_EDGE_ARROWHEADSTYLE,\n labelpos: G_EDGE_LABELPOS,\n labelType: G_EDGE_LABELTYPE,\n thickness: G_EDGE_THICKNESS,\n look\n });\n } else {\n insertOrUpdateNode(nodes, nodeData, classes);\n }\n }\n if (parsedItem.doc) {\n log.trace(\"Adding nodes children \");\n setupDoc(parsedItem, parsedItem.doc, diagramStates, nodes, edges, !altFlag, look, classes);\n }\n}, \"dataFetcher\");\nvar reset = /* @__PURE__ */ __name(() => {\n nodeDb.clear();\n graphItemCount = 0;\n}, \"reset\");\n\n// src/diagrams/state/stateDb.ts\nvar CONSTANTS = {\n START_NODE: \"[*]\",\n START_TYPE: \"start\",\n END_NODE: \"[*]\",\n END_TYPE: \"end\",\n COLOR_KEYWORD: \"color\",\n FILL_KEYWORD: \"fill\",\n BG_FILL: \"bgFill\",\n STYLECLASS_SEP: \",\"\n};\nvar newClassesList = /* @__PURE__ */ __name(() => /* @__PURE__ */ new Map(), \"newClassesList\");\nvar newDoc = /* @__PURE__ */ __name(() => ({\n relations: [],\n states: /* @__PURE__ */ new Map(),\n documents: {}\n}), \"newDoc\");\nvar clone = /* @__PURE__ */ __name((o) => JSON.parse(JSON.stringify(o)), \"clone\");\nvar StateDB = class {\n constructor(version) {\n this.version = version;\n this.nodes = [];\n this.edges = [];\n this.rootDoc = [];\n this.classes = newClassesList();\n this.documents = { root: newDoc() };\n this.currentDocument = this.documents.root;\n this.startEndCount = 0;\n this.dividerCnt = 0;\n this.links = /* @__PURE__ */ new Map();\n this.getAccTitle = getAccTitle;\n this.setAccTitle = setAccTitle;\n this.getAccDescription = getAccDescription;\n this.setAccDescription = setAccDescription;\n this.setDiagramTitle = setDiagramTitle;\n this.getDiagramTitle = getDiagramTitle;\n this.clear();\n this.setRootDoc = this.setRootDoc.bind(this);\n this.getDividerId = this.getDividerId.bind(this);\n this.setDirection = this.setDirection.bind(this);\n this.trimColon = this.trimColon.bind(this);\n }\n static {\n __name(this, \"StateDB\");\n }\n static {\n this.relationType = {\n AGGREGATION: 0,\n EXTENSION: 1,\n COMPOSITION: 2,\n DEPENDENCY: 3\n };\n }\n /**\n * Convert all of the statements (stmts) that were parsed into states and relationships.\n * This is done because a state diagram may have nested sections,\n * where each section is a 'document' and has its own set of statements.\n * Ex: the section within a fork has its own statements, and incoming and outgoing statements\n * refer to the fork as a whole (document).\n * See the parser grammar: the definition of a document is a document then a 'line', where a line can be a statement.\n * This will push the statement into the list of statements for the current document.\n */\n extract(statements) {\n this.clear(true);\n for (const item of Array.isArray(statements) ? statements : statements.doc) {\n switch (item.stmt) {\n case STMT_STATE:\n this.addState(item.id.trim(), item.type, item.doc, item.description, item.note);\n break;\n case STMT_RELATION:\n this.addRelation(item.state1, item.state2, item.description);\n break;\n case STMT_CLASSDEF:\n this.addStyleClass(item.id.trim(), item.classes);\n break;\n case STMT_STYLEDEF:\n this.handleStyleDef(item);\n break;\n case STMT_APPLYCLASS:\n this.setCssClass(item.id.trim(), item.styleClass);\n break;\n case \"click\":\n this.addLink(item.id, item.url, item.tooltip);\n break;\n }\n }\n const diagramStates = this.getStates();\n const config = getConfig();\n reset();\n dataFetcher(\n void 0,\n this.getRootDocV2(),\n diagramStates,\n this.nodes,\n this.edges,\n true,\n config.look,\n this.classes\n );\n for (const node of this.nodes) {\n if (!Array.isArray(node.label)) {\n continue;\n }\n node.description = node.label.slice(1);\n if (node.isGroup && node.description.length > 0) {\n throw new Error(\n `Group nodes can only have label. Remove the additional description for node [${node.id}]`\n );\n }\n node.label = node.label[0];\n }\n }\n handleStyleDef(item) {\n const ids = item.id.trim().split(\",\");\n const styles = item.styleClass.split(\",\");\n for (const id of ids) {\n let state = this.getState(id);\n if (!state) {\n const trimmedId = id.trim();\n this.addState(trimmedId);\n state = this.getState(trimmedId);\n }\n if (state) {\n state.styles = styles.map((s) => s.replace(/;/g, \"\")?.trim());\n }\n }\n }\n setRootDoc(o) {\n log.info(\"Setting root doc\", o);\n this.rootDoc = o;\n if (this.version === 1) {\n this.extract(o);\n } else {\n this.extract(this.getRootDocV2());\n }\n }\n docTranslator(parent, node, first) {\n if (node.stmt === STMT_RELATION) {\n this.docTranslator(parent, node.state1, true);\n this.docTranslator(parent, node.state2, false);\n return;\n }\n if (node.stmt === STMT_STATE) {\n if (node.id === CONSTANTS.START_NODE) {\n node.id = parent.id + (first ? \"_start\" : \"_end\");\n node.start = first;\n } else {\n node.id = node.id.trim();\n }\n }\n if (node.stmt !== STMT_ROOT && node.stmt !== STMT_STATE || !node.doc) {\n return;\n }\n const doc = [];\n let currentDoc = [];\n for (const stmt of node.doc) {\n if (stmt.type === DIVIDER_TYPE) {\n const newNode = clone(stmt);\n newNode.doc = clone(currentDoc);\n doc.push(newNode);\n currentDoc = [];\n } else {\n currentDoc.push(stmt);\n }\n }\n if (doc.length > 0 && currentDoc.length > 0) {\n const newNode = {\n stmt: STMT_STATE,\n id: generateId(),\n type: \"divider\",\n doc: clone(currentDoc)\n };\n doc.push(clone(newNode));\n node.doc = doc;\n }\n node.doc.forEach((docNode) => this.docTranslator(node, docNode, true));\n }\n getRootDocV2() {\n this.docTranslator(\n { id: STMT_ROOT, stmt: STMT_ROOT },\n { id: STMT_ROOT, stmt: STMT_ROOT, doc: this.rootDoc },\n true\n );\n return { id: STMT_ROOT, doc: this.rootDoc };\n }\n /**\n * Function called by parser when a node definition has been found.\n *\n * @param descr - description for the state. Can be a string or a list or strings\n * @param classes - class styles to apply to this state. Can be a string (1 style) or an array of styles. If it's just 1 class, convert it to an array of that 1 class.\n * @param styles - styles to apply to this state. Can be a string (1 style) or an array of styles. If it's just 1 style, convert it to an array of that 1 style.\n * @param textStyles - text styles to apply to this state. Can be a string (1 text test) or an array of text styles. If it's just 1 text style, convert it to an array of that 1 text style.\n */\n addState(id, type = DEFAULT_STATE_TYPE, doc = void 0, descr = void 0, note = void 0, classes = void 0, styles = void 0, textStyles = void 0) {\n const trimmedId = id?.trim();\n if (!this.currentDocument.states.has(trimmedId)) {\n log.info(\"Adding state \", trimmedId, descr);\n this.currentDocument.states.set(trimmedId, {\n stmt: STMT_STATE,\n id: trimmedId,\n descriptions: [],\n type,\n doc,\n note,\n classes: [],\n styles: [],\n textStyles: []\n });\n } else {\n const state = this.currentDocument.states.get(trimmedId);\n if (!state) {\n throw new Error(`State not found: ${trimmedId}`);\n }\n if (!state.doc) {\n state.doc = doc;\n }\n if (!state.type) {\n state.type = type;\n }\n }\n if (descr) {\n log.info(\"Setting state description\", trimmedId, descr);\n const descriptions = Array.isArray(descr) ? descr : [descr];\n descriptions.forEach((des) => this.addDescription(trimmedId, des.trim()));\n }\n if (note) {\n const doc2 = this.currentDocument.states.get(trimmedId);\n if (!doc2) {\n throw new Error(`State not found: ${trimmedId}`);\n }\n doc2.note = note;\n doc2.note.text = common_default.sanitizeText(doc2.note.text, getConfig());\n }\n if (classes) {\n log.info(\"Setting state classes\", trimmedId, classes);\n const classesList = Array.isArray(classes) ? classes : [classes];\n classesList.forEach((cssClass) => this.setCssClass(trimmedId, cssClass.trim()));\n }\n if (styles) {\n log.info(\"Setting state styles\", trimmedId, styles);\n const stylesList = Array.isArray(styles) ? styles : [styles];\n stylesList.forEach((style) => this.setStyle(trimmedId, style.trim()));\n }\n if (textStyles) {\n log.info(\"Setting state styles\", trimmedId, styles);\n const textStylesList = Array.isArray(textStyles) ? textStyles : [textStyles];\n textStylesList.forEach((textStyle) => this.setTextStyle(trimmedId, textStyle.trim()));\n }\n }\n clear(saveCommon) {\n this.nodes = [];\n this.edges = [];\n this.documents = { root: newDoc() };\n this.currentDocument = this.documents.root;\n this.startEndCount = 0;\n this.classes = newClassesList();\n if (!saveCommon) {\n this.links = /* @__PURE__ */ new Map();\n clear();\n }\n }\n getState(id) {\n return this.currentDocument.states.get(id);\n }\n getStates() {\n return this.currentDocument.states;\n }\n logDocuments() {\n log.info(\"Documents = \", this.documents);\n }\n getRelations() {\n return this.currentDocument.relations;\n }\n /**\n * Adds a clickable link to a state.\n */\n addLink(stateId, url, tooltip) {\n this.links.set(stateId, { url, tooltip });\n log.warn(\"Adding link\", stateId, url, tooltip);\n }\n /**\n * Get all registered links.\n */\n getLinks() {\n return this.links;\n }\n /**\n * If the id is a start node ( [*] ), then return a new id constructed from\n * the start node name and the current start node count.\n * else return the given id\n */\n startIdIfNeeded(id = \"\") {\n if (id === CONSTANTS.START_NODE) {\n this.startEndCount++;\n return `${CONSTANTS.START_TYPE}${this.startEndCount}`;\n }\n return id;\n }\n /**\n * If the id is a start node ( [*] ), then return the start type ('start')\n * else return the given type\n */\n startTypeIfNeeded(id = \"\", type = DEFAULT_STATE_TYPE) {\n return id === CONSTANTS.START_NODE ? CONSTANTS.START_TYPE : type;\n }\n /**\n * If the id is an end node ( [*] ), then return a new id constructed from\n * the end node name and the current start_end node count.\n * else return the given id\n */\n endIdIfNeeded(id = \"\") {\n if (id === CONSTANTS.END_NODE) {\n this.startEndCount++;\n return `${CONSTANTS.END_TYPE}${this.startEndCount}`;\n }\n return id;\n }\n /**\n * If the id is an end node ( [*] ), then return the end type\n * else return the given type\n *\n */\n endTypeIfNeeded(id = \"\", type = DEFAULT_STATE_TYPE) {\n return id === CONSTANTS.END_NODE ? CONSTANTS.END_TYPE : type;\n }\n addRelationObjs(item1, item2, relationTitle = \"\") {\n const id1 = this.startIdIfNeeded(item1.id.trim());\n const type1 = this.startTypeIfNeeded(item1.id.trim(), item1.type);\n const id2 = this.startIdIfNeeded(item2.id.trim());\n const type2 = this.startTypeIfNeeded(item2.id.trim(), item2.type);\n this.addState(\n id1,\n type1,\n item1.doc,\n item1.description,\n item1.note,\n item1.classes,\n item1.styles,\n item1.textStyles\n );\n this.addState(\n id2,\n type2,\n item2.doc,\n item2.description,\n item2.note,\n item2.classes,\n item2.styles,\n item2.textStyles\n );\n this.currentDocument.relations.push({\n id1,\n id2,\n relationTitle: common_default.sanitizeText(relationTitle, getConfig())\n });\n }\n /**\n * Add a relation between two items. The items may be full objects or just the string id of a state.\n */\n addRelation(item1, item2, title) {\n if (typeof item1 === \"object\" && typeof item2 === \"object\") {\n this.addRelationObjs(item1, item2, title);\n } else if (typeof item1 === \"string\" && typeof item2 === \"string\") {\n const id1 = this.startIdIfNeeded(item1.trim());\n const type1 = this.startTypeIfNeeded(item1);\n const id2 = this.endIdIfNeeded(item2.trim());\n const type2 = this.endTypeIfNeeded(item2);\n this.addState(id1, type1);\n this.addState(id2, type2);\n this.currentDocument.relations.push({\n id1,\n id2,\n relationTitle: title ? common_default.sanitizeText(title, getConfig()) : void 0\n });\n }\n }\n addDescription(id, descr) {\n const theState = this.currentDocument.states.get(id);\n const _descr = descr.startsWith(\":\") ? descr.replace(\":\", \"\").trim() : descr;\n theState?.descriptions?.push(common_default.sanitizeText(_descr, getConfig()));\n }\n cleanupLabel(label) {\n return label.startsWith(\":\") ? label.slice(2).trim() : label.trim();\n }\n getDividerId() {\n this.dividerCnt++;\n return `divider-id-${this.dividerCnt}`;\n }\n /**\n * Called when the parser comes across a (style) class definition\n * @example classDef my-style fill:#f96;\n *\n * @param id - the id of this (style) class\n * @param styleAttributes - the string with 1 or more style attributes (each separated by a comma)\n */\n addStyleClass(id, styleAttributes = \"\") {\n if (!this.classes.has(id)) {\n this.classes.set(id, { id, styles: [], textStyles: [] });\n }\n const foundClass = this.classes.get(id);\n if (styleAttributes && foundClass) {\n styleAttributes.split(CONSTANTS.STYLECLASS_SEP).forEach((attrib) => {\n const fixedAttrib = attrib.replace(/([^;]*);/, \"$1\").trim();\n if (RegExp(CONSTANTS.COLOR_KEYWORD).exec(attrib)) {\n const newStyle1 = fixedAttrib.replace(CONSTANTS.FILL_KEYWORD, CONSTANTS.BG_FILL);\n const newStyle2 = newStyle1.replace(CONSTANTS.COLOR_KEYWORD, CONSTANTS.FILL_KEYWORD);\n foundClass.textStyles.push(newStyle2);\n }\n foundClass.styles.push(fixedAttrib);\n });\n }\n }\n getClasses() {\n return this.classes;\n }\n /**\n * Add a (style) class or css class to a state with the given id.\n * If the state isn't already in the list of known states, add it.\n * Might be called by parser when a style class or CSS class should be applied to a state\n *\n * @param itemIds - The id or a list of ids of the item(s) to apply the css class to\n * @param cssClassName - CSS class name\n */\n setCssClass(itemIds, cssClassName) {\n itemIds.split(\",\").forEach((id) => {\n let foundState = this.getState(id);\n if (!foundState) {\n const trimmedId = id.trim();\n this.addState(trimmedId);\n foundState = this.getState(trimmedId);\n }\n foundState?.classes?.push(cssClassName);\n });\n }\n /**\n * Add a style to a state with the given id.\n * @example style stateId fill:#f9f,stroke:#333,stroke-width:4px\n * where 'style' is the keyword\n * stateId is the id of a state\n * the rest of the string is the styleText (all of the attributes to be applied to the state)\n *\n * @param itemId - The id of item to apply the style to\n * @param styleText - the text of the attributes for the style\n */\n setStyle(itemId, styleText) {\n this.getState(itemId)?.styles?.push(styleText);\n }\n /**\n * Add a text style to a state with the given id\n *\n * @param itemId - The id of item to apply the css class to\n * @param cssClassName - CSS class name\n */\n setTextStyle(itemId, cssClassName) {\n this.getState(itemId)?.textStyles?.push(cssClassName);\n }\n /**\n * Finds the direction statement in the root document.\n * @returns the direction statement if present\n */\n getDirectionStatement() {\n return this.rootDoc.find((doc) => doc.stmt === STMT_DIRECTION);\n }\n getDirection() {\n return this.getDirectionStatement()?.value ?? DEFAULT_DIAGRAM_DIRECTION;\n }\n setDirection(dir) {\n const doc = this.getDirectionStatement();\n if (doc) {\n doc.value = dir;\n } else {\n this.rootDoc.unshift({ stmt: STMT_DIRECTION, value: dir });\n }\n }\n trimColon(str) {\n return str.startsWith(\":\") ? str.slice(1).trim() : str.trim();\n }\n getData() {\n const config = getConfig();\n return {\n nodes: this.nodes,\n edges: this.edges,\n other: {},\n config,\n direction: getDir(this.getRootDocV2())\n };\n }\n getConfig() {\n return getConfig().state;\n }\n};\n\n// src/diagrams/state/styles.js\nvar getStyles = /* @__PURE__ */ __name((options) => `\ndefs #statediagram-barbEnd {\n fill: ${options.transitionColor};\n stroke: ${options.transitionColor};\n }\ng.stateGroup text {\n fill: ${options.nodeBorder};\n stroke: none;\n font-size: 10px;\n}\ng.stateGroup text {\n fill: ${options.textColor};\n stroke: none;\n font-size: 10px;\n\n}\ng.stateGroup .state-title {\n font-weight: bolder;\n fill: ${options.stateLabelColor};\n}\n\ng.stateGroup rect {\n fill: ${options.mainBkg};\n stroke: ${options.nodeBorder};\n}\n\ng.stateGroup line {\n stroke: ${options.lineColor};\n stroke-width: 1;\n}\n\n.transition {\n stroke: ${options.transitionColor};\n stroke-width: 1;\n fill: none;\n}\n\n.stateGroup .composit {\n fill: ${options.background};\n border-bottom: 1px\n}\n\n.stateGroup .alt-composit {\n fill: #e0e0e0;\n border-bottom: 1px\n}\n\n.state-note {\n stroke: ${options.noteBorderColor};\n fill: ${options.noteBkgColor};\n\n text {\n fill: ${options.noteTextColor};\n stroke: none;\n font-size: 10px;\n }\n}\n\n.stateLabel .box {\n stroke: none;\n stroke-width: 0;\n fill: ${options.mainBkg};\n opacity: 0.5;\n}\n\n.edgeLabel .label rect {\n fill: ${options.labelBackgroundColor};\n opacity: 0.5;\n}\n.edgeLabel {\n background-color: ${options.edgeLabelBackground};\n p {\n background-color: ${options.edgeLabelBackground};\n }\n rect {\n opacity: 0.5;\n background-color: ${options.edgeLabelBackground};\n fill: ${options.edgeLabelBackground};\n }\n text-align: center;\n}\n.edgeLabel .label text {\n fill: ${options.transitionLabelColor || options.tertiaryTextColor};\n}\n.label div .edgeLabel {\n color: ${options.transitionLabelColor || options.tertiaryTextColor};\n}\n\n.stateLabel text {\n fill: ${options.stateLabelColor};\n font-size: 10px;\n font-weight: bold;\n}\n\n.node circle.state-start {\n fill: ${options.specialStateColor};\n stroke: ${options.specialStateColor};\n}\n\n.node .fork-join {\n fill: ${options.specialStateColor};\n stroke: ${options.specialStateColor};\n}\n\n.node circle.state-end {\n fill: ${options.innerEndBackground};\n stroke: ${options.background};\n stroke-width: 1.5\n}\n.end-state-inner {\n fill: ${options.compositeBackground || options.background};\n // stroke: ${options.background};\n stroke-width: 1.5\n}\n\n.node rect {\n fill: ${options.stateBkg || options.mainBkg};\n stroke: ${options.stateBorder || options.nodeBorder};\n stroke-width: 1px;\n}\n.node polygon {\n fill: ${options.mainBkg};\n stroke: ${options.stateBorder || options.nodeBorder};;\n stroke-width: 1px;\n}\n#statediagram-barbEnd {\n fill: ${options.lineColor};\n}\n\n.statediagram-cluster rect {\n fill: ${options.compositeTitleBackground};\n stroke: ${options.stateBorder || options.nodeBorder};\n stroke-width: 1px;\n}\n\n.cluster-label, .nodeLabel {\n color: ${options.stateLabelColor};\n // line-height: 1;\n}\n\n.statediagram-cluster rect.outer {\n rx: 5px;\n ry: 5px;\n}\n.statediagram-state .divider {\n stroke: ${options.stateBorder || options.nodeBorder};\n}\n\n.statediagram-state .title-state {\n rx: 5px;\n ry: 5px;\n}\n.statediagram-cluster.statediagram-cluster .inner {\n fill: ${options.compositeBackground || options.background};\n}\n.statediagram-cluster.statediagram-cluster-alt .inner {\n fill: ${options.altBackground ? options.altBackground : \"#efefef\"};\n}\n\n.statediagram-cluster .inner {\n rx:0;\n ry:0;\n}\n\n.statediagram-state rect.basic {\n rx: 5px;\n ry: 5px;\n}\n.statediagram-state rect.divider {\n stroke-dasharray: 10,10;\n fill: ${options.altBackground ? options.altBackground : \"#efefef\"};\n}\n\n.note-edge {\n stroke-dasharray: 5;\n}\n\n.statediagram-note rect {\n fill: ${options.noteBkgColor};\n stroke: ${options.noteBorderColor};\n stroke-width: 1px;\n rx: 0;\n ry: 0;\n}\n.statediagram-note rect {\n fill: ${options.noteBkgColor};\n stroke: ${options.noteBorderColor};\n stroke-width: 1px;\n rx: 0;\n ry: 0;\n}\n\n.statediagram-note text {\n fill: ${options.noteTextColor};\n}\n\n.statediagram-note .nodeLabel {\n color: ${options.noteTextColor};\n}\n.statediagram .edgeLabel {\n color: red; // ${options.noteTextColor};\n}\n\n#dependencyStart, #dependencyEnd {\n fill: ${options.lineColor};\n stroke: ${options.lineColor};\n stroke-width: 1;\n}\n\n.statediagramTitleText {\n text-anchor: middle;\n font-size: 18px;\n fill: ${options.textColor};\n}\n`, \"getStyles\");\nvar styles_default = getStyles;\n\nexport {\n stateDiagram_default,\n stateRenderer_v3_unified_default,\n StateDB,\n styles_default\n};\n"], + "mappings": "0VA8BA,IAAIA,IAAU,UAAW,CACvB,IAAIC,EAAoBC,EAAO,SAASC,EAAGC,EAAGC,EAAIC,EAAG,CACnD,IAAKD,EAAKA,GAAM,CAAC,EAAGC,EAAIH,EAAE,OAAQG,IAAKD,EAAGF,EAAEG,CAAC,CAAC,EAAIF,EAAG,CACrD,OAAOC,CACT,EAAG,GAAG,EAAGE,EAAM,CAAC,EAAG,CAAC,EAAGC,EAAM,CAAC,EAAG,CAAC,EAAGC,EAAM,CAAC,EAAG,CAAC,EAAGC,EAAM,CAAC,EAAG,CAAC,EAAGC,EAAM,CAAC,EAAG,CAAC,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM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,aAAa;AAAA;AAAA;AAAA,mBAGbA,EAAQ,aAAa;AAAA;AAAA;AAAA;AAAA,UAI9BA,EAAQ,SAAS;AAAA,YACfA,EAAQ,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAOnBA,EAAQ,SAAS;AAAA;AAAA,EAExB,WAAW,EACVC,GAAiBF", + "names": ["parser", "o", "__name", "k", "v", "o2", "l", "$V0", "$V1", "$V2", "$V3", "$V4", "$V5", "$V6", "$V7", "$V8", "$V9", "$Va", "$Vb", "$Vc", "$Vd", "$Ve", "$Vf", "$Vg", "$Vh", "$Vi", "$Vj", "$Vk", "$Vl", "$Vm", "$Vn", "$Vo", "$Vp", "$Vq", "$Vr", "$Vs", "$Vt", "$Vu", "parser2", "yytext", "yyleng", "yylineno", "yy", "yystate", "$$", "_$", "$0", "stateStmt", "relDescription", "id", "description", "parts", "str", "hash", "error", "input", "self", "stack", "tstack", "vstack", "lstack", "table", "recovering", "TERROR", "EOF", "args", "lexer2", "sharedState", "yyloc", "ranges", "popStack", "n", "lex", "token", "symbol", "preErrorSymbol", "state", "action", "a", "r", "yyval", "p", "len", "newState", "expected", "errStr", "lexer", "ch", "lines", "oldLines", "past", "next", "pre", "match", "indexed_rule", "backup", "tempMatch", "index", "rules", "condition", "yy_", "$avoiding_name_collisions", "YY_START", "YYSTATE", "Parser", "stateDiagram_default", "DEFAULT_DIAGRAM_DIRECTION", "DEFAULT_NESTED_DOC_DIR", "STMT_DIRECTION", "STMT_STATE", "STMT_ROOT", "STMT_RELATION", "STMT_CLASSDEF", "STMT_STYLEDEF", "STMT_APPLYCLASS", "DEFAULT_STATE_TYPE", "DIVIDER_TYPE", "G_EDGE_STYLE", "G_EDGE_ARROWHEADSTYLE", "G_EDGE_LABELPOS", "G_EDGE_LABELTYPE", "G_EDGE_THICKNESS", "SHAPE_STATE", "SHAPE_STATE_WITH_DESC", "SHAPE_START", "SHAPE_END", "SHAPE_DIVIDER", "SHAPE_GROUP", "SHAPE_NOTE", "SHAPE_NOTEGROUP", "CSS_DIAGRAM", "CSS_STATE", "CSS_DIAGRAM_STATE", "CSS_EDGE", "CSS_NOTE", "CSS_NOTE_EDGE", "CSS_EDGE_NOTE_EDGE", "CSS_DIAGRAM_NOTE", "CSS_CLUSTER", "CSS_DIAGRAM_CLUSTER", "CSS_CLUSTER_ALT", "CSS_DIAGRAM_CLUSTER_ALT", "PARENT", "NOTE", "DOMID_STATE", "DOMID_TYPE_SPACER", "NOTE_ID", "PARENT_ID", "getDir", "parsedItem", "defaultDir", "dir", "parsedItemDoc", "getClasses", "text", "diagramObj", "draw", "_version", "diag", "log", "securityLevel", "conf", "layout", "getConfig2", "data4Layout", "svg", "getDiagramElement", "render", "padding", "linkInfo", "key", "stateId", "allNodes", "matchedElem", "g", "parent", "cleanedUrl", "tooltip", "err", "utils_default", "setupViewPortForSVG", "stateRenderer_v3_unified_default", "nodeDb", "graphItemCount", "stateDomId", "itemId", "counter", "type", "typeSpacer", "typeStr", "setupDoc", "parentParsedItem", "doc", "diagramStates", "nodes", "edges", "altFlag", "look", "classes", "item", "dataFetcher", "edgeData", "common_default", "getDir2", "insertOrUpdateNode", "nodeData", "cssClass", "classDef", "existingNodeData", "node", "getClassesFromDbInfo", "dbInfoItem", "getStylesFromDbInfo", "dbState", "classStr", "style", "config", "shape", "newNode", "noteData", "parentNodeId", "groupData", "from", "to", "reset", "CONSTANTS", "newClassesList", "newDoc", "clone", "StateDB", "version", "getAccTitle", "setAccTitle", "getAccDescription", "setAccDescription", "setDiagramTitle", "getDiagramTitle", "statements", "ids", "styles", "trimmedId", "s", "first", "currentDoc", "stmt", "generateId", "docNode", "descr", "note", "textStyles", "des", "doc2", "textStyle", "saveCommon", "clear", "url", "item1", "item2", "relationTitle", "id1", "type1", "id2", "type2", "title", "theState", "_descr", "label", "styleAttributes", "foundClass", "attrib", "fixedAttrib", "newStyle2", "itemIds", "cssClassName", "foundState", "styleText", "getStyles", "options", "styles_default"] +} diff --git a/docs/website/public/chunk-HVSI2YYT.min.js b/docs/website/public/chunk-HVSI2YYT.min.js new file mode 100644 index 000000000..fc7c8b59c --- /dev/null +++ b/docs/website/public/chunk-HVSI2YYT.min.js @@ -0,0 +1,2 @@ +import{a as o,b as n,c as a,d as s,e as m,f as e,g as u,j as d,o as c,q as l}from"./chunk-LBFZT66H.min.js";var v=class extends l{static{e(this,"PieTokenBuilder")}constructor(){super(["pie","showData"])}},C=class extends c{static{e(this,"PieValueConverter")}runCustomConverter(t,r,i){if(t.name==="PIE_SECTION_LABEL")return r.replace(/"/g,"").trim()}},P={parser:{TokenBuilder:e(()=>new v,"TokenBuilder"),ValueConverter:e(()=>new C,"ValueConverter")}};function p(t=s){let r=a(n(t),u),i=a(o({shared:r}),d,P);return r.ServiceRegistry.register(i),{shared:r,Pie:i}}e(p,"createPieServices");export{P as a,p as b}; +//# sourceMappingURL=chunk-HVSI2YYT.min.js.map diff --git a/docs/website/public/chunk-HVSI2YYT.min.js.map b/docs/website/public/chunk-HVSI2YYT.min.js.map new file mode 100644 index 000000000..5f792870c --- /dev/null +++ b/docs/website/public/chunk-HVSI2YYT.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/@mermaid-js/parser/dist/chunks/mermaid-parser.core/chunk-WFWHJNB7.mjs"], + "sourcesContent": ["import {\n AbstractMermaidTokenBuilder,\n AbstractMermaidValueConverter,\n MermaidGeneratedSharedModule,\n PieGeneratedModule,\n __name\n} from \"./chunk-4KMFLZZN.mjs\";\n\n// src/language/pie/module.ts\nimport {\n EmptyFileSystem,\n createDefaultCoreModule,\n createDefaultSharedCoreModule,\n inject\n} from \"langium\";\n\n// src/language/pie/tokenBuilder.ts\nvar PieTokenBuilder = class extends AbstractMermaidTokenBuilder {\n static {\n __name(this, \"PieTokenBuilder\");\n }\n constructor() {\n super([\"pie\", \"showData\"]);\n }\n};\n\n// src/language/pie/valueConverter.ts\nvar PieValueConverter = class extends AbstractMermaidValueConverter {\n static {\n __name(this, \"PieValueConverter\");\n }\n runCustomConverter(rule, input, _cstNode) {\n if (rule.name !== \"PIE_SECTION_LABEL\") {\n return void 0;\n }\n return input.replace(/\"/g, \"\").trim();\n }\n};\n\n// src/language/pie/module.ts\nvar PieModule = {\n parser: {\n TokenBuilder: /* @__PURE__ */ __name(() => new PieTokenBuilder(), \"TokenBuilder\"),\n ValueConverter: /* @__PURE__ */ __name(() => new PieValueConverter(), \"ValueConverter\")\n }\n};\nfunction createPieServices(context = EmptyFileSystem) {\n const shared = inject(\n createDefaultSharedCoreModule(context),\n MermaidGeneratedSharedModule\n );\n const Pie = inject(\n createDefaultCoreModule({ shared }),\n PieGeneratedModule,\n PieModule\n );\n shared.ServiceRegistry.register(Pie);\n return { shared, Pie };\n}\n__name(createPieServices, \"createPieServices\");\n\nexport {\n PieModule,\n createPieServices\n};\n"], + "mappings": "2GAiBA,IAAIA,EAAkB,cAAcC,CAA4B,CAC9D,MAAO,CACLC,EAAO,KAAM,iBAAiB,CAChC,CACA,aAAc,CACZ,MAAM,CAAC,MAAO,UAAU,CAAC,CAC3B,CACF,EAGIC,EAAoB,cAAcC,CAA8B,CAClE,MAAO,CACLF,EAAO,KAAM,mBAAmB,CAClC,CACA,mBAAmBG,EAAMC,EAAOC,EAAU,CACxC,GAAIF,EAAK,OAAS,oBAGlB,OAAOC,EAAM,QAAQ,KAAM,EAAE,EAAE,KAAK,CACtC,CACF,EAGIE,EAAY,CACd,OAAQ,CACN,aAA8BN,EAAO,IAAM,IAAIF,EAAmB,cAAc,EAChF,eAAgCE,EAAO,IAAM,IAAIC,EAAqB,gBAAgB,CACxF,CACF,EACA,SAASM,EAAkBC,EAAUC,EAAiB,CACpD,IAAMC,EAASC,EACbC,EAA8BJ,CAAO,EACrCK,CACF,EACMC,EAAMH,EACVI,EAAwB,CAAE,OAAAL,CAAO,CAAC,EAClCM,EACAV,CACF,EACA,OAAAI,EAAO,gBAAgB,SAASI,CAAG,EAC5B,CAAE,OAAAJ,EAAQ,IAAAI,CAAI,CACvB,CACAd,EAAOO,EAAmB,mBAAmB", + "names": ["PieTokenBuilder", "AbstractMermaidTokenBuilder", "__name", "PieValueConverter", "AbstractMermaidValueConverter", "rule", "input", "_cstNode", "PieModule", "createPieServices", "context", "EmptyFileSystem", "shared", "inject", "createDefaultSharedCoreModule", "MermaidGeneratedSharedModule", "Pie", "createDefaultCoreModule", "PieGeneratedModule"] +} diff --git a/docs/website/public/chunk-I6VG5SPK.min.js b/docs/website/public/chunk-I6VG5SPK.min.js new file mode 100644 index 000000000..8a9c51667 --- /dev/null +++ b/docs/website/public/chunk-I6VG5SPK.min.js @@ -0,0 +1,4 @@ +import{f as a}from"./chunk-LBFZT66H.min.js";var t={},o={info:a(async()=>{let{createInfoServices:e}=await import("./info-63CPKGFF-5MUB2N6Y.min.js"),r=e().Info.parser.LangiumParser;t.info=r},"info"),packet:a(async()=>{let{createPacketServices:e}=await import("./packet-HUATNLJX-RNXZU7WE.min.js"),r=e().Packet.parser.LangiumParser;t.packet=r},"packet"),pie:a(async()=>{let{createPieServices:e}=await import("./pie-WTHONI2E-GI627NZ2.min.js"),r=e().Pie.parser.LangiumParser;t.pie=r},"pie"),architecture:a(async()=>{let{createArchitectureServices:e}=await import("./architecture-O4VJ6CD3-GQAMQMPJ.min.js"),r=e().Architecture.parser.LangiumParser;t.architecture=r},"architecture"),gitGraph:a(async()=>{let{createGitGraphServices:e}=await import("./gitGraph-ZV4HHKMB-ZION4T7A.min.js"),r=e().GitGraph.parser.LangiumParser;t.gitGraph=r},"gitGraph"),radar:a(async()=>{let{createRadarServices:e}=await import("./radar-NJJJXTRR-ATVXO2RU.min.js"),r=e().Radar.parser.LangiumParser;t.radar=r},"radar"),treemap:a(async()=>{let{createTreemapServices:e}=await import("./treemap-75Q7IDZK-DQ2GXHQO.min.js"),r=e().Treemap.parser.LangiumParser;t.treemap=r},"treemap")};async function n(e,r){let i=o[e];if(!i)throw new Error(`Unknown diagram type: ${e}`);t[e]||await i();let s=t[e].parse(r);if(s.lexerErrors.length>0||s.parserErrors.length>0)throw new p(s);return s.value}a(n,"parse");var p=class extends Error{constructor(e){let r=e.lexerErrors.map(c=>c.message).join(` +`),i=e.parserErrors.map(c=>c.message).join(` +`);super(`Parsing failed: ${r} ${i}`),this.result=e}static{a(this,"MermaidParseError")}};export{n as a}; +//# sourceMappingURL=chunk-I6VG5SPK.min.js.map diff --git a/docs/website/public/chunk-I6VG5SPK.min.js.map b/docs/website/public/chunk-I6VG5SPK.min.js.map new file mode 100644 index 000000000..74680238f --- /dev/null +++ b/docs/website/public/chunk-I6VG5SPK.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/@mermaid-js/parser/dist/mermaid-parser.core.mjs"], + "sourcesContent": ["import {\n GitGraphModule,\n createGitGraphServices\n} from \"./chunks/mermaid-parser.core/chunk-BN7GFLIU.mjs\";\nimport {\n InfoModule,\n createInfoServices\n} from \"./chunks/mermaid-parser.core/chunk-T44TD3VJ.mjs\";\nimport {\n PacketModule,\n createPacketServices\n} from \"./chunks/mermaid-parser.core/chunk-KMC2YHZD.mjs\";\nimport {\n PieModule,\n createPieServices\n} from \"./chunks/mermaid-parser.core/chunk-WFWHJNB7.mjs\";\nimport {\n ArchitectureModule,\n createArchitectureServices\n} from \"./chunks/mermaid-parser.core/chunk-JEIROHC2.mjs\";\nimport {\n RadarModule,\n createRadarServices\n} from \"./chunks/mermaid-parser.core/chunk-WFRQ32O7.mjs\";\nimport {\n TreemapModule,\n createTreemapServices\n} from \"./chunks/mermaid-parser.core/chunk-XRWGC2XP.mjs\";\nimport {\n AbstractMermaidTokenBuilder,\n AbstractMermaidValueConverter,\n Architecture,\n ArchitectureGeneratedModule,\n Branch,\n Commit,\n CommonTokenBuilder,\n CommonValueConverter,\n GitGraph,\n GitGraphGeneratedModule,\n Info,\n InfoGeneratedModule,\n Merge,\n MermaidGeneratedSharedModule,\n Packet,\n PacketBlock,\n PacketGeneratedModule,\n Pie,\n PieGeneratedModule,\n PieSection,\n Radar,\n RadarGeneratedModule,\n Statement,\n Treemap,\n TreemapGeneratedModule,\n __name,\n isArchitecture,\n isBranch,\n isCommit,\n isGitGraph,\n isInfo,\n isMerge,\n isPacket,\n isPacketBlock,\n isPie,\n isPieSection,\n isTreemap\n} from \"./chunks/mermaid-parser.core/chunk-4KMFLZZN.mjs\";\n\n// src/parse.ts\nvar parsers = {};\nvar initializers = {\n info: /* @__PURE__ */ __name(async () => {\n const { createInfoServices: createInfoServices2 } = await import(\"./chunks/mermaid-parser.core/info-63CPKGFF.mjs\");\n const parser = createInfoServices2().Info.parser.LangiumParser;\n parsers.info = parser;\n }, \"info\"),\n packet: /* @__PURE__ */ __name(async () => {\n const { createPacketServices: createPacketServices2 } = await import(\"./chunks/mermaid-parser.core/packet-HUATNLJX.mjs\");\n const parser = createPacketServices2().Packet.parser.LangiumParser;\n parsers.packet = parser;\n }, \"packet\"),\n pie: /* @__PURE__ */ __name(async () => {\n const { createPieServices: createPieServices2 } = await import(\"./chunks/mermaid-parser.core/pie-WTHONI2E.mjs\");\n const parser = createPieServices2().Pie.parser.LangiumParser;\n parsers.pie = parser;\n }, \"pie\"),\n architecture: /* @__PURE__ */ __name(async () => {\n const { createArchitectureServices: createArchitectureServices2 } = await import(\"./chunks/mermaid-parser.core/architecture-O4VJ6CD3.mjs\");\n const parser = createArchitectureServices2().Architecture.parser.LangiumParser;\n parsers.architecture = parser;\n }, \"architecture\"),\n gitGraph: /* @__PURE__ */ __name(async () => {\n const { createGitGraphServices: createGitGraphServices2 } = await import(\"./chunks/mermaid-parser.core/gitGraph-ZV4HHKMB.mjs\");\n const parser = createGitGraphServices2().GitGraph.parser.LangiumParser;\n parsers.gitGraph = parser;\n }, \"gitGraph\"),\n radar: /* @__PURE__ */ __name(async () => {\n const { createRadarServices: createRadarServices2 } = await import(\"./chunks/mermaid-parser.core/radar-NJJJXTRR.mjs\");\n const parser = createRadarServices2().Radar.parser.LangiumParser;\n parsers.radar = parser;\n }, \"radar\"),\n treemap: /* @__PURE__ */ __name(async () => {\n const { createTreemapServices: createTreemapServices2 } = await import(\"./chunks/mermaid-parser.core/treemap-75Q7IDZK.mjs\");\n const parser = createTreemapServices2().Treemap.parser.LangiumParser;\n parsers.treemap = parser;\n }, \"treemap\")\n};\nasync function parse(diagramType, text) {\n const initializer = initializers[diagramType];\n if (!initializer) {\n throw new Error(`Unknown diagram type: ${diagramType}`);\n }\n if (!parsers[diagramType]) {\n await initializer();\n }\n const parser = parsers[diagramType];\n const result = parser.parse(text);\n if (result.lexerErrors.length > 0 || result.parserErrors.length > 0) {\n throw new MermaidParseError(result);\n }\n return result.value;\n}\n__name(parse, \"parse\");\nvar MermaidParseError = class extends Error {\n constructor(result) {\n const lexerErrors = result.lexerErrors.map((err) => err.message).join(\"\\n\");\n const parserErrors = result.parserErrors.map((err) => err.message).join(\"\\n\");\n super(`Parsing failed: ${lexerErrors} ${parserErrors}`);\n this.result = result;\n }\n static {\n __name(this, \"MermaidParseError\");\n }\n};\nexport {\n AbstractMermaidTokenBuilder,\n AbstractMermaidValueConverter,\n Architecture,\n ArchitectureGeneratedModule,\n ArchitectureModule,\n Branch,\n Commit,\n CommonTokenBuilder,\n CommonValueConverter,\n GitGraph,\n GitGraphGeneratedModule,\n GitGraphModule,\n Info,\n InfoGeneratedModule,\n InfoModule,\n Merge,\n MermaidGeneratedSharedModule,\n MermaidParseError,\n Packet,\n PacketBlock,\n PacketGeneratedModule,\n PacketModule,\n Pie,\n PieGeneratedModule,\n PieModule,\n PieSection,\n Radar,\n RadarGeneratedModule,\n RadarModule,\n Statement,\n Treemap,\n TreemapGeneratedModule,\n TreemapModule,\n createArchitectureServices,\n createGitGraphServices,\n createInfoServices,\n createPacketServices,\n createPieServices,\n createRadarServices,\n createTreemapServices,\n isArchitecture,\n isBranch,\n isCommit,\n isGitGraph,\n isInfo,\n isMerge,\n isPacket,\n isPacketBlock,\n isPie,\n isPieSection,\n isTreemap,\n parse\n};\n"], + "mappings": "4CAqEA,IAAIA,EA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IAAMC,EAAcb,EAAaW,CAAW,EAC5C,GAAI,CAACE,EACH,MAAM,IAAI,MAAM,yBAAyBF,CAAW,EAAE,EAEnDZ,EAAQY,CAAW,GACtB,MAAME,EAAY,EAGpB,IAAMC,EADSf,EAAQY,CAAW,EACZ,MAAMC,CAAI,EAChC,GAAIE,EAAO,YAAY,OAAS,GAAKA,EAAO,aAAa,OAAS,EAChE,MAAM,IAAIC,EAAkBD,CAAM,EAEpC,OAAOA,EAAO,KAChB,CACAb,EAAOS,EAAO,OAAO,EACrB,IAAIK,EAAoB,cAAc,KAAM,CAC1C,YAAYD,EAAQ,CAClB,IAAME,EAAcF,EAAO,YAAY,IAAKG,GAAQA,EAAI,OAAO,EAAE,KAAK;AAAA,CAAI,EACpEC,EAAeJ,EAAO,aAAa,IAAKG,GAAQA,EAAI,OAAO,EAAE,KAAK;AAAA,CAAI,EAC5E,MAAM,mBAAmBD,CAAW,IAAIE,CAAY,EAAE,EACtD,KAAK,OAASJ,CAChB,CACA,MAAO,CACLb,EAAO,KAAM,mBAAmB,CAClC,CACF", + "names": ["parsers", "initializers", "__name", "createInfoServices2", "parser", "createPacketServices2", "createPieServices2", "createArchitectureServices2", "createGitGraphServices2", "createRadarServices2", "createTreemapServices2", "parse", "diagramType", "text", "initializer", "result", "MermaidParseError", "lexerErrors", "err", "parserErrors"] +} diff --git a/docs/website/public/chunk-IDQ2RCY2.min.js b/docs/website/public/chunk-IDQ2RCY2.min.js new file mode 100644 index 000000000..c7ae19bfe --- /dev/null +++ b/docs/website/public/chunk-IDQ2RCY2.min.js @@ -0,0 +1,55 @@ +import{a as Zt}from"./chunk-ANLQN3B7.min.js";import{a as Me,b as Mt,d as T,e as W}from"./chunk-OEBO5CRK.min.js";import{d as vt,g as ht}from"./chunk-XCAVDAZC.min.js";import{i as kt,k as ke,o as xt,q as U}from"./chunk-QZZKR5JD.min.js";import{D as Lt,F as J,G as Xt,H as Yt,J as Se,K as $e,W as V,Z as Vt,q as we,y as mt}from"./chunk-3EE2TK35.min.js";import{b as $,d as F,j as Y}from"./chunk-6TVUEPFY.min.js";function Qt(o,t,i){if(o&&o.length){let[a,e]=t,r=Math.PI/180*i,h=Math.cos(r),s=Math.sin(r);for(let c of o){let[n,l]=c;c[0]=(n-a)*h-(l-e)*s+a,c[1]=(n-a)*s+(l-e)*h+e}}}function ia(o,t){return o[0]===t[0]&&o[1]===t[1]}function la(o,t,i,a=1){let e=i,r=Math.max(t,.1),h=o[0]&&o[0][0]&&typeof o[0][0]=="number"?[o]:o,s=[0,0];if(e)for(let n of h)Qt(n,s,e);let c=(function(n,l,g){let f=[];for(let x of n){let b=[...x];ia(b[0],b[b.length-1])||b.push([b[0][0],b[0][1]]),b.length>2&&f.push(b)}let p=[];l=Math.max(l,.1);let u=[];for(let x of f)for(let b=0;bx.yminb.ymin?1:x.xb.x?1:x.ymax===b.ymax?0:(x.ymax-b.ymax)/Math.abs(x.ymax-b.ymax))),!u.length)return p;let y=[],m=u[0].ymin,d=0;for(;y.length||u.length;){if(u.length){let x=-1;for(let b=0;bm);b++)x=b;u.splice(0,x+1).forEach((b=>{y.push({s:m,edge:b})}))}if(y=y.filter((x=>!(x.edge.ymax<=m))),y.sort(((x,b)=>x.edge.x===b.edge.x?0:(x.edge.x-b.edge.x)/Math.abs(x.edge.x-b.edge.x))),(g!==1||d%l==0)&&y.length>1)for(let x=0;x=y.length)break;let M=y[x].edge,w=y[b].edge;p.push([[Math.round(M.x),m],[Math.round(w.x),m]])}m+=g,y.forEach((x=>{x.edge.x=x.edge.x+g*x.edge.islope})),d++}return p})(h,r,a);if(e){for(let n of h)Qt(n,s,-e);(function(n,l,g){let f=[];n.forEach((p=>f.push(...p))),Qt(f,l,g)})(c,s,-e)}return c}function Ct(o,t){var i;let a=t.hachureAngle+90,e=t.hachureGap;e<0&&(e=4*t.strokeWidth),e=Math.round(Math.max(e,.1));let r=1;return t.roughness>=1&&(((i=t.randomizer)===null||i===void 0?void 0:i.next())||Math.random())>.7&&(r=e),la(o,e,a,r||1)}var Bt=class{constructor(t){this.helper=t}fillPolygons(t,i){return this._fillPolygons(t,i)}_fillPolygons(t,i){let a=Ct(t,i);return{type:"fillSketch",ops:this.renderLines(a,i)}}renderLines(t,i){let a=[];for(let e of t)a.push(...this.helper.doubleLineOps(e[0][0],e[0][1],e[1][0],e[1][1],i));return a}};function jt(o){let t=o[0],i=o[1];return Math.sqrt(Math.pow(t[0]-i[0],2)+Math.pow(t[1]-i[1],2))}var ee=class extends Bt{fillPolygons(t,i){let a=i.hachureGap;a<0&&(a=4*i.strokeWidth),a=Math.max(a,.1);let e=Ct(t,Object.assign({},i,{hachureGap:a})),r=Math.PI/180*i.hachureAngle,h=[],s=.5*a*Math.cos(r),c=.5*a*Math.sin(r);for(let[n,l]of e)jt([n,l])&&h.push([[n[0]-s,n[1]+c],[...l]],[[n[0]+s,n[1]-c],[...l]]);return{type:"fillSketch",ops:this.renderLines(h,i)}}},se=class extends Bt{fillPolygons(t,i){let a=this._fillPolygons(t,i),e=Object.assign({},i,{hachureAngle:i.hachureAngle+90}),r=this._fillPolygons(t,e);return a.ops=a.ops.concat(r.ops),a}},ae=class{constructor(t){this.helper=t}fillPolygons(t,i){let a=Ct(t,i=Object.assign({},i,{hachureAngle:0}));return this.dotsOnLines(a,i)}dotsOnLines(t,i){let a=[],e=i.hachureGap;e<0&&(e=4*i.strokeWidth),e=Math.max(e,.1);let r=i.fillWeight;r<0&&(r=i.strokeWidth/2);let h=e/4;for(let s of t){let c=jt(s),n=c/e,l=Math.ceil(n)-1,g=c-l*e,f=(s[0][0]+s[1][0])/2-e/4,p=Math.min(s[0][1],s[1][1]);for(let u=0;u{let s=jt(h),c=Math.floor(s/(a+e)),n=(s+e-c*(a+e))/2,l=h[0],g=h[1];l[0]>g[0]&&(l=h[1],g=h[0]);let f=Math.atan((g[1]-l[1])/(g[0]-l[0]));for(let p=0;p{let h=jt(r),s=Math.round(h/(2*i)),c=r[0],n=r[1];c[0]>n[0]&&(c=r[1],n=r[0]);let l=Math.atan((n[1]-c[1])/(n[0]-c[0]));for(let g=0;gl%2?n+i:n+t));r.push({key:"C",data:c}),t=c[4],i=c[5];break}case"Q":r.push({key:"Q",data:[...s]}),t=s[2],i=s[3];break;case"q":{let c=s.map(((n,l)=>l%2?n+i:n+t));r.push({key:"Q",data:c}),t=c[2],i=c[3];break}case"A":r.push({key:"A",data:[...s]}),t=s[5],i=s[6];break;case"a":t+=s[5],i+=s[6],r.push({key:"A",data:[s[0],s[1],s[2],s[3],s[4],t,i]});break;case"H":r.push({key:"H",data:[...s]}),t=s[0];break;case"h":t+=s[0],r.push({key:"H",data:[t]});break;case"V":r.push({key:"V",data:[...s]}),i=s[0];break;case"v":i+=s[0],r.push({key:"V",data:[i]});break;case"S":r.push({key:"S",data:[...s]}),t=s[2],i=s[3];break;case"s":{let c=s.map(((n,l)=>l%2?n+i:n+t));r.push({key:"S",data:c}),t=c[2],i=c[3];break}case"T":r.push({key:"T",data:[...s]}),t=s[0],i=s[1];break;case"t":t+=s[0],i+=s[1],r.push({key:"T",data:[t,i]});break;case"Z":case"z":r.push({key:"Z",data:[]}),t=a,i=e}return r}function We(o){let t=[],i="",a=0,e=0,r=0,h=0,s=0,c=0;for(let{key:n,data:l}of o){switch(n){case"M":t.push({key:"M",data:[...l]}),[a,e]=l,[r,h]=l;break;case"C":t.push({key:"C",data:[...l]}),a=l[4],e=l[5],s=l[2],c=l[3];break;case"L":t.push({key:"L",data:[...l]}),[a,e]=l;break;case"H":a=l[0],t.push({key:"L",data:[a,e]});break;case"V":e=l[0],t.push({key:"L",data:[a,e]});break;case"S":{let g=0,f=0;i==="C"||i==="S"?(g=a+(a-s),f=e+(e-c)):(g=a,f=e),t.push({key:"C",data:[g,f,...l]}),s=l[0],c=l[1],a=l[2],e=l[3];break}case"T":{let[g,f]=l,p=0,u=0;i==="Q"||i==="T"?(p=a+(a-s),u=e+(e-c)):(p=a,u=e);let y=a+2*(p-a)/3,m=e+2*(u-e)/3,d=g+2*(p-g)/3,x=f+2*(u-f)/3;t.push({key:"C",data:[y,m,d,x,g,f]}),s=p,c=u,a=g,e=f;break}case"Q":{let[g,f,p,u]=l,y=a+2*(g-a)/3,m=e+2*(f-e)/3,d=p+2*(g-p)/3,x=u+2*(f-u)/3;t.push({key:"C",data:[y,m,d,x,p,u]}),s=g,c=f,a=p,e=u;break}case"A":{let g=Math.abs(l[0]),f=Math.abs(l[1]),p=l[2],u=l[3],y=l[4],m=l[5],d=l[6];g===0||f===0?(t.push({key:"C",data:[a,e,m,d,m,d]}),a=m,e=d):(a!==m||e!==d)&&(Te(a,e,m,d,g,f,p,u,y).forEach((function(x){t.push({key:"C",data:x})})),a=m,e=d);break}case"Z":t.push({key:"Z",data:[]}),a=r,e=h}i=n}return t}function Dt(o,t,i){return[o*Math.cos(i)-t*Math.sin(i),o*Math.sin(i)+t*Math.cos(i)]}function Te(o,t,i,a,e,r,h,s,c,n){let l=(g=h,Math.PI*g/180);var g;let f=[],p=0,u=0,y=0,m=0;if(n)[p,u,y,m]=n;else{[o,t]=Dt(o,t,-l),[i,a]=Dt(i,a,-l);let P=(o-i)/2,C=(t-a)/2,E=P*P/(e*e)+C*C/(r*r);E>1&&(E=Math.sqrt(E),e*=E,r*=E);let R=e*e,O=r*r,z=R*O-R*C*C-O*P*P,Z=R*C*C+O*P*P,rt=(s===c?-1:1)*Math.sqrt(Math.abs(z/Z));y=rt*e*C/r+(o+i)/2,m=rt*-r*P/e+(t+a)/2,p=Math.asin(parseFloat(((t-m)/r).toFixed(9))),u=Math.asin(parseFloat(((a-m)/r).toFixed(9))),ou&&(p-=2*Math.PI),!c&&u>p&&(u-=2*Math.PI)}let d=u-p;if(Math.abs(d)>120*Math.PI/180){let P=u,C=i,E=a;u=c&&u>p?p+120*Math.PI/180*1:p+120*Math.PI/180*-1,f=Te(i=y+e*Math.cos(u),a=m+r*Math.sin(u),C,E,e,r,h,0,c,[u,P,y,m])}d=u-p;let x=Math.cos(p),b=Math.sin(p),M=Math.cos(u),w=Math.sin(u),k=Math.tan(d/4),v=4/3*e*k,D=4/3*r*k,B=[o,t],L=[o+v*b,t-D*x],A=[i+v*w,a-D*M],I=[i,a];if(L[0]=2*B[0]-L[0],L[1]=2*B[1]-L[1],n)return[L,A,I].concat(f);{f=[L,A,I].concat(f);let P=[];for(let C=0;C2){let e=[];for(let r=0;r2*Math.PI&&(p=0,u=2*Math.PI);let y=2*Math.PI/c.curveStepCount,m=Math.min(y/2,(u-p)/2),d=Re(m,n,l,g,f,p,u,1,c);if(!c.disableMultiStroke){let x=Re(m,n,l,g,f,p,u,1.5,c);d.push(...x)}return h&&(s?d.push(...gt(n,l,n+g*Math.cos(p),l+f*Math.sin(p),c),...gt(n,l,n+g*Math.cos(u),l+f*Math.sin(u),c)):d.push({op:"lineTo",data:[n,l]},{op:"lineTo",data:[n+g*Math.cos(p),l+f*Math.sin(p)]})),{type:"path",ops:d}}function Be(o,t){let i=We(Le(pe(o))),a=[],e=[0,0],r=[0,0];for(let{key:h,data:s}of i)switch(h){case"M":r=[s[0],s[1]],e=[s[0],s[1]];break;case"L":a.push(...gt(r[0],r[1],s[0],s[1],t)),r=[s[0],s[1]];break;case"C":{let[c,n,l,g,f,p]=s;a.push(...ga(c,n,l,g,f,p,r,t)),r=[f,p];break}case"Z":a.push(...gt(r[0],r[1],e[0],e[1],t)),r=[e[0],e[1]]}return{type:"path",ops:a}}function Ut(o,t){let i=[];for(let a of o)if(a.length){let e=t.maxRandomnessOffset||0,r=a.length;if(r>2){i.push({op:"move",data:[a[0][0]+j(e,t),a[0][1]+j(e,t)]});for(let h=1;h500?.4:-.0016668*c+1.233334;let l=e.maxRandomnessOffset||0;l*l*100>s&&(l=c/10);let g=l/2,f=.2+.2*Ee(e),p=e.bowing*e.maxRandomnessOffset*(a-t)/200,u=e.bowing*e.maxRandomnessOffset*(o-i)/200;p=j(p,e,n),u=j(u,e,n);let y=[],m=()=>j(g,e,n),d=()=>j(l,e,n),x=e.preserveVertices;return r&&(h?y.push({op:"move",data:[o+(x?0:m()),t+(x?0:m())]}):y.push({op:"move",data:[o+(x?0:j(l,e,n)),t+(x?0:j(l,e,n))]})),h?y.push({op:"bcurveTo",data:[p+o+(i-o)*f+m(),u+t+(a-t)*f+m(),p+o+2*(i-o)*f+m(),u+t+2*(a-t)*f+m(),i+(x?0:m()),a+(x?0:m())]}):y.push({op:"bcurveTo",data:[p+o+(i-o)*f+d(),u+t+(a-t)*f+d(),p+o+2*(i-o)*f+d(),u+t+2*(a-t)*f+d(),i+(x?0:d()),a+(x?0:d())]}),y}function Tt(o,t,i){if(!o.length)return[];let a=[];a.push([o[0][0]+j(t,i),o[0][1]+j(t,i)]),a.push([o[0][0]+j(t,i),o[0][1]+j(t,i)]);for(let e=1;e3){let r=[],h=1-i.curveTightness;e.push({op:"move",data:[o[1][0],o[1][1]]});for(let s=1;s+21&&e.push(s)):e.push(s),e.push(o[t+3])}else{let c=o[t+0],n=o[t+1],l=o[t+2],g=o[t+3],f=dt(c,n,.5),p=dt(n,l,.5),u=dt(l,g,.5),y=dt(f,p,.5),m=dt(p,u,.5),d=dt(y,m,.5);oe([c,f,y,d],0,i,e),oe([d,m,u,g],0,i,e)}var r,h;return e}function fa(o,t){return zt(o,0,o.length,t)}function zt(o,t,i,a,e){let r=e||[],h=o[t],s=o[i-1],c=0,n=1;for(let l=t+1;lc&&(c=g,n=l)}return Math.sqrt(c)>a?(zt(o,t,n+1,a,r),zt(o,n,i,a,r)):(r.length||r.push(h),r.push(s)),r}function te(o,t=.15,i){let a=[],e=(o.length-1)/3;for(let r=0;r0?zt(a,0,a.length,i):a}var at="none",wt=class{constructor(t){this.defaultOptions={maxRandomnessOffset:2,roughness:1,bowing:1,stroke:"#000",strokeWidth:1,curveTightness:0,curveFitting:.95,curveStepCount:9,fillStyle:"hachure",fillWeight:-1,hachureAngle:-41,hachureGap:-1,dashOffset:-1,dashGap:-1,zigzagOffset:-1,seed:0,disableMultiStroke:!1,disableMultiStrokeFill:!1,preserveVertices:!1,fillShapeRoughnessGain:.8},this.config=t||{},this.config.options&&(this.defaultOptions=this._o(this.config.options))}static newSeed(){return Math.floor(Math.random()*2**31)}_o(t){return t?Object.assign({},this.defaultOptions,t):this.defaultOptions}_d(t,i,a){return{shape:t,sets:i||[],options:a||this.defaultOptions}}line(t,i,a,e,r){let h=this._o(r);return this._d("line",[He(t,i,a,e,h)],h)}rectangle(t,i,a,e,r){let h=this._o(r),s=[],c=ha(t,i,a,e,h);if(h.fill){let n=[[t,i],[t+a,i],[t+a,i+e],[t,i+e]];h.fillStyle==="solid"?s.push(Ut([n],h)):s.push(bt([n],h))}return h.stroke!==at&&s.push(c),this._d("rectangle",s,h)}ellipse(t,i,a,e,r){let h=this._o(r),s=[],c=Ie(a,e,h),n=le(t,i,h,c);if(h.fill)if(h.fillStyle==="solid"){let l=le(t,i,h,c).opset;l.type="fillPath",s.push(l)}else s.push(bt([n.estimatedPoints],h));return h.stroke!==at&&s.push(n.opset),this._d("ellipse",s,h)}circle(t,i,a,e){let r=this.ellipse(t,i,a,a,e);return r.shape="circle",r}linearPath(t,i){let a=this._o(i);return this._d("linearPath",[It(t,!1,a)],a)}arc(t,i,a,e,r,h,s=!1,c){let n=this._o(c),l=[],g=Pe(t,i,a,e,r,h,s,!0,n);if(s&&n.fill)if(n.fillStyle==="solid"){let f=Object.assign({},n);f.disableMultiStroke=!0;let p=Pe(t,i,a,e,r,h,!0,!1,f);p.type="fillPath",l.push(p)}else l.push((function(f,p,u,y,m,d,x){let b=f,M=p,w=Math.abs(u/2),k=Math.abs(y/2);w+=j(.01*w,x),k+=j(.01*k,x);let v=m,D=d;for(;v<0;)v+=2*Math.PI,D+=2*Math.PI;D-v>2*Math.PI&&(v=0,D=2*Math.PI);let B=(D-v)/x.curveStepCount,L=[];for(let A=v;A<=D;A+=B)L.push([b+w*Math.cos(A),M+k*Math.sin(A)]);return L.push([b+w*Math.cos(D),M+k*Math.sin(D)]),L.push([b,M]),bt([L],x)})(t,i,a,e,r,h,n));return n.stroke!==at&&l.push(g),this._d("arc",l,n)}curve(t,i){let a=this._o(i),e=[],r=De(t,a);if(a.fill&&a.fill!==at)if(a.fillStyle==="solid"){let h=De(t,Object.assign(Object.assign({},a),{disableMultiStroke:!0,roughness:a.roughness?a.roughness+a.fillShapeRoughnessGain:0}));e.push({type:"fillPath",ops:this._mergedShape(h.ops)})}else{let h=[],s=t;if(s.length){let c=typeof s[0][0]=="number"?[s]:s;for(let n of c)n.length<3?h.push(...n):n.length===3?h.push(...te(Ae([n[0],n[0],n[1],n[2]]),10,(1+a.roughness)/2)):h.push(...te(Ae(n),10,(1+a.roughness)/2))}h.length&&e.push(bt([h],a))}return a.stroke!==at&&e.push(r),this._d("curve",e,a)}polygon(t,i){let a=this._o(i),e=[],r=It(t,!0,a);return a.fill&&(a.fillStyle==="solid"?e.push(Ut([t],a)):e.push(bt([t],a))),a.stroke!==at&&e.push(r),this._d("polygon",e,a)}path(t,i){let a=this._o(i),e=[];if(!t)return this._d("path",e,a);t=(t||"").replace(/\n/g," ").replace(/(-\s)/g,"-").replace("/(ss)/g"," ");let r=a.fill&&a.fill!=="transparent"&&a.fill!==at,h=a.stroke!==at,s=!!(a.simplification&&a.simplification<1),c=(function(l,g,f){let p=We(Le(pe(l))),u=[],y=[],m=[0,0],d=[],x=()=>{d.length>=4&&y.push(...te(d,g)),d=[]},b=()=>{x(),y.length&&(u.push(y),y=[])};for(let{key:w,data:k}of p)switch(w){case"M":b(),m=[k[0],k[1]],y.push(m);break;case"L":x(),y.push([k[0],k[1]]);break;case"C":if(!d.length){let v=y.length?y[y.length-1]:m;d.push([v[0],v[1]])}d.push([k[0],k[1]]),d.push([k[2],k[3]]),d.push([k[4],k[5]]);break;case"Z":x(),y.push([m[0],m[1]])}if(b(),!f)return u;let M=[];for(let w of u){let k=fa(w,f);k.length&&M.push(k)}return M})(t,1,s?4-4*(a.simplification||1):(1+a.roughness)/2),n=Be(t,a);if(r)if(a.fillStyle==="solid")if(c.length===1){let l=Be(t,Object.assign(Object.assign({},a),{disableMultiStroke:!0,roughness:a.roughness?a.roughness+a.fillShapeRoughnessGain:0}));e.push({type:"fillPath",ops:this._mergedShape(l.ops)})}else e.push(Ut(c,a));else e.push(bt(c,a));return h&&(s?c.forEach((l=>{e.push(It(l,!1,a))})):e.push(n)),this._d("path",e,a)}opsToPath(t,i){let a="";for(let e of t.ops){let r=typeof i=="number"&&i>=0?e.data.map((h=>+h.toFixed(i))):e.data;switch(e.op){case"move":a+=`M${r[0]} ${r[1]} `;break;case"bcurveTo":a+=`C${r[0]} ${r[1]}, ${r[2]} ${r[3]}, ${r[4]} ${r[5]} `;break;case"lineTo":a+=`L${r[0]} ${r[1]} `}}return a.trim()}toPaths(t){let i=t.sets||[],a=t.options||this.defaultOptions,e=[];for(let r of i){let h=null;switch(r.type){case"path":h={d:this.opsToPath(r),stroke:a.stroke,strokeWidth:a.strokeWidth,fill:at};break;case"fillPath":h={d:this.opsToPath(r),stroke:at,strokeWidth:0,fill:a.fill||at};break;case"fillSketch":h=this.fillSketch(r,a)}h&&e.push(h)}return e}fillSketch(t,i){let a=i.fillWeight;return a<0&&(a=i.strokeWidth/2),{d:this.opsToPath(t),stroke:i.fill||at,strokeWidth:a,fill:at}}_mergedShape(t){return t.filter(((i,a)=>a===0||i.op!=="move"))}},he=class{constructor(t,i){this.canvas=t,this.ctx=this.canvas.getContext("2d"),this.gen=new wt(i)}draw(t){let i=t.sets||[],a=t.options||this.getDefaultOptions(),e=this.ctx,r=t.options.fixedDecimalPlaceDigits;for(let h of i)switch(h.type){case"path":e.save(),e.strokeStyle=a.stroke==="none"?"transparent":a.stroke,e.lineWidth=a.strokeWidth,a.strokeLineDash&&e.setLineDash(a.strokeLineDash),a.strokeLineDashOffset&&(e.lineDashOffset=a.strokeLineDashOffset),this._drawToContext(e,h,r),e.restore();break;case"fillPath":{e.save(),e.fillStyle=a.fill||"";let s=t.shape==="curve"||t.shape==="polygon"||t.shape==="path"?"evenodd":"nonzero";this._drawToContext(e,h,r,s),e.restore();break}case"fillSketch":this.fillSketch(e,h,a)}}fillSketch(t,i,a){let e=a.fillWeight;e<0&&(e=a.strokeWidth/2),t.save(),a.fillLineDash&&t.setLineDash(a.fillLineDash),a.fillLineDashOffset&&(t.lineDashOffset=a.fillLineDashOffset),t.strokeStyle=a.fill||"",t.lineWidth=e,this._drawToContext(t,i,a.fixedDecimalPlaceDigits),t.restore()}_drawToContext(t,i,a,e="nonzero"){t.beginPath();for(let r of i.ops){let h=typeof a=="number"&&a>=0?r.data.map((s=>+s.toFixed(a))):r.data;switch(r.op){case"move":t.moveTo(h[0],h[1]);break;case"bcurveTo":t.bezierCurveTo(h[0],h[1],h[2],h[3],h[4],h[5]);break;case"lineTo":t.lineTo(h[0],h[1])}}i.type==="fillPath"?t.fill(e):t.stroke()}get generator(){return this.gen}getDefaultOptions(){return this.gen.defaultOptions}line(t,i,a,e,r){let h=this.gen.line(t,i,a,e,r);return this.draw(h),h}rectangle(t,i,a,e,r){let h=this.gen.rectangle(t,i,a,e,r);return this.draw(h),h}ellipse(t,i,a,e,r){let h=this.gen.ellipse(t,i,a,e,r);return this.draw(h),h}circle(t,i,a,e){let r=this.gen.circle(t,i,a,e);return this.draw(r),r}linearPath(t,i){let a=this.gen.linearPath(t,i);return this.draw(a),a}polygon(t,i){let a=this.gen.polygon(t,i);return this.draw(a),a}arc(t,i,a,e,r,h,s=!1,c){let n=this.gen.arc(t,i,a,e,r,h,s,c);return this.draw(n),n}curve(t,i){let a=this.gen.curve(t,i);return this.draw(a),a}path(t,i){let a=this.gen.path(t,i);return this.draw(a),a}},Ht="http://www.w3.org/2000/svg",ge=class{constructor(t,i){this.svg=t,this.gen=new wt(i)}draw(t){let i=t.sets||[],a=t.options||this.getDefaultOptions(),e=this.svg.ownerDocument||window.document,r=e.createElementNS(Ht,"g"),h=t.options.fixedDecimalPlaceDigits;for(let s of i){let c=null;switch(s.type){case"path":c=e.createElementNS(Ht,"path"),c.setAttribute("d",this.opsToPath(s,h)),c.setAttribute("stroke",a.stroke),c.setAttribute("stroke-width",a.strokeWidth+""),c.setAttribute("fill","none"),a.strokeLineDash&&c.setAttribute("stroke-dasharray",a.strokeLineDash.join(" ").trim()),a.strokeLineDashOffset&&c.setAttribute("stroke-dashoffset",`${a.strokeLineDashOffset}`);break;case"fillPath":c=e.createElementNS(Ht,"path"),c.setAttribute("d",this.opsToPath(s,h)),c.setAttribute("stroke","none"),c.setAttribute("stroke-width","0"),c.setAttribute("fill",a.fill||""),t.shape!=="curve"&&t.shape!=="polygon"||c.setAttribute("fill-rule","evenodd");break;case"fillSketch":c=this.fillSketch(e,s,a)}c&&r.appendChild(c)}return r}fillSketch(t,i,a){let e=a.fillWeight;e<0&&(e=a.strokeWidth/2);let r=t.createElementNS(Ht,"path");return r.setAttribute("d",this.opsToPath(i,a.fixedDecimalPlaceDigits)),r.setAttribute("stroke",a.fill||""),r.setAttribute("stroke-width",e+""),r.setAttribute("fill","none"),a.fillLineDash&&r.setAttribute("stroke-dasharray",a.fillLineDash.join(" ").trim()),a.fillLineDashOffset&&r.setAttribute("stroke-dashoffset",`${a.fillLineDashOffset}`),r}get generator(){return this.gen}getDefaultOptions(){return this.gen.defaultOptions}opsToPath(t,i){return this.gen.opsToPath(t,i)}line(t,i,a,e,r){let h=this.gen.line(t,i,a,e,r);return this.draw(h)}rectangle(t,i,a,e,r){let h=this.gen.rectangle(t,i,a,e,r);return this.draw(h)}ellipse(t,i,a,e,r){let h=this.gen.ellipse(t,i,a,e,r);return this.draw(h)}circle(t,i,a,e){let r=this.gen.circle(t,i,a,e);return this.draw(r)}linearPath(t,i){let a=this.gen.linearPath(t,i);return this.draw(a)}polygon(t,i){let a=this.gen.polygon(t,i);return this.draw(a)}arc(t,i,a,e,r,h,s=!1,c){let n=this.gen.arc(t,i,a,e,r,h,s,c);return this.draw(n)}curve(t,i){let a=this.gen.curve(t,i);return this.draw(a)}path(t,i){let a=this.gen.path(t,i);return this.draw(a)}},S={canvas:(o,t)=>new he(o,t),svg:(o,t)=>new ge(o,t),generator:o=>new wt(o),newSeed:()=>wt.newSeed()};var G=$(async(o,t,i)=>{let a,e=t.useHtmlLabels||J(V()?.htmlLabels);i?a=i:a="node default";let r=o.insert("g").attr("class",a).attr("id",t.domId||t.id),h=r.insert("g").attr("class","label").attr("style",U(t.labelStyle)),s;t.label===void 0?s="":s=typeof t.label=="string"?t.label:t.label[0];let c=await ht(h,Lt(xt(s),V()),{useHtmlLabels:e,width:t.width||V().flowchart?.wrappingWidth,cssClasses:"markdown-node-label",style:t.labelStyle,addSvgBackground:!!t.icon||!!t.img}),n=c.getBBox(),l=(t?.padding??0)/2;if(e){let g=c.children[0],f=Y(c),p=g.getElementsByTagName("img");if(p){let u=s.replace(/]*>/g,"").trim()==="";await Promise.all([...p].map(y=>new Promise(m=>{function d(){if(y.style.display="flex",y.style.flexDirection="column",u){let x=V().fontSize?V().fontSize:window.getComputedStyle(document.body).fontSize,b=5,[M=we.fontSize]=ke(x),w=M*b+"px";y.style.minWidth=w,y.style.maxWidth=w}else y.style.width="100%";m(y)}$(d,"setupImage"),setTimeout(()=>{y.complete&&d()}),y.addEventListener("error",d),y.addEventListener("load",d)})))}n=g.getBoundingClientRect(),f.attr("width",n.width),f.attr("height",n.height)}return e?h.attr("transform","translate("+-n.width/2+", "+-n.height/2+")"):h.attr("transform","translate(0, "+-n.height/2+")"),t.centerLabel&&h.attr("transform","translate("+-n.width/2+", "+-n.height/2+")"),h.insert("rect",":first-child"),{shapeSvg:r,bbox:n,halfPadding:l,label:h}},"labelHelper"),fe=$(async(o,t,i)=>{let a=i.useHtmlLabels||J(V()?.flowchart?.htmlLabels),e=o.insert("g").attr("class","label").attr("style",i.labelStyle||""),r=await ht(e,Lt(xt(t),V()),{useHtmlLabels:a,width:i.width||V()?.flowchart?.wrappingWidth,style:i.labelStyle,addSvgBackground:!!i.icon||!!i.img}),h=r.getBBox(),s=i.padding/2;if(J(V()?.flowchart?.htmlLabels)){let c=r.children[0],n=Y(r);h=c.getBoundingClientRect(),n.attr("width",h.width),n.attr("height",h.height)}return a?e.attr("transform","translate("+-h.width/2+", "+-h.height/2+")"):e.attr("transform","translate(0, "+-h.height/2+")"),i.centerLabel&&e.attr("transform","translate("+-h.width/2+", "+-h.height/2+")"),e.insert("rect",":first-child"),{shapeSvg:o,bbox:h,halfPadding:s,label:e}},"insertLabel"),H=$((o,t)=>{let i=t.node().getBBox();o.width=i.width,o.height=i.height},"updateNodeBounds"),_=$((o,t)=>(o.look==="handDrawn"?"rough-node":"node")+" "+o.cssClasses+" "+(t||""),"getNodeClasses");function q(o){let t=o.map((i,a)=>`${a===0?"M":"L"}${i.x},${i.y}`);return t.push("Z"),t.join(" ")}$(q,"createPathFromPoints");function pt(o,t,i,a,e,r){let h=[],c=i-o,n=a-t,l=c/r,g=2*Math.PI/l,f=t+n/2;for(let p=0;p<=50;p++){let u=p/50,y=o+u*c,m=f+e*Math.sin(g*(y-o));h.push({x:y,y:m})}return h}$(pt,"generateFullSineWavePoints");function At(o,t,i,a,e,r){let h=[],s=e*Math.PI/180,l=(r*Math.PI/180-s)/(a-1);for(let g=0;g{var i=o.x,a=o.y,e=t.x-i,r=t.y-a,h=o.width/2,s=o.height/2,c,n;return Math.abs(r)*h>Math.abs(e)*s?(r<0&&(s=-s),c=r===0?0:s*e/r,n=s):(e<0&&(h=-h),c=h,n=e===0?0:h*r/e),{x:i+c,y:a+n}},"intersectRect"),$t=ua;function Oe(o,t){t&&o.attr("style",t)}$(Oe,"applyStyle");async function _e(o){let t=Y(document.createElementNS("http://www.w3.org/2000/svg","foreignObject")),i=t.append("xhtml:div"),a=V(),e=o.label;o.label&&Yt(o.label)&&(e=await Se(o.label.replace($e.lineBreakRegex,` +`),a));let h='"+e+"";return i.html(Lt(h,a)),Oe(i,o.labelStyle),i.style("display","inline-block"),i.style("padding-right","1px"),i.style("white-space","nowrap"),i.attr("xmlns","http://www.w3.org/1999/xhtml"),t.node()}$(_e,"addHtmlLabel");var ya=$(async(o,t,i,a)=>{let e=o||"";if(typeof e=="object"&&(e=e[0]),J(V().flowchart.htmlLabels)){e=e.replace(/\\n|\n/g,"
"),F.info("vertexText"+e);let r={isNode:a,label:xt(e).replace(/fa[blrs]?:fa-[\w-]+/g,s=>``),labelStyle:t&&t.replace("fill:","color:")};return await _e(r)}else{let r=document.createElementNS("http://www.w3.org/2000/svg","text");r.setAttribute("style",t.replace("color:","fill:"));let h=[];typeof e=="string"?h=e.split(/\\n|\n|/gi):Array.isArray(e)?h=e:h=[];for(let s of h){let c=document.createElementNS("http://www.w3.org/2000/svg","tspan");c.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve"),c.setAttribute("dy","1em"),c.setAttribute("x","0"),i?c.setAttribute("class","title-row"):c.setAttribute("class","row"),c.textContent=s.trim(),r.appendChild(c)}return r}},"createLabel"),ue=ya,ft=$((o,t,i,a,e)=>["M",o+e,t,"H",o+i-e,"A",e,e,0,0,1,o+i,t+e,"V",t+a-e,"A",e,e,0,0,1,o+i-e,t+a,"H",o+e,"A",e,e,0,0,1,o,t+a-e,"V",t+e,"A",e,e,0,0,1,o+e,t,"Z"].join(" "),"createRoundedRectPathD"),ze=$(async(o,t)=>{F.info("Creating subgraph rect for ",t.id,t);let i=V(),{themeVariables:a,handDrawnSeed:e}=i,{clusterBkg:r,clusterBorder:h}=a,{labelStyles:s,nodeStyles:c,borderStyles:n,backgroundStyles:l}=T(t),g=o.insert("g").attr("class","cluster "+t.cssClasses).attr("id",t.id).attr("data-look",t.look),f=J(i.flowchart.htmlLabels),p=g.insert("g").attr("class","cluster-label "),u=await ht(p,t.label,{style:t.labelStyle,useHtmlLabels:f,isNode:!0}),y=u.getBBox();if(J(i.flowchart.htmlLabels)){let v=u.children[0],D=Y(u);y=v.getBoundingClientRect(),D.attr("width",y.width),D.attr("height",y.height)}let m=t.width<=y.width+t.padding?y.width+t.padding:t.width;t.width<=y.width+t.padding?t.diff=(m-t.width)/2-t.padding:t.diff=-t.padding;let d=t.height,x=t.x-m/2,b=t.y-d/2;F.trace("Data ",t,JSON.stringify(t));let M;if(t.look==="handDrawn"){let v=S.svg(g),D=W(t,{roughness:.7,fill:r,stroke:h,fillWeight:3,seed:e}),B=v.path(ft(x,b,m,d,0),D);M=g.insert(()=>(F.debug("Rough node insert CXC",B),B),":first-child"),M.select("path:nth-child(2)").attr("style",n.join(";")),M.select("path").attr("style",l.join(";").replace("fill","stroke"))}else M=g.insert("rect",":first-child"),M.attr("style",c).attr("rx",t.rx).attr("ry",t.ry).attr("x",x).attr("y",b).attr("width",m).attr("height",d);let{subGraphTitleTopMargin:w}=Zt(i);if(p.attr("transform",`translate(${t.x-y.width/2}, ${t.y-t.height/2+w})`),s){let v=p.select("span");v&&v.attr("style",s)}let k=M.node().getBBox();return t.offsetX=0,t.width=k.width,t.height=k.height,t.offsetY=y.height-t.padding/2,t.intersect=function(v){return $t(t,v)},{cluster:g,labelBBox:y}},"rect"),da=$((o,t)=>{let i=o.insert("g").attr("class","note-cluster").attr("id",t.id),a=i.insert("rect",":first-child"),e=0*t.padding,r=e/2;a.attr("rx",t.rx).attr("ry",t.ry).attr("x",t.x-t.width/2-r).attr("y",t.y-t.height/2-r).attr("width",t.width+e).attr("height",t.height+e).attr("fill","none");let h=a.node().getBBox();return t.width=h.width,t.height=h.height,t.intersect=function(s){return $t(t,s)},{cluster:i,labelBBox:{width:0,height:0}}},"noteGroup"),ma=$(async(o,t)=>{let i=V(),{themeVariables:a,handDrawnSeed:e}=i,{altBackground:r,compositeBackground:h,compositeTitleBackground:s,nodeBorder:c}=a,n=o.insert("g").attr("class",t.cssClasses).attr("id",t.id).attr("data-id",t.id).attr("data-look",t.look),l=n.insert("g",":first-child"),g=n.insert("g").attr("class","cluster-label"),f=n.append("rect"),p=g.node().appendChild(await ue(t.label,t.labelStyle,void 0,!0)),u=p.getBBox();if(J(i.flowchart.htmlLabels)){let B=p.children[0],L=Y(p);u=B.getBoundingClientRect(),L.attr("width",u.width),L.attr("height",u.height)}let y=0*t.padding,m=y/2,d=(t.width<=u.width+t.padding?u.width+t.padding:t.width)+y;t.width<=u.width+t.padding?t.diff=(d-t.width)/2-t.padding:t.diff=-t.padding;let x=t.height+y,b=t.height+y-u.height-6,M=t.x-d/2,w=t.y-x/2;t.width=d;let k=t.y-t.height/2-m+u.height+2,v;if(t.look==="handDrawn"){let B=t.cssClasses.includes("statediagram-cluster-alt"),L=S.svg(n),A=t.rx||t.ry?L.path(ft(M,w,d,x,10),{roughness:.7,fill:s,fillStyle:"solid",stroke:c,seed:e}):L.rectangle(M,w,d,x,{seed:e});v=n.insert(()=>A,":first-child");let I=L.rectangle(M,k,d,b,{fill:B?r:h,fillStyle:B?"hachure":"solid",stroke:c,seed:e});v=n.insert(()=>A,":first-child"),f=n.insert(()=>I)}else v=l.insert("rect",":first-child"),v.attr("class","outer").attr("x",M).attr("y",w).attr("width",d).attr("height",x).attr("data-look",t.look),f.attr("class","inner").attr("x",M).attr("y",k).attr("width",d).attr("height",b);g.attr("transform",`translate(${t.x-u.width/2}, ${w+1-(J(i.flowchart.htmlLabels)?0:3)})`);let D=v.node().getBBox();return t.height=D.height,t.offsetX=0,t.offsetY=u.height-t.padding/2,t.labelBBox=u,t.intersect=function(B){return $t(t,B)},{cluster:n,labelBBox:u}},"roundedWithTitle"),xa=$(async(o,t)=>{F.info("Creating subgraph rect for ",t.id,t);let i=V(),{themeVariables:a,handDrawnSeed:e}=i,{clusterBkg:r,clusterBorder:h}=a,{labelStyles:s,nodeStyles:c,borderStyles:n,backgroundStyles:l}=T(t),g=o.insert("g").attr("class","cluster "+t.cssClasses).attr("id",t.id).attr("data-look",t.look),f=J(i.flowchart.htmlLabels),p=g.insert("g").attr("class","cluster-label "),u=await ht(p,t.label,{style:t.labelStyle,useHtmlLabels:f,isNode:!0,width:t.width}),y=u.getBBox();if(J(i.flowchart.htmlLabels)){let v=u.children[0],D=Y(u);y=v.getBoundingClientRect(),D.attr("width",y.width),D.attr("height",y.height)}let m=t.width<=y.width+t.padding?y.width+t.padding:t.width;t.width<=y.width+t.padding?t.diff=(m-t.width)/2-t.padding:t.diff=-t.padding;let d=t.height,x=t.x-m/2,b=t.y-d/2;F.trace("Data ",t,JSON.stringify(t));let M;if(t.look==="handDrawn"){let v=S.svg(g),D=W(t,{roughness:.7,fill:r,stroke:h,fillWeight:4,seed:e}),B=v.path(ft(x,b,m,d,t.rx),D);M=g.insert(()=>(F.debug("Rough node insert CXC",B),B),":first-child"),M.select("path:nth-child(2)").attr("style",n.join(";")),M.select("path").attr("style",l.join(";").replace("fill","stroke"))}else M=g.insert("rect",":first-child"),M.attr("style",c).attr("rx",t.rx).attr("ry",t.ry).attr("x",x).attr("y",b).attr("width",m).attr("height",d);let{subGraphTitleTopMargin:w}=Zt(i);if(p.attr("transform",`translate(${t.x-y.width/2}, ${t.y-t.height/2+w})`),s){let v=p.select("span");v&&v.attr("style",s)}let k=M.node().getBBox();return t.offsetX=0,t.width=k.width,t.height=k.height,t.offsetY=y.height-t.padding/2,t.intersect=function(v){return $t(t,v)},{cluster:g,labelBBox:y}},"kanbanSection"),ba=$((o,t)=>{let i=V(),{themeVariables:a,handDrawnSeed:e}=i,{nodeBorder:r}=a,h=o.insert("g").attr("class",t.cssClasses).attr("id",t.id).attr("data-look",t.look),s=h.insert("g",":first-child"),c=0*t.padding,n=t.width+c;t.diff=-t.padding;let l=t.height+c,g=t.x-n/2,f=t.y-l/2;t.width=n;let p;if(t.look==="handDrawn"){let m=S.svg(h).rectangle(g,f,n,l,{fill:"lightgrey",roughness:.5,strokeLineDash:[5],stroke:r,seed:e});p=h.insert(()=>m,":first-child")}else p=s.insert("rect",":first-child"),p.attr("class","divider").attr("x",g).attr("y",f).attr("width",n).attr("height",l).attr("data-look",t.look);let u=p.node().getBBox();return t.height=u.height,t.offsetX=0,t.offsetY=0,t.intersect=function(y){return $t(t,y)},{cluster:h,labelBBox:{}}},"divider"),wa=ze,Sa={rect:ze,squareRect:wa,roundedWithTitle:ma,noteGroup:da,divider:ba,kanbanSection:xa},je=new Map,Ua=$(async(o,t)=>{let i=t.shape||"rect",a=await Sa[i](o,t);return je.set(t.id,a),a},"insertCluster"),tr=$(()=>{je=new Map},"clear");function Ge(o,t){return o.intersect(t)}$(Ge,"intersectNode");var $a=Ge;function qe(o,t,i,a){var e=o.x,r=o.y,h=e-a.x,s=r-a.y,c=Math.sqrt(t*t*s*s+i*i*h*h),n=Math.abs(t*i*h/c);a.x0}$(ye,"sameSign");var ka=Ye;function Ve(o,t,i){let a=o.x,e=o.y,r=[],h=Number.POSITIVE_INFINITY,s=Number.POSITIVE_INFINITY;typeof t.forEach=="function"?t.forEach(function(l){h=Math.min(h,l.x),s=Math.min(s,l.y)}):(h=Math.min(h,t.x),s=Math.min(s,t.y));let c=a-o.width/2-h,n=e-o.height/2-s;for(let l=0;l1&&r.sort(function(l,g){let f=l.x-i.x,p=l.y-i.y,u=Math.sqrt(f*f+p*p),y=g.x-i.x,m=g.y-i.y,d=Math.sqrt(y*y+m*m);return ul,":first-child");return g.attr("class","anchor").attr("style",U(s)),H(t,g),t.intersect=function(f){return F.info("Circle intersect",t,h,f),N.circle(t,h,f)},r}$(Ze,"anchor");function de(o,t,i,a,e,r,h){let c=(o+i)/2,n=(t+a)/2,l=Math.atan2(a-t,i-o),g=(i-o)/2,f=(a-t)/2,p=g/e,u=f/r,y=Math.sqrt(p**2+u**2);if(y>1)throw new Error("The given radii are too small to create an arc between the points.");let m=Math.sqrt(1-y**2),d=c+m*r*Math.sin(l)*(h?-1:1),x=n-m*e*Math.cos(l)*(h?-1:1),b=Math.atan2((t-x)/r,(o-d)/e),w=Math.atan2((a-x)/r,(i-d)/e)-b;h&&w<0&&(w+=2*Math.PI),!h&&w>0&&(w-=2*Math.PI);let k=[];for(let v=0;v<20;v++){let D=v/19,B=b+D*w,L=d+e*Math.cos(B),A=x+r*Math.sin(B);k.push({x:L,y:A})}return k}$(de,"generateArcPoints");async function Qe(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r}=await G(o,t,_(t)),h=r.width+t.padding+20,s=r.height+t.padding,c=s/2,n=c/(2.5+s/50),{cssStyles:l}=t,g=[{x:h/2,y:-s/2},{x:-h/2,y:-s/2},...de(-h/2,-s/2,-h/2,s/2,n,c,!1),{x:h/2,y:s/2},...de(h/2,s/2,h/2,-s/2,n,c,!0)],f=S.svg(e),p=W(t,{});t.look!=="handDrawn"&&(p.roughness=0,p.fillStyle="solid");let u=q(g),y=f.path(u,p),m=e.insert(()=>y,":first-child");return m.attr("class","basic label-container"),l&&t.look!=="handDrawn"&&m.selectAll("path").attr("style",l),a&&t.look!=="handDrawn"&&m.selectAll("path").attr("style",a),m.attr("transform",`translate(${n/2}, 0)`),H(t,m),t.intersect=function(d){return N.polygon(t,g,d)},e}$(Qe,"bowTieRect");function ut(o,t,i,a){return o.insert("polygon",":first-child").attr("points",a.map(function(e){return e.x+","+e.y}).join(" ")).attr("class","label-container").attr("transform","translate("+-t/2+","+i/2+")")}$(ut,"insertPolygonShape");async function Je(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r}=await G(o,t,_(t)),h=r.height+t.padding,s=12,c=r.width+t.padding+s,n=0,l=c,g=-h,f=0,p=[{x:n+s,y:g},{x:l,y:g},{x:l,y:f},{x:n,y:f},{x:n,y:g+s},{x:n+s,y:g}],u,{cssStyles:y}=t;if(t.look==="handDrawn"){let m=S.svg(e),d=W(t,{}),x=q(p),b=m.path(x,d);u=e.insert(()=>b,":first-child").attr("transform",`translate(${-c/2}, ${h/2})`),y&&u.attr("style",y)}else u=ut(e,c,h,p);return a&&u.attr("style",a),H(t,u),t.intersect=function(m){return N.polygon(t,p,m)},e}$(Je,"card");function Ke(o,t){let{nodeStyles:i}=T(t);t.label="";let a=o.insert("g").attr("class",_(t)).attr("id",t.domId??t.id),{cssStyles:e}=t,r=Math.max(28,t.width??0),h=[{x:0,y:r/2},{x:r/2,y:0},{x:0,y:-r/2},{x:-r/2,y:0}],s=S.svg(a),c=W(t,{});t.look!=="handDrawn"&&(c.roughness=0,c.fillStyle="solid");let n=q(h),l=s.path(n,c),g=a.insert(()=>l,":first-child");return e&&t.look!=="handDrawn"&&g.selectAll("path").attr("style",e),i&&t.look!=="handDrawn"&&g.selectAll("path").attr("style",i),t.width=28,t.height=28,t.intersect=function(f){return N.polygon(t,h,f)},a}$(Ke,"choice");async function me(o,t,i){let{labelStyles:a,nodeStyles:e}=T(t);t.labelStyle=a;let{shapeSvg:r,bbox:h,halfPadding:s}=await G(o,t,_(t)),c=i?.padding??s,n=h.width/2+c,l,{cssStyles:g}=t;if(t.look==="handDrawn"){let f=S.svg(r),p=W(t,{}),u=f.circle(0,0,n*2,p);l=r.insert(()=>u,":first-child"),l.attr("class","basic label-container").attr("style",U(g))}else l=r.insert("circle",":first-child").attr("class","basic label-container").attr("style",e).attr("r",n).attr("cx",0).attr("cy",0);return H(t,l),t.calcIntersect=function(f,p){let u=f.width/2;return N.circle(f,u,p)},t.intersect=function(f){return F.info("Circle intersect",t,n,f),N.circle(t,n,f)},r}$(me,"circle");function Ue(o){let t=Math.cos(Math.PI/4),i=Math.sin(Math.PI/4),a=o*2,e={x:a/2*t,y:a/2*i},r={x:-(a/2)*t,y:a/2*i},h={x:-(a/2)*t,y:-(a/2)*i},s={x:a/2*t,y:-(a/2)*i};return`M ${r.x},${r.y} L ${s.x},${s.y} + M ${e.x},${e.y} L ${h.x},${h.y}`}$(Ue,"createLine");function ts(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i,t.label="";let e=o.insert("g").attr("class",_(t)).attr("id",t.domId??t.id),r=Math.max(30,t?.width??0),{cssStyles:h}=t,s=S.svg(e),c=W(t,{});t.look!=="handDrawn"&&(c.roughness=0,c.fillStyle="solid");let n=s.circle(0,0,r*2,c),l=Ue(r),g=s.path(l,c),f=e.insert(()=>n,":first-child");return f.insert(()=>g),h&&t.look!=="handDrawn"&&f.selectAll("path").attr("style",h),a&&t.look!=="handDrawn"&&f.selectAll("path").attr("style",a),H(t,f),t.intersect=function(p){return F.info("crossedCircle intersect",t,{radius:r,point:p}),N.circle(t,r,p)},e}$(ts,"crossedCircle");function lt(o,t,i,a=100,e=0,r=180){let h=[],s=e*Math.PI/180,l=(r*Math.PI/180-s)/(a-1);for(let g=0;gb,":first-child").attr("stroke-opacity",0),M.insert(()=>d,":first-child"),M.attr("class","text"),l&&t.look!=="handDrawn"&&M.selectAll("path").attr("style",l),a&&t.look!=="handDrawn"&&M.selectAll("path").attr("style",a),M.attr("transform",`translate(${n}, 0)`),h.attr("transform",`translate(${-s/2+n-(r.x-(r.left??0))},${-c/2+(t.padding??0)/2-(r.y-(r.top??0))})`),H(t,M),t.intersect=function(w){return N.polygon(t,f,w)},e}$(es,"curlyBraceLeft");function ct(o,t,i,a=100,e=0,r=180){let h=[],s=e*Math.PI/180,l=(r*Math.PI/180-s)/(a-1);for(let g=0;gb,":first-child").attr("stroke-opacity",0),M.insert(()=>d,":first-child"),M.attr("class","text"),l&&t.look!=="handDrawn"&&M.selectAll("path").attr("style",l),a&&t.look!=="handDrawn"&&M.selectAll("path").attr("style",a),M.attr("transform",`translate(${-n}, 0)`),h.attr("transform",`translate(${-s/2+(t.padding??0)/2-(r.x-(r.left??0))},${-c/2+(t.padding??0)/2-(r.y-(r.top??0))})`),H(t,M),t.intersect=function(w){return N.polygon(t,f,w)},e}$(ss,"curlyBraceRight");function K(o,t,i,a=100,e=0,r=180){let h=[],s=e*Math.PI/180,l=(r*Math.PI/180-s)/(a-1);for(let g=0;gv,":first-child").attr("stroke-opacity",0),D.insert(()=>x,":first-child"),D.insert(()=>w,":first-child"),D.attr("class","text"),l&&t.look!=="handDrawn"&&D.selectAll("path").attr("style",l),a&&t.look!=="handDrawn"&&D.selectAll("path").attr("style",a),D.attr("transform",`translate(${n-n/4}, 0)`),h.attr("transform",`translate(${-s/2+(t.padding??0)/2-(r.x-(r.left??0))},${-c/2+(t.padding??0)/2-(r.y-(r.top??0))})`),H(t,D),t.intersect=function(B){return N.polygon(t,p,B)},e}$(as,"curlyBraces");async function rs(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r}=await G(o,t,_(t)),h=80,s=20,c=Math.max(h,(r.width+(t.padding??0)*2)*1.25,t?.width??0),n=Math.max(s,r.height+(t.padding??0)*2,t?.height??0),l=n/2,{cssStyles:g}=t,f=S.svg(e),p=W(t,{});t.look!=="handDrawn"&&(p.roughness=0,p.fillStyle="solid");let u=c,y=n,m=u-l,d=y/4,x=[{x:m,y:0},{x:d,y:0},{x:0,y:y/2},{x:d,y},{x:m,y},...At(-m,-y/2,l,50,270,90)],b=q(x),M=f.path(b,p),w=e.insert(()=>M,":first-child");return w.attr("class","basic label-container"),g&&t.look!=="handDrawn"&&w.selectChildren("path").attr("style",g),a&&t.look!=="handDrawn"&&w.selectChildren("path").attr("style",a),w.attr("transform",`translate(${-c/2}, ${-n/2})`),H(t,w),t.intersect=function(k){return N.polygon(t,x,k)},e}$(rs,"curvedTrapezoid");var Da=$((o,t,i,a,e,r)=>[`M${o},${t+r}`,`a${e},${r} 0,0,0 ${i},0`,`a${e},${r} 0,0,0 ${-i},0`,`l0,${a}`,`a${e},${r} 0,0,0 ${i},0`,`l0,${-a}`].join(" "),"createCylinderPathD"),Pa=$((o,t,i,a,e,r)=>[`M${o},${t+r}`,`M${o+i},${t+r}`,`a${e},${r} 0,0,0 ${-i},0`,`l0,${a}`,`a${e},${r} 0,0,0 ${i},0`,`l0,${-a}`].join(" "),"createOuterCylinderPathD"),Ba=$((o,t,i,a,e,r)=>[`M${o-i/2},${-a/2}`,`a${e},${r} 0,0,0 ${i},0`].join(" "),"createInnerCylinderPathD");async function ns(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,label:h}=await G(o,t,_(t)),s=Math.max(r.width+t.padding,t.width??0),c=s/2,n=c/(2.5+s/50),l=Math.max(r.height+n+t.padding,t.height??0),g,{cssStyles:f}=t;if(t.look==="handDrawn"){let p=S.svg(e),u=Pa(0,0,s,l,c,n),y=Ba(0,n,s,l,c,n),m=p.path(u,W(t,{})),d=p.path(y,W(t,{fill:"none"}));g=e.insert(()=>d,":first-child"),g=e.insert(()=>m,":first-child"),g.attr("class","basic label-container"),f&&g.attr("style",f)}else{let p=Da(0,0,s,l,c,n);g=e.insert("path",":first-child").attr("d",p).attr("class","basic label-container").attr("style",U(f)).attr("style",a)}return g.attr("label-offset-y",n),g.attr("transform",`translate(${-s/2}, ${-(l/2+n)})`),H(t,g),h.attr("transform",`translate(${-(r.width/2)-(r.x-(r.left??0))}, ${-(r.height/2)+(t.padding??0)/1.5-(r.y-(r.top??0))})`),t.intersect=function(p){let u=N.rect(t,p),y=u.x-(t.x??0);if(c!=0&&(Math.abs(y)<(t.width??0)/2||Math.abs(y)==(t.width??0)/2&&Math.abs(u.y-(t.y??0))>(t.height??0)/2-n)){let m=n*n*(1-y*y/(c*c));m>0&&(m=Math.sqrt(m)),m=n-m,p.y-(t.y??0)>0&&(m=-m),u.y+=m}return u},e}$(ns,"cylinder");async function is(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,label:h}=await G(o,t,_(t)),s=r.width+t.padding,c=r.height+t.padding,n=c*.2,l=-s/2,g=-c/2-n/2,{cssStyles:f}=t,p=S.svg(e),u=W(t,{});t.look!=="handDrawn"&&(u.roughness=0,u.fillStyle="solid");let y=[{x:l,y:g+n},{x:-l,y:g+n},{x:-l,y:-g},{x:l,y:-g},{x:l,y:g},{x:-l,y:g},{x:-l,y:g+n}],m=p.polygon(y.map(x=>[x.x,x.y]),u),d=e.insert(()=>m,":first-child");return d.attr("class","basic label-container"),f&&t.look!=="handDrawn"&&d.selectAll("path").attr("style",f),a&&t.look!=="handDrawn"&&d.selectAll("path").attr("style",a),h.attr("transform",`translate(${l+(t.padding??0)/2-(r.x-(r.left??0))}, ${g+n+(t.padding??0)/2-(r.y-(r.top??0))})`),H(t,d),t.intersect=function(x){return N.rect(t,x)},e}$(is,"dividedRectangle");async function ls(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,halfPadding:h}=await G(o,t,_(t)),c=r.width/2+h+5,n=r.width/2+h,l,{cssStyles:g}=t;if(t.look==="handDrawn"){let f=S.svg(e),p=W(t,{roughness:.2,strokeWidth:2.5}),u=W(t,{roughness:.2,strokeWidth:1.5}),y=f.circle(0,0,c*2,p),m=f.circle(0,0,n*2,u);l=e.insert("g",":first-child"),l.attr("class",U(t.cssClasses)).attr("style",U(g)),l.node()?.appendChild(y),l.node()?.appendChild(m)}else{l=e.insert("g",":first-child");let f=l.insert("circle",":first-child"),p=l.insert("circle");l.attr("class","basic label-container").attr("style",a),f.attr("class","outer-circle").attr("style",a).attr("r",c).attr("cx",0).attr("cy",0),p.attr("class","inner-circle").attr("style",a).attr("r",n).attr("cx",0).attr("cy",0)}return H(t,l),t.intersect=function(f){return F.info("DoubleCircle intersect",t,c,f),N.circle(t,c,f)},e}$(ls,"doublecircle");function cs(o,t,{config:{themeVariables:i}}){let{labelStyles:a,nodeStyles:e}=T(t);t.label="",t.labelStyle=a;let r=o.insert("g").attr("class",_(t)).attr("id",t.domId??t.id),h=7,{cssStyles:s}=t,c=S.svg(r),{nodeBorder:n}=i,l=W(t,{fillStyle:"solid"});t.look!=="handDrawn"&&(l.roughness=0);let g=c.circle(0,0,h*2,l),f=r.insert(()=>g,":first-child");return f.selectAll("path").attr("style",`fill: ${n} !important;`),s&&s.length>0&&t.look!=="handDrawn"&&f.selectAll("path").attr("style",s),e&&t.look!=="handDrawn"&&f.selectAll("path").attr("style",e),H(t,f),t.intersect=function(p){return F.info("filledCircle intersect",t,{radius:h,point:p}),N.circle(t,h,p)},r}$(cs,"filledCircle");async function os(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,label:h}=await G(o,t,_(t)),s=r.width+(t.padding??0),c=s+r.height,n=s+r.height,l=[{x:0,y:-c},{x:n,y:-c},{x:n/2,y:0}],{cssStyles:g}=t,f=S.svg(e),p=W(t,{});t.look!=="handDrawn"&&(p.roughness=0,p.fillStyle="solid");let u=q(l),y=f.path(u,p),m=e.insert(()=>y,":first-child").attr("transform",`translate(${-c/2}, ${c/2})`);return g&&t.look!=="handDrawn"&&m.selectChildren("path").attr("style",g),a&&t.look!=="handDrawn"&&m.selectChildren("path").attr("style",a),t.width=s,t.height=c,H(t,m),h.attr("transform",`translate(${-r.width/2-(r.x-(r.left??0))}, ${-c/2+(t.padding??0)/2+(r.y-(r.top??0))})`),t.intersect=function(d){return F.info("Triangle intersect",t,l,d),N.polygon(t,l,d)},e}$(os,"flippedTriangle");function hs(o,t,{dir:i,config:{state:a,themeVariables:e}}){let{nodeStyles:r}=T(t);t.label="";let h=o.insert("g").attr("class",_(t)).attr("id",t.domId??t.id),{cssStyles:s}=t,c=Math.max(70,t?.width??0),n=Math.max(10,t?.height??0);i==="LR"&&(c=Math.max(10,t?.width??0),n=Math.max(70,t?.height??0));let l=-1*c/2,g=-1*n/2,f=S.svg(h),p=W(t,{stroke:e.lineColor,fill:e.lineColor});t.look!=="handDrawn"&&(p.roughness=0,p.fillStyle="solid");let u=f.rectangle(l,g,c,n,p),y=h.insert(()=>u,":first-child");s&&t.look!=="handDrawn"&&y.selectAll("path").attr("style",s),r&&t.look!=="handDrawn"&&y.selectAll("path").attr("style",r),H(t,y);let m=a?.padding??0;return t.width&&t.height&&(t.width+=m/2||0,t.height+=m/2||0),t.intersect=function(d){return N.rect(t,d)},h}$(hs,"forkJoin");async function gs(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let e=80,r=50,{shapeSvg:h,bbox:s}=await G(o,t,_(t)),c=Math.max(e,s.width+(t.padding??0)*2,t?.width??0),n=Math.max(r,s.height+(t.padding??0)*2,t?.height??0),l=n/2,{cssStyles:g}=t,f=S.svg(h),p=W(t,{});t.look!=="handDrawn"&&(p.roughness=0,p.fillStyle="solid");let u=[{x:-c/2,y:-n/2},{x:c/2-l,y:-n/2},...At(-c/2+l,0,l,50,90,270),{x:c/2-l,y:n/2},{x:-c/2,y:n/2}],y=q(u),m=f.path(y,p),d=h.insert(()=>m,":first-child");return d.attr("class","basic label-container"),g&&t.look!=="handDrawn"&&d.selectChildren("path").attr("style",g),a&&t.look!=="handDrawn"&&d.selectChildren("path").attr("style",a),H(t,d),t.intersect=function(x){return F.info("Pill intersect",t,{radius:l,point:x}),N.polygon(t,u,x)},h}$(gs,"halfRoundedRectangle");async function ps(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r}=await G(o,t,_(t)),h=r.height+(t.padding??0),s=r.width+(t.padding??0)*2.5,{cssStyles:c}=t,n=S.svg(e),l=W(t,{});t.look!=="handDrawn"&&(l.roughness=0,l.fillStyle="solid");let g=s/2,f=g/6;g=g+f;let p=h/2,u=p/2,y=g-u,m=[{x:-y,y:-p},{x:0,y:-p},{x:y,y:-p},{x:g,y:0},{x:y,y:p},{x:0,y:p},{x:-y,y:p},{x:-g,y:0}],d=q(m),x=n.path(d,l),b=e.insert(()=>x,":first-child");return b.attr("class","basic label-container"),c&&t.look!=="handDrawn"&&b.selectChildren("path").attr("style",c),a&&t.look!=="handDrawn"&&b.selectChildren("path").attr("style",a),t.width=s,t.height=h,H(t,b),t.intersect=function(M){return N.polygon(t,m,M)},e}$(ps,"hexagon");async function fs(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.label="",t.labelStyle=i;let{shapeSvg:e}=await G(o,t,_(t)),r=Math.max(30,t?.width??0),h=Math.max(30,t?.height??0),{cssStyles:s}=t,c=S.svg(e),n=W(t,{});t.look!=="handDrawn"&&(n.roughness=0,n.fillStyle="solid");let l=[{x:0,y:0},{x:r,y:0},{x:0,y:h},{x:r,y:h}],g=q(l),f=c.path(g,n),p=e.insert(()=>f,":first-child");return p.attr("class","basic label-container"),s&&t.look!=="handDrawn"&&p.selectChildren("path").attr("style",s),a&&t.look!=="handDrawn"&&p.selectChildren("path").attr("style",a),p.attr("transform",`translate(${-r/2}, ${-h/2})`),H(t,p),t.intersect=function(u){return F.info("Pill intersect",t,{points:l}),N.polygon(t,l,u)},e}$(fs,"hourglass");async function us(o,t,{config:{themeVariables:i,flowchart:a}}){let{labelStyles:e}=T(t);t.labelStyle=e;let r=t.assetHeight??48,h=t.assetWidth??48,s=Math.max(r,h),c=a?.wrappingWidth;t.width=Math.max(s,c??0);let{shapeSvg:n,bbox:l,label:g}=await G(o,t,"icon-shape default"),f=t.pos==="t",p=s,u=s,{nodeBorder:y}=i,{stylesMap:m}=Mt(t),d=-u/2,x=-p/2,b=t.label?8:0,M=S.svg(n),w=W(t,{stroke:"none",fill:"none"});t.look!=="handDrawn"&&(w.roughness=0,w.fillStyle="solid");let k=M.rectangle(d,x,u,p,w),v=Math.max(u,l.width),D=p+l.height+b,B=M.rectangle(-v/2,-D/2,v,D,{...w,fill:"transparent",stroke:"none"}),L=n.insert(()=>k,":first-child"),A=n.insert(()=>B);if(t.icon){let I=n.append("g");I.html(`${await vt(t.icon,{height:s,width:s,fallbackPrefix:""})}`);let P=I.node().getBBox(),C=P.width,E=P.height,R=P.x,O=P.y;I.attr("transform",`translate(${-C/2-R},${f?l.height/2+b/2-E/2-O:-l.height/2-b/2-E/2-O})`),I.attr("style",`color: ${m.get("stroke")??y};`)}return g.attr("transform",`translate(${-l.width/2-(l.x-(l.left??0))},${f?-D/2:D/2-l.height})`),L.attr("transform",`translate(0,${f?l.height/2+b/2:-l.height/2-b/2})`),H(t,A),t.intersect=function(I){if(F.info("iconSquare intersect",t,I),!t.label)return N.rect(t,I);let P=t.x??0,C=t.y??0,E=t.height??0,R=[];return f?R=[{x:P-l.width/2,y:C-E/2},{x:P+l.width/2,y:C-E/2},{x:P+l.width/2,y:C-E/2+l.height+b},{x:P+u/2,y:C-E/2+l.height+b},{x:P+u/2,y:C+E/2},{x:P-u/2,y:C+E/2},{x:P-u/2,y:C-E/2+l.height+b},{x:P-l.width/2,y:C-E/2+l.height+b}]:R=[{x:P-u/2,y:C-E/2},{x:P+u/2,y:C-E/2},{x:P+u/2,y:C-E/2+p},{x:P+l.width/2,y:C-E/2+p},{x:P+l.width/2/2,y:C+E/2},{x:P-l.width/2,y:C+E/2},{x:P-l.width/2,y:C-E/2+p},{x:P-u/2,y:C-E/2+p}],N.polygon(t,R,I)},n}$(us,"icon");async function ys(o,t,{config:{themeVariables:i,flowchart:a}}){let{labelStyles:e}=T(t);t.labelStyle=e;let r=t.assetHeight??48,h=t.assetWidth??48,s=Math.max(r,h),c=a?.wrappingWidth;t.width=Math.max(s,c??0);let{shapeSvg:n,bbox:l,label:g}=await G(o,t,"icon-shape default"),f=20,p=t.label?8:0,u=t.pos==="t",{nodeBorder:y,mainBkg:m}=i,{stylesMap:d}=Mt(t),x=S.svg(n),b=W(t,{});t.look!=="handDrawn"&&(b.roughness=0,b.fillStyle="solid");let M=d.get("fill");b.stroke=M??m;let w=n.append("g");t.icon&&w.html(`${await vt(t.icon,{height:s,width:s,fallbackPrefix:""})}`);let k=w.node().getBBox(),v=k.width,D=k.height,B=k.x,L=k.y,A=Math.max(v,D)*Math.SQRT2+f*2,I=x.circle(0,0,A,b),P=Math.max(A,l.width),C=A+l.height+p,E=x.rectangle(-P/2,-C/2,P,C,{...b,fill:"transparent",stroke:"none"}),R=n.insert(()=>I,":first-child"),O=n.insert(()=>E);return w.attr("transform",`translate(${-v/2-B},${u?l.height/2+p/2-D/2-L:-l.height/2-p/2-D/2-L})`),w.attr("style",`color: ${d.get("stroke")??y};`),g.attr("transform",`translate(${-l.width/2-(l.x-(l.left??0))},${u?-C/2:C/2-l.height})`),R.attr("transform",`translate(0,${u?l.height/2+p/2:-l.height/2-p/2})`),H(t,O),t.intersect=function(z){return F.info("iconSquare intersect",t,z),N.rect(t,z)},n}$(ys,"iconCircle");async function ds(o,t,{config:{themeVariables:i,flowchart:a}}){let{labelStyles:e}=T(t);t.labelStyle=e;let r=t.assetHeight??48,h=t.assetWidth??48,s=Math.max(r,h),c=a?.wrappingWidth;t.width=Math.max(s,c??0);let{shapeSvg:n,bbox:l,halfPadding:g,label:f}=await G(o,t,"icon-shape default"),p=t.pos==="t",u=s+g*2,y=s+g*2,{nodeBorder:m,mainBkg:d}=i,{stylesMap:x}=Mt(t),b=-y/2,M=-u/2,w=t.label?8:0,k=S.svg(n),v=W(t,{});t.look!=="handDrawn"&&(v.roughness=0,v.fillStyle="solid");let D=x.get("fill");v.stroke=D??d;let B=k.path(ft(b,M,y,u,5),v),L=Math.max(y,l.width),A=u+l.height+w,I=k.rectangle(-L/2,-A/2,L,A,{...v,fill:"transparent",stroke:"none"}),P=n.insert(()=>B,":first-child").attr("class","icon-shape2"),C=n.insert(()=>I);if(t.icon){let E=n.append("g");E.html(`${await vt(t.icon,{height:s,width:s,fallbackPrefix:""})}`);let R=E.node().getBBox(),O=R.width,z=R.height,Z=R.x,rt=R.y;E.attr("transform",`translate(${-O/2-Z},${p?l.height/2+w/2-z/2-rt:-l.height/2-w/2-z/2-rt})`),E.attr("style",`color: ${x.get("stroke")??m};`)}return f.attr("transform",`translate(${-l.width/2-(l.x-(l.left??0))},${p?-A/2:A/2-l.height})`),P.attr("transform",`translate(0,${p?l.height/2+w/2:-l.height/2-w/2})`),H(t,C),t.intersect=function(E){if(F.info("iconSquare intersect",t,E),!t.label)return N.rect(t,E);let R=t.x??0,O=t.y??0,z=t.height??0,Z=[];return p?Z=[{x:R-l.width/2,y:O-z/2},{x:R+l.width/2,y:O-z/2},{x:R+l.width/2,y:O-z/2+l.height+w},{x:R+y/2,y:O-z/2+l.height+w},{x:R+y/2,y:O+z/2},{x:R-y/2,y:O+z/2},{x:R-y/2,y:O-z/2+l.height+w},{x:R-l.width/2,y:O-z/2+l.height+w}]:Z=[{x:R-y/2,y:O-z/2},{x:R+y/2,y:O-z/2},{x:R+y/2,y:O-z/2+u},{x:R+l.width/2,y:O-z/2+u},{x:R+l.width/2/2,y:O+z/2},{x:R-l.width/2,y:O+z/2},{x:R-l.width/2,y:O-z/2+u},{x:R-y/2,y:O-z/2+u}],N.polygon(t,Z,E)},n}$(ds,"iconRounded");async function ms(o,t,{config:{themeVariables:i,flowchart:a}}){let{labelStyles:e}=T(t);t.labelStyle=e;let r=t.assetHeight??48,h=t.assetWidth??48,s=Math.max(r,h),c=a?.wrappingWidth;t.width=Math.max(s,c??0);let{shapeSvg:n,bbox:l,halfPadding:g,label:f}=await G(o,t,"icon-shape default"),p=t.pos==="t",u=s+g*2,y=s+g*2,{nodeBorder:m,mainBkg:d}=i,{stylesMap:x}=Mt(t),b=-y/2,M=-u/2,w=t.label?8:0,k=S.svg(n),v=W(t,{});t.look!=="handDrawn"&&(v.roughness=0,v.fillStyle="solid");let D=x.get("fill");v.stroke=D??d;let B=k.path(ft(b,M,y,u,.1),v),L=Math.max(y,l.width),A=u+l.height+w,I=k.rectangle(-L/2,-A/2,L,A,{...v,fill:"transparent",stroke:"none"}),P=n.insert(()=>B,":first-child"),C=n.insert(()=>I);if(t.icon){let E=n.append("g");E.html(`${await vt(t.icon,{height:s,width:s,fallbackPrefix:""})}`);let R=E.node().getBBox(),O=R.width,z=R.height,Z=R.x,rt=R.y;E.attr("transform",`translate(${-O/2-Z},${p?l.height/2+w/2-z/2-rt:-l.height/2-w/2-z/2-rt})`),E.attr("style",`color: ${x.get("stroke")??m};`)}return f.attr("transform",`translate(${-l.width/2-(l.x-(l.left??0))},${p?-A/2:A/2-l.height})`),P.attr("transform",`translate(0,${p?l.height/2+w/2:-l.height/2-w/2})`),H(t,C),t.intersect=function(E){if(F.info("iconSquare intersect",t,E),!t.label)return N.rect(t,E);let R=t.x??0,O=t.y??0,z=t.height??0,Z=[];return p?Z=[{x:R-l.width/2,y:O-z/2},{x:R+l.width/2,y:O-z/2},{x:R+l.width/2,y:O-z/2+l.height+w},{x:R+y/2,y:O-z/2+l.height+w},{x:R+y/2,y:O+z/2},{x:R-y/2,y:O+z/2},{x:R-y/2,y:O-z/2+l.height+w},{x:R-l.width/2,y:O-z/2+l.height+w}]:Z=[{x:R-y/2,y:O-z/2},{x:R+y/2,y:O-z/2},{x:R+y/2,y:O-z/2+u},{x:R+l.width/2,y:O-z/2+u},{x:R+l.width/2/2,y:O+z/2},{x:R-l.width/2,y:O+z/2},{x:R-l.width/2,y:O-z/2+u},{x:R-y/2,y:O-z/2+u}],N.polygon(t,Z,E)},n}$(ms,"iconSquare");async function xs(o,t,{config:{flowchart:i}}){let a=new Image;a.src=t?.img??"",await a.decode();let e=Number(a.naturalWidth.toString().replace("px","")),r=Number(a.naturalHeight.toString().replace("px",""));t.imageAspectRatio=e/r;let{labelStyles:h}=T(t);t.labelStyle=h;let s=i?.wrappingWidth;t.defaultWidth=i?.wrappingWidth;let c=Math.max(t.label?s??0:0,t?.assetWidth??e),n=t.constraint==="on"&&t?.assetHeight?t.assetHeight*t.imageAspectRatio:c,l=t.constraint==="on"?n/t.imageAspectRatio:t?.assetHeight??r;t.width=Math.max(n,s??0);let{shapeSvg:g,bbox:f,label:p}=await G(o,t,"image-shape default"),u=t.pos==="t",y=-n/2,m=-l/2,d=t.label?8:0,x=S.svg(g),b=W(t,{});t.look!=="handDrawn"&&(b.roughness=0,b.fillStyle="solid");let M=x.rectangle(y,m,n,l,b),w=Math.max(n,f.width),k=l+f.height+d,v=x.rectangle(-w/2,-k/2,w,k,{...b,fill:"none",stroke:"none"}),D=g.insert(()=>M,":first-child"),B=g.insert(()=>v);if(t.img){let L=g.append("image");L.attr("href",t.img),L.attr("width",n),L.attr("height",l),L.attr("preserveAspectRatio","none"),L.attr("transform",`translate(${-n/2},${u?k/2-l:-k/2})`)}return p.attr("transform",`translate(${-f.width/2-(f.x-(f.left??0))},${u?-l/2-f.height/2-d/2:l/2-f.height/2+d/2})`),D.attr("transform",`translate(0,${u?f.height/2+d/2:-f.height/2-d/2})`),H(t,B),t.intersect=function(L){if(F.info("iconSquare intersect",t,L),!t.label)return N.rect(t,L);let A=t.x??0,I=t.y??0,P=t.height??0,C=[];return u?C=[{x:A-f.width/2,y:I-P/2},{x:A+f.width/2,y:I-P/2},{x:A+f.width/2,y:I-P/2+f.height+d},{x:A+n/2,y:I-P/2+f.height+d},{x:A+n/2,y:I+P/2},{x:A-n/2,y:I+P/2},{x:A-n/2,y:I-P/2+f.height+d},{x:A-f.width/2,y:I-P/2+f.height+d}]:C=[{x:A-n/2,y:I-P/2},{x:A+n/2,y:I-P/2},{x:A+n/2,y:I-P/2+l},{x:A+f.width/2,y:I-P/2+l},{x:A+f.width/2/2,y:I+P/2},{x:A-f.width/2,y:I+P/2},{x:A-f.width/2,y:I-P/2+l},{x:A-n/2,y:I-P/2+l}],N.polygon(t,C,L)},g}$(xs,"imageSquare");async function bs(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r}=await G(o,t,_(t)),h=Math.max(r.width+(t.padding??0)*2,t?.width??0),s=Math.max(r.height+(t.padding??0)*2,t?.height??0),c=[{x:0,y:0},{x:h,y:0},{x:h+3*s/6,y:-s},{x:-3*s/6,y:-s}],n,{cssStyles:l}=t;if(t.look==="handDrawn"){let g=S.svg(e),f=W(t,{}),p=q(c),u=g.path(p,f);n=e.insert(()=>u,":first-child").attr("transform",`translate(${-h/2}, ${s/2})`),l&&n.attr("style",l)}else n=ut(e,h,s,c);return a&&n.attr("style",a),t.width=h,t.height=s,H(t,n),t.intersect=function(g){return N.polygon(t,c,g)},e}$(bs,"inv_trapezoid");async function Gt(o,t,i){let{labelStyles:a,nodeStyles:e}=T(t);t.labelStyle=a;let{shapeSvg:r,bbox:h}=await G(o,t,_(t)),s=Math.max(h.width+i.labelPaddingX*2,t?.width||0),c=Math.max(h.height+i.labelPaddingY*2,t?.height||0),n=-s/2,l=-c/2,g,{rx:f,ry:p}=t,{cssStyles:u}=t;if(i?.rx&&i.ry&&(f=i.rx,p=i.ry),t.look==="handDrawn"){let y=S.svg(r),m=W(t,{}),d=f||p?y.path(ft(n,l,s,c,f||0),m):y.rectangle(n,l,s,c,m);g=r.insert(()=>d,":first-child"),g.attr("class","basic label-container").attr("style",U(u))}else g=r.insert("rect",":first-child"),g.attr("class","basic label-container").attr("style",e).attr("rx",U(f)).attr("ry",U(p)).attr("x",n).attr("y",l).attr("width",s).attr("height",c);return H(t,g),t.calcIntersect=function(y,m){return N.rect(y,m)},t.intersect=function(y){return N.rect(t,y)},r}$(Gt,"drawRect");async function ws(o,t){let{shapeSvg:i,bbox:a,label:e}=await G(o,t,"label"),r=i.insert("rect",":first-child");return r.attr("width",.1).attr("height",.1),i.attr("class","label edgeLabel"),e.attr("transform",`translate(${-(a.width/2)-(a.x-(a.left??0))}, ${-(a.height/2)-(a.y-(a.top??0))})`),H(t,r),t.intersect=function(c){return N.rect(t,c)},i}$(ws,"labelRect");async function Ss(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r}=await G(o,t,_(t)),h=Math.max(r.width+(t.padding??0),t?.width??0),s=Math.max(r.height+(t.padding??0),t?.height??0),c=[{x:0,y:0},{x:h+3*s/6,y:0},{x:h,y:-s},{x:-(3*s)/6,y:-s}],n,{cssStyles:l}=t;if(t.look==="handDrawn"){let g=S.svg(e),f=W(t,{}),p=q(c),u=g.path(p,f);n=e.insert(()=>u,":first-child").attr("transform",`translate(${-h/2}, ${s/2})`),l&&n.attr("style",l)}else n=ut(e,h,s,c);return a&&n.attr("style",a),t.width=h,t.height=s,H(t,n),t.intersect=function(g){return N.polygon(t,c,g)},e}$(Ss,"lean_left");async function $s(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r}=await G(o,t,_(t)),h=Math.max(r.width+(t.padding??0),t?.width??0),s=Math.max(r.height+(t.padding??0),t?.height??0),c=[{x:-3*s/6,y:0},{x:h,y:0},{x:h+3*s/6,y:-s},{x:0,y:-s}],n,{cssStyles:l}=t;if(t.look==="handDrawn"){let g=S.svg(e),f=W(t,{}),p=q(c),u=g.path(p,f);n=e.insert(()=>u,":first-child").attr("transform",`translate(${-h/2}, ${s/2})`),l&&n.attr("style",l)}else n=ut(e,h,s,c);return a&&n.attr("style",a),t.width=h,t.height=s,H(t,n),t.intersect=function(g){return N.polygon(t,c,g)},e}$($s,"lean_right");function Ms(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.label="",t.labelStyle=i;let e=o.insert("g").attr("class",_(t)).attr("id",t.domId??t.id),{cssStyles:r}=t,h=Math.max(35,t?.width??0),s=Math.max(35,t?.height??0),c=7,n=[{x:h,y:0},{x:0,y:s+c/2},{x:h-2*c,y:s+c/2},{x:0,y:2*s},{x:h,y:s-c/2},{x:2*c,y:s-c/2}],l=S.svg(e),g=W(t,{});t.look!=="handDrawn"&&(g.roughness=0,g.fillStyle="solid");let f=q(n),p=l.path(f,g),u=e.insert(()=>p,":first-child");return r&&t.look!=="handDrawn"&&u.selectAll("path").attr("style",r),a&&t.look!=="handDrawn"&&u.selectAll("path").attr("style",a),u.attr("transform",`translate(-${h/2},${-s})`),H(t,u),t.intersect=function(y){return F.info("lightningBolt intersect",t,y),N.polygon(t,n,y)},e}$(Ms,"lightningBolt");var Ca=$((o,t,i,a,e,r,h)=>[`M${o},${t+r}`,`a${e},${r} 0,0,0 ${i},0`,`a${e},${r} 0,0,0 ${-i},0`,`l0,${a}`,`a${e},${r} 0,0,0 ${i},0`,`l0,${-a}`,`M${o},${t+r+h}`,`a${e},${r} 0,0,0 ${i},0`].join(" "),"createCylinderPathD"),Na=$((o,t,i,a,e,r,h)=>[`M${o},${t+r}`,`M${o+i},${t+r}`,`a${e},${r} 0,0,0 ${-i},0`,`l0,${a}`,`a${e},${r} 0,0,0 ${i},0`,`l0,${-a}`,`M${o},${t+r+h}`,`a${e},${r} 0,0,0 ${i},0`].join(" "),"createOuterCylinderPathD"),Ra=$((o,t,i,a,e,r)=>[`M${o-i/2},${-a/2}`,`a${e},${r} 0,0,0 ${i},0`].join(" "),"createInnerCylinderPathD");async function ks(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,label:h}=await G(o,t,_(t)),s=Math.max(r.width+(t.padding??0),t.width??0),c=s/2,n=c/(2.5+s/50),l=Math.max(r.height+n+(t.padding??0),t.height??0),g=l*.1,f,{cssStyles:p}=t;if(t.look==="handDrawn"){let u=S.svg(e),y=Na(0,0,s,l,c,n,g),m=Ra(0,n,s,l,c,n),d=W(t,{}),x=u.path(y,d),b=u.path(m,d);e.insert(()=>b,":first-child").attr("class","line"),f=e.insert(()=>x,":first-child"),f.attr("class","basic label-container"),p&&f.attr("style",p)}else{let u=Ca(0,0,s,l,c,n,g);f=e.insert("path",":first-child").attr("d",u).attr("class","basic label-container").attr("style",U(p)).attr("style",a)}return f.attr("label-offset-y",n),f.attr("transform",`translate(${-s/2}, ${-(l/2+n)})`),H(t,f),h.attr("transform",`translate(${-(r.width/2)-(r.x-(r.left??0))}, ${-(r.height/2)+n-(r.y-(r.top??0))})`),t.intersect=function(u){let y=N.rect(t,u),m=y.x-(t.x??0);if(c!=0&&(Math.abs(m)<(t.width??0)/2||Math.abs(m)==(t.width??0)/2&&Math.abs(y.y-(t.y??0))>(t.height??0)/2-n)){let d=n*n*(1-m*m/(c*c));d>0&&(d=Math.sqrt(d)),d=n-d,u.y-(t.y??0)>0&&(d=-d),y.y+=d}return y},e}$(ks,"linedCylinder");async function vs(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,label:h}=await G(o,t,_(t)),s=Math.max(r.width+(t.padding??0)*2,t?.width??0),c=Math.max(r.height+(t.padding??0)*2,t?.height??0),n=c/4,l=c+n,{cssStyles:g}=t,f=S.svg(e),p=W(t,{});t.look!=="handDrawn"&&(p.roughness=0,p.fillStyle="solid");let u=[{x:-s/2-s/2*.1,y:-l/2},{x:-s/2-s/2*.1,y:l/2},...pt(-s/2-s/2*.1,l/2,s/2+s/2*.1,l/2,n,.8),{x:s/2+s/2*.1,y:-l/2},{x:-s/2-s/2*.1,y:-l/2},{x:-s/2,y:-l/2},{x:-s/2,y:l/2*1.1},{x:-s/2,y:-l/2}],y=f.polygon(u.map(d=>[d.x,d.y]),p),m=e.insert(()=>y,":first-child");return m.attr("class","basic label-container"),g&&t.look!=="handDrawn"&&m.selectAll("path").attr("style",g),a&&t.look!=="handDrawn"&&m.selectAll("path").attr("style",a),m.attr("transform",`translate(0,${-n/2})`),h.attr("transform",`translate(${-s/2+(t.padding??0)+s/2*.1/2-(r.x-(r.left??0))},${-c/2+(t.padding??0)-n/2-(r.y-(r.top??0))})`),H(t,m),t.intersect=function(d){return N.polygon(t,u,d)},e}$(vs,"linedWaveEdgedRect");async function Ds(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,label:h}=await G(o,t,_(t)),s=Math.max(r.width+(t.padding??0)*2,t?.width??0),c=Math.max(r.height+(t.padding??0)*2,t?.height??0),n=5,l=-s/2,g=-c/2,{cssStyles:f}=t,p=S.svg(e),u=W(t,{}),y=[{x:l-n,y:g+n},{x:l-n,y:g+c+n},{x:l+s-n,y:g+c+n},{x:l+s-n,y:g+c},{x:l+s,y:g+c},{x:l+s,y:g+c-n},{x:l+s+n,y:g+c-n},{x:l+s+n,y:g-n},{x:l+n,y:g-n},{x:l+n,y:g},{x:l,y:g},{x:l,y:g+n}],m=[{x:l,y:g+n},{x:l+s-n,y:g+n},{x:l+s-n,y:g+c},{x:l+s,y:g+c},{x:l+s,y:g},{x:l,y:g}];t.look!=="handDrawn"&&(u.roughness=0,u.fillStyle="solid");let d=q(y),x=p.path(d,u),b=q(m),M=p.path(b,{...u,fill:"none"}),w=e.insert(()=>M,":first-child");return w.insert(()=>x,":first-child"),w.attr("class","basic label-container"),f&&t.look!=="handDrawn"&&w.selectAll("path").attr("style",f),a&&t.look!=="handDrawn"&&w.selectAll("path").attr("style",a),h.attr("transform",`translate(${-(r.width/2)-n-(r.x-(r.left??0))}, ${-(r.height/2)+n-(r.y-(r.top??0))})`),H(t,w),t.intersect=function(k){return N.polygon(t,y,k)},e}$(Ds,"multiRect");async function Ps(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,label:h}=await G(o,t,_(t)),s=Math.max(r.width+(t.padding??0)*2,t?.width??0),c=Math.max(r.height+(t.padding??0)*2,t?.height??0),n=c/4,l=c+n,g=-s/2,f=-l/2,p=5,{cssStyles:u}=t,y=pt(g-p,f+l+p,g+s-p,f+l+p,n,.8),m=y?.[y.length-1],d=[{x:g-p,y:f+p},{x:g-p,y:f+l+p},...y,{x:g+s-p,y:m.y-p},{x:g+s,y:m.y-p},{x:g+s,y:m.y-2*p},{x:g+s+p,y:m.y-2*p},{x:g+s+p,y:f-p},{x:g+p,y:f-p},{x:g+p,y:f},{x:g,y:f},{x:g,y:f+p}],x=[{x:g,y:f+p},{x:g+s-p,y:f+p},{x:g+s-p,y:m.y-p},{x:g+s,y:m.y-p},{x:g+s,y:f},{x:g,y:f}],b=S.svg(e),M=W(t,{});t.look!=="handDrawn"&&(M.roughness=0,M.fillStyle="solid");let w=q(d),k=b.path(w,M),v=q(x),D=b.path(v,M),B=e.insert(()=>k,":first-child");return B.insert(()=>D),B.attr("class","basic label-container"),u&&t.look!=="handDrawn"&&B.selectAll("path").attr("style",u),a&&t.look!=="handDrawn"&&B.selectAll("path").attr("style",a),B.attr("transform",`translate(0,${-n/2})`),h.attr("transform",`translate(${-(r.width/2)-p-(r.x-(r.left??0))}, ${-(r.height/2)+p-n/2-(r.y-(r.top??0))})`),H(t,B),t.intersect=function(L){return N.polygon(t,d,L)},e}$(Ps,"multiWaveEdgedRectangle");async function Bs(o,t,{config:{themeVariables:i}}){let{labelStyles:a,nodeStyles:e}=T(t);t.labelStyle=a,t.useHtmlLabels||mt().flowchart?.htmlLabels!==!1||(t.centerLabel=!0);let{shapeSvg:h,bbox:s,label:c}=await G(o,t,_(t)),n=Math.max(s.width+(t.padding??0)*2,t?.width??0),l=Math.max(s.height+(t.padding??0)*2,t?.height??0),g=-n/2,f=-l/2,{cssStyles:p}=t,u=S.svg(h),y=W(t,{fill:i.noteBkgColor,stroke:i.noteBorderColor});t.look!=="handDrawn"&&(y.roughness=0,y.fillStyle="solid");let m=u.rectangle(g,f,n,l,y),d=h.insert(()=>m,":first-child");return d.attr("class","basic label-container"),p&&t.look!=="handDrawn"&&d.selectAll("path").attr("style",p),e&&t.look!=="handDrawn"&&d.selectAll("path").attr("style",e),c.attr("transform",`translate(${-s.width/2-(s.x-(s.left??0))}, ${-(s.height/2)-(s.y-(s.top??0))})`),H(t,d),t.intersect=function(x){return N.rect(t,x)},h}$(Bs,"note");var Aa=$((o,t,i)=>[`M${o+i/2},${t}`,`L${o+i},${t-i/2}`,`L${o+i/2},${t-i}`,`L${o},${t-i/2}`,"Z"].join(" "),"createDecisionBoxPathD");async function Cs(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r}=await G(o,t,_(t)),h=r.width+t.padding,s=r.height+t.padding,c=h+s,n=.5,l=[{x:c/2,y:0},{x:c,y:-c/2},{x:c/2,y:-c},{x:0,y:-c/2}],g,{cssStyles:f}=t;if(t.look==="handDrawn"){let p=S.svg(e),u=W(t,{}),y=Aa(0,0,c),m=p.path(y,u);g=e.insert(()=>m,":first-child").attr("transform",`translate(${-c/2+n}, ${c/2})`),f&&g.attr("style",f)}else g=ut(e,c,c,l),g.attr("transform",`translate(${-c/2+n}, ${c/2})`);return a&&g.attr("style",a),H(t,g),t.calcIntersect=function(p,u){let y=p.width,m=[{x:y/2,y:0},{x:y,y:-y/2},{x:y/2,y:-y},{x:0,y:-y/2}],d=N.polygon(p,m,u);return{x:d.x-.5,y:d.y-.5}},t.intersect=function(p){return this.calcIntersect(t,p)},e}$(Cs,"question");async function Ns(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,label:h}=await G(o,t,_(t)),s=Math.max(r.width+(t.padding??0),t?.width??0),c=Math.max(r.height+(t.padding??0),t?.height??0),n=-s/2,l=-c/2,g=l/2,f=[{x:n+g,y:l},{x:n,y:0},{x:n+g,y:-l},{x:-n,y:-l},{x:-n,y:l}],{cssStyles:p}=t,u=S.svg(e),y=W(t,{});t.look!=="handDrawn"&&(y.roughness=0,y.fillStyle="solid");let m=q(f),d=u.path(m,y),x=e.insert(()=>d,":first-child");return x.attr("class","basic label-container"),p&&t.look!=="handDrawn"&&x.selectAll("path").attr("style",p),a&&t.look!=="handDrawn"&&x.selectAll("path").attr("style",a),x.attr("transform",`translate(${-g/2},0)`),h.attr("transform",`translate(${-g/2-r.width/2-(r.x-(r.left??0))}, ${-(r.height/2)-(r.y-(r.top??0))})`),H(t,x),t.intersect=function(b){return N.polygon(t,f,b)},e}$(Ns,"rect_left_inv_arrow");async function Rs(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let e;t.cssClasses?e="node "+t.cssClasses:e="node default";let r=o.insert("g").attr("class",e).attr("id",t.domId||t.id),h=r.insert("g"),s=r.insert("g").attr("class","label").attr("style",a),c=t.description,n=t.label,l=s.node().appendChild(await ue(n,t.labelStyle,!0,!0)),g={width:0,height:0};if(J(V()?.flowchart?.htmlLabels)){let D=l.children[0],B=Y(l);g=D.getBoundingClientRect(),B.attr("width",g.width),B.attr("height",g.height)}F.info("Text 2",c);let f=c||[],p=l.getBBox(),u=s.node().appendChild(await ue(f.join?f.join("
"):f,t.labelStyle,!0,!0)),y=u.children[0],m=Y(u);g=y.getBoundingClientRect(),m.attr("width",g.width),m.attr("height",g.height);let d=(t.padding||0)/2;Y(u).attr("transform","translate( "+(g.width>p.width?0:(p.width-g.width)/2)+", "+(p.height+d+5)+")"),Y(l).attr("transform","translate( "+(g.width(F.debug("Rough node insert CXC",L),A),":first-child"),k=r.insert(()=>(F.debug("Rough node insert CXC",L),L),":first-child")}else k=h.insert("rect",":first-child"),v=h.insert("line"),k.attr("class","outer title-state").attr("style",a).attr("x",-g.width/2-d).attr("y",-g.height/2-d).attr("width",g.width+(t.padding||0)).attr("height",g.height+(t.padding||0)),v.attr("class","divider").attr("x1",-g.width/2-d).attr("x2",g.width/2+d).attr("y1",-g.height/2-d+p.height+d).attr("y2",-g.height/2-d+p.height+d);return H(t,k),t.intersect=function(D){return N.rect(t,D)},r}$(Rs,"rectWithTitle");function Nt(o,t,i,a,e,r,h){let c=(o+i)/2,n=(t+a)/2,l=Math.atan2(a-t,i-o),g=(i-o)/2,f=(a-t)/2,p=g/e,u=f/r,y=Math.sqrt(p**2+u**2);if(y>1)throw new Error("The given radii are too small to create an arc between the points.");let m=Math.sqrt(1-y**2),d=c+m*r*Math.sin(l)*(h?-1:1),x=n-m*e*Math.cos(l)*(h?-1:1),b=Math.atan2((t-x)/r,(o-d)/e),w=Math.atan2((a-x)/r,(i-d)/e)-b;h&&w<0&&(w+=2*Math.PI),!h&&w>0&&(w-=2*Math.PI);let k=[];for(let v=0;v<20;v++){let D=v/19,B=b+D*w,L=d+e*Math.cos(B),A=x+r*Math.sin(B);k.push({x:L,y:A})}return k}$(Nt,"generateArcPoints");async function As(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r}=await G(o,t,_(t)),h=t?.padding??0,s=t?.padding??0,c=(t?.width?t?.width:r.width)+h*2,n=(t?.height?t?.height:r.height)+s*2,l=t.radius||5,g=t.taper||5,{cssStyles:f}=t,p=S.svg(e),u=W(t,{});t.stroke&&(u.stroke=t.stroke),t.look!=="handDrawn"&&(u.roughness=0,u.fillStyle="solid");let y=[{x:-c/2+g,y:-n/2},{x:c/2-g,y:-n/2},...Nt(c/2-g,-n/2,c/2,-n/2+g,l,l,!0),{x:c/2,y:-n/2+g},{x:c/2,y:n/2-g},...Nt(c/2,n/2-g,c/2-g,n/2,l,l,!0),{x:c/2-g,y:n/2},{x:-c/2+g,y:n/2},...Nt(-c/2+g,n/2,-c/2,n/2-g,l,l,!0),{x:-c/2,y:n/2-g},{x:-c/2,y:-n/2+g},...Nt(-c/2,-n/2+g,-c/2+g,-n/2,l,l,!0)],m=q(y),d=p.path(m,u),x=e.insert(()=>d,":first-child");return x.attr("class","basic label-container outer-path"),f&&t.look!=="handDrawn"&&x.selectChildren("path").attr("style",f),a&&t.look!=="handDrawn"&&x.selectChildren("path").attr("style",a),H(t,x),t.intersect=function(b){return N.polygon(t,y,b)},e}$(As,"roundedRect");async function Ls(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,label:h}=await G(o,t,_(t)),s=t?.padding??0,c=Math.max(r.width+(t.padding??0)*2,t?.width??0),n=Math.max(r.height+(t.padding??0)*2,t?.height??0),l=-r.width/2-s,g=-r.height/2-s,{cssStyles:f}=t,p=S.svg(e),u=W(t,{});t.look!=="handDrawn"&&(u.roughness=0,u.fillStyle="solid");let y=[{x:l,y:g},{x:l+c+8,y:g},{x:l+c+8,y:g+n},{x:l-8,y:g+n},{x:l-8,y:g},{x:l,y:g},{x:l,y:g+n}],m=p.polygon(y.map(x=>[x.x,x.y]),u),d=e.insert(()=>m,":first-child");return d.attr("class","basic label-container").attr("style",U(f)),a&&t.look!=="handDrawn"&&d.selectAll("path").attr("style",a),f&&t.look!=="handDrawn"&&d.selectAll("path").attr("style",a),h.attr("transform",`translate(${-c/2+4+(t.padding??0)-(r.x-(r.left??0))},${-n/2+(t.padding??0)-(r.y-(r.top??0))})`),H(t,d),t.intersect=function(x){return N.rect(t,x)},e}$(Ls,"shadedProcess");async function Ws(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,label:h}=await G(o,t,_(t)),s=Math.max(r.width+(t.padding??0)*2,t?.width??0),c=Math.max(r.height+(t.padding??0)*2,t?.height??0),n=-s/2,l=-c/2,{cssStyles:g}=t,f=S.svg(e),p=W(t,{});t.look!=="handDrawn"&&(p.roughness=0,p.fillStyle="solid");let u=[{x:n,y:l},{x:n,y:l+c},{x:n+s,y:l+c},{x:n+s,y:l-c/2}],y=q(u),m=f.path(y,p),d=e.insert(()=>m,":first-child");return d.attr("class","basic label-container"),g&&t.look!=="handDrawn"&&d.selectChildren("path").attr("style",g),a&&t.look!=="handDrawn"&&d.selectChildren("path").attr("style",a),d.attr("transform",`translate(0, ${c/4})`),h.attr("transform",`translate(${-s/2+(t.padding??0)-(r.x-(r.left??0))}, ${-c/4+(t.padding??0)-(r.y-(r.top??0))})`),H(t,d),t.intersect=function(x){return N.polygon(t,u,x)},e}$(Ws,"slopedRect");async function Ts(o,t){let i={rx:0,ry:0,classes:"",labelPaddingX:t.labelPaddingX??(t?.padding||0)*2,labelPaddingY:(t?.padding||0)*1};return Gt(o,t,i)}$(Ts,"squareRect");async function Hs(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r}=await G(o,t,_(t)),h=r.height+t.padding,s=r.width+h/4+t.padding,c=h/2,{cssStyles:n}=t,l=S.svg(e),g=W(t,{});t.look!=="handDrawn"&&(g.roughness=0,g.fillStyle="solid");let f=[{x:-s/2+c,y:-h/2},{x:s/2-c,y:-h/2},...At(-s/2+c,0,c,50,90,270),{x:s/2-c,y:h/2},...At(s/2-c,0,c,50,270,450)],p=q(f),u=l.path(p,g),y=e.insert(()=>u,":first-child");return y.attr("class","basic label-container outer-path"),n&&t.look!=="handDrawn"&&y.selectChildren("path").attr("style",n),a&&t.look!=="handDrawn"&&y.selectChildren("path").attr("style",a),H(t,y),t.intersect=function(m){return N.polygon(t,f,m)},e}$(Hs,"stadium");async function Is(o,t){return Gt(o,t,{rx:5,ry:5,classes:"flowchart-node"})}$(Is,"state");function Es(o,t,{config:{themeVariables:i}}){let{labelStyles:a,nodeStyles:e}=T(t);t.labelStyle=a;let{cssStyles:r}=t,{lineColor:h,stateBorder:s,nodeBorder:c}=i,n=o.insert("g").attr("class","node default").attr("id",t.domId||t.id),l=S.svg(n),g=W(t,{});t.look!=="handDrawn"&&(g.roughness=0,g.fillStyle="solid");let f=l.circle(0,0,14,{...g,stroke:h,strokeWidth:2}),p=s??c,u=l.circle(0,0,5,{...g,fill:p,stroke:p,strokeWidth:2,fillStyle:"solid"}),y=n.insert(()=>f,":first-child");return y.insert(()=>u),r&&y.selectAll("path").attr("style",r),e&&y.selectAll("path").attr("style",e),H(t,y),t.intersect=function(m){return N.circle(t,7,m)},n}$(Es,"stateEnd");function Os(o,t,{config:{themeVariables:i}}){let{lineColor:a}=i,e=o.insert("g").attr("class","node default").attr("id",t.domId||t.id),r;if(t.look==="handDrawn"){let s=S.svg(e).circle(0,0,14,Me(a));r=e.insert(()=>s),r.attr("class","state-start").attr("r",7).attr("width",14).attr("height",14)}else r=e.insert("circle",":first-child"),r.attr("class","state-start").attr("r",7).attr("width",14).attr("height",14);return H(t,r),t.intersect=function(h){return N.circle(t,7,h)},e}$(Os,"stateStart");async function _s(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r}=await G(o,t,_(t)),h=(t?.padding||0)/2,s=r.width+t.padding,c=r.height+t.padding,n=-r.width/2-h,l=-r.height/2-h,g=[{x:0,y:0},{x:s,y:0},{x:s,y:-c},{x:0,y:-c},{x:0,y:0},{x:-8,y:0},{x:s+8,y:0},{x:s+8,y:-c},{x:-8,y:-c},{x:-8,y:0}];if(t.look==="handDrawn"){let f=S.svg(e),p=W(t,{}),u=f.rectangle(n-8,l,s+16,c,p),y=f.line(n,l,n,l+c,p),m=f.line(n+s,l,n+s,l+c,p);e.insert(()=>y,":first-child"),e.insert(()=>m,":first-child");let d=e.insert(()=>u,":first-child"),{cssStyles:x}=t;d.attr("class","basic label-container").attr("style",U(x)),H(t,d)}else{let f=ut(e,s,c,g);a&&f.attr("style",a),H(t,f)}return t.intersect=function(f){return N.polygon(t,g,f)},e}$(_s,"subroutine");async function zs(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r}=await G(o,t,_(t)),h=Math.max(r.width+(t.padding??0)*2,t?.width??0),s=Math.max(r.height+(t.padding??0)*2,t?.height??0),c=-h/2,n=-s/2,l=.2*s,g=.2*s,{cssStyles:f}=t,p=S.svg(e),u=W(t,{}),y=[{x:c-l/2,y:n},{x:c+h+l/2,y:n},{x:c+h+l/2,y:n+s},{x:c-l/2,y:n+s}],m=[{x:c+h-l/2,y:n+s},{x:c+h+l/2,y:n+s},{x:c+h+l/2,y:n+s-g}];t.look!=="handDrawn"&&(u.roughness=0,u.fillStyle="solid");let d=q(y),x=p.path(d,u),b=q(m),M=p.path(b,{...u,fillStyle:"solid"}),w=e.insert(()=>M,":first-child");return w.insert(()=>x,":first-child"),w.attr("class","basic label-container"),f&&t.look!=="handDrawn"&&w.selectAll("path").attr("style",f),a&&t.look!=="handDrawn"&&w.selectAll("path").attr("style",a),H(t,w),t.intersect=function(k){return N.polygon(t,y,k)},e}$(zs,"taggedRect");async function js(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,label:h}=await G(o,t,_(t)),s=Math.max(r.width+(t.padding??0)*2,t?.width??0),c=Math.max(r.height+(t.padding??0)*2,t?.height??0),n=c/4,l=.2*s,g=.2*c,f=c+n,{cssStyles:p}=t,u=S.svg(e),y=W(t,{});t.look!=="handDrawn"&&(y.roughness=0,y.fillStyle="solid");let m=[{x:-s/2-s/2*.1,y:f/2},...pt(-s/2-s/2*.1,f/2,s/2+s/2*.1,f/2,n,.8),{x:s/2+s/2*.1,y:-f/2},{x:-s/2-s/2*.1,y:-f/2}],d=-s/2+s/2*.1,x=-f/2-g*.4,b=[{x:d+s-l,y:(x+c)*1.4},{x:d+s,y:x+c-g},{x:d+s,y:(x+c)*.9},...pt(d+s,(x+c)*1.3,d+s-l,(x+c)*1.5,-c*.03,.5)],M=q(m),w=u.path(M,y),k=q(b),v=u.path(k,{...y,fillStyle:"solid"}),D=e.insert(()=>v,":first-child");return D.insert(()=>w,":first-child"),D.attr("class","basic label-container"),p&&t.look!=="handDrawn"&&D.selectAll("path").attr("style",p),a&&t.look!=="handDrawn"&&D.selectAll("path").attr("style",a),D.attr("transform",`translate(0,${-n/2})`),h.attr("transform",`translate(${-s/2+(t.padding??0)-(r.x-(r.left??0))},${-c/2+(t.padding??0)-n/2-(r.y-(r.top??0))})`),H(t,D),t.intersect=function(B){return N.polygon(t,m,B)},e}$(js,"taggedWaveEdgedRectangle");async function Gs(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r}=await G(o,t,_(t)),h=Math.max(r.width+t.padding,t?.width||0),s=Math.max(r.height+t.padding,t?.height||0),c=-h/2,n=-s/2,l=e.insert("rect",":first-child");return l.attr("class","text").attr("style",a).attr("rx",0).attr("ry",0).attr("x",c).attr("y",n).attr("width",h).attr("height",s),H(t,l),t.intersect=function(g){return N.rect(t,g)},e}$(Gs,"text");var La=$((o,t,i,a,e,r)=>`M${o},${t} + a${e},${r} 0,0,1 0,${-a} + l${i},0 + a${e},${r} 0,0,1 0,${a} + M${i},${-a} + a${e},${r} 0,0,0 0,${a} + l${-i},0`,"createCylinderPathD"),Wa=$((o,t,i,a,e,r)=>[`M${o},${t}`,`M${o+i},${t}`,`a${e},${r} 0,0,0 0,${-a}`,`l${-i},0`,`a${e},${r} 0,0,0 0,${a}`,`l${i},0`].join(" "),"createOuterCylinderPathD"),Ta=$((o,t,i,a,e,r)=>[`M${o+i/2},${-a/2}`,`a${e},${r} 0,0,0 0,${a}`].join(" "),"createInnerCylinderPathD");async function qs(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,label:h,halfPadding:s}=await G(o,t,_(t)),c=t.look==="neo"?s*2:s,n=r.height+c,l=n/2,g=l/(2.5+n/50),f=r.width+g+c,{cssStyles:p}=t,u;if(t.look==="handDrawn"){let y=S.svg(e),m=Wa(0,0,f,n,g,l),d=Ta(0,0,f,n,g,l),x=y.path(m,W(t,{})),b=y.path(d,W(t,{fill:"none"}));u=e.insert(()=>b,":first-child"),u=e.insert(()=>x,":first-child"),u.attr("class","basic label-container"),p&&u.attr("style",p)}else{let y=La(0,0,f,n,g,l);u=e.insert("path",":first-child").attr("d",y).attr("class","basic label-container").attr("style",U(p)).attr("style",a),u.attr("class","basic label-container"),p&&u.selectAll("path").attr("style",p),a&&u.selectAll("path").attr("style",a)}return u.attr("label-offset-x",g),u.attr("transform",`translate(${-f/2}, ${n/2} )`),h.attr("transform",`translate(${-(r.width/2)-g-(r.x-(r.left??0))}, ${-(r.height/2)-(r.y-(r.top??0))})`),H(t,u),t.intersect=function(y){let m=N.rect(t,y),d=m.y-(t.y??0);if(l!=0&&(Math.abs(d)<(t.height??0)/2||Math.abs(d)==(t.height??0)/2&&Math.abs(m.x-(t.x??0))>(t.width??0)/2-g)){let x=g*g*(1-d*d/(l*l));x!=0&&(x=Math.sqrt(Math.abs(x))),x=g-x,y.x-(t.x??0)>0&&(x=-x),m.x+=x}return m},e}$(qs,"tiltedCylinder");async function Fs(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r}=await G(o,t,_(t)),h=r.width+t.padding,s=r.height+t.padding,c=[{x:-3*s/6,y:0},{x:h+3*s/6,y:0},{x:h,y:-s},{x:0,y:-s}],n,{cssStyles:l}=t;if(t.look==="handDrawn"){let g=S.svg(e),f=W(t,{}),p=q(c),u=g.path(p,f);n=e.insert(()=>u,":first-child").attr("transform",`translate(${-h/2}, ${s/2})`),l&&n.attr("style",l)}else n=ut(e,h,s,c);return a&&n.attr("style",a),t.width=h,t.height=s,H(t,n),t.intersect=function(g){return N.polygon(t,c,g)},e}$(Fs,"trapezoid");async function Xs(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r}=await G(o,t,_(t)),h=60,s=20,c=Math.max(h,r.width+(t.padding??0)*2,t?.width??0),n=Math.max(s,r.height+(t.padding??0)*2,t?.height??0),{cssStyles:l}=t,g=S.svg(e),f=W(t,{});t.look!=="handDrawn"&&(f.roughness=0,f.fillStyle="solid");let p=[{x:-c/2*.8,y:-n/2},{x:c/2*.8,y:-n/2},{x:c/2,y:-n/2*.6},{x:c/2,y:n/2},{x:-c/2,y:n/2},{x:-c/2,y:-n/2*.6}],u=q(p),y=g.path(u,f),m=e.insert(()=>y,":first-child");return m.attr("class","basic label-container"),l&&t.look!=="handDrawn"&&m.selectChildren("path").attr("style",l),a&&t.look!=="handDrawn"&&m.selectChildren("path").attr("style",a),H(t,m),t.intersect=function(d){return N.polygon(t,p,d)},e}$(Xs,"trapezoidalPentagon");async function Ys(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,label:h}=await G(o,t,_(t)),s=J(V().flowchart?.htmlLabels),c=r.width+(t.padding??0),n=c+r.height,l=c+r.height,g=[{x:0,y:0},{x:l,y:0},{x:l/2,y:-n}],{cssStyles:f}=t,p=S.svg(e),u=W(t,{});t.look!=="handDrawn"&&(u.roughness=0,u.fillStyle="solid");let y=q(g),m=p.path(y,u),d=e.insert(()=>m,":first-child").attr("transform",`translate(${-n/2}, ${n/2})`);return f&&t.look!=="handDrawn"&&d.selectChildren("path").attr("style",f),a&&t.look!=="handDrawn"&&d.selectChildren("path").attr("style",a),t.width=c,t.height=n,H(t,d),h.attr("transform",`translate(${-r.width/2-(r.x-(r.left??0))}, ${n/2-(r.height+(t.padding??0)/(s?2:1)-(r.y-(r.top??0)))})`),t.intersect=function(x){return F.info("Triangle intersect",t,g,x),N.polygon(t,g,x)},e}$(Ys,"triangle");async function Vs(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,label:h}=await G(o,t,_(t)),s=Math.max(r.width+(t.padding??0)*2,t?.width??0),c=Math.max(r.height+(t.padding??0)*2,t?.height??0),n=c/8,l=c+n,{cssStyles:g}=t,p=70-s,u=p>0?p/2:0,y=S.svg(e),m=W(t,{});t.look!=="handDrawn"&&(m.roughness=0,m.fillStyle="solid");let d=[{x:-s/2-u,y:l/2},...pt(-s/2-u,l/2,s/2+u,l/2,n,.8),{x:s/2+u,y:-l/2},{x:-s/2-u,y:-l/2}],x=q(d),b=y.path(x,m),M=e.insert(()=>b,":first-child");return M.attr("class","basic label-container"),g&&t.look!=="handDrawn"&&M.selectAll("path").attr("style",g),a&&t.look!=="handDrawn"&&M.selectAll("path").attr("style",a),M.attr("transform",`translate(0,${-n/2})`),h.attr("transform",`translate(${-s/2+(t.padding??0)-(r.x-(r.left??0))},${-c/2+(t.padding??0)-n-(r.y-(r.top??0))})`),H(t,M),t.intersect=function(w){return N.polygon(t,d,w)},e}$(Vs,"waveEdgedRectangle");async function Zs(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r}=await G(o,t,_(t)),h=100,s=50,c=Math.max(r.width+(t.padding??0)*2,t?.width??0),n=Math.max(r.height+(t.padding??0)*2,t?.height??0),l=c/n,g=c,f=n;g>f*l?f=g/l:g=f*l,g=Math.max(g,h),f=Math.max(f,s);let p=Math.min(f*.2,f/4),u=f+p*2,{cssStyles:y}=t,m=S.svg(e),d=W(t,{});t.look!=="handDrawn"&&(d.roughness=0,d.fillStyle="solid");let x=[{x:-g/2,y:u/2},...pt(-g/2,u/2,g/2,u/2,p,1),{x:g/2,y:-u/2},...pt(g/2,-u/2,-g/2,-u/2,p,-1)],b=q(x),M=m.path(b,d),w=e.insert(()=>M,":first-child");return w.attr("class","basic label-container"),y&&t.look!=="handDrawn"&&w.selectAll("path").attr("style",y),a&&t.look!=="handDrawn"&&w.selectAll("path").attr("style",a),H(t,w),t.intersect=function(k){return N.polygon(t,x,k)},e}$(Zs,"waveRectangle");async function Qs(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,label:h}=await G(o,t,_(t)),s=Math.max(r.width+(t.padding??0)*2,t?.width??0),c=Math.max(r.height+(t.padding??0)*2,t?.height??0),n=5,l=-s/2,g=-c/2,{cssStyles:f}=t,p=S.svg(e),u=W(t,{}),y=[{x:l-n,y:g-n},{x:l-n,y:g+c},{x:l+s,y:g+c},{x:l+s,y:g-n}],m=`M${l-n},${g-n} L${l+s},${g-n} L${l+s},${g+c} L${l-n},${g+c} L${l-n},${g-n} + M${l-n},${g} L${l+s},${g} + M${l},${g-n} L${l},${g+c}`;t.look!=="handDrawn"&&(u.roughness=0,u.fillStyle="solid");let d=p.path(m,u),x=e.insert(()=>d,":first-child");return x.attr("transform",`translate(${n/2}, ${n/2})`),x.attr("class","basic label-container"),f&&t.look!=="handDrawn"&&x.selectAll("path").attr("style",f),a&&t.look!=="handDrawn"&&x.selectAll("path").attr("style",a),h.attr("transform",`translate(${-(r.width/2)+n/2-(r.x-(r.left??0))}, ${-(r.height/2)+n/2-(r.y-(r.top??0))})`),H(t,x),t.intersect=function(b){return N.polygon(t,y,b)},e}$(Qs,"windowPane");async function xe(o,t){let i=t;if(i.alias&&(t.label=i.alias),t.look==="handDrawn"){let{themeVariables:X}=mt(),{background:Q}=X,tt={...t,id:t.id+"-background",look:"default",cssStyles:["stroke: none",`fill: ${Q}`]};await xe(o,tt)}let a=mt();t.useHtmlLabels=a.htmlLabels;let e=a.er?.diagramPadding??10,r=a.er?.entityPadding??6,{cssStyles:h}=t,{labelStyles:s,nodeStyles:c}=T(t);if(i.attributes.length===0&&t.label){let X={rx:0,ry:0,labelPaddingX:e,labelPaddingY:e*1.5,classes:""};kt(t.label,a)+X.labelPaddingX*20){let X=g.width+e*2-(y+m+d+x);y+=X/w,m+=X/w,d>0&&(d+=X/w),x>0&&(x+=X/w)}let v=y+m+d+x,D=S.svg(l),B=W(t,{});t.look!=="handDrawn"&&(B.roughness=0,B.fillStyle="solid");let L=0;u.length>0&&(L=u.reduce((X,Q)=>X+(Q?.rowHeight??0),0));let A=Math.max(k.width+e*2,t?.width||0,v),I=Math.max((L??0)+g.height,t?.height||0),P=-A/2,C=-I/2;l.selectAll("g:not(:first-child)").each((X,Q,tt)=>{let st=Y(tt[Q]),yt=st.attr("transform"),ot=0,be=0;if(yt){let Ft=RegExp(/translate\(([^,]+),([^)]+)\)/).exec(yt);Ft&&(ot=parseFloat(Ft[1]),be=parseFloat(Ft[2]),st.attr("class").includes("attribute-name")?ot+=y:st.attr("class").includes("attribute-keys")?ot+=y+m:st.attr("class").includes("attribute-comment")&&(ot+=y+m+d))}st.attr("transform",`translate(${P+e/2+ot}, ${be+C+g.height+r/2})`)}),l.select(".name").attr("transform","translate("+-g.width/2+", "+(C+r/2)+")");let E=D.rectangle(P,C,A,I,B),R=l.insert(()=>E,":first-child").attr("style",h.join("")),{themeVariables:O}=mt(),{rowEven:z,rowOdd:Z,nodeBorder:rt}=O;p.push(0);for(let[X,Q]of u.entries()){let st=(X+1)%2===0&&Q.yOffset!==0,yt=D.rectangle(P,g.height+C+Q?.yOffset,A,Q?.rowHeight,{...B,fill:st?z:Z,stroke:rt});l.insert(()=>yt,"g.label").attr("style",h.join("")).attr("class",`row-rect-${st?"even":"odd"}`)}let it=D.line(P,g.height+C,A+P,g.height+C,B);l.insert(()=>it).attr("class","divider"),it=D.line(y+P,g.height+C,y+P,I+C,B),l.insert(()=>it).attr("class","divider"),b&&(it=D.line(y+m+P,g.height+C,y+m+P,I+C,B),l.insert(()=>it).attr("class","divider")),M&&(it=D.line(y+m+d+P,g.height+C,y+m+d+P,I+C,B),l.insert(()=>it).attr("class","divider"));for(let X of p)it=D.line(P,g.height+C+X,A+P,g.height+C+X,B),l.insert(()=>it).attr("class","divider");if(H(t,R),c&&t.look!=="handDrawn"){let Q=c.split(";")?.filter(tt=>tt.includes("stroke"))?.map(tt=>`${tt}`).join("; ");l.selectAll("path").attr("style",Q??""),l.selectAll(".row-rect-even path").attr("style",c)}return t.intersect=function(X){return N.rect(t,X)},l}$(xe,"erBox");async function St(o,t,i,a=0,e=0,r=[],h=""){let s=o.insert("g").attr("class",`label ${r.join(" ")}`).attr("transform",`translate(${a}, ${e})`).attr("style",h);t!==Xt(t)&&(t=Xt(t),t=t.replaceAll("<","<").replaceAll(">",">"));let c=s.node().appendChild(await ht(s,t,{width:kt(t,i)+100,style:h,useHtmlLabels:i.htmlLabels},i));if(t.includes("<")||t.includes(">")){let l=c.children[0];for(l.textContent=l.textContent.replaceAll("<","<").replaceAll(">",">");l.childNodes[0];)l=l.childNodes[0],l.textContent=l.textContent.replaceAll("<","<").replaceAll(">",">")}let n=c.getBBox();if(J(i.htmlLabels)){let l=c.children[0];l.style.textAlign="start";let g=Y(c);n=l.getBoundingClientRect(),g.attr("width",n.width),g.attr("height",n.height)}return n}$(St,"addText");async function Js(o,t,i,a,e=i.class.padding??12){let r=a?0:3,h=o.insert("g").attr("class",_(t)).attr("id",t.domId||t.id),s=null,c=null,n=null,l=null,g=0,f=0,p=0;if(s=h.insert("g").attr("class","annotation-group text"),t.annotations.length>0){let x=t.annotations[0];await Rt(s,{text:`\xAB${x}\xBB`},0),g=s.node().getBBox().height}c=h.insert("g").attr("class","label-group text"),await Rt(c,t,0,["font-weight: bolder"]);let u=c.node().getBBox();f=u.height,n=h.insert("g").attr("class","members-group text");let y=0;for(let x of t.members){let b=await Rt(n,x,y,[x.parseClassifier()]);y+=b+r}p=n.node().getBBox().height,p<=0&&(p=e/2),l=h.insert("g").attr("class","methods-group text");let m=0;for(let x of t.methods){let b=await Rt(l,x,m,[x.parseClassifier()]);m+=b+r}let d=h.node().getBBox();if(s!==null){let x=s.node().getBBox();s.attr("transform",`translate(${-x.width/2})`)}return c.attr("transform",`translate(${-u.width/2}, ${g})`),d=h.node().getBBox(),n.attr("transform",`translate(0, ${g+f+e*2})`),d=h.node().getBBox(),l.attr("transform",`translate(0, ${g+f+(p?p+e*4:e*2)})`),d=h.node().getBBox(),{shapeSvg:h,bbox:d}}$(Js,"textHelper");async function Rt(o,t,i,a=[]){let e=o.insert("g").attr("class","label").attr("style",a.join("; ")),r=mt(),h="useHtmlLabels"in t?t.useHtmlLabels:J(r.htmlLabels)??!0,s="";"text"in t?s=t.text:s=t.label,!h&&s.startsWith("\\")&&(s=s.substring(1)),Yt(s)&&(h=!0);let c=await ht(e,Vt(xt(s)),{width:kt(s,r)+50,classes:"markdown-node-label",useHtmlLabels:h},r),n,l=1;if(h){let g=c.children[0],f=Y(c);l=g.innerHTML.split("
").length,g.innerHTML.includes("")&&(l+=g.innerHTML.split("").length-1);let p=g.getElementsByTagName("img");if(p){let u=s.replace(/]*>/g,"").trim()==="";await Promise.all([...p].map(y=>new Promise(m=>{function d(){if(y.style.display="flex",y.style.flexDirection="column",u){let x=r.fontSize?.toString()??window.getComputedStyle(document.body).fontSize,M=parseInt(x,10)*5+"px";y.style.minWidth=M,y.style.maxWidth=M}else y.style.width="100%";m(y)}$(d,"setupImage"),setTimeout(()=>{y.complete&&d()}),y.addEventListener("error",d),y.addEventListener("load",d)})))}n=g.getBoundingClientRect(),f.attr("width",n.width),f.attr("height",n.height)}else{a.includes("font-weight: bolder")&&Y(c).selectAll("tspan").attr("font-weight",""),l=c.children.length;let g=c.children[0];(c.textContent===""||c.textContent.includes(">"))&&(g.textContent=s[0]+s.substring(1).replaceAll(">",">").replaceAll("<","<").trim(),s[1]===" "&&(g.textContent=g.textContent[0]+" "+g.textContent.substring(1))),g.textContent==="undefined"&&(g.textContent=""),n=c.getBBox()}return e.attr("transform","translate(0,"+(-n.height/(2*l)+i)+")"),n.height}$(Rt,"addText");async function Ks(o,t){let i=V(),a=i.class.padding??12,e=a,r=t.useHtmlLabels??J(i.htmlLabels)??!0,h=t;h.annotations=h.annotations??[],h.members=h.members??[],h.methods=h.methods??[];let{shapeSvg:s,bbox:c}=await Js(o,t,i,r,e),{labelStyles:n,nodeStyles:l}=T(t);t.labelStyle=n,t.cssStyles=h.styles||"";let g=h.styles?.join(";")||l||"";t.cssStyles||(t.cssStyles=g.replaceAll("!important","").split(";"));let f=h.members.length===0&&h.methods.length===0&&!i.class?.hideEmptyMembersBox,p=S.svg(s),u=W(t,{});t.look!=="handDrawn"&&(u.roughness=0,u.fillStyle="solid");let y=c.width,m=c.height;h.members.length===0&&h.methods.length===0?m+=e:h.members.length>0&&h.methods.length===0&&(m+=e*2);let d=-y/2,x=-m/2,b=p.rectangle(d-a,x-a-(f?a:h.members.length===0&&h.methods.length===0?-a/2:0),y+2*a,m+2*a+(f?a*2:h.members.length===0&&h.methods.length===0?-a:0),u),M=s.insert(()=>b,":first-child");M.attr("class","basic label-container");let w=M.node().getBBox();s.selectAll(".text").each((B,L,A)=>{let I=Y(A[L]),P=I.attr("transform"),C=0;if(P){let z=RegExp(/translate\(([^,]+),([^)]+)\)/).exec(P);z&&(C=parseFloat(z[2]))}let E=C+x+a-(f?a:h.members.length===0&&h.methods.length===0?-a/2:0);r||(E-=4);let R=d;(I.attr("class").includes("label-group")||I.attr("class").includes("annotation-group"))&&(R=-I.node()?.getBBox().width/2||0,s.selectAll("text").each(function(O,z,Z){window.getComputedStyle(Z[z]).textAnchor==="middle"&&(R=0)})),I.attr("transform",`translate(${R}, ${E})`)});let k=s.select(".annotation-group").node().getBBox().height-(f?a/2:0)||0,v=s.select(".label-group").node().getBBox().height-(f?a/2:0)||0,D=s.select(".members-group").node().getBBox().height-(f?a/2:0)||0;if(h.members.length>0||h.methods.length>0||f){let B=p.line(w.x,k+v+x+a,w.x+w.width,k+v+x+a,u);s.insert(()=>B).attr("class","divider").attr("style",g)}if(f||h.members.length>0||h.methods.length>0){let B=p.line(w.x,k+v+D+x+e*2+a,w.x+w.width,k+v+D+x+a+e*2,u);s.insert(()=>B).attr("class","divider").attr("style",g)}if(h.look!=="handDrawn"&&s.selectAll("path").attr("style",g),M.select(":nth-child(2)").attr("style",g),s.selectAll(".divider").select("path").attr("style",g),t.labelStyle?s.selectAll("span").attr("style",t.labelStyle):s.selectAll("span").attr("style",g),!r){let B=RegExp(/color\s*:\s*([^;]*)/),L=B.exec(g);if(L){let A=L[0].replace("color","fill");s.selectAll("tspan").attr("style",A)}else if(n){let A=B.exec(n);if(A){let I=A[0].replace("color","fill");s.selectAll("tspan").attr("style",I)}}}return H(t,M),t.intersect=function(B){return N.rect(t,B)},s}$(Ks,"classBox");async function Us(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let e=t,r=t,h=20,s=20,c="verifyMethod"in t,n=_(t),l=o.insert("g").attr("class",n).attr("id",t.domId??t.id),g;c?g=await nt(l,`<<${e.type}>>`,0,t.labelStyle):g=await nt(l,"<<Element>>",0,t.labelStyle);let f=g,p=await nt(l,e.name,f,t.labelStyle+"; font-weight: bold;");if(f+=p+s,c){let k=await nt(l,`${e.requirementId?`ID: ${e.requirementId}`:""}`,f,t.labelStyle);f+=k;let v=await nt(l,`${e.text?`Text: ${e.text}`:""}`,f,t.labelStyle);f+=v;let D=await nt(l,`${e.risk?`Risk: ${e.risk}`:""}`,f,t.labelStyle);f+=D,await nt(l,`${e.verifyMethod?`Verification: ${e.verifyMethod}`:""}`,f,t.labelStyle)}else{let k=await nt(l,`${r.type?`Type: ${r.type}`:""}`,f,t.labelStyle);f+=k,await nt(l,`${r.docRef?`Doc Ref: ${r.docRef}`:""}`,f,t.labelStyle)}let u=(l.node()?.getBBox().width??200)+h,y=(l.node()?.getBBox().height??200)+h,m=-u/2,d=-y/2,x=S.svg(l),b=W(t,{});t.look!=="handDrawn"&&(b.roughness=0,b.fillStyle="solid");let M=x.rectangle(m,d,u,y,b),w=l.insert(()=>M,":first-child");if(w.attr("class","basic label-container").attr("style",a),l.selectAll(".label").each((k,v,D)=>{let B=Y(D[v]),L=B.attr("transform"),A=0,I=0;if(L){let R=RegExp(/translate\(([^,]+),([^)]+)\)/).exec(L);R&&(A=parseFloat(R[1]),I=parseFloat(R[2]))}let P=I-y/2,C=m+h/2;(v===0||v===1)&&(C=A),B.attr("transform",`translate(${C}, ${P+h})`)}),f>g+p+s){let k=x.line(m,d+g+p+s,m+u,d+g+p+s,b);l.insert(()=>k).attr("style",a)}return H(t,w),t.intersect=function(k){return N.rect(t,k)},l}$(Us,"requirementBox");async function nt(o,t,i,a=""){if(t==="")return 0;let e=o.insert("g").attr("class","label").attr("style",a),r=V(),h=r.htmlLabels??!0,s=await ht(e,Vt(xt(t)),{width:kt(t,r)+50,classes:"markdown-node-label",useHtmlLabels:h,style:a},r),c;if(h){let n=s.children[0],l=Y(s);c=n.getBoundingClientRect(),l.attr("width",c.width),l.attr("height",c.height)}else{let n=s.children[0];for(let l of n.children)l.textContent=l.textContent.replaceAll(">",">").replaceAll("<","<"),a&&l.setAttribute("style",a);c=s.getBBox(),c.height+=6}return e.attr("transform",`translate(${-c.width/2},${-c.height/2+i})`),c.height}$(nt,"addText");var Ha=$(o=>{switch(o){case"Very High":return"red";case"High":return"orange";case"Medium":return null;case"Low":return"blue";case"Very Low":return"lightblue"}},"colorFromPriority");async function ta(o,t,{config:i}){let{labelStyles:a,nodeStyles:e}=T(t);t.labelStyle=a||"";let r=10,h=t.width;t.width=(t.width??200)-10;let{shapeSvg:s,bbox:c,label:n}=await G(o,t,_(t)),l=t.padding||10,g="",f;"ticket"in t&&t.ticket&&i?.kanban?.ticketBaseUrl&&(g=i?.kanban?.ticketBaseUrl.replace("#TICKET#",t.ticket),f=s.insert("svg:a",":first-child").attr("class","kanban-ticket-link").attr("xlink:href",g).attr("target","_blank"));let p={useHtmlLabels:t.useHtmlLabels,labelStyle:t.labelStyle||"",width:t.width,img:t.img,padding:t.padding||8,centerLabel:!1},u,y;f?{label:u,bbox:y}=await fe(f,"ticket"in t&&t.ticket||"",p):{label:u,bbox:y}=await fe(s,"ticket"in t&&t.ticket||"",p);let{label:m,bbox:d}=await fe(s,"assigned"in t&&t.assigned||"",p);t.width=h;let x=10,b=t?.width||0,M=Math.max(y.height,d.height)/2,w=Math.max(c.height+x*2,t?.height||0)+M,k=-b/2,v=-w/2;n.attr("transform","translate("+(l-b/2)+", "+(-M-c.height/2)+")"),u.attr("transform","translate("+(l-b/2)+", "+(-M+c.height/2)+")"),m.attr("transform","translate("+(l+b/2-d.width-2*r)+", "+(-M+c.height/2)+")");let D,{rx:B,ry:L}=t,{cssStyles:A}=t;if(t.look==="handDrawn"){let I=S.svg(s),P=W(t,{}),C=B||L?I.path(ft(k,v,b,w,B||0),P):I.rectangle(k,v,b,w,P);D=s.insert(()=>C,":first-child"),D.attr("class","basic label-container").attr("style",A||null)}else{D=s.insert("rect",":first-child"),D.attr("class","basic label-container __APA__").attr("style",e).attr("rx",B??5).attr("ry",L??5).attr("x",k).attr("y",v).attr("width",b).attr("height",w);let I="priority"in t&&t.priority;if(I){let P=s.append("line"),C=k+2,E=v+Math.floor((B??0)/2),R=v+w-Math.floor((B??0)/2);P.attr("x1",C).attr("y1",E).attr("x2",C).attr("y2",R).attr("stroke-width","4").attr("stroke",Ha(I))}}return H(t,D),t.height=w,t.intersect=function(I){return N.rect(t,I)},s}$(ta,"kanbanItem");async function ea(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,halfPadding:h,label:s}=await G(o,t,_(t)),c=r.width+10*h,n=r.height+8*h,l=.15*c,{cssStyles:g}=t,f=r.width+20,p=r.height+20,u=Math.max(c,f),y=Math.max(n,p);s.attr("transform",`translate(${-r.width/2}, ${-r.height/2})`);let m,d=`M0 0 + a${l},${l} 1 0,0 ${u*.25},${-1*y*.1} + a${l},${l} 1 0,0 ${u*.25},0 + a${l},${l} 1 0,0 ${u*.25},0 + a${l},${l} 1 0,0 ${u*.25},${y*.1} + + a${l},${l} 1 0,0 ${u*.15},${y*.33} + a${l*.8},${l*.8} 1 0,0 0,${y*.34} + a${l},${l} 1 0,0 ${-1*u*.15},${y*.33} + + a${l},${l} 1 0,0 ${-1*u*.25},${y*.15} + a${l},${l} 1 0,0 ${-1*u*.25},0 + a${l},${l} 1 0,0 ${-1*u*.25},0 + a${l},${l} 1 0,0 ${-1*u*.25},${-1*y*.15} + + a${l},${l} 1 0,0 ${-1*u*.1},${-1*y*.33} + a${l*.8},${l*.8} 1 0,0 0,${-1*y*.34} + a${l},${l} 1 0,0 ${u*.1},${-1*y*.33} + H0 V0 Z`;if(t.look==="handDrawn"){let x=S.svg(e),b=W(t,{}),M=x.path(d,b);m=e.insert(()=>M,":first-child"),m.attr("class","basic label-container").attr("style",U(g))}else m=e.insert("path",":first-child").attr("class","basic label-container").attr("style",a).attr("d",d);return m.attr("transform",`translate(${-u/2}, ${-y/2})`),H(t,m),t.calcIntersect=function(x,b){return N.rect(x,b)},t.intersect=function(x){return F.info("Bang intersect",t,x),N.rect(t,x)},e}$(ea,"bang");async function sa(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,halfPadding:h,label:s}=await G(o,t,_(t)),c=r.width+2*h,n=r.height+2*h,l=.15*c,g=.25*c,f=.35*c,p=.2*c,{cssStyles:u}=t,y,m=`M0 0 + a${l},${l} 0 0,1 ${c*.25},${-1*c*.1} + a${f},${f} 1 0,1 ${c*.4},${-1*c*.1} + a${g},${g} 1 0,1 ${c*.35},${c*.2} + + a${l},${l} 1 0,1 ${c*.15},${n*.35} + a${p},${p} 1 0,1 ${-1*c*.15},${n*.65} + + a${g},${l} 1 0,1 ${-1*c*.25},${c*.15} + a${f},${f} 1 0,1 ${-1*c*.5},0 + a${l},${l} 1 0,1 ${-1*c*.25},${-1*c*.15} + + a${l},${l} 1 0,1 ${-1*c*.1},${-1*n*.35} + a${p},${p} 1 0,1 ${c*.1},${-1*n*.65} + H0 V0 Z`;if(t.look==="handDrawn"){let d=S.svg(e),x=W(t,{}),b=d.path(m,x);y=e.insert(()=>b,":first-child"),y.attr("class","basic label-container").attr("style",U(u))}else y=e.insert("path",":first-child").attr("class","basic label-container").attr("style",a).attr("d",m);return s.attr("transform",`translate(${-r.width/2}, ${-r.height/2})`),y.attr("transform",`translate(${-c/2}, ${-n/2})`),H(t,y),t.calcIntersect=function(d,x){return N.rect(d,x)},t.intersect=function(d){return F.info("Cloud intersect",t,d),N.rect(t,d)},e}$(sa,"cloud");async function aa(o,t){let{labelStyles:i,nodeStyles:a}=T(t);t.labelStyle=i;let{shapeSvg:e,bbox:r,halfPadding:h,label:s}=await G(o,t,_(t)),c=r.width+8*h,n=r.height+2*h,l=5,g=` + M${-c/2} ${n/2-l} + v${-n+2*l} + q0,-${l} ${l},-${l} + h${c-2*l} + q${l},0 ${l},${l} + v${n-2*l} + q0,${l} -${l},${l} + h${-c+2*l} + q-${l},0 -${l},-${l} + Z + `,f=e.append("path").attr("id","node-"+t.id).attr("class","node-bkg node-"+t.type).attr("style",a).attr("d",g);return e.append("line").attr("class","node-line-").attr("x1",-c/2).attr("y1",n/2).attr("x2",c/2).attr("y2",n/2),s.attr("transform",`translate(${-r.width/2}, ${-r.height/2})`),e.append(()=>s.node()),H(t,f),t.calcIntersect=function(p,u){return N.rect(p,u)},t.intersect=function(p){return N.rect(t,p)},e}$(aa,"defaultMindmapNode");async function ra(o,t){let i={padding:t.padding??0};return me(o,t,i)}$(ra,"mindmapCircle");var Ia=[{semanticName:"Process",name:"Rectangle",shortName:"rect",description:"Standard process shape",aliases:["proc","process","rectangle"],internalAliases:["squareRect"],handler:Ts},{semanticName:"Event",name:"Rounded Rectangle",shortName:"rounded",description:"Represents an event",aliases:["event"],internalAliases:["roundedRect"],handler:As},{semanticName:"Terminal Point",name:"Stadium",shortName:"stadium",description:"Terminal point",aliases:["terminal","pill"],handler:Hs},{semanticName:"Subprocess",name:"Framed Rectangle",shortName:"fr-rect",description:"Subprocess",aliases:["subprocess","subproc","framed-rectangle","subroutine"],handler:_s},{semanticName:"Database",name:"Cylinder",shortName:"cyl",description:"Database storage",aliases:["db","database","cylinder"],handler:ns},{semanticName:"Start",name:"Circle",shortName:"circle",description:"Starting point",aliases:["circ"],handler:me},{semanticName:"Bang",name:"Bang",shortName:"bang",description:"Bang",aliases:["bang"],handler:ea},{semanticName:"Cloud",name:"Cloud",shortName:"cloud",description:"cloud",aliases:["cloud"],handler:sa},{semanticName:"Decision",name:"Diamond",shortName:"diam",description:"Decision-making step",aliases:["decision","diamond","question"],handler:Cs},{semanticName:"Prepare Conditional",name:"Hexagon",shortName:"hex",description:"Preparation or condition step",aliases:["hexagon","prepare"],handler:ps},{semanticName:"Data Input/Output",name:"Lean Right",shortName:"lean-r",description:"Represents input or output",aliases:["lean-right","in-out"],internalAliases:["lean_right"],handler:$s},{semanticName:"Data Input/Output",name:"Lean Left",shortName:"lean-l",description:"Represents output or input",aliases:["lean-left","out-in"],internalAliases:["lean_left"],handler:Ss},{semanticName:"Priority Action",name:"Trapezoid Base Bottom",shortName:"trap-b",description:"Priority action",aliases:["priority","trapezoid-bottom","trapezoid"],handler:Fs},{semanticName:"Manual Operation",name:"Trapezoid Base Top",shortName:"trap-t",description:"Represents a manual task",aliases:["manual","trapezoid-top","inv-trapezoid"],internalAliases:["inv_trapezoid"],handler:bs},{semanticName:"Stop",name:"Double Circle",shortName:"dbl-circ",description:"Represents a stop point",aliases:["double-circle"],internalAliases:["doublecircle"],handler:ls},{semanticName:"Text Block",name:"Text Block",shortName:"text",description:"Text block",handler:Gs},{semanticName:"Card",name:"Notched Rectangle",shortName:"notch-rect",description:"Represents a card",aliases:["card","notched-rectangle"],handler:Je},{semanticName:"Lined/Shaded Process",name:"Lined Rectangle",shortName:"lin-rect",description:"Lined process shape",aliases:["lined-rectangle","lined-process","lin-proc","shaded-process"],handler:Ls},{semanticName:"Start",name:"Small Circle",shortName:"sm-circ",description:"Small starting point",aliases:["start","small-circle"],internalAliases:["stateStart"],handler:Os},{semanticName:"Stop",name:"Framed Circle",shortName:"fr-circ",description:"Stop point",aliases:["stop","framed-circle"],internalAliases:["stateEnd"],handler:Es},{semanticName:"Fork/Join",name:"Filled Rectangle",shortName:"fork",description:"Fork or join in process flow",aliases:["join"],internalAliases:["forkJoin"],handler:hs},{semanticName:"Collate",name:"Hourglass",shortName:"hourglass",description:"Represents a collate operation",aliases:["hourglass","collate"],handler:fs},{semanticName:"Comment",name:"Curly Brace",shortName:"brace",description:"Adds a comment",aliases:["comment","brace-l"],handler:es},{semanticName:"Comment Right",name:"Curly Brace",shortName:"brace-r",description:"Adds a comment",handler:ss},{semanticName:"Comment with braces on both sides",name:"Curly Braces",shortName:"braces",description:"Adds a comment",handler:as},{semanticName:"Com Link",name:"Lightning Bolt",shortName:"bolt",description:"Communication link",aliases:["com-link","lightning-bolt"],handler:Ms},{semanticName:"Document",name:"Document",shortName:"doc",description:"Represents a document",aliases:["doc","document"],handler:Vs},{semanticName:"Delay",name:"Half-Rounded Rectangle",shortName:"delay",description:"Represents a delay",aliases:["half-rounded-rectangle"],handler:gs},{semanticName:"Direct Access Storage",name:"Horizontal Cylinder",shortName:"h-cyl",description:"Direct access storage",aliases:["das","horizontal-cylinder"],handler:qs},{semanticName:"Disk Storage",name:"Lined Cylinder",shortName:"lin-cyl",description:"Disk storage",aliases:["disk","lined-cylinder"],handler:ks},{semanticName:"Display",name:"Curved Trapezoid",shortName:"curv-trap",description:"Represents a display",aliases:["curved-trapezoid","display"],handler:rs},{semanticName:"Divided Process",name:"Divided Rectangle",shortName:"div-rect",description:"Divided process shape",aliases:["div-proc","divided-rectangle","divided-process"],handler:is},{semanticName:"Extract",name:"Triangle",shortName:"tri",description:"Extraction process",aliases:["extract","triangle"],handler:Ys},{semanticName:"Internal Storage",name:"Window Pane",shortName:"win-pane",description:"Internal storage",aliases:["internal-storage","window-pane"],handler:Qs},{semanticName:"Junction",name:"Filled Circle",shortName:"f-circ",description:"Junction point",aliases:["junction","filled-circle"],handler:cs},{semanticName:"Loop Limit",name:"Trapezoidal Pentagon",shortName:"notch-pent",description:"Loop limit step",aliases:["loop-limit","notched-pentagon"],handler:Xs},{semanticName:"Manual File",name:"Flipped Triangle",shortName:"flip-tri",description:"Manual file operation",aliases:["manual-file","flipped-triangle"],handler:os},{semanticName:"Manual Input",name:"Sloped Rectangle",shortName:"sl-rect",description:"Manual input step",aliases:["manual-input","sloped-rectangle"],handler:Ws},{semanticName:"Multi-Document",name:"Stacked Document",shortName:"docs",description:"Multiple documents",aliases:["documents","st-doc","stacked-document"],handler:Ps},{semanticName:"Multi-Process",name:"Stacked Rectangle",shortName:"st-rect",description:"Multiple processes",aliases:["procs","processes","stacked-rectangle"],handler:Ds},{semanticName:"Stored Data",name:"Bow Tie Rectangle",shortName:"bow-rect",description:"Stored data",aliases:["stored-data","bow-tie-rectangle"],handler:Qe},{semanticName:"Summary",name:"Crossed Circle",shortName:"cross-circ",description:"Summary",aliases:["summary","crossed-circle"],handler:ts},{semanticName:"Tagged Document",name:"Tagged Document",shortName:"tag-doc",description:"Tagged document",aliases:["tag-doc","tagged-document"],handler:js},{semanticName:"Tagged Process",name:"Tagged Rectangle",shortName:"tag-rect",description:"Tagged process",aliases:["tagged-rectangle","tag-proc","tagged-process"],handler:zs},{semanticName:"Paper Tape",name:"Flag",shortName:"flag",description:"Paper tape",aliases:["paper-tape"],handler:Zs},{semanticName:"Odd",name:"Odd",shortName:"odd",description:"Odd shape",internalAliases:["rect_left_inv_arrow"],handler:Ns},{semanticName:"Lined Document",name:"Lined Document",shortName:"lin-doc",description:"Lined document",aliases:["lined-document"],handler:vs}],Ea=$(()=>{let t=[...Object.entries({state:Is,choice:Ke,note:Bs,rectWithTitle:Rs,labelRect:ws,iconSquare:ms,iconCircle:ys,icon:us,iconRounded:ds,imageSquare:xs,anchor:Ze,kanbanItem:ta,mindmapCircle:ra,defaultMindmapNode:aa,classBox:Ks,erBox:xe,requirementBox:Us}),...Ia.flatMap(i=>[i.shortName,..."aliases"in i?i.aliases:[],..."internalAliases"in i?i.internalAliases:[]].map(e=>[e,i.handler]))];return Object.fromEntries(t)},"generateShapeMap"),na=Ea();function Oa(o){return o in na}$(Oa,"isValidShape");var qt=new Map;async function _a(o,t,i){let a,e;t.shape==="rect"&&(t.rx&&t.ry?t.shape="roundedRect":t.shape="squareRect");let r=t.shape?na[t.shape]:void 0;if(!r)throw new Error(`No such shape: ${t.shape}. Please check your syntax.`);if(t.link){let h;i.config.securityLevel==="sandbox"?h="_top":t.linkTarget&&(h=t.linkTarget||"_blank"),a=o.insert("svg:a").attr("xlink:href",t.link).attr("target",h??null),e=await r(a,t,i)}else e=await r(o,t,i),a=e;return t.tooltip&&e.attr("title",t.tooltip),qt.set(t.id,a),t.haveCallback&&a.attr("class",a.attr("class")+" clickable"),a}$(_a,"insertNode");var pn=$((o,t)=>{qt.set(t.id,o)},"setNodeElem"),fn=$(()=>{qt.clear()},"clear"),un=$(o=>{let t=qt.get(o.id);F.trace("Transforming node",o.diff,o,"translate("+(o.x-o.width/2-5)+", "+o.width/2+")");let i=8,a=o.diff||0;return o.clusterNode?t.attr("transform","translate("+(o.x+a-o.width/2)+", "+(o.y-o.height/2-i)+")"):t.attr("transform","translate("+o.x+", "+o.y+")"),a},"positionNode");export{S as a,G as b,H as c,ue as d,Ua as e,tr as f,Oa as g,_a as h,pn as i,fn as j,un as k}; +//# sourceMappingURL=chunk-IDQ2RCY2.min.js.map diff --git a/docs/website/public/chunk-IDQ2RCY2.min.js.map b/docs/website/public/chunk-IDQ2RCY2.min.js.map new file mode 100644 index 000000000..2ef86bef4 --- /dev/null +++ b/docs/website/public/chunk-IDQ2RCY2.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/roughjs/bundled/rough.esm.js", "../../node_modules/mermaid/dist/chunks/mermaid.core/chunk-JZLCHNYA.mjs"], + "sourcesContent": ["function t(t,e,s){if(t&&t.length){const[n,o]=e,a=Math.PI/180*s,h=Math.cos(a),r=Math.sin(a);for(const e of t){const[t,s]=e;e[0]=(t-n)*h-(s-o)*r+n,e[1]=(t-n)*r+(s-o)*h+o}}}function e(t,e){return t[0]===e[0]&&t[1]===e[1]}function s(s,n,o,a=1){const h=o,r=Math.max(n,.1),i=s[0]&&s[0][0]&&\"number\"==typeof s[0][0]?[s]:s,c=[0,0];if(h)for(const e of i)t(e,c,h);const l=function(t,s,n){const o=[];for(const s of t){const t=[...s];e(t[0],t[t.length-1])||t.push([t[0][0],t[0][1]]),t.length>2&&o.push(t)}const a=[];s=Math.max(s,.1);const h=[];for(const t of o)for(let e=0;et.ymine.ymin?1:t.xe.x?1:t.ymax===e.ymax?0:(t.ymax-e.ymax)/Math.abs(t.ymax-e.ymax))),!h.length)return a;let r=[],i=h[0].ymin,c=0;for(;r.length||h.length;){if(h.length){let t=-1;for(let e=0;ei);e++)t=e;h.splice(0,t+1).forEach((t=>{r.push({s:i,edge:t})}))}if(r=r.filter((t=>!(t.edge.ymax<=i))),r.sort(((t,e)=>t.edge.x===e.edge.x?0:(t.edge.x-e.edge.x)/Math.abs(t.edge.x-e.edge.x))),(1!==n||c%s==0)&&r.length>1)for(let t=0;t=r.length)break;const s=r[t].edge,n=r[e].edge;a.push([[Math.round(s.x),i],[Math.round(n.x),i]])}i+=n,r.forEach((t=>{t.edge.x=t.edge.x+n*t.edge.islope})),c++}return a}(i,r,a);if(h){for(const e of i)t(e,c,-h);!function(e,s,n){const o=[];e.forEach((t=>o.push(...t))),t(o,s,n)}(l,c,-h)}return l}function n(t,e){var n;const o=e.hachureAngle+90;let a=e.hachureGap;a<0&&(a=4*e.strokeWidth),a=Math.round(Math.max(a,.1));let h=1;return e.roughness>=1&&((null===(n=e.randomizer)||void 0===n?void 0:n.next())||Math.random())>.7&&(h=a),s(t,a,o,h||1)}class o{constructor(t){this.helper=t}fillPolygons(t,e){return this._fillPolygons(t,e)}_fillPolygons(t,e){const s=n(t,e);return{type:\"fillSketch\",ops:this.renderLines(s,e)}}renderLines(t,e){const s=[];for(const n of t)s.push(...this.helper.doubleLineOps(n[0][0],n[0][1],n[1][0],n[1][1],e));return s}}function a(t){const e=t[0],s=t[1];return Math.sqrt(Math.pow(e[0]-s[0],2)+Math.pow(e[1]-s[1],2))}class h extends o{fillPolygons(t,e){let s=e.hachureGap;s<0&&(s=4*e.strokeWidth),s=Math.max(s,.1);const o=n(t,Object.assign({},e,{hachureGap:s})),h=Math.PI/180*e.hachureAngle,r=[],i=.5*s*Math.cos(h),c=.5*s*Math.sin(h);for(const[t,e]of o)a([t,e])&&r.push([[t[0]-i,t[1]+c],[...e]],[[t[0]+i,t[1]-c],[...e]]);return{type:\"fillSketch\",ops:this.renderLines(r,e)}}}class r extends o{fillPolygons(t,e){const s=this._fillPolygons(t,e),n=Object.assign({},e,{hachureAngle:e.hachureAngle+90}),o=this._fillPolygons(t,n);return s.ops=s.ops.concat(o.ops),s}}class i{constructor(t){this.helper=t}fillPolygons(t,e){const s=n(t,e=Object.assign({},e,{hachureAngle:0}));return this.dotsOnLines(s,e)}dotsOnLines(t,e){const s=[];let n=e.hachureGap;n<0&&(n=4*e.strokeWidth),n=Math.max(n,.1);let o=e.fillWeight;o<0&&(o=e.strokeWidth/2);const h=n/4;for(const r of t){const t=a(r),i=t/n,c=Math.ceil(i)-1,l=t-c*n,u=(r[0][0]+r[1][0])/2-n/4,p=Math.min(r[0][1],r[1][1]);for(let t=0;t{const h=a(t),r=Math.floor(h/(s+n)),i=(h+n-r*(s+n))/2;let c=t[0],l=t[1];c[0]>l[0]&&(c=t[1],l=t[0]);const u=Math.atan((l[1]-c[1])/(l[0]-c[0]));for(let t=0;t{const o=a(t),h=Math.round(o/(2*e));let r=t[0],i=t[1];r[0]>i[0]&&(r=t[1],i=t[0]);const c=Math.atan((i[1]-r[1])/(i[0]-r[0]));for(let t=0;tn%2?t+s:t+e));a.push({key:\"C\",data:t}),e=t[4],s=t[5];break}case\"Q\":a.push({key:\"Q\",data:[...r]}),e=r[2],s=r[3];break;case\"q\":{const t=r.map(((t,n)=>n%2?t+s:t+e));a.push({key:\"Q\",data:t}),e=t[2],s=t[3];break}case\"A\":a.push({key:\"A\",data:[...r]}),e=r[5],s=r[6];break;case\"a\":e+=r[5],s+=r[6],a.push({key:\"A\",data:[r[0],r[1],r[2],r[3],r[4],e,s]});break;case\"H\":a.push({key:\"H\",data:[...r]}),e=r[0];break;case\"h\":e+=r[0],a.push({key:\"H\",data:[e]});break;case\"V\":a.push({key:\"V\",data:[...r]}),s=r[0];break;case\"v\":s+=r[0],a.push({key:\"V\",data:[s]});break;case\"S\":a.push({key:\"S\",data:[...r]}),e=r[2],s=r[3];break;case\"s\":{const t=r.map(((t,n)=>n%2?t+s:t+e));a.push({key:\"S\",data:t}),e=t[2],s=t[3];break}case\"T\":a.push({key:\"T\",data:[...r]}),e=r[0],s=r[1];break;case\"t\":e+=r[0],s+=r[1],a.push({key:\"T\",data:[e,s]});break;case\"Z\":case\"z\":a.push({key:\"Z\",data:[]}),e=n,s=o}return a}function m(t){const e=[];let s=\"\",n=0,o=0,a=0,h=0,r=0,i=0;for(const{key:c,data:l}of t){switch(c){case\"M\":e.push({key:\"M\",data:[...l]}),[n,o]=l,[a,h]=l;break;case\"C\":e.push({key:\"C\",data:[...l]}),n=l[4],o=l[5],r=l[2],i=l[3];break;case\"L\":e.push({key:\"L\",data:[...l]}),[n,o]=l;break;case\"H\":n=l[0],e.push({key:\"L\",data:[n,o]});break;case\"V\":o=l[0],e.push({key:\"L\",data:[n,o]});break;case\"S\":{let t=0,a=0;\"C\"===s||\"S\"===s?(t=n+(n-r),a=o+(o-i)):(t=n,a=o),e.push({key:\"C\",data:[t,a,...l]}),r=l[0],i=l[1],n=l[2],o=l[3];break}case\"T\":{const[t,a]=l;let h=0,c=0;\"Q\"===s||\"T\"===s?(h=n+(n-r),c=o+(o-i)):(h=n,c=o);const u=n+2*(h-n)/3,p=o+2*(c-o)/3,f=t+2*(h-t)/3,d=a+2*(c-a)/3;e.push({key:\"C\",data:[u,p,f,d,t,a]}),r=h,i=c,n=t,o=a;break}case\"Q\":{const[t,s,a,h]=l,c=n+2*(t-n)/3,u=o+2*(s-o)/3,p=a+2*(t-a)/3,f=h+2*(s-h)/3;e.push({key:\"C\",data:[c,u,p,f,a,h]}),r=t,i=s,n=a,o=h;break}case\"A\":{const t=Math.abs(l[0]),s=Math.abs(l[1]),a=l[2],h=l[3],r=l[4],i=l[5],c=l[6];if(0===t||0===s)e.push({key:\"C\",data:[n,o,i,c,i,c]}),n=i,o=c;else if(n!==i||o!==c){x(n,o,i,c,t,s,a,h,r).forEach((function(t){e.push({key:\"C\",data:t})})),n=i,o=c}break}case\"Z\":e.push({key:\"Z\",data:[]}),n=a,o=h}s=c}return e}function w(t,e,s){return[t*Math.cos(s)-e*Math.sin(s),t*Math.sin(s)+e*Math.cos(s)]}function x(t,e,s,n,o,a,h,r,i,c){const l=(u=h,Math.PI*u/180);var u;let p=[],f=0,d=0,g=0,M=0;if(c)[f,d,g,M]=c;else{[t,e]=w(t,e,-l),[s,n]=w(s,n,-l);const h=(t-s)/2,c=(e-n)/2;let u=h*h/(o*o)+c*c/(a*a);u>1&&(u=Math.sqrt(u),o*=u,a*=u);const p=o*o,k=a*a,b=p*k-p*c*c-k*h*h,y=p*c*c+k*h*h,m=(r===i?-1:1)*Math.sqrt(Math.abs(b/y));g=m*o*c/a+(t+s)/2,M=m*-a*h/o+(e+n)/2,f=Math.asin(parseFloat(((e-M)/a).toFixed(9))),d=Math.asin(parseFloat(((n-M)/a).toFixed(9))),td&&(f-=2*Math.PI),!i&&d>f&&(d-=2*Math.PI)}let k=d-f;if(Math.abs(k)>120*Math.PI/180){const t=d,e=s,r=n;d=i&&d>f?f+120*Math.PI/180*1:f+120*Math.PI/180*-1,p=x(s=g+o*Math.cos(d),n=M+a*Math.sin(d),e,r,o,a,h,0,i,[d,t,g,M])}k=d-f;const b=Math.cos(f),y=Math.sin(f),m=Math.cos(d),P=Math.sin(d),v=Math.tan(k/4),S=4/3*o*v,O=4/3*a*v,L=[t,e],T=[t+S*y,e-O*b],D=[s+S*P,n-O*m],A=[s,n];if(T[0]=2*L[0]-T[0],T[1]=2*L[1]-T[1],c)return[T,D,A].concat(p);{p=[T,D,A].concat(p);const t=[];for(let e=0;e2){const o=[];for(let e=0;e2*Math.PI&&(f=0,d=2*Math.PI);const g=2*Math.PI/i.curveStepCount,M=Math.min(g/2,(d-f)/2),k=V(M,c,l,u,p,f,d,1,i);if(!i.disableMultiStroke){const t=V(M,c,l,u,p,f,d,1.5,i);k.push(...t)}return h&&(r?k.push(...$(c,l,c+u*Math.cos(f),l+p*Math.sin(f),i),...$(c,l,c+u*Math.cos(d),l+p*Math.sin(d),i)):k.push({op:\"lineTo\",data:[c,l]},{op:\"lineTo\",data:[c+u*Math.cos(f),l+p*Math.sin(f)]})),{type:\"path\",ops:k}}function _(t,e){const s=m(y(b(t))),n=[];let o=[0,0],a=[0,0];for(const{key:t,data:h}of s)switch(t){case\"M\":a=[h[0],h[1]],o=[h[0],h[1]];break;case\"L\":n.push(...$(a[0],a[1],h[0],h[1],e)),a=[h[0],h[1]];break;case\"C\":{const[t,s,o,r,i,c]=h;n.push(...Z(t,s,o,r,i,c,a,e)),a=[i,c];break}case\"Z\":n.push(...$(a[0],a[1],o[0],o[1],e)),a=[o[0],o[1]]}return{type:\"path\",ops:n}}function I(t,e){const s=[];for(const n of t)if(n.length){const t=e.maxRandomnessOffset||0,o=n.length;if(o>2){s.push({op:\"move\",data:[n[0][0]+G(t,e),n[0][1]+G(t,e)]});for(let a=1;a500?.4:-.0016668*i+1.233334;let l=o.maxRandomnessOffset||0;l*l*100>r&&(l=i/10);const u=l/2,p=.2+.2*W(o);let f=o.bowing*o.maxRandomnessOffset*(n-e)/200,d=o.bowing*o.maxRandomnessOffset*(t-s)/200;f=G(f,o,c),d=G(d,o,c);const g=[],M=()=>G(u,o,c),k=()=>G(l,o,c),b=o.preserveVertices;return a&&(h?g.push({op:\"move\",data:[t+(b?0:M()),e+(b?0:M())]}):g.push({op:\"move\",data:[t+(b?0:G(l,o,c)),e+(b?0:G(l,o,c))]})),h?g.push({op:\"bcurveTo\",data:[f+t+(s-t)*p+M(),d+e+(n-e)*p+M(),f+t+2*(s-t)*p+M(),d+e+2*(n-e)*p+M(),s+(b?0:M()),n+(b?0:M())]}):g.push({op:\"bcurveTo\",data:[f+t+(s-t)*p+k(),d+e+(n-e)*p+k(),f+t+2*(s-t)*p+k(),d+e+2*(n-e)*p+k(),s+(b?0:k()),n+(b?0:k())]}),g}function j(t,e,s){if(!t.length)return[];const n=[];n.push([t[0][0]+G(e,s),t[0][1]+G(e,s)]),n.push([t[0][0]+G(e,s),t[0][1]+G(e,s)]);for(let o=1;o3){const a=[],h=1-s.curveTightness;o.push({op:\"move\",data:[t[1][0],t[1][1]]});for(let e=1;e+21&&o.push(s)}else o.push(s);o.push(t[e+3])}else{const n=.5,a=t[e+0],h=t[e+1],r=t[e+2],i=t[e+3],c=J(a,h,n),l=J(h,r,n),u=J(r,i,n),p=J(c,l,n),f=J(l,u,n),d=J(p,f,n);K([a,c,p,d],0,s,o),K([d,f,u,i],0,s,o)}var a,h;return o}function U(t,e){return X(t,0,t.length,e)}function X(t,e,s,n,o){const a=o||[],h=t[e],r=t[s-1];let i=0,c=1;for(let n=e+1;ni&&(i=e,c=n)}return Math.sqrt(i)>n?(X(t,e,c+1,n,a),X(t,c,s,n,a)):(a.length||a.push(h),a.push(r)),a}function Y(t,e=.15,s){const n=[],o=(t.length-1)/3;for(let s=0;s0?X(n,0,n.length,s):n}const tt=\"none\";class et{constructor(t){this.defaultOptions={maxRandomnessOffset:2,roughness:1,bowing:1,stroke:\"#000\",strokeWidth:1,curveTightness:0,curveFitting:.95,curveStepCount:9,fillStyle:\"hachure\",fillWeight:-1,hachureAngle:-41,hachureGap:-1,dashOffset:-1,dashGap:-1,zigzagOffset:-1,seed:0,disableMultiStroke:!1,disableMultiStrokeFill:!1,preserveVertices:!1,fillShapeRoughnessGain:.8},this.config=t||{},this.config.options&&(this.defaultOptions=this._o(this.config.options))}static newSeed(){return Math.floor(Math.random()*2**31)}_o(t){return t?Object.assign({},this.defaultOptions,t):this.defaultOptions}_d(t,e,s){return{shape:t,sets:e||[],options:s||this.defaultOptions}}line(t,e,s,n,o){const a=this._o(o);return this._d(\"line\",[v(t,e,s,n,a)],a)}rectangle(t,e,s,n,o){const a=this._o(o),h=[],r=O(t,e,s,n,a);if(a.fill){const o=[[t,e],[t+s,e],[t+s,e+n],[t,e+n]];\"solid\"===a.fillStyle?h.push(I([o],a)):h.push(C([o],a))}return a.stroke!==tt&&h.push(r),this._d(\"rectangle\",h,a)}ellipse(t,e,s,n,o){const a=this._o(o),h=[],r=T(s,n,a),i=D(t,e,a,r);if(a.fill)if(\"solid\"===a.fillStyle){const s=D(t,e,a,r).opset;s.type=\"fillPath\",h.push(s)}else h.push(C([i.estimatedPoints],a));return a.stroke!==tt&&h.push(i.opset),this._d(\"ellipse\",h,a)}circle(t,e,s,n){const o=this.ellipse(t,e,s,s,n);return o.shape=\"circle\",o}linearPath(t,e){const s=this._o(e);return this._d(\"linearPath\",[S(t,!1,s)],s)}arc(t,e,s,n,o,a,h=!1,r){const i=this._o(r),c=[],l=A(t,e,s,n,o,a,h,!0,i);if(h&&i.fill)if(\"solid\"===i.fillStyle){const h=Object.assign({},i);h.disableMultiStroke=!0;const r=A(t,e,s,n,o,a,!0,!1,h);r.type=\"fillPath\",c.push(r)}else c.push(function(t,e,s,n,o,a,h){const r=t,i=e;let c=Math.abs(s/2),l=Math.abs(n/2);c+=G(.01*c,h),l+=G(.01*l,h);let u=o,p=a;for(;u<0;)u+=2*Math.PI,p+=2*Math.PI;p-u>2*Math.PI&&(u=0,p=2*Math.PI);const f=(p-u)/h.curveStepCount,d=[];for(let t=u;t<=p;t+=f)d.push([r+c*Math.cos(t),i+l*Math.sin(t)]);return d.push([r+c*Math.cos(p),i+l*Math.sin(p)]),d.push([r,i]),C([d],h)}(t,e,s,n,o,a,i));return i.stroke!==tt&&c.push(l),this._d(\"arc\",c,i)}curve(t,e){const s=this._o(e),n=[],o=L(t,s);if(s.fill&&s.fill!==tt)if(\"solid\"===s.fillStyle){const e=L(t,Object.assign(Object.assign({},s),{disableMultiStroke:!0,roughness:s.roughness?s.roughness+s.fillShapeRoughnessGain:0}));n.push({type:\"fillPath\",ops:this._mergedShape(e.ops)})}else{const e=[],o=t;if(o.length){const t=\"number\"==typeof o[0][0]?[o]:o;for(const n of t)n.length<3?e.push(...n):3===n.length?e.push(...Y(H([n[0],n[0],n[1],n[2]]),10,(1+s.roughness)/2)):e.push(...Y(H(n),10,(1+s.roughness)/2))}e.length&&n.push(C([e],s))}return s.stroke!==tt&&n.push(o),this._d(\"curve\",n,s)}polygon(t,e){const s=this._o(e),n=[],o=S(t,!0,s);return s.fill&&(\"solid\"===s.fillStyle?n.push(I([t],s)):n.push(C([t],s))),s.stroke!==tt&&n.push(o),this._d(\"polygon\",n,s)}path(t,e){const s=this._o(e),n=[];if(!t)return this._d(\"path\",n,s);t=(t||\"\").replace(/\\n/g,\" \").replace(/(-\\s)/g,\"-\").replace(\"/(ss)/g\",\" \");const o=s.fill&&\"transparent\"!==s.fill&&s.fill!==tt,a=s.stroke!==tt,h=!!(s.simplification&&s.simplification<1),r=function(t,e,s){const n=m(y(b(t))),o=[];let a=[],h=[0,0],r=[];const i=()=>{r.length>=4&&a.push(...Y(r,e)),r=[]},c=()=>{i(),a.length&&(o.push(a),a=[])};for(const{key:t,data:e}of n)switch(t){case\"M\":c(),h=[e[0],e[1]],a.push(h);break;case\"L\":i(),a.push([e[0],e[1]]);break;case\"C\":if(!r.length){const t=a.length?a[a.length-1]:h;r.push([t[0],t[1]])}r.push([e[0],e[1]]),r.push([e[2],e[3]]),r.push([e[4],e[5]]);break;case\"Z\":i(),a.push([h[0],h[1]])}if(c(),!s)return o;const l=[];for(const t of o){const e=U(t,s);e.length&&l.push(e)}return l}(t,1,h?4-4*(s.simplification||1):(1+s.roughness)/2),i=_(t,s);if(o)if(\"solid\"===s.fillStyle)if(1===r.length){const e=_(t,Object.assign(Object.assign({},s),{disableMultiStroke:!0,roughness:s.roughness?s.roughness+s.fillShapeRoughnessGain:0}));n.push({type:\"fillPath\",ops:this._mergedShape(e.ops)})}else n.push(I(r,s));else n.push(C(r,s));return a&&(h?r.forEach((t=>{n.push(S(t,!1,s))})):n.push(i)),this._d(\"path\",n,s)}opsToPath(t,e){let s=\"\";for(const n of t.ops){const t=\"number\"==typeof e&&e>=0?n.data.map((t=>+t.toFixed(e))):n.data;switch(n.op){case\"move\":s+=`M${t[0]} ${t[1]} `;break;case\"bcurveTo\":s+=`C${t[0]} ${t[1]}, ${t[2]} ${t[3]}, ${t[4]} ${t[5]} `;break;case\"lineTo\":s+=`L${t[0]} ${t[1]} `}}return s.trim()}toPaths(t){const e=t.sets||[],s=t.options||this.defaultOptions,n=[];for(const t of e){let e=null;switch(t.type){case\"path\":e={d:this.opsToPath(t),stroke:s.stroke,strokeWidth:s.strokeWidth,fill:tt};break;case\"fillPath\":e={d:this.opsToPath(t),stroke:tt,strokeWidth:0,fill:s.fill||tt};break;case\"fillSketch\":e=this.fillSketch(t,s)}e&&n.push(e)}return n}fillSketch(t,e){let s=e.fillWeight;return s<0&&(s=e.strokeWidth/2),{d:this.opsToPath(t),stroke:e.fill||tt,strokeWidth:s,fill:tt}}_mergedShape(t){return t.filter(((t,e)=>0===e||\"move\"!==t.op))}}class st{constructor(t,e){this.canvas=t,this.ctx=this.canvas.getContext(\"2d\"),this.gen=new et(e)}draw(t){const e=t.sets||[],s=t.options||this.getDefaultOptions(),n=this.ctx,o=t.options.fixedDecimalPlaceDigits;for(const a of e)switch(a.type){case\"path\":n.save(),n.strokeStyle=\"none\"===s.stroke?\"transparent\":s.stroke,n.lineWidth=s.strokeWidth,s.strokeLineDash&&n.setLineDash(s.strokeLineDash),s.strokeLineDashOffset&&(n.lineDashOffset=s.strokeLineDashOffset),this._drawToContext(n,a,o),n.restore();break;case\"fillPath\":{n.save(),n.fillStyle=s.fill||\"\";const e=\"curve\"===t.shape||\"polygon\"===t.shape||\"path\"===t.shape?\"evenodd\":\"nonzero\";this._drawToContext(n,a,o,e),n.restore();break}case\"fillSketch\":this.fillSketch(n,a,s)}}fillSketch(t,e,s){let n=s.fillWeight;n<0&&(n=s.strokeWidth/2),t.save(),s.fillLineDash&&t.setLineDash(s.fillLineDash),s.fillLineDashOffset&&(t.lineDashOffset=s.fillLineDashOffset),t.strokeStyle=s.fill||\"\",t.lineWidth=n,this._drawToContext(t,e,s.fixedDecimalPlaceDigits),t.restore()}_drawToContext(t,e,s,n=\"nonzero\"){t.beginPath();for(const n of e.ops){const e=\"number\"==typeof s&&s>=0?n.data.map((t=>+t.toFixed(s))):n.data;switch(n.op){case\"move\":t.moveTo(e[0],e[1]);break;case\"bcurveTo\":t.bezierCurveTo(e[0],e[1],e[2],e[3],e[4],e[5]);break;case\"lineTo\":t.lineTo(e[0],e[1])}}\"fillPath\"===e.type?t.fill(n):t.stroke()}get generator(){return this.gen}getDefaultOptions(){return this.gen.defaultOptions}line(t,e,s,n,o){const a=this.gen.line(t,e,s,n,o);return this.draw(a),a}rectangle(t,e,s,n,o){const a=this.gen.rectangle(t,e,s,n,o);return this.draw(a),a}ellipse(t,e,s,n,o){const a=this.gen.ellipse(t,e,s,n,o);return this.draw(a),a}circle(t,e,s,n){const o=this.gen.circle(t,e,s,n);return this.draw(o),o}linearPath(t,e){const s=this.gen.linearPath(t,e);return this.draw(s),s}polygon(t,e){const s=this.gen.polygon(t,e);return this.draw(s),s}arc(t,e,s,n,o,a,h=!1,r){const i=this.gen.arc(t,e,s,n,o,a,h,r);return this.draw(i),i}curve(t,e){const s=this.gen.curve(t,e);return this.draw(s),s}path(t,e){const s=this.gen.path(t,e);return this.draw(s),s}}const nt=\"http://www.w3.org/2000/svg\";class ot{constructor(t,e){this.svg=t,this.gen=new et(e)}draw(t){const e=t.sets||[],s=t.options||this.getDefaultOptions(),n=this.svg.ownerDocument||window.document,o=n.createElementNS(nt,\"g\"),a=t.options.fixedDecimalPlaceDigits;for(const h of e){let e=null;switch(h.type){case\"path\":e=n.createElementNS(nt,\"path\"),e.setAttribute(\"d\",this.opsToPath(h,a)),e.setAttribute(\"stroke\",s.stroke),e.setAttribute(\"stroke-width\",s.strokeWidth+\"\"),e.setAttribute(\"fill\",\"none\"),s.strokeLineDash&&e.setAttribute(\"stroke-dasharray\",s.strokeLineDash.join(\" \").trim()),s.strokeLineDashOffset&&e.setAttribute(\"stroke-dashoffset\",`${s.strokeLineDashOffset}`);break;case\"fillPath\":e=n.createElementNS(nt,\"path\"),e.setAttribute(\"d\",this.opsToPath(h,a)),e.setAttribute(\"stroke\",\"none\"),e.setAttribute(\"stroke-width\",\"0\"),e.setAttribute(\"fill\",s.fill||\"\"),\"curve\"!==t.shape&&\"polygon\"!==t.shape||e.setAttribute(\"fill-rule\",\"evenodd\");break;case\"fillSketch\":e=this.fillSketch(n,h,s)}e&&o.appendChild(e)}return o}fillSketch(t,e,s){let n=s.fillWeight;n<0&&(n=s.strokeWidth/2);const o=t.createElementNS(nt,\"path\");return o.setAttribute(\"d\",this.opsToPath(e,s.fixedDecimalPlaceDigits)),o.setAttribute(\"stroke\",s.fill||\"\"),o.setAttribute(\"stroke-width\",n+\"\"),o.setAttribute(\"fill\",\"none\"),s.fillLineDash&&o.setAttribute(\"stroke-dasharray\",s.fillLineDash.join(\" \").trim()),s.fillLineDashOffset&&o.setAttribute(\"stroke-dashoffset\",`${s.fillLineDashOffset}`),o}get generator(){return this.gen}getDefaultOptions(){return this.gen.defaultOptions}opsToPath(t,e){return this.gen.opsToPath(t,e)}line(t,e,s,n,o){const a=this.gen.line(t,e,s,n,o);return this.draw(a)}rectangle(t,e,s,n,o){const a=this.gen.rectangle(t,e,s,n,o);return this.draw(a)}ellipse(t,e,s,n,o){const a=this.gen.ellipse(t,e,s,n,o);return this.draw(a)}circle(t,e,s,n){const o=this.gen.circle(t,e,s,n);return this.draw(o)}linearPath(t,e){const s=this.gen.linearPath(t,e);return this.draw(s)}polygon(t,e){const s=this.gen.polygon(t,e);return this.draw(s)}arc(t,e,s,n,o,a,h=!1,r){const i=this.gen.arc(t,e,s,n,o,a,h,r);return this.draw(i)}curve(t,e){const s=this.gen.curve(t,e);return this.draw(s)}path(t,e){const s=this.gen.path(t,e);return this.draw(s)}}var at={canvas:(t,e)=>new st(t,e),svg:(t,e)=>new ot(t,e),generator:t=>new et(t),newSeed:()=>et.newSeed()};export{at as default};\n", "import {\n getSubGraphTitleMargins\n} from \"./chunk-CVBHYZKI.mjs\";\nimport {\n compileStyles,\n solidStateFill,\n styles2String,\n userNodeOverrides\n} from \"./chunk-ATLVNIR6.mjs\";\nimport {\n createText,\n getIconSVG\n} from \"./chunk-JA3XYJ7Z.mjs\";\nimport {\n calculateTextWidth,\n decodeEntities,\n handleUndefinedAttr,\n parseFontSize\n} from \"./chunk-S3R3BYOJ.mjs\";\nimport {\n common_default,\n defaultConfig_default,\n evaluate,\n getConfig,\n getConfig2,\n hasKatex,\n parseGenericTypes,\n renderKatexSanitized,\n sanitizeText,\n sanitizeText2\n} from \"./chunk-ABZYJK2D.mjs\";\nimport {\n __name,\n log\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/rendering-util/rendering-elements/shapes/util.ts\nimport { select } from \"d3\";\nvar labelHelper = /* @__PURE__ */ __name(async (parent, node, _classes) => {\n let cssClasses;\n const useHtmlLabels = node.useHtmlLabels || evaluate(getConfig2()?.htmlLabels);\n if (!_classes) {\n cssClasses = \"node default\";\n } else {\n cssClasses = _classes;\n }\n const shapeSvg = parent.insert(\"g\").attr(\"class\", cssClasses).attr(\"id\", node.domId || node.id);\n const labelEl = shapeSvg.insert(\"g\").attr(\"class\", \"label\").attr(\"style\", handleUndefinedAttr(node.labelStyle));\n let label;\n if (node.label === void 0) {\n label = \"\";\n } else {\n label = typeof node.label === \"string\" ? node.label : node.label[0];\n }\n const text2 = await createText(labelEl, sanitizeText(decodeEntities(label), getConfig2()), {\n useHtmlLabels,\n width: node.width || getConfig2().flowchart?.wrappingWidth,\n // @ts-expect-error -- This is currently not used. Should this be `classes` instead?\n cssClasses: \"markdown-node-label\",\n style: node.labelStyle,\n addSvgBackground: !!node.icon || !!node.img\n });\n let bbox = text2.getBBox();\n const halfPadding = (node?.padding ?? 0) / 2;\n if (useHtmlLabels) {\n const div = text2.children[0];\n const dv = select(text2);\n const images = div.getElementsByTagName(\"img\");\n if (images) {\n const noImgText = label.replace(/]*>/g, \"\").trim() === \"\";\n await Promise.all(\n [...images].map(\n (img) => new Promise((res) => {\n function setupImage() {\n img.style.display = \"flex\";\n img.style.flexDirection = \"column\";\n if (noImgText) {\n const bodyFontSize = getConfig2().fontSize ? getConfig2().fontSize : window.getComputedStyle(document.body).fontSize;\n const enlargingFactor = 5;\n const [parsedBodyFontSize = defaultConfig_default.fontSize] = parseFontSize(bodyFontSize);\n const width = parsedBodyFontSize * enlargingFactor + \"px\";\n img.style.minWidth = width;\n img.style.maxWidth = width;\n } else {\n img.style.width = \"100%\";\n }\n res(img);\n }\n __name(setupImage, \"setupImage\");\n setTimeout(() => {\n if (img.complete) {\n setupImage();\n }\n });\n img.addEventListener(\"error\", setupImage);\n img.addEventListener(\"load\", setupImage);\n })\n )\n );\n }\n bbox = div.getBoundingClientRect();\n dv.attr(\"width\", bbox.width);\n dv.attr(\"height\", bbox.height);\n }\n if (useHtmlLabels) {\n labelEl.attr(\"transform\", \"translate(\" + -bbox.width / 2 + \", \" + -bbox.height / 2 + \")\");\n } else {\n labelEl.attr(\"transform\", \"translate(0, \" + -bbox.height / 2 + \")\");\n }\n if (node.centerLabel) {\n labelEl.attr(\"transform\", \"translate(\" + -bbox.width / 2 + \", \" + -bbox.height / 2 + \")\");\n }\n labelEl.insert(\"rect\", \":first-child\");\n return { shapeSvg, bbox, halfPadding, label: labelEl };\n}, \"labelHelper\");\nvar insertLabel = /* @__PURE__ */ __name(async (parent, label, options) => {\n const useHtmlLabels = options.useHtmlLabels || evaluate(getConfig2()?.flowchart?.htmlLabels);\n const labelEl = parent.insert(\"g\").attr(\"class\", \"label\").attr(\"style\", options.labelStyle || \"\");\n const text2 = await createText(labelEl, sanitizeText(decodeEntities(label), getConfig2()), {\n useHtmlLabels,\n width: options.width || getConfig2()?.flowchart?.wrappingWidth,\n style: options.labelStyle,\n addSvgBackground: !!options.icon || !!options.img\n });\n let bbox = text2.getBBox();\n const halfPadding = options.padding / 2;\n if (evaluate(getConfig2()?.flowchart?.htmlLabels)) {\n const div = text2.children[0];\n const dv = select(text2);\n bbox = div.getBoundingClientRect();\n dv.attr(\"width\", bbox.width);\n dv.attr(\"height\", bbox.height);\n }\n if (useHtmlLabels) {\n labelEl.attr(\"transform\", \"translate(\" + -bbox.width / 2 + \", \" + -bbox.height / 2 + \")\");\n } else {\n labelEl.attr(\"transform\", \"translate(0, \" + -bbox.height / 2 + \")\");\n }\n if (options.centerLabel) {\n labelEl.attr(\"transform\", \"translate(\" + -bbox.width / 2 + \", \" + -bbox.height / 2 + \")\");\n }\n labelEl.insert(\"rect\", \":first-child\");\n return { shapeSvg: parent, bbox, halfPadding, label: labelEl };\n}, \"insertLabel\");\nvar updateNodeBounds = /* @__PURE__ */ __name((node, element) => {\n const bbox = element.node().getBBox();\n node.width = bbox.width;\n node.height = bbox.height;\n}, \"updateNodeBounds\");\nvar getNodeClasses = /* @__PURE__ */ __name((node, extra) => (node.look === \"handDrawn\" ? \"rough-node\" : \"node\") + \" \" + node.cssClasses + \" \" + (extra || \"\"), \"getNodeClasses\");\nfunction createPathFromPoints(points) {\n const pointStrings = points.map((p, i) => `${i === 0 ? \"M\" : \"L\"}${p.x},${p.y}`);\n pointStrings.push(\"Z\");\n return pointStrings.join(\" \");\n}\n__name(createPathFromPoints, \"createPathFromPoints\");\nfunction generateFullSineWavePoints(x1, y1, x2, y2, amplitude, numCycles) {\n const points = [];\n const steps = 50;\n const deltaX = x2 - x1;\n const deltaY = y2 - y1;\n const cycleLength = deltaX / numCycles;\n const frequency = 2 * Math.PI / cycleLength;\n const midY = y1 + deltaY / 2;\n for (let i = 0; i <= steps; i++) {\n const t = i / steps;\n const x = x1 + t * deltaX;\n const y = midY + amplitude * Math.sin(frequency * (x - x1));\n points.push({ x, y });\n }\n return points;\n}\n__name(generateFullSineWavePoints, \"generateFullSineWavePoints\");\nfunction generateCirclePoints(centerX, centerY, radius, numPoints, startAngle, endAngle) {\n const points = [];\n const startAngleRad = startAngle * Math.PI / 180;\n const endAngleRad = endAngle * Math.PI / 180;\n const angleRange = endAngleRad - startAngleRad;\n const angleStep = angleRange / (numPoints - 1);\n for (let i = 0; i < numPoints; i++) {\n const angle = startAngleRad + i * angleStep;\n const x = centerX + radius * Math.cos(angle);\n const y = centerY + radius * Math.sin(angle);\n points.push({ x: -x, y: -y });\n }\n return points;\n}\n__name(generateCirclePoints, \"generateCirclePoints\");\n\n// src/rendering-util/rendering-elements/clusters.js\nimport { select as select3 } from \"d3\";\nimport rough from \"roughjs\";\n\n// src/rendering-util/rendering-elements/intersect/intersect-rect.js\nvar intersectRect = /* @__PURE__ */ __name((node, point) => {\n var x = node.x;\n var y = node.y;\n var dx = point.x - x;\n var dy = point.y - y;\n var w = node.width / 2;\n var h = node.height / 2;\n var sx, sy;\n if (Math.abs(dy) * w > Math.abs(dx) * h) {\n if (dy < 0) {\n h = -h;\n }\n sx = dy === 0 ? 0 : h * dx / dy;\n sy = h;\n } else {\n if (dx < 0) {\n w = -w;\n }\n sx = w;\n sy = dx === 0 ? 0 : w * dy / dx;\n }\n return { x: x + sx, y: y + sy };\n}, \"intersectRect\");\nvar intersect_rect_default = intersectRect;\n\n// src/rendering-util/rendering-elements/createLabel.js\nimport { select as select2 } from \"d3\";\nfunction applyStyle(dom, styleFn) {\n if (styleFn) {\n dom.attr(\"style\", styleFn);\n }\n}\n__name(applyStyle, \"applyStyle\");\nasync function addHtmlLabel(node) {\n const fo = select2(document.createElementNS(\"http://www.w3.org/2000/svg\", \"foreignObject\"));\n const div = fo.append(\"xhtml:div\");\n const config = getConfig2();\n let label = node.label;\n if (node.label && hasKatex(node.label)) {\n label = await renderKatexSanitized(node.label.replace(common_default.lineBreakRegex, \"\\n\"), config);\n }\n const labelClass = node.isNode ? \"nodeLabel\" : \"edgeLabel\";\n const labelSpan = '\" + label + \"\";\n div.html(sanitizeText(labelSpan, config));\n applyStyle(div, node.labelStyle);\n div.style(\"display\", \"inline-block\");\n div.style(\"padding-right\", \"1px\");\n div.style(\"white-space\", \"nowrap\");\n div.attr(\"xmlns\", \"http://www.w3.org/1999/xhtml\");\n return fo.node();\n}\n__name(addHtmlLabel, \"addHtmlLabel\");\nvar createLabel = /* @__PURE__ */ __name(async (_vertexText, style, isTitle, isNode) => {\n let vertexText = _vertexText || \"\";\n if (typeof vertexText === \"object\") {\n vertexText = vertexText[0];\n }\n if (evaluate(getConfig2().flowchart.htmlLabels)) {\n vertexText = vertexText.replace(/\\\\n|\\n/g, \"
\");\n log.info(\"vertexText\" + vertexText);\n const node = {\n isNode,\n label: decodeEntities(vertexText).replace(\n /fa[blrs]?:fa-[\\w-]+/g,\n (s) => ``\n ),\n labelStyle: style ? style.replace(\"fill:\", \"color:\") : style\n };\n let vertexNode = await addHtmlLabel(node);\n return vertexNode;\n } else {\n const svgLabel = document.createElementNS(\"http://www.w3.org/2000/svg\", \"text\");\n svgLabel.setAttribute(\"style\", style.replace(\"color:\", \"fill:\"));\n let rows = [];\n if (typeof vertexText === \"string\") {\n rows = vertexText.split(/\\\\n|\\n|/gi);\n } else if (Array.isArray(vertexText)) {\n rows = vertexText;\n } else {\n rows = [];\n }\n for (const row of rows) {\n const tspan = document.createElementNS(\"http://www.w3.org/2000/svg\", \"tspan\");\n tspan.setAttributeNS(\"http://www.w3.org/XML/1998/namespace\", \"xml:space\", \"preserve\");\n tspan.setAttribute(\"dy\", \"1em\");\n tspan.setAttribute(\"x\", \"0\");\n if (isTitle) {\n tspan.setAttribute(\"class\", \"title-row\");\n } else {\n tspan.setAttribute(\"class\", \"row\");\n }\n tspan.textContent = row.trim();\n svgLabel.appendChild(tspan);\n }\n return svgLabel;\n }\n}, \"createLabel\");\nvar createLabel_default = createLabel;\n\n// src/rendering-util/rendering-elements/shapes/roundedRectPath.ts\nvar createRoundedRectPathD = /* @__PURE__ */ __name((x, y, totalWidth, totalHeight, radius) => [\n \"M\",\n x + radius,\n y,\n // Move to the first point\n \"H\",\n x + totalWidth - radius,\n // Draw horizontal line to the beginning of the right corner\n \"A\",\n radius,\n radius,\n 0,\n 0,\n 1,\n x + totalWidth,\n y + radius,\n // Draw arc to the right top corner\n \"V\",\n y + totalHeight - radius,\n // Draw vertical line down to the beginning of the right bottom corner\n \"A\",\n radius,\n radius,\n 0,\n 0,\n 1,\n x + totalWidth - radius,\n y + totalHeight,\n // Draw arc to the right bottom corner\n \"H\",\n x + radius,\n // Draw horizontal line to the beginning of the left bottom corner\n \"A\",\n radius,\n radius,\n 0,\n 0,\n 1,\n x,\n y + totalHeight - radius,\n // Draw arc to the left bottom corner\n \"V\",\n y + radius,\n // Draw vertical line up to the beginning of the left top corner\n \"A\",\n radius,\n radius,\n 0,\n 0,\n 1,\n x + radius,\n y,\n // Draw arc to the left top corner\n \"Z\"\n // Close the path\n].join(\" \"), \"createRoundedRectPathD\");\n\n// src/rendering-util/rendering-elements/clusters.js\nvar rect = /* @__PURE__ */ __name(async (parent, node) => {\n log.info(\"Creating subgraph rect for \", node.id, node);\n const siteConfig = getConfig2();\n const { themeVariables, handDrawnSeed } = siteConfig;\n const { clusterBkg, clusterBorder } = themeVariables;\n const { labelStyles, nodeStyles, borderStyles, backgroundStyles } = styles2String(node);\n const shapeSvg = parent.insert(\"g\").attr(\"class\", \"cluster \" + node.cssClasses).attr(\"id\", node.id).attr(\"data-look\", node.look);\n const useHtmlLabels = evaluate(siteConfig.flowchart.htmlLabels);\n const labelEl = shapeSvg.insert(\"g\").attr(\"class\", \"cluster-label \");\n const text2 = await createText(labelEl, node.label, {\n style: node.labelStyle,\n useHtmlLabels,\n isNode: true\n });\n let bbox = text2.getBBox();\n if (evaluate(siteConfig.flowchart.htmlLabels)) {\n const div = text2.children[0];\n const dv = select3(text2);\n bbox = div.getBoundingClientRect();\n dv.attr(\"width\", bbox.width);\n dv.attr(\"height\", bbox.height);\n }\n const width = node.width <= bbox.width + node.padding ? bbox.width + node.padding : node.width;\n if (node.width <= bbox.width + node.padding) {\n node.diff = (width - node.width) / 2 - node.padding;\n } else {\n node.diff = -node.padding;\n }\n const height = node.height;\n const x = node.x - width / 2;\n const y = node.y - height / 2;\n log.trace(\"Data \", node, JSON.stringify(node));\n let rect2;\n if (node.look === \"handDrawn\") {\n const rc = rough.svg(shapeSvg);\n const options = userNodeOverrides(node, {\n roughness: 0.7,\n fill: clusterBkg,\n // fill: 'red',\n stroke: clusterBorder,\n fillWeight: 3,\n seed: handDrawnSeed\n });\n const roughNode = rc.path(createRoundedRectPathD(x, y, width, height, 0), options);\n rect2 = shapeSvg.insert(() => {\n log.debug(\"Rough node insert CXC\", roughNode);\n return roughNode;\n }, \":first-child\");\n rect2.select(\"path:nth-child(2)\").attr(\"style\", borderStyles.join(\";\"));\n rect2.select(\"path\").attr(\"style\", backgroundStyles.join(\";\").replace(\"fill\", \"stroke\"));\n } else {\n rect2 = shapeSvg.insert(\"rect\", \":first-child\");\n rect2.attr(\"style\", nodeStyles).attr(\"rx\", node.rx).attr(\"ry\", node.ry).attr(\"x\", x).attr(\"y\", y).attr(\"width\", width).attr(\"height\", height);\n }\n const { subGraphTitleTopMargin } = getSubGraphTitleMargins(siteConfig);\n labelEl.attr(\n \"transform\",\n // This puts the label on top of the box instead of inside it\n `translate(${node.x - bbox.width / 2}, ${node.y - node.height / 2 + subGraphTitleTopMargin})`\n );\n if (labelStyles) {\n const span = labelEl.select(\"span\");\n if (span) {\n span.attr(\"style\", labelStyles);\n }\n }\n const rectBox = rect2.node().getBBox();\n node.offsetX = 0;\n node.width = rectBox.width;\n node.height = rectBox.height;\n node.offsetY = bbox.height - node.padding / 2;\n node.intersect = function(point) {\n return intersect_rect_default(node, point);\n };\n return { cluster: shapeSvg, labelBBox: bbox };\n}, \"rect\");\nvar noteGroup = /* @__PURE__ */ __name((parent, node) => {\n const shapeSvg = parent.insert(\"g\").attr(\"class\", \"note-cluster\").attr(\"id\", node.id);\n const rect2 = shapeSvg.insert(\"rect\", \":first-child\");\n const padding = 0 * node.padding;\n const halfPadding = padding / 2;\n rect2.attr(\"rx\", node.rx).attr(\"ry\", node.ry).attr(\"x\", node.x - node.width / 2 - halfPadding).attr(\"y\", node.y - node.height / 2 - halfPadding).attr(\"width\", node.width + padding).attr(\"height\", node.height + padding).attr(\"fill\", \"none\");\n const rectBox = rect2.node().getBBox();\n node.width = rectBox.width;\n node.height = rectBox.height;\n node.intersect = function(point) {\n return intersect_rect_default(node, point);\n };\n return { cluster: shapeSvg, labelBBox: { width: 0, height: 0 } };\n}, \"noteGroup\");\nvar roundedWithTitle = /* @__PURE__ */ __name(async (parent, node) => {\n const siteConfig = getConfig2();\n const { themeVariables, handDrawnSeed } = siteConfig;\n const { altBackground, compositeBackground, compositeTitleBackground, nodeBorder } = themeVariables;\n const shapeSvg = parent.insert(\"g\").attr(\"class\", node.cssClasses).attr(\"id\", node.id).attr(\"data-id\", node.id).attr(\"data-look\", node.look);\n const outerRectG = shapeSvg.insert(\"g\", \":first-child\");\n const label = shapeSvg.insert(\"g\").attr(\"class\", \"cluster-label\");\n let innerRect = shapeSvg.append(\"rect\");\n const text2 = label.node().appendChild(await createLabel_default(node.label, node.labelStyle, void 0, true));\n let bbox = text2.getBBox();\n if (evaluate(siteConfig.flowchart.htmlLabels)) {\n const div = text2.children[0];\n const dv = select3(text2);\n bbox = div.getBoundingClientRect();\n dv.attr(\"width\", bbox.width);\n dv.attr(\"height\", bbox.height);\n }\n const padding = 0 * node.padding;\n const halfPadding = padding / 2;\n const width = (node.width <= bbox.width + node.padding ? bbox.width + node.padding : node.width) + padding;\n if (node.width <= bbox.width + node.padding) {\n node.diff = (width - node.width) / 2 - node.padding;\n } else {\n node.diff = -node.padding;\n }\n const height = node.height + padding;\n const innerHeight = node.height + padding - bbox.height - 6;\n const x = node.x - width / 2;\n const y = node.y - height / 2;\n node.width = width;\n const innerY = node.y - node.height / 2 - halfPadding + bbox.height + 2;\n let rect2;\n if (node.look === \"handDrawn\") {\n const isAlt = node.cssClasses.includes(\"statediagram-cluster-alt\");\n const rc = rough.svg(shapeSvg);\n const roughOuterNode = node.rx || node.ry ? rc.path(createRoundedRectPathD(x, y, width, height, 10), {\n roughness: 0.7,\n fill: compositeTitleBackground,\n fillStyle: \"solid\",\n stroke: nodeBorder,\n seed: handDrawnSeed\n }) : rc.rectangle(x, y, width, height, { seed: handDrawnSeed });\n rect2 = shapeSvg.insert(() => roughOuterNode, \":first-child\");\n const roughInnerNode = rc.rectangle(x, innerY, width, innerHeight, {\n fill: isAlt ? altBackground : compositeBackground,\n fillStyle: isAlt ? \"hachure\" : \"solid\",\n stroke: nodeBorder,\n seed: handDrawnSeed\n });\n rect2 = shapeSvg.insert(() => roughOuterNode, \":first-child\");\n innerRect = shapeSvg.insert(() => roughInnerNode);\n } else {\n rect2 = outerRectG.insert(\"rect\", \":first-child\");\n const outerRectClass = \"outer\";\n rect2.attr(\"class\", outerRectClass).attr(\"x\", x).attr(\"y\", y).attr(\"width\", width).attr(\"height\", height).attr(\"data-look\", node.look);\n innerRect.attr(\"class\", \"inner\").attr(\"x\", x).attr(\"y\", innerY).attr(\"width\", width).attr(\"height\", innerHeight);\n }\n label.attr(\n \"transform\",\n `translate(${node.x - bbox.width / 2}, ${y + 1 - (evaluate(siteConfig.flowchart.htmlLabels) ? 0 : 3)})`\n );\n const rectBox = rect2.node().getBBox();\n node.height = rectBox.height;\n node.offsetX = 0;\n node.offsetY = bbox.height - node.padding / 2;\n node.labelBBox = bbox;\n node.intersect = function(point) {\n return intersect_rect_default(node, point);\n };\n return { cluster: shapeSvg, labelBBox: bbox };\n}, \"roundedWithTitle\");\nvar kanbanSection = /* @__PURE__ */ __name(async (parent, node) => {\n log.info(\"Creating subgraph rect for \", node.id, node);\n const siteConfig = getConfig2();\n const { themeVariables, handDrawnSeed } = siteConfig;\n const { clusterBkg, clusterBorder } = themeVariables;\n const { labelStyles, nodeStyles, borderStyles, backgroundStyles } = styles2String(node);\n const shapeSvg = parent.insert(\"g\").attr(\"class\", \"cluster \" + node.cssClasses).attr(\"id\", node.id).attr(\"data-look\", node.look);\n const useHtmlLabels = evaluate(siteConfig.flowchart.htmlLabels);\n const labelEl = shapeSvg.insert(\"g\").attr(\"class\", \"cluster-label \");\n const text2 = await createText(labelEl, node.label, {\n style: node.labelStyle,\n useHtmlLabels,\n isNode: true,\n width: node.width\n });\n let bbox = text2.getBBox();\n if (evaluate(siteConfig.flowchart.htmlLabels)) {\n const div = text2.children[0];\n const dv = select3(text2);\n bbox = div.getBoundingClientRect();\n dv.attr(\"width\", bbox.width);\n dv.attr(\"height\", bbox.height);\n }\n const width = node.width <= bbox.width + node.padding ? bbox.width + node.padding : node.width;\n if (node.width <= bbox.width + node.padding) {\n node.diff = (width - node.width) / 2 - node.padding;\n } else {\n node.diff = -node.padding;\n }\n const height = node.height;\n const x = node.x - width / 2;\n const y = node.y - height / 2;\n log.trace(\"Data \", node, JSON.stringify(node));\n let rect2;\n if (node.look === \"handDrawn\") {\n const rc = rough.svg(shapeSvg);\n const options = userNodeOverrides(node, {\n roughness: 0.7,\n fill: clusterBkg,\n // fill: 'red',\n stroke: clusterBorder,\n fillWeight: 4,\n seed: handDrawnSeed\n });\n const roughNode = rc.path(createRoundedRectPathD(x, y, width, height, node.rx), options);\n rect2 = shapeSvg.insert(() => {\n log.debug(\"Rough node insert CXC\", roughNode);\n return roughNode;\n }, \":first-child\");\n rect2.select(\"path:nth-child(2)\").attr(\"style\", borderStyles.join(\";\"));\n rect2.select(\"path\").attr(\"style\", backgroundStyles.join(\";\").replace(\"fill\", \"stroke\"));\n } else {\n rect2 = shapeSvg.insert(\"rect\", \":first-child\");\n rect2.attr(\"style\", nodeStyles).attr(\"rx\", node.rx).attr(\"ry\", node.ry).attr(\"x\", x).attr(\"y\", y).attr(\"width\", width).attr(\"height\", height);\n }\n const { subGraphTitleTopMargin } = getSubGraphTitleMargins(siteConfig);\n labelEl.attr(\n \"transform\",\n // This puts the label on top of the box instead of inside it\n `translate(${node.x - bbox.width / 2}, ${node.y - node.height / 2 + subGraphTitleTopMargin})`\n );\n if (labelStyles) {\n const span = labelEl.select(\"span\");\n if (span) {\n span.attr(\"style\", labelStyles);\n }\n }\n const rectBox = rect2.node().getBBox();\n node.offsetX = 0;\n node.width = rectBox.width;\n node.height = rectBox.height;\n node.offsetY = bbox.height - node.padding / 2;\n node.intersect = function(point) {\n return intersect_rect_default(node, point);\n };\n return { cluster: shapeSvg, labelBBox: bbox };\n}, \"kanbanSection\");\nvar divider = /* @__PURE__ */ __name((parent, node) => {\n const siteConfig = getConfig2();\n const { themeVariables, handDrawnSeed } = siteConfig;\n const { nodeBorder } = themeVariables;\n const shapeSvg = parent.insert(\"g\").attr(\"class\", node.cssClasses).attr(\"id\", node.id).attr(\"data-look\", node.look);\n const outerRectG = shapeSvg.insert(\"g\", \":first-child\");\n const padding = 0 * node.padding;\n const width = node.width + padding;\n node.diff = -node.padding;\n const height = node.height + padding;\n const x = node.x - width / 2;\n const y = node.y - height / 2;\n node.width = width;\n let rect2;\n if (node.look === \"handDrawn\") {\n const rc = rough.svg(shapeSvg);\n const roughOuterNode = rc.rectangle(x, y, width, height, {\n fill: \"lightgrey\",\n roughness: 0.5,\n strokeLineDash: [5],\n stroke: nodeBorder,\n seed: handDrawnSeed\n });\n rect2 = shapeSvg.insert(() => roughOuterNode, \":first-child\");\n } else {\n rect2 = outerRectG.insert(\"rect\", \":first-child\");\n const outerRectClass = \"divider\";\n rect2.attr(\"class\", outerRectClass).attr(\"x\", x).attr(\"y\", y).attr(\"width\", width).attr(\"height\", height).attr(\"data-look\", node.look);\n }\n const rectBox = rect2.node().getBBox();\n node.height = rectBox.height;\n node.offsetX = 0;\n node.offsetY = 0;\n node.intersect = function(point) {\n return intersect_rect_default(node, point);\n };\n return { cluster: shapeSvg, labelBBox: {} };\n}, \"divider\");\nvar squareRect = rect;\nvar shapes = {\n rect,\n squareRect,\n roundedWithTitle,\n noteGroup,\n divider,\n kanbanSection\n};\nvar clusterElems = /* @__PURE__ */ new Map();\nvar insertCluster = /* @__PURE__ */ __name(async (elem, node) => {\n const shape = node.shape || \"rect\";\n const cluster = await shapes[shape](elem, node);\n clusterElems.set(node.id, cluster);\n return cluster;\n}, \"insertCluster\");\nvar clear = /* @__PURE__ */ __name(() => {\n clusterElems = /* @__PURE__ */ new Map();\n}, \"clear\");\n\n// src/rendering-util/rendering-elements/intersect/intersect-node.js\nfunction intersectNode(node, point) {\n return node.intersect(point);\n}\n__name(intersectNode, \"intersectNode\");\nvar intersect_node_default = intersectNode;\n\n// src/rendering-util/rendering-elements/intersect/intersect-ellipse.js\nfunction intersectEllipse(node, rx, ry, point) {\n var cx = node.x;\n var cy = node.y;\n var px = cx - point.x;\n var py = cy - point.y;\n var det = Math.sqrt(rx * rx * py * py + ry * ry * px * px);\n var dx = Math.abs(rx * ry * px / det);\n if (point.x < cx) {\n dx = -dx;\n }\n var dy = Math.abs(rx * ry * py / det);\n if (point.y < cy) {\n dy = -dy;\n }\n return { x: cx + dx, y: cy + dy };\n}\n__name(intersectEllipse, \"intersectEllipse\");\nvar intersect_ellipse_default = intersectEllipse;\n\n// src/rendering-util/rendering-elements/intersect/intersect-circle.js\nfunction intersectCircle(node, rx, point) {\n return intersect_ellipse_default(node, rx, rx, point);\n}\n__name(intersectCircle, \"intersectCircle\");\nvar intersect_circle_default = intersectCircle;\n\n// src/rendering-util/rendering-elements/intersect/intersect-line.js\nfunction intersectLine(p1, p2, q1, q2) {\n {\n const a1 = p2.y - p1.y;\n const b1 = p1.x - p2.x;\n const c1 = p2.x * p1.y - p1.x * p2.y;\n const r3 = a1 * q1.x + b1 * q1.y + c1;\n const r4 = a1 * q2.x + b1 * q2.y + c1;\n const epsilon = 1e-6;\n if (r3 !== 0 && r4 !== 0 && sameSign(r3, r4)) {\n return;\n }\n const a2 = q2.y - q1.y;\n const b2 = q1.x - q2.x;\n const c2 = q2.x * q1.y - q1.x * q2.y;\n const r1 = a2 * p1.x + b2 * p1.y + c2;\n const r2 = a2 * p2.x + b2 * p2.y + c2;\n if (Math.abs(r1) < epsilon && Math.abs(r2) < epsilon && sameSign(r1, r2)) {\n return;\n }\n const denom = a1 * b2 - a2 * b1;\n if (denom === 0) {\n return;\n }\n const offset = Math.abs(denom / 2);\n let num = b1 * c2 - b2 * c1;\n const x = num < 0 ? (num - offset) / denom : (num + offset) / denom;\n num = a2 * c1 - a1 * c2;\n const y = num < 0 ? (num - offset) / denom : (num + offset) / denom;\n return { x, y };\n }\n}\n__name(intersectLine, \"intersectLine\");\nfunction sameSign(r1, r2) {\n return r1 * r2 > 0;\n}\n__name(sameSign, \"sameSign\");\nvar intersect_line_default = intersectLine;\n\n// src/rendering-util/rendering-elements/intersect/intersect-polygon.js\nfunction intersectPolygon(node, polyPoints, point) {\n let x1 = node.x;\n let y1 = node.y;\n let intersections = [];\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n if (typeof polyPoints.forEach === \"function\") {\n polyPoints.forEach(function(entry) {\n minX = Math.min(minX, entry.x);\n minY = Math.min(minY, entry.y);\n });\n } else {\n minX = Math.min(minX, polyPoints.x);\n minY = Math.min(minY, polyPoints.y);\n }\n let left = x1 - node.width / 2 - minX;\n let top = y1 - node.height / 2 - minY;\n for (let i = 0; i < polyPoints.length; i++) {\n let p1 = polyPoints[i];\n let p2 = polyPoints[i < polyPoints.length - 1 ? i + 1 : 0];\n let intersect = intersect_line_default(\n node,\n point,\n { x: left + p1.x, y: top + p1.y },\n { x: left + p2.x, y: top + p2.y }\n );\n if (intersect) {\n intersections.push(intersect);\n }\n }\n if (!intersections.length) {\n return node;\n }\n if (intersections.length > 1) {\n intersections.sort(function(p, q) {\n let pdx = p.x - point.x;\n let pdy = p.y - point.y;\n let distp = Math.sqrt(pdx * pdx + pdy * pdy);\n let qdx = q.x - point.x;\n let qdy = q.y - point.y;\n let distq = Math.sqrt(qdx * qdx + qdy * qdy);\n return distp < distq ? -1 : distp === distq ? 0 : 1;\n });\n }\n return intersections[0];\n}\n__name(intersectPolygon, \"intersectPolygon\");\nvar intersect_polygon_default = intersectPolygon;\n\n// src/rendering-util/rendering-elements/intersect/index.js\nvar intersect_default = {\n node: intersect_node_default,\n circle: intersect_circle_default,\n ellipse: intersect_ellipse_default,\n polygon: intersect_polygon_default,\n rect: intersect_rect_default\n};\n\n// src/rendering-util/rendering-elements/shapes/anchor.ts\nimport rough2 from \"roughjs\";\nfunction anchor(parent, node) {\n const { labelStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const classes = getNodeClasses(node);\n let cssClasses = classes;\n if (!classes) {\n cssClasses = \"anchor\";\n }\n const shapeSvg = parent.insert(\"g\").attr(\"class\", cssClasses).attr(\"id\", node.domId || node.id);\n const radius = 1;\n const { cssStyles } = node;\n const rc = rough2.svg(shapeSvg);\n const options = userNodeOverrides(node, { fill: \"black\", stroke: \"none\", fillStyle: \"solid\" });\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n }\n const roughNode = rc.circle(0, 0, radius * 2, options);\n const circleElem = shapeSvg.insert(() => roughNode, \":first-child\");\n circleElem.attr(\"class\", \"anchor\").attr(\"style\", handleUndefinedAttr(cssStyles));\n updateNodeBounds(node, circleElem);\n node.intersect = function(point) {\n log.info(\"Circle intersect\", node, radius, point);\n return intersect_default.circle(node, radius, point);\n };\n return shapeSvg;\n}\n__name(anchor, \"anchor\");\n\n// src/rendering-util/rendering-elements/shapes/bowTieRect.ts\nimport rough3 from \"roughjs\";\nfunction generateArcPoints(x1, y1, x2, y2, rx, ry, clockwise) {\n const numPoints = 20;\n const midX = (x1 + x2) / 2;\n const midY = (y1 + y2) / 2;\n const angle = Math.atan2(y2 - y1, x2 - x1);\n const dx = (x2 - x1) / 2;\n const dy = (y2 - y1) / 2;\n const transformedX = dx / rx;\n const transformedY = dy / ry;\n const distance = Math.sqrt(transformedX ** 2 + transformedY ** 2);\n if (distance > 1) {\n throw new Error(\"The given radii are too small to create an arc between the points.\");\n }\n const scaledCenterDistance = Math.sqrt(1 - distance ** 2);\n const centerX = midX + scaledCenterDistance * ry * Math.sin(angle) * (clockwise ? -1 : 1);\n const centerY = midY - scaledCenterDistance * rx * Math.cos(angle) * (clockwise ? -1 : 1);\n const startAngle = Math.atan2((y1 - centerY) / ry, (x1 - centerX) / rx);\n const endAngle = Math.atan2((y2 - centerY) / ry, (x2 - centerX) / rx);\n let angleRange = endAngle - startAngle;\n if (clockwise && angleRange < 0) {\n angleRange += 2 * Math.PI;\n }\n if (!clockwise && angleRange > 0) {\n angleRange -= 2 * Math.PI;\n }\n const points = [];\n for (let i = 0; i < numPoints; i++) {\n const t = i / (numPoints - 1);\n const angle2 = startAngle + t * angleRange;\n const x = centerX + rx * Math.cos(angle2);\n const y = centerY + ry * Math.sin(angle2);\n points.push({ x, y });\n }\n return points;\n}\n__name(generateArcPoints, \"generateArcPoints\");\nasync function bowTieRect(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const w = bbox.width + node.padding + 20;\n const h = bbox.height + node.padding;\n const ry = h / 2;\n const rx = ry / (2.5 + h / 50);\n const { cssStyles } = node;\n const points = [\n { x: w / 2, y: -h / 2 },\n { x: -w / 2, y: -h / 2 },\n ...generateArcPoints(-w / 2, -h / 2, -w / 2, h / 2, rx, ry, false),\n { x: w / 2, y: h / 2 },\n ...generateArcPoints(w / 2, h / 2, w / 2, -h / 2, rx, ry, true)\n ];\n const rc = rough3.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const bowTieRectPath = createPathFromPoints(points);\n const bowTieRectShapePath = rc.path(bowTieRectPath, options);\n const bowTieRectShape = shapeSvg.insert(() => bowTieRectShapePath, \":first-child\");\n bowTieRectShape.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n bowTieRectShape.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n bowTieRectShape.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n bowTieRectShape.attr(\"transform\", `translate(${rx / 2}, 0)`);\n updateNodeBounds(node, bowTieRectShape);\n node.intersect = function(point) {\n const pos = intersect_default.polygon(node, points, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(bowTieRect, \"bowTieRect\");\n\n// src/rendering-util/rendering-elements/shapes/card.ts\nimport rough4 from \"roughjs\";\n\n// src/rendering-util/rendering-elements/shapes/insertPolygonShape.ts\nfunction insertPolygonShape(parent, w, h, points) {\n return parent.insert(\"polygon\", \":first-child\").attr(\n \"points\",\n points.map(function(d) {\n return d.x + \",\" + d.y;\n }).join(\" \")\n ).attr(\"class\", \"label-container\").attr(\"transform\", \"translate(\" + -w / 2 + \",\" + h / 2 + \")\");\n}\n__name(insertPolygonShape, \"insertPolygonShape\");\n\n// src/rendering-util/rendering-elements/shapes/card.ts\nasync function card(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const h = bbox.height + node.padding;\n const padding = 12;\n const w = bbox.width + node.padding + padding;\n const left = 0;\n const right = w;\n const top = -h;\n const bottom = 0;\n const points = [\n { x: left + padding, y: top },\n { x: right, y: top },\n { x: right, y: bottom },\n { x: left, y: bottom },\n { x: left, y: top + padding },\n { x: left + padding, y: top }\n ];\n let polygon;\n const { cssStyles } = node;\n if (node.look === \"handDrawn\") {\n const rc = rough4.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n const pathData = createPathFromPoints(points);\n const roughNode = rc.path(pathData, options);\n polygon = shapeSvg.insert(() => roughNode, \":first-child\").attr(\"transform\", `translate(${-w / 2}, ${h / 2})`);\n if (cssStyles) {\n polygon.attr(\"style\", cssStyles);\n }\n } else {\n polygon = insertPolygonShape(shapeSvg, w, h, points);\n }\n if (nodeStyles) {\n polygon.attr(\"style\", nodeStyles);\n }\n updateNodeBounds(node, polygon);\n node.intersect = function(point) {\n return intersect_default.polygon(node, points, point);\n };\n return shapeSvg;\n}\n__name(card, \"card\");\n\n// src/rendering-util/rendering-elements/shapes/choice.ts\nimport rough5 from \"roughjs\";\nfunction choice(parent, node) {\n const { nodeStyles } = styles2String(node);\n node.label = \"\";\n const shapeSvg = parent.insert(\"g\").attr(\"class\", getNodeClasses(node)).attr(\"id\", node.domId ?? node.id);\n const { cssStyles } = node;\n const s = Math.max(28, node.width ?? 0);\n const points = [\n { x: 0, y: s / 2 },\n { x: s / 2, y: 0 },\n { x: 0, y: -s / 2 },\n { x: -s / 2, y: 0 }\n ];\n const rc = rough5.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const choicePath = createPathFromPoints(points);\n const roughNode = rc.path(choicePath, options);\n const choiceShape = shapeSvg.insert(() => roughNode, \":first-child\");\n if (cssStyles && node.look !== \"handDrawn\") {\n choiceShape.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n choiceShape.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n node.width = 28;\n node.height = 28;\n node.intersect = function(point) {\n return intersect_default.polygon(node, points, point);\n };\n return shapeSvg;\n}\n__name(choice, \"choice\");\n\n// src/rendering-util/rendering-elements/shapes/circle.ts\nimport rough6 from \"roughjs\";\nasync function circle(parent, node, options) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, halfPadding } = await labelHelper(parent, node, getNodeClasses(node));\n const padding = options?.padding ?? halfPadding;\n const radius = bbox.width / 2 + padding;\n let circleElem;\n const { cssStyles } = node;\n if (node.look === \"handDrawn\") {\n const rc = rough6.svg(shapeSvg);\n const options2 = userNodeOverrides(node, {});\n const roughNode = rc.circle(0, 0, radius * 2, options2);\n circleElem = shapeSvg.insert(() => roughNode, \":first-child\");\n circleElem.attr(\"class\", \"basic label-container\").attr(\"style\", handleUndefinedAttr(cssStyles));\n } else {\n circleElem = shapeSvg.insert(\"circle\", \":first-child\").attr(\"class\", \"basic label-container\").attr(\"style\", nodeStyles).attr(\"r\", radius).attr(\"cx\", 0).attr(\"cy\", 0);\n }\n updateNodeBounds(node, circleElem);\n node.calcIntersect = function(bounds, point) {\n const radius2 = bounds.width / 2;\n return intersect_default.circle(bounds, radius2, point);\n };\n node.intersect = function(point) {\n log.info(\"Circle intersect\", node, radius, point);\n return intersect_default.circle(node, radius, point);\n };\n return shapeSvg;\n}\n__name(circle, \"circle\");\n\n// src/rendering-util/rendering-elements/shapes/crossedCircle.ts\nimport rough7 from \"roughjs\";\nfunction createLine(r) {\n const xAxis45 = Math.cos(Math.PI / 4);\n const yAxis45 = Math.sin(Math.PI / 4);\n const lineLength = r * 2;\n const pointQ1 = { x: lineLength / 2 * xAxis45, y: lineLength / 2 * yAxis45 };\n const pointQ2 = { x: -(lineLength / 2) * xAxis45, y: lineLength / 2 * yAxis45 };\n const pointQ3 = { x: -(lineLength / 2) * xAxis45, y: -(lineLength / 2) * yAxis45 };\n const pointQ4 = { x: lineLength / 2 * xAxis45, y: -(lineLength / 2) * yAxis45 };\n return `M ${pointQ2.x},${pointQ2.y} L ${pointQ4.x},${pointQ4.y}\n M ${pointQ1.x},${pointQ1.y} L ${pointQ3.x},${pointQ3.y}`;\n}\n__name(createLine, \"createLine\");\nfunction crossedCircle(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n node.label = \"\";\n const shapeSvg = parent.insert(\"g\").attr(\"class\", getNodeClasses(node)).attr(\"id\", node.domId ?? node.id);\n const radius = Math.max(30, node?.width ?? 0);\n const { cssStyles } = node;\n const rc = rough7.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const circleNode = rc.circle(0, 0, radius * 2, options);\n const linePath = createLine(radius);\n const lineNode = rc.path(linePath, options);\n const crossedCircle2 = shapeSvg.insert(() => circleNode, \":first-child\");\n crossedCircle2.insert(() => lineNode);\n if (cssStyles && node.look !== \"handDrawn\") {\n crossedCircle2.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n crossedCircle2.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n updateNodeBounds(node, crossedCircle2);\n node.intersect = function(point) {\n log.info(\"crossedCircle intersect\", node, { radius, point });\n const pos = intersect_default.circle(node, radius, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(crossedCircle, \"crossedCircle\");\n\n// src/rendering-util/rendering-elements/shapes/curlyBraceLeft.ts\nimport rough8 from \"roughjs\";\nfunction generateCirclePoints2(centerX, centerY, radius, numPoints = 100, startAngle = 0, endAngle = 180) {\n const points = [];\n const startAngleRad = startAngle * Math.PI / 180;\n const endAngleRad = endAngle * Math.PI / 180;\n const angleRange = endAngleRad - startAngleRad;\n const angleStep = angleRange / (numPoints - 1);\n for (let i = 0; i < numPoints; i++) {\n const angle = startAngleRad + i * angleStep;\n const x = centerX + radius * Math.cos(angle);\n const y = centerY + radius * Math.sin(angle);\n points.push({ x: -x, y: -y });\n }\n return points;\n}\n__name(generateCirclePoints2, \"generateCirclePoints\");\nasync function curlyBraceLeft(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const w = bbox.width + (node.padding ?? 0);\n const h = bbox.height + (node.padding ?? 0);\n const radius = Math.max(5, h * 0.1);\n const { cssStyles } = node;\n const points = [\n ...generateCirclePoints2(w / 2, -h / 2, radius, 30, -90, 0),\n { x: -w / 2 - radius, y: radius },\n ...generateCirclePoints2(w / 2 + radius * 2, -radius, radius, 20, -180, -270),\n ...generateCirclePoints2(w / 2 + radius * 2, radius, radius, 20, -90, -180),\n { x: -w / 2 - radius, y: -h / 2 },\n ...generateCirclePoints2(w / 2, h / 2, radius, 20, 0, 90)\n ];\n const rectPoints = [\n { x: w / 2, y: -h / 2 - radius },\n { x: -w / 2, y: -h / 2 - radius },\n ...generateCirclePoints2(w / 2, -h / 2, radius, 20, -90, 0),\n { x: -w / 2 - radius, y: -radius },\n ...generateCirclePoints2(w / 2 + w * 0.1, -radius, radius, 20, -180, -270),\n ...generateCirclePoints2(w / 2 + w * 0.1, radius, radius, 20, -90, -180),\n { x: -w / 2 - radius, y: h / 2 },\n ...generateCirclePoints2(w / 2, h / 2, radius, 20, 0, 90),\n { x: -w / 2, y: h / 2 + radius },\n { x: w / 2, y: h / 2 + radius }\n ];\n const rc = rough8.svg(shapeSvg);\n const options = userNodeOverrides(node, { fill: \"none\" });\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const curlyBraceLeftPath = createPathFromPoints(points);\n const newCurlyBracePath = curlyBraceLeftPath.replace(\"Z\", \"\");\n const curlyBraceLeftNode = rc.path(newCurlyBracePath, options);\n const rectPath = createPathFromPoints(rectPoints);\n const rectShape = rc.path(rectPath, { ...options });\n const curlyBraceLeftShape = shapeSvg.insert(\"g\", \":first-child\");\n curlyBraceLeftShape.insert(() => rectShape, \":first-child\").attr(\"stroke-opacity\", 0);\n curlyBraceLeftShape.insert(() => curlyBraceLeftNode, \":first-child\");\n curlyBraceLeftShape.attr(\"class\", \"text\");\n if (cssStyles && node.look !== \"handDrawn\") {\n curlyBraceLeftShape.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n curlyBraceLeftShape.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n curlyBraceLeftShape.attr(\"transform\", `translate(${radius}, 0)`);\n label.attr(\n \"transform\",\n `translate(${-w / 2 + radius - (bbox.x - (bbox.left ?? 0))},${-h / 2 + (node.padding ?? 0) / 2 - (bbox.y - (bbox.top ?? 0))})`\n );\n updateNodeBounds(node, curlyBraceLeftShape);\n node.intersect = function(point) {\n const pos = intersect_default.polygon(node, rectPoints, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(curlyBraceLeft, \"curlyBraceLeft\");\n\n// src/rendering-util/rendering-elements/shapes/curlyBraceRight.ts\nimport rough9 from \"roughjs\";\nfunction generateCirclePoints3(centerX, centerY, radius, numPoints = 100, startAngle = 0, endAngle = 180) {\n const points = [];\n const startAngleRad = startAngle * Math.PI / 180;\n const endAngleRad = endAngle * Math.PI / 180;\n const angleRange = endAngleRad - startAngleRad;\n const angleStep = angleRange / (numPoints - 1);\n for (let i = 0; i < numPoints; i++) {\n const angle = startAngleRad + i * angleStep;\n const x = centerX + radius * Math.cos(angle);\n const y = centerY + radius * Math.sin(angle);\n points.push({ x, y });\n }\n return points;\n}\n__name(generateCirclePoints3, \"generateCirclePoints\");\nasync function curlyBraceRight(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const w = bbox.width + (node.padding ?? 0);\n const h = bbox.height + (node.padding ?? 0);\n const radius = Math.max(5, h * 0.1);\n const { cssStyles } = node;\n const points = [\n ...generateCirclePoints3(w / 2, -h / 2, radius, 20, -90, 0),\n { x: w / 2 + radius, y: -radius },\n ...generateCirclePoints3(w / 2 + radius * 2, -radius, radius, 20, -180, -270),\n ...generateCirclePoints3(w / 2 + radius * 2, radius, radius, 20, -90, -180),\n { x: w / 2 + radius, y: h / 2 },\n ...generateCirclePoints3(w / 2, h / 2, radius, 20, 0, 90)\n ];\n const rectPoints = [\n { x: -w / 2, y: -h / 2 - radius },\n { x: w / 2, y: -h / 2 - radius },\n ...generateCirclePoints3(w / 2, -h / 2, radius, 20, -90, 0),\n { x: w / 2 + radius, y: -radius },\n ...generateCirclePoints3(w / 2 + radius * 2, -radius, radius, 20, -180, -270),\n ...generateCirclePoints3(w / 2 + radius * 2, radius, radius, 20, -90, -180),\n { x: w / 2 + radius, y: h / 2 },\n ...generateCirclePoints3(w / 2, h / 2, radius, 20, 0, 90),\n { x: w / 2, y: h / 2 + radius },\n { x: -w / 2, y: h / 2 + radius }\n ];\n const rc = rough9.svg(shapeSvg);\n const options = userNodeOverrides(node, { fill: \"none\" });\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const curlyBraceRightPath = createPathFromPoints(points);\n const newCurlyBracePath = curlyBraceRightPath.replace(\"Z\", \"\");\n const curlyBraceRightNode = rc.path(newCurlyBracePath, options);\n const rectPath = createPathFromPoints(rectPoints);\n const rectShape = rc.path(rectPath, { ...options });\n const curlyBraceRightShape = shapeSvg.insert(\"g\", \":first-child\");\n curlyBraceRightShape.insert(() => rectShape, \":first-child\").attr(\"stroke-opacity\", 0);\n curlyBraceRightShape.insert(() => curlyBraceRightNode, \":first-child\");\n curlyBraceRightShape.attr(\"class\", \"text\");\n if (cssStyles && node.look !== \"handDrawn\") {\n curlyBraceRightShape.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n curlyBraceRightShape.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n curlyBraceRightShape.attr(\"transform\", `translate(${-radius}, 0)`);\n label.attr(\n \"transform\",\n `translate(${-w / 2 + (node.padding ?? 0) / 2 - (bbox.x - (bbox.left ?? 0))},${-h / 2 + (node.padding ?? 0) / 2 - (bbox.y - (bbox.top ?? 0))})`\n );\n updateNodeBounds(node, curlyBraceRightShape);\n node.intersect = function(point) {\n const pos = intersect_default.polygon(node, rectPoints, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(curlyBraceRight, \"curlyBraceRight\");\n\n// src/rendering-util/rendering-elements/shapes/curlyBraces.ts\nimport rough10 from \"roughjs\";\nfunction generateCirclePoints4(centerX, centerY, radius, numPoints = 100, startAngle = 0, endAngle = 180) {\n const points = [];\n const startAngleRad = startAngle * Math.PI / 180;\n const endAngleRad = endAngle * Math.PI / 180;\n const angleRange = endAngleRad - startAngleRad;\n const angleStep = angleRange / (numPoints - 1);\n for (let i = 0; i < numPoints; i++) {\n const angle = startAngleRad + i * angleStep;\n const x = centerX + radius * Math.cos(angle);\n const y = centerY + radius * Math.sin(angle);\n points.push({ x: -x, y: -y });\n }\n return points;\n}\n__name(generateCirclePoints4, \"generateCirclePoints\");\nasync function curlyBraces(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const w = bbox.width + (node.padding ?? 0);\n const h = bbox.height + (node.padding ?? 0);\n const radius = Math.max(5, h * 0.1);\n const { cssStyles } = node;\n const leftCurlyBracePoints = [\n ...generateCirclePoints4(w / 2, -h / 2, radius, 30, -90, 0),\n { x: -w / 2 - radius, y: radius },\n ...generateCirclePoints4(w / 2 + radius * 2, -radius, radius, 20, -180, -270),\n ...generateCirclePoints4(w / 2 + radius * 2, radius, radius, 20, -90, -180),\n { x: -w / 2 - radius, y: -h / 2 },\n ...generateCirclePoints4(w / 2, h / 2, radius, 20, 0, 90)\n ];\n const rightCurlyBracePoints = [\n ...generateCirclePoints4(-w / 2 + radius + radius / 2, -h / 2, radius, 20, -90, -180),\n { x: w / 2 - radius / 2, y: radius },\n ...generateCirclePoints4(-w / 2 - radius / 2, -radius, radius, 20, 0, 90),\n ...generateCirclePoints4(-w / 2 - radius / 2, radius, radius, 20, -90, 0),\n { x: w / 2 - radius / 2, y: -radius },\n ...generateCirclePoints4(-w / 2 + radius + radius / 2, h / 2, radius, 30, -180, -270)\n ];\n const rectPoints = [\n { x: w / 2, y: -h / 2 - radius },\n { x: -w / 2, y: -h / 2 - radius },\n ...generateCirclePoints4(w / 2, -h / 2, radius, 20, -90, 0),\n { x: -w / 2 - radius, y: -radius },\n ...generateCirclePoints4(w / 2 + radius * 2, -radius, radius, 20, -180, -270),\n ...generateCirclePoints4(w / 2 + radius * 2, radius, radius, 20, -90, -180),\n { x: -w / 2 - radius, y: h / 2 },\n ...generateCirclePoints4(w / 2, h / 2, radius, 20, 0, 90),\n { x: -w / 2, y: h / 2 + radius },\n { x: w / 2 - radius - radius / 2, y: h / 2 + radius },\n ...generateCirclePoints4(-w / 2 + radius + radius / 2, -h / 2, radius, 20, -90, -180),\n { x: w / 2 - radius / 2, y: radius },\n ...generateCirclePoints4(-w / 2 - radius / 2, -radius, radius, 20, 0, 90),\n ...generateCirclePoints4(-w / 2 - radius / 2, radius, radius, 20, -90, 0),\n { x: w / 2 - radius / 2, y: -radius },\n ...generateCirclePoints4(-w / 2 + radius + radius / 2, h / 2, radius, 30, -180, -270)\n ];\n const rc = rough10.svg(shapeSvg);\n const options = userNodeOverrides(node, { fill: \"none\" });\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const leftCurlyBracePath = createPathFromPoints(leftCurlyBracePoints);\n const newLeftCurlyBracePath = leftCurlyBracePath.replace(\"Z\", \"\");\n const leftCurlyBraceNode = rc.path(newLeftCurlyBracePath, options);\n const rightCurlyBracePath = createPathFromPoints(rightCurlyBracePoints);\n const newRightCurlyBracePath = rightCurlyBracePath.replace(\"Z\", \"\");\n const rightCurlyBraceNode = rc.path(newRightCurlyBracePath, options);\n const rectPath = createPathFromPoints(rectPoints);\n const rectShape = rc.path(rectPath, { ...options });\n const curlyBracesShape = shapeSvg.insert(\"g\", \":first-child\");\n curlyBracesShape.insert(() => rectShape, \":first-child\").attr(\"stroke-opacity\", 0);\n curlyBracesShape.insert(() => leftCurlyBraceNode, \":first-child\");\n curlyBracesShape.insert(() => rightCurlyBraceNode, \":first-child\");\n curlyBracesShape.attr(\"class\", \"text\");\n if (cssStyles && node.look !== \"handDrawn\") {\n curlyBracesShape.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n curlyBracesShape.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n curlyBracesShape.attr(\"transform\", `translate(${radius - radius / 4}, 0)`);\n label.attr(\n \"transform\",\n `translate(${-w / 2 + (node.padding ?? 0) / 2 - (bbox.x - (bbox.left ?? 0))},${-h / 2 + (node.padding ?? 0) / 2 - (bbox.y - (bbox.top ?? 0))})`\n );\n updateNodeBounds(node, curlyBracesShape);\n node.intersect = function(point) {\n const pos = intersect_default.polygon(node, rectPoints, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(curlyBraces, \"curlyBraces\");\n\n// src/rendering-util/rendering-elements/shapes/curvedTrapezoid.ts\nimport rough11 from \"roughjs\";\nasync function curvedTrapezoid(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const minWidth = 80, minHeight = 20;\n const w = Math.max(minWidth, (bbox.width + (node.padding ?? 0) * 2) * 1.25, node?.width ?? 0);\n const h = Math.max(minHeight, bbox.height + (node.padding ?? 0) * 2, node?.height ?? 0);\n const radius = h / 2;\n const { cssStyles } = node;\n const rc = rough11.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const totalWidth = w, totalHeight = h;\n const rw = totalWidth - radius;\n const tw = totalHeight / 4;\n const points = [\n { x: rw, y: 0 },\n { x: tw, y: 0 },\n { x: 0, y: totalHeight / 2 },\n { x: tw, y: totalHeight },\n { x: rw, y: totalHeight },\n ...generateCirclePoints(-rw, -totalHeight / 2, radius, 50, 270, 90)\n ];\n const pathData = createPathFromPoints(points);\n const shapeNode = rc.path(pathData, options);\n const polygon = shapeSvg.insert(() => shapeNode, \":first-child\");\n polygon.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", nodeStyles);\n }\n polygon.attr(\"transform\", `translate(${-w / 2}, ${-h / 2})`);\n updateNodeBounds(node, polygon);\n node.intersect = function(point) {\n const pos = intersect_default.polygon(node, points, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(curvedTrapezoid, \"curvedTrapezoid\");\n\n// src/rendering-util/rendering-elements/shapes/cylinder.ts\nimport rough12 from \"roughjs\";\nvar createCylinderPathD = /* @__PURE__ */ __name((x, y, width, height, rx, ry) => {\n return [\n `M${x},${y + ry}`,\n `a${rx},${ry} 0,0,0 ${width},0`,\n `a${rx},${ry} 0,0,0 ${-width},0`,\n `l0,${height}`,\n `a${rx},${ry} 0,0,0 ${width},0`,\n `l0,${-height}`\n ].join(\" \");\n}, \"createCylinderPathD\");\nvar createOuterCylinderPathD = /* @__PURE__ */ __name((x, y, width, height, rx, ry) => {\n return [\n `M${x},${y + ry}`,\n `M${x + width},${y + ry}`,\n `a${rx},${ry} 0,0,0 ${-width},0`,\n `l0,${height}`,\n `a${rx},${ry} 0,0,0 ${width},0`,\n `l0,${-height}`\n ].join(\" \");\n}, \"createOuterCylinderPathD\");\nvar createInnerCylinderPathD = /* @__PURE__ */ __name((x, y, width, height, rx, ry) => {\n return [`M${x - width / 2},${-height / 2}`, `a${rx},${ry} 0,0,0 ${width},0`].join(\" \");\n}, \"createInnerCylinderPathD\");\nasync function cylinder(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const w = Math.max(bbox.width + node.padding, node.width ?? 0);\n const rx = w / 2;\n const ry = rx / (2.5 + w / 50);\n const h = Math.max(bbox.height + ry + node.padding, node.height ?? 0);\n let cylinder2;\n const { cssStyles } = node;\n if (node.look === \"handDrawn\") {\n const rc = rough12.svg(shapeSvg);\n const outerPathData = createOuterCylinderPathD(0, 0, w, h, rx, ry);\n const innerPathData = createInnerCylinderPathD(0, ry, w, h, rx, ry);\n const outerNode = rc.path(outerPathData, userNodeOverrides(node, {}));\n const innerLine = rc.path(innerPathData, userNodeOverrides(node, { fill: \"none\" }));\n cylinder2 = shapeSvg.insert(() => innerLine, \":first-child\");\n cylinder2 = shapeSvg.insert(() => outerNode, \":first-child\");\n cylinder2.attr(\"class\", \"basic label-container\");\n if (cssStyles) {\n cylinder2.attr(\"style\", cssStyles);\n }\n } else {\n const pathData = createCylinderPathD(0, 0, w, h, rx, ry);\n cylinder2 = shapeSvg.insert(\"path\", \":first-child\").attr(\"d\", pathData).attr(\"class\", \"basic label-container\").attr(\"style\", handleUndefinedAttr(cssStyles)).attr(\"style\", nodeStyles);\n }\n cylinder2.attr(\"label-offset-y\", ry);\n cylinder2.attr(\"transform\", `translate(${-w / 2}, ${-(h / 2 + ry)})`);\n updateNodeBounds(node, cylinder2);\n label.attr(\n \"transform\",\n `translate(${-(bbox.width / 2) - (bbox.x - (bbox.left ?? 0))}, ${-(bbox.height / 2) + (node.padding ?? 0) / 1.5 - (bbox.y - (bbox.top ?? 0))})`\n );\n node.intersect = function(point) {\n const pos = intersect_default.rect(node, point);\n const x = pos.x - (node.x ?? 0);\n if (rx != 0 && (Math.abs(x) < (node.width ?? 0) / 2 || Math.abs(x) == (node.width ?? 0) / 2 && Math.abs(pos.y - (node.y ?? 0)) > (node.height ?? 0) / 2 - ry)) {\n let y = ry * ry * (1 - x * x / (rx * rx));\n if (y > 0) {\n y = Math.sqrt(y);\n }\n y = ry - y;\n if (point.y - (node.y ?? 0) > 0) {\n y = -y;\n }\n pos.y += y;\n }\n return pos;\n };\n return shapeSvg;\n}\n__name(cylinder, \"cylinder\");\n\n// src/rendering-util/rendering-elements/shapes/dividedRect.ts\nimport rough13 from \"roughjs\";\nasync function dividedRectangle(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const w = bbox.width + node.padding;\n const h = bbox.height + node.padding;\n const rectOffset = h * 0.2;\n const x = -w / 2;\n const y = -h / 2 - rectOffset / 2;\n const { cssStyles } = node;\n const rc = rough13.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const pts = [\n { x, y: y + rectOffset },\n { x: -x, y: y + rectOffset },\n { x: -x, y: -y },\n { x, y: -y },\n { x, y },\n { x: -x, y },\n { x: -x, y: y + rectOffset }\n ];\n const poly = rc.polygon(\n pts.map((p) => [p.x, p.y]),\n options\n );\n const polygon = shapeSvg.insert(() => poly, \":first-child\");\n polygon.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n polygon.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n polygon.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n label.attr(\n \"transform\",\n `translate(${x + (node.padding ?? 0) / 2 - (bbox.x - (bbox.left ?? 0))}, ${y + rectOffset + (node.padding ?? 0) / 2 - (bbox.y - (bbox.top ?? 0))})`\n );\n updateNodeBounds(node, polygon);\n node.intersect = function(point) {\n const pos = intersect_default.rect(node, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(dividedRectangle, \"dividedRectangle\");\n\n// src/rendering-util/rendering-elements/shapes/doubleCircle.ts\nimport rough14 from \"roughjs\";\nasync function doublecircle(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, halfPadding } = await labelHelper(parent, node, getNodeClasses(node));\n const gap = 5;\n const outerRadius = bbox.width / 2 + halfPadding + gap;\n const innerRadius = bbox.width / 2 + halfPadding;\n let circleGroup;\n const { cssStyles } = node;\n if (node.look === \"handDrawn\") {\n const rc = rough14.svg(shapeSvg);\n const outerOptions = userNodeOverrides(node, { roughness: 0.2, strokeWidth: 2.5 });\n const innerOptions = userNodeOverrides(node, { roughness: 0.2, strokeWidth: 1.5 });\n const outerRoughNode = rc.circle(0, 0, outerRadius * 2, outerOptions);\n const innerRoughNode = rc.circle(0, 0, innerRadius * 2, innerOptions);\n circleGroup = shapeSvg.insert(\"g\", \":first-child\");\n circleGroup.attr(\"class\", handleUndefinedAttr(node.cssClasses)).attr(\"style\", handleUndefinedAttr(cssStyles));\n circleGroup.node()?.appendChild(outerRoughNode);\n circleGroup.node()?.appendChild(innerRoughNode);\n } else {\n circleGroup = shapeSvg.insert(\"g\", \":first-child\");\n const outerCircle = circleGroup.insert(\"circle\", \":first-child\");\n const innerCircle = circleGroup.insert(\"circle\");\n circleGroup.attr(\"class\", \"basic label-container\").attr(\"style\", nodeStyles);\n outerCircle.attr(\"class\", \"outer-circle\").attr(\"style\", nodeStyles).attr(\"r\", outerRadius).attr(\"cx\", 0).attr(\"cy\", 0);\n innerCircle.attr(\"class\", \"inner-circle\").attr(\"style\", nodeStyles).attr(\"r\", innerRadius).attr(\"cx\", 0).attr(\"cy\", 0);\n }\n updateNodeBounds(node, circleGroup);\n node.intersect = function(point) {\n log.info(\"DoubleCircle intersect\", node, outerRadius, point);\n return intersect_default.circle(node, outerRadius, point);\n };\n return shapeSvg;\n}\n__name(doublecircle, \"doublecircle\");\n\n// src/rendering-util/rendering-elements/shapes/filledCircle.ts\nimport rough15 from \"roughjs\";\nfunction filledCircle(parent, node, { config: { themeVariables } }) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.label = \"\";\n node.labelStyle = labelStyles;\n const shapeSvg = parent.insert(\"g\").attr(\"class\", getNodeClasses(node)).attr(\"id\", node.domId ?? node.id);\n const radius = 7;\n const { cssStyles } = node;\n const rc = rough15.svg(shapeSvg);\n const { nodeBorder } = themeVariables;\n const options = userNodeOverrides(node, { fillStyle: \"solid\" });\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n }\n const circleNode = rc.circle(0, 0, radius * 2, options);\n const filledCircle2 = shapeSvg.insert(() => circleNode, \":first-child\");\n filledCircle2.selectAll(\"path\").attr(\"style\", `fill: ${nodeBorder} !important;`);\n if (cssStyles && cssStyles.length > 0 && node.look !== \"handDrawn\") {\n filledCircle2.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n filledCircle2.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n updateNodeBounds(node, filledCircle2);\n node.intersect = function(point) {\n log.info(\"filledCircle intersect\", node, { radius, point });\n const pos = intersect_default.circle(node, radius, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(filledCircle, \"filledCircle\");\n\n// src/rendering-util/rendering-elements/shapes/flippedTriangle.ts\nimport rough16 from \"roughjs\";\nasync function flippedTriangle(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const w = bbox.width + (node.padding ?? 0);\n const h = w + bbox.height;\n const tw = w + bbox.height;\n const points = [\n { x: 0, y: -h },\n { x: tw, y: -h },\n { x: tw / 2, y: 0 }\n ];\n const { cssStyles } = node;\n const rc = rough16.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const pathData = createPathFromPoints(points);\n const roughNode = rc.path(pathData, options);\n const flippedTriangle2 = shapeSvg.insert(() => roughNode, \":first-child\").attr(\"transform\", `translate(${-h / 2}, ${h / 2})`);\n if (cssStyles && node.look !== \"handDrawn\") {\n flippedTriangle2.selectChildren(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n flippedTriangle2.selectChildren(\"path\").attr(\"style\", nodeStyles);\n }\n node.width = w;\n node.height = h;\n updateNodeBounds(node, flippedTriangle2);\n label.attr(\n \"transform\",\n `translate(${-bbox.width / 2 - (bbox.x - (bbox.left ?? 0))}, ${-h / 2 + (node.padding ?? 0) / 2 + (bbox.y - (bbox.top ?? 0))})`\n );\n node.intersect = function(point) {\n log.info(\"Triangle intersect\", node, points, point);\n return intersect_default.polygon(node, points, point);\n };\n return shapeSvg;\n}\n__name(flippedTriangle, \"flippedTriangle\");\n\n// src/rendering-util/rendering-elements/shapes/forkJoin.ts\nimport rough17 from \"roughjs\";\nfunction forkJoin(parent, node, { dir, config: { state: state2, themeVariables } }) {\n const { nodeStyles } = styles2String(node);\n node.label = \"\";\n const shapeSvg = parent.insert(\"g\").attr(\"class\", getNodeClasses(node)).attr(\"id\", node.domId ?? node.id);\n const { cssStyles } = node;\n let width = Math.max(70, node?.width ?? 0);\n let height = Math.max(10, node?.height ?? 0);\n if (dir === \"LR\") {\n width = Math.max(10, node?.width ?? 0);\n height = Math.max(70, node?.height ?? 0);\n }\n const x = -1 * width / 2;\n const y = -1 * height / 2;\n const rc = rough17.svg(shapeSvg);\n const options = userNodeOverrides(node, {\n stroke: themeVariables.lineColor,\n fill: themeVariables.lineColor\n });\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const roughNode = rc.rectangle(x, y, width, height, options);\n const shape = shapeSvg.insert(() => roughNode, \":first-child\");\n if (cssStyles && node.look !== \"handDrawn\") {\n shape.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n shape.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n updateNodeBounds(node, shape);\n const padding = state2?.padding ?? 0;\n if (node.width && node.height) {\n node.width += padding / 2 || 0;\n node.height += padding / 2 || 0;\n }\n node.intersect = function(point) {\n return intersect_default.rect(node, point);\n };\n return shapeSvg;\n}\n__name(forkJoin, \"forkJoin\");\n\n// src/rendering-util/rendering-elements/shapes/halfRoundedRectangle.ts\nimport rough18 from \"roughjs\";\nasync function halfRoundedRectangle(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const minWidth = 80, minHeight = 50;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const w = Math.max(minWidth, bbox.width + (node.padding ?? 0) * 2, node?.width ?? 0);\n const h = Math.max(minHeight, bbox.height + (node.padding ?? 0) * 2, node?.height ?? 0);\n const radius = h / 2;\n const { cssStyles } = node;\n const rc = rough18.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const points = [\n { x: -w / 2, y: -h / 2 },\n { x: w / 2 - radius, y: -h / 2 },\n ...generateCirclePoints(-w / 2 + radius, 0, radius, 50, 90, 270),\n { x: w / 2 - radius, y: h / 2 },\n { x: -w / 2, y: h / 2 }\n ];\n const pathData = createPathFromPoints(points);\n const shapeNode = rc.path(pathData, options);\n const polygon = shapeSvg.insert(() => shapeNode, \":first-child\");\n polygon.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", nodeStyles);\n }\n updateNodeBounds(node, polygon);\n node.intersect = function(point) {\n log.info(\"Pill intersect\", node, { radius, point });\n const pos = intersect_default.polygon(node, points, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(halfRoundedRectangle, \"halfRoundedRectangle\");\n\n// src/rendering-util/rendering-elements/shapes/hexagon.ts\nimport rough19 from \"roughjs\";\nasync function hexagon(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const h = bbox.height + (node.padding ?? 0);\n const w = bbox.width + (node.padding ?? 0) * 2.5;\n const { cssStyles } = node;\n const rc = rough19.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n let halfWidth = w / 2;\n const m = halfWidth / 6;\n halfWidth = halfWidth + m;\n const halfHeight = h / 2;\n const fixedLength = halfHeight / 2;\n const deducedWidth = halfWidth - fixedLength;\n const points = [\n { x: -deducedWidth, y: -halfHeight },\n { x: 0, y: -halfHeight },\n { x: deducedWidth, y: -halfHeight },\n { x: halfWidth, y: 0 },\n { x: deducedWidth, y: halfHeight },\n { x: 0, y: halfHeight },\n { x: -deducedWidth, y: halfHeight },\n { x: -halfWidth, y: 0 }\n ];\n const pathData = createPathFromPoints(points);\n const shapeNode = rc.path(pathData, options);\n const polygon = shapeSvg.insert(() => shapeNode, \":first-child\");\n polygon.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", nodeStyles);\n }\n node.width = w;\n node.height = h;\n updateNodeBounds(node, polygon);\n node.intersect = function(point) {\n return intersect_default.polygon(node, points, point);\n };\n return shapeSvg;\n}\n__name(hexagon, \"hexagon\");\n\n// src/rendering-util/rendering-elements/shapes/hourglass.ts\nimport rough20 from \"roughjs\";\nasync function hourglass(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.label = \"\";\n node.labelStyle = labelStyles;\n const { shapeSvg } = await labelHelper(parent, node, getNodeClasses(node));\n const w = Math.max(30, node?.width ?? 0);\n const h = Math.max(30, node?.height ?? 0);\n const { cssStyles } = node;\n const rc = rough20.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const points = [\n { x: 0, y: 0 },\n { x: w, y: 0 },\n { x: 0, y: h },\n { x: w, y: h }\n ];\n const pathData = createPathFromPoints(points);\n const shapeNode = rc.path(pathData, options);\n const polygon = shapeSvg.insert(() => shapeNode, \":first-child\");\n polygon.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", nodeStyles);\n }\n polygon.attr(\"transform\", `translate(${-w / 2}, ${-h / 2})`);\n updateNodeBounds(node, polygon);\n node.intersect = function(point) {\n log.info(\"Pill intersect\", node, { points });\n const pos = intersect_default.polygon(node, points, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(hourglass, \"hourglass\");\n\n// src/rendering-util/rendering-elements/shapes/icon.ts\nimport rough21 from \"roughjs\";\nasync function icon(parent, node, { config: { themeVariables, flowchart } }) {\n const { labelStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const assetHeight = node.assetHeight ?? 48;\n const assetWidth = node.assetWidth ?? 48;\n const iconSize = Math.max(assetHeight, assetWidth);\n const defaultWidth = flowchart?.wrappingWidth;\n node.width = Math.max(iconSize, defaultWidth ?? 0);\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, \"icon-shape default\");\n const topLabel = node.pos === \"t\";\n const height = iconSize;\n const width = iconSize;\n const { nodeBorder } = themeVariables;\n const { stylesMap } = compileStyles(node);\n const x = -width / 2;\n const y = -height / 2;\n const labelPadding = node.label ? 8 : 0;\n const rc = rough21.svg(shapeSvg);\n const options = userNodeOverrides(node, { stroke: \"none\", fill: \"none\" });\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const iconNode = rc.rectangle(x, y, width, height, options);\n const outerWidth = Math.max(width, bbox.width);\n const outerHeight = height + bbox.height + labelPadding;\n const outerNode = rc.rectangle(-outerWidth / 2, -outerHeight / 2, outerWidth, outerHeight, {\n ...options,\n fill: \"transparent\",\n stroke: \"none\"\n });\n const iconShape = shapeSvg.insert(() => iconNode, \":first-child\");\n const outerShape = shapeSvg.insert(() => outerNode);\n if (node.icon) {\n const iconElem = shapeSvg.append(\"g\");\n iconElem.html(\n `${await getIconSVG(node.icon, {\n height: iconSize,\n width: iconSize,\n fallbackPrefix: \"\"\n })}`\n );\n const iconBBox = iconElem.node().getBBox();\n const iconWidth = iconBBox.width;\n const iconHeight = iconBBox.height;\n const iconX = iconBBox.x;\n const iconY = iconBBox.y;\n iconElem.attr(\n \"transform\",\n `translate(${-iconWidth / 2 - iconX},${topLabel ? bbox.height / 2 + labelPadding / 2 - iconHeight / 2 - iconY : -bbox.height / 2 - labelPadding / 2 - iconHeight / 2 - iconY})`\n );\n iconElem.attr(\"style\", `color: ${stylesMap.get(\"stroke\") ?? nodeBorder};`);\n }\n label.attr(\n \"transform\",\n `translate(${-bbox.width / 2 - (bbox.x - (bbox.left ?? 0))},${topLabel ? -outerHeight / 2 : outerHeight / 2 - bbox.height})`\n );\n iconShape.attr(\n \"transform\",\n `translate(${0},${topLabel ? bbox.height / 2 + labelPadding / 2 : -bbox.height / 2 - labelPadding / 2})`\n );\n updateNodeBounds(node, outerShape);\n node.intersect = function(point) {\n log.info(\"iconSquare intersect\", node, point);\n if (!node.label) {\n return intersect_default.rect(node, point);\n }\n const dx = node.x ?? 0;\n const dy = node.y ?? 0;\n const nodeHeight = node.height ?? 0;\n let points = [];\n if (topLabel) {\n points = [\n { x: dx - bbox.width / 2, y: dy - nodeHeight / 2 },\n { x: dx + bbox.width / 2, y: dy - nodeHeight / 2 },\n { x: dx + bbox.width / 2, y: dy - nodeHeight / 2 + bbox.height + labelPadding },\n { x: dx + width / 2, y: dy - nodeHeight / 2 + bbox.height + labelPadding },\n { x: dx + width / 2, y: dy + nodeHeight / 2 },\n { x: dx - width / 2, y: dy + nodeHeight / 2 },\n { x: dx - width / 2, y: dy - nodeHeight / 2 + bbox.height + labelPadding },\n { x: dx - bbox.width / 2, y: dy - nodeHeight / 2 + bbox.height + labelPadding }\n ];\n } else {\n points = [\n { x: dx - width / 2, y: dy - nodeHeight / 2 },\n { x: dx + width / 2, y: dy - nodeHeight / 2 },\n { x: dx + width / 2, y: dy - nodeHeight / 2 + height },\n { x: dx + bbox.width / 2, y: dy - nodeHeight / 2 + height },\n { x: dx + bbox.width / 2 / 2, y: dy + nodeHeight / 2 },\n { x: dx - bbox.width / 2, y: dy + nodeHeight / 2 },\n { x: dx - bbox.width / 2, y: dy - nodeHeight / 2 + height },\n { x: dx - width / 2, y: dy - nodeHeight / 2 + height }\n ];\n }\n const pos = intersect_default.polygon(node, points, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(icon, \"icon\");\n\n// src/rendering-util/rendering-elements/shapes/iconCircle.ts\nimport rough22 from \"roughjs\";\nasync function iconCircle(parent, node, { config: { themeVariables, flowchart } }) {\n const { labelStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const assetHeight = node.assetHeight ?? 48;\n const assetWidth = node.assetWidth ?? 48;\n const iconSize = Math.max(assetHeight, assetWidth);\n const defaultWidth = flowchart?.wrappingWidth;\n node.width = Math.max(iconSize, defaultWidth ?? 0);\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, \"icon-shape default\");\n const padding = 20;\n const labelPadding = node.label ? 8 : 0;\n const topLabel = node.pos === \"t\";\n const { nodeBorder, mainBkg } = themeVariables;\n const { stylesMap } = compileStyles(node);\n const rc = rough22.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const fill = stylesMap.get(\"fill\");\n options.stroke = fill ?? mainBkg;\n const iconElem = shapeSvg.append(\"g\");\n if (node.icon) {\n iconElem.html(\n `${await getIconSVG(node.icon, {\n height: iconSize,\n width: iconSize,\n fallbackPrefix: \"\"\n })}`\n );\n }\n const iconBBox = iconElem.node().getBBox();\n const iconWidth = iconBBox.width;\n const iconHeight = iconBBox.height;\n const iconX = iconBBox.x;\n const iconY = iconBBox.y;\n const diameter = Math.max(iconWidth, iconHeight) * Math.SQRT2 + padding * 2;\n const iconNode = rc.circle(0, 0, diameter, options);\n const outerWidth = Math.max(diameter, bbox.width);\n const outerHeight = diameter + bbox.height + labelPadding;\n const outerNode = rc.rectangle(-outerWidth / 2, -outerHeight / 2, outerWidth, outerHeight, {\n ...options,\n fill: \"transparent\",\n stroke: \"none\"\n });\n const iconShape = shapeSvg.insert(() => iconNode, \":first-child\");\n const outerShape = shapeSvg.insert(() => outerNode);\n iconElem.attr(\n \"transform\",\n `translate(${-iconWidth / 2 - iconX},${topLabel ? bbox.height / 2 + labelPadding / 2 - iconHeight / 2 - iconY : -bbox.height / 2 - labelPadding / 2 - iconHeight / 2 - iconY})`\n );\n iconElem.attr(\"style\", `color: ${stylesMap.get(\"stroke\") ?? nodeBorder};`);\n label.attr(\n \"transform\",\n `translate(${-bbox.width / 2 - (bbox.x - (bbox.left ?? 0))},${topLabel ? -outerHeight / 2 : outerHeight / 2 - bbox.height})`\n );\n iconShape.attr(\n \"transform\",\n `translate(${0},${topLabel ? bbox.height / 2 + labelPadding / 2 : -bbox.height / 2 - labelPadding / 2})`\n );\n updateNodeBounds(node, outerShape);\n node.intersect = function(point) {\n log.info(\"iconSquare intersect\", node, point);\n const pos = intersect_default.rect(node, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(iconCircle, \"iconCircle\");\n\n// src/rendering-util/rendering-elements/shapes/iconRounded.ts\nimport rough23 from \"roughjs\";\nasync function iconRounded(parent, node, { config: { themeVariables, flowchart } }) {\n const { labelStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const assetHeight = node.assetHeight ?? 48;\n const assetWidth = node.assetWidth ?? 48;\n const iconSize = Math.max(assetHeight, assetWidth);\n const defaultWidth = flowchart?.wrappingWidth;\n node.width = Math.max(iconSize, defaultWidth ?? 0);\n const { shapeSvg, bbox, halfPadding, label } = await labelHelper(\n parent,\n node,\n \"icon-shape default\"\n );\n const topLabel = node.pos === \"t\";\n const height = iconSize + halfPadding * 2;\n const width = iconSize + halfPadding * 2;\n const { nodeBorder, mainBkg } = themeVariables;\n const { stylesMap } = compileStyles(node);\n const x = -width / 2;\n const y = -height / 2;\n const labelPadding = node.label ? 8 : 0;\n const rc = rough23.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const fill = stylesMap.get(\"fill\");\n options.stroke = fill ?? mainBkg;\n const iconNode = rc.path(createRoundedRectPathD(x, y, width, height, 5), options);\n const outerWidth = Math.max(width, bbox.width);\n const outerHeight = height + bbox.height + labelPadding;\n const outerNode = rc.rectangle(-outerWidth / 2, -outerHeight / 2, outerWidth, outerHeight, {\n ...options,\n fill: \"transparent\",\n stroke: \"none\"\n });\n const iconShape = shapeSvg.insert(() => iconNode, \":first-child\").attr(\"class\", \"icon-shape2\");\n const outerShape = shapeSvg.insert(() => outerNode);\n if (node.icon) {\n const iconElem = shapeSvg.append(\"g\");\n iconElem.html(\n `${await getIconSVG(node.icon, {\n height: iconSize,\n width: iconSize,\n fallbackPrefix: \"\"\n })}`\n );\n const iconBBox = iconElem.node().getBBox();\n const iconWidth = iconBBox.width;\n const iconHeight = iconBBox.height;\n const iconX = iconBBox.x;\n const iconY = iconBBox.y;\n iconElem.attr(\n \"transform\",\n `translate(${-iconWidth / 2 - iconX},${topLabel ? bbox.height / 2 + labelPadding / 2 - iconHeight / 2 - iconY : -bbox.height / 2 - labelPadding / 2 - iconHeight / 2 - iconY})`\n );\n iconElem.attr(\"style\", `color: ${stylesMap.get(\"stroke\") ?? nodeBorder};`);\n }\n label.attr(\n \"transform\",\n `translate(${-bbox.width / 2 - (bbox.x - (bbox.left ?? 0))},${topLabel ? -outerHeight / 2 : outerHeight / 2 - bbox.height})`\n );\n iconShape.attr(\n \"transform\",\n `translate(${0},${topLabel ? bbox.height / 2 + labelPadding / 2 : -bbox.height / 2 - labelPadding / 2})`\n );\n updateNodeBounds(node, outerShape);\n node.intersect = function(point) {\n log.info(\"iconSquare intersect\", node, point);\n if (!node.label) {\n return intersect_default.rect(node, point);\n }\n const dx = node.x ?? 0;\n const dy = node.y ?? 0;\n const nodeHeight = node.height ?? 0;\n let points = [];\n if (topLabel) {\n points = [\n { x: dx - bbox.width / 2, y: dy - nodeHeight / 2 },\n { x: dx + bbox.width / 2, y: dy - nodeHeight / 2 },\n { x: dx + bbox.width / 2, y: dy - nodeHeight / 2 + bbox.height + labelPadding },\n { x: dx + width / 2, y: dy - nodeHeight / 2 + bbox.height + labelPadding },\n { x: dx + width / 2, y: dy + nodeHeight / 2 },\n { x: dx - width / 2, y: dy + nodeHeight / 2 },\n { x: dx - width / 2, y: dy - nodeHeight / 2 + bbox.height + labelPadding },\n { x: dx - bbox.width / 2, y: dy - nodeHeight / 2 + bbox.height + labelPadding }\n ];\n } else {\n points = [\n { x: dx - width / 2, y: dy - nodeHeight / 2 },\n { x: dx + width / 2, y: dy - nodeHeight / 2 },\n { x: dx + width / 2, y: dy - nodeHeight / 2 + height },\n { x: dx + bbox.width / 2, y: dy - nodeHeight / 2 + height },\n { x: dx + bbox.width / 2 / 2, y: dy + nodeHeight / 2 },\n { x: dx - bbox.width / 2, y: dy + nodeHeight / 2 },\n { x: dx - bbox.width / 2, y: dy - nodeHeight / 2 + height },\n { x: dx - width / 2, y: dy - nodeHeight / 2 + height }\n ];\n }\n const pos = intersect_default.polygon(node, points, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(iconRounded, \"iconRounded\");\n\n// src/rendering-util/rendering-elements/shapes/iconSquare.ts\nimport rough24 from \"roughjs\";\nasync function iconSquare(parent, node, { config: { themeVariables, flowchart } }) {\n const { labelStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const assetHeight = node.assetHeight ?? 48;\n const assetWidth = node.assetWidth ?? 48;\n const iconSize = Math.max(assetHeight, assetWidth);\n const defaultWidth = flowchart?.wrappingWidth;\n node.width = Math.max(iconSize, defaultWidth ?? 0);\n const { shapeSvg, bbox, halfPadding, label } = await labelHelper(\n parent,\n node,\n \"icon-shape default\"\n );\n const topLabel = node.pos === \"t\";\n const height = iconSize + halfPadding * 2;\n const width = iconSize + halfPadding * 2;\n const { nodeBorder, mainBkg } = themeVariables;\n const { stylesMap } = compileStyles(node);\n const x = -width / 2;\n const y = -height / 2;\n const labelPadding = node.label ? 8 : 0;\n const rc = rough24.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const fill = stylesMap.get(\"fill\");\n options.stroke = fill ?? mainBkg;\n const iconNode = rc.path(createRoundedRectPathD(x, y, width, height, 0.1), options);\n const outerWidth = Math.max(width, bbox.width);\n const outerHeight = height + bbox.height + labelPadding;\n const outerNode = rc.rectangle(-outerWidth / 2, -outerHeight / 2, outerWidth, outerHeight, {\n ...options,\n fill: \"transparent\",\n stroke: \"none\"\n });\n const iconShape = shapeSvg.insert(() => iconNode, \":first-child\");\n const outerShape = shapeSvg.insert(() => outerNode);\n if (node.icon) {\n const iconElem = shapeSvg.append(\"g\");\n iconElem.html(\n `${await getIconSVG(node.icon, {\n height: iconSize,\n width: iconSize,\n fallbackPrefix: \"\"\n })}`\n );\n const iconBBox = iconElem.node().getBBox();\n const iconWidth = iconBBox.width;\n const iconHeight = iconBBox.height;\n const iconX = iconBBox.x;\n const iconY = iconBBox.y;\n iconElem.attr(\n \"transform\",\n `translate(${-iconWidth / 2 - iconX},${topLabel ? bbox.height / 2 + labelPadding / 2 - iconHeight / 2 - iconY : -bbox.height / 2 - labelPadding / 2 - iconHeight / 2 - iconY})`\n );\n iconElem.attr(\"style\", `color: ${stylesMap.get(\"stroke\") ?? nodeBorder};`);\n }\n label.attr(\n \"transform\",\n `translate(${-bbox.width / 2 - (bbox.x - (bbox.left ?? 0))},${topLabel ? -outerHeight / 2 : outerHeight / 2 - bbox.height})`\n );\n iconShape.attr(\n \"transform\",\n `translate(${0},${topLabel ? bbox.height / 2 + labelPadding / 2 : -bbox.height / 2 - labelPadding / 2})`\n );\n updateNodeBounds(node, outerShape);\n node.intersect = function(point) {\n log.info(\"iconSquare intersect\", node, point);\n if (!node.label) {\n return intersect_default.rect(node, point);\n }\n const dx = node.x ?? 0;\n const dy = node.y ?? 0;\n const nodeHeight = node.height ?? 0;\n let points = [];\n if (topLabel) {\n points = [\n { x: dx - bbox.width / 2, y: dy - nodeHeight / 2 },\n { x: dx + bbox.width / 2, y: dy - nodeHeight / 2 },\n { x: dx + bbox.width / 2, y: dy - nodeHeight / 2 + bbox.height + labelPadding },\n { x: dx + width / 2, y: dy - nodeHeight / 2 + bbox.height + labelPadding },\n { x: dx + width / 2, y: dy + nodeHeight / 2 },\n { x: dx - width / 2, y: dy + nodeHeight / 2 },\n { x: dx - width / 2, y: dy - nodeHeight / 2 + bbox.height + labelPadding },\n { x: dx - bbox.width / 2, y: dy - nodeHeight / 2 + bbox.height + labelPadding }\n ];\n } else {\n points = [\n { x: dx - width / 2, y: dy - nodeHeight / 2 },\n { x: dx + width / 2, y: dy - nodeHeight / 2 },\n { x: dx + width / 2, y: dy - nodeHeight / 2 + height },\n { x: dx + bbox.width / 2, y: dy - nodeHeight / 2 + height },\n { x: dx + bbox.width / 2 / 2, y: dy + nodeHeight / 2 },\n { x: dx - bbox.width / 2, y: dy + nodeHeight / 2 },\n { x: dx - bbox.width / 2, y: dy - nodeHeight / 2 + height },\n { x: dx - width / 2, y: dy - nodeHeight / 2 + height }\n ];\n }\n const pos = intersect_default.polygon(node, points, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(iconSquare, \"iconSquare\");\n\n// src/rendering-util/rendering-elements/shapes/imageSquare.ts\nimport rough25 from \"roughjs\";\nasync function imageSquare(parent, node, { config: { flowchart } }) {\n const img = new Image();\n img.src = node?.img ?? \"\";\n await img.decode();\n const imageNaturalWidth = Number(img.naturalWidth.toString().replace(\"px\", \"\"));\n const imageNaturalHeight = Number(img.naturalHeight.toString().replace(\"px\", \"\"));\n node.imageAspectRatio = imageNaturalWidth / imageNaturalHeight;\n const { labelStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const defaultWidth = flowchart?.wrappingWidth;\n node.defaultWidth = flowchart?.wrappingWidth;\n const imageRawWidth = Math.max(\n node.label ? defaultWidth ?? 0 : 0,\n node?.assetWidth ?? imageNaturalWidth\n );\n const imageWidth = node.constraint === \"on\" ? node?.assetHeight ? node.assetHeight * node.imageAspectRatio : imageRawWidth : imageRawWidth;\n const imageHeight = node.constraint === \"on\" ? imageWidth / node.imageAspectRatio : node?.assetHeight ?? imageNaturalHeight;\n node.width = Math.max(imageWidth, defaultWidth ?? 0);\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, \"image-shape default\");\n const topLabel = node.pos === \"t\";\n const x = -imageWidth / 2;\n const y = -imageHeight / 2;\n const labelPadding = node.label ? 8 : 0;\n const rc = rough25.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const imageNode = rc.rectangle(x, y, imageWidth, imageHeight, options);\n const outerWidth = Math.max(imageWidth, bbox.width);\n const outerHeight = imageHeight + bbox.height + labelPadding;\n const outerNode = rc.rectangle(-outerWidth / 2, -outerHeight / 2, outerWidth, outerHeight, {\n ...options,\n fill: \"none\",\n stroke: \"none\"\n });\n const iconShape = shapeSvg.insert(() => imageNode, \":first-child\");\n const outerShape = shapeSvg.insert(() => outerNode);\n if (node.img) {\n const image = shapeSvg.append(\"image\");\n image.attr(\"href\", node.img);\n image.attr(\"width\", imageWidth);\n image.attr(\"height\", imageHeight);\n image.attr(\"preserveAspectRatio\", \"none\");\n image.attr(\n \"transform\",\n `translate(${-imageWidth / 2},${topLabel ? outerHeight / 2 - imageHeight : -outerHeight / 2})`\n );\n }\n label.attr(\n \"transform\",\n `translate(${-bbox.width / 2 - (bbox.x - (bbox.left ?? 0))},${topLabel ? -imageHeight / 2 - bbox.height / 2 - labelPadding / 2 : imageHeight / 2 - bbox.height / 2 + labelPadding / 2})`\n );\n iconShape.attr(\n \"transform\",\n `translate(${0},${topLabel ? bbox.height / 2 + labelPadding / 2 : -bbox.height / 2 - labelPadding / 2})`\n );\n updateNodeBounds(node, outerShape);\n node.intersect = function(point) {\n log.info(\"iconSquare intersect\", node, point);\n if (!node.label) {\n return intersect_default.rect(node, point);\n }\n const dx = node.x ?? 0;\n const dy = node.y ?? 0;\n const nodeHeight = node.height ?? 0;\n let points = [];\n if (topLabel) {\n points = [\n { x: dx - bbox.width / 2, y: dy - nodeHeight / 2 },\n { x: dx + bbox.width / 2, y: dy - nodeHeight / 2 },\n { x: dx + bbox.width / 2, y: dy - nodeHeight / 2 + bbox.height + labelPadding },\n { x: dx + imageWidth / 2, y: dy - nodeHeight / 2 + bbox.height + labelPadding },\n { x: dx + imageWidth / 2, y: dy + nodeHeight / 2 },\n { x: dx - imageWidth / 2, y: dy + nodeHeight / 2 },\n { x: dx - imageWidth / 2, y: dy - nodeHeight / 2 + bbox.height + labelPadding },\n { x: dx - bbox.width / 2, y: dy - nodeHeight / 2 + bbox.height + labelPadding }\n ];\n } else {\n points = [\n { x: dx - imageWidth / 2, y: dy - nodeHeight / 2 },\n { x: dx + imageWidth / 2, y: dy - nodeHeight / 2 },\n { x: dx + imageWidth / 2, y: dy - nodeHeight / 2 + imageHeight },\n { x: dx + bbox.width / 2, y: dy - nodeHeight / 2 + imageHeight },\n { x: dx + bbox.width / 2 / 2, y: dy + nodeHeight / 2 },\n { x: dx - bbox.width / 2, y: dy + nodeHeight / 2 },\n { x: dx - bbox.width / 2, y: dy - nodeHeight / 2 + imageHeight },\n { x: dx - imageWidth / 2, y: dy - nodeHeight / 2 + imageHeight }\n ];\n }\n const pos = intersect_default.polygon(node, points, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(imageSquare, \"imageSquare\");\n\n// src/rendering-util/rendering-elements/shapes/invertedTrapezoid.ts\nimport rough26 from \"roughjs\";\nasync function inv_trapezoid(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const w = Math.max(bbox.width + (node.padding ?? 0) * 2, node?.width ?? 0);\n const h = Math.max(bbox.height + (node.padding ?? 0) * 2, node?.height ?? 0);\n const points = [\n { x: 0, y: 0 },\n { x: w, y: 0 },\n { x: w + 3 * h / 6, y: -h },\n { x: -3 * h / 6, y: -h }\n ];\n let polygon;\n const { cssStyles } = node;\n if (node.look === \"handDrawn\") {\n const rc = rough26.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n const pathData = createPathFromPoints(points);\n const roughNode = rc.path(pathData, options);\n polygon = shapeSvg.insert(() => roughNode, \":first-child\").attr(\"transform\", `translate(${-w / 2}, ${h / 2})`);\n if (cssStyles) {\n polygon.attr(\"style\", cssStyles);\n }\n } else {\n polygon = insertPolygonShape(shapeSvg, w, h, points);\n }\n if (nodeStyles) {\n polygon.attr(\"style\", nodeStyles);\n }\n node.width = w;\n node.height = h;\n updateNodeBounds(node, polygon);\n node.intersect = function(point) {\n return intersect_default.polygon(node, points, point);\n };\n return shapeSvg;\n}\n__name(inv_trapezoid, \"inv_trapezoid\");\n\n// src/rendering-util/rendering-elements/shapes/drawRect.ts\nimport rough27 from \"roughjs\";\nasync function drawRect(parent, node, options) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const totalWidth = Math.max(bbox.width + options.labelPaddingX * 2, node?.width || 0);\n const totalHeight = Math.max(bbox.height + options.labelPaddingY * 2, node?.height || 0);\n const x = -totalWidth / 2;\n const y = -totalHeight / 2;\n let rect2;\n let { rx, ry } = node;\n const { cssStyles } = node;\n if (options?.rx && options.ry) {\n rx = options.rx;\n ry = options.ry;\n }\n if (node.look === \"handDrawn\") {\n const rc = rough27.svg(shapeSvg);\n const options2 = userNodeOverrides(node, {});\n const roughNode = rx || ry ? rc.path(createRoundedRectPathD(x, y, totalWidth, totalHeight, rx || 0), options2) : rc.rectangle(x, y, totalWidth, totalHeight, options2);\n rect2 = shapeSvg.insert(() => roughNode, \":first-child\");\n rect2.attr(\"class\", \"basic label-container\").attr(\"style\", handleUndefinedAttr(cssStyles));\n } else {\n rect2 = shapeSvg.insert(\"rect\", \":first-child\");\n rect2.attr(\"class\", \"basic label-container\").attr(\"style\", nodeStyles).attr(\"rx\", handleUndefinedAttr(rx)).attr(\"ry\", handleUndefinedAttr(ry)).attr(\"x\", x).attr(\"y\", y).attr(\"width\", totalWidth).attr(\"height\", totalHeight);\n }\n updateNodeBounds(node, rect2);\n node.calcIntersect = function(bounds, point) {\n return intersect_default.rect(bounds, point);\n };\n node.intersect = function(point) {\n return intersect_default.rect(node, point);\n };\n return shapeSvg;\n}\n__name(drawRect, \"drawRect\");\n\n// src/rendering-util/rendering-elements/shapes/labelRect.ts\nasync function labelRect(parent, node) {\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, \"label\");\n const rect2 = shapeSvg.insert(\"rect\", \":first-child\");\n const totalWidth = 0.1;\n const totalHeight = 0.1;\n rect2.attr(\"width\", totalWidth).attr(\"height\", totalHeight);\n shapeSvg.attr(\"class\", \"label edgeLabel\");\n label.attr(\n \"transform\",\n `translate(${-(bbox.width / 2) - (bbox.x - (bbox.left ?? 0))}, ${-(bbox.height / 2) - (bbox.y - (bbox.top ?? 0))})`\n );\n updateNodeBounds(node, rect2);\n node.intersect = function(point) {\n return intersect_default.rect(node, point);\n };\n return shapeSvg;\n}\n__name(labelRect, \"labelRect\");\n\n// src/rendering-util/rendering-elements/shapes/leanLeft.ts\nimport rough28 from \"roughjs\";\nasync function lean_left(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const w = Math.max(bbox.width + (node.padding ?? 0), node?.width ?? 0);\n const h = Math.max(bbox.height + (node.padding ?? 0), node?.height ?? 0);\n const points = [\n { x: 0, y: 0 },\n { x: w + 3 * h / 6, y: 0 },\n { x: w, y: -h },\n { x: -(3 * h) / 6, y: -h }\n ];\n let polygon;\n const { cssStyles } = node;\n if (node.look === \"handDrawn\") {\n const rc = rough28.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n const pathData = createPathFromPoints(points);\n const roughNode = rc.path(pathData, options);\n polygon = shapeSvg.insert(() => roughNode, \":first-child\").attr(\"transform\", `translate(${-w / 2}, ${h / 2})`);\n if (cssStyles) {\n polygon.attr(\"style\", cssStyles);\n }\n } else {\n polygon = insertPolygonShape(shapeSvg, w, h, points);\n }\n if (nodeStyles) {\n polygon.attr(\"style\", nodeStyles);\n }\n node.width = w;\n node.height = h;\n updateNodeBounds(node, polygon);\n node.intersect = function(point) {\n return intersect_default.polygon(node, points, point);\n };\n return shapeSvg;\n}\n__name(lean_left, \"lean_left\");\n\n// src/rendering-util/rendering-elements/shapes/leanRight.ts\nimport rough29 from \"roughjs\";\nasync function lean_right(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const w = Math.max(bbox.width + (node.padding ?? 0), node?.width ?? 0);\n const h = Math.max(bbox.height + (node.padding ?? 0), node?.height ?? 0);\n const points = [\n { x: -3 * h / 6, y: 0 },\n { x: w, y: 0 },\n { x: w + 3 * h / 6, y: -h },\n { x: 0, y: -h }\n ];\n let polygon;\n const { cssStyles } = node;\n if (node.look === \"handDrawn\") {\n const rc = rough29.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n const pathData = createPathFromPoints(points);\n const roughNode = rc.path(pathData, options);\n polygon = shapeSvg.insert(() => roughNode, \":first-child\").attr(\"transform\", `translate(${-w / 2}, ${h / 2})`);\n if (cssStyles) {\n polygon.attr(\"style\", cssStyles);\n }\n } else {\n polygon = insertPolygonShape(shapeSvg, w, h, points);\n }\n if (nodeStyles) {\n polygon.attr(\"style\", nodeStyles);\n }\n node.width = w;\n node.height = h;\n updateNodeBounds(node, polygon);\n node.intersect = function(point) {\n return intersect_default.polygon(node, points, point);\n };\n return shapeSvg;\n}\n__name(lean_right, \"lean_right\");\n\n// src/rendering-util/rendering-elements/shapes/lightningBolt.ts\nimport rough30 from \"roughjs\";\nfunction lightningBolt(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.label = \"\";\n node.labelStyle = labelStyles;\n const shapeSvg = parent.insert(\"g\").attr(\"class\", getNodeClasses(node)).attr(\"id\", node.domId ?? node.id);\n const { cssStyles } = node;\n const width = Math.max(35, node?.width ?? 0);\n const height = Math.max(35, node?.height ?? 0);\n const gap = 7;\n const points = [\n { x: width, y: 0 },\n { x: 0, y: height + gap / 2 },\n { x: width - 2 * gap, y: height + gap / 2 },\n { x: 0, y: 2 * height },\n { x: width, y: height - gap / 2 },\n { x: 2 * gap, y: height - gap / 2 }\n ];\n const rc = rough30.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const linePath = createPathFromPoints(points);\n const lineNode = rc.path(linePath, options);\n const lightningBolt2 = shapeSvg.insert(() => lineNode, \":first-child\");\n if (cssStyles && node.look !== \"handDrawn\") {\n lightningBolt2.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n lightningBolt2.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n lightningBolt2.attr(\"transform\", `translate(-${width / 2},${-height})`);\n updateNodeBounds(node, lightningBolt2);\n node.intersect = function(point) {\n log.info(\"lightningBolt intersect\", node, point);\n const pos = intersect_default.polygon(node, points, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(lightningBolt, \"lightningBolt\");\n\n// src/rendering-util/rendering-elements/shapes/linedCylinder.ts\nimport rough31 from \"roughjs\";\nvar createCylinderPathD2 = /* @__PURE__ */ __name((x, y, width, height, rx, ry, outerOffset) => {\n return [\n `M${x},${y + ry}`,\n `a${rx},${ry} 0,0,0 ${width},0`,\n `a${rx},${ry} 0,0,0 ${-width},0`,\n `l0,${height}`,\n `a${rx},${ry} 0,0,0 ${width},0`,\n `l0,${-height}`,\n `M${x},${y + ry + outerOffset}`,\n `a${rx},${ry} 0,0,0 ${width},0`\n ].join(\" \");\n}, \"createCylinderPathD\");\nvar createOuterCylinderPathD2 = /* @__PURE__ */ __name((x, y, width, height, rx, ry, outerOffset) => {\n return [\n `M${x},${y + ry}`,\n `M${x + width},${y + ry}`,\n `a${rx},${ry} 0,0,0 ${-width},0`,\n `l0,${height}`,\n `a${rx},${ry} 0,0,0 ${width},0`,\n `l0,${-height}`,\n `M${x},${y + ry + outerOffset}`,\n `a${rx},${ry} 0,0,0 ${width},0`\n ].join(\" \");\n}, \"createOuterCylinderPathD\");\nvar createInnerCylinderPathD2 = /* @__PURE__ */ __name((x, y, width, height, rx, ry) => {\n return [`M${x - width / 2},${-height / 2}`, `a${rx},${ry} 0,0,0 ${width},0`].join(\" \");\n}, \"createInnerCylinderPathD\");\nasync function linedCylinder(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const w = Math.max(bbox.width + (node.padding ?? 0), node.width ?? 0);\n const rx = w / 2;\n const ry = rx / (2.5 + w / 50);\n const h = Math.max(bbox.height + ry + (node.padding ?? 0), node.height ?? 0);\n const outerOffset = h * 0.1;\n let cylinder2;\n const { cssStyles } = node;\n if (node.look === \"handDrawn\") {\n const rc = rough31.svg(shapeSvg);\n const outerPathData = createOuterCylinderPathD2(0, 0, w, h, rx, ry, outerOffset);\n const innerPathData = createInnerCylinderPathD2(0, ry, w, h, rx, ry);\n const options = userNodeOverrides(node, {});\n const outerNode = rc.path(outerPathData, options);\n const innerLine = rc.path(innerPathData, options);\n const innerLineEl = shapeSvg.insert(() => innerLine, \":first-child\");\n innerLineEl.attr(\"class\", \"line\");\n cylinder2 = shapeSvg.insert(() => outerNode, \":first-child\");\n cylinder2.attr(\"class\", \"basic label-container\");\n if (cssStyles) {\n cylinder2.attr(\"style\", cssStyles);\n }\n } else {\n const pathData = createCylinderPathD2(0, 0, w, h, rx, ry, outerOffset);\n cylinder2 = shapeSvg.insert(\"path\", \":first-child\").attr(\"d\", pathData).attr(\"class\", \"basic label-container\").attr(\"style\", handleUndefinedAttr(cssStyles)).attr(\"style\", nodeStyles);\n }\n cylinder2.attr(\"label-offset-y\", ry);\n cylinder2.attr(\"transform\", `translate(${-w / 2}, ${-(h / 2 + ry)})`);\n updateNodeBounds(node, cylinder2);\n label.attr(\n \"transform\",\n `translate(${-(bbox.width / 2) - (bbox.x - (bbox.left ?? 0))}, ${-(bbox.height / 2) + ry - (bbox.y - (bbox.top ?? 0))})`\n );\n node.intersect = function(point) {\n const pos = intersect_default.rect(node, point);\n const x = pos.x - (node.x ?? 0);\n if (rx != 0 && (Math.abs(x) < (node.width ?? 0) / 2 || Math.abs(x) == (node.width ?? 0) / 2 && Math.abs(pos.y - (node.y ?? 0)) > (node.height ?? 0) / 2 - ry)) {\n let y = ry * ry * (1 - x * x / (rx * rx));\n if (y > 0) {\n y = Math.sqrt(y);\n }\n y = ry - y;\n if (point.y - (node.y ?? 0) > 0) {\n y = -y;\n }\n pos.y += y;\n }\n return pos;\n };\n return shapeSvg;\n}\n__name(linedCylinder, \"linedCylinder\");\n\n// src/rendering-util/rendering-elements/shapes/linedWaveEdgedRect.ts\nimport rough32 from \"roughjs\";\nasync function linedWaveEdgedRect(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const w = Math.max(bbox.width + (node.padding ?? 0) * 2, node?.width ?? 0);\n const h = Math.max(bbox.height + (node.padding ?? 0) * 2, node?.height ?? 0);\n const waveAmplitude = h / 4;\n const finalH = h + waveAmplitude;\n const { cssStyles } = node;\n const rc = rough32.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const points = [\n { x: -w / 2 - w / 2 * 0.1, y: -finalH / 2 },\n { x: -w / 2 - w / 2 * 0.1, y: finalH / 2 },\n ...generateFullSineWavePoints(\n -w / 2 - w / 2 * 0.1,\n finalH / 2,\n w / 2 + w / 2 * 0.1,\n finalH / 2,\n waveAmplitude,\n 0.8\n ),\n { x: w / 2 + w / 2 * 0.1, y: -finalH / 2 },\n { x: -w / 2 - w / 2 * 0.1, y: -finalH / 2 },\n { x: -w / 2, y: -finalH / 2 },\n { x: -w / 2, y: finalH / 2 * 1.1 },\n { x: -w / 2, y: -finalH / 2 }\n ];\n const poly = rc.polygon(\n points.map((p) => [p.x, p.y]),\n options\n );\n const waveEdgeRect = shapeSvg.insert(() => poly, \":first-child\");\n waveEdgeRect.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n waveEdgeRect.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n waveEdgeRect.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n waveEdgeRect.attr(\"transform\", `translate(0,${-waveAmplitude / 2})`);\n label.attr(\n \"transform\",\n `translate(${-w / 2 + (node.padding ?? 0) + w / 2 * 0.1 / 2 - (bbox.x - (bbox.left ?? 0))},${-h / 2 + (node.padding ?? 0) - waveAmplitude / 2 - (bbox.y - (bbox.top ?? 0))})`\n );\n updateNodeBounds(node, waveEdgeRect);\n node.intersect = function(point) {\n const pos = intersect_default.polygon(node, points, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(linedWaveEdgedRect, \"linedWaveEdgedRect\");\n\n// src/rendering-util/rendering-elements/shapes/multiRect.ts\nimport rough33 from \"roughjs\";\nasync function multiRect(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const w = Math.max(bbox.width + (node.padding ?? 0) * 2, node?.width ?? 0);\n const h = Math.max(bbox.height + (node.padding ?? 0) * 2, node?.height ?? 0);\n const rectOffset = 5;\n const x = -w / 2;\n const y = -h / 2;\n const { cssStyles } = node;\n const rc = rough33.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n const outerPathPoints = [\n { x: x - rectOffset, y: y + rectOffset },\n { x: x - rectOffset, y: y + h + rectOffset },\n { x: x + w - rectOffset, y: y + h + rectOffset },\n { x: x + w - rectOffset, y: y + h },\n { x: x + w, y: y + h },\n { x: x + w, y: y + h - rectOffset },\n { x: x + w + rectOffset, y: y + h - rectOffset },\n { x: x + w + rectOffset, y: y - rectOffset },\n { x: x + rectOffset, y: y - rectOffset },\n { x: x + rectOffset, y },\n { x, y },\n { x, y: y + rectOffset }\n ];\n const innerPathPoints = [\n { x, y: y + rectOffset },\n { x: x + w - rectOffset, y: y + rectOffset },\n { x: x + w - rectOffset, y: y + h },\n { x: x + w, y: y + h },\n { x: x + w, y },\n { x, y }\n ];\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const outerPath = createPathFromPoints(outerPathPoints);\n const outerNode = rc.path(outerPath, options);\n const innerPath = createPathFromPoints(innerPathPoints);\n const innerNode = rc.path(innerPath, { ...options, fill: \"none\" });\n const multiRect2 = shapeSvg.insert(() => innerNode, \":first-child\");\n multiRect2.insert(() => outerNode, \":first-child\");\n multiRect2.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n multiRect2.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n multiRect2.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n label.attr(\n \"transform\",\n `translate(${-(bbox.width / 2) - rectOffset - (bbox.x - (bbox.left ?? 0))}, ${-(bbox.height / 2) + rectOffset - (bbox.y - (bbox.top ?? 0))})`\n );\n updateNodeBounds(node, multiRect2);\n node.intersect = function(point) {\n const pos = intersect_default.polygon(node, outerPathPoints, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(multiRect, \"multiRect\");\n\n// src/rendering-util/rendering-elements/shapes/multiWaveEdgedRectangle.ts\nimport rough34 from \"roughjs\";\nasync function multiWaveEdgedRectangle(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const w = Math.max(bbox.width + (node.padding ?? 0) * 2, node?.width ?? 0);\n const h = Math.max(bbox.height + (node.padding ?? 0) * 2, node?.height ?? 0);\n const waveAmplitude = h / 4;\n const finalH = h + waveAmplitude;\n const x = -w / 2;\n const y = -finalH / 2;\n const rectOffset = 5;\n const { cssStyles } = node;\n const wavePoints = generateFullSineWavePoints(\n x - rectOffset,\n y + finalH + rectOffset,\n x + w - rectOffset,\n y + finalH + rectOffset,\n waveAmplitude,\n 0.8\n );\n const lastWavePoint = wavePoints?.[wavePoints.length - 1];\n const outerPathPoints = [\n { x: x - rectOffset, y: y + rectOffset },\n { x: x - rectOffset, y: y + finalH + rectOffset },\n ...wavePoints,\n { x: x + w - rectOffset, y: lastWavePoint.y - rectOffset },\n { x: x + w, y: lastWavePoint.y - rectOffset },\n { x: x + w, y: lastWavePoint.y - 2 * rectOffset },\n { x: x + w + rectOffset, y: lastWavePoint.y - 2 * rectOffset },\n { x: x + w + rectOffset, y: y - rectOffset },\n { x: x + rectOffset, y: y - rectOffset },\n { x: x + rectOffset, y },\n { x, y },\n { x, y: y + rectOffset }\n ];\n const innerPathPoints = [\n { x, y: y + rectOffset },\n { x: x + w - rectOffset, y: y + rectOffset },\n { x: x + w - rectOffset, y: lastWavePoint.y - rectOffset },\n { x: x + w, y: lastWavePoint.y - rectOffset },\n { x: x + w, y },\n { x, y }\n ];\n const rc = rough34.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const outerPath = createPathFromPoints(outerPathPoints);\n const outerNode = rc.path(outerPath, options);\n const innerPath = createPathFromPoints(innerPathPoints);\n const innerNode = rc.path(innerPath, options);\n const shape = shapeSvg.insert(() => outerNode, \":first-child\");\n shape.insert(() => innerNode);\n shape.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n shape.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n shape.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n shape.attr(\"transform\", `translate(0,${-waveAmplitude / 2})`);\n label.attr(\n \"transform\",\n `translate(${-(bbox.width / 2) - rectOffset - (bbox.x - (bbox.left ?? 0))}, ${-(bbox.height / 2) + rectOffset - waveAmplitude / 2 - (bbox.y - (bbox.top ?? 0))})`\n );\n updateNodeBounds(node, shape);\n node.intersect = function(point) {\n const pos = intersect_default.polygon(node, outerPathPoints, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(multiWaveEdgedRectangle, \"multiWaveEdgedRectangle\");\n\n// src/rendering-util/rendering-elements/shapes/note.ts\nimport rough35 from \"roughjs\";\nasync function note(parent, node, { config: { themeVariables } }) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const useHtmlLabels = node.useHtmlLabels || getConfig().flowchart?.htmlLabels !== false;\n if (!useHtmlLabels) {\n node.centerLabel = true;\n }\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const totalWidth = Math.max(bbox.width + (node.padding ?? 0) * 2, node?.width ?? 0);\n const totalHeight = Math.max(bbox.height + (node.padding ?? 0) * 2, node?.height ?? 0);\n const x = -totalWidth / 2;\n const y = -totalHeight / 2;\n const { cssStyles } = node;\n const rc = rough35.svg(shapeSvg);\n const options = userNodeOverrides(node, {\n fill: themeVariables.noteBkgColor,\n stroke: themeVariables.noteBorderColor\n });\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const noteShapeNode = rc.rectangle(x, y, totalWidth, totalHeight, options);\n const rect2 = shapeSvg.insert(() => noteShapeNode, \":first-child\");\n rect2.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n rect2.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n rect2.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n label.attr(\n \"transform\",\n `translate(${-bbox.width / 2 - (bbox.x - (bbox.left ?? 0))}, ${-(bbox.height / 2) - (bbox.y - (bbox.top ?? 0))})`\n );\n updateNodeBounds(node, rect2);\n node.intersect = function(point) {\n return intersect_default.rect(node, point);\n };\n return shapeSvg;\n}\n__name(note, \"note\");\n\n// src/rendering-util/rendering-elements/shapes/question.ts\nimport rough36 from \"roughjs\";\nvar createDecisionBoxPathD = /* @__PURE__ */ __name((x, y, size) => {\n return [\n `M${x + size / 2},${y}`,\n `L${x + size},${y - size / 2}`,\n `L${x + size / 2},${y - size}`,\n `L${x},${y - size / 2}`,\n \"Z\"\n ].join(\" \");\n}, \"createDecisionBoxPathD\");\nasync function question(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const w = bbox.width + node.padding;\n const h = bbox.height + node.padding;\n const s = w + h;\n const adjustment = 0.5;\n const points = [\n { x: s / 2, y: 0 },\n { x: s, y: -s / 2 },\n { x: s / 2, y: -s },\n { x: 0, y: -s / 2 }\n ];\n let polygon;\n const { cssStyles } = node;\n if (node.look === \"handDrawn\") {\n const rc = rough36.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n const pathData = createDecisionBoxPathD(0, 0, s);\n const roughNode = rc.path(pathData, options);\n polygon = shapeSvg.insert(() => roughNode, \":first-child\").attr(\"transform\", `translate(${-s / 2 + adjustment}, ${s / 2})`);\n if (cssStyles) {\n polygon.attr(\"style\", cssStyles);\n }\n } else {\n polygon = insertPolygonShape(shapeSvg, s, s, points);\n polygon.attr(\"transform\", `translate(${-s / 2 + adjustment}, ${s / 2})`);\n }\n if (nodeStyles) {\n polygon.attr(\"style\", nodeStyles);\n }\n updateNodeBounds(node, polygon);\n node.calcIntersect = function(bounds, point) {\n const s2 = bounds.width;\n const points2 = [\n { x: s2 / 2, y: 0 },\n { x: s2, y: -s2 / 2 },\n { x: s2 / 2, y: -s2 },\n { x: 0, y: -s2 / 2 }\n ];\n const res = intersect_default.polygon(bounds, points2, point);\n return { x: res.x - 0.5, y: res.y - 0.5 };\n };\n node.intersect = function(point) {\n return this.calcIntersect(node, point);\n };\n return shapeSvg;\n}\n__name(question, \"question\");\n\n// src/rendering-util/rendering-elements/shapes/rectLeftInvArrow.ts\nimport rough37 from \"roughjs\";\nasync function rect_left_inv_arrow(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const w = Math.max(bbox.width + (node.padding ?? 0), node?.width ?? 0);\n const h = Math.max(bbox.height + (node.padding ?? 0), node?.height ?? 0);\n const x = -w / 2;\n const y = -h / 2;\n const notch = y / 2;\n const points = [\n { x: x + notch, y },\n { x, y: 0 },\n { x: x + notch, y: -y },\n { x: -x, y: -y },\n { x: -x, y }\n ];\n const { cssStyles } = node;\n const rc = rough37.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const pathData = createPathFromPoints(points);\n const roughNode = rc.path(pathData, options);\n const polygon = shapeSvg.insert(() => roughNode, \":first-child\");\n polygon.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n polygon.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n polygon.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n polygon.attr(\"transform\", `translate(${-notch / 2},0)`);\n label.attr(\n \"transform\",\n `translate(${-notch / 2 - bbox.width / 2 - (bbox.x - (bbox.left ?? 0))}, ${-(bbox.height / 2) - (bbox.y - (bbox.top ?? 0))})`\n );\n updateNodeBounds(node, polygon);\n node.intersect = function(point) {\n return intersect_default.polygon(node, points, point);\n };\n return shapeSvg;\n}\n__name(rect_left_inv_arrow, \"rect_left_inv_arrow\");\n\n// src/rendering-util/rendering-elements/shapes/rectWithTitle.ts\nimport { select as select4 } from \"d3\";\nimport rough38 from \"roughjs\";\nasync function rectWithTitle(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n let classes;\n if (!node.cssClasses) {\n classes = \"node default\";\n } else {\n classes = \"node \" + node.cssClasses;\n }\n const shapeSvg = parent.insert(\"g\").attr(\"class\", classes).attr(\"id\", node.domId || node.id);\n const g = shapeSvg.insert(\"g\");\n const label = shapeSvg.insert(\"g\").attr(\"class\", \"label\").attr(\"style\", nodeStyles);\n const description = node.description;\n const title = node.label;\n const text2 = label.node().appendChild(await createLabel_default(title, node.labelStyle, true, true));\n let bbox = { width: 0, height: 0 };\n if (evaluate(getConfig2()?.flowchart?.htmlLabels)) {\n const div2 = text2.children[0];\n const dv2 = select4(text2);\n bbox = div2.getBoundingClientRect();\n dv2.attr(\"width\", bbox.width);\n dv2.attr(\"height\", bbox.height);\n }\n log.info(\"Text 2\", description);\n const textRows = description || [];\n const titleBox = text2.getBBox();\n const descr = label.node().appendChild(\n await createLabel_default(\n textRows.join ? textRows.join(\"
\") : textRows,\n node.labelStyle,\n true,\n true\n )\n );\n const div = descr.children[0];\n const dv = select4(descr);\n bbox = div.getBoundingClientRect();\n dv.attr(\"width\", bbox.width);\n dv.attr(\"height\", bbox.height);\n const halfPadding = (node.padding || 0) / 2;\n select4(descr).attr(\n \"transform\",\n \"translate( \" + (bbox.width > titleBox.width ? 0 : (titleBox.width - bbox.width) / 2) + \", \" + (titleBox.height + halfPadding + 5) + \")\"\n );\n select4(text2).attr(\n \"transform\",\n \"translate( \" + (bbox.width < titleBox.width ? 0 : -(titleBox.width - bbox.width) / 2) + \", 0)\"\n );\n bbox = label.node().getBBox();\n label.attr(\n \"transform\",\n \"translate(\" + -bbox.width / 2 + \", \" + (-bbox.height / 2 - halfPadding + 3) + \")\"\n );\n const totalWidth = bbox.width + (node.padding || 0);\n const totalHeight = bbox.height + (node.padding || 0);\n const x = -bbox.width / 2 - halfPadding;\n const y = -bbox.height / 2 - halfPadding;\n let rect2;\n let innerLine;\n if (node.look === \"handDrawn\") {\n const rc = rough38.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n const roughNode = rc.path(\n createRoundedRectPathD(x, y, totalWidth, totalHeight, node.rx || 0),\n options\n );\n const roughLine = rc.line(\n -bbox.width / 2 - halfPadding,\n -bbox.height / 2 - halfPadding + titleBox.height + halfPadding,\n bbox.width / 2 + halfPadding,\n -bbox.height / 2 - halfPadding + titleBox.height + halfPadding,\n options\n );\n innerLine = shapeSvg.insert(() => {\n log.debug(\"Rough node insert CXC\", roughNode);\n return roughLine;\n }, \":first-child\");\n rect2 = shapeSvg.insert(() => {\n log.debug(\"Rough node insert CXC\", roughNode);\n return roughNode;\n }, \":first-child\");\n } else {\n rect2 = g.insert(\"rect\", \":first-child\");\n innerLine = g.insert(\"line\");\n rect2.attr(\"class\", \"outer title-state\").attr(\"style\", nodeStyles).attr(\"x\", -bbox.width / 2 - halfPadding).attr(\"y\", -bbox.height / 2 - halfPadding).attr(\"width\", bbox.width + (node.padding || 0)).attr(\"height\", bbox.height + (node.padding || 0));\n innerLine.attr(\"class\", \"divider\").attr(\"x1\", -bbox.width / 2 - halfPadding).attr(\"x2\", bbox.width / 2 + halfPadding).attr(\"y1\", -bbox.height / 2 - halfPadding + titleBox.height + halfPadding).attr(\"y2\", -bbox.height / 2 - halfPadding + titleBox.height + halfPadding);\n }\n updateNodeBounds(node, rect2);\n node.intersect = function(point) {\n return intersect_default.rect(node, point);\n };\n return shapeSvg;\n}\n__name(rectWithTitle, \"rectWithTitle\");\n\n// src/rendering-util/rendering-elements/shapes/roundedRect.ts\nimport rough39 from \"roughjs\";\nfunction generateArcPoints2(x1, y1, x2, y2, rx, ry, clockwise) {\n const numPoints = 20;\n const midX = (x1 + x2) / 2;\n const midY = (y1 + y2) / 2;\n const angle = Math.atan2(y2 - y1, x2 - x1);\n const dx = (x2 - x1) / 2;\n const dy = (y2 - y1) / 2;\n const transformedX = dx / rx;\n const transformedY = dy / ry;\n const distance = Math.sqrt(transformedX ** 2 + transformedY ** 2);\n if (distance > 1) {\n throw new Error(\"The given radii are too small to create an arc between the points.\");\n }\n const scaledCenterDistance = Math.sqrt(1 - distance ** 2);\n const centerX = midX + scaledCenterDistance * ry * Math.sin(angle) * (clockwise ? -1 : 1);\n const centerY = midY - scaledCenterDistance * rx * Math.cos(angle) * (clockwise ? -1 : 1);\n const startAngle = Math.atan2((y1 - centerY) / ry, (x1 - centerX) / rx);\n const endAngle = Math.atan2((y2 - centerY) / ry, (x2 - centerX) / rx);\n let angleRange = endAngle - startAngle;\n if (clockwise && angleRange < 0) {\n angleRange += 2 * Math.PI;\n }\n if (!clockwise && angleRange > 0) {\n angleRange -= 2 * Math.PI;\n }\n const points = [];\n for (let i = 0; i < numPoints; i++) {\n const t = i / (numPoints - 1);\n const angle2 = startAngle + t * angleRange;\n const x = centerX + rx * Math.cos(angle2);\n const y = centerY + ry * Math.sin(angle2);\n points.push({ x, y });\n }\n return points;\n}\n__name(generateArcPoints2, \"generateArcPoints\");\nasync function roundedRect(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const labelPaddingX = node?.padding ?? 0;\n const labelPaddingY = node?.padding ?? 0;\n const w = (node?.width ? node?.width : bbox.width) + labelPaddingX * 2;\n const h = (node?.height ? node?.height : bbox.height) + labelPaddingY * 2;\n const radius = node.radius || 5;\n const taper = node.taper || 5;\n const { cssStyles } = node;\n const rc = rough39.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.stroke) {\n options.stroke = node.stroke;\n }\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const points = [\n // Top edge (left to right)\n { x: -w / 2 + taper, y: -h / 2 },\n // Top-left corner start (1)\n { x: w / 2 - taper, y: -h / 2 },\n // Top-right corner start (2)\n ...generateArcPoints2(w / 2 - taper, -h / 2, w / 2, -h / 2 + taper, radius, radius, true),\n // Top-left arc (2 to 3)\n // Right edge (top to bottom)\n { x: w / 2, y: -h / 2 + taper },\n // Top-right taper point (3)\n { x: w / 2, y: h / 2 - taper },\n // Bottom-right taper point (4)\n ...generateArcPoints2(w / 2, h / 2 - taper, w / 2 - taper, h / 2, radius, radius, true),\n // Top-left arc (4 to 5)\n // Bottom edge (right to left)\n { x: w / 2 - taper, y: h / 2 },\n // Bottom-right corner start (5)\n { x: -w / 2 + taper, y: h / 2 },\n // Bottom-left corner start (6)\n ...generateArcPoints2(-w / 2 + taper, h / 2, -w / 2, h / 2 - taper, radius, radius, true),\n // Top-left arc (4 to 5)\n // Left edge (bottom to top)\n { x: -w / 2, y: h / 2 - taper },\n // Bottom-left taper point (7)\n { x: -w / 2, y: -h / 2 + taper },\n // Top-left taper point (8)\n ...generateArcPoints2(-w / 2, -h / 2 + taper, -w / 2 + taper, -h / 2, radius, radius, true)\n // Top-left arc (4 to 5)\n ];\n const pathData = createPathFromPoints(points);\n const shapeNode = rc.path(pathData, options);\n const polygon = shapeSvg.insert(() => shapeNode, \":first-child\");\n polygon.attr(\"class\", \"basic label-container outer-path\");\n if (cssStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", nodeStyles);\n }\n updateNodeBounds(node, polygon);\n node.intersect = function(point) {\n const pos = intersect_default.polygon(node, points, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(roundedRect, \"roundedRect\");\n\n// src/rendering-util/rendering-elements/shapes/shadedProcess.ts\nimport rough40 from \"roughjs\";\nasync function shadedProcess(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const halfPadding = node?.padding ?? 0;\n const w = Math.max(bbox.width + (node.padding ?? 0) * 2, node?.width ?? 0);\n const h = Math.max(bbox.height + (node.padding ?? 0) * 2, node?.height ?? 0);\n const x = -bbox.width / 2 - halfPadding;\n const y = -bbox.height / 2 - halfPadding;\n const { cssStyles } = node;\n const rc = rough40.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const points = [\n { x, y },\n { x: x + w + 8, y },\n { x: x + w + 8, y: y + h },\n { x: x - 8, y: y + h },\n { x: x - 8, y },\n { x, y },\n { x, y: y + h }\n ];\n const roughNode = rc.polygon(\n points.map((p) => [p.x, p.y]),\n options\n );\n const rect2 = shapeSvg.insert(() => roughNode, \":first-child\");\n rect2.attr(\"class\", \"basic label-container\").attr(\"style\", handleUndefinedAttr(cssStyles));\n if (nodeStyles && node.look !== \"handDrawn\") {\n rect2.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n if (cssStyles && node.look !== \"handDrawn\") {\n rect2.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n label.attr(\n \"transform\",\n `translate(${-w / 2 + 4 + (node.padding ?? 0) - (bbox.x - (bbox.left ?? 0))},${-h / 2 + (node.padding ?? 0) - (bbox.y - (bbox.top ?? 0))})`\n );\n updateNodeBounds(node, rect2);\n node.intersect = function(point) {\n return intersect_default.rect(node, point);\n };\n return shapeSvg;\n}\n__name(shadedProcess, \"shadedProcess\");\n\n// src/rendering-util/rendering-elements/shapes/slopedRect.ts\nimport rough41 from \"roughjs\";\nasync function slopedRect(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const w = Math.max(bbox.width + (node.padding ?? 0) * 2, node?.width ?? 0);\n const h = Math.max(bbox.height + (node.padding ?? 0) * 2, node?.height ?? 0);\n const x = -w / 2;\n const y = -h / 2;\n const { cssStyles } = node;\n const rc = rough41.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const points = [\n { x, y },\n { x, y: y + h },\n { x: x + w, y: y + h },\n { x: x + w, y: y - h / 2 }\n ];\n const pathData = createPathFromPoints(points);\n const shapeNode = rc.path(pathData, options);\n const polygon = shapeSvg.insert(() => shapeNode, \":first-child\");\n polygon.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", nodeStyles);\n }\n polygon.attr(\"transform\", `translate(0, ${h / 4})`);\n label.attr(\n \"transform\",\n `translate(${-w / 2 + (node.padding ?? 0) - (bbox.x - (bbox.left ?? 0))}, ${-h / 4 + (node.padding ?? 0) - (bbox.y - (bbox.top ?? 0))})`\n );\n updateNodeBounds(node, polygon);\n node.intersect = function(point) {\n const pos = intersect_default.polygon(node, points, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(slopedRect, \"slopedRect\");\n\n// src/rendering-util/rendering-elements/shapes/squareRect.ts\nasync function squareRect2(parent, node) {\n const options = {\n rx: 0,\n ry: 0,\n classes: \"\",\n labelPaddingX: node.labelPaddingX ?? (node?.padding || 0) * 2,\n labelPaddingY: (node?.padding || 0) * 1\n };\n return drawRect(parent, node, options);\n}\n__name(squareRect2, \"squareRect\");\n\n// src/rendering-util/rendering-elements/shapes/stadium.ts\nimport rough42 from \"roughjs\";\nasync function stadium(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const h = bbox.height + node.padding;\n const w = bbox.width + h / 4 + node.padding;\n const radius = h / 2;\n const { cssStyles } = node;\n const rc = rough42.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const points = [\n { x: -w / 2 + radius, y: -h / 2 },\n { x: w / 2 - radius, y: -h / 2 },\n ...generateCirclePoints(-w / 2 + radius, 0, radius, 50, 90, 270),\n { x: w / 2 - radius, y: h / 2 },\n ...generateCirclePoints(w / 2 - radius, 0, radius, 50, 270, 450)\n ];\n const pathData = createPathFromPoints(points);\n const shapeNode = rc.path(pathData, options);\n const polygon = shapeSvg.insert(() => shapeNode, \":first-child\");\n polygon.attr(\"class\", \"basic label-container outer-path\");\n if (cssStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", nodeStyles);\n }\n updateNodeBounds(node, polygon);\n node.intersect = function(point) {\n const pos = intersect_default.polygon(node, points, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(stadium, \"stadium\");\n\n// src/rendering-util/rendering-elements/shapes/state.ts\nasync function state(parent, node) {\n const options = {\n rx: 5,\n ry: 5,\n classes: \"flowchart-node\"\n };\n return drawRect(parent, node, options);\n}\n__name(state, \"state\");\n\n// src/rendering-util/rendering-elements/shapes/stateEnd.ts\nimport rough43 from \"roughjs\";\nfunction stateEnd(parent, node, { config: { themeVariables } }) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { cssStyles } = node;\n const { lineColor, stateBorder, nodeBorder } = themeVariables;\n const shapeSvg = parent.insert(\"g\").attr(\"class\", \"node default\").attr(\"id\", node.domId || node.id);\n const rc = rough43.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const roughNode = rc.circle(0, 0, 14, {\n ...options,\n stroke: lineColor,\n strokeWidth: 2\n });\n const innerFill = stateBorder ?? nodeBorder;\n const roughInnerNode = rc.circle(0, 0, 5, {\n ...options,\n fill: innerFill,\n stroke: innerFill,\n strokeWidth: 2,\n fillStyle: \"solid\"\n });\n const circle2 = shapeSvg.insert(() => roughNode, \":first-child\");\n circle2.insert(() => roughInnerNode);\n if (cssStyles) {\n circle2.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles) {\n circle2.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n updateNodeBounds(node, circle2);\n node.intersect = function(point) {\n return intersect_default.circle(node, 7, point);\n };\n return shapeSvg;\n}\n__name(stateEnd, \"stateEnd\");\n\n// src/rendering-util/rendering-elements/shapes/stateStart.ts\nimport rough44 from \"roughjs\";\nfunction stateStart(parent, node, { config: { themeVariables } }) {\n const { lineColor } = themeVariables;\n const shapeSvg = parent.insert(\"g\").attr(\"class\", \"node default\").attr(\"id\", node.domId || node.id);\n let circle2;\n if (node.look === \"handDrawn\") {\n const rc = rough44.svg(shapeSvg);\n const roughNode = rc.circle(0, 0, 14, solidStateFill(lineColor));\n circle2 = shapeSvg.insert(() => roughNode);\n circle2.attr(\"class\", \"state-start\").attr(\"r\", 7).attr(\"width\", 14).attr(\"height\", 14);\n } else {\n circle2 = shapeSvg.insert(\"circle\", \":first-child\");\n circle2.attr(\"class\", \"state-start\").attr(\"r\", 7).attr(\"width\", 14).attr(\"height\", 14);\n }\n updateNodeBounds(node, circle2);\n node.intersect = function(point) {\n return intersect_default.circle(node, 7, point);\n };\n return shapeSvg;\n}\n__name(stateStart, \"stateStart\");\n\n// src/rendering-util/rendering-elements/shapes/subroutine.ts\nimport rough45 from \"roughjs\";\nasync function subroutine(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const halfPadding = (node?.padding || 0) / 2;\n const w = bbox.width + node.padding;\n const h = bbox.height + node.padding;\n const x = -bbox.width / 2 - halfPadding;\n const y = -bbox.height / 2 - halfPadding;\n const points = [\n { x: 0, y: 0 },\n { x: w, y: 0 },\n { x: w, y: -h },\n { x: 0, y: -h },\n { x: 0, y: 0 },\n { x: -8, y: 0 },\n { x: w + 8, y: 0 },\n { x: w + 8, y: -h },\n { x: -8, y: -h },\n { x: -8, y: 0 }\n ];\n if (node.look === \"handDrawn\") {\n const rc = rough45.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n const roughNode = rc.rectangle(x - 8, y, w + 16, h, options);\n const l1 = rc.line(x, y, x, y + h, options);\n const l2 = rc.line(x + w, y, x + w, y + h, options);\n shapeSvg.insert(() => l1, \":first-child\");\n shapeSvg.insert(() => l2, \":first-child\");\n const rect2 = shapeSvg.insert(() => roughNode, \":first-child\");\n const { cssStyles } = node;\n rect2.attr(\"class\", \"basic label-container\").attr(\"style\", handleUndefinedAttr(cssStyles));\n updateNodeBounds(node, rect2);\n } else {\n const el = insertPolygonShape(shapeSvg, w, h, points);\n if (nodeStyles) {\n el.attr(\"style\", nodeStyles);\n }\n updateNodeBounds(node, el);\n }\n node.intersect = function(point) {\n return intersect_default.polygon(node, points, point);\n };\n return shapeSvg;\n}\n__name(subroutine, \"subroutine\");\n\n// src/rendering-util/rendering-elements/shapes/taggedRect.ts\nimport rough46 from \"roughjs\";\nasync function taggedRect(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const w = Math.max(bbox.width + (node.padding ?? 0) * 2, node?.width ?? 0);\n const h = Math.max(bbox.height + (node.padding ?? 0) * 2, node?.height ?? 0);\n const x = -w / 2;\n const y = -h / 2;\n const tagWidth = 0.2 * h;\n const tagHeight = 0.2 * h;\n const { cssStyles } = node;\n const rc = rough46.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n const rectPoints = [\n { x: x - tagWidth / 2, y },\n { x: x + w + tagWidth / 2, y },\n { x: x + w + tagWidth / 2, y: y + h },\n { x: x - tagWidth / 2, y: y + h }\n ];\n const tagPoints = [\n { x: x + w - tagWidth / 2, y: y + h },\n { x: x + w + tagWidth / 2, y: y + h },\n { x: x + w + tagWidth / 2, y: y + h - tagHeight }\n ];\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const rectPath = createPathFromPoints(rectPoints);\n const rectNode = rc.path(rectPath, options);\n const tagPath = createPathFromPoints(tagPoints);\n const tagNode = rc.path(tagPath, { ...options, fillStyle: \"solid\" });\n const taggedRect2 = shapeSvg.insert(() => tagNode, \":first-child\");\n taggedRect2.insert(() => rectNode, \":first-child\");\n taggedRect2.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n taggedRect2.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n taggedRect2.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n updateNodeBounds(node, taggedRect2);\n node.intersect = function(point) {\n const pos = intersect_default.polygon(node, rectPoints, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(taggedRect, \"taggedRect\");\n\n// src/rendering-util/rendering-elements/shapes/taggedWaveEdgedRectangle.ts\nimport rough47 from \"roughjs\";\nasync function taggedWaveEdgedRectangle(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const w = Math.max(bbox.width + (node.padding ?? 0) * 2, node?.width ?? 0);\n const h = Math.max(bbox.height + (node.padding ?? 0) * 2, node?.height ?? 0);\n const waveAmplitude = h / 4;\n const tagWidth = 0.2 * w;\n const tagHeight = 0.2 * h;\n const finalH = h + waveAmplitude;\n const { cssStyles } = node;\n const rc = rough47.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const points = [\n { x: -w / 2 - w / 2 * 0.1, y: finalH / 2 },\n ...generateFullSineWavePoints(\n -w / 2 - w / 2 * 0.1,\n finalH / 2,\n w / 2 + w / 2 * 0.1,\n finalH / 2,\n waveAmplitude,\n 0.8\n ),\n { x: w / 2 + w / 2 * 0.1, y: -finalH / 2 },\n { x: -w / 2 - w / 2 * 0.1, y: -finalH / 2 }\n ];\n const x = -w / 2 + w / 2 * 0.1;\n const y = -finalH / 2 - tagHeight * 0.4;\n const tagPoints = [\n { x: x + w - tagWidth, y: (y + h) * 1.4 },\n { x: x + w, y: y + h - tagHeight },\n { x: x + w, y: (y + h) * 0.9 },\n ...generateFullSineWavePoints(\n x + w,\n (y + h) * 1.3,\n x + w - tagWidth,\n (y + h) * 1.5,\n -h * 0.03,\n 0.5\n )\n ];\n const waveEdgeRectPath = createPathFromPoints(points);\n const waveEdgeRectNode = rc.path(waveEdgeRectPath, options);\n const taggedWaveEdgeRectPath = createPathFromPoints(tagPoints);\n const taggedWaveEdgeRectNode = rc.path(taggedWaveEdgeRectPath, {\n ...options,\n fillStyle: \"solid\"\n });\n const waveEdgeRect = shapeSvg.insert(() => taggedWaveEdgeRectNode, \":first-child\");\n waveEdgeRect.insert(() => waveEdgeRectNode, \":first-child\");\n waveEdgeRect.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n waveEdgeRect.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n waveEdgeRect.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n waveEdgeRect.attr(\"transform\", `translate(0,${-waveAmplitude / 2})`);\n label.attr(\n \"transform\",\n `translate(${-w / 2 + (node.padding ?? 0) - (bbox.x - (bbox.left ?? 0))},${-h / 2 + (node.padding ?? 0) - waveAmplitude / 2 - (bbox.y - (bbox.top ?? 0))})`\n );\n updateNodeBounds(node, waveEdgeRect);\n node.intersect = function(point) {\n const pos = intersect_default.polygon(node, points, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(taggedWaveEdgedRectangle, \"taggedWaveEdgedRectangle\");\n\n// src/rendering-util/rendering-elements/shapes/text.ts\nasync function text(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const totalWidth = Math.max(bbox.width + node.padding, node?.width || 0);\n const totalHeight = Math.max(bbox.height + node.padding, node?.height || 0);\n const x = -totalWidth / 2;\n const y = -totalHeight / 2;\n const rect2 = shapeSvg.insert(\"rect\", \":first-child\");\n rect2.attr(\"class\", \"text\").attr(\"style\", nodeStyles).attr(\"rx\", 0).attr(\"ry\", 0).attr(\"x\", x).attr(\"y\", y).attr(\"width\", totalWidth).attr(\"height\", totalHeight);\n updateNodeBounds(node, rect2);\n node.intersect = function(point) {\n return intersect_default.rect(node, point);\n };\n return shapeSvg;\n}\n__name(text, \"text\");\n\n// src/rendering-util/rendering-elements/shapes/tiltedCylinder.ts\nimport rough48 from \"roughjs\";\nvar createCylinderPathD3 = /* @__PURE__ */ __name((x, y, width, height, rx, ry) => {\n return `M${x},${y}\n a${rx},${ry} 0,0,1 ${0},${-height}\n l${width},${0}\n a${rx},${ry} 0,0,1 ${0},${height}\n M${width},${-height}\n a${rx},${ry} 0,0,0 ${0},${height}\n l${-width},${0}`;\n}, \"createCylinderPathD\");\nvar createOuterCylinderPathD3 = /* @__PURE__ */ __name((x, y, width, height, rx, ry) => {\n return [\n `M${x},${y}`,\n `M${x + width},${y}`,\n `a${rx},${ry} 0,0,0 ${0},${-height}`,\n `l${-width},0`,\n `a${rx},${ry} 0,0,0 ${0},${height}`,\n `l${width},0`\n ].join(\" \");\n}, \"createOuterCylinderPathD\");\nvar createInnerCylinderPathD3 = /* @__PURE__ */ __name((x, y, width, height, rx, ry) => {\n return [`M${x + width / 2},${-height / 2}`, `a${rx},${ry} 0,0,0 0,${height}`].join(\" \");\n}, \"createInnerCylinderPathD\");\nasync function tiltedCylinder(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label, halfPadding } = await labelHelper(\n parent,\n node,\n getNodeClasses(node)\n );\n const labelPadding = node.look === \"neo\" ? halfPadding * 2 : halfPadding;\n const h = bbox.height + labelPadding;\n const ry = h / 2;\n const rx = ry / (2.5 + h / 50);\n const w = bbox.width + rx + labelPadding;\n const { cssStyles } = node;\n let cylinder2;\n if (node.look === \"handDrawn\") {\n const rc = rough48.svg(shapeSvg);\n const outerPathData = createOuterCylinderPathD3(0, 0, w, h, rx, ry);\n const innerPathData = createInnerCylinderPathD3(0, 0, w, h, rx, ry);\n const outerNode = rc.path(outerPathData, userNodeOverrides(node, {}));\n const innerLine = rc.path(innerPathData, userNodeOverrides(node, { fill: \"none\" }));\n cylinder2 = shapeSvg.insert(() => innerLine, \":first-child\");\n cylinder2 = shapeSvg.insert(() => outerNode, \":first-child\");\n cylinder2.attr(\"class\", \"basic label-container\");\n if (cssStyles) {\n cylinder2.attr(\"style\", cssStyles);\n }\n } else {\n const pathData = createCylinderPathD3(0, 0, w, h, rx, ry);\n cylinder2 = shapeSvg.insert(\"path\", \":first-child\").attr(\"d\", pathData).attr(\"class\", \"basic label-container\").attr(\"style\", handleUndefinedAttr(cssStyles)).attr(\"style\", nodeStyles);\n cylinder2.attr(\"class\", \"basic label-container\");\n if (cssStyles) {\n cylinder2.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles) {\n cylinder2.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n }\n cylinder2.attr(\"label-offset-x\", rx);\n cylinder2.attr(\"transform\", `translate(${-w / 2}, ${h / 2} )`);\n label.attr(\n \"transform\",\n `translate(${-(bbox.width / 2) - rx - (bbox.x - (bbox.left ?? 0))}, ${-(bbox.height / 2) - (bbox.y - (bbox.top ?? 0))})`\n );\n updateNodeBounds(node, cylinder2);\n node.intersect = function(point) {\n const pos = intersect_default.rect(node, point);\n const y = pos.y - (node.y ?? 0);\n if (ry != 0 && (Math.abs(y) < (node.height ?? 0) / 2 || Math.abs(y) == (node.height ?? 0) / 2 && Math.abs(pos.x - (node.x ?? 0)) > (node.width ?? 0) / 2 - rx)) {\n let x = rx * rx * (1 - y * y / (ry * ry));\n if (x != 0) {\n x = Math.sqrt(Math.abs(x));\n }\n x = rx - x;\n if (point.x - (node.x ?? 0) > 0) {\n x = -x;\n }\n pos.x += x;\n }\n return pos;\n };\n return shapeSvg;\n}\n__name(tiltedCylinder, \"tiltedCylinder\");\n\n// src/rendering-util/rendering-elements/shapes/trapezoid.ts\nimport rough49 from \"roughjs\";\nasync function trapezoid(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const w = bbox.width + node.padding;\n const h = bbox.height + node.padding;\n const points = [\n { x: -3 * h / 6, y: 0 },\n { x: w + 3 * h / 6, y: 0 },\n { x: w, y: -h },\n { x: 0, y: -h }\n ];\n let polygon;\n const { cssStyles } = node;\n if (node.look === \"handDrawn\") {\n const rc = rough49.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n const pathData = createPathFromPoints(points);\n const roughNode = rc.path(pathData, options);\n polygon = shapeSvg.insert(() => roughNode, \":first-child\").attr(\"transform\", `translate(${-w / 2}, ${h / 2})`);\n if (cssStyles) {\n polygon.attr(\"style\", cssStyles);\n }\n } else {\n polygon = insertPolygonShape(shapeSvg, w, h, points);\n }\n if (nodeStyles) {\n polygon.attr(\"style\", nodeStyles);\n }\n node.width = w;\n node.height = h;\n updateNodeBounds(node, polygon);\n node.intersect = function(point) {\n return intersect_default.polygon(node, points, point);\n };\n return shapeSvg;\n}\n__name(trapezoid, \"trapezoid\");\n\n// src/rendering-util/rendering-elements/shapes/trapezoidalPentagon.ts\nimport rough50 from \"roughjs\";\nasync function trapezoidalPentagon(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const minWidth = 60, minHeight = 20;\n const w = Math.max(minWidth, bbox.width + (node.padding ?? 0) * 2, node?.width ?? 0);\n const h = Math.max(minHeight, bbox.height + (node.padding ?? 0) * 2, node?.height ?? 0);\n const { cssStyles } = node;\n const rc = rough50.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const points = [\n { x: -w / 2 * 0.8, y: -h / 2 },\n { x: w / 2 * 0.8, y: -h / 2 },\n { x: w / 2, y: -h / 2 * 0.6 },\n { x: w / 2, y: h / 2 },\n { x: -w / 2, y: h / 2 },\n { x: -w / 2, y: -h / 2 * 0.6 }\n ];\n const pathData = createPathFromPoints(points);\n const shapeNode = rc.path(pathData, options);\n const polygon = shapeSvg.insert(() => shapeNode, \":first-child\");\n polygon.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", nodeStyles);\n }\n updateNodeBounds(node, polygon);\n node.intersect = function(point) {\n const pos = intersect_default.polygon(node, points, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(trapezoidalPentagon, \"trapezoidalPentagon\");\n\n// src/rendering-util/rendering-elements/shapes/triangle.ts\nimport rough51 from \"roughjs\";\nasync function triangle(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const useHtmlLabels = evaluate(getConfig2().flowchart?.htmlLabels);\n const w = bbox.width + (node.padding ?? 0);\n const h = w + bbox.height;\n const tw = w + bbox.height;\n const points = [\n { x: 0, y: 0 },\n { x: tw, y: 0 },\n { x: tw / 2, y: -h }\n ];\n const { cssStyles } = node;\n const rc = rough51.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const pathData = createPathFromPoints(points);\n const roughNode = rc.path(pathData, options);\n const polygon = shapeSvg.insert(() => roughNode, \":first-child\").attr(\"transform\", `translate(${-h / 2}, ${h / 2})`);\n if (cssStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n polygon.selectChildren(\"path\").attr(\"style\", nodeStyles);\n }\n node.width = w;\n node.height = h;\n updateNodeBounds(node, polygon);\n label.attr(\n \"transform\",\n `translate(${-bbox.width / 2 - (bbox.x - (bbox.left ?? 0))}, ${h / 2 - (bbox.height + (node.padding ?? 0) / (useHtmlLabels ? 2 : 1) - (bbox.y - (bbox.top ?? 0)))})`\n );\n node.intersect = function(point) {\n log.info(\"Triangle intersect\", node, points, point);\n return intersect_default.polygon(node, points, point);\n };\n return shapeSvg;\n}\n__name(triangle, \"triangle\");\n\n// src/rendering-util/rendering-elements/shapes/waveEdgedRectangle.ts\nimport rough52 from \"roughjs\";\nasync function waveEdgedRectangle(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const w = Math.max(bbox.width + (node.padding ?? 0) * 2, node?.width ?? 0);\n const h = Math.max(bbox.height + (node.padding ?? 0) * 2, node?.height ?? 0);\n const waveAmplitude = h / 8;\n const finalH = h + waveAmplitude;\n const { cssStyles } = node;\n const minWidth = 70;\n const widthDif = minWidth - w;\n const extraW = widthDif > 0 ? widthDif / 2 : 0;\n const rc = rough52.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const points = [\n { x: -w / 2 - extraW, y: finalH / 2 },\n ...generateFullSineWavePoints(\n -w / 2 - extraW,\n finalH / 2,\n w / 2 + extraW,\n finalH / 2,\n waveAmplitude,\n 0.8\n ),\n { x: w / 2 + extraW, y: -finalH / 2 },\n { x: -w / 2 - extraW, y: -finalH / 2 }\n ];\n const waveEdgeRectPath = createPathFromPoints(points);\n const waveEdgeRectNode = rc.path(waveEdgeRectPath, options);\n const waveEdgeRect = shapeSvg.insert(() => waveEdgeRectNode, \":first-child\");\n waveEdgeRect.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n waveEdgeRect.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n waveEdgeRect.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n waveEdgeRect.attr(\"transform\", `translate(0,${-waveAmplitude / 2})`);\n label.attr(\n \"transform\",\n `translate(${-w / 2 + (node.padding ?? 0) - (bbox.x - (bbox.left ?? 0))},${-h / 2 + (node.padding ?? 0) - waveAmplitude - (bbox.y - (bbox.top ?? 0))})`\n );\n updateNodeBounds(node, waveEdgeRect);\n node.intersect = function(point) {\n const pos = intersect_default.polygon(node, points, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(waveEdgedRectangle, \"waveEdgedRectangle\");\n\n// src/rendering-util/rendering-elements/shapes/waveRectangle.ts\nimport rough53 from \"roughjs\";\nasync function waveRectangle(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));\n const minWidth = 100;\n const minHeight = 50;\n const baseWidth = Math.max(bbox.width + (node.padding ?? 0) * 2, node?.width ?? 0);\n const baseHeight = Math.max(bbox.height + (node.padding ?? 0) * 2, node?.height ?? 0);\n const aspectRatio = baseWidth / baseHeight;\n let w = baseWidth;\n let h = baseHeight;\n if (w > h * aspectRatio) {\n h = w / aspectRatio;\n } else {\n w = h * aspectRatio;\n }\n w = Math.max(w, minWidth);\n h = Math.max(h, minHeight);\n const waveAmplitude = Math.min(h * 0.2, h / 4);\n const finalH = h + waveAmplitude * 2;\n const { cssStyles } = node;\n const rc = rough53.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const points = [\n { x: -w / 2, y: finalH / 2 },\n ...generateFullSineWavePoints(-w / 2, finalH / 2, w / 2, finalH / 2, waveAmplitude, 1),\n { x: w / 2, y: -finalH / 2 },\n ...generateFullSineWavePoints(w / 2, -finalH / 2, -w / 2, -finalH / 2, waveAmplitude, -1)\n ];\n const waveRectPath = createPathFromPoints(points);\n const waveRectNode = rc.path(waveRectPath, options);\n const waveRect = shapeSvg.insert(() => waveRectNode, \":first-child\");\n waveRect.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n waveRect.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n waveRect.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n updateNodeBounds(node, waveRect);\n node.intersect = function(point) {\n const pos = intersect_default.polygon(node, points, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(waveRectangle, \"waveRectangle\");\n\n// src/rendering-util/rendering-elements/shapes/windowPane.ts\nimport rough54 from \"roughjs\";\nasync function windowPane(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));\n const w = Math.max(bbox.width + (node.padding ?? 0) * 2, node?.width ?? 0);\n const h = Math.max(bbox.height + (node.padding ?? 0) * 2, node?.height ?? 0);\n const rectOffset = 5;\n const x = -w / 2;\n const y = -h / 2;\n const { cssStyles } = node;\n const rc = rough54.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n const outerPathPoints = [\n { x: x - rectOffset, y: y - rectOffset },\n { x: x - rectOffset, y: y + h },\n { x: x + w, y: y + h },\n { x: x + w, y: y - rectOffset }\n ];\n const path = `M${x - rectOffset},${y - rectOffset} L${x + w},${y - rectOffset} L${x + w},${y + h} L${x - rectOffset},${y + h} L${x - rectOffset},${y - rectOffset}\n M${x - rectOffset},${y} L${x + w},${y}\n M${x},${y - rectOffset} L${x},${y + h}`;\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const no = rc.path(path, options);\n const windowPane2 = shapeSvg.insert(() => no, \":first-child\");\n windowPane2.attr(\"transform\", `translate(${rectOffset / 2}, ${rectOffset / 2})`);\n windowPane2.attr(\"class\", \"basic label-container\");\n if (cssStyles && node.look !== \"handDrawn\") {\n windowPane2.selectAll(\"path\").attr(\"style\", cssStyles);\n }\n if (nodeStyles && node.look !== \"handDrawn\") {\n windowPane2.selectAll(\"path\").attr(\"style\", nodeStyles);\n }\n label.attr(\n \"transform\",\n `translate(${-(bbox.width / 2) + rectOffset / 2 - (bbox.x - (bbox.left ?? 0))}, ${-(bbox.height / 2) + rectOffset / 2 - (bbox.y - (bbox.top ?? 0))})`\n );\n updateNodeBounds(node, windowPane2);\n node.intersect = function(point) {\n const pos = intersect_default.polygon(node, outerPathPoints, point);\n return pos;\n };\n return shapeSvg;\n}\n__name(windowPane, \"windowPane\");\n\n// src/rendering-util/rendering-elements/shapes/erBox.ts\nimport rough55 from \"roughjs\";\nimport { select as select5 } from \"d3\";\nasync function erBox(parent, node) {\n const entityNode = node;\n if (entityNode.alias) {\n node.label = entityNode.alias;\n }\n if (node.look === \"handDrawn\") {\n const { themeVariables: themeVariables2 } = getConfig();\n const { background } = themeVariables2;\n const backgroundNode = {\n ...node,\n id: node.id + \"-background\",\n look: \"default\",\n cssStyles: [\"stroke: none\", `fill: ${background}`]\n };\n await erBox(parent, backgroundNode);\n }\n const config = getConfig();\n node.useHtmlLabels = config.htmlLabels;\n let PADDING = config.er?.diagramPadding ?? 10;\n let TEXT_PADDING = config.er?.entityPadding ?? 6;\n const { cssStyles } = node;\n const { labelStyles, nodeStyles } = styles2String(node);\n if (entityNode.attributes.length === 0 && node.label) {\n const options2 = {\n rx: 0,\n ry: 0,\n labelPaddingX: PADDING,\n labelPaddingY: PADDING * 1.5,\n classes: \"\"\n };\n if (calculateTextWidth(node.label, config) + options2.labelPaddingX * 2 < config.er.minEntityWidth) {\n node.width = config.er.minEntityWidth;\n }\n const shapeSvg2 = await drawRect(parent, node, options2);\n if (!evaluate(config.htmlLabels)) {\n const textElement = shapeSvg2.select(\"text\");\n const bbox = textElement.node()?.getBBox();\n textElement.attr(\"transform\", `translate(${-bbox.width / 2}, 0)`);\n }\n return shapeSvg2;\n }\n if (!config.htmlLabels) {\n PADDING *= 1.25;\n TEXT_PADDING *= 1.25;\n }\n let cssClasses = getNodeClasses(node);\n if (!cssClasses) {\n cssClasses = \"node default\";\n }\n const shapeSvg = parent.insert(\"g\").attr(\"class\", cssClasses).attr(\"id\", node.domId || node.id);\n const nameBBox = await addText(shapeSvg, node.label ?? \"\", config, 0, 0, [\"name\"], labelStyles);\n nameBBox.height += TEXT_PADDING;\n let yOffset = 0;\n const yOffsets = [];\n const rows = [];\n let maxTypeWidth = 0;\n let maxNameWidth = 0;\n let maxKeysWidth = 0;\n let maxCommentWidth = 0;\n let keysPresent = true;\n let commentPresent = true;\n for (const attribute of entityNode.attributes) {\n const typeBBox = await addText(\n shapeSvg,\n attribute.type,\n config,\n 0,\n yOffset,\n [\"attribute-type\"],\n labelStyles\n );\n maxTypeWidth = Math.max(maxTypeWidth, typeBBox.width + PADDING);\n const nameBBox2 = await addText(\n shapeSvg,\n attribute.name,\n config,\n 0,\n yOffset,\n [\"attribute-name\"],\n labelStyles\n );\n maxNameWidth = Math.max(maxNameWidth, nameBBox2.width + PADDING);\n const keysBBox = await addText(\n shapeSvg,\n attribute.keys.join(),\n config,\n 0,\n yOffset,\n [\"attribute-keys\"],\n labelStyles\n );\n maxKeysWidth = Math.max(maxKeysWidth, keysBBox.width + PADDING);\n const commentBBox = await addText(\n shapeSvg,\n attribute.comment,\n config,\n 0,\n yOffset,\n [\"attribute-comment\"],\n labelStyles\n );\n maxCommentWidth = Math.max(maxCommentWidth, commentBBox.width + PADDING);\n const rowHeight = Math.max(typeBBox.height, nameBBox2.height, keysBBox.height, commentBBox.height) + TEXT_PADDING;\n rows.push({ yOffset, rowHeight });\n yOffset += rowHeight;\n }\n let totalWidthSections = 4;\n if (maxKeysWidth <= PADDING) {\n keysPresent = false;\n maxKeysWidth = 0;\n totalWidthSections--;\n }\n if (maxCommentWidth <= PADDING) {\n commentPresent = false;\n maxCommentWidth = 0;\n totalWidthSections--;\n }\n const shapeBBox = shapeSvg.node().getBBox();\n if (nameBBox.width + PADDING * 2 - (maxTypeWidth + maxNameWidth + maxKeysWidth + maxCommentWidth) > 0) {\n const difference = nameBBox.width + PADDING * 2 - (maxTypeWidth + maxNameWidth + maxKeysWidth + maxCommentWidth);\n maxTypeWidth += difference / totalWidthSections;\n maxNameWidth += difference / totalWidthSections;\n if (maxKeysWidth > 0) {\n maxKeysWidth += difference / totalWidthSections;\n }\n if (maxCommentWidth > 0) {\n maxCommentWidth += difference / totalWidthSections;\n }\n }\n const maxWidth = maxTypeWidth + maxNameWidth + maxKeysWidth + maxCommentWidth;\n const rc = rough55.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n let totalShapeBBoxHeight = 0;\n if (rows.length > 0) {\n totalShapeBBoxHeight = rows.reduce((sum, row) => sum + (row?.rowHeight ?? 0), 0);\n }\n const w = Math.max(shapeBBox.width + PADDING * 2, node?.width || 0, maxWidth);\n const h = Math.max((totalShapeBBoxHeight ?? 0) + nameBBox.height, node?.height || 0);\n const x = -w / 2;\n const y = -h / 2;\n shapeSvg.selectAll(\"g:not(:first-child)\").each((_, i, nodes) => {\n const text2 = select5(nodes[i]);\n const transform = text2.attr(\"transform\");\n let translateX = 0;\n let translateY = 0;\n if (transform) {\n const regex = RegExp(/translate\\(([^,]+),([^)]+)\\)/);\n const translate = regex.exec(transform);\n if (translate) {\n translateX = parseFloat(translate[1]);\n translateY = parseFloat(translate[2]);\n if (text2.attr(\"class\").includes(\"attribute-name\")) {\n translateX += maxTypeWidth;\n } else if (text2.attr(\"class\").includes(\"attribute-keys\")) {\n translateX += maxTypeWidth + maxNameWidth;\n } else if (text2.attr(\"class\").includes(\"attribute-comment\")) {\n translateX += maxTypeWidth + maxNameWidth + maxKeysWidth;\n }\n }\n }\n text2.attr(\n \"transform\",\n `translate(${x + PADDING / 2 + translateX}, ${translateY + y + nameBBox.height + TEXT_PADDING / 2})`\n );\n });\n shapeSvg.select(\".name\").attr(\"transform\", \"translate(\" + -nameBBox.width / 2 + \", \" + (y + TEXT_PADDING / 2) + \")\");\n const roughRect = rc.rectangle(x, y, w, h, options);\n const rect2 = shapeSvg.insert(() => roughRect, \":first-child\").attr(\"style\", cssStyles.join(\"\"));\n const { themeVariables } = getConfig();\n const { rowEven, rowOdd, nodeBorder } = themeVariables;\n yOffsets.push(0);\n for (const [i, row] of rows.entries()) {\n const contentRowIndex = i + 1;\n const isEven = contentRowIndex % 2 === 0 && row.yOffset !== 0;\n const roughRect2 = rc.rectangle(x, nameBBox.height + y + row?.yOffset, w, row?.rowHeight, {\n ...options,\n fill: isEven ? rowEven : rowOdd,\n stroke: nodeBorder\n });\n shapeSvg.insert(() => roughRect2, \"g.label\").attr(\"style\", cssStyles.join(\"\")).attr(\"class\", `row-rect-${isEven ? \"even\" : \"odd\"}`);\n }\n let roughLine = rc.line(x, nameBBox.height + y, w + x, nameBBox.height + y, options);\n shapeSvg.insert(() => roughLine).attr(\"class\", \"divider\");\n roughLine = rc.line(maxTypeWidth + x, nameBBox.height + y, maxTypeWidth + x, h + y, options);\n shapeSvg.insert(() => roughLine).attr(\"class\", \"divider\");\n if (keysPresent) {\n roughLine = rc.line(\n maxTypeWidth + maxNameWidth + x,\n nameBBox.height + y,\n maxTypeWidth + maxNameWidth + x,\n h + y,\n options\n );\n shapeSvg.insert(() => roughLine).attr(\"class\", \"divider\");\n }\n if (commentPresent) {\n roughLine = rc.line(\n maxTypeWidth + maxNameWidth + maxKeysWidth + x,\n nameBBox.height + y,\n maxTypeWidth + maxNameWidth + maxKeysWidth + x,\n h + y,\n options\n );\n shapeSvg.insert(() => roughLine).attr(\"class\", \"divider\");\n }\n for (const yOffset2 of yOffsets) {\n roughLine = rc.line(\n x,\n nameBBox.height + y + yOffset2,\n w + x,\n nameBBox.height + y + yOffset2,\n options\n );\n shapeSvg.insert(() => roughLine).attr(\"class\", \"divider\");\n }\n updateNodeBounds(node, rect2);\n if (nodeStyles && node.look !== \"handDrawn\") {\n const allStyle = nodeStyles.split(\";\");\n const strokeStyles = allStyle?.filter((e) => {\n return e.includes(\"stroke\");\n })?.map((s) => `${s}`).join(\"; \");\n shapeSvg.selectAll(\"path\").attr(\"style\", strokeStyles ?? \"\");\n shapeSvg.selectAll(\".row-rect-even path\").attr(\"style\", nodeStyles);\n }\n node.intersect = function(point) {\n return intersect_default.rect(node, point);\n };\n return shapeSvg;\n}\n__name(erBox, \"erBox\");\nasync function addText(shapeSvg, labelText, config, translateX = 0, translateY = 0, classes = [], style = \"\") {\n const label = shapeSvg.insert(\"g\").attr(\"class\", `label ${classes.join(\" \")}`).attr(\"transform\", `translate(${translateX}, ${translateY})`).attr(\"style\", style);\n if (labelText !== parseGenericTypes(labelText)) {\n labelText = parseGenericTypes(labelText);\n labelText = labelText.replaceAll(\"<\", \"<\").replaceAll(\">\", \">\");\n }\n const text2 = label.node().appendChild(\n await createText(\n label,\n labelText,\n {\n width: calculateTextWidth(labelText, config) + 100,\n style,\n useHtmlLabels: config.htmlLabels\n },\n config\n )\n );\n if (labelText.includes(\"<\") || labelText.includes(\">\")) {\n let child = text2.children[0];\n child.textContent = child.textContent.replaceAll(\"<\", \"<\").replaceAll(\">\", \">\");\n while (child.childNodes[0]) {\n child = child.childNodes[0];\n child.textContent = child.textContent.replaceAll(\"<\", \"<\").replaceAll(\">\", \">\");\n }\n }\n let bbox = text2.getBBox();\n if (evaluate(config.htmlLabels)) {\n const div = text2.children[0];\n div.style.textAlign = \"start\";\n const dv = select5(text2);\n bbox = div.getBoundingClientRect();\n dv.attr(\"width\", bbox.width);\n dv.attr(\"height\", bbox.height);\n }\n return bbox;\n}\n__name(addText, \"addText\");\n\n// src/rendering-util/rendering-elements/shapes/classBox.ts\nimport { select as select7 } from \"d3\";\nimport rough56 from \"roughjs\";\n\n// src/diagrams/class/shapeUtil.ts\nimport { select as select6 } from \"d3\";\nasync function textHelper(parent, node, config, useHtmlLabels, GAP = config.class.padding ?? 12) {\n const TEXT_PADDING = !useHtmlLabels ? 3 : 0;\n const shapeSvg = parent.insert(\"g\").attr(\"class\", getNodeClasses(node)).attr(\"id\", node.domId || node.id);\n let annotationGroup = null;\n let labelGroup = null;\n let membersGroup = null;\n let methodsGroup = null;\n let annotationGroupHeight = 0;\n let labelGroupHeight = 0;\n let membersGroupHeight = 0;\n annotationGroup = shapeSvg.insert(\"g\").attr(\"class\", \"annotation-group text\");\n if (node.annotations.length > 0) {\n const annotation = node.annotations[0];\n await addText2(annotationGroup, { text: `\\xAB${annotation}\\xBB` }, 0);\n const annotationGroupBBox = annotationGroup.node().getBBox();\n annotationGroupHeight = annotationGroupBBox.height;\n }\n labelGroup = shapeSvg.insert(\"g\").attr(\"class\", \"label-group text\");\n await addText2(labelGroup, node, 0, [\"font-weight: bolder\"]);\n const labelGroupBBox = labelGroup.node().getBBox();\n labelGroupHeight = labelGroupBBox.height;\n membersGroup = shapeSvg.insert(\"g\").attr(\"class\", \"members-group text\");\n let yOffset = 0;\n for (const member of node.members) {\n const height = await addText2(membersGroup, member, yOffset, [member.parseClassifier()]);\n yOffset += height + TEXT_PADDING;\n }\n membersGroupHeight = membersGroup.node().getBBox().height;\n if (membersGroupHeight <= 0) {\n membersGroupHeight = GAP / 2;\n }\n methodsGroup = shapeSvg.insert(\"g\").attr(\"class\", \"methods-group text\");\n let methodsYOffset = 0;\n for (const method of node.methods) {\n const height = await addText2(methodsGroup, method, methodsYOffset, [method.parseClassifier()]);\n methodsYOffset += height + TEXT_PADDING;\n }\n let bbox = shapeSvg.node().getBBox();\n if (annotationGroup !== null) {\n const annotationGroupBBox = annotationGroup.node().getBBox();\n annotationGroup.attr(\"transform\", `translate(${-annotationGroupBBox.width / 2})`);\n }\n labelGroup.attr(\"transform\", `translate(${-labelGroupBBox.width / 2}, ${annotationGroupHeight})`);\n bbox = shapeSvg.node().getBBox();\n membersGroup.attr(\n \"transform\",\n `translate(${0}, ${annotationGroupHeight + labelGroupHeight + GAP * 2})`\n );\n bbox = shapeSvg.node().getBBox();\n methodsGroup.attr(\n \"transform\",\n `translate(${0}, ${annotationGroupHeight + labelGroupHeight + (membersGroupHeight ? membersGroupHeight + GAP * 4 : GAP * 2)})`\n );\n bbox = shapeSvg.node().getBBox();\n return { shapeSvg, bbox };\n}\n__name(textHelper, \"textHelper\");\nasync function addText2(parentGroup, node, yOffset, styles = []) {\n const textEl = parentGroup.insert(\"g\").attr(\"class\", \"label\").attr(\"style\", styles.join(\"; \"));\n const config = getConfig();\n let useHtmlLabels = \"useHtmlLabels\" in node ? node.useHtmlLabels : evaluate(config.htmlLabels) ?? true;\n let textContent = \"\";\n if (\"text\" in node) {\n textContent = node.text;\n } else {\n textContent = node.label;\n }\n if (!useHtmlLabels && textContent.startsWith(\"\\\\\")) {\n textContent = textContent.substring(1);\n }\n if (hasKatex(textContent)) {\n useHtmlLabels = true;\n }\n const text2 = await createText(\n textEl,\n sanitizeText2(decodeEntities(textContent)),\n {\n width: calculateTextWidth(textContent, config) + 50,\n // Add room for error when splitting text into multiple lines\n classes: \"markdown-node-label\",\n useHtmlLabels\n },\n config\n );\n let bbox;\n let numberOfLines = 1;\n if (!useHtmlLabels) {\n if (styles.includes(\"font-weight: bolder\")) {\n select6(text2).selectAll(\"tspan\").attr(\"font-weight\", \"\");\n }\n numberOfLines = text2.children.length;\n const textChild = text2.children[0];\n if (text2.textContent === \"\" || text2.textContent.includes(\">\")) {\n textChild.textContent = textContent[0] + textContent.substring(1).replaceAll(\">\", \">\").replaceAll(\"<\", \"<\").trim();\n const preserveSpace = textContent[1] === \" \";\n if (preserveSpace) {\n textChild.textContent = textChild.textContent[0] + \" \" + textChild.textContent.substring(1);\n }\n }\n if (textChild.textContent === \"undefined\") {\n textChild.textContent = \"\";\n }\n bbox = text2.getBBox();\n } else {\n const div = text2.children[0];\n const dv = select6(text2);\n numberOfLines = div.innerHTML.split(\"
\").length;\n if (div.innerHTML.includes(\"\")) {\n numberOfLines += div.innerHTML.split(\"\").length - 1;\n }\n const images = div.getElementsByTagName(\"img\");\n if (images) {\n const noImgText = textContent.replace(/]*>/g, \"\").trim() === \"\";\n await Promise.all(\n [...images].map(\n (img) => new Promise((res) => {\n function setupImage() {\n img.style.display = \"flex\";\n img.style.flexDirection = \"column\";\n if (noImgText) {\n const bodyFontSize = config.fontSize?.toString() ?? window.getComputedStyle(document.body).fontSize;\n const enlargingFactor = 5;\n const width = parseInt(bodyFontSize, 10) * enlargingFactor + \"px\";\n img.style.minWidth = width;\n img.style.maxWidth = width;\n } else {\n img.style.width = \"100%\";\n }\n res(img);\n }\n __name(setupImage, \"setupImage\");\n setTimeout(() => {\n if (img.complete) {\n setupImage();\n }\n });\n img.addEventListener(\"error\", setupImage);\n img.addEventListener(\"load\", setupImage);\n })\n )\n );\n }\n bbox = div.getBoundingClientRect();\n dv.attr(\"width\", bbox.width);\n dv.attr(\"height\", bbox.height);\n }\n textEl.attr(\"transform\", \"translate(0,\" + (-bbox.height / (2 * numberOfLines) + yOffset) + \")\");\n return bbox.height;\n}\n__name(addText2, \"addText\");\n\n// src/rendering-util/rendering-elements/shapes/classBox.ts\nasync function classBox(parent, node) {\n const config = getConfig2();\n const PADDING = config.class.padding ?? 12;\n const GAP = PADDING;\n const useHtmlLabels = node.useHtmlLabels ?? evaluate(config.htmlLabels) ?? true;\n const classNode = node;\n classNode.annotations = classNode.annotations ?? [];\n classNode.members = classNode.members ?? [];\n classNode.methods = classNode.methods ?? [];\n const { shapeSvg, bbox } = await textHelper(parent, node, config, useHtmlLabels, GAP);\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n node.cssStyles = classNode.styles || \"\";\n const styles = classNode.styles?.join(\";\") || nodeStyles || \"\";\n if (!node.cssStyles) {\n node.cssStyles = styles.replaceAll(\"!important\", \"\").split(\";\");\n }\n const renderExtraBox = classNode.members.length === 0 && classNode.methods.length === 0 && !config.class?.hideEmptyMembersBox;\n const rc = rough56.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const w = bbox.width;\n let h = bbox.height;\n if (classNode.members.length === 0 && classNode.methods.length === 0) {\n h += GAP;\n } else if (classNode.members.length > 0 && classNode.methods.length === 0) {\n h += GAP * 2;\n }\n const x = -w / 2;\n const y = -h / 2;\n const roughRect = rc.rectangle(\n x - PADDING,\n y - PADDING - (renderExtraBox ? PADDING : classNode.members.length === 0 && classNode.methods.length === 0 ? -PADDING / 2 : 0),\n w + 2 * PADDING,\n h + 2 * PADDING + (renderExtraBox ? PADDING * 2 : classNode.members.length === 0 && classNode.methods.length === 0 ? -PADDING : 0),\n options\n );\n const rect2 = shapeSvg.insert(() => roughRect, \":first-child\");\n rect2.attr(\"class\", \"basic label-container\");\n const rectBBox = rect2.node().getBBox();\n shapeSvg.selectAll(\".text\").each((_, i, nodes) => {\n const text2 = select7(nodes[i]);\n const transform = text2.attr(\"transform\");\n let translateY = 0;\n if (transform) {\n const regex = RegExp(/translate\\(([^,]+),([^)]+)\\)/);\n const translate = regex.exec(transform);\n if (translate) {\n translateY = parseFloat(translate[2]);\n }\n }\n let newTranslateY = translateY + y + PADDING - (renderExtraBox ? PADDING : classNode.members.length === 0 && classNode.methods.length === 0 ? -PADDING / 2 : 0);\n if (!useHtmlLabels) {\n newTranslateY -= 4;\n }\n let newTranslateX = x;\n if (text2.attr(\"class\").includes(\"label-group\") || text2.attr(\"class\").includes(\"annotation-group\")) {\n newTranslateX = -text2.node()?.getBBox().width / 2 || 0;\n shapeSvg.selectAll(\"text\").each(function(_2, i2, nodes2) {\n if (window.getComputedStyle(nodes2[i2]).textAnchor === \"middle\") {\n newTranslateX = 0;\n }\n });\n }\n text2.attr(\"transform\", `translate(${newTranslateX}, ${newTranslateY})`);\n });\n const annotationGroupHeight = shapeSvg.select(\".annotation-group\").node().getBBox().height - (renderExtraBox ? PADDING / 2 : 0) || 0;\n const labelGroupHeight = shapeSvg.select(\".label-group\").node().getBBox().height - (renderExtraBox ? PADDING / 2 : 0) || 0;\n const membersGroupHeight = shapeSvg.select(\".members-group\").node().getBBox().height - (renderExtraBox ? PADDING / 2 : 0) || 0;\n if (classNode.members.length > 0 || classNode.methods.length > 0 || renderExtraBox) {\n const roughLine = rc.line(\n rectBBox.x,\n annotationGroupHeight + labelGroupHeight + y + PADDING,\n rectBBox.x + rectBBox.width,\n annotationGroupHeight + labelGroupHeight + y + PADDING,\n options\n );\n const line = shapeSvg.insert(() => roughLine);\n line.attr(\"class\", \"divider\").attr(\"style\", styles);\n }\n if (renderExtraBox || classNode.members.length > 0 || classNode.methods.length > 0) {\n const roughLine = rc.line(\n rectBBox.x,\n annotationGroupHeight + labelGroupHeight + membersGroupHeight + y + GAP * 2 + PADDING,\n rectBBox.x + rectBBox.width,\n annotationGroupHeight + labelGroupHeight + membersGroupHeight + y + PADDING + GAP * 2,\n options\n );\n const line = shapeSvg.insert(() => roughLine);\n line.attr(\"class\", \"divider\").attr(\"style\", styles);\n }\n if (classNode.look !== \"handDrawn\") {\n shapeSvg.selectAll(\"path\").attr(\"style\", styles);\n }\n rect2.select(\":nth-child(2)\").attr(\"style\", styles);\n shapeSvg.selectAll(\".divider\").select(\"path\").attr(\"style\", styles);\n if (node.labelStyle) {\n shapeSvg.selectAll(\"span\").attr(\"style\", node.labelStyle);\n } else {\n shapeSvg.selectAll(\"span\").attr(\"style\", styles);\n }\n if (!useHtmlLabels) {\n const colorRegex = RegExp(/color\\s*:\\s*([^;]*)/);\n const match = colorRegex.exec(styles);\n if (match) {\n const colorStyle = match[0].replace(\"color\", \"fill\");\n shapeSvg.selectAll(\"tspan\").attr(\"style\", colorStyle);\n } else if (labelStyles) {\n const match2 = colorRegex.exec(labelStyles);\n if (match2) {\n const colorStyle = match2[0].replace(\"color\", \"fill\");\n shapeSvg.selectAll(\"tspan\").attr(\"style\", colorStyle);\n }\n }\n }\n updateNodeBounds(node, rect2);\n node.intersect = function(point) {\n return intersect_default.rect(node, point);\n };\n return shapeSvg;\n}\n__name(classBox, \"classBox\");\n\n// src/rendering-util/rendering-elements/shapes/requirementBox.ts\nimport rough57 from \"roughjs\";\nimport { select as select8 } from \"d3\";\nasync function requirementBox(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const requirementNode = node;\n const elementNode = node;\n const padding = 20;\n const gap = 20;\n const isRequirementNode = \"verifyMethod\" in node;\n const classes = getNodeClasses(node);\n const shapeSvg = parent.insert(\"g\").attr(\"class\", classes).attr(\"id\", node.domId ?? node.id);\n let typeHeight;\n if (isRequirementNode) {\n typeHeight = await addText3(\n shapeSvg,\n `<<${requirementNode.type}>>`,\n 0,\n node.labelStyle\n );\n } else {\n typeHeight = await addText3(shapeSvg, \"<<Element>>\", 0, node.labelStyle);\n }\n let accumulativeHeight = typeHeight;\n const nameHeight = await addText3(\n shapeSvg,\n requirementNode.name,\n accumulativeHeight,\n node.labelStyle + \"; font-weight: bold;\"\n );\n accumulativeHeight += nameHeight + gap;\n if (isRequirementNode) {\n const idHeight = await addText3(\n shapeSvg,\n `${requirementNode.requirementId ? `ID: ${requirementNode.requirementId}` : \"\"}`,\n accumulativeHeight,\n node.labelStyle\n );\n accumulativeHeight += idHeight;\n const textHeight = await addText3(\n shapeSvg,\n `${requirementNode.text ? `Text: ${requirementNode.text}` : \"\"}`,\n accumulativeHeight,\n node.labelStyle\n );\n accumulativeHeight += textHeight;\n const riskHeight = await addText3(\n shapeSvg,\n `${requirementNode.risk ? `Risk: ${requirementNode.risk}` : \"\"}`,\n accumulativeHeight,\n node.labelStyle\n );\n accumulativeHeight += riskHeight;\n await addText3(\n shapeSvg,\n `${requirementNode.verifyMethod ? `Verification: ${requirementNode.verifyMethod}` : \"\"}`,\n accumulativeHeight,\n node.labelStyle\n );\n } else {\n const typeHeight2 = await addText3(\n shapeSvg,\n `${elementNode.type ? `Type: ${elementNode.type}` : \"\"}`,\n accumulativeHeight,\n node.labelStyle\n );\n accumulativeHeight += typeHeight2;\n await addText3(\n shapeSvg,\n `${elementNode.docRef ? `Doc Ref: ${elementNode.docRef}` : \"\"}`,\n accumulativeHeight,\n node.labelStyle\n );\n }\n const totalWidth = (shapeSvg.node()?.getBBox().width ?? 200) + padding;\n const totalHeight = (shapeSvg.node()?.getBBox().height ?? 200) + padding;\n const x = -totalWidth / 2;\n const y = -totalHeight / 2;\n const rc = rough57.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n if (node.look !== \"handDrawn\") {\n options.roughness = 0;\n options.fillStyle = \"solid\";\n }\n const roughRect = rc.rectangle(x, y, totalWidth, totalHeight, options);\n const rect2 = shapeSvg.insert(() => roughRect, \":first-child\");\n rect2.attr(\"class\", \"basic label-container\").attr(\"style\", nodeStyles);\n shapeSvg.selectAll(\".label\").each((_, i, nodes) => {\n const text2 = select8(nodes[i]);\n const transform = text2.attr(\"transform\");\n let translateX = 0;\n let translateY = 0;\n if (transform) {\n const regex = RegExp(/translate\\(([^,]+),([^)]+)\\)/);\n const translate = regex.exec(transform);\n if (translate) {\n translateX = parseFloat(translate[1]);\n translateY = parseFloat(translate[2]);\n }\n }\n const newTranslateY = translateY - totalHeight / 2;\n let newTranslateX = x + padding / 2;\n if (i === 0 || i === 1) {\n newTranslateX = translateX;\n }\n text2.attr(\"transform\", `translate(${newTranslateX}, ${newTranslateY + padding})`);\n });\n if (accumulativeHeight > typeHeight + nameHeight + gap) {\n const roughLine = rc.line(\n x,\n y + typeHeight + nameHeight + gap,\n x + totalWidth,\n y + typeHeight + nameHeight + gap,\n options\n );\n const dividerLine = shapeSvg.insert(() => roughLine);\n dividerLine.attr(\"style\", nodeStyles);\n }\n updateNodeBounds(node, rect2);\n node.intersect = function(point) {\n return intersect_default.rect(node, point);\n };\n return shapeSvg;\n}\n__name(requirementBox, \"requirementBox\");\nasync function addText3(parentGroup, inputText, yOffset, style = \"\") {\n if (inputText === \"\") {\n return 0;\n }\n const textEl = parentGroup.insert(\"g\").attr(\"class\", \"label\").attr(\"style\", style);\n const config = getConfig2();\n const useHtmlLabels = config.htmlLabels ?? true;\n const text2 = await createText(\n textEl,\n sanitizeText2(decodeEntities(inputText)),\n {\n width: calculateTextWidth(inputText, config) + 50,\n // Add room for error when splitting text into multiple lines\n classes: \"markdown-node-label\",\n useHtmlLabels,\n style\n },\n config\n );\n let bbox;\n if (!useHtmlLabels) {\n const textChild = text2.children[0];\n for (const child of textChild.children) {\n child.textContent = child.textContent.replaceAll(\">\", \">\").replaceAll(\"<\", \"<\");\n if (style) {\n child.setAttribute(\"style\", style);\n }\n }\n bbox = text2.getBBox();\n bbox.height += 6;\n } else {\n const div = text2.children[0];\n const dv = select8(text2);\n bbox = div.getBoundingClientRect();\n dv.attr(\"width\", bbox.width);\n dv.attr(\"height\", bbox.height);\n }\n textEl.attr(\"transform\", `translate(${-bbox.width / 2},${-bbox.height / 2 + yOffset})`);\n return bbox.height;\n}\n__name(addText3, \"addText\");\n\n// src/rendering-util/rendering-elements/shapes/kanbanItem.ts\nimport rough58 from \"roughjs\";\nvar colorFromPriority = /* @__PURE__ */ __name((priority) => {\n switch (priority) {\n case \"Very High\":\n return \"red\";\n case \"High\":\n return \"orange\";\n case \"Medium\":\n return null;\n // no stroke\n case \"Low\":\n return \"blue\";\n case \"Very Low\":\n return \"lightblue\";\n }\n}, \"colorFromPriority\");\nasync function kanbanItem(parent, kanbanNode, { config }) {\n const { labelStyles, nodeStyles } = styles2String(kanbanNode);\n kanbanNode.labelStyle = labelStyles || \"\";\n const labelPaddingX = 10;\n const orgWidth = kanbanNode.width;\n kanbanNode.width = (kanbanNode.width ?? 200) - 10;\n const {\n shapeSvg,\n bbox,\n label: labelElTitle\n } = await labelHelper(parent, kanbanNode, getNodeClasses(kanbanNode));\n const padding = kanbanNode.padding || 10;\n let ticketUrl = \"\";\n let link;\n if (\"ticket\" in kanbanNode && kanbanNode.ticket && config?.kanban?.ticketBaseUrl) {\n ticketUrl = config?.kanban?.ticketBaseUrl.replace(\"#TICKET#\", kanbanNode.ticket);\n link = shapeSvg.insert(\"svg:a\", \":first-child\").attr(\"class\", \"kanban-ticket-link\").attr(\"xlink:href\", ticketUrl).attr(\"target\", \"_blank\");\n }\n const options = {\n useHtmlLabels: kanbanNode.useHtmlLabels,\n labelStyle: kanbanNode.labelStyle || \"\",\n width: kanbanNode.width,\n img: kanbanNode.img,\n padding: kanbanNode.padding || 8,\n centerLabel: false\n };\n let labelEl, bbox2;\n if (link) {\n ({ label: labelEl, bbox: bbox2 } = await insertLabel(\n link,\n \"ticket\" in kanbanNode && kanbanNode.ticket || \"\",\n options\n ));\n } else {\n ({ label: labelEl, bbox: bbox2 } = await insertLabel(\n shapeSvg,\n \"ticket\" in kanbanNode && kanbanNode.ticket || \"\",\n options\n ));\n }\n const { label: labelElAssigned, bbox: bboxAssigned } = await insertLabel(\n shapeSvg,\n \"assigned\" in kanbanNode && kanbanNode.assigned || \"\",\n options\n );\n kanbanNode.width = orgWidth;\n const labelPaddingY = 10;\n const totalWidth = kanbanNode?.width || 0;\n const heightAdj = Math.max(bbox2.height, bboxAssigned.height) / 2;\n const totalHeight = Math.max(bbox.height + labelPaddingY * 2, kanbanNode?.height || 0) + heightAdj;\n const x = -totalWidth / 2;\n const y = -totalHeight / 2;\n labelElTitle.attr(\n \"transform\",\n \"translate(\" + (padding - totalWidth / 2) + \", \" + (-heightAdj - bbox.height / 2) + \")\"\n );\n labelEl.attr(\n \"transform\",\n \"translate(\" + (padding - totalWidth / 2) + \", \" + (-heightAdj + bbox.height / 2) + \")\"\n );\n labelElAssigned.attr(\n \"transform\",\n \"translate(\" + (padding + totalWidth / 2 - bboxAssigned.width - 2 * labelPaddingX) + \", \" + (-heightAdj + bbox.height / 2) + \")\"\n );\n let rect2;\n const { rx, ry } = kanbanNode;\n const { cssStyles } = kanbanNode;\n if (kanbanNode.look === \"handDrawn\") {\n const rc = rough58.svg(shapeSvg);\n const options2 = userNodeOverrides(kanbanNode, {});\n const roughNode = rx || ry ? rc.path(createRoundedRectPathD(x, y, totalWidth, totalHeight, rx || 0), options2) : rc.rectangle(x, y, totalWidth, totalHeight, options2);\n rect2 = shapeSvg.insert(() => roughNode, \":first-child\");\n rect2.attr(\"class\", \"basic label-container\").attr(\"style\", cssStyles ? cssStyles : null);\n } else {\n rect2 = shapeSvg.insert(\"rect\", \":first-child\");\n rect2.attr(\"class\", \"basic label-container __APA__\").attr(\"style\", nodeStyles).attr(\"rx\", rx ?? 5).attr(\"ry\", ry ?? 5).attr(\"x\", x).attr(\"y\", y).attr(\"width\", totalWidth).attr(\"height\", totalHeight);\n const priority = \"priority\" in kanbanNode && kanbanNode.priority;\n if (priority) {\n const line = shapeSvg.append(\"line\");\n const lineX = x + 2;\n const y1 = y + Math.floor((rx ?? 0) / 2);\n const y2 = y + totalHeight - Math.floor((rx ?? 0) / 2);\n line.attr(\"x1\", lineX).attr(\"y1\", y1).attr(\"x2\", lineX).attr(\"y2\", y2).attr(\"stroke-width\", \"4\").attr(\"stroke\", colorFromPriority(priority));\n }\n }\n updateNodeBounds(kanbanNode, rect2);\n kanbanNode.height = totalHeight;\n kanbanNode.intersect = function(point) {\n return intersect_default.rect(kanbanNode, point);\n };\n return shapeSvg;\n}\n__name(kanbanItem, \"kanbanItem\");\n\n// src/rendering-util/rendering-elements/shapes/bang.ts\nimport rough59 from \"roughjs\";\nasync function bang(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, halfPadding, label } = await labelHelper(\n parent,\n node,\n getNodeClasses(node)\n );\n const w = bbox.width + 10 * halfPadding;\n const h = bbox.height + 8 * halfPadding;\n const r = 0.15 * w;\n const { cssStyles } = node;\n const minWidth = bbox.width + 20;\n const minHeight = bbox.height + 20;\n const effectiveWidth = Math.max(w, minWidth);\n const effectiveHeight = Math.max(h, minHeight);\n label.attr(\"transform\", `translate(${-bbox.width / 2}, ${-bbox.height / 2})`);\n let bangElem;\n const path = `M0 0 \n a${r},${r} 1 0,0 ${effectiveWidth * 0.25},${-1 * effectiveHeight * 0.1}\n a${r},${r} 1 0,0 ${effectiveWidth * 0.25},${0}\n a${r},${r} 1 0,0 ${effectiveWidth * 0.25},${0}\n a${r},${r} 1 0,0 ${effectiveWidth * 0.25},${effectiveHeight * 0.1}\n\n a${r},${r} 1 0,0 ${effectiveWidth * 0.15},${effectiveHeight * 0.33}\n a${r * 0.8},${r * 0.8} 1 0,0 0,${effectiveHeight * 0.34}\n a${r},${r} 1 0,0 ${-1 * effectiveWidth * 0.15},${effectiveHeight * 0.33}\n\n a${r},${r} 1 0,0 ${-1 * effectiveWidth * 0.25},${effectiveHeight * 0.15}\n a${r},${r} 1 0,0 ${-1 * effectiveWidth * 0.25},0\n a${r},${r} 1 0,0 ${-1 * effectiveWidth * 0.25},0\n a${r},${r} 1 0,0 ${-1 * effectiveWidth * 0.25},${-1 * effectiveHeight * 0.15}\n\n a${r},${r} 1 0,0 ${-1 * effectiveWidth * 0.1},${-1 * effectiveHeight * 0.33}\n a${r * 0.8},${r * 0.8} 1 0,0 0,${-1 * effectiveHeight * 0.34}\n a${r},${r} 1 0,0 ${effectiveWidth * 0.1},${-1 * effectiveHeight * 0.33}\n H0 V0 Z`;\n if (node.look === \"handDrawn\") {\n const rc = rough59.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n const roughNode = rc.path(path, options);\n bangElem = shapeSvg.insert(() => roughNode, \":first-child\");\n bangElem.attr(\"class\", \"basic label-container\").attr(\"style\", handleUndefinedAttr(cssStyles));\n } else {\n bangElem = shapeSvg.insert(\"path\", \":first-child\").attr(\"class\", \"basic label-container\").attr(\"style\", nodeStyles).attr(\"d\", path);\n }\n bangElem.attr(\"transform\", `translate(${-effectiveWidth / 2}, ${-effectiveHeight / 2})`);\n updateNodeBounds(node, bangElem);\n node.calcIntersect = function(bounds, point) {\n return intersect_default.rect(bounds, point);\n };\n node.intersect = function(point) {\n log.info(\"Bang intersect\", node, point);\n return intersect_default.rect(node, point);\n };\n return shapeSvg;\n}\n__name(bang, \"bang\");\n\n// src/rendering-util/rendering-elements/shapes/cloud.ts\nimport rough60 from \"roughjs\";\nasync function cloud(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, halfPadding, label } = await labelHelper(\n parent,\n node,\n getNodeClasses(node)\n );\n const w = bbox.width + 2 * halfPadding;\n const h = bbox.height + 2 * halfPadding;\n const r1 = 0.15 * w;\n const r2 = 0.25 * w;\n const r3 = 0.35 * w;\n const r4 = 0.2 * w;\n const { cssStyles } = node;\n let cloudElem;\n const path = `M0 0 \n a${r1},${r1} 0 0,1 ${w * 0.25},${-1 * w * 0.1}\n a${r3},${r3} 1 0,1 ${w * 0.4},${-1 * w * 0.1}\n a${r2},${r2} 1 0,1 ${w * 0.35},${w * 0.2}\n\n a${r1},${r1} 1 0,1 ${w * 0.15},${h * 0.35}\n a${r4},${r4} 1 0,1 ${-1 * w * 0.15},${h * 0.65}\n\n a${r2},${r1} 1 0,1 ${-1 * w * 0.25},${w * 0.15}\n a${r3},${r3} 1 0,1 ${-1 * w * 0.5},0\n a${r1},${r1} 1 0,1 ${-1 * w * 0.25},${-1 * w * 0.15}\n\n a${r1},${r1} 1 0,1 ${-1 * w * 0.1},${-1 * h * 0.35}\n a${r4},${r4} 1 0,1 ${w * 0.1},${-1 * h * 0.65}\n H0 V0 Z`;\n if (node.look === \"handDrawn\") {\n const rc = rough60.svg(shapeSvg);\n const options = userNodeOverrides(node, {});\n const roughNode = rc.path(path, options);\n cloudElem = shapeSvg.insert(() => roughNode, \":first-child\");\n cloudElem.attr(\"class\", \"basic label-container\").attr(\"style\", handleUndefinedAttr(cssStyles));\n } else {\n cloudElem = shapeSvg.insert(\"path\", \":first-child\").attr(\"class\", \"basic label-container\").attr(\"style\", nodeStyles).attr(\"d\", path);\n }\n label.attr(\"transform\", `translate(${-bbox.width / 2}, ${-bbox.height / 2})`);\n cloudElem.attr(\"transform\", `translate(${-w / 2}, ${-h / 2})`);\n updateNodeBounds(node, cloudElem);\n node.calcIntersect = function(bounds, point) {\n return intersect_default.rect(bounds, point);\n };\n node.intersect = function(point) {\n log.info(\"Cloud intersect\", node, point);\n return intersect_default.rect(node, point);\n };\n return shapeSvg;\n}\n__name(cloud, \"cloud\");\n\n// src/rendering-util/rendering-elements/shapes/defaultMindmapNode.ts\nasync function defaultMindmapNode(parent, node) {\n const { labelStyles, nodeStyles } = styles2String(node);\n node.labelStyle = labelStyles;\n const { shapeSvg, bbox, halfPadding, label } = await labelHelper(\n parent,\n node,\n getNodeClasses(node)\n );\n const w = bbox.width + 8 * halfPadding;\n const h = bbox.height + 2 * halfPadding;\n const rd = 5;\n const rectPath = `\n M${-w / 2} ${h / 2 - rd}\n v${-h + 2 * rd}\n q0,-${rd} ${rd},-${rd}\n h${w - 2 * rd}\n q${rd},0 ${rd},${rd}\n v${h - 2 * rd}\n q0,${rd} -${rd},${rd}\n h${-w + 2 * rd}\n q-${rd},0 -${rd},-${rd}\n Z\n `;\n const bg = shapeSvg.append(\"path\").attr(\"id\", \"node-\" + node.id).attr(\"class\", \"node-bkg node-\" + node.type).attr(\"style\", nodeStyles).attr(\"d\", rectPath);\n shapeSvg.append(\"line\").attr(\"class\", \"node-line-\").attr(\"x1\", -w / 2).attr(\"y1\", h / 2).attr(\"x2\", w / 2).attr(\"y2\", h / 2);\n label.attr(\"transform\", `translate(${-bbox.width / 2}, ${-bbox.height / 2})`);\n shapeSvg.append(() => label.node());\n updateNodeBounds(node, bg);\n node.calcIntersect = function(bounds, point) {\n return intersect_default.rect(bounds, point);\n };\n node.intersect = function(point) {\n return intersect_default.rect(node, point);\n };\n return shapeSvg;\n}\n__name(defaultMindmapNode, \"defaultMindmapNode\");\n\n// src/rendering-util/rendering-elements/shapes/mindmapCircle.ts\nasync function mindmapCircle(parent, node) {\n const options = {\n padding: node.padding ?? 0\n };\n return circle(parent, node, options);\n}\n__name(mindmapCircle, \"mindmapCircle\");\n\n// src/rendering-util/rendering-elements/shapes.ts\nvar shapesDefs = [\n {\n semanticName: \"Process\",\n name: \"Rectangle\",\n shortName: \"rect\",\n description: \"Standard process shape\",\n aliases: [\"proc\", \"process\", \"rectangle\"],\n internalAliases: [\"squareRect\"],\n handler: squareRect2\n },\n {\n semanticName: \"Event\",\n name: \"Rounded Rectangle\",\n shortName: \"rounded\",\n description: \"Represents an event\",\n aliases: [\"event\"],\n internalAliases: [\"roundedRect\"],\n handler: roundedRect\n },\n {\n semanticName: \"Terminal Point\",\n name: \"Stadium\",\n shortName: \"stadium\",\n description: \"Terminal point\",\n aliases: [\"terminal\", \"pill\"],\n handler: stadium\n },\n {\n semanticName: \"Subprocess\",\n name: \"Framed Rectangle\",\n shortName: \"fr-rect\",\n description: \"Subprocess\",\n aliases: [\"subprocess\", \"subproc\", \"framed-rectangle\", \"subroutine\"],\n handler: subroutine\n },\n {\n semanticName: \"Database\",\n name: \"Cylinder\",\n shortName: \"cyl\",\n description: \"Database storage\",\n aliases: [\"db\", \"database\", \"cylinder\"],\n handler: cylinder\n },\n {\n semanticName: \"Start\",\n name: \"Circle\",\n shortName: \"circle\",\n description: \"Starting point\",\n aliases: [\"circ\"],\n handler: circle\n },\n {\n semanticName: \"Bang\",\n name: \"Bang\",\n shortName: \"bang\",\n description: \"Bang\",\n aliases: [\"bang\"],\n handler: bang\n },\n {\n semanticName: \"Cloud\",\n name: \"Cloud\",\n shortName: \"cloud\",\n description: \"cloud\",\n aliases: [\"cloud\"],\n handler: cloud\n },\n {\n semanticName: \"Decision\",\n name: \"Diamond\",\n shortName: \"diam\",\n description: \"Decision-making step\",\n aliases: [\"decision\", \"diamond\", \"question\"],\n handler: question\n },\n {\n semanticName: \"Prepare Conditional\",\n name: \"Hexagon\",\n shortName: \"hex\",\n description: \"Preparation or condition step\",\n aliases: [\"hexagon\", \"prepare\"],\n handler: hexagon\n },\n {\n semanticName: \"Data Input/Output\",\n name: \"Lean Right\",\n shortName: \"lean-r\",\n description: \"Represents input or output\",\n aliases: [\"lean-right\", \"in-out\"],\n internalAliases: [\"lean_right\"],\n handler: lean_right\n },\n {\n semanticName: \"Data Input/Output\",\n name: \"Lean Left\",\n shortName: \"lean-l\",\n description: \"Represents output or input\",\n aliases: [\"lean-left\", \"out-in\"],\n internalAliases: [\"lean_left\"],\n handler: lean_left\n },\n {\n semanticName: \"Priority Action\",\n name: \"Trapezoid Base Bottom\",\n shortName: \"trap-b\",\n description: \"Priority action\",\n aliases: [\"priority\", \"trapezoid-bottom\", \"trapezoid\"],\n handler: trapezoid\n },\n {\n semanticName: \"Manual Operation\",\n name: \"Trapezoid Base Top\",\n shortName: \"trap-t\",\n description: \"Represents a manual task\",\n aliases: [\"manual\", \"trapezoid-top\", \"inv-trapezoid\"],\n internalAliases: [\"inv_trapezoid\"],\n handler: inv_trapezoid\n },\n {\n semanticName: \"Stop\",\n name: \"Double Circle\",\n shortName: \"dbl-circ\",\n description: \"Represents a stop point\",\n aliases: [\"double-circle\"],\n internalAliases: [\"doublecircle\"],\n handler: doublecircle\n },\n {\n semanticName: \"Text Block\",\n name: \"Text Block\",\n shortName: \"text\",\n description: \"Text block\",\n handler: text\n },\n {\n semanticName: \"Card\",\n name: \"Notched Rectangle\",\n shortName: \"notch-rect\",\n description: \"Represents a card\",\n aliases: [\"card\", \"notched-rectangle\"],\n handler: card\n },\n {\n semanticName: \"Lined/Shaded Process\",\n name: \"Lined Rectangle\",\n shortName: \"lin-rect\",\n description: \"Lined process shape\",\n aliases: [\"lined-rectangle\", \"lined-process\", \"lin-proc\", \"shaded-process\"],\n handler: shadedProcess\n },\n {\n semanticName: \"Start\",\n name: \"Small Circle\",\n shortName: \"sm-circ\",\n description: \"Small starting point\",\n aliases: [\"start\", \"small-circle\"],\n internalAliases: [\"stateStart\"],\n handler: stateStart\n },\n {\n semanticName: \"Stop\",\n name: \"Framed Circle\",\n shortName: \"fr-circ\",\n description: \"Stop point\",\n aliases: [\"stop\", \"framed-circle\"],\n internalAliases: [\"stateEnd\"],\n handler: stateEnd\n },\n {\n semanticName: \"Fork/Join\",\n name: \"Filled Rectangle\",\n shortName: \"fork\",\n description: \"Fork or join in process flow\",\n aliases: [\"join\"],\n internalAliases: [\"forkJoin\"],\n handler: forkJoin\n },\n {\n semanticName: \"Collate\",\n name: \"Hourglass\",\n shortName: \"hourglass\",\n description: \"Represents a collate operation\",\n aliases: [\"hourglass\", \"collate\"],\n handler: hourglass\n },\n {\n semanticName: \"Comment\",\n name: \"Curly Brace\",\n shortName: \"brace\",\n description: \"Adds a comment\",\n aliases: [\"comment\", \"brace-l\"],\n handler: curlyBraceLeft\n },\n {\n semanticName: \"Comment Right\",\n name: \"Curly Brace\",\n shortName: \"brace-r\",\n description: \"Adds a comment\",\n handler: curlyBraceRight\n },\n {\n semanticName: \"Comment with braces on both sides\",\n name: \"Curly Braces\",\n shortName: \"braces\",\n description: \"Adds a comment\",\n handler: curlyBraces\n },\n {\n semanticName: \"Com Link\",\n name: \"Lightning Bolt\",\n shortName: \"bolt\",\n description: \"Communication link\",\n aliases: [\"com-link\", \"lightning-bolt\"],\n handler: lightningBolt\n },\n {\n semanticName: \"Document\",\n name: \"Document\",\n shortName: \"doc\",\n description: \"Represents a document\",\n aliases: [\"doc\", \"document\"],\n handler: waveEdgedRectangle\n },\n {\n semanticName: \"Delay\",\n name: \"Half-Rounded Rectangle\",\n shortName: \"delay\",\n description: \"Represents a delay\",\n aliases: [\"half-rounded-rectangle\"],\n handler: halfRoundedRectangle\n },\n {\n semanticName: \"Direct Access Storage\",\n name: \"Horizontal Cylinder\",\n shortName: \"h-cyl\",\n description: \"Direct access storage\",\n aliases: [\"das\", \"horizontal-cylinder\"],\n handler: tiltedCylinder\n },\n {\n semanticName: \"Disk Storage\",\n name: \"Lined Cylinder\",\n shortName: \"lin-cyl\",\n description: \"Disk storage\",\n aliases: [\"disk\", \"lined-cylinder\"],\n handler: linedCylinder\n },\n {\n semanticName: \"Display\",\n name: \"Curved Trapezoid\",\n shortName: \"curv-trap\",\n description: \"Represents a display\",\n aliases: [\"curved-trapezoid\", \"display\"],\n handler: curvedTrapezoid\n },\n {\n semanticName: \"Divided Process\",\n name: \"Divided Rectangle\",\n shortName: \"div-rect\",\n description: \"Divided process shape\",\n aliases: [\"div-proc\", \"divided-rectangle\", \"divided-process\"],\n handler: dividedRectangle\n },\n {\n semanticName: \"Extract\",\n name: \"Triangle\",\n shortName: \"tri\",\n description: \"Extraction process\",\n aliases: [\"extract\", \"triangle\"],\n handler: triangle\n },\n {\n semanticName: \"Internal Storage\",\n name: \"Window Pane\",\n shortName: \"win-pane\",\n description: \"Internal storage\",\n aliases: [\"internal-storage\", \"window-pane\"],\n handler: windowPane\n },\n {\n semanticName: \"Junction\",\n name: \"Filled Circle\",\n shortName: \"f-circ\",\n description: \"Junction point\",\n aliases: [\"junction\", \"filled-circle\"],\n handler: filledCircle\n },\n {\n semanticName: \"Loop Limit\",\n name: \"Trapezoidal Pentagon\",\n shortName: \"notch-pent\",\n description: \"Loop limit step\",\n aliases: [\"loop-limit\", \"notched-pentagon\"],\n handler: trapezoidalPentagon\n },\n {\n semanticName: \"Manual File\",\n name: \"Flipped Triangle\",\n shortName: \"flip-tri\",\n description: \"Manual file operation\",\n aliases: [\"manual-file\", \"flipped-triangle\"],\n handler: flippedTriangle\n },\n {\n semanticName: \"Manual Input\",\n name: \"Sloped Rectangle\",\n shortName: \"sl-rect\",\n description: \"Manual input step\",\n aliases: [\"manual-input\", \"sloped-rectangle\"],\n handler: slopedRect\n },\n {\n semanticName: \"Multi-Document\",\n name: \"Stacked Document\",\n shortName: \"docs\",\n description: \"Multiple documents\",\n aliases: [\"documents\", \"st-doc\", \"stacked-document\"],\n handler: multiWaveEdgedRectangle\n },\n {\n semanticName: \"Multi-Process\",\n name: \"Stacked Rectangle\",\n shortName: \"st-rect\",\n description: \"Multiple processes\",\n aliases: [\"procs\", \"processes\", \"stacked-rectangle\"],\n handler: multiRect\n },\n {\n semanticName: \"Stored Data\",\n name: \"Bow Tie Rectangle\",\n shortName: \"bow-rect\",\n description: \"Stored data\",\n aliases: [\"stored-data\", \"bow-tie-rectangle\"],\n handler: bowTieRect\n },\n {\n semanticName: \"Summary\",\n name: \"Crossed Circle\",\n shortName: \"cross-circ\",\n description: \"Summary\",\n aliases: [\"summary\", \"crossed-circle\"],\n handler: crossedCircle\n },\n {\n semanticName: \"Tagged Document\",\n name: \"Tagged Document\",\n shortName: \"tag-doc\",\n description: \"Tagged document\",\n aliases: [\"tag-doc\", \"tagged-document\"],\n handler: taggedWaveEdgedRectangle\n },\n {\n semanticName: \"Tagged Process\",\n name: \"Tagged Rectangle\",\n shortName: \"tag-rect\",\n description: \"Tagged process\",\n aliases: [\"tagged-rectangle\", \"tag-proc\", \"tagged-process\"],\n handler: taggedRect\n },\n {\n semanticName: \"Paper Tape\",\n name: \"Flag\",\n shortName: \"flag\",\n description: \"Paper tape\",\n aliases: [\"paper-tape\"],\n handler: waveRectangle\n },\n {\n semanticName: \"Odd\",\n name: \"Odd\",\n shortName: \"odd\",\n description: \"Odd shape\",\n internalAliases: [\"rect_left_inv_arrow\"],\n handler: rect_left_inv_arrow\n },\n {\n semanticName: \"Lined Document\",\n name: \"Lined Document\",\n shortName: \"lin-doc\",\n description: \"Lined document\",\n aliases: [\"lined-document\"],\n handler: linedWaveEdgedRect\n }\n];\nvar generateShapeMap = /* @__PURE__ */ __name(() => {\n const undocumentedShapes = {\n // States\n state,\n choice,\n note,\n // Rectangles\n rectWithTitle,\n labelRect,\n // Icons\n iconSquare,\n iconCircle,\n icon,\n iconRounded,\n imageSquare,\n anchor,\n // Kanban diagram\n kanbanItem,\n //Mindmap diagram\n mindmapCircle,\n defaultMindmapNode,\n // class diagram\n classBox,\n // er diagram\n erBox,\n // Requirement diagram\n requirementBox\n };\n const entries = [\n ...Object.entries(undocumentedShapes),\n ...shapesDefs.flatMap((shape) => {\n const aliases = [\n shape.shortName,\n ...\"aliases\" in shape ? shape.aliases : [],\n ...\"internalAliases\" in shape ? shape.internalAliases : []\n ];\n return aliases.map((alias) => [alias, shape.handler]);\n })\n ];\n return Object.fromEntries(entries);\n}, \"generateShapeMap\");\nvar shapes2 = generateShapeMap();\nfunction isValidShape(shape) {\n return shape in shapes2;\n}\n__name(isValidShape, \"isValidShape\");\n\n// src/rendering-util/rendering-elements/nodes.ts\nvar nodeElems = /* @__PURE__ */ new Map();\nasync function insertNode(elem, node, renderOptions) {\n let newEl;\n let el;\n if (node.shape === \"rect\") {\n if (node.rx && node.ry) {\n node.shape = \"roundedRect\";\n } else {\n node.shape = \"squareRect\";\n }\n }\n const shapeHandler = node.shape ? shapes2[node.shape] : void 0;\n if (!shapeHandler) {\n throw new Error(`No such shape: ${node.shape}. Please check your syntax.`);\n }\n if (node.link) {\n let target;\n if (renderOptions.config.securityLevel === \"sandbox\") {\n target = \"_top\";\n } else if (node.linkTarget) {\n target = node.linkTarget || \"_blank\";\n }\n newEl = elem.insert(\"svg:a\").attr(\"xlink:href\", node.link).attr(\"target\", target ?? null);\n el = await shapeHandler(newEl, node, renderOptions);\n } else {\n el = await shapeHandler(elem, node, renderOptions);\n newEl = el;\n }\n if (node.tooltip) {\n el.attr(\"title\", node.tooltip);\n }\n nodeElems.set(node.id, newEl);\n if (node.haveCallback) {\n newEl.attr(\"class\", newEl.attr(\"class\") + \" clickable\");\n }\n return newEl;\n}\n__name(insertNode, \"insertNode\");\nvar setNodeElem = /* @__PURE__ */ __name((elem, node) => {\n nodeElems.set(node.id, elem);\n}, \"setNodeElem\");\nvar clear2 = /* @__PURE__ */ __name(() => {\n nodeElems.clear();\n}, \"clear\");\nvar positionNode = /* @__PURE__ */ __name((node) => {\n const el = nodeElems.get(node.id);\n log.trace(\n \"Transforming node\",\n node.diff,\n node,\n \"translate(\" + (node.x - node.width / 2 - 5) + \", \" + node.width / 2 + \")\"\n );\n const padding = 8;\n const diff = node.diff || 0;\n if (node.clusterNode) {\n el.attr(\n \"transform\",\n \"translate(\" + (node.x + diff - node.width / 2) + \", \" + (node.y - node.height / 2 - padding) + \")\"\n );\n } else {\n el.attr(\"transform\", \"translate(\" + node.x + \", \" + node.y + \")\");\n }\n return diff;\n}, \"positionNode\");\n\nexport {\n labelHelper,\n updateNodeBounds,\n createLabel_default,\n isValidShape,\n insertCluster,\n clear,\n insertNode,\n setNodeElem,\n clear2,\n positionNode\n};\n"], + "mappings": "sZAAA,SAASA,GAAEA,EAAEC,EAAEC,EAAE,CAAC,GAAGF,GAAGA,EAAE,OAAO,CAAC,GAAK,CAACG,EAAEC,CAAC,EAAEH,EAAEI,EAAE,KAAK,GAAG,IAAIH,EAAE,EAAE,KAAK,IAAIG,CAAC,EAAEC,EAAE,KAAK,IAAID,CAAC,EAAE,QAAUJ,KAAKD,EAAE,CAAC,GAAK,CAACA,EAAEE,CAAC,EAAED,EAAEA,EAAE,CAAC,GAAGD,EAAEG,GAAG,GAAGD,EAAEE,GAAGE,EAAEH,EAAEF,EAAE,CAAC,GAAGD,EAAEG,GAAGG,GAAGJ,EAAEE,GAAG,EAAEA,CAAC,CAAC,CAAC,CAAC,SAASH,GAAED,EAAEC,EAAE,CAAC,OAAOD,EAAE,CAAC,IAAIC,EAAE,CAAC,GAAGD,EAAE,CAAC,IAAIC,EAAE,CAAC,CAAC,CAAC,SAASC,GAAEA,EAAEC,EAAEC,EAAE,EAAE,EAAE,CAAC,IAAMG,EAAEH,EAAE,EAAE,KAAK,IAAID,EAAE,EAAE,EAAEK,EAAEN,EAAE,CAAC,GAAGA,EAAE,CAAC,EAAE,CAAC,GAAa,OAAOA,EAAE,CAAC,EAAE,CAAC,GAAvB,SAAyB,CAACA,CAAC,EAAEA,EAAEO,EAAE,CAAC,EAAE,CAAC,EAAE,GAAGF,EAAE,QAAUN,KAAKO,EAAER,GAAEC,EAAEQ,EAAEF,CAAC,EAAE,IAAMG,GAAE,SAASV,EAAEE,EAA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K,MAAQ,EAAI,GACzE,EACA,IAAM0H,EAAU,EACVid,EAAO3kB,EAAK,MAAQ,EAC1B,OAAIA,EAAK,YACP8Z,EAAG,KACD,YACA,cAAgB9Z,EAAK,EAAI2kB,EAAO3kB,EAAK,MAAQ,GAAK,MAAQA,EAAK,EAAIA,EAAK,OAAS,EAAI0H,GAAW,GAClG,EAEAoS,EAAG,KAAK,YAAa,aAAe9Z,EAAK,EAAI,KAAOA,EAAK,EAAI,GAAG,EAE3D2kB,CACT,EAAG,cAAc", + "names": ["t", "e", "s", "n", "o", "a", "r", "h", "i", "c", "l", "u", "p", "f", "d", "g", "M", "k", "b", "y", "m", "x", "w", "P", "v", "S", "O", "L", "T", "D", "A", "G", "E", "$", "j", "z", "F", "q", "V", "_", "Z", "I", "C", "W", "R", "Q", "H", "N", "B", "J", "K", "U", "X", "Y", "tt", "et", "st", "nt", "ot", "at", "labelHelper", "__name", "parent", "node", "_classes", "cssClasses", "useHtmlLabels", "evaluate", "getConfig2", "shapeSvg", "labelEl", "handleUndefinedAttr", "label", "text2", "createText", "sanitizeText", "decodeEntities", "bbox", "halfPadding", "div", "dv", "select_default", "images", "noImgText", "img", "res", "setupImage", "bodyFontSize", "enlargingFactor", "parsedBodyFontSize", "defaultConfig_default", "parseFontSize", "width", "insertLabel", "options", "updateNodeBounds", "element", "getNodeClasses", "extra", "createPathFromPoints", "points", "pointStrings", "p", "i", "generateFullSineWavePoints", "x1", "y1", "x2", "y2", "amplitude", "numCycles", "deltaX", "deltaY", "cycleLength", "frequency", "midY", "t", "x", "y", "generateCirclePoints", "centerX", "centerY", "radius", "numPoints", "startAngle", "endAngle", "startAngleRad", "angleStep", "angle", "intersectRect", "point", "dx", "dy", "w", "h", "sx", "sy", "intersect_rect_default", "applyStyle", "dom", "styleFn", "addHtmlLabel", "fo", "config", "hasKatex", "renderKatexSanitized", "common_default", "labelSpan", "createLabel", "_vertexText", "style", "isTitle", "isNode", "vertexText", "log", "svgLabel", "rows", "row", "tspan", "createLabel_default", "createRoundedRectPathD", "totalWidth", "totalHeight", "rect", "siteConfig", "themeVariables", "handDrawnSeed", "clusterBkg", "clusterBorder", "labelStyles", "nodeStyles", "borderStyles", "backgroundStyles", "styles2String", "height", "rect2", "rc", "at", "userNodeOverrides", "roughNode", "subGraphTitleTopMargin", "getSubGraphTitleMargins", "span", "rectBox", "noteGroup", "padding", "roundedWithTitle", "altBackground", "compositeBackground", "compositeTitleBackground", "nodeBorder", "outerRectG", "innerRect", "innerHeight", "innerY", "isAlt", "roughOuterNode", "roughInnerNode", "kanbanSection", "divider", "squareRect", "shapes", "clusterElems", "insertCluster", "elem", "shape", "cluster", "clear", "intersectNode", "intersect_node_default", "intersectEllipse", "rx", "ry", "cx", "cy", "px", "py", "det", "intersect_ellipse_default", "intersectCircle", "intersect_circle_default", "intersectLine", "p1", "p2", "q1", "q2", "a1", "b1", "c1", "r3", "r4", "epsilon", "sameSign", "a2", "b2", "c2", "r1", "r2", "denom", "offset", "num", "intersect_line_default", "intersectPolygon", "polyPoints", "intersections", "minX", "minY", "entry", "left", "top", "intersect", "q", "pdx", "pdy", "distp", "qdx", "qdy", "distq", "intersect_polygon_default", "intersect_default", "anchor", "classes", "cssStyles", "circleElem", "generateArcPoints", "clockwise", "midX", "transformedX", "transformedY", "distance", "scaledCenterDistance", "angleRange", "angle2", "bowTieRect", "bowTieRectPath", "bowTieRectShapePath", "bowTieRectShape", "insertPolygonShape", "d", "card", "right", "bottom", "polygon", "pathData", "choice", "s", "choicePath", "choiceShape", "circle", "options2", "bounds", "radius2", "createLine", "r", "xAxis45", "yAxis45", "lineLength", "pointQ1", "pointQ2", "pointQ3", "pointQ4", "crossedCircle", "circleNode", "linePath", "lineNode", "crossedCircle2", "generateCirclePoints2", "curlyBraceLeft", "rectPoints", "newCurlyBracePath", "curlyBraceLeftNode", "rectPath", "rectShape", "curlyBraceLeftShape", "generateCirclePoints3", "curlyBraceRight", "curlyBraceRightNode", "curlyBraceRightShape", "generateCirclePoints4", "curlyBraces", "leftCurlyBracePoints", "rightCurlyBracePoints", "newLeftCurlyBracePath", "leftCurlyBraceNode", "newRightCurlyBracePath", "rightCurlyBraceNode", "curlyBracesShape", "curvedTrapezoid", "minWidth", "minHeight", "rw", "tw", "shapeNode", "createCylinderPathD", "createOuterCylinderPathD", "createInnerCylinderPathD", "cylinder", "cylinder2", "outerPathData", "innerPathData", "outerNode", "innerLine", "pos", "dividedRectangle", "rectOffset", "pts", "poly", "doublecircle", "outerRadius", "innerRadius", "circleGroup", "outerOptions", "innerOptions", "outerRoughNode", "innerRoughNode", "outerCircle", "innerCircle", "filledCircle", "filledCircle2", "flippedTriangle", "flippedTriangle2", "forkJoin", "dir", "state2", "halfRoundedRectangle", "hexagon", "halfWidth", "m", "halfHeight", "fixedLength", "deducedWidth", "hourglass", "icon", "flowchart", "assetHeight", "assetWidth", "iconSize", "defaultWidth", "topLabel", "stylesMap", "compileStyles", "labelPadding", "iconNode", "outerWidth", "outerHeight", "iconShape", "outerShape", "iconElem", "getIconSVG", "iconBBox", "iconWidth", "iconHeight", "iconX", "iconY", "nodeHeight", "iconCircle", "mainBkg", "fill", "diameter", "iconRounded", "iconSquare", "imageSquare", "imageNaturalWidth", "imageNaturalHeight", "imageRawWidth", "imageWidth", "imageHeight", "imageNode", "image", "inv_trapezoid", "drawRect", "labelRect", "lean_left", "lean_right", "lightningBolt", "gap", "lightningBolt2", "createCylinderPathD2", "outerOffset", "createOuterCylinderPathD2", "createInnerCylinderPathD2", "linedCylinder", "linedWaveEdgedRect", "waveAmplitude", "finalH", "waveEdgeRect", "multiRect", "outerPathPoints", "innerPathPoints", "outerPath", "innerPath", "innerNode", "multiRect2", "multiWaveEdgedRectangle", "wavePoints", "lastWavePoint", "note", "getConfig", "noteShapeNode", "createDecisionBoxPathD", "size", "question", "adjustment", "s2", "points2", "rect_left_inv_arrow", "notch", "rectWithTitle", "g", "description", "title", "div2", "dv2", "textRows", "titleBox", "descr", "roughLine", "generateArcPoints2", "roundedRect", "labelPaddingX", "labelPaddingY", "taper", "shadedProcess", "slopedRect", "squareRect2", "stadium", "state", "stateEnd", "lineColor", "stateBorder", "innerFill", "circle2", "stateStart", "solidStateFill", "subroutine", "l1", "l2", "el", "taggedRect", "tagWidth", "tagHeight", "tagPoints", "rectNode", "tagPath", "tagNode", "taggedRect2", "taggedWaveEdgedRectangle", "waveEdgeRectPath", "waveEdgeRectNode", "taggedWaveEdgeRectPath", "taggedWaveEdgeRectNode", "text", "createCylinderPathD3", "createOuterCylinderPathD3", "createInnerCylinderPathD3", "tiltedCylinder", "trapezoid", "trapezoidalPentagon", "triangle", "waveEdgedRectangle", "widthDif", "extraW", "waveRectangle", "baseWidth", "baseHeight", "aspectRatio", "waveRectPath", "waveRectNode", "waveRect", "windowPane", "path", "no", "windowPane2", "erBox", "entityNode", "themeVariables2", "background", "backgroundNode", "PADDING", "TEXT_PADDING", "calculateTextWidth", "shapeSvg2", "textElement", "nameBBox", "addText", "yOffset", "yOffsets", "maxTypeWidth", "maxNameWidth", "maxKeysWidth", "maxCommentWidth", "keysPresent", "commentPresent", "attribute", "typeBBox", "nameBBox2", "keysBBox", "commentBBox", "rowHeight", "totalWidthSections", "shapeBBox", "difference", "maxWidth", "totalShapeBBoxHeight", "sum", "_", "nodes", "transform", "translateX", "translateY", "translate", "roughRect", "rowEven", "rowOdd", "isEven", "roughRect2", "yOffset2", "strokeStyles", "e", "labelText", "parseGenericTypes", "child", "textHelper", "GAP", "annotationGroup", "labelGroup", "membersGroup", "methodsGroup", "annotationGroupHeight", "labelGroupHeight", "membersGroupHeight", "annotation", "addText2", "labelGroupBBox", "member", "methodsYOffset", "method", "annotationGroupBBox", "parentGroup", "styles", "textEl", "textContent", "sanitizeText3", "numberOfLines", "textChild", "classBox", "classNode", "renderExtraBox", "rectBBox", "newTranslateY", "newTranslateX", "_2", "i2", "nodes2", "colorRegex", "match", "colorStyle", "match2", "requirementBox", "requirementNode", "elementNode", "isRequirementNode", "typeHeight", "addText3", "accumulativeHeight", "nameHeight", "idHeight", "textHeight", "riskHeight", "typeHeight2", "inputText", "colorFromPriority", "priority", "kanbanItem", "kanbanNode", "orgWidth", "labelElTitle", "ticketUrl", "link", "bbox2", "labelElAssigned", "bboxAssigned", "heightAdj", "line", "lineX", "bang", "effectiveWidth", "effectiveHeight", "bangElem", "cloud", "cloudElem", "defaultMindmapNode", "rd", "bg", "mindmapCircle", "shapesDefs", "generateShapeMap", "entries", "alias", "shapes2", "isValidShape", "nodeElems", "insertNode", "renderOptions", "newEl", "shapeHandler", "target", "setNodeElem", "clear2", "positionNode", "diff"] +} diff --git a/docs/website/public/chunk-LBFZT66H.min.js b/docs/website/public/chunk-LBFZT66H.min.js new file mode 100644 index 000000000..29f48b8f2 --- /dev/null +++ b/docs/website/public/chunk-LBFZT66H.min.js @@ -0,0 +1,128 @@ +import{A as ae,B as fo,C as Ze,D as Pe,G as Hu,I as Ke,L as le,M as Xt,O as $s,R as Jn,S as zu,a as fe,b as xt,c as ve,d as de,e as ee,g as Et,i as Yn,j as qt,k as At,l as he,m as Dt,n as k,o as Oe,p as Re,q as vt,r as ke,s as x,t as $e,w as ju,x as $,y as Ie,z as te}from"./chunk-R5JLOOQ4.min.js";import{d as b}from"./chunk-PTL4EUOE.min.js";import{M as co,d as Vu,e as at,z as me}from"./chunk-E5F23VE2.min.js";import{a as ks,b as zt,c as U,d as Ku}from"./chunk-OSRY5VT3.min.js";var su=ks(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});var ru;function nu(){if(ru===void 0)throw new Error("No runtime abstraction layer installed");return ru}(function(r){function e(t){if(t===void 0)throw new Error("No runtime abstraction layer provided");ru=t}r.install=e})(nu||(nu={}));iu.default=nu});var Kd=ks(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.stringArray=we.array=we.func=we.error=we.number=we.string=we.boolean=void 0;function eg(r){return r===!0||r===!1}we.boolean=eg;function Bd(r){return typeof r=="string"||r instanceof String}we.string=Bd;function tg(r){return typeof r=="number"||r instanceof Number}we.number=tg;function rg(r){return r instanceof Error}we.error=rg;function ng(r){return typeof r=="function"}we.func=ng;function Wd(r){return Array.isArray(r)}we.array=Wd;function ig(r){return Wd(r)&&r.every(e=>Bd(e))}we.stringArray=ig});var ou=ks(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.Emitter=Wn.Event=void 0;var sg=su(),Vd;(function(r){let e={dispose(){}};r.None=function(){return e}})(Vd||(Wn.Event=Vd={}));var au=class{add(e,t=null,n){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(e),this._contexts.push(t),Array.isArray(n)&&n.push({dispose:()=>this.remove(e,t)})}remove(e,t=null){if(!this._callbacks)return;let n=!1;for(let i=0,s=this._callbacks.length;i{this._callbacks||(this._callbacks=new au),this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(e,t);let i={dispose:()=>{this._callbacks&&(this._callbacks.remove(e,t),i.dispose=r._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty()&&this._options.onLastListenerRemove(this))}};return Array.isArray(n)&&n.push(i),i}),this._event}fire(e){this._callbacks&&this._callbacks.invoke.call(this._callbacks,e)}dispose(){this._callbacks&&(this._callbacks.dispose(),this._callbacks=void 0)}};Wn.Emitter=Oa;Oa._noop=function(){}});var jd=ks(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.CancellationTokenSource=Kn.CancellationToken=void 0;var ag=su(),og=Kd(),lu=ou(),Pa;(function(r){r.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:lu.Event.None}),r.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:lu.Event.None});function e(t){let n=t;return n&&(n===r.None||n===r.Cancelled||og.boolean(n.isCancellationRequested)&&!!n.onCancellationRequested)}r.is=e})(Pa||(Kn.CancellationToken=Pa={}));var lg=Object.freeze(function(r,e){let t=(0,ag.default)().timer.setTimeout(r.bind(e),0);return{dispose(){t.dispose()}}}),ba=class{constructor(){this._isCancelled=!1}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?lg:(this._emitter||(this._emitter=new lu.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}},uu=class{get token(){return this._token||(this._token=new ba),this._token}cancel(){this._token?this._token.cancel():this._token=Pa.Cancelled}dispose(){this._token?this._token instanceof ba&&this._token.dispose():this._token=Pa.None}};Kn.CancellationTokenSource=uu});var ce={};zt(ce,{AbstractAstReflection:()=>Yt,AbstractCstNode:()=>Bi,AbstractLangiumParser:()=>Wi,AbstractParserErrorMessageProvider:()=>_a,AbstractThreadedAsyncParser:()=>Eu,AstUtils:()=>Ds,BiMap:()=>Tr,Cancellation:()=>C,CompositeCstNodeImpl:()=>mr,ContextCache:()=>Rr,CstNodeBuilder:()=>Ui,CstUtils:()=>Cs,DEFAULT_TOKENIZE_OPTIONS:()=>Ba,DONE_RESULT:()=>Ne,DatatypeSymbol:()=>wa,DefaultAstNodeDescriptionProvider:()=>ss,DefaultAstNodeLocator:()=>os,DefaultAsyncParser:()=>ys,DefaultCommentProvider:()=>gs,DefaultConfigurationProvider:()=>ls,DefaultDocumentBuilder:()=>us,DefaultDocumentValidator:()=>is,DefaultHydrator:()=>Rs,DefaultIndexManager:()=>cs,DefaultJsonSerializer:()=>ts,DefaultLangiumDocumentFactory:()=>Hi,DefaultLangiumDocuments:()=>zi,DefaultLexer:()=>Er,DefaultLexerErrorMessageProvider:()=>ds,DefaultLinker:()=>qi,DefaultNameProvider:()=>Xi,DefaultReferenceDescriptionProvider:()=>as,DefaultReferences:()=>Yi,DefaultScopeComputation:()=>Ji,DefaultScopeProvider:()=>es,DefaultServiceRegistry:()=>rs,DefaultTokenBuilder:()=>Pt,DefaultValueConverter:()=>yr,DefaultWorkspaceLock:()=>Ts,DefaultWorkspaceManager:()=>fs,Deferred:()=>Fe,Disposable:()=>Vt,DisposableCache:()=>zn,DocumentCache:()=>Ga,DocumentState:()=>X,DocumentValidator:()=>Je,EMPTY_SCOPE:()=>cg,EMPTY_STREAM:()=>Zn,EmptyFileSystem:()=>Cu,EmptyFileSystemProvider:()=>qa,ErrorWithLocation:()=>er,GrammarAST:()=>li,GrammarUtils:()=>Ws,IndentationAwareLexer:()=>Nu,IndentationAwareTokenBuilder:()=>za,JSDocDocumentationProvider:()=>ms,LangiumCompletionParser:()=>Vi,LangiumParser:()=>Ki,LangiumParserErrorMessageProvider:()=>Bn,LeafCstNodeImpl:()=>pr,LexingMode:()=>Ar,MapScope:()=>Qi,Module:()=>$u,MultiMap:()=>it,OperationCancelled:()=>pt,ParserWorker:()=>Au,Reduction:()=>$r,RegExpUtils:()=>Us,RootCstNodeImpl:()=>Un,SimpleCache:()=>Zi,StreamImpl:()=>Ve,StreamScope:()=>Hn,TextDocument:()=>Vn,TreeStreamImpl:()=>ot,URI:()=>Ge,UriUtils:()=>Ue,ValidationCategory:()=>Xn,ValidationRegistry:()=>ns,ValueConverter:()=>ht,WorkspaceCache:()=>qn,assertUnreachable:()=>ut,createCompletionParser:()=>eu,createDefaultCoreModule:()=>vu,createDefaultSharedCoreModule:()=>ku,createGrammarConfig:()=>nl,createLangiumParser:()=>tu,createParser:()=>ji,delayNextTick:()=>cu,diagnosticData:()=>xr,eagerLoad:()=>fh,getDiagnosticRange:()=>eh,indentationBuilderDefaultOptions:()=>Iu,inject:()=>Ha,interruptAndCheck:()=>ue,isAstNode:()=>oe,isAstNodeDescription:()=>ho,isAstNodeWithComment:()=>hu,isCompositeCstNode:()=>et,isIMultiModeLexerDefinition:()=>mu,isJSDoc:()=>Ru,isLeafCstNode:()=>Ft,isLinkingError:()=>Jt,isNamed:()=>Qd,isOperationCancelled:()=>mt,isReference:()=>xe,isRootCstNode:()=>Qn,isTokenTypeArray:()=>Wa,isTokenTypeDictionary:()=>pu,loadGrammarFromJson:()=>gt,parseJSDoc:()=>Tu,prepareLangiumParser:()=>Ud,setInterruptionPeriod:()=>zd,startCancelableOperation:()=>Da,stream:()=>V,toDiagnosticData:()=>th,toDiagnosticSeverity:()=>Ua});var Cs={};zt(Cs,{DefaultNameRegexp:()=>Ns,RangeComparison:()=>lt,compareRange:()=>Xu,findCommentNode:()=>yo,findDeclarationNodeAtOffset:()=>$h,findLeafNodeAtOffset:()=>To,findLeafNodeBeforeOffset:()=>Yu,flattenCst:()=>kh,getInteriorNodes:()=>Ch,getNextNode:()=>Ih,getPreviousNode:()=>Qu,getStartlineNode:()=>Nh,inRange:()=>go,isChildNode:()=>mo,isCommentNode:()=>po,streamCst:()=>Qt,toDocumentSegment:()=>Zt,tokenToRange:()=>Ir});function oe(r){return typeof r=="object"&&r!==null&&typeof r.$type=="string"}function xe(r){return typeof r=="object"&&r!==null&&typeof r.$refText=="string"}function ho(r){return typeof r=="object"&&r!==null&&typeof r.name=="string"&&typeof r.type=="string"&&typeof r.path=="string"}function Jt(r){return typeof r=="object"&&r!==null&&oe(r.container)&&xe(r.reference)&&typeof r.message=="string"}var Yt=class{constructor(){this.subtypes={},this.allSubtypes={}}isInstance(e,t){return oe(e)&&this.isSubtype(e.$type,t)}isSubtype(e,t){if(e===t)return!0;let n=this.subtypes[e];n||(n=this.subtypes[e]={});let i=n[t];if(i!==void 0)return i;{let s=this.computeIsSubtype(e,t);return n[t]=s,s}}getAllSubTypes(e){let t=this.allSubtypes[e];if(t)return t;{let n=this.getAllTypes(),i=[];for(let s of n)this.isSubtype(s,e)&&i.push(s);return this.allSubtypes[e]=i,i}}};function et(r){return typeof r=="object"&&r!==null&&Array.isArray(r.content)}function Ft(r){return typeof r=="object"&&r!==null&&typeof r.tokenType=="object"}function Qn(r){return et(r)&&typeof r.fullText=="string"}var Ve=class r{constructor(e,t){this.startFn=e,this.nextFn=t}iterator(){let e={state:this.startFn(),next:()=>this.nextFn(e.state),[Symbol.iterator]:()=>e};return e}[Symbol.iterator](){return this.iterator()}isEmpty(){return!!this.iterator().next().done}count(){let e=this.iterator(),t=0,n=e.next();for(;!n.done;)t++,n=e.next();return t}toArray(){let e=[],t=this.iterator(),n;do n=t.next(),n.value!==void 0&&e.push(n.value);while(!n.done);return e}toSet(){return new Set(this)}toMap(e,t){let n=this.map(i=>[e?e(i):i,t?t(i):i]);return new Map(n)}toString(){return this.join()}concat(e){return new r(()=>({first:this.startFn(),firstDone:!1,iterator:e[Symbol.iterator]()}),t=>{let n;if(!t.firstDone){do if(n=this.nextFn(t.first),!n.done)return n;while(!n.done);t.firstDone=!0}do if(n=t.iterator.next(),!n.done)return n;while(!n.done);return Ne})}join(e=","){let t=this.iterator(),n="",i,s=!1;do i=t.next(),i.done||(s&&(n+=e),n+=vh(i.value)),s=!0;while(!i.done);return n}indexOf(e,t=0){let n=this.iterator(),i=0,s=n.next();for(;!s.done;){if(i>=t&&s.value===e)return i;s=n.next(),i++}return-1}every(e){let t=this.iterator(),n=t.next();for(;!n.done;){if(!e(n.value))return!1;n=t.next()}return!0}some(e){let t=this.iterator(),n=t.next();for(;!n.done;){if(e(n.value))return!0;n=t.next()}return!1}forEach(e){let t=this.iterator(),n=0,i=t.next();for(;!i.done;)e(i.value,n),i=t.next(),n++}map(e){return new r(this.startFn,t=>{let{done:n,value:i}=this.nextFn(t);return n?Ne:{done:!1,value:e(i)}})}filter(e){return new r(this.startFn,t=>{let n;do if(n=this.nextFn(t),!n.done&&e(n.value))return n;while(!n.done);return Ne})}nonNullable(){return this.filter(e=>e!=null)}reduce(e,t){let n=this.iterator(),i=t,s=n.next();for(;!s.done;)i===void 0?i=s.value:i=e(i,s.value),s=n.next();return i}reduceRight(e,t){return this.recursiveReduce(this.iterator(),e,t)}recursiveReduce(e,t,n){let i=e.next();if(i.done)return n;let s=this.recursiveReduce(e,t,n);return s===void 0?i.value:t(s,i.value)}find(e){let t=this.iterator(),n=t.next();for(;!n.done;){if(e(n.value))return n.value;n=t.next()}}findIndex(e){let t=this.iterator(),n=0,i=t.next();for(;!i.done;){if(e(i.value))return n;i=t.next(),n++}return-1}includes(e){let t=this.iterator(),n=t.next();for(;!n.done;){if(n.value===e)return!0;n=t.next()}return!1}flatMap(e){return new r(()=>({this:this.startFn()}),t=>{do{if(t.iterator){let s=t.iterator.next();if(s.done)t.iterator=void 0;else return s}let{done:n,value:i}=this.nextFn(t.this);if(!n){let s=e(i);if(Is(s))t.iterator=s[Symbol.iterator]();else return{done:!1,value:s}}}while(t.iterator);return Ne})}flat(e){if(e===void 0&&(e=1),e<=0)return this;let t=e>1?this.flat(e-1):this;return new r(()=>({this:t.startFn()}),n=>{do{if(n.iterator){let a=n.iterator.next();if(a.done)n.iterator=void 0;else return a}let{done:i,value:s}=t.nextFn(n.this);if(!i)if(Is(s))n.iterator=s[Symbol.iterator]();else return{done:!1,value:s}}while(n.iterator);return Ne})}head(){let t=this.iterator().next();if(!t.done)return t.value}tail(e=1){return new r(()=>{let t=this.startFn();for(let n=0;n({size:0,state:this.startFn()}),t=>(t.size++,t.size>e?Ne:this.nextFn(t.state)))}distinct(e){return new r(()=>({set:new Set,internalState:this.startFn()}),t=>{let n;do if(n=this.nextFn(t.internalState),!n.done){let i=e?e(n.value):n.value;if(!t.set.has(i))return t.set.add(i),n}while(!n.done);return Ne})}exclude(e,t){let n=new Set;for(let i of e){let s=t?t(i):i;n.add(s)}return this.filter(i=>{let s=t?t(i):i;return!n.has(s)})}};function vh(r){return typeof r=="string"?r:typeof r>"u"?"undefined":typeof r.toString=="function"?r.toString():Object.prototype.toString.call(r)}function Is(r){return!!r&&typeof r[Symbol.iterator]=="function"}var Zn=new Ve(()=>{},()=>Ne),Ne=Object.freeze({done:!0,value:void 0});function V(...r){if(r.length===1){let e=r[0];if(e instanceof Ve)return e;if(Is(e))return new Ve(()=>e[Symbol.iterator](),t=>t.next());if(typeof e.length=="number")return new Ve(()=>({index:0}),t=>t.index1?new Ve(()=>({collIndex:0,arrIndex:0}),e=>{do{if(e.iterator){let t=e.iterator.next();if(!t.done)return t;e.iterator=void 0}if(e.array){if(e.arrIndex({iterators:n?.includeRoot?[[e][Symbol.iterator]()]:[t(e)[Symbol.iterator]()],pruned:!1}),i=>{for(i.pruned&&(i.iterators.pop(),i.pruned=!1);i.iterators.length>0;){let a=i.iterators[i.iterators.length-1].next();if(a.done)i.iterators.pop();else return i.iterators.push(t(a.value)[Symbol.iterator]()),a}return Ne})}iterator(){let e={state:this.startFn(),next:()=>this.nextFn(e.state),prune:()=>{e.state.pruned=!0},[Symbol.iterator]:()=>e};return e}},$r;(function(r){function e(s){return s.reduce((a,o)=>a+o,0)}r.sum=e;function t(s){return s.reduce((a,o)=>a*o,0)}r.product=t;function n(s){return s.reduce((a,o)=>Math.min(a,o))}r.min=n;function i(s){return s.reduce((a,o)=>Math.max(a,o))}r.max=i})($r||($r={}));function Qt(r){return new ot(r,e=>et(e)?e.content:[],{includeRoot:!0})}function kh(r){return Qt(r).filter(Ft)}function mo(r,e){for(;r.container;)if(r=r.container,r===e)return!0;return!1}function Ir(r){return{start:{character:r.startColumn-1,line:r.startLine-1},end:{character:r.endColumn,line:r.endLine-1}}}function Zt(r){if(!r)return;let{offset:e,end:t,range:n}=r;return{range:n,offset:e,end:t,length:t-e}}var lt;(function(r){r[r.Before=0]="Before",r[r.After=1]="After",r[r.OverlapFront=2]="OverlapFront",r[r.OverlapBack=3]="OverlapBack",r[r.Inside=4]="Inside",r[r.Outside=5]="Outside"})(lt||(lt={}));function Xu(r,e){if(r.end.linee.end.line||r.start.line===e.end.line&&r.start.character>=e.end.character)return lt.After;let t=r.start.line>e.start.line||r.start.line===e.start.line&&r.start.character>=e.start.character,n=r.end.linelt.After}var Ns=/^[\w\p{L}]$/u;function $h(r,e,t=Ns){if(r){if(e>0){let n=e-r.offset,i=r.text.charAt(n);t.test(i)||e--}return To(r,e)}}function yo(r,e){if(r){let t=Qu(r,!0);if(t&&po(t,e))return t;if(Qn(r)){let n=r.content.findIndex(i=>!i.hidden);for(let i=n-1;i>=0;i--){let s=r.content[i];if(po(s,e))return s}}}}function po(r,e){return Ft(r)&&e.includes(r.tokenType.name)}function To(r,e){if(Ft(r))return r;if(et(r)){let t=Ju(r,e,!1);if(t)return To(t,e)}}function Yu(r,e){if(Ft(r))return r;if(et(r)){let t=Ju(r,e,!0);if(t)return Yu(t,e)}}function Ju(r,e,t){let n=0,i=r.content.length-1,s;for(;n<=i;){let a=Math.floor((n+i)/2),o=r.content[a];if(o.offset<=e&&o.end>e)return o;o.end<=e?(s=t?o:void 0,n=a+1):i=a-1}return s}function Qu(r,e=!0){for(;r.container;){let t=r.container,n=t.content.indexOf(r);for(;n>0;){n--;let i=t.content[n];if(e||!i.hidden)return i}r=t}}function Ih(r,e=!0){for(;r.container;){let t=r.container,n=t.content.indexOf(r),i=t.content.length-1;for(;nel,findNameAssignment:()=>Bs,findNodeForKeyword:()=>Qo,findNodeForProperty:()=>mi,findNodesForKeyword:()=>Yh,findNodesForKeywordInternal:()=>Zo,findNodesForProperty:()=>Yo,getActionAtElement:()=>lc,getActionType:()=>cc,getAllReachableRules:()=>pi,getCrossReferenceTerminal:()=>qo,getEntryRule:()=>ic,getExplicitRuleType:()=>gn,getHiddenRules:()=>sc,getRuleType:()=>tl,getRuleTypeName:()=>tp,getTypeName:()=>yi,isArrayCardinality:()=>Qh,isArrayOperator:()=>Zh,isCommentTerminal:()=>Xo,isDataType:()=>ep,isDataTypeRule:()=>gi,isOptionalCardinality:()=>Jh,terminalRegex:()=>yn});var er=class extends Error{constructor(e,t){super(e?`${t} at ${e.range.start.line}:${e.range.start.character}`:t)}};function ut(r){throw new Error("Error! The input value was not handled.")}var li={};zt(li,{AbstractElement:()=>Sr,AbstractRule:()=>Nr,AbstractType:()=>Cr,Action:()=>qr,Alternatives:()=>Xr,ArrayLiteral:()=>wr,ArrayType:()=>_r,Assignment:()=>Yr,BooleanLiteral:()=>Lr,CharacterRange:()=>Jr,Condition:()=>ei,Conjunction:()=>Or,CrossReference:()=>Qr,Disjunction:()=>Pr,EndOfFile:()=>Zr,Grammar:()=>br,GrammarImport:()=>ri,Group:()=>en,InferredType:()=>Mr,Interface:()=>Dr,Keyword:()=>tn,LangiumGrammarAstReflection:()=>dn,LangiumGrammarTerminals:()=>wh,NamedArgument:()=>ni,NegatedToken:()=>rn,Negation:()=>Fr,NumberLiteral:()=>Gr,Parameter:()=>Ur,ParameterReference:()=>Br,ParserRule:()=>Wr,ReferenceType:()=>Kr,RegexToken:()=>nn,ReturnType:()=>ii,RuleCall:()=>sn,SimpleType:()=>Vr,StringLiteral:()=>jr,TerminalAlternatives:()=>an,TerminalGroup:()=>on,TerminalRule:()=>tr,TerminalRuleCall:()=>ln,Type:()=>Hr,TypeAttribute:()=>si,TypeDefinition:()=>Ss,UnionType:()=>zr,UnorderedGroup:()=>un,UntilToken:()=>cn,ValueLiteral:()=>ti,Wildcard:()=>fn,isAbstractElement:()=>ai,isAbstractRule:()=>_h,isAbstractType:()=>Lh,isAction:()=>kt,isAlternatives:()=>Os,isArrayLiteral:()=>Dh,isArrayType:()=>Ro,isAssignment:()=>tt,isBooleanLiteral:()=>xo,isCharacterRange:()=>Co,isCondition:()=>Oh,isConjunction:()=>Eo,isCrossReference:()=>rr,isDisjunction:()=>Ao,isEndOfFile:()=>So,isFeatureName:()=>Ph,isGrammar:()=>Fh,isGrammarImport:()=>Gh,isGroup:()=>Gt,isInferredType:()=>ws,isInterface:()=>_s,isKeyword:()=>Xe,isNamedArgument:()=>Uh,isNegatedToken:()=>wo,isNegation:()=>vo,isNumberLiteral:()=>Bh,isParameter:()=>Wh,isParameterReference:()=>ko,isParserRule:()=>Ce,isPrimitiveType:()=>Zu,isReferenceType:()=>$o,isRegexToken:()=>_o,isReturnType:()=>Io,isRuleCall:()=>rt,isSimpleType:()=>Ls,isStringLiteral:()=>Kh,isTerminalAlternatives:()=>Lo,isTerminalGroup:()=>Oo,isTerminalRule:()=>je,isTerminalRuleCall:()=>Ps,isType:()=>oi,isTypeAttribute:()=>Vh,isTypeDefinition:()=>bh,isUnionType:()=>No,isUnorderedGroup:()=>bs,isUntilToken:()=>Po,isValueLiteral:()=>Mh,isWildcard:()=>bo,reflection:()=>w});var wh={ID:/\^?[_a-zA-Z][\w_]*/,STRING:/"(\\.|[^"\\])*"|'(\\.|[^'\\])*'/,NUMBER:/NaN|-?((\d*\.\d+|\d+)([Ee][+-]?\d+)?|Infinity)/,RegexLiteral:/\/(?![*+?])(?:[^\r\n\[/\\]|\\.|\[(?:[^\r\n\]\\]|\\.)*\])+\/[a-z]*/,WS:/\s+/,ML_COMMENT:/\/\*[\s\S]*?\*\//,SL_COMMENT:/\/\/[^\n\r]*/},Nr="AbstractRule";function _h(r){return w.isInstance(r,Nr)}var Cr="AbstractType";function Lh(r){return w.isInstance(r,Cr)}var ei="Condition";function Oh(r){return w.isInstance(r,ei)}function Ph(r){return Zu(r)||r==="current"||r==="entry"||r==="extends"||r==="false"||r==="fragment"||r==="grammar"||r==="hidden"||r==="import"||r==="interface"||r==="returns"||r==="terminal"||r==="true"||r==="type"||r==="infer"||r==="infers"||r==="with"||typeof r=="string"&&/\^?[_a-zA-Z][\w_]*/.test(r)}function Zu(r){return r==="string"||r==="number"||r==="boolean"||r==="Date"||r==="bigint"}var Ss="TypeDefinition";function bh(r){return w.isInstance(r,Ss)}var ti="ValueLiteral";function Mh(r){return w.isInstance(r,ti)}var Sr="AbstractElement";function ai(r){return w.isInstance(r,Sr)}var wr="ArrayLiteral";function Dh(r){return w.isInstance(r,wr)}var _r="ArrayType";function Ro(r){return w.isInstance(r,_r)}var Lr="BooleanLiteral";function xo(r){return w.isInstance(r,Lr)}var Or="Conjunction";function Eo(r){return w.isInstance(r,Or)}var Pr="Disjunction";function Ao(r){return w.isInstance(r,Pr)}var br="Grammar";function Fh(r){return w.isInstance(r,br)}var ri="GrammarImport";function Gh(r){return w.isInstance(r,ri)}var Mr="InferredType";function ws(r){return w.isInstance(r,Mr)}var Dr="Interface";function _s(r){return w.isInstance(r,Dr)}var ni="NamedArgument";function Uh(r){return w.isInstance(r,ni)}var Fr="Negation";function vo(r){return w.isInstance(r,Fr)}var Gr="NumberLiteral";function Bh(r){return w.isInstance(r,Gr)}var Ur="Parameter";function Wh(r){return w.isInstance(r,Ur)}var Br="ParameterReference";function ko(r){return w.isInstance(r,Br)}var Wr="ParserRule";function Ce(r){return w.isInstance(r,Wr)}var Kr="ReferenceType";function $o(r){return w.isInstance(r,Kr)}var ii="ReturnType";function Io(r){return w.isInstance(r,ii)}var Vr="SimpleType";function Ls(r){return w.isInstance(r,Vr)}var jr="StringLiteral";function Kh(r){return w.isInstance(r,jr)}var tr="TerminalRule";function je(r){return w.isInstance(r,tr)}var Hr="Type";function oi(r){return w.isInstance(r,Hr)}var si="TypeAttribute";function Vh(r){return w.isInstance(r,si)}var zr="UnionType";function No(r){return w.isInstance(r,zr)}var qr="Action";function kt(r){return w.isInstance(r,qr)}var Xr="Alternatives";function Os(r){return w.isInstance(r,Xr)}var Yr="Assignment";function tt(r){return w.isInstance(r,Yr)}var Jr="CharacterRange";function Co(r){return w.isInstance(r,Jr)}var Qr="CrossReference";function rr(r){return w.isInstance(r,Qr)}var Zr="EndOfFile";function So(r){return w.isInstance(r,Zr)}var en="Group";function Gt(r){return w.isInstance(r,en)}var tn="Keyword";function Xe(r){return w.isInstance(r,tn)}var rn="NegatedToken";function wo(r){return w.isInstance(r,rn)}var nn="RegexToken";function _o(r){return w.isInstance(r,nn)}var sn="RuleCall";function rt(r){return w.isInstance(r,sn)}var an="TerminalAlternatives";function Lo(r){return w.isInstance(r,an)}var on="TerminalGroup";function Oo(r){return w.isInstance(r,on)}var ln="TerminalRuleCall";function Ps(r){return w.isInstance(r,ln)}var un="UnorderedGroup";function bs(r){return w.isInstance(r,un)}var cn="UntilToken";function Po(r){return w.isInstance(r,cn)}var fn="Wildcard";function bo(r){return w.isInstance(r,fn)}var dn=class extends Yt{getAllTypes(){return[Sr,Nr,Cr,qr,Xr,wr,_r,Yr,Lr,Jr,ei,Or,Qr,Pr,Zr,br,ri,en,Mr,Dr,tn,ni,rn,Fr,Gr,Ur,Br,Wr,Kr,nn,ii,sn,Vr,jr,an,on,tr,ln,Hr,si,Ss,zr,un,cn,ti,fn]}computeIsSubtype(e,t){switch(e){case qr:case Xr:case Yr:case Jr:case Qr:case Zr:case en:case tn:case rn:case nn:case sn:case an:case on:case ln:case un:case cn:case fn:return this.isSubtype(Sr,t);case wr:case Gr:case jr:return this.isSubtype(ti,t);case _r:case Kr:case Vr:case zr:return this.isSubtype(Ss,t);case Lr:return this.isSubtype(ei,t)||this.isSubtype(ti,t);case Or:case Pr:case Fr:case Br:return this.isSubtype(ei,t);case Mr:case Dr:case Hr:return this.isSubtype(Cr,t);case Wr:return this.isSubtype(Nr,t)||this.isSubtype(Cr,t);case tr:return this.isSubtype(Nr,t);default:return!1}}getReferenceType(e){let t=`${e.container.$type}:${e.property}`;switch(t){case"Action:type":case"CrossReference:type":case"Interface:superTypes":case"ParserRule:returnType":case"SimpleType:typeRef":return Cr;case"Grammar:hiddenTokens":case"ParserRule:hiddenTokens":case"RuleCall:rule":return Nr;case"Grammar:usedGrammars":return br;case"NamedArgument:parameter":case"ParameterReference:parameter":return Ur;case"TerminalRuleCall:rule":return tr;default:throw new Error(`${t} is not a valid reference id.`)}}getTypeMetaData(e){switch(e){case Sr:return{name:Sr,properties:[{name:"cardinality"},{name:"lookahead"}]};case wr:return{name:wr,properties:[{name:"elements",defaultValue:[]}]};case _r:return{name:_r,properties:[{name:"elementType"}]};case Lr:return{name:Lr,properties:[{name:"true",defaultValue:!1}]};case Or:return{name:Or,properties:[{name:"left"},{name:"right"}]};case Pr:return{name:Pr,properties:[{name:"left"},{name:"right"}]};case br:return{name:br,properties:[{name:"definesHiddenTokens",defaultValue:!1},{name:"hiddenTokens",defaultValue:[]},{name:"imports",defaultValue:[]},{name:"interfaces",defaultValue:[]},{name:"isDeclared",defaultValue:!1},{name:"name"},{name:"rules",defaultValue:[]},{name:"types",defaultValue:[]},{name:"usedGrammars",defaultValue:[]}]};case ri:return{name:ri,properties:[{name:"path"}]};case Mr:return{name:Mr,properties:[{name:"name"}]};case Dr:return{name:Dr,properties:[{name:"attributes",defaultValue:[]},{name:"name"},{name:"superTypes",defaultValue:[]}]};case ni:return{name:ni,properties:[{name:"calledByName",defaultValue:!1},{name:"parameter"},{name:"value"}]};case Fr:return{name:Fr,properties:[{name:"value"}]};case Gr:return{name:Gr,properties:[{name:"value"}]};case Ur:return{name:Ur,properties:[{name:"name"}]};case Br:return{name:Br,properties:[{name:"parameter"}]};case Wr:return{name:Wr,properties:[{name:"dataType"},{name:"definesHiddenTokens",defaultValue:!1},{name:"definition"},{name:"entry",defaultValue:!1},{name:"fragment",defaultValue:!1},{name:"hiddenTokens",defaultValue:[]},{name:"inferredType"},{name:"name"},{name:"parameters",defaultValue:[]},{name:"returnType"},{name:"wildcard",defaultValue:!1}]};case Kr:return{name:Kr,properties:[{name:"referenceType"}]};case ii:return{name:ii,properties:[{name:"name"}]};case Vr:return{name:Vr,properties:[{name:"primitiveType"},{name:"stringType"},{name:"typeRef"}]};case jr:return{name:jr,properties:[{name:"value"}]};case tr:return{name:tr,properties:[{name:"definition"},{name:"fragment",defaultValue:!1},{name:"hidden",defaultValue:!1},{name:"name"},{name:"type"}]};case Hr:return{name:Hr,properties:[{name:"name"},{name:"type"}]};case si:return{name:si,properties:[{name:"defaultValue"},{name:"isOptional",defaultValue:!1},{name:"name"},{name:"type"}]};case zr:return{name:zr,properties:[{name:"types",defaultValue:[]}]};case qr:return{name:qr,properties:[{name:"cardinality"},{name:"feature"},{name:"inferredType"},{name:"lookahead"},{name:"operator"},{name:"type"}]};case Xr:return{name:Xr,properties:[{name:"cardinality"},{name:"elements",defaultValue:[]},{name:"lookahead"}]};case Yr:return{name:Yr,properties:[{name:"cardinality"},{name:"feature"},{name:"lookahead"},{name:"operator"},{name:"terminal"}]};case Jr:return{name:Jr,properties:[{name:"cardinality"},{name:"left"},{name:"lookahead"},{name:"right"}]};case Qr:return{name:Qr,properties:[{name:"cardinality"},{name:"deprecatedSyntax",defaultValue:!1},{name:"lookahead"},{name:"terminal"},{name:"type"}]};case Zr:return{name:Zr,properties:[{name:"cardinality"},{name:"lookahead"}]};case en:return{name:en,properties:[{name:"cardinality"},{name:"elements",defaultValue:[]},{name:"guardCondition"},{name:"lookahead"}]};case tn:return{name:tn,properties:[{name:"cardinality"},{name:"lookahead"},{name:"value"}]};case rn:return{name:rn,properties:[{name:"cardinality"},{name:"lookahead"},{name:"terminal"}]};case nn:return{name:nn,properties:[{name:"cardinality"},{name:"lookahead"},{name:"regex"}]};case sn:return{name:sn,properties:[{name:"arguments",defaultValue:[]},{name:"cardinality"},{name:"lookahead"},{name:"rule"}]};case an:return{name:an,properties:[{name:"cardinality"},{name:"elements",defaultValue:[]},{name:"lookahead"}]};case on:return{name:on,properties:[{name:"cardinality"},{name:"elements",defaultValue:[]},{name:"lookahead"}]};case ln:return{name:ln,properties:[{name:"cardinality"},{name:"lookahead"},{name:"rule"}]};case un:return{name:un,properties:[{name:"cardinality"},{name:"elements",defaultValue:[]},{name:"lookahead"}]};case cn:return{name:cn,properties:[{name:"cardinality"},{name:"lookahead"},{name:"terminal"}]};case fn:return{name:fn,properties:[{name:"cardinality"},{name:"lookahead"}]};default:return{name:e,properties:[]}}}},w=new dn;var Ds={};zt(Ds,{assignMandatoryProperties:()=>Fo,copyAstNode:()=>Do,findLocalReferences:()=>Hh,findRootNode:()=>ui,getContainerOfType:()=>nr,getDocument:()=>Se,hasContainerOfType:()=>jh,linkContentToContainer:()=>Ms,streamAllContents:()=>ct,streamAst:()=>Ye,streamContents:()=>ci,streamReferences:()=>hn});function Ms(r){for(let[e,t]of Object.entries(r))e.startsWith("$")||(Array.isArray(t)?t.forEach((n,i)=>{oe(n)&&(n.$container=r,n.$containerProperty=e,n.$containerIndex=i)}):oe(t)&&(t.$container=r,t.$containerProperty=e))}function nr(r,e){let t=r;for(;t;){if(e(t))return t;t=t.$container}}function jh(r,e){let t=r;for(;t;){if(e(t))return!0;t=t.$container}return!1}function Se(r){let t=ui(r).$document;if(!t)throw new Error("AST node has no document.");return t}function ui(r){for(;r.$container;)r=r.$container;return r}function ci(r,e){if(!r)throw new Error("Node must be an AstNode.");let t=e?.range;return new Ve(()=>({keys:Object.keys(r),keyIndex:0,arrayIndex:0}),n=>{for(;n.keyIndexci(t,e))}function Ye(r,e){if(r){if(e?.range&&!Mo(r,e.range))return new ot(r,()=>[])}else throw new Error("Root node must be an AstNode.");return new ot(r,t=>ci(t,e),{includeRoot:!0})}function Mo(r,e){var t;if(!e)return!0;let n=(t=r.$cstNode)===null||t===void 0?void 0:t.range;return n?go(n,e):!1}function hn(r){return new Ve(()=>({keys:Object.keys(r),keyIndex:0,arrayIndex:0}),e=>{for(;e.keyIndex{hn(n).forEach(i=>{i.reference.ref===r&&t.push(i.reference)})}),V(t)}function Fo(r,e){let t=r.getTypeMetaData(e.$type),n=e;for(let i of t.properties)i.defaultValue!==void 0&&n[i.name]===void 0&&(n[i.name]=ec(i.defaultValue))}function ec(r){return Array.isArray(r)?[...r.map(ec)]:r}function Do(r,e){let t={$type:r.$type};for(let[n,i]of Object.entries(r))if(!n.startsWith("$"))if(oe(i))t[n]=Do(i,e);else if(xe(i))t[n]=e(t,n,i.$refNode,i.$refText);else if(Array.isArray(i)){let s=[];for(let a of i)oe(a)?s.push(Do(a,e)):xe(a)?s.push(e(t,n,a.$refNode,a.$refText)):s.push(a);t[n]=s}else t[n]=i;return Ms(t),t}var Us={};zt(Us,{NEWLINE_REGEXP:()=>Wo,escapeRegExp:()=>or,getCaseInsensitivePattern:()=>Vo,getTerminalParts:()=>Xh,isMultilineComment:()=>Ko,isWhitespace:()=>mn,partialMatches:()=>jo,partialRegExp:()=>nc,whitespaceCharacters:()=>rc});function S(r){return r.charCodeAt(0)}function Fs(r,e){Array.isArray(r)?r.forEach(function(t){e.push(t)}):e.push(r)}function pn(r,e){if(r[e]===!0)throw"duplicate flag "+e;let t=r[e];r[e]=!0}function ir(r){if(r===void 0)throw Error("Internal Error - Should never get here!");return!0}function fi(){throw Error("Internal Error - Should never get here!")}function Go(r){return r.type==="Character"}var di=[];for(let r=S("0");r<=S("9");r++)di.push(r);var hi=[S("_")].concat(di);for(let r=S("a");r<=S("z");r++)hi.push(r);for(let r=S("A");r<=S("Z");r++)hi.push(r);var Uo=[S(" "),S("\f"),S(` +`),S("\r"),S(" "),S("\v"),S(" "),S("\xA0"),S("\u1680"),S("\u2000"),S("\u2001"),S("\u2002"),S("\u2003"),S("\u2004"),S("\u2005"),S("\u2006"),S("\u2007"),S("\u2008"),S("\u2009"),S("\u200A"),S("\u2028"),S("\u2029"),S("\u202F"),S("\u205F"),S("\u3000"),S("\uFEFF")];var zh=/[0-9a-fA-F]/,Gs=/[0-9]/,qh=/[1-9]/,sr=class{constructor(){this.idx=0,this.input="",this.groupIdx=0}saveState(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}}restoreState(e){this.idx=e.idx,this.input=e.input,this.groupIdx=e.groupIdx}pattern(e){this.idx=0,this.input=e,this.groupIdx=0,this.consumeChar("/");let t=this.disjunction();this.consumeChar("/");let n={type:"Flags",loc:{begin:this.idx,end:e.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};for(;this.isRegExpFlag();)switch(this.popChar()){case"g":pn(n,"global");break;case"i":pn(n,"ignoreCase");break;case"m":pn(n,"multiLine");break;case"u":pn(n,"unicode");break;case"y":pn(n,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:n,value:t,loc:this.loc(0)}}disjunction(){let e=[],t=this.idx;for(e.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),e.push(this.alternative());return{type:"Disjunction",value:e,loc:this.loc(t)}}alternative(){let e=[],t=this.idx;for(;this.isTerm();)e.push(this.term());return{type:"Alternative",value:e,loc:this.loc(t)}}term(){return this.isAssertion()?this.assertion():this.atom()}assertion(){let e=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(e)};case"$":return{type:"EndAnchor",loc:this.loc(e)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(e)};case"B":return{type:"NonWordBoundary",loc:this.loc(e)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");let t;switch(this.popChar()){case"=":t="Lookahead";break;case"!":t="NegativeLookahead";break}ir(t);let n=this.disjunction();return this.consumeChar(")"),{type:t,value:n,loc:this.loc(e)}}return fi()}quantifier(e=!1){let t,n=this.idx;switch(this.popChar()){case"*":t={atLeast:0,atMost:1/0};break;case"+":t={atLeast:1,atMost:1/0};break;case"?":t={atLeast:0,atMost:1};break;case"{":let i=this.integerIncludingZero();switch(this.popChar()){case"}":t={atLeast:i,atMost:i};break;case",":let s;this.isDigit()?(s=this.integerIncludingZero(),t={atLeast:i,atMost:s}):t={atLeast:i,atMost:1/0},this.consumeChar("}");break}if(e===!0&&t===void 0)return;ir(t);break}if(!(e===!0&&t===void 0)&&ir(t))return this.peekChar(0)==="?"?(this.consumeChar("?"),t.greedy=!1):t.greedy=!0,t.type="Quantifier",t.loc=this.loc(n),t}atom(){let e,t=this.idx;switch(this.peekChar()){case".":e=this.dotAll();break;case"\\":e=this.atomEscape();break;case"[":e=this.characterClass();break;case"(":e=this.group();break}return e===void 0&&this.isPatternCharacter()&&(e=this.patternCharacter()),ir(e)?(e.loc=this.loc(t),this.isQuantifier()&&(e.quantifier=this.quantifier()),e):fi()}dotAll(){return this.consumeChar("."),{type:"Set",complement:!0,value:[S(` +`),S("\r"),S("\u2028"),S("\u2029")]}}atomEscape(){switch(this.consumeChar("\\"),this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}}decimalEscapeAtom(){return{type:"GroupBackReference",value:this.positiveInteger()}}characterClassEscape(){let e,t=!1;switch(this.popChar()){case"d":e=di;break;case"D":e=di,t=!0;break;case"s":e=Uo;break;case"S":e=Uo,t=!0;break;case"w":e=hi;break;case"W":e=hi,t=!0;break}return ir(e)?{type:"Set",value:e,complement:t}:fi()}controlEscapeAtom(){let e;switch(this.popChar()){case"f":e=S("\f");break;case"n":e=S(` +`);break;case"r":e=S("\r");break;case"t":e=S(" ");break;case"v":e=S("\v");break}return ir(e)?{type:"Character",value:e}:fi()}controlLetterEscapeAtom(){this.consumeChar("c");let e=this.popChar();if(/[a-zA-Z]/.test(e)===!1)throw Error("Invalid ");return{type:"Character",value:e.toUpperCase().charCodeAt(0)-64}}nulCharacterAtom(){return this.consumeChar("0"),{type:"Character",value:S("\0")}}hexEscapeSequenceAtom(){return this.consumeChar("x"),this.parseHexDigits(2)}regExpUnicodeEscapeSequenceAtom(){return this.consumeChar("u"),this.parseHexDigits(4)}identityEscapeAtom(){let e=this.popChar();return{type:"Character",value:S(e)}}classPatternCharacterAtom(){switch(this.peekChar()){case` +`:case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:let e=this.popChar();return{type:"Character",value:S(e)}}}characterClass(){let e=[],t=!1;for(this.consumeChar("["),this.peekChar(0)==="^"&&(this.consumeChar("^"),t=!0);this.isClassAtom();){let n=this.classAtom(),i=n.type==="Character";if(Go(n)&&this.isRangeDash()){this.consumeChar("-");let s=this.classAtom(),a=s.type==="Character";if(Go(s)){if(s.value=this.input.length)throw Error("Unexpected end of input");this.idx++}loc(e){return{begin:e,end:this.idx}}};var ft=class{visitChildren(e){for(let t in e){let n=e[t];e.hasOwnProperty(t)&&(n.type!==void 0?this.visit(n):Array.isArray(n)&&n.forEach(i=>{this.visit(i)},this))}}visit(e){switch(e.type){case"Pattern":this.visitPattern(e);break;case"Flags":this.visitFlags(e);break;case"Disjunction":this.visitDisjunction(e);break;case"Alternative":this.visitAlternative(e);break;case"StartAnchor":this.visitStartAnchor(e);break;case"EndAnchor":this.visitEndAnchor(e);break;case"WordBoundary":this.visitWordBoundary(e);break;case"NonWordBoundary":this.visitNonWordBoundary(e);break;case"Lookahead":this.visitLookahead(e);break;case"NegativeLookahead":this.visitNegativeLookahead(e);break;case"Character":this.visitCharacter(e);break;case"Set":this.visitSet(e);break;case"Group":this.visitGroup(e);break;case"GroupBackReference":this.visitGroupBackReference(e);break;case"Quantifier":this.visitQuantifier(e);break}this.visitChildren(e)}visitPattern(e){}visitFlags(e){}visitDisjunction(e){}visitAlternative(e){}visitStartAnchor(e){}visitEndAnchor(e){}visitWordBoundary(e){}visitNonWordBoundary(e){}visitLookahead(e){}visitNegativeLookahead(e){}visitCharacter(e){}visitSet(e){}visitGroup(e){}visitGroupBackReference(e){}visitQuantifier(e){}};var Wo=/\r?\n/gm,tc=new sr,Bo=class extends ft{constructor(){super(...arguments),this.isStarting=!0,this.endRegexpStack=[],this.multiline=!1}get endRegex(){return this.endRegexpStack.join("")}reset(e){this.multiline=!1,this.regex=e,this.startRegexp="",this.isStarting=!0,this.endRegexpStack=[]}visitGroup(e){e.quantifier&&(this.isStarting=!1,this.endRegexpStack=[])}visitCharacter(e){let t=String.fromCharCode(e.value);if(!this.multiline&&t===` +`&&(this.multiline=!0),e.quantifier)this.isStarting=!1,this.endRegexpStack=[];else{let n=or(t);this.endRegexpStack.push(n),this.isStarting&&(this.startRegexp+=n)}}visitSet(e){if(!this.multiline){let t=this.regex.substring(e.loc.begin,e.loc.end),n=new RegExp(t);this.multiline=!!` +`.match(n)}if(e.quantifier)this.isStarting=!1,this.endRegexpStack=[];else{let t=this.regex.substring(e.loc.begin,e.loc.end);this.endRegexpStack.push(t),this.isStarting&&(this.startRegexp+=t)}}visitChildren(e){e.type==="Group"&&e.quantifier||super.visitChildren(e)}},ar=new Bo;function Xh(r){try{typeof r!="string"&&(r=r.source),r=`/${r}/`;let e=tc.pattern(r),t=[];for(let n of e.value.value)ar.reset(r),ar.visit(n),t.push({start:ar.startRegexp,end:ar.endRegex});return t}catch{return[]}}function Ko(r){try{return typeof r=="string"&&(r=new RegExp(r)),r=r.toString(),ar.reset(r),ar.visit(tc.pattern(r)),ar.multiline}catch{return!1}}var rc=`\f +\r \v \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF`.split("");function mn(r){let e=typeof r=="string"?new RegExp(r):r;return rc.some(t=>e.test(t))}function or(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Vo(r){return Array.prototype.map.call(r,e=>/\w/.test(e)?`[${e.toLowerCase()}${e.toUpperCase()}]`:or(e)).join("")}function jo(r,e){let t=nc(r),n=e.match(t);return!!n&&n[0].length>0}function nc(r){typeof r=="string"&&(r=new RegExp(r));let e=r,t=r.source,n=0;function i(){let s="",a;function o(u){s+=t.substr(n,u),n+=u}function l(u){s+="(?:"+t.substr(n,u)+"|$)",n+=u}for(;n",n)-n+1);break;default:l(2);break}break;case"[":a=/\[(?:\\.|.)*?\]/g,a.lastIndex=n,a=a.exec(t)||[],l(a[0].length);break;case"|":case"^":case"$":case"*":case"+":case"?":o(1);break;case"{":a=/\{\d+,?\d*\}/g,a.lastIndex=n,a=a.exec(t),a?o(a[0].length):l(1);break;case"(":if(t[n+1]==="?")switch(t[n+2]){case":":s+="(?:",n+=3,s+=i()+"|$)";break;case"=":s+="(?=",n+=3,s+=i()+")";break;case"!":a=n,n+=3,i(),s+=t.substr(a,n-a);break;case"<":switch(t[n+3]){case"=":case"!":a=n,n+=4,i(),s+=t.substr(a,n-a);break;default:o(t.indexOf(">",n)-n+1),s+=i()+"|$)";break}break}else o(1),s+=i()+"|$)";break;case")":return++n,s;default:l(1);break}return s}return new RegExp(i(),r.flags)}function ic(r){return r.rules.find(e=>Ce(e)&&e.entry)}function sc(r){return r.rules.filter(e=>je(e)&&e.hidden)}function pi(r,e){let t=new Set,n=ic(r);if(!n)return new Set(r.rules);let i=[n].concat(sc(r));for(let a of i)ac(a,t,e);let s=new Set;for(let a of r.rules)(t.has(a.name)||je(a)&&a.hidden)&&s.add(a);return s}function ac(r,e,t){e.add(r.name),ct(r).forEach(n=>{if(rt(n)||t&&Ps(n)){let i=n.rule.ref;i&&!e.has(i.name)&&ac(i,e,t)}})}function qo(r){if(r.terminal)return r.terminal;if(r.type.ref){let e=Bs(r.type.ref);return e?.terminal}}function Xo(r){return r.hidden&&!mn(yn(r))}function Yo(r,e){return!r||!e?[]:Jo(r,e,r.astNode,!0)}function mi(r,e,t){if(!r||!e)return;let n=Jo(r,e,r.astNode,!0);if(n.length!==0)return t!==void 0?t=Math.max(0,Math.min(t,n.length-1)):t=0,n[t]}function Jo(r,e,t,n){if(!n){let i=nr(r.grammarSource,tt);if(i&&i.feature===e)return[r]}return et(r)&&r.astNode===t?r.content.flatMap(i=>Jo(i,e,t,!1)):[]}function Yh(r,e){return r?Zo(r,e,r?.astNode):[]}function Qo(r,e,t){if(!r)return;let n=Zo(r,e,r?.astNode);if(n.length!==0)return t!==void 0?t=Math.max(0,Math.min(t,n.length-1)):t=0,n[t]}function Zo(r,e,t){if(r.astNode!==t)return[];if(Xe(r.grammarSource)&&r.grammarSource.value===e)return[r];let n=Qt(r).iterator(),i,s=[];do if(i=n.next(),!i.done){let a=i.value;a.astNode===t?Xe(a.grammarSource)&&a.grammarSource.value===e&&s.push(a):n.prune()}while(!i.done);return s}function el(r){var e;let t=r.astNode;for(;t===((e=r.container)===null||e===void 0?void 0:e.astNode);){let n=nr(r.grammarSource,tt);if(n)return n;r=r.container}}function Bs(r){let e=r;return ws(e)&&(kt(e.$container)?e=e.$container.$container:Ce(e.$container)?e=e.$container:ut(e.$container)),oc(r,e,new Map)}function oc(r,e,t){var n;function i(s,a){let o;return nr(s,tt)||(o=oc(a,a,t)),t.set(r,o),o}if(t.has(r))return t.get(r);t.set(r,void 0);for(let s of ct(e)){if(tt(s)&&s.feature.toLowerCase()==="name")return t.set(r,s),s;if(rt(s)&&Ce(s.rule.ref))return i(s,s.rule.ref);if(Ls(s)&&(!((n=s.typeRef)===null||n===void 0)&&n.ref))return i(s,s.typeRef.ref)}}function lc(r){let e=r.$container;if(Gt(e)){let t=e.elements,n=t.indexOf(r);for(let i=n-1;i>=0;i--){let s=t[i];if(kt(s))return s;{let a=ct(t[i]).find(kt);if(a)return a}}}if(ai(e))return lc(e)}function Jh(r,e){return r==="?"||r==="*"||Gt(e)&&!!e.guardCondition}function Qh(r){return r==="*"||r==="+"}function Zh(r){return r==="+="}function gi(r){return uc(r,new Set)}function uc(r,e){if(e.has(r))return!0;e.add(r);for(let t of ct(r))if(rt(t)){if(!t.rule.ref||Ce(t.rule.ref)&&!uc(t.rule.ref,e))return!1}else{if(tt(t))return!1;if(kt(t))return!1}return!!r.definition}function ep(r){return zo(r.type,new Set)}function zo(r,e){if(e.has(r))return!0;if(e.add(r),Ro(r))return!1;if($o(r))return!1;if(No(r))return r.types.every(t=>zo(t,e));if(Ls(r)){if(r.primitiveType!==void 0)return!0;if(r.stringType!==void 0)return!0;if(r.typeRef!==void 0){let t=r.typeRef.ref;return oi(t)?zo(t.type,e):!1}else return!1}else return!1}function gn(r){if(r.inferredType)return r.inferredType.name;if(r.dataType)return r.dataType;if(r.returnType){let e=r.returnType.ref;if(e){if(Ce(e))return e.name;if(_s(e)||oi(e))return e.name}}}function yi(r){var e;if(Ce(r))return gi(r)?r.name:(e=gn(r))!==null&&e!==void 0?e:r.name;if(_s(r)||oi(r)||Io(r))return r.name;if(kt(r)){let t=cc(r);if(t)return t}else if(ws(r))return r.name;throw new Error("Cannot get name of Unknown Type")}function cc(r){var e;if(r.inferredType)return r.inferredType.name;if(!((e=r.type)===null||e===void 0)&&e.ref)return yi(r.type.ref)}function tp(r){var e,t,n;return je(r)?(t=(e=r.type)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:"string":gi(r)?r.name:(n=gn(r))!==null&&n!==void 0?n:r.name}function tl(r){var e,t,n;return je(r)?(t=(e=r.type)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:"string":(n=gn(r))!==null&&n!==void 0?n:r.name}function yn(r){let e={s:!1,i:!1,u:!1},t=Tn(r.definition,e),n=Object.entries(e).filter(([,i])=>i).map(([i])=>i).join("");return new RegExp(t,n)}var rl=/[\s\S]/.source;function Tn(r,e){if(Lo(r))return rp(r);if(Oo(r))return np(r);if(Co(r))return ap(r);if(Ps(r)){let t=r.rule.ref;if(!t)throw new Error("Missing rule reference.");return $t(Tn(t.definition),{cardinality:r.cardinality,lookahead:r.lookahead})}else{if(wo(r))return sp(r);if(Po(r))return ip(r);if(_o(r)){let t=r.regex.lastIndexOf("/"),n=r.regex.substring(1,t),i=r.regex.substring(t+1);return e&&(e.i=i.includes("i"),e.s=i.includes("s"),e.u=i.includes("u")),$t(n,{cardinality:r.cardinality,lookahead:r.lookahead,wrap:!1})}else{if(bo(r))return $t(rl,{cardinality:r.cardinality,lookahead:r.lookahead});throw new Error(`Invalid terminal element: ${r?.$type}`)}}}function rp(r){return $t(r.elements.map(e=>Tn(e)).join("|"),{cardinality:r.cardinality,lookahead:r.lookahead})}function np(r){return $t(r.elements.map(e=>Tn(e)).join(""),{cardinality:r.cardinality,lookahead:r.lookahead})}function ip(r){return $t(`${rl}*?${Tn(r.terminal)}`,{cardinality:r.cardinality,lookahead:r.lookahead})}function sp(r){return $t(`(?!${Tn(r.terminal)})${rl}*?`,{cardinality:r.cardinality,lookahead:r.lookahead})}function ap(r){return r.right?$t(`[${Ho(r.left)}-${Ho(r.right)}]`,{cardinality:r.cardinality,lookahead:r.lookahead,wrap:!1}):$t(Ho(r.left),{cardinality:r.cardinality,lookahead:r.lookahead,wrap:!1})}function Ho(r){return or(r.value)}function $t(r,e){var t;return(e.wrap!==!1||e.lookahead)&&(r=`(${(t=e.lookahead)!==null&&t!==void 0?t:""}${r})`),e.cardinality?`${r}${e.cardinality}`:r}function nl(r){let e=[],t=r.Grammar;for(let n of t.rules)je(n)&&Xo(n)&&Ko(yn(n))&&e.push(n.name);return{multilineCommentRules:e,nameRegexp:Ns}}function Rn(r){console&&console.error&&console.error(`Error: ${r}`)}function Ti(r){console&&console.warn&&console.warn(`Warning: ${r}`)}function Ri(r){let e=new Date().getTime(),t=r();return{time:new Date().getTime()-e,value:t}}function xi(r){function e(){}e.prototype=r;let t=new e;function n(){return typeof t.bar}return n(),n(),r;(0,eval)(r)}function op(r){return lp(r)?r.LABEL:r.name}function lp(r){return Ie(r.LABEL)&&r.LABEL!==""}var He=class{get definition(){return this._definition}set definition(e){this._definition=e}constructor(e){this._definition=e}accept(e){e.visit(this),k(this.definition,t=>{t.accept(e)})}},j=class extends He{constructor(e){super([]),this.idx=1,ve(this,Ke(e,t=>t!==void 0))}set definition(e){}get definition(){return this.referencedRule!==void 0?this.referencedRule.definition:[]}accept(e){e.visit(this)}},be=class extends He{constructor(e){super(e.definition),this.orgText="",ve(this,Ke(e,t=>t!==void 0))}},Y=class extends He{constructor(e){super(e.definition),this.ignoreAmbiguities=!1,ve(this,Ke(e,t=>t!==void 0))}},H=class extends He{constructor(e){super(e.definition),this.idx=1,ve(this,Ke(e,t=>t!==void 0))}},J=class extends He{constructor(e){super(e.definition),this.idx=1,ve(this,Ke(e,t=>t!==void 0))}},Q=class extends He{constructor(e){super(e.definition),this.idx=1,ve(this,Ke(e,t=>t!==void 0))}},F=class extends He{constructor(e){super(e.definition),this.idx=1,ve(this,Ke(e,t=>t!==void 0))}},z=class extends He{constructor(e){super(e.definition),this.idx=1,ve(this,Ke(e,t=>t!==void 0))}},q=class extends He{get definition(){return this._definition}set definition(e){this._definition=e}constructor(e){super(e.definition),this.idx=1,this.ignoreAmbiguities=!1,this.hasPredicates=!1,ve(this,Ke(e,t=>t!==void 0))}},M=class{constructor(e){this.idx=1,ve(this,Ke(e,t=>t!==void 0))}accept(e){e.visit(this)}};function Ks(r){return x(r,xn)}function xn(r){function e(t){return x(t,xn)}if(r instanceof j){let t={type:"NonTerminal",name:r.nonTerminalName,idx:r.idx};return Ie(r.label)&&(t.label=r.label),t}else{if(r instanceof Y)return{type:"Alternative",definition:e(r.definition)};if(r instanceof H)return{type:"Option",idx:r.idx,definition:e(r.definition)};if(r instanceof J)return{type:"RepetitionMandatory",idx:r.idx,definition:e(r.definition)};if(r instanceof Q)return{type:"RepetitionMandatoryWithSeparator",idx:r.idx,separator:xn(new M({terminalType:r.separator})),definition:e(r.definition)};if(r instanceof z)return{type:"RepetitionWithSeparator",idx:r.idx,separator:xn(new M({terminalType:r.separator})),definition:e(r.definition)};if(r instanceof F)return{type:"Repetition",idx:r.idx,definition:e(r.definition)};if(r instanceof q)return{type:"Alternation",idx:r.idx,definition:e(r.definition)};if(r instanceof M){let t={type:"Terminal",name:r.terminalType.name,label:op(r.terminalType),idx:r.idx};Ie(r.label)&&(t.terminalLabel=r.label);let n=r.terminalType.PATTERN;return r.terminalType.PATTERN&&(t.pattern=Ze(n)?n.source:n),t}else{if(r instanceof be)return{type:"Rule",name:r.name,orgText:r.orgText,definition:e(r.definition)};throw Error("non exhaustive match")}}}var Me=class{visit(e){let t=e;switch(t.constructor){case j:return this.visitNonTerminal(t);case Y:return this.visitAlternative(t);case H:return this.visitOption(t);case J:return this.visitRepetitionMandatory(t);case Q:return this.visitRepetitionMandatoryWithSeparator(t);case z:return this.visitRepetitionWithSeparator(t);case F:return this.visitRepetition(t);case q:return this.visitAlternation(t);case M:return this.visitTerminal(t);case be:return this.visitRule(t);default:throw Error("non exhaustive match")}}visitNonTerminal(e){}visitAlternative(e){}visitOption(e){}visitRepetition(e){}visitRepetitionMandatory(e){}visitRepetitionMandatoryWithSeparator(e){}visitRepetitionWithSeparator(e){}visitAlternation(e){}visitTerminal(e){}visitRule(e){}};function il(r){return r instanceof Y||r instanceof H||r instanceof F||r instanceof J||r instanceof Q||r instanceof z||r instanceof M||r instanceof be}function lr(r,e=[]){return r instanceof H||r instanceof F||r instanceof z?!0:r instanceof q?$s(r.definition,n=>lr(n,e)):r instanceof j&&ae(e,r)?!1:r instanceof He?(r instanceof j&&e.push(r),Oe(r.definition,n=>lr(n,e))):!1}function sl(r){return r instanceof q}function Be(r){if(r instanceof j)return"SUBRULE";if(r instanceof H)return"OPTION";if(r instanceof q)return"OR";if(r instanceof J)return"AT_LEAST_ONE";if(r instanceof Q)return"AT_LEAST_ONE_SEP";if(r instanceof z)return"MANY_SEP";if(r instanceof F)return"MANY";if(r instanceof M)return"CONSUME";throw Error("non exhaustive match")}var It=class{walk(e,t=[]){k(e.definition,(n,i)=>{let s=he(e.definition,i+1);if(n instanceof j)this.walkProdRef(n,s,t);else if(n instanceof M)this.walkTerminal(n,s,t);else if(n instanceof Y)this.walkFlat(n,s,t);else if(n instanceof H)this.walkOption(n,s,t);else if(n instanceof J)this.walkAtLeastOne(n,s,t);else if(n instanceof Q)this.walkAtLeastOneSep(n,s,t);else if(n instanceof z)this.walkManySep(n,s,t);else if(n instanceof F)this.walkMany(n,s,t);else if(n instanceof q)this.walkOr(n,s,t);else throw Error("non exhaustive match")})}walkTerminal(e,t,n){}walkProdRef(e,t,n){}walkFlat(e,t,n){let i=t.concat(n);this.walk(e,i)}walkOption(e,t,n){let i=t.concat(n);this.walk(e,i)}walkAtLeastOne(e,t,n){let i=[new H({definition:e.definition})].concat(t,n);this.walk(e,i)}walkAtLeastOneSep(e,t,n){let i=fc(e,t,n);this.walk(e,i)}walkMany(e,t,n){let i=[new H({definition:e.definition})].concat(t,n);this.walk(e,i)}walkManySep(e,t,n){let i=fc(e,t,n);this.walk(e,i)}walkOr(e,t,n){let i=t.concat(n);k(e.definition,s=>{let a=new Y({definition:[s]});this.walk(a,i)})}};function fc(r,e,t){return[new H({definition:[new M({terminalType:r.separator})].concat(r.definition)})].concat(e,t)}function ur(r){if(r instanceof j)return ur(r.referencedRule);if(r instanceof M)return fp(r);if(il(r))return up(r);if(sl(r))return cp(r);throw Error("non exhaustive match")}function up(r){let e=[],t=r.definition,n=0,i=t.length>n,s,a=!0;for(;i&&a;)s=t[n],a=lr(s),e=e.concat(ur(s)),n=n+1,i=t.length>n;return Jn(e)}function cp(r){let e=x(r.definition,t=>ur(t));return Jn(de(e))}function fp(r){return[r.terminalType]}var Vs="_~IN~_";var al=class extends It{constructor(e){super(),this.topProd=e,this.follows={}}startWalking(){return this.walk(this.topProd),this.follows}walkTerminal(e,t,n){}walkProdRef(e,t,n){let i=dp(e.referencedRule,e.idx)+this.topProd.name,s=t.concat(n),a=new Y({definition:s}),o=ur(a);this.follows[i]=o}};function dc(r){let e={};return k(r,t=>{let n=new al(t).startWalking();ve(e,n)}),e}function dp(r,e){return r.name+e+Vs}var js={},hp=new sr;function En(r){let e=r.toString();if(js.hasOwnProperty(e))return js[e];{let t=hp.pattern(e);return js[e]=t,t}}function hc(){js={}}var mc="Complement Sets are not supported for first char optimization",Ei=`Unable to use "first char" lexer optimizations: +`;function gc(r,e=!1){try{let t=En(r);return ol(t.value,{},t.flags.ignoreCase)}catch(t){if(t.message===mc)e&&Ti(`${Ei} Unable to optimize: < ${r.toString()} > + Complement Sets cannot be automatically optimized. + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{let n="";e&&(n=` + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`),Rn(`${Ei} + Failed parsing: < ${r.toString()} > + Using the @chevrotain/regexp-to-ast library + Please open an issue at: https://github.com/chevrotain/chevrotain/issues`+n)}}return[]}function ol(r,e,t){switch(r.type){case"Disjunction":for(let i=0;i{if(typeof l=="number")Hs(l,e,t);else{let u=l;if(t===!0)for(let c=u.from;c<=u.to;c++)Hs(c,e,t);else{for(let c=u.from;c<=u.to&&c=An){let c=u.from>=An?u.from:An,f=u.to,d=dt(c),h=dt(f);for(let m=d;m<=h;m++)e[m]=m}}}});break;case"Group":ol(a.value,e,t);break;default:throw Error("Non Exhaustive Match")}let o=a.quantifier!==void 0&&a.quantifier.atLeast===0;if(a.type==="Group"&&ll(a)===!1||a.type!=="Group"&&o===!1)break}break;default:throw Error("non exhaustive match!")}return te(e)}function Hs(r,e,t){let n=dt(r);e[n]=n,t===!0&&pp(r,e)}function pp(r,e){let t=String.fromCharCode(r),n=t.toUpperCase();if(n!==t){let i=dt(n.charCodeAt(0));e[i]=i}else{let i=t.toLowerCase();if(i!==t){let s=dt(i.charCodeAt(0));e[s]=s}}}function pc(r,e){return vt(r.value,t=>{if(typeof t=="number")return ae(e,t);{let n=t;return vt(e,i=>n.from<=i&&i<=n.to)!==void 0}})}function ll(r){let e=r.quantifier;return e&&e.atLeast===0?!0:r.value?me(r.value)?Oe(r.value,ll):ll(r.value):!1}var ul=class extends ft{constructor(e){super(),this.targetCharCodes=e,this.found=!1}visitChildren(e){if(this.found!==!0){switch(e.type){case"Lookahead":this.visitLookahead(e);return;case"NegativeLookahead":this.visitNegativeLookahead(e);return}super.visitChildren(e)}}visitCharacter(e){ae(this.targetCharCodes,e.value)&&(this.found=!0)}visitSet(e){e.complement?pc(e,this.targetCharCodes)===void 0&&(this.found=!0):pc(e,this.targetCharCodes)!==void 0&&(this.found=!0)}};function zs(r,e){if(e instanceof RegExp){let t=En(e),n=new ul(r);return n.visit(t),n.found}else return vt(e,t=>ae(r,t.charCodeAt(0)))!==void 0}var cr="PATTERN",vn="defaultMode",qs="modes",fl=typeof new RegExp("(?:)").sticky=="boolean";function Rc(r,e){e=Yn(e,{useSticky:fl,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",` +`],tracer:(E,T)=>T()});let t=e.tracer;t("initCharCodeToOptimizedIndexMap",()=>{Lp()});let n;t("Reject Lexer.NA",()=>{n=Xt(r,E=>E[cr]===ie.NA)});let i=!1,s;t("Transform Patterns",()=>{i=!1,s=x(n,E=>{let T=E[cr];if(Ze(T)){let O=T.source;return O.length===1&&O!=="^"&&O!=="$"&&O!=="."&&!T.ignoreCase?O:O.length===2&&O[0]==="\\"&&!ae(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],O[1])?O[1]:e.useSticky?Tc(T):yc(T)}else{if(at(T))return i=!0,{exec:T};if(typeof T=="object")return i=!0,T;if(typeof T=="string"){if(T.length===1)return T;{let O=T.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),P=new RegExp(O);return e.useSticky?Tc(P):yc(P)}}else throw Error("non exhaustive match")}})});let a,o,l,u,c;t("misc mapping",()=>{a=x(n,E=>E.tokenTypeIdx),o=x(n,E=>{let T=E.GROUP;if(T!==ie.SKIPPED){if(Ie(T))return T;if(Pe(T))return!1;throw Error("non exhaustive match")}}),l=x(n,E=>{let T=E.LONGER_ALT;if(T)return me(T)?x(T,P=>fo(n,P)):[fo(n,T)]}),u=x(n,E=>E.PUSH_MODE),c=x(n,E=>$(E,"POP_MODE"))});let f;t("Line Terminator Handling",()=>{let E=Nc(e.lineTerminatorCharacters);f=x(n,T=>!1),e.positionTracking!=="onlyOffset"&&(f=x(n,T=>$(T,"LINE_BREAKS")?!!T.LINE_BREAKS:Ic(T,E)===!1&&zs(E,T.PATTERN)))});let d,h,m,g;t("Misc Mapping #2",()=>{d=x(n,kc),h=x(s,wp),m=le(n,(E,T)=>{let O=T.GROUP;return Ie(O)&&O!==ie.SKIPPED&&(E[O]=[]),E},{}),g=x(s,(E,T)=>({pattern:s[T],longerAlt:l[T],canLineTerminator:f[T],isCustom:d[T],short:h[T],group:o[T],push:u[T],pop:c[T],tokenTypeIdx:a[T],tokenType:n[T]}))});let A=!0,R=[];return e.safeMode||t("First Char Optimization",()=>{R=le(n,(E,T,O)=>{if(typeof T.PATTERN=="string"){let P=T.PATTERN.charCodeAt(0),ye=dt(P);cl(E,ye,g[O])}else if(me(T.START_CHARS_HINT)){let P;k(T.START_CHARS_HINT,ye=>{let vr=typeof ye=="string"?ye.charCodeAt(0):ye,Ee=dt(vr);P!==Ee&&(P=Ee,cl(E,Ee,g[O]))})}else if(Ze(T.PATTERN))if(T.PATTERN.unicode)A=!1,e.ensureOptimizations&&Rn(`${Ei} Unable to analyze < ${T.PATTERN.toString()} > pattern. + The regexp unicode flag is not currently supported by the regexp-to-ast library. + This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{let P=gc(T.PATTERN,e.ensureOptimizations);b(P)&&(A=!1),k(P,ye=>{cl(E,ye,g[O])})}else e.ensureOptimizations&&Rn(`${Ei} TokenType: <${T.name}> is using a custom token pattern without providing parameter. + This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),A=!1;return E},[])}),{emptyGroups:m,patternIdxToConfig:g,charCodeToPatternIdxToConfig:R,hasCustom:i,canBeOptimized:A}}function xc(r,e){let t=[],n=gp(r);t=t.concat(n.errors);let i=yp(n.valid),s=i.valid;return t=t.concat(i.errors),t=t.concat(mp(s)),t=t.concat($p(s)),t=t.concat(Ip(s,e)),t=t.concat(Np(s)),t}function mp(r){let e=[],t=Re(r,n=>Ze(n[cr]));return e=e.concat(Rp(t)),e=e.concat(Ap(t)),e=e.concat(vp(t)),e=e.concat(kp(t)),e=e.concat(xp(t)),e}function gp(r){let e=Re(r,i=>!$(i,cr)),t=x(e,i=>({message:"Token Type: ->"+i.name+"<- missing static 'PATTERN' property",type:ne.MISSING_PATTERN,tokenTypes:[i]})),n=qt(r,e);return{errors:t,valid:n}}function yp(r){let e=Re(r,i=>{let s=i[cr];return!Ze(s)&&!at(s)&&!$(s,"exec")&&!Ie(s)}),t=x(e,i=>({message:"Token Type: ->"+i.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:ne.INVALID_PATTERN,tokenTypes:[i]})),n=qt(r,e);return{errors:t,valid:n}}var Tp=/[^\\][$]/;function Rp(r){class e extends ft{constructor(){super(...arguments),this.found=!1}visitEndAnchor(s){this.found=!0}}let t=Re(r,i=>{let s=i.PATTERN;try{let a=En(s),o=new e;return o.visit(a),o.found}catch{return Tp.test(s.source)}});return x(t,i=>({message:`Unexpected RegExp Anchor Error: + Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain end of input anchor '$' + See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:ne.EOI_ANCHOR_FOUND,tokenTypes:[i]}))}function xp(r){let e=Re(r,n=>n.PATTERN.test(""));return x(e,n=>({message:"Token Type: ->"+n.name+"<- static 'PATTERN' must not match an empty string",type:ne.EMPTY_MATCH_PATTERN,tokenTypes:[n]}))}var Ep=/[^\\[][\^]|^\^/;function Ap(r){class e extends ft{constructor(){super(...arguments),this.found=!1}visitStartAnchor(s){this.found=!0}}let t=Re(r,i=>{let s=i.PATTERN;try{let a=En(s),o=new e;return o.visit(a),o.found}catch{return Ep.test(s.source)}});return x(t,i=>({message:`Unexpected RegExp Anchor Error: + Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain start of input anchor '^' + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:ne.SOI_ANCHOR_FOUND,tokenTypes:[i]}))}function vp(r){let e=Re(r,n=>{let i=n[cr];return i instanceof RegExp&&(i.multiline||i.global)});return x(e,n=>({message:"Token Type: ->"+n.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:ne.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[n]}))}function kp(r){let e=[],t=x(r,s=>le(r,(a,o)=>(s.PATTERN.source===o.PATTERN.source&&!ae(e,o)&&o.PATTERN!==ie.NA&&(e.push(o),a.push(o)),a),[]));t=Et(t);let n=Re(t,s=>s.length>1);return x(n,s=>{let a=x(s,l=>l.name);return{message:`The same RegExp pattern ->${ke(s).PATTERN}<-has been used in all of the following Token Types: ${a.join(", ")} <-`,type:ne.DUPLICATE_PATTERNS_FOUND,tokenTypes:s}})}function $p(r){let e=Re(r,n=>{if(!$(n,"GROUP"))return!1;let i=n.GROUP;return i!==ie.SKIPPED&&i!==ie.NA&&!Ie(i)});return x(e,n=>({message:"Token Type: ->"+n.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:ne.INVALID_GROUP_TYPE_FOUND,tokenTypes:[n]}))}function Ip(r,e){let t=Re(r,i=>i.PUSH_MODE!==void 0&&!ae(e,i.PUSH_MODE));return x(t,i=>({message:`Token Type: ->${i.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${i.PUSH_MODE}<-which does not exist`,type:ne.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[i]}))}function Np(r){let e=[],t=le(r,(n,i,s)=>{let a=i.PATTERN;return a===ie.NA||(Ie(a)?n.push({str:a,idx:s,tokenType:i}):Ze(a)&&Sp(a)&&n.push({str:a.source,idx:s,tokenType:i})),n},[]);return k(r,(n,i)=>{k(t,({str:s,idx:a,tokenType:o})=>{if(i${o.name}<- can never be matched. +Because it appears AFTER the Token Type ->${n.name}<-in the lexer's definition. +See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;e.push({message:l,type:ne.UNREACHABLE_PATTERN,tokenTypes:[n,o]})}})}),e}function Cp(r,e){if(Ze(e)){let t=e.exec(r);return t!==null&&t.index===0}else{if(at(e))return e(r,0,[],{});if($(e,"exec"))return e.exec(r,0,[],{});if(typeof e=="string")return e===r;throw Error("non exhaustive match")}}function Sp(r){return vt([".","\\","[","]","|","^","$","(",")","?","*","+","{"],t=>r.source.indexOf(t)!==-1)===void 0}function yc(r){let e=r.ignoreCase?"i":"";return new RegExp(`^(?:${r.source})`,e)}function Tc(r){let e=r.ignoreCase?"iy":"y";return new RegExp(`${r.source}`,e)}function Ec(r,e,t){let n=[];return $(r,vn)||n.push({message:"A MultiMode Lexer cannot be initialized without a <"+vn+`> property in its definition +`,type:ne.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),$(r,qs)||n.push({message:"A MultiMode Lexer cannot be initialized without a <"+qs+`> property in its definition +`,type:ne.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),$(r,qs)&&$(r,vn)&&!$(r.modes,r.defaultMode)&&n.push({message:`A MultiMode Lexer cannot be initialized with a ${vn}: <${r.defaultMode}>which does not exist +`,type:ne.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),$(r,qs)&&k(r.modes,(i,s)=>{k(i,(a,o)=>{if(Pe(a))n.push({message:`A Lexer cannot be initialized using an undefined Token Type. Mode:<${s}> at index: <${o}> +`,type:ne.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED});else if($(a,"LONGER_ALT")){let l=me(a.LONGER_ALT)?a.LONGER_ALT:[a.LONGER_ALT];k(l,u=>{!Pe(u)&&!ae(i,u)&&n.push({message:`A MultiMode Lexer cannot be initialized with a longer_alt <${u.name}> on token <${a.name}> outside of mode <${s}> +`,type:ne.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE})})}})}),n}function Ac(r,e,t){let n=[],i=!1,s=Et(de(te(r.modes))),a=Xt(s,l=>l[cr]===ie.NA),o=Nc(t);return e&&k(a,l=>{let u=Ic(l,o);if(u!==!1){let f={message:_p(l,u),type:u.issue,tokenType:l};n.push(f)}else $(l,"LINE_BREAKS")?l.LINE_BREAKS===!0&&(i=!0):zs(o,l.PATTERN)&&(i=!0)}),e&&!i&&n.push({message:`Warning: No LINE_BREAKS Found. + This Lexer has been defined to track line and column information, + But none of the Token Types can be identified as matching a line terminator. + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS + for details.`,type:ne.NO_LINE_BREAKS_FLAGS}),n}function vc(r){let e={},t=xt(r);return k(t,n=>{let i=r[n];if(me(i))e[n]=[];else throw Error("non exhaustive match")}),e}function kc(r){let e=r.PATTERN;if(Ze(e))return!1;if(at(e))return!0;if($(e,"exec"))return!0;if(Ie(e))return!1;throw Error("non exhaustive match")}function wp(r){return Ie(r)&&r.length===1?r.charCodeAt(0):!1}var $c={test:function(r){let e=r.length;for(let t=this.lastIndex;t Token Type + Root cause: ${e.errMsg}. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR`;if(e.issue===ne.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the option. + The problem is in the <${r.name}> Token Type + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`;throw Error("non exhaustive match")}function Nc(r){return x(r,t=>Ie(t)?t.charCodeAt(0):t)}function cl(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}var An=256,Xs=[];function dt(r){return r255?255+~~(r/255):r}}function Nt(r,e){let t=r.tokenTypeIdx;return t===e.tokenTypeIdx?!0:e.isParent===!0&&e.categoryMatchesMap[t]===!0}function kn(r,e){return r.tokenTypeIdx===e.tokenTypeIdx}var Cc=1,wc={};function Ct(r){let e=Op(r);Pp(e),Mp(e),bp(e),k(e,t=>{t.isParent=t.categoryMatches.length>0})}function Op(r){let e=ee(r),t=r,n=!0;for(;n;){t=Et(de(x(t,s=>s.CATEGORIES)));let i=qt(t,e);e=e.concat(i),b(i)?n=!1:t=i}return e}function Pp(r){k(r,e=>{dl(e)||(wc[Cc]=e,e.tokenTypeIdx=Cc++),Sc(e)&&!me(e.CATEGORIES)&&(e.CATEGORIES=[e.CATEGORIES]),Sc(e)||(e.CATEGORIES=[]),Dp(e)||(e.categoryMatches=[]),Fp(e)||(e.categoryMatchesMap={})})}function bp(r){k(r,e=>{e.categoryMatches=[],k(e.categoryMatchesMap,(t,n)=>{e.categoryMatches.push(wc[n].tokenTypeIdx)})})}function Mp(r){k(r,e=>{_c([],e)})}function _c(r,e){k(r,t=>{e.categoryMatchesMap[t.tokenTypeIdx]=!0}),k(e.CATEGORIES,t=>{let n=r.concat(e);ae(n,t)||_c(n,t)})}function dl(r){return $(r,"tokenTypeIdx")}function Sc(r){return $(r,"CATEGORIES")}function Dp(r){return $(r,"categoryMatches")}function Fp(r){return $(r,"categoryMatchesMap")}function Lc(r){return $(r,"tokenTypeIdx")}var $n={buildUnableToPopLexerModeMessage(r){return`Unable to pop Lexer Mode after encountering Token ->${r.image}<- The Mode Stack is empty`},buildUnexpectedCharactersMessage(r,e,t,n,i){return`unexpected character: ->${r.charAt(e)}<- at offset: ${e}, skipped ${t} characters.`}};var ne;(function(r){r[r.MISSING_PATTERN=0]="MISSING_PATTERN",r[r.INVALID_PATTERN=1]="INVALID_PATTERN",r[r.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",r[r.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",r[r.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",r[r.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",r[r.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",r[r.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",r[r.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",r[r.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",r[r.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",r[r.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",r[r.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",r[r.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",r[r.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",r[r.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",r[r.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK",r[r.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE=17]="MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE"})(ne||(ne={}));var Ai={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[` +`,"\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:$n,traceInitPerf:!1,skipValidations:!1,recoveryEnabled:!0};Object.freeze(Ai);var ie=class{constructor(e,t=Ai){if(this.lexerDefinition=e,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},this.TRACE_INIT=(i,s)=>{if(this.traceInitPerf===!0){this.traceInitIndent++;let a=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${i}>`);let{time:o,value:l}=Ri(s),u=o>10?console.warn:console.log;return this.traceInitIndent time: ${o}ms`),this.traceInitIndent--,l}else return s()},typeof t=="boolean")throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. +a boolean 2nd argument is no longer supported`);this.config=ve({},Ai,t);let n=this.config.traceInitPerf;n===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof n=="number"&&(this.traceInitMaxIdent=n,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",()=>{let i,s=!0;this.TRACE_INIT("Lexer Config handling",()=>{if(this.config.lineTerminatorsPattern===Ai.lineTerminatorsPattern)this.config.lineTerminatorsPattern=$c;else if(this.config.lineTerminatorCharacters===Ai.lineTerminatorCharacters)throw Error(`Error: Missing property on the Lexer config. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if(t.safeMode&&t.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');this.trackStartLines=/full|onlyStart/i.test(this.config.positionTracking),this.trackEndLines=/full/i.test(this.config.positionTracking),me(e)?i={modes:{defaultMode:ee(e)},defaultMode:vn}:(s=!1,i=ee(e))}),this.config.skipValidations===!1&&(this.TRACE_INIT("performRuntimeChecks",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(Ec(i,this.trackStartLines,this.config.lineTerminatorCharacters))}),this.TRACE_INIT("performWarningRuntimeChecks",()=>{this.lexerDefinitionWarning=this.lexerDefinitionWarning.concat(Ac(i,this.trackStartLines,this.config.lineTerminatorCharacters))})),i.modes=i.modes?i.modes:{},k(i.modes,(o,l)=>{i.modes[l]=Xt(o,u=>Pe(u))});let a=xt(i.modes);if(k(i.modes,(o,l)=>{this.TRACE_INIT(`Mode: <${l}> processing`,()=>{if(this.modes.push(l),this.config.skipValidations===!1&&this.TRACE_INIT("validatePatterns",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(xc(o,a))}),b(this.lexerDefinitionErrors)){Ct(o);let u;this.TRACE_INIT("analyzeTokenTypes",()=>{u=Rc(o,{lineTerminatorCharacters:this.config.lineTerminatorCharacters,positionTracking:t.positionTracking,ensureOptimizations:t.ensureOptimizations,safeMode:t.safeMode,tracer:this.TRACE_INIT})}),this.patternIdxToConfig[l]=u.patternIdxToConfig,this.charCodeToPatternIdxToConfig[l]=u.charCodeToPatternIdxToConfig,this.emptyGroups=ve({},this.emptyGroups,u.emptyGroups),this.hasCustom=u.hasCustom||this.hasCustom,this.canModeBeOptimized[l]=u.canBeOptimized}})}),this.defaultMode=i.defaultMode,!b(this.lexerDefinitionErrors)&&!this.config.deferDefinitionErrorsHandling){let l=x(this.lexerDefinitionErrors,u=>u.message).join(`----------------------- +`);throw new Error(`Errors detected in definition of Lexer: +`+l)}k(this.lexerDefinitionWarning,o=>{Ti(o.message)}),this.TRACE_INIT("Choosing sub-methods implementations",()=>{if(fl?(this.chopInput=co,this.match=this.matchWithTest):(this.updateLastIndex=fe,this.match=this.matchWithExec),s&&(this.handleModes=fe),this.trackStartLines===!1&&(this.computeNewColumn=co),this.trackEndLines===!1&&(this.updateTokenEndLineColumnLocation=fe),/full/i.test(this.config.positionTracking))this.createTokenInstance=this.createFullToken;else if(/onlyStart/i.test(this.config.positionTracking))this.createTokenInstance=this.createStartOnlyToken;else if(/onlyOffset/i.test(this.config.positionTracking))this.createTokenInstance=this.createOffsetOnlyToken;else throw Error(`Invalid config option: "${this.config.positionTracking}"`);this.hasCustom?(this.addToken=this.addTokenUsingPush,this.handlePayload=this.handlePayloadWithCustom):(this.addToken=this.addTokenUsingMemberAccess,this.handlePayload=this.handlePayloadNoCustom)}),this.TRACE_INIT("Failed Optimization Warnings",()=>{let o=le(this.canModeBeOptimized,(l,u,c)=>(u===!1&&l.push(c),l),[]);if(t.ensureOptimizations&&!b(o))throw Error(`Lexer Modes: < ${o.join(", ")} > cannot be optimized. + Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. + Or inspect the console log for details on how to resolve these issues.`)}),this.TRACE_INIT("clearRegExpParserCache",()=>{hc()}),this.TRACE_INIT("toFastProperties",()=>{xi(this)})})}tokenize(e,t=this.defaultMode){if(!b(this.lexerDefinitionErrors)){let i=x(this.lexerDefinitionErrors,s=>s.message).join(`----------------------- +`);throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer: +`+i)}return this.tokenizeInternal(e,t)}tokenizeInternal(e,t){let n,i,s,a,o,l,u,c,f,d,h,m,g,A,R,E,T=e,O=T.length,P=0,ye=0,vr=this.hasCustom?0:Math.floor(e.length/10),Ee=new Array(vr),bt=[],yt=this.trackStartLines?1:void 0,v=this.trackStartLines?1:void 0,y=vc(this.emptyGroups),N=this.trackStartLines,I=this.config.lineTerminatorsPattern,K=0,L=[],_=[],_e=[],Le=[];Object.freeze(Le);let Z;function jt(){return L}function Gu(Ae){let qe=dt(Ae),kr=_[qe];return kr===void 0?Le:kr}let Ah=Ae=>{if(_e.length===1&&Ae.tokenType.PUSH_MODE===void 0){let qe=this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(Ae);bt.push({offset:Ae.startOffset,line:Ae.startLine,column:Ae.startColumn,length:Ae.image.length,message:qe})}else{_e.pop();let qe=At(_e);L=this.patternIdxToConfig[qe],_=this.charCodeToPatternIdxToConfig[qe],K=L.length;let kr=this.canModeBeOptimized[qe]&&this.config.safeMode===!1;_&&kr?Z=Gu:Z=jt}};function Uu(Ae){_e.push(Ae),_=this.charCodeToPatternIdxToConfig[Ae],L=this.patternIdxToConfig[Ae],K=L.length,K=L.length;let qe=this.canModeBeOptimized[Ae]&&this.config.safeMode===!1;_&&qe?Z=Gu:Z=jt}Uu.call(this,t);let Qe,Bu=this.config.recoveryEnabled;for(;Pl.length){l=a,u=c,Qe=Rt;break}}}break}}if(l!==null){if(f=l.length,d=Qe.group,d!==void 0&&(h=Qe.tokenTypeIdx,m=this.createTokenInstance(l,P,h,Qe.tokenType,yt,v,f),this.handlePayload(m,u),d===!1?ye=this.addToken(Ee,ye,m):y[d].push(m)),e=this.chopInput(e,f),P=P+f,v=this.computeNewColumn(v,f),N===!0&&Qe.canLineTerminator===!0){let We=0,Tt,Mt;I.lastIndex=0;do Tt=I.test(l),Tt===!0&&(Mt=I.lastIndex-1,We++);while(Tt===!0);We!==0&&(yt=yt+We,v=f-Mt,this.updateTokenEndLineColumnLocation(m,d,Mt,We,yt,v,f))}this.handleModes(Qe,Ah,Uu,m)}else{let We=P,Tt=yt,Mt=v,Rt=Bu===!1;for(;Rt===!1&&P ${St(r)} <--`:`token of type --> ${r.name} <--`} but found --> '${e.image}' <--`},buildNotAllInputParsedMessage({firstRedundant:r,ruleName:e}){return"Redundant input, expecting EOF but found: "+r.image},buildNoViableAltMessage({expectedPathsPerAlt:r,actual:e,previous:t,customUserDescription:n,ruleName:i}){let s="Expecting: ",o=` +but found: '`+ke(e).image+"'";if(n)return s+n+o;{let l=le(r,(d,h)=>d.concat(h),[]),u=x(l,d=>`[${x(d,h=>St(h)).join(", ")}]`),f=`one of these possible Token sequences: +${x(u,(d,h)=>` ${h+1}. ${d}`).join(` +`)}`;return s+f+o}},buildEarlyExitMessage({expectedIterationPaths:r,actual:e,customUserDescription:t,ruleName:n}){let i="Expecting: ",a=` +but found: '`+ke(e).image+"'";if(t)return i+t+a;{let l=`expecting at least one iteration which starts with one of these possible Token sequences:: + <${x(r,u=>`[${x(u,c=>St(c)).join(",")}]`).join(" ,")}>`;return i+l+a}}};Object.freeze(_t);var Bc={buildRuleNotFoundError(r,e){return"Invalid grammar, reference to a rule which is not defined: ->"+e.nonTerminalName+`<- +inside top level rule: ->`+r.name+"<-"}},nt={buildDuplicateFoundError(r,e){function t(c){return c instanceof M?c.terminalType.name:c instanceof j?c.nonTerminalName:""}let n=r.name,i=ke(e),s=i.idx,a=Be(i),o=t(i),l=s>0,u=`->${a}${l?s:""}<- ${o?`with argument: ->${o}<-`:""} + appears more than once (${e.length} times) in the top level rule: ->${n}<-. + For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES + `;return u=u.replace(/[ \t]+/g," "),u=u.replace(/\s\s+/g,` +`),u},buildNamespaceConflictError(r){return`Namespace conflict found in grammar. +The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${r.name}>. +To resolve this make sure each Terminal and Non-Terminal names are unique +This is easy to accomplish by using the convention that Terminal names start with an uppercase letter +and Non-Terminal names start with a lower case letter.`},buildAlternationPrefixAmbiguityError(r){let e=x(r.prefixPath,i=>St(i)).join(", "),t=r.alternation.idx===0?"":r.alternation.idx;return`Ambiguous alternatives: <${r.ambiguityIndices.join(" ,")}> due to common lookahead prefix +in inside <${r.topLevelRule.name}> Rule, +<${e}> may appears as a prefix path in all these alternatives. +See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX +For Further details.`},buildAlternationAmbiguityError(r){let e=x(r.prefixPath,i=>St(i)).join(", "),t=r.alternation.idx===0?"":r.alternation.idx,n=`Ambiguous Alternatives Detected: <${r.ambiguityIndices.join(" ,")}> in inside <${r.topLevelRule.name}> Rule, +<${e}> may appears as a prefix path in all these alternatives. +`;return n=n+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES +For Further details.`,n},buildEmptyRepetitionError(r){let e=Be(r.repetition);return r.repetition.idx!==0&&(e+=r.repetition.idx),`The repetition <${e}> within Rule <${r.topLevelRule.name}> can never consume any tokens. +This could lead to an infinite loop.`},buildTokenNameError(r){return"deprecated"},buildEmptyAlternationError(r){return`Ambiguous empty alternative: <${r.emptyChoiceIdx+1}> in inside <${r.topLevelRule.name}> Rule. +Only the last alternative may be an empty alternative.`},buildTooManyAlternativesError(r){return`An Alternation cannot have more than 256 alternatives: + inside <${r.topLevelRule.name}> Rule. + has ${r.alternation.definition.length+1} alternatives.`},buildLeftRecursionError(r){let e=r.topLevelRule.name,t=x(r.leftRecursionPath,s=>s.name),n=`${e} --> ${t.concat([e]).join(" --> ")}`;return`Left Recursion found in grammar. +rule: <${e}> can be invoked from itself (directly or indirectly) +without consuming any Tokens. The grammar path that causes this is: + ${n} + To fix this refactor your grammar to remove the left recursion. +see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`},buildInvalidRuleNameError(r){return"deprecated"},buildDuplicateRuleNameError(r){let e;return r.topLevelRule instanceof be?e=r.topLevelRule.name:e=r.topLevelRule,`Duplicate definition, rule: ->${e}<- is already defined in the grammar: ->${r.grammarName}<-`}};function Wc(r,e){let t=new pl(r,e);return t.resolveRefs(),t.errors}var pl=class extends Me{constructor(e,t){super(),this.nameToTopRule=e,this.errMsgProvider=t,this.errors=[]}resolveRefs(){k(te(this.nameToTopRule),e=>{this.currTopLevel=e,e.accept(this)})}visitNonTerminal(e){let t=this.nameToTopRule[e.nonTerminalName];if(t)e.referencedRule=t;else{let n=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,e);this.errors.push({message:n,type:ge.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:e.nonTerminalName})}}};var ml=class extends It{constructor(e,t){super(),this.topProd=e,this.path=t,this.possibleTokTypes=[],this.nextProductionName="",this.nextProductionOccurrence=0,this.found=!1,this.isAtEndOfPath=!1}startWalking(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=ee(this.path.ruleStack).reverse(),this.occurrenceStack=ee(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes}walk(e,t=[]){this.found||super.walk(e,t)}walkProdRef(e,t,n){if(e.referencedRule.name===this.nextProductionName&&e.idx===this.nextProductionOccurrence){let i=t.concat(n);this.updateExpectedNext(),this.walk(e.referencedRule,i)}}updateExpectedNext(){b(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())}},Ys=class extends ml{constructor(e,t){super(e,t),this.path=t,this.nextTerminalName="",this.nextTerminalOccurrence=0,this.nextTerminalName=this.path.lastTok.name,this.nextTerminalOccurrence=this.path.lastTokOccurrence}walkTerminal(e,t,n){if(this.isAtEndOfPath&&e.terminalType.name===this.nextTerminalName&&e.idx===this.nextTerminalOccurrence&&!this.found){let i=t.concat(n),s=new Y({definition:i});this.possibleTokTypes=ur(s),this.found=!0}}},In=class extends It{constructor(e,t){super(),this.topRule=e,this.occurrence=t,this.result={token:void 0,occurrence:void 0,isEndOfRule:void 0}}startWalking(){return this.walk(this.topRule),this.result}},Js=class extends In{walkMany(e,t,n){if(e.idx===this.occurrence){let i=ke(t.concat(n));this.result.isEndOfRule=i===void 0,i instanceof M&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkMany(e,t,n)}},ki=class extends In{walkManySep(e,t,n){if(e.idx===this.occurrence){let i=ke(t.concat(n));this.result.isEndOfRule=i===void 0,i instanceof M&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkManySep(e,t,n)}},Qs=class extends In{walkAtLeastOne(e,t,n){if(e.idx===this.occurrence){let i=ke(t.concat(n));this.result.isEndOfRule=i===void 0,i instanceof M&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOne(e,t,n)}},$i=class extends In{walkAtLeastOneSep(e,t,n){if(e.idx===this.occurrence){let i=ke(t.concat(n));this.result.isEndOfRule=i===void 0,i instanceof M&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOneSep(e,t,n)}};function Zs(r,e,t=[]){t=ee(t);let n=[],i=0;function s(o){return o.concat(he(r,i+1))}function a(o){let l=Zs(s(o),e,t);return n.concat(l)}for(;t.length{b(l.definition)===!1&&(n=a(l.definition))}),n;if(o instanceof M)t.push(o.terminalType);else throw Error("non exhaustive match")}i++}return n.push({partialPath:t,suffixDef:he(r,i)}),n}function ea(r,e,t,n){let i="EXIT_NONE_TERMINAL",s=[i],a="EXIT_ALTERNATIVE",o=!1,l=e.length,u=l-n-1,c=[],f=[];for(f.push({idx:-1,def:r,ruleStack:[],occurrenceStack:[]});!b(f);){let d=f.pop();if(d===a){o&&At(f).idx<=u&&f.pop();continue}let h=d.def,m=d.idx,g=d.ruleStack,A=d.occurrenceStack;if(b(h))continue;let R=h[0];if(R===i){let E={idx:m,def:he(h),ruleStack:Dt(g),occurrenceStack:Dt(A)};f.push(E)}else if(R instanceof M)if(m=0;E--){let T=R.definition[E],O={idx:m,def:T.definition.concat(he(h)),ruleStack:g,occurrenceStack:A};f.push(O),f.push(a)}else if(R instanceof Y)f.push({idx:m,def:R.definition.concat(he(h)),ruleStack:g,occurrenceStack:A});else if(R instanceof be)f.push(Bp(R,m,g,A));else throw Error("non exhaustive match")}return c}function Bp(r,e,t,n){let i=ee(t);i.push(r.name);let s=ee(n);return s.push(1),{idx:e,def:r.definition,ruleStack:i,occurrenceStack:s}}var se;(function(r){r[r.OPTION=0]="OPTION",r[r.REPETITION=1]="REPETITION",r[r.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",r[r.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",r[r.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",r[r.ALTERNATION=5]="ALTERNATION"})(se||(se={}));function Ii(r){if(r instanceof H||r==="Option")return se.OPTION;if(r instanceof F||r==="Repetition")return se.REPETITION;if(r instanceof J||r==="RepetitionMandatory")return se.REPETITION_MANDATORY;if(r instanceof Q||r==="RepetitionMandatoryWithSeparator")return se.REPETITION_MANDATORY_WITH_SEPARATOR;if(r instanceof z||r==="RepetitionWithSeparator")return se.REPETITION_WITH_SEPARATOR;if(r instanceof q||r==="Alternation")return se.ALTERNATION;throw Error("non exhaustive match")}function ra(r){let{occurrence:e,rule:t,prodType:n,maxLookahead:i}=r,s=Ii(n);return s===se.ALTERNATION?Nn(e,t,i):Cn(e,t,s,i)}function Vc(r,e,t,n,i,s){let a=Nn(r,e,t),o=Yc(a)?kn:Nt;return s(a,n,o,i)}function jc(r,e,t,n,i,s){let a=Cn(r,e,i,t),o=Yc(a)?kn:Nt;return s(a[0],o,n)}function Hc(r,e,t,n){let i=r.length,s=Oe(r,a=>Oe(a,o=>o.length===1));if(e)return function(a){let o=x(a,l=>l.GATE);for(let l=0;lde(l)),o=le(a,(l,u,c)=>(k(u,f=>{$(l,f.tokenTypeIdx)||(l[f.tokenTypeIdx]=c),k(f.categoryMatches,d=>{$(l,d)||(l[d]=c)})}),l),{});return function(){let l=this.LA(1);return o[l.tokenTypeIdx]}}else return function(){for(let a=0;as.length===1),i=r.length;if(n&&!t){let s=de(r);if(s.length===1&&b(s[0].categoryMatches)){let o=s[0].tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===o}}else{let a=le(s,(o,l,u)=>(o[l.tokenTypeIdx]=!0,k(l.categoryMatches,c=>{o[c]=!0}),o),[]);return function(){let o=this.LA(1);return a[o.tokenTypeIdx]===!0}}}else return function(){e:for(let s=0;sZs([a],1)),n=Kc(t.length),i=x(t,a=>{let o={};return k(a,l=>{let u=gl(l.partialPath);k(u,c=>{o[c]=!0})}),o}),s=t;for(let a=1;a<=e;a++){let o=s;s=Kc(o.length);for(let l=0;l{let R=gl(A.partialPath);k(R,E=>{i[l][E]=!0})})}}}}return n}function Nn(r,e,t,n){let i=new ta(r,se.ALTERNATION,n);return e.accept(i),qc(i.result,t)}function Cn(r,e,t,n){let i=new ta(r,t);e.accept(i);let s=i.result,o=new yl(e,r,t).startWalking(),l=new Y({definition:s}),u=new Y({definition:o});return qc([l,u],n)}function na(r,e){e:for(let t=0;t{let i=e[n];return t===i||i.categoryMatchesMap[t.tokenTypeIdx]})}function Yc(r){return Oe(r,e=>Oe(e,t=>Oe(t,n=>b(n.categoryMatches))))}function Jc(r){let e=r.lookaheadStrategy.validate({rules:r.rules,tokenTypes:r.tokenTypes,grammarName:r.grammarName});return x(e,t=>Object.assign({type:ge.CUSTOM_LOOKAHEAD_VALIDATION},t))}function Qc(r,e,t,n){let i=$e(r,l=>Kp(l,t)),s=Xp(r,e,t),a=$e(r,l=>Hp(l,t)),o=$e(r,l=>jp(l,r,n,t));return i.concat(s,a,o)}function Kp(r,e){let t=new Tl;r.accept(t);let n=t.allProductions,i=ju(n,Vp),s=Ke(i,o=>o.length>1);return x(te(s),o=>{let l=ke(o),u=e.buildDuplicateFoundError(r,o),c=Be(l),f={message:u,type:ge.DUPLICATE_PRODUCTIONS,ruleName:r.name,dslName:c,occurrence:l.idx},d=Zc(l);return d&&(f.parameter=d),f})}function Vp(r){return`${Be(r)}_#_${r.idx}_#_${Zc(r)}`}function Zc(r){return r instanceof M?r.terminalType.name:r instanceof j?r.nonTerminalName:""}var Tl=class extends Me{constructor(){super(...arguments),this.allProductions=[]}visitNonTerminal(e){this.allProductions.push(e)}visitOption(e){this.allProductions.push(e)}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}visitAlternation(e){this.allProductions.push(e)}visitTerminal(e){this.allProductions.push(e)}};function jp(r,e,t,n){let i=[];if(le(e,(a,o)=>o.name===r.name?a+1:a,0)>1){let a=n.buildDuplicateRuleNameError({topLevelRule:r,grammarName:t});i.push({message:a,type:ge.DUPLICATE_RULE_NAME,ruleName:r.name})}return i}function ef(r,e,t){let n=[],i;return ae(e,r)||(i=`Invalid rule override, rule: ->${r}<- cannot be overridden in the grammar: ->${t}<-as it is not defined in any of the super grammars `,n.push({message:i,type:ge.INVALID_RULE_OVERRIDE,ruleName:r})),n}function xl(r,e,t,n=[]){let i=[],s=ia(e.definition);if(b(s))return[];{let a=r.name;ae(s,r)&&i.push({message:t.buildLeftRecursionError({topLevelRule:r,leftRecursionPath:n}),type:ge.LEFT_RECURSION,ruleName:a});let l=qt(s,n.concat([r])),u=$e(l,c=>{let f=ee(n);return f.push(c),xl(r,c,t,f)});return i.concat(u)}}function ia(r){let e=[];if(b(r))return e;let t=ke(r);if(t instanceof j)e.push(t.referencedRule);else if(t instanceof Y||t instanceof H||t instanceof J||t instanceof Q||t instanceof z||t instanceof F)e=e.concat(ia(t.definition));else if(t instanceof q)e=de(x(t.definition,s=>ia(s.definition)));else if(!(t instanceof M))throw Error("non exhaustive match");let n=lr(t),i=r.length>1;if(n&&i){let s=he(r);return e.concat(ia(s))}else return e}var Ni=class extends Me{constructor(){super(...arguments),this.alternations=[]}visitAlternation(e){this.alternations.push(e)}};function tf(r,e){let t=new Ni;r.accept(t);let n=t.alternations;return $e(n,s=>{let a=Dt(s.definition);return $e(a,(o,l)=>{let u=ea([o],[],Nt,1);return b(u)?[{message:e.buildEmptyAlternationError({topLevelRule:r,alternation:s,emptyChoiceIdx:l}),type:ge.NONE_LAST_EMPTY_ALT,ruleName:r.name,occurrence:s.idx,alternative:l+1}]:[]})})}function rf(r,e,t){let n=new Ni;r.accept(n);let i=n.alternations;return i=Xt(i,a=>a.ignoreAmbiguities===!0),$e(i,a=>{let o=a.idx,l=a.maxLookahead||e,u=Nn(o,r,l,a),c=zp(u,a,r,t),f=qp(u,a,r,t);return c.concat(f)})}var Rl=class extends Me{constructor(){super(...arguments),this.allProductions=[]}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}};function Hp(r,e){let t=new Ni;r.accept(t);let n=t.alternations;return $e(n,s=>s.definition.length>255?[{message:e.buildTooManyAlternativesError({topLevelRule:r,alternation:s}),type:ge.TOO_MANY_ALTS,ruleName:r.name,occurrence:s.idx}]:[])}function nf(r,e,t){let n=[];return k(r,i=>{let s=new Rl;i.accept(s);let a=s.allProductions;k(a,o=>{let l=Ii(o),u=o.maxLookahead||e,c=o.idx,d=Cn(c,i,l,u)[0];if(b(de(d))){let h=t.buildEmptyRepetitionError({topLevelRule:i,repetition:o});n.push({message:h,type:ge.NO_NON_EMPTY_LOOKAHEAD,ruleName:i.name})}})}),n}function zp(r,e,t,n){let i=[],s=le(r,(o,l,u)=>(e.definition[u].ignoreAmbiguities===!0||k(l,c=>{let f=[u];k(r,(d,h)=>{u!==h&&na(d,c)&&e.definition[h].ignoreAmbiguities!==!0&&f.push(h)}),f.length>1&&!na(i,c)&&(i.push(c),o.push({alts:f,path:c}))}),o),[]);return x(s,o=>{let l=x(o.alts,c=>c+1);return{message:n.buildAlternationAmbiguityError({topLevelRule:t,alternation:e,ambiguityIndices:l,prefixPath:o.path}),type:ge.AMBIGUOUS_ALTS,ruleName:t.name,occurrence:e.idx,alternatives:o.alts}})}function qp(r,e,t,n){let i=le(r,(a,o,l)=>{let u=x(o,c=>({idx:l,path:c}));return a.concat(u)},[]);return Et($e(i,a=>{if(e.definition[a.idx].ignoreAmbiguities===!0)return[];let l=a.idx,u=a.path,c=Re(i,d=>e.definition[d.idx].ignoreAmbiguities!==!0&&d.idx{let h=[d.idx+1,l+1],m=e.idx===0?"":e.idx;return{message:n.buildAlternationPrefixAmbiguityError({topLevelRule:t,alternation:e,ambiguityIndices:h,prefixPath:d.path}),type:ge.AMBIGUOUS_PREFIX_ALTS,ruleName:t.name,occurrence:m,alternatives:h}})}))}function Xp(r,e,t){let n=[],i=x(e,s=>s.name);return k(r,s=>{let a=s.name;if(ae(i,a)){let o=t.buildNamespaceConflictError(s);n.push({message:o,type:ge.CONFLICT_TOKENS_RULES_NAMESPACE,ruleName:a})}}),n}function sf(r){let e=Yn(r,{errMsgProvider:Bc}),t={};return k(r.rules,n=>{t[n.name]=n}),Wc(t,e.errMsgProvider)}function af(r){return r=Yn(r,{errMsgProvider:nt}),Qc(r.rules,r.tokenTypes,r.errMsgProvider,r.grammarName)}var of="MismatchedTokenException",lf="NoViableAltException",uf="EarlyExitException",cf="NotAllInputParsedException",ff=[of,lf,uf,cf];Object.freeze(ff);function Bt(r){return ae(ff,r.name)}var Sn=class extends Error{constructor(e,t){super(e),this.token=t,this.resyncedTokens=[],Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},fr=class extends Sn{constructor(e,t,n){super(e,t),this.previousToken=n,this.name=of}},Ci=class extends Sn{constructor(e,t,n){super(e,t),this.previousToken=n,this.name=lf}},Si=class extends Sn{constructor(e,t){super(e,t),this.name=cf}},wi=class extends Sn{constructor(e,t,n){super(e,t),this.previousToken=n,this.name=uf}};var El={},vl="InRuleRecoveryException",Al=class extends Error{constructor(e){super(e),this.name=vl}},sa=class{initRecoverable(e){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=$(e,"recoveryEnabled")?e.recoveryEnabled:De.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=Yp)}getTokenToInsert(e){let t=wt(e,"",NaN,NaN,NaN,NaN,NaN,NaN);return t.isInsertedInRecovery=!0,t}canTokenTypeBeInsertedInRecovery(e){return!0}canTokenTypeBeDeletedInRecovery(e){return!0}tryInRepetitionRecovery(e,t,n,i){let s=this.findReSyncTokenType(),a=this.exportLexerState(),o=[],l=!1,u=this.LA(1),c=this.LA(1),f=()=>{let d=this.LA(0),h=this.errorMessageProvider.buildMismatchTokenMessage({expected:i,actual:u,previous:d,ruleName:this.getCurrRuleFullName()}),m=new fr(h,u,this.LA(0));m.resyncedTokens=Dt(o),this.SAVE_ERROR(m)};for(;!l;)if(this.tokenMatcher(c,i)){f();return}else if(n.call(this)){f(),e.apply(this,t);return}else this.tokenMatcher(c,s)?l=!0:(c=this.SKIP_TOKEN(),this.addToResyncTokens(c,o));this.importLexerState(a)}shouldInRepetitionRecoveryBeTried(e,t,n){return!(n===!1||this.tokenMatcher(this.LA(1),e)||this.isBackTracking()||this.canPerformInRuleRecovery(e,this.getFollowsForInRuleRecovery(e,t)))}getFollowsForInRuleRecovery(e,t){let n=this.getCurrentGrammarPath(e,t);return this.getNextPossibleTokenTypes(n)}tryInRuleRecovery(e,t){if(this.canRecoverWithSingleTokenInsertion(e,t))return this.getTokenToInsert(e);if(this.canRecoverWithSingleTokenDeletion(e)){let n=this.SKIP_TOKEN();return this.consumeToken(),n}throw new Al("sad sad panda")}canPerformInRuleRecovery(e,t){return this.canRecoverWithSingleTokenInsertion(e,t)||this.canRecoverWithSingleTokenDeletion(e)}canRecoverWithSingleTokenInsertion(e,t){if(!this.canTokenTypeBeInsertedInRecovery(e)||b(t))return!1;let n=this.LA(1);return vt(t,s=>this.tokenMatcher(n,s))!==void 0}canRecoverWithSingleTokenDeletion(e){return this.canTokenTypeBeDeletedInRecovery(e)?this.tokenMatcher(this.LA(2),e):!1}isInCurrentRuleReSyncSet(e){let t=this.getCurrFollowKey(),n=this.getFollowSetFromFollowKey(t);return ae(n,e)}findReSyncTokenType(){let e=this.flattenFollowSet(),t=this.LA(1),n=2;for(;;){let i=vt(e,s=>vi(t,s));if(i!==void 0)return i;t=this.LA(n),n++}}getCurrFollowKey(){if(this.RULE_STACK.length===1)return El;let e=this.getLastExplicitRuleShortName(),t=this.getLastExplicitRuleOccurrenceIndex(),n=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(e),idxInCallingRule:t,inRule:this.shortRuleNameToFullName(n)}}buildFullFollowKeyStack(){let e=this.RULE_STACK,t=this.RULE_OCCURRENCE_STACK;return x(e,(n,i)=>i===0?El:{ruleName:this.shortRuleNameToFullName(n),idxInCallingRule:t[i],inRule:this.shortRuleNameToFullName(e[i-1])})}flattenFollowSet(){let e=x(this.buildFullFollowKeyStack(),t=>this.getFollowSetFromFollowKey(t));return de(e)}getFollowSetFromFollowKey(e){if(e===El)return[ze];let t=e.ruleName+e.idxInCallingRule+Vs+e.inRule;return this.resyncFollows[t]}addToResyncTokens(e,t){return this.tokenMatcher(e,ze)||t.push(e),t}reSyncTo(e){let t=[],n=this.LA(1);for(;this.tokenMatcher(n,e)===!1;)n=this.SKIP_TOKEN(),this.addToResyncTokens(n,t);return Dt(t)}attemptInRepetitionRecovery(e,t,n,i,s,a,o){}getCurrentGrammarPath(e,t){let n=this.getHumanReadableRuleStack(),i=ee(this.RULE_OCCURRENCE_STACK);return{ruleStack:n,occurrenceStack:i,lastTok:e,lastTokOccurrence:t}}getHumanReadableRuleStack(){return x(this.RULE_STACK,e=>this.shortRuleNameToFullName(e))}};function Yp(r,e,t,n,i,s,a){let o=this.getKeyForAutomaticLookahead(n,i),l=this.firstAfterRepMap[o];if(l===void 0){let d=this.getCurrRuleFullName(),h=this.getGAstProductions()[d];l=new s(h,i).startWalking(),this.firstAfterRepMap[o]=l}let u=l.token,c=l.occurrence,f=l.isEndOfRule;this.RULE_STACK.length===1&&f&&u===void 0&&(u=ze,c=1),!(u===void 0||c===void 0)&&this.shouldInRepetitionRecoveryBeTried(u,c,a)&&this.tryInRepetitionRecovery(r,e,t,u)}function aa(r,e,t){return t|e|r}var Lt=class{constructor(e){var t;this.maxLookahead=(t=e?.maxLookahead)!==null&&t!==void 0?t:De.maxLookahead}validate(e){let t=this.validateNoLeftRecursion(e.rules);if(b(t)){let n=this.validateEmptyOrAlternatives(e.rules),i=this.validateAmbiguousAlternationAlternatives(e.rules,this.maxLookahead),s=this.validateSomeNonEmptyLookaheadPath(e.rules,this.maxLookahead);return[...t,...n,...i,...s]}return t}validateNoLeftRecursion(e){return $e(e,t=>xl(t,t,nt))}validateEmptyOrAlternatives(e){return $e(e,t=>tf(t,nt))}validateAmbiguousAlternationAlternatives(e,t){return $e(e,n=>rf(n,t,nt))}validateSomeNonEmptyLookaheadPath(e,t){return nf(e,t,nt)}buildLookaheadForAlternation(e){return Vc(e.prodOccurrence,e.rule,e.maxLookahead,e.hasPredicates,e.dynamicTokensEnabled,Hc)}buildLookaheadForOptional(e){return jc(e.prodOccurrence,e.rule,e.maxLookahead,e.dynamicTokensEnabled,Ii(e.prodType),zc)}};var la=class{initLooksAhead(e){this.dynamicTokensEnabled=$(e,"dynamicTokensEnabled")?e.dynamicTokensEnabled:De.dynamicTokensEnabled,this.maxLookahead=$(e,"maxLookahead")?e.maxLookahead:De.maxLookahead,this.lookaheadStrategy=$(e,"lookaheadStrategy")?e.lookaheadStrategy:new Lt({maxLookahead:this.maxLookahead}),this.lookAheadFuncsCache=new Map}preComputeLookaheadFunctions(e){k(e,t=>{this.TRACE_INIT(`${t.name} Rule Lookahead`,()=>{let{alternation:n,repetition:i,option:s,repetitionMandatory:a,repetitionMandatoryWithSeparator:o,repetitionWithSeparator:l}=Jp(t);k(n,u=>{let c=u.idx===0?"":u.idx;this.TRACE_INIT(`${Be(u)}${c}`,()=>{let f=this.lookaheadStrategy.buildLookaheadForAlternation({prodOccurrence:u.idx,rule:t,maxLookahead:u.maxLookahead||this.maxLookahead,hasPredicates:u.hasPredicates,dynamicTokensEnabled:this.dynamicTokensEnabled}),d=aa(this.fullRuleNameToShort[t.name],256,u.idx);this.setLaFuncCache(d,f)})}),k(i,u=>{this.computeLookaheadFunc(t,u.idx,768,"Repetition",u.maxLookahead,Be(u))}),k(s,u=>{this.computeLookaheadFunc(t,u.idx,512,"Option",u.maxLookahead,Be(u))}),k(a,u=>{this.computeLookaheadFunc(t,u.idx,1024,"RepetitionMandatory",u.maxLookahead,Be(u))}),k(o,u=>{this.computeLookaheadFunc(t,u.idx,1536,"RepetitionMandatoryWithSeparator",u.maxLookahead,Be(u))}),k(l,u=>{this.computeLookaheadFunc(t,u.idx,1280,"RepetitionWithSeparator",u.maxLookahead,Be(u))})})})}computeLookaheadFunc(e,t,n,i,s,a){this.TRACE_INIT(`${a}${t===0?"":t}`,()=>{let o=this.lookaheadStrategy.buildLookaheadForOptional({prodOccurrence:t,rule:e,maxLookahead:s||this.maxLookahead,dynamicTokensEnabled:this.dynamicTokensEnabled,prodType:i}),l=aa(this.fullRuleNameToShort[e.name],n,t);this.setLaFuncCache(l,o)})}getKeyForAutomaticLookahead(e,t){let n=this.getLastExplicitRuleShortName();return aa(n,e,t)}getLaFuncFromCache(e){return this.lookAheadFuncsCache.get(e)}setLaFuncCache(e,t){this.lookAheadFuncsCache.set(e,t)}},kl=class extends Me{constructor(){super(...arguments),this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}reset(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}visitOption(e){this.dslMethods.option.push(e)}visitRepetitionWithSeparator(e){this.dslMethods.repetitionWithSeparator.push(e)}visitRepetitionMandatory(e){this.dslMethods.repetitionMandatory.push(e)}visitRepetitionMandatoryWithSeparator(e){this.dslMethods.repetitionMandatoryWithSeparator.push(e)}visitRepetition(e){this.dslMethods.repetition.push(e)}visitAlternation(e){this.dslMethods.alternation.push(e)}},oa=new kl;function Jp(r){oa.reset(),r.accept(oa);let e=oa.dslMethods;return oa.reset(),e}function Nl(r,e){isNaN(r.startOffset)===!0?(r.startOffset=e.startOffset,r.endOffset=e.endOffset):r.endOffseta.msg);throw Error(`Errors Detected in CST Visitor <${this.constructor.name}>: + ${s.join(` + +`).replace(/\n/g,` + `)}`)}}};return t.prototype=n,t.prototype.constructor=t,t._RULE_NAMES=e,t}function mf(r,e,t){let n=function(){};Sl(n,r+"BaseSemanticsWithDefaults");let i=Object.create(t.prototype);return k(e,s=>{i[s]=Zp}),n.prototype=i,n.prototype.constructor=n,n}var wl;(function(r){r[r.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",r[r.MISSING_METHOD=1]="MISSING_METHOD"})(wl||(wl={}));function em(r,e){return tm(r,e)}function tm(r,e){let t=Re(e,i=>at(r[i])===!1),n=x(t,i=>({msg:`Missing visitor method: <${i}> on ${r.constructor.name} CST Visitor.`,type:wl.MISSING_METHOD,methodName:i}));return Et(n)}var da=class{initTreeBuilder(e){if(this.CST_STACK=[],this.outputCst=e.outputCst,this.nodeLocationTracking=$(e,"nodeLocationTracking")?e.nodeLocationTracking:De.nodeLocationTracking,!this.outputCst)this.cstInvocationStateUpdate=fe,this.cstFinallyStateUpdate=fe,this.cstPostTerminal=fe,this.cstPostNonTerminal=fe,this.cstPostRule=fe;else if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Cl,this.setNodeLocationFromNode=Cl,this.cstPostRule=fe,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=fe,this.setNodeLocationFromNode=fe,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Nl,this.setNodeLocationFromNode=Nl,this.cstPostRule=fe,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=fe,this.setNodeLocationFromNode=fe,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else if(/none/i.test(this.nodeLocationTracking))this.setNodeLocationFromToken=fe,this.setNodeLocationFromNode=fe,this.cstPostRule=fe,this.setInitialNodeLocation=fe;else throw Error(`Invalid config option: "${e.nodeLocationTracking}"`)}setInitialNodeLocationOnlyOffsetRecovery(e){e.location={startOffset:NaN,endOffset:NaN}}setInitialNodeLocationOnlyOffsetRegular(e){e.location={startOffset:this.LA(1).startOffset,endOffset:NaN}}setInitialNodeLocationFullRecovery(e){e.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}}setInitialNodeLocationFullRegular(e){let t=this.LA(1);e.location={startOffset:t.startOffset,startLine:t.startLine,startColumn:t.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}}cstInvocationStateUpdate(e){let t={name:e,children:Object.create(null)};this.setInitialNodeLocation(t),this.CST_STACK.push(t)}cstFinallyStateUpdate(){this.CST_STACK.pop()}cstPostRuleFull(e){let t=this.LA(0),n=e.location;n.startOffset<=t.startOffset?(n.endOffset=t.endOffset,n.endLine=t.endLine,n.endColumn=t.endColumn):(n.startOffset=NaN,n.startLine=NaN,n.startColumn=NaN)}cstPostRuleOnlyOffset(e){let t=this.LA(0),n=e.location;n.startOffset<=t.startOffset?n.endOffset=t.endOffset:n.startOffset=NaN}cstPostTerminal(e,t){let n=this.CST_STACK[this.CST_STACK.length-1];df(n,t,e),this.setNodeLocationFromToken(n.location,t)}cstPostNonTerminal(e,t){let n=this.CST_STACK[this.CST_STACK.length-1];hf(n,t,e),this.setNodeLocationFromNode(n.location,e.location)}getBaseCstVisitorConstructor(){if(Pe(this.baseCstVisitorConstructor)){let e=pf(this.className,xt(this.gastProductionsCache));return this.baseCstVisitorConstructor=e,e}return this.baseCstVisitorConstructor}getBaseCstVisitorConstructorWithDefaults(){if(Pe(this.baseCstVisitorWithDefaultsConstructor)){let e=mf(this.className,xt(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=e,e}return this.baseCstVisitorWithDefaultsConstructor}getLastExplicitRuleShortName(){let e=this.RULE_STACK;return e[e.length-1]}getPreviousExplicitRuleShortName(){let e=this.RULE_STACK;return e[e.length-2]}getLastExplicitRuleOccurrenceIndex(){let e=this.RULE_OCCURRENCE_STACK;return e[e.length-1]}};var ha=class{initLexerAdapter(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1}set input(e){if(this.selfAnalysisDone!==!0)throw Error("Missing invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=e,this.tokVectorLength=e.length}get input(){return this.tokVector}SKIP_TOKEN(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):wn}LA(e){let t=this.currIdx+e;return t<0||this.tokVectorLength<=t?wn:this.tokVector[t]}consumeToken(){this.currIdx++}exportLexerState(){return this.currIdx}importLexerState(e){this.currIdx=e}resetLexerState(){this.currIdx=-1}moveToTerminatedState(){this.currIdx=this.tokVector.length-1}getLexerPosition(){return this.exportLexerState()}};var pa=class{ACTION(e){return e.call(this)}consume(e,t,n){return this.consumeInternal(t,e,n)}subrule(e,t,n){return this.subruleInternal(t,e,n)}option(e,t){return this.optionInternal(t,e)}or(e,t){return this.orInternal(t,e)}many(e,t){return this.manyInternal(e,t)}atLeastOne(e,t){return this.atLeastOneInternal(e,t)}CONSUME(e,t){return this.consumeInternal(e,0,t)}CONSUME1(e,t){return this.consumeInternal(e,1,t)}CONSUME2(e,t){return this.consumeInternal(e,2,t)}CONSUME3(e,t){return this.consumeInternal(e,3,t)}CONSUME4(e,t){return this.consumeInternal(e,4,t)}CONSUME5(e,t){return this.consumeInternal(e,5,t)}CONSUME6(e,t){return this.consumeInternal(e,6,t)}CONSUME7(e,t){return this.consumeInternal(e,7,t)}CONSUME8(e,t){return this.consumeInternal(e,8,t)}CONSUME9(e,t){return this.consumeInternal(e,9,t)}SUBRULE(e,t){return this.subruleInternal(e,0,t)}SUBRULE1(e,t){return this.subruleInternal(e,1,t)}SUBRULE2(e,t){return this.subruleInternal(e,2,t)}SUBRULE3(e,t){return this.subruleInternal(e,3,t)}SUBRULE4(e,t){return this.subruleInternal(e,4,t)}SUBRULE5(e,t){return this.subruleInternal(e,5,t)}SUBRULE6(e,t){return this.subruleInternal(e,6,t)}SUBRULE7(e,t){return this.subruleInternal(e,7,t)}SUBRULE8(e,t){return this.subruleInternal(e,8,t)}SUBRULE9(e,t){return this.subruleInternal(e,9,t)}OPTION(e){return this.optionInternal(e,0)}OPTION1(e){return this.optionInternal(e,1)}OPTION2(e){return this.optionInternal(e,2)}OPTION3(e){return this.optionInternal(e,3)}OPTION4(e){return this.optionInternal(e,4)}OPTION5(e){return this.optionInternal(e,5)}OPTION6(e){return this.optionInternal(e,6)}OPTION7(e){return this.optionInternal(e,7)}OPTION8(e){return this.optionInternal(e,8)}OPTION9(e){return this.optionInternal(e,9)}OR(e){return this.orInternal(e,0)}OR1(e){return this.orInternal(e,1)}OR2(e){return this.orInternal(e,2)}OR3(e){return this.orInternal(e,3)}OR4(e){return this.orInternal(e,4)}OR5(e){return this.orInternal(e,5)}OR6(e){return this.orInternal(e,6)}OR7(e){return this.orInternal(e,7)}OR8(e){return this.orInternal(e,8)}OR9(e){return this.orInternal(e,9)}MANY(e){this.manyInternal(0,e)}MANY1(e){this.manyInternal(1,e)}MANY2(e){this.manyInternal(2,e)}MANY3(e){this.manyInternal(3,e)}MANY4(e){this.manyInternal(4,e)}MANY5(e){this.manyInternal(5,e)}MANY6(e){this.manyInternal(6,e)}MANY7(e){this.manyInternal(7,e)}MANY8(e){this.manyInternal(8,e)}MANY9(e){this.manyInternal(9,e)}MANY_SEP(e){this.manySepFirstInternal(0,e)}MANY_SEP1(e){this.manySepFirstInternal(1,e)}MANY_SEP2(e){this.manySepFirstInternal(2,e)}MANY_SEP3(e){this.manySepFirstInternal(3,e)}MANY_SEP4(e){this.manySepFirstInternal(4,e)}MANY_SEP5(e){this.manySepFirstInternal(5,e)}MANY_SEP6(e){this.manySepFirstInternal(6,e)}MANY_SEP7(e){this.manySepFirstInternal(7,e)}MANY_SEP8(e){this.manySepFirstInternal(8,e)}MANY_SEP9(e){this.manySepFirstInternal(9,e)}AT_LEAST_ONE(e){this.atLeastOneInternal(0,e)}AT_LEAST_ONE1(e){return this.atLeastOneInternal(1,e)}AT_LEAST_ONE2(e){this.atLeastOneInternal(2,e)}AT_LEAST_ONE3(e){this.atLeastOneInternal(3,e)}AT_LEAST_ONE4(e){this.atLeastOneInternal(4,e)}AT_LEAST_ONE5(e){this.atLeastOneInternal(5,e)}AT_LEAST_ONE6(e){this.atLeastOneInternal(6,e)}AT_LEAST_ONE7(e){this.atLeastOneInternal(7,e)}AT_LEAST_ONE8(e){this.atLeastOneInternal(8,e)}AT_LEAST_ONE9(e){this.atLeastOneInternal(9,e)}AT_LEAST_ONE_SEP(e){this.atLeastOneSepFirstInternal(0,e)}AT_LEAST_ONE_SEP1(e){this.atLeastOneSepFirstInternal(1,e)}AT_LEAST_ONE_SEP2(e){this.atLeastOneSepFirstInternal(2,e)}AT_LEAST_ONE_SEP3(e){this.atLeastOneSepFirstInternal(3,e)}AT_LEAST_ONE_SEP4(e){this.atLeastOneSepFirstInternal(4,e)}AT_LEAST_ONE_SEP5(e){this.atLeastOneSepFirstInternal(5,e)}AT_LEAST_ONE_SEP6(e){this.atLeastOneSepFirstInternal(6,e)}AT_LEAST_ONE_SEP7(e){this.atLeastOneSepFirstInternal(7,e)}AT_LEAST_ONE_SEP8(e){this.atLeastOneSepFirstInternal(8,e)}AT_LEAST_ONE_SEP9(e){this.atLeastOneSepFirstInternal(9,e)}RULE(e,t,n=_n){if(ae(this.definedRulesNames,e)){let a={message:nt.buildDuplicateRuleNameError({topLevelRule:e,grammarName:this.className}),type:ge.DUPLICATE_RULE_NAME,ruleName:e};this.definitionErrors.push(a)}this.definedRulesNames.push(e);let i=this.defineRule(e,t,n);return this[e]=i,i}OVERRIDE_RULE(e,t,n=_n){let i=ef(e,this.definedRulesNames,this.className);this.definitionErrors=this.definitionErrors.concat(i);let s=this.defineRule(e,t,n);return this[e]=s,s}BACKTRACK(e,t){return function(){this.isBackTrackingStack.push(1);let n=this.saveRecogState();try{return e.apply(this,t),!0}catch(i){if(Bt(i))return!1;throw i}finally{this.reloadRecogState(n),this.isBackTrackingStack.pop()}}}getGAstProductions(){return this.gastProductionsCache}getSerializedGastProductions(){return Ks(te(this.gastProductionsCache))}};var ma=class{initRecognizerEngine(e,t){if(this.className=this.constructor.name,this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=kn,this.subruleIdx=0,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},$(t,"serializedGrammar"))throw Error(`The Parser's configuration can no longer contain a property. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0 + For Further details.`);if(me(e)){if(b(e))throw Error(`A Token Vocabulary cannot be empty. + Note that the first argument for the parser constructor + is no longer a Token vector (since v4.0).`);if(typeof e[0].startOffset=="number")throw Error(`The Parser constructor no longer accepts a token vector as the first argument. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0 + For Further details.`)}if(me(e))this.tokensMap=le(e,(s,a)=>(s[a.name]=a,s),{});else if($(e,"modes")&&Oe(de(te(e.modes)),Lc)){let s=de(te(e.modes)),a=Jn(s);this.tokensMap=le(a,(o,l)=>(o[l.name]=l,o),{})}else if(Vu(e))this.tokensMap=ee(e);else throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap.EOF=ze;let n=$(e,"modes")?de(te(e.modes)):te(e),i=Oe(n,s=>b(s.categoryMatches));this.tokenMatcher=i?kn:Nt,Ct(te(this.tokensMap))}defineRule(e,t,n){if(this.selfAnalysisDone)throw Error(`Grammar rule <${e}> may not be defined after the 'performSelfAnalysis' method has been called' +Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);let i=$(n,"resyncEnabled")?n.resyncEnabled:_n.resyncEnabled,s=$(n,"recoveryValueFunc")?n.recoveryValueFunc:_n.recoveryValueFunc,a=this.ruleShortNameIdx<<12;this.ruleShortNameIdx++,this.shortRuleNameToFull[a]=e,this.fullRuleNameToShort[e]=a;let o;return this.outputCst===!0?o=function(...c){try{this.ruleInvocationStateUpdate(a,e,this.subruleIdx),t.apply(this,c);let f=this.CST_STACK[this.CST_STACK.length-1];return this.cstPostRule(f),f}catch(f){return this.invokeRuleCatch(f,i,s)}finally{this.ruleFinallyStateUpdate()}}:o=function(...c){try{return this.ruleInvocationStateUpdate(a,e,this.subruleIdx),t.apply(this,c)}catch(f){return this.invokeRuleCatch(f,i,s)}finally{this.ruleFinallyStateUpdate()}},Object.assign(o,{ruleName:e,originalGrammarAction:t})}invokeRuleCatch(e,t,n){let i=this.RULE_STACK.length===1,s=t&&!this.isBackTracking()&&this.recoveryEnabled;if(Bt(e)){let a=e;if(s){let o=this.findReSyncTokenType();if(this.isInCurrentRuleReSyncSet(o))if(a.resyncedTokens=this.reSyncTo(o),this.outputCst){let l=this.CST_STACK[this.CST_STACK.length-1];return l.recoveredNode=!0,l}else return n(e);else{if(this.outputCst){let l=this.CST_STACK[this.CST_STACK.length-1];l.recoveredNode=!0,a.partialCstResult=l}throw a}}else{if(i)return this.moveToTerminatedState(),n(e);throw a}}else throw e}optionInternal(e,t){let n=this.getKeyForAutomaticLookahead(512,t);return this.optionInternalLogic(e,t,n)}optionInternalLogic(e,t,n){let i=this.getLaFuncFromCache(n),s;if(typeof e!="function"){s=e.DEF;let a=e.GATE;if(a!==void 0){let o=i;i=()=>a.call(this)&&o.call(this)}}else s=e;if(i.call(this)===!0)return s.call(this)}atLeastOneInternal(e,t){let n=this.getKeyForAutomaticLookahead(1024,e);return this.atLeastOneInternalLogic(e,t,n)}atLeastOneInternalLogic(e,t,n){let i=this.getLaFuncFromCache(n),s;if(typeof t!="function"){s=t.DEF;let a=t.GATE;if(a!==void 0){let o=i;i=()=>a.call(this)&&o.call(this)}}else s=t;if(i.call(this)===!0){let a=this.doSingleRepetition(s);for(;i.call(this)===!0&&a===!0;)a=this.doSingleRepetition(s)}else throw this.raiseEarlyExitException(e,se.REPETITION_MANDATORY,t.ERR_MSG);this.attemptInRepetitionRecovery(this.atLeastOneInternal,[e,t],i,1024,e,Qs)}atLeastOneSepFirstInternal(e,t){let n=this.getKeyForAutomaticLookahead(1536,e);this.atLeastOneSepFirstInternalLogic(e,t,n)}atLeastOneSepFirstInternalLogic(e,t,n){let i=t.DEF,s=t.SEP;if(this.getLaFuncFromCache(n).call(this)===!0){i.call(this);let o=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,s,o,i,$i],o,1536,e,$i)}else throw this.raiseEarlyExitException(e,se.REPETITION_MANDATORY_WITH_SEPARATOR,t.ERR_MSG)}manyInternal(e,t){let n=this.getKeyForAutomaticLookahead(768,e);return this.manyInternalLogic(e,t,n)}manyInternalLogic(e,t,n){let i=this.getLaFuncFromCache(n),s;if(typeof t!="function"){s=t.DEF;let o=t.GATE;if(o!==void 0){let l=i;i=()=>o.call(this)&&l.call(this)}}else s=t;let a=!0;for(;i.call(this)===!0&&a===!0;)a=this.doSingleRepetition(s);this.attemptInRepetitionRecovery(this.manyInternal,[e,t],i,768,e,Js,a)}manySepFirstInternal(e,t){let n=this.getKeyForAutomaticLookahead(1280,e);this.manySepFirstInternalLogic(e,t,n)}manySepFirstInternalLogic(e,t,n){let i=t.DEF,s=t.SEP;if(this.getLaFuncFromCache(n).call(this)===!0){i.call(this);let o=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,s,o,i,ki],o,1280,e,ki)}}repetitionSepSecondInternal(e,t,n,i,s){for(;n();)this.CONSUME(t),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,t,n,i,s],n,1536,e,s)}doSingleRepetition(e){let t=this.getLexerPosition();return e.call(this),this.getLexerPosition()>t}orInternal(e,t){let n=this.getKeyForAutomaticLookahead(256,t),i=me(e)?e:e.DEF,a=this.getLaFuncFromCache(n).call(this,i);if(a!==void 0)return i[a].ALT.call(this);this.raiseNoAltException(t,e.ERR_MSG)}ruleFinallyStateUpdate(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),this.RULE_STACK.length===0&&this.isAtEndOfInput()===!1){let e=this.LA(1),t=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:e,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new Si(t,e))}}subruleInternal(e,t,n){let i;try{let s=n!==void 0?n.ARGS:void 0;return this.subruleIdx=t,i=e.apply(this,s),this.cstPostNonTerminal(i,n!==void 0&&n.LABEL!==void 0?n.LABEL:e.ruleName),i}catch(s){throw this.subruleInternalError(s,n,e.ruleName)}}subruleInternalError(e,t,n){throw Bt(e)&&e.partialCstResult!==void 0&&(this.cstPostNonTerminal(e.partialCstResult,t!==void 0&&t.LABEL!==void 0?t.LABEL:n),delete e.partialCstResult),e}consumeInternal(e,t,n){let i;try{let s=this.LA(1);this.tokenMatcher(s,e)===!0?(this.consumeToken(),i=s):this.consumeInternalError(e,s,n)}catch(s){i=this.consumeInternalRecovery(e,t,s)}return this.cstPostTerminal(n!==void 0&&n.LABEL!==void 0?n.LABEL:e.name,i),i}consumeInternalError(e,t,n){let i,s=this.LA(0);throw n!==void 0&&n.ERR_MSG?i=n.ERR_MSG:i=this.errorMessageProvider.buildMismatchTokenMessage({expected:e,actual:t,previous:s,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new fr(i,t,s))}consumeInternalRecovery(e,t,n){if(this.recoveryEnabled&&n.name==="MismatchedTokenException"&&!this.isBackTracking()){let i=this.getFollowsForInRuleRecovery(e,t);try{return this.tryInRuleRecovery(e,i)}catch(s){throw s.name===vl?n:s}}else throw n}saveRecogState(){let e=this.errors,t=ee(this.RULE_STACK);return{errors:e,lexerState:this.exportLexerState(),RULE_STACK:t,CST_STACK:this.CST_STACK}}reloadRecogState(e){this.errors=e.errors,this.importLexerState(e.lexerState),this.RULE_STACK=e.RULE_STACK}ruleInvocationStateUpdate(e,t,n){this.RULE_OCCURRENCE_STACK.push(n),this.RULE_STACK.push(e),this.cstInvocationStateUpdate(t)}isBackTracking(){return this.isBackTrackingStack.length!==0}getCurrRuleFullName(){let e=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[e]}shortRuleNameToFullName(e){return this.shortRuleNameToFull[e]}isAtEndOfInput(){return this.tokenMatcher(this.LA(1),ze)}reset(){this.resetLexerState(),this.subruleIdx=0,this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]}};var ga=class{initErrorHandler(e){this._errors=[],this.errorMessageProvider=$(e,"errorMessageProvider")?e.errorMessageProvider:De.errorMessageProvider}SAVE_ERROR(e){if(Bt(e))return e.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:ee(this.RULE_OCCURRENCE_STACK)},this._errors.push(e),e;throw Error("Trying to save an Error which is not a RecognitionException")}get errors(){return ee(this._errors)}set errors(e){this._errors=e}raiseEarlyExitException(e,t,n){let i=this.getCurrRuleFullName(),s=this.getGAstProductions()[i],o=Cn(e,s,t,this.maxLookahead)[0],l=[];for(let c=1;c<=this.maxLookahead;c++)l.push(this.LA(c));let u=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:o,actual:l,previous:this.LA(0),customUserDescription:n,ruleName:i});throw this.SAVE_ERROR(new wi(u,this.LA(1),this.LA(0)))}raiseNoAltException(e,t){let n=this.getCurrRuleFullName(),i=this.getGAstProductions()[n],s=Nn(e,i,this.maxLookahead),a=[];for(let u=1;u<=this.maxLookahead;u++)a.push(this.LA(u));let o=this.LA(0),l=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:s,actual:a,previous:o,customUserDescription:t,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new Ci(l,this.LA(1),o))}};var ya=class{initContentAssist(){}computeContentAssist(e,t){let n=this.gastProductionsCache[e];if(Pe(n))throw Error(`Rule ->${e}<- does not exist in this grammar.`);return ea([n],t,this.tokenMatcher,this.maxLookahead)}getNextPossibleTokenTypes(e){let t=ke(e.ruleStack),i=this.getGAstProductions()[t];return new Ys(i,e).startWalking()}};var xa={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(xa);var gf=!0,yf=Math.pow(2,8)-1,Rf=Ut({name:"RECORDING_PHASE_TOKEN",pattern:ie.NA});Ct([Rf]);var xf=wt(Rf,`This IToken indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,-1,-1,-1,-1,-1,-1);Object.freeze(xf);var nm={name:`This CSTNode indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}},Ta=class{initGastRecorder(e){this.recordingProdStack=[],this.RECORDING_PHASE=!1}enableRecording(){this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",()=>{for(let e=0;e<10;e++){let t=e>0?e:"";this[`CONSUME${t}`]=function(n,i){return this.consumeInternalRecord(n,e,i)},this[`SUBRULE${t}`]=function(n,i){return this.subruleInternalRecord(n,e,i)},this[`OPTION${t}`]=function(n){return this.optionInternalRecord(n,e)},this[`OR${t}`]=function(n){return this.orInternalRecord(n,e)},this[`MANY${t}`]=function(n){this.manyInternalRecord(e,n)},this[`MANY_SEP${t}`]=function(n){this.manySepFirstInternalRecord(e,n)},this[`AT_LEAST_ONE${t}`]=function(n){this.atLeastOneInternalRecord(e,n)},this[`AT_LEAST_ONE_SEP${t}`]=function(n){this.atLeastOneSepFirstInternalRecord(e,n)}}this.consume=function(e,t,n){return this.consumeInternalRecord(t,e,n)},this.subrule=function(e,t,n){return this.subruleInternalRecord(t,e,n)},this.option=function(e,t){return this.optionInternalRecord(t,e)},this.or=function(e,t){return this.orInternalRecord(t,e)},this.many=function(e,t){this.manyInternalRecord(e,t)},this.atLeastOne=function(e,t){this.atLeastOneInternalRecord(e,t)},this.ACTION=this.ACTION_RECORD,this.BACKTRACK=this.BACKTRACK_RECORD,this.LA=this.LA_RECORD})}disableRecording(){this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",()=>{let e=this;for(let t=0;t<10;t++){let n=t>0?t:"";delete e[`CONSUME${n}`],delete e[`SUBRULE${n}`],delete e[`OPTION${n}`],delete e[`OR${n}`],delete e[`MANY${n}`],delete e[`MANY_SEP${n}`],delete e[`AT_LEAST_ONE${n}`],delete e[`AT_LEAST_ONE_SEP${n}`]}delete e.consume,delete e.subrule,delete e.option,delete e.or,delete e.many,delete e.atLeastOne,delete e.ACTION,delete e.BACKTRACK,delete e.LA})}ACTION_RECORD(e){}BACKTRACK_RECORD(e,t){return()=>!0}LA_RECORD(e){return wn}topLevelRuleRecord(e,t){try{let n=new be({definition:[],name:e});return n.name=e,this.recordingProdStack.push(n),t.call(this),this.recordingProdStack.pop(),n}catch(n){if(n.KNOWN_RECORDER_ERROR!==!0)try{n.message=n.message+` + This error was thrown during the "grammar recording phase" For more info see: + https://chevrotain.io/docs/guide/internals.html#grammar-recording`}catch{throw n}throw n}}optionInternalRecord(e,t){return Li.call(this,H,e,t)}atLeastOneInternalRecord(e,t){Li.call(this,J,t,e)}atLeastOneSepFirstInternalRecord(e,t){Li.call(this,Q,t,e,gf)}manyInternalRecord(e,t){Li.call(this,F,t,e)}manySepFirstInternalRecord(e,t){Li.call(this,z,t,e,gf)}orInternalRecord(e,t){return im.call(this,e,t)}subruleInternalRecord(e,t,n){if(Ra(t),!e||$(e,"ruleName")===!1){let o=new Error(` argument is invalid expecting a Parser method reference but got: <${JSON.stringify(e)}> + inside top level rule: <${this.recordingProdStack[0].name}>`);throw o.KNOWN_RECORDER_ERROR=!0,o}let i=At(this.recordingProdStack),s=e.ruleName,a=new j({idx:t,nonTerminalName:s,label:n?.LABEL,referencedRule:void 0});return i.definition.push(a),this.outputCst?nm:xa}consumeInternalRecord(e,t,n){if(Ra(t),!dl(e)){let a=new Error(` argument is invalid expecting a TokenType reference but got: <${JSON.stringify(e)}> + inside top level rule: <${this.recordingProdStack[0].name}>`);throw a.KNOWN_RECORDER_ERROR=!0,a}let i=At(this.recordingProdStack),s=new M({idx:t,terminalType:e,label:n?.LABEL});return i.definition.push(s),xf}};function Li(r,e,t,n=!1){Ra(t);let i=At(this.recordingProdStack),s=at(e)?e:e.DEF,a=new r({definition:[],idx:t});return n&&(a.separator=e.SEP),$(e,"MAX_LOOKAHEAD")&&(a.maxLookahead=e.MAX_LOOKAHEAD),this.recordingProdStack.push(a),s.call(this),i.definition.push(a),this.recordingProdStack.pop(),xa}function im(r,e){Ra(e);let t=At(this.recordingProdStack),n=me(r)===!1,i=n===!1?r:r.DEF,s=new q({definition:[],idx:e,ignoreAmbiguities:n&&r.IGNORE_AMBIGUITIES===!0});$(r,"MAX_LOOKAHEAD")&&(s.maxLookahead=r.MAX_LOOKAHEAD);let a=$s(i,o=>at(o.GATE));return s.hasPredicates=a,t.definition.push(s),k(i,o=>{let l=new Y({definition:[]});s.definition.push(l),$(o,"IGNORE_AMBIGUITIES")?l.ignoreAmbiguities=o.IGNORE_AMBIGUITIES:$(o,"GATE")&&(l.ignoreAmbiguities=!0),this.recordingProdStack.push(l),o.ALT.call(this),this.recordingProdStack.pop()}),xa}function Tf(r){return r===0?"":`${r}`}function Ra(r){if(r<0||r>yf){let e=new Error(`Invalid DSL Method idx value: <${r}> + Idx value must be a none negative value smaller than ${yf+1}`);throw e.KNOWN_RECORDER_ERROR=!0,e}}var Ea=class{initPerformanceTracer(e){if($(e,"traceInitPerf")){let t=e.traceInitPerf,n=typeof t=="number";this.traceInitMaxIdent=n?t:1/0,this.traceInitPerf=n?t>0:t}else this.traceInitMaxIdent=0,this.traceInitPerf=De.traceInitPerf;this.traceInitIndent=-1}TRACE_INIT(e,t){if(this.traceInitPerf===!0){this.traceInitIndent++;let n=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${e}>`);let{time:i,value:s}=Ri(t),a=i>10?console.warn:console.log;return this.traceInitIndent time: ${i}ms`),this.traceInitIndent--,s}else return t()}};function Ef(r,e){e.forEach(t=>{let n=t.prototype;Object.getOwnPropertyNames(n).forEach(i=>{if(i==="constructor")return;let s=Object.getOwnPropertyDescriptor(n,i);s&&(s.get||s.set)?Object.defineProperty(r.prototype,i,s):r.prototype[i]=t.prototype[i]})})}var wn=wt(ze,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(wn);var De=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:_t,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),_n=Object.freeze({recoveryValueFunc:()=>{},resyncEnabled:!0}),ge;(function(r){r[r.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",r[r.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",r[r.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",r[r.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",r[r.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",r[r.LEFT_RECURSION=5]="LEFT_RECURSION",r[r.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",r[r.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",r[r.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",r[r.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",r[r.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",r[r.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",r[r.TOO_MANY_ALTS=12]="TOO_MANY_ALTS",r[r.CUSTOM_LOOKAHEAD_VALIDATION=13]="CUSTOM_LOOKAHEAD_VALIDATION"})(ge||(ge={}));function Aa(r=void 0){return function(){return r}}var Oi=class r{static performSelfAnalysis(e){throw Error("The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead.")}performSelfAnalysis(){this.TRACE_INIT("performSelfAnalysis",()=>{let e;this.selfAnalysisDone=!0;let t=this.className;this.TRACE_INIT("toFastProps",()=>{xi(this)}),this.TRACE_INIT("Grammar Recording",()=>{try{this.enableRecording(),k(this.definedRulesNames,i=>{let a=this[i].originalGrammarAction,o;this.TRACE_INIT(`${i} Rule`,()=>{o=this.topLevelRuleRecord(i,a)}),this.gastProductionsCache[i]=o})}finally{this.disableRecording()}});let n=[];if(this.TRACE_INIT("Grammar Resolving",()=>{n=sf({rules:te(this.gastProductionsCache)}),this.definitionErrors=this.definitionErrors.concat(n)}),this.TRACE_INIT("Grammar Validations",()=>{if(b(n)&&this.skipValidations===!1){let i=af({rules:te(this.gastProductionsCache),tokenTypes:te(this.tokensMap),errMsgProvider:nt,grammarName:t}),s=Jc({lookaheadStrategy:this.lookaheadStrategy,rules:te(this.gastProductionsCache),tokenTypes:te(this.tokensMap),grammarName:t});this.definitionErrors=this.definitionErrors.concat(i,s)}}),b(this.definitionErrors)&&(this.recoveryEnabled&&this.TRACE_INIT("computeAllProdsFollows",()=>{let i=dc(te(this.gastProductionsCache));this.resyncFollows=i}),this.TRACE_INIT("ComputeLookaheadFunctions",()=>{var i,s;(s=(i=this.lookaheadStrategy).initialize)===null||s===void 0||s.call(i,{rules:te(this.gastProductionsCache)}),this.preComputeLookaheadFunctions(te(this.gastProductionsCache))})),!r.DEFER_DEFINITION_ERRORS_HANDLING&&!b(this.definitionErrors))throw e=x(this.definitionErrors,i=>i.message),new Error(`Parser Definition Errors detected: + ${e.join(` +------------------------------- +`)}`)})}constructor(e,t){this.definitionErrors=[],this.selfAnalysisDone=!1;let n=this;if(n.initErrorHandler(t),n.initLexerAdapter(),n.initLooksAhead(t),n.initRecognizerEngine(e,t),n.initRecoverable(t),n.initTreeBuilder(t),n.initContentAssist(),n.initGastRecorder(t),n.initPerformanceTracer(t),$(t,"ignoredIssues"))throw new Error(`The IParserConfig property has been deprecated. + Please use the flag on the relevant DSL method instead. + See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES + For further details.`);this.skipValidations=$(t,"skipValidations")?t.skipValidations:De.skipValidations}};Oi.DEFER_DEFINITION_ERRORS_HANDLING=!1;Ef(Oi,[sa,la,da,ha,ma,pa,ga,ya,Ta,Ea]);var Pi=class extends Oi{constructor(e,t=De){let n=ee(t);n.outputCst=!1,super(e,n)}};function dr(r,e,t){return`${r.name}_${e}_${t}`}var Wt=1,am=2,Af=4,vf=5;var Pn=7,om=8,lm=9,um=10,cm=11,kf=12,bi=class{constructor(e){this.target=e}isEpsilon(){return!1}},Ln=class extends bi{constructor(e,t){super(e),this.tokenType=t}},Mi=class extends bi{constructor(e){super(e)}isEpsilon(){return!0}},On=class extends bi{constructor(e,t,n){super(e),this.rule=t,this.followState=n}isEpsilon(){return!0}};function $f(r){let e={decisionMap:{},decisionStates:[],ruleToStartState:new Map,ruleToStopState:new Map,states:[]};fm(e,r);let t=r.length;for(let n=0;nIf(r,e,a));return bn(r,e,n,t,...i)}function ym(r,e,t){let n=Te(r,e,t,{type:Wt});Kt(r,n);let i=bn(r,e,n,t,hr(r,e,t));return Tm(r,e,t,i)}function hr(r,e,t){let n=Re(x(t.definition,i=>If(r,e,i)),i=>i!==void 0);return n.length===1?n[0]:n.length===0?void 0:xm(r,n)}function Nf(r,e,t,n,i){let s=n.left,a=n.right,o=Te(r,e,t,{type:cm});Kt(r,o);let l=Te(r,e,t,{type:kf});return s.loopback=o,l.loopback=o,r.decisionMap[dr(e,i?"RepetitionMandatoryWithSeparator":"RepetitionMandatory",t.idx)]=o,pe(a,o),i===void 0?(pe(o,s),pe(o,l)):(pe(o,l),pe(o,i.left),pe(i.right,s)),{left:s,right:l}}function Cf(r,e,t,n,i){let s=n.left,a=n.right,o=Te(r,e,t,{type:um});Kt(r,o);let l=Te(r,e,t,{type:kf}),u=Te(r,e,t,{type:lm});return o.loopback=u,l.loopback=u,pe(o,s),pe(o,l),pe(a,u),i!==void 0?(pe(u,l),pe(u,i.left),pe(i.right,s)):pe(u,o),r.decisionMap[dr(e,i?"RepetitionWithSeparator":"Repetition",t.idx)]=o,{left:o,right:l}}function Tm(r,e,t,n){let i=n.left,s=n.right;return pe(i,s),r.decisionMap[dr(e,"Option",t.idx)]=i,n}function Kt(r,e){return r.decisionStates.push(e),e.decision=r.decisionStates.length-1,e.decision}function bn(r,e,t,n,...i){let s=Te(r,e,n,{type:om,start:t});t.end=s;for(let o of i)o!==void 0?(pe(t,o.left),pe(o.right,s)):pe(t,s);let a={left:t,right:s};return r.decisionMap[dr(e,Rm(n),n.idx)]=t,a}function Rm(r){if(r instanceof q)return"Alternation";if(r instanceof H)return"Option";if(r instanceof F)return"Repetition";if(r instanceof z)return"RepetitionWithSeparator";if(r instanceof J)return"RepetitionMandatory";if(r instanceof Q)return"RepetitionMandatoryWithSeparator";throw new Error("Invalid production type encountered")}function xm(r,e){let t=e.length;for(let s=0;se.alt)}get key(){let e="";for(let t in this.map)e+=t+":";return e}};function Pl(r,e=!0){return`${e?`a${r.alt}`:""}s${r.state.stateNumber}:${r.stack.map(t=>t.stateNumber.toString()).join("_")}`}function km(r,e){let t={};return n=>{let i=n.toString(),s=t[i];return s!==void 0||(s={atnStartState:r,decision:e,states:{}},t[i]=s),s}}var va=class{constructor(){this.predicates=[]}is(e){return e>=this.predicates.length||this.predicates[e]}set(e,t){this.predicates[e]=t}toString(){let e="",t=this.predicates.length;for(let n=0;nconsole.log(n))}initialize(e){this.atn=$f(e.rules),this.dfas=$m(this.atn)}validateAmbiguousAlternationAlternatives(){return[]}validateEmptyOrAlternatives(){return[]}buildLookaheadForAlternation(e){let{prodOccurrence:t,rule:n,hasPredicates:i,dynamicTokensEnabled:s}=e,a=this.dfas,o=this.logging,l=dr(n,"Alternation",t),c=this.atn.decisionMap[l].decision,f=x(ra({maxLookahead:1,occurrence:t,prodType:"Alternation",rule:n}),d=>x(d,h=>h[0]));if(wf(f,!1)&&!s){let d=le(f,(h,m,g)=>(k(m,A=>{A&&(h[A.tokenTypeIdx]=g,k(A.categoryMatches,R=>{h[R]=g}))}),h),{});return i?function(h){var m;let g=this.LA(1),A=d[g.tokenTypeIdx];if(h!==void 0&&A!==void 0){let R=(m=h[A])===null||m===void 0?void 0:m.GATE;if(R!==void 0&&R.call(this)===!1)return}return A}:function(){let h=this.LA(1);return d[h.tokenTypeIdx]}}else return i?function(d){let h=new va,m=d===void 0?0:d.length;for(let A=0;Ax(d,h=>h[0]));if(wf(f)&&f[0][0]&&!s){let d=f[0],h=de(d);if(h.length===1&&b(h[0].categoryMatches)){let g=h[0].tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===g}}else{let m=le(h,(g,A)=>(A!==void 0&&(g[A.tokenTypeIdx]=!0,k(A.categoryMatches,R=>{g[R]=!0})),g),{});return function(){let g=this.LA(1);return m[g.tokenTypeIdx]===!0}}}return function(){let d=bl.call(this,a,c,Sf,o);return typeof d=="object"?!1:d===0}}};function wf(r,e=!0){let t=new Set;for(let n of r){let i=new Set;for(let s of n){if(s===void 0){if(e)break;return!1}let a=[s.tokenTypeIdx].concat(s.categoryMatches);for(let o of a)if(t.has(o)){if(!i.has(o))return!1}else t.add(o),i.add(o)}}return!0}function $m(r){let e=r.decisionStates.length,t=Array(e);for(let n=0;nSt(i)).join(", "),t=r.production.idx===0?"":r.production.idx,n=`Ambiguous Alternatives Detected: <${r.ambiguityIndices.join(", ")}> in <${wm(r.production)}${t}> inside <${r.topLevelRule.name}> Rule, +<${e}> may appears as a prefix path in all these alternatives. +`;return n=n+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES +For Further details.`,n}function wm(r){if(r instanceof j)return"SUBRULE";if(r instanceof H)return"OPTION";if(r instanceof q)return"OR";if(r instanceof J)return"AT_LEAST_ONE";if(r instanceof Q)return"AT_LEAST_ONE_SEP";if(r instanceof z)return"MANY_SEP";if(r instanceof F)return"MANY";if(r instanceof M)return"CONSUME";throw Error("non exhaustive match")}function _m(r,e,t){let n=$e(e.configs.elements,s=>s.state.transitions),i=zu(n.filter(s=>s instanceof Ln).map(s=>s.tokenType),s=>s.tokenTypeIdx);return{actualToken:t,possibleTokenTypes:i,tokenPath:r}}function Lm(r,e){return r.edges[e.tokenTypeIdx]}function Om(r,e,t){let n=new Mn,i=[];for(let a of r.elements){if(t.is(a.alt)===!1)continue;if(a.state.type===Pn){i.push(a);continue}let o=a.state.transitions.length;for(let l=0;l0&&!Fm(s))for(let a of i)s.add(a);return s}function Pm(r,e){if(r instanceof Ln&&vi(e,r.tokenType))return r.target}function bm(r,e){let t;for(let n of r.elements)if(e.is(n.alt)===!0){if(t===void 0)t=n.alt;else if(t!==n.alt)return}return t}function Lf(r){return{configs:r,edges:{},isAcceptState:!1,prediction:-1}}function _f(r,e,t,n){return n=Of(r,n),e.edges[t.tokenTypeIdx]=n,n}function Of(r,e){if(e===Di)return e;let t=e.configs.key,n=r.states[t];return n!==void 0?n:(e.configs.finalize(),r.states[t]=e,e)}function Mm(r){let e=new Mn,t=r.transitions.length;for(let n=0;n0){let i=[...r.stack],a={state:i.pop(),alt:r.alt,stack:i};ka(a,e)}else e.add(r);return}t.epsilonOnlyTransitions||e.add(r);let n=t.transitions.length;for(let i=0;i1)return!0;return!1}function Km(r){for(let e of Array.from(r.values()))if(Object.keys(e).length===1)return!0;return!1}var Pf;(function(r){function e(t){return typeof t=="string"}r.is=e})(Pf||(Pf={}));var Ml;(function(r){function e(t){return typeof t=="string"}r.is=e})(Ml||(Ml={}));var bf;(function(r){r.MIN_VALUE=-2147483648,r.MAX_VALUE=2147483647;function e(t){return typeof t=="number"&&r.MIN_VALUE<=t&&t<=r.MAX_VALUE}r.is=e})(bf||(bf={}));var $a;(function(r){r.MIN_VALUE=0,r.MAX_VALUE=2147483647;function e(t){return typeof t=="number"&&r.MIN_VALUE<=t&&t<=r.MAX_VALUE}r.is=e})($a||($a={}));var B;(function(r){function e(n,i){return n===Number.MAX_VALUE&&(n=$a.MAX_VALUE),i===Number.MAX_VALUE&&(i=$a.MAX_VALUE),{line:n,character:i}}r.create=e;function t(n){let i=n;return p.objectLiteral(i)&&p.uinteger(i.line)&&p.uinteger(i.character)}r.is=t})(B||(B={}));var G;(function(r){function e(n,i,s,a){if(p.uinteger(n)&&p.uinteger(i)&&p.uinteger(s)&&p.uinteger(a))return{start:B.create(n,i),end:B.create(s,a)};if(B.is(n)&&B.is(i))return{start:n,end:i};throw new Error(`Range#create called with invalid arguments[${n}, ${i}, ${s}, ${a}]`)}r.create=e;function t(n){let i=n;return p.objectLiteral(i)&&B.is(i.start)&&B.is(i.end)}r.is=t})(G||(G={}));var Ia;(function(r){function e(n,i){return{uri:n,range:i}}r.create=e;function t(n){let i=n;return p.objectLiteral(i)&&G.is(i.range)&&(p.string(i.uri)||p.undefined(i.uri))}r.is=t})(Ia||(Ia={}));var Mf;(function(r){function e(n,i,s,a){return{targetUri:n,targetRange:i,targetSelectionRange:s,originSelectionRange:a}}r.create=e;function t(n){let i=n;return p.objectLiteral(i)&&G.is(i.targetRange)&&p.string(i.targetUri)&&G.is(i.targetSelectionRange)&&(G.is(i.originSelectionRange)||p.undefined(i.originSelectionRange))}r.is=t})(Mf||(Mf={}));var Dl;(function(r){function e(n,i,s,a){return{red:n,green:i,blue:s,alpha:a}}r.create=e;function t(n){let i=n;return p.objectLiteral(i)&&p.numberRange(i.red,0,1)&&p.numberRange(i.green,0,1)&&p.numberRange(i.blue,0,1)&&p.numberRange(i.alpha,0,1)}r.is=t})(Dl||(Dl={}));var Df;(function(r){function e(n,i){return{range:n,color:i}}r.create=e;function t(n){let i=n;return p.objectLiteral(i)&&G.is(i.range)&&Dl.is(i.color)}r.is=t})(Df||(Df={}));var Ff;(function(r){function e(n,i,s){return{label:n,textEdit:i,additionalTextEdits:s}}r.create=e;function t(n){let i=n;return p.objectLiteral(i)&&p.string(i.label)&&(p.undefined(i.textEdit)||Fn.is(i))&&(p.undefined(i.additionalTextEdits)||p.typedArray(i.additionalTextEdits,Fn.is))}r.is=t})(Ff||(Ff={}));var Gf;(function(r){r.Comment="comment",r.Imports="imports",r.Region="region"})(Gf||(Gf={}));var Uf;(function(r){function e(n,i,s,a,o,l){let u={startLine:n,endLine:i};return p.defined(s)&&(u.startCharacter=s),p.defined(a)&&(u.endCharacter=a),p.defined(o)&&(u.kind=o),p.defined(l)&&(u.collapsedText=l),u}r.create=e;function t(n){let i=n;return p.objectLiteral(i)&&p.uinteger(i.startLine)&&p.uinteger(i.startLine)&&(p.undefined(i.startCharacter)||p.uinteger(i.startCharacter))&&(p.undefined(i.endCharacter)||p.uinteger(i.endCharacter))&&(p.undefined(i.kind)||p.string(i.kind))}r.is=t})(Uf||(Uf={}));var Fl;(function(r){function e(n,i){return{location:n,message:i}}r.create=e;function t(n){let i=n;return p.defined(i)&&Ia.is(i.location)&&p.string(i.message)}r.is=t})(Fl||(Fl={}));var Bf;(function(r){r.Error=1,r.Warning=2,r.Information=3,r.Hint=4})(Bf||(Bf={}));var Wf;(function(r){r.Unnecessary=1,r.Deprecated=2})(Wf||(Wf={}));var Kf;(function(r){function e(t){let n=t;return p.objectLiteral(n)&&p.string(n.href)}r.is=e})(Kf||(Kf={}));var Na;(function(r){function e(n,i,s,a,o,l){let u={range:n,message:i};return p.defined(s)&&(u.severity=s),p.defined(a)&&(u.code=a),p.defined(o)&&(u.source=o),p.defined(l)&&(u.relatedInformation=l),u}r.create=e;function t(n){var i;let s=n;return p.defined(s)&&G.is(s.range)&&p.string(s.message)&&(p.number(s.severity)||p.undefined(s.severity))&&(p.integer(s.code)||p.string(s.code)||p.undefined(s.code))&&(p.undefined(s.codeDescription)||p.string((i=s.codeDescription)===null||i===void 0?void 0:i.href))&&(p.string(s.source)||p.undefined(s.source))&&(p.undefined(s.relatedInformation)||p.typedArray(s.relatedInformation,Fl.is))}r.is=t})(Na||(Na={}));var Dn;(function(r){function e(n,i,...s){let a={title:n,command:i};return p.defined(s)&&s.length>0&&(a.arguments=s),a}r.create=e;function t(n){let i=n;return p.defined(i)&&p.string(i.title)&&p.string(i.command)}r.is=t})(Dn||(Dn={}));var Fn;(function(r){function e(s,a){return{range:s,newText:a}}r.replace=e;function t(s,a){return{range:{start:s,end:s},newText:a}}r.insert=t;function n(s){return{range:s,newText:""}}r.del=n;function i(s){let a=s;return p.objectLiteral(a)&&p.string(a.newText)&&G.is(a.range)}r.is=i})(Fn||(Fn={}));var Gl;(function(r){function e(n,i,s){let a={label:n};return i!==void 0&&(a.needsConfirmation=i),s!==void 0&&(a.description=s),a}r.create=e;function t(n){let i=n;return p.objectLiteral(i)&&p.string(i.label)&&(p.boolean(i.needsConfirmation)||i.needsConfirmation===void 0)&&(p.string(i.description)||i.description===void 0)}r.is=t})(Gl||(Gl={}));var Gn;(function(r){function e(t){let n=t;return p.string(n)}r.is=e})(Gn||(Gn={}));var Vf;(function(r){function e(s,a,o){return{range:s,newText:a,annotationId:o}}r.replace=e;function t(s,a,o){return{range:{start:s,end:s},newText:a,annotationId:o}}r.insert=t;function n(s,a){return{range:s,newText:"",annotationId:a}}r.del=n;function i(s){let a=s;return Fn.is(a)&&(Gl.is(a.annotationId)||Gn.is(a.annotationId))}r.is=i})(Vf||(Vf={}));var Ul;(function(r){function e(n,i){return{textDocument:n,edits:i}}r.create=e;function t(n){let i=n;return p.defined(i)&&jl.is(i.textDocument)&&Array.isArray(i.edits)}r.is=t})(Ul||(Ul={}));var Bl;(function(r){function e(n,i,s){let a={kind:"create",uri:n};return i!==void 0&&(i.overwrite!==void 0||i.ignoreIfExists!==void 0)&&(a.options=i),s!==void 0&&(a.annotationId=s),a}r.create=e;function t(n){let i=n;return i&&i.kind==="create"&&p.string(i.uri)&&(i.options===void 0||(i.options.overwrite===void 0||p.boolean(i.options.overwrite))&&(i.options.ignoreIfExists===void 0||p.boolean(i.options.ignoreIfExists)))&&(i.annotationId===void 0||Gn.is(i.annotationId))}r.is=t})(Bl||(Bl={}));var Wl;(function(r){function e(n,i,s,a){let o={kind:"rename",oldUri:n,newUri:i};return s!==void 0&&(s.overwrite!==void 0||s.ignoreIfExists!==void 0)&&(o.options=s),a!==void 0&&(o.annotationId=a),o}r.create=e;function t(n){let i=n;return i&&i.kind==="rename"&&p.string(i.oldUri)&&p.string(i.newUri)&&(i.options===void 0||(i.options.overwrite===void 0||p.boolean(i.options.overwrite))&&(i.options.ignoreIfExists===void 0||p.boolean(i.options.ignoreIfExists)))&&(i.annotationId===void 0||Gn.is(i.annotationId))}r.is=t})(Wl||(Wl={}));var Kl;(function(r){function e(n,i,s){let a={kind:"delete",uri:n};return i!==void 0&&(i.recursive!==void 0||i.ignoreIfNotExists!==void 0)&&(a.options=i),s!==void 0&&(a.annotationId=s),a}r.create=e;function t(n){let i=n;return i&&i.kind==="delete"&&p.string(i.uri)&&(i.options===void 0||(i.options.recursive===void 0||p.boolean(i.options.recursive))&&(i.options.ignoreIfNotExists===void 0||p.boolean(i.options.ignoreIfNotExists)))&&(i.annotationId===void 0||Gn.is(i.annotationId))}r.is=t})(Kl||(Kl={}));var Vl;(function(r){function e(t){let n=t;return n&&(n.changes!==void 0||n.documentChanges!==void 0)&&(n.documentChanges===void 0||n.documentChanges.every(i=>p.string(i.kind)?Bl.is(i)||Wl.is(i)||Kl.is(i):Ul.is(i)))}r.is=e})(Vl||(Vl={}));var jf;(function(r){function e(n){return{uri:n}}r.create=e;function t(n){let i=n;return p.defined(i)&&p.string(i.uri)}r.is=t})(jf||(jf={}));var Hf;(function(r){function e(n,i){return{uri:n,version:i}}r.create=e;function t(n){let i=n;return p.defined(i)&&p.string(i.uri)&&p.integer(i.version)}r.is=t})(Hf||(Hf={}));var jl;(function(r){function e(n,i){return{uri:n,version:i}}r.create=e;function t(n){let i=n;return p.defined(i)&&p.string(i.uri)&&(i.version===null||p.integer(i.version))}r.is=t})(jl||(jl={}));var zf;(function(r){function e(n,i,s,a){return{uri:n,languageId:i,version:s,text:a}}r.create=e;function t(n){let i=n;return p.defined(i)&&p.string(i.uri)&&p.string(i.languageId)&&p.integer(i.version)&&p.string(i.text)}r.is=t})(zf||(zf={}));var Hl;(function(r){r.PlainText="plaintext",r.Markdown="markdown";function e(t){let n=t;return n===r.PlainText||n===r.Markdown}r.is=e})(Hl||(Hl={}));var Gi;(function(r){function e(t){let n=t;return p.objectLiteral(t)&&Hl.is(n.kind)&&p.string(n.value)}r.is=e})(Gi||(Gi={}));var qf;(function(r){r.Text=1,r.Method=2,r.Function=3,r.Constructor=4,r.Field=5,r.Variable=6,r.Class=7,r.Interface=8,r.Module=9,r.Property=10,r.Unit=11,r.Value=12,r.Enum=13,r.Keyword=14,r.Snippet=15,r.Color=16,r.File=17,r.Reference=18,r.Folder=19,r.EnumMember=20,r.Constant=21,r.Struct=22,r.Event=23,r.Operator=24,r.TypeParameter=25})(qf||(qf={}));var Xf;(function(r){r.PlainText=1,r.Snippet=2})(Xf||(Xf={}));var Yf;(function(r){r.Deprecated=1})(Yf||(Yf={}));var Jf;(function(r){function e(n,i,s){return{newText:n,insert:i,replace:s}}r.create=e;function t(n){let i=n;return i&&p.string(i.newText)&&G.is(i.insert)&&G.is(i.replace)}r.is=t})(Jf||(Jf={}));var Qf;(function(r){r.asIs=1,r.adjustIndentation=2})(Qf||(Qf={}));var Zf;(function(r){function e(t){let n=t;return n&&(p.string(n.detail)||n.detail===void 0)&&(p.string(n.description)||n.description===void 0)}r.is=e})(Zf||(Zf={}));var ed;(function(r){function e(t){return{label:t}}r.create=e})(ed||(ed={}));var td;(function(r){function e(t,n){return{items:t||[],isIncomplete:!!n}}r.create=e})(td||(td={}));var Ca;(function(r){function e(n){return n.replace(/[\\`*_{}[\]()#+\-.!]/g,"\\$&")}r.fromPlainText=e;function t(n){let i=n;return p.string(i)||p.objectLiteral(i)&&p.string(i.language)&&p.string(i.value)}r.is=t})(Ca||(Ca={}));var rd;(function(r){function e(t){let n=t;return!!n&&p.objectLiteral(n)&&(Gi.is(n.contents)||Ca.is(n.contents)||p.typedArray(n.contents,Ca.is))&&(t.range===void 0||G.is(t.range))}r.is=e})(rd||(rd={}));var nd;(function(r){function e(t,n){return n?{label:t,documentation:n}:{label:t}}r.create=e})(nd||(nd={}));var id;(function(r){function e(t,n,...i){let s={label:t};return p.defined(n)&&(s.documentation=n),p.defined(i)?s.parameters=i:s.parameters=[],s}r.create=e})(id||(id={}));var sd;(function(r){r.Text=1,r.Read=2,r.Write=3})(sd||(sd={}));var ad;(function(r){function e(t,n){let i={range:t};return p.number(n)&&(i.kind=n),i}r.create=e})(ad||(ad={}));var od;(function(r){r.File=1,r.Module=2,r.Namespace=3,r.Package=4,r.Class=5,r.Method=6,r.Property=7,r.Field=8,r.Constructor=9,r.Enum=10,r.Interface=11,r.Function=12,r.Variable=13,r.Constant=14,r.String=15,r.Number=16,r.Boolean=17,r.Array=18,r.Object=19,r.Key=20,r.Null=21,r.EnumMember=22,r.Struct=23,r.Event=24,r.Operator=25,r.TypeParameter=26})(od||(od={}));var ld;(function(r){r.Deprecated=1})(ld||(ld={}));var ud;(function(r){function e(t,n,i,s,a){let o={name:t,kind:n,location:{uri:s,range:i}};return a&&(o.containerName=a),o}r.create=e})(ud||(ud={}));var cd;(function(r){function e(t,n,i,s){return s!==void 0?{name:t,kind:n,location:{uri:i,range:s}}:{name:t,kind:n,location:{uri:i}}}r.create=e})(cd||(cd={}));var fd;(function(r){function e(n,i,s,a,o,l){let u={name:n,detail:i,kind:s,range:a,selectionRange:o};return l!==void 0&&(u.children=l),u}r.create=e;function t(n){let i=n;return i&&p.string(i.name)&&p.number(i.kind)&&G.is(i.range)&&G.is(i.selectionRange)&&(i.detail===void 0||p.string(i.detail))&&(i.deprecated===void 0||p.boolean(i.deprecated))&&(i.children===void 0||Array.isArray(i.children))&&(i.tags===void 0||Array.isArray(i.tags))}r.is=t})(fd||(fd={}));var dd;(function(r){r.Empty="",r.QuickFix="quickfix",r.Refactor="refactor",r.RefactorExtract="refactor.extract",r.RefactorInline="refactor.inline",r.RefactorRewrite="refactor.rewrite",r.Source="source",r.SourceOrganizeImports="source.organizeImports",r.SourceFixAll="source.fixAll"})(dd||(dd={}));var Sa;(function(r){r.Invoked=1,r.Automatic=2})(Sa||(Sa={}));var hd;(function(r){function e(n,i,s){let a={diagnostics:n};return i!=null&&(a.only=i),s!=null&&(a.triggerKind=s),a}r.create=e;function t(n){let i=n;return p.defined(i)&&p.typedArray(i.diagnostics,Na.is)&&(i.only===void 0||p.typedArray(i.only,p.string))&&(i.triggerKind===void 0||i.triggerKind===Sa.Invoked||i.triggerKind===Sa.Automatic)}r.is=t})(hd||(hd={}));var pd;(function(r){function e(n,i,s){let a={title:n},o=!0;return typeof i=="string"?(o=!1,a.kind=i):Dn.is(i)?a.command=i:a.edit=i,o&&s!==void 0&&(a.kind=s),a}r.create=e;function t(n){let i=n;return i&&p.string(i.title)&&(i.diagnostics===void 0||p.typedArray(i.diagnostics,Na.is))&&(i.kind===void 0||p.string(i.kind))&&(i.edit!==void 0||i.command!==void 0)&&(i.command===void 0||Dn.is(i.command))&&(i.isPreferred===void 0||p.boolean(i.isPreferred))&&(i.edit===void 0||Vl.is(i.edit))}r.is=t})(pd||(pd={}));var md;(function(r){function e(n,i){let s={range:n};return p.defined(i)&&(s.data=i),s}r.create=e;function t(n){let i=n;return p.defined(i)&&G.is(i.range)&&(p.undefined(i.command)||Dn.is(i.command))}r.is=t})(md||(md={}));var gd;(function(r){function e(n,i){return{tabSize:n,insertSpaces:i}}r.create=e;function t(n){let i=n;return p.defined(i)&&p.uinteger(i.tabSize)&&p.boolean(i.insertSpaces)}r.is=t})(gd||(gd={}));var yd;(function(r){function e(n,i,s){return{range:n,target:i,data:s}}r.create=e;function t(n){let i=n;return p.defined(i)&&G.is(i.range)&&(p.undefined(i.target)||p.string(i.target))}r.is=t})(yd||(yd={}));var Td;(function(r){function e(n,i){return{range:n,parent:i}}r.create=e;function t(n){let i=n;return p.objectLiteral(i)&&G.is(i.range)&&(i.parent===void 0||r.is(i.parent))}r.is=t})(Td||(Td={}));var Rd;(function(r){r.namespace="namespace",r.type="type",r.class="class",r.enum="enum",r.interface="interface",r.struct="struct",r.typeParameter="typeParameter",r.parameter="parameter",r.variable="variable",r.property="property",r.enumMember="enumMember",r.event="event",r.function="function",r.method="method",r.macro="macro",r.keyword="keyword",r.modifier="modifier",r.comment="comment",r.string="string",r.number="number",r.regexp="regexp",r.operator="operator",r.decorator="decorator"})(Rd||(Rd={}));var xd;(function(r){r.declaration="declaration",r.definition="definition",r.readonly="readonly",r.static="static",r.deprecated="deprecated",r.abstract="abstract",r.async="async",r.modification="modification",r.documentation="documentation",r.defaultLibrary="defaultLibrary"})(xd||(xd={}));var Ed;(function(r){function e(t){let n=t;return p.objectLiteral(n)&&(n.resultId===void 0||typeof n.resultId=="string")&&Array.isArray(n.data)&&(n.data.length===0||typeof n.data[0]=="number")}r.is=e})(Ed||(Ed={}));var Ad;(function(r){function e(n,i){return{range:n,text:i}}r.create=e;function t(n){let i=n;return i!=null&&G.is(i.range)&&p.string(i.text)}r.is=t})(Ad||(Ad={}));var vd;(function(r){function e(n,i,s){return{range:n,variableName:i,caseSensitiveLookup:s}}r.create=e;function t(n){let i=n;return i!=null&&G.is(i.range)&&p.boolean(i.caseSensitiveLookup)&&(p.string(i.variableName)||i.variableName===void 0)}r.is=t})(vd||(vd={}));var kd;(function(r){function e(n,i){return{range:n,expression:i}}r.create=e;function t(n){let i=n;return i!=null&&G.is(i.range)&&(p.string(i.expression)||i.expression===void 0)}r.is=t})(kd||(kd={}));var $d;(function(r){function e(n,i){return{frameId:n,stoppedLocation:i}}r.create=e;function t(n){let i=n;return p.defined(i)&&G.is(n.stoppedLocation)}r.is=t})($d||($d={}));var zl;(function(r){r.Type=1,r.Parameter=2;function e(t){return t===1||t===2}r.is=e})(zl||(zl={}));var ql;(function(r){function e(n){return{value:n}}r.create=e;function t(n){let i=n;return p.objectLiteral(i)&&(i.tooltip===void 0||p.string(i.tooltip)||Gi.is(i.tooltip))&&(i.location===void 0||Ia.is(i.location))&&(i.command===void 0||Dn.is(i.command))}r.is=t})(ql||(ql={}));var Id;(function(r){function e(n,i,s){let a={position:n,label:i};return s!==void 0&&(a.kind=s),a}r.create=e;function t(n){let i=n;return p.objectLiteral(i)&&B.is(i.position)&&(p.string(i.label)||p.typedArray(i.label,ql.is))&&(i.kind===void 0||zl.is(i.kind))&&i.textEdits===void 0||p.typedArray(i.textEdits,Fn.is)&&(i.tooltip===void 0||p.string(i.tooltip)||Gi.is(i.tooltip))&&(i.paddingLeft===void 0||p.boolean(i.paddingLeft))&&(i.paddingRight===void 0||p.boolean(i.paddingRight))}r.is=t})(Id||(Id={}));var Nd;(function(r){function e(t){return{kind:"snippet",value:t}}r.createSnippet=e})(Nd||(Nd={}));var Cd;(function(r){function e(t,n,i,s){return{insertText:t,filterText:n,range:i,command:s}}r.create=e})(Cd||(Cd={}));var Sd;(function(r){function e(t){return{items:t}}r.create=e})(Sd||(Sd={}));var wd;(function(r){r.Invoked=0,r.Automatic=1})(wd||(wd={}));var _d;(function(r){function e(t,n){return{range:t,text:n}}r.create=e})(_d||(_d={}));var Ld;(function(r){function e(t,n){return{triggerKind:t,selectedCompletionInfo:n}}r.create=e})(Ld||(Ld={}));var Od;(function(r){function e(t){let n=t;return p.objectLiteral(n)&&Ml.is(n.uri)&&p.string(n.name)}r.is=e})(Od||(Od={}));var Pd;(function(r){function e(s,a,o,l){return new Xl(s,a,o,l)}r.create=e;function t(s){let a=s;return!!(p.defined(a)&&p.string(a.uri)&&(p.undefined(a.languageId)||p.string(a.languageId))&&p.uinteger(a.lineCount)&&p.func(a.getText)&&p.func(a.positionAt)&&p.func(a.offsetAt))}r.is=t;function n(s,a){let o=s.getText(),l=i(a,(c,f)=>{let d=c.range.start.line-f.range.start.line;return d===0?c.range.start.character-f.range.start.character:d}),u=o.length;for(let c=l.length-1;c>=0;c--){let f=l[c],d=s.offsetAt(f.range.start),h=s.offsetAt(f.range.end);if(h<=u)o=o.substring(0,d)+f.newText+o.substring(h,o.length);else throw new Error("Overlapping edit");u=d}return o}r.applyEdits=n;function i(s,a){if(s.length<=1)return s;let o=s.length/2|0,l=s.slice(0,o),u=s.slice(o);i(l,a),i(u,a);let c=0,f=0,d=0;for(;c0&&e.push(t.length),this._lineOffsets=e}return this._lineOffsets}positionAt(e){e=Math.max(Math.min(e,this._content.length),0);let t=this.getLineOffsets(),n=0,i=t.length;if(i===0)return B.create(0,e);for(;ne?i=a:n=a+1}let s=n-1;return B.create(s,e-t[s])}offsetAt(e){let t=this.getLineOffsets();if(e.line>=t.length)return this._content.length;if(e.line<0)return 0;let n=t[e.line],i=e.line+1"u"}r.undefined=n;function i(h){return h===!0||h===!1}r.boolean=i;function s(h){return e.call(h)==="[object String]"}r.string=s;function a(h){return e.call(h)==="[object Number]"}r.number=a;function o(h,m,g){return e.call(h)==="[object Number]"&&m<=h&&h<=g}r.numberRange=o;function l(h){return e.call(h)==="[object Number]"&&-2147483648<=h&&h<=2147483647}r.integer=l;function u(h){return e.call(h)==="[object Number]"&&0<=h&&h<=2147483647}r.uinteger=u;function c(h){return e.call(h)==="[object Function]"}r.func=c;function f(h){return h!==null&&typeof h=="object"}r.objectLiteral=f;function d(h,m){return Array.isArray(h)&&h.every(m)}r.typedArray=d})(p||(p={}));var Ui=class{constructor(){this.nodeStack=[]}get current(){var e;return(e=this.nodeStack[this.nodeStack.length-1])!==null&&e!==void 0?e:this.rootNode}buildRootNode(e){return this.rootNode=new Un(e),this.rootNode.root=this.rootNode,this.nodeStack=[this.rootNode],this.rootNode}buildCompositeNode(e){let t=new mr;return t.grammarSource=e,t.root=this.rootNode,this.current.content.push(t),this.nodeStack.push(t),t}buildLeafNode(e,t){let n=new pr(e.startOffset,e.image.length,Ir(e),e.tokenType,!t);return n.grammarSource=t,n.root=this.rootNode,this.current.content.push(n),n}removeNode(e){let t=e.container;if(t){let n=t.content.indexOf(e);n>=0&&t.content.splice(n,1)}}addHiddenNodes(e){let t=[];for(let s of e){let a=new pr(s.startOffset,s.image.length,Ir(s),s.tokenType,!0);a.root=this.rootNode,t.push(a)}let n=this.current,i=!1;if(n.content.length>0){n.content.push(...t);return}for(;n.container;){let s=n.container.content.indexOf(n);if(s>0){n.container.content.splice(s,0,...t),i=!0;break}n=n.container}i||this.rootNode.content.unshift(...t)}construct(e){let t=this.current;typeof e.$type=="string"&&(this.current.astNode=e),e.$cstNode=t;let n=this.nodeStack.pop();n?.content.length===0&&this.removeNode(n)}},Bi=class{get parent(){return this.container}get feature(){return this.grammarSource}get hidden(){return!1}get astNode(){var e,t;let n=typeof((e=this._astNode)===null||e===void 0?void 0:e.$type)=="string"?this._astNode:(t=this.container)===null||t===void 0?void 0:t.astNode;if(!n)throw new Error("This node has no associated AST element");return n}set astNode(e){this._astNode=e}get element(){return this.astNode}get text(){return this.root.fullText.substring(this.offset,this.end)}},pr=class extends Bi{get offset(){return this._offset}get length(){return this._length}get end(){return this._offset+this._length}get hidden(){return this._hidden}get tokenType(){return this._tokenType}get range(){return this._range}constructor(e,t,n,i,s=!1){super(),this._hidden=s,this._offset=e,this._tokenType=i,this._length=t,this._range=n}},mr=class extends Bi{constructor(){super(...arguments),this.content=new Yl(this)}get children(){return this.content}get offset(){var e,t;return(t=(e=this.firstNonHiddenNode)===null||e===void 0?void 0:e.offset)!==null&&t!==void 0?t:0}get length(){return this.end-this.offset}get end(){var e,t;return(t=(e=this.lastNonHiddenNode)===null||e===void 0?void 0:e.end)!==null&&t!==void 0?t:0}get range(){let e=this.firstNonHiddenNode,t=this.lastNonHiddenNode;if(e&&t){if(this._rangeCache===void 0){let{range:n}=e,{range:i}=t;this._rangeCache={start:n.start,end:i.end.line=0;e--){let t=this.content[e];if(!t.hidden)return t}return this.content[this.content.length-1]}},Yl=class r extends Array{constructor(e){super(),this.parent=e,Object.setPrototypeOf(this,r.prototype)}push(...e){return this.addParents(e),super.push(...e)}unshift(...e){return this.addParents(e),super.unshift(...e)}splice(e,t,...n){return this.addParents(n),super.splice(e,t,...n)}addParents(e){for(let t of e)t.container=this.parent}},Un=class extends mr{get text(){return this._text.substring(this.offset,this.end)}get fullText(){return this._text}constructor(e){super(),this._text="",this._text=e??""}};var wa=Symbol("Datatype");function Jl(r){return r.$type===wa}var bd="\u200B",Md=r=>r.endsWith(bd)?r:r+bd,Wi=class{constructor(e){this._unorderedGroups=new Map,this.allRules=new Map,this.lexer=e.parser.Lexer;let t=this.lexer.definition,n=e.LanguageMetaData.mode==="production";this.wrapper=new Ql(t,Object.assign(Object.assign({},e.parser.ParserConfig),{skipValidations:n,errorMessageProvider:e.parser.ParserErrorMessageProvider}))}alternatives(e,t){this.wrapper.wrapOr(e,t)}optional(e,t){this.wrapper.wrapOption(e,t)}many(e,t){this.wrapper.wrapMany(e,t)}atLeastOne(e,t){this.wrapper.wrapAtLeastOne(e,t)}getRule(e){return this.allRules.get(e)}isRecording(){return this.wrapper.IS_RECORDING}get unorderedGroups(){return this._unorderedGroups}getRuleStack(){return this.wrapper.RULE_STACK}finalize(){this.wrapper.wrapSelfAnalysis()}},Ki=class extends Wi{get current(){return this.stack[this.stack.length-1]}constructor(e){super(e),this.nodeBuilder=new Ui,this.stack=[],this.assignmentMap=new Map,this.linker=e.references.Linker,this.converter=e.parser.ValueConverter,this.astReflection=e.shared.AstReflection}rule(e,t){let n=this.computeRuleType(e),i=this.wrapper.DEFINE_RULE(Md(e.name),this.startImplementation(n,t).bind(this));return this.allRules.set(e.name,i),e.entry&&(this.mainRule=i),i}computeRuleType(e){if(!e.fragment){if(gi(e))return wa;{let t=gn(e);return t??e.name}}}parse(e,t={}){this.nodeBuilder.buildRootNode(e);let n=this.lexerResult=this.lexer.tokenize(e);this.wrapper.input=n.tokens;let i=t.rule?this.allRules.get(t.rule):this.mainRule;if(!i)throw new Error(t.rule?`No rule found with name '${t.rule}'`:"No main rule available.");let s=i.call(this.wrapper,{});return this.nodeBuilder.addHiddenNodes(n.hidden),this.unorderedGroups.clear(),this.lexerResult=void 0,{value:s,lexerErrors:n.errors,lexerReport:n.report,parserErrors:this.wrapper.errors}}startImplementation(e,t){return n=>{let i=!this.isRecording()&&e!==void 0;if(i){let a={$type:e};this.stack.push(a),e===wa&&(a.value="")}let s;try{s=t(n)}catch{s=void 0}return s===void 0&&i&&(s=this.construct()),s}}extractHiddenTokens(e){let t=this.lexerResult.hidden;if(!t.length)return[];let n=e.startOffset;for(let i=0;in)return t.splice(0,i);return t.splice(0,t.length)}consume(e,t,n){let i=this.wrapper.wrapConsume(e,t);if(!this.isRecording()&&this.isValidToken(i)){let s=this.extractHiddenTokens(i);this.nodeBuilder.addHiddenNodes(s);let a=this.nodeBuilder.buildLeafNode(i,n),{assignment:o,isCrossRef:l}=this.getAssignment(n),u=this.current;if(o){let c=Xe(n)?i.image:this.converter.convert(i.image,a);this.assign(o.operator,o.feature,c,a,l)}else if(Jl(u)){let c=i.image;Xe(n)||(c=this.converter.convert(c,a).toString()),u.value+=c}}}isValidToken(e){return!e.isInsertedInRecovery&&!isNaN(e.startOffset)&&typeof e.endOffset=="number"&&!isNaN(e.endOffset)}subrule(e,t,n,i,s){let a;!this.isRecording()&&!n&&(a=this.nodeBuilder.buildCompositeNode(i));let o=this.wrapper.wrapSubrule(e,t,s);!this.isRecording()&&a&&a.length>0&&this.performSubruleAssignment(o,i,a)}performSubruleAssignment(e,t,n){let{assignment:i,isCrossRef:s}=this.getAssignment(t);if(i)this.assign(i.operator,i.feature,e,n,s);else if(!i){let a=this.current;if(Jl(a))a.value+=e.toString();else if(typeof e=="object"&&e){let l=this.assignWithoutOverride(e,a);this.stack.pop(),this.stack.push(l)}}}action(e,t){if(!this.isRecording()){let n=this.current;if(t.feature&&t.operator){n=this.construct(),this.nodeBuilder.removeNode(n.$cstNode),this.nodeBuilder.buildCompositeNode(t).content.push(n.$cstNode);let s={$type:e};this.stack.push(s),this.assign(t.operator,t.feature,n,n.$cstNode,!1)}else n.$type=e}}construct(){if(this.isRecording())return;let e=this.current;return Ms(e),this.nodeBuilder.construct(e),this.stack.pop(),Jl(e)?this.converter.convert(e.value,e.$cstNode):(Fo(this.astReflection,e),e)}getAssignment(e){if(!this.assignmentMap.has(e)){let t=nr(e,tt);this.assignmentMap.set(e,{assignment:t,isCrossRef:t?rr(t.terminal):!1})}return this.assignmentMap.get(e)}assign(e,t,n,i,s){let a=this.current,o;switch(s&&typeof n=="string"?o=this.linker.buildReference(a,t,i,n):o=n,e){case"=":{a[t]=o;break}case"?=":{a[t]=!0;break}case"+=":Array.isArray(a[t])||(a[t]=[]),a[t].push(o)}}assignWithoutOverride(e,t){for(let[i,s]of Object.entries(t)){let a=e[i];a===void 0?e[i]=s:Array.isArray(a)&&Array.isArray(s)&&(s.push(...a),e[i]=s)}let n=e.$cstNode;return n&&(n.astNode=void 0,e.$cstNode=void 0),e}get definitionErrors(){return this.wrapper.definitionErrors}},_a=class{buildMismatchTokenMessage(e){return _t.buildMismatchTokenMessage(e)}buildNotAllInputParsedMessage(e){return _t.buildNotAllInputParsedMessage(e)}buildNoViableAltMessage(e){return _t.buildNoViableAltMessage(e)}buildEarlyExitMessage(e){return _t.buildEarlyExitMessage(e)}},Bn=class extends _a{buildMismatchTokenMessage({expected:e,actual:t}){return`Expecting ${e.LABEL?"`"+e.LABEL+"`":e.name.endsWith(":KW")?`keyword '${e.name.substring(0,e.name.length-3)}'`:`token of type '${e.name}'`} but found \`${t.image}\`.`}buildNotAllInputParsedMessage({firstRedundant:e}){return`Expecting end of file but found \`${e.image}\`.`}},Vi=class extends Wi{constructor(){super(...arguments),this.tokens=[],this.elementStack=[],this.lastElementStack=[],this.nextTokenIndex=0,this.stackSize=0}action(){}construct(){}parse(e){this.resetState();let t=this.lexer.tokenize(e,{mode:"partial"});return this.tokens=t.tokens,this.wrapper.input=[...this.tokens],this.mainRule.call(this.wrapper,{}),this.unorderedGroups.clear(),{tokens:this.tokens,elementStack:[...this.lastElementStack],tokenIndex:this.nextTokenIndex}}rule(e,t){let n=this.wrapper.DEFINE_RULE(Md(e.name),this.startImplementation(t).bind(this));return this.allRules.set(e.name,n),e.entry&&(this.mainRule=n),n}resetState(){this.elementStack=[],this.lastElementStack=[],this.nextTokenIndex=0,this.stackSize=0}startImplementation(e){return t=>{let n=this.keepStackSize();try{e(t)}finally{this.resetStackSize(n)}}}removeUnexpectedElements(){this.elementStack.splice(this.stackSize)}keepStackSize(){let e=this.elementStack.length;return this.stackSize=e,e}resetStackSize(e){this.removeUnexpectedElements(),this.stackSize=e}consume(e,t,n){this.wrapper.wrapConsume(e,t),this.isRecording()||(this.lastElementStack=[...this.elementStack,n],this.nextTokenIndex=this.currIdx+1)}subrule(e,t,n,i,s){this.before(i),this.wrapper.wrapSubrule(e,t,s),this.after(i)}before(e){this.isRecording()||this.elementStack.push(e)}after(e){if(!this.isRecording()){let t=this.elementStack.lastIndexOf(e);t>=0&&this.elementStack.splice(t)}}get currIdx(){return this.wrapper.currIdx}},Vm={recoveryEnabled:!0,nodeLocationTracking:"full",skipValidations:!0,errorMessageProvider:new Bn},Ql=class extends Pi{constructor(e,t){let n=t&&"maxLookahead"in t;super(e,Object.assign(Object.assign(Object.assign({},Vm),{lookaheadStrategy:n?new Lt({maxLookahead:t.maxLookahead}):new Fi({logging:t.skipValidations?()=>{}:void 0})}),t))}get IS_RECORDING(){return this.RECORDING_PHASE}DEFINE_RULE(e,t){return this.RULE(e,t)}wrapSelfAnalysis(){this.performSelfAnalysis()}wrapConsume(e,t){return this.consume(e,t)}wrapSubrule(e,t,n){return this.subrule(e,t,{ARGS:[n]})}wrapOr(e,t){this.or(e,t)}wrapOption(e,t){this.option(e,t)}wrapMany(e,t){this.many(e,t)}wrapAtLeastOne(e,t){this.atLeastOne(e,t)}};function ji(r,e,t){return jm({parser:e,tokens:t,ruleNames:new Map},r),e}function jm(r,e){let t=pi(e,!1),n=V(e.rules).filter(Ce).filter(i=>t.has(i));for(let i of n){let s=Object.assign(Object.assign({},r),{consume:1,optional:1,subrule:1,many:1,or:1});r.parser.rule(i,gr(s,i.definition))}}function gr(r,e,t=!1){let n;if(Xe(e))n=Qm(r,e);else if(kt(e))n=Hm(r,e);else if(tt(e))n=gr(r,e.terminal);else if(rr(e))n=Dd(r,e);else if(rt(e))n=zm(r,e);else if(Os(e))n=Xm(r,e);else if(bs(e))n=Ym(r,e);else if(Gt(e))n=Jm(r,e);else if(So(e)){let i=r.consume++;n=()=>r.parser.consume(i,ze,e)}else throw new er(e.$cstNode,`Unexpected element type: ${e.$type}`);return Fd(r,t?void 0:La(e),n,e.cardinality)}function Hm(r,e){let t=yi(e);return()=>r.parser.action(t,e)}function zm(r,e){let t=e.rule.ref;if(Ce(t)){let n=r.subrule++,i=t.fragment,s=e.arguments.length>0?qm(t,e.arguments):()=>({});return a=>r.parser.subrule(n,Gd(r,t),i,e,s(a))}else if(je(t)){let n=r.consume++,i=Zl(r,t.name);return()=>r.parser.consume(n,i,e)}else if(t)ut(t);else throw new er(e.$cstNode,`Undefined rule: ${e.rule.$refText}`)}function qm(r,e){let t=e.map(n=>Ot(n.value));return n=>{let i={};for(let s=0;se(n)||t(n)}else if(Eo(r)){let e=Ot(r.left),t=Ot(r.right);return n=>e(n)&&t(n)}else if(vo(r)){let e=Ot(r.value);return t=>!e(t)}else if(ko(r)){let e=r.parameter.ref.name;return t=>t!==void 0&&t[e]===!0}else if(xo(r)){let e=!!r.true;return()=>e}ut(r)}function Xm(r,e){if(e.elements.length===1)return gr(r,e.elements[0]);{let t=[];for(let i of e.elements){let s={ALT:gr(r,i,!0)},a=La(i);a&&(s.GATE=Ot(a)),t.push(s)}let n=r.or++;return i=>r.parser.alternatives(n,t.map(s=>{let a={ALT:()=>s.ALT(i)},o=s.GATE;return o&&(a.GATE=()=>o(i)),a}))}}function Ym(r,e){if(e.elements.length===1)return gr(r,e.elements[0]);let t=[];for(let o of e.elements){let l={ALT:gr(r,o,!0)},u=La(o);u&&(l.GATE=Ot(u)),t.push(l)}let n=r.or++,i=(o,l)=>{let u=l.getRuleStack().join("-");return`uGroup_${o}_${u}`},s=o=>r.parser.alternatives(n,t.map((l,u)=>{let c={ALT:()=>!0},f=r.parser;c.ALT=()=>{if(l.ALT(o),!f.isRecording()){let h=i(n,f);f.unorderedGroups.get(h)||f.unorderedGroups.set(h,[]);let m=f.unorderedGroups.get(h);typeof m?.[u]>"u"&&(m[u]=!0)}};let d=l.GATE;return d?c.GATE=()=>d(o):c.GATE=()=>{let h=f.unorderedGroups.get(i(n,f));return!h?.[u]},c})),a=Fd(r,La(e),s,"*");return o=>{a(o),r.parser.isRecording()||r.parser.unorderedGroups.delete(i(n,r.parser))}}function Jm(r,e){let t=e.elements.map(n=>gr(r,n));return n=>t.forEach(i=>i(n))}function La(r){if(Gt(r))return r.guardCondition}function Dd(r,e,t=e.terminal){if(t)if(rt(t)&&Ce(t.rule.ref)){let n=t.rule.ref,i=r.subrule++;return s=>r.parser.subrule(i,Gd(r,n),!1,e,s)}else if(rt(t)&&je(t.rule.ref)){let n=r.consume++,i=Zl(r,t.rule.ref.name);return()=>r.parser.consume(n,i,e)}else if(Xe(t)){let n=r.consume++,i=Zl(r,t.value);return()=>r.parser.consume(n,i,e)}else throw new Error("Could not build cross reference parser");else{if(!e.type.ref)throw new Error("Could not resolve reference to type: "+e.type.$refText);let n=Bs(e.type.ref),i=n?.terminal;if(!i)throw new Error("Could not find name assignment for type: "+yi(e.type.ref));return Dd(r,e,i)}}function Qm(r,e){let t=r.consume++,n=r.tokens[e.value];if(!n)throw new Error("Could not find token for keyword: "+e.value);return()=>r.parser.consume(t,n,e)}function Fd(r,e,t,n){let i=e&&Ot(e);if(!n)if(i){let s=r.or++;return a=>r.parser.alternatives(s,[{ALT:()=>t(a),GATE:()=>i(a)},{ALT:Aa(),GATE:()=>!i(a)}])}else return t;if(n==="*"){let s=r.many++;return a=>r.parser.many(s,{DEF:()=>t(a),GATE:i?()=>i(a):void 0})}else if(n==="+"){let s=r.many++;if(i){let a=r.or++;return o=>r.parser.alternatives(a,[{ALT:()=>r.parser.atLeastOne(s,{DEF:()=>t(o)}),GATE:()=>i(o)},{ALT:Aa(),GATE:()=>!i(o)}])}else return a=>r.parser.atLeastOne(s,{DEF:()=>t(a)})}else if(n==="?"){let s=r.optional++;return a=>r.parser.optional(s,{DEF:()=>t(a),GATE:i?()=>i(a):void 0})}else ut(n)}function Gd(r,e){let t=Zm(r,e),n=r.parser.getRule(t);if(!n)throw new Error(`Rule "${t}" not found."`);return n}function Zm(r,e){if(Ce(e))return e.name;if(r.ruleNames.has(e))return r.ruleNames.get(e);{let t=e,n=t.$container,i=e.$type;for(;!Ce(n);)(Gt(n)||Os(n)||bs(n))&&(i=n.elements.indexOf(t).toString()+":"+i),t=n,n=n.$container;return i=n.name+":"+i,r.ruleNames.set(e,i),i}}function Zl(r,e){let t=r.tokens[e];if(!t)throw new Error(`Token "${e}" not found."`);return t}function eu(r){let e=r.Grammar,t=r.parser.Lexer,n=new Vi(r);return ji(e,n,t.definition),n.finalize(),n}function tu(r){let e=Ud(r);return e.finalize(),e}function Ud(r){let e=r.Grammar,t=r.parser.Lexer,n=new Ki(r);return ji(e,n,t.definition)}var Pt=class{constructor(){this.diagnostics=[]}buildTokens(e,t){let n=V(pi(e,!1)),i=this.buildTerminalTokens(n),s=this.buildKeywordTokens(n,i,t);return i.forEach(a=>{let o=a.PATTERN;typeof o=="object"&&o&&"test"in o&&mn(o)?s.unshift(a):s.push(a)}),s}flushLexingReport(e){return{diagnostics:this.popDiagnostics()}}popDiagnostics(){let e=[...this.diagnostics];return this.diagnostics=[],e}buildTerminalTokens(e){return e.filter(je).filter(t=>!t.fragment).map(t=>this.buildTerminalToken(t)).toArray()}buildTerminalToken(e){let t=yn(e),n=this.requiresCustomPattern(t)?this.regexPatternFunction(t):t,i={name:e.name,PATTERN:n};return typeof n=="function"&&(i.LINE_BREAKS=!0),e.hidden&&(i.GROUP=mn(t)?ie.SKIPPED:"hidden"),i}requiresCustomPattern(e){return e.flags.includes("u")||e.flags.includes("s")?!0:!!(e.source.includes("?<=")||e.source.includes("?(t.lastIndex=i,t.exec(n))}buildKeywordTokens(e,t,n){return e.filter(Ce).flatMap(i=>ct(i).filter(Xe)).distinct(i=>i.value).toArray().sort((i,s)=>s.value.length-i.value.length).map(i=>this.buildKeywordToken(i,t,!!n?.caseInsensitive))}buildKeywordToken(e,t,n){let i=this.buildKeywordPattern(e,n),s={name:e.value,PATTERN:i,LONGER_ALT:this.findLongerAlt(e,t)};return typeof i=="function"&&(s.LINE_BREAKS=!0),s}buildKeywordPattern(e,t){return t?new RegExp(Vo(e.value)):e.value}findLongerAlt(e,t){return t.reduce((n,i)=>{let s=i?.PATTERN;return s?.source&&jo("^"+s.source+"$",e.value)&&n.push(i),n},[])}};var yr=class{convert(e,t){let n=t.grammarSource;if(rr(n)&&(n=qo(n)),rt(n)){let i=n.rule.ref;if(!i)throw new Error("This cst node was not parsed by a rule.");return this.runConverter(i,e,t)}return e}runConverter(e,t,n){var i;switch(e.name.toUpperCase()){case"INT":return ht.convertInt(t);case"STRING":return ht.convertString(t);case"ID":return ht.convertID(t)}switch((i=tl(e))===null||i===void 0?void 0:i.toLowerCase()){case"number":return ht.convertNumber(t);case"boolean":return ht.convertBoolean(t);case"bigint":return ht.convertBigint(t);case"date":return ht.convertDate(t);default:return t}}},ht;(function(r){function e(u){let c="";for(let f=1;f{typeof setImmediate>"u"?setTimeout(r,0):setImmediate(r)})}var Ma=0,Hd=10;function Da(){return Ma=performance.now(),new C.CancellationTokenSource}function zd(r){Hd=r}var pt=Symbol("OperationCancelled");function mt(r){return r===pt}async function ue(r){if(r===C.CancellationToken.None)return;let e=performance.now();if(e-Ma>=Hd&&(Ma=e,await cu(),Ma=performance.now()),r.isCancellationRequested)throw pt}var Fe=class{constructor(){this.promise=new Promise((e,t)=>{this.resolve=n=>(e(n),this),this.reject=n=>(t(n),this)})}};var Fa=class r{constructor(e,t,n,i){this._uri=e,this._languageId=t,this._version=n,this._content=i,this._lineOffsets=void 0}get uri(){return this._uri}get languageId(){return this._languageId}get version(){return this._version}getText(e){if(e){let t=this.offsetAt(e.start),n=this.offsetAt(e.end);return this._content.substring(t,n)}return this._content}update(e,t){for(let n of e)if(r.isIncremental(n)){let i=Yd(n.range),s=this.offsetAt(i.start),a=this.offsetAt(i.end);this._content=this._content.substring(0,s)+n.text+this._content.substring(a,this._content.length);let o=Math.max(i.start.line,0),l=Math.max(i.end.line,0),u=this._lineOffsets,c=qd(n.text,!1,s);if(l-o===c.length)for(let d=0,h=c.length;de?i=a:n=a+1}let s=n-1;return e=this.ensureBeforeEOL(e,t[s]),{line:s,character:e-t[s]}}offsetAt(e){let t=this.getLineOffsets();if(e.line>=t.length)return this._content.length;if(e.line<0)return 0;let n=t[e.line];if(e.character<=0)return n;let i=e.line+1t&&Xd(this._content.charCodeAt(e-1));)e--;return e}get lineCount(){return this.getLineOffsets().length}static isIncremental(e){let t=e;return t!=null&&typeof t.text=="string"&&t.range!==void 0&&(t.rangeLength===void 0||typeof t.rangeLength=="number")}static isFull(e){let t=e;return t!=null&&typeof t.text=="string"&&t.range===void 0&&t.rangeLength===void 0}},Vn;(function(r){function e(i,s,a,o){return new Fa(i,s,a,o)}r.create=e;function t(i,s,a){if(i instanceof Fa)return i.update(s,a),i;throw new Error("TextDocument.update: document must be created by TextDocument.create")}r.update=t;function n(i,s){let a=i.getText(),o=fu(s.map(ug),(c,f)=>{let d=c.range.start.line-f.range.start.line;return d===0?c.range.start.character-f.range.start.character:d}),l=0,u=[];for(let c of o){let f=i.offsetAt(c.range.start);if(fl&&u.push(a.substring(l,f)),c.newText.length&&u.push(c.newText),l=i.offsetAt(c.range.end)}return u.push(a.substr(l)),u.join("")}r.applyEdits=n})(Vn||(Vn={}));function fu(r,e){if(r.length<=1)return r;let t=r.length/2|0,n=r.slice(0,t),i=r.slice(t);fu(n,e),fu(i,e);let s=0,a=0,o=0;for(;st.line||e.line===t.line&&e.character>t.character?{start:t,end:e}:r}function ug(r){let e=Yd(r.range);return e!==r.range?{newText:r.newText,range:e}:r}var Jd;(()=>{"use strict";var r={470:i=>{function s(l){if(typeof l!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(l))}function a(l,u){for(var c,f="",d=0,h=-1,m=0,g=0;g<=l.length;++g){if(g2){var A=f.lastIndexOf("/");if(A!==f.length-1){A===-1?(f="",d=0):d=(f=f.slice(0,A)).length-1-f.lastIndexOf("/"),h=g,m=0;continue}}else if(f.length===2||f.length===1){f="",d=0,h=g,m=0;continue}}u&&(f.length>0?f+="/..":f="..",d=2)}else f.length>0?f+="/"+l.slice(h+1,g):f=l.slice(h+1,g),d=g-h-1;h=g,m=0}else c===46&&m!==-1?++m:m=-1}return f}var o={resolve:function(){for(var l,u="",c=!1,f=arguments.length-1;f>=-1&&!c;f--){var d;f>=0?d=arguments[f]:(l===void 0&&(l=process.cwd()),d=l),s(d),d.length!==0&&(u=d+"/"+u,c=d.charCodeAt(0)===47)}return u=a(u,!c),c?u.length>0?"/"+u:"/":u.length>0?u:"."},normalize:function(l){if(s(l),l.length===0)return".";var u=l.charCodeAt(0)===47,c=l.charCodeAt(l.length-1)===47;return(l=a(l,!u)).length!==0||u||(l="."),l.length>0&&c&&(l+="/"),u?"/"+l:l},isAbsolute:function(l){return s(l),l.length>0&&l.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var l,u=0;u0&&(l===void 0?l=c:l+="/"+c)}return l===void 0?".":o.normalize(l)},relative:function(l,u){if(s(l),s(u),l===u||(l=o.resolve(l))===(u=o.resolve(u)))return"";for(var c=1;cg){if(u.charCodeAt(h+R)===47)return u.slice(h+R+1);if(R===0)return u.slice(h+R)}else d>g&&(l.charCodeAt(c+R)===47?A=R:R===0&&(A=0));break}var E=l.charCodeAt(c+R);if(E!==u.charCodeAt(h+R))break;E===47&&(A=R)}var T="";for(R=c+A+1;R<=f;++R)R!==f&&l.charCodeAt(R)!==47||(T.length===0?T+="..":T+="/..");return T.length>0?T+u.slice(h+A):(h+=A,u.charCodeAt(h)===47&&++h,u.slice(h))},_makeLong:function(l){return l},dirname:function(l){if(s(l),l.length===0)return".";for(var u=l.charCodeAt(0),c=u===47,f=-1,d=!0,h=l.length-1;h>=1;--h)if((u=l.charCodeAt(h))===47){if(!d){f=h;break}}else d=!1;return f===-1?c?"/":".":c&&f===1?"//":l.slice(0,f)},basename:function(l,u){if(u!==void 0&&typeof u!="string")throw new TypeError('"ext" argument must be a string');s(l);var c,f=0,d=-1,h=!0;if(u!==void 0&&u.length>0&&u.length<=l.length){if(u.length===l.length&&u===l)return"";var m=u.length-1,g=-1;for(c=l.length-1;c>=0;--c){var A=l.charCodeAt(c);if(A===47){if(!h){f=c+1;break}}else g===-1&&(h=!1,g=c+1),m>=0&&(A===u.charCodeAt(m)?--m==-1&&(d=c):(m=-1,d=g))}return f===d?d=g:d===-1&&(d=l.length),l.slice(f,d)}for(c=l.length-1;c>=0;--c)if(l.charCodeAt(c)===47){if(!h){f=c+1;break}}else d===-1&&(h=!1,d=c+1);return d===-1?"":l.slice(f,d)},extname:function(l){s(l);for(var u=-1,c=0,f=-1,d=!0,h=0,m=l.length-1;m>=0;--m){var g=l.charCodeAt(m);if(g!==47)f===-1&&(d=!1,f=m+1),g===46?u===-1?u=m:h!==1&&(h=1):u!==-1&&(h=-1);else if(!d){c=m+1;break}}return u===-1||f===-1||h===0||h===1&&u===f-1&&u===c+1?"":l.slice(u,f)},format:function(l){if(l===null||typeof l!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof l);return(function(u,c){var f=c.dir||c.root,d=c.base||(c.name||"")+(c.ext||"");return f?f===c.root?f+d:f+"/"+d:d})(0,l)},parse:function(l){s(l);var u={root:"",dir:"",base:"",ext:"",name:""};if(l.length===0)return u;var c,f=l.charCodeAt(0),d=f===47;d?(u.root="/",c=1):c=0;for(var h=-1,m=0,g=-1,A=!0,R=l.length-1,E=0;R>=c;--R)if((f=l.charCodeAt(R))!==47)g===-1&&(A=!1,g=R+1),f===46?h===-1?h=R:E!==1&&(E=1):h!==-1&&(E=-1);else if(!A){m=R+1;break}return h===-1||g===-1||E===0||E===1&&h===g-1&&h===m+1?g!==-1&&(u.base=u.name=m===0&&d?l.slice(1,g):l.slice(m,g)):(m===0&&d?(u.name=l.slice(1,h),u.base=l.slice(1,g)):(u.name=l.slice(m,h),u.base=l.slice(m,g)),u.ext=l.slice(h,g)),m>0?u.dir=l.slice(0,m-1):d&&(u.dir="/"),u},sep:"/",delimiter:":",win32:null,posix:null};o.posix=o,i.exports=o}},e={};function t(i){var s=e[i];if(s!==void 0)return s.exports;var a=e[i]={exports:{}};return r[i](a,a.exports,t),a.exports}t.d=(i,s)=>{for(var a in s)t.o(s,a)&&!t.o(i,a)&&Object.defineProperty(i,a,{enumerable:!0,get:s[a]})},t.o=(i,s)=>Object.prototype.hasOwnProperty.call(i,s),t.r=i=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(i,"__esModule",{value:!0})};var n={};(()=>{let i;t.r(n),t.d(n,{URI:()=>d,Utils:()=>yt}),typeof process=="object"?i=process.platform==="win32":typeof navigator=="object"&&(i=navigator.userAgent.indexOf("Windows")>=0);let s=/^\w[\w\d+.-]*$/,a=/^\//,o=/^\/\//;function l(v,y){if(!v.scheme&&y)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${v.authority}", path: "${v.path}", query: "${v.query}", fragment: "${v.fragment}"}`);if(v.scheme&&!s.test(v.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(v.path){if(v.authority){if(!a.test(v.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(o.test(v.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}}let u="",c="/",f=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class d{static isUri(y){return y instanceof d||!!y&&typeof y.authority=="string"&&typeof y.fragment=="string"&&typeof y.path=="string"&&typeof y.query=="string"&&typeof y.scheme=="string"&&typeof y.fsPath=="string"&&typeof y.with=="function"&&typeof y.toString=="function"}scheme;authority;path;query;fragment;constructor(y,N,I,K,L,_=!1){typeof y=="object"?(this.scheme=y.scheme||u,this.authority=y.authority||u,this.path=y.path||u,this.query=y.query||u,this.fragment=y.fragment||u):(this.scheme=(function(_e,Le){return _e||Le?_e:"file"})(y,_),this.authority=N||u,this.path=(function(_e,Le){switch(_e){case"https":case"http":case"file":Le?Le[0]!==c&&(Le=c+Le):Le=c}return Le})(this.scheme,I||u),this.query=K||u,this.fragment=L||u,l(this,_))}get fsPath(){return E(this,!1)}with(y){if(!y)return this;let{scheme:N,authority:I,path:K,query:L,fragment:_}=y;return N===void 0?N=this.scheme:N===null&&(N=u),I===void 0?I=this.authority:I===null&&(I=u),K===void 0?K=this.path:K===null&&(K=u),L===void 0?L=this.query:L===null&&(L=u),_===void 0?_=this.fragment:_===null&&(_=u),N===this.scheme&&I===this.authority&&K===this.path&&L===this.query&&_===this.fragment?this:new m(N,I,K,L,_)}static parse(y,N=!1){let I=f.exec(y);return I?new m(I[2]||u,ye(I[4]||u),ye(I[5]||u),ye(I[7]||u),ye(I[9]||u),N):new m(u,u,u,u,u)}static file(y){let N=u;if(i&&(y=y.replace(/\\/g,c)),y[0]===c&&y[1]===c){let I=y.indexOf(c,2);I===-1?(N=y.substring(2),y=c):(N=y.substring(2,I),y=y.substring(I)||c)}return new m("file",N,y,u,u)}static from(y){let N=new m(y.scheme,y.authority,y.path,y.query,y.fragment);return l(N,!0),N}toString(y=!1){return T(this,y)}toJSON(){return this}static revive(y){if(y){if(y instanceof d)return y;{let N=new m(y);return N._formatted=y.external,N._fsPath=y._sep===h?y.fsPath:null,N}}return y}}let h=i?1:void 0;class m extends d{_formatted=null;_fsPath=null;get fsPath(){return this._fsPath||(this._fsPath=E(this,!1)),this._fsPath}toString(y=!1){return y?T(this,!0):(this._formatted||(this._formatted=T(this,!1)),this._formatted)}toJSON(){let y={$mid:1};return this._fsPath&&(y.fsPath=this._fsPath,y._sep=h),this._formatted&&(y.external=this._formatted),this.path&&(y.path=this.path),this.scheme&&(y.scheme=this.scheme),this.authority&&(y.authority=this.authority),this.query&&(y.query=this.query),this.fragment&&(y.fragment=this.fragment),y}}let g={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function A(v,y,N){let I,K=-1;for(let L=0;L=97&&_<=122||_>=65&&_<=90||_>=48&&_<=57||_===45||_===46||_===95||_===126||y&&_===47||N&&_===91||N&&_===93||N&&_===58)K!==-1&&(I+=encodeURIComponent(v.substring(K,L)),K=-1),I!==void 0&&(I+=v.charAt(L));else{I===void 0&&(I=v.substr(0,L));let _e=g[_];_e!==void 0?(K!==-1&&(I+=encodeURIComponent(v.substring(K,L)),K=-1),I+=_e):K===-1&&(K=L)}}return K!==-1&&(I+=encodeURIComponent(v.substring(K))),I!==void 0?I:v}function R(v){let y;for(let N=0;N1&&v.scheme==="file"?`//${v.authority}${v.path}`:v.path.charCodeAt(0)===47&&(v.path.charCodeAt(1)>=65&&v.path.charCodeAt(1)<=90||v.path.charCodeAt(1)>=97&&v.path.charCodeAt(1)<=122)&&v.path.charCodeAt(2)===58?y?v.path.substr(1):v.path[1].toLowerCase()+v.path.substr(2):v.path,i&&(N=N.replace(/\//g,"\\")),N}function T(v,y){let N=y?R:A,I="",{scheme:K,authority:L,path:_,query:_e,fragment:Le}=v;if(K&&(I+=K,I+=":"),(L||K==="file")&&(I+=c,I+=c),L){let Z=L.indexOf("@");if(Z!==-1){let jt=L.substr(0,Z);L=L.substr(Z+1),Z=jt.lastIndexOf(":"),Z===-1?I+=N(jt,!1,!1):(I+=N(jt.substr(0,Z),!1,!1),I+=":",I+=N(jt.substr(Z+1),!1,!0)),I+="@"}L=L.toLowerCase(),Z=L.lastIndexOf(":"),Z===-1?I+=N(L,!1,!0):(I+=N(L.substr(0,Z),!1,!0),I+=L.substr(Z))}if(_){if(_.length>=3&&_.charCodeAt(0)===47&&_.charCodeAt(2)===58){let Z=_.charCodeAt(1);Z>=65&&Z<=90&&(_=`/${String.fromCharCode(Z+32)}:${_.substr(3)}`)}else if(_.length>=2&&_.charCodeAt(1)===58){let Z=_.charCodeAt(0);Z>=65&&Z<=90&&(_=`${String.fromCharCode(Z+32)}:${_.substr(2)}`)}I+=N(_,!0,!1)}return _e&&(I+="?",I+=N(_e,!1,!1)),Le&&(I+="#",I+=y?Le:A(Le,!1,!1)),I}function O(v){try{return decodeURIComponent(v)}catch{return v.length>3?v.substr(0,3)+O(v.substr(3)):v}}let P=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function ye(v){return v.match(P)?v.replace(P,(y=>O(y))):v}var vr=t(470);let Ee=vr.posix||vr,bt="/";var yt;(function(v){v.joinPath=function(y,...N){return y.with({path:Ee.join(y.path,...N)})},v.resolvePath=function(y,...N){let I=y.path,K=!1;I[0]!==bt&&(I=bt+I,K=!0);let L=Ee.resolve(I,...N);return K&&L[0]===bt&&!y.authority&&(L=L.substring(1)),y.with({path:L})},v.dirname=function(y){if(y.path.length===0||y.path===bt)return y;let N=Ee.dirname(y.path);return N.length===1&&N.charCodeAt(0)===46&&(N=""),y.with({path:N})},v.basename=function(y){return Ee.basename(y.path)},v.extname=function(y){return Ee.extname(y.path)}})(yt||(yt={}))})(),Jd=n})();var{URI:Ge,Utils:jn}=Jd;var Ue;(function(r){r.basename=jn.basename,r.dirname=jn.dirname,r.extname=jn.extname,r.joinPath=jn.joinPath,r.resolvePath=jn.resolvePath;function e(i,s){return i?.toString()===s?.toString()}r.equals=e;function t(i,s){let a=typeof i=="string"?i:i.path,o=typeof s=="string"?s:s.path,l=a.split("/").filter(h=>h.length>0),u=o.split("/").filter(h=>h.length>0),c=0;for(;ci??(i=Vn.create(e.toString(),n.getServices(e).LanguageMetaData.languageId,0,t??""))}},zi=class{constructor(e){this.documentMap=new Map,this.langiumDocumentFactory=e.workspace.LangiumDocumentFactory,this.serviceRegistry=e.ServiceRegistry}get all(){return V(this.documentMap.values())}addDocument(e){let t=e.uri.toString();if(this.documentMap.has(t))throw new Error(`A document with the URI '${t}' is already present.`);this.documentMap.set(t,e)}getDocument(e){let t=e.toString();return this.documentMap.get(t)}async getOrCreateDocument(e,t){let n=this.getDocument(e);return n||(n=await this.langiumDocumentFactory.fromUri(e,t),this.addDocument(n),n)}createDocument(e,t,n){if(n)return this.langiumDocumentFactory.fromString(t,e,n).then(i=>(this.addDocument(i),i));{let i=this.langiumDocumentFactory.fromString(t,e);return this.addDocument(i),i}}hasDocument(e){return this.documentMap.has(e.toString())}invalidateDocument(e){let t=e.toString(),n=this.documentMap.get(t);return n&&(this.serviceRegistry.getServices(e).references.Linker.unlink(n),n.state=X.Changed,n.precomputedScopes=void 0,n.diagnostics=void 0),n}deleteDocument(e){let t=e.toString(),n=this.documentMap.get(t);return n&&(n.state=X.Changed,this.documentMap.delete(t)),n}};var du=Symbol("ref_resolving"),qi=class{constructor(e){this.reflection=e.shared.AstReflection,this.langiumDocuments=()=>e.shared.workspace.LangiumDocuments,this.scopeProvider=e.references.ScopeProvider,this.astNodeLocator=e.workspace.AstNodeLocator}async link(e,t=C.CancellationToken.None){for(let n of Ye(e.parseResult.value))await ue(t),hn(n).forEach(i=>this.doLink(i,e))}doLink(e,t){var n;let i=e.reference;if(i._ref===void 0){i._ref=du;try{let s=this.getCandidate(e);if(Jt(s))i._ref=s;else if(i._nodeDescription=s,this.langiumDocuments().hasDocument(s.documentUri)){let a=this.loadAstNode(s);i._ref=a??this.createLinkingError(e,s)}else i._ref=void 0}catch(s){console.error(`An error occurred while resolving reference to '${i.$refText}':`,s);let a=(n=s.message)!==null&&n!==void 0?n:String(s);i._ref=Object.assign(Object.assign({},e),{message:`An error occurred while resolving reference to '${i.$refText}': ${a}`})}t.references.push(i)}}unlink(e){for(let t of e.references)delete t._ref,delete t._nodeDescription;e.references=[]}getCandidate(e){let n=this.scopeProvider.getScope(e).getElement(e.reference.$refText);return n??this.createLinkingError(e)}buildReference(e,t,n,i){let s=this,a={$refNode:n,$refText:i,get ref(){var o;if(oe(this._ref))return this._ref;if(ho(this._nodeDescription)){let l=s.loadAstNode(this._nodeDescription);this._ref=l??s.createLinkingError({reference:a,container:e,property:t},this._nodeDescription)}else if(this._ref===void 0){this._ref=du;let l=ui(e).$document,u=s.getLinkedNode({reference:a,container:e,property:t});if(u.error&&l&&l.state=e.end)return s.ref}}if(n){let i=this.nameProvider.getNameNode(n);if(i&&(i===e||mo(e,i)))return n}}}findDeclarationNode(e){let t=this.findDeclaration(e);if(t?.$cstNode){let n=this.nameProvider.getNameNode(t);return n??t.$cstNode}}findReferences(e,t){let n=[];if(t.includeDeclaration){let s=this.getReferenceToSelf(e);s&&n.push(s)}let i=this.index.findAllReferences(e,this.nodeLocator.getAstNodePath(e));return t.documentUri&&(i=i.filter(s=>Ue.equals(s.sourceUri,t.documentUri))),n.push(...i),V(n)}getReferenceToSelf(e){let t=this.nameProvider.getNameNode(e);if(t){let n=Se(e),i=this.nodeLocator.getAstNodePath(e);return{sourceUri:n.uri,sourcePath:i,targetUri:n.uri,targetPath:i,segment:Zt(t),local:!0}}}};var it=class{constructor(e){if(this.map=new Map,e)for(let[t,n]of e)this.add(t,n)}get size(){return $r.sum(V(this.map.values()).map(e=>e.length))}clear(){this.map.clear()}delete(e,t){if(t===void 0)return this.map.delete(e);{let n=this.map.get(e);if(n){let i=n.indexOf(t);if(i>=0)return n.length===1?this.map.delete(e):n.splice(i,1),!0}return!1}}get(e){var t;return(t=this.map.get(e))!==null&&t!==void 0?t:[]}has(e,t){if(t===void 0)return this.map.has(e);{let n=this.map.get(e);return n?n.indexOf(t)>=0:!1}}add(e,t){return this.map.has(e)?this.map.get(e).push(t):this.map.set(e,[t]),this}addAll(e,t){return this.map.has(e)?this.map.get(e).push(...t):this.map.set(e,Array.from(t)),this}forEach(e){this.map.forEach((t,n)=>t.forEach(i=>e(i,n,this)))}[Symbol.iterator](){return this.entries().iterator()}entries(){return V(this.map.entries()).flatMap(([e,t])=>t.map(n=>[e,n]))}keys(){return V(this.map.keys())}values(){return V(this.map.values()).flat()}entriesGroupedByKey(){return V(this.map.entries())}},Tr=class{get size(){return this.map.size}constructor(e){if(this.map=new Map,this.inverse=new Map,e)for(let[t,n]of e)this.set(t,n)}clear(){this.map.clear(),this.inverse.clear()}set(e,t){return this.map.set(e,t),this.inverse.set(t,e),this}get(e){return this.map.get(e)}getKey(e){return this.inverse.get(e)}delete(e){let t=this.map.get(e);return t!==void 0?(this.map.delete(e),this.inverse.delete(t),!0):!1}};var Ji=class{constructor(e){this.nameProvider=e.references.NameProvider,this.descriptions=e.workspace.AstNodeDescriptionProvider}async computeExports(e,t=C.CancellationToken.None){return this.computeExportsForNode(e.parseResult.value,e,void 0,t)}async computeExportsForNode(e,t,n=ci,i=C.CancellationToken.None){let s=[];this.exportNode(e,s,t);for(let a of n(e))await ue(i),this.exportNode(a,s,t);return s}exportNode(e,t,n){let i=this.nameProvider.getName(e);i&&t.push(this.descriptions.createDescription(e,i,n))}async computeLocalScopes(e,t=C.CancellationToken.None){let n=e.parseResult.value,i=new it;for(let s of ct(n))await ue(t),this.processNode(s,e,i);return i}processNode(e,t,n){let i=e.$container;if(i){let s=this.nameProvider.getName(e);s&&n.add(i,this.descriptions.createDescription(e,s,t))}}};var Hn=class{constructor(e,t,n){var i;this.elements=e,this.outerScope=t,this.caseInsensitive=(i=n?.caseInsensitive)!==null&&i!==void 0?i:!1}getAllElements(){return this.outerScope?this.elements.concat(this.outerScope.getAllElements()):this.elements}getElement(e){let t=this.caseInsensitive?this.elements.find(n=>n.name.toLowerCase()===e.toLowerCase()):this.elements.find(n=>n.name===e);if(t)return t;if(this.outerScope)return this.outerScope.getElement(e)}},Qi=class{constructor(e,t,n){var i;this.elements=new Map,this.caseInsensitive=(i=n?.caseInsensitive)!==null&&i!==void 0?i:!1;for(let s of e){let a=this.caseInsensitive?s.name.toLowerCase():s.name;this.elements.set(a,s)}this.outerScope=t}getElement(e){let t=this.caseInsensitive?e.toLowerCase():e,n=this.elements.get(t);if(n)return n;if(this.outerScope)return this.outerScope.getElement(e)}getAllElements(){let e=V(this.elements.values());return this.outerScope&&(e=e.concat(this.outerScope.getAllElements())),e}},cg={getElement(){},getAllElements(){return Zn}};var zn=class{constructor(){this.toDispose=[],this.isDisposed=!1}onDispose(e){this.toDispose.push(e)}dispose(){this.throwIfDisposed(),this.clear(),this.isDisposed=!0,this.toDispose.forEach(e=>e.dispose())}throwIfDisposed(){if(this.isDisposed)throw new Error("This cache has already been disposed")}},Zi=class extends zn{constructor(){super(...arguments),this.cache=new Map}has(e){return this.throwIfDisposed(),this.cache.has(e)}set(e,t){this.throwIfDisposed(),this.cache.set(e,t)}get(e,t){if(this.throwIfDisposed(),this.cache.has(e))return this.cache.get(e);if(t){let n=t();return this.cache.set(e,n),n}else return}delete(e){return this.throwIfDisposed(),this.cache.delete(e)}clear(){this.throwIfDisposed(),this.cache.clear()}},Rr=class extends zn{constructor(e){super(),this.cache=new Map,this.converter=e??(t=>t)}has(e,t){return this.throwIfDisposed(),this.cacheForContext(e).has(t)}set(e,t,n){this.throwIfDisposed(),this.cacheForContext(e).set(t,n)}get(e,t,n){this.throwIfDisposed();let i=this.cacheForContext(e);if(i.has(t))return i.get(t);if(n){let s=n();return i.set(t,s),s}else return}delete(e,t){return this.throwIfDisposed(),this.cacheForContext(e).delete(t)}clear(e){if(this.throwIfDisposed(),e){let t=this.converter(e);this.cache.delete(t)}else this.cache.clear()}cacheForContext(e){let t=this.converter(e),n=this.cache.get(t);return n||(n=new Map,this.cache.set(t,n)),n}},Ga=class extends Rr{constructor(e,t){super(n=>n.toString()),t?(this.toDispose.push(e.workspace.DocumentBuilder.onDocumentPhase(t,n=>{this.clear(n.uri.toString())})),this.toDispose.push(e.workspace.DocumentBuilder.onUpdate((n,i)=>{for(let s of i)this.clear(s)}))):this.toDispose.push(e.workspace.DocumentBuilder.onUpdate((n,i)=>{let s=n.concat(i);for(let a of s)this.clear(a)}))}},qn=class extends Zi{constructor(e,t){super(),t?(this.toDispose.push(e.workspace.DocumentBuilder.onBuildPhase(t,()=>{this.clear()})),this.toDispose.push(e.workspace.DocumentBuilder.onUpdate((n,i)=>{i.length>0&&this.clear()}))):this.toDispose.push(e.workspace.DocumentBuilder.onUpdate(()=>{this.clear()}))}};var es=class{constructor(e){this.reflection=e.shared.AstReflection,this.nameProvider=e.references.NameProvider,this.descriptions=e.workspace.AstNodeDescriptionProvider,this.indexManager=e.shared.workspace.IndexManager,this.globalScopeCache=new qn(e.shared)}getScope(e){let t=[],n=this.reflection.getReferenceType(e),i=Se(e.container).precomputedScopes;if(i){let a=e.container;do{let o=i.get(a);o.length>0&&t.push(V(o).filter(l=>this.reflection.isSubtype(l.type,n))),a=a.$container}while(a)}let s=this.getGlobalScope(n,e);for(let a=t.length-1;a>=0;a--)s=this.createScope(t[a],s);return s}createScope(e,t,n){return new Hn(V(e),t,n)}createScopeForNodes(e,t,n){let i=V(e).map(s=>{let a=this.nameProvider.getName(s);if(a)return this.descriptions.createDescription(s,a)}).nonNullable();return new Hn(i,t,n)}getGlobalScope(e,t){return this.globalScopeCache.get(e,()=>new Qi(this.indexManager.allElements(e)))}};function hu(r){return typeof r.$comment=="string"}function Zd(r){return typeof r=="object"&&!!r&&("$ref"in r||"$error"in r)}var ts=class{constructor(e){this.ignoreProperties=new Set(["$container","$containerProperty","$containerIndex","$document","$cstNode"]),this.langiumDocuments=e.shared.workspace.LangiumDocuments,this.astNodeLocator=e.workspace.AstNodeLocator,this.nameProvider=e.references.NameProvider,this.commentProvider=e.documentation.CommentProvider}serialize(e,t){let n=t??{},i=t?.replacer,s=(o,l)=>this.replacer(o,l,n),a=i?(o,l)=>i(o,l,s):s;try{return this.currentDocument=Se(e),JSON.stringify(e,a,t?.space)}finally{this.currentDocument=void 0}}deserialize(e,t){let n=t??{},i=JSON.parse(e);return this.linkNode(i,i,n),i}replacer(e,t,{refText:n,sourceText:i,textRegions:s,comments:a,uriConverter:o}){var l,u,c,f;if(!this.ignoreProperties.has(e))if(xe(t)){let d=t.ref,h=n?t.$refText:void 0;if(d){let m=Se(d),g="";this.currentDocument&&this.currentDocument!==m&&(o?g=o(m.uri,t):g=m.uri.toString());let A=this.astNodeLocator.getAstNodePath(d);return{$ref:`${g}#${A}`,$refText:h}}else return{$error:(u=(l=t.error)===null||l===void 0?void 0:l.message)!==null&&u!==void 0?u:"Could not resolve reference",$refText:h}}else if(oe(t)){let d;if(s&&(d=this.addAstNodeRegionWithAssignmentsTo(Object.assign({},t)),(!e||t.$document)&&d?.$textRegion&&(d.$textRegion.documentURI=(c=this.currentDocument)===null||c===void 0?void 0:c.uri.toString())),i&&!e&&(d??(d=Object.assign({},t)),d.$sourceText=(f=t.$cstNode)===null||f===void 0?void 0:f.text),a){d??(d=Object.assign({},t));let h=this.commentProvider.getComment(t);h&&(d.$comment=h.replace(/\r/g,""))}return d??t}else return t}addAstNodeRegionWithAssignmentsTo(e){let t=n=>({offset:n.offset,end:n.end,length:n.length,range:n.range});if(e.$cstNode){let n=e.$textRegion=t(e.$cstNode),i=n.assignments={};return Object.keys(e).filter(s=>!s.startsWith("$")).forEach(s=>{let a=Yo(e.$cstNode,s).map(t);a.length!==0&&(i[s]=a)}),e}}linkNode(e,t,n,i,s,a){for(let[l,u]of Object.entries(e))if(Array.isArray(u))for(let c=0;c{await this.handleException(()=>e.call(t,n,i,s),"An error occurred during validation",i,n)}}async handleException(e,t,n,i){try{await e()}catch(s){if(mt(s))throw s;console.error(`${t}:`,s),s instanceof Error&&s.stack&&console.error(s.stack);let a=s instanceof Error?s.message:String(s);n("error",`${t}: ${a}`,{node:i})}}addEntry(e,t){if(e==="AstNode"){this.entries.add("AstNode",t);return}for(let n of this.reflection.getAllSubTypes(e))this.entries.add(n,t)}getChecks(e,t){let n=V(this.entries.get(e)).concat(this.entries.get("AstNode"));return t&&(n=n.filter(i=>t.includes(i.category))),n.map(i=>i.check)}registerBeforeDocument(e,t=this){this.entriesBefore.push(this.wrapPreparationException(e,"An error occurred during set-up of the validation",t))}registerAfterDocument(e,t=this){this.entriesAfter.push(this.wrapPreparationException(e,"An error occurred during tear-down of the validation",t))}wrapPreparationException(e,t,n){return async(i,s,a,o)=>{await this.handleException(()=>e.call(n,i,s,a,o),t,s,i)}}get checksBefore(){return this.entriesBefore}get checksAfter(){return this.entriesAfter}};var is=class{constructor(e){this.validationRegistry=e.validation.ValidationRegistry,this.metadata=e.LanguageMetaData}async validateDocument(e,t={},n=C.CancellationToken.None){let i=e.parseResult,s=[];if(await ue(n),(!t.categories||t.categories.includes("built-in"))&&(this.processLexingErrors(i,s,t),t.stopAfterLexingErrors&&s.some(a=>{var o;return((o=a.data)===null||o===void 0?void 0:o.code)===Je.LexingError})||(this.processParsingErrors(i,s,t),t.stopAfterParsingErrors&&s.some(a=>{var o;return((o=a.data)===null||o===void 0?void 0:o.code)===Je.ParsingError}))||(this.processLinkingErrors(e,s,t),t.stopAfterLinkingErrors&&s.some(a=>{var o;return((o=a.data)===null||o===void 0?void 0:o.code)===Je.LinkingError}))))return s;try{s.push(...await this.validateAst(i.value,t,n))}catch(a){if(mt(a))throw a;console.error("An error occurred during validation:",a)}return await ue(n),s}processLexingErrors(e,t,n){var i,s,a;let o=[...e.lexerErrors,...(s=(i=e.lexerReport)===null||i===void 0?void 0:i.diagnostics)!==null&&s!==void 0?s:[]];for(let l of o){let u=(a=l.severity)!==null&&a!==void 0?a:"error",c={severity:Ua(u),range:{start:{line:l.line-1,character:l.column-1},end:{line:l.line-1,character:l.column+l.length-1}},message:l.message,data:th(u),source:this.getSource()};t.push(c)}}processParsingErrors(e,t,n){for(let i of e.parserErrors){let s;if(isNaN(i.token.startOffset)){if("previousToken"in i){let a=i.previousToken;if(isNaN(a.startOffset)){let o={line:0,character:0};s={start:o,end:o}}else{let o={line:a.endLine-1,character:a.endColumn};s={start:o,end:o}}}}else s=Ir(i.token);if(s){let a={severity:Ua("error"),range:s,message:i.message,data:xr(Je.ParsingError),source:this.getSource()};t.push(a)}}}processLinkingErrors(e,t,n){for(let i of e.references){let s=i.error;if(s){let a={node:s.container,property:s.property,index:s.index,data:{code:Je.LinkingError,containerType:s.container.$type,property:s.property,refText:s.reference.$refText}};t.push(this.toDiagnostic("error",s.message,a))}}}async validateAst(e,t,n=C.CancellationToken.None){let i=[],s=(a,o,l)=>{i.push(this.toDiagnostic(a,o,l))};return await this.validateAstBefore(e,t,s,n),await this.validateAstNodes(e,t,s,n),await this.validateAstAfter(e,t,s,n),i}async validateAstBefore(e,t,n,i=C.CancellationToken.None){var s;let a=this.validationRegistry.checksBefore;for(let o of a)await ue(i),await o(e,n,(s=t.categories)!==null&&s!==void 0?s:[],i)}async validateAstNodes(e,t,n,i=C.CancellationToken.None){await Promise.all(Ye(e).map(async s=>{await ue(i);let a=this.validationRegistry.getChecks(s.$type,t.categories);for(let o of a)await o(s,n,i)}))}async validateAstAfter(e,t,n,i=C.CancellationToken.None){var s;let a=this.validationRegistry.checksAfter;for(let o of a)await ue(i),await o(e,n,(s=t.categories)!==null&&s!==void 0?s:[],i)}toDiagnostic(e,t,n){return{message:t,range:eh(n),severity:Ua(e),code:n.code,codeDescription:n.codeDescription,tags:n.tags,relatedInformation:n.relatedInformation,data:n.data,source:this.getSource()}}getSource(){return this.metadata.languageId}};function eh(r){if(r.range)return r.range;let e;return typeof r.property=="string"?e=mi(r.node.$cstNode,r.property,r.index):typeof r.keyword=="string"&&(e=Qo(r.node.$cstNode,r.keyword,r.index)),e??(e=r.node.$cstNode),e?e.range:{start:{line:0,character:0},end:{line:0,character:0}}}function Ua(r){switch(r){case"error":return 1;case"warning":return 2;case"info":return 3;case"hint":return 4;default:throw new Error("Invalid diagnostic severity: "+r)}}function th(r){switch(r){case"error":return xr(Je.LexingError);case"warning":return xr(Je.LexingWarning);case"info":return xr(Je.LexingInfo);case"hint":return xr(Je.LexingHint);default:throw new Error("Invalid diagnostic severity: "+r)}}var Je;(function(r){r.LexingError="lexing-error",r.LexingWarning="lexing-warning",r.LexingInfo="lexing-info",r.LexingHint="lexing-hint",r.ParsingError="parsing-error",r.LinkingError="linking-error"})(Je||(Je={}));var ss=class{constructor(e){this.astNodeLocator=e.workspace.AstNodeLocator,this.nameProvider=e.references.NameProvider}createDescription(e,t,n){let i=n??Se(e);t??(t=this.nameProvider.getName(e));let s=this.astNodeLocator.getAstNodePath(e);if(!t)throw new Error(`Node at path ${s} has no name.`);let a,o=()=>{var l;return a??(a=Zt((l=this.nameProvider.getNameNode(e))!==null&&l!==void 0?l:e.$cstNode))};return{node:e,name:t,get nameSegment(){return o()},selectionSegment:Zt(e.$cstNode),type:e.$type,documentUri:i.uri,path:s}}},as=class{constructor(e){this.nodeLocator=e.workspace.AstNodeLocator}async createDescriptions(e,t=C.CancellationToken.None){let n=[],i=e.parseResult.value;for(let s of Ye(i))await ue(t),hn(s).filter(a=>!Jt(a)).forEach(a=>{let o=this.createDescription(a);o&&n.push(o)});return n}createDescription(e){let t=e.reference.$nodeDescription,n=e.reference.$refNode;if(!t||!n)return;let i=Se(e.container).uri;return{sourceUri:i,sourcePath:this.nodeLocator.getAstNodePath(e.container),targetUri:t.documentUri,targetPath:t.path,segment:Zt(n),local:Ue.equals(t.documentUri,i)}}};var os=class{constructor(){this.segmentSeparator="/",this.indexSeparator="@"}getAstNodePath(e){if(e.$container){let t=this.getAstNodePath(e.$container),n=this.getPathSegment(e);return t+this.segmentSeparator+n}return""}getPathSegment({$containerProperty:e,$containerIndex:t}){if(!e)throw new Error("Missing '$containerProperty' in AST node.");return t!==void 0?e+this.indexSeparator+t:e}getAstNode(e,t){return t.split(this.segmentSeparator).reduce((i,s)=>{if(!i||s.length===0)return i;let a=s.indexOf(this.indexSeparator);if(a>0){let o=s.substring(0,a),l=parseInt(s.substring(a+1)),u=i[o];return u?.[l]}return i[s]},e)}};var re={};U(re,Ku(ou(),1));var ls=class{constructor(e){this._ready=new Fe,this.settings={},this.workspaceConfig=!1,this.onConfigurationSectionUpdateEmitter=new re.Emitter,this.serviceRegistry=e.ServiceRegistry}get ready(){return this._ready.promise}initialize(e){var t,n;this.workspaceConfig=(n=(t=e.capabilities.workspace)===null||t===void 0?void 0:t.configuration)!==null&&n!==void 0?n:!1}async initialized(e){if(this.workspaceConfig){if(e.register){let t=this.serviceRegistry.all;e.register({section:t.map(n=>this.toSectionName(n.LanguageMetaData.languageId))})}if(e.fetchConfiguration){let t=this.serviceRegistry.all.map(i=>({section:this.toSectionName(i.LanguageMetaData.languageId)})),n=await e.fetchConfiguration(t);t.forEach((i,s)=>{this.updateSectionConfiguration(i.section,n[s])})}}this._ready.resolve()}updateConfiguration(e){e.settings&&Object.keys(e.settings).forEach(t=>{let n=e.settings[t];this.updateSectionConfiguration(t,n),this.onConfigurationSectionUpdateEmitter.fire({section:t,configuration:n})})}updateSectionConfiguration(e,t){this.settings[e]=t}async getConfiguration(e,t){await this.ready;let n=this.toSectionName(e);if(this.settings[n])return this.settings[n][t]}toSectionName(e){return`${e}`}get onConfigurationSectionUpdate(){return this.onConfigurationSectionUpdateEmitter.event}};var Vt;(function(r){function e(t){return{dispose:async()=>await t()}}r.create=e})(Vt||(Vt={}));var us=class{constructor(e){this.updateBuildOptions={validation:{categories:["built-in","fast"]}},this.updateListeners=[],this.buildPhaseListeners=new it,this.documentPhaseListeners=new it,this.buildState=new Map,this.documentBuildWaiters=new Map,this.currentState=X.Changed,this.langiumDocuments=e.workspace.LangiumDocuments,this.langiumDocumentFactory=e.workspace.LangiumDocumentFactory,this.textDocuments=e.workspace.TextDocuments,this.indexManager=e.workspace.IndexManager,this.serviceRegistry=e.ServiceRegistry}async build(e,t={},n=C.CancellationToken.None){var i,s;for(let a of e){let o=a.uri.toString();if(a.state===X.Validated){if(typeof t.validation=="boolean"&&t.validation)a.state=X.IndexedReferences,a.diagnostics=void 0,this.buildState.delete(o);else if(typeof t.validation=="object"){let l=this.buildState.get(o),u=(i=l?.result)===null||i===void 0?void 0:i.validationChecks;if(u){let f=((s=t.validation.categories)!==null&&s!==void 0?s:Xn.all).filter(d=>!u.includes(d));f.length>0&&(this.buildState.set(o,{completed:!1,options:{validation:Object.assign(Object.assign({},t.validation),{categories:f})},result:l.result}),a.state=X.IndexedReferences)}}}else this.buildState.delete(o)}this.currentState=X.Changed,await this.emitUpdate(e.map(a=>a.uri),[]),await this.buildDocuments(e,t,n)}async update(e,t,n=C.CancellationToken.None){this.currentState=X.Changed;for(let a of t)this.langiumDocuments.deleteDocument(a),this.buildState.delete(a.toString()),this.indexManager.remove(a);for(let a of e){if(!this.langiumDocuments.invalidateDocument(a)){let l=this.langiumDocumentFactory.fromModel({$type:"INVALID"},a);l.state=X.Changed,this.langiumDocuments.addDocument(l)}this.buildState.delete(a.toString())}let i=V(e).concat(t).map(a=>a.toString()).toSet();this.langiumDocuments.all.filter(a=>!i.has(a.uri.toString())&&this.shouldRelink(a,i)).forEach(a=>{this.serviceRegistry.getServices(a.uri).references.Linker.unlink(a),a.state=Math.min(a.state,X.ComputedScopes),a.diagnostics=void 0}),await this.emitUpdate(e,t),await ue(n);let s=this.sortDocuments(this.langiumDocuments.all.filter(a=>{var o;return a.staten(e,t)))}sortDocuments(e){let t=0,n=e.length-1;for(;t=0&&!this.hasTextDocument(e[n]);)n--;tn.error!==void 0)?!0:this.indexManager.isAffected(e,t)}onUpdate(e){return this.updateListeners.push(e),Vt.create(()=>{let t=this.updateListeners.indexOf(e);t>=0&&this.updateListeners.splice(t,1)})}async buildDocuments(e,t,n){this.prepareBuild(e,t),await this.runCancelable(e,X.Parsed,n,s=>this.langiumDocumentFactory.update(s,n)),await this.runCancelable(e,X.IndexedContent,n,s=>this.indexManager.updateContent(s,n)),await this.runCancelable(e,X.ComputedScopes,n,async s=>{let a=this.serviceRegistry.getServices(s.uri).references.ScopeComputation;s.precomputedScopes=await a.computeLocalScopes(s,n)}),await this.runCancelable(e,X.Linked,n,s=>this.serviceRegistry.getServices(s.uri).references.Linker.link(s,n)),await this.runCancelable(e,X.IndexedReferences,n,s=>this.indexManager.updateReferences(s,n));let i=e.filter(s=>this.shouldValidate(s));await this.runCancelable(i,X.Validated,n,s=>this.validate(s,n));for(let s of e){let a=this.buildState.get(s.uri.toString());a&&(a.completed=!0)}}prepareBuild(e,t){for(let n of e){let i=n.uri.toString(),s=this.buildState.get(i);(!s||s.completed)&&this.buildState.set(i,{completed:!1,options:t,result:s?.result})}}async runCancelable(e,t,n,i){let s=e.filter(o=>o.stateo.state===t);await this.notifyBuildPhase(a,t,n),this.currentState=t}onBuildPhase(e,t){return this.buildPhaseListeners.add(e,t),Vt.create(()=>{this.buildPhaseListeners.delete(e,t)})}onDocumentPhase(e,t){return this.documentPhaseListeners.add(e,t),Vt.create(()=>{this.documentPhaseListeners.delete(e,t)})}waitUntil(e,t,n){let i;if(t&&"path"in t?i=t:n=t,n??(n=C.CancellationToken.None),i){let s=this.langiumDocuments.getDocument(i);if(s&&s.state>e)return Promise.resolve(i)}return this.currentState>=e?Promise.resolve(void 0):n.isCancellationRequested?Promise.reject(pt):new Promise((s,a)=>{let o=this.onBuildPhase(e,()=>{if(o.dispose(),l.dispose(),i){let u=this.langiumDocuments.getDocument(i);s(u?.uri)}else s(void 0)}),l=n.onCancellationRequested(()=>{o.dispose(),l.dispose(),a(pt)})})}async notifyDocumentPhase(e,t,n){let s=this.documentPhaseListeners.get(t).slice();for(let a of s)try{await a(e,n)}catch(o){if(!mt(o))throw o}}async notifyBuildPhase(e,t,n){if(e.length===0)return;let s=this.buildPhaseListeners.get(t).slice();for(let a of s)await ue(n),await a(e,n)}shouldValidate(e){return!!this.getBuildOptions(e).validation}async validate(e,t){var n,i;let s=this.serviceRegistry.getServices(e.uri).validation.DocumentValidator,a=this.getBuildOptions(e).validation,o=typeof a=="object"?a:void 0,l=await s.validateDocument(e,o,t);e.diagnostics?e.diagnostics.push(...l):e.diagnostics=l;let u=this.buildState.get(e.uri.toString());if(u){(n=u.result)!==null&&n!==void 0||(u.result={});let c=(i=o?.categories)!==null&&i!==void 0?i:Xn.all;u.result.validationChecks?u.result.validationChecks.push(...c):u.result.validationChecks=[...c]}}getBuildOptions(e){var t,n;return(n=(t=this.buildState.get(e.uri.toString()))===null||t===void 0?void 0:t.options)!==null&&n!==void 0?n:{}}};var cs=class{constructor(e){this.symbolIndex=new Map,this.symbolByTypeIndex=new Rr,this.referenceIndex=new Map,this.documents=e.workspace.LangiumDocuments,this.serviceRegistry=e.ServiceRegistry,this.astReflection=e.AstReflection}findAllReferences(e,t){let n=Se(e).uri,i=[];return this.referenceIndex.forEach(s=>{s.forEach(a=>{Ue.equals(a.targetUri,n)&&a.targetPath===t&&i.push(a)})}),V(i)}allElements(e,t){let n=V(this.symbolIndex.keys());return t&&(n=n.filter(i=>!t||t.has(i))),n.map(i=>this.getFileDescriptions(i,e)).flat()}getFileDescriptions(e,t){var n;return t?this.symbolByTypeIndex.get(e,t,()=>{var s;return((s=this.symbolIndex.get(e))!==null&&s!==void 0?s:[]).filter(o=>this.astReflection.isSubtype(o.type,t))}):(n=this.symbolIndex.get(e))!==null&&n!==void 0?n:[]}remove(e){let t=e.toString();this.symbolIndex.delete(t),this.symbolByTypeIndex.clear(t),this.referenceIndex.delete(t)}async updateContent(e,t=C.CancellationToken.None){let i=await this.serviceRegistry.getServices(e.uri).references.ScopeComputation.computeExports(e,t),s=e.uri.toString();this.symbolIndex.set(s,i),this.symbolByTypeIndex.clear(s)}async updateReferences(e,t=C.CancellationToken.None){let i=await this.serviceRegistry.getServices(e.uri).workspace.ReferenceDescriptionProvider.createDescriptions(e,t);this.referenceIndex.set(e.uri.toString(),i)}isAffected(e,t){let n=this.referenceIndex.get(e.uri.toString());return n?n.some(i=>!i.local&&t.has(i.targetUri.toString())):!1}};var fs=class{constructor(e){this.initialBuildOptions={},this._ready=new Fe,this.serviceRegistry=e.ServiceRegistry,this.langiumDocuments=e.workspace.LangiumDocuments,this.documentBuilder=e.workspace.DocumentBuilder,this.fileSystemProvider=e.workspace.FileSystemProvider,this.mutex=e.workspace.WorkspaceLock}get ready(){return this._ready.promise}get workspaceFolders(){return this.folders}initialize(e){var t;this.folders=(t=e.workspaceFolders)!==null&&t!==void 0?t:void 0}initialized(e){return this.mutex.write(t=>{var n;return this.initializeWorkspace((n=this.folders)!==null&&n!==void 0?n:[],t)})}async initializeWorkspace(e,t=C.CancellationToken.None){let n=await this.performStartup(e);await ue(t),await this.documentBuilder.build(n,this.initialBuildOptions,t)}async performStartup(e){let t=this.serviceRegistry.all.flatMap(s=>s.LanguageMetaData.fileExtensions),n=[],i=s=>{n.push(s),this.langiumDocuments.hasDocument(s.uri)||this.langiumDocuments.addDocument(s)};return await this.loadAdditionalDocuments(e,i),await Promise.all(e.map(s=>[s,this.getRootFolder(s)]).map(async s=>this.traverseFolder(...s,t,i))),this._ready.resolve(),n}loadAdditionalDocuments(e,t){return Promise.resolve()}getRootFolder(e){return Ge.parse(e.uri)}async traverseFolder(e,t,n,i){let s=await this.fileSystemProvider.readDirectory(t);await Promise.all(s.map(async a=>{if(this.includeEntry(e,a,n)){if(a.isDirectory)await this.traverseFolder(e,a.uri,n,i);else if(a.isFile){let o=await this.langiumDocuments.getOrCreateDocument(a.uri);i(o)}}}))}includeEntry(e,t,n){let i=Ue.basename(t.uri);if(i.startsWith("."))return!1;if(t.isDirectory)return i!=="node_modules"&&i!=="out";if(t.isFile){let s=Ue.extname(t.uri);return n.includes(s)}return!1}};var ds=class{buildUnexpectedCharactersMessage(e,t,n,i,s){return $n.buildUnexpectedCharactersMessage(e,t,n,i,s)}buildUnableToPopLexerModeMessage(e){return $n.buildUnableToPopLexerModeMessage(e)}},Ba={mode:"full"},Er=class{constructor(e){this.errorMessageProvider=e.parser.LexerErrorMessageProvider,this.tokenBuilder=e.parser.TokenBuilder;let t=this.tokenBuilder.buildTokens(e.Grammar,{caseInsensitive:e.LanguageMetaData.caseInsensitive});this.tokenTypes=this.toTokenTypeDictionary(t);let n=pu(t)?Object.values(t):t,i=e.LanguageMetaData.mode==="production";this.chevrotainLexer=new ie(n,{positionTracking:"full",skipValidations:i,errorMessageProvider:this.errorMessageProvider})}get definition(){return this.tokenTypes}tokenize(e,t=Ba){var n,i,s;let a=this.chevrotainLexer.tokenize(e);return{tokens:a.tokens,errors:a.errors,hidden:(n=a.groups.hidden)!==null&&n!==void 0?n:[],report:(s=(i=this.tokenBuilder).flushLexingReport)===null||s===void 0?void 0:s.call(i,e)}}toTokenTypeDictionary(e){if(pu(e))return e;let t=mu(e)?Object.values(e.modes).flat():e,n={};return t.forEach(i=>n[i.name]=i),n}};function Wa(r){return Array.isArray(r)&&(r.length===0||"name"in r[0])}function mu(r){return r&&"modes"in r&&"defaultMode"in r}function pu(r){return!Wa(r)&&!mu(r)}function Tu(r,e,t){let n,i;typeof r=="string"?(i=e,n=t):(i=r.range.start,n=e),i||(i=B.create(0,0));let s=ih(r),a=xu(n),o=dg({lines:s,position:i,options:a});return yg({index:0,tokens:o,position:i})}function Ru(r,e){let t=xu(e),n=ih(r);if(n.length===0)return!1;let i=n[0],s=n[n.length-1],a=t.start,o=t.end;return!!a?.exec(i)&&!!o?.exec(s)}function ih(r){let e="";return typeof r=="string"?e=r:e=r.text,e.split(Wo)}var rh=/\s*(@([\p{L}][\p{L}\p{N}]*)?)/uy,fg=/\{(@[\p{L}][\p{L}\p{N}]*)(\s*)([^\r\n}]+)?\}/gu;function dg(r){var e,t,n;let i=[],s=r.position.line,a=r.position.character;for(let o=0;o=c.length){if(i.length>0){let h=B.create(s,a);i.push({type:"break",content:"",range:G.create(h,h)})}}else{rh.lastIndex=f;let h=rh.exec(c);if(h){let m=h[0],g=h[1],A=B.create(s,a+f),R=B.create(s,a+f+m.length);i.push({type:"tag",content:g,range:G.create(A,R)}),f+=m.length,f=yu(c,f)}if(f0&&i[i.length-1].type==="break"?i.slice(0,-1):i}function hg(r,e,t,n){let i=[];if(r.length===0){let s=B.create(t,n),a=B.create(t,n+e.length);i.push({type:"text",content:e,range:G.create(s,a)})}else{let s=0;for(let o of r){let l=o.index,u=e.substring(s,l);u.length>0&&i.push({type:"text",content:e.substring(s,l),range:G.create(B.create(t,s+n),B.create(t,l+n))});let c=u.length+1,f=o[1];if(i.push({type:"inline-tag",content:f,range:G.create(B.create(t,s+c+n),B.create(t,s+c+f.length+n))}),c+=f.length,o.length===4){c+=o[2].length;let d=o[3];i.push({type:"text",content:d,range:G.create(B.create(t,s+c+n),B.create(t,s+c+d.length+n))})}else i.push({type:"text",content:"",range:G.create(B.create(t,s+c+n),B.create(t,s+c+n))});s=l+o[0].length}let a=e.substring(s);a.length>0&&i.push({type:"text",content:a,range:G.create(B.create(t,s+n),B.create(t,s+n+a.length))})}return i}var pg=/\S/,mg=/\s*$/;function yu(r,e){let t=r.substring(e).match(pg);return t?e+t.index:r.length}function gg(r){let e=r.match(mg);if(e&&typeof e.index=="number")return e.index}function yg(r){var e,t,n,i;let s=B.create(r.position.line,r.position.character);if(r.tokens.length===0)return new Ka([],G.create(s,s));let a=[];for(;r.indext.name===e)}getTags(e){return this.getAllTags().filter(t=>t.name===e)}getAllTags(){return this.elements.filter(e=>"name"in e)}toString(){let e="";for(let t of this.elements)if(e.length===0)e=t.toString();else{let n=t.toString();e+=nh(e)+n}return e.trim()}toMarkdown(e){let t="";for(let n of this.elements)if(t.length===0)t=n.toMarkdown(e);else{let i=n.toMarkdown(e);t+=nh(t)+i}return t.trim()}},hs=class{constructor(e,t,n,i){this.name=e,this.content=t,this.inline=n,this.range=i}toString(){let e=`@${this.name}`,t=this.content.toString();return this.content.inlines.length===1?e=`${e} ${t}`:this.content.inlines.length>1&&(e=`${e} +${t}`),this.inline?`{${e}}`:e}toMarkdown(e){var t,n;return(n=(t=e?.renderTag)===null||t===void 0?void 0:t.call(e,this))!==null&&n!==void 0?n:this.toMarkdownDefault(e)}toMarkdownDefault(e){let t=this.content.toMarkdown(e);if(this.inline){let s=Eg(this.name,t,e??{});if(typeof s=="string")return s}let n="";e?.tag==="italic"||e?.tag===void 0?n="*":e?.tag==="bold"?n="**":e?.tag==="bold-italic"&&(n="***");let i=`${n}@${this.name}${n}`;return this.content.inlines.length===1?i=`${i} \u2014 ${t}`:this.content.inlines.length>1&&(i=`${i} +${t}`),this.inline?`{${i}}`:i}};function Eg(r,e,t){var n,i;if(r==="linkplain"||r==="linkcode"||r==="link"){let s=e.indexOf(" "),a=e;if(s>0){let l=yu(e,s);a=e.substring(l),e=e.substring(0,s)}return(r==="linkcode"||r==="link"&&t.link==="code")&&(a=`\`${a}\``),(i=(n=t.renderLink)===null||n===void 0?void 0:n.call(t,e,a))!==null&&i!==void 0?i:Ag(e,a)}}function Ag(r,e){try{return Ge.parse(r,!0),`[${e}](${r})`}catch{return r}}var ps=class{constructor(e,t){this.inlines=e,this.range=t}toString(){let e="";for(let t=0;tn.range.start.line&&(e+=` +`)}return e}toMarkdown(e){let t="";for(let n=0;ni.range.start.line&&(t+=` +`)}return t}},Va=class{constructor(e,t){this.text=e,this.range=t}toString(){return this.text}toMarkdown(){return this.text}};function nh(r){return r.endsWith(` +`)?` +`:` + +`}var ms=class{constructor(e){this.indexManager=e.shared.workspace.IndexManager,this.commentProvider=e.documentation.CommentProvider}getDocumentation(e){let t=this.commentProvider.getComment(e);if(t&&Ru(t))return Tu(t).toMarkdown({renderLink:(i,s)=>this.documentationLinkRenderer(e,i,s),renderTag:i=>this.documentationTagRenderer(e,i)})}documentationLinkRenderer(e,t,n){var i;let s=(i=this.findNameInPrecomputedScopes(e,t))!==null&&i!==void 0?i:this.findNameInGlobalScope(e,t);if(s&&s.nameSegment){let a=s.nameSegment.range.start.line+1,o=s.nameSegment.range.start.character+1,l=s.documentUri.with({fragment:`L${a},${o}`});return`[${n}](${l.toString()})`}else return}documentationTagRenderer(e,t){}findNameInPrecomputedScopes(e,t){let i=Se(e).precomputedScopes;if(!i)return;let s=e;do{let o=i.get(s).find(l=>l.name===t);if(o)return o;s=s.$container}while(s)}findNameInGlobalScope(e,t){return this.indexManager.allElements().find(i=>i.name===t)}};var gs=class{constructor(e){this.grammarConfig=()=>e.parser.GrammarConfig}getComment(e){var t;return hu(e)?e.$comment:(t=yo(e.$cstNode,this.grammarConfig().multilineCommentRules))===null||t===void 0?void 0:t.text}};var ys=class{constructor(e){this.syncParser=e.parser.LangiumParser}parse(e,t){return Promise.resolve(this.syncParser.parse(e))}},Eu=class{constructor(e){this.threadCount=8,this.terminationDelay=200,this.workerPool=[],this.queue=[],this.hydrator=e.serializer.Hydrator}initializeWorkers(){for(;this.workerPool.length{if(this.queue.length>0){let t=this.queue.shift();t&&(e.lock(),t.resolve(e))}}),this.workerPool.push(e)}}async parse(e,t){let n=await this.acquireParserWorker(t),i=new Fe,s,a=t.onCancellationRequested(()=>{s=setTimeout(()=>{this.terminateWorker(n)},this.terminationDelay)});return n.parse(e).then(o=>{let l=this.hydrator.hydrate(o);i.resolve(l)}).catch(o=>{i.reject(o)}).finally(()=>{a.dispose(),clearTimeout(s)}),i.promise}terminateWorker(e){e.terminate();let t=this.workerPool.indexOf(e);t>=0&&this.workerPool.splice(t,1)}async acquireParserWorker(e){this.initializeWorkers();for(let n of this.workerPool)if(n.ready)return n.lock(),n;let t=new Fe;return e.onCancellationRequested(()=>{let n=this.queue.indexOf(t);n>=0&&this.queue.splice(n,1),t.reject(pt)}),this.queue.push(t),t.promise}},Au=class{get ready(){return this._ready}get onReady(){return this.onReadyEmitter.event}constructor(e,t,n,i){this.onReadyEmitter=new re.Emitter,this.deferred=new Fe,this._ready=!0,this._parsing=!1,this.sendMessage=e,this._terminate=i,t(s=>{let a=s;this.deferred.resolve(a),this.unlock()}),n(s=>{this.deferred.reject(s),this.unlock()})}terminate(){this.deferred.reject(pt),this._terminate()}lock(){this._ready=!1}unlock(){this._parsing=!1,this._ready=!0,this.onReadyEmitter.fire()}parse(e){if(this._parsing)throw new Error("Parser worker is busy");return this._parsing=!0,this.deferred=new Fe,this.sendMessage(e),this.deferred.promise}};var Ts=class{constructor(){this.previousTokenSource=new C.CancellationTokenSource,this.writeQueue=[],this.readQueue=[],this.done=!0}write(e){this.cancelWrite();let t=Da();return this.previousTokenSource=t,this.enqueue(this.writeQueue,e,t.token)}read(e){return this.enqueue(this.readQueue,e)}enqueue(e,t,n=C.CancellationToken.None){let i=new Fe,s={action:t,deferred:i,cancellationToken:n};return e.push(s),this.performNextOperation(),i.promise}async performNextOperation(){if(!this.done)return;let e=[];if(this.writeQueue.length>0)e.push(this.writeQueue.shift());else if(this.readQueue.length>0)e.push(...this.readQueue.splice(0,this.readQueue.length));else return;this.done=!1,await Promise.all(e.map(async({action:t,deferred:n,cancellationToken:i})=>{try{let s=await Promise.resolve().then(()=>t(i));n.resolve(s)}catch(s){mt(s)?n.resolve(void 0):n.reject(s)}})),this.done=!0,this.performNextOperation()}cancelWrite(){this.previousTokenSource.cancel()}};var Rs=class{constructor(e){this.grammarElementIdMap=new Tr,this.tokenTypeIdMap=new Tr,this.grammar=e.Grammar,this.lexer=e.parser.Lexer,this.linker=e.references.Linker}dehydrate(e){return{lexerErrors:e.lexerErrors,lexerReport:e.lexerReport?this.dehydrateLexerReport(e.lexerReport):void 0,parserErrors:e.parserErrors.map(t=>Object.assign(Object.assign({},t),{message:t.message})),value:this.dehydrateAstNode(e.value,this.createDehyrationContext(e.value))}}dehydrateLexerReport(e){return e}createDehyrationContext(e){let t=new Map,n=new Map;for(let i of Ye(e))t.set(i,{});if(e.$cstNode)for(let i of Qt(e.$cstNode))n.set(i,{});return{astNodes:t,cstNodes:n}}dehydrateAstNode(e,t){let n=t.astNodes.get(e);n.$type=e.$type,n.$containerIndex=e.$containerIndex,n.$containerProperty=e.$containerProperty,e.$cstNode!==void 0&&(n.$cstNode=this.dehydrateCstNode(e.$cstNode,t));for(let[i,s]of Object.entries(e))if(!i.startsWith("$"))if(Array.isArray(s)){let a=[];n[i]=a;for(let o of s)oe(o)?a.push(this.dehydrateAstNode(o,t)):xe(o)?a.push(this.dehydrateReference(o,t)):a.push(o)}else oe(s)?n[i]=this.dehydrateAstNode(s,t):xe(s)?n[i]=this.dehydrateReference(s,t):s!==void 0&&(n[i]=s);return n}dehydrateReference(e,t){let n={};return n.$refText=e.$refText,e.$refNode&&(n.$refNode=t.cstNodes.get(e.$refNode)),n}dehydrateCstNode(e,t){let n=t.cstNodes.get(e);return Qn(e)?n.fullText=e.fullText:n.grammarSource=this.getGrammarElementId(e.grammarSource),n.hidden=e.hidden,n.astNode=t.astNodes.get(e.astNode),et(e)?n.content=e.content.map(i=>this.dehydrateCstNode(i,t)):Ft(e)&&(n.tokenType=e.tokenType.name,n.offset=e.offset,n.length=e.length,n.startLine=e.range.start.line,n.startColumn=e.range.start.character,n.endLine=e.range.end.line,n.endColumn=e.range.end.character),n}hydrate(e){let t=e.value,n=this.createHydrationContext(t);return"$cstNode"in t&&this.hydrateCstNode(t.$cstNode,n),{lexerErrors:e.lexerErrors,lexerReport:e.lexerReport,parserErrors:e.parserErrors,value:this.hydrateAstNode(t,n)}}createHydrationContext(e){let t=new Map,n=new Map;for(let s of Ye(e))t.set(s,{});let i;if(e.$cstNode)for(let s of Qt(e.$cstNode)){let a;"fullText"in s?(a=new Un(s.fullText),i=a):"content"in s?a=new mr:"tokenType"in s&&(a=this.hydrateCstLeafNode(s)),a&&(n.set(s,a),a.root=i)}return{astNodes:t,cstNodes:n}}hydrateAstNode(e,t){let n=t.astNodes.get(e);n.$type=e.$type,n.$containerIndex=e.$containerIndex,n.$containerProperty=e.$containerProperty,e.$cstNode&&(n.$cstNode=t.cstNodes.get(e.$cstNode));for(let[i,s]of Object.entries(e))if(!i.startsWith("$"))if(Array.isArray(s)){let a=[];n[i]=a;for(let o of s)oe(o)?a.push(this.setParent(this.hydrateAstNode(o,t),n)):xe(o)?a.push(this.hydrateReference(o,n,i,t)):a.push(o)}else oe(s)?n[i]=this.setParent(this.hydrateAstNode(s,t),n):xe(s)?n[i]=this.hydrateReference(s,n,i,t):s!==void 0&&(n[i]=s);return n}setParent(e,t){return e.$container=t,e}hydrateReference(e,t,n,i){return this.linker.buildReference(t,n,i.cstNodes.get(e.$refNode),e.$refText)}hydrateCstNode(e,t,n=0){let i=t.cstNodes.get(e);if(typeof e.grammarSource=="number"&&(i.grammarSource=this.getGrammarElement(e.grammarSource)),i.astNode=t.astNodes.get(e.astNode),et(i))for(let s of e.content){let a=this.hydrateCstNode(s,t,n++);i.content.push(a)}return i}hydrateCstLeafNode(e){let t=this.getTokenType(e.tokenType),n=e.offset,i=e.length,s=e.startLine,a=e.startColumn,o=e.endLine,l=e.endColumn,u=e.hidden;return new pr(n,i,{start:{line:s,character:a},end:{line:o,character:l}},t,u)}getTokenType(e){return this.lexer.definition[e]}getGrammarElementId(e){if(e)return this.grammarElementIdMap.size===0&&this.createGrammarElementIdMap(),this.grammarElementIdMap.get(e)}getGrammarElement(e){return this.grammarElementIdMap.size===0&&this.createGrammarElementIdMap(),this.grammarElementIdMap.getKey(e)}createGrammarElementIdMap(){let e=0;for(let t of Ye(this.grammar))ai(t)&&this.grammarElementIdMap.set(t,e++)}};function vu(r){return{documentation:{CommentProvider:e=>new gs(e),DocumentationProvider:e=>new ms(e)},parser:{AsyncParser:e=>new ys(e),GrammarConfig:e=>nl(e),LangiumParser:e=>tu(e),CompletionParser:e=>eu(e),ValueConverter:()=>new yr,TokenBuilder:()=>new Pt,Lexer:e=>new Er(e),ParserErrorMessageProvider:()=>new Bn,LexerErrorMessageProvider:()=>new ds},workspace:{AstNodeLocator:()=>new os,AstNodeDescriptionProvider:e=>new ss(e),ReferenceDescriptionProvider:e=>new as(e)},references:{Linker:e=>new qi(e),NameProvider:()=>new Xi,ScopeProvider:e=>new es(e),ScopeComputation:e=>new Ji(e),References:e=>new Yi(e)},serializer:{Hydrator:e=>new Rs(e),JsonSerializer:e=>new ts(e)},validation:{DocumentValidator:e=>new is(e),ValidationRegistry:e=>new ns(e)},shared:()=>r.shared}}function ku(r){return{ServiceRegistry:e=>new rs(e),workspace:{LangiumDocuments:e=>new zi(e),LangiumDocumentFactory:e=>new Hi(e),DocumentBuilder:e=>new us(e),IndexManager:e=>new cs(e),WorkspaceManager:e=>new fs(e),FileSystemProvider:e=>r.fileSystemProvider(e),WorkspaceLock:()=>new Ts,ConfigurationProvider:e=>new ls(e)}}}var $u;(function(r){r.merge=(e,t)=>ja(ja({},e),t)})($u||($u={}));function Ha(r,e,t,n,i,s,a,o,l){let u=[r,e,t,n,i,s,a,o,l].reduce(ja,{});return dh(u)}var ch=Symbol("isProxy");function fh(r){if(r&&r[ch])for(let e of Object.values(r))fh(e);return r}function dh(r,e){let t=new Proxy({},{deleteProperty:()=>!1,set:()=>{throw new Error("Cannot set property on injected service container")},get:(n,i)=>i===ch?!0:uh(n,i,r,e||t),getOwnPropertyDescriptor:(n,i)=>(uh(n,i,r,e||t),Object.getOwnPropertyDescriptor(n,i)),has:(n,i)=>i in r,ownKeys:()=>[...Object.getOwnPropertyNames(r)]});return t}var lh=Symbol();function uh(r,e,t,n){if(e in r){if(r[e]instanceof Error)throw new Error("Construction failure. Please make sure that your dependencies are constructable.",{cause:r[e]});if(r[e]===lh)throw new Error('Cycle detected. Please make "'+String(e)+'" lazy. Visit https://langium.org/docs/reference/configuration-services/#resolving-cyclic-dependencies');return r[e]}else if(e in t){let i=t[e];r[e]=lh;try{r[e]=typeof i=="function"?i(n):dh(i,n)}catch(s){throw r[e]=s instanceof Error?s:void 0,s}return r[e]}else return}function ja(r,e){if(e){for(let[t,n]of Object.entries(e))if(n!==void 0){let i=r[t];i!==null&&n!==null&&typeof i=="object"&&typeof n=="object"?r[t]=ja(i,n):r[t]=n}}return r}var Iu={indentTokenName:"INDENT",dedentTokenName:"DEDENT",whitespaceTokenName:"WS",ignoreIndentationDelimiters:[]},Ar;(function(r){r.REGULAR="indentation-sensitive",r.IGNORE_INDENTATION="ignore-indentation"})(Ar||(Ar={}));var za=class extends Pt{constructor(e=Iu){super(),this.indentationStack=[0],this.whitespaceRegExp=/[ \t]+/y,this.options=Object.assign(Object.assign({},Iu),e),this.indentTokenType=Ut({name:this.options.indentTokenName,pattern:this.indentMatcher.bind(this),line_breaks:!1}),this.dedentTokenType=Ut({name:this.options.dedentTokenName,pattern:this.dedentMatcher.bind(this),line_breaks:!1})}buildTokens(e,t){let n=super.buildTokens(e,t);if(!Wa(n))throw new Error("Invalid tokens built by default builder");let{indentTokenName:i,dedentTokenName:s,whitespaceTokenName:a,ignoreIndentationDelimiters:o}=this.options,l,u,c,f=[];for(let d of n){for(let[h,m]of o)d.name===h?d.PUSH_MODE=Ar.IGNORE_INDENTATION:d.name===m&&(d.POP_MODE=!0);d.name===s?l=d:d.name===i?u=d:d.name===a?c=d:f.push(d)}if(!l||!u||!c)throw new Error("Some indentation/whitespace tokens not found!");return o.length>0?{modes:{[Ar.REGULAR]:[l,u,...f,c],[Ar.IGNORE_INDENTATION]:[...f,c]},defaultMode:Ar.REGULAR}:[l,u,c,...f]}flushLexingReport(e){let t=super.flushLexingReport(e);return Object.assign(Object.assign({},t),{remainingDedents:this.flushRemainingDedents(e)})}isStartOfLine(e,t){return t===0||`\r +`.includes(e[t-1])}matchWhitespace(e,t,n,i){var s;this.whitespaceRegExp.lastIndex=t;let a=this.whitespaceRegExp.exec(e);return{currIndentLevel:(s=a?.[0].length)!==null&&s!==void 0?s:0,prevIndentLevel:this.indentationStack.at(-1),match:a}}createIndentationTokenInstance(e,t,n,i){let s=this.getLineNumber(t,i);return wt(e,n,i,i+n.length,s,s,1,n.length)}getLineNumber(e,t){return e.substring(0,t).split(/\r\n|\r|\n/).length}indentMatcher(e,t,n,i){if(!this.isStartOfLine(e,t))return null;let{currIndentLevel:s,prevIndentLevel:a,match:o}=this.matchWhitespace(e,t,n,i);return s<=a?null:(this.indentationStack.push(s),o)}dedentMatcher(e,t,n,i){var s,a,o,l;if(!this.isStartOfLine(e,t))return null;let{currIndentLevel:u,prevIndentLevel:c,match:f}=this.matchWhitespace(e,t,n,i);if(u>=c)return null;let d=this.indentationStack.lastIndexOf(u);if(d===-1)return this.diagnostics.push({severity:"error",message:`Invalid dedent level ${u} at offset: ${t}. Current indentation stack: ${this.indentationStack}`,offset:t,length:(a=(s=f?.[0])===null||s===void 0?void 0:s.length)!==null&&a!==void 0?a:0,line:this.getLineNumber(e,t),column:1}),null;let h=this.indentationStack.length-d-1,m=(l=(o=e.substring(0,t).match(/[\r\n]+$/))===null||o===void 0?void 0:o[0].length)!==null&&l!==void 0?l:1;for(let g=0;g1;)t.push(this.createIndentationTokenInstance(this.dedentTokenType,e,"",e.length)),this.indentationStack.pop();return this.indentationStack=[0],t}},Nu=class extends Er{constructor(e){if(super(e),e.parser.TokenBuilder instanceof za)this.indentationTokenBuilder=e.parser.TokenBuilder;else throw new Error("IndentationAwareLexer requires an accompanying IndentationAwareTokenBuilder")}tokenize(e,t=Ba){let n=super.tokenize(e),i=n.report;t?.mode==="full"&&n.tokens.push(...i.remainingDedents),i.remainingDedents=[];let{indentTokenType:s,dedentTokenType:a}=this.indentationTokenBuilder,o=s.tokenTypeIdx,l=a.tokenTypeIdx,u=[],c=n.tokens.length-1;for(let f=0;f=0&&u.push(n.tokens[c]),n.tokens=u,n}};var W={};zt(W,{AstUtils:()=>Ds,BiMap:()=>Tr,Cancellation:()=>C,ContextCache:()=>Rr,CstUtils:()=>Cs,DONE_RESULT:()=>Ne,Deferred:()=>Fe,Disposable:()=>Vt,DisposableCache:()=>zn,DocumentCache:()=>Ga,EMPTY_STREAM:()=>Zn,ErrorWithLocation:()=>er,GrammarUtils:()=>Ws,MultiMap:()=>it,OperationCancelled:()=>pt,Reduction:()=>$r,RegExpUtils:()=>Us,SimpleCache:()=>Zi,StreamImpl:()=>Ve,TreeStreamImpl:()=>ot,URI:()=>Ge,UriUtils:()=>Ue,WorkspaceCache:()=>qn,assertUnreachable:()=>ut,delayNextTick:()=>cu,interruptAndCheck:()=>ue,isOperationCancelled:()=>mt,loadGrammarFromJson:()=>gt,setInterruptionPeriod:()=>zd,startCancelableOperation:()=>Da,stream:()=>V});U(W,re);var qa=class{readFile(){throw new Error("No file system is available.")}async readDirectory(){return[]}},Cu={fileSystemProvider:()=>new qa};var vg={Grammar:()=>{},LanguageMetaData:()=>({caseInsensitive:!1,fileExtensions:[".langium"],languageId:"langium"})},kg={AstReflection:()=>new dn};function $g(){let r=Ha(ku(Cu),kg),e=Ha(vu({shared:r}),vg);return r.ServiceRegistry.register(e),e}function gt(r){var e;let t=$g(),n=t.serializer.JsonSerializer.deserialize(r);return t.shared.workspace.LangiumDocumentFactory.fromModel(n,Ge.parse(`memory://${(e=n.name)!==null&&e!==void 0?e:"grammar"}.langium`)),n}U(ce,W);var Ig=Object.defineProperty,D=(r,e)=>Ig(r,"name",{value:e,configurable:!0}),hh="Statement",ro="Architecture";function Ng(r){return st.isInstance(r,ro)}D(Ng,"isArchitecture");var Xa="Axis",xs="Branch";function Cg(r){return st.isInstance(r,xs)}D(Cg,"isBranch");var Ya="Checkout",Ja="CherryPicking",Su="ClassDefStatement",Es="Commit";function Sg(r){return st.isInstance(r,Es)}D(Sg,"isCommit");var wu="Curve",_u="Edge",Lu="Entry",As="GitGraph";function wg(r){return st.isInstance(r,As)}D(wg,"isGitGraph");var Ou="Group",no="Info";function _g(r){return st.isInstance(r,no)}D(_g,"isInfo");var Qa="Item",Pu="Junction",vs="Merge";function Lg(r){return st.isInstance(r,vs)}D(Lg,"isMerge");var bu="Option",io="Packet";function Og(r){return st.isInstance(r,io)}D(Og,"isPacket");var so="PacketBlock";function Pg(r){return st.isInstance(r,so)}D(Pg,"isPacketBlock");var ao="Pie";function bg(r){return st.isInstance(r,ao)}D(bg,"isPie");var oo="PieSection";function Mg(r){return st.isInstance(r,oo)}D(Mg,"isPieSection");var Mu="Radar",Du="Service",lo="Treemap";function Dg(r){return st.isInstance(r,lo)}D(Dg,"isTreemap");var Fu="TreemapRow",Za="Direction",eo="Leaf",to="Section",Eh=class extends Yt{static{D(this,"MermaidAstReflection")}getAllTypes(){return[ro,Xa,xs,Ya,Ja,Su,Es,wu,Za,_u,Lu,As,Ou,no,Qa,Pu,eo,vs,bu,io,so,ao,oo,Mu,to,Du,hh,lo,Fu]}computeIsSubtype(r,e){switch(r){case xs:case Ya:case Ja:case Es:case vs:return this.isSubtype(hh,e);case Za:return this.isSubtype(As,e);case eo:case to:return this.isSubtype(Qa,e);default:return!1}}getReferenceType(r){let e=`${r.container.$type}:${r.property}`;switch(e){case"Entry:axis":return Xa;default:throw new Error(`${e} is not a valid reference id.`)}}getTypeMetaData(r){switch(r){case ro:return{name:ro,properties:[{name:"accDescr"},{name:"accTitle"},{name:"edges",defaultValue:[]},{name:"groups",defaultValue:[]},{name:"junctions",defaultValue:[]},{name:"services",defaultValue:[]},{name:"title"}]};case Xa:return{name:Xa,properties:[{name:"label"},{name:"name"}]};case xs:return{name:xs,properties:[{name:"name"},{name:"order"}]};case Ya:return{name:Ya,properties:[{name:"branch"}]};case Ja:return{name:Ja,properties:[{name:"id"},{name:"parent"},{name:"tags",defaultValue:[]}]};case Su:return{name:Su,properties:[{name:"className"},{name:"styleText"}]};case Es:return{name:Es,properties:[{name:"id"},{name:"message"},{name:"tags",defaultValue:[]},{name:"type"}]};case wu:return{name:wu,properties:[{name:"entries",defaultValue:[]},{name:"label"},{name:"name"}]};case _u:return{name:_u,properties:[{name:"lhsDir"},{name:"lhsGroup",defaultValue:!1},{name:"lhsId"},{name:"lhsInto",defaultValue:!1},{name:"rhsDir"},{name:"rhsGroup",defaultValue:!1},{name:"rhsId"},{name:"rhsInto",defaultValue:!1},{name:"title"}]};case Lu:return{name:Lu,properties:[{name:"axis"},{name:"value"}]};case As:return{name:As,properties:[{name:"accDescr"},{name:"accTitle"},{name:"statements",defaultValue:[]},{name:"title"}]};case Ou:return{name:Ou,properties:[{name:"icon"},{name:"id"},{name:"in"},{name:"title"}]};case no:return{name:no,properties:[{name:"accDescr"},{name:"accTitle"},{name:"title"}]};case Qa:return{name:Qa,properties:[{name:"classSelector"},{name:"name"}]};case Pu:return{name:Pu,properties:[{name:"id"},{name:"in"}]};case vs:return{name:vs,properties:[{name:"branch"},{name:"id"},{name:"tags",defaultValue:[]},{name:"type"}]};case bu:return{name:bu,properties:[{name:"name"},{name:"value",defaultValue:!1}]};case io:return{name:io,properties:[{name:"accDescr"},{name:"accTitle"},{name:"blocks",defaultValue:[]},{name:"title"}]};case so:return{name:so,properties:[{name:"bits"},{name:"end"},{name:"label"},{name:"start"}]};case ao:return{name:ao,properties:[{name:"accDescr"},{name:"accTitle"},{name:"sections",defaultValue:[]},{name:"showData",defaultValue:!1},{name:"title"}]};case oo:return{name:oo,properties:[{name:"label"},{name:"value"}]};case Mu:return{name:Mu,properties:[{name:"accDescr"},{name:"accTitle"},{name:"axes",defaultValue:[]},{name:"curves",defaultValue:[]},{name:"options",defaultValue:[]},{name:"title"}]};case Du:return{name:Du,properties:[{name:"icon"},{name:"iconText"},{name:"id"},{name:"in"},{name:"title"}]};case lo:return{name:lo,properties:[{name:"accDescr"},{name:"accTitle"},{name:"title"},{name:"TreemapRows",defaultValue:[]}]};case Fu:return{name:Fu,properties:[{name:"indent"},{name:"item"}]};case Za:return{name:Za,properties:[{name:"accDescr"},{name:"accTitle"},{name:"dir"},{name:"statements",defaultValue:[]},{name:"title"}]};case eo:return{name:eo,properties:[{name:"classSelector"},{name:"name"},{name:"value"}]};case to:return{name:to,properties:[{name:"classSelector"},{name:"name"}]};default:return{name:r,properties:[]}}}},st=new Eh,ph,Fg=D(()=>ph??(ph=gt(`{"$type":"Grammar","isDeclared":true,"name":"Info","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Info","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"*"},{"$type":"Keyword","value":"info"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"*"},{"$type":"Group","elements":[{"$type":"Keyword","value":"showInfo"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"*"}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[],"cardinality":"?"}]},"definesHiddenTokens":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","fragment":true,"name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}],"cardinality":"+"},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"}},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"}}]},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@7"}},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@8"}}]},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/"},"fragment":false}],"definesHiddenTokens":false,"hiddenTokens":[],"interfaces":[],"types":[],"usedGrammars":[]}`)),"InfoGrammar"),mh,Gg=D(()=>mh??(mh=gt(`{"$type":"Grammar","isDeclared":true,"name":"Packet","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Packet","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"packet"},{"$type":"Keyword","value":"packet-beta"}]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]},{"$type":"Assignment","feature":"blocks","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}],"cardinality":"*"}]},"definesHiddenTokens":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"PacketBlock","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Assignment","feature":"start","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"-"},{"$type":"Assignment","feature":"end","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}}],"cardinality":"?"}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"+"},{"$type":"Assignment","feature":"bits","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}}]}]},{"$type":"Keyword","value":":"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","fragment":true,"name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}],"cardinality":"+"},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"}},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"}}]},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@8"}},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@9"}}]},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/"},"fragment":false}],"definesHiddenTokens":false,"hiddenTokens":[],"interfaces":[],"types":[],"usedGrammars":[]}`)),"PacketGrammar"),gh,Ug=D(()=>gh??(gh=gt(`{"$type":"Grammar","isDeclared":true,"name":"Pie","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Pie","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[],"cardinality":"*"},{"$type":"Keyword","value":"pie"},{"$type":"Assignment","feature":"showData","operator":"?=","terminal":{"$type":"Keyword","value":"showData"},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]},{"$type":"Assignment","feature":"sections","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}],"cardinality":"*"}]},"definesHiddenTokens":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"PieSection","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}},{"$type":"Keyword","value":":"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","fragment":true,"name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}],"cardinality":"+"},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"}},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"}}]},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@8"}},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@9"}}]},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/"},"fragment":false}],"definesHiddenTokens":false,"hiddenTokens":[],"interfaces":[],"types":[],"usedGrammars":[]}`)),"PieGrammar"),yh,Bg=D(()=>yh??(yh=gt(`{"$type":"Grammar","isDeclared":true,"name":"Architecture","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Architecture","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[],"cardinality":"*"},{"$type":"Keyword","value":"architecture-beta"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}],"cardinality":"*"}]},"definesHiddenTokens":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","fragment":true,"name":"Statement","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"groups","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"services","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"junctions","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}},{"$type":"Assignment","feature":"edges","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}}]},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","fragment":true,"name":"LeftPort","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":":"},{"$type":"Assignment","feature":"lhsDir","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}}]},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","fragment":true,"name":"RightPort","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"rhsDir","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Keyword","value":":"}]},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","fragment":true,"name":"Arrow","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]},{"$type":"Assignment","feature":"lhsInto","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"--"},{"$type":"Group","elements":[{"$type":"Keyword","value":"-"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]}},{"$type":"Keyword","value":"-"}]}]},{"$type":"Assignment","feature":"rhsInto","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}]},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"Group","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"group"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Assignment","feature":"icon","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@28"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},"cardinality":"?"},{"$type":"Group","elements":[{"$type":"Keyword","value":"in"},{"$type":"Assignment","feature":"in","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"Service","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"service"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"iconText","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]}},{"$type":"Assignment","feature":"icon","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@28"},"arguments":[]}}],"cardinality":"?"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},"cardinality":"?"},{"$type":"Group","elements":[{"$type":"Keyword","value":"in"},{"$type":"Assignment","feature":"in","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"Junction","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"junction"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"in"},{"$type":"Assignment","feature":"in","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"Edge","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"lhsId","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Assignment","feature":"lhsGroup","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]},{"$type":"Assignment","feature":"rhsId","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Assignment","feature":"rhsGroup","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"TerminalRule","name":"ARROW_DIRECTION","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"L"}},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"R"}}]},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"T"}}]},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"B"}}]},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARROW_GROUP","definition":{"$type":"RegexToken","regex":"/\\\\{group\\\\}/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARROW_INTO","definition":{"$type":"RegexToken","regex":"/<|>/"},"fragment":false,"hidden":false},{"$type":"ParserRule","fragment":true,"name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}],"cardinality":"+"},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"}},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"}}]},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@18"}},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@19"}}]},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/"},"fragment":false},{"$type":"TerminalRule","name":"ARCH_ICON","definition":{"$type":"RegexToken","regex":"/\\\\([\\\\w-:]+\\\\)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARCH_TITLE","definition":{"$type":"RegexToken","regex":"/\\\\[[\\\\w ]+\\\\]/"},"fragment":false,"hidden":false}],"definesHiddenTokens":false,"hiddenTokens":[],"interfaces":[],"types":[],"usedGrammars":[]}`)),"ArchitectureGrammar"),Th,Wg=D(()=>Th??(Th=gt(`{"$type":"Grammar","isDeclared":true,"name":"GitGraph","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"GitGraph","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"gitGraph"},{"$type":"Group","elements":[{"$type":"Keyword","value":"gitGraph"},{"$type":"Keyword","value":":"}]},{"$type":"Keyword","value":"gitGraph:"},{"$type":"Group","elements":[{"$type":"Keyword","value":"gitGraph"},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]},{"$type":"Keyword","value":":"}]}]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]},{"$type":"Assignment","feature":"statements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}}],"cardinality":"*"}]},"definesHiddenTokens":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"Statement","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"Direction","definition":{"$type":"Assignment","feature":"dir","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"LR"},{"$type":"Keyword","value":"TB"},{"$type":"Keyword","value":"BT"}]}},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"Commit","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"commit"},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"id:"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"msg:","cardinality":"?"},{"$type":"Assignment","feature":"message","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"tag:"},{"$type":"Assignment","feature":"tags","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"type:"},{"$type":"Assignment","feature":"type","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"NORMAL"},{"$type":"Keyword","value":"REVERSE"},{"$type":"Keyword","value":"HIGHLIGHT"}]}}]}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"Branch","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"branch"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"order:"},{"$type":"Assignment","feature":"order","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"Merge","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"merge"},{"$type":"Assignment","feature":"branch","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}]}},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"id:"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"tag:"},{"$type":"Assignment","feature":"tags","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"type:"},{"$type":"Assignment","feature":"type","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"NORMAL"},{"$type":"Keyword","value":"REVERSE"},{"$type":"Keyword","value":"HIGHLIGHT"}]}}]}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"Checkout","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"checkout"},{"$type":"Keyword","value":"switch"}]},{"$type":"Assignment","feature":"branch","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"CherryPicking","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"cherry-pick"},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"id:"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"tag:"},{"$type":"Assignment","feature":"tags","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"parent:"},{"$type":"Assignment","feature":"parent","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","fragment":true,"name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}],"cardinality":"+"},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"}},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"}}]},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@14"}},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@15"}}]},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/"},"fragment":false},{"$type":"TerminalRule","name":"REFERENCE","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\\\w([-\\\\./\\\\w]*[-\\\\w])?/"},"fragment":false,"hidden":false}],"definesHiddenTokens":false,"hiddenTokens":[],"interfaces":[],"types":[],"usedGrammars":[]}`)),"GitGraphGrammar"),Rh,Kg=D(()=>Rh??(Rh=gt(`{"$type":"Grammar","isDeclared":true,"name":"Radar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Radar","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"radar-beta"},{"$type":"Keyword","value":"radar-beta:"},{"$type":"Group","elements":[{"$type":"Keyword","value":"radar-beta"},{"$type":"Keyword","value":":"}]}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Keyword","value":"axis"},{"$type":"Assignment","feature":"axes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"axes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}}],"cardinality":"*"}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"curve"},{"$type":"Assignment","feature":"curves","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"curves","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}}],"cardinality":"*"}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"options","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"options","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}}],"cardinality":"*"}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}],"cardinality":"*"}]},"definesHiddenTokens":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","fragment":true,"name":"Label","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}},{"$type":"Keyword","value":"]"}]},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"Axis","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[],"cardinality":"?"}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"Curve","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[],"cardinality":"?"},{"$type":"Keyword","value":"{"},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]},{"$type":"Keyword","value":"}"}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","fragment":true,"name":"Entries","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"}]},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"}]}]},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"DetailedEntry","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"axis","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@2"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},"deprecatedSyntax":false}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"NumberEntry","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"Option","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"showLegend"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"ticks"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"max"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"min"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"graticule"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}}]}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"TerminalRule","name":"GRATICULE","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"circle"}},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"polygon"}}]},"fragment":false,"hidden":false},{"$type":"ParserRule","fragment":true,"name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}],"cardinality":"+"},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"}},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"}}]},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@15"}},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@16"}}]},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/"},"fragment":false}],"interfaces":[{"$type":"Interface","name":"Entry","attributes":[{"$type":"TypeAttribute","name":"axis","isOptional":true,"type":{"$type":"ReferenceType","referenceType":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@2"}}}},{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"number"},"isOptional":false}],"superTypes":[]}],"definesHiddenTokens":false,"hiddenTokens":[],"types":[],"usedGrammars":[]}`)),"RadarGrammar"),xh,Vg=D(()=>xh??(xh=gt(`{"$type":"Grammar","isDeclared":true,"name":"Treemap","rules":[{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}}],"cardinality":"+"},"definesHiddenTokens":false,"entry":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"}},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"}}]},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/"},"fragment":false,"hidden":false},{"$type":"ParserRule","entry":true,"name":"Treemap","returnType":{"$ref":"#/interfaces@4"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@0"},"arguments":[]},{"$type":"Assignment","feature":"TreemapRows","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}}],"cardinality":"*"}]},"definesHiddenTokens":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"TerminalRule","name":"TREEMAP_KEYWORD","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"treemap-beta"}},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"treemap"}}]},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"CLASS_DEF","definition":{"$type":"RegexToken","regex":"/classDef\\\\s+([a-zA-Z_][a-zA-Z0-9_]+)(?:\\\\s+([^;\\\\r\\\\n]*))?(?:;)?/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STYLE_SEPARATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":":::"}},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"SEPARATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":":"}},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"COMMA","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":","}},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WS","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"ML_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\%\\\\%[^\\\\n]*/"},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"NL","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/"},"fragment":false},{"$type":"ParserRule","name":"TreemapRow","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"indent","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"item","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}]}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"ClassDef","dataType":"string","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"Item","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"Section","returnType":{"$ref":"#/interfaces@1"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},{"$type":"Assignment","feature":"classSelector","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}}],"cardinality":"?"}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"ParserRule","name":"Leaf","returnType":{"$ref":"#/interfaces@2"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[],"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[],"cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},{"$type":"Assignment","feature":"classSelector","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}}],"cardinality":"?"}]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"TerminalRule","name":"INDENTATION","definition":{"$type":"RegexToken","regex":"/[ \\\\t]{1,}/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID2","definition":{"$type":"RegexToken","regex":"/[a-zA-Z_][a-zA-Z0-9_]*/"},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER2","definition":{"$type":"RegexToken","regex":"/[0-9_\\\\.\\\\,]+/"},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"MyNumber","dataType":"number","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},"definesHiddenTokens":false,"entry":false,"fragment":false,"hiddenTokens":[],"parameters":[],"wildcard":false},{"$type":"TerminalRule","name":"STRING2","definition":{"$type":"RegexToken","regex":"/\\"[^\\"]*\\"|'[^']*'/"},"fragment":false,"hidden":false}],"interfaces":[{"$type":"Interface","name":"Item","attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"classSelector","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]},{"$type":"Interface","name":"Section","superTypes":[{"$ref":"#/interfaces@0"}],"attributes":[]},{"$type":"Interface","name":"Leaf","superTypes":[{"$ref":"#/interfaces@0"}],"attributes":[{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"number"},"isOptional":false}]},{"$type":"Interface","name":"ClassDefStatement","attributes":[{"$type":"TypeAttribute","name":"className","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"styleText","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"Treemap","attributes":[{"$type":"TypeAttribute","name":"TreemapRows","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@14"}}},"isOptional":false},{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]}],"definesHiddenTokens":false,"hiddenTokens":[],"imports":[],"types":[],"usedGrammars":[],"$comment":"/**\\n * Treemap grammar for Langium\\n * Converted from mindmap grammar\\n *\\n * The ML_COMMENT and NL hidden terminals handle whitespace, comments, and newlines\\n * before the treemap keyword, allowing for empty lines and comments before the\\n * treemap declaration.\\n */"}`)),"TreemapGrammar"),jg={languageId:"info",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},Hg={languageId:"packet",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},zg={languageId:"pie",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},qg={languageId:"architecture",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},Xg={languageId:"gitGraph",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},Yg={languageId:"radar",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},Jg={languageId:"treemap",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},J$={AstReflection:D(()=>new Eh,"AstReflection")},Q$={Grammar:D(()=>Fg(),"Grammar"),LanguageMetaData:D(()=>jg,"LanguageMetaData"),parser:{}},Z$={Grammar:D(()=>Gg(),"Grammar"),LanguageMetaData:D(()=>Hg,"LanguageMetaData"),parser:{}},eI={Grammar:D(()=>Ug(),"Grammar"),LanguageMetaData:D(()=>zg,"LanguageMetaData"),parser:{}},tI={Grammar:D(()=>Bg(),"Grammar"),LanguageMetaData:D(()=>qg,"LanguageMetaData"),parser:{}},rI={Grammar:D(()=>Wg(),"Grammar"),LanguageMetaData:D(()=>Xg,"LanguageMetaData"),parser:{}},nI={Grammar:D(()=>Kg(),"Grammar"),LanguageMetaData:D(()=>Yg,"LanguageMetaData"),parser:{}},iI={Grammar:D(()=>Vg(),"Grammar"),LanguageMetaData:D(()=>Jg,"LanguageMetaData"),parser:{}},Qg=/accDescr(?:[\t ]*:([^\n\r]*)|\s*{([^}]*)})/,Zg=/accTitle[\t ]*:([^\n\r]*)/,ey=/title([\t ][^\n\r]*|)/,ty={ACC_DESCR:Qg,ACC_TITLE:Zg,TITLE:ey},ry=class extends yr{static{D(this,"AbstractMermaidValueConverter")}runConverter(r,e,t){let n=this.runCommonConverter(r,e,t);return n===void 0&&(n=this.runCustomConverter(r,e,t)),n===void 0?super.runConverter(r,e,t):n}runCommonConverter(r,e,t){let n=ty[r.name];if(n===void 0)return;let i=n.exec(e);if(i!==null){if(i[1]!==void 0)return i[1].trim().replace(/[\t ]{2,}/gm," ");if(i[2]!==void 0)return i[2].replace(/^\s*/gm,"").replace(/\s+$/gm,"").replace(/[\t ]{2,}/gm," ").replace(/[\n\r]{2,}/gm,` +`)}}},aI=class extends ry{static{D(this,"CommonValueConverter")}runCustomConverter(r,e,t){}},ny=class extends Pt{static{D(this,"AbstractMermaidTokenBuilder")}constructor(r){super(),this.keywords=new Set(r)}buildKeywordTokens(r,e,t){let n=super.buildKeywordTokens(r,e,t);return n.forEach(i=>{this.keywords.has(i.name)&&i.PATTERN!==void 0&&(i.PATTERN=new RegExp(i.PATTERN.toString()+"(?:(?=%%)|(?!\\S))"))}),n}},lI=class extends ny{static{D(this,"CommonTokenBuilder")}};export{vu as a,ku as b,Ha as c,Cu as d,ce as e,D as f,J$ as g,Q$ as h,Z$ as i,eI as j,tI as k,rI as l,nI as m,iI as n,ry as o,aI as p,ny as q}; +//# sourceMappingURL=chunk-LBFZT66H.min.js.map diff --git a/docs/website/public/chunk-LBFZT66H.min.js.map b/docs/website/public/chunk-LBFZT66H.min.js.map new file mode 100644 index 000000000..dac7e3cf0 --- /dev/null +++ b/docs/website/public/chunk-LBFZT66H.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/vscode-jsonrpc/lib/common/ral.js", "../../node_modules/vscode-jsonrpc/lib/common/is.js", "../../node_modules/vscode-jsonrpc/lib/common/events.js", "../../node_modules/vscode-jsonrpc/lib/common/cancellation.js", "../../node_modules/langium/src/index.ts", "../../node_modules/langium/src/utils/cst-utils.ts", "../../node_modules/langium/src/syntax-tree.ts", "../../node_modules/langium/src/utils/stream.ts", "../../node_modules/langium/src/utils/grammar-utils.ts", "../../node_modules/langium/src/utils/errors.ts", "../../node_modules/langium/src/languages/generated/ast.ts", "../../node_modules/langium/src/utils/ast-utils.ts", "../../node_modules/langium/src/utils/regexp-utils.ts", "../../node_modules/@chevrotain/regexp-to-ast/src/utils.ts", "../../node_modules/@chevrotain/regexp-to-ast/src/character-classes.ts", "../../node_modules/@chevrotain/regexp-to-ast/src/regexp-parser.ts", "../../node_modules/@chevrotain/regexp-to-ast/src/base-regexp-visitor.ts", "../../node_modules/langium/src/languages/grammar-config.ts", "../../node_modules/@chevrotain/utils/src/print.ts", "../../node_modules/@chevrotain/utils/src/timer.ts", "../../node_modules/@chevrotain/utils/src/to-fast-properties.ts", "../../node_modules/@chevrotain/gast/src/model.ts", "../../node_modules/@chevrotain/gast/src/visitor.ts", "../../node_modules/@chevrotain/gast/src/helpers.ts", "../../node_modules/chevrotain/src/parse/grammar/rest.ts", "../../node_modules/chevrotain/src/parse/grammar/first.ts", "../../node_modules/chevrotain/src/parse/constants.ts", "../../node_modules/chevrotain/src/parse/grammar/follow.ts", "../../node_modules/chevrotain/src/scan/reg_exp_parser.ts", "../../node_modules/chevrotain/src/scan/reg_exp.ts", "../../node_modules/chevrotain/src/scan/lexer.ts", "../../node_modules/chevrotain/src/scan/tokens.ts", "../../node_modules/chevrotain/src/scan/lexer_errors_public.ts", "../../node_modules/chevrotain/src/scan/lexer_public.ts", "../../node_modules/chevrotain/src/scan/tokens_public.ts", "../../node_modules/chevrotain/src/parse/errors_public.ts", "../../node_modules/chevrotain/src/parse/grammar/resolver.ts", "../../node_modules/chevrotain/src/parse/grammar/interpreter.ts", "../../node_modules/chevrotain/src/parse/grammar/lookahead.ts", "../../node_modules/chevrotain/src/parse/grammar/checks.ts", "../../node_modules/chevrotain/src/parse/grammar/gast/gast_resolver_public.ts", "../../node_modules/chevrotain/src/parse/exceptions_public.ts", "../../node_modules/chevrotain/src/parse/parser/traits/recoverable.ts", "../../node_modules/chevrotain/src/parse/grammar/keys.ts", "../../node_modules/chevrotain/src/parse/grammar/llk_lookahead.ts", "../../node_modules/chevrotain/src/parse/parser/traits/looksahead.ts", "../../node_modules/chevrotain/src/parse/cst/cst.ts", "../../node_modules/chevrotain/src/lang/lang_extensions.ts", "../../node_modules/chevrotain/src/parse/cst/cst_visitor.ts", "../../node_modules/chevrotain/src/parse/parser/traits/tree_builder.ts", "../../node_modules/chevrotain/src/parse/parser/traits/lexer_adapter.ts", "../../node_modules/chevrotain/src/parse/parser/traits/recognizer_api.ts", "../../node_modules/chevrotain/src/parse/parser/traits/recognizer_engine.ts", "../../node_modules/chevrotain/src/parse/parser/traits/error_handler.ts", "../../node_modules/chevrotain/src/parse/parser/traits/context_assist.ts", "../../node_modules/chevrotain/src/parse/parser/traits/gast_recorder.ts", "../../node_modules/chevrotain/src/parse/parser/traits/perf_tracer.ts", "../../node_modules/chevrotain/src/parse/parser/utils/apply_mixins.ts", "../../node_modules/chevrotain/src/parse/parser/parser.ts", "../../node_modules/chevrotain-allstar/src/atn.ts", "../../node_modules/chevrotain-allstar/src/dfa.ts", "../../node_modules/chevrotain-allstar/src/all-star-lookahead.ts", "../../node_modules/vscode-languageserver-types/lib/esm/main.js", "../../node_modules/langium/src/parser/cst-node-builder.ts", "../../node_modules/langium/src/parser/langium-parser.ts", "../../node_modules/langium/src/parser/parser-builder-base.ts", "../../node_modules/langium/src/parser/completion-parser-builder.ts", "../../node_modules/langium/src/parser/langium-parser-builder.ts", "../../node_modules/langium/src/parser/token-builder.ts", "../../node_modules/langium/src/parser/value-converter.ts", "../../node_modules/langium/src/utils/cancellation.ts", "../../node_modules/langium/src/utils/promise-utils.ts", "../../node_modules/vscode-languageserver-textdocument/lib/esm/main.js", "webpack://LIB/node_modules/path-browserify/index.js", "webpack://LIB/webpack/bootstrap", "webpack://LIB/webpack/runtime/define%20property%20getters", "webpack://LIB/webpack/runtime/hasOwnProperty%20shorthand", "webpack://LIB/webpack/runtime/make%20namespace%20object", "webpack://LIB/src/platform.ts", "webpack://LIB/src/uri.ts", "webpack://LIB/src/utils.ts", "../../node_modules/langium/src/utils/uri-utils.ts", "../../node_modules/langium/src/workspace/documents.ts", "../../node_modules/langium/src/references/linker.ts", "../../node_modules/langium/src/references/name-provider.ts", "../../node_modules/langium/src/references/references.ts", "../../node_modules/langium/src/utils/collections.ts", "../../node_modules/langium/src/references/scope-computation.ts", "../../node_modules/langium/src/references/scope.ts", "../../node_modules/langium/src/utils/caching.ts", "../../node_modules/langium/src/references/scope-provider.ts", "../../node_modules/langium/src/serializer/json-serializer.ts", "../../node_modules/langium/src/service-registry.ts", "../../node_modules/langium/src/validation/validation-registry.ts", "../../node_modules/langium/src/validation/document-validator.ts", "../../node_modules/langium/src/workspace/ast-descriptions.ts", "../../node_modules/langium/src/workspace/ast-node-locator.ts", "../../node_modules/langium/src/utils/event.ts", "../../node_modules/langium/src/workspace/configuration.ts", "../../node_modules/langium/src/utils/disposable.ts", "../../node_modules/langium/src/workspace/document-builder.ts", "../../node_modules/langium/src/workspace/index-manager.ts", "../../node_modules/langium/src/workspace/workspace-manager.ts", "../../node_modules/langium/src/parser/lexer.ts", "../../node_modules/langium/src/documentation/jsdoc.ts", "../../node_modules/langium/src/documentation/documentation-provider.ts", "../../node_modules/langium/src/documentation/comment-provider.ts", "../../node_modules/langium/src/parser/async-parser.ts", "../../node_modules/langium/src/workspace/workspace-lock.ts", "../../node_modules/langium/src/serializer/hydrator.ts", "../../node_modules/langium/src/default-module.ts", "../../node_modules/langium/src/dependency-injection.ts", "../../node_modules/langium/src/parser/indentation-aware.ts", "../../node_modules/langium/src/utils/index.ts", "../../node_modules/langium/src/workspace/file-system-provider.ts", "../../node_modules/langium/src/utils/grammar-loader.ts", "../../node_modules/@mermaid-js/parser/dist/chunks/mermaid-parser.core/chunk-4KMFLZZN.mjs"], + "sourcesContent": ["\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nlet _ral;\nfunction RAL() {\n if (_ral === undefined) {\n throw new Error(`No runtime abstraction layer installed`);\n }\n return _ral;\n}\n(function (RAL) {\n function install(ral) {\n if (ral === undefined) {\n throw new Error(`No runtime abstraction layer provided`);\n }\n _ral = ral;\n }\n RAL.install = install;\n})(RAL || (RAL = {}));\nexports.default = RAL;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.stringArray = exports.array = exports.func = exports.error = exports.number = exports.string = exports.boolean = void 0;\nfunction boolean(value) {\n return value === true || value === false;\n}\nexports.boolean = boolean;\nfunction string(value) {\n return typeof value === 'string' || value instanceof String;\n}\nexports.string = string;\nfunction number(value) {\n return typeof value === 'number' || value instanceof Number;\n}\nexports.number = number;\nfunction error(value) {\n return value instanceof Error;\n}\nexports.error = error;\nfunction func(value) {\n return typeof value === 'function';\n}\nexports.func = func;\nfunction array(value) {\n return Array.isArray(value);\n}\nexports.array = array;\nfunction stringArray(value) {\n return array(value) && value.every(elem => string(elem));\n}\nexports.stringArray = stringArray;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Emitter = exports.Event = void 0;\nconst ral_1 = require(\"./ral\");\nvar Event;\n(function (Event) {\n const _disposable = { dispose() { } };\n Event.None = function () { return _disposable; };\n})(Event || (exports.Event = Event = {}));\nclass CallbackList {\n add(callback, context = null, bucket) {\n if (!this._callbacks) {\n this._callbacks = [];\n this._contexts = [];\n }\n this._callbacks.push(callback);\n this._contexts.push(context);\n if (Array.isArray(bucket)) {\n bucket.push({ dispose: () => this.remove(callback, context) });\n }\n }\n remove(callback, context = null) {\n if (!this._callbacks) {\n return;\n }\n let foundCallbackWithDifferentContext = false;\n for (let i = 0, len = this._callbacks.length; i < len; i++) {\n if (this._callbacks[i] === callback) {\n if (this._contexts[i] === context) {\n // callback & context match => remove it\n this._callbacks.splice(i, 1);\n this._contexts.splice(i, 1);\n return;\n }\n else {\n foundCallbackWithDifferentContext = true;\n }\n }\n }\n if (foundCallbackWithDifferentContext) {\n throw new Error('When adding a listener with a context, you should remove it with the same context');\n }\n }\n invoke(...args) {\n if (!this._callbacks) {\n return [];\n }\n const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);\n for (let i = 0, len = callbacks.length; i < len; i++) {\n try {\n ret.push(callbacks[i].apply(contexts[i], args));\n }\n catch (e) {\n // eslint-disable-next-line no-console\n (0, ral_1.default)().console.error(e);\n }\n }\n return ret;\n }\n isEmpty() {\n return !this._callbacks || this._callbacks.length === 0;\n }\n dispose() {\n this._callbacks = undefined;\n this._contexts = undefined;\n }\n}\nclass Emitter {\n constructor(_options) {\n this._options = _options;\n }\n /**\n * For the public to allow to subscribe\n * to events from this Emitter\n */\n get event() {\n if (!this._event) {\n this._event = (listener, thisArgs, disposables) => {\n if (!this._callbacks) {\n this._callbacks = new CallbackList();\n }\n if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {\n this._options.onFirstListenerAdd(this);\n }\n this._callbacks.add(listener, thisArgs);\n const result = {\n dispose: () => {\n if (!this._callbacks) {\n // disposable is disposed after emitter is disposed.\n return;\n }\n this._callbacks.remove(listener, thisArgs);\n result.dispose = Emitter._noop;\n if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {\n this._options.onLastListenerRemove(this);\n }\n }\n };\n if (Array.isArray(disposables)) {\n disposables.push(result);\n }\n return result;\n };\n }\n return this._event;\n }\n /**\n * To be kept private to fire an event to\n * subscribers\n */\n fire(event) {\n if (this._callbacks) {\n this._callbacks.invoke.call(this._callbacks, event);\n }\n }\n dispose() {\n if (this._callbacks) {\n this._callbacks.dispose();\n this._callbacks = undefined;\n }\n }\n}\nexports.Emitter = Emitter;\nEmitter._noop = function () { };\n", "\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CancellationTokenSource = exports.CancellationToken = void 0;\nconst ral_1 = require(\"./ral\");\nconst Is = require(\"./is\");\nconst events_1 = require(\"./events\");\nvar CancellationToken;\n(function (CancellationToken) {\n CancellationToken.None = Object.freeze({\n isCancellationRequested: false,\n onCancellationRequested: events_1.Event.None\n });\n CancellationToken.Cancelled = Object.freeze({\n isCancellationRequested: true,\n onCancellationRequested: events_1.Event.None\n });\n function is(value) {\n const candidate = value;\n return candidate && (candidate === CancellationToken.None\n || candidate === CancellationToken.Cancelled\n || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));\n }\n CancellationToken.is = is;\n})(CancellationToken || (exports.CancellationToken = CancellationToken = {}));\nconst shortcutEvent = Object.freeze(function (callback, context) {\n const handle = (0, ral_1.default)().timer.setTimeout(callback.bind(context), 0);\n return { dispose() { handle.dispose(); } };\n});\nclass MutableToken {\n constructor() {\n this._isCancelled = false;\n }\n cancel() {\n if (!this._isCancelled) {\n this._isCancelled = true;\n if (this._emitter) {\n this._emitter.fire(undefined);\n this.dispose();\n }\n }\n }\n get isCancellationRequested() {\n return this._isCancelled;\n }\n get onCancellationRequested() {\n if (this._isCancelled) {\n return shortcutEvent;\n }\n if (!this._emitter) {\n this._emitter = new events_1.Emitter();\n }\n return this._emitter.event;\n }\n dispose() {\n if (this._emitter) {\n this._emitter.dispose();\n this._emitter = undefined;\n }\n }\n}\nclass CancellationTokenSource {\n get token() {\n if (!this._token) {\n // be lazy and create the token only when\n // actually needed\n this._token = new MutableToken();\n }\n return this._token;\n }\n cancel() {\n if (!this._token) {\n // save an object by returning the default\n // cancelled token when cancellation happens\n // before someone asks for the token\n this._token = CancellationToken.Cancelled;\n }\n else {\n this._token.cancel();\n }\n }\n dispose() {\n if (!this._token) {\n // ensure to initialize with an empty token if we had none\n this._token = CancellationToken.None;\n }\n else if (this._token instanceof MutableToken) {\n // actually dispose\n this._token.dispose();\n }\n }\n}\nexports.CancellationTokenSource = CancellationTokenSource;\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n *\r\n * @module langium\r\n */\r\n\r\nexport * from './default-module.js';\r\nexport * from './dependency-injection.js';\r\nexport * from './service-registry.js';\r\nexport * from './services.js';\r\nexport * from './syntax-tree.js';\r\nexport * from './documentation/index.js';\r\nexport * from './languages/index.js';\r\nexport * from './parser/index.js';\r\nexport * from './references/index.js';\r\nexport * from './serializer/index.js';\r\nexport * from './utils/index.js';\r\nexport * from './validation/index.js';\r\nexport * from './workspace/index.js';\r\n\r\n// Export the Langium Grammar AST definitions in the `GrammarAST` namespace\r\nimport * as GrammarAST from './languages/generated/ast.js';\r\nimport type { Grammar } from './languages/generated/ast.js';\r\nexport { Grammar, GrammarAST };\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { IToken } from '@chevrotain/types';\r\nimport type { Range } from 'vscode-languageserver-types';\r\nimport type { CstNode, CompositeCstNode, LeafCstNode } from '../syntax-tree.js';\r\nimport type { DocumentSegment } from '../workspace/documents.js';\r\nimport type { Stream, TreeStream } from './stream.js';\r\nimport { isCompositeCstNode, isLeafCstNode, isRootCstNode } from '../syntax-tree.js';\r\nimport { TreeStreamImpl } from './stream.js';\r\n\r\n/**\r\n * Create a stream of all CST nodes that are directly and indirectly contained in the given root node,\r\n * including the root node itself.\r\n */\r\nexport function streamCst(node: CstNode): TreeStream {\r\n return new TreeStreamImpl(node, element => {\r\n if (isCompositeCstNode(element)) {\r\n return element.content;\r\n } else {\r\n return [];\r\n }\r\n }, { includeRoot: true });\r\n}\r\n\r\n/**\r\n * Create a stream of all leaf nodes that are directly and indirectly contained in the given root node.\r\n */\r\nexport function flattenCst(node: CstNode): Stream {\r\n return streamCst(node).filter(isLeafCstNode);\r\n}\r\n\r\n/**\r\n * Determines whether the specified cst node is a child of the specified parent node.\r\n */\r\nexport function isChildNode(child: CstNode, parent: CstNode): boolean {\r\n while (child.container) {\r\n child = child.container;\r\n if (child === parent) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\n\r\nexport function tokenToRange(token: IToken): Range {\r\n // Chevrotain uses 1-based indices everywhere\r\n // So we subtract 1 from every value to align with the LSP\r\n return {\r\n start: {\r\n character: token.startColumn! - 1,\r\n line: token.startLine! - 1\r\n },\r\n end: {\r\n character: token.endColumn!, // endColumn uses the correct index\r\n line: token.endLine! - 1\r\n }\r\n };\r\n}\r\n\r\nexport function toDocumentSegment(node: CstNode): DocumentSegment;\r\nexport function toDocumentSegment(node?: CstNode): DocumentSegment | undefined;\r\nexport function toDocumentSegment(node?: CstNode): DocumentSegment | undefined {\r\n if (!node) {\r\n return undefined;\r\n }\r\n const { offset, end, range } = node;\r\n return {\r\n range,\r\n offset,\r\n end,\r\n length: end - offset\r\n };\r\n}\r\n\r\nexport enum RangeComparison {\r\n Before = 0,\r\n After = 1,\r\n OverlapFront = 2,\r\n OverlapBack = 3,\r\n Inside = 4,\r\n Outside = 5,\r\n}\r\n\r\nexport function compareRange(range: Range, to: Range): RangeComparison {\r\n if (range.end.line < to.start.line || (range.end.line === to.start.line && range.end.character <= to.start.character)) {\r\n return RangeComparison.Before;\r\n } else if (range.start.line > to.end.line || (range.start.line === to.end.line && range.start.character >= to.end.character)) {\r\n return RangeComparison.After;\r\n }\r\n const startInside = range.start.line > to.start.line || (range.start.line === to.start.line && range.start.character >= to.start.character);\r\n const endInside = range.end.line < to.end.line || (range.end.line === to.end.line && range.end.character <= to.end.character);\r\n if (startInside && endInside) {\r\n return RangeComparison.Inside;\r\n } else if (startInside) {\r\n return RangeComparison.OverlapBack;\r\n } else if (endInside) {\r\n return RangeComparison.OverlapFront;\r\n } else {\r\n return RangeComparison.Outside;\r\n }\r\n}\r\n\r\nexport function inRange(range: Range, to: Range): boolean {\r\n const comparison = compareRange(range, to);\r\n return comparison > RangeComparison.After;\r\n}\r\n\r\n// The \\p{L} regex matches any unicode letter character, i.e. characters from non-english alphabets\r\n// Together with \\w it matches any kind of character which can commonly appear in IDs\r\nexport const DefaultNameRegexp = /^[\\w\\p{L}]$/u;\r\n\r\n/**\r\n * Performs `findLeafNodeAtOffset` with a minor difference: When encountering a character that matches the `nameRegexp` argument,\r\n * it will instead return the leaf node at the `offset - 1` position.\r\n *\r\n * For LSP services, users expect that the declaration of an element is available if the cursor is directly after the element.\r\n */\r\nexport function findDeclarationNodeAtOffset(cstNode: CstNode | undefined, offset: number, nameRegexp = DefaultNameRegexp): LeafCstNode | undefined {\r\n if (cstNode) {\r\n if (offset > 0) {\r\n const localOffset = offset - cstNode.offset;\r\n const textAtOffset = cstNode.text.charAt(localOffset);\r\n if (!nameRegexp.test(textAtOffset)) {\r\n offset--;\r\n }\r\n }\r\n return findLeafNodeAtOffset(cstNode, offset);\r\n }\r\n return undefined;\r\n}\r\n\r\nexport function findCommentNode(cstNode: CstNode | undefined, commentNames: string[]): CstNode | undefined {\r\n if (cstNode) {\r\n const previous = getPreviousNode(cstNode, true);\r\n if (previous && isCommentNode(previous, commentNames)) {\r\n return previous;\r\n }\r\n if (isRootCstNode(cstNode)) {\r\n // Go from the first non-hidden node through all nodes in reverse order\r\n // We do this to find the comment node which directly precedes the root node\r\n const endIndex = cstNode.content.findIndex(e => !e.hidden);\r\n for (let i = endIndex - 1; i >= 0; i--) {\r\n const child = cstNode.content[i];\r\n if (isCommentNode(child, commentNames)) {\r\n return child;\r\n }\r\n }\r\n }\r\n }\r\n return undefined;\r\n}\r\n\r\nexport function isCommentNode(cstNode: CstNode, commentNames: string[]): boolean {\r\n return isLeafCstNode(cstNode) && commentNames.includes(cstNode.tokenType.name);\r\n}\r\n\r\n/**\r\n * Finds the leaf CST node at the specified 0-based string offset.\r\n * Note that the given offset will be within the range of the returned leaf node.\r\n *\r\n * If the offset does not point to a CST node (but just white space), this method will return `undefined`.\r\n *\r\n * @param node The CST node to search through.\r\n * @param offset The specified offset.\r\n * @returns The CST node at the specified offset.\r\n */\r\nexport function findLeafNodeAtOffset(node: CstNode, offset: number): LeafCstNode | undefined {\r\n if (isLeafCstNode(node)) {\r\n return node;\r\n } else if (isCompositeCstNode(node)) {\r\n const searchResult = binarySearch(node, offset, false);\r\n if (searchResult) {\r\n return findLeafNodeAtOffset(searchResult, offset);\r\n }\r\n }\r\n return undefined;\r\n}\r\n\r\n/**\r\n * Finds the leaf CST node at the specified 0-based string offset.\r\n * If no CST node exists at the specified position, it will return the leaf node before it.\r\n *\r\n * If there is no leaf node before the specified offset, this method will return `undefined`.\r\n *\r\n * @param node The CST node to search through.\r\n * @param offset The specified offset.\r\n * @returns The CST node closest to the specified offset.\r\n */\r\nexport function findLeafNodeBeforeOffset(node: CstNode, offset: number): LeafCstNode | undefined {\r\n if (isLeafCstNode(node)) {\r\n return node;\r\n } else if (isCompositeCstNode(node)) {\r\n const searchResult = binarySearch(node, offset, true);\r\n if (searchResult) {\r\n return findLeafNodeBeforeOffset(searchResult, offset);\r\n }\r\n }\r\n return undefined;\r\n}\r\n\r\nfunction binarySearch(node: CompositeCstNode, offset: number, closest: boolean): CstNode | undefined {\r\n let left = 0;\r\n let right = node.content.length - 1;\r\n let closestNode: CstNode | undefined = undefined;\r\n\r\n while (left <= right) {\r\n const middle = Math.floor((left + right) / 2);\r\n const middleNode = node.content[middle];\r\n\r\n if (middleNode.offset <= offset && middleNode.end > offset) {\r\n // Found an exact match\r\n return middleNode;\r\n }\r\n\r\n if (middleNode.end <= offset) {\r\n // Update the closest node (less than offset) and move to the right half\r\n closestNode = closest ? middleNode : undefined;\r\n left = middle + 1;\r\n } else {\r\n // Move to the left half\r\n right = middle - 1;\r\n }\r\n }\r\n\r\n return closestNode;\r\n}\r\n\r\nexport function getPreviousNode(node: CstNode, hidden = true): CstNode | undefined {\r\n while (node.container) {\r\n const parent = node.container;\r\n let index = parent.content.indexOf(node);\r\n while (index > 0) {\r\n index--;\r\n const previous = parent.content[index];\r\n if (hidden || !previous.hidden) {\r\n return previous;\r\n }\r\n }\r\n node = parent;\r\n }\r\n return undefined;\r\n}\r\n\r\nexport function getNextNode(node: CstNode, hidden = true): CstNode | undefined {\r\n while (node.container) {\r\n const parent = node.container;\r\n let index = parent.content.indexOf(node);\r\n const last = parent.content.length - 1;\r\n while (index < last) {\r\n index++;\r\n const next = parent.content[index];\r\n if (hidden || !next.hidden) {\r\n return next;\r\n }\r\n }\r\n node = parent;\r\n }\r\n return undefined;\r\n}\r\n\r\nexport function getStartlineNode(node: CstNode): CstNode {\r\n if (node.range.start.character === 0) {\r\n return node;\r\n }\r\n const line = node.range.start.line;\r\n let last = node;\r\n let index: number | undefined;\r\n while (node.container) {\r\n const parent = node.container;\r\n const selfIndex = index ?? parent.content.indexOf(node);\r\n if (selfIndex === 0) {\r\n node = parent;\r\n index = undefined;\r\n } else {\r\n index = selfIndex - 1;\r\n node = parent.content[index];\r\n }\r\n if (node.range.start.line !== line) {\r\n break;\r\n }\r\n last = node;\r\n }\r\n return last;\r\n}\r\n\r\nexport function getInteriorNodes(start: CstNode, end: CstNode): CstNode[] {\r\n const commonParent = getCommonParent(start, end);\r\n if (!commonParent) {\r\n return [];\r\n }\r\n return commonParent.parent.content.slice(commonParent.a + 1, commonParent.b);\r\n}\r\n\r\nfunction getCommonParent(a: CstNode, b: CstNode): CommonParent | undefined {\r\n const aParents = getParentChain(a);\r\n const bParents = getParentChain(b);\r\n let current: CommonParent | undefined;\r\n for (let i = 0; i < aParents.length && i < bParents.length; i++) {\r\n const aParent = aParents[i];\r\n const bParent = bParents[i];\r\n if (aParent.parent === bParent.parent) {\r\n current = {\r\n parent: aParent.parent,\r\n a: aParent.index,\r\n b: bParent.index\r\n };\r\n } else {\r\n break;\r\n }\r\n }\r\n return current;\r\n}\r\n\r\ninterface CommonParent {\r\n parent: CompositeCstNode\r\n a: number\r\n b: number\r\n}\r\n\r\nfunction getParentChain(node: CstNode): ParentLink[] {\r\n const chain: ParentLink[] = [];\r\n while (node.container) {\r\n const parent = node.container;\r\n const index = parent.content.indexOf(node);\r\n chain.push({\r\n parent,\r\n index\r\n });\r\n node = parent;\r\n }\r\n return chain.reverse();\r\n}\r\n\r\ninterface ParentLink {\r\n parent: CompositeCstNode\r\n index: number\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { TokenType } from 'chevrotain';\r\nimport type { URI } from './utils/uri-utils.js';\r\nimport type { AbstractElement } from './languages/generated/ast.js';\r\nimport type { DocumentSegment, LangiumDocument } from './workspace/documents.js';\r\n\r\n/**\r\n * A node in the Abstract Syntax Tree (AST).\r\n */\r\nexport interface AstNode {\r\n /** Every AST node has a type corresponding to what was specified in the grammar declaration. */\r\n readonly $type: string;\r\n /** The container node in the AST; every node except the root node has a container. */\r\n readonly $container?: AstNode;\r\n /** The property of the `$container` node that contains this node. This is either a direct reference or an array. */\r\n readonly $containerProperty?: string;\r\n /** In case `$containerProperty` is an array, the array index is stored here. */\r\n readonly $containerIndex?: number;\r\n /** The Concrete Syntax Tree (CST) node of the text range from which this node was parsed. */\r\n readonly $cstNode?: CstNode;\r\n /** The document containing the AST; only the root node has a direct reference to the document. */\r\n readonly $document?: LangiumDocument;\r\n}\r\n\r\nexport function isAstNode(obj: unknown): obj is AstNode {\r\n return typeof obj === 'object' && obj !== null && typeof (obj as AstNode).$type === 'string';\r\n}\r\n\r\nexport interface GenericAstNode extends AstNode {\r\n [key: string]: unknown\r\n}\r\n\r\ntype SpecificNodeProperties = keyof Omit;\r\n\r\n/**\r\n * The property names of a given AST node type.\r\n */\r\nexport type Properties = SpecificNodeProperties extends never ? string : SpecificNodeProperties\r\n\r\n/**\r\n * A cross-reference in the AST. Cross-references may or may not be successfully resolved.\r\n */\r\nexport interface Reference {\r\n /**\r\n * The target AST node of this reference. Accessing this property may trigger cross-reference\r\n * resolution by the `Linker` in case it has not been done yet. If the reference cannot be resolved,\r\n * the value is `undefined`.\r\n */\r\n readonly ref?: T;\r\n\r\n /** If any problem occurred while resolving the reference, it is described by this property. */\r\n readonly error?: LinkingError;\r\n /** The CST node from which the reference was parsed */\r\n readonly $refNode?: CstNode;\r\n /** The actual text used to look up in the surrounding scope */\r\n readonly $refText: string;\r\n /** The node description for the AstNode returned by `ref` */\r\n readonly $nodeDescription?: AstNodeDescription;\r\n}\r\n\r\nexport function isReference(obj: unknown): obj is Reference {\r\n return typeof obj === 'object' && obj !== null && typeof (obj as Reference).$refText === 'string';\r\n}\r\n\r\nexport type ResolvedReference = Reference & {\r\n readonly ref: T;\r\n}\r\n\r\n/**\r\n * A description of an AST node is used when constructing scopes and looking up cross-reference targets.\r\n */\r\nexport interface AstNodeDescription {\r\n /** The target node; should be present only for local references (linking to the same document). */\r\n node?: AstNode;\r\n /**\r\n * The document segment that represents the range of the name of the AST node.\r\n */\r\n nameSegment?: DocumentSegment;\r\n /**\r\n * The document segment that represents the full range of the AST node.\r\n */\r\n selectionSegment?: DocumentSegment;\r\n /** `$type` property value of the AST node */\r\n type: string;\r\n /** Name of the AST node; this is usually determined by the `NameProvider` service. */\r\n name: string;\r\n /** URI to the document containing the AST node */\r\n documentUri: URI;\r\n /** Navigation path inside the document */\r\n path: string;\r\n}\r\n\r\nexport function isAstNodeDescription(obj: unknown): obj is AstNodeDescription {\r\n return typeof obj === 'object' && obj !== null\r\n && typeof (obj as AstNodeDescription).name === 'string'\r\n && typeof (obj as AstNodeDescription).type === 'string'\r\n && typeof (obj as AstNodeDescription).path === 'string';\r\n}\r\n\r\n/**\r\n * Information about a cross-reference. This is used when traversing references in an AST or to describe\r\n * unresolved references.\r\n */\r\nexport interface ReferenceInfo {\r\n reference: Reference\r\n container: AstNode\r\n property: string\r\n index?: number\r\n}\r\n\r\n/**\r\n * Used to collect information when the `Linker` service fails to resolve a cross-reference.\r\n */\r\nexport interface LinkingError extends ReferenceInfo {\r\n message: string;\r\n targetDescription?: AstNodeDescription;\r\n}\r\n\r\nexport function isLinkingError(obj: unknown): obj is LinkingError {\r\n return typeof obj === 'object' && obj !== null\r\n && isAstNode((obj as LinkingError).container)\r\n && isReference((obj as LinkingError).reference)\r\n && typeof (obj as LinkingError).message === 'string';\r\n}\r\n\r\n/**\r\n * Service used for generic access to the structure of the AST. This service is shared between\r\n * all involved languages, so it operates on the superset of types of these languages.\r\n */\r\nexport interface AstReflection {\r\n getAllTypes(): string[]\r\n getAllSubTypes(type: string): string[]\r\n getReferenceType(refInfo: ReferenceInfo): string\r\n getTypeMetaData(type: string): TypeMetaData\r\n isInstance(node: unknown, type: string): boolean\r\n isSubtype(subtype: string, supertype: string): boolean\r\n}\r\n\r\n/**\r\n * An abstract implementation of the {@link AstReflection} interface.\r\n * Serves to cache subtype computation results to improve performance throughout different parts of Langium.\r\n */\r\nexport abstract class AbstractAstReflection implements AstReflection {\r\n\r\n protected subtypes: Record> = {};\r\n protected allSubtypes: Record = {};\r\n\r\n abstract getAllTypes(): string[];\r\n abstract getReferenceType(refInfo: ReferenceInfo): string;\r\n abstract getTypeMetaData(type: string): TypeMetaData;\r\n protected abstract computeIsSubtype(subtype: string, supertype: string): boolean;\r\n\r\n isInstance(node: unknown, type: string): boolean {\r\n return isAstNode(node) && this.isSubtype(node.$type, type);\r\n }\r\n\r\n isSubtype(subtype: string, supertype: string): boolean {\r\n if (subtype === supertype) {\r\n return true;\r\n }\r\n let nested = this.subtypes[subtype];\r\n if (!nested) {\r\n nested = this.subtypes[subtype] = {};\r\n }\r\n const existing = nested[supertype];\r\n if (existing !== undefined) {\r\n return existing;\r\n } else {\r\n const result = this.computeIsSubtype(subtype, supertype);\r\n nested[supertype] = result;\r\n return result;\r\n }\r\n }\r\n\r\n getAllSubTypes(type: string): string[] {\r\n const existing = this.allSubtypes[type];\r\n if (existing) {\r\n return existing;\r\n } else {\r\n const allTypes = this.getAllTypes();\r\n const types: string[] = [];\r\n for (const possibleSubType of allTypes) {\r\n if (this.isSubtype(possibleSubType, type)) {\r\n types.push(possibleSubType);\r\n }\r\n }\r\n this.allSubtypes[type] = types;\r\n return types;\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Represents runtime meta data about a meta model type.\r\n */\r\nexport interface TypeMetaData {\r\n /** The name of this meta model type. Corresponds to the `AstNode.$type` value. */\r\n name: string\r\n /** A list of properties. They can contain default values for their respective property in the AST. */\r\n properties: TypeProperty[]\r\n}\r\n\r\n/**\r\n * Describes the meta data of a property of an AST node.\r\n *\r\n * The optional `defaultValue` indicates that the property is mandatory in the AST node.\r\n * For example, if an AST node contains an array, but no elements of this array have been parsed, we still expect an empty array instead of `undefined`.\r\n */\r\nexport interface TypeProperty {\r\n name: string\r\n defaultValue?: PropertyType\r\n}\r\n\r\n/**\r\n * Represents a default value for an AST property.\r\n */\r\nexport type PropertyType = number | string | boolean | PropertyType[];\r\n\r\n/**\r\n * A node in the Concrete Syntax Tree (CST).\r\n */\r\nexport interface CstNode extends DocumentSegment {\r\n /** The container node in the CST */\r\n readonly container?: CompositeCstNode;\r\n /** @deprecated use `container` instead. */\r\n readonly parent?: CompositeCstNode;\r\n /** The actual text */\r\n readonly text: string;\r\n /** The root CST node */\r\n readonly root: RootCstNode;\r\n /** The grammar element from which this node was parsed */\r\n readonly grammarSource?: AbstractElement;\r\n /** @deprecated use `grammarSource` instead. */\r\n readonly feature?: AbstractElement;\r\n /** The AST node created from this CST node */\r\n readonly astNode: AstNode;\r\n /** @deprecated use `astNode` instead. */\r\n readonly element: AstNode;\r\n /** Whether the token is hidden, i.e. not explicitly part of the containing grammar rule */\r\n readonly hidden: boolean;\r\n}\r\n\r\n/**\r\n * A composite CST node contains other nodes, but no directly associated token.\r\n */\r\nexport interface CompositeCstNode extends CstNode {\r\n readonly content: CstNode[];\r\n /** @deprecated use `content` instead. */\r\n readonly children: CstNode[];\r\n}\r\n\r\nexport function isCompositeCstNode(node: unknown): node is CompositeCstNode {\r\n return typeof node === 'object' && node !== null && Array.isArray((node as CompositeCstNode).content);\r\n}\r\n\r\n/**\r\n * A leaf CST node corresponds to a token in the input token stream.\r\n */\r\nexport interface LeafCstNode extends CstNode {\r\n readonly tokenType: TokenType;\r\n}\r\n\r\nexport function isLeafCstNode(node: unknown): node is LeafCstNode {\r\n return typeof node === 'object' && node !== null && typeof (node as LeafCstNode).tokenType === 'object';\r\n}\r\n\r\nexport interface RootCstNode extends CompositeCstNode {\r\n readonly fullText: string\r\n}\r\n\r\nexport function isRootCstNode(node: unknown): node is RootCstNode {\r\n return isCompositeCstNode(node) && typeof (node as RootCstNode).fullText === 'string';\r\n}\r\n\r\n/**\r\n * Returns a type to have only properties names (!) of a type T whose property value is of a certain type K.\r\n */\r\ntype ExtractKeysOfValueType = { [I in keyof T]: T[I] extends K ? I : never }[keyof T];\r\n\r\n/**\r\n * Returns the property names (!) of an AstNode that are cross-references.\r\n * Meant to be used during cross-reference resolution in combination with `assertUnreachable(context.property)`.\r\n */\r\nexport type CrossReferencesOfAstNodeType = (\r\n ExtractKeysOfValueType\r\n | ExtractKeysOfValueType|undefined>\r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\n) & {};\r\n\r\n/**\r\n * Represents the enumeration-like type, that lists all AstNode types of your grammar.\r\n */\r\nexport type AstTypeList = Record;\r\n\r\n/**\r\n * Returns all types that contain cross-references, A is meant to be the interface `XXXAstType` fromm your generated `ast.ts` file.\r\n * Meant to be used during cross-reference resolution in combination with `assertUnreachable(context.container)`.\r\n */\r\nexport type AstNodeTypesWithCrossReferences
> = {\r\n [T in keyof A]: CrossReferencesOfAstNodeType extends never ? never : A[T]\r\n}[keyof A];\r\n\r\nexport type Mutable = {\r\n -readonly [P in keyof T]: T[P]\r\n};\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\n/**\r\n * A stream is a read-only sequence of values. While the contents of an array can be accessed\r\n * both sequentially and randomly (via index), a stream allows only sequential access.\r\n *\r\n * The advantage of this is that a stream can be evaluated lazily, so it does not require\r\n * to store intermediate values. This can boost performance when a large sequence is\r\n * processed via filtering, mapping etc. and accessed at most once. However, lazy\r\n * evaluation means that all processing is repeated when you access the sequence multiple\r\n * times; in such a case, it may be better to store the resulting sequence into an array.\r\n */\r\nexport interface Stream extends Iterable {\r\n\r\n /**\r\n * Returns an iterator for this stream. This is the same as calling the `Symbol.iterator` function property.\r\n */\r\n iterator(): IterableIterator;\r\n\r\n /**\r\n * Determines whether this stream contains no elements.\r\n */\r\n isEmpty(): boolean;\r\n\r\n /**\r\n * Determines the number of elements in this stream.\r\n */\r\n count(): number;\r\n\r\n /**\r\n * Collects all elements of this stream into an array.\r\n */\r\n toArray(): T[];\r\n\r\n /**\r\n * Collects all elements of this stream into a Set.\r\n */\r\n toSet(): Set;\r\n\r\n /**\r\n * Collects all elements of this stream into a Map, applying the provided functions to determine keys and values.\r\n *\r\n * @param keyFn The function to derive map keys. If omitted, the stream elements are used as keys.\r\n * @param valueFn The function to derive map values. If omitted, the stream elements are used as values.\r\n */\r\n toMap(keyFn?: (e: T) => K, valueFn?: (e: T) => V): Map;\r\n\r\n /**\r\n * Returns a string representation of a stream.\r\n */\r\n toString(): string;\r\n\r\n /**\r\n * Combines two streams by returning a new stream that yields all elements of this stream and the other stream.\r\n *\r\n * @param other Stream to be concatenated with this one.\r\n */\r\n concat(other: Iterable): Stream;\r\n\r\n /**\r\n * Adds all elements of the stream into a string, separated by the specified separator string.\r\n *\r\n * @param separator A string used to separate one element of the stream from the next in the resulting string.\r\n * If omitted, the steam elements are separated with a comma.\r\n */\r\n join(separator?: string): string\r\n\r\n /**\r\n * Returns the index of the first occurrence of a value in the stream, or -1 if it is not present.\r\n *\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The stream index at which to begin the search. If fromIndex is omitted, the search\r\n * starts at index 0.\r\n */\r\n indexOf(searchElement: T, fromIndex?: number): number;\r\n\r\n /**\r\n * Determines whether all members of the stream satisfy the specified test.\r\n *\r\n * @param predicate This method calls the predicate function for each element in the stream until the\r\n * predicate returns a value which is coercible to the Boolean value `false`, or until the end\r\n * of the stream.\r\n */\r\n every(predicate: (value: T) => value is S): this is Stream;\r\n every(predicate: (value: T) => unknown): boolean;\r\n\r\n /**\r\n * Determines whether any member of the stream satisfies the specified test.\r\n *\r\n * @param predicate This method calls the predicate function for each element in the stream until the\r\n * predicate returns a value which is coercible to the Boolean value `true`, or until the end\r\n * of the stream.\r\n */\r\n some(predicate: (value: T) => unknown): boolean;\r\n\r\n /**\r\n * Performs the specified action for each element in the stream.\r\n *\r\n * @param callbackfn Function called once for each element in the stream.\r\n */\r\n forEach(callbackfn: (value: T, index: number) => void): void;\r\n\r\n /**\r\n * Returns a stream that yields the results of calling the specified callback function on each element\r\n * of the stream. The function is called when the resulting stream elements are actually accessed, so\r\n * accessing the resulting stream multiple times means the function is also called multiple times for\r\n * each element of the stream.\r\n *\r\n * @param callbackfn Lazily evaluated function mapping stream elements.\r\n */\r\n map(callbackfn: (value: T) => U): Stream;\r\n\r\n /**\r\n * Returns the elements of the stream that meet the condition specified in a callback function.\r\n * The function is called when the resulting stream elements are actually accessed, so accessing the\r\n * resulting stream multiple times means the function is also called multiple times for each element\r\n * of the stream.\r\n *\r\n * @param predicate Lazily evaluated function checking a condition on stream elements.\r\n */\r\n filter(predicate: (value: T) => value is S): Stream;\r\n filter(predicate: (value: T) => unknown): Stream;\r\n\r\n /**\r\n * Returns the elements of the stream that are _non-nullable_, which means they are neither `undefined`\r\n * nor `null`.\r\n */\r\n nonNullable(): Stream>;\r\n\r\n /**\r\n * Calls the specified callback function for all elements in the stream. The return value of the\r\n * callback function is the accumulated result, and is provided as an argument in the next call to\r\n * the callback function.\r\n *\r\n * @param callbackfn This method calls the function once for each element in the stream, providing\r\n * the previous and current values of the reduction.\r\n * @param initialValue If specified, `initialValue` is used as the initial value to start the\r\n * accumulation. The first call to the function provides this value as an argument instead\r\n * of a stream value.\r\n */\r\n reduce(callbackfn: (previousValue: T, currentValue: T) => T): T | undefined;\r\n reduce(callbackfn: (previousValue: U, currentValue: T) => U, initialValue: U): U;\r\n\r\n /**\r\n * Calls the specified callback function for all elements in the stream, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n *\r\n * @param callbackfn This method calls the function once for each element in the stream, providing\r\n * the previous and current values of the reduction.\r\n * @param initialValue If specified, `initialValue` is used as the initial value to start the\r\n * accumulation. The first call to the function provides this value as an argument instead\r\n * of an array value.\r\n */\r\n reduceRight(callbackfn: (previousValue: T, currentValue: T) => T): T | undefined;\r\n reduceRight(callbackfn: (previousValue: U, currentValue: T) => U, initialValue: U): U;\r\n\r\n /**\r\n * Returns the value of the first element in the stream that meets the condition, or `undefined`\r\n * if there is no such element.\r\n *\r\n * @param predicate This method calls `predicate` once for each element of the stream, in ascending\r\n * order, until it finds one where `predicate` returns a value which is coercible to the\r\n * Boolean value `true`.\r\n */\r\n find(predicate: (value: T) => value is S): S | undefined;\r\n find(predicate: (value: T) => unknown): T | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the stream that meets the condition, or `-1`\r\n * if there is no such element.\r\n *\r\n * @param predicate This method calls `predicate` once for each element of the stream, in ascending\r\n * order, until it finds one where `predicate` returns a value which is coercible to the\r\n * Boolean value `true`.\r\n */\r\n findIndex(predicate: (value: T) => unknown): number;\r\n\r\n /**\r\n * Determines whether the stream includes a certain element, returning `true` or `false` as appropriate.\r\n *\r\n * @param searchElement The element to search for.\r\n */\r\n includes(searchElement: T): boolean;\r\n\r\n /**\r\n * Calls a defined callback function on each element of the stream and then flattens the result into\r\n * a new stream. This is identical to a `map` followed by `flat` with depth 1.\r\n *\r\n * @param callbackfn Lazily evaluated function mapping stream elements.\r\n */\r\n flatMap(callbackfn: (value: T) => U | Iterable): Stream;\r\n\r\n /**\r\n * Returns a new stream with all sub-stream or sub-array elements concatenated into it recursively up\r\n * to the specified depth.\r\n *\r\n * @param depth The maximum recursion depth. Defaults to 1.\r\n */\r\n flat(depth?: D): FlatStream;\r\n\r\n /**\r\n * Returns the first element in the stream, or `undefined` if the stream is empty.\r\n */\r\n head(): T | undefined;\r\n\r\n /**\r\n * Returns a stream that skips the first `skipCount` elements from this stream.\r\n *\r\n * @param skipCount The number of elements to skip. If this is larger than the number of elements in\r\n * the stream, an empty stream is returned. Defaults to 1.\r\n */\r\n tail(skipCount?: number): Stream;\r\n\r\n /**\r\n * Returns a stream consisting of the elements of this stream, truncated to be no longer than `maxSize`\r\n * in length.\r\n *\r\n * @param maxSize The number of elements the stream should be limited to\r\n */\r\n limit(maxSize: number): Stream;\r\n\r\n /**\r\n * Returns a stream containing only the distinct elements from this stream.\r\n * Equality is determined with the same rules as a standard `Set`.\r\n *\r\n * @param by A function returning the key used to check equality with a previous stream element.\r\n * If omitted, the stream elements themselves are used for comparison.\r\n */\r\n distinct(by?: (element: T) => Key): Stream;\r\n\r\n /**\r\n * Returns a stream that contains all elements that don't exist in the {@link other} iterable.\r\n * Equality is determined with the same rules as a standard `Set`.\r\n * @param other The elements that should be exluded from this stream.\r\n * @param key A function returning the key used to check quality.\r\n * If omitted, the stream elements themselves are used for comparison.\r\n */\r\n exclude(other: Iterable, key?: (element: T) => Key): Stream;\r\n\r\n}\r\n\r\nexport type FlatStream = {\r\n 'done': Stream,\r\n 'recur': T extends Iterable\r\n ? FlatStream>\r\n : Stream\r\n}[Depth extends 0 ? 'done' : 'recur'];\r\n\r\nexport type MinusOne = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20][N];\r\n\r\n/**\r\n * The default implementation of `Stream` works with two input functions:\r\n * - The first function creates the initial state of an iteration.\r\n * - The second function gets the current state as argument and returns an `IteratorResult`.\r\n */\r\nexport class StreamImpl implements Stream {\r\n protected readonly startFn: () => S;\r\n protected readonly nextFn: (state: S) => IteratorResult;\r\n\r\n constructor(startFn: () => S, nextFn: (state: S) => IteratorResult) {\r\n this.startFn = startFn;\r\n this.nextFn = nextFn;\r\n }\r\n\r\n iterator(): IterableIterator {\r\n const iterator = {\r\n state: this.startFn(),\r\n next: () => this.nextFn(iterator.state),\r\n [Symbol.iterator]: () => iterator\r\n };\r\n return iterator;\r\n }\r\n\r\n [Symbol.iterator](): Iterator {\r\n return this.iterator();\r\n }\r\n\r\n isEmpty(): boolean {\r\n const iterator = this.iterator();\r\n return Boolean(iterator.next().done);\r\n }\r\n\r\n count(): number {\r\n const iterator = this.iterator();\r\n let count = 0;\r\n let next = iterator.next();\r\n while (!next.done) {\r\n count++;\r\n next = iterator.next();\r\n }\r\n return count;\r\n }\r\n\r\n toArray(): T[] {\r\n const result: T[] = [];\r\n const iterator = this.iterator();\r\n let next: IteratorResult;\r\n do {\r\n next = iterator.next();\r\n if (next.value !== undefined) {\r\n result.push(next.value);\r\n }\r\n } while (!next.done);\r\n return result;\r\n }\r\n\r\n toSet(): Set {\r\n return new Set(this);\r\n }\r\n\r\n toMap(keyFn?: (e: T) => K, valueFn?: (e: T) => V): Map {\r\n const entryStream = this.map(element => <[K, V]>[\r\n keyFn ? keyFn(element) : element,\r\n valueFn ? valueFn(element) : element\r\n ]);\r\n return new Map(entryStream);\r\n }\r\n\r\n toString(): string {\r\n return this.join();\r\n }\r\n\r\n concat(other: Iterable): Stream {\r\n return new StreamImpl<{ first: S, firstDone: boolean, iterator: Iterator }, T | T2>(\r\n () => ({ first: this.startFn(), firstDone: false, iterator: other[Symbol.iterator]() }),\r\n state => {\r\n let result: IteratorResult;\r\n if (!state.firstDone) {\r\n do {\r\n result = this.nextFn(state.first);\r\n if (!result.done) {\r\n return result;\r\n }\r\n } while (!result.done);\r\n state.firstDone = true;\r\n }\r\n do {\r\n result = state.iterator.next();\r\n if (!result.done) {\r\n return result;\r\n }\r\n } while (!result.done);\r\n return DONE_RESULT;\r\n }\r\n );\r\n }\r\n\r\n join(separator = ','): string {\r\n const iterator = this.iterator();\r\n let value = '';\r\n let result: IteratorResult;\r\n let addSeparator = false;\r\n do {\r\n result = iterator.next();\r\n if (!result.done) {\r\n if (addSeparator) {\r\n value += separator;\r\n }\r\n value += toString(result.value);\r\n }\r\n addSeparator = true;\r\n } while (!result.done);\r\n return value;\r\n }\r\n\r\n indexOf(searchElement: T, fromIndex = 0): number {\r\n const iterator = this.iterator();\r\n let index = 0;\r\n let next = iterator.next();\r\n while (!next.done) {\r\n if (index >= fromIndex && next.value === searchElement) {\r\n return index;\r\n }\r\n next = iterator.next();\r\n index++;\r\n }\r\n return -1;\r\n }\r\n\r\n // In the following definition the '& this' part in the return type is important\r\n // _and_ the order within 'Stream & this' is crucial!\r\n // Otherwise Typescript would infer the type of 'this' as 'StreamImpl & Stream'\r\n // (or ' & Stream') and usages like\r\n // ```\r\n // const stream = new StreamImpl(...);\r\n // ... stream.every() & stream....\r\n // ```\r\n // cannot benefit from '', as Typescript would priorize the signatures\r\n // of 'StreamImpl' (i.e. those of 'Stream') over those of 'Stream'.\r\n // With the order of 'Stream & this' the signatures of 'Stream' get precedence.\r\n every(predicate: (value: T) => value is U): this is Stream & this;\r\n every(predicate: (value: T) => unknown): boolean;\r\n every(predicate: (value: T) => unknown): boolean {\r\n const iterator = this.iterator();\r\n let next = iterator.next();\r\n while (!next.done) {\r\n if (!predicate(next.value)) {\r\n return false;\r\n }\r\n next = iterator.next();\r\n }\r\n return true;\r\n }\r\n\r\n some(predicate: (value: T) => unknown): boolean {\r\n const iterator = this.iterator();\r\n let next = iterator.next();\r\n while (!next.done) {\r\n if (predicate(next.value)) {\r\n return true;\r\n }\r\n next = iterator.next();\r\n }\r\n return false;\r\n }\r\n\r\n forEach(callbackfn: (value: T, index: number) => void): void {\r\n const iterator = this.iterator();\r\n let index = 0;\r\n let next = iterator.next();\r\n while (!next.done) {\r\n callbackfn(next.value, index);\r\n next = iterator.next();\r\n index++;\r\n }\r\n }\r\n\r\n map(callbackfn: (value: T) => U): Stream {\r\n return new StreamImpl(\r\n this.startFn,\r\n (state) => {\r\n const { done, value } = this.nextFn(state);\r\n if (done) {\r\n return DONE_RESULT;\r\n } else {\r\n return { done: false, value: callbackfn(value) };\r\n }\r\n }\r\n );\r\n }\r\n\r\n // for remarks on the return type definition refer to 'every(...)'\r\n filter(predicate: (value: T) => value is U): Stream & this;\r\n filter(predicate: (value: T) => unknown): Stream & this;\r\n filter(predicate: (value: T) => unknown): Stream {\r\n return new StreamImpl(\r\n this.startFn,\r\n state => {\r\n let result: IteratorResult;\r\n do {\r\n result = this.nextFn(state);\r\n if (!result.done && predicate(result.value)) {\r\n return result;\r\n }\r\n } while (!result.done);\r\n return DONE_RESULT;\r\n }\r\n );\r\n }\r\n\r\n nonNullable(): Stream> {\r\n return this.filter(e => e !== undefined && e !== null) as Stream>;\r\n }\r\n\r\n reduce(callbackfn: (previousValue: T, currentValue: T) => T): T | undefined;\r\n reduce(callbackfn: (previousValue: U, currentValue: T) => U, initialValue: U): U;\r\n reduce(callbackfn: (previousValue: U | T, currentValue: T) => U, initialValue?: U): U | T | undefined {\r\n const iterator = this.iterator();\r\n let previousValue: U | T | undefined = initialValue;\r\n let next = iterator.next();\r\n while (!next.done) {\r\n if (previousValue === undefined) {\r\n previousValue = next.value;\r\n } else {\r\n previousValue = callbackfn(previousValue, next.value);\r\n }\r\n next = iterator.next();\r\n }\r\n return previousValue;\r\n }\r\n\r\n reduceRight(callbackfn: (previousValue: T, currentValue: T) => T): T | undefined;\r\n reduceRight(callbackfn: (previousValue: U, currentValue: T) => U, initialValue: U): U;\r\n reduceRight(callbackfn: (previousValue: U | T, currentValue: T) => U, initialValue?: U): U | T | undefined {\r\n return this.recursiveReduce(this.iterator(), callbackfn, initialValue);\r\n }\r\n\r\n protected recursiveReduce(iterator: Iterator, callbackfn: (previousValue: U | T, currentValue: T) => U, initialValue?: U): U | T | undefined {\r\n const next = iterator.next();\r\n if (next.done) {\r\n return initialValue;\r\n }\r\n const previousValue = this.recursiveReduce(iterator, callbackfn, initialValue);\r\n if (previousValue === undefined) {\r\n return next.value;\r\n }\r\n return callbackfn(previousValue, next.value);\r\n }\r\n\r\n find(predicate: (value: T) => value is S): S | undefined;\r\n find(predicate: (value: T) => unknown): T | undefined;\r\n find(predicate: (value: T) => unknown): T | undefined {\r\n const iterator = this.iterator();\r\n let next = iterator.next();\r\n while (!next.done) {\r\n if (predicate(next.value)) {\r\n return next.value;\r\n }\r\n next = iterator.next();\r\n }\r\n return undefined;\r\n }\r\n\r\n findIndex(predicate: (value: T) => unknown): number {\r\n const iterator = this.iterator();\r\n let index = 0;\r\n let next = iterator.next();\r\n while (!next.done) {\r\n if (predicate(next.value)) {\r\n return index;\r\n }\r\n next = iterator.next();\r\n index++;\r\n }\r\n return -1;\r\n }\r\n\r\n includes(searchElement: T): boolean {\r\n const iterator = this.iterator();\r\n let next = iterator.next();\r\n while (!next.done) {\r\n if (next.value === searchElement) {\r\n return true;\r\n }\r\n next = iterator.next();\r\n }\r\n return false;\r\n }\r\n\r\n flatMap(callbackfn: (value: T) => U | Iterable): Stream {\r\n type FlatMapState = { this: S, iterator?: Iterator }\r\n return new StreamImpl(\r\n () => ({ this: this.startFn() }),\r\n (state) => {\r\n do {\r\n if (state.iterator) {\r\n const next = state.iterator.next();\r\n if (next.done) {\r\n state.iterator = undefined;\r\n } else {\r\n return next;\r\n }\r\n }\r\n const { done, value } = this.nextFn(state.this);\r\n if (!done) {\r\n const mapped = callbackfn(value);\r\n if (isIterable(mapped)) {\r\n state.iterator = mapped[Symbol.iterator]();\r\n } else {\r\n return { done: false, value: mapped };\r\n }\r\n }\r\n } while (state.iterator);\r\n return DONE_RESULT;\r\n }\r\n );\r\n }\r\n\r\n flat(depth?: D): FlatStream {\r\n if (depth === undefined) {\r\n depth = 1 as D;\r\n }\r\n if (depth <= 0) {\r\n return this as unknown as FlatStream;\r\n }\r\n const stream = depth > 1 ? this.flat(depth - 1) as unknown as StreamImpl : this;\r\n type FlatMapState = { this: S, iterator?: Iterator }\r\n return new StreamImpl(\r\n () => ({ this: stream.startFn() }),\r\n (state) => {\r\n do {\r\n if (state.iterator) {\r\n const next = state.iterator.next();\r\n if (next.done) {\r\n state.iterator = undefined;\r\n } else {\r\n return next;\r\n }\r\n }\r\n const { done, value } = stream.nextFn(state.this);\r\n if (!done) {\r\n if (isIterable(value)) {\r\n state.iterator = value[Symbol.iterator]() as Iterator;\r\n } else {\r\n return { done: false, value: value };\r\n }\r\n }\r\n } while (state.iterator);\r\n return DONE_RESULT;\r\n }\r\n ) as unknown as FlatStream;\r\n }\r\n\r\n head(): T | undefined {\r\n const iterator = this.iterator();\r\n const result = iterator.next();\r\n if (result.done) {\r\n return undefined;\r\n }\r\n return result.value;\r\n }\r\n\r\n tail(skipCount = 1): Stream {\r\n return new StreamImpl(\r\n () => {\r\n const state = this.startFn();\r\n for (let i = 0; i < skipCount; i++) {\r\n const next = this.nextFn(state);\r\n if (next.done) {\r\n return state;\r\n }\r\n }\r\n return state;\r\n },\r\n this.nextFn\r\n );\r\n }\r\n\r\n limit(maxSize: number): Stream {\r\n return new StreamImpl<{ size: number, state: S }, T>(\r\n () => ({ size: 0, state: this.startFn() }),\r\n state => {\r\n state.size++;\r\n if (state.size > maxSize) {\r\n return DONE_RESULT;\r\n }\r\n return this.nextFn(state.state);\r\n }\r\n );\r\n }\r\n\r\n distinct(by?: (element: T) => Key): Stream {\r\n return new StreamImpl<{ set: Set, internalState: S }, T>(\r\n () => ({ set: new Set(), internalState: this.startFn() }),\r\n state => {\r\n let result: IteratorResult;\r\n do {\r\n result = this.nextFn(state.internalState);\r\n if (!result.done) {\r\n const value = by ? by(result.value) : result.value;\r\n if (!state.set.has(value)) {\r\n state.set.add(value);\r\n return result;\r\n }\r\n }\r\n } while (!result.done);\r\n return DONE_RESULT;\r\n }\r\n );\r\n }\r\n\r\n exclude(other: Iterable, key?: (element: T) => Key): Stream {\r\n const otherKeySet = new Set();\r\n for (const item of other) {\r\n const value = key ? key(item) : item;\r\n otherKeySet.add(value);\r\n }\r\n return this.filter(e => {\r\n const ownKey = key ? key(e) : e;\r\n return !otherKeySet.has(ownKey);\r\n });\r\n }\r\n}\r\n\r\nfunction toString(item: unknown): string {\r\n if (typeof item === 'string') {\r\n return item as string;\r\n }\r\n if (typeof item === 'undefined') {\r\n return 'undefined';\r\n }\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n if (typeof (item as any).toString === 'function') {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return (item as any).toString();\r\n }\r\n return Object.prototype.toString.call(item);\r\n}\r\n\r\nfunction isIterable(obj: unknown): obj is Iterable {\r\n return !!obj && typeof (obj as Iterable)[Symbol.iterator] === 'function';\r\n}\r\n\r\n/**\r\n * An empty stream of any type.\r\n */\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nexport const EMPTY_STREAM: Stream = new StreamImpl(() => undefined, () => DONE_RESULT);\r\n\r\n/**\r\n * Use this `IteratorResult` when implementing a `StreamImpl` to indicate that there are no more elements in the stream.\r\n */\r\nexport const DONE_RESULT: IteratorReturnResult = Object.freeze({ done: true, value: undefined });\r\n\r\n/**\r\n * Create a stream from one or more iterables or array-likes.\r\n */\r\nexport function stream(...collections: Array | ArrayLike>): Stream {\r\n if (collections.length === 1) {\r\n const collection = collections[0];\r\n if (collection instanceof StreamImpl) {\r\n return collection as Stream;\r\n }\r\n if (isIterable(collection)) {\r\n return new StreamImpl, T>(\r\n () => collection[Symbol.iterator](),\r\n (iterator) => iterator.next()\r\n );\r\n }\r\n if (typeof collection.length === 'number') {\r\n return new StreamImpl<{ index: number }, T>(\r\n () => ({ index: 0 }),\r\n (state) => {\r\n if (state.index < collection.length) {\r\n return { done: false, value: collection[state.index++] };\r\n } else {\r\n return DONE_RESULT;\r\n }\r\n }\r\n );\r\n }\r\n }\r\n if (collections.length > 1) {\r\n type State = { collIndex: number, iterator?: Iterator, array?: ArrayLike, arrIndex: number };\r\n return new StreamImpl(\r\n () => ({ collIndex: 0, arrIndex: 0 }),\r\n (state) => {\r\n do {\r\n if (state.iterator) {\r\n const next = state.iterator.next();\r\n if (!next.done) {\r\n return next;\r\n }\r\n state.iterator = undefined;\r\n }\r\n if (state.array) {\r\n if (state.arrIndex < state.array.length) {\r\n return { done: false, value: state.array[state.arrIndex++] };\r\n }\r\n state.array = undefined;\r\n state.arrIndex = 0;\r\n }\r\n if (state.collIndex < collections.length) {\r\n const collection = collections[state.collIndex++];\r\n if (isIterable(collection)) {\r\n state.iterator = collection[Symbol.iterator]();\r\n } else if (collection && typeof collection.length === 'number') {\r\n state.array = collection;\r\n }\r\n }\r\n } while (state.iterator || state.array || state.collIndex < collections.length);\r\n return DONE_RESULT;\r\n }\r\n );\r\n }\r\n return EMPTY_STREAM;\r\n}\r\n\r\n/**\r\n * A tree iterator adds the ability to prune the current iteration.\r\n */\r\nexport interface TreeIterator extends IterableIterator {\r\n /**\r\n * Skip the whole subtree below the last returned element. The iteration continues as if that\r\n * element had no children.\r\n */\r\n prune(): void\r\n}\r\n\r\n/**\r\n * A tree stream is used to stream the elements of a tree, for example an AST or CST.\r\n */\r\nexport interface TreeStream extends Stream {\r\n iterator(): TreeIterator\r\n}\r\n\r\n/**\r\n * The default implementation of `TreeStream` takes a root element and a function that computes the\r\n * children of its argument. Whether the root node included in the stream is controlled with the\r\n * `includeRoot` option, which defaults to `false`.\r\n */\r\nexport class TreeStreamImpl\r\n extends StreamImpl<{ iterators: Array>, pruned: boolean }, T>\r\n implements TreeStream {\r\n\r\n constructor(root: T, children: (node: T) => Iterable, options?: { includeRoot?: boolean }) {\r\n super(\r\n () => ({\r\n iterators: options?.includeRoot ? [[root][Symbol.iterator]()] : [children(root)[Symbol.iterator]()],\r\n pruned: false\r\n }),\r\n state => {\r\n if (state.pruned) {\r\n state.iterators.pop();\r\n state.pruned = false;\r\n }\r\n while (state.iterators.length > 0) {\r\n const iterator = state.iterators[state.iterators.length - 1];\r\n const next = iterator.next();\r\n if (next.done) {\r\n state.iterators.pop();\r\n } else {\r\n state.iterators.push(children(next.value)[Symbol.iterator]());\r\n return next;\r\n }\r\n }\r\n return DONE_RESULT;\r\n }\r\n );\r\n }\r\n\r\n override iterator(): TreeIterator {\r\n const iterator = {\r\n state: this.startFn(),\r\n next: () => this.nextFn(iterator.state),\r\n prune: () => {\r\n iterator.state.pruned = true;\r\n },\r\n [Symbol.iterator]: () => iterator\r\n };\r\n return iterator;\r\n }\r\n}\r\n\r\n/**\r\n * A set of utility functions that reduce a stream to a single value.\r\n */\r\nexport namespace Reduction {\r\n\r\n /**\r\n * Compute the sum of a number stream.\r\n */\r\n export function sum(stream: Stream): number {\r\n return stream.reduce((a, b) => a + b, 0);\r\n }\r\n\r\n /**\r\n * Compute the product of a number stream.\r\n */\r\n export function product(stream: Stream): number {\r\n return stream.reduce((a, b) => a * b, 0);\r\n }\r\n\r\n /**\r\n * Compute the minimum of a number stream. Returns `undefined` if the stream is empty.\r\n */\r\n export function min(stream: Stream): number | undefined {\r\n return stream.reduce((a, b) => Math.min(a, b));\r\n }\r\n\r\n /**\r\n * Compute the maximum of a number stream. Returns `undefined` if the stream is empty.\r\n */\r\n export function max(stream: Stream): number | undefined {\r\n return stream.reduce((a, b) => Math.max(a, b));\r\n }\r\n\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021-2022 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport { assertUnreachable } from '../utils/errors.js';\r\nimport * as ast from '../languages/generated/ast.js';\r\nimport type { AstNode, CstNode } from '../syntax-tree.js';\r\nimport { isCompositeCstNode } from '../syntax-tree.js';\r\nimport { getContainerOfType, streamAllContents } from './ast-utils.js';\r\nimport { streamCst } from './cst-utils.js';\r\nimport { escapeRegExp, isWhitespace } from './regexp-utils.js';\r\n\r\n/**\r\n * Returns the entry rule of the given grammar, if any. If the grammar file does not contain an entry rule,\r\n * the result is `undefined`.\r\n */\r\nexport function getEntryRule(grammar: ast.Grammar): ast.ParserRule | undefined {\r\n return grammar.rules.find(e => ast.isParserRule(e) && e.entry) as ast.ParserRule;\r\n}\r\n\r\n/**\r\n * Returns all hidden terminal rules of the given grammar, if any.\r\n */\r\nexport function getHiddenRules(grammar: ast.Grammar) {\r\n return grammar.rules.filter((e): e is ast.TerminalRule => ast.isTerminalRule(e) && e.hidden);\r\n}\r\n\r\n/**\r\n * Returns all rules that can be reached from the topmost rules of the specified grammar (entry and hidden terminal rules).\r\n *\r\n * @param grammar The grammar that contains all rules\r\n * @param allTerminals Whether or not to include terminals that are referenced only by other terminals\r\n * @returns A list of referenced parser and terminal rules. If the grammar contains no entry rule,\r\n * this function returns all rules of the specified grammar.\r\n */\r\nexport function getAllReachableRules(grammar: ast.Grammar, allTerminals: boolean): Set {\r\n const ruleNames = new Set();\r\n const entryRule = getEntryRule(grammar);\r\n if (!entryRule) {\r\n return new Set(grammar.rules);\r\n }\r\n\r\n const topMostRules = [entryRule as ast.AbstractRule].concat(getHiddenRules(grammar));\r\n for (const rule of topMostRules) {\r\n ruleDfs(rule, ruleNames, allTerminals);\r\n }\r\n\r\n const rules = new Set();\r\n for (const rule of grammar.rules) {\r\n if (ruleNames.has(rule.name) || (ast.isTerminalRule(rule) && rule.hidden)) {\r\n rules.add(rule);\r\n }\r\n }\r\n return rules;\r\n}\r\n\r\nfunction ruleDfs(rule: ast.AbstractRule, visitedSet: Set, allTerminals: boolean): void {\r\n visitedSet.add(rule.name);\r\n streamAllContents(rule).forEach(node => {\r\n if (ast.isRuleCall(node) || (allTerminals && ast.isTerminalRuleCall(node))) {\r\n const refRule = node.rule.ref;\r\n if (refRule && !visitedSet.has(refRule.name)) {\r\n ruleDfs(refRule, visitedSet, allTerminals);\r\n }\r\n }\r\n });\r\n}\r\n\r\n/**\r\n * Determines the grammar expression used to parse a cross-reference (usually a reference to a terminal rule).\r\n * A cross-reference can declare this expression explicitly in the form `[Type : Terminal]`, but if `Terminal`\r\n * is omitted, this function attempts to infer it from the name of the referenced `Type` (using `findNameAssignment`).\r\n *\r\n * Returns the grammar expression used to parse the given cross-reference, or `undefined` if it is not declared\r\n * and cannot be inferred.\r\n */\r\nexport function getCrossReferenceTerminal(crossRef: ast.CrossReference): ast.AbstractElement | undefined {\r\n if (crossRef.terminal) {\r\n return crossRef.terminal;\r\n } else if (crossRef.type.ref) {\r\n const nameAssigment = findNameAssignment(crossRef.type.ref);\r\n return nameAssigment?.terminal;\r\n }\r\n return undefined;\r\n}\r\n\r\n/**\r\n * Determines whether the given terminal rule represents a comment. This is true if the rule is marked\r\n * as `hidden` and it does not match white space. This means every hidden token (i.e. excluded from the AST)\r\n * that contains visible characters is considered a comment.\r\n */\r\nexport function isCommentTerminal(terminalRule: ast.TerminalRule): boolean {\r\n return terminalRule.hidden && !isWhitespace(terminalRegex(terminalRule));\r\n}\r\n\r\n/**\r\n * Find all CST nodes within the given node that contribute to the specified property.\r\n *\r\n * @param node A CST node in which to look for property assignments. If this is undefined, the result is an empty array.\r\n * @param property A property name of the constructed AST node. If this is undefined, the result is an empty array.\r\n */\r\nexport function findNodesForProperty(node: CstNode | undefined, property: string | undefined): CstNode[] {\r\n if (!node || !property) {\r\n return [];\r\n }\r\n return findNodesForPropertyInternal(node, property, node.astNode, true);\r\n}\r\n\r\n/**\r\n * Find a single CST node within the given node that contributes to the specified property.\r\n *\r\n * @param node A CST node in which to look for property assignments. If this is undefined, the result is `undefined`.\r\n * @param property A property name of the constructed AST node. If this is undefined, the result is `undefined`.\r\n * @param index If no index is specified or the index is less than zero, the first found node is returned. If the\r\n * specified index exceeds the number of assignments to the property, the last found node is returned. Otherwise,\r\n * the node with the specified index is returned.\r\n */\r\nexport function findNodeForProperty(node: CstNode | undefined, property: string | undefined, index?: number): CstNode | undefined {\r\n if (!node || !property) {\r\n return undefined;\r\n }\r\n const nodes = findNodesForPropertyInternal(node, property, node.astNode, true);\r\n if (nodes.length === 0) {\r\n return undefined;\r\n }\r\n if (index !== undefined) {\r\n index = Math.max(0, Math.min(index, nodes.length - 1));\r\n } else {\r\n index = 0;\r\n }\r\n return nodes[index];\r\n}\r\n\r\nfunction findNodesForPropertyInternal(node: CstNode, property: string, element: AstNode | undefined, first: boolean): CstNode[] {\r\n if (!first) {\r\n const nodeFeature = getContainerOfType(node.grammarSource, ast.isAssignment);\r\n if (nodeFeature && nodeFeature.feature === property) {\r\n return [node];\r\n }\r\n }\r\n if (isCompositeCstNode(node) && node.astNode === element) {\r\n return node.content.flatMap(e => findNodesForPropertyInternal(e, property, element, false));\r\n }\r\n return [];\r\n}\r\n\r\n/**\r\n * Find all CST nodes within the given node that correspond to the specified keyword.\r\n *\r\n * @param node A CST node in which to look for keywords. If this is undefined, the result is an empty array.\r\n * @param keyword A keyword as specified in the grammar.\r\n */\r\nexport function findNodesForKeyword(node: CstNode | undefined, keyword: string): CstNode[] {\r\n if (!node) {\r\n return [];\r\n }\r\n return findNodesForKeywordInternal(node, keyword, node?.astNode);\r\n}\r\n\r\n/**\r\n * Find a single CST node within the given node that corresponds to the specified keyword.\r\n *\r\n * @param node A CST node in which to look for keywords. If this is undefined, the result is `undefined`.\r\n * @param keyword A keyword as specified in the grammar.\r\n * @param index If no index is specified or the index is less than zero, the first found node is returned. If the\r\n * specified index exceeds the number of keyword occurrences, the last found node is returned. Otherwise,\r\n * the node with the specified index is returned.\r\n */\r\nexport function findNodeForKeyword(node: CstNode | undefined, keyword: string, index?: number): CstNode | undefined {\r\n if (!node) {\r\n return undefined;\r\n }\r\n const nodes = findNodesForKeywordInternal(node, keyword, node?.astNode);\r\n if (nodes.length === 0) {\r\n return undefined;\r\n }\r\n if (index !== undefined) {\r\n index = Math.max(0, Math.min(index, nodes.length - 1));\r\n } else {\r\n index = 0;\r\n }\r\n return nodes[index];\r\n}\r\n\r\nexport function findNodesForKeywordInternal(node: CstNode, keyword: string, element: AstNode | undefined): CstNode[] {\r\n if (node.astNode !== element) {\r\n return [];\r\n }\r\n if (ast.isKeyword(node.grammarSource) && node.grammarSource.value === keyword) {\r\n return [node];\r\n }\r\n const treeIterator = streamCst(node).iterator();\r\n let result: IteratorResult;\r\n const keywordNodes: CstNode[] = [];\r\n do {\r\n result = treeIterator.next();\r\n if (!result.done) {\r\n const childNode = result.value;\r\n if (childNode.astNode === element) {\r\n if (ast.isKeyword(childNode.grammarSource) && childNode.grammarSource.value === keyword) {\r\n keywordNodes.push(childNode);\r\n }\r\n } else {\r\n treeIterator.prune();\r\n }\r\n }\r\n } while (!result.done);\r\n return keywordNodes;\r\n}\r\n\r\n/**\r\n * If the given CST node was parsed in the context of a property assignment, the respective `Assignment` grammar\r\n * node is returned. If no assignment is found, the result is `undefined`.\r\n *\r\n * @param cstNode A CST node for which to find a property assignment.\r\n */\r\nexport function findAssignment(cstNode: CstNode): ast.Assignment | undefined {\r\n const astNode = cstNode.astNode;\r\n // Only search until the ast node of the parent cst node is no longer the original ast node\r\n // This would make us jump to a preceding rule call, which contains only unrelated assignments\r\n while (astNode === cstNode.container?.astNode) {\r\n const assignment = getContainerOfType(cstNode.grammarSource, ast.isAssignment);\r\n if (assignment) {\r\n return assignment;\r\n }\r\n cstNode = cstNode.container;\r\n }\r\n return undefined;\r\n}\r\n\r\n/**\r\n * Find an assignment to the `name` property for the given grammar type. This requires the `type` to be inferred\r\n * from a parser rule, and that rule must contain an assignment to the `name` property. In all other cases,\r\n * this function returns `undefined`.\r\n */\r\nexport function findNameAssignment(type: ast.AbstractType): ast.Assignment | undefined {\r\n let startNode: AstNode = type;\r\n if (ast.isInferredType(startNode)) {\r\n // for inferred types, the location to start searching for the name-assignment is different\r\n if (ast.isAction(startNode.$container)) {\r\n // a type which is explicitly inferred by an action: investigate the sibbling of the Action node, i.e. start searching at the Action's parent\r\n startNode = startNode.$container.$container!;\r\n } else if (ast.isParserRule(startNode.$container)) {\r\n // investigate the parser rule with the explicitly inferred type\r\n startNode = startNode.$container;\r\n } else {\r\n assertUnreachable(startNode.$container);\r\n }\r\n }\r\n return findNameAssignmentInternal(type, startNode, new Map());\r\n}\r\n\r\nfunction findNameAssignmentInternal(type: ast.AbstractType, startNode: AstNode, cache: Map): ast.Assignment | undefined {\r\n // the cache is only required to prevent infinite loops\r\n function go(node: AstNode, refType: ast.AbstractType): ast.Assignment | undefined {\r\n let childAssignment: ast.Assignment | undefined = undefined;\r\n const parentAssignment = getContainerOfType(node, ast.isAssignment);\r\n // No parent assignment implies unassigned rule call\r\n if (!parentAssignment) {\r\n childAssignment = findNameAssignmentInternal(refType, refType, cache);\r\n }\r\n cache.set(type, childAssignment);\r\n return childAssignment;\r\n }\r\n\r\n if (cache.has(type)) {\r\n return cache.get(type);\r\n }\r\n cache.set(type, undefined);\r\n for (const node of streamAllContents(startNode)) {\r\n if (ast.isAssignment(node) && node.feature.toLowerCase() === 'name') {\r\n cache.set(type, node);\r\n return node;\r\n } else if (ast.isRuleCall(node) && ast.isParserRule(node.rule.ref)) {\r\n return go(node, node.rule.ref);\r\n } else if (ast.isSimpleType(node) && node.typeRef?.ref) {\r\n return go(node, node.typeRef.ref);\r\n }\r\n }\r\n return undefined;\r\n}\r\n\r\nexport function getActionAtElement(element: ast.AbstractElement): ast.Action | undefined {\r\n const parent = element.$container;\r\n if (ast.isGroup(parent)) {\r\n const elements = parent.elements;\r\n const index = elements.indexOf(element);\r\n for (let i = index - 1; i >= 0; i--) {\r\n const item = elements[i];\r\n if (ast.isAction(item)) {\r\n return item;\r\n } else {\r\n const action = streamAllContents(elements[i]).find(ast.isAction);\r\n if (action) {\r\n return action;\r\n }\r\n }\r\n }\r\n }\r\n if (ast.isAbstractElement(parent)) {\r\n return getActionAtElement(parent);\r\n } else {\r\n return undefined;\r\n }\r\n}\r\n\r\nexport type Cardinality = '?' | '*' | '+' | undefined;\r\nexport type Operator = '=' | '+=' | '?=' | undefined;\r\n\r\nexport function isOptionalCardinality(cardinality?: Cardinality, element?: ast.AbstractElement): boolean {\r\n return cardinality === '?' || cardinality === '*' || (ast.isGroup(element) && Boolean(element.guardCondition));\r\n}\r\n\r\nexport function isArrayCardinality(cardinality?: Cardinality): boolean {\r\n return cardinality === '*' || cardinality === '+';\r\n}\r\n\r\nexport function isArrayOperator(operator?: Operator): boolean {\r\n return operator === '+=';\r\n}\r\n\r\n/**\r\n * Determines whether the given parser rule is a _data type rule_, meaning that it has a\r\n * primitive return type like `number`, `boolean`, etc.\r\n */\r\nexport function isDataTypeRule(rule: ast.ParserRule): boolean {\r\n return isDataTypeRuleInternal(rule, new Set());\r\n}\r\n\r\nfunction isDataTypeRuleInternal(rule: ast.ParserRule, visited: Set): boolean {\r\n if (visited.has(rule)) {\r\n return true;\r\n } else {\r\n visited.add(rule);\r\n }\r\n for (const node of streamAllContents(rule)) {\r\n if (ast.isRuleCall(node)) {\r\n if (!node.rule.ref) {\r\n // RuleCall to unresolved rule. Don't assume `rule` is a DataType rule.\r\n return false;\r\n }\r\n if (ast.isParserRule(node.rule.ref) && !isDataTypeRuleInternal(node.rule.ref, visited)) {\r\n return false;\r\n }\r\n } else if (ast.isAssignment(node)) {\r\n return false;\r\n } else if (ast.isAction(node)) {\r\n return false;\r\n }\r\n }\r\n return Boolean(rule.definition);\r\n}\r\n\r\nexport function isDataType(type: ast.Type): boolean {\r\n return isDataTypeInternal(type.type, new Set());\r\n}\r\n\r\nfunction isDataTypeInternal(type: ast.TypeDefinition, visited: Set): boolean {\r\n if (visited.has(type)) {\r\n return true;\r\n } else {\r\n visited.add(type);\r\n }\r\n if (ast.isArrayType(type)) {\r\n return false;\r\n } else if (ast.isReferenceType(type)) {\r\n return false;\r\n } else if (ast.isUnionType(type)) {\r\n return type.types.every(e => isDataTypeInternal(e, visited));\r\n } else if (ast.isSimpleType(type)) {\r\n if (type.primitiveType !== undefined) {\r\n return true;\r\n } else if (type.stringType !== undefined) {\r\n return true;\r\n } else if (type.typeRef !== undefined) {\r\n const ref = type.typeRef.ref;\r\n if (ast.isType(ref)) {\r\n return isDataTypeInternal(ref.type, visited);\r\n } else {\r\n return false;\r\n }\r\n } else {\r\n return false;\r\n }\r\n } else {\r\n return false;\r\n }\r\n}\r\n\r\nexport function getExplicitRuleType(rule: ast.ParserRule): string | undefined {\r\n if (rule.inferredType) {\r\n return rule.inferredType.name;\r\n } else if (rule.dataType) {\r\n return rule.dataType;\r\n } else if (rule.returnType) {\r\n const refType = rule.returnType.ref;\r\n if (refType) {\r\n // check if we need to check Action as return type\r\n if (ast.isParserRule(refType)) {\r\n return refType.name;\r\n } else if (ast.isInterface(refType) || ast.isType(refType)) {\r\n return refType.name;\r\n }\r\n }\r\n }\r\n return undefined;\r\n}\r\n\r\nexport function getTypeName(type: ast.AbstractType | ast.Action): string {\r\n if (ast.isParserRule(type)) {\r\n return isDataTypeRule(type) ? type.name : getExplicitRuleType(type) ?? type.name;\r\n } else if (ast.isInterface(type) || ast.isType(type) || ast.isReturnType(type)) {\r\n return type.name;\r\n } else if (ast.isAction(type)) {\r\n const actionType = getActionType(type);\r\n if (actionType) {\r\n return actionType;\r\n }\r\n } else if (ast.isInferredType(type)) {\r\n return type.name;\r\n }\r\n throw new Error('Cannot get name of Unknown Type');\r\n}\r\n\r\nexport function getActionType(action: ast.Action): string | undefined {\r\n if (action.inferredType) {\r\n return action.inferredType.name;\r\n } else if (action.type?.ref) {\r\n return getTypeName(action.type.ref);\r\n }\r\n return undefined; // not inferring and not referencing a valid type\r\n}\r\n\r\n/**\r\n * This function is used at development time (for code generation and the internal type system) to get the type of the AST node produced by the given rule.\r\n * For data type rules, the name of the rule is returned,\r\n * e.g. \"INT_value returns number: MY_INT;\" returns \"INT_value\".\r\n * @param rule the given rule\r\n * @returns the name of the AST node type of the rule\r\n */\r\nexport function getRuleTypeName(rule: ast.AbstractRule): string {\r\n if (ast.isTerminalRule(rule)) {\r\n return rule.type?.name ?? 'string';\r\n } else {\r\n return isDataTypeRule(rule) ? rule.name : getExplicitRuleType(rule) ?? rule.name;\r\n }\r\n}\r\n\r\n/**\r\n * This function is used at runtime to get the actual type of the values produced by the given rule at runtime.\r\n * For data type rules, the name of the declared return type of the rule is returned (if any),\r\n * e.g. \"INT_value returns number: MY_INT;\" returns \"number\".\r\n * @param rule the given rule\r\n * @returns the name of the type of the produced values of the rule at runtime\r\n */\r\nexport function getRuleType(rule: ast.AbstractRule): string {\r\n if (ast.isTerminalRule(rule)) {\r\n return rule.type?.name ?? 'string';\r\n } else {\r\n return getExplicitRuleType(rule) ?? rule.name;\r\n }\r\n}\r\n\r\nexport function terminalRegex(terminalRule: ast.TerminalRule): RegExp {\r\n const flags: Flags = {\r\n s: false,\r\n i: false,\r\n u: false\r\n };\r\n const source = abstractElementToRegex(terminalRule.definition, flags);\r\n const flagText = Object.entries(flags).filter(([, value]) => value).map(([name]) => name).join('');\r\n return new RegExp(source, flagText);\r\n}\r\n\r\n// Using [\\s\\S]* allows to match everything, compared to . which doesn't match line terminators\r\nconst WILDCARD = /[\\s\\S]/.source;\r\n\r\ntype Flags = {\r\n s: boolean;\r\n i: boolean;\r\n u: boolean;\r\n}\r\n\r\nfunction abstractElementToRegex(element: ast.AbstractElement, flags?: Flags): string {\r\n if (ast.isTerminalAlternatives(element)) {\r\n return terminalAlternativesToRegex(element);\r\n } else if (ast.isTerminalGroup(element)) {\r\n return terminalGroupToRegex(element);\r\n } else if (ast.isCharacterRange(element)) {\r\n return characterRangeToRegex(element);\r\n } else if (ast.isTerminalRuleCall(element)) {\r\n const rule = element.rule.ref;\r\n if (!rule) {\r\n throw new Error('Missing rule reference.');\r\n }\r\n return withCardinality(abstractElementToRegex(rule.definition), {\r\n cardinality: element.cardinality,\r\n lookahead: element.lookahead\r\n });\r\n } else if (ast.isNegatedToken(element)) {\r\n return negateTokenToRegex(element);\r\n } else if (ast.isUntilToken(element)) {\r\n return untilTokenToRegex(element);\r\n } else if (ast.isRegexToken(element)) {\r\n const lastSlash = element.regex.lastIndexOf('/');\r\n const source = element.regex.substring(1, lastSlash);\r\n const regexFlags = element.regex.substring(lastSlash + 1);\r\n if (flags) {\r\n flags.i = regexFlags.includes('i');\r\n flags.s = regexFlags.includes('s');\r\n flags.u = regexFlags.includes('u');\r\n }\r\n return withCardinality(source, {\r\n cardinality: element.cardinality,\r\n lookahead: element.lookahead,\r\n wrap: false\r\n });\r\n } else if (ast.isWildcard(element)) {\r\n return withCardinality(WILDCARD, {\r\n cardinality: element.cardinality,\r\n lookahead: element.lookahead\r\n });\r\n } else {\r\n throw new Error(`Invalid terminal element: ${element?.$type}`);\r\n }\r\n}\r\n\r\nfunction terminalAlternativesToRegex(alternatives: ast.TerminalAlternatives): string {\r\n return withCardinality(alternatives.elements.map(e => abstractElementToRegex(e)).join('|'), {\r\n cardinality: alternatives.cardinality,\r\n lookahead: alternatives.lookahead\r\n });\r\n}\r\n\r\nfunction terminalGroupToRegex(group: ast.TerminalGroup): string {\r\n return withCardinality(group.elements.map(e => abstractElementToRegex(e)).join(''), {\r\n cardinality: group.cardinality,\r\n lookahead: group.lookahead\r\n });\r\n}\r\n\r\nfunction untilTokenToRegex(until: ast.UntilToken): string {\r\n return withCardinality(`${WILDCARD}*?${abstractElementToRegex(until.terminal)}`, {\r\n cardinality: until.cardinality,\r\n lookahead: until.lookahead\r\n });\r\n}\r\n\r\nfunction negateTokenToRegex(negate: ast.NegatedToken): string {\r\n return withCardinality(`(?!${abstractElementToRegex(negate.terminal)})${WILDCARD}*?`, {\r\n cardinality: negate.cardinality,\r\n lookahead: negate.lookahead\r\n });\r\n}\r\n\r\nfunction characterRangeToRegex(range: ast.CharacterRange): string {\r\n if (range.right) {\r\n return withCardinality(`[${keywordToRegex(range.left)}-${keywordToRegex(range.right)}]`, {\r\n cardinality: range.cardinality,\r\n lookahead: range.lookahead,\r\n wrap: false\r\n });\r\n }\r\n return withCardinality(keywordToRegex(range.left), {\r\n cardinality: range.cardinality,\r\n lookahead: range.lookahead,\r\n wrap: false\r\n });\r\n}\r\n\r\nfunction keywordToRegex(keyword: ast.Keyword): string {\r\n return escapeRegExp(keyword.value);\r\n}\r\n\r\nfunction withCardinality(regex: string, options: {\r\n cardinality?: string\r\n wrap?: boolean\r\n lookahead?: string\r\n}): string {\r\n if (options.wrap !== false || options.lookahead) {\r\n regex = `(${options.lookahead ?? ''}${regex})`;\r\n }\r\n if (options.cardinality) {\r\n return `${regex}${options.cardinality}`;\r\n }\r\n return regex;\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { CstNode } from '../syntax-tree.js';\r\n\r\nexport class ErrorWithLocation extends Error {\r\n constructor(node: CstNode | undefined, message: string) {\r\n super(node ? `${message} at ${node.range.start.line}:${node.range.start.character}` : message);\r\n }\r\n}\r\n\r\nexport function assertUnreachable(_: never): never {\r\n throw new Error('Error! The input value was not handled.');\r\n}\r\n", "/******************************************************************************\r\n * This file was generated by langium-cli 3.3.0.\r\n * DO NOT EDIT MANUALLY!\r\n ******************************************************************************/\r\n\r\n/* eslint-disable */\r\nimport type { AstNode, Reference, ReferenceInfo, TypeMetaData } from '../../syntax-tree.js';\r\nimport { AbstractAstReflection } from '../../syntax-tree.js';\r\n\r\nexport const LangiumGrammarTerminals = {\r\n ID: /\\^?[_a-zA-Z][\\w_]*/,\r\n STRING: /\"(\\\\.|[^\"\\\\])*\"|'(\\\\.|[^'\\\\])*'/,\r\n NUMBER: /NaN|-?((\\d*\\.\\d+|\\d+)([Ee][+-]?\\d+)?|Infinity)/,\r\n RegexLiteral: /\\/(?![*+?])(?:[^\\r\\n\\[/\\\\]|\\\\.|\\[(?:[^\\r\\n\\]\\\\]|\\\\.)*\\])+\\/[a-z]*/,\r\n WS: /\\s+/,\r\n ML_COMMENT: /\\/\\*[\\s\\S]*?\\*\\//,\r\n SL_COMMENT: /\\/\\/[^\\n\\r]*/,\r\n};\r\n\r\nexport type LangiumGrammarTerminalNames = keyof typeof LangiumGrammarTerminals;\r\n\r\nexport type LangiumGrammarKeywordNames = \r\n | \"!\"\r\n | \"&\"\r\n | \"(\"\r\n | \")\"\r\n | \"*\"\r\n | \"+\"\r\n | \"+=\"\r\n | \",\"\r\n | \"->\"\r\n | \".\"\r\n | \"..\"\r\n | \":\"\r\n | \";\"\r\n | \"<\"\r\n | \"=\"\r\n | \"=>\"\r\n | \">\"\r\n | \"?\"\r\n | \"?!\"\r\n | \"?;\r\n}\r\n\r\nexport const ArrayLiteral = 'ArrayLiteral';\r\n\r\nexport function isArrayLiteral(item: unknown): item is ArrayLiteral {\r\n return reflection.isInstance(item, ArrayLiteral);\r\n}\r\n\r\nexport interface ArrayType extends AstNode {\r\n readonly $container: ArrayType | ReferenceType | Type | TypeAttribute | UnionType;\r\n readonly $type: 'ArrayType';\r\n elementType: TypeDefinition;\r\n}\r\n\r\nexport const ArrayType = 'ArrayType';\r\n\r\nexport function isArrayType(item: unknown): item is ArrayType {\r\n return reflection.isInstance(item, ArrayType);\r\n}\r\n\r\nexport interface BooleanLiteral extends AstNode {\r\n readonly $container: ArrayLiteral | Conjunction | Disjunction | Group | NamedArgument | Negation | TypeAttribute;\r\n readonly $type: 'BooleanLiteral';\r\n true: boolean;\r\n}\r\n\r\nexport const BooleanLiteral = 'BooleanLiteral';\r\n\r\nexport function isBooleanLiteral(item: unknown): item is BooleanLiteral {\r\n return reflection.isInstance(item, BooleanLiteral);\r\n}\r\n\r\nexport interface Conjunction extends AstNode {\r\n readonly $container: Conjunction | Disjunction | Group | NamedArgument | Negation;\r\n readonly $type: 'Conjunction';\r\n left: Condition;\r\n right: Condition;\r\n}\r\n\r\nexport const Conjunction = 'Conjunction';\r\n\r\nexport function isConjunction(item: unknown): item is Conjunction {\r\n return reflection.isInstance(item, Conjunction);\r\n}\r\n\r\nexport interface Disjunction extends AstNode {\r\n readonly $container: Conjunction | Disjunction | Group | NamedArgument | Negation;\r\n readonly $type: 'Disjunction';\r\n left: Condition;\r\n right: Condition;\r\n}\r\n\r\nexport const Disjunction = 'Disjunction';\r\n\r\nexport function isDisjunction(item: unknown): item is Disjunction {\r\n return reflection.isInstance(item, Disjunction);\r\n}\r\n\r\nexport interface Grammar extends AstNode {\r\n readonly $type: 'Grammar';\r\n definesHiddenTokens: boolean;\r\n hiddenTokens: Array>;\r\n imports: Array;\r\n interfaces: Array;\r\n isDeclared: boolean;\r\n name?: string;\r\n rules: Array;\r\n types: Array;\r\n usedGrammars: Array>;\r\n}\r\n\r\nexport const Grammar = 'Grammar';\r\n\r\nexport function isGrammar(item: unknown): item is Grammar {\r\n return reflection.isInstance(item, Grammar);\r\n}\r\n\r\nexport interface GrammarImport extends AstNode {\r\n readonly $container: Grammar;\r\n readonly $type: 'GrammarImport';\r\n path: string;\r\n}\r\n\r\nexport const GrammarImport = 'GrammarImport';\r\n\r\nexport function isGrammarImport(item: unknown): item is GrammarImport {\r\n return reflection.isInstance(item, GrammarImport);\r\n}\r\n\r\nexport interface InferredType extends AstNode {\r\n readonly $container: Action | ParserRule;\r\n readonly $type: 'InferredType';\r\n name: string;\r\n}\r\n\r\nexport const InferredType = 'InferredType';\r\n\r\nexport function isInferredType(item: unknown): item is InferredType {\r\n return reflection.isInstance(item, InferredType);\r\n}\r\n\r\nexport interface Interface extends AstNode {\r\n readonly $container: Grammar;\r\n readonly $type: 'Interface';\r\n attributes: Array;\r\n name: string;\r\n superTypes: Array>;\r\n}\r\n\r\nexport const Interface = 'Interface';\r\n\r\nexport function isInterface(item: unknown): item is Interface {\r\n return reflection.isInstance(item, Interface);\r\n}\r\n\r\nexport interface NamedArgument extends AstNode {\r\n readonly $container: RuleCall;\r\n readonly $type: 'NamedArgument';\r\n calledByName: boolean;\r\n parameter?: Reference;\r\n value: Condition;\r\n}\r\n\r\nexport const NamedArgument = 'NamedArgument';\r\n\r\nexport function isNamedArgument(item: unknown): item is NamedArgument {\r\n return reflection.isInstance(item, NamedArgument);\r\n}\r\n\r\nexport interface Negation extends AstNode {\r\n readonly $container: Conjunction | Disjunction | Group | NamedArgument | Negation;\r\n readonly $type: 'Negation';\r\n value: Condition;\r\n}\r\n\r\nexport const Negation = 'Negation';\r\n\r\nexport function isNegation(item: unknown): item is Negation {\r\n return reflection.isInstance(item, Negation);\r\n}\r\n\r\nexport interface NumberLiteral extends AstNode {\r\n readonly $container: ArrayLiteral | TypeAttribute;\r\n readonly $type: 'NumberLiteral';\r\n value: number;\r\n}\r\n\r\nexport const NumberLiteral = 'NumberLiteral';\r\n\r\nexport function isNumberLiteral(item: unknown): item is NumberLiteral {\r\n return reflection.isInstance(item, NumberLiteral);\r\n}\r\n\r\nexport interface Parameter extends AstNode {\r\n readonly $container: ParserRule;\r\n readonly $type: 'Parameter';\r\n name: string;\r\n}\r\n\r\nexport const Parameter = 'Parameter';\r\n\r\nexport function isParameter(item: unknown): item is Parameter {\r\n return reflection.isInstance(item, Parameter);\r\n}\r\n\r\nexport interface ParameterReference extends AstNode {\r\n readonly $container: Conjunction | Disjunction | Group | NamedArgument | Negation;\r\n readonly $type: 'ParameterReference';\r\n parameter: Reference;\r\n}\r\n\r\nexport const ParameterReference = 'ParameterReference';\r\n\r\nexport function isParameterReference(item: unknown): item is ParameterReference {\r\n return reflection.isInstance(item, ParameterReference);\r\n}\r\n\r\nexport interface ParserRule extends AstNode {\r\n readonly $container: Grammar;\r\n readonly $type: 'ParserRule';\r\n dataType?: PrimitiveType;\r\n definesHiddenTokens: boolean;\r\n definition: AbstractElement;\r\n entry: boolean;\r\n fragment: boolean;\r\n hiddenTokens: Array>;\r\n inferredType?: InferredType;\r\n name: string;\r\n parameters: Array;\r\n returnType?: Reference;\r\n wildcard: boolean;\r\n}\r\n\r\nexport const ParserRule = 'ParserRule';\r\n\r\nexport function isParserRule(item: unknown): item is ParserRule {\r\n return reflection.isInstance(item, ParserRule);\r\n}\r\n\r\nexport interface ReferenceType extends AstNode {\r\n readonly $container: ArrayType | ReferenceType | Type | TypeAttribute | UnionType;\r\n readonly $type: 'ReferenceType';\r\n referenceType: TypeDefinition;\r\n}\r\n\r\nexport const ReferenceType = 'ReferenceType';\r\n\r\nexport function isReferenceType(item: unknown): item is ReferenceType {\r\n return reflection.isInstance(item, ReferenceType);\r\n}\r\n\r\nexport interface ReturnType extends AstNode {\r\n readonly $container: TerminalRule;\r\n readonly $type: 'ReturnType';\r\n name: PrimitiveType | string;\r\n}\r\n\r\nexport const ReturnType = 'ReturnType';\r\n\r\nexport function isReturnType(item: unknown): item is ReturnType {\r\n return reflection.isInstance(item, ReturnType);\r\n}\r\n\r\nexport interface SimpleType extends AstNode {\r\n readonly $container: ArrayType | ReferenceType | Type | TypeAttribute | UnionType;\r\n readonly $type: 'SimpleType';\r\n primitiveType?: PrimitiveType;\r\n stringType?: string;\r\n typeRef?: Reference;\r\n}\r\n\r\nexport const SimpleType = 'SimpleType';\r\n\r\nexport function isSimpleType(item: unknown): item is SimpleType {\r\n return reflection.isInstance(item, SimpleType);\r\n}\r\n\r\nexport interface StringLiteral extends AstNode {\r\n readonly $container: ArrayLiteral | TypeAttribute;\r\n readonly $type: 'StringLiteral';\r\n value: string;\r\n}\r\n\r\nexport const StringLiteral = 'StringLiteral';\r\n\r\nexport function isStringLiteral(item: unknown): item is StringLiteral {\r\n return reflection.isInstance(item, StringLiteral);\r\n}\r\n\r\nexport interface TerminalRule extends AstNode {\r\n readonly $container: Grammar;\r\n readonly $type: 'TerminalRule';\r\n definition: AbstractElement;\r\n fragment: boolean;\r\n hidden: boolean;\r\n name: string;\r\n type?: ReturnType;\r\n}\r\n\r\nexport const TerminalRule = 'TerminalRule';\r\n\r\nexport function isTerminalRule(item: unknown): item is TerminalRule {\r\n return reflection.isInstance(item, TerminalRule);\r\n}\r\n\r\nexport interface Type extends AstNode {\r\n readonly $container: Grammar;\r\n readonly $type: 'Type';\r\n name: string;\r\n type: TypeDefinition;\r\n}\r\n\r\nexport const Type = 'Type';\r\n\r\nexport function isType(item: unknown): item is Type {\r\n return reflection.isInstance(item, Type);\r\n}\r\n\r\nexport interface TypeAttribute extends AstNode {\r\n readonly $container: Interface;\r\n readonly $type: 'TypeAttribute';\r\n defaultValue?: ValueLiteral;\r\n isOptional: boolean;\r\n name: FeatureName;\r\n type: TypeDefinition;\r\n}\r\n\r\nexport const TypeAttribute = 'TypeAttribute';\r\n\r\nexport function isTypeAttribute(item: unknown): item is TypeAttribute {\r\n return reflection.isInstance(item, TypeAttribute);\r\n}\r\n\r\nexport interface UnionType extends AstNode {\r\n readonly $container: ArrayType | ReferenceType | Type | TypeAttribute | UnionType;\r\n readonly $type: 'UnionType';\r\n types: Array;\r\n}\r\n\r\nexport const UnionType = 'UnionType';\r\n\r\nexport function isUnionType(item: unknown): item is UnionType {\r\n return reflection.isInstance(item, UnionType);\r\n}\r\n\r\nexport interface Action extends AbstractElement {\r\n readonly $type: 'Action';\r\n feature?: FeatureName;\r\n inferredType?: InferredType;\r\n operator?: '+=' | '=';\r\n type?: Reference;\r\n}\r\n\r\nexport const Action = 'Action';\r\n\r\nexport function isAction(item: unknown): item is Action {\r\n return reflection.isInstance(item, Action);\r\n}\r\n\r\nexport interface Alternatives extends AbstractElement {\r\n readonly $type: 'Alternatives';\r\n elements: Array;\r\n}\r\n\r\nexport const Alternatives = 'Alternatives';\r\n\r\nexport function isAlternatives(item: unknown): item is Alternatives {\r\n return reflection.isInstance(item, Alternatives);\r\n}\r\n\r\nexport interface Assignment extends AbstractElement {\r\n readonly $type: 'Assignment';\r\n feature: FeatureName;\r\n operator: '+=' | '=' | '?=';\r\n terminal: AbstractElement;\r\n}\r\n\r\nexport const Assignment = 'Assignment';\r\n\r\nexport function isAssignment(item: unknown): item is Assignment {\r\n return reflection.isInstance(item, Assignment);\r\n}\r\n\r\nexport interface CharacterRange extends AbstractElement {\r\n readonly $type: 'CharacterRange';\r\n left: Keyword;\r\n right?: Keyword;\r\n}\r\n\r\nexport const CharacterRange = 'CharacterRange';\r\n\r\nexport function isCharacterRange(item: unknown): item is CharacterRange {\r\n return reflection.isInstance(item, CharacterRange);\r\n}\r\n\r\nexport interface CrossReference extends AbstractElement {\r\n readonly $type: 'CrossReference';\r\n deprecatedSyntax: boolean;\r\n terminal?: AbstractElement;\r\n type: Reference;\r\n}\r\n\r\nexport const CrossReference = 'CrossReference';\r\n\r\nexport function isCrossReference(item: unknown): item is CrossReference {\r\n return reflection.isInstance(item, CrossReference);\r\n}\r\n\r\nexport interface EndOfFile extends AbstractElement {\r\n readonly $type: 'EndOfFile';\r\n}\r\n\r\nexport const EndOfFile = 'EndOfFile';\r\n\r\nexport function isEndOfFile(item: unknown): item is EndOfFile {\r\n return reflection.isInstance(item, EndOfFile);\r\n}\r\n\r\nexport interface Group extends AbstractElement {\r\n readonly $type: 'Group';\r\n elements: Array;\r\n guardCondition?: Condition;\r\n}\r\n\r\nexport const Group = 'Group';\r\n\r\nexport function isGroup(item: unknown): item is Group {\r\n return reflection.isInstance(item, Group);\r\n}\r\n\r\nexport interface Keyword extends AbstractElement {\r\n readonly $container: CharacterRange;\r\n readonly $type: 'Keyword';\r\n value: string;\r\n}\r\n\r\nexport const Keyword = 'Keyword';\r\n\r\nexport function isKeyword(item: unknown): item is Keyword {\r\n return reflection.isInstance(item, Keyword);\r\n}\r\n\r\nexport interface NegatedToken extends AbstractElement {\r\n readonly $type: 'NegatedToken';\r\n terminal: AbstractElement;\r\n}\r\n\r\nexport const NegatedToken = 'NegatedToken';\r\n\r\nexport function isNegatedToken(item: unknown): item is NegatedToken {\r\n return reflection.isInstance(item, NegatedToken);\r\n}\r\n\r\nexport interface RegexToken extends AbstractElement {\r\n readonly $type: 'RegexToken';\r\n regex: string;\r\n}\r\n\r\nexport const RegexToken = 'RegexToken';\r\n\r\nexport function isRegexToken(item: unknown): item is RegexToken {\r\n return reflection.isInstance(item, RegexToken);\r\n}\r\n\r\nexport interface RuleCall extends AbstractElement {\r\n readonly $type: 'RuleCall';\r\n arguments: Array;\r\n rule: Reference;\r\n}\r\n\r\nexport const RuleCall = 'RuleCall';\r\n\r\nexport function isRuleCall(item: unknown): item is RuleCall {\r\n return reflection.isInstance(item, RuleCall);\r\n}\r\n\r\nexport interface TerminalAlternatives extends AbstractElement {\r\n readonly $type: 'TerminalAlternatives';\r\n elements: Array;\r\n}\r\n\r\nexport const TerminalAlternatives = 'TerminalAlternatives';\r\n\r\nexport function isTerminalAlternatives(item: unknown): item is TerminalAlternatives {\r\n return reflection.isInstance(item, TerminalAlternatives);\r\n}\r\n\r\nexport interface TerminalGroup extends AbstractElement {\r\n readonly $type: 'TerminalGroup';\r\n elements: Array;\r\n}\r\n\r\nexport const TerminalGroup = 'TerminalGroup';\r\n\r\nexport function isTerminalGroup(item: unknown): item is TerminalGroup {\r\n return reflection.isInstance(item, TerminalGroup);\r\n}\r\n\r\nexport interface TerminalRuleCall extends AbstractElement {\r\n readonly $type: 'TerminalRuleCall';\r\n rule: Reference;\r\n}\r\n\r\nexport const TerminalRuleCall = 'TerminalRuleCall';\r\n\r\nexport function isTerminalRuleCall(item: unknown): item is TerminalRuleCall {\r\n return reflection.isInstance(item, TerminalRuleCall);\r\n}\r\n\r\nexport interface UnorderedGroup extends AbstractElement {\r\n readonly $type: 'UnorderedGroup';\r\n elements: Array;\r\n}\r\n\r\nexport const UnorderedGroup = 'UnorderedGroup';\r\n\r\nexport function isUnorderedGroup(item: unknown): item is UnorderedGroup {\r\n return reflection.isInstance(item, UnorderedGroup);\r\n}\r\n\r\nexport interface UntilToken extends AbstractElement {\r\n readonly $type: 'UntilToken';\r\n terminal: AbstractElement;\r\n}\r\n\r\nexport const UntilToken = 'UntilToken';\r\n\r\nexport function isUntilToken(item: unknown): item is UntilToken {\r\n return reflection.isInstance(item, UntilToken);\r\n}\r\n\r\nexport interface Wildcard extends AbstractElement {\r\n readonly $type: 'Wildcard';\r\n}\r\n\r\nexport const Wildcard = 'Wildcard';\r\n\r\nexport function isWildcard(item: unknown): item is Wildcard {\r\n return reflection.isInstance(item, Wildcard);\r\n}\r\n\r\nexport type LangiumGrammarAstType = {\r\n AbstractElement: AbstractElement\r\n AbstractRule: AbstractRule\r\n AbstractType: AbstractType\r\n Action: Action\r\n Alternatives: Alternatives\r\n ArrayLiteral: ArrayLiteral\r\n ArrayType: ArrayType\r\n Assignment: Assignment\r\n BooleanLiteral: BooleanLiteral\r\n CharacterRange: CharacterRange\r\n Condition: Condition\r\n Conjunction: Conjunction\r\n CrossReference: CrossReference\r\n Disjunction: Disjunction\r\n EndOfFile: EndOfFile\r\n Grammar: Grammar\r\n GrammarImport: GrammarImport\r\n Group: Group\r\n InferredType: InferredType\r\n Interface: Interface\r\n Keyword: Keyword\r\n NamedArgument: NamedArgument\r\n NegatedToken: NegatedToken\r\n Negation: Negation\r\n NumberLiteral: NumberLiteral\r\n Parameter: Parameter\r\n ParameterReference: ParameterReference\r\n ParserRule: ParserRule\r\n ReferenceType: ReferenceType\r\n RegexToken: RegexToken\r\n ReturnType: ReturnType\r\n RuleCall: RuleCall\r\n SimpleType: SimpleType\r\n StringLiteral: StringLiteral\r\n TerminalAlternatives: TerminalAlternatives\r\n TerminalGroup: TerminalGroup\r\n TerminalRule: TerminalRule\r\n TerminalRuleCall: TerminalRuleCall\r\n Type: Type\r\n TypeAttribute: TypeAttribute\r\n TypeDefinition: TypeDefinition\r\n UnionType: UnionType\r\n UnorderedGroup: UnorderedGroup\r\n UntilToken: UntilToken\r\n ValueLiteral: ValueLiteral\r\n Wildcard: Wildcard\r\n}\r\n\r\nexport class LangiumGrammarAstReflection extends AbstractAstReflection {\r\n\r\n getAllTypes(): string[] {\r\n return [AbstractElement, AbstractRule, AbstractType, Action, Alternatives, ArrayLiteral, ArrayType, Assignment, BooleanLiteral, CharacterRange, Condition, Conjunction, CrossReference, Disjunction, EndOfFile, Grammar, GrammarImport, Group, InferredType, Interface, Keyword, NamedArgument, NegatedToken, Negation, NumberLiteral, Parameter, ParameterReference, ParserRule, ReferenceType, RegexToken, ReturnType, RuleCall, SimpleType, StringLiteral, TerminalAlternatives, TerminalGroup, TerminalRule, TerminalRuleCall, Type, TypeAttribute, TypeDefinition, UnionType, UnorderedGroup, UntilToken, ValueLiteral, Wildcard];\r\n }\r\n\r\n protected override computeIsSubtype(subtype: string, supertype: string): boolean {\r\n switch (subtype) {\r\n case Action:\r\n case Alternatives:\r\n case Assignment:\r\n case CharacterRange:\r\n case CrossReference:\r\n case EndOfFile:\r\n case Group:\r\n case Keyword:\r\n case NegatedToken:\r\n case RegexToken:\r\n case RuleCall:\r\n case TerminalAlternatives:\r\n case TerminalGroup:\r\n case TerminalRuleCall:\r\n case UnorderedGroup:\r\n case UntilToken:\r\n case Wildcard: {\r\n return this.isSubtype(AbstractElement, supertype);\r\n }\r\n case ArrayLiteral:\r\n case NumberLiteral:\r\n case StringLiteral: {\r\n return this.isSubtype(ValueLiteral, supertype);\r\n }\r\n case ArrayType:\r\n case ReferenceType:\r\n case SimpleType:\r\n case UnionType: {\r\n return this.isSubtype(TypeDefinition, supertype);\r\n }\r\n case BooleanLiteral: {\r\n return this.isSubtype(Condition, supertype) || this.isSubtype(ValueLiteral, supertype);\r\n }\r\n case Conjunction:\r\n case Disjunction:\r\n case Negation:\r\n case ParameterReference: {\r\n return this.isSubtype(Condition, supertype);\r\n }\r\n case InferredType:\r\n case Interface:\r\n case Type: {\r\n return this.isSubtype(AbstractType, supertype);\r\n }\r\n case ParserRule: {\r\n return this.isSubtype(AbstractRule, supertype) || this.isSubtype(AbstractType, supertype);\r\n }\r\n case TerminalRule: {\r\n return this.isSubtype(AbstractRule, supertype);\r\n }\r\n default: {\r\n return false;\r\n }\r\n }\r\n }\r\n\r\n getReferenceType(refInfo: ReferenceInfo): string {\r\n const referenceId = `${refInfo.container.$type}:${refInfo.property}`;\r\n switch (referenceId) {\r\n case 'Action:type':\r\n case 'CrossReference:type':\r\n case 'Interface:superTypes':\r\n case 'ParserRule:returnType':\r\n case 'SimpleType:typeRef': {\r\n return AbstractType;\r\n }\r\n case 'Grammar:hiddenTokens':\r\n case 'ParserRule:hiddenTokens':\r\n case 'RuleCall:rule': {\r\n return AbstractRule;\r\n }\r\n case 'Grammar:usedGrammars': {\r\n return Grammar;\r\n }\r\n case 'NamedArgument:parameter':\r\n case 'ParameterReference:parameter': {\r\n return Parameter;\r\n }\r\n case 'TerminalRuleCall:rule': {\r\n return TerminalRule;\r\n }\r\n default: {\r\n throw new Error(`${referenceId} is not a valid reference id.`);\r\n }\r\n }\r\n }\r\n\r\n getTypeMetaData(type: string): TypeMetaData {\r\n switch (type) {\r\n case AbstractElement: {\r\n return {\r\n name: AbstractElement,\r\n properties: [\r\n { name: 'cardinality' },\r\n { name: 'lookahead' }\r\n ]\r\n };\r\n }\r\n case ArrayLiteral: {\r\n return {\r\n name: ArrayLiteral,\r\n properties: [\r\n { name: 'elements', defaultValue: [] }\r\n ]\r\n };\r\n }\r\n case ArrayType: {\r\n return {\r\n name: ArrayType,\r\n properties: [\r\n { name: 'elementType' }\r\n ]\r\n };\r\n }\r\n case BooleanLiteral: {\r\n return {\r\n name: BooleanLiteral,\r\n properties: [\r\n { name: 'true', defaultValue: false }\r\n ]\r\n };\r\n }\r\n case Conjunction: {\r\n return {\r\n name: Conjunction,\r\n properties: [\r\n { name: 'left' },\r\n { name: 'right' }\r\n ]\r\n };\r\n }\r\n case Disjunction: {\r\n return {\r\n name: Disjunction,\r\n properties: [\r\n { name: 'left' },\r\n { name: 'right' }\r\n ]\r\n };\r\n }\r\n case Grammar: {\r\n return {\r\n name: Grammar,\r\n properties: [\r\n { name: 'definesHiddenTokens', defaultValue: false },\r\n { name: 'hiddenTokens', defaultValue: [] },\r\n { name: 'imports', defaultValue: [] },\r\n { name: 'interfaces', defaultValue: [] },\r\n { name: 'isDeclared', defaultValue: false },\r\n { name: 'name' },\r\n { name: 'rules', defaultValue: [] },\r\n { name: 'types', defaultValue: [] },\r\n { name: 'usedGrammars', defaultValue: [] }\r\n ]\r\n };\r\n }\r\n case GrammarImport: {\r\n return {\r\n name: GrammarImport,\r\n properties: [\r\n { name: 'path' }\r\n ]\r\n };\r\n }\r\n case InferredType: {\r\n return {\r\n name: InferredType,\r\n properties: [\r\n { name: 'name' }\r\n ]\r\n };\r\n }\r\n case Interface: {\r\n return {\r\n name: Interface,\r\n properties: [\r\n { name: 'attributes', defaultValue: [] },\r\n { name: 'name' },\r\n { name: 'superTypes', defaultValue: [] }\r\n ]\r\n };\r\n }\r\n case NamedArgument: {\r\n return {\r\n name: NamedArgument,\r\n properties: [\r\n { name: 'calledByName', defaultValue: false },\r\n { name: 'parameter' },\r\n { name: 'value' }\r\n ]\r\n };\r\n }\r\n case Negation: {\r\n return {\r\n name: Negation,\r\n properties: [\r\n { name: 'value' }\r\n ]\r\n };\r\n }\r\n case NumberLiteral: {\r\n return {\r\n name: NumberLiteral,\r\n properties: [\r\n { name: 'value' }\r\n ]\r\n };\r\n }\r\n case Parameter: {\r\n return {\r\n name: Parameter,\r\n properties: [\r\n { name: 'name' }\r\n ]\r\n };\r\n }\r\n case ParameterReference: {\r\n return {\r\n name: ParameterReference,\r\n properties: [\r\n { name: 'parameter' }\r\n ]\r\n };\r\n }\r\n case ParserRule: {\r\n return {\r\n name: ParserRule,\r\n properties: [\r\n { name: 'dataType' },\r\n { name: 'definesHiddenTokens', defaultValue: false },\r\n { name: 'definition' },\r\n { name: 'entry', defaultValue: false },\r\n { name: 'fragment', defaultValue: false },\r\n { name: 'hiddenTokens', defaultValue: [] },\r\n { name: 'inferredType' },\r\n { name: 'name' },\r\n { name: 'parameters', defaultValue: [] },\r\n { name: 'returnType' },\r\n { name: 'wildcard', defaultValue: false }\r\n ]\r\n };\r\n }\r\n case ReferenceType: {\r\n return {\r\n name: ReferenceType,\r\n properties: [\r\n { name: 'referenceType' }\r\n ]\r\n };\r\n }\r\n case ReturnType: {\r\n return {\r\n name: ReturnType,\r\n properties: [\r\n { name: 'name' }\r\n ]\r\n };\r\n }\r\n case SimpleType: {\r\n return {\r\n name: SimpleType,\r\n properties: [\r\n { name: 'primitiveType' },\r\n { name: 'stringType' },\r\n { name: 'typeRef' }\r\n ]\r\n };\r\n }\r\n case StringLiteral: {\r\n return {\r\n name: StringLiteral,\r\n properties: [\r\n { name: 'value' }\r\n ]\r\n };\r\n }\r\n case TerminalRule: {\r\n return {\r\n name: TerminalRule,\r\n properties: [\r\n { name: 'definition' },\r\n { name: 'fragment', defaultValue: false },\r\n { name: 'hidden', defaultValue: false },\r\n { name: 'name' },\r\n { name: 'type' }\r\n ]\r\n };\r\n }\r\n case Type: {\r\n return {\r\n name: Type,\r\n properties: [\r\n { name: 'name' },\r\n { name: 'type' }\r\n ]\r\n };\r\n }\r\n case TypeAttribute: {\r\n return {\r\n name: TypeAttribute,\r\n properties: [\r\n { name: 'defaultValue' },\r\n { name: 'isOptional', defaultValue: false },\r\n { name: 'name' },\r\n { name: 'type' }\r\n ]\r\n };\r\n }\r\n case UnionType: {\r\n return {\r\n name: UnionType,\r\n properties: [\r\n { name: 'types', defaultValue: [] }\r\n ]\r\n };\r\n }\r\n case Action: {\r\n return {\r\n name: Action,\r\n properties: [\r\n { name: 'cardinality' },\r\n { name: 'feature' },\r\n { name: 'inferredType' },\r\n { name: 'lookahead' },\r\n { name: 'operator' },\r\n { name: 'type' }\r\n ]\r\n };\r\n }\r\n case Alternatives: {\r\n return {\r\n name: Alternatives,\r\n properties: [\r\n { name: 'cardinality' },\r\n { name: 'elements', defaultValue: [] },\r\n { name: 'lookahead' }\r\n ]\r\n };\r\n }\r\n case Assignment: {\r\n return {\r\n name: Assignment,\r\n properties: [\r\n { name: 'cardinality' },\r\n { name: 'feature' },\r\n { name: 'lookahead' },\r\n { name: 'operator' },\r\n { name: 'terminal' }\r\n ]\r\n };\r\n }\r\n case CharacterRange: {\r\n return {\r\n name: CharacterRange,\r\n properties: [\r\n { name: 'cardinality' },\r\n { name: 'left' },\r\n { name: 'lookahead' },\r\n { name: 'right' }\r\n ]\r\n };\r\n }\r\n case CrossReference: {\r\n return {\r\n name: CrossReference,\r\n properties: [\r\n { name: 'cardinality' },\r\n { name: 'deprecatedSyntax', defaultValue: false },\r\n { name: 'lookahead' },\r\n { name: 'terminal' },\r\n { name: 'type' }\r\n ]\r\n };\r\n }\r\n case EndOfFile: {\r\n return {\r\n name: EndOfFile,\r\n properties: [\r\n { name: 'cardinality' },\r\n { name: 'lookahead' }\r\n ]\r\n };\r\n }\r\n case Group: {\r\n return {\r\n name: Group,\r\n properties: [\r\n { name: 'cardinality' },\r\n { name: 'elements', defaultValue: [] },\r\n { name: 'guardCondition' },\r\n { name: 'lookahead' }\r\n ]\r\n };\r\n }\r\n case Keyword: {\r\n return {\r\n name: Keyword,\r\n properties: [\r\n { name: 'cardinality' },\r\n { name: 'lookahead' },\r\n { name: 'value' }\r\n ]\r\n };\r\n }\r\n case NegatedToken: {\r\n return {\r\n name: NegatedToken,\r\n properties: [\r\n { name: 'cardinality' },\r\n { name: 'lookahead' },\r\n { name: 'terminal' }\r\n ]\r\n };\r\n }\r\n case RegexToken: {\r\n return {\r\n name: RegexToken,\r\n properties: [\r\n { name: 'cardinality' },\r\n { name: 'lookahead' },\r\n { name: 'regex' }\r\n ]\r\n };\r\n }\r\n case RuleCall: {\r\n return {\r\n name: RuleCall,\r\n properties: [\r\n { name: 'arguments', defaultValue: [] },\r\n { name: 'cardinality' },\r\n { name: 'lookahead' },\r\n { name: 'rule' }\r\n ]\r\n };\r\n }\r\n case TerminalAlternatives: {\r\n return {\r\n name: TerminalAlternatives,\r\n properties: [\r\n { name: 'cardinality' },\r\n { name: 'elements', defaultValue: [] },\r\n { name: 'lookahead' }\r\n ]\r\n };\r\n }\r\n case TerminalGroup: {\r\n return {\r\n name: TerminalGroup,\r\n properties: [\r\n { name: 'cardinality' },\r\n { name: 'elements', defaultValue: [] },\r\n { name: 'lookahead' }\r\n ]\r\n };\r\n }\r\n case TerminalRuleCall: {\r\n return {\r\n name: TerminalRuleCall,\r\n properties: [\r\n { name: 'cardinality' },\r\n { name: 'lookahead' },\r\n { name: 'rule' }\r\n ]\r\n };\r\n }\r\n case UnorderedGroup: {\r\n return {\r\n name: UnorderedGroup,\r\n properties: [\r\n { name: 'cardinality' },\r\n { name: 'elements', defaultValue: [] },\r\n { name: 'lookahead' }\r\n ]\r\n };\r\n }\r\n case UntilToken: {\r\n return {\r\n name: UntilToken,\r\n properties: [\r\n { name: 'cardinality' },\r\n { name: 'lookahead' },\r\n { name: 'terminal' }\r\n ]\r\n };\r\n }\r\n case Wildcard: {\r\n return {\r\n name: Wildcard,\r\n properties: [\r\n { name: 'cardinality' },\r\n { name: 'lookahead' }\r\n ]\r\n };\r\n }\r\n default: {\r\n return {\r\n name: type,\r\n properties: []\r\n };\r\n }\r\n }\r\n }\r\n}\r\n\r\nexport const reflection = new LangiumGrammarAstReflection();\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { Range } from 'vscode-languageserver-types';\r\nimport type { AstNode, AstReflection, CstNode, GenericAstNode, Mutable, PropertyType, Reference, ReferenceInfo } from '../syntax-tree.js';\r\nimport type { Stream, TreeStream } from './stream.js';\r\nimport type { LangiumDocument } from '../workspace/documents.js';\r\nimport { isAstNode, isReference } from '../syntax-tree.js';\r\nimport { DONE_RESULT, stream, StreamImpl, TreeStreamImpl } from './stream.js';\r\nimport { inRange } from './cst-utils.js';\r\n\r\n/**\r\n * Link the `$container` and other related properties of every AST node that is directly contained\r\n * in the given `node`.\r\n */\r\nexport function linkContentToContainer(node: AstNode): void {\r\n for (const [name, value] of Object.entries(node)) {\r\n if (!name.startsWith('$')) {\r\n if (Array.isArray(value)) {\r\n value.forEach((item, index) => {\r\n if (isAstNode(item)) {\r\n (item as Mutable).$container = node;\r\n (item as Mutable).$containerProperty = name;\r\n (item as Mutable).$containerIndex = index;\r\n }\r\n });\r\n } else if (isAstNode(value)) {\r\n (value as Mutable).$container = node;\r\n (value as Mutable).$containerProperty = name;\r\n }\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Walk along the hierarchy of containers from the given AST node to the root and return the first\r\n * node that matches the type predicate. If the start node itself matches, it is returned.\r\n * If no container matches, `undefined` is returned.\r\n */\r\nexport function getContainerOfType(node: AstNode | undefined, typePredicate: (n: AstNode) => n is T): T | undefined {\r\n let item = node;\r\n while (item) {\r\n if (typePredicate(item)) {\r\n return item;\r\n }\r\n item = item.$container;\r\n }\r\n return undefined;\r\n}\r\n\r\n/**\r\n * Walk along the hierarchy of containers from the given AST node to the root and check for existence\r\n * of a container that matches the given predicate. The start node is included in the checks.\r\n */\r\nexport function hasContainerOfType(node: AstNode | undefined, predicate: (n: AstNode) => boolean): boolean {\r\n let item = node;\r\n while (item) {\r\n if (predicate(item)) {\r\n return true;\r\n }\r\n item = item.$container;\r\n }\r\n return false;\r\n}\r\n\r\n/**\r\n * Retrieve the document in which the given AST node is contained. A reference to the document is\r\n * usually held by the root node of the AST.\r\n *\r\n * @throws an error if the node is not contained in a document.\r\n */\r\nexport function getDocument(node: AstNode): LangiumDocument {\r\n const rootNode = findRootNode(node);\r\n const result = rootNode.$document;\r\n if (!result) {\r\n throw new Error('AST node has no document.');\r\n }\r\n return result as LangiumDocument;\r\n}\r\n\r\n/**\r\n * Returns the root node of the given AST node by following the `$container` references.\r\n */\r\nexport function findRootNode(node: AstNode): AstNode {\r\n while (node.$container) {\r\n node = node.$container;\r\n }\r\n return node;\r\n}\r\n\r\nexport interface AstStreamOptions {\r\n /**\r\n * Optional target range that the nodes in the stream need to intersect\r\n */\r\n range?: Range\r\n}\r\n\r\n/**\r\n * Create a stream of all AST nodes that are directly contained in the given node. This includes\r\n * single-valued as well as multi-valued (array) properties.\r\n */\r\nexport function streamContents(node: AstNode, options?: AstStreamOptions): Stream {\r\n if (!node) {\r\n throw new Error('Node must be an AstNode.');\r\n }\r\n const range = options?.range;\r\n type State = { keys: string[], keyIndex: number, arrayIndex: number };\r\n return new StreamImpl(() => ({\r\n keys: Object.keys(node),\r\n keyIndex: 0,\r\n arrayIndex: 0\r\n }), state => {\r\n while (state.keyIndex < state.keys.length) {\r\n const property = state.keys[state.keyIndex];\r\n if (!property.startsWith('$')) {\r\n const value = (node as GenericAstNode)[property];\r\n if (isAstNode(value)) {\r\n state.keyIndex++;\r\n if (isAstNodeInRange(value, range)) {\r\n return { done: false, value };\r\n }\r\n } else if (Array.isArray(value)) {\r\n while (state.arrayIndex < value.length) {\r\n const index = state.arrayIndex++;\r\n const element = value[index];\r\n if (isAstNode(element) && isAstNodeInRange(element, range)) {\r\n return { done: false, value: element };\r\n }\r\n }\r\n state.arrayIndex = 0;\r\n }\r\n }\r\n state.keyIndex++;\r\n }\r\n return DONE_RESULT;\r\n });\r\n}\r\n\r\n/**\r\n * Create a stream of all AST nodes that are directly and indirectly contained in the given root node.\r\n * This does not include the root node itself.\r\n */\r\nexport function streamAllContents(root: AstNode, options?: AstStreamOptions): TreeStream {\r\n if (!root) {\r\n throw new Error('Root node must be an AstNode.');\r\n }\r\n return new TreeStreamImpl(root, node => streamContents(node, options));\r\n}\r\n\r\n/**\r\n * Create a stream of all AST nodes that are directly and indirectly contained in the given root node,\r\n * including the root node itself.\r\n */\r\nexport function streamAst(root: AstNode, options?: AstStreamOptions): TreeStream {\r\n if (!root) {\r\n throw new Error('Root node must be an AstNode.');\r\n } else if (options?.range && !isAstNodeInRange(root, options.range)) {\r\n // Return an empty stream if the root node isn't in range\r\n return new TreeStreamImpl(root, () => []);\r\n }\r\n return new TreeStreamImpl(root, node => streamContents(node, options), { includeRoot: true });\r\n}\r\n\r\nfunction isAstNodeInRange(astNode: AstNode, range?: Range): boolean {\r\n if (!range) {\r\n return true;\r\n }\r\n const nodeRange = astNode.$cstNode?.range;\r\n if (!nodeRange) {\r\n return false;\r\n }\r\n return inRange(nodeRange, range);\r\n}\r\n\r\n/**\r\n * Create a stream of all cross-references that are held by the given AST node. This includes\r\n * single-valued as well as multi-valued (array) properties.\r\n */\r\nexport function streamReferences(node: AstNode): Stream {\r\n type State = { keys: string[], keyIndex: number, arrayIndex: number };\r\n return new StreamImpl(() => ({\r\n keys: Object.keys(node),\r\n keyIndex: 0,\r\n arrayIndex: 0\r\n }), state => {\r\n while (state.keyIndex < state.keys.length) {\r\n const property = state.keys[state.keyIndex];\r\n if (!property.startsWith('$')) {\r\n const value = (node as GenericAstNode)[property];\r\n if (isReference(value)) {\r\n state.keyIndex++;\r\n return { done: false, value: { reference: value, container: node, property } };\r\n } else if (Array.isArray(value)) {\r\n while (state.arrayIndex < value.length) {\r\n const index = state.arrayIndex++;\r\n const element = value[index];\r\n if (isReference(element)) {\r\n return { done: false, value: { reference: element, container: node, property, index } };\r\n }\r\n }\r\n state.arrayIndex = 0;\r\n }\r\n }\r\n state.keyIndex++;\r\n }\r\n return DONE_RESULT;\r\n });\r\n}\r\n\r\n/**\r\n * Returns a Stream of references to the target node from the AstNode tree\r\n *\r\n * @param targetNode AstNode we are looking for\r\n * @param lookup AstNode where we search for references. If not provided, the root node of the document is used as the default value\r\n */\r\nexport function findLocalReferences(targetNode: AstNode, lookup = getDocument(targetNode).parseResult.value): Stream {\r\n const refs: Reference[] = [];\r\n streamAst(lookup).forEach(node => {\r\n streamReferences(node).forEach(refInfo => {\r\n if (refInfo.reference.ref === targetNode) {\r\n refs.push(refInfo.reference);\r\n }\r\n });\r\n });\r\n return stream(refs);\r\n}\r\n\r\n/**\r\n * Assigns all mandatory AST properties to the specified node.\r\n *\r\n * @param reflection Reflection object used to gather mandatory properties for the node.\r\n * @param node Specified node is modified in place and properties are directly assigned.\r\n */\r\nexport function assignMandatoryProperties(reflection: AstReflection, node: AstNode): void {\r\n const typeMetaData = reflection.getTypeMetaData(node.$type);\r\n const genericNode = node as GenericAstNode;\r\n for (const property of typeMetaData.properties) {\r\n // Only set the value if the property is not already set and if it has a default value\r\n if (property.defaultValue !== undefined && genericNode[property.name] === undefined) {\r\n genericNode[property.name] = copyDefaultValue(property.defaultValue);\r\n }\r\n }\r\n}\r\n\r\nfunction copyDefaultValue(propertyType: PropertyType): PropertyType {\r\n if (Array.isArray(propertyType)) {\r\n return [...propertyType.map(copyDefaultValue)];\r\n } else {\r\n return propertyType;\r\n }\r\n}\r\n\r\n/**\r\n * Creates a deep copy of the specified AST node.\r\n * The resulting copy will only contain semantically relevant information, such as the `$type` property and AST properties.\r\n *\r\n * References are copied without resolved cross reference. The specified function is used to rebuild them.\r\n */\r\nexport function copyAstNode(node: T, buildReference: (node: AstNode, property: string, refNode: CstNode | undefined, refText: string) => Reference): T {\r\n const copy: GenericAstNode = { $type: node.$type };\r\n\r\n for (const [name, value] of Object.entries(node)) {\r\n if (!name.startsWith('$')) {\r\n if (isAstNode(value)) {\r\n copy[name] = copyAstNode(value, buildReference);\r\n } else if (isReference(value)) {\r\n copy[name] = buildReference(\r\n copy,\r\n name,\r\n value.$refNode,\r\n value.$refText\r\n );\r\n } else if (Array.isArray(value)) {\r\n const copiedArray: unknown[] = [];\r\n for (const element of value) {\r\n if (isAstNode(element)) {\r\n copiedArray.push(copyAstNode(element, buildReference));\r\n } else if (isReference(element)) {\r\n copiedArray.push(\r\n buildReference(\r\n copy,\r\n name,\r\n element.$refNode,\r\n element.$refText\r\n )\r\n );\r\n } else {\r\n copiedArray.push(element);\r\n }\r\n }\r\n copy[name] = copiedArray;\r\n } else {\r\n copy[name] = value;\r\n }\r\n }\r\n }\r\n\r\n linkContentToContainer(copy);\r\n return copy as unknown as T;\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { Set, Group, Character, IRegExpAST } from '@chevrotain/regexp-to-ast';\r\nimport { RegExpParser, BaseRegExpVisitor } from '@chevrotain/regexp-to-ast';\r\n\r\nexport const NEWLINE_REGEXP = /\\r?\\n/gm;\r\n\r\nconst regexpParser = new RegExpParser();\r\n\r\n/**\r\n * This class is in charge of heuristically identifying start/end tokens of terminals.\r\n *\r\n * The way this works is by doing the following:\r\n * 1. Traverse the regular expression in the \"start state\"\r\n * 2. Add any encountered sets/single characters to the \"start regexp\"\r\n * 3. Once we encounter any variable-length content (i.e. with quantifiers such as +/?/*), we enter the \"end state\"\r\n * 4. In the end state, any sets/single characters are added to an \"end stack\".\r\n * 5. If we re-encounter any variable-length content we reset the end stack\r\n * 6. We continue visiting the regex until the end, reseting the end stack and rebuilding it as necessary\r\n *\r\n * After traversing a regular expression the `startRegexp/endRegexp` properties allow access to the stored start/end of the terminal\r\n */\r\nclass TerminalRegExpVisitor extends BaseRegExpVisitor {\r\n\r\n private isStarting = true;\r\n startRegexp: string;\r\n private endRegexpStack: string[] = [];\r\n multiline = false;\r\n regex: string;\r\n\r\n get endRegex(): string {\r\n return this.endRegexpStack.join('');\r\n }\r\n\r\n reset(regex: string): void {\r\n this.multiline = false;\r\n this.regex = regex;\r\n this.startRegexp = '';\r\n this.isStarting = true;\r\n this.endRegexpStack = [];\r\n }\r\n\r\n override visitGroup(node: Group) {\r\n if (node.quantifier) {\r\n this.isStarting = false;\r\n this.endRegexpStack = [];\r\n }\r\n }\r\n\r\n override visitCharacter(node: Character): void {\r\n const char = String.fromCharCode(node.value);\r\n if (!this.multiline && char === '\\n') {\r\n this.multiline = true;\r\n }\r\n if (node.quantifier) {\r\n this.isStarting = false;\r\n this.endRegexpStack = [];\r\n } else {\r\n const escapedChar = escapeRegExp(char);\r\n this.endRegexpStack.push(escapedChar);\r\n if (this.isStarting) {\r\n this.startRegexp += escapedChar;\r\n }\r\n }\r\n }\r\n\r\n override visitSet(node: Set): void {\r\n if (!this.multiline) {\r\n const set = this.regex.substring(node.loc.begin, node.loc.end);\r\n const regex = new RegExp(set);\r\n this.multiline = Boolean('\\n'.match(regex));\r\n }\r\n if (node.quantifier) {\r\n this.isStarting = false;\r\n this.endRegexpStack = [];\r\n } else {\r\n const set = this.regex.substring(node.loc.begin, node.loc.end);\r\n this.endRegexpStack.push(set);\r\n if (this.isStarting) {\r\n this.startRegexp += set;\r\n }\r\n }\r\n }\r\n\r\n override visitChildren(node: IRegExpAST): void {\r\n if (node.type === 'Group') {\r\n // Ignore children of groups with quantifier (+/*/?)\r\n // These groups are unrelated to start/end tokens of terminals\r\n const group = node as Group;\r\n if (group.quantifier) {\r\n return;\r\n }\r\n }\r\n super.visitChildren(node);\r\n }\r\n}\r\n\r\nconst visitor = new TerminalRegExpVisitor();\r\n\r\nexport function getTerminalParts(regexp: RegExp | string): Array<{ start: string, end: string }> {\r\n try {\r\n if (typeof regexp !== 'string') {\r\n regexp = regexp.source;\r\n }\r\n regexp = `/${regexp}/`;\r\n const pattern = regexpParser.pattern(regexp);\r\n const parts: Array<{ start: string, end: string }> = [];\r\n for (const alternative of pattern.value.value) {\r\n visitor.reset(regexp);\r\n visitor.visit(alternative);\r\n parts.push({\r\n start: visitor.startRegexp,\r\n end: visitor.endRegex\r\n });\r\n }\r\n return parts;\r\n } catch {\r\n return [];\r\n }\r\n}\r\n\r\nexport function isMultilineComment(regexp: RegExp | string): boolean {\r\n try {\r\n if (typeof regexp === 'string') {\r\n regexp = new RegExp(regexp);\r\n }\r\n regexp = regexp.toString();\r\n visitor.reset(regexp);\r\n // Parsing the pattern might fail (since it's user code)\r\n visitor.visit(regexpParser.pattern(regexp));\r\n return visitor.multiline;\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * A set of all characters that are considered whitespace by the '\\s' RegExp character class.\r\n * Taken from [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes).\r\n */\r\nexport const whitespaceCharacters = (\r\n '\\f\\n\\r\\t\\v\\u0020\\u00a0\\u1680\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007' +\r\n '\\u2008\\u2009\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff').split('');\r\n\r\nexport function isWhitespace(value: RegExp | string): boolean {\r\n const regexp = typeof value === 'string' ? new RegExp(value) : value;\r\n return whitespaceCharacters.some((ws) => regexp.test(ws));\r\n}\r\n\r\nexport function escapeRegExp(value: string): string {\r\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\n\r\nexport function getCaseInsensitivePattern(keyword: string): string {\r\n return Array.prototype.map.call(keyword, letter =>\r\n /\\w/.test(letter) ? `[${letter.toLowerCase()}${letter.toUpperCase()}]` : escapeRegExp(letter)\r\n ).join('');\r\n}\r\n\r\n/**\r\n * Determines whether the given input has a partial match with the specified regex.\r\n * @param regex The regex to partially match against\r\n * @param input The input string\r\n * @returns Whether any match exists.\r\n */\r\nexport function partialMatches(regex: RegExp | string, input: string): boolean {\r\n const partial = partialRegExp(regex);\r\n const match = input.match(partial);\r\n return !!match && match[0].length > 0;\r\n}\r\n\r\n/**\r\n * Builds a partial regex from the input regex. A partial regex is able to match incomplete input strings. E.g.\r\n * a partial regex constructed from `/ab/` is able to match the string `a` without needing a following `b` character. However it won't match `b` alone.\r\n * @param regex The input regex to be converted.\r\n * @returns A partial regex constructed from the input regex.\r\n */\r\nexport function partialRegExp(regex: RegExp | string): RegExp {\r\n if (typeof regex === 'string') {\r\n regex = new RegExp(regex);\r\n }\r\n const re = regex, source = regex.source;\r\n let i = 0;\r\n\r\n function process() {\r\n let result = '',\r\n tmp;\r\n\r\n function appendRaw(nbChars: number) {\r\n result += source.substr(i, nbChars);\r\n i += nbChars;\r\n }\r\n\r\n function appendOptional(nbChars: number) {\r\n result += '(?:' + source.substr(i, nbChars) + '|$)';\r\n i += nbChars;\r\n }\r\n\r\n while (i < source.length) {\r\n switch (source[i]) {\r\n case '\\\\':\r\n switch (source[i + 1]) {\r\n case 'c':\r\n appendOptional(3);\r\n break;\r\n case 'x':\r\n appendOptional(4);\r\n break;\r\n case 'u':\r\n if (re.unicode) {\r\n if (source[i + 2] === '{') {\r\n appendOptional(source.indexOf('}', i) - i + 1);\r\n } else {\r\n appendOptional(6);\r\n }\r\n } else {\r\n appendOptional(2);\r\n }\r\n break;\r\n case 'p':\r\n case 'P':\r\n if (re.unicode) {\r\n appendOptional(source.indexOf('}', i) - i + 1);\r\n } else {\r\n appendOptional(2);\r\n }\r\n break;\r\n case 'k':\r\n appendOptional(source.indexOf('>', i) - i + 1);\r\n break;\r\n default:\r\n appendOptional(2);\r\n break;\r\n }\r\n break;\r\n\r\n case '[':\r\n tmp = /\\[(?:\\\\.|.)*?\\]/g;\r\n tmp.lastIndex = i;\r\n tmp = tmp.exec(source) || [];\r\n appendOptional(tmp[0].length);\r\n break;\r\n\r\n case '|':\r\n case '^':\r\n case '$':\r\n case '*':\r\n case '+':\r\n case '?':\r\n appendRaw(1);\r\n break;\r\n case '{':\r\n tmp = /\\{\\d+,?\\d*\\}/g;\r\n tmp.lastIndex = i;\r\n tmp = tmp.exec(source);\r\n if (tmp) {\r\n appendRaw(tmp[0].length);\r\n } else {\r\n appendOptional(1);\r\n }\r\n break;\r\n case '(':\r\n if (source[i + 1] === '?') {\r\n switch (source[i + 2]) {\r\n case ':':\r\n result += '(?:';\r\n i += 3;\r\n result += process() + '|$)';\r\n break;\r\n case '=':\r\n result += '(?=';\r\n i += 3;\r\n result += process() + ')';\r\n break;\r\n case '!':\r\n tmp = i;\r\n i += 3;\r\n process();\r\n result += source.substr(tmp, i - tmp);\r\n break;\r\n case '<':\r\n switch (source[i + 3]) {\r\n case '=':\r\n case '!':\r\n tmp = i;\r\n i += 4;\r\n process();\r\n result += source.substr(tmp, i - tmp);\r\n break;\r\n default:\r\n appendRaw(source.indexOf('>', i) - i + 1);\r\n result += process() + '|$)';\r\n break;\r\n }\r\n break;\r\n }\r\n } else {\r\n appendRaw(1);\r\n result += process() + '|$)';\r\n }\r\n break;\r\n case ')':\r\n ++i;\r\n return result;\r\n default:\r\n appendOptional(1);\r\n break;\r\n }\r\n }\r\n\r\n return result;\r\n }\r\n\r\n return new RegExp(process(), regex.flags);\r\n}\r\n", "import type { Character, IRegExpAST, RegExpFlags } from \"../types\";\n\nexport function cc(char: string): number {\n return char.charCodeAt(0);\n}\n\nexport function insertToSet(item: T | T[], set: T[]) {\n if (Array.isArray(item)) {\n item.forEach(function (subItem) {\n set.push(subItem);\n });\n } else {\n set.push(item);\n }\n}\n\nexport function addFlag(\n flagObj: RegExpFlags,\n flagKey: keyof Omit,\n) {\n if (flagObj[flagKey] === true) {\n throw \"duplicate flag \" + flagKey;\n }\n\n const x: boolean = flagObj[flagKey];\n flagObj[flagKey] = true;\n}\n\nexport function ASSERT_EXISTS(obj: any): obj is T {\n // istanbul ignore next\n if (obj === undefined) {\n throw Error(\"Internal Error - Should never get here!\");\n }\n return true;\n}\n\n// istanbul ignore next\nexport function ASSERT_NEVER_REACH_HERE(): any {\n throw Error(\"Internal Error - Should never get here!\");\n}\n\nexport function isCharacter(obj: { type: string }): obj is Character {\n return obj[\"type\"] === \"Character\";\n}\n", "import { cc } from \"./utils.js\";\n\nexport const digitsCharCodes: number[] = [];\nfor (let i = cc(\"0\"); i <= cc(\"9\"); i++) {\n digitsCharCodes.push(i);\n}\n\nexport const wordCharCodes: number[] = [cc(\"_\")].concat(digitsCharCodes);\nfor (let i = cc(\"a\"); i <= cc(\"z\"); i++) {\n wordCharCodes.push(i);\n}\n\nfor (let i = cc(\"A\"); i <= cc(\"Z\"); i++) {\n wordCharCodes.push(i);\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#character-classes\nexport const whitespaceCodes: number[] = [\n cc(\" \"),\n cc(\"\\f\"),\n cc(\"\\n\"),\n cc(\"\\r\"),\n cc(\"\\t\"),\n cc(\"\\v\"),\n cc(\"\\t\"),\n cc(\"\\u00a0\"),\n cc(\"\\u1680\"),\n cc(\"\\u2000\"),\n cc(\"\\u2001\"),\n cc(\"\\u2002\"),\n cc(\"\\u2003\"),\n cc(\"\\u2004\"),\n cc(\"\\u2005\"),\n cc(\"\\u2006\"),\n cc(\"\\u2007\"),\n cc(\"\\u2008\"),\n cc(\"\\u2009\"),\n cc(\"\\u200a\"),\n cc(\"\\u2028\"),\n cc(\"\\u2029\"),\n cc(\"\\u202f\"),\n cc(\"\\u205f\"),\n cc(\"\\u3000\"),\n cc(\"\\ufeff\"),\n];\n", "import type {\n Alternative,\n Assertion,\n Atom,\n Character,\n Disjunction,\n Group,\n GroupBackReference,\n Location,\n Quantifier,\n Range,\n RegExpFlags,\n RegExpPattern,\n Set,\n Term,\n} from \"../types\";\nimport {\n addFlag,\n ASSERT_EXISTS,\n ASSERT_NEVER_REACH_HERE,\n cc,\n insertToSet,\n isCharacter,\n} from \"./utils.js\";\nimport {\n digitsCharCodes,\n whitespaceCodes,\n wordCharCodes,\n} from \"./character-classes.js\";\n\n// consts and utilities\nconst hexDigitPattern = /[0-9a-fA-F]/;\nconst decimalPattern = /[0-9]/;\nconst decimalPatternNoZero = /[1-9]/;\n\n// https://hackernoon.com/the-madness-of-parsing-real-world-javascript-regexps-d9ee336df983\n// https://www.ecma-international.org/ecma-262/8.0/index.html#prod-Pattern\nexport class RegExpParser {\n protected idx: number = 0;\n protected input: string = \"\";\n protected groupIdx: number = 0;\n\n protected saveState() {\n return {\n idx: this.idx,\n input: this.input,\n groupIdx: this.groupIdx,\n };\n }\n\n protected restoreState(newState: {\n idx: number;\n input: string;\n groupIdx: number;\n }) {\n this.idx = newState.idx;\n this.input = newState.input;\n this.groupIdx = newState.groupIdx;\n }\n\n public pattern(input: string): RegExpPattern {\n // parser state\n this.idx = 0;\n this.input = input;\n this.groupIdx = 0;\n\n this.consumeChar(\"/\");\n const value = this.disjunction();\n this.consumeChar(\"/\");\n\n const flags: RegExpFlags = {\n type: \"Flags\",\n loc: { begin: this.idx, end: input.length },\n global: false,\n ignoreCase: false,\n multiLine: false,\n unicode: false,\n sticky: false,\n };\n\n while (this.isRegExpFlag()) {\n switch (this.popChar()) {\n case \"g\":\n addFlag(flags, \"global\");\n break;\n case \"i\":\n addFlag(flags, \"ignoreCase\");\n break;\n case \"m\":\n addFlag(flags, \"multiLine\");\n break;\n case \"u\":\n addFlag(flags, \"unicode\");\n break;\n case \"y\":\n addFlag(flags, \"sticky\");\n break;\n }\n }\n\n if (this.idx !== this.input.length) {\n throw Error(\"Redundant input: \" + this.input.substring(this.idx));\n }\n return {\n type: \"Pattern\",\n flags: flags,\n value: value,\n loc: this.loc(0),\n };\n }\n\n protected disjunction(): Disjunction {\n const alts = [];\n const begin = this.idx;\n\n alts.push(this.alternative());\n\n while (this.peekChar() === \"|\") {\n this.consumeChar(\"|\");\n alts.push(this.alternative());\n }\n\n return { type: \"Disjunction\", value: alts, loc: this.loc(begin) };\n }\n\n protected alternative(): Alternative {\n const terms = [];\n const begin = this.idx;\n\n while (this.isTerm()) {\n terms.push(this.term());\n }\n\n return { type: \"Alternative\", value: terms, loc: this.loc(begin) };\n }\n\n protected term(): Term {\n if (this.isAssertion()) {\n return this.assertion();\n } else {\n return this.atom();\n }\n }\n\n protected assertion(): Assertion {\n const begin = this.idx;\n switch (this.popChar()) {\n case \"^\":\n return {\n type: \"StartAnchor\",\n loc: this.loc(begin),\n };\n case \"$\":\n return { type: \"EndAnchor\", loc: this.loc(begin) };\n // '\\b' or '\\B'\n case \"\\\\\":\n switch (this.popChar()) {\n case \"b\":\n return {\n type: \"WordBoundary\",\n loc: this.loc(begin),\n };\n case \"B\":\n return {\n type: \"NonWordBoundary\",\n loc: this.loc(begin),\n };\n }\n // istanbul ignore next\n throw Error(\"Invalid Assertion Escape\");\n // '(?=' or '(?!'\n case \"(\":\n this.consumeChar(\"?\");\n\n let type: \"Lookahead\" | \"NegativeLookahead\" | undefined;\n switch (this.popChar()) {\n case \"=\":\n type = \"Lookahead\";\n break;\n case \"!\":\n type = \"NegativeLookahead\";\n break;\n }\n ASSERT_EXISTS(type);\n\n const disjunction = this.disjunction();\n\n this.consumeChar(\")\");\n\n return {\n type: type!,\n value: disjunction,\n loc: this.loc(begin),\n };\n }\n // istanbul ignore next\n return ASSERT_NEVER_REACH_HERE();\n }\n\n protected quantifier(\n isBacktracking: boolean = false,\n ): Quantifier | undefined {\n let range: Partial | undefined = undefined;\n const begin = this.idx;\n switch (this.popChar()) {\n case \"*\":\n range = {\n atLeast: 0,\n atMost: Infinity,\n };\n break;\n case \"+\":\n range = {\n atLeast: 1,\n atMost: Infinity,\n };\n break;\n case \"?\":\n range = {\n atLeast: 0,\n atMost: 1,\n };\n break;\n case \"{\":\n const atLeast = this.integerIncludingZero();\n switch (this.popChar()) {\n case \"}\":\n range = {\n atLeast: atLeast,\n atMost: atLeast,\n };\n break;\n case \",\":\n let atMost;\n if (this.isDigit()) {\n atMost = this.integerIncludingZero();\n range = {\n atLeast: atLeast,\n atMost: atMost,\n };\n } else {\n range = {\n atLeast: atLeast,\n atMost: Infinity,\n };\n }\n this.consumeChar(\"}\");\n break;\n }\n // throwing exceptions from \"ASSERT_EXISTS\" during backtracking\n // causes severe performance degradations\n if (isBacktracking === true && range === undefined) {\n return undefined;\n }\n ASSERT_EXISTS(range);\n break;\n }\n\n // throwing exceptions from \"ASSERT_EXISTS\" during backtracking\n // causes severe performance degradations\n if (isBacktracking === true && range === undefined) {\n return undefined;\n }\n\n // istanbul ignore else\n if (ASSERT_EXISTS(range)) {\n if (this.peekChar(0) === \"?\") {\n this.consumeChar(\"?\");\n range.greedy = false;\n } else {\n range.greedy = true;\n }\n\n range.type = \"Quantifier\";\n range.loc = this.loc(begin);\n return range as Quantifier;\n }\n }\n\n protected atom(): Atom {\n let atom: Omit | undefined;\n const begin = this.idx;\n switch (this.peekChar()) {\n case \".\":\n atom = this.dotAll();\n break;\n case \"\\\\\":\n atom = this.atomEscape();\n break;\n case \"[\":\n atom = this.characterClass();\n break;\n case \"(\":\n atom = this.group();\n break;\n }\n\n if (atom === undefined && this.isPatternCharacter()) {\n atom = this.patternCharacter();\n }\n\n // istanbul ignore else\n if (ASSERT_EXISTS(atom)) {\n atom.loc = this.loc(begin);\n\n if (this.isQuantifier()) {\n atom.quantifier = this.quantifier();\n }\n\n return atom;\n }\n\n // istanbul ignore next\n return ASSERT_NEVER_REACH_HERE();\n }\n\n protected dotAll(): Omit {\n this.consumeChar(\".\");\n return {\n type: \"Set\",\n complement: true,\n value: [cc(\"\\n\"), cc(\"\\r\"), cc(\"\\u2028\"), cc(\"\\u2029\")],\n };\n }\n\n protected atomEscape(): Omit {\n this.consumeChar(\"\\\\\");\n\n switch (this.peekChar()) {\n case \"1\":\n case \"2\":\n case \"3\":\n case \"4\":\n case \"5\":\n case \"6\":\n case \"7\":\n case \"8\":\n case \"9\":\n return this.decimalEscapeAtom();\n case \"d\":\n case \"D\":\n case \"s\":\n case \"S\":\n case \"w\":\n case \"W\":\n return this.characterClassEscape();\n case \"f\":\n case \"n\":\n case \"r\":\n case \"t\":\n case \"v\":\n return this.controlEscapeAtom();\n case \"c\":\n return this.controlLetterEscapeAtom();\n case \"0\":\n return this.nulCharacterAtom();\n case \"x\":\n return this.hexEscapeSequenceAtom();\n case \"u\":\n return this.regExpUnicodeEscapeSequenceAtom();\n default:\n return this.identityEscapeAtom();\n }\n }\n\n protected decimalEscapeAtom(): Omit {\n const value = this.positiveInteger();\n\n return { type: \"GroupBackReference\", value: value };\n }\n\n protected characterClassEscape(): Omit {\n let set: (number | Range)[] | undefined;\n let complement = false;\n switch (this.popChar()) {\n case \"d\":\n set = digitsCharCodes;\n break;\n case \"D\":\n set = digitsCharCodes;\n complement = true;\n break;\n case \"s\":\n set = whitespaceCodes;\n break;\n case \"S\":\n set = whitespaceCodes;\n complement = true;\n break;\n case \"w\":\n set = wordCharCodes;\n break;\n case \"W\":\n set = wordCharCodes;\n complement = true;\n break;\n }\n\n // istanbul ignore else\n if (ASSERT_EXISTS(set)) {\n return { type: \"Set\", value: set, complement: complement };\n }\n // istanbul ignore next\n return ASSERT_NEVER_REACH_HERE();\n }\n\n protected controlEscapeAtom(): Omit {\n let escapeCode;\n switch (this.popChar()) {\n case \"f\":\n escapeCode = cc(\"\\f\");\n break;\n case \"n\":\n escapeCode = cc(\"\\n\");\n break;\n case \"r\":\n escapeCode = cc(\"\\r\");\n break;\n case \"t\":\n escapeCode = cc(\"\\t\");\n break;\n case \"v\":\n escapeCode = cc(\"\\v\");\n break;\n }\n\n // istanbul ignore else\n if (ASSERT_EXISTS(escapeCode)) {\n return { type: \"Character\", value: escapeCode };\n }\n // istanbul ignore next\n return ASSERT_NEVER_REACH_HERE();\n }\n\n protected controlLetterEscapeAtom(): Omit {\n this.consumeChar(\"c\");\n const letter = this.popChar();\n if (/[a-zA-Z]/.test(letter) === false) {\n throw Error(\"Invalid \");\n }\n\n const letterCode = letter.toUpperCase().charCodeAt(0) - 64;\n return { type: \"Character\", value: letterCode };\n }\n\n protected nulCharacterAtom(): Omit {\n // TODO implement '[lookahead \u2209 DecimalDigit]'\n // TODO: for the deprecated octal escape sequence\n this.consumeChar(\"0\");\n return { type: \"Character\", value: cc(\"\\0\") };\n }\n\n protected hexEscapeSequenceAtom(): Omit {\n this.consumeChar(\"x\");\n return this.parseHexDigits(2);\n }\n\n protected regExpUnicodeEscapeSequenceAtom(): Omit {\n this.consumeChar(\"u\");\n return this.parseHexDigits(4);\n }\n\n protected identityEscapeAtom(): Omit {\n // TODO: implement \"SourceCharacter but not UnicodeIDContinue\"\n // // http://unicode.org/reports/tr31/#Specific_Character_Adjustments\n const escapedChar = this.popChar();\n return { type: \"Character\", value: cc(escapedChar) };\n }\n\n protected classPatternCharacterAtom(): Omit {\n switch (this.peekChar()) {\n // istanbul ignore next\n case \"\\n\":\n // istanbul ignore next\n case \"\\r\":\n // istanbul ignore next\n case \"\\u2028\":\n // istanbul ignore next\n case \"\\u2029\":\n // istanbul ignore next\n case \"\\\\\":\n // istanbul ignore next\n case \"]\":\n throw Error(\"TBD\");\n default:\n const nextChar = this.popChar();\n return { type: \"Character\", value: cc(nextChar) };\n }\n }\n\n protected characterClass(): Omit {\n const set: (number | Range)[] = [];\n let complement = false;\n this.consumeChar(\"[\");\n if (this.peekChar(0) === \"^\") {\n this.consumeChar(\"^\");\n complement = true;\n }\n\n while (this.isClassAtom()) {\n const from = this.classAtom();\n const isFromSingleChar = from.type === \"Character\";\n if (isCharacter(from) && this.isRangeDash()) {\n this.consumeChar(\"-\");\n const to = this.classAtom();\n const isToSingleChar = to.type === \"Character\";\n\n // a range can only be used when both sides are single characters\n if (isCharacter(to)) {\n if (to.value < from.value) {\n throw Error(\"Range out of order in character class\");\n }\n set.push({ from: from.value, to: to.value });\n } else {\n // literal dash\n insertToSet(from.value, set);\n set.push(cc(\"-\"));\n insertToSet(to.value, set);\n }\n } else {\n insertToSet(from.value, set);\n }\n }\n\n this.consumeChar(\"]\");\n\n return { type: \"Set\", complement: complement, value: set };\n }\n\n protected classAtom(): Omit {\n switch (this.peekChar()) {\n // istanbul ignore next\n case \"]\":\n // istanbul ignore next\n case \"\\n\":\n // istanbul ignore next\n case \"\\r\":\n // istanbul ignore next\n case \"\\u2028\":\n // istanbul ignore next\n case \"\\u2029\":\n throw Error(\"TBD\");\n case \"\\\\\":\n return this.classEscape();\n default:\n return this.classPatternCharacterAtom();\n }\n }\n\n protected classEscape(): Omit {\n this.consumeChar(\"\\\\\");\n switch (this.peekChar()) {\n // Matches a backspace.\n // (Not to be confused with \\b word boundary outside characterClass)\n case \"b\":\n this.consumeChar(\"b\");\n return { type: \"Character\", value: cc(\"\\u0008\") };\n case \"d\":\n case \"D\":\n case \"s\":\n case \"S\":\n case \"w\":\n case \"W\":\n return this.characterClassEscape();\n case \"f\":\n case \"n\":\n case \"r\":\n case \"t\":\n case \"v\":\n return this.controlEscapeAtom();\n case \"c\":\n return this.controlLetterEscapeAtom();\n case \"0\":\n return this.nulCharacterAtom();\n case \"x\":\n return this.hexEscapeSequenceAtom();\n case \"u\":\n return this.regExpUnicodeEscapeSequenceAtom();\n default:\n return this.identityEscapeAtom();\n }\n }\n\n protected group(): Omit {\n let capturing = true;\n this.consumeChar(\"(\");\n switch (this.peekChar(0)) {\n case \"?\":\n this.consumeChar(\"?\");\n this.consumeChar(\":\");\n capturing = false;\n break;\n default:\n this.groupIdx++;\n break;\n }\n const value = this.disjunction();\n this.consumeChar(\")\");\n\n const groupAst: Omit = {\n type: \"Group\",\n capturing: capturing,\n value: value,\n };\n\n if (capturing) {\n groupAst[\"idx\"] = this.groupIdx;\n }\n\n return groupAst;\n }\n\n protected positiveInteger(): number {\n let number = this.popChar();\n\n // istanbul ignore next - can't ever get here due to previous lookahead checks\n // still implementing this error checking in case this ever changes.\n if (decimalPatternNoZero.test(number) === false) {\n throw Error(\"Expecting a positive integer\");\n }\n\n while (decimalPattern.test(this.peekChar(0))) {\n number += this.popChar();\n }\n\n return parseInt(number, 10);\n }\n\n protected integerIncludingZero(): number {\n let number = this.popChar();\n if (decimalPattern.test(number) === false) {\n throw Error(\"Expecting an integer\");\n }\n\n while (decimalPattern.test(this.peekChar(0))) {\n number += this.popChar();\n }\n\n return parseInt(number, 10);\n }\n\n protected patternCharacter(): Omit {\n const nextChar = this.popChar();\n switch (nextChar) {\n // istanbul ignore next\n case \"\\n\":\n // istanbul ignore next\n case \"\\r\":\n // istanbul ignore next\n case \"\\u2028\":\n // istanbul ignore next\n case \"\\u2029\":\n // istanbul ignore next\n case \"^\":\n // istanbul ignore next\n case \"$\":\n // istanbul ignore next\n case \"\\\\\":\n // istanbul ignore next\n case \".\":\n // istanbul ignore next\n case \"*\":\n // istanbul ignore next\n case \"+\":\n // istanbul ignore next\n case \"?\":\n // istanbul ignore next\n case \"(\":\n // istanbul ignore next\n case \")\":\n // istanbul ignore next\n case \"[\":\n // istanbul ignore next\n case \"|\":\n // istanbul ignore next\n throw Error(\"TBD\");\n default:\n return { type: \"Character\", value: cc(nextChar) };\n }\n }\n protected isRegExpFlag(): boolean {\n switch (this.peekChar(0)) {\n case \"g\":\n case \"i\":\n case \"m\":\n case \"u\":\n case \"y\":\n return true;\n default:\n return false;\n }\n }\n\n protected isRangeDash(): boolean {\n return this.peekChar() === \"-\" && this.isClassAtom(1);\n }\n\n protected isDigit(): boolean {\n return decimalPattern.test(this.peekChar(0));\n }\n\n protected isClassAtom(howMuch = 0): boolean {\n switch (this.peekChar(howMuch)) {\n case \"]\":\n case \"\\n\":\n case \"\\r\":\n case \"\\u2028\":\n case \"\\u2029\":\n return false;\n default:\n return true;\n }\n }\n\n protected isTerm() {\n return this.isAtom() || this.isAssertion();\n }\n\n protected isAtom(): boolean {\n if (this.isPatternCharacter()) {\n return true;\n }\n\n switch (this.peekChar(0)) {\n case \".\":\n case \"\\\\\": // atomEscape\n case \"[\": // characterClass\n // TODO: isAtom must be called before isAssertion - disambiguate\n case \"(\": // group\n return true;\n default:\n return false;\n }\n }\n\n protected isAssertion(): boolean {\n switch (this.peekChar(0)) {\n case \"^\":\n case \"$\":\n return true;\n // '\\b' or '\\B'\n case \"\\\\\":\n switch (this.peekChar(1)) {\n case \"b\":\n case \"B\":\n return true;\n default:\n return false;\n }\n // '(?=' or '(?!'\n case \"(\":\n return (\n this.peekChar(1) === \"?\" &&\n (this.peekChar(2) === \"=\" || this.peekChar(2) === \"!\")\n );\n default:\n return false;\n }\n }\n\n protected isQuantifier(): boolean {\n const prevState = this.saveState();\n try {\n return this.quantifier(true) !== undefined;\n } catch (e) {\n return false;\n } finally {\n this.restoreState(prevState);\n }\n }\n\n protected isPatternCharacter(): boolean {\n switch (this.peekChar()) {\n case \"^\":\n case \"$\":\n case \"\\\\\":\n case \".\":\n case \"*\":\n case \"+\":\n case \"?\":\n case \"(\":\n case \")\":\n case \"[\":\n case \"|\":\n case \"/\":\n case \"\\n\":\n case \"\\r\":\n case \"\\u2028\":\n case \"\\u2029\":\n return false;\n default:\n return true;\n }\n }\n\n protected parseHexDigits(howMany: number): Omit {\n let hexString = \"\";\n for (let i = 0; i < howMany; i++) {\n const hexChar = this.popChar();\n if (hexDigitPattern.test(hexChar) === false) {\n throw Error(\"Expecting a HexDecimal digits\");\n }\n hexString += hexChar;\n }\n const charCode = parseInt(hexString, 16);\n return { type: \"Character\", value: charCode };\n }\n\n protected peekChar(howMuch = 0): string {\n return this.input[this.idx + howMuch];\n }\n\n protected popChar(): string {\n const nextChar = this.peekChar(0);\n this.consumeChar(undefined);\n return nextChar;\n }\n\n protected consumeChar(char: string | undefined): void {\n if (char !== undefined && this.input[this.idx] !== char) {\n throw Error(\n \"Expected: '\" +\n char +\n \"' but found: '\" +\n this.input[this.idx] +\n \"' at offset: \" +\n this.idx,\n );\n }\n\n if (this.idx >= this.input.length) {\n throw Error(\"Unexpected end of input\");\n }\n this.idx++;\n }\n\n protected loc(begin: number): Location {\n return { begin: begin, end: this.idx };\n }\n}\n", "import type {\n Alternative,\n Assertion,\n Character,\n Disjunction,\n Group,\n GroupBackReference,\n IRegExpAST,\n Quantifier,\n RegExpAstPart,\n RegExpFlags,\n RegExpPattern,\n Set,\n} from \"../types\";\n\nexport class BaseRegExpVisitor {\n public visitChildren(node: IRegExpAST) {\n for (const key in node) {\n const child = (node as any)[key];\n /* istanbul ignore else */\n if (node.hasOwnProperty(key)) {\n if (child.type !== undefined) {\n this.visit(child);\n } else if (Array.isArray(child)) {\n child.forEach((subChild) => {\n this.visit(subChild);\n }, this);\n }\n }\n }\n }\n\n public visit(node: RegExpAstPart): void {\n switch (node.type) {\n case \"Pattern\":\n this.visitPattern(node);\n break;\n case \"Flags\":\n this.visitFlags(node);\n break;\n case \"Disjunction\":\n this.visitDisjunction(node);\n break;\n case \"Alternative\":\n this.visitAlternative(node);\n break;\n case \"StartAnchor\":\n this.visitStartAnchor(node);\n break;\n case \"EndAnchor\":\n this.visitEndAnchor(node);\n break;\n case \"WordBoundary\":\n this.visitWordBoundary(node);\n break;\n case \"NonWordBoundary\":\n this.visitNonWordBoundary(node);\n break;\n case \"Lookahead\":\n this.visitLookahead(node);\n break;\n case \"NegativeLookahead\":\n this.visitNegativeLookahead(node);\n break;\n case \"Character\":\n this.visitCharacter(node);\n break;\n case \"Set\":\n this.visitSet(node);\n break;\n case \"Group\":\n this.visitGroup(node);\n break;\n case \"GroupBackReference\":\n this.visitGroupBackReference(node);\n break;\n case \"Quantifier\":\n this.visitQuantifier(node);\n break;\n }\n\n this.visitChildren(node);\n }\n\n public visitPattern(node: RegExpPattern): void {}\n\n public visitFlags(node: RegExpFlags): void {}\n\n public visitDisjunction(node: Disjunction): void {}\n\n public visitAlternative(node: Alternative): void {}\n\n // Assertion\n public visitStartAnchor(node: Assertion): void {}\n\n public visitEndAnchor(node: Assertion): void {}\n\n public visitWordBoundary(node: Assertion): void {}\n\n public visitNonWordBoundary(node: Assertion): void {}\n\n public visitLookahead(node: Assertion): void {}\n\n public visitNegativeLookahead(node: Assertion): void {}\n\n // atoms\n public visitCharacter(node: Character): void {}\n\n public visitSet(node: Set): void {}\n\n public visitGroup(node: Group): void {}\n\n public visitGroupBackReference(node: GroupBackReference): void {}\n\n public visitQuantifier(node: Quantifier): void {}\n}\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport { DefaultNameRegexp } from '../utils/cst-utils.js';\r\nimport { isCommentTerminal, terminalRegex } from '../utils/grammar-utils.js';\r\nimport { isMultilineComment } from '../utils/regexp-utils.js';\r\nimport { isTerminalRule } from './generated/ast.js';\r\n\r\nexport interface GrammarConfig {\r\n /**\r\n * Lists all rule names which are classified as multiline comment rules\r\n */\r\n multilineCommentRules: string[]\r\n /**\r\n * A regular expression which matches characters of names\r\n */\r\n nameRegexp: RegExp\r\n}\r\n\r\n/**\r\n * Create the default grammar configuration (used by `createDefaultModule`). This can be overridden in a\r\n * language-specific module.\r\n */\r\nexport function createGrammarConfig(services: LangiumCoreServices): GrammarConfig {\r\n const rules: string[] = [];\r\n const grammar = services.Grammar;\r\n for (const rule of grammar.rules) {\r\n if (isTerminalRule(rule) && isCommentTerminal(rule) && isMultilineComment(terminalRegex(rule))) {\r\n rules.push(rule.name);\r\n }\r\n }\r\n return {\r\n multilineCommentRules: rules,\r\n nameRegexp: DefaultNameRegexp\r\n };\r\n}\r\n", "export function PRINT_ERROR(msg: string) {\n /* istanbul ignore else - can't override global.console in node.js */\n if (console && console.error) {\n console.error(`Error: ${msg}`);\n }\n}\n\nexport function PRINT_WARNING(msg: string) {\n /* istanbul ignore else - can't override global.console in node.js*/\n if (console && console.warn) {\n // TODO: modify docs accordingly\n console.warn(`Warning: ${msg}`);\n }\n}\n", "export function timer(func: () => T): { time: number; value: T } {\n const start = new Date().getTime();\n const val = func();\n const end = new Date().getTime();\n const total = end - start;\n return { time: total, value: val };\n}\n", "// based on: https://github.com/petkaantonov/bluebird/blob/b97c0d2d487e8c5076e8bd897e0dcd4622d31846/src/util.js#L201-L216\nexport function toFastProperties(toBecomeFast: any) {\n function FakeConstructor() {}\n\n // If our object is used as a constructor, it would receive\n FakeConstructor.prototype = toBecomeFast;\n const fakeInstance = new (FakeConstructor as any)();\n\n function fakeAccess() {\n return typeof fakeInstance.bar;\n }\n\n // help V8 understand this is a \"real\" prototype by actually using\n // the fake instance.\n fakeAccess();\n fakeAccess();\n\n // Always true condition to suppress the Firefox warning of unreachable\n // code after a return statement.\n if (1) return toBecomeFast;\n\n // Eval prevents optimization of this method (even though this is dead code)\n // - https://esbuild.github.io/content-types/#direct-eval\n /* istanbul ignore next */\n // tslint:disable-next-line\n (0, eval)(toBecomeFast);\n}\n", "import { assign, forEach, isRegExp, isString, map, pickBy } from \"lodash-es\";\nimport type {\n IGASTVisitor,\n IProduction,\n IProductionWithOccurrence,\n ISerializedGast,\n TokenType,\n} from \"@chevrotain/types\";\n\n// TODO: duplicated code to avoid extracting another sub-package -- how to avoid?\nfunction tokenLabel(tokType: TokenType): string {\n if (hasTokenLabel(tokType)) {\n return tokType.LABEL;\n } else {\n return tokType.name;\n }\n}\n\n// TODO: duplicated code to avoid extracting another sub-package -- how to avoid?\nfunction hasTokenLabel(\n obj: TokenType,\n): obj is TokenType & Pick, \"LABEL\"> {\n return isString(obj.LABEL) && obj.LABEL !== \"\";\n}\n\nexport abstract class AbstractProduction\n implements IProduction\n{\n public get definition(): T[] {\n return this._definition;\n }\n public set definition(value: T[]) {\n this._definition = value;\n }\n\n constructor(protected _definition: T[]) {}\n\n accept(visitor: IGASTVisitor): void {\n visitor.visit(this);\n forEach(this.definition, (prod) => {\n prod.accept(visitor);\n });\n }\n}\n\nexport class NonTerminal\n extends AbstractProduction\n implements IProductionWithOccurrence\n{\n public nonTerminalName!: string;\n public label?: string;\n public referencedRule!: Rule;\n public idx: number = 1;\n\n constructor(options: {\n nonTerminalName: string;\n label?: string;\n referencedRule?: Rule;\n idx?: number;\n }) {\n super([]);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n\n set definition(definition: IProduction[]) {\n // immutable\n }\n\n get definition(): IProduction[] {\n if (this.referencedRule !== undefined) {\n return this.referencedRule.definition;\n }\n return [];\n }\n\n accept(visitor: IGASTVisitor): void {\n visitor.visit(this);\n // don't visit children of a reference, we will get cyclic infinite loops if we do so\n }\n}\n\nexport class Rule extends AbstractProduction {\n public name!: string;\n public orgText: string = \"\";\n\n constructor(options: {\n name: string;\n definition: IProduction[];\n orgText?: string;\n }) {\n super(options.definition);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n}\n\nexport class Alternative extends AbstractProduction {\n public ignoreAmbiguities: boolean = false;\n\n constructor(options: {\n definition: IProduction[];\n ignoreAmbiguities?: boolean;\n }) {\n super(options.definition);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n}\n\nexport class Option\n extends AbstractProduction\n implements IProductionWithOccurrence\n{\n public idx: number = 1;\n public maxLookahead?: number;\n\n constructor(options: {\n definition: IProduction[];\n idx?: number;\n maxLookahead?: number;\n }) {\n super(options.definition);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n}\n\nexport class RepetitionMandatory\n extends AbstractProduction\n implements IProductionWithOccurrence\n{\n public idx: number = 1;\n public maxLookahead?: number;\n\n constructor(options: {\n definition: IProduction[];\n idx?: number;\n maxLookahead?: number;\n }) {\n super(options.definition);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n}\n\nexport class RepetitionMandatoryWithSeparator\n extends AbstractProduction\n implements IProductionWithOccurrence\n{\n public separator!: TokenType;\n public idx: number = 1;\n public maxLookahead?: number;\n\n constructor(options: {\n definition: IProduction[];\n separator: TokenType;\n idx?: number;\n }) {\n super(options.definition);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n}\n\nexport class Repetition\n extends AbstractProduction\n implements IProductionWithOccurrence\n{\n public separator!: TokenType;\n public idx: number = 1;\n public maxLookahead?: number;\n\n constructor(options: {\n definition: IProduction[];\n idx?: number;\n maxLookahead?: number;\n }) {\n super(options.definition);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n}\n\nexport class RepetitionWithSeparator\n extends AbstractProduction\n implements IProductionWithOccurrence\n{\n public separator!: TokenType;\n public idx: number = 1;\n public maxLookahead?: number;\n\n constructor(options: {\n definition: IProduction[];\n separator: TokenType;\n idx?: number;\n }) {\n super(options.definition);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n}\n\nexport class Alternation\n extends AbstractProduction\n implements IProductionWithOccurrence\n{\n public idx: number = 1;\n public ignoreAmbiguities: boolean = false;\n public hasPredicates: boolean = false;\n public maxLookahead?: number;\n\n public get definition(): Alternative[] {\n return this._definition;\n }\n public set definition(value: Alternative[]) {\n this._definition = value;\n }\n\n constructor(options: {\n definition: Alternative[];\n idx?: number;\n ignoreAmbiguities?: boolean;\n hasPredicates?: boolean;\n maxLookahead?: number;\n }) {\n super(options.definition);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n}\n\nexport class Terminal implements IProductionWithOccurrence {\n public terminalType!: TokenType;\n public label?: string;\n public idx: number = 1;\n\n constructor(options: {\n terminalType: TokenType;\n label?: string;\n idx?: number;\n }) {\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n\n accept(visitor: IGASTVisitor): void {\n visitor.visit(this);\n }\n}\n\nexport interface ISerializedBasic extends ISerializedGast {\n type:\n | \"Alternative\"\n | \"Option\"\n | \"RepetitionMandatory\"\n | \"Repetition\"\n | \"Alternation\";\n idx?: number;\n}\n\nexport interface ISerializedGastRule extends ISerializedGast {\n type: \"Rule\";\n name: string;\n orgText: string;\n}\n\nexport interface ISerializedNonTerminal extends ISerializedGast {\n type: \"NonTerminal\";\n name: string;\n label?: string;\n idx: number;\n}\n\nexport interface ISerializedTerminal extends ISerializedGast {\n type: \"Terminal\";\n name: string;\n terminalLabel?: string;\n label?: string;\n pattern?: string;\n idx: number;\n}\n\nexport interface ISerializedTerminalWithSeparator extends ISerializedGast {\n type: \"RepetitionMandatoryWithSeparator\" | \"RepetitionWithSeparator\";\n idx: number;\n separator: ISerializedTerminal;\n}\n\nexport type ISerializedGastAny =\n | ISerializedBasic\n | ISerializedGastRule\n | ISerializedNonTerminal\n | ISerializedTerminal\n | ISerializedTerminalWithSeparator;\n\nexport function serializeGrammar(topRules: Rule[]): ISerializedGast[] {\n return map(topRules, serializeProduction);\n}\n\nexport function serializeProduction(node: IProduction): ISerializedGast {\n function convertDefinition(definition: IProduction[]): ISerializedGast[] {\n return map(definition, serializeProduction);\n }\n /* istanbul ignore else */\n if (node instanceof NonTerminal) {\n const serializedNonTerminal: ISerializedNonTerminal = {\n type: \"NonTerminal\",\n name: node.nonTerminalName,\n idx: node.idx,\n };\n\n if (isString(node.label)) {\n serializedNonTerminal.label = node.label;\n }\n\n return serializedNonTerminal;\n } else if (node instanceof Alternative) {\n return {\n type: \"Alternative\",\n definition: convertDefinition(node.definition),\n };\n } else if (node instanceof Option) {\n return {\n type: \"Option\",\n idx: node.idx,\n definition: convertDefinition(node.definition),\n };\n } else if (node instanceof RepetitionMandatory) {\n return {\n type: \"RepetitionMandatory\",\n idx: node.idx,\n definition: convertDefinition(node.definition),\n };\n } else if (node instanceof RepetitionMandatoryWithSeparator) {\n return {\n type: \"RepetitionMandatoryWithSeparator\",\n idx: node.idx,\n separator: (\n serializeProduction(new Terminal({ terminalType: node.separator }))\n ),\n definition: convertDefinition(node.definition),\n };\n } else if (node instanceof RepetitionWithSeparator) {\n return {\n type: \"RepetitionWithSeparator\",\n idx: node.idx,\n separator: (\n serializeProduction(new Terminal({ terminalType: node.separator }))\n ),\n definition: convertDefinition(node.definition),\n };\n } else if (node instanceof Repetition) {\n return {\n type: \"Repetition\",\n idx: node.idx,\n definition: convertDefinition(node.definition),\n };\n } else if (node instanceof Alternation) {\n return {\n type: \"Alternation\",\n idx: node.idx,\n definition: convertDefinition(node.definition),\n };\n } else if (node instanceof Terminal) {\n const serializedTerminal = {\n type: \"Terminal\",\n name: node.terminalType.name,\n label: tokenLabel(node.terminalType),\n idx: node.idx,\n };\n\n if (isString(node.label)) {\n serializedTerminal.terminalLabel = node.label;\n }\n\n const pattern = node.terminalType.PATTERN;\n if (node.terminalType.PATTERN) {\n serializedTerminal.pattern = isRegExp(pattern)\n ? (pattern).source\n : pattern;\n }\n\n return serializedTerminal;\n } else if (node instanceof Rule) {\n return {\n type: \"Rule\",\n name: node.name,\n orgText: node.orgText,\n definition: convertDefinition(node.definition),\n };\n /* c8 ignore next 3 */\n } else {\n throw Error(\"non exhaustive match\");\n }\n}\n", "import {\n Alternation,\n Alternative,\n NonTerminal,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n Rule,\n Terminal,\n} from \"./model.js\";\nimport type { IProduction } from \"@chevrotain/types\";\n\nexport abstract class GAstVisitor {\n public visit(node: IProduction): any {\n const nodeAny: any = node;\n switch (nodeAny.constructor) {\n case NonTerminal:\n return this.visitNonTerminal(nodeAny);\n case Alternative:\n return this.visitAlternative(nodeAny);\n case Option:\n return this.visitOption(nodeAny);\n case RepetitionMandatory:\n return this.visitRepetitionMandatory(nodeAny);\n case RepetitionMandatoryWithSeparator:\n return this.visitRepetitionMandatoryWithSeparator(nodeAny);\n case RepetitionWithSeparator:\n return this.visitRepetitionWithSeparator(nodeAny);\n case Repetition:\n return this.visitRepetition(nodeAny);\n case Alternation:\n return this.visitAlternation(nodeAny);\n case Terminal:\n return this.visitTerminal(nodeAny);\n case Rule:\n return this.visitRule(nodeAny);\n /* c8 ignore next 2 */\n default:\n throw Error(\"non exhaustive match\");\n }\n }\n\n /* c8 ignore next */\n public visitNonTerminal(node: NonTerminal): any {}\n\n /* c8 ignore next */\n public visitAlternative(node: Alternative): any {}\n\n /* c8 ignore next */\n public visitOption(node: Option): any {}\n\n /* c8 ignore next */\n public visitRepetition(node: Repetition): any {}\n\n /* c8 ignore next */\n public visitRepetitionMandatory(node: RepetitionMandatory): any {}\n\n /* c8 ignore next 3 */\n public visitRepetitionMandatoryWithSeparator(\n node: RepetitionMandatoryWithSeparator,\n ): any {}\n\n /* c8 ignore next */\n public visitRepetitionWithSeparator(node: RepetitionWithSeparator): any {}\n\n /* c8 ignore next */\n public visitAlternation(node: Alternation): any {}\n\n /* c8 ignore next */\n public visitTerminal(node: Terminal): any {}\n\n /* c8 ignore next */\n public visitRule(node: Rule): any {}\n}\n", "import { every, includes, some } from \"lodash-es\";\nimport {\n AbstractProduction,\n Alternation,\n Alternative,\n NonTerminal,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n Rule,\n Terminal,\n} from \"./model.js\";\nimport type { IProduction, IProductionWithOccurrence } from \"@chevrotain/types\";\n\nexport function isSequenceProd(\n prod: IProduction,\n): prod is { definition: IProduction[] } & IProduction {\n return (\n prod instanceof Alternative ||\n prod instanceof Option ||\n prod instanceof Repetition ||\n prod instanceof RepetitionMandatory ||\n prod instanceof RepetitionMandatoryWithSeparator ||\n prod instanceof RepetitionWithSeparator ||\n prod instanceof Terminal ||\n prod instanceof Rule\n );\n}\n\nexport function isOptionalProd(\n prod: IProduction,\n alreadyVisited: NonTerminal[] = [],\n): boolean {\n const isDirectlyOptional =\n prod instanceof Option ||\n prod instanceof Repetition ||\n prod instanceof RepetitionWithSeparator;\n if (isDirectlyOptional) {\n return true;\n }\n\n // note that this can cause infinite loop if one optional empty TOP production has a cyclic dependency with another\n // empty optional top rule\n // may be indirectly optional ((A?B?C?) | (D?E?F?))\n if (prod instanceof Alternation) {\n // for OR its enough for just one of the alternatives to be optional\n return some((prod).definition, (subProd: IProduction) => {\n return isOptionalProd(subProd, alreadyVisited);\n });\n } else if (prod instanceof NonTerminal && includes(alreadyVisited, prod)) {\n // avoiding stack overflow due to infinite recursion\n return false;\n } else if (prod instanceof AbstractProduction) {\n if (prod instanceof NonTerminal) {\n alreadyVisited.push(prod);\n }\n return every(\n (prod).definition,\n (subProd: IProduction) => {\n return isOptionalProd(subProd, alreadyVisited);\n },\n );\n } else {\n return false;\n }\n}\n\nexport function isBranchingProd(\n prod: IProduction,\n): prod is { definition: IProduction[] } & IProduction {\n return prod instanceof Alternation;\n}\n\nexport function getProductionDslName(prod: IProductionWithOccurrence): string {\n /* istanbul ignore else */\n if (prod instanceof NonTerminal) {\n return \"SUBRULE\";\n } else if (prod instanceof Option) {\n return \"OPTION\";\n } else if (prod instanceof Alternation) {\n return \"OR\";\n } else if (prod instanceof RepetitionMandatory) {\n return \"AT_LEAST_ONE\";\n } else if (prod instanceof RepetitionMandatoryWithSeparator) {\n return \"AT_LEAST_ONE_SEP\";\n } else if (prod instanceof RepetitionWithSeparator) {\n return \"MANY_SEP\";\n } else if (prod instanceof Repetition) {\n return \"MANY\";\n } else if (prod instanceof Terminal) {\n return \"CONSUME\";\n /* c8 ignore next 3 */\n } else {\n throw Error(\"non exhaustive match\");\n }\n}\n", "import { drop, forEach } from \"lodash-es\";\nimport {\n Alternation,\n Alternative,\n NonTerminal,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n Terminal,\n} from \"@chevrotain/gast\";\nimport { IProduction } from \"@chevrotain/types\";\n\n/**\n * A Grammar Walker that computes the \"remaining\" grammar \"after\" a productions in the grammar.\n */\nexport abstract class RestWalker {\n walk(prod: { definition: IProduction[] }, prevRest: any[] = []): void {\n forEach(prod.definition, (subProd: IProduction, index) => {\n const currRest = drop(prod.definition, index + 1);\n /* istanbul ignore else */\n if (subProd instanceof NonTerminal) {\n this.walkProdRef(subProd, currRest, prevRest);\n } else if (subProd instanceof Terminal) {\n this.walkTerminal(subProd, currRest, prevRest);\n } else if (subProd instanceof Alternative) {\n this.walkFlat(subProd, currRest, prevRest);\n } else if (subProd instanceof Option) {\n this.walkOption(subProd, currRest, prevRest);\n } else if (subProd instanceof RepetitionMandatory) {\n this.walkAtLeastOne(subProd, currRest, prevRest);\n } else if (subProd instanceof RepetitionMandatoryWithSeparator) {\n this.walkAtLeastOneSep(subProd, currRest, prevRest);\n } else if (subProd instanceof RepetitionWithSeparator) {\n this.walkManySep(subProd, currRest, prevRest);\n } else if (subProd instanceof Repetition) {\n this.walkMany(subProd, currRest, prevRest);\n } else if (subProd instanceof Alternation) {\n this.walkOr(subProd, currRest, prevRest);\n } else {\n throw Error(\"non exhaustive match\");\n }\n });\n }\n\n walkTerminal(\n terminal: Terminal,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {}\n\n walkProdRef(\n refProd: NonTerminal,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {}\n\n walkFlat(\n flatProd: Alternative,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // ABCDEF => after the D the rest is EF\n const fullOrRest = currRest.concat(prevRest);\n this.walk(flatProd, fullOrRest);\n }\n\n walkOption(\n optionProd: Option,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // ABC(DE)?F => after the (DE)? the rest is F\n const fullOrRest = currRest.concat(prevRest);\n this.walk(optionProd, fullOrRest);\n }\n\n walkAtLeastOne(\n atLeastOneProd: RepetitionMandatory,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // ABC(DE)+F => after the (DE)+ the rest is (DE)?F\n const fullAtLeastOneRest: IProduction[] = [\n new Option({ definition: atLeastOneProd.definition }),\n ].concat(currRest, prevRest);\n this.walk(atLeastOneProd, fullAtLeastOneRest);\n }\n\n walkAtLeastOneSep(\n atLeastOneSepProd: RepetitionMandatoryWithSeparator,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // ABC DE(,DE)* F => after the (,DE)+ the rest is (,DE)?F\n const fullAtLeastOneSepRest = restForRepetitionWithSeparator(\n atLeastOneSepProd,\n currRest,\n prevRest,\n );\n this.walk(atLeastOneSepProd, fullAtLeastOneSepRest);\n }\n\n walkMany(\n manyProd: Repetition,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // ABC(DE)*F => after the (DE)* the rest is (DE)?F\n const fullManyRest: IProduction[] = [\n new Option({ definition: manyProd.definition }),\n ].concat(currRest, prevRest);\n this.walk(manyProd, fullManyRest);\n }\n\n walkManySep(\n manySepProd: RepetitionWithSeparator,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // ABC (DE(,DE)*)? F => after the (,DE)* the rest is (,DE)?F\n const fullManySepRest = restForRepetitionWithSeparator(\n manySepProd,\n currRest,\n prevRest,\n );\n this.walk(manySepProd, fullManySepRest);\n }\n\n walkOr(\n orProd: Alternation,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // ABC(D|E|F)G => when finding the (D|E|F) the rest is G\n const fullOrRest = currRest.concat(prevRest);\n // walk all different alternatives\n forEach(orProd.definition, (alt) => {\n // wrapping each alternative in a single definition wrapper\n // to avoid errors in computing the rest of that alternative in the invocation to computeInProdFollows\n // (otherwise for OR([alt1,alt2]) alt2 will be considered in 'rest' of alt1\n const prodWrapper = new Alternative({ definition: [alt] });\n this.walk(prodWrapper, fullOrRest);\n });\n }\n}\n\nfunction restForRepetitionWithSeparator(\n repSepProd: RepetitionWithSeparator,\n currRest: IProduction[],\n prevRest: IProduction[],\n) {\n const repSepRest = [\n new Option({\n definition: [\n new Terminal({ terminalType: repSepProd.separator }) as IProduction,\n ].concat(repSepProd.definition),\n }) as IProduction,\n ];\n const fullRepSepRest: IProduction[] = repSepRest.concat(currRest, prevRest);\n return fullRepSepRest;\n}\n", "import { flatten, map, uniq } from \"lodash-es\";\nimport {\n isBranchingProd,\n isOptionalProd,\n isSequenceProd,\n NonTerminal,\n Terminal,\n} from \"@chevrotain/gast\";\nimport { IProduction, TokenType } from \"@chevrotain/types\";\n\nexport function first(prod: IProduction): TokenType[] {\n /* istanbul ignore else */\n if (prod instanceof NonTerminal) {\n // this could in theory cause infinite loops if\n // (1) prod A refs prod B.\n // (2) prod B refs prod A\n // (3) AB can match the empty set\n // in other words a cycle where everything is optional so the first will keep\n // looking ahead for the next optional part and will never exit\n // currently there is no safeguard for this unique edge case because\n // (1) not sure a grammar in which this can happen is useful for anything (productive)\n return first((prod).referencedRule);\n } else if (prod instanceof Terminal) {\n return firstForTerminal(prod);\n } else if (isSequenceProd(prod)) {\n return firstForSequence(prod);\n } else if (isBranchingProd(prod)) {\n return firstForBranching(prod);\n } else {\n throw Error(\"non exhaustive match\");\n }\n}\n\nexport function firstForSequence(prod: {\n definition: IProduction[];\n}): TokenType[] {\n let firstSet: TokenType[] = [];\n const seq = prod.definition;\n let nextSubProdIdx = 0;\n let hasInnerProdsRemaining = seq.length > nextSubProdIdx;\n let currSubProd;\n // so we enter the loop at least once (if the definition is not empty\n let isLastInnerProdOptional = true;\n // scan a sequence until it's end or until we have found a NONE optional production in it\n while (hasInnerProdsRemaining && isLastInnerProdOptional) {\n currSubProd = seq[nextSubProdIdx];\n isLastInnerProdOptional = isOptionalProd(currSubProd);\n firstSet = firstSet.concat(first(currSubProd));\n nextSubProdIdx = nextSubProdIdx + 1;\n hasInnerProdsRemaining = seq.length > nextSubProdIdx;\n }\n\n return uniq(firstSet);\n}\n\nexport function firstForBranching(prod: {\n definition: IProduction[];\n}): TokenType[] {\n const allAlternativesFirsts: TokenType[][] = map(\n prod.definition,\n (innerProd) => {\n return first(innerProd);\n },\n );\n return uniq(flatten(allAlternativesFirsts));\n}\n\nexport function firstForTerminal(terminal: Terminal): TokenType[] {\n return [terminal.terminalType];\n}\n", "// TODO: can this be removed? where is it used?\nexport const IN = \"_~IN~_\";\n", "import { RestWalker } from \"./rest.js\";\nimport { first } from \"./first.js\";\nimport { assign, forEach } from \"lodash-es\";\nimport { IN } from \"../constants.js\";\nimport { Alternative, NonTerminal, Rule, Terminal } from \"@chevrotain/gast\";\nimport { IProduction, TokenType } from \"@chevrotain/types\";\n\n// This ResyncFollowsWalker computes all of the follows required for RESYNC\n// (skipping reference production).\nexport class ResyncFollowsWalker extends RestWalker {\n public follows: Record = {};\n\n constructor(private topProd: Rule) {\n super();\n }\n\n startWalking(): Record {\n this.walk(this.topProd);\n return this.follows;\n }\n\n walkTerminal(\n terminal: Terminal,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // do nothing! just like in the public sector after 13:00\n }\n\n walkProdRef(\n refProd: NonTerminal,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n const followName =\n buildBetweenProdsFollowPrefix(refProd.referencedRule, refProd.idx) +\n this.topProd.name;\n const fullRest: IProduction[] = currRest.concat(prevRest);\n const restProd = new Alternative({ definition: fullRest });\n const t_in_topProd_follows = first(restProd);\n this.follows[followName] = t_in_topProd_follows;\n }\n}\n\nexport function computeAllProdsFollows(\n topProductions: Rule[],\n): Record {\n const reSyncFollows = {};\n\n forEach(topProductions, (topProd) => {\n const currRefsFollow = new ResyncFollowsWalker(topProd).startWalking();\n assign(reSyncFollows, currRefsFollow);\n });\n return reSyncFollows;\n}\n\nexport function buildBetweenProdsFollowPrefix(\n inner: Rule,\n occurenceInParent: number,\n): string {\n return inner.name + occurenceInParent + IN;\n}\n\nexport function buildInProdFollowPrefix(terminal: Terminal): string {\n const terminalName = terminal.terminalType.name;\n return terminalName + terminal.idx + IN;\n}\n", "import {\n Alternative,\n Assertion,\n Atom,\n Disjunction,\n RegExpParser,\n RegExpPattern,\n} from \"@chevrotain/regexp-to-ast\";\n\nlet regExpAstCache: { [regex: string]: RegExpPattern } = {};\nconst regExpParser = new RegExpParser();\n\n// this should be moved to regexp-to-ast\nexport type ASTNode =\n | RegExpPattern\n | Disjunction\n | Alternative\n | Assertion\n | Atom;\n\nexport function getRegExpAst(regExp: RegExp): RegExpPattern {\n const regExpStr = regExp.toString();\n if (regExpAstCache.hasOwnProperty(regExpStr)) {\n return regExpAstCache[regExpStr];\n } else {\n const regExpAst = regExpParser.pattern(regExpStr);\n regExpAstCache[regExpStr] = regExpAst;\n return regExpAst;\n }\n}\n\nexport function clearRegExpParserCache() {\n regExpAstCache = {};\n}\n", "import {\n Alternative,\n Atom,\n BaseRegExpVisitor,\n Character,\n Disjunction,\n Group,\n Set,\n} from \"@chevrotain/regexp-to-ast\";\nimport { every, find, forEach, includes, isArray, values } from \"lodash-es\";\nimport { PRINT_ERROR, PRINT_WARNING } from \"@chevrotain/utils\";\nimport { ASTNode, getRegExpAst } from \"./reg_exp_parser.js\";\nimport { charCodeToOptimizedIndex, minOptimizationVal } from \"./lexer.js\";\n\nconst complementErrorMessage =\n \"Complement Sets are not supported for first char optimization\";\nexport const failedOptimizationPrefixMsg =\n 'Unable to use \"first char\" lexer optimizations:\\n';\n\nexport function getOptimizedStartCodesIndices(\n regExp: RegExp,\n ensureOptimizations = false,\n): number[] {\n try {\n const ast = getRegExpAst(regExp);\n const firstChars = firstCharOptimizedIndices(\n ast.value,\n {},\n ast.flags.ignoreCase,\n );\n return firstChars;\n } catch (e) {\n /* istanbul ignore next */\n // Testing this relies on the regexp-to-ast library having a bug... */\n // TODO: only the else branch needs to be ignored, try to fix with newer prettier / tsc\n if (e.message === complementErrorMessage) {\n if (ensureOptimizations) {\n PRINT_WARNING(\n `${failedOptimizationPrefixMsg}` +\n `\\tUnable to optimize: < ${regExp.toString()} >\\n` +\n \"\\tComplement Sets cannot be automatically optimized.\\n\" +\n \"\\tThis will disable the lexer's first char optimizations.\\n\" +\n \"\\tSee: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.\",\n );\n }\n } else {\n let msgSuffix = \"\";\n if (ensureOptimizations) {\n msgSuffix =\n \"\\n\\tThis will disable the lexer's first char optimizations.\\n\" +\n \"\\tSee: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.\";\n }\n PRINT_ERROR(\n `${failedOptimizationPrefixMsg}\\n` +\n `\\tFailed parsing: < ${regExp.toString()} >\\n` +\n `\\tUsing the @chevrotain/regexp-to-ast library\\n` +\n \"\\tPlease open an issue at: https://github.com/chevrotain/chevrotain/issues\" +\n msgSuffix,\n );\n }\n }\n\n return [];\n}\n\nexport function firstCharOptimizedIndices(\n ast: ASTNode,\n result: { [charCode: number]: number },\n ignoreCase: boolean,\n): number[] {\n switch (ast.type) {\n case \"Disjunction\":\n for (let i = 0; i < ast.value.length; i++) {\n firstCharOptimizedIndices(ast.value[i], result, ignoreCase);\n }\n break;\n case \"Alternative\":\n const terms = ast.value;\n for (let i = 0; i < terms.length; i++) {\n const term = terms[i];\n\n // skip terms that cannot effect the first char results\n switch (term.type) {\n case \"EndAnchor\":\n // A group back reference cannot affect potential starting char.\n // because if a back reference is the first production than automatically\n // the group being referenced has had to come BEFORE so its codes have already been added\n case \"GroupBackReference\":\n // assertions do not affect potential starting codes\n case \"Lookahead\":\n case \"NegativeLookahead\":\n case \"StartAnchor\":\n case \"WordBoundary\":\n case \"NonWordBoundary\":\n continue;\n }\n\n const atom = term;\n switch (atom.type) {\n case \"Character\":\n addOptimizedIdxToResult(atom.value, result, ignoreCase);\n break;\n case \"Set\":\n if (atom.complement === true) {\n throw Error(complementErrorMessage);\n }\n forEach(atom.value, (code) => {\n if (typeof code === \"number\") {\n addOptimizedIdxToResult(code, result, ignoreCase);\n } else {\n // range\n const range = code as any;\n // cannot optimize when ignoreCase is\n if (ignoreCase === true) {\n for (\n let rangeCode = range.from;\n rangeCode <= range.to;\n rangeCode++\n ) {\n addOptimizedIdxToResult(rangeCode, result, ignoreCase);\n }\n }\n // Optimization (2 orders of magnitude less work for very large ranges)\n else {\n // handle unoptimized values\n for (\n let rangeCode = range.from;\n rangeCode <= range.to && rangeCode < minOptimizationVal;\n rangeCode++\n ) {\n addOptimizedIdxToResult(rangeCode, result, ignoreCase);\n }\n\n // Less common charCode where we optimize for faster init time, by using larger \"buckets\"\n if (range.to >= minOptimizationVal) {\n const minUnOptVal =\n range.from >= minOptimizationVal\n ? range.from\n : minOptimizationVal;\n const maxUnOptVal = range.to;\n const minOptIdx = charCodeToOptimizedIndex(minUnOptVal);\n const maxOptIdx = charCodeToOptimizedIndex(maxUnOptVal);\n\n for (\n let currOptIdx = minOptIdx;\n currOptIdx <= maxOptIdx;\n currOptIdx++\n ) {\n result[currOptIdx] = currOptIdx;\n }\n }\n }\n }\n });\n break;\n case \"Group\":\n firstCharOptimizedIndices(atom.value, result, ignoreCase);\n break;\n /* istanbul ignore next */\n default:\n throw Error(\"Non Exhaustive Match\");\n }\n\n // reached a mandatory production, no more **start** codes can be found on this alternative\n const isOptionalQuantifier =\n atom.quantifier !== undefined && atom.quantifier.atLeast === 0;\n if (\n // A group may be optional due to empty contents /(?:)/\n // or if everything inside it is optional /((a)?)/\n (atom.type === \"Group\" && isWholeOptional(atom) === false) ||\n // If this term is not a group it may only be optional if it has an optional quantifier\n (atom.type !== \"Group\" && isOptionalQuantifier === false)\n ) {\n break;\n }\n }\n break;\n /* istanbul ignore next */\n default:\n throw Error(\"non exhaustive match!\");\n }\n\n // console.log(Object.keys(result).length)\n return values(result);\n}\n\nfunction addOptimizedIdxToResult(\n code: number,\n result: { [charCode: number]: number },\n ignoreCase: boolean,\n) {\n const optimizedCharIdx = charCodeToOptimizedIndex(code);\n result[optimizedCharIdx] = optimizedCharIdx;\n\n if (ignoreCase === true) {\n handleIgnoreCase(code, result);\n }\n}\n\nfunction handleIgnoreCase(\n code: number,\n result: { [charCode: number]: number },\n) {\n const char = String.fromCharCode(code);\n const upperChar = char.toUpperCase();\n /* istanbul ignore else */\n if (upperChar !== char) {\n const optimizedCharIdx = charCodeToOptimizedIndex(upperChar.charCodeAt(0));\n result[optimizedCharIdx] = optimizedCharIdx;\n } else {\n const lowerChar = char.toLowerCase();\n if (lowerChar !== char) {\n const optimizedCharIdx = charCodeToOptimizedIndex(\n lowerChar.charCodeAt(0),\n );\n result[optimizedCharIdx] = optimizedCharIdx;\n }\n }\n}\n\nfunction findCode(setNode: Set, targetCharCodes: number[]) {\n return find(setNode.value, (codeOrRange) => {\n if (typeof codeOrRange === \"number\") {\n return includes(targetCharCodes, codeOrRange);\n } else {\n // range\n const range = codeOrRange;\n return (\n find(\n targetCharCodes,\n (targetCode) => range.from <= targetCode && targetCode <= range.to,\n ) !== undefined\n );\n }\n });\n}\n\nfunction isWholeOptional(ast: any): boolean {\n const quantifier = (ast as Atom).quantifier;\n if (quantifier && quantifier.atLeast === 0) {\n return true;\n }\n\n if (!ast.value) {\n return false;\n }\n\n return isArray(ast.value)\n ? every(ast.value, isWholeOptional)\n : isWholeOptional(ast.value);\n}\n\nclass CharCodeFinder extends BaseRegExpVisitor {\n found: boolean = false;\n\n constructor(private targetCharCodes: number[]) {\n super();\n }\n\n visitChildren(node: ASTNode) {\n // No need to keep looking...\n if (this.found === true) {\n return;\n }\n\n // switch lookaheads as they do not actually consume any characters thus\n // finding a charCode at lookahead context does not mean that regexp can actually contain it in a match.\n switch (node.type) {\n case \"Lookahead\":\n this.visitLookahead(node);\n return;\n case \"NegativeLookahead\":\n this.visitNegativeLookahead(node);\n return;\n }\n\n super.visitChildren(node);\n }\n\n visitCharacter(node: Character) {\n if (includes(this.targetCharCodes, node.value)) {\n this.found = true;\n }\n }\n\n visitSet(node: Set) {\n if (node.complement) {\n if (findCode(node, this.targetCharCodes) === undefined) {\n this.found = true;\n }\n } else {\n if (findCode(node, this.targetCharCodes) !== undefined) {\n this.found = true;\n }\n }\n }\n}\n\nexport function canMatchCharCode(\n charCodes: number[],\n pattern: RegExp | string,\n) {\n if (pattern instanceof RegExp) {\n const ast = getRegExpAst(pattern);\n const charCodeFinder = new CharCodeFinder(charCodes);\n charCodeFinder.visit(ast);\n return charCodeFinder.found;\n } else {\n return (\n find(pattern, (char) => {\n return includes(charCodes, (char).charCodeAt(0));\n }) !== undefined\n );\n }\n}\n", "import { BaseRegExpVisitor } from \"@chevrotain/regexp-to-ast\";\nimport {\n IRegExpExec,\n Lexer,\n LexerDefinitionErrorType,\n} from \"./lexer_public.js\";\nimport {\n compact,\n defaults,\n difference,\n filter,\n find,\n first,\n flatten,\n forEach,\n has,\n includes,\n indexOf,\n isArray,\n isEmpty,\n isFunction,\n isRegExp,\n isString,\n isUndefined,\n keys,\n map,\n reduce,\n reject,\n values,\n} from \"lodash-es\";\nimport { PRINT_ERROR } from \"@chevrotain/utils\";\nimport {\n canMatchCharCode,\n failedOptimizationPrefixMsg,\n getOptimizedStartCodesIndices,\n} from \"./reg_exp.js\";\nimport {\n ILexerDefinitionError,\n ILineTerminatorsTester,\n IMultiModeLexerDefinition,\n IToken,\n TokenType,\n} from \"@chevrotain/types\";\nimport { getRegExpAst } from \"./reg_exp_parser.js\";\n\nconst PATTERN = \"PATTERN\";\nexport const DEFAULT_MODE = \"defaultMode\";\nexport const MODES = \"modes\";\n\nexport interface IPatternConfig {\n pattern: IRegExpExec | string;\n longerAlt: number[] | undefined;\n canLineTerminator: boolean;\n isCustom: boolean;\n short: number | false;\n group: string | undefined | false;\n push: string | undefined;\n pop: boolean;\n tokenType: TokenType;\n tokenTypeIdx: number;\n}\n\nexport interface IAnalyzeResult {\n patternIdxToConfig: IPatternConfig[];\n charCodeToPatternIdxToConfig: { [charCode: number]: IPatternConfig[] };\n emptyGroups: { [groupName: string]: IToken[] };\n hasCustom: boolean;\n canBeOptimized: boolean;\n}\n\nexport let SUPPORT_STICKY =\n typeof (new RegExp(\"(?:)\")).sticky === \"boolean\";\n\nexport function disableSticky() {\n SUPPORT_STICKY = false;\n}\n\nexport function enableSticky() {\n SUPPORT_STICKY = true;\n}\n\nexport function analyzeTokenTypes(\n tokenTypes: TokenType[],\n options: {\n positionTracking?: \"full\" | \"onlyStart\" | \"onlyOffset\";\n ensureOptimizations?: boolean;\n lineTerminatorCharacters?: (number | string)[];\n // TODO: should `useSticky` be an argument here?\n useSticky?: boolean;\n safeMode?: boolean;\n tracer?: (msg: string, action: () => void) => void;\n },\n): IAnalyzeResult {\n options = defaults(options, {\n useSticky: SUPPORT_STICKY,\n debug: false as boolean,\n safeMode: false as boolean,\n positionTracking: \"full\",\n lineTerminatorCharacters: [\"\\r\", \"\\n\"],\n tracer: (msg: string, action: Function) => action(),\n });\n\n const tracer = options.tracer!;\n\n tracer(\"initCharCodeToOptimizedIndexMap\", () => {\n initCharCodeToOptimizedIndexMap();\n });\n\n let onlyRelevantTypes: TokenType[];\n tracer(\"Reject Lexer.NA\", () => {\n onlyRelevantTypes = reject(tokenTypes, (currType) => {\n return currType[PATTERN] === Lexer.NA;\n });\n });\n\n let hasCustom = false;\n let allTransformedPatterns: (IRegExpExec | string)[];\n tracer(\"Transform Patterns\", () => {\n hasCustom = false;\n allTransformedPatterns = map(\n onlyRelevantTypes,\n (currType): IRegExpExec | string => {\n const currPattern = currType[PATTERN];\n\n /* istanbul ignore else */\n if (isRegExp(currPattern)) {\n const regExpSource = currPattern.source;\n if (\n regExpSource.length === 1 &&\n // only these regExp meta characters which can appear in a length one regExp\n regExpSource !== \"^\" &&\n regExpSource !== \"$\" &&\n regExpSource !== \".\" &&\n !currPattern.ignoreCase\n ) {\n return regExpSource;\n } else if (\n regExpSource.length === 2 &&\n regExpSource[0] === \"\\\\\" &&\n // not a meta character\n !includes(\n [\n \"d\",\n \"D\",\n \"s\",\n \"S\",\n \"t\",\n \"r\",\n \"n\",\n \"t\",\n \"0\",\n \"c\",\n \"b\",\n \"B\",\n \"f\",\n \"v\",\n \"w\",\n \"W\",\n ],\n regExpSource[1],\n )\n ) {\n // escaped meta Characters: /\\+/ /\\[/\n // or redundant escaping: /\\a/\n // without the escaping \"\\\"\n return regExpSource[1];\n } else {\n return options.useSticky\n ? addStickyFlag(currPattern)\n : addStartOfInput(currPattern);\n }\n } else if (isFunction(currPattern)) {\n hasCustom = true;\n // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object\n return { exec: currPattern };\n } else if (typeof currPattern === \"object\") {\n hasCustom = true;\n // ICustomPattern\n return currPattern;\n } else if (typeof currPattern === \"string\") {\n if (currPattern.length === 1) {\n return currPattern;\n } else {\n const escapedRegExpString = currPattern.replace(\n /[\\\\^$.*+?()[\\]{}|]/g,\n \"\\\\$&\",\n );\n const wrappedRegExp = new RegExp(escapedRegExpString);\n return options.useSticky\n ? addStickyFlag(wrappedRegExp)\n : addStartOfInput(wrappedRegExp);\n }\n } else {\n throw Error(\"non exhaustive match\");\n }\n },\n );\n });\n\n let patternIdxToType: number[];\n let patternIdxToGroup: (string | undefined | false)[];\n let patternIdxToLongerAltIdxArr: (number[] | undefined)[];\n let patternIdxToPushMode: (string | undefined)[];\n let patternIdxToPopMode: boolean[];\n tracer(\"misc mapping\", () => {\n patternIdxToType = map(\n onlyRelevantTypes,\n (currType) => currType.tokenTypeIdx!,\n );\n\n patternIdxToGroup = map(onlyRelevantTypes, (clazz: any) => {\n const groupName = clazz.GROUP;\n /* istanbul ignore next */\n if (groupName === Lexer.SKIPPED) {\n return undefined;\n } else if (isString(groupName)) {\n return groupName;\n } else if (isUndefined(groupName)) {\n return false;\n } else {\n throw Error(\"non exhaustive match\");\n }\n });\n\n patternIdxToLongerAltIdxArr = map(onlyRelevantTypes, (clazz: any) => {\n const longerAltType = clazz.LONGER_ALT;\n\n if (longerAltType) {\n const longerAltIdxArr = isArray(longerAltType)\n ? map(longerAltType, (type: any) => indexOf(onlyRelevantTypes, type))\n : [indexOf(onlyRelevantTypes, longerAltType)];\n return longerAltIdxArr;\n }\n });\n\n patternIdxToPushMode = map(\n onlyRelevantTypes,\n (clazz: any) => clazz.PUSH_MODE,\n );\n\n patternIdxToPopMode = map(onlyRelevantTypes, (clazz: any) =>\n has(clazz, \"POP_MODE\"),\n );\n });\n\n let patternIdxToCanLineTerminator: boolean[];\n tracer(\"Line Terminator Handling\", () => {\n const lineTerminatorCharCodes = getCharCodes(\n options.lineTerminatorCharacters!,\n );\n patternIdxToCanLineTerminator = map(onlyRelevantTypes, (tokType) => false);\n if (options.positionTracking !== \"onlyOffset\") {\n patternIdxToCanLineTerminator = map(onlyRelevantTypes, (tokType) => {\n if (has(tokType, \"LINE_BREAKS\")) {\n return !!tokType.LINE_BREAKS;\n } else {\n return (\n checkLineBreaksIssues(tokType, lineTerminatorCharCodes) === false &&\n canMatchCharCode(\n lineTerminatorCharCodes,\n tokType.PATTERN as RegExp | string,\n )\n );\n }\n });\n }\n });\n\n let patternIdxToIsCustom: boolean[];\n let patternIdxToShort: (number | false)[];\n let emptyGroups!: { [groupName: string]: IToken[] };\n let patternIdxToConfig!: IPatternConfig[];\n tracer(\"Misc Mapping #2\", () => {\n patternIdxToIsCustom = map(onlyRelevantTypes, isCustomPattern);\n patternIdxToShort = map(allTransformedPatterns, isShortPattern);\n\n emptyGroups = reduce(\n onlyRelevantTypes,\n (acc, clazz: any) => {\n const groupName = clazz.GROUP;\n if (isString(groupName) && !(groupName === Lexer.SKIPPED)) {\n acc[groupName] = [];\n }\n return acc;\n },\n {} as { [groupName: string]: IToken[] },\n );\n\n patternIdxToConfig = map(\n allTransformedPatterns,\n (x, idx): IPatternConfig => {\n return {\n pattern: allTransformedPatterns[idx],\n longerAlt: patternIdxToLongerAltIdxArr[idx],\n canLineTerminator: patternIdxToCanLineTerminator[idx],\n isCustom: patternIdxToIsCustom[idx],\n short: patternIdxToShort[idx],\n group: patternIdxToGroup[idx],\n push: patternIdxToPushMode[idx],\n pop: patternIdxToPopMode[idx],\n tokenTypeIdx: patternIdxToType[idx],\n tokenType: onlyRelevantTypes[idx],\n };\n },\n );\n });\n\n let canBeOptimized = true;\n let charCodeToPatternIdxToConfig: { [charCode: number]: IPatternConfig[] } =\n [];\n\n if (!options.safeMode) {\n tracer(\"First Char Optimization\", () => {\n charCodeToPatternIdxToConfig = reduce(\n onlyRelevantTypes,\n (result, currTokType, idx) => {\n if (typeof currTokType.PATTERN === \"string\") {\n const charCode = currTokType.PATTERN.charCodeAt(0);\n const optimizedIdx = charCodeToOptimizedIndex(charCode);\n addToMapOfArrays(result, optimizedIdx, patternIdxToConfig[idx]);\n } else if (isArray(currTokType.START_CHARS_HINT)) {\n let lastOptimizedIdx: number;\n forEach(currTokType.START_CHARS_HINT, (charOrInt) => {\n const charCode =\n typeof charOrInt === \"string\"\n ? charOrInt.charCodeAt(0)\n : charOrInt;\n const currOptimizedIdx = charCodeToOptimizedIndex(charCode);\n // Avoid adding the config multiple times\n /* istanbul ignore else */\n // - Difficult to check this scenario effects as it is only a performance\n // optimization that does not change correctness\n if (lastOptimizedIdx !== currOptimizedIdx) {\n lastOptimizedIdx = currOptimizedIdx;\n addToMapOfArrays(\n result,\n currOptimizedIdx,\n patternIdxToConfig[idx],\n );\n }\n });\n } else if (isRegExp(currTokType.PATTERN)) {\n if (currTokType.PATTERN.unicode) {\n canBeOptimized = false;\n if (options.ensureOptimizations) {\n PRINT_ERROR(\n `${failedOptimizationPrefixMsg}` +\n `\\tUnable to analyze < ${currTokType.PATTERN.toString()} > pattern.\\n` +\n \"\\tThe regexp unicode flag is not currently supported by the regexp-to-ast library.\\n\" +\n \"\\tThis will disable the lexer's first char optimizations.\\n\" +\n \"\\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE\",\n );\n }\n } else {\n const optimizedCodes = getOptimizedStartCodesIndices(\n currTokType.PATTERN,\n options.ensureOptimizations,\n );\n /* istanbul ignore if */\n // start code will only be empty given an empty regExp or failure of regexp-to-ast library\n // the first should be a different validation and the second cannot be tested.\n if (isEmpty(optimizedCodes)) {\n // we cannot understand what codes may start possible matches\n // The optimization correctness requires knowing start codes for ALL patterns.\n // Not actually sure this is an error, no debug message\n canBeOptimized = false;\n }\n forEach(optimizedCodes, (code) => {\n addToMapOfArrays(result, code, patternIdxToConfig[idx]);\n });\n }\n } else {\n if (options.ensureOptimizations) {\n PRINT_ERROR(\n `${failedOptimizationPrefixMsg}` +\n `\\tTokenType: <${currTokType.name}> is using a custom token pattern without providing parameter.\\n` +\n \"\\tThis will disable the lexer's first char optimizations.\\n\" +\n \"\\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE\",\n );\n }\n canBeOptimized = false;\n }\n\n return result;\n },\n [] as { [charCode: number]: IPatternConfig[] },\n );\n });\n }\n\n return {\n emptyGroups: emptyGroups,\n patternIdxToConfig: patternIdxToConfig,\n charCodeToPatternIdxToConfig: charCodeToPatternIdxToConfig,\n hasCustom: hasCustom,\n canBeOptimized: canBeOptimized,\n };\n}\n\nexport function validatePatterns(\n tokenTypes: TokenType[],\n validModesNames: string[],\n): ILexerDefinitionError[] {\n let errors: ILexerDefinitionError[] = [];\n\n const missingResult = findMissingPatterns(tokenTypes);\n errors = errors.concat(missingResult.errors);\n\n const invalidResult = findInvalidPatterns(missingResult.valid);\n const validTokenTypes = invalidResult.valid;\n errors = errors.concat(invalidResult.errors);\n\n errors = errors.concat(validateRegExpPattern(validTokenTypes));\n\n errors = errors.concat(findInvalidGroupType(validTokenTypes));\n\n errors = errors.concat(\n findModesThatDoNotExist(validTokenTypes, validModesNames),\n );\n\n errors = errors.concat(findUnreachablePatterns(validTokenTypes));\n\n return errors;\n}\n\nfunction validateRegExpPattern(\n tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n let errors: ILexerDefinitionError[] = [];\n const withRegExpPatterns = filter(tokenTypes, (currTokType) =>\n isRegExp(currTokType[PATTERN]),\n );\n\n errors = errors.concat(findEndOfInputAnchor(withRegExpPatterns));\n\n errors = errors.concat(findStartOfInputAnchor(withRegExpPatterns));\n\n errors = errors.concat(findUnsupportedFlags(withRegExpPatterns));\n\n errors = errors.concat(findDuplicatePatterns(withRegExpPatterns));\n\n errors = errors.concat(findEmptyMatchRegExps(withRegExpPatterns));\n\n return errors;\n}\n\nexport interface ILexerFilterResult {\n errors: ILexerDefinitionError[];\n valid: TokenType[];\n}\n\nexport function findMissingPatterns(\n tokenTypes: TokenType[],\n): ILexerFilterResult {\n const tokenTypesWithMissingPattern = filter(tokenTypes, (currType) => {\n return !has(currType, PATTERN);\n });\n\n const errors = map(tokenTypesWithMissingPattern, (currType) => {\n return {\n message:\n \"Token Type: ->\" +\n currType.name +\n \"<- missing static 'PATTERN' property\",\n type: LexerDefinitionErrorType.MISSING_PATTERN,\n tokenTypes: [currType],\n };\n });\n\n const valid = difference(tokenTypes, tokenTypesWithMissingPattern);\n return { errors, valid };\n}\n\nexport function findInvalidPatterns(\n tokenTypes: TokenType[],\n): ILexerFilterResult {\n const tokenTypesWithInvalidPattern = filter(tokenTypes, (currType) => {\n const pattern = currType[PATTERN];\n return (\n !isRegExp(pattern) &&\n !isFunction(pattern) &&\n !has(pattern, \"exec\") &&\n !isString(pattern)\n );\n });\n\n const errors = map(tokenTypesWithInvalidPattern, (currType) => {\n return {\n message:\n \"Token Type: ->\" +\n currType.name +\n \"<- static 'PATTERN' can only be a RegExp, a\" +\n \" Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.\",\n type: LexerDefinitionErrorType.INVALID_PATTERN,\n tokenTypes: [currType],\n };\n });\n\n const valid = difference(tokenTypes, tokenTypesWithInvalidPattern);\n return { errors, valid };\n}\n\nconst end_of_input = /[^\\\\][$]/;\n\nexport function findEndOfInputAnchor(\n tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n class EndAnchorFinder extends BaseRegExpVisitor {\n found = false;\n\n visitEndAnchor(node: unknown) {\n this.found = true;\n }\n }\n\n const invalidRegex = filter(tokenTypes, (currType) => {\n const pattern = currType.PATTERN;\n\n try {\n const regexpAst = getRegExpAst(pattern as RegExp);\n const endAnchorVisitor = new EndAnchorFinder();\n endAnchorVisitor.visit(regexpAst);\n\n return endAnchorVisitor.found;\n } catch (e) {\n // old behavior in case of runtime exceptions with regexp-to-ast.\n /* istanbul ignore next - cannot ensure an error in regexp-to-ast*/\n return end_of_input.test((pattern as RegExp).source);\n }\n });\n\n const errors = map(invalidRegex, (currType) => {\n return {\n message:\n \"Unexpected RegExp Anchor Error:\\n\" +\n \"\\tToken Type: ->\" +\n currType.name +\n \"<- static 'PATTERN' cannot contain end of input anchor '$'\\n\" +\n \"\\tSee chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS\" +\n \"\\tfor details.\",\n type: LexerDefinitionErrorType.EOI_ANCHOR_FOUND,\n tokenTypes: [currType],\n };\n });\n\n return errors;\n}\n\nexport function findEmptyMatchRegExps(\n tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n const matchesEmptyString = filter(tokenTypes, (currType) => {\n const pattern = currType.PATTERN as RegExp;\n return pattern.test(\"\");\n });\n\n const errors = map(matchesEmptyString, (currType) => {\n return {\n message:\n \"Token Type: ->\" +\n currType.name +\n \"<- static 'PATTERN' must not match an empty string\",\n type: LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,\n tokenTypes: [currType],\n };\n });\n\n return errors;\n}\n\nconst start_of_input = /[^\\\\[][\\^]|^\\^/;\n\nexport function findStartOfInputAnchor(\n tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n class StartAnchorFinder extends BaseRegExpVisitor {\n found = false;\n\n visitStartAnchor(node: unknown) {\n this.found = true;\n }\n }\n\n const invalidRegex = filter(tokenTypes, (currType) => {\n const pattern = currType.PATTERN as RegExp;\n try {\n const regexpAst = getRegExpAst(pattern);\n const startAnchorVisitor = new StartAnchorFinder();\n startAnchorVisitor.visit(regexpAst);\n\n return startAnchorVisitor.found;\n } catch (e) {\n // old behavior in case of runtime exceptions with regexp-to-ast.\n /* istanbul ignore next - cannot ensure an error in regexp-to-ast*/\n return start_of_input.test(pattern.source);\n }\n });\n\n const errors = map(invalidRegex, (currType) => {\n return {\n message:\n \"Unexpected RegExp Anchor Error:\\n\" +\n \"\\tToken Type: ->\" +\n currType.name +\n \"<- static 'PATTERN' cannot contain start of input anchor '^'\\n\" +\n \"\\tSee https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS\" +\n \"\\tfor details.\",\n type: LexerDefinitionErrorType.SOI_ANCHOR_FOUND,\n tokenTypes: [currType],\n };\n });\n\n return errors;\n}\n\nexport function findUnsupportedFlags(\n tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n const invalidFlags = filter(tokenTypes, (currType) => {\n const pattern = currType[PATTERN];\n return pattern instanceof RegExp && (pattern.multiline || pattern.global);\n });\n\n const errors = map(invalidFlags, (currType) => {\n return {\n message:\n \"Token Type: ->\" +\n currType.name +\n \"<- static 'PATTERN' may NOT contain global('g') or multiline('m')\",\n type: LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,\n tokenTypes: [currType],\n };\n });\n\n return errors;\n}\n\n// This can only test for identical duplicate RegExps, not semantically equivalent ones.\nexport function findDuplicatePatterns(\n tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n const found: TokenType[] = [];\n let identicalPatterns = map(tokenTypes, (outerType: any) => {\n return reduce(\n tokenTypes,\n (result, innerType) => {\n if (\n outerType.PATTERN.source === (innerType.PATTERN as RegExp).source &&\n !includes(found, innerType) &&\n innerType.PATTERN !== Lexer.NA\n ) {\n // this avoids duplicates in the result, each Token Type may only appear in one \"set\"\n // in essence we are creating Equivalence classes on equality relation.\n found.push(innerType);\n result.push(innerType);\n return result;\n }\n return result;\n },\n [] as TokenType[],\n );\n });\n\n identicalPatterns = compact(identicalPatterns);\n\n const duplicatePatterns = filter(identicalPatterns, (currIdenticalSet) => {\n return currIdenticalSet.length > 1;\n });\n\n const errors = map(duplicatePatterns, (setOfIdentical: any) => {\n const tokenTypeNames = map(setOfIdentical, (currType: any) => {\n return currType.name;\n });\n\n const dupPatternSrc = (first(setOfIdentical)).PATTERN;\n return {\n message:\n `The same RegExp pattern ->${dupPatternSrc}<-` +\n `has been used in all of the following Token Types: ${tokenTypeNames.join(\n \", \",\n )} <-`,\n type: LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,\n tokenTypes: setOfIdentical,\n };\n });\n\n return errors;\n}\n\nexport function findInvalidGroupType(\n tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n const invalidTypes = filter(tokenTypes, (clazz: any) => {\n if (!has(clazz, \"GROUP\")) {\n return false;\n }\n const group = clazz.GROUP;\n\n return group !== Lexer.SKIPPED && group !== Lexer.NA && !isString(group);\n });\n\n const errors = map(invalidTypes, (currType) => {\n return {\n message:\n \"Token Type: ->\" +\n currType.name +\n \"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String\",\n type: LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,\n tokenTypes: [currType],\n };\n });\n\n return errors;\n}\n\nexport function findModesThatDoNotExist(\n tokenTypes: TokenType[],\n validModes: string[],\n): ILexerDefinitionError[] {\n const invalidModes = filter(tokenTypes, (clazz: any) => {\n return (\n clazz.PUSH_MODE !== undefined && !includes(validModes, clazz.PUSH_MODE)\n );\n });\n\n const errors = map(invalidModes, (tokType) => {\n const msg =\n `Token Type: ->${tokType.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${tokType.PUSH_MODE}<-` +\n `which does not exist`;\n return {\n message: msg,\n type: LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,\n tokenTypes: [tokType],\n };\n });\n\n return errors;\n}\n\nexport function findUnreachablePatterns(\n tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n const errors: ILexerDefinitionError[] = [];\n\n const canBeTested = reduce(\n tokenTypes,\n (result, tokType, idx) => {\n const pattern = tokType.PATTERN;\n\n if (pattern === Lexer.NA) {\n return result;\n }\n\n // a more comprehensive validation for all forms of regExps would require\n // deeper regExp analysis capabilities\n if (isString(pattern)) {\n result.push({ str: pattern, idx, tokenType: tokType });\n } else if (isRegExp(pattern) && noMetaChar(pattern)) {\n result.push({ str: pattern.source, idx, tokenType: tokType });\n }\n return result;\n },\n [] as { str: string; idx: number; tokenType: TokenType }[],\n );\n\n forEach(tokenTypes, (tokType, testIdx) => {\n forEach(canBeTested, ({ str, idx, tokenType }) => {\n if (testIdx < idx && testTokenType(str, tokType.PATTERN)) {\n const msg =\n `Token: ->${tokenType.name}<- can never be matched.\\n` +\n `Because it appears AFTER the Token Type ->${tokType.name}<-` +\n `in the lexer's definition.\\n` +\n `See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;\n errors.push({\n message: msg,\n type: LexerDefinitionErrorType.UNREACHABLE_PATTERN,\n tokenTypes: [tokType, tokenType],\n });\n }\n });\n });\n\n return errors;\n}\n\nfunction testTokenType(str: string, pattern: any): boolean {\n /* istanbul ignore else */\n if (isRegExp(pattern)) {\n const regExpArray = pattern.exec(str);\n return regExpArray !== null && regExpArray.index === 0;\n } else if (isFunction(pattern)) {\n // maintain the API of custom patterns\n return pattern(str, 0, [], {});\n } else if (has(pattern, \"exec\")) {\n // maintain the API of custom patterns\n return pattern.exec(str, 0, [], {});\n } else if (typeof pattern === \"string\") {\n return pattern === str;\n } else {\n throw Error(\"non exhaustive match\");\n }\n}\n\nfunction noMetaChar(regExp: RegExp): boolean {\n //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp\n const metaChars = [\n \".\",\n \"\\\\\",\n \"[\",\n \"]\",\n \"|\",\n \"^\",\n \"$\",\n \"(\",\n \")\",\n \"?\",\n \"*\",\n \"+\",\n \"{\",\n ];\n return (\n find(metaChars, (char) => regExp.source.indexOf(char) !== -1) === undefined\n );\n}\n\nexport function addStartOfInput(pattern: RegExp): RegExp {\n const flags = pattern.ignoreCase ? \"i\" : \"\";\n // always wrapping in a none capturing group preceded by '^' to make sure matching can only work on start of input.\n // duplicate/redundant start of input markers have no meaning (/^^^^A/ === /^A/)\n return new RegExp(`^(?:${pattern.source})`, flags);\n}\n\nexport function addStickyFlag(pattern: RegExp): RegExp {\n const flags = pattern.ignoreCase ? \"iy\" : \"y\";\n // always wrapping in a none capturing group preceded by '^' to make sure matching can only work on start of input.\n // duplicate/redundant start of input markers have no meaning (/^^^^A/ === /^A/)\n return new RegExp(`${pattern.source}`, flags);\n}\n\nexport function performRuntimeChecks(\n lexerDefinition: IMultiModeLexerDefinition,\n trackLines: boolean,\n lineTerminatorCharacters: (number | string)[],\n): ILexerDefinitionError[] {\n const errors: ILexerDefinitionError[] = [];\n\n // some run time checks to help the end users.\n if (!has(lexerDefinition, DEFAULT_MODE)) {\n errors.push({\n message:\n \"A MultiMode Lexer cannot be initialized without a <\" +\n DEFAULT_MODE +\n \"> property in its definition\\n\",\n type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE,\n });\n }\n if (!has(lexerDefinition, MODES)) {\n errors.push({\n message:\n \"A MultiMode Lexer cannot be initialized without a <\" +\n MODES +\n \"> property in its definition\\n\",\n type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY,\n });\n }\n\n if (\n has(lexerDefinition, MODES) &&\n has(lexerDefinition, DEFAULT_MODE) &&\n !has(lexerDefinition.modes, lexerDefinition.defaultMode)\n ) {\n errors.push({\n message:\n `A MultiMode Lexer cannot be initialized with a ${DEFAULT_MODE}: <${lexerDefinition.defaultMode}>` +\n `which does not exist\\n`,\n type: LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST,\n });\n }\n\n if (has(lexerDefinition, MODES)) {\n forEach(lexerDefinition.modes, (currModeValue, currModeName) => {\n forEach(currModeValue, (currTokType, currIdx) => {\n if (isUndefined(currTokType)) {\n errors.push({\n message:\n `A Lexer cannot be initialized using an undefined Token Type. Mode:` +\n `<${currModeName}> at index: <${currIdx}>\\n`,\n type: LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED,\n });\n } else if (has(currTokType, \"LONGER_ALT\")) {\n const longerAlt = isArray(currTokType.LONGER_ALT)\n ? currTokType.LONGER_ALT\n : [currTokType.LONGER_ALT];\n forEach(longerAlt, (currLongerAlt) => {\n if (\n !isUndefined(currLongerAlt) &&\n !includes(currModeValue, currLongerAlt)\n ) {\n errors.push({\n message: `A MultiMode Lexer cannot be initialized with a longer_alt <${currLongerAlt.name}> on token <${currTokType.name}> outside of mode <${currModeName}>\\n`,\n type: LexerDefinitionErrorType.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE,\n });\n }\n });\n }\n });\n });\n }\n\n return errors;\n}\n\nexport function performWarningRuntimeChecks(\n lexerDefinition: IMultiModeLexerDefinition,\n trackLines: boolean,\n lineTerminatorCharacters: (number | string)[],\n): ILexerDefinitionError[] {\n const warnings = [];\n let hasAnyLineBreak = false;\n const allTokenTypes = compact(flatten(values(lexerDefinition.modes)));\n\n const concreteTokenTypes = reject(\n allTokenTypes,\n (currType) => currType[PATTERN] === Lexer.NA,\n );\n const terminatorCharCodes = getCharCodes(lineTerminatorCharacters);\n if (trackLines) {\n forEach(concreteTokenTypes, (tokType) => {\n const currIssue = checkLineBreaksIssues(tokType, terminatorCharCodes);\n if (currIssue !== false) {\n const message = buildLineBreakIssueMessage(tokType, currIssue);\n const warningDescriptor = {\n message,\n type: currIssue.issue,\n tokenType: tokType,\n };\n warnings.push(warningDescriptor);\n } else {\n // we don't want to attempt to scan if the user explicitly specified the line_breaks option.\n if (has(tokType, \"LINE_BREAKS\")) {\n if (tokType.LINE_BREAKS === true) {\n hasAnyLineBreak = true;\n }\n } else {\n if (\n canMatchCharCode(terminatorCharCodes, tokType.PATTERN as RegExp)\n ) {\n hasAnyLineBreak = true;\n }\n }\n }\n });\n }\n\n if (trackLines && !hasAnyLineBreak) {\n warnings.push({\n message:\n \"Warning: No LINE_BREAKS Found.\\n\" +\n \"\\tThis Lexer has been defined to track line and column information,\\n\" +\n \"\\tBut none of the Token Types can be identified as matching a line terminator.\\n\" +\n \"\\tSee https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \\n\" +\n \"\\tfor details.\",\n type: LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS,\n });\n }\n return warnings;\n}\n\nexport function cloneEmptyGroups(emptyGroups: {\n [groupName: string]: IToken;\n}): { [groupName: string]: IToken } {\n const clonedResult: any = {};\n const groupKeys = keys(emptyGroups);\n\n forEach(groupKeys, (currKey) => {\n const currGroupValue = emptyGroups[currKey];\n\n /* istanbul ignore else */\n if (isArray(currGroupValue)) {\n clonedResult[currKey] = [];\n } else {\n throw Error(\"non exhaustive match\");\n }\n });\n\n return clonedResult;\n}\n\n// TODO: refactor to avoid duplication\nexport function isCustomPattern(tokenType: TokenType): boolean {\n const pattern = tokenType.PATTERN;\n /* istanbul ignore else */\n if (isRegExp(pattern)) {\n return false;\n } else if (isFunction(pattern)) {\n // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object\n return true;\n } else if (has(pattern, \"exec\")) {\n // ICustomPattern\n return true;\n } else if (isString(pattern)) {\n return false;\n } else {\n throw Error(\"non exhaustive match\");\n }\n}\n\nexport function isShortPattern(pattern: any): number | false {\n if (isString(pattern) && pattern.length === 1) {\n return pattern.charCodeAt(0);\n } else {\n return false;\n }\n}\n\n/**\n * Faster than using a RegExp for default newline detection during lexing.\n */\nexport const LineTerminatorOptimizedTester: ILineTerminatorsTester = {\n // implements /\\n|\\r\\n?/g.test\n test: function (text) {\n const len = text.length;\n for (let i = this.lastIndex; i < len; i++) {\n const c = text.charCodeAt(i);\n if (c === 10) {\n this.lastIndex = i + 1;\n return true;\n } else if (c === 13) {\n if (text.charCodeAt(i + 1) === 10) {\n this.lastIndex = i + 2;\n } else {\n this.lastIndex = i + 1;\n }\n return true;\n }\n }\n return false;\n },\n\n lastIndex: 0,\n};\n\nfunction checkLineBreaksIssues(\n tokType: TokenType,\n lineTerminatorCharCodes: number[],\n):\n | {\n issue:\n | LexerDefinitionErrorType.IDENTIFY_TERMINATOR\n | LexerDefinitionErrorType.CUSTOM_LINE_BREAK;\n errMsg?: string;\n }\n | false {\n if (has(tokType, \"LINE_BREAKS\")) {\n // if the user explicitly declared the line_breaks option we will respect their choice\n // and assume it is correct.\n return false;\n } else {\n /* istanbul ignore else */\n if (isRegExp(tokType.PATTERN)) {\n try {\n // TODO: why is the casting suddenly needed?\n canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN as RegExp);\n } catch (e) {\n /* istanbul ignore next - to test this we would have to mock to throw an error */\n return {\n issue: LexerDefinitionErrorType.IDENTIFY_TERMINATOR,\n errMsg: (e as Error).message,\n };\n }\n return false;\n } else if (isString(tokType.PATTERN)) {\n // string literal patterns can always be analyzed to detect line terminator usage\n return false;\n } else if (isCustomPattern(tokType)) {\n // custom token types\n return { issue: LexerDefinitionErrorType.CUSTOM_LINE_BREAK };\n } else {\n throw Error(\"non exhaustive match\");\n }\n }\n}\n\nexport function buildLineBreakIssueMessage(\n tokType: TokenType,\n details: {\n issue:\n | LexerDefinitionErrorType.IDENTIFY_TERMINATOR\n | LexerDefinitionErrorType.CUSTOM_LINE_BREAK;\n errMsg?: string;\n },\n): string {\n /* istanbul ignore else */\n if (details.issue === LexerDefinitionErrorType.IDENTIFY_TERMINATOR) {\n return (\n \"Warning: unable to identify line terminator usage in pattern.\\n\" +\n `\\tThe problem is in the <${tokType.name}> Token Type\\n` +\n `\\t Root cause: ${details.errMsg}.\\n` +\n \"\\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR\"\n );\n } else if (details.issue === LexerDefinitionErrorType.CUSTOM_LINE_BREAK) {\n return (\n \"Warning: A Custom Token Pattern should specify the option.\\n\" +\n `\\tThe problem is in the <${tokType.name}> Token Type\\n` +\n \"\\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK\"\n );\n } else {\n throw Error(\"non exhaustive match\");\n }\n}\n\nfunction getCharCodes(charsOrCodes: (number | string)[]): number[] {\n const charCodes = map(charsOrCodes, (numOrString) => {\n if (isString(numOrString)) {\n return numOrString.charCodeAt(0);\n } else {\n return numOrString;\n }\n });\n\n return charCodes;\n}\n\nfunction addToMapOfArrays(\n map: Record,\n key: number,\n value: T,\n): void {\n if (map[key] === undefined) {\n map[key] = [value];\n } else {\n map[key].push(value);\n }\n}\n\nexport const minOptimizationVal = 256;\n\n/**\n * We are mapping charCode above ASCI (256) into buckets each in the size of 256.\n * This is because ASCI are the most common start chars so each one of those will get its own\n * possible token configs vector.\n *\n * Tokens starting with charCodes \"above\" ASCI are uncommon, so we can \"afford\"\n * to place these into buckets of possible token configs, What we gain from\n * this is avoiding the case of creating an optimization 'charCodeToPatternIdxToConfig'\n * which would contain 10,000+ arrays of small size (e.g unicode Identifiers scenario).\n * Our 'charCodeToPatternIdxToConfig' max size will now be:\n * 256 + (2^16 / 2^8) - 1 === 511\n *\n * note the hack for fast division integer part extraction\n * See: https://stackoverflow.com/a/4228528\n */\nlet charCodeToOptimizedIdxMap: number[] = [];\nexport function charCodeToOptimizedIndex(charCode: number): number {\n return charCode < minOptimizationVal\n ? charCode\n : charCodeToOptimizedIdxMap[charCode];\n}\n\n/**\n * This is a compromise between cold start / hot running performance\n * Creating this array takes ~3ms on a modern machine,\n * But if we perform the computation at runtime as needed the CSS Lexer benchmark\n * performance degrades by ~10%\n *\n * TODO: Perhaps it should be lazy initialized only if a charCode > 255 is used.\n */\nfunction initCharCodeToOptimizedIndexMap() {\n if (isEmpty(charCodeToOptimizedIdxMap)) {\n charCodeToOptimizedIdxMap = new Array(65536);\n for (let i = 0; i < 65536; i++) {\n charCodeToOptimizedIdxMap[i] = i > 255 ? 255 + ~~(i / 255) : i;\n }\n }\n}\n", "import {\n clone,\n compact,\n difference,\n flatten,\n forEach,\n has,\n includes,\n isArray,\n isEmpty,\n map,\n} from \"lodash-es\";\nimport { IToken, TokenType } from \"@chevrotain/types\";\n\nexport function tokenStructuredMatcher(\n tokInstance: IToken,\n tokConstructor: TokenType,\n) {\n const instanceType = tokInstance.tokenTypeIdx;\n if (instanceType === tokConstructor.tokenTypeIdx) {\n return true;\n } else {\n return (\n tokConstructor.isParent === true &&\n tokConstructor.categoryMatchesMap![instanceType] === true\n );\n }\n}\n\n// Optimized tokenMatcher in case our grammar does not use token categories\n// Being so tiny it is much more likely to be in-lined and this avoid the function call overhead\nexport function tokenStructuredMatcherNoCategories(\n token: IToken,\n tokType: TokenType,\n) {\n return token.tokenTypeIdx === tokType.tokenTypeIdx;\n}\n\nexport let tokenShortNameIdx = 1;\nexport const tokenIdxToClass: { [tokenIdx: number]: TokenType } = {};\n\nexport function augmentTokenTypes(tokenTypes: TokenType[]): void {\n // collect the parent Token Types as well.\n const tokenTypesAndParents = expandCategories(tokenTypes);\n\n // add required tokenType and categoryMatches properties\n assignTokenDefaultProps(tokenTypesAndParents);\n\n // fill up the categoryMatches\n assignCategoriesMapProp(tokenTypesAndParents);\n assignCategoriesTokensProp(tokenTypesAndParents);\n\n forEach(tokenTypesAndParents, (tokType) => {\n tokType.isParent = tokType.categoryMatches!.length > 0;\n });\n}\n\nexport function expandCategories(tokenTypes: TokenType[]): TokenType[] {\n let result = clone(tokenTypes);\n\n let categories = tokenTypes;\n let searching = true;\n while (searching) {\n categories = compact(\n flatten(map(categories, (currTokType) => currTokType.CATEGORIES)),\n );\n\n const newCategories = difference(categories, result);\n\n result = result.concat(newCategories);\n\n if (isEmpty(newCategories)) {\n searching = false;\n } else {\n categories = newCategories;\n }\n }\n return result;\n}\n\nexport function assignTokenDefaultProps(tokenTypes: TokenType[]): void {\n forEach(tokenTypes, (currTokType) => {\n if (!hasShortKeyProperty(currTokType)) {\n tokenIdxToClass[tokenShortNameIdx] = currTokType;\n (currTokType).tokenTypeIdx = tokenShortNameIdx++;\n }\n\n // CATEGORIES? : TokenType | TokenType[]\n if (\n hasCategoriesProperty(currTokType) &&\n !isArray(currTokType.CATEGORIES)\n // &&\n // !isUndefined(currTokType.CATEGORIES.PATTERN)\n ) {\n currTokType.CATEGORIES = [currTokType.CATEGORIES as unknown as TokenType];\n }\n\n if (!hasCategoriesProperty(currTokType)) {\n currTokType.CATEGORIES = [];\n }\n\n if (!hasExtendingTokensTypesProperty(currTokType)) {\n currTokType.categoryMatches = [];\n }\n\n if (!hasExtendingTokensTypesMapProperty(currTokType)) {\n currTokType.categoryMatchesMap = {};\n }\n });\n}\n\nexport function assignCategoriesTokensProp(tokenTypes: TokenType[]): void {\n forEach(tokenTypes, (currTokType) => {\n // avoid duplications\n currTokType.categoryMatches = [];\n forEach(currTokType.categoryMatchesMap!, (val, key) => {\n currTokType.categoryMatches!.push(\n tokenIdxToClass[key as unknown as number].tokenTypeIdx!,\n );\n });\n });\n}\n\nexport function assignCategoriesMapProp(tokenTypes: TokenType[]): void {\n forEach(tokenTypes, (currTokType) => {\n singleAssignCategoriesToksMap([], currTokType);\n });\n}\n\nexport function singleAssignCategoriesToksMap(\n path: TokenType[],\n nextNode: TokenType,\n): void {\n forEach(path, (pathNode) => {\n nextNode.categoryMatchesMap![pathNode.tokenTypeIdx!] = true;\n });\n\n forEach(nextNode.CATEGORIES, (nextCategory) => {\n const newPath = path.concat(nextNode);\n // avoids infinite loops due to cyclic categories.\n if (!includes(newPath, nextCategory)) {\n singleAssignCategoriesToksMap(newPath, nextCategory);\n }\n });\n}\n\nexport function hasShortKeyProperty(tokType: TokenType): boolean {\n return has(tokType, \"tokenTypeIdx\");\n}\n\nexport function hasCategoriesProperty(tokType: TokenType): boolean {\n return has(tokType, \"CATEGORIES\");\n}\n\nexport function hasExtendingTokensTypesProperty(tokType: TokenType): boolean {\n return has(tokType, \"categoryMatches\");\n}\n\nexport function hasExtendingTokensTypesMapProperty(\n tokType: TokenType,\n): boolean {\n return has(tokType, \"categoryMatchesMap\");\n}\n\nexport function isTokenType(tokType: TokenType): boolean {\n return has(tokType, \"tokenTypeIdx\");\n}\n", "import { ILexerErrorMessageProvider, IToken } from \"@chevrotain/types\";\n\nexport const defaultLexerErrorProvider: ILexerErrorMessageProvider = {\n buildUnableToPopLexerModeMessage(token: IToken): string {\n return `Unable to pop Lexer Mode after encountering Token ->${token.image}<- The Mode Stack is empty`;\n },\n\n buildUnexpectedCharactersMessage(\n fullText: string,\n startOffset: number,\n length: number,\n line?: number,\n column?: number,\n ): string {\n return (\n `unexpected character: ->${fullText.charAt(\n startOffset,\n )}<- at offset: ${startOffset},` + ` skipped ${length} characters.`\n );\n },\n};\n", "import {\n analyzeTokenTypes,\n charCodeToOptimizedIndex,\n cloneEmptyGroups,\n DEFAULT_MODE,\n IAnalyzeResult,\n IPatternConfig,\n LineTerminatorOptimizedTester,\n performRuntimeChecks,\n performWarningRuntimeChecks,\n SUPPORT_STICKY,\n validatePatterns,\n} from \"./lexer.js\";\nimport {\n assign,\n clone,\n forEach,\n identity,\n isArray,\n isEmpty,\n isUndefined,\n keys,\n last,\n map,\n noop,\n reduce,\n reject,\n} from \"lodash-es\";\nimport { PRINT_WARNING, timer, toFastProperties } from \"@chevrotain/utils\";\nimport { augmentTokenTypes } from \"./tokens.js\";\nimport {\n CustomPatternMatcherFunc,\n CustomPatternMatcherReturn,\n ILexerConfig,\n ILexerDefinitionError,\n ILexingError,\n IMultiModeLexerDefinition,\n IToken,\n TokenType,\n} from \"@chevrotain/types\";\nimport { defaultLexerErrorProvider } from \"./lexer_errors_public.js\";\nimport { clearRegExpParserCache } from \"./reg_exp_parser.js\";\n\nexport interface ILexingResult {\n tokens: IToken[];\n groups: { [groupName: string]: IToken[] };\n errors: ILexingError[];\n}\n\nexport enum LexerDefinitionErrorType {\n MISSING_PATTERN,\n INVALID_PATTERN,\n EOI_ANCHOR_FOUND,\n UNSUPPORTED_FLAGS_FOUND,\n DUPLICATE_PATTERNS_FOUND,\n INVALID_GROUP_TYPE_FOUND,\n PUSH_MODE_DOES_NOT_EXIST,\n MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE,\n MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY,\n MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST,\n LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED,\n SOI_ANCHOR_FOUND,\n EMPTY_MATCH_PATTERN,\n NO_LINE_BREAKS_FLAGS,\n UNREACHABLE_PATTERN,\n IDENTIFY_TERMINATOR,\n CUSTOM_LINE_BREAK,\n MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE,\n}\n\nexport interface IRegExpExec {\n exec: CustomPatternMatcherFunc;\n}\n\nconst DEFAULT_LEXER_CONFIG: Required = {\n deferDefinitionErrorsHandling: false,\n positionTracking: \"full\",\n lineTerminatorsPattern: /\\n|\\r\\n?/g,\n lineTerminatorCharacters: [\"\\n\", \"\\r\"],\n ensureOptimizations: false,\n safeMode: false,\n errorMessageProvider: defaultLexerErrorProvider,\n traceInitPerf: false,\n skipValidations: false,\n recoveryEnabled: true,\n};\n\nObject.freeze(DEFAULT_LEXER_CONFIG);\n\nexport class Lexer {\n public static SKIPPED =\n \"This marks a skipped Token pattern, this means each token identified by it will\" +\n \"be consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.\";\n\n public static NA = /NOT_APPLICABLE/;\n public lexerDefinitionErrors: ILexerDefinitionError[] = [];\n public lexerDefinitionWarning: ILexerDefinitionError[] = [];\n\n protected patternIdxToConfig: Record = {};\n protected charCodeToPatternIdxToConfig: {\n [modeName: string]: { [charCode: number]: IPatternConfig[] };\n } = {};\n\n protected modes: string[] = [];\n protected defaultMode!: string;\n protected emptyGroups: { [groupName: string]: IToken } = {};\n\n private config: Required;\n private trackStartLines: boolean = true;\n private trackEndLines: boolean = true;\n private hasCustom: boolean = false;\n private canModeBeOptimized: Record = {};\n\n private traceInitPerf!: boolean | number;\n private traceInitMaxIdent!: number;\n private traceInitIndent: number;\n\n constructor(\n protected lexerDefinition: TokenType[] | IMultiModeLexerDefinition,\n config: ILexerConfig = DEFAULT_LEXER_CONFIG,\n ) {\n if (typeof config === \"boolean\") {\n throw Error(\n \"The second argument to the Lexer constructor is now an ILexerConfig Object.\\n\" +\n \"a boolean 2nd argument is no longer supported\",\n );\n }\n\n // todo: defaults func?\n this.config = assign({}, DEFAULT_LEXER_CONFIG, config) as any;\n\n const traceInitVal = this.config.traceInitPerf;\n if (traceInitVal === true) {\n this.traceInitMaxIdent = Infinity;\n this.traceInitPerf = true;\n } else if (typeof traceInitVal === \"number\") {\n this.traceInitMaxIdent = traceInitVal;\n this.traceInitPerf = true;\n }\n this.traceInitIndent = -1;\n\n this.TRACE_INIT(\"Lexer Constructor\", () => {\n let actualDefinition!: IMultiModeLexerDefinition;\n let hasOnlySingleMode = true;\n this.TRACE_INIT(\"Lexer Config handling\", () => {\n if (\n this.config.lineTerminatorsPattern ===\n DEFAULT_LEXER_CONFIG.lineTerminatorsPattern\n ) {\n // optimized built-in implementation for the defaults definition of lineTerminators\n this.config.lineTerminatorsPattern = LineTerminatorOptimizedTester;\n } else {\n if (\n this.config.lineTerminatorCharacters ===\n DEFAULT_LEXER_CONFIG.lineTerminatorCharacters\n ) {\n throw Error(\n \"Error: Missing property on the Lexer config.\\n\" +\n \"\\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS\",\n );\n }\n }\n\n if (config.safeMode && config.ensureOptimizations) {\n throw Error(\n '\"safeMode\" and \"ensureOptimizations\" flags are mutually exclusive.',\n );\n }\n\n this.trackStartLines = /full|onlyStart/i.test(\n this.config.positionTracking,\n );\n this.trackEndLines = /full/i.test(this.config.positionTracking);\n\n // Convert SingleModeLexerDefinition into a IMultiModeLexerDefinition.\n if (isArray(lexerDefinition)) {\n actualDefinition = {\n modes: { defaultMode: clone(lexerDefinition) },\n defaultMode: DEFAULT_MODE,\n };\n } else {\n // no conversion needed, input should already be a IMultiModeLexerDefinition\n hasOnlySingleMode = false;\n actualDefinition = clone(lexerDefinition);\n }\n });\n\n if (this.config.skipValidations === false) {\n this.TRACE_INIT(\"performRuntimeChecks\", () => {\n this.lexerDefinitionErrors = this.lexerDefinitionErrors.concat(\n performRuntimeChecks(\n actualDefinition,\n this.trackStartLines,\n this.config.lineTerminatorCharacters,\n ),\n );\n });\n\n this.TRACE_INIT(\"performWarningRuntimeChecks\", () => {\n this.lexerDefinitionWarning = this.lexerDefinitionWarning.concat(\n performWarningRuntimeChecks(\n actualDefinition,\n this.trackStartLines,\n this.config.lineTerminatorCharacters,\n ),\n );\n });\n }\n\n // for extra robustness to avoid throwing an none informative error message\n actualDefinition.modes = actualDefinition.modes\n ? actualDefinition.modes\n : {};\n\n // an error of undefined TokenTypes will be detected in \"performRuntimeChecks\" above.\n // this transformation is to increase robustness in the case of partially invalid lexer definition.\n forEach(actualDefinition.modes, (currModeValue, currModeName) => {\n actualDefinition.modes[currModeName] = reject(\n currModeValue,\n (currTokType) => isUndefined(currTokType),\n );\n });\n\n const allModeNames = keys(actualDefinition.modes);\n\n forEach(\n actualDefinition.modes,\n (currModDef: TokenType[], currModName) => {\n this.TRACE_INIT(`Mode: <${currModName}> processing`, () => {\n this.modes.push(currModName);\n\n if (this.config.skipValidations === false) {\n this.TRACE_INIT(`validatePatterns`, () => {\n this.lexerDefinitionErrors = this.lexerDefinitionErrors.concat(\n validatePatterns(currModDef, allModeNames),\n );\n });\n }\n\n // If definition errors were encountered, the analysis phase may fail unexpectedly/\n // Considering a lexer with definition errors may never be used, there is no point\n // to performing the analysis anyhow...\n if (isEmpty(this.lexerDefinitionErrors)) {\n augmentTokenTypes(currModDef);\n\n let currAnalyzeResult!: IAnalyzeResult;\n this.TRACE_INIT(`analyzeTokenTypes`, () => {\n currAnalyzeResult = analyzeTokenTypes(currModDef, {\n lineTerminatorCharacters:\n this.config.lineTerminatorCharacters,\n positionTracking: config.positionTracking,\n ensureOptimizations: config.ensureOptimizations,\n safeMode: config.safeMode,\n tracer: this.TRACE_INIT,\n });\n });\n\n this.patternIdxToConfig[currModName] =\n currAnalyzeResult.patternIdxToConfig;\n\n this.charCodeToPatternIdxToConfig[currModName] =\n currAnalyzeResult.charCodeToPatternIdxToConfig;\n\n this.emptyGroups = assign(\n {},\n this.emptyGroups,\n currAnalyzeResult.emptyGroups,\n ) as any;\n\n this.hasCustom = currAnalyzeResult.hasCustom || this.hasCustom;\n\n this.canModeBeOptimized[currModName] =\n currAnalyzeResult.canBeOptimized;\n }\n });\n },\n );\n\n this.defaultMode = actualDefinition.defaultMode;\n\n if (\n !isEmpty(this.lexerDefinitionErrors) &&\n !this.config.deferDefinitionErrorsHandling\n ) {\n const allErrMessages = map(this.lexerDefinitionErrors, (error) => {\n return error.message;\n });\n const allErrMessagesString = allErrMessages.join(\n \"-----------------------\\n\",\n );\n throw new Error(\n \"Errors detected in definition of Lexer:\\n\" + allErrMessagesString,\n );\n }\n\n // Only print warning if there are no errors, This will avoid pl\n forEach(this.lexerDefinitionWarning, (warningDescriptor) => {\n PRINT_WARNING(warningDescriptor.message);\n });\n\n this.TRACE_INIT(\"Choosing sub-methods implementations\", () => {\n // Choose the relevant internal implementations for this specific parser.\n // These implementations should be in-lined by the JavaScript engine\n // to provide optimal performance in each scenario.\n if (SUPPORT_STICKY) {\n this.chopInput = identity;\n this.match = this.matchWithTest;\n } else {\n this.updateLastIndex = noop;\n this.match = this.matchWithExec;\n }\n\n if (hasOnlySingleMode) {\n this.handleModes = noop;\n }\n\n if (this.trackStartLines === false) {\n this.computeNewColumn = identity;\n }\n\n if (this.trackEndLines === false) {\n this.updateTokenEndLineColumnLocation = noop;\n }\n\n if (/full/i.test(this.config.positionTracking)) {\n this.createTokenInstance = this.createFullToken;\n } else if (/onlyStart/i.test(this.config.positionTracking)) {\n this.createTokenInstance = this.createStartOnlyToken;\n } else if (/onlyOffset/i.test(this.config.positionTracking)) {\n this.createTokenInstance = this.createOffsetOnlyToken;\n } else {\n throw Error(\n `Invalid config option: \"${this.config.positionTracking}\"`,\n );\n }\n\n if (this.hasCustom) {\n this.addToken = this.addTokenUsingPush;\n this.handlePayload = this.handlePayloadWithCustom;\n } else {\n this.addToken = this.addTokenUsingMemberAccess;\n this.handlePayload = this.handlePayloadNoCustom;\n }\n });\n\n this.TRACE_INIT(\"Failed Optimization Warnings\", () => {\n const unOptimizedModes = reduce(\n this.canModeBeOptimized,\n (cannotBeOptimized, canBeOptimized, modeName) => {\n if (canBeOptimized === false) {\n cannotBeOptimized.push(modeName);\n }\n return cannotBeOptimized;\n },\n [] as string[],\n );\n\n if (config.ensureOptimizations && !isEmpty(unOptimizedModes)) {\n throw Error(\n `Lexer Modes: < ${unOptimizedModes.join(\n \", \",\n )} > cannot be optimized.\\n` +\n '\\t Disable the \"ensureOptimizations\" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.\\n' +\n \"\\t Or inspect the console log for details on how to resolve these issues.\",\n );\n }\n });\n\n this.TRACE_INIT(\"clearRegExpParserCache\", () => {\n clearRegExpParserCache();\n });\n\n this.TRACE_INIT(\"toFastProperties\", () => {\n toFastProperties(this);\n });\n });\n }\n\n public tokenize(\n text: string,\n initialMode: string = this.defaultMode,\n ): ILexingResult {\n if (!isEmpty(this.lexerDefinitionErrors)) {\n const allErrMessages = map(this.lexerDefinitionErrors, (error) => {\n return error.message;\n });\n const allErrMessagesString = allErrMessages.join(\n \"-----------------------\\n\",\n );\n throw new Error(\n \"Unable to Tokenize because Errors detected in definition of Lexer:\\n\" +\n allErrMessagesString,\n );\n }\n\n return this.tokenizeInternal(text, initialMode);\n }\n\n // There is quite a bit of duplication between this and \"tokenizeInternalLazy\"\n // This is intentional due to performance considerations.\n // this method also used quite a bit of `!` none null assertions because it is too optimized\n // for `tsc` to always understand it is \"safe\"\n private tokenizeInternal(text: string, initialMode: string): ILexingResult {\n let i,\n j,\n k,\n matchAltImage,\n longerAlt,\n matchedImage: string | null,\n payload,\n altPayload,\n imageLength,\n group,\n tokType,\n newToken: IToken,\n errLength,\n droppedChar,\n msg,\n match;\n const orgText = text;\n const orgLength = orgText.length;\n let offset = 0;\n let matchedTokensIndex = 0;\n // initializing the tokensArray to the \"guessed\" size.\n // guessing too little will still reduce the number of array re-sizes on pushes.\n // guessing too large (Tested by guessing x4 too large) may cost a bit more of memory\n // but would still have a faster runtime by avoiding (All but one) array resizing.\n const guessedNumberOfTokens = this.hasCustom\n ? 0 // will break custom token pattern APIs the matchedTokens array will contain undefined elements.\n : Math.floor(text.length / 10);\n const matchedTokens = new Array(guessedNumberOfTokens);\n const errors: ILexingError[] = [];\n let line = this.trackStartLines ? 1 : undefined;\n let column = this.trackStartLines ? 1 : undefined;\n const groups: any = cloneEmptyGroups(this.emptyGroups);\n const trackLines = this.trackStartLines;\n const lineTerminatorPattern = this.config.lineTerminatorsPattern;\n\n let currModePatternsLength = 0;\n let patternIdxToConfig: IPatternConfig[] = [];\n let currCharCodeToPatternIdxToConfig: {\n [charCode: number]: IPatternConfig[];\n } = [];\n\n const modeStack: string[] = [];\n\n const emptyArray: IPatternConfig[] = [];\n Object.freeze(emptyArray);\n let getPossiblePatterns!: (charCode: number) => IPatternConfig[];\n\n function getPossiblePatternsSlow() {\n return patternIdxToConfig;\n }\n\n function getPossiblePatternsOptimized(charCode: number): IPatternConfig[] {\n const optimizedCharIdx = charCodeToOptimizedIndex(charCode);\n const possiblePatterns =\n currCharCodeToPatternIdxToConfig[optimizedCharIdx];\n if (possiblePatterns === undefined) {\n return emptyArray;\n } else {\n return possiblePatterns;\n }\n }\n\n const pop_mode = (popToken: IToken) => {\n // TODO: perhaps avoid this error in the edge case there is no more input?\n if (\n modeStack.length === 1 &&\n // if we have both a POP_MODE and a PUSH_MODE this is in-fact a \"transition\"\n // So no error should occur.\n popToken.tokenType.PUSH_MODE === undefined\n ) {\n // if we try to pop the last mode there lexer will no longer have ANY mode.\n // thus the pop is ignored, an error will be created and the lexer will continue parsing in the previous mode.\n const msg =\n this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(\n popToken,\n );\n\n errors.push({\n offset: popToken.startOffset,\n line: popToken.startLine,\n column: popToken.startColumn,\n length: popToken.image.length,\n message: msg,\n });\n } else {\n modeStack.pop();\n const newMode = last(modeStack)!;\n patternIdxToConfig = this.patternIdxToConfig[newMode];\n currCharCodeToPatternIdxToConfig =\n this.charCodeToPatternIdxToConfig[newMode];\n currModePatternsLength = patternIdxToConfig.length;\n const modeCanBeOptimized =\n this.canModeBeOptimized[newMode] && this.config.safeMode === false;\n\n if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {\n getPossiblePatterns = getPossiblePatternsOptimized;\n } else {\n getPossiblePatterns = getPossiblePatternsSlow;\n }\n }\n };\n\n function push_mode(this: Lexer, newMode: string) {\n modeStack.push(newMode);\n currCharCodeToPatternIdxToConfig =\n this.charCodeToPatternIdxToConfig[newMode];\n\n patternIdxToConfig = this.patternIdxToConfig[newMode];\n currModePatternsLength = patternIdxToConfig.length;\n\n currModePatternsLength = patternIdxToConfig.length;\n const modeCanBeOptimized =\n this.canModeBeOptimized[newMode] && this.config.safeMode === false;\n\n if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {\n getPossiblePatterns = getPossiblePatternsOptimized;\n } else {\n getPossiblePatterns = getPossiblePatternsSlow;\n }\n }\n\n // this pattern seems to avoid a V8 de-optimization, although that de-optimization does not\n // seem to matter performance wise.\n push_mode.call(this, initialMode);\n\n let currConfig!: IPatternConfig;\n\n const recoveryEnabled = this.config.recoveryEnabled;\n\n while (offset < orgLength) {\n matchedImage = null;\n\n const nextCharCode = orgText.charCodeAt(offset);\n const chosenPatternIdxToConfig = getPossiblePatterns(nextCharCode);\n const chosenPatternsLength = chosenPatternIdxToConfig.length;\n\n for (i = 0; i < chosenPatternsLength; i++) {\n currConfig = chosenPatternIdxToConfig[i];\n const currPattern = currConfig.pattern;\n payload = null;\n\n // manually in-lined because > 600 chars won't be in-lined in V8\n const singleCharCode = currConfig.short;\n if (singleCharCode !== false) {\n if (nextCharCode === singleCharCode) {\n // single character string\n matchedImage = currPattern as string;\n }\n } else if (currConfig.isCustom === true) {\n match = (currPattern as IRegExpExec).exec(\n orgText,\n offset,\n matchedTokens,\n groups,\n );\n if (match !== null) {\n matchedImage = match[0];\n if ((match as CustomPatternMatcherReturn).payload !== undefined) {\n payload = (match as CustomPatternMatcherReturn).payload;\n }\n } else {\n matchedImage = null;\n }\n } else {\n this.updateLastIndex(currPattern as RegExp, offset);\n matchedImage = this.match(currPattern as RegExp, text, offset);\n }\n\n if (matchedImage !== null) {\n // even though this pattern matched we must try a another longer alternative.\n // this can be used to prioritize keywords over identifiers\n longerAlt = currConfig.longerAlt;\n if (longerAlt !== undefined) {\n // TODO: micro optimize, avoid extra prop access\n // by saving/linking longerAlt on the original config?\n const longerAltLength = longerAlt.length;\n for (k = 0; k < longerAltLength; k++) {\n const longerAltConfig = patternIdxToConfig[longerAlt[k]];\n const longerAltPattern = longerAltConfig.pattern;\n altPayload = null;\n\n // single Char can never be a longer alt so no need to test it.\n // manually in-lined because > 600 chars won't be in-lined in V8\n if (longerAltConfig.isCustom === true) {\n match = (longerAltPattern as IRegExpExec).exec(\n orgText,\n offset,\n matchedTokens,\n groups,\n );\n if (match !== null) {\n matchAltImage = match[0];\n if (\n (match as CustomPatternMatcherReturn).payload !== undefined\n ) {\n altPayload = (match as CustomPatternMatcherReturn).payload;\n }\n } else {\n matchAltImage = null;\n }\n } else {\n this.updateLastIndex(longerAltPattern as RegExp, offset);\n matchAltImage = this.match(\n longerAltPattern as RegExp,\n text,\n offset,\n );\n }\n\n if (matchAltImage && matchAltImage.length > matchedImage.length) {\n matchedImage = matchAltImage;\n payload = altPayload;\n currConfig = longerAltConfig;\n // Exit the loop early after matching one of the longer alternatives\n // The first matched alternative takes precedence\n break;\n }\n }\n }\n break;\n }\n }\n\n // successful match\n if (matchedImage !== null) {\n imageLength = matchedImage.length;\n group = currConfig.group;\n if (group !== undefined) {\n tokType = currConfig.tokenTypeIdx;\n // TODO: \"offset + imageLength\" and the new column may be computed twice in case of \"full\" location information inside\n // createFullToken method\n newToken = this.createTokenInstance(\n matchedImage,\n offset,\n tokType,\n currConfig.tokenType,\n line,\n column,\n imageLength,\n );\n\n this.handlePayload(newToken, payload);\n\n // TODO: optimize NOOP in case there are no special groups?\n if (group === false) {\n matchedTokensIndex = this.addToken(\n matchedTokens,\n matchedTokensIndex,\n newToken,\n );\n } else {\n groups[group].push(newToken);\n }\n }\n text = this.chopInput(text, imageLength);\n offset = offset + imageLength;\n\n // TODO: with newlines the column may be assigned twice\n column = this.computeNewColumn(column!, imageLength);\n\n if (trackLines === true && currConfig.canLineTerminator === true) {\n let numOfLTsInMatch = 0;\n let foundTerminator;\n let lastLTEndOffset: number;\n lineTerminatorPattern.lastIndex = 0;\n do {\n foundTerminator = lineTerminatorPattern.test(matchedImage);\n if (foundTerminator === true) {\n lastLTEndOffset = lineTerminatorPattern.lastIndex - 1;\n numOfLTsInMatch++;\n }\n } while (foundTerminator === true);\n\n if (numOfLTsInMatch !== 0) {\n line = line! + numOfLTsInMatch;\n column = imageLength - lastLTEndOffset!;\n this.updateTokenEndLineColumnLocation(\n newToken!,\n group!,\n lastLTEndOffset!,\n numOfLTsInMatch,\n line,\n column,\n imageLength,\n );\n }\n }\n // will be NOOP if no modes present\n this.handleModes(currConfig, pop_mode, push_mode, newToken!);\n } else {\n // error recovery, drop characters until we identify a valid token's start point\n const errorStartOffset = offset;\n const errorLine = line;\n const errorColumn = column;\n let foundResyncPoint = recoveryEnabled === false;\n\n while (foundResyncPoint === false && offset < orgLength) {\n // Identity Func (when sticky flag is enabled)\n text = this.chopInput(text, 1);\n offset++;\n for (j = 0; j < currModePatternsLength; j++) {\n const currConfig = patternIdxToConfig[j];\n const currPattern = currConfig.pattern;\n\n // manually in-lined because > 600 chars won't be in-lined in V8\n const singleCharCode = currConfig.short;\n if (singleCharCode !== false) {\n if (orgText.charCodeAt(offset) === singleCharCode) {\n // single character string\n foundResyncPoint = true;\n }\n } else if (currConfig.isCustom === true) {\n foundResyncPoint =\n (currPattern as IRegExpExec).exec(\n orgText,\n offset,\n matchedTokens,\n groups,\n ) !== null;\n } else {\n this.updateLastIndex(currPattern as RegExp, offset);\n foundResyncPoint = (currPattern as RegExp).exec(text) !== null;\n }\n\n if (foundResyncPoint === true) {\n break;\n }\n }\n }\n\n errLength = offset - errorStartOffset;\n column = this.computeNewColumn(column!, errLength);\n // at this point we either re-synced or reached the end of the input text\n msg = this.config.errorMessageProvider.buildUnexpectedCharactersMessage(\n orgText,\n errorStartOffset,\n errLength,\n errorLine,\n errorColumn,\n );\n errors.push({\n offset: errorStartOffset,\n line: errorLine,\n column: errorColumn,\n length: errLength,\n message: msg,\n });\n\n if (recoveryEnabled === false) {\n break;\n }\n }\n }\n\n // if we do have custom patterns which push directly into the\n // TODO: custom tokens should not push directly??\n if (!this.hasCustom) {\n // if we guessed a too large size for the tokens array this will shrink it to the right size.\n matchedTokens.length = matchedTokensIndex;\n }\n\n return {\n tokens: matchedTokens,\n groups: groups,\n errors: errors,\n };\n }\n\n private handleModes(\n config: IPatternConfig,\n pop_mode: (tok: IToken) => void,\n push_mode: (this: Lexer, pushMode: string) => void,\n newToken: IToken,\n ) {\n if (config.pop === true) {\n // need to save the PUSH_MODE property as if the mode is popped\n // patternIdxToPopMode is updated to reflect the new mode after popping the stack\n const pushMode = config.push;\n pop_mode(newToken);\n if (pushMode !== undefined) {\n push_mode.call(this, pushMode);\n }\n } else if (config.push !== undefined) {\n push_mode.call(this, config.push);\n }\n }\n\n private chopInput(text: string, length: number): string {\n return text.substring(length);\n }\n\n private updateLastIndex(regExp: RegExp, newLastIndex: number): void {\n regExp.lastIndex = newLastIndex;\n }\n\n // TODO: decrease this under 600 characters? inspect stripping comments option in TSC compiler\n private updateTokenEndLineColumnLocation(\n newToken: IToken,\n group: string | false,\n lastLTIdx: number,\n numOfLTsInMatch: number,\n line: number,\n column: number,\n imageLength: number,\n ): void {\n let lastCharIsLT, fixForEndingInLT;\n if (group !== undefined) {\n // a none skipped multi line Token, need to update endLine/endColumn\n lastCharIsLT = lastLTIdx === imageLength - 1;\n fixForEndingInLT = lastCharIsLT ? -1 : 0;\n if (!(numOfLTsInMatch === 1 && lastCharIsLT === true)) {\n // if a token ends in a LT that last LT only affects the line numbering of following Tokens\n newToken.endLine = line + fixForEndingInLT;\n // the last LT in a token does not affect the endColumn either as the [columnStart ... columnEnd)\n // inclusive to exclusive range.\n newToken.endColumn = column - 1 + -fixForEndingInLT;\n }\n // else single LT in the last character of a token, no need to modify the endLine/EndColumn\n }\n }\n\n private computeNewColumn(oldColumn: number, imageLength: number) {\n return oldColumn + imageLength;\n }\n\n // Place holder, will be replaced by the correct variant according to the locationTracking option at runtime.\n /* istanbul ignore next - place holder */\n private createTokenInstance!: (...args: any[]) => IToken;\n\n private createOffsetOnlyToken(\n image: string,\n startOffset: number,\n tokenTypeIdx: number,\n tokenType: TokenType,\n ) {\n return {\n image,\n startOffset,\n tokenTypeIdx,\n tokenType,\n };\n }\n\n private createStartOnlyToken(\n image: string,\n startOffset: number,\n tokenTypeIdx: number,\n tokenType: TokenType,\n startLine: number,\n startColumn: number,\n ) {\n return {\n image,\n startOffset,\n startLine,\n startColumn,\n tokenTypeIdx,\n tokenType,\n };\n }\n\n private createFullToken(\n image: string,\n startOffset: number,\n tokenTypeIdx: number,\n tokenType: TokenType,\n startLine: number,\n startColumn: number,\n imageLength: number,\n ): IToken {\n return {\n image,\n startOffset,\n endOffset: startOffset + imageLength - 1,\n startLine,\n endLine: startLine,\n startColumn,\n endColumn: startColumn + imageLength - 1,\n tokenTypeIdx,\n tokenType,\n };\n }\n\n // Place holder, will be replaced by the correct variant according to the locationTracking option at runtime.\n /* istanbul ignore next - place holder */\n private addToken!: (\n tokenVector: IToken[],\n index: number,\n tokenToAdd: IToken,\n ) => number;\n\n private addTokenUsingPush(\n tokenVector: IToken[],\n index: number,\n tokenToAdd: IToken,\n ): number {\n tokenVector.push(tokenToAdd);\n return index;\n }\n\n private addTokenUsingMemberAccess(\n tokenVector: IToken[],\n index: number,\n tokenToAdd: IToken,\n ): number {\n tokenVector[index] = tokenToAdd;\n index++;\n return index;\n }\n\n // Place holder, will be replaced by the correct variant according to the hasCustom flag option at runtime.\n private handlePayload: (token: IToken, payload: any) => void;\n\n private handlePayloadNoCustom(token: IToken, payload: any): void {}\n\n private handlePayloadWithCustom(token: IToken, payload: any): void {\n if (payload !== null) {\n token.payload = payload;\n }\n }\n\n // place holder to be replaced with chosen alternative at runtime\n private match!: (\n pattern: RegExp,\n text: string,\n offset: number,\n ) => string | null;\n\n private matchWithTest(\n pattern: RegExp,\n text: string,\n offset: number,\n ): string | null {\n const found = pattern.test(text);\n if (found === true) {\n return text.substring(offset, pattern.lastIndex);\n }\n return null;\n }\n\n private matchWithExec(pattern: RegExp, text: string): string | null {\n const regExpArray = pattern.exec(text);\n return regExpArray !== null ? regExpArray[0] : null;\n }\n\n // Duplicated from the parser's perf trace trait to allow future extraction\n // of the lexer to a separate package.\n TRACE_INIT = (phaseDesc: string, phaseImpl: () => T): T => {\n // No need to optimize this using NOOP pattern because\n // It is not called in a hot spot...\n if (this.traceInitPerf === true) {\n this.traceInitIndent++;\n const indent = new Array(this.traceInitIndent + 1).join(\"\\t\");\n if (this.traceInitIndent < this.traceInitMaxIdent) {\n console.log(`${indent}--> <${phaseDesc}>`);\n }\n const { time, value } = timer(phaseImpl);\n /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */\n const traceMethod = time > 10 ? console.warn : console.log;\n if (this.traceInitIndent < this.traceInitMaxIdent) {\n traceMethod(`${indent}<-- <${phaseDesc}> time: ${time}ms`);\n }\n this.traceInitIndent--;\n return value;\n } else {\n return phaseImpl();\n }\n };\n}\n", "import { has, isString, isUndefined } from \"lodash-es\";\nimport { Lexer } from \"./lexer_public.js\";\nimport { augmentTokenTypes, tokenStructuredMatcher } from \"./tokens.js\";\nimport { IToken, ITokenConfig, TokenType } from \"@chevrotain/types\";\n\nexport function tokenLabel(tokType: TokenType): string {\n if (hasTokenLabel(tokType)) {\n return tokType.LABEL;\n } else {\n return tokType.name;\n }\n}\n\nexport function tokenName(tokType: TokenType): string {\n return tokType.name;\n}\n\nexport function hasTokenLabel(\n obj: TokenType,\n): obj is TokenType & Pick, \"LABEL\"> {\n return isString(obj.LABEL) && obj.LABEL !== \"\";\n}\n\nconst PARENT = \"parent\";\nconst CATEGORIES = \"categories\";\nconst LABEL = \"label\";\nconst GROUP = \"group\";\nconst PUSH_MODE = \"push_mode\";\nconst POP_MODE = \"pop_mode\";\nconst LONGER_ALT = \"longer_alt\";\nconst LINE_BREAKS = \"line_breaks\";\nconst START_CHARS_HINT = \"start_chars_hint\";\n\nexport function createToken(config: ITokenConfig): TokenType {\n return createTokenInternal(config);\n}\n\nfunction createTokenInternal(config: ITokenConfig): TokenType {\n const pattern = config.pattern;\n\n const tokenType: TokenType = {};\n tokenType.name = config.name;\n\n if (!isUndefined(pattern)) {\n tokenType.PATTERN = pattern;\n }\n\n if (has(config, PARENT)) {\n throw (\n \"The parent property is no longer supported.\\n\" +\n \"See: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.\"\n );\n }\n\n if (has(config, CATEGORIES)) {\n // casting to ANY as this will be fixed inside `augmentTokenTypes``\n tokenType.CATEGORIES = config[CATEGORIES];\n }\n\n augmentTokenTypes([tokenType]);\n\n if (has(config, LABEL)) {\n tokenType.LABEL = config[LABEL];\n }\n\n if (has(config, GROUP)) {\n tokenType.GROUP = config[GROUP];\n }\n\n if (has(config, POP_MODE)) {\n tokenType.POP_MODE = config[POP_MODE];\n }\n\n if (has(config, PUSH_MODE)) {\n tokenType.PUSH_MODE = config[PUSH_MODE];\n }\n\n if (has(config, LONGER_ALT)) {\n tokenType.LONGER_ALT = config[LONGER_ALT];\n }\n\n if (has(config, LINE_BREAKS)) {\n tokenType.LINE_BREAKS = config[LINE_BREAKS];\n }\n\n if (has(config, START_CHARS_HINT)) {\n tokenType.START_CHARS_HINT = config[START_CHARS_HINT];\n }\n\n return tokenType;\n}\n\nexport const EOF = createToken({ name: \"EOF\", pattern: Lexer.NA });\naugmentTokenTypes([EOF]);\n\nexport function createTokenInstance(\n tokType: TokenType,\n image: string,\n startOffset: number,\n endOffset: number,\n startLine: number,\n endLine: number,\n startColumn: number,\n endColumn: number,\n): IToken {\n return {\n image,\n startOffset,\n endOffset,\n startLine,\n endLine,\n startColumn,\n endColumn,\n tokenTypeIdx: (tokType).tokenTypeIdx,\n tokenType: tokType,\n };\n}\n\nexport function tokenMatcher(token: IToken, tokType: TokenType): boolean {\n return tokenStructuredMatcher(token, tokType);\n}\n", "import { hasTokenLabel, tokenLabel } from \"../scan/tokens_public.js\";\nimport { first, map, reduce } from \"lodash-es\";\nimport {\n Alternation,\n getProductionDslName,\n NonTerminal,\n Rule,\n Terminal,\n} from \"@chevrotain/gast\";\nimport {\n IParserErrorMessageProvider,\n IProductionWithOccurrence,\n TokenType,\n} from \"@chevrotain/types\";\nimport {\n IGrammarResolverErrorMessageProvider,\n IGrammarValidatorErrorMessageProvider,\n} from \"./grammar/types.js\";\n\nexport const defaultParserErrorProvider: IParserErrorMessageProvider = {\n buildMismatchTokenMessage({ expected, actual, previous, ruleName }): string {\n const hasLabel = hasTokenLabel(expected);\n const expectedMsg = hasLabel\n ? `--> ${tokenLabel(expected)} <--`\n : `token of type --> ${expected.name} <--`;\n\n const msg = `Expecting ${expectedMsg} but found --> '${actual.image}' <--`;\n\n return msg;\n },\n\n buildNotAllInputParsedMessage({ firstRedundant, ruleName }): string {\n return \"Redundant input, expecting EOF but found: \" + firstRedundant.image;\n },\n\n buildNoViableAltMessage({\n expectedPathsPerAlt,\n actual,\n previous,\n customUserDescription,\n ruleName,\n }): string {\n const errPrefix = \"Expecting: \";\n // TODO: issue: No Viable Alternative Error may have incomplete details. #502\n const actualText = first(actual)!.image;\n const errSuffix = \"\\nbut found: '\" + actualText + \"'\";\n\n if (customUserDescription) {\n return errPrefix + customUserDescription + errSuffix;\n } else {\n const allLookAheadPaths = reduce(\n expectedPathsPerAlt,\n (result, currAltPaths) => result.concat(currAltPaths),\n [] as TokenType[][],\n );\n const nextValidTokenSequences = map(\n allLookAheadPaths,\n (currPath) =>\n `[${map(currPath, (currTokenType) => tokenLabel(currTokenType)).join(\n \", \",\n )}]`,\n );\n const nextValidSequenceItems = map(\n nextValidTokenSequences,\n (itemMsg, idx) => ` ${idx + 1}. ${itemMsg}`,\n );\n const calculatedDescription = `one of these possible Token sequences:\\n${nextValidSequenceItems.join(\n \"\\n\",\n )}`;\n\n return errPrefix + calculatedDescription + errSuffix;\n }\n },\n\n buildEarlyExitMessage({\n expectedIterationPaths,\n actual,\n customUserDescription,\n ruleName,\n }): string {\n const errPrefix = \"Expecting: \";\n // TODO: issue: No Viable Alternative Error may have incomplete details. #502\n const actualText = first(actual)!.image;\n const errSuffix = \"\\nbut found: '\" + actualText + \"'\";\n\n if (customUserDescription) {\n return errPrefix + customUserDescription + errSuffix;\n } else {\n const nextValidTokenSequences = map(\n expectedIterationPaths,\n (currPath) =>\n `[${map(currPath, (currTokenType) => tokenLabel(currTokenType)).join(\n \",\",\n )}]`,\n );\n const calculatedDescription =\n `expecting at least one iteration which starts with one of these possible Token sequences::\\n ` +\n `<${nextValidTokenSequences.join(\" ,\")}>`;\n\n return errPrefix + calculatedDescription + errSuffix;\n }\n },\n};\n\nObject.freeze(defaultParserErrorProvider);\n\nexport const defaultGrammarResolverErrorProvider: IGrammarResolverErrorMessageProvider =\n {\n buildRuleNotFoundError(\n topLevelRule: Rule,\n undefinedRule: NonTerminal,\n ): string {\n const msg =\n \"Invalid grammar, reference to a rule which is not defined: ->\" +\n undefinedRule.nonTerminalName +\n \"<-\\n\" +\n \"inside top level rule: ->\" +\n topLevelRule.name +\n \"<-\";\n return msg;\n },\n };\n\nexport const defaultGrammarValidatorErrorProvider: IGrammarValidatorErrorMessageProvider =\n {\n buildDuplicateFoundError(\n topLevelRule: Rule,\n duplicateProds: IProductionWithOccurrence[],\n ): string {\n function getExtraProductionArgument(\n prod: IProductionWithOccurrence,\n ): string {\n if (prod instanceof Terminal) {\n return prod.terminalType.name;\n } else if (prod instanceof NonTerminal) {\n return prod.nonTerminalName;\n } else {\n return \"\";\n }\n }\n\n const topLevelName = topLevelRule.name;\n const duplicateProd = first(duplicateProds)!;\n const index = duplicateProd.idx;\n const dslName = getProductionDslName(duplicateProd);\n const extraArgument = getExtraProductionArgument(duplicateProd);\n\n const hasExplicitIndex = index > 0;\n let msg = `->${dslName}${hasExplicitIndex ? index : \"\"}<- ${\n extraArgument ? `with argument: ->${extraArgument}<-` : \"\"\n }\n appears more than once (${\n duplicateProds.length\n } times) in the top level rule: ->${topLevelName}<-. \n For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES \n `;\n\n // white space trimming time! better to trim afterwards as it allows to use WELL formatted multi line template strings...\n msg = msg.replace(/[ \\t]+/g, \" \");\n msg = msg.replace(/\\s\\s+/g, \"\\n\");\n\n return msg;\n },\n\n buildNamespaceConflictError(rule: Rule): string {\n const errMsg =\n `Namespace conflict found in grammar.\\n` +\n `The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${rule.name}>.\\n` +\n `To resolve this make sure each Terminal and Non-Terminal names are unique\\n` +\n `This is easy to accomplish by using the convention that Terminal names start with an uppercase letter\\n` +\n `and Non-Terminal names start with a lower case letter.`;\n\n return errMsg;\n },\n\n buildAlternationPrefixAmbiguityError(options: {\n topLevelRule: Rule;\n prefixPath: TokenType[];\n ambiguityIndices: number[];\n alternation: Alternation;\n }): string {\n const pathMsg = map(options.prefixPath, (currTok) =>\n tokenLabel(currTok),\n ).join(\", \");\n const occurrence =\n options.alternation.idx === 0 ? \"\" : options.alternation.idx;\n const errMsg =\n `Ambiguous alternatives: <${options.ambiguityIndices.join(\n \" ,\",\n )}> due to common lookahead prefix\\n` +\n `in inside <${options.topLevelRule.name}> Rule,\\n` +\n `<${pathMsg}> may appears as a prefix path in all these alternatives.\\n` +\n `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX\\n` +\n `For Further details.`;\n\n return errMsg;\n },\n\n buildAlternationAmbiguityError(options: {\n topLevelRule: Rule;\n prefixPath: TokenType[];\n ambiguityIndices: number[];\n alternation: Alternation;\n }): string {\n const pathMsg = map(options.prefixPath, (currtok) =>\n tokenLabel(currtok),\n ).join(\", \");\n const occurrence =\n options.alternation.idx === 0 ? \"\" : options.alternation.idx;\n let currMessage =\n `Ambiguous Alternatives Detected: <${options.ambiguityIndices.join(\n \" ,\",\n )}> in ` +\n ` inside <${options.topLevelRule.name}> Rule,\\n` +\n `<${pathMsg}> may appears as a prefix path in all these alternatives.\\n`;\n\n currMessage =\n currMessage +\n `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES\\n` +\n `For Further details.`;\n return currMessage;\n },\n\n buildEmptyRepetitionError(options: {\n topLevelRule: Rule;\n repetition: IProductionWithOccurrence;\n }): string {\n let dslName = getProductionDslName(options.repetition);\n if (options.repetition.idx !== 0) {\n dslName += options.repetition.idx;\n }\n\n const errMsg =\n `The repetition <${dslName}> within Rule <${options.topLevelRule.name}> can never consume any tokens.\\n` +\n `This could lead to an infinite loop.`;\n\n return errMsg;\n },\n\n // TODO: remove - `errors_public` from nyc.config.js exclude\n // once this method is fully removed from this file\n buildTokenNameError(options: {\n tokenType: TokenType;\n expectedPattern: RegExp;\n }): string {\n /* istanbul ignore next */\n return \"deprecated\";\n },\n\n buildEmptyAlternationError(options: {\n topLevelRule: Rule;\n alternation: Alternation;\n emptyChoiceIdx: number;\n }): string {\n const errMsg =\n `Ambiguous empty alternative: <${options.emptyChoiceIdx + 1}>` +\n ` in inside <${options.topLevelRule.name}> Rule.\\n` +\n `Only the last alternative may be an empty alternative.`;\n\n return errMsg;\n },\n\n buildTooManyAlternativesError(options: {\n topLevelRule: Rule;\n alternation: Alternation;\n }): string {\n const errMsg =\n `An Alternation cannot have more than 256 alternatives:\\n` +\n ` inside <${\n options.topLevelRule.name\n }> Rule.\\n has ${\n options.alternation.definition.length + 1\n } alternatives.`;\n\n return errMsg;\n },\n\n buildLeftRecursionError(options: {\n topLevelRule: Rule;\n leftRecursionPath: Rule[];\n }): string {\n const ruleName = options.topLevelRule.name;\n const pathNames = map(\n options.leftRecursionPath,\n (currRule) => currRule.name,\n );\n const leftRecursivePath = `${ruleName} --> ${pathNames\n .concat([ruleName])\n .join(\" --> \")}`;\n const errMsg =\n `Left Recursion found in grammar.\\n` +\n `rule: <${ruleName}> can be invoked from itself (directly or indirectly)\\n` +\n `without consuming any Tokens. The grammar path that causes this is: \\n ${leftRecursivePath}\\n` +\n ` To fix this refactor your grammar to remove the left recursion.\\n` +\n `see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`;\n\n return errMsg;\n },\n\n // TODO: remove - `errors_public` from nyc.config.js exclude\n // once this method is fully removed from this file\n buildInvalidRuleNameError(options: {\n topLevelRule: Rule;\n expectedPattern: RegExp;\n }): string {\n /* istanbul ignore next */\n return \"deprecated\";\n },\n\n buildDuplicateRuleNameError(options: {\n topLevelRule: Rule | string;\n grammarName: string;\n }): string {\n let ruleName;\n if (options.topLevelRule instanceof Rule) {\n ruleName = options.topLevelRule.name;\n } else {\n ruleName = options.topLevelRule;\n }\n\n const errMsg = `Duplicate definition, rule: ->${ruleName}<- is already defined in the grammar: ->${options.grammarName}<-`;\n\n return errMsg;\n },\n };\n", "import {\n IParserUnresolvedRefDefinitionError,\n ParserDefinitionErrorType,\n} from \"../parser/parser.js\";\nimport { forEach, values } from \"lodash-es\";\nimport { GAstVisitor, NonTerminal, Rule } from \"@chevrotain/gast\";\nimport {\n IGrammarResolverErrorMessageProvider,\n IParserDefinitionError,\n} from \"./types.js\";\n\nexport function resolveGrammar(\n topLevels: Record,\n errMsgProvider: IGrammarResolverErrorMessageProvider,\n): IParserDefinitionError[] {\n const refResolver = new GastRefResolverVisitor(topLevels, errMsgProvider);\n refResolver.resolveRefs();\n return refResolver.errors;\n}\n\nexport class GastRefResolverVisitor extends GAstVisitor {\n public errors: IParserUnresolvedRefDefinitionError[] = [];\n private currTopLevel: Rule;\n\n constructor(\n private nameToTopRule: Record,\n private errMsgProvider: IGrammarResolverErrorMessageProvider,\n ) {\n super();\n }\n\n public resolveRefs(): void {\n forEach(values(this.nameToTopRule), (prod) => {\n this.currTopLevel = prod;\n prod.accept(this);\n });\n }\n\n public visitNonTerminal(node: NonTerminal): void {\n const ref = this.nameToTopRule[node.nonTerminalName];\n\n if (!ref) {\n const msg = this.errMsgProvider.buildRuleNotFoundError(\n this.currTopLevel,\n node,\n );\n this.errors.push({\n message: msg,\n type: ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,\n ruleName: this.currTopLevel.name,\n unresolvedRefName: node.nonTerminalName,\n });\n } else {\n node.referencedRule = ref;\n }\n }\n}\n", "import {\n clone,\n drop,\n dropRight,\n first as _first,\n forEach,\n isEmpty,\n last,\n} from \"lodash-es\";\nimport { first } from \"./first.js\";\nimport { RestWalker } from \"./rest.js\";\nimport { TokenMatcher } from \"../parser/parser.js\";\nimport {\n Alternation,\n Alternative,\n NonTerminal,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n Rule,\n Terminal,\n} from \"@chevrotain/gast\";\nimport {\n IGrammarPath,\n IProduction,\n ISyntacticContentAssistPath,\n IToken,\n ITokenGrammarPath,\n TokenType,\n} from \"@chevrotain/types\";\n\nexport abstract class AbstractNextPossibleTokensWalker extends RestWalker {\n protected possibleTokTypes: TokenType[] = [];\n protected ruleStack: string[];\n protected occurrenceStack: number[];\n\n protected nextProductionName = \"\";\n protected nextProductionOccurrence = 0;\n protected found = false;\n protected isAtEndOfPath = false;\n\n constructor(\n protected topProd: Rule,\n protected path: IGrammarPath,\n ) {\n super();\n }\n\n startWalking(): TokenType[] {\n this.found = false;\n\n if (this.path.ruleStack[0] !== this.topProd.name) {\n throw Error(\"The path does not start with the walker's top Rule!\");\n }\n\n // immutable for the win\n this.ruleStack = clone(this.path.ruleStack).reverse(); // intelij bug requires assertion\n this.occurrenceStack = clone(this.path.occurrenceStack).reverse(); // intelij bug requires assertion\n\n // already verified that the first production is valid, we now seek the 2nd production\n this.ruleStack.pop();\n this.occurrenceStack.pop();\n\n this.updateExpectedNext();\n this.walk(this.topProd);\n\n return this.possibleTokTypes;\n }\n\n walk(\n prod: { definition: IProduction[] },\n prevRest: IProduction[] = [],\n ): void {\n // stop scanning once we found the path\n if (!this.found) {\n super.walk(prod, prevRest);\n }\n }\n\n walkProdRef(\n refProd: NonTerminal,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // found the next production, need to keep walking in it\n if (\n refProd.referencedRule.name === this.nextProductionName &&\n refProd.idx === this.nextProductionOccurrence\n ) {\n const fullRest = currRest.concat(prevRest);\n this.updateExpectedNext();\n this.walk(refProd.referencedRule, fullRest);\n }\n }\n\n updateExpectedNext(): void {\n // need to consume the Terminal\n if (isEmpty(this.ruleStack)) {\n // must reset nextProductionXXX to avoid walking down another Top Level production while what we are\n // really seeking is the last Terminal...\n this.nextProductionName = \"\";\n this.nextProductionOccurrence = 0;\n this.isAtEndOfPath = true;\n } else {\n this.nextProductionName = this.ruleStack.pop()!;\n this.nextProductionOccurrence = this.occurrenceStack.pop()!;\n }\n }\n}\n\nexport class NextAfterTokenWalker extends AbstractNextPossibleTokensWalker {\n private nextTerminalName = \"\";\n private nextTerminalOccurrence = 0;\n\n constructor(\n topProd: Rule,\n protected path: ITokenGrammarPath,\n ) {\n super(topProd, path);\n this.nextTerminalName = this.path.lastTok.name;\n this.nextTerminalOccurrence = this.path.lastTokOccurrence;\n }\n\n walkTerminal(\n terminal: Terminal,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (\n this.isAtEndOfPath &&\n terminal.terminalType.name === this.nextTerminalName &&\n terminal.idx === this.nextTerminalOccurrence &&\n !this.found\n ) {\n const fullRest = currRest.concat(prevRest);\n const restProd = new Alternative({ definition: fullRest });\n this.possibleTokTypes = first(restProd);\n this.found = true;\n }\n }\n}\n\nexport type AlternativesFirstTokens = TokenType[][];\n\nexport interface IFirstAfterRepetition {\n token: TokenType | undefined;\n occurrence: number | undefined;\n isEndOfRule: boolean | undefined;\n}\n\n/**\n * This walker only \"walks\" a single \"TOP\" level in the Grammar Ast, this means\n * it never \"follows\" production refs\n */\nexport class AbstractNextTerminalAfterProductionWalker extends RestWalker {\n protected result: IFirstAfterRepetition = {\n token: undefined,\n occurrence: undefined,\n isEndOfRule: undefined,\n };\n\n constructor(\n protected topRule: Rule,\n protected occurrence: number,\n ) {\n super();\n }\n\n startWalking(): IFirstAfterRepetition {\n this.walk(this.topRule);\n return this.result;\n }\n}\n\nexport class NextTerminalAfterManyWalker extends AbstractNextTerminalAfterProductionWalker {\n walkMany(\n manyProd: Repetition,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (manyProd.idx === this.occurrence) {\n const firstAfterMany = _first(currRest.concat(prevRest));\n this.result.isEndOfRule = firstAfterMany === undefined;\n if (firstAfterMany instanceof Terminal) {\n this.result.token = firstAfterMany.terminalType;\n this.result.occurrence = firstAfterMany.idx;\n }\n } else {\n super.walkMany(manyProd, currRest, prevRest);\n }\n }\n}\n\nexport class NextTerminalAfterManySepWalker extends AbstractNextTerminalAfterProductionWalker {\n walkManySep(\n manySepProd: RepetitionWithSeparator,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (manySepProd.idx === this.occurrence) {\n const firstAfterManySep = _first(currRest.concat(prevRest));\n this.result.isEndOfRule = firstAfterManySep === undefined;\n if (firstAfterManySep instanceof Terminal) {\n this.result.token = firstAfterManySep.terminalType;\n this.result.occurrence = firstAfterManySep.idx;\n }\n } else {\n super.walkManySep(manySepProd, currRest, prevRest);\n }\n }\n}\n\nexport class NextTerminalAfterAtLeastOneWalker extends AbstractNextTerminalAfterProductionWalker {\n walkAtLeastOne(\n atLeastOneProd: RepetitionMandatory,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (atLeastOneProd.idx === this.occurrence) {\n const firstAfterAtLeastOne = _first(currRest.concat(prevRest));\n this.result.isEndOfRule = firstAfterAtLeastOne === undefined;\n if (firstAfterAtLeastOne instanceof Terminal) {\n this.result.token = firstAfterAtLeastOne.terminalType;\n this.result.occurrence = firstAfterAtLeastOne.idx;\n }\n } else {\n super.walkAtLeastOne(atLeastOneProd, currRest, prevRest);\n }\n }\n}\n\n// TODO: reduce code duplication in the AfterWalkers\nexport class NextTerminalAfterAtLeastOneSepWalker extends AbstractNextTerminalAfterProductionWalker {\n walkAtLeastOneSep(\n atleastOneSepProd: RepetitionMandatoryWithSeparator,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (atleastOneSepProd.idx === this.occurrence) {\n const firstAfterfirstAfterAtLeastOneSep = _first(\n currRest.concat(prevRest),\n );\n this.result.isEndOfRule = firstAfterfirstAfterAtLeastOneSep === undefined;\n if (firstAfterfirstAfterAtLeastOneSep instanceof Terminal) {\n this.result.token = firstAfterfirstAfterAtLeastOneSep.terminalType;\n this.result.occurrence = firstAfterfirstAfterAtLeastOneSep.idx;\n }\n } else {\n super.walkAtLeastOneSep(atleastOneSepProd, currRest, prevRest);\n }\n }\n}\n\nexport interface PartialPathAndSuffixes {\n partialPath: TokenType[];\n suffixDef: IProduction[];\n}\n\nexport function possiblePathsFrom(\n targetDef: IProduction[],\n maxLength: number,\n currPath: TokenType[] = [],\n): PartialPathAndSuffixes[] {\n // avoid side effects\n currPath = clone(currPath);\n let result: PartialPathAndSuffixes[] = [];\n let i = 0;\n\n // TODO: avoid inner funcs\n function remainingPathWith(nextDef: IProduction[]) {\n return nextDef.concat(drop(targetDef, i + 1));\n }\n\n // TODO: avoid inner funcs\n function getAlternativesForProd(definition: IProduction[]) {\n const alternatives = possiblePathsFrom(\n remainingPathWith(definition),\n maxLength,\n currPath,\n );\n return result.concat(alternatives);\n }\n\n /**\n * Mandatory productions will halt the loop as the paths computed from their recursive calls will already contain the\n * following (rest) of the targetDef.\n *\n * For optional productions (Option/Repetition/...) the loop will continue to represent the paths that do not include the\n * the optional production.\n */\n while (currPath.length < maxLength && i < targetDef.length) {\n const prod = targetDef[i];\n\n /* istanbul ignore else */\n if (prod instanceof Alternative) {\n return getAlternativesForProd(prod.definition);\n } else if (prod instanceof NonTerminal) {\n return getAlternativesForProd(prod.definition);\n } else if (prod instanceof Option) {\n result = getAlternativesForProd(prod.definition);\n } else if (prod instanceof RepetitionMandatory) {\n const newDef = prod.definition.concat([\n new Repetition({\n definition: prod.definition,\n }),\n ]);\n return getAlternativesForProd(newDef);\n } else if (prod instanceof RepetitionMandatoryWithSeparator) {\n const newDef = [\n new Alternative({ definition: prod.definition }),\n new Repetition({\n definition: [new Terminal({ terminalType: prod.separator })].concat(\n prod.definition,\n ),\n }),\n ];\n return getAlternativesForProd(newDef);\n } else if (prod instanceof RepetitionWithSeparator) {\n const newDef = prod.definition.concat([\n new Repetition({\n definition: [new Terminal({ terminalType: prod.separator })].concat(\n prod.definition,\n ),\n }),\n ]);\n result = getAlternativesForProd(newDef);\n } else if (prod instanceof Repetition) {\n const newDef = prod.definition.concat([\n new Repetition({\n definition: prod.definition,\n }),\n ]);\n result = getAlternativesForProd(newDef);\n } else if (prod instanceof Alternation) {\n forEach(prod.definition, (currAlt) => {\n // TODO: this is a limited check for empty alternatives\n // It would prevent a common case of infinite loops during parser initialization.\n // However **in-directly** empty alternatives may still cause issues.\n if (isEmpty(currAlt.definition) === false) {\n result = getAlternativesForProd(currAlt.definition);\n }\n });\n return result;\n } else if (prod instanceof Terminal) {\n currPath.push(prod.terminalType);\n } else {\n throw Error(\"non exhaustive match\");\n }\n\n i++;\n }\n result.push({\n partialPath: currPath,\n suffixDef: drop(targetDef, i),\n });\n\n return result;\n}\n\ninterface IPathToExamine {\n idx: number;\n def: IProduction[];\n ruleStack: string[];\n occurrenceStack: number[];\n}\n\nexport function nextPossibleTokensAfter(\n initialDef: IProduction[],\n tokenVector: IToken[],\n tokMatcher: TokenMatcher,\n maxLookAhead: number,\n): ISyntacticContentAssistPath[] {\n const EXIT_NON_TERMINAL: any = \"EXIT_NONE_TERMINAL\";\n // to avoid creating a new Array each time.\n const EXIT_NON_TERMINAL_ARR = [EXIT_NON_TERMINAL];\n const EXIT_ALTERNATIVE: any = \"EXIT_ALTERNATIVE\";\n let foundCompletePath = false;\n\n const tokenVectorLength = tokenVector.length;\n const minimalAlternativesIndex = tokenVectorLength - maxLookAhead - 1;\n\n const result: ISyntacticContentAssistPath[] = [];\n\n const possiblePaths: IPathToExamine[] = [];\n possiblePaths.push({\n idx: -1,\n def: initialDef,\n ruleStack: [],\n occurrenceStack: [],\n });\n\n while (!isEmpty(possiblePaths)) {\n const currPath = possiblePaths.pop()!;\n\n // skip alternatives if no more results can be found (assuming deterministic grammar with fixed lookahead)\n if (currPath === EXIT_ALTERNATIVE) {\n if (\n foundCompletePath &&\n last(possiblePaths)!.idx <= minimalAlternativesIndex\n ) {\n // remove irrelevant alternative\n possiblePaths.pop();\n }\n continue;\n }\n\n const currDef = currPath.def;\n const currIdx = currPath.idx;\n const currRuleStack = currPath.ruleStack;\n const currOccurrenceStack = currPath.occurrenceStack;\n\n // For Example: an empty path could exist in a valid grammar in the case of an EMPTY_ALT\n if (isEmpty(currDef)) {\n continue;\n }\n\n const prod = currDef[0];\n /* istanbul ignore else */\n if (prod === EXIT_NON_TERMINAL) {\n const nextPath = {\n idx: currIdx,\n def: drop(currDef),\n ruleStack: dropRight(currRuleStack),\n occurrenceStack: dropRight(currOccurrenceStack),\n };\n possiblePaths.push(nextPath);\n } else if (prod instanceof Terminal) {\n /* istanbul ignore else */\n if (currIdx < tokenVectorLength - 1) {\n const nextIdx = currIdx + 1;\n const actualToken = tokenVector[nextIdx];\n if (tokMatcher!(actualToken, prod.terminalType)) {\n const nextPath = {\n idx: nextIdx,\n def: drop(currDef),\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPath);\n }\n // end of the line\n } else if (currIdx === tokenVectorLength - 1) {\n // IGNORE ABOVE ELSE\n result.push({\n nextTokenType: prod.terminalType,\n nextTokenOccurrence: prod.idx,\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n });\n foundCompletePath = true;\n } else {\n throw Error(\"non exhaustive match\");\n }\n } else if (prod instanceof NonTerminal) {\n const newRuleStack = clone(currRuleStack);\n newRuleStack.push(prod.nonTerminalName);\n\n const newOccurrenceStack = clone(currOccurrenceStack);\n newOccurrenceStack.push(prod.idx);\n\n const nextPath = {\n idx: currIdx,\n def: prod.definition.concat(EXIT_NON_TERMINAL_ARR, drop(currDef)),\n ruleStack: newRuleStack,\n occurrenceStack: newOccurrenceStack,\n };\n possiblePaths.push(nextPath);\n } else if (prod instanceof Option) {\n // the order of alternatives is meaningful, FILO (Last path will be traversed first).\n const nextPathWithout = {\n idx: currIdx,\n def: drop(currDef),\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPathWithout);\n // required marker to avoid backtracking paths whose higher priority alternatives already matched\n possiblePaths.push(EXIT_ALTERNATIVE);\n\n const nextPathWith = {\n idx: currIdx,\n def: prod.definition.concat(drop(currDef)),\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPathWith);\n } else if (prod instanceof RepetitionMandatory) {\n // TODO:(THE NEW operators here take a while...) (convert once?)\n const secondIteration = new Repetition({\n definition: prod.definition,\n idx: prod.idx,\n });\n const nextDef = prod.definition.concat([secondIteration], drop(currDef));\n const nextPath = {\n idx: currIdx,\n def: nextDef,\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPath);\n } else if (prod instanceof RepetitionMandatoryWithSeparator) {\n // TODO:(THE NEW operators here take a while...) (convert once?)\n const separatorGast = new Terminal({\n terminalType: prod.separator,\n });\n const secondIteration = new Repetition({\n definition: [separatorGast].concat(prod.definition),\n idx: prod.idx,\n });\n const nextDef = prod.definition.concat([secondIteration], drop(currDef));\n const nextPath = {\n idx: currIdx,\n def: nextDef,\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPath);\n } else if (prod instanceof RepetitionWithSeparator) {\n // the order of alternatives is meaningful, FILO (Last path will be traversed first).\n const nextPathWithout = {\n idx: currIdx,\n def: drop(currDef),\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPathWithout);\n // required marker to avoid backtracking paths whose higher priority alternatives already matched\n possiblePaths.push(EXIT_ALTERNATIVE);\n\n const separatorGast = new Terminal({\n terminalType: prod.separator,\n });\n const nthRepetition = new Repetition({\n definition: [separatorGast].concat(prod.definition),\n idx: prod.idx,\n });\n const nextDef = prod.definition.concat([nthRepetition], drop(currDef));\n const nextPathWith = {\n idx: currIdx,\n def: nextDef,\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPathWith);\n } else if (prod instanceof Repetition) {\n // the order of alternatives is meaningful, FILO (Last path will be traversed first).\n const nextPathWithout = {\n idx: currIdx,\n def: drop(currDef),\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPathWithout);\n // required marker to avoid backtracking paths whose higher priority alternatives already matched\n possiblePaths.push(EXIT_ALTERNATIVE);\n\n // TODO: an empty repetition will cause infinite loops here, will the parser detect this in selfAnalysis?\n const nthRepetition = new Repetition({\n definition: prod.definition,\n idx: prod.idx,\n });\n const nextDef = prod.definition.concat([nthRepetition], drop(currDef));\n const nextPathWith = {\n idx: currIdx,\n def: nextDef,\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPathWith);\n } else if (prod instanceof Alternation) {\n // the order of alternatives is meaningful, FILO (Last path will be traversed first).\n for (let i = prod.definition.length - 1; i >= 0; i--) {\n const currAlt: any = prod.definition[i];\n const currAltPath = {\n idx: currIdx,\n def: currAlt.definition.concat(drop(currDef)),\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(currAltPath);\n possiblePaths.push(EXIT_ALTERNATIVE);\n }\n } else if (prod instanceof Alternative) {\n possiblePaths.push({\n idx: currIdx,\n def: prod.definition.concat(drop(currDef)),\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n });\n } else if (prod instanceof Rule) {\n // last because we should only encounter at most a single one of these per invocation.\n possiblePaths.push(\n expandTopLevelRule(prod, currIdx, currRuleStack, currOccurrenceStack),\n );\n } else {\n throw Error(\"non exhaustive match\");\n }\n }\n return result;\n}\n\nfunction expandTopLevelRule(\n topRule: Rule,\n currIdx: number,\n currRuleStack: string[],\n currOccurrenceStack: number[],\n): IPathToExamine {\n const newRuleStack = clone(currRuleStack);\n newRuleStack.push(topRule.name);\n\n const newCurrOccurrenceStack = clone(currOccurrenceStack);\n // top rule is always assumed to have been called with occurrence index 1\n newCurrOccurrenceStack.push(1);\n\n return {\n idx: currIdx,\n def: topRule.definition,\n ruleStack: newRuleStack,\n occurrenceStack: newCurrOccurrenceStack,\n };\n}\n", "import { every, flatten, forEach, has, isEmpty, map, reduce } from \"lodash-es\";\nimport { possiblePathsFrom } from \"./interpreter.js\";\nimport { RestWalker } from \"./rest.js\";\nimport { Predicate, TokenMatcher } from \"../parser/parser.js\";\nimport {\n tokenStructuredMatcher,\n tokenStructuredMatcherNoCategories,\n} from \"../../scan/tokens.js\";\nimport {\n Alternation,\n Alternative as AlternativeGAST,\n GAstVisitor,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n} from \"@chevrotain/gast\";\nimport {\n BaseParser,\n IOrAlt,\n IProduction,\n IProductionWithOccurrence,\n LookaheadProductionType,\n LookaheadSequence,\n Rule,\n TokenType,\n} from \"@chevrotain/types\";\n\nexport enum PROD_TYPE {\n OPTION,\n REPETITION,\n REPETITION_MANDATORY,\n REPETITION_MANDATORY_WITH_SEPARATOR,\n REPETITION_WITH_SEPARATOR,\n ALTERNATION,\n}\n\nexport function getProdType(\n prod: IProduction | LookaheadProductionType,\n): PROD_TYPE {\n /* istanbul ignore else */\n if (prod instanceof Option || prod === \"Option\") {\n return PROD_TYPE.OPTION;\n } else if (prod instanceof Repetition || prod === \"Repetition\") {\n return PROD_TYPE.REPETITION;\n } else if (\n prod instanceof RepetitionMandatory ||\n prod === \"RepetitionMandatory\"\n ) {\n return PROD_TYPE.REPETITION_MANDATORY;\n } else if (\n prod instanceof RepetitionMandatoryWithSeparator ||\n prod === \"RepetitionMandatoryWithSeparator\"\n ) {\n return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR;\n } else if (\n prod instanceof RepetitionWithSeparator ||\n prod === \"RepetitionWithSeparator\"\n ) {\n return PROD_TYPE.REPETITION_WITH_SEPARATOR;\n } else if (prod instanceof Alternation || prod === \"Alternation\") {\n return PROD_TYPE.ALTERNATION;\n } else {\n throw Error(\"non exhaustive match\");\n }\n}\n\nexport function getLookaheadPaths(options: {\n occurrence: number;\n rule: Rule;\n prodType: LookaheadProductionType;\n maxLookahead: number;\n}): LookaheadSequence[] {\n const { occurrence, rule, prodType, maxLookahead } = options;\n const type = getProdType(prodType);\n if (type === PROD_TYPE.ALTERNATION) {\n return getLookaheadPathsForOr(occurrence, rule, maxLookahead);\n } else {\n return getLookaheadPathsForOptionalProd(\n occurrence,\n rule,\n type,\n maxLookahead,\n );\n }\n}\n\nexport function buildLookaheadFuncForOr(\n occurrence: number,\n ruleGrammar: Rule,\n maxLookahead: number,\n hasPredicates: boolean,\n dynamicTokensEnabled: boolean,\n laFuncBuilder: Function,\n): (orAlts?: IOrAlt[]) => number | undefined {\n const lookAheadPaths = getLookaheadPathsForOr(\n occurrence,\n ruleGrammar,\n maxLookahead,\n );\n\n const tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths)\n ? tokenStructuredMatcherNoCategories\n : tokenStructuredMatcher;\n\n return laFuncBuilder(\n lookAheadPaths,\n hasPredicates,\n tokenMatcher,\n dynamicTokensEnabled,\n );\n}\n\n/**\n * When dealing with an Optional production (OPTION/MANY/2nd iteration of AT_LEAST_ONE/...) we need to compare\n * the lookahead \"inside\" the production and the lookahead immediately \"after\" it in the same top level rule (context free).\n *\n * Example: given a production:\n * ABC(DE)?DF\n *\n * The optional '(DE)?' should only be entered if we see 'DE'. a single Token 'D' is not sufficient to distinguish between the two\n * alternatives.\n *\n * @returns A Lookahead function which will return true IFF the parser should parse the Optional production.\n */\nexport function buildLookaheadFuncForOptionalProd(\n occurrence: number,\n ruleGrammar: Rule,\n k: number,\n dynamicTokensEnabled: boolean,\n prodType: PROD_TYPE,\n lookaheadBuilder: (\n lookAheadSequence: LookaheadSequence,\n tokenMatcher: TokenMatcher,\n dynamicTokensEnabled: boolean,\n ) => () => boolean,\n): () => boolean {\n const lookAheadPaths = getLookaheadPathsForOptionalProd(\n occurrence,\n ruleGrammar,\n prodType,\n k,\n );\n\n const tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths)\n ? tokenStructuredMatcherNoCategories\n : tokenStructuredMatcher;\n\n return lookaheadBuilder(\n lookAheadPaths[0],\n tokenMatcher,\n dynamicTokensEnabled,\n );\n}\n\nexport type Alternative = TokenType[][];\n\nexport function buildAlternativesLookAheadFunc(\n alts: LookaheadSequence[],\n hasPredicates: boolean,\n tokenMatcher: TokenMatcher,\n dynamicTokensEnabled: boolean,\n): (orAlts: IOrAlt[]) => number | undefined {\n const numOfAlts = alts.length;\n const areAllOneTokenLookahead = every(alts, (currAlt) => {\n return every(currAlt, (currPath) => {\n return currPath.length === 1;\n });\n });\n\n // This version takes into account the predicates as well.\n if (hasPredicates) {\n /**\n * @returns {number} - The chosen alternative index\n */\n return function (\n this: BaseParser,\n orAlts: IOrAlt[],\n ): number | undefined {\n // unfortunately the predicates must be extracted every single time\n // as they cannot be cached due to references to parameters(vars) which are no longer valid.\n // note that in the common case of no predicates, no cpu time will be wasted on this (see else block)\n const predicates: (Predicate | undefined)[] = map(\n orAlts,\n (currAlt) => currAlt.GATE,\n );\n\n for (let t = 0; t < numOfAlts; t++) {\n const currAlt = alts[t];\n const currNumOfPaths = currAlt.length;\n\n const currPredicate = predicates[t];\n if (currPredicate !== undefined && currPredicate.call(this) === false) {\n // if the predicate does not match there is no point in checking the paths\n continue;\n }\n nextPath: for (let j = 0; j < currNumOfPaths; j++) {\n const currPath = currAlt[j];\n const currPathLength = currPath.length;\n for (let i = 0; i < currPathLength; i++) {\n const nextToken = this.LA(i + 1);\n if (tokenMatcher(nextToken, currPath[i]) === false) {\n // mismatch in current path\n // try the next pth\n continue nextPath;\n }\n }\n // found a full path that matches.\n // this will also work for an empty ALT as the loop will be skipped\n return t;\n }\n // none of the paths for the current alternative matched\n // try the next alternative\n }\n // none of the alternatives could be matched\n return undefined;\n };\n } else if (areAllOneTokenLookahead && !dynamicTokensEnabled) {\n // optimized (common) case of all the lookaheads paths requiring only\n // a single token lookahead. These Optimizations cannot work if dynamically defined Tokens are used.\n const singleTokenAlts = map(alts, (currAlt) => {\n return flatten(currAlt);\n });\n\n const choiceToAlt = reduce(\n singleTokenAlts,\n (result, currAlt, idx) => {\n forEach(currAlt, (currTokType) => {\n if (!has(result, currTokType.tokenTypeIdx!)) {\n result[currTokType.tokenTypeIdx!] = idx;\n }\n forEach(currTokType.categoryMatches!, (currExtendingType) => {\n if (!has(result, currExtendingType)) {\n result[currExtendingType] = idx;\n }\n });\n });\n return result;\n },\n {} as Record,\n );\n\n /**\n * @returns {number} - The chosen alternative index\n */\n return function (this: BaseParser): number {\n const nextToken = this.LA(1);\n return choiceToAlt[nextToken.tokenTypeIdx];\n };\n } else {\n // optimized lookahead without needing to check the predicates at all.\n // this causes code duplication which is intentional to improve performance.\n /**\n * @returns {number} - The chosen alternative index\n */\n return function (this: BaseParser): number | undefined {\n for (let t = 0; t < numOfAlts; t++) {\n const currAlt = alts[t];\n const currNumOfPaths = currAlt.length;\n nextPath: for (let j = 0; j < currNumOfPaths; j++) {\n const currPath = currAlt[j];\n const currPathLength = currPath.length;\n for (let i = 0; i < currPathLength; i++) {\n const nextToken = this.LA(i + 1);\n if (tokenMatcher(nextToken, currPath[i]) === false) {\n // mismatch in current path\n // try the next pth\n continue nextPath;\n }\n }\n // found a full path that matches.\n // this will also work for an empty ALT as the loop will be skipped\n return t;\n }\n // none of the paths for the current alternative matched\n // try the next alternative\n }\n // none of the alternatives could be matched\n return undefined;\n };\n }\n}\n\nexport function buildSingleAlternativeLookaheadFunction(\n alt: LookaheadSequence,\n tokenMatcher: TokenMatcher,\n dynamicTokensEnabled: boolean,\n): () => boolean {\n const areAllOneTokenLookahead = every(alt, (currPath) => {\n return currPath.length === 1;\n });\n\n const numOfPaths = alt.length;\n\n // optimized (common) case of all the lookaheads paths requiring only\n // a single token lookahead.\n if (areAllOneTokenLookahead && !dynamicTokensEnabled) {\n const singleTokensTypes = flatten(alt);\n\n if (\n singleTokensTypes.length === 1 &&\n isEmpty((singleTokensTypes[0]).categoryMatches)\n ) {\n const expectedTokenType = singleTokensTypes[0];\n const expectedTokenUniqueKey = (expectedTokenType).tokenTypeIdx;\n\n return function (this: BaseParser): boolean {\n return this.LA(1).tokenTypeIdx === expectedTokenUniqueKey;\n };\n } else {\n const choiceToAlt = reduce(\n singleTokensTypes,\n (result, currTokType, idx) => {\n result[currTokType.tokenTypeIdx!] = true;\n forEach(currTokType.categoryMatches!, (currExtendingType) => {\n result[currExtendingType] = true;\n });\n return result;\n },\n [] as boolean[],\n );\n\n return function (this: BaseParser): boolean {\n const nextToken = this.LA(1);\n return choiceToAlt[nextToken.tokenTypeIdx] === true;\n };\n }\n } else {\n return function (this: BaseParser): boolean {\n nextPath: for (let j = 0; j < numOfPaths; j++) {\n const currPath = alt[j];\n const currPathLength = currPath.length;\n for (let i = 0; i < currPathLength; i++) {\n const nextToken = this.LA(i + 1);\n if (tokenMatcher(nextToken, currPath[i]) === false) {\n // mismatch in current path\n // try the next pth\n continue nextPath;\n }\n }\n // found a full path that matches.\n return true;\n }\n\n // none of the paths matched\n return false;\n };\n }\n}\n\nclass RestDefinitionFinderWalker extends RestWalker {\n private restDef: IProduction[];\n\n constructor(\n private topProd: Rule,\n private targetOccurrence: number,\n private targetProdType: PROD_TYPE,\n ) {\n super();\n }\n\n startWalking(): IProduction[] {\n this.walk(this.topProd);\n return this.restDef;\n }\n\n private checkIsTarget(\n node: IProductionWithOccurrence,\n expectedProdType: PROD_TYPE,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): boolean {\n if (\n node.idx === this.targetOccurrence &&\n this.targetProdType === expectedProdType\n ) {\n this.restDef = currRest.concat(prevRest);\n return true;\n }\n // performance optimization, do not iterate over the entire Grammar ast after we have found the target\n return false;\n }\n\n walkOption(\n optionProd: Option,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (!this.checkIsTarget(optionProd, PROD_TYPE.OPTION, currRest, prevRest)) {\n super.walkOption(optionProd, currRest, prevRest);\n }\n }\n\n walkAtLeastOne(\n atLeastOneProd: RepetitionMandatory,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (\n !this.checkIsTarget(\n atLeastOneProd,\n PROD_TYPE.REPETITION_MANDATORY,\n currRest,\n prevRest,\n )\n ) {\n super.walkOption(atLeastOneProd, currRest, prevRest);\n }\n }\n\n walkAtLeastOneSep(\n atLeastOneSepProd: RepetitionMandatoryWithSeparator,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (\n !this.checkIsTarget(\n atLeastOneSepProd,\n PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,\n currRest,\n prevRest,\n )\n ) {\n super.walkOption(atLeastOneSepProd, currRest, prevRest);\n }\n }\n\n walkMany(\n manyProd: Repetition,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (\n !this.checkIsTarget(manyProd, PROD_TYPE.REPETITION, currRest, prevRest)\n ) {\n super.walkOption(manyProd, currRest, prevRest);\n }\n }\n\n walkManySep(\n manySepProd: RepetitionWithSeparator,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (\n !this.checkIsTarget(\n manySepProd,\n PROD_TYPE.REPETITION_WITH_SEPARATOR,\n currRest,\n prevRest,\n )\n ) {\n super.walkOption(manySepProd, currRest, prevRest);\n }\n }\n}\n\n/**\n * Returns the definition of a target production in a top level level rule.\n */\nclass InsideDefinitionFinderVisitor extends GAstVisitor {\n public result: IProduction[] = [];\n\n constructor(\n private targetOccurrence: number,\n private targetProdType: PROD_TYPE,\n private targetRef?: any,\n ) {\n super();\n }\n\n private checkIsTarget(\n node: { definition: IProduction[] } & IProductionWithOccurrence,\n expectedProdName: PROD_TYPE,\n ): void {\n if (\n node.idx === this.targetOccurrence &&\n this.targetProdType === expectedProdName &&\n (this.targetRef === undefined || node === this.targetRef)\n ) {\n this.result = node.definition;\n }\n }\n\n public visitOption(node: Option): void {\n this.checkIsTarget(node, PROD_TYPE.OPTION);\n }\n\n public visitRepetition(node: Repetition): void {\n this.checkIsTarget(node, PROD_TYPE.REPETITION);\n }\n\n public visitRepetitionMandatory(node: RepetitionMandatory): void {\n this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY);\n }\n\n public visitRepetitionMandatoryWithSeparator(\n node: RepetitionMandatoryWithSeparator,\n ): void {\n this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR);\n }\n\n public visitRepetitionWithSeparator(node: RepetitionWithSeparator): void {\n this.checkIsTarget(node, PROD_TYPE.REPETITION_WITH_SEPARATOR);\n }\n\n public visitAlternation(node: Alternation): void {\n this.checkIsTarget(node, PROD_TYPE.ALTERNATION);\n }\n}\n\nfunction initializeArrayOfArrays(size: number): any[][] {\n const result = new Array(size);\n for (let i = 0; i < size; i++) {\n result[i] = [];\n }\n return result;\n}\n\n/**\n * A sort of hash function between a Path in the grammar and a string.\n * Note that this returns multiple \"hashes\" to support the scenario of token categories.\n * - A single path with categories may match multiple **actual** paths.\n */\nfunction pathToHashKeys(path: TokenType[]): string[] {\n let keys = [\"\"];\n for (let i = 0; i < path.length; i++) {\n const tokType = path[i];\n const longerKeys = [];\n for (let j = 0; j < keys.length; j++) {\n const currShorterKey = keys[j];\n longerKeys.push(currShorterKey + \"_\" + tokType.tokenTypeIdx);\n for (let t = 0; t < tokType.categoryMatches!.length; t++) {\n const categoriesKeySuffix = \"_\" + tokType.categoryMatches![t];\n longerKeys.push(currShorterKey + categoriesKeySuffix);\n }\n }\n keys = longerKeys;\n }\n return keys;\n}\n\n/**\n * Imperative style due to being called from a hot spot\n */\nfunction isUniquePrefixHash(\n altKnownPathsKeys: Record[],\n searchPathKeys: string[],\n idx: number,\n): boolean {\n for (\n let currAltIdx = 0;\n currAltIdx < altKnownPathsKeys.length;\n currAltIdx++\n ) {\n // We only want to test vs the other alternatives\n if (currAltIdx === idx) {\n continue;\n }\n const otherAltKnownPathsKeys = altKnownPathsKeys[currAltIdx];\n for (let searchIdx = 0; searchIdx < searchPathKeys.length; searchIdx++) {\n const searchKey = searchPathKeys[searchIdx];\n if (otherAltKnownPathsKeys[searchKey] === true) {\n return false;\n }\n }\n }\n // None of the SearchPathKeys were found in any of the other alternatives\n return true;\n}\n\nexport function lookAheadSequenceFromAlternatives(\n altsDefs: IProduction[],\n k: number,\n): LookaheadSequence[] {\n const partialAlts = map(altsDefs, (currAlt) =>\n possiblePathsFrom([currAlt], 1),\n );\n const finalResult = initializeArrayOfArrays(partialAlts.length);\n const altsHashes = map(partialAlts, (currAltPaths) => {\n const dict: { [key: string]: boolean } = {};\n forEach(currAltPaths, (item) => {\n const keys = pathToHashKeys(item.partialPath);\n forEach(keys, (currKey) => {\n dict[currKey] = true;\n });\n });\n return dict;\n });\n let newData = partialAlts;\n\n // maxLookahead loop\n for (let pathLength = 1; pathLength <= k; pathLength++) {\n const currDataset = newData;\n newData = initializeArrayOfArrays(currDataset.length);\n\n // alternatives loop\n for (let altIdx = 0; altIdx < currDataset.length; altIdx++) {\n const currAltPathsAndSuffixes = currDataset[altIdx];\n // paths in current alternative loop\n for (\n let currPathIdx = 0;\n currPathIdx < currAltPathsAndSuffixes.length;\n currPathIdx++\n ) {\n const currPathPrefix = currAltPathsAndSuffixes[currPathIdx].partialPath;\n const suffixDef = currAltPathsAndSuffixes[currPathIdx].suffixDef;\n const prefixKeys = pathToHashKeys(currPathPrefix);\n const isUnique = isUniquePrefixHash(altsHashes, prefixKeys, altIdx);\n // End of the line for this path.\n if (isUnique || isEmpty(suffixDef) || currPathPrefix.length === k) {\n const currAltResult = finalResult[altIdx];\n // TODO: Can we implement a containsPath using Maps/Dictionaries?\n if (containsPath(currAltResult, currPathPrefix) === false) {\n currAltResult.push(currPathPrefix);\n // Update all new keys for the current path.\n for (let j = 0; j < prefixKeys.length; j++) {\n const currKey = prefixKeys[j];\n altsHashes[altIdx][currKey] = true;\n }\n }\n }\n // Expand longer paths\n else {\n const newPartialPathsAndSuffixes = possiblePathsFrom(\n suffixDef,\n pathLength + 1,\n currPathPrefix,\n );\n newData[altIdx] = newData[altIdx].concat(newPartialPathsAndSuffixes);\n\n // Update keys for new known paths\n forEach(newPartialPathsAndSuffixes, (item) => {\n const prefixKeys = pathToHashKeys(item.partialPath);\n forEach(prefixKeys, (key) => {\n altsHashes[altIdx][key] = true;\n });\n });\n }\n }\n }\n }\n\n return finalResult;\n}\n\nexport function getLookaheadPathsForOr(\n occurrence: number,\n ruleGrammar: Rule,\n k: number,\n orProd?: Alternation,\n): LookaheadSequence[] {\n const visitor = new InsideDefinitionFinderVisitor(\n occurrence,\n PROD_TYPE.ALTERNATION,\n orProd,\n );\n ruleGrammar.accept(visitor);\n return lookAheadSequenceFromAlternatives(visitor.result, k);\n}\n\nexport function getLookaheadPathsForOptionalProd(\n occurrence: number,\n ruleGrammar: Rule,\n prodType: PROD_TYPE,\n k: number,\n): LookaheadSequence[] {\n const insideDefVisitor = new InsideDefinitionFinderVisitor(\n occurrence,\n prodType,\n );\n ruleGrammar.accept(insideDefVisitor);\n const insideDef = insideDefVisitor.result;\n\n const afterDefWalker = new RestDefinitionFinderWalker(\n ruleGrammar,\n occurrence,\n prodType,\n );\n const afterDef = afterDefWalker.startWalking();\n\n const insideFlat = new AlternativeGAST({ definition: insideDef });\n const afterFlat = new AlternativeGAST({ definition: afterDef });\n\n return lookAheadSequenceFromAlternatives([insideFlat, afterFlat], k);\n}\n\nexport function containsPath(\n alternative: Alternative,\n searchPath: TokenType[],\n): boolean {\n compareOtherPath: for (let i = 0; i < alternative.length; i++) {\n const otherPath = alternative[i];\n if (otherPath.length !== searchPath.length) {\n continue;\n }\n for (let j = 0; j < otherPath.length; j++) {\n const searchTok = searchPath[j];\n const otherTok = otherPath[j];\n\n const matchingTokens =\n searchTok === otherTok ||\n otherTok.categoryMatchesMap![searchTok.tokenTypeIdx!] !== undefined;\n if (matchingTokens === false) {\n continue compareOtherPath;\n }\n }\n return true;\n }\n\n return false;\n}\n\nexport function isStrictPrefixOfPath(\n prefix: TokenType[],\n other: TokenType[],\n): boolean {\n return (\n prefix.length < other.length &&\n every(prefix, (tokType, idx) => {\n const otherTokType = other[idx];\n return (\n tokType === otherTokType ||\n otherTokType.categoryMatchesMap![tokType.tokenTypeIdx!]\n );\n })\n );\n}\n\nexport function areTokenCategoriesNotUsed(\n lookAheadPaths: LookaheadSequence[],\n): boolean {\n return every(lookAheadPaths, (singleAltPaths) =>\n every(singleAltPaths, (singlePath) =>\n every(singlePath, (token) => isEmpty(token.categoryMatches!)),\n ),\n );\n}\n", "import {\n clone,\n compact,\n difference,\n drop,\n dropRight,\n filter,\n first,\n flatMap,\n flatten,\n forEach,\n groupBy,\n includes,\n isEmpty,\n map,\n pickBy,\n reduce,\n reject,\n values,\n} from \"lodash-es\";\nimport {\n IParserAmbiguousAlternativesDefinitionError,\n IParserDuplicatesDefinitionError,\n IParserEmptyAlternativeDefinitionError,\n ParserDefinitionErrorType,\n} from \"../parser/parser.js\";\nimport {\n Alternation,\n Alternative as AlternativeGAST,\n GAstVisitor,\n getProductionDslName,\n isOptionalProd,\n NonTerminal,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n Terminal,\n} from \"@chevrotain/gast\";\nimport {\n Alternative,\n containsPath,\n getLookaheadPathsForOptionalProd,\n getLookaheadPathsForOr,\n getProdType,\n isStrictPrefixOfPath,\n} from \"./lookahead.js\";\nimport { nextPossibleTokensAfter } from \"./interpreter.js\";\nimport {\n ILookaheadStrategy,\n IProduction,\n IProductionWithOccurrence,\n Rule,\n TokenType,\n} from \"@chevrotain/types\";\nimport {\n IGrammarValidatorErrorMessageProvider,\n IParserDefinitionError,\n} from \"./types.js\";\nimport { tokenStructuredMatcher } from \"../../scan/tokens.js\";\n\nexport function validateLookahead(options: {\n lookaheadStrategy: ILookaheadStrategy;\n rules: Rule[];\n tokenTypes: TokenType[];\n grammarName: string;\n}): IParserDefinitionError[] {\n const lookaheadValidationErrorMessages = options.lookaheadStrategy.validate({\n rules: options.rules,\n tokenTypes: options.tokenTypes,\n grammarName: options.grammarName,\n });\n return map(lookaheadValidationErrorMessages, (errorMessage) => ({\n type: ParserDefinitionErrorType.CUSTOM_LOOKAHEAD_VALIDATION,\n ...errorMessage,\n }));\n}\n\nexport function validateGrammar(\n topLevels: Rule[],\n tokenTypes: TokenType[],\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n grammarName: string,\n): IParserDefinitionError[] {\n const duplicateErrors: IParserDefinitionError[] = flatMap(\n topLevels,\n (currTopLevel) =>\n validateDuplicateProductions(currTopLevel, errMsgProvider),\n );\n\n const termsNamespaceConflictErrors = checkTerminalAndNoneTerminalsNameSpace(\n topLevels,\n tokenTypes,\n errMsgProvider,\n );\n\n const tooManyAltsErrors = flatMap(topLevels, (curRule) =>\n validateTooManyAlts(curRule, errMsgProvider),\n );\n\n const duplicateRulesError = flatMap(topLevels, (curRule) =>\n validateRuleDoesNotAlreadyExist(\n curRule,\n topLevels,\n grammarName,\n errMsgProvider,\n ),\n );\n\n return duplicateErrors.concat(\n termsNamespaceConflictErrors,\n tooManyAltsErrors,\n duplicateRulesError,\n );\n}\n\nfunction validateDuplicateProductions(\n topLevelRule: Rule,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserDuplicatesDefinitionError[] {\n const collectorVisitor = new OccurrenceValidationCollector();\n topLevelRule.accept(collectorVisitor);\n const allRuleProductions = collectorVisitor.allProductions;\n\n const productionGroups = groupBy(\n allRuleProductions,\n identifyProductionForDuplicates,\n );\n\n const duplicates: any = pickBy(productionGroups, (currGroup) => {\n return currGroup.length > 1;\n });\n\n const errors = map(values(duplicates), (currDuplicates: any) => {\n const firstProd: any = first(currDuplicates);\n const msg = errMsgProvider.buildDuplicateFoundError(\n topLevelRule,\n currDuplicates,\n );\n const dslName = getProductionDslName(firstProd);\n const defError: IParserDuplicatesDefinitionError = {\n message: msg,\n type: ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,\n ruleName: topLevelRule.name,\n dslName: dslName,\n occurrence: firstProd.idx,\n };\n\n const param = getExtraProductionArgument(firstProd);\n if (param) {\n defError.parameter = param;\n }\n\n return defError;\n });\n return errors;\n}\n\nexport function identifyProductionForDuplicates(\n prod: IProductionWithOccurrence,\n): string {\n return `${getProductionDslName(prod)}_#_${\n prod.idx\n }_#_${getExtraProductionArgument(prod)}`;\n}\n\nfunction getExtraProductionArgument(prod: IProductionWithOccurrence): string {\n if (prod instanceof Terminal) {\n return prod.terminalType.name;\n } else if (prod instanceof NonTerminal) {\n return prod.nonTerminalName;\n } else {\n return \"\";\n }\n}\n\nexport class OccurrenceValidationCollector extends GAstVisitor {\n public allProductions: IProductionWithOccurrence[] = [];\n\n public visitNonTerminal(subrule: NonTerminal): void {\n this.allProductions.push(subrule);\n }\n\n public visitOption(option: Option): void {\n this.allProductions.push(option);\n }\n\n public visitRepetitionWithSeparator(manySep: RepetitionWithSeparator): void {\n this.allProductions.push(manySep);\n }\n\n public visitRepetitionMandatory(atLeastOne: RepetitionMandatory): void {\n this.allProductions.push(atLeastOne);\n }\n\n public visitRepetitionMandatoryWithSeparator(\n atLeastOneSep: RepetitionMandatoryWithSeparator,\n ): void {\n this.allProductions.push(atLeastOneSep);\n }\n\n public visitRepetition(many: Repetition): void {\n this.allProductions.push(many);\n }\n\n public visitAlternation(or: Alternation): void {\n this.allProductions.push(or);\n }\n\n public visitTerminal(terminal: Terminal): void {\n this.allProductions.push(terminal);\n }\n}\n\nexport function validateRuleDoesNotAlreadyExist(\n rule: Rule,\n allRules: Rule[],\n className: string,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserDefinitionError[] {\n const errors = [];\n const occurrences = reduce(\n allRules,\n (result, curRule) => {\n if (curRule.name === rule.name) {\n return result + 1;\n }\n return result;\n },\n 0,\n );\n if (occurrences > 1) {\n const errMsg = errMsgProvider.buildDuplicateRuleNameError({\n topLevelRule: rule,\n grammarName: className,\n });\n errors.push({\n message: errMsg,\n type: ParserDefinitionErrorType.DUPLICATE_RULE_NAME,\n ruleName: rule.name,\n });\n }\n\n return errors;\n}\n\n// TODO: is there anyway to get only the rule names of rules inherited from the super grammars?\n// This is not part of the IGrammarErrorProvider because the validation cannot be performed on\n// The grammar structure, only at runtime.\nexport function validateRuleIsOverridden(\n ruleName: string,\n definedRulesNames: string[],\n className: string,\n): IParserDefinitionError[] {\n const errors = [];\n let errMsg;\n\n if (!includes(definedRulesNames, ruleName)) {\n errMsg =\n `Invalid rule override, rule: ->${ruleName}<- cannot be overridden in the grammar: ->${className}<-` +\n `as it is not defined in any of the super grammars `;\n errors.push({\n message: errMsg,\n type: ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,\n ruleName: ruleName,\n });\n }\n\n return errors;\n}\n\nexport function validateNoLeftRecursion(\n topRule: Rule,\n currRule: Rule,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n path: Rule[] = [],\n): IParserDefinitionError[] {\n const errors: IParserDefinitionError[] = [];\n const nextNonTerminals = getFirstNoneTerminal(currRule.definition);\n if (isEmpty(nextNonTerminals)) {\n return [];\n } else {\n const ruleName = topRule.name;\n const foundLeftRecursion = includes(nextNonTerminals, topRule);\n if (foundLeftRecursion) {\n errors.push({\n message: errMsgProvider.buildLeftRecursionError({\n topLevelRule: topRule,\n leftRecursionPath: path,\n }),\n type: ParserDefinitionErrorType.LEFT_RECURSION,\n ruleName: ruleName,\n });\n }\n\n // we are only looking for cyclic paths leading back to the specific topRule\n // other cyclic paths are ignored, we still need this difference to avoid infinite loops...\n const validNextSteps = difference(nextNonTerminals, path.concat([topRule]));\n const errorsFromNextSteps = flatMap(validNextSteps, (currRefRule) => {\n const newPath = clone(path);\n newPath.push(currRefRule);\n return validateNoLeftRecursion(\n topRule,\n currRefRule,\n errMsgProvider,\n newPath,\n );\n });\n\n return errors.concat(errorsFromNextSteps);\n }\n}\n\nexport function getFirstNoneTerminal(definition: IProduction[]): Rule[] {\n let result: Rule[] = [];\n if (isEmpty(definition)) {\n return result;\n }\n const firstProd = first(definition);\n\n /* istanbul ignore else */\n if (firstProd instanceof NonTerminal) {\n result.push(firstProd.referencedRule);\n } else if (\n firstProd instanceof AlternativeGAST ||\n firstProd instanceof Option ||\n firstProd instanceof RepetitionMandatory ||\n firstProd instanceof RepetitionMandatoryWithSeparator ||\n firstProd instanceof RepetitionWithSeparator ||\n firstProd instanceof Repetition\n ) {\n result = result.concat(\n getFirstNoneTerminal(firstProd.definition),\n );\n } else if (firstProd instanceof Alternation) {\n // each sub definition in alternation is a FLAT\n result = flatten(\n map(firstProd.definition, (currSubDef) =>\n getFirstNoneTerminal((currSubDef).definition),\n ),\n );\n } else if (firstProd instanceof Terminal) {\n // nothing to see, move along\n } else {\n throw Error(\"non exhaustive match\");\n }\n\n const isFirstOptional = isOptionalProd(firstProd);\n const hasMore = definition.length > 1;\n if (isFirstOptional && hasMore) {\n const rest = drop(definition);\n return result.concat(getFirstNoneTerminal(rest));\n } else {\n return result;\n }\n}\n\nclass OrCollector extends GAstVisitor {\n public alternations: Alternation[] = [];\n\n public visitAlternation(node: Alternation): void {\n this.alternations.push(node);\n }\n}\n\nexport function validateEmptyOrAlternative(\n topLevelRule: Rule,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserEmptyAlternativeDefinitionError[] {\n const orCollector = new OrCollector();\n topLevelRule.accept(orCollector);\n const ors = orCollector.alternations;\n\n const errors = flatMap(\n ors,\n (currOr) => {\n const exceptLast = dropRight(currOr.definition);\n return flatMap(exceptLast, (currAlternative, currAltIdx) => {\n const possibleFirstInAlt = nextPossibleTokensAfter(\n [currAlternative],\n [],\n tokenStructuredMatcher,\n 1,\n );\n if (isEmpty(possibleFirstInAlt)) {\n return [\n {\n message: errMsgProvider.buildEmptyAlternationError({\n topLevelRule: topLevelRule,\n alternation: currOr,\n emptyChoiceIdx: currAltIdx,\n }),\n type: ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,\n ruleName: topLevelRule.name,\n occurrence: currOr.idx,\n alternative: currAltIdx + 1,\n },\n ];\n } else {\n return [];\n }\n });\n },\n );\n\n return errors;\n}\n\nexport function validateAmbiguousAlternationAlternatives(\n topLevelRule: Rule,\n globalMaxLookahead: number,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserAmbiguousAlternativesDefinitionError[] {\n const orCollector = new OrCollector();\n topLevelRule.accept(orCollector);\n let ors = orCollector.alternations;\n\n // New Handling of ignoring ambiguities\n // - https://github.com/chevrotain/chevrotain/issues/869\n ors = reject(ors, (currOr) => currOr.ignoreAmbiguities === true);\n\n const errors = flatMap(ors, (currOr: Alternation) => {\n const currOccurrence = currOr.idx;\n const actualMaxLookahead = currOr.maxLookahead || globalMaxLookahead;\n const alternatives = getLookaheadPathsForOr(\n currOccurrence,\n topLevelRule,\n actualMaxLookahead,\n currOr,\n );\n const altsAmbiguityErrors = checkAlternativesAmbiguities(\n alternatives,\n currOr,\n topLevelRule,\n errMsgProvider,\n );\n const altsPrefixAmbiguityErrors = checkPrefixAlternativesAmbiguities(\n alternatives,\n currOr,\n topLevelRule,\n errMsgProvider,\n );\n\n return altsAmbiguityErrors.concat(altsPrefixAmbiguityErrors);\n });\n\n return errors;\n}\n\nexport class RepetitionCollector extends GAstVisitor {\n public allProductions: (IProductionWithOccurrence & {\n maxLookahead?: number;\n })[] = [];\n\n public visitRepetitionWithSeparator(manySep: RepetitionWithSeparator): void {\n this.allProductions.push(manySep);\n }\n\n public visitRepetitionMandatory(atLeastOne: RepetitionMandatory): void {\n this.allProductions.push(atLeastOne);\n }\n\n public visitRepetitionMandatoryWithSeparator(\n atLeastOneSep: RepetitionMandatoryWithSeparator,\n ): void {\n this.allProductions.push(atLeastOneSep);\n }\n\n public visitRepetition(many: Repetition): void {\n this.allProductions.push(many);\n }\n}\n\nexport function validateTooManyAlts(\n topLevelRule: Rule,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserDefinitionError[] {\n const orCollector = new OrCollector();\n topLevelRule.accept(orCollector);\n const ors = orCollector.alternations;\n\n const errors = flatMap(ors, (currOr) => {\n if (currOr.definition.length > 255) {\n return [\n {\n message: errMsgProvider.buildTooManyAlternativesError({\n topLevelRule: topLevelRule,\n alternation: currOr,\n }),\n type: ParserDefinitionErrorType.TOO_MANY_ALTS,\n ruleName: topLevelRule.name,\n occurrence: currOr.idx,\n },\n ];\n } else {\n return [];\n }\n });\n\n return errors;\n}\n\nexport function validateSomeNonEmptyLookaheadPath(\n topLevelRules: Rule[],\n maxLookahead: number,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserDefinitionError[] {\n const errors: IParserDefinitionError[] = [];\n forEach(topLevelRules, (currTopRule) => {\n const collectorVisitor = new RepetitionCollector();\n currTopRule.accept(collectorVisitor);\n const allRuleProductions = collectorVisitor.allProductions;\n forEach(allRuleProductions, (currProd) => {\n const prodType = getProdType(currProd);\n const actualMaxLookahead = currProd.maxLookahead || maxLookahead;\n const currOccurrence = currProd.idx;\n const paths = getLookaheadPathsForOptionalProd(\n currOccurrence,\n currTopRule,\n prodType,\n actualMaxLookahead,\n );\n const pathsInsideProduction = paths[0];\n if (isEmpty(flatten(pathsInsideProduction))) {\n const errMsg = errMsgProvider.buildEmptyRepetitionError({\n topLevelRule: currTopRule,\n repetition: currProd,\n });\n errors.push({\n message: errMsg,\n type: ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,\n ruleName: currTopRule.name,\n });\n }\n });\n });\n\n return errors;\n}\n\nexport interface IAmbiguityDescriptor {\n alts: number[];\n path: TokenType[];\n}\n\nfunction checkAlternativesAmbiguities(\n alternatives: Alternative[],\n alternation: Alternation,\n rule: Rule,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserAmbiguousAlternativesDefinitionError[] {\n const foundAmbiguousPaths: Alternative = [];\n const identicalAmbiguities = reduce(\n alternatives,\n (result, currAlt, currAltIdx) => {\n // ignore (skip) ambiguities with this alternative\n if (alternation.definition[currAltIdx].ignoreAmbiguities === true) {\n return result;\n }\n\n forEach(currAlt, (currPath) => {\n const altsCurrPathAppearsIn = [currAltIdx];\n forEach(alternatives, (currOtherAlt, currOtherAltIdx) => {\n if (\n currAltIdx !== currOtherAltIdx &&\n containsPath(currOtherAlt, currPath) &&\n // ignore (skip) ambiguities with this \"other\" alternative\n alternation.definition[currOtherAltIdx].ignoreAmbiguities !== true\n ) {\n altsCurrPathAppearsIn.push(currOtherAltIdx);\n }\n });\n\n if (\n altsCurrPathAppearsIn.length > 1 &&\n !containsPath(foundAmbiguousPaths, currPath)\n ) {\n foundAmbiguousPaths.push(currPath);\n result.push({\n alts: altsCurrPathAppearsIn,\n path: currPath,\n });\n }\n });\n return result;\n },\n [] as { alts: number[]; path: TokenType[] }[],\n );\n\n const currErrors = map(identicalAmbiguities, (currAmbDescriptor) => {\n const ambgIndices = map(\n currAmbDescriptor.alts,\n (currAltIdx) => currAltIdx + 1,\n );\n\n const currMessage = errMsgProvider.buildAlternationAmbiguityError({\n topLevelRule: rule,\n alternation: alternation,\n ambiguityIndices: ambgIndices,\n prefixPath: currAmbDescriptor.path,\n });\n\n return {\n message: currMessage,\n type: ParserDefinitionErrorType.AMBIGUOUS_ALTS,\n ruleName: rule.name,\n occurrence: alternation.idx,\n alternatives: currAmbDescriptor.alts,\n };\n });\n\n return currErrors;\n}\n\nexport function checkPrefixAlternativesAmbiguities(\n alternatives: Alternative[],\n alternation: Alternation,\n rule: Rule,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserAmbiguousAlternativesDefinitionError[] {\n // flatten\n const pathsAndIndices = reduce(\n alternatives,\n (result, currAlt, idx) => {\n const currPathsAndIdx = map(currAlt, (currPath) => {\n return { idx: idx, path: currPath };\n });\n return result.concat(currPathsAndIdx);\n },\n [] as { idx: number; path: TokenType[] }[],\n );\n\n const errors = compact(\n flatMap(pathsAndIndices, (currPathAndIdx) => {\n const alternativeGast = alternation.definition[currPathAndIdx.idx];\n // ignore (skip) ambiguities with this alternative\n if (alternativeGast.ignoreAmbiguities === true) {\n return [];\n }\n const targetIdx = currPathAndIdx.idx;\n const targetPath = currPathAndIdx.path;\n\n const prefixAmbiguitiesPathsAndIndices = filter(\n pathsAndIndices,\n (searchPathAndIdx) => {\n // prefix ambiguity can only be created from lower idx (higher priority) path\n return (\n // ignore (skip) ambiguities with this \"other\" alternative\n alternation.definition[searchPathAndIdx.idx].ignoreAmbiguities !==\n true &&\n searchPathAndIdx.idx < targetIdx &&\n // checking for strict prefix because identical lookaheads\n // will be be detected using a different validation.\n isStrictPrefixOfPath(searchPathAndIdx.path, targetPath)\n );\n },\n );\n\n const currPathPrefixErrors = map(\n prefixAmbiguitiesPathsAndIndices,\n (currAmbPathAndIdx): IParserAmbiguousAlternativesDefinitionError => {\n const ambgIndices = [currAmbPathAndIdx.idx + 1, targetIdx + 1];\n const occurrence = alternation.idx === 0 ? \"\" : alternation.idx;\n\n const message = errMsgProvider.buildAlternationPrefixAmbiguityError({\n topLevelRule: rule,\n alternation: alternation,\n ambiguityIndices: ambgIndices,\n prefixPath: currAmbPathAndIdx.path,\n });\n return {\n message: message,\n type: ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS,\n ruleName: rule.name,\n occurrence: occurrence,\n alternatives: ambgIndices,\n };\n },\n );\n\n return currPathPrefixErrors;\n }),\n );\n\n return errors;\n}\n\nfunction checkTerminalAndNoneTerminalsNameSpace(\n topLevels: Rule[],\n tokenTypes: TokenType[],\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserDefinitionError[] {\n const errors: IParserDefinitionError[] = [];\n\n const tokenNames = map(tokenTypes, (currToken) => currToken.name);\n\n forEach(topLevels, (currRule) => {\n const currRuleName = currRule.name;\n if (includes(tokenNames, currRuleName)) {\n const errMsg = errMsgProvider.buildNamespaceConflictError(currRule);\n\n errors.push({\n message: errMsg,\n type: ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE,\n ruleName: currRuleName,\n });\n }\n });\n\n return errors;\n}\n", "import { Rule } from \"@chevrotain/gast\";\nimport { defaults, forEach } from \"lodash-es\";\nimport { resolveGrammar as orgResolveGrammar } from \"../resolver.js\";\nimport { validateGrammar as orgValidateGrammar } from \"../checks.js\";\nimport {\n defaultGrammarResolverErrorProvider,\n defaultGrammarValidatorErrorProvider,\n} from \"../../errors_public.js\";\nimport { TokenType } from \"@chevrotain/types\";\nimport {\n IGrammarResolverErrorMessageProvider,\n IGrammarValidatorErrorMessageProvider,\n IParserDefinitionError,\n} from \"../types.js\";\n\ntype ResolveGrammarOpts = {\n rules: Rule[];\n errMsgProvider?: IGrammarResolverErrorMessageProvider;\n};\nexport function resolveGrammar(\n options: ResolveGrammarOpts,\n): IParserDefinitionError[] {\n const actualOptions: Required = defaults(options, {\n errMsgProvider: defaultGrammarResolverErrorProvider,\n });\n\n const topRulesTable: { [ruleName: string]: Rule } = {};\n forEach(options.rules, (rule) => {\n topRulesTable[rule.name] = rule;\n });\n return orgResolveGrammar(topRulesTable, actualOptions.errMsgProvider);\n}\n\nexport function validateGrammar(options: {\n rules: Rule[];\n tokenTypes: TokenType[];\n grammarName: string;\n errMsgProvider: IGrammarValidatorErrorMessageProvider;\n}): IParserDefinitionError[] {\n options = defaults(options, {\n errMsgProvider: defaultGrammarValidatorErrorProvider,\n });\n\n return orgValidateGrammar(\n options.rules,\n options.tokenTypes,\n options.errMsgProvider,\n options.grammarName,\n );\n}\n", "import { includes } from \"lodash-es\";\nimport {\n IRecognitionException,\n IRecognizerContext,\n IToken,\n} from \"@chevrotain/types\";\n\nconst MISMATCHED_TOKEN_EXCEPTION = \"MismatchedTokenException\";\nconst NO_VIABLE_ALT_EXCEPTION = \"NoViableAltException\";\nconst EARLY_EXIT_EXCEPTION = \"EarlyExitException\";\nconst NOT_ALL_INPUT_PARSED_EXCEPTION = \"NotAllInputParsedException\";\n\nconst RECOGNITION_EXCEPTION_NAMES = [\n MISMATCHED_TOKEN_EXCEPTION,\n NO_VIABLE_ALT_EXCEPTION,\n EARLY_EXIT_EXCEPTION,\n NOT_ALL_INPUT_PARSED_EXCEPTION,\n];\n\nObject.freeze(RECOGNITION_EXCEPTION_NAMES);\n\n// hacks to bypass no support for custom Errors in javascript/typescript\nexport function isRecognitionException(error: Error) {\n // can't do instanceof on hacked custom js exceptions\n return includes(RECOGNITION_EXCEPTION_NAMES, error.name);\n}\n\nabstract class RecognitionException\n extends Error\n implements IRecognitionException\n{\n context: IRecognizerContext;\n resyncedTokens: IToken[] = [];\n\n protected constructor(\n message: string,\n public token: IToken,\n ) {\n super(message);\n\n // fix prototype chain when typescript target is ES5\n Object.setPrototypeOf(this, new.target.prototype);\n\n /* istanbul ignore next - V8 workaround to remove constructor from stacktrace when typescript target is ES5 */\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\nexport class MismatchedTokenException extends RecognitionException {\n constructor(\n message: string,\n token: IToken,\n public previousToken: IToken,\n ) {\n super(message, token);\n this.name = MISMATCHED_TOKEN_EXCEPTION;\n }\n}\n\nexport class NoViableAltException extends RecognitionException {\n constructor(\n message: string,\n token: IToken,\n public previousToken: IToken,\n ) {\n super(message, token);\n this.name = NO_VIABLE_ALT_EXCEPTION;\n }\n}\n\nexport class NotAllInputParsedException extends RecognitionException {\n constructor(message: string, token: IToken) {\n super(message, token);\n this.name = NOT_ALL_INPUT_PARSED_EXCEPTION;\n }\n}\n\nexport class EarlyExitException extends RecognitionException {\n constructor(\n message: string,\n token: IToken,\n public previousToken: IToken,\n ) {\n super(message, token);\n this.name = EARLY_EXIT_EXCEPTION;\n }\n}\n", "import {\n createTokenInstance,\n EOF,\n tokenMatcher,\n} from \"../../../scan/tokens_public.js\";\nimport {\n AbstractNextTerminalAfterProductionWalker,\n IFirstAfterRepetition,\n} from \"../../grammar/interpreter.js\";\nimport {\n clone,\n dropRight,\n find,\n flatten,\n has,\n includes,\n isEmpty,\n map,\n} from \"lodash-es\";\nimport {\n IParserConfig,\n IToken,\n ITokenGrammarPath,\n TokenType,\n} from \"@chevrotain/types\";\nimport { MismatchedTokenException } from \"../../exceptions_public.js\";\nimport { IN } from \"../../constants.js\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport { DEFAULT_PARSER_CONFIG } from \"../parser.js\";\n\nexport const EOF_FOLLOW_KEY: any = {};\n\nexport interface IFollowKey {\n ruleName: string;\n idxInCallingRule: number;\n inRule: string;\n}\n\nexport const IN_RULE_RECOVERY_EXCEPTION = \"InRuleRecoveryException\";\n\nexport class InRuleRecoveryException extends Error {\n constructor(message: string) {\n super(message);\n this.name = IN_RULE_RECOVERY_EXCEPTION;\n }\n}\n\n/**\n * This trait is responsible for the error recovery and fault tolerant logic\n */\nexport class Recoverable {\n recoveryEnabled: boolean;\n firstAfterRepMap: Record;\n resyncFollows: Record;\n\n initRecoverable(config: IParserConfig) {\n this.firstAfterRepMap = {};\n this.resyncFollows = {};\n\n this.recoveryEnabled = has(config, \"recoveryEnabled\")\n ? (config.recoveryEnabled as boolean) // assumes end user provides the correct config value/type\n : DEFAULT_PARSER_CONFIG.recoveryEnabled;\n\n // performance optimization, NOOP will be inlined which\n // effectively means that this optional feature does not exist\n // when not used.\n if (this.recoveryEnabled) {\n this.attemptInRepetitionRecovery = attemptInRepetitionRecovery;\n }\n }\n\n public getTokenToInsert(tokType: TokenType): IToken {\n const tokToInsert = createTokenInstance(\n tokType,\n \"\",\n NaN,\n NaN,\n NaN,\n NaN,\n NaN,\n NaN,\n );\n tokToInsert.isInsertedInRecovery = true;\n return tokToInsert;\n }\n\n public canTokenTypeBeInsertedInRecovery(tokType: TokenType): boolean {\n return true;\n }\n\n public canTokenTypeBeDeletedInRecovery(tokType: TokenType): boolean {\n return true;\n }\n\n tryInRepetitionRecovery(\n this: MixedInParser,\n grammarRule: Function,\n grammarRuleArgs: any[],\n lookAheadFunc: () => boolean,\n expectedTokType: TokenType,\n ): void {\n // TODO: can the resyncTokenType be cached?\n const reSyncTokType = this.findReSyncTokenType();\n const savedLexerState = this.exportLexerState();\n const resyncedTokens: IToken[] = [];\n let passedResyncPoint = false;\n\n const nextTokenWithoutResync = this.LA(1);\n let currToken = this.LA(1);\n\n const generateErrorMessage = () => {\n const previousToken = this.LA(0);\n // we are preemptively re-syncing before an error has been detected, therefor we must reproduce\n // the error that would have been thrown\n const msg = this.errorMessageProvider.buildMismatchTokenMessage({\n expected: expectedTokType,\n actual: nextTokenWithoutResync,\n previous: previousToken,\n ruleName: this.getCurrRuleFullName(),\n });\n const error = new MismatchedTokenException(\n msg,\n nextTokenWithoutResync,\n this.LA(0),\n );\n // the first token here will be the original cause of the error, this is not part of the resyncedTokens property.\n error.resyncedTokens = dropRight(resyncedTokens);\n this.SAVE_ERROR(error);\n };\n\n while (!passedResyncPoint) {\n // re-synced to a point where we can safely exit the repetition/\n if (this.tokenMatcher(currToken, expectedTokType)) {\n generateErrorMessage();\n return; // must return here to avoid reverting the inputIdx\n } else if (lookAheadFunc.call(this)) {\n // we skipped enough tokens so we can resync right back into another iteration of the repetition grammar rule\n generateErrorMessage();\n // recursive invocation in other to support multiple re-syncs in the same top level repetition grammar rule\n grammarRule.apply(this, grammarRuleArgs);\n return; // must return here to avoid reverting the inputIdx\n } else if (this.tokenMatcher(currToken, reSyncTokType)) {\n passedResyncPoint = true;\n } else {\n currToken = this.SKIP_TOKEN();\n this.addToResyncTokens(currToken, resyncedTokens);\n }\n }\n\n // we were unable to find a CLOSER point to resync inside the Repetition, reset the state.\n // The parsing exception we were trying to prevent will happen in the NEXT parsing step. it may be handled by\n // \"between rules\" resync recovery later in the flow.\n this.importLexerState(savedLexerState);\n }\n\n shouldInRepetitionRecoveryBeTried(\n this: MixedInParser,\n expectTokAfterLastMatch: TokenType,\n nextTokIdx: number,\n notStuck: boolean | undefined,\n ): boolean {\n // Edge case of arriving from a MANY repetition which is stuck\n // Attempting recovery in this case could cause an infinite loop\n if (notStuck === false) {\n return false;\n }\n\n // no need to recover, next token is what we expect...\n if (this.tokenMatcher(this.LA(1), expectTokAfterLastMatch)) {\n return false;\n }\n\n // error recovery is disabled during backtracking as it can make the parser ignore a valid grammar path\n // and prefer some backtracking path that includes recovered errors.\n if (this.isBackTracking()) {\n return false;\n }\n\n // if we can perform inRule recovery (single token insertion or deletion) we always prefer that recovery algorithm\n // because if it works, it makes the least amount of changes to the input stream (greedy algorithm)\n //noinspection RedundantIfStatementJS\n if (\n this.canPerformInRuleRecovery(\n expectTokAfterLastMatch,\n this.getFollowsForInRuleRecovery(expectTokAfterLastMatch, nextTokIdx),\n )\n ) {\n return false;\n }\n\n return true;\n }\n\n // Error Recovery functionality\n getFollowsForInRuleRecovery(\n this: MixedInParser,\n tokType: TokenType,\n tokIdxInRule: number,\n ): TokenType[] {\n const grammarPath = this.getCurrentGrammarPath(tokType, tokIdxInRule);\n const follows = this.getNextPossibleTokenTypes(grammarPath);\n return follows;\n }\n\n tryInRuleRecovery(\n this: MixedInParser,\n expectedTokType: TokenType,\n follows: TokenType[],\n ): IToken {\n if (this.canRecoverWithSingleTokenInsertion(expectedTokType, follows)) {\n const tokToInsert = this.getTokenToInsert(expectedTokType);\n return tokToInsert;\n }\n\n if (this.canRecoverWithSingleTokenDeletion(expectedTokType)) {\n const nextTok = this.SKIP_TOKEN();\n this.consumeToken();\n return nextTok;\n }\n\n throw new InRuleRecoveryException(\"sad sad panda\");\n }\n\n canPerformInRuleRecovery(\n this: MixedInParser,\n expectedToken: TokenType,\n follows: TokenType[],\n ): boolean {\n return (\n this.canRecoverWithSingleTokenInsertion(expectedToken, follows) ||\n this.canRecoverWithSingleTokenDeletion(expectedToken)\n );\n }\n\n canRecoverWithSingleTokenInsertion(\n this: MixedInParser,\n expectedTokType: TokenType,\n follows: TokenType[],\n ): boolean {\n if (!this.canTokenTypeBeInsertedInRecovery(expectedTokType)) {\n return false;\n }\n\n // must know the possible following tokens to perform single token insertion\n if (isEmpty(follows)) {\n return false;\n }\n\n const mismatchedTok = this.LA(1);\n const isMisMatchedTokInFollows =\n find(follows, (possibleFollowsTokType: TokenType) => {\n return this.tokenMatcher(mismatchedTok, possibleFollowsTokType);\n }) !== undefined;\n\n return isMisMatchedTokInFollows;\n }\n\n canRecoverWithSingleTokenDeletion(\n this: MixedInParser,\n expectedTokType: TokenType,\n ): boolean {\n if (!this.canTokenTypeBeDeletedInRecovery(expectedTokType)) {\n return false;\n }\n\n const isNextTokenWhatIsExpected = this.tokenMatcher(\n this.LA(2),\n expectedTokType,\n );\n return isNextTokenWhatIsExpected;\n }\n\n isInCurrentRuleReSyncSet(\n this: MixedInParser,\n tokenTypeIdx: TokenType,\n ): boolean {\n const followKey = this.getCurrFollowKey();\n const currentRuleReSyncSet = this.getFollowSetFromFollowKey(followKey);\n return includes(currentRuleReSyncSet, tokenTypeIdx);\n }\n\n findReSyncTokenType(this: MixedInParser): TokenType {\n const allPossibleReSyncTokTypes = this.flattenFollowSet();\n // this loop will always terminate as EOF is always in the follow stack and also always (virtually) in the input\n let nextToken = this.LA(1);\n let k = 2;\n while (true) {\n const foundMatch = find(allPossibleReSyncTokTypes, (resyncTokType) => {\n const canMatch = tokenMatcher(nextToken, resyncTokType);\n return canMatch;\n });\n if (foundMatch !== undefined) {\n return foundMatch;\n }\n nextToken = this.LA(k);\n k++;\n }\n }\n\n getCurrFollowKey(this: MixedInParser): IFollowKey {\n // the length is at least one as we always add the ruleName to the stack before invoking the rule.\n if (this.RULE_STACK.length === 1) {\n return EOF_FOLLOW_KEY;\n }\n const currRuleShortName = this.getLastExplicitRuleShortName();\n const currRuleIdx = this.getLastExplicitRuleOccurrenceIndex();\n const prevRuleShortName = this.getPreviousExplicitRuleShortName();\n\n return {\n ruleName: this.shortRuleNameToFullName(currRuleShortName),\n idxInCallingRule: currRuleIdx,\n inRule: this.shortRuleNameToFullName(prevRuleShortName),\n };\n }\n\n buildFullFollowKeyStack(this: MixedInParser): IFollowKey[] {\n const explicitRuleStack = this.RULE_STACK;\n const explicitOccurrenceStack = this.RULE_OCCURRENCE_STACK;\n\n return map(explicitRuleStack, (ruleName, idx) => {\n if (idx === 0) {\n return EOF_FOLLOW_KEY;\n }\n return {\n ruleName: this.shortRuleNameToFullName(ruleName),\n idxInCallingRule: explicitOccurrenceStack[idx],\n inRule: this.shortRuleNameToFullName(explicitRuleStack[idx - 1]),\n };\n });\n }\n\n flattenFollowSet(this: MixedInParser): TokenType[] {\n const followStack = map(this.buildFullFollowKeyStack(), (currKey) => {\n return this.getFollowSetFromFollowKey(currKey);\n });\n return flatten(followStack);\n }\n\n getFollowSetFromFollowKey(\n this: MixedInParser,\n followKey: IFollowKey,\n ): TokenType[] {\n if (followKey === EOF_FOLLOW_KEY) {\n return [EOF];\n }\n\n const followName =\n followKey.ruleName + followKey.idxInCallingRule + IN + followKey.inRule;\n\n return this.resyncFollows[followName];\n }\n\n // It does not make any sense to include a virtual EOF token in the list of resynced tokens\n // as EOF does not really exist and thus does not contain any useful information (line/column numbers)\n addToResyncTokens(\n this: MixedInParser,\n token: IToken,\n resyncTokens: IToken[],\n ): IToken[] {\n if (!this.tokenMatcher(token, EOF)) {\n resyncTokens.push(token);\n }\n return resyncTokens;\n }\n\n reSyncTo(this: MixedInParser, tokType: TokenType): IToken[] {\n const resyncedTokens: IToken[] = [];\n let nextTok = this.LA(1);\n while (this.tokenMatcher(nextTok, tokType) === false) {\n nextTok = this.SKIP_TOKEN();\n this.addToResyncTokens(nextTok, resyncedTokens);\n }\n // the last token is not part of the error.\n return dropRight(resyncedTokens);\n }\n\n attemptInRepetitionRecovery(\n this: MixedInParser,\n prodFunc: Function,\n args: any[],\n lookaheadFunc: () => boolean,\n dslMethodIdx: number,\n prodOccurrence: number,\n nextToksWalker: typeof AbstractNextTerminalAfterProductionWalker,\n notStuck?: boolean,\n ): void {\n // by default this is a NO-OP\n // The actual implementation is with the function(not method) below\n }\n\n getCurrentGrammarPath(\n this: MixedInParser,\n tokType: TokenType,\n tokIdxInRule: number,\n ): ITokenGrammarPath {\n const pathRuleStack: string[] = this.getHumanReadableRuleStack();\n const pathOccurrenceStack: number[] = clone(this.RULE_OCCURRENCE_STACK);\n const grammarPath: any = {\n ruleStack: pathRuleStack,\n occurrenceStack: pathOccurrenceStack,\n lastTok: tokType,\n lastTokOccurrence: tokIdxInRule,\n };\n\n return grammarPath;\n }\n getHumanReadableRuleStack(this: MixedInParser): string[] {\n return map(this.RULE_STACK, (currShortName) =>\n this.shortRuleNameToFullName(currShortName),\n );\n }\n}\n\nexport function attemptInRepetitionRecovery(\n this: MixedInParser,\n prodFunc: Function,\n args: any[],\n lookaheadFunc: () => boolean,\n dslMethodIdx: number,\n prodOccurrence: number,\n nextToksWalker: typeof AbstractNextTerminalAfterProductionWalker,\n notStuck?: boolean,\n): void {\n const key = this.getKeyForAutomaticLookahead(dslMethodIdx, prodOccurrence);\n let firstAfterRepInfo = this.firstAfterRepMap[key];\n if (firstAfterRepInfo === undefined) {\n const currRuleName = this.getCurrRuleFullName();\n const ruleGrammar = this.getGAstProductions()[currRuleName];\n const walker: AbstractNextTerminalAfterProductionWalker =\n new nextToksWalker(ruleGrammar, prodOccurrence);\n firstAfterRepInfo = walker.startWalking();\n this.firstAfterRepMap[key] = firstAfterRepInfo;\n }\n\n let expectTokAfterLastMatch = firstAfterRepInfo.token;\n let nextTokIdx = firstAfterRepInfo.occurrence;\n const isEndOfRule = firstAfterRepInfo.isEndOfRule;\n\n // special edge case of a TOP most repetition after which the input should END.\n // this will force an attempt for inRule recovery in that scenario.\n if (\n this.RULE_STACK.length === 1 &&\n isEndOfRule &&\n expectTokAfterLastMatch === undefined\n ) {\n expectTokAfterLastMatch = EOF;\n nextTokIdx = 1;\n }\n\n // We don't have anything to re-sync to...\n // this condition was extracted from `shouldInRepetitionRecoveryBeTried` to act as a type-guard\n if (expectTokAfterLastMatch === undefined || nextTokIdx === undefined) {\n return;\n }\n\n if (\n this.shouldInRepetitionRecoveryBeTried(\n expectTokAfterLastMatch,\n nextTokIdx,\n notStuck,\n )\n ) {\n // TODO: performance optimization: instead of passing the original args here, we modify\n // the args param (or create a new one) and make sure the lookahead func is explicitly provided\n // to avoid searching the cache for it once more.\n this.tryInRepetitionRecovery(\n prodFunc,\n args,\n lookaheadFunc,\n expectTokAfterLastMatch,\n );\n }\n}\n", "// Lookahead keys are 32Bit integers in the form\n// TTTTTTTT-ZZZZZZZZZZZZ-YYYY-XXXXXXXX\n// XXXX -> Occurrence Index bitmap.\n// YYYY -> DSL Method Type bitmap.\n// ZZZZZZZZZZZZZZZ -> Rule short Index bitmap.\n// TTTTTTTTT -> alternation alternative index bitmap\n\nexport const BITS_FOR_METHOD_TYPE = 4;\nexport const BITS_FOR_OCCURRENCE_IDX = 8;\nexport const BITS_FOR_RULE_IDX = 12;\n// TODO: validation, this means that there may at most 2^8 --> 256 alternatives for an alternation.\nexport const BITS_FOR_ALT_IDX = 8;\n\n// short string used as part of mapping keys.\n// being short improves the performance when composing KEYS for maps out of these\n// The 5 - 8 bits (16 possible values, are reserved for the DSL method indices)\nexport const OR_IDX = 1 << BITS_FOR_OCCURRENCE_IDX;\nexport const OPTION_IDX = 2 << BITS_FOR_OCCURRENCE_IDX;\nexport const MANY_IDX = 3 << BITS_FOR_OCCURRENCE_IDX;\nexport const AT_LEAST_ONE_IDX = 4 << BITS_FOR_OCCURRENCE_IDX;\nexport const MANY_SEP_IDX = 5 << BITS_FOR_OCCURRENCE_IDX;\nexport const AT_LEAST_ONE_SEP_IDX = 6 << BITS_FOR_OCCURRENCE_IDX;\n\n// this actually returns a number, but it is always used as a string (object prop key)\nexport function getKeyForAutomaticLookahead(\n ruleIdx: number,\n dslMethodIdx: number,\n occurrence: number,\n): number {\n return occurrence | dslMethodIdx | ruleIdx;\n}\n\nconst BITS_START_FOR_ALT_IDX = 32 - BITS_FOR_ALT_IDX;\n", "import {\n ILookaheadStrategy,\n ILookaheadValidationError,\n IOrAlt,\n OptionalProductionType,\n Rule,\n TokenType,\n} from \"@chevrotain/types\";\nimport { flatMap, isEmpty } from \"lodash-es\";\nimport { defaultGrammarValidatorErrorProvider } from \"../errors_public.js\";\nimport { DEFAULT_PARSER_CONFIG } from \"../parser/parser.js\";\nimport {\n validateAmbiguousAlternationAlternatives,\n validateEmptyOrAlternative,\n validateNoLeftRecursion,\n validateSomeNonEmptyLookaheadPath,\n} from \"./checks.js\";\nimport {\n buildAlternativesLookAheadFunc,\n buildLookaheadFuncForOptionalProd,\n buildLookaheadFuncForOr,\n buildSingleAlternativeLookaheadFunction,\n getProdType,\n} from \"./lookahead.js\";\nimport { IParserDefinitionError } from \"./types.js\";\n\nexport class LLkLookaheadStrategy implements ILookaheadStrategy {\n readonly maxLookahead: number;\n\n constructor(options?: { maxLookahead?: number }) {\n this.maxLookahead =\n options?.maxLookahead ?? DEFAULT_PARSER_CONFIG.maxLookahead;\n }\n\n validate(options: {\n rules: Rule[];\n tokenTypes: TokenType[];\n grammarName: string;\n }): ILookaheadValidationError[] {\n const leftRecursionErrors = this.validateNoLeftRecursion(options.rules);\n\n if (isEmpty(leftRecursionErrors)) {\n const emptyAltErrors = this.validateEmptyOrAlternatives(options.rules);\n const ambiguousAltsErrors = this.validateAmbiguousAlternationAlternatives(\n options.rules,\n this.maxLookahead,\n );\n const emptyRepetitionErrors = this.validateSomeNonEmptyLookaheadPath(\n options.rules,\n this.maxLookahead,\n );\n const allErrors = [\n ...leftRecursionErrors,\n ...emptyAltErrors,\n ...ambiguousAltsErrors,\n ...emptyRepetitionErrors,\n ];\n return allErrors;\n }\n return leftRecursionErrors;\n }\n\n validateNoLeftRecursion(rules: Rule[]): IParserDefinitionError[] {\n return flatMap(rules, (currTopRule) =>\n validateNoLeftRecursion(\n currTopRule,\n currTopRule,\n defaultGrammarValidatorErrorProvider,\n ),\n );\n }\n\n validateEmptyOrAlternatives(rules: Rule[]): IParserDefinitionError[] {\n return flatMap(rules, (currTopRule) =>\n validateEmptyOrAlternative(\n currTopRule,\n defaultGrammarValidatorErrorProvider,\n ),\n );\n }\n\n validateAmbiguousAlternationAlternatives(\n rules: Rule[],\n maxLookahead: number,\n ): IParserDefinitionError[] {\n return flatMap(rules, (currTopRule) =>\n validateAmbiguousAlternationAlternatives(\n currTopRule,\n maxLookahead,\n defaultGrammarValidatorErrorProvider,\n ),\n );\n }\n\n validateSomeNonEmptyLookaheadPath(\n rules: Rule[],\n maxLookahead: number,\n ): IParserDefinitionError[] {\n return validateSomeNonEmptyLookaheadPath(\n rules,\n maxLookahead,\n defaultGrammarValidatorErrorProvider,\n );\n }\n\n buildLookaheadForAlternation(options: {\n prodOccurrence: number;\n rule: Rule;\n maxLookahead: number;\n hasPredicates: boolean;\n dynamicTokensEnabled: boolean;\n }): (orAlts?: IOrAlt[] | undefined) => number | undefined {\n return buildLookaheadFuncForOr(\n options.prodOccurrence,\n options.rule,\n options.maxLookahead,\n options.hasPredicates,\n options.dynamicTokensEnabled,\n buildAlternativesLookAheadFunc,\n );\n }\n\n buildLookaheadForOptional(options: {\n prodOccurrence: number;\n prodType: OptionalProductionType;\n rule: Rule;\n maxLookahead: number;\n dynamicTokensEnabled: boolean;\n }): () => boolean {\n return buildLookaheadFuncForOptionalProd(\n options.prodOccurrence,\n options.rule,\n options.maxLookahead,\n options.dynamicTokensEnabled,\n getProdType(options.prodType),\n buildSingleAlternativeLookaheadFunction,\n );\n }\n}\n", "import { forEach, has } from \"lodash-es\";\nimport { DEFAULT_PARSER_CONFIG } from \"../parser.js\";\nimport {\n ILookaheadStrategy,\n IParserConfig,\n OptionalProductionType,\n} from \"@chevrotain/types\";\nimport {\n AT_LEAST_ONE_IDX,\n AT_LEAST_ONE_SEP_IDX,\n getKeyForAutomaticLookahead,\n MANY_IDX,\n MANY_SEP_IDX,\n OPTION_IDX,\n OR_IDX,\n} from \"../../grammar/keys.js\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport {\n Alternation,\n GAstVisitor,\n getProductionDslName,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n Rule,\n} from \"@chevrotain/gast\";\nimport { LLkLookaheadStrategy } from \"../../grammar/llk_lookahead.js\";\n\n/**\n * Trait responsible for the lookahead related utilities and optimizations.\n */\nexport class LooksAhead {\n maxLookahead: number;\n lookAheadFuncsCache: any;\n dynamicTokensEnabled: boolean;\n lookaheadStrategy: ILookaheadStrategy;\n\n initLooksAhead(config: IParserConfig) {\n this.dynamicTokensEnabled = has(config, \"dynamicTokensEnabled\")\n ? (config.dynamicTokensEnabled as boolean) // assumes end user provides the correct config value/type\n : DEFAULT_PARSER_CONFIG.dynamicTokensEnabled;\n\n this.maxLookahead = has(config, \"maxLookahead\")\n ? (config.maxLookahead as number) // assumes end user provides the correct config value/type\n : DEFAULT_PARSER_CONFIG.maxLookahead;\n\n this.lookaheadStrategy = has(config, \"lookaheadStrategy\")\n ? (config.lookaheadStrategy as ILookaheadStrategy) // assumes end user provides the correct config value/type\n : new LLkLookaheadStrategy({ maxLookahead: this.maxLookahead });\n\n this.lookAheadFuncsCache = new Map();\n }\n\n preComputeLookaheadFunctions(this: MixedInParser, rules: Rule[]): void {\n forEach(rules, (currRule) => {\n this.TRACE_INIT(`${currRule.name} Rule Lookahead`, () => {\n const {\n alternation,\n repetition,\n option,\n repetitionMandatory,\n repetitionMandatoryWithSeparator,\n repetitionWithSeparator,\n } = collectMethods(currRule);\n\n forEach(alternation, (currProd) => {\n const prodIdx = currProd.idx === 0 ? \"\" : currProd.idx;\n this.TRACE_INIT(`${getProductionDslName(currProd)}${prodIdx}`, () => {\n const laFunc = this.lookaheadStrategy.buildLookaheadForAlternation({\n prodOccurrence: currProd.idx,\n rule: currRule,\n maxLookahead: currProd.maxLookahead || this.maxLookahead,\n hasPredicates: currProd.hasPredicates,\n dynamicTokensEnabled: this.dynamicTokensEnabled,\n });\n\n const key = getKeyForAutomaticLookahead(\n this.fullRuleNameToShort[currRule.name],\n OR_IDX,\n currProd.idx,\n );\n this.setLaFuncCache(key, laFunc);\n });\n });\n\n forEach(repetition, (currProd) => {\n this.computeLookaheadFunc(\n currRule,\n currProd.idx,\n MANY_IDX,\n \"Repetition\",\n currProd.maxLookahead,\n getProductionDslName(currProd),\n );\n });\n\n forEach(option, (currProd) => {\n this.computeLookaheadFunc(\n currRule,\n currProd.idx,\n OPTION_IDX,\n \"Option\",\n currProd.maxLookahead,\n getProductionDslName(currProd),\n );\n });\n\n forEach(repetitionMandatory, (currProd) => {\n this.computeLookaheadFunc(\n currRule,\n currProd.idx,\n AT_LEAST_ONE_IDX,\n \"RepetitionMandatory\",\n currProd.maxLookahead,\n getProductionDslName(currProd),\n );\n });\n\n forEach(repetitionMandatoryWithSeparator, (currProd) => {\n this.computeLookaheadFunc(\n currRule,\n currProd.idx,\n AT_LEAST_ONE_SEP_IDX,\n \"RepetitionMandatoryWithSeparator\",\n currProd.maxLookahead,\n getProductionDslName(currProd),\n );\n });\n\n forEach(repetitionWithSeparator, (currProd) => {\n this.computeLookaheadFunc(\n currRule,\n currProd.idx,\n MANY_SEP_IDX,\n \"RepetitionWithSeparator\",\n currProd.maxLookahead,\n getProductionDslName(currProd),\n );\n });\n });\n });\n }\n\n computeLookaheadFunc(\n this: MixedInParser,\n rule: Rule,\n prodOccurrence: number,\n prodKey: number,\n prodType: OptionalProductionType,\n prodMaxLookahead: number | undefined,\n dslMethodName: string,\n ): void {\n this.TRACE_INIT(\n `${dslMethodName}${prodOccurrence === 0 ? \"\" : prodOccurrence}`,\n () => {\n const laFunc = this.lookaheadStrategy.buildLookaheadForOptional({\n prodOccurrence,\n rule,\n maxLookahead: prodMaxLookahead || this.maxLookahead,\n dynamicTokensEnabled: this.dynamicTokensEnabled,\n prodType,\n });\n const key = getKeyForAutomaticLookahead(\n this.fullRuleNameToShort[rule.name],\n prodKey,\n prodOccurrence,\n );\n this.setLaFuncCache(key, laFunc);\n },\n );\n }\n\n // this actually returns a number, but it is always used as a string (object prop key)\n getKeyForAutomaticLookahead(\n this: MixedInParser,\n dslMethodIdx: number,\n occurrence: number,\n ): number {\n const currRuleShortName: any = this.getLastExplicitRuleShortName();\n return getKeyForAutomaticLookahead(\n currRuleShortName,\n dslMethodIdx,\n occurrence,\n );\n }\n\n getLaFuncFromCache(this: MixedInParser, key: number): Function {\n return this.lookAheadFuncsCache.get(key);\n }\n\n /* istanbul ignore next */\n setLaFuncCache(this: MixedInParser, key: number, value: Function): void {\n this.lookAheadFuncsCache.set(key, value);\n }\n}\n\nclass DslMethodsCollectorVisitor extends GAstVisitor {\n public dslMethods: {\n option: Option[];\n alternation: Alternation[];\n repetition: Repetition[];\n repetitionWithSeparator: RepetitionWithSeparator[];\n repetitionMandatory: RepetitionMandatory[];\n repetitionMandatoryWithSeparator: RepetitionMandatoryWithSeparator[];\n } = {\n option: [],\n alternation: [],\n repetition: [],\n repetitionWithSeparator: [],\n repetitionMandatory: [],\n repetitionMandatoryWithSeparator: [],\n };\n\n reset() {\n this.dslMethods = {\n option: [],\n alternation: [],\n repetition: [],\n repetitionWithSeparator: [],\n repetitionMandatory: [],\n repetitionMandatoryWithSeparator: [],\n };\n }\n\n public visitOption(option: Option): void {\n this.dslMethods.option.push(option);\n }\n\n public visitRepetitionWithSeparator(manySep: RepetitionWithSeparator): void {\n this.dslMethods.repetitionWithSeparator.push(manySep);\n }\n\n public visitRepetitionMandatory(atLeastOne: RepetitionMandatory): void {\n this.dslMethods.repetitionMandatory.push(atLeastOne);\n }\n\n public visitRepetitionMandatoryWithSeparator(\n atLeastOneSep: RepetitionMandatoryWithSeparator,\n ): void {\n this.dslMethods.repetitionMandatoryWithSeparator.push(atLeastOneSep);\n }\n\n public visitRepetition(many: Repetition): void {\n this.dslMethods.repetition.push(many);\n }\n\n public visitAlternation(or: Alternation): void {\n this.dslMethods.alternation.push(or);\n }\n}\n\nconst collectorVisitor = new DslMethodsCollectorVisitor();\nexport function collectMethods(rule: Rule): {\n option: Option[];\n alternation: Alternation[];\n repetition: Repetition[];\n repetitionWithSeparator: RepetitionWithSeparator[];\n repetitionMandatory: RepetitionMandatory[];\n repetitionMandatoryWithSeparator: RepetitionMandatoryWithSeparator[];\n} {\n collectorVisitor.reset();\n rule.accept(collectorVisitor);\n const dslMethods = collectorVisitor.dslMethods;\n // avoid uncleaned references\n collectorVisitor.reset();\n return dslMethods;\n}\n", "import { CstNode, CstNodeLocation, IToken } from \"@chevrotain/types\";\n\n/**\n * This nodeLocation tracking is not efficient and should only be used\n * when error recovery is enabled or the Token Vector contains virtual Tokens\n * (e.g, Python Indent/Outdent)\n * As it executes the calculation for every single terminal/nonTerminal\n * and does not rely on the fact the token vector is **sorted**\n */\nexport function setNodeLocationOnlyOffset(\n currNodeLocation: CstNodeLocation,\n newLocationInfo: Required>,\n): void {\n // First (valid) update for this cst node\n if (isNaN(currNodeLocation.startOffset) === true) {\n // assumption1: Token location information is either NaN or a valid number\n // assumption2: Token location information is fully valid if it exist\n // (both start/end offsets exist and are numbers).\n currNodeLocation.startOffset = newLocationInfo.startOffset;\n currNodeLocation.endOffset = newLocationInfo.endOffset;\n }\n // Once the startOffset has been updated with a valid number it should never receive\n // any farther updates as the Token vector is sorted.\n // We still have to check this this condition for every new possible location info\n // because with error recovery enabled we may encounter invalid tokens (NaN location props)\n else if (currNodeLocation.endOffset! < newLocationInfo.endOffset === true) {\n currNodeLocation.endOffset = newLocationInfo.endOffset;\n }\n}\n\n/**\n * This nodeLocation tracking is not efficient and should only be used\n * when error recovery is enabled or the Token Vector contains virtual Tokens\n * (e.g, Python Indent/Outdent)\n * As it executes the calculation for every single terminal/nonTerminal\n * and does not rely on the fact the token vector is **sorted**\n */\nexport function setNodeLocationFull(\n currNodeLocation: CstNodeLocation,\n newLocationInfo: CstNodeLocation,\n): void {\n // First (valid) update for this cst node\n if (isNaN(currNodeLocation.startOffset) === true) {\n // assumption1: Token location information is either NaN or a valid number\n // assumption2: Token location information is fully valid if it exist\n // (all start/end props exist and are numbers).\n currNodeLocation.startOffset = newLocationInfo.startOffset;\n currNodeLocation.startColumn = newLocationInfo.startColumn;\n currNodeLocation.startLine = newLocationInfo.startLine;\n currNodeLocation.endOffset = newLocationInfo.endOffset;\n currNodeLocation.endColumn = newLocationInfo.endColumn;\n currNodeLocation.endLine = newLocationInfo.endLine;\n }\n // Once the start props has been updated with a valid number it should never receive\n // any farther updates as the Token vector is sorted.\n // We still have to check this this condition for every new possible location info\n // because with error recovery enabled we may encounter invalid tokens (NaN location props)\n else if (currNodeLocation.endOffset! < newLocationInfo.endOffset! === true) {\n currNodeLocation.endOffset = newLocationInfo.endOffset;\n currNodeLocation.endColumn = newLocationInfo.endColumn;\n currNodeLocation.endLine = newLocationInfo.endLine;\n }\n}\n\nexport function addTerminalToCst(\n node: CstNode,\n token: IToken,\n tokenTypeName: string,\n): void {\n if (node.children[tokenTypeName] === undefined) {\n node.children[tokenTypeName] = [token];\n } else {\n node.children[tokenTypeName].push(token);\n }\n}\n\nexport function addNoneTerminalToCst(\n node: CstNode,\n ruleName: string,\n ruleResult: any,\n): void {\n if (node.children[ruleName] === undefined) {\n node.children[ruleName] = [ruleResult];\n } else {\n node.children[ruleName].push(ruleResult);\n }\n}\n", "const NAME = \"name\";\n\nexport function defineNameProp(obj: {}, nameValue: string): void {\n Object.defineProperty(obj, NAME, {\n enumerable: false,\n configurable: true,\n writable: false,\n value: nameValue,\n });\n}\n", "import {\n compact,\n filter,\n forEach,\n isArray,\n isEmpty,\n isFunction,\n isUndefined,\n keys,\n map,\n} from \"lodash-es\";\nimport { defineNameProp } from \"../../lang/lang_extensions.js\";\nimport { CstNode, ICstVisitor } from \"@chevrotain/types\";\n\nexport function defaultVisit(ctx: any, param: IN): void {\n const childrenNames = keys(ctx);\n const childrenNamesLength = childrenNames.length;\n for (let i = 0; i < childrenNamesLength; i++) {\n const currChildName = childrenNames[i];\n const currChildArray = ctx[currChildName];\n const currChildArrayLength = currChildArray.length;\n for (let j = 0; j < currChildArrayLength; j++) {\n const currChild: any = currChildArray[j];\n // distinction between Tokens Children and CstNode children\n if (currChild.tokenTypeIdx === undefined) {\n this[currChild.name](currChild.children, param);\n }\n }\n }\n // defaultVisit does not support generic out param\n}\n\nexport function createBaseSemanticVisitorConstructor(\n grammarName: string,\n ruleNames: string[],\n): {\n new (...args: any[]): ICstVisitor;\n} {\n const derivedConstructor: any = function () {};\n\n // can be overwritten according to:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/\n // name?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fname\n defineNameProp(derivedConstructor, grammarName + \"BaseSemantics\");\n\n const semanticProto = {\n visit: function (cstNode: CstNode | CstNode[], param: any) {\n // enables writing more concise visitor methods when CstNode has only a single child\n if (isArray(cstNode)) {\n // A CST Node's children dictionary can never have empty arrays as values\n // If a key is defined there will be at least one element in the corresponding value array.\n cstNode = cstNode[0];\n }\n\n // enables passing optional CstNodes concisely.\n if (isUndefined(cstNode)) {\n return undefined;\n }\n\n return this[cstNode.name](cstNode.children, param);\n },\n\n validateVisitor: function () {\n const semanticDefinitionErrors = validateVisitor(this, ruleNames);\n if (!isEmpty(semanticDefinitionErrors)) {\n const errorMessages = map(\n semanticDefinitionErrors,\n (currDefError) => currDefError.msg,\n );\n throw Error(\n `Errors Detected in CST Visitor <${this.constructor.name}>:\\n\\t` +\n `${errorMessages.join(\"\\n\\n\").replace(/\\n/g, \"\\n\\t\")}`,\n );\n }\n },\n };\n\n derivedConstructor.prototype = semanticProto;\n derivedConstructor.prototype.constructor = derivedConstructor;\n\n derivedConstructor._RULE_NAMES = ruleNames;\n\n return derivedConstructor;\n}\n\nexport function createBaseVisitorConstructorWithDefaults(\n grammarName: string,\n ruleNames: string[],\n baseConstructor: Function,\n): {\n new (...args: any[]): ICstVisitor;\n} {\n const derivedConstructor: any = function () {};\n\n // can be overwritten according to:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/\n // name?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fname\n defineNameProp(derivedConstructor, grammarName + \"BaseSemanticsWithDefaults\");\n\n const withDefaultsProto = Object.create(baseConstructor.prototype);\n forEach(ruleNames, (ruleName) => {\n withDefaultsProto[ruleName] = defaultVisit;\n });\n\n derivedConstructor.prototype = withDefaultsProto;\n derivedConstructor.prototype.constructor = derivedConstructor;\n\n return derivedConstructor;\n}\n\nexport enum CstVisitorDefinitionError {\n REDUNDANT_METHOD,\n MISSING_METHOD,\n}\n\nexport interface IVisitorDefinitionError {\n msg: string;\n type: CstVisitorDefinitionError;\n methodName: string;\n}\n\nexport function validateVisitor(\n visitorInstance: ICstVisitor,\n ruleNames: string[],\n): IVisitorDefinitionError[] {\n const missingErrors = validateMissingCstMethods(visitorInstance, ruleNames);\n\n return missingErrors;\n}\n\nexport function validateMissingCstMethods(\n visitorInstance: ICstVisitor,\n ruleNames: string[],\n): IVisitorDefinitionError[] {\n const missingRuleNames = filter(ruleNames, (currRuleName) => {\n return isFunction((visitorInstance as any)[currRuleName]) === false;\n });\n\n const errors: IVisitorDefinitionError[] = map(\n missingRuleNames,\n (currRuleName) => {\n return {\n msg: `Missing visitor method: <${currRuleName}> on ${(\n visitorInstance.constructor.name\n )} CST Visitor.`,\n type: CstVisitorDefinitionError.MISSING_METHOD,\n methodName: currRuleName,\n };\n },\n );\n\n return compact(errors);\n}\n", "import {\n addNoneTerminalToCst,\n addTerminalToCst,\n setNodeLocationFull,\n setNodeLocationOnlyOffset,\n} from \"../../cst/cst.js\";\nimport { has, isUndefined, keys, noop } from \"lodash-es\";\nimport {\n createBaseSemanticVisitorConstructor,\n createBaseVisitorConstructorWithDefaults,\n} from \"../../cst/cst_visitor.js\";\nimport {\n CstNode,\n CstNodeLocation,\n ICstVisitor,\n IParserConfig,\n IToken,\n nodeLocationTrackingOptions,\n} from \"@chevrotain/types\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport { DEFAULT_PARSER_CONFIG } from \"../parser.js\";\n\n/**\n * This trait is responsible for the CST building logic.\n */\nexport class TreeBuilder {\n outputCst: boolean;\n CST_STACK: CstNode[];\n baseCstVisitorConstructor: Function;\n baseCstVisitorWithDefaultsConstructor: Function;\n\n // dynamically assigned Methods\n setNodeLocationFromNode: (\n nodeLocation: CstNodeLocation,\n locationInformation: CstNodeLocation,\n ) => void;\n setNodeLocationFromToken: (\n nodeLocation: CstNodeLocation,\n locationInformation: CstNodeLocation,\n ) => void;\n cstPostRule: (this: MixedInParser, ruleCstNode: CstNode) => void;\n\n setInitialNodeLocation: (cstNode: CstNode) => void;\n nodeLocationTracking: nodeLocationTrackingOptions;\n\n initTreeBuilder(this: MixedInParser, config: IParserConfig) {\n this.CST_STACK = [];\n\n // outputCst is no longer exposed/defined in the pubic API\n this.outputCst = (config as any).outputCst;\n\n this.nodeLocationTracking = has(config, \"nodeLocationTracking\")\n ? (config.nodeLocationTracking as nodeLocationTrackingOptions) // assumes end user provides the correct config value/type\n : DEFAULT_PARSER_CONFIG.nodeLocationTracking;\n\n if (!this.outputCst) {\n this.cstInvocationStateUpdate = noop;\n this.cstFinallyStateUpdate = noop;\n this.cstPostTerminal = noop;\n this.cstPostNonTerminal = noop;\n this.cstPostRule = noop;\n } else {\n if (/full/i.test(this.nodeLocationTracking)) {\n if (this.recoveryEnabled) {\n this.setNodeLocationFromToken = setNodeLocationFull;\n this.setNodeLocationFromNode = setNodeLocationFull;\n this.cstPostRule = noop;\n this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery;\n } else {\n this.setNodeLocationFromToken = noop;\n this.setNodeLocationFromNode = noop;\n this.cstPostRule = this.cstPostRuleFull;\n this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular;\n }\n } else if (/onlyOffset/i.test(this.nodeLocationTracking)) {\n if (this.recoveryEnabled) {\n this.setNodeLocationFromToken = setNodeLocationOnlyOffset;\n this.setNodeLocationFromNode = setNodeLocationOnlyOffset;\n this.cstPostRule = noop;\n this.setInitialNodeLocation =\n this.setInitialNodeLocationOnlyOffsetRecovery;\n } else {\n this.setNodeLocationFromToken = noop;\n this.setNodeLocationFromNode = noop;\n this.cstPostRule = this.cstPostRuleOnlyOffset;\n this.setInitialNodeLocation =\n this.setInitialNodeLocationOnlyOffsetRegular;\n }\n } else if (/none/i.test(this.nodeLocationTracking)) {\n this.setNodeLocationFromToken = noop;\n this.setNodeLocationFromNode = noop;\n this.cstPostRule = noop;\n this.setInitialNodeLocation = noop;\n } else {\n throw Error(\n `Invalid config option: \"${config.nodeLocationTracking}\"`,\n );\n }\n }\n }\n\n setInitialNodeLocationOnlyOffsetRecovery(\n this: MixedInParser,\n cstNode: any,\n ): void {\n cstNode.location = {\n startOffset: NaN,\n endOffset: NaN,\n };\n }\n\n setInitialNodeLocationOnlyOffsetRegular(\n this: MixedInParser,\n cstNode: any,\n ): void {\n cstNode.location = {\n // without error recovery the starting Location of a new CstNode is guaranteed\n // To be the next Token's startOffset (for valid inputs).\n // For invalid inputs there won't be any CSTOutput so this potential\n // inaccuracy does not matter\n startOffset: this.LA(1).startOffset,\n endOffset: NaN,\n };\n }\n\n setInitialNodeLocationFullRecovery(this: MixedInParser, cstNode: any): void {\n cstNode.location = {\n startOffset: NaN,\n startLine: NaN,\n startColumn: NaN,\n endOffset: NaN,\n endLine: NaN,\n endColumn: NaN,\n };\n }\n\n /**\n * @see setInitialNodeLocationOnlyOffsetRegular for explanation why this work\n\n * @param cstNode\n */\n setInitialNodeLocationFullRegular(this: MixedInParser, cstNode: any): void {\n const nextToken = this.LA(1);\n cstNode.location = {\n startOffset: nextToken.startOffset,\n startLine: nextToken.startLine,\n startColumn: nextToken.startColumn,\n endOffset: NaN,\n endLine: NaN,\n endColumn: NaN,\n };\n }\n\n cstInvocationStateUpdate(this: MixedInParser, fullRuleName: string): void {\n const cstNode: CstNode = {\n name: fullRuleName,\n children: Object.create(null),\n };\n\n this.setInitialNodeLocation(cstNode);\n this.CST_STACK.push(cstNode);\n }\n\n cstFinallyStateUpdate(this: MixedInParser): void {\n this.CST_STACK.pop();\n }\n\n cstPostRuleFull(this: MixedInParser, ruleCstNode: CstNode): void {\n // casts to `required` are safe because `cstPostRuleFull` should only be invoked when full location is enabled\n const prevToken = this.LA(0) as Required;\n const loc = ruleCstNode.location as Required;\n\n // If this condition is true it means we consumed at least one Token\n // In this CstNode.\n if (loc.startOffset <= prevToken.startOffset === true) {\n loc.endOffset = prevToken.endOffset;\n loc.endLine = prevToken.endLine;\n loc.endColumn = prevToken.endColumn;\n }\n // \"empty\" CstNode edge case\n else {\n loc.startOffset = NaN;\n loc.startLine = NaN;\n loc.startColumn = NaN;\n }\n }\n\n cstPostRuleOnlyOffset(this: MixedInParser, ruleCstNode: CstNode): void {\n const prevToken = this.LA(0);\n // `location' is not null because `cstPostRuleOnlyOffset` will only be invoked when location tracking is enabled.\n const loc = ruleCstNode.location!;\n\n // If this condition is true it means we consumed at least one Token\n // In this CstNode.\n if (loc.startOffset <= prevToken.startOffset === true) {\n loc.endOffset = prevToken.endOffset;\n }\n // \"empty\" CstNode edge case\n else {\n loc.startOffset = NaN;\n }\n }\n\n cstPostTerminal(\n this: MixedInParser,\n key: string,\n consumedToken: IToken,\n ): void {\n const rootCst = this.CST_STACK[this.CST_STACK.length - 1];\n addTerminalToCst(rootCst, consumedToken, key);\n // This is only used when **both** error recovery and CST Output are enabled.\n this.setNodeLocationFromToken(rootCst.location!, consumedToken);\n }\n\n cstPostNonTerminal(\n this: MixedInParser,\n ruleCstResult: CstNode,\n ruleName: string,\n ): void {\n const preCstNode = this.CST_STACK[this.CST_STACK.length - 1];\n addNoneTerminalToCst(preCstNode, ruleName, ruleCstResult);\n // This is only used when **both** error recovery and CST Output are enabled.\n this.setNodeLocationFromNode(preCstNode.location!, ruleCstResult.location!);\n }\n\n getBaseCstVisitorConstructor(\n this: MixedInParser,\n ): {\n new (...args: any[]): ICstVisitor;\n } {\n if (isUndefined(this.baseCstVisitorConstructor)) {\n const newBaseCstVisitorConstructor = createBaseSemanticVisitorConstructor(\n this.className,\n keys(this.gastProductionsCache),\n );\n this.baseCstVisitorConstructor = newBaseCstVisitorConstructor;\n return newBaseCstVisitorConstructor;\n }\n\n return this.baseCstVisitorConstructor;\n }\n\n getBaseCstVisitorConstructorWithDefaults(\n this: MixedInParser,\n ): {\n new (...args: any[]): ICstVisitor;\n } {\n if (isUndefined(this.baseCstVisitorWithDefaultsConstructor)) {\n const newConstructor = createBaseVisitorConstructorWithDefaults(\n this.className,\n keys(this.gastProductionsCache),\n this.getBaseCstVisitorConstructor(),\n );\n this.baseCstVisitorWithDefaultsConstructor = newConstructor;\n return newConstructor;\n }\n\n return this.baseCstVisitorWithDefaultsConstructor;\n }\n\n getLastExplicitRuleShortName(this: MixedInParser): number {\n const ruleStack = this.RULE_STACK;\n return ruleStack[ruleStack.length - 1];\n }\n\n getPreviousExplicitRuleShortName(this: MixedInParser): number {\n const ruleStack = this.RULE_STACK;\n return ruleStack[ruleStack.length - 2];\n }\n\n getLastExplicitRuleOccurrenceIndex(this: MixedInParser): number {\n const occurrenceStack = this.RULE_OCCURRENCE_STACK;\n return occurrenceStack[occurrenceStack.length - 1];\n }\n}\n", "import { END_OF_FILE } from \"../parser.js\";\nimport { IToken } from \"@chevrotain/types\";\nimport { MixedInParser } from \"./parser_traits.js\";\n\n/**\n * Trait responsible abstracting over the interaction with Lexer output (Token vector).\n *\n * This could be generalized to support other kinds of lexers, e.g.\n * - Just in Time Lexing / Lexer-Less parsing.\n * - Streaming Lexer.\n */\nexport class LexerAdapter {\n tokVector: IToken[];\n tokVectorLength: number;\n currIdx: number;\n\n initLexerAdapter() {\n this.tokVector = [];\n this.tokVectorLength = 0;\n this.currIdx = -1;\n }\n\n set input(newInput: IToken[]) {\n // @ts-ignore - `this parameter` not supported in setters/getters\n // - https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters\n if (this.selfAnalysisDone !== true) {\n throw Error(\n `Missing invocation at the end of the Parser's constructor.`,\n );\n }\n // @ts-ignore - `this parameter` not supported in setters/getters\n // - https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters\n this.reset();\n this.tokVector = newInput;\n this.tokVectorLength = newInput.length;\n }\n\n get input(): IToken[] {\n return this.tokVector;\n }\n\n // skips a token and returns the next token\n SKIP_TOKEN(this: MixedInParser): IToken {\n if (this.currIdx <= this.tokVector.length - 2) {\n this.consumeToken();\n return this.LA(1);\n } else {\n return END_OF_FILE;\n }\n }\n\n // Lexer (accessing Token vector) related methods which can be overridden to implement lazy lexers\n // or lexers dependent on parser context.\n LA(this: MixedInParser, howMuch: number): IToken {\n const soughtIdx = this.currIdx + howMuch;\n if (soughtIdx < 0 || this.tokVectorLength <= soughtIdx) {\n return END_OF_FILE;\n } else {\n return this.tokVector[soughtIdx];\n }\n }\n\n consumeToken(this: MixedInParser) {\n this.currIdx++;\n }\n\n exportLexerState(this: MixedInParser): number {\n return this.currIdx;\n }\n\n importLexerState(this: MixedInParser, newState: number) {\n this.currIdx = newState;\n }\n\n resetLexerState(this: MixedInParser): void {\n this.currIdx = -1;\n }\n\n moveToTerminatedState(this: MixedInParser): void {\n this.currIdx = this.tokVector.length - 1;\n }\n\n getLexerPosition(this: MixedInParser): number {\n return this.exportLexerState();\n }\n}\n", "import {\n AtLeastOneSepMethodOpts,\n ConsumeMethodOpts,\n DSLMethodOpts,\n DSLMethodOptsWithErr,\n GrammarAction,\n IOrAlt,\n IRuleConfig,\n ISerializedGast,\n IToken,\n ManySepMethodOpts,\n OrMethodOpts,\n SubruleMethodOpts,\n TokenType,\n} from \"@chevrotain/types\";\nimport { includes, values } from \"lodash-es\";\nimport { isRecognitionException } from \"../../exceptions_public.js\";\nimport { DEFAULT_RULE_CONFIG, ParserDefinitionErrorType } from \"../parser.js\";\nimport { defaultGrammarValidatorErrorProvider } from \"../../errors_public.js\";\nimport { validateRuleIsOverridden } from \"../../grammar/checks.js\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport { Rule, serializeGrammar } from \"@chevrotain/gast\";\nimport { IParserDefinitionError } from \"../../grammar/types.js\";\nimport { ParserMethodInternal } from \"../types.js\";\n\n/**\n * This trait is responsible for implementing the public API\n * for defining Chevrotain parsers, i.e:\n * - CONSUME\n * - RULE\n * - OPTION\n * - ...\n */\nexport class RecognizerApi {\n ACTION(this: MixedInParser, impl: () => T): T {\n return impl.call(this);\n }\n\n consume(\n this: MixedInParser,\n idx: number,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, idx, options);\n }\n\n subrule(\n this: MixedInParser,\n idx: number,\n ruleToCall: ParserMethodInternal,\n options?: SubruleMethodOpts,\n ): R {\n return this.subruleInternal(ruleToCall, idx, options);\n }\n\n option(\n this: MixedInParser,\n idx: number,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, idx);\n }\n\n or(\n this: MixedInParser,\n idx: number,\n altsOrOpts: IOrAlt[] | OrMethodOpts,\n ): any {\n return this.orInternal(altsOrOpts, idx);\n }\n\n many(\n this: MixedInParser,\n idx: number,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): void {\n return this.manyInternal(idx, actionORMethodDef);\n }\n\n atLeastOne(\n this: MixedInParser,\n idx: number,\n actionORMethodDef: GrammarAction | DSLMethodOptsWithErr,\n ): void {\n return this.atLeastOneInternal(idx, actionORMethodDef);\n }\n\n CONSUME(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 0, options);\n }\n\n CONSUME1(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 1, options);\n }\n\n CONSUME2(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 2, options);\n }\n\n CONSUME3(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 3, options);\n }\n\n CONSUME4(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 4, options);\n }\n\n CONSUME5(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 5, options);\n }\n\n CONSUME6(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 6, options);\n }\n\n CONSUME7(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 7, options);\n }\n\n CONSUME8(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 8, options);\n }\n\n CONSUME9(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 9, options);\n }\n\n SUBRULE(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal,\n options?: SubruleMethodOpts,\n ): R {\n return this.subruleInternal(ruleToCall, 0, options);\n }\n\n SUBRULE1(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal,\n options?: SubruleMethodOpts,\n ): R {\n return this.subruleInternal(ruleToCall, 1, options);\n }\n\n SUBRULE2(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal,\n options?: SubruleMethodOpts,\n ): R {\n return this.subruleInternal(ruleToCall, 2, options);\n }\n\n SUBRULE3(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal,\n options?: SubruleMethodOpts,\n ): R {\n return this.subruleInternal(ruleToCall, 3, options);\n }\n\n SUBRULE4(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal,\n options?: SubruleMethodOpts,\n ): R {\n return this.subruleInternal(ruleToCall, 4, options);\n }\n\n SUBRULE5(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal,\n options?: SubruleMethodOpts,\n ): R {\n return this.subruleInternal(ruleToCall, 5, options);\n }\n\n SUBRULE6(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal,\n options?: SubruleMethodOpts,\n ): R {\n return this.subruleInternal(ruleToCall, 6, options);\n }\n\n SUBRULE7(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal,\n options?: SubruleMethodOpts,\n ): R {\n return this.subruleInternal(ruleToCall, 7, options);\n }\n\n SUBRULE8(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal,\n options?: SubruleMethodOpts,\n ): R {\n return this.subruleInternal(ruleToCall, 8, options);\n }\n\n SUBRULE9(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal,\n options?: SubruleMethodOpts,\n ): R {\n return this.subruleInternal(ruleToCall, 9, options);\n }\n\n OPTION(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 0);\n }\n\n OPTION1(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 1);\n }\n\n OPTION2(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 2);\n }\n\n OPTION3(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 3);\n }\n\n OPTION4(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 4);\n }\n\n OPTION5(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 5);\n }\n\n OPTION6(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 6);\n }\n\n OPTION7(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 7);\n }\n\n OPTION8(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 8);\n }\n\n OPTION9(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 9);\n }\n\n OR(\n this: MixedInParser,\n altsOrOpts: IOrAlt[] | OrMethodOpts,\n ): T {\n return this.orInternal(altsOrOpts, 0);\n }\n\n OR1(\n this: MixedInParser,\n altsOrOpts: IOrAlt[] | OrMethodOpts,\n ): T {\n return this.orInternal(altsOrOpts, 1);\n }\n\n OR2(\n this: MixedInParser,\n altsOrOpts: IOrAlt[] | OrMethodOpts,\n ): T {\n return this.orInternal(altsOrOpts, 2);\n }\n\n OR3(\n this: MixedInParser,\n altsOrOpts: IOrAlt[] | OrMethodOpts,\n ): T {\n return this.orInternal(altsOrOpts, 3);\n }\n\n OR4(\n this: MixedInParser,\n altsOrOpts: IOrAlt[] | OrMethodOpts,\n ): T {\n return this.orInternal(altsOrOpts, 4);\n }\n\n OR5(\n this: MixedInParser,\n altsOrOpts: IOrAlt[] | OrMethodOpts,\n ): T {\n return this.orInternal(altsOrOpts, 5);\n }\n\n OR6(\n this: MixedInParser,\n altsOrOpts: IOrAlt[] | OrMethodOpts,\n ): T {\n return this.orInternal(altsOrOpts, 6);\n }\n\n OR7(\n this: MixedInParser,\n altsOrOpts: IOrAlt[] | OrMethodOpts,\n ): T {\n return this.orInternal(altsOrOpts, 7);\n }\n\n OR8(\n this: MixedInParser,\n altsOrOpts: IOrAlt[] | OrMethodOpts,\n ): T {\n return this.orInternal(altsOrOpts, 8);\n }\n\n OR9(\n this: MixedInParser,\n altsOrOpts: IOrAlt[] | OrMethodOpts,\n ): T {\n return this.orInternal(altsOrOpts, 9);\n }\n\n MANY(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): void {\n this.manyInternal(0, actionORMethodDef);\n }\n\n MANY1(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): void {\n this.manyInternal(1, actionORMethodDef);\n }\n\n MANY2(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): void {\n this.manyInternal(2, actionORMethodDef);\n }\n\n MANY3(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): void {\n this.manyInternal(3, actionORMethodDef);\n }\n\n MANY4(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): void {\n this.manyInternal(4, actionORMethodDef);\n }\n\n MANY5(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): void {\n this.manyInternal(5, actionORMethodDef);\n }\n\n MANY6(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): void {\n this.manyInternal(6, actionORMethodDef);\n }\n\n MANY7(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): void {\n this.manyInternal(7, actionORMethodDef);\n }\n\n MANY8(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): void {\n this.manyInternal(8, actionORMethodDef);\n }\n\n MANY9(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): void {\n this.manyInternal(9, actionORMethodDef);\n }\n\n MANY_SEP(this: MixedInParser, options: ManySepMethodOpts): void {\n this.manySepFirstInternal(0, options);\n }\n\n MANY_SEP1(this: MixedInParser, options: ManySepMethodOpts): void {\n this.manySepFirstInternal(1, options);\n }\n\n MANY_SEP2(this: MixedInParser, options: ManySepMethodOpts): void {\n this.manySepFirstInternal(2, options);\n }\n\n MANY_SEP3(this: MixedInParser, options: ManySepMethodOpts): void {\n this.manySepFirstInternal(3, options);\n }\n\n MANY_SEP4(this: MixedInParser, options: ManySepMethodOpts): void {\n this.manySepFirstInternal(4, options);\n }\n\n MANY_SEP5(this: MixedInParser, options: ManySepMethodOpts): void {\n this.manySepFirstInternal(5, options);\n }\n\n MANY_SEP6(this: MixedInParser, options: ManySepMethodOpts): void {\n this.manySepFirstInternal(6, options);\n }\n\n MANY_SEP7(this: MixedInParser, options: ManySepMethodOpts): void {\n this.manySepFirstInternal(7, options);\n }\n\n MANY_SEP8(this: MixedInParser, options: ManySepMethodOpts): void {\n this.manySepFirstInternal(8, options);\n }\n\n MANY_SEP9(this: MixedInParser, options: ManySepMethodOpts): void {\n this.manySepFirstInternal(9, options);\n }\n\n AT_LEAST_ONE(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOptsWithErr,\n ): void {\n this.atLeastOneInternal(0, actionORMethodDef);\n }\n\n AT_LEAST_ONE1(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOptsWithErr,\n ): void {\n return this.atLeastOneInternal(1, actionORMethodDef);\n }\n\n AT_LEAST_ONE2(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOptsWithErr,\n ): void {\n this.atLeastOneInternal(2, actionORMethodDef);\n }\n\n AT_LEAST_ONE3(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOptsWithErr,\n ): void {\n this.atLeastOneInternal(3, actionORMethodDef);\n }\n\n AT_LEAST_ONE4(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOptsWithErr,\n ): void {\n this.atLeastOneInternal(4, actionORMethodDef);\n }\n\n AT_LEAST_ONE5(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOptsWithErr,\n ): void {\n this.atLeastOneInternal(5, actionORMethodDef);\n }\n\n AT_LEAST_ONE6(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOptsWithErr,\n ): void {\n this.atLeastOneInternal(6, actionORMethodDef);\n }\n\n AT_LEAST_ONE7(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOptsWithErr,\n ): void {\n this.atLeastOneInternal(7, actionORMethodDef);\n }\n\n AT_LEAST_ONE8(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOptsWithErr,\n ): void {\n this.atLeastOneInternal(8, actionORMethodDef);\n }\n\n AT_LEAST_ONE9(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOptsWithErr,\n ): void {\n this.atLeastOneInternal(9, actionORMethodDef);\n }\n\n AT_LEAST_ONE_SEP(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts,\n ): void {\n this.atLeastOneSepFirstInternal(0, options);\n }\n\n AT_LEAST_ONE_SEP1(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts,\n ): void {\n this.atLeastOneSepFirstInternal(1, options);\n }\n\n AT_LEAST_ONE_SEP2(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts,\n ): void {\n this.atLeastOneSepFirstInternal(2, options);\n }\n\n AT_LEAST_ONE_SEP3(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts,\n ): void {\n this.atLeastOneSepFirstInternal(3, options);\n }\n\n AT_LEAST_ONE_SEP4(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts,\n ): void {\n this.atLeastOneSepFirstInternal(4, options);\n }\n\n AT_LEAST_ONE_SEP5(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts,\n ): void {\n this.atLeastOneSepFirstInternal(5, options);\n }\n\n AT_LEAST_ONE_SEP6(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts,\n ): void {\n this.atLeastOneSepFirstInternal(6, options);\n }\n\n AT_LEAST_ONE_SEP7(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts,\n ): void {\n this.atLeastOneSepFirstInternal(7, options);\n }\n\n AT_LEAST_ONE_SEP8(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts,\n ): void {\n this.atLeastOneSepFirstInternal(8, options);\n }\n\n AT_LEAST_ONE_SEP9(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts,\n ): void {\n this.atLeastOneSepFirstInternal(9, options);\n }\n\n RULE(\n this: MixedInParser,\n name: string,\n implementation: (...implArgs: any[]) => T,\n config: IRuleConfig = DEFAULT_RULE_CONFIG,\n ): (idxInCallingRule?: number, ...args: any[]) => T | any {\n if (includes(this.definedRulesNames, name)) {\n const errMsg =\n defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({\n topLevelRule: name,\n grammarName: this.className,\n });\n\n const error = {\n message: errMsg,\n type: ParserDefinitionErrorType.DUPLICATE_RULE_NAME,\n ruleName: name,\n };\n this.definitionErrors.push(error);\n }\n\n this.definedRulesNames.push(name);\n\n const ruleImplementation = this.defineRule(name, implementation, config);\n (this as any)[name] = ruleImplementation;\n return ruleImplementation;\n }\n\n OVERRIDE_RULE(\n this: MixedInParser,\n name: string,\n impl: (...implArgs: any[]) => T,\n config: IRuleConfig = DEFAULT_RULE_CONFIG,\n ): (idxInCallingRule?: number, ...args: any[]) => T {\n const ruleErrors: IParserDefinitionError[] = validateRuleIsOverridden(\n name,\n this.definedRulesNames,\n this.className,\n );\n this.definitionErrors = this.definitionErrors.concat(ruleErrors);\n\n const ruleImplementation = this.defineRule(name, impl, config);\n (this as any)[name] = ruleImplementation;\n return ruleImplementation;\n }\n\n BACKTRACK(\n this: MixedInParser,\n grammarRule: (...args: any[]) => T,\n args?: any[],\n ): () => boolean {\n return function () {\n // save org state\n this.isBackTrackingStack.push(1);\n const orgState = this.saveRecogState();\n try {\n grammarRule.apply(this, args);\n // if no exception was thrown we have succeed parsing the rule.\n return true;\n } catch (e) {\n if (isRecognitionException(e)) {\n return false;\n } else {\n throw e;\n }\n } finally {\n this.reloadRecogState(orgState);\n this.isBackTrackingStack.pop();\n }\n };\n }\n\n // GAST export APIs\n public getGAstProductions(this: MixedInParser): Record {\n return this.gastProductionsCache;\n }\n\n public getSerializedGastProductions(this: MixedInParser): ISerializedGast[] {\n return serializeGrammar(values(this.gastProductionsCache));\n }\n}\n", "import {\n AtLeastOneSepMethodOpts,\n ConsumeMethodOpts,\n DSLMethodOpts,\n DSLMethodOptsWithErr,\n GrammarAction,\n IOrAlt,\n IParserConfig,\n IRuleConfig,\n IToken,\n ManySepMethodOpts,\n OrMethodOpts,\n ParserMethod,\n SubruleMethodOpts,\n TokenType,\n TokenTypeDictionary,\n TokenVocabulary,\n} from \"@chevrotain/types\";\nimport {\n clone,\n every,\n flatten,\n has,\n isArray,\n isEmpty,\n isObject,\n reduce,\n uniq,\n values,\n} from \"lodash-es\";\nimport {\n AT_LEAST_ONE_IDX,\n AT_LEAST_ONE_SEP_IDX,\n BITS_FOR_METHOD_TYPE,\n BITS_FOR_OCCURRENCE_IDX,\n MANY_IDX,\n MANY_SEP_IDX,\n OPTION_IDX,\n OR_IDX,\n} from \"../../grammar/keys.js\";\nimport {\n isRecognitionException,\n MismatchedTokenException,\n NotAllInputParsedException,\n} from \"../../exceptions_public.js\";\nimport { PROD_TYPE } from \"../../grammar/lookahead.js\";\nimport {\n AbstractNextTerminalAfterProductionWalker,\n NextTerminalAfterAtLeastOneSepWalker,\n NextTerminalAfterAtLeastOneWalker,\n NextTerminalAfterManySepWalker,\n NextTerminalAfterManyWalker,\n} from \"../../grammar/interpreter.js\";\nimport { DEFAULT_RULE_CONFIG, IParserState, TokenMatcher } from \"../parser.js\";\nimport { IN_RULE_RECOVERY_EXCEPTION } from \"./recoverable.js\";\nimport { EOF } from \"../../../scan/tokens_public.js\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport {\n augmentTokenTypes,\n isTokenType,\n tokenStructuredMatcher,\n tokenStructuredMatcherNoCategories,\n} from \"../../../scan/tokens.js\";\nimport { Rule } from \"@chevrotain/gast\";\nimport { ParserMethodInternal } from \"../types.js\";\n\n/**\n * This trait is responsible for the runtime parsing engine\n * Used by the official API (recognizer_api.ts)\n */\nexport class RecognizerEngine {\n isBackTrackingStack: boolean[];\n className: string;\n RULE_STACK: number[];\n RULE_OCCURRENCE_STACK: number[];\n definedRulesNames: string[];\n tokensMap: { [fqn: string]: TokenType };\n gastProductionsCache: Record;\n shortRuleNameToFull: Record;\n fullRuleNameToShort: Record;\n // The shortName Index must be coded \"after\" the first 8bits to enable building unique lookahead keys\n ruleShortNameIdx: number;\n tokenMatcher: TokenMatcher;\n subruleIdx: number;\n\n initRecognizerEngine(\n tokenVocabulary: TokenVocabulary,\n config: IParserConfig,\n ) {\n this.className = this.constructor.name;\n // TODO: would using an ES6 Map or plain object be faster (CST building scenario)\n this.shortRuleNameToFull = {};\n this.fullRuleNameToShort = {};\n this.ruleShortNameIdx = 256;\n this.tokenMatcher = tokenStructuredMatcherNoCategories;\n this.subruleIdx = 0;\n\n this.definedRulesNames = [];\n this.tokensMap = {};\n this.isBackTrackingStack = [];\n this.RULE_STACK = [];\n this.RULE_OCCURRENCE_STACK = [];\n this.gastProductionsCache = {};\n\n if (has(config, \"serializedGrammar\")) {\n throw Error(\n \"The Parser's configuration can no longer contain a property.\\n\" +\n \"\\tSee: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0\\n\" +\n \"\\tFor Further details.\",\n );\n }\n\n if (isArray(tokenVocabulary)) {\n // This only checks for Token vocabularies provided as arrays.\n // That is good enough because the main objective is to detect users of pre-V4.0 APIs\n // rather than all edge cases of empty Token vocabularies.\n if (isEmpty(tokenVocabulary as any[])) {\n throw Error(\n \"A Token Vocabulary cannot be empty.\\n\" +\n \"\\tNote that the first argument for the parser constructor\\n\" +\n \"\\tis no longer a Token vector (since v4.0).\",\n );\n }\n\n if (typeof (tokenVocabulary as any[])[0].startOffset === \"number\") {\n throw Error(\n \"The Parser constructor no longer accepts a token vector as the first argument.\\n\" +\n \"\\tSee: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0\\n\" +\n \"\\tFor Further details.\",\n );\n }\n }\n\n if (isArray(tokenVocabulary)) {\n this.tokensMap = reduce(\n tokenVocabulary,\n (acc, tokType: TokenType) => {\n acc[tokType.name] = tokType;\n return acc;\n },\n {} as { [tokenName: string]: TokenType },\n );\n } else if (\n has(tokenVocabulary, \"modes\") &&\n every(flatten(values((tokenVocabulary).modes)), isTokenType)\n ) {\n const allTokenTypes = flatten(values((tokenVocabulary).modes));\n const uniqueTokens = uniq(allTokenTypes);\n this.tokensMap = reduce(\n uniqueTokens,\n (acc, tokType: TokenType) => {\n acc[tokType.name] = tokType;\n return acc;\n },\n {} as { [tokenName: string]: TokenType },\n );\n } else if (isObject(tokenVocabulary)) {\n this.tokensMap = clone(tokenVocabulary as TokenTypeDictionary);\n } else {\n throw new Error(\n \" argument must be An Array of Token constructors,\" +\n \" A dictionary of Token constructors or an IMultiModeLexerDefinition\",\n );\n }\n\n // always add EOF to the tokenNames -> constructors map. it is useful to assure all the input has been\n // parsed with a clear error message (\"expecting EOF but found ...\")\n this.tokensMap[\"EOF\"] = EOF;\n\n const allTokenTypes = has(tokenVocabulary, \"modes\")\n ? flatten(values((tokenVocabulary).modes))\n : values(tokenVocabulary);\n const noTokenCategoriesUsed = every(allTokenTypes, (tokenConstructor) =>\n isEmpty(tokenConstructor.categoryMatches),\n );\n\n this.tokenMatcher = noTokenCategoriesUsed\n ? tokenStructuredMatcherNoCategories\n : tokenStructuredMatcher;\n\n // Because ES2015+ syntax should be supported for creating Token classes\n // We cannot assume that the Token classes were created using the \"extendToken\" utilities\n // Therefore we must augment the Token classes both on Lexer initialization and on Parser initialization\n augmentTokenTypes(values(this.tokensMap));\n }\n\n defineRule(\n this: MixedInParser,\n ruleName: string,\n impl: (...args: ARGS) => R,\n config: IRuleConfig,\n ): ParserMethodInternal {\n if (this.selfAnalysisDone) {\n throw Error(\n `Grammar rule <${ruleName}> may not be defined after the 'performSelfAnalysis' method has been called'\\n` +\n `Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`,\n );\n }\n const resyncEnabled: boolean = has(config, \"resyncEnabled\")\n ? (config.resyncEnabled as boolean) // assumes end user provides the correct config value/type\n : DEFAULT_RULE_CONFIG.resyncEnabled;\n const recoveryValueFunc = has(config, \"recoveryValueFunc\")\n ? (config.recoveryValueFunc as () => R) // assumes end user provides the correct config value/type\n : DEFAULT_RULE_CONFIG.recoveryValueFunc;\n\n // performance optimization: Use small integers as keys for the longer human readable \"full\" rule names.\n // this greatly improves Map access time (as much as 8% for some performance benchmarks).\n const shortName =\n this.ruleShortNameIdx << (BITS_FOR_METHOD_TYPE + BITS_FOR_OCCURRENCE_IDX);\n\n this.ruleShortNameIdx++;\n this.shortRuleNameToFull[shortName] = ruleName;\n this.fullRuleNameToShort[ruleName] = shortName;\n\n let invokeRuleWithTry: ParserMethod;\n\n // Micro optimization, only check the condition **once** on rule definition\n // instead of **every single** rule invocation.\n if (this.outputCst === true) {\n invokeRuleWithTry = function invokeRuleWithTry(\n this: MixedInParser,\n ...args: ARGS\n ): R {\n try {\n this.ruleInvocationStateUpdate(shortName, ruleName, this.subruleIdx);\n impl.apply(this, args);\n const cst = this.CST_STACK[this.CST_STACK.length - 1];\n this.cstPostRule(cst);\n return cst as unknown as R;\n } catch (e) {\n return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc) as R;\n } finally {\n this.ruleFinallyStateUpdate();\n }\n };\n } else {\n invokeRuleWithTry = function invokeRuleWithTryCst(\n this: MixedInParser,\n ...args: ARGS\n ): R {\n try {\n this.ruleInvocationStateUpdate(shortName, ruleName, this.subruleIdx);\n return impl.apply(this, args);\n } catch (e) {\n return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc) as R;\n } finally {\n this.ruleFinallyStateUpdate();\n }\n };\n }\n\n const wrappedGrammarRule: ParserMethodInternal = Object.assign(\n invokeRuleWithTry as any,\n { ruleName, originalGrammarAction: impl },\n );\n\n return wrappedGrammarRule;\n }\n\n invokeRuleCatch(\n this: MixedInParser,\n e: Error,\n resyncEnabledConfig: boolean,\n recoveryValueFunc: Function,\n ): unknown {\n const isFirstInvokedRule = this.RULE_STACK.length === 1;\n // note the reSync is always enabled for the first rule invocation, because we must always be able to\n // reSync with EOF and just output some INVALID ParseTree\n // during backtracking reSync recovery is disabled, otherwise we can't be certain the backtracking\n // path is really the most valid one\n const reSyncEnabled =\n resyncEnabledConfig && !this.isBackTracking() && this.recoveryEnabled;\n\n if (isRecognitionException(e)) {\n const recogError: any = e;\n if (reSyncEnabled) {\n const reSyncTokType = this.findReSyncTokenType();\n if (this.isInCurrentRuleReSyncSet(reSyncTokType)) {\n recogError.resyncedTokens = this.reSyncTo(reSyncTokType);\n if (this.outputCst) {\n const partialCstResult: any =\n this.CST_STACK[this.CST_STACK.length - 1];\n partialCstResult.recoveredNode = true;\n return partialCstResult;\n } else {\n return recoveryValueFunc(e);\n }\n } else {\n if (this.outputCst) {\n const partialCstResult: any =\n this.CST_STACK[this.CST_STACK.length - 1];\n partialCstResult.recoveredNode = true;\n recogError.partialCstResult = partialCstResult;\n }\n // to be handled Further up the call stack\n throw recogError;\n }\n } else if (isFirstInvokedRule) {\n // otherwise a Redundant input error will be created as well and we cannot guarantee that this is indeed the case\n this.moveToTerminatedState();\n // the parser should never throw one of its own errors outside its flow.\n // even if error recovery is disabled\n return recoveryValueFunc(e);\n } else {\n // to be recovered Further up the call stack\n throw recogError;\n }\n } else {\n // some other Error type which we don't know how to handle (for example a built in JavaScript Error)\n throw e;\n }\n }\n\n // Implementation of parsing DSL\n optionInternal(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n occurrence: number,\n ): OUT | undefined {\n const key = this.getKeyForAutomaticLookahead(OPTION_IDX, occurrence);\n return this.optionInternalLogic(actionORMethodDef, occurrence, key);\n }\n\n optionInternalLogic(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n occurrence: number,\n key: number,\n ): OUT | undefined {\n let lookAheadFunc = this.getLaFuncFromCache(key);\n let action: GrammarAction;\n if (typeof actionORMethodDef !== \"function\") {\n action = actionORMethodDef.DEF;\n const predicate = actionORMethodDef.GATE;\n // predicate present\n if (predicate !== undefined) {\n const orgLookaheadFunction = lookAheadFunc;\n lookAheadFunc = () => {\n return predicate.call(this) && orgLookaheadFunction.call(this);\n };\n }\n } else {\n action = actionORMethodDef;\n }\n\n if (lookAheadFunc.call(this) === true) {\n return action.call(this);\n }\n return undefined;\n }\n\n atLeastOneInternal(\n this: MixedInParser,\n prodOccurrence: number,\n actionORMethodDef: GrammarAction | DSLMethodOptsWithErr,\n ): void {\n const laKey = this.getKeyForAutomaticLookahead(\n AT_LEAST_ONE_IDX,\n prodOccurrence,\n );\n return this.atLeastOneInternalLogic(\n prodOccurrence,\n actionORMethodDef,\n laKey,\n );\n }\n\n atLeastOneInternalLogic(\n this: MixedInParser,\n prodOccurrence: number,\n actionORMethodDef: GrammarAction | DSLMethodOptsWithErr,\n key: number,\n ): void {\n let lookAheadFunc = this.getLaFuncFromCache(key);\n let action;\n if (typeof actionORMethodDef !== \"function\") {\n action = actionORMethodDef.DEF;\n const predicate = actionORMethodDef.GATE;\n // predicate present\n if (predicate !== undefined) {\n const orgLookaheadFunction = lookAheadFunc;\n lookAheadFunc = () => {\n return predicate.call(this) && orgLookaheadFunction.call(this);\n };\n }\n } else {\n action = actionORMethodDef;\n }\n\n if ((lookAheadFunc).call(this) === true) {\n let notStuck = this.doSingleRepetition(action);\n while (\n (lookAheadFunc).call(this) === true &&\n notStuck === true\n ) {\n notStuck = this.doSingleRepetition(action);\n }\n } else {\n throw this.raiseEarlyExitException(\n prodOccurrence,\n PROD_TYPE.REPETITION_MANDATORY,\n (>actionORMethodDef).ERR_MSG,\n );\n }\n\n // note that while it may seem that this can cause an error because by using a recursive call to\n // AT_LEAST_ONE we change the grammar to AT_LEAST_TWO, AT_LEAST_THREE ... , the possible recursive call\n // from the tryInRepetitionRecovery(...) will only happen IFF there really are TWO/THREE/.... items.\n\n // Performance optimization: \"attemptInRepetitionRecovery\" will be defined as NOOP unless recovery is enabled\n this.attemptInRepetitionRecovery(\n this.atLeastOneInternal,\n [prodOccurrence, actionORMethodDef],\n lookAheadFunc,\n AT_LEAST_ONE_IDX,\n prodOccurrence,\n NextTerminalAfterAtLeastOneWalker,\n );\n }\n\n atLeastOneSepFirstInternal(\n this: MixedInParser,\n prodOccurrence: number,\n options: AtLeastOneSepMethodOpts,\n ): void {\n const laKey = this.getKeyForAutomaticLookahead(\n AT_LEAST_ONE_SEP_IDX,\n prodOccurrence,\n );\n this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, laKey);\n }\n\n atLeastOneSepFirstInternalLogic(\n this: MixedInParser,\n prodOccurrence: number,\n options: AtLeastOneSepMethodOpts,\n key: number,\n ): void {\n const action = options.DEF;\n const separator = options.SEP;\n\n const firstIterationLookaheadFunc = this.getLaFuncFromCache(key);\n\n // 1st iteration\n if (firstIterationLookaheadFunc.call(this) === true) {\n (>action).call(this);\n\n // TODO: Optimization can move this function construction into \"attemptInRepetitionRecovery\"\n // because it is only needed in error recovery scenarios.\n const separatorLookAheadFunc = () => {\n return this.tokenMatcher(this.LA(1), separator);\n };\n\n // 2nd..nth iterations\n while (this.tokenMatcher(this.LA(1), separator) === true) {\n // note that this CONSUME will never enter recovery because\n // the separatorLookAheadFunc checks that the separator really does exist.\n this.CONSUME(separator);\n // No need for checking infinite loop here due to consuming the separator.\n (>action).call(this);\n }\n\n // Performance optimization: \"attemptInRepetitionRecovery\" will be defined as NOOP unless recovery is enabled\n this.attemptInRepetitionRecovery(\n this.repetitionSepSecondInternal,\n [\n prodOccurrence,\n separator,\n separatorLookAheadFunc,\n action,\n NextTerminalAfterAtLeastOneSepWalker,\n ],\n separatorLookAheadFunc,\n AT_LEAST_ONE_SEP_IDX,\n prodOccurrence,\n NextTerminalAfterAtLeastOneSepWalker,\n );\n } else {\n throw this.raiseEarlyExitException(\n prodOccurrence,\n PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,\n options.ERR_MSG,\n );\n }\n }\n\n manyInternal(\n this: MixedInParser,\n prodOccurrence: number,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): void {\n const laKey = this.getKeyForAutomaticLookahead(MANY_IDX, prodOccurrence);\n return this.manyInternalLogic(prodOccurrence, actionORMethodDef, laKey);\n }\n\n manyInternalLogic(\n this: MixedInParser,\n prodOccurrence: number,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n key: number,\n ) {\n let lookaheadFunction = this.getLaFuncFromCache(key);\n let action;\n if (typeof actionORMethodDef !== \"function\") {\n action = actionORMethodDef.DEF;\n const predicate = actionORMethodDef.GATE;\n // predicate present\n if (predicate !== undefined) {\n const orgLookaheadFunction = lookaheadFunction;\n lookaheadFunction = () => {\n return predicate.call(this) && orgLookaheadFunction.call(this);\n };\n }\n } else {\n action = actionORMethodDef;\n }\n\n let notStuck = true;\n while (lookaheadFunction.call(this) === true && notStuck === true) {\n notStuck = this.doSingleRepetition(action);\n }\n\n // Performance optimization: \"attemptInRepetitionRecovery\" will be defined as NOOP unless recovery is enabled\n this.attemptInRepetitionRecovery(\n this.manyInternal,\n [prodOccurrence, actionORMethodDef],\n lookaheadFunction,\n MANY_IDX,\n prodOccurrence,\n NextTerminalAfterManyWalker,\n // The notStuck parameter is only relevant when \"attemptInRepetitionRecovery\"\n // is invoked from manyInternal, in the MANY_SEP case and AT_LEAST_ONE[_SEP]\n // An infinite loop cannot occur as:\n // - Either the lookahead is guaranteed to consume something (Single Token Separator)\n // - AT_LEAST_ONE by definition is guaranteed to consume something (or error out).\n notStuck,\n );\n }\n\n manySepFirstInternal(\n this: MixedInParser,\n prodOccurrence: number,\n options: ManySepMethodOpts,\n ): void {\n const laKey = this.getKeyForAutomaticLookahead(\n MANY_SEP_IDX,\n prodOccurrence,\n );\n this.manySepFirstInternalLogic(prodOccurrence, options, laKey);\n }\n\n manySepFirstInternalLogic(\n this: MixedInParser,\n prodOccurrence: number,\n options: ManySepMethodOpts,\n key: number,\n ): void {\n const action = options.DEF;\n const separator = options.SEP;\n const firstIterationLaFunc = this.getLaFuncFromCache(key);\n\n // 1st iteration\n if (firstIterationLaFunc.call(this) === true) {\n action.call(this);\n\n const separatorLookAheadFunc = () => {\n return this.tokenMatcher(this.LA(1), separator);\n };\n // 2nd..nth iterations\n while (this.tokenMatcher(this.LA(1), separator) === true) {\n // note that this CONSUME will never enter recovery because\n // the separatorLookAheadFunc checks that the separator really does exist.\n this.CONSUME(separator);\n // No need for checking infinite loop here due to consuming the separator.\n action.call(this);\n }\n\n // Performance optimization: \"attemptInRepetitionRecovery\" will be defined as NOOP unless recovery is enabled\n this.attemptInRepetitionRecovery(\n this.repetitionSepSecondInternal,\n [\n prodOccurrence,\n separator,\n separatorLookAheadFunc,\n action,\n NextTerminalAfterManySepWalker,\n ],\n separatorLookAheadFunc,\n MANY_SEP_IDX,\n prodOccurrence,\n NextTerminalAfterManySepWalker,\n );\n }\n }\n\n repetitionSepSecondInternal(\n this: MixedInParser,\n prodOccurrence: number,\n separator: TokenType,\n separatorLookAheadFunc: () => boolean,\n action: GrammarAction,\n nextTerminalAfterWalker: typeof AbstractNextTerminalAfterProductionWalker,\n ): void {\n while (separatorLookAheadFunc()) {\n // note that this CONSUME will never enter recovery because\n // the separatorLookAheadFunc checks that the separator really does exist.\n this.CONSUME(separator);\n action.call(this);\n }\n\n // we can only arrive to this function after an error\n // has occurred (hence the name 'second') so the following\n // IF will always be entered, its possible to remove it...\n // however it is kept to avoid confusion and be consistent.\n // Performance optimization: \"attemptInRepetitionRecovery\" will be defined as NOOP unless recovery is enabled\n /* istanbul ignore else */\n this.attemptInRepetitionRecovery(\n this.repetitionSepSecondInternal,\n [\n prodOccurrence,\n separator,\n separatorLookAheadFunc,\n action,\n nextTerminalAfterWalker,\n ],\n separatorLookAheadFunc,\n AT_LEAST_ONE_SEP_IDX,\n prodOccurrence,\n nextTerminalAfterWalker,\n );\n }\n\n doSingleRepetition(this: MixedInParser, action: Function): any {\n const beforeIteration = this.getLexerPosition();\n action.call(this);\n const afterIteration = this.getLexerPosition();\n\n // This boolean will indicate if this repetition progressed\n // or if we are \"stuck\" (potential infinite loop in the repetition).\n return afterIteration > beforeIteration;\n }\n\n orInternal(\n this: MixedInParser,\n altsOrOpts: IOrAlt[] | OrMethodOpts,\n occurrence: number,\n ): T {\n const laKey = this.getKeyForAutomaticLookahead(OR_IDX, occurrence);\n const alts = isArray(altsOrOpts) ? altsOrOpts : altsOrOpts.DEF;\n\n const laFunc = this.getLaFuncFromCache(laKey);\n const altIdxToTake = laFunc.call(this, alts);\n if (altIdxToTake !== undefined) {\n const chosenAlternative: any = alts[altIdxToTake];\n return chosenAlternative.ALT.call(this);\n }\n this.raiseNoAltException(\n occurrence,\n (altsOrOpts as OrMethodOpts).ERR_MSG,\n );\n }\n\n ruleFinallyStateUpdate(this: MixedInParser): void {\n this.RULE_STACK.pop();\n this.RULE_OCCURRENCE_STACK.pop();\n\n // NOOP when cst is disabled\n this.cstFinallyStateUpdate();\n\n if (this.RULE_STACK.length === 0 && this.isAtEndOfInput() === false) {\n const firstRedundantTok = this.LA(1);\n const errMsg = this.errorMessageProvider.buildNotAllInputParsedMessage({\n firstRedundant: firstRedundantTok,\n ruleName: this.getCurrRuleFullName(),\n });\n this.SAVE_ERROR(\n new NotAllInputParsedException(errMsg, firstRedundantTok),\n );\n }\n }\n\n subruleInternal(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal,\n idx: number,\n options?: SubruleMethodOpts,\n ): R {\n let ruleResult;\n try {\n const args = options !== undefined ? options.ARGS : undefined;\n this.subruleIdx = idx;\n ruleResult = ruleToCall.apply(this, args);\n this.cstPostNonTerminal(\n ruleResult,\n options !== undefined && options.LABEL !== undefined\n ? options.LABEL\n : ruleToCall.ruleName,\n );\n return ruleResult;\n } catch (e) {\n throw this.subruleInternalError(e, options, ruleToCall.ruleName);\n }\n }\n\n subruleInternalError(\n this: MixedInParser,\n e: any,\n options: SubruleMethodOpts | undefined,\n ruleName: string,\n ): void {\n if (isRecognitionException(e) && e.partialCstResult !== undefined) {\n this.cstPostNonTerminal(\n e.partialCstResult,\n options !== undefined && options.LABEL !== undefined\n ? options.LABEL\n : ruleName,\n );\n\n delete e.partialCstResult;\n }\n throw e;\n }\n\n consumeInternal(\n this: MixedInParser,\n tokType: TokenType,\n idx: number,\n options: ConsumeMethodOpts | undefined,\n ): IToken {\n let consumedToken!: IToken;\n try {\n const nextToken = this.LA(1);\n if (this.tokenMatcher(nextToken, tokType) === true) {\n this.consumeToken();\n consumedToken = nextToken;\n } else {\n this.consumeInternalError(tokType, nextToken, options);\n }\n } catch (eFromConsumption) {\n consumedToken = this.consumeInternalRecovery(\n tokType,\n idx,\n eFromConsumption,\n );\n }\n\n this.cstPostTerminal(\n options !== undefined && options.LABEL !== undefined\n ? options.LABEL\n : tokType.name,\n consumedToken,\n );\n return consumedToken;\n }\n\n consumeInternalError(\n this: MixedInParser,\n tokType: TokenType,\n nextToken: IToken,\n options: ConsumeMethodOpts | undefined,\n ): void {\n let msg;\n const previousToken = this.LA(0);\n if (options !== undefined && options.ERR_MSG) {\n msg = options.ERR_MSG;\n } else {\n msg = this.errorMessageProvider.buildMismatchTokenMessage({\n expected: tokType,\n actual: nextToken,\n previous: previousToken,\n ruleName: this.getCurrRuleFullName(),\n });\n }\n throw this.SAVE_ERROR(\n new MismatchedTokenException(msg, nextToken, previousToken),\n );\n }\n\n consumeInternalRecovery(\n this: MixedInParser,\n tokType: TokenType,\n idx: number,\n eFromConsumption: Error,\n ): IToken {\n // no recovery allowed during backtracking, otherwise backtracking may recover invalid syntax and accept it\n // but the original syntax could have been parsed successfully without any backtracking + recovery\n if (\n this.recoveryEnabled &&\n // TODO: more robust checking of the exception type. Perhaps Typescript extending expressions?\n eFromConsumption.name === \"MismatchedTokenException\" &&\n !this.isBackTracking()\n ) {\n const follows = this.getFollowsForInRuleRecovery(tokType, idx);\n try {\n return this.tryInRuleRecovery(tokType, follows);\n } catch (eFromInRuleRecovery) {\n if (eFromInRuleRecovery.name === IN_RULE_RECOVERY_EXCEPTION) {\n // failed in RuleRecovery.\n // throw the original error in order to trigger reSync error recovery\n throw eFromConsumption;\n } else {\n throw eFromInRuleRecovery;\n }\n }\n } else {\n throw eFromConsumption;\n }\n }\n\n saveRecogState(this: MixedInParser): IParserState {\n // errors is a getter which will clone the errors array\n const savedErrors = this.errors;\n const savedRuleStack = clone(this.RULE_STACK);\n return {\n errors: savedErrors,\n lexerState: this.exportLexerState(),\n RULE_STACK: savedRuleStack,\n CST_STACK: this.CST_STACK,\n };\n }\n\n reloadRecogState(this: MixedInParser, newState: IParserState) {\n this.errors = newState.errors;\n this.importLexerState(newState.lexerState);\n this.RULE_STACK = newState.RULE_STACK;\n }\n\n ruleInvocationStateUpdate(\n this: MixedInParser,\n shortName: number,\n fullName: string,\n idxInCallingRule: number,\n ): void {\n this.RULE_OCCURRENCE_STACK.push(idxInCallingRule);\n this.RULE_STACK.push(shortName);\n // NOOP when cst is disabled\n this.cstInvocationStateUpdate(fullName);\n }\n\n isBackTracking(this: MixedInParser): boolean {\n return this.isBackTrackingStack.length !== 0;\n }\n\n getCurrRuleFullName(this: MixedInParser): string {\n const shortName = this.getLastExplicitRuleShortName();\n return this.shortRuleNameToFull[shortName];\n }\n\n shortRuleNameToFullName(this: MixedInParser, shortName: number) {\n return this.shortRuleNameToFull[shortName];\n }\n\n public isAtEndOfInput(this: MixedInParser): boolean {\n return this.tokenMatcher(this.LA(1), EOF);\n }\n\n public reset(this: MixedInParser): void {\n this.resetLexerState();\n this.subruleIdx = 0;\n this.isBackTrackingStack = [];\n this.errors = [];\n this.RULE_STACK = [];\n // TODO: extract a specific reset for TreeBuilder trait\n this.CST_STACK = [];\n this.RULE_OCCURRENCE_STACK = [];\n }\n}\n", "import {\n IParserConfig,\n IParserErrorMessageProvider,\n IRecognitionException,\n} from \"@chevrotain/types\";\nimport {\n EarlyExitException,\n isRecognitionException,\n NoViableAltException,\n} from \"../../exceptions_public.js\";\nimport { clone, has } from \"lodash-es\";\nimport {\n getLookaheadPathsForOptionalProd,\n getLookaheadPathsForOr,\n PROD_TYPE,\n} from \"../../grammar/lookahead.js\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport { DEFAULT_PARSER_CONFIG } from \"../parser.js\";\n\n/**\n * Trait responsible for runtime parsing errors.\n */\nexport class ErrorHandler {\n _errors: IRecognitionException[];\n errorMessageProvider: IParserErrorMessageProvider;\n\n initErrorHandler(config: IParserConfig) {\n this._errors = [];\n this.errorMessageProvider = has(config, \"errorMessageProvider\")\n ? (config.errorMessageProvider as IParserErrorMessageProvider) // assumes end user provides the correct config value/type\n : DEFAULT_PARSER_CONFIG.errorMessageProvider;\n }\n\n SAVE_ERROR(\n this: MixedInParser,\n error: IRecognitionException,\n ): IRecognitionException {\n if (isRecognitionException(error)) {\n error.context = {\n ruleStack: this.getHumanReadableRuleStack(),\n ruleOccurrenceStack: clone(this.RULE_OCCURRENCE_STACK),\n };\n this._errors.push(error);\n return error;\n } else {\n throw Error(\n \"Trying to save an Error which is not a RecognitionException\",\n );\n }\n }\n\n get errors(): IRecognitionException[] {\n return clone(this._errors);\n }\n\n set errors(newErrors: IRecognitionException[]) {\n this._errors = newErrors;\n }\n\n // TODO: consider caching the error message computed information\n raiseEarlyExitException(\n this: MixedInParser,\n occurrence: number,\n prodType: PROD_TYPE,\n userDefinedErrMsg: string | undefined,\n ): never {\n const ruleName = this.getCurrRuleFullName();\n const ruleGrammar = this.getGAstProductions()[ruleName];\n const lookAheadPathsPerAlternative = getLookaheadPathsForOptionalProd(\n occurrence,\n ruleGrammar,\n prodType,\n this.maxLookahead,\n );\n const insideProdPaths = lookAheadPathsPerAlternative[0];\n const actualTokens = [];\n for (let i = 1; i <= this.maxLookahead; i++) {\n actualTokens.push(this.LA(i));\n }\n const msg = this.errorMessageProvider.buildEarlyExitMessage({\n expectedIterationPaths: insideProdPaths,\n actual: actualTokens,\n previous: this.LA(0),\n customUserDescription: userDefinedErrMsg,\n ruleName: ruleName,\n });\n\n throw this.SAVE_ERROR(new EarlyExitException(msg, this.LA(1), this.LA(0)));\n }\n\n // TODO: consider caching the error message computed information\n raiseNoAltException(\n this: MixedInParser,\n occurrence: number,\n errMsgTypes: string | undefined,\n ): never {\n const ruleName = this.getCurrRuleFullName();\n const ruleGrammar = this.getGAstProductions()[ruleName];\n // TODO: getLookaheadPathsForOr can be slow for large enough maxLookahead and certain grammars, consider caching ?\n const lookAheadPathsPerAlternative = getLookaheadPathsForOr(\n occurrence,\n ruleGrammar,\n this.maxLookahead,\n );\n\n const actualTokens = [];\n for (let i = 1; i <= this.maxLookahead; i++) {\n actualTokens.push(this.LA(i));\n }\n const previousToken = this.LA(0);\n\n const errMsg = this.errorMessageProvider.buildNoViableAltMessage({\n expectedPathsPerAlt: lookAheadPathsPerAlternative,\n actual: actualTokens,\n previous: previousToken,\n customUserDescription: errMsgTypes,\n ruleName: this.getCurrRuleFullName(),\n });\n\n throw this.SAVE_ERROR(\n new NoViableAltException(errMsg, this.LA(1), previousToken),\n );\n }\n}\n", "import {\n ISyntacticContentAssistPath,\n IToken,\n ITokenGrammarPath,\n TokenType,\n} from \"@chevrotain/types\";\nimport {\n NextAfterTokenWalker,\n nextPossibleTokensAfter,\n} from \"../../grammar/interpreter.js\";\nimport { first, isUndefined } from \"lodash-es\";\nimport { MixedInParser } from \"./parser_traits.js\";\n\nexport class ContentAssist {\n initContentAssist() {}\n\n public computeContentAssist(\n this: MixedInParser,\n startRuleName: string,\n precedingInput: IToken[],\n ): ISyntacticContentAssistPath[] {\n const startRuleGast = this.gastProductionsCache[startRuleName];\n\n if (isUndefined(startRuleGast)) {\n throw Error(`Rule ->${startRuleName}<- does not exist in this grammar.`);\n }\n\n return nextPossibleTokensAfter(\n [startRuleGast],\n precedingInput,\n this.tokenMatcher,\n this.maxLookahead,\n );\n }\n\n // TODO: should this be a member method or a utility? it does not have any state or usage of 'this'...\n // TODO: should this be more explicitly part of the public API?\n public getNextPossibleTokenTypes(\n this: MixedInParser,\n grammarPath: ITokenGrammarPath,\n ): TokenType[] {\n const topRuleName = first(grammarPath.ruleStack)!;\n const gastProductions = this.getGAstProductions();\n const topProduction = gastProductions[topRuleName];\n const nextPossibleTokenTypes = new NextAfterTokenWalker(\n topProduction,\n grammarPath,\n ).startWalking();\n return nextPossibleTokenTypes;\n }\n}\n", "import {\n AtLeastOneSepMethodOpts,\n ConsumeMethodOpts,\n CstNode,\n DSLMethodOpts,\n DSLMethodOptsWithErr,\n GrammarAction,\n IOrAlt,\n IParserConfig,\n IProduction,\n IToken,\n ManySepMethodOpts,\n OrMethodOpts,\n SubruleMethodOpts,\n TokenType,\n} from \"@chevrotain/types\";\nimport {\n forEach,\n has,\n isArray,\n isFunction,\n last as peek,\n some,\n} from \"lodash-es\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport {\n Alternation,\n Alternative,\n NonTerminal,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n Rule,\n Terminal,\n} from \"@chevrotain/gast\";\nimport { Lexer } from \"../../../scan/lexer_public.js\";\nimport {\n augmentTokenTypes,\n hasShortKeyProperty,\n} from \"../../../scan/tokens.js\";\nimport {\n createToken,\n createTokenInstance,\n} from \"../../../scan/tokens_public.js\";\nimport { END_OF_FILE } from \"../parser.js\";\nimport { BITS_FOR_OCCURRENCE_IDX } from \"../../grammar/keys.js\";\nimport { ParserMethodInternal } from \"../types.js\";\n\ntype ProdWithDef = IProduction & { definition?: IProduction[] };\nconst RECORDING_NULL_OBJECT = {\n description: \"This Object indicates the Parser is during Recording Phase\",\n};\nObject.freeze(RECORDING_NULL_OBJECT);\n\nconst HANDLE_SEPARATOR = true;\nconst MAX_METHOD_IDX = Math.pow(2, BITS_FOR_OCCURRENCE_IDX) - 1;\n\nconst RFT = createToken({ name: \"RECORDING_PHASE_TOKEN\", pattern: Lexer.NA });\naugmentTokenTypes([RFT]);\nconst RECORDING_PHASE_TOKEN = createTokenInstance(\n RFT,\n \"This IToken indicates the Parser is in Recording Phase\\n\\t\" +\n \"\" +\n \"See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details\",\n // Using \"-1\" instead of NaN (as in EOF) because an actual number is less likely to\n // cause errors if the output of LA or CONSUME would be (incorrectly) used during the recording phase.\n -1,\n -1,\n -1,\n -1,\n -1,\n -1,\n);\nObject.freeze(RECORDING_PHASE_TOKEN);\n\nconst RECORDING_PHASE_CSTNODE: CstNode = {\n name:\n \"This CSTNode indicates the Parser is in Recording Phase\\n\\t\" +\n \"See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details\",\n children: {},\n};\n\n/**\n * This trait handles the creation of the GAST structure for Chevrotain Grammars\n */\nexport class GastRecorder {\n recordingProdStack: ProdWithDef[];\n RECORDING_PHASE: boolean;\n\n initGastRecorder(this: MixedInParser, config: IParserConfig): void {\n this.recordingProdStack = [];\n this.RECORDING_PHASE = false;\n }\n\n enableRecording(this: MixedInParser): void {\n this.RECORDING_PHASE = true;\n\n this.TRACE_INIT(\"Enable Recording\", () => {\n /**\n * Warning Dark Voodoo Magic upcoming!\n * We are \"replacing\" the public parsing DSL methods API\n * With **new** alternative implementations on the Parser **instance**\n *\n * So far this is the only way I've found to avoid performance regressions during parsing time.\n * - Approx 30% performance regression was measured on Chrome 75 Canary when attempting to replace the \"internal\"\n * implementations directly instead.\n */\n for (let i = 0; i < 10; i++) {\n const idx = i > 0 ? i : \"\";\n this[`CONSUME${idx}` as \"CONSUME\"] = function (arg1, arg2) {\n return this.consumeInternalRecord(arg1, i, arg2);\n };\n this[`SUBRULE${idx}` as \"SUBRULE\"] = function (arg1, arg2) {\n return this.subruleInternalRecord(arg1, i, arg2) as any;\n };\n this[`OPTION${idx}` as \"OPTION\"] = function (arg1) {\n return this.optionInternalRecord(arg1, i);\n };\n this[`OR${idx}` as \"OR\"] = function (arg1) {\n return this.orInternalRecord(arg1, i);\n };\n this[`MANY${idx}` as \"MANY\"] = function (arg1) {\n this.manyInternalRecord(i, arg1);\n };\n this[`MANY_SEP${idx}` as \"MANY_SEP\"] = function (arg1) {\n this.manySepFirstInternalRecord(i, arg1);\n };\n this[`AT_LEAST_ONE${idx}` as \"AT_LEAST_ONE\"] = function (arg1) {\n this.atLeastOneInternalRecord(i, arg1);\n };\n this[`AT_LEAST_ONE_SEP${idx}` as \"AT_LEAST_ONE_SEP\"] = function (arg1) {\n this.atLeastOneSepFirstInternalRecord(i, arg1);\n };\n }\n\n // DSL methods with the idx(suffix) as an argument\n this[`consume`] = function (idx, arg1, arg2) {\n return this.consumeInternalRecord(arg1, idx, arg2);\n };\n this[`subrule`] = function (idx, arg1, arg2) {\n return this.subruleInternalRecord(arg1, idx, arg2) as any;\n };\n this[`option`] = function (idx, arg1) {\n return this.optionInternalRecord(arg1, idx);\n };\n this[`or`] = function (idx, arg1) {\n return this.orInternalRecord(arg1, idx);\n };\n this[`many`] = function (idx, arg1) {\n this.manyInternalRecord(idx, arg1);\n };\n this[`atLeastOne`] = function (idx, arg1) {\n this.atLeastOneInternalRecord(idx, arg1);\n };\n\n this.ACTION = this.ACTION_RECORD;\n this.BACKTRACK = this.BACKTRACK_RECORD;\n this.LA = this.LA_RECORD;\n });\n }\n\n disableRecording(this: MixedInParser) {\n this.RECORDING_PHASE = false;\n // By deleting these **instance** properties, any future invocation\n // will be deferred to the original methods on the **prototype** object\n // This seems to get rid of any incorrect optimizations that V8 may\n // do during the recording phase.\n this.TRACE_INIT(\"Deleting Recording methods\", () => {\n const that: any = this;\n\n for (let i = 0; i < 10; i++) {\n const idx = i > 0 ? i : \"\";\n delete that[`CONSUME${idx}`];\n delete that[`SUBRULE${idx}`];\n delete that[`OPTION${idx}`];\n delete that[`OR${idx}`];\n delete that[`MANY${idx}`];\n delete that[`MANY_SEP${idx}`];\n delete that[`AT_LEAST_ONE${idx}`];\n delete that[`AT_LEAST_ONE_SEP${idx}`];\n }\n\n delete that[`consume`];\n delete that[`subrule`];\n delete that[`option`];\n delete that[`or`];\n delete that[`many`];\n delete that[`atLeastOne`];\n\n delete that.ACTION;\n delete that.BACKTRACK;\n delete that.LA;\n });\n }\n\n // Parser methods are called inside an ACTION?\n // Maybe try/catch/finally on ACTIONS while disabling the recorders state changes?\n // @ts-expect-error -- noop place holder\n ACTION_RECORD(this: MixedInParser, impl: () => T): T {\n // NO-OP during recording\n }\n\n // Executing backtracking logic will break our recording logic assumptions\n BACKTRACK_RECORD(\n grammarRule: (...args: any[]) => T,\n args?: any[],\n ): () => boolean {\n return () => true;\n }\n\n // LA is part of the official API and may be used for custom lookahead logic\n // by end users who may forget to wrap it in ACTION or inside a GATE\n LA_RECORD(howMuch: number): IToken {\n // We cannot use the RECORD_PHASE_TOKEN here because someone may depend\n // On LA return EOF at the end of the input so an infinite loop may occur.\n return END_OF_FILE;\n }\n\n topLevelRuleRecord(name: string, def: Function): Rule {\n try {\n const newTopLevelRule = new Rule({ definition: [], name: name });\n newTopLevelRule.name = name;\n this.recordingProdStack.push(newTopLevelRule);\n def.call(this);\n this.recordingProdStack.pop();\n return newTopLevelRule;\n } catch (originalError) {\n if (originalError.KNOWN_RECORDER_ERROR !== true) {\n try {\n originalError.message =\n originalError.message +\n '\\n\\t This error was thrown during the \"grammar recording phase\" For more info see:\\n\\t' +\n \"https://chevrotain.io/docs/guide/internals.html#grammar-recording\";\n } catch (mutabilityError) {\n // We may not be able to modify the original error object\n throw originalError;\n }\n }\n throw originalError;\n }\n }\n\n // Implementation of parsing DSL\n optionInternalRecord(\n this: MixedInParser,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n occurrence: number,\n ): OUT {\n return recordProd.call(this, Option, actionORMethodDef, occurrence);\n }\n\n atLeastOneInternalRecord(\n this: MixedInParser,\n occurrence: number,\n actionORMethodDef: GrammarAction | DSLMethodOptsWithErr,\n ): void {\n recordProd.call(this, RepetitionMandatory, actionORMethodDef, occurrence);\n }\n\n atLeastOneSepFirstInternalRecord(\n this: MixedInParser,\n occurrence: number,\n options: AtLeastOneSepMethodOpts,\n ): void {\n recordProd.call(\n this,\n RepetitionMandatoryWithSeparator,\n options,\n occurrence,\n HANDLE_SEPARATOR,\n );\n }\n\n manyInternalRecord(\n this: MixedInParser,\n occurrence: number,\n actionORMethodDef: GrammarAction | DSLMethodOpts,\n ): void {\n recordProd.call(this, Repetition, actionORMethodDef, occurrence);\n }\n\n manySepFirstInternalRecord(\n this: MixedInParser,\n occurrence: number,\n options: ManySepMethodOpts,\n ): void {\n recordProd.call(\n this,\n RepetitionWithSeparator,\n options,\n occurrence,\n HANDLE_SEPARATOR,\n );\n }\n\n orInternalRecord(\n this: MixedInParser,\n altsOrOpts: IOrAlt[] | OrMethodOpts,\n occurrence: number,\n ): T {\n return recordOrProd.call(this, altsOrOpts, occurrence);\n }\n\n subruleInternalRecord(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal,\n occurrence: number,\n options?: SubruleMethodOpts,\n ): R | CstNode {\n assertMethodIdxIsValid(occurrence);\n if (!ruleToCall || has(ruleToCall, \"ruleName\") === false) {\n const error: any = new Error(\n ` argument is invalid` +\n ` expecting a Parser method reference but got: <${JSON.stringify(\n ruleToCall,\n )}>` +\n `\\n inside top level rule: <${\n (this.recordingProdStack[0]).name\n }>`,\n );\n error.KNOWN_RECORDER_ERROR = true;\n throw error;\n }\n\n const prevProd: any = peek(this.recordingProdStack);\n const ruleName = ruleToCall.ruleName;\n const newNoneTerminal = new NonTerminal({\n idx: occurrence,\n nonTerminalName: ruleName,\n label: options?.LABEL,\n // The resolving of the `referencedRule` property will be done once all the Rule's GASTs have been created\n referencedRule: undefined,\n });\n prevProd.definition.push(newNoneTerminal);\n\n return this.outputCst\n ? RECORDING_PHASE_CSTNODE\n : RECORDING_NULL_OBJECT;\n }\n\n consumeInternalRecord(\n this: MixedInParser,\n tokType: TokenType,\n occurrence: number,\n options?: ConsumeMethodOpts,\n ): IToken {\n assertMethodIdxIsValid(occurrence);\n if (!hasShortKeyProperty(tokType)) {\n const error: any = new Error(\n ` argument is invalid` +\n ` expecting a TokenType reference but got: <${JSON.stringify(\n tokType,\n )}>` +\n `\\n inside top level rule: <${\n (this.recordingProdStack[0]).name\n }>`,\n );\n error.KNOWN_RECORDER_ERROR = true;\n throw error;\n }\n const prevProd: any = peek(this.recordingProdStack);\n const newNoneTerminal = new Terminal({\n idx: occurrence,\n terminalType: tokType,\n label: options?.LABEL,\n });\n prevProd.definition.push(newNoneTerminal);\n\n return RECORDING_PHASE_TOKEN;\n }\n}\n\nfunction recordProd(\n prodConstructor: any,\n mainProdArg: any,\n occurrence: number,\n handleSep: boolean = false,\n): any {\n assertMethodIdxIsValid(occurrence);\n const prevProd: any = peek(this.recordingProdStack);\n const grammarAction = isFunction(mainProdArg) ? mainProdArg : mainProdArg.DEF;\n\n const newProd = new prodConstructor({ definition: [], idx: occurrence });\n if (handleSep) {\n newProd.separator = mainProdArg.SEP;\n }\n if (has(mainProdArg, \"MAX_LOOKAHEAD\")) {\n newProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD;\n }\n\n this.recordingProdStack.push(newProd);\n grammarAction.call(this);\n prevProd.definition.push(newProd);\n this.recordingProdStack.pop();\n\n return RECORDING_NULL_OBJECT;\n}\n\nfunction recordOrProd(mainProdArg: any, occurrence: number): any {\n assertMethodIdxIsValid(occurrence);\n const prevProd: any = peek(this.recordingProdStack);\n // Only an array of alternatives\n const hasOptions = isArray(mainProdArg) === false;\n const alts: IOrAlt[] =\n hasOptions === false ? mainProdArg : mainProdArg.DEF;\n\n const newOrProd = new Alternation({\n definition: [],\n idx: occurrence,\n ignoreAmbiguities: hasOptions && mainProdArg.IGNORE_AMBIGUITIES === true,\n });\n if (has(mainProdArg, \"MAX_LOOKAHEAD\")) {\n newOrProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD;\n }\n\n const hasPredicates = some(alts, (currAlt: any) => isFunction(currAlt.GATE));\n newOrProd.hasPredicates = hasPredicates;\n\n prevProd.definition.push(newOrProd);\n\n forEach(alts, (currAlt) => {\n const currAltFlat = new Alternative({ definition: [] });\n newOrProd.definition.push(currAltFlat);\n if (has(currAlt, \"IGNORE_AMBIGUITIES\")) {\n currAltFlat.ignoreAmbiguities = currAlt.IGNORE_AMBIGUITIES as boolean; // assumes end user provides the correct config value/type\n }\n // **implicit** ignoreAmbiguities due to usage of gate\n else if (has(currAlt, \"GATE\")) {\n currAltFlat.ignoreAmbiguities = true;\n }\n this.recordingProdStack.push(currAltFlat);\n currAlt.ALT.call(this);\n this.recordingProdStack.pop();\n });\n return RECORDING_NULL_OBJECT;\n}\n\nfunction getIdxSuffix(idx: number): string {\n return idx === 0 ? \"\" : `${idx}`;\n}\n\nfunction assertMethodIdxIsValid(idx: number): void {\n if (idx < 0 || idx > MAX_METHOD_IDX) {\n const error: any = new Error(\n // The stack trace will contain all the needed details\n `Invalid DSL Method idx value: <${idx}>\\n\\t` +\n `Idx value must be a none negative value smaller than ${\n MAX_METHOD_IDX + 1\n }`,\n );\n error.KNOWN_RECORDER_ERROR = true;\n throw error;\n }\n}\n", "import { IParserConfig } from \"@chevrotain/types\";\nimport { has } from \"lodash-es\";\nimport { timer } from \"@chevrotain/utils\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport { DEFAULT_PARSER_CONFIG } from \"../parser.js\";\n\n/**\n * Trait responsible for runtime parsing errors.\n */\nexport class PerformanceTracer {\n traceInitPerf: boolean | number;\n traceInitMaxIdent: number;\n traceInitIndent: number;\n\n initPerformanceTracer(config: IParserConfig) {\n if (has(config, \"traceInitPerf\")) {\n const userTraceInitPerf = config.traceInitPerf;\n const traceIsNumber = typeof userTraceInitPerf === \"number\";\n this.traceInitMaxIdent = traceIsNumber\n ? userTraceInitPerf\n : Infinity;\n this.traceInitPerf = traceIsNumber\n ? userTraceInitPerf > 0\n : (userTraceInitPerf as boolean); // assumes end user provides the correct config value/type\n } else {\n this.traceInitMaxIdent = 0;\n this.traceInitPerf = DEFAULT_PARSER_CONFIG.traceInitPerf;\n }\n\n this.traceInitIndent = -1;\n }\n\n TRACE_INIT(this: MixedInParser, phaseDesc: string, phaseImpl: () => T): T {\n // No need to optimize this using NOOP pattern because\n // It is not called in a hot spot...\n if (this.traceInitPerf === true) {\n this.traceInitIndent++;\n const indent = new Array(this.traceInitIndent + 1).join(\"\\t\");\n if (this.traceInitIndent < this.traceInitMaxIdent) {\n console.log(`${indent}--> <${phaseDesc}>`);\n }\n const { time, value } = timer(phaseImpl);\n /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */\n const traceMethod = time > 10 ? console.warn : console.log;\n if (this.traceInitIndent < this.traceInitMaxIdent) {\n traceMethod(`${indent}<-- <${phaseDesc}> time: ${time}ms`);\n }\n this.traceInitIndent--;\n return value;\n } else {\n return phaseImpl();\n }\n }\n}\n", "export function applyMixins(derivedCtor: any, baseCtors: any[]) {\n baseCtors.forEach((baseCtor) => {\n const baseProto = baseCtor.prototype;\n Object.getOwnPropertyNames(baseProto).forEach((propName) => {\n if (propName === \"constructor\") {\n return;\n }\n\n const basePropDescriptor = Object.getOwnPropertyDescriptor(\n baseProto,\n propName,\n );\n // Handle Accessors\n if (\n basePropDescriptor &&\n (basePropDescriptor.get || basePropDescriptor.set)\n ) {\n Object.defineProperty(\n derivedCtor.prototype,\n propName,\n basePropDescriptor,\n );\n } else {\n derivedCtor.prototype[propName] = baseCtor.prototype[propName];\n }\n });\n });\n}\n", "import { clone, forEach, has, isEmpty, map, values } from \"lodash-es\";\nimport { toFastProperties } from \"@chevrotain/utils\";\nimport { computeAllProdsFollows } from \"../grammar/follow.js\";\nimport { createTokenInstance, EOF } from \"../../scan/tokens_public.js\";\nimport {\n defaultGrammarValidatorErrorProvider,\n defaultParserErrorProvider,\n} from \"../errors_public.js\";\nimport {\n resolveGrammar,\n validateGrammar,\n} from \"../grammar/gast/gast_resolver_public.js\";\nimport {\n CstNode,\n IParserConfig,\n IRecognitionException,\n IRuleConfig,\n IToken,\n TokenType,\n TokenVocabulary,\n} from \"@chevrotain/types\";\nimport { Recoverable } from \"./traits/recoverable.js\";\nimport { LooksAhead } from \"./traits/looksahead.js\";\nimport { TreeBuilder } from \"./traits/tree_builder.js\";\nimport { LexerAdapter } from \"./traits/lexer_adapter.js\";\nimport { RecognizerApi } from \"./traits/recognizer_api.js\";\nimport { RecognizerEngine } from \"./traits/recognizer_engine.js\";\n\nimport { ErrorHandler } from \"./traits/error_handler.js\";\nimport { MixedInParser } from \"./traits/parser_traits.js\";\nimport { ContentAssist } from \"./traits/context_assist.js\";\nimport { GastRecorder } from \"./traits/gast_recorder.js\";\nimport { PerformanceTracer } from \"./traits/perf_tracer.js\";\nimport { applyMixins } from \"./utils/apply_mixins.js\";\nimport { IParserDefinitionError } from \"../grammar/types.js\";\nimport { Rule } from \"@chevrotain/gast\";\nimport { IParserConfigInternal, ParserMethodInternal } from \"./types.js\";\nimport { validateLookahead } from \"../grammar/checks.js\";\n\nexport const END_OF_FILE = createTokenInstance(\n EOF,\n \"\",\n NaN,\n NaN,\n NaN,\n NaN,\n NaN,\n NaN,\n);\nObject.freeze(END_OF_FILE);\n\nexport type TokenMatcher = (token: IToken, tokType: TokenType) => boolean;\n\nexport const DEFAULT_PARSER_CONFIG: Required<\n Omit\n> = Object.freeze({\n recoveryEnabled: false,\n maxLookahead: 3,\n dynamicTokensEnabled: false,\n outputCst: true,\n errorMessageProvider: defaultParserErrorProvider,\n nodeLocationTracking: \"none\",\n traceInitPerf: false,\n skipValidations: false,\n});\n\nexport const DEFAULT_RULE_CONFIG: Required> = Object.freeze({\n recoveryValueFunc: () => undefined,\n resyncEnabled: true,\n});\n\nexport enum ParserDefinitionErrorType {\n INVALID_RULE_NAME = 0,\n DUPLICATE_RULE_NAME = 1,\n INVALID_RULE_OVERRIDE = 2,\n DUPLICATE_PRODUCTIONS = 3,\n UNRESOLVED_SUBRULE_REF = 4,\n LEFT_RECURSION = 5,\n NONE_LAST_EMPTY_ALT = 6,\n AMBIGUOUS_ALTS = 7,\n CONFLICT_TOKENS_RULES_NAMESPACE = 8,\n INVALID_TOKEN_NAME = 9,\n NO_NON_EMPTY_LOOKAHEAD = 10,\n AMBIGUOUS_PREFIX_ALTS = 11,\n TOO_MANY_ALTS = 12,\n CUSTOM_LOOKAHEAD_VALIDATION = 13,\n}\n\nexport interface IParserDuplicatesDefinitionError\n extends IParserDefinitionError {\n dslName: string;\n occurrence: number;\n parameter?: string;\n}\n\nexport interface IParserEmptyAlternativeDefinitionError\n extends IParserDefinitionError {\n occurrence: number;\n alternative: number;\n}\n\nexport interface IParserAmbiguousAlternativesDefinitionError\n extends IParserDefinitionError {\n occurrence: number | string;\n alternatives: number[];\n}\n\nexport interface IParserUnresolvedRefDefinitionError\n extends IParserDefinitionError {\n unresolvedRefName: string;\n}\n\nexport interface IParserState {\n errors: IRecognitionException[];\n lexerState: any;\n RULE_STACK: number[];\n CST_STACK: CstNode[];\n}\n\nexport type Predicate = () => boolean;\n\nexport function EMPTY_ALT(): () => undefined;\nexport function EMPTY_ALT(value: T): () => T;\nexport function EMPTY_ALT(value: any = undefined) {\n return function () {\n return value;\n };\n}\n\nexport class Parser {\n // Set this flag to true if you don't want the Parser to throw error when problems in it's definition are detected.\n // (normally during the parser's constructor).\n // This is a design time flag, it will not affect the runtime error handling of the parser, just design time errors,\n // for example: duplicate rule names, referencing an unresolved subrule, ect...\n // This flag should not be enabled during normal usage, it is used in special situations, for example when\n // needing to display the parser definition errors in some GUI(online playground).\n static DEFER_DEFINITION_ERRORS_HANDLING: boolean = false;\n\n /**\n * @deprecated use the **instance** method with the same name instead\n */\n static performSelfAnalysis(parserInstance: Parser): void {\n throw Error(\n \"The **static** `performSelfAnalysis` method has been deprecated.\" +\n \"\\t\\nUse the **instance** method with the same name instead.\",\n );\n }\n\n public performSelfAnalysis(this: MixedInParser): void {\n this.TRACE_INIT(\"performSelfAnalysis\", () => {\n let defErrorsMsgs;\n\n this.selfAnalysisDone = true;\n const className = this.className;\n\n this.TRACE_INIT(\"toFastProps\", () => {\n // Without this voodoo magic the parser would be x3-x4 slower\n // It seems it is better to invoke `toFastProperties` **before**\n // Any manipulations of the `this` object done during the recording phase.\n toFastProperties(this);\n });\n\n this.TRACE_INIT(\"Grammar Recording\", () => {\n try {\n this.enableRecording();\n // Building the GAST\n forEach(this.definedRulesNames, (currRuleName) => {\n const wrappedRule = (this as any)[\n currRuleName\n ] as ParserMethodInternal;\n const originalGrammarAction = wrappedRule[\"originalGrammarAction\"];\n let recordedRuleGast!: Rule;\n this.TRACE_INIT(`${currRuleName} Rule`, () => {\n recordedRuleGast = this.topLevelRuleRecord(\n currRuleName,\n originalGrammarAction,\n );\n });\n this.gastProductionsCache[currRuleName] = recordedRuleGast;\n });\n } finally {\n this.disableRecording();\n }\n });\n\n let resolverErrors: IParserDefinitionError[] = [];\n this.TRACE_INIT(\"Grammar Resolving\", () => {\n resolverErrors = resolveGrammar({\n rules: values(this.gastProductionsCache),\n });\n this.definitionErrors = this.definitionErrors.concat(resolverErrors);\n });\n\n this.TRACE_INIT(\"Grammar Validations\", () => {\n // only perform additional grammar validations IFF no resolving errors have occurred.\n // as unresolved grammar may lead to unhandled runtime exceptions in the follow up validations.\n if (isEmpty(resolverErrors) && this.skipValidations === false) {\n const validationErrors = validateGrammar({\n rules: values(this.gastProductionsCache),\n tokenTypes: values(this.tokensMap),\n errMsgProvider: defaultGrammarValidatorErrorProvider,\n grammarName: className,\n });\n const lookaheadValidationErrors = validateLookahead({\n lookaheadStrategy: this.lookaheadStrategy,\n rules: values(this.gastProductionsCache),\n tokenTypes: values(this.tokensMap),\n grammarName: className,\n });\n this.definitionErrors = this.definitionErrors.concat(\n validationErrors,\n lookaheadValidationErrors,\n );\n }\n });\n\n // this analysis may fail if the grammar is not perfectly valid\n if (isEmpty(this.definitionErrors)) {\n // The results of these computations are not needed unless error recovery is enabled.\n if (this.recoveryEnabled) {\n this.TRACE_INIT(\"computeAllProdsFollows\", () => {\n const allFollows = computeAllProdsFollows(\n values(this.gastProductionsCache),\n );\n this.resyncFollows = allFollows;\n });\n }\n\n this.TRACE_INIT(\"ComputeLookaheadFunctions\", () => {\n this.lookaheadStrategy.initialize?.({\n rules: values(this.gastProductionsCache),\n });\n this.preComputeLookaheadFunctions(values(this.gastProductionsCache));\n });\n }\n\n if (\n !Parser.DEFER_DEFINITION_ERRORS_HANDLING &&\n !isEmpty(this.definitionErrors)\n ) {\n defErrorsMsgs = map(\n this.definitionErrors,\n (defError) => defError.message,\n );\n throw new Error(\n `Parser Definition Errors detected:\\n ${defErrorsMsgs.join(\n \"\\n-------------------------------\\n\",\n )}`,\n );\n }\n });\n }\n\n definitionErrors: IParserDefinitionError[] = [];\n selfAnalysisDone = false;\n protected skipValidations: boolean;\n\n constructor(tokenVocabulary: TokenVocabulary, config: IParserConfig) {\n const that: MixedInParser = this as any;\n that.initErrorHandler(config);\n that.initLexerAdapter();\n that.initLooksAhead(config);\n that.initRecognizerEngine(tokenVocabulary, config);\n that.initRecoverable(config);\n that.initTreeBuilder(config);\n that.initContentAssist();\n that.initGastRecorder(config);\n that.initPerformanceTracer(config);\n\n if (has(config, \"ignoredIssues\")) {\n throw new Error(\n \"The IParserConfig property has been deprecated.\\n\\t\" +\n \"Please use the flag on the relevant DSL method instead.\\n\\t\" +\n \"See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES\\n\\t\" +\n \"For further details.\",\n );\n }\n\n this.skipValidations = has(config, \"skipValidations\")\n ? (config.skipValidations as boolean) // casting assumes the end user passing the correct type\n : DEFAULT_PARSER_CONFIG.skipValidations;\n }\n}\n\napplyMixins(Parser, [\n Recoverable,\n LooksAhead,\n TreeBuilder,\n LexerAdapter,\n RecognizerEngine,\n RecognizerApi,\n ErrorHandler,\n ContentAssist,\n GastRecorder,\n PerformanceTracer,\n]);\n\nexport class CstParser extends Parser {\n constructor(\n tokenVocabulary: TokenVocabulary,\n config: IParserConfigInternal = DEFAULT_PARSER_CONFIG,\n ) {\n const configClone = clone(config);\n configClone.outputCst = true;\n super(tokenVocabulary, configClone);\n }\n}\n\nexport class EmbeddedActionsParser extends Parser {\n constructor(\n tokenVocabulary: TokenVocabulary,\n config: IParserConfigInternal = DEFAULT_PARSER_CONFIG,\n ) {\n const configClone = clone(config);\n configClone.outputCst = false;\n super(tokenVocabulary, configClone);\n }\n}\n", "/******************************************************************************\r\n * Copyright 2022 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport map from \"lodash-es/map.js\"\r\nimport filter from \"lodash-es/filter.js\"\r\nimport {\r\n IProduction,\r\n IProductionWithOccurrence,\r\n TokenType,\r\n Alternation,\r\n NonTerminal,\r\n Rule,\r\n Option,\r\n RepetitionMandatory,\r\n Repetition,\r\n Terminal,\r\n Alternative,\r\n RepetitionWithSeparator,\r\n RepetitionMandatoryWithSeparator,\r\n LookaheadProductionType\r\n} from \"chevrotain\"\r\n\r\nexport function buildATNKey(rule: Rule, type: LookaheadProductionType, occurrence: number): string {\r\n return `${rule.name}_${type}_${occurrence}`;\r\n}\r\n\r\nexport interface ATN {\r\n decisionMap: Record\r\n states: ATNState[]\r\n decisionStates: DecisionState[]\r\n ruleToStartState: Map\r\n ruleToStopState: Map\r\n}\r\n\r\nexport const ATN_INVALID_TYPE = 0\r\nexport const ATN_BASIC = 1\r\nexport const ATN_RULE_START = 2\r\nexport const ATN_PLUS_BLOCK_START = 4\r\nexport const ATN_STAR_BLOCK_START = 5\r\n// Currently unused as the ATN is not used for lexing\r\nexport const ATN_TOKEN_START = 6\r\nexport const ATN_RULE_STOP = 7\r\nexport const ATN_BLOCK_END = 8\r\nexport const ATN_STAR_LOOP_BACK = 9\r\nexport const ATN_STAR_LOOP_ENTRY = 10\r\nexport const ATN_PLUS_LOOP_BACK = 11\r\nexport const ATN_LOOP_END = 12\r\n\r\nexport type ATNState =\r\n | BasicState\r\n | BasicBlockStartState\r\n | PlusBlockStartState\r\n | PlusLoopbackState\r\n | StarBlockStartState\r\n | StarLoopbackState\r\n | StarLoopEntryState\r\n | BlockEndState\r\n | RuleStartState\r\n | RuleStopState\r\n | LoopEndState\r\n\r\nexport interface ATNBaseState {\r\n atn: ATN\r\n production: IProductionWithOccurrence\r\n stateNumber: number\r\n rule: Rule\r\n epsilonOnlyTransitions: boolean\r\n transitions: Transition[]\r\n nextTokenWithinRule: number[]\r\n}\r\n\r\nexport interface BasicState extends ATNBaseState {\r\n type: typeof ATN_BASIC\r\n}\r\n\r\nexport interface BlockStartState extends DecisionState {\r\n end: BlockEndState\r\n}\r\n\r\nexport interface BasicBlockStartState extends BlockStartState {\r\n type: typeof ATN_BASIC\r\n}\r\n\r\nexport interface PlusBlockStartState extends BlockStartState {\r\n loopback: PlusLoopbackState\r\n type: typeof ATN_PLUS_BLOCK_START\r\n}\r\n\r\nexport interface PlusLoopbackState extends DecisionState {\r\n type: typeof ATN_PLUS_LOOP_BACK\r\n}\r\n\r\nexport interface StarBlockStartState extends BlockStartState {\r\n type: typeof ATN_STAR_BLOCK_START\r\n}\r\n\r\nexport interface StarLoopbackState extends ATNBaseState {\r\n type: typeof ATN_STAR_LOOP_BACK\r\n}\r\n\r\nexport interface StarLoopEntryState extends DecisionState {\r\n loopback: StarLoopbackState\r\n type: typeof ATN_STAR_LOOP_ENTRY\r\n}\r\n\r\nexport interface BlockEndState extends ATNBaseState {\r\n start: BlockStartState\r\n type: typeof ATN_BLOCK_END\r\n}\r\n\r\nexport interface DecisionState extends ATNBaseState {\r\n decision: number\r\n}\r\n\r\nexport interface LoopEndState extends ATNBaseState {\r\n loopback: ATNState\r\n type: typeof ATN_LOOP_END\r\n}\r\n\r\nexport interface RuleStartState extends ATNBaseState {\r\n stop: RuleStopState\r\n type: typeof ATN_RULE_START\r\n}\r\n\r\nexport interface RuleStopState extends ATNBaseState {\r\n type: typeof ATN_RULE_STOP\r\n}\r\n\r\nexport interface Transition {\r\n target: ATNState\r\n isEpsilon(): boolean\r\n}\r\n\r\nexport abstract class AbstractTransition implements Transition {\r\n target: ATNState\r\n\r\n constructor(target: ATNState) {\r\n this.target = target\r\n }\r\n\r\n isEpsilon() {\r\n return false\r\n }\r\n}\r\n\r\nexport class AtomTransition extends AbstractTransition {\r\n tokenType: TokenType\r\n\r\n constructor(target: ATNState, tokenType: TokenType) {\r\n super(target)\r\n this.tokenType = tokenType\r\n }\r\n}\r\n\r\nexport class EpsilonTransition extends AbstractTransition {\r\n constructor(target: ATNState) {\r\n super(target)\r\n }\r\n\r\n isEpsilon() {\r\n return true\r\n }\r\n}\r\n\r\nexport class RuleTransition extends AbstractTransition {\r\n rule: Rule\r\n followState: ATNState\r\n\r\n constructor(ruleStart: RuleStartState, rule: Rule, followState: ATNState) {\r\n super(ruleStart)\r\n this.rule = rule\r\n this.followState = followState\r\n }\r\n\r\n isEpsilon() {\r\n return true\r\n }\r\n}\r\n\r\ninterface ATNHandle {\r\n left: ATNState\r\n right: ATNState\r\n}\r\n\r\nexport function createATN(rules: Rule[]): ATN {\r\n const atn: ATN = {\r\n decisionMap: {},\r\n decisionStates: [],\r\n ruleToStartState: new Map(),\r\n ruleToStopState: new Map(),\r\n states: []\r\n }\r\n createRuleStartAndStopATNStates(atn, rules)\r\n const ruleLength = rules.length\r\n for (let i = 0; i < ruleLength; i++) {\r\n const rule = rules[i]\r\n const ruleBlock = block(atn, rule, rule)\r\n if (ruleBlock === undefined) {\r\n continue\r\n }\r\n buildRuleHandle(atn, rule, ruleBlock)\r\n }\r\n return atn\r\n}\r\n\r\nfunction createRuleStartAndStopATNStates(atn: ATN, rules: Rule[]): void {\r\n const ruleLength = rules.length\r\n for (let i = 0; i < ruleLength; i++) {\r\n const rule = rules[i]\r\n const start = newState(atn, rule, undefined, {\r\n type: ATN_RULE_START\r\n })\r\n const stop = newState(atn, rule, undefined, {\r\n type: ATN_RULE_STOP\r\n })\r\n start.stop = stop\r\n atn.ruleToStartState.set(rule, start)\r\n atn.ruleToStopState.set(rule, stop)\r\n }\r\n}\r\n\r\nfunction atom(\r\n atn: ATN,\r\n rule: Rule,\r\n production: IProduction\r\n): ATNHandle | undefined {\r\n if (production instanceof Terminal) {\r\n return tokenRef(atn, rule, production.terminalType, production)\r\n } else if (production instanceof NonTerminal) {\r\n return ruleRef(atn, rule, production)\r\n } else if (production instanceof Alternation) {\r\n return alternation(atn, rule, production)\r\n } else if (production instanceof Option) {\r\n return option(atn, rule, production)\r\n } else if (production instanceof Repetition) {\r\n return repetition(atn, rule, production)\r\n } else if (production instanceof RepetitionWithSeparator) {\r\n return repetitionSep(atn, rule, production)\r\n } else if (production instanceof RepetitionMandatory) {\r\n return repetitionMandatory(atn, rule, production)\r\n } else if (production instanceof RepetitionMandatoryWithSeparator) {\r\n return repetitionMandatorySep(atn, rule, production)\r\n } else {\r\n return block(atn, rule, production as Alternative)\r\n }\r\n}\r\n\r\nfunction repetition(atn: ATN, rule: Rule, repetition: Repetition): ATNHandle {\r\n const starState = newState(atn, rule, repetition, {\r\n type: ATN_STAR_BLOCK_START\r\n })\r\n defineDecisionState(atn, starState)\r\n const handle = makeAlts(\r\n atn,\r\n rule,\r\n starState,\r\n repetition,\r\n block(atn, rule, repetition)\r\n )\r\n return star(atn, rule, repetition, handle)\r\n}\r\n\r\nfunction repetitionSep(\r\n atn: ATN,\r\n rule: Rule,\r\n repetition: RepetitionWithSeparator\r\n): ATNHandle {\r\n const starState = newState(atn, rule, repetition, {\r\n type: ATN_STAR_BLOCK_START\r\n })\r\n defineDecisionState(atn, starState)\r\n const handle = makeAlts(\r\n atn,\r\n rule,\r\n starState,\r\n repetition,\r\n block(atn, rule, repetition)\r\n )\r\n const sep = tokenRef(atn, rule, repetition.separator, repetition)\r\n return star(atn, rule, repetition, handle, sep)\r\n}\r\n\r\nfunction repetitionMandatory(\r\n atn: ATN,\r\n rule: Rule,\r\n repetition: RepetitionMandatory\r\n): ATNHandle {\r\n const plusState = newState(atn, rule, repetition, {\r\n type: ATN_PLUS_BLOCK_START\r\n })\r\n defineDecisionState(atn, plusState)\r\n const handle = makeAlts(\r\n atn,\r\n rule,\r\n plusState,\r\n repetition,\r\n block(atn, rule, repetition)\r\n )\r\n return plus(atn, rule, repetition, handle)\r\n}\r\n\r\nfunction repetitionMandatorySep(\r\n atn: ATN,\r\n rule: Rule,\r\n repetition: RepetitionMandatoryWithSeparator\r\n): ATNHandle {\r\n const plusState = newState(atn, rule, repetition, {\r\n type: ATN_PLUS_BLOCK_START\r\n })\r\n defineDecisionState(atn, plusState)\r\n const handle = makeAlts(\r\n atn,\r\n rule,\r\n plusState,\r\n repetition,\r\n block(atn, rule, repetition)\r\n )\r\n const sep = tokenRef(atn, rule, repetition.separator, repetition)\r\n return plus(atn, rule, repetition, handle, sep)\r\n}\r\n\r\nfunction alternation(\r\n atn: ATN,\r\n rule: Rule,\r\n alternation: Alternation\r\n): ATNHandle {\r\n const start = newState(atn, rule, alternation, {\r\n type: ATN_BASIC\r\n })\r\n defineDecisionState(atn, start)\r\n const alts = map(alternation.definition, (e) => atom(atn, rule, e))\r\n const handle = makeAlts(atn, rule, start, alternation, ...alts)\r\n return handle\r\n}\r\n\r\nfunction option(atn: ATN, rule: Rule, option: Option): ATNHandle {\r\n const start = newState(atn, rule, option, {\r\n type: ATN_BASIC\r\n })\r\n defineDecisionState(atn, start)\r\n const handle = makeAlts(atn, rule, start, option, block(atn, rule, option))\r\n return optional(atn, rule, option, handle)\r\n}\r\n\r\nfunction block(\r\n atn: ATN,\r\n rule: Rule,\r\n block: { definition: IProduction[] }\r\n): ATNHandle | undefined {\r\n const handles = filter(\r\n map(block.definition, (e) => atom(atn, rule, e)),\r\n (e) => e !== undefined\r\n ) as ATNHandle[]\r\n if (handles.length === 1) {\r\n return handles[0]\r\n } else if (handles.length === 0) {\r\n return undefined\r\n } else {\r\n return makeBlock(atn, handles)\r\n }\r\n}\r\n\r\nfunction plus(\r\n atn: ATN,\r\n rule: Rule,\r\n plus: IProductionWithOccurrence,\r\n handle: ATNHandle,\r\n sep?: ATNHandle\r\n): ATNHandle {\r\n const blkStart = handle.left as PlusBlockStartState\r\n const blkEnd = handle.right\r\n\r\n const loop = newState(atn, rule, plus, {\r\n type: ATN_PLUS_LOOP_BACK\r\n })\r\n defineDecisionState(atn, loop)\r\n const end = newState(atn, rule, plus, {\r\n type: ATN_LOOP_END\r\n })\r\n blkStart.loopback = loop\r\n end.loopback = loop\r\n atn.decisionMap[buildATNKey(rule, sep ? 'RepetitionMandatoryWithSeparator' : 'RepetitionMandatory', plus.idx)] = loop;\r\n epsilon(blkEnd, loop) // block can see loop back\r\n\r\n // Depending on whether we have a separator we put the exit transition at index 1 or 0\r\n // This influences the chosen option in the lookahead DFA\r\n if (sep === undefined) {\r\n epsilon(loop, blkStart) // loop back to start\r\n epsilon(loop, end) // exit\r\n } else {\r\n epsilon(loop, end) // exit\r\n // loop back to start with separator\r\n epsilon(loop, sep.left)\r\n epsilon(sep.right, blkStart)\r\n }\r\n\r\n return {\r\n left: blkStart,\r\n right: end\r\n }\r\n}\r\n\r\nfunction star(\r\n atn: ATN,\r\n rule: Rule,\r\n star: IProductionWithOccurrence,\r\n handle: ATNHandle,\r\n sep?: ATNHandle\r\n): ATNHandle {\r\n const start = handle.left\r\n const end = handle.right\r\n\r\n const entry = newState(atn, rule, star, {\r\n type: ATN_STAR_LOOP_ENTRY\r\n })\r\n defineDecisionState(atn, entry)\r\n const loopEnd = newState(atn, rule, star, {\r\n type: ATN_LOOP_END\r\n })\r\n const loop = newState(atn, rule, star, {\r\n type: ATN_STAR_LOOP_BACK\r\n })\r\n entry.loopback = loop\r\n loopEnd.loopback = loop\r\n\r\n epsilon(entry, start) // loop enter edge (alt 2)\r\n epsilon(entry, loopEnd) // bypass loop edge (alt 1)\r\n epsilon(end, loop) // block end hits loop back\r\n\r\n if (sep !== undefined) {\r\n epsilon(loop, loopEnd) // end loop\r\n // loop back to start of handle using separator\r\n epsilon(loop, sep.left)\r\n epsilon(sep.right, start)\r\n } else {\r\n epsilon(loop, entry) // loop back to entry/exit decision\r\n }\r\n\r\n atn.decisionMap[buildATNKey(rule, sep ? 'RepetitionWithSeparator' : 'Repetition', star.idx)] = entry;\r\n return {\r\n left: entry,\r\n right: loopEnd\r\n }\r\n}\r\n\r\nfunction optional(atn: ATN, rule: Rule, optional: Option, handle: ATNHandle): ATNHandle {\r\n const start = handle.left as DecisionState\r\n const end = handle.right\r\n\r\n epsilon(start, end)\r\n\r\n atn.decisionMap[buildATNKey(rule, 'Option', optional.idx)] = start;\r\n return handle\r\n}\r\n\r\nfunction defineDecisionState(atn: ATN, state: DecisionState): number {\r\n atn.decisionStates.push(state)\r\n state.decision = atn.decisionStates.length - 1\r\n return state.decision\r\n}\r\n\r\nfunction makeAlts(\r\n atn: ATN,\r\n rule: Rule,\r\n start: BlockStartState,\r\n production: IProductionWithOccurrence,\r\n ...alts: (ATNHandle | undefined)[]\r\n): ATNHandle {\r\n const end = newState(atn, rule, production, {\r\n type: ATN_BLOCK_END,\r\n start\r\n })\r\n start.end = end\r\n for (const alt of alts) {\r\n if (alt !== undefined) {\r\n // hook alts up to decision block\r\n epsilon(start, alt.left)\r\n epsilon(alt.right, end)\r\n } else {\r\n epsilon(start, end)\r\n }\r\n }\r\n\r\n const handle: ATNHandle = {\r\n left: start as ATNState,\r\n right: end\r\n }\r\n atn.decisionMap[buildATNKey(rule, getProdType(production), production.idx)] = start\r\n return handle\r\n}\r\n\r\nfunction getProdType(production: IProduction): LookaheadProductionType {\r\n if (production instanceof Alternation) {\r\n return 'Alternation';\r\n } else if (production instanceof Option) {\r\n return 'Option';\r\n } else if (production instanceof Repetition) {\r\n return 'Repetition';\r\n } else if (production instanceof RepetitionWithSeparator) {\r\n return 'RepetitionWithSeparator';\r\n } else if (production instanceof RepetitionMandatory) {\r\n return 'RepetitionMandatory';\r\n } else if (production instanceof RepetitionMandatoryWithSeparator) {\r\n return 'RepetitionMandatoryWithSeparator';\r\n } else {\r\n throw new Error('Invalid production type encountered');\r\n }\r\n}\r\n\r\nfunction makeBlock(atn: ATN, alts: ATNHandle[]): ATNHandle {\r\n const altsLength = alts.length\r\n for (let i = 0; i < altsLength - 1; i++) {\r\n const handle = alts[i]\r\n let transition: Transition | undefined\r\n if (handle.left.transitions.length === 1) {\r\n transition = handle.left.transitions[0]\r\n }\r\n const isRuleTransition = transition instanceof RuleTransition\r\n const ruleTransition = transition as RuleTransition\r\n const next = alts[i + 1].left\r\n if (\r\n handle.left.type === ATN_BASIC &&\r\n handle.right.type === ATN_BASIC &&\r\n transition !== undefined &&\r\n ((isRuleTransition && ruleTransition.followState === handle.right) ||\r\n transition.target === handle.right)\r\n ) {\r\n // we can avoid epsilon edge to next element\r\n if (isRuleTransition) {\r\n ruleTransition.followState = next\r\n } else {\r\n transition.target = next\r\n }\r\n removeState(atn, handle.right) // we skipped over this state\r\n } else {\r\n // need epsilon if previous block's right end node is complex\r\n epsilon(handle.right, next)\r\n }\r\n }\r\n\r\n const first = alts[0]\r\n const last = alts[altsLength - 1]\r\n return {\r\n left: first.left,\r\n right: last.right\r\n }\r\n}\r\n\r\nfunction tokenRef(\r\n atn: ATN,\r\n rule: Rule,\r\n tokenType: TokenType,\r\n production: IProductionWithOccurrence\r\n): ATNHandle {\r\n const left = newState(atn, rule, production, {\r\n type: ATN_BASIC\r\n })\r\n const right = newState(atn, rule, production, {\r\n type: ATN_BASIC\r\n })\r\n addTransition(left, new AtomTransition(right, tokenType))\r\n return {\r\n left,\r\n right\r\n }\r\n}\r\n\r\nfunction ruleRef(\r\n atn: ATN,\r\n currentRule: Rule,\r\n nonTerminal: NonTerminal\r\n): ATNHandle {\r\n const rule = nonTerminal.referencedRule\r\n const start = atn.ruleToStartState.get(rule)!\r\n const left = newState(atn, currentRule, nonTerminal, {\r\n type: ATN_BASIC\r\n })\r\n const right = newState(atn, currentRule, nonTerminal, {\r\n type: ATN_BASIC\r\n })\r\n\r\n const call = new RuleTransition(start, rule, right)\r\n addTransition(left, call)\r\n\r\n return {\r\n left,\r\n right\r\n }\r\n}\r\n\r\nfunction buildRuleHandle(atn: ATN, rule: Rule, block: ATNHandle): ATNHandle {\r\n const start = atn.ruleToStartState.get(rule)!\r\n epsilon(start, block.left)\r\n const stop = atn.ruleToStopState.get(rule)!\r\n epsilon(block.right, stop)\r\n const handle: ATNHandle = {\r\n left: start,\r\n right: stop\r\n }\r\n return handle\r\n}\r\n\r\nfunction epsilon(a: ATNBaseState, b: ATNBaseState): void {\r\n const transition = new EpsilonTransition(b as ATNState)\r\n addTransition(a, transition)\r\n}\r\n\r\nfunction newState(\r\n atn: ATN,\r\n rule: Rule,\r\n production: IProductionWithOccurrence | undefined,\r\n partial: Partial\r\n): T {\r\n const t: T = {\r\n atn,\r\n production,\r\n epsilonOnlyTransitions: false,\r\n rule,\r\n transitions: [],\r\n nextTokenWithinRule: [],\r\n stateNumber: atn.states.length,\r\n ...partial\r\n } as unknown as T\r\n atn.states.push(t)\r\n return t\r\n}\r\n\r\nfunction addTransition(state: ATNBaseState, transition: Transition) {\r\n // A single ATN state can only contain epsilon transitions or non-epsilon transitions\r\n // Because they are never mixed, only setting the property for the first transition is fine\r\n if (state.transitions.length === 0) {\r\n state.epsilonOnlyTransitions = transition.isEpsilon()\r\n }\r\n state.transitions.push(transition)\r\n}\r\n\r\nfunction removeState(atn: ATN, state: ATNState): void {\r\n atn.states.splice(atn.states.indexOf(state), 1)\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2022 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport map from \"lodash-es/map.js\"\r\nimport { ATNState, DecisionState } from \"./atn.js\"\r\n\r\nexport interface DFA {\r\n start?: DFAState\r\n states: Record\r\n decision: number\r\n atnStartState: DecisionState\r\n}\r\n\r\nexport interface DFAState {\r\n configs: ATNConfigSet\r\n edges: Record\r\n isAcceptState: boolean\r\n prediction: number\r\n}\r\n\r\nexport const DFA_ERROR = {} as DFAState\r\n\r\nexport interface ATNConfig {\r\n state: ATNState\r\n alt: number\r\n stack: ATNState[]\r\n}\r\n\r\nexport class ATNConfigSet {\r\n private map: Record = {}\r\n private configs: ATNConfig[] = []\r\n\r\n uniqueAlt: number | undefined\r\n\r\n get size(): number {\r\n return this.configs.length\r\n }\r\n\r\n finalize(): void {\r\n // Empties the map to free up memory\r\n this.map = {}\r\n }\r\n\r\n add(config: ATNConfig): void {\r\n const key = getATNConfigKey(config)\r\n // Only add configs which don't exist in our map already\r\n // While this does not influence the actual algorithm, adding them anyway would massively increase memory consumption\r\n if (!(key in this.map)) {\r\n this.map[key] = this.configs.length\r\n this.configs.push(config)\r\n }\r\n }\r\n\r\n get elements(): readonly ATNConfig[] {\r\n return this.configs\r\n }\r\n\r\n get alts(): number[] {\r\n return map(this.configs, (e) => e.alt)\r\n }\r\n\r\n get key(): string {\r\n let value = \"\"\r\n for (const k in this.map) {\r\n value += k + \":\"\r\n }\r\n return value\r\n }\r\n}\r\n\r\nexport function getATNConfigKey(config: ATNConfig, alt = true) {\r\n return `${alt ? `a${config.alt}` : \"\"}s${\r\n config.state.stateNumber\r\n }:${config.stack.map((e) => e.stateNumber.toString()).join(\"_\")}`\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2022 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport {\r\n IToken,\r\n TokenType,\r\n tokenMatcher,\r\n tokenLabel,\r\n Rule,\r\n IProductionWithOccurrence,\r\n NonTerminal,\r\n Alternation,\r\n Option,\r\n RepetitionMandatory,\r\n RepetitionMandatoryWithSeparator,\r\n RepetitionWithSeparator,\r\n Repetition,\r\n Terminal,\r\n BaseParser,\r\n LLkLookaheadStrategy,\r\n ILookaheadValidationError,\r\n IOrAlt,\r\n getLookaheadPaths,\r\n OptionalProductionType\r\n} from \"chevrotain\";\r\nimport {\r\n ATN,\r\n ATNState,\r\n ATN_RULE_STOP,\r\n AtomTransition,\r\n buildATNKey,\r\n createATN,\r\n DecisionState,\r\n EpsilonTransition,\r\n RuleTransition,\r\n Transition\r\n} from \"./atn.js\";\r\nimport {\r\n ATNConfig,\r\n ATNConfigSet,\r\n DFA,\r\n DFAState,\r\n DFA_ERROR,\r\n getATNConfigKey\r\n} from \"./dfa.js\";\r\nimport min from \"lodash-es/min.js\";\r\nimport flatMap from \"lodash-es/flatMap.js\";\r\nimport uniqBy from \"lodash-es/uniqBy.js\";\r\nimport map from \"lodash-es/map.js\";\r\nimport flatten from \"lodash-es/flatten.js\";\r\nimport forEach from \"lodash-es/forEach.js\";\r\nimport isEmpty from \"lodash-es/isEmpty.js\";\r\nimport reduce from \"lodash-es/reduce.js\";\r\n\r\ntype DFACache = (predicateSet: PredicateSet) => DFA\r\n\r\nexport type AmbiguityReport = (message: string) => void;\r\n\r\nfunction createDFACache(startState: DecisionState, decision: number): DFACache {\r\n const map: Record = {}\r\n return (predicateSet) => {\r\n const key = predicateSet.toString()\r\n let existing = map[key]\r\n if (existing !== undefined) {\r\n return existing\r\n } else {\r\n existing = {\r\n atnStartState: startState,\r\n decision,\r\n states: {}\r\n }\r\n map[key] = existing\r\n return existing\r\n }\r\n }\r\n}\r\n\r\nclass PredicateSet {\r\n private predicates: boolean[] = []\r\n\r\n is(index: number): boolean {\r\n return index >= this.predicates.length || this.predicates[index]\r\n }\r\n\r\n set(index: number, value: boolean) {\r\n this.predicates[index] = value\r\n }\r\n\r\n toString(): string {\r\n let value = \"\"\r\n const size = this.predicates.length\r\n for (let i = 0; i < size; i++) {\r\n value += this.predicates[i] === true ? \"1\" : \"0\"\r\n }\r\n return value\r\n }\r\n}\r\n\r\ninterface AdaptivePredictError {\r\n tokenPath: IToken[]\r\n possibleTokenTypes: TokenType[]\r\n actualToken: IToken\r\n}\r\n\r\nconst EMPTY_PREDICATES = new PredicateSet()\r\n\r\nexport interface LLStarLookaheadOptions {\r\n logging?: AmbiguityReport\r\n}\r\n\r\nexport class LLStarLookaheadStrategy extends LLkLookaheadStrategy {\r\n\r\n private atn: ATN;\r\n private dfas: DFACache[];\r\n private logging: AmbiguityReport;\r\n\r\n constructor(options?: LLStarLookaheadOptions) {\r\n super();\r\n this.logging = options?.logging ?? ((message) => console.log(message));\r\n }\r\n\r\n override initialize(options: { rules: Rule[] }): void {\r\n this.atn = createATN(options.rules);\r\n this.dfas = initATNSimulator(this.atn);\r\n }\r\n\r\n override validateAmbiguousAlternationAlternatives(): ILookaheadValidationError[] {\r\n return [];\r\n }\r\n\r\n override validateEmptyOrAlternatives(): ILookaheadValidationError[] {\r\n return [];\r\n }\r\n\r\n override buildLookaheadForAlternation(options: {\r\n prodOccurrence: number;\r\n rule: Rule;\r\n maxLookahead: number;\r\n hasPredicates: boolean;\r\n dynamicTokensEnabled: boolean\r\n }): (this: BaseParser, orAlts?: IOrAlt[] | undefined) => number | undefined {\r\n const { prodOccurrence, rule, hasPredicates, dynamicTokensEnabled } = options;\r\n const dfas = this.dfas;\r\n const logging = this.logging;\r\n const key = buildATNKey(rule, 'Alternation', prodOccurrence);\r\n const decisionState = this.atn.decisionMap[key];\r\n const decisionIndex = decisionState.decision;\r\n const partialAlts: (TokenType | undefined)[][] = map(\r\n getLookaheadPaths({\r\n maxLookahead: 1,\r\n occurrence: prodOccurrence,\r\n prodType: \"Alternation\",\r\n rule: rule\r\n }),\r\n (currAlt) => map(currAlt, (path) => path[0])\r\n )\r\n\r\n if (isLL1Sequence(partialAlts, false) && !dynamicTokensEnabled) {\r\n const choiceToAlt = reduce(\r\n partialAlts,\r\n (result, currAlt, idx) => {\r\n forEach(currAlt, (currTokType) => {\r\n if (currTokType) {\r\n result[currTokType.tokenTypeIdx!] = idx\r\n forEach(currTokType.categoryMatches!, (currExtendingType) => {\r\n result[currExtendingType] = idx\r\n })\r\n }\r\n })\r\n return result\r\n },\r\n {} as Record\r\n )\r\n\r\n if (hasPredicates) {\r\n return function (this: BaseParser, orAlts) {\r\n const nextToken = this.LA(1)\r\n const prediction: number | undefined = choiceToAlt[nextToken.tokenTypeIdx]\r\n if (orAlts !== undefined && prediction !== undefined) {\r\n const gate = orAlts[prediction]?.GATE\r\n if (gate !== undefined && gate.call(this) === false) {\r\n return undefined;\r\n }\r\n }\r\n return prediction\r\n }\r\n } else {\r\n return function (this: BaseParser): number | undefined {\r\n const nextToken = this.LA(1)\r\n return choiceToAlt[nextToken.tokenTypeIdx];\r\n }\r\n }\r\n } else if (hasPredicates) {\r\n return function (this: BaseParser, orAlts) {\r\n const predicates = new PredicateSet()\r\n const length = orAlts === undefined ? 0 : orAlts.length\r\n for (let i = 0; i < length; i++) {\r\n const gate = orAlts?.[i].GATE\r\n predicates.set(i, gate === undefined || gate.call(this))\r\n }\r\n const result = adaptivePredict.call(this, dfas, decisionIndex, predicates, logging);\r\n return typeof result === 'number' ? result : undefined;\r\n }\r\n } else {\r\n return function (this: BaseParser) {\r\n const result = adaptivePredict.call(this, dfas, decisionIndex, EMPTY_PREDICATES, logging);\r\n return typeof result === 'number' ? result : undefined;\r\n }\r\n }\r\n }\r\n\r\n override buildLookaheadForOptional(options: {\r\n prodOccurrence: number;\r\n prodType: OptionalProductionType;\r\n rule: Rule;\r\n maxLookahead: number;\r\n dynamicTokensEnabled: boolean\r\n }): (this: BaseParser) => boolean {\r\n const { prodOccurrence, rule, prodType, dynamicTokensEnabled } = options;\r\n const dfas = this.dfas;\r\n const logging = this.logging;\r\n const key = buildATNKey(rule, prodType, prodOccurrence);\r\n const decisionState = this.atn.decisionMap[key];\r\n const decisionIndex = decisionState.decision;\r\n const alts = map(\r\n getLookaheadPaths({\r\n maxLookahead: 1,\r\n occurrence: prodOccurrence,\r\n prodType,\r\n rule\r\n }),\r\n (e) => {\r\n return map(e, (g) => g[0])\r\n }\r\n )\r\n \r\n if (isLL1Sequence(alts) && alts[0][0] && !dynamicTokensEnabled) {\r\n const alt = alts[0]\r\n const singleTokensTypes = flatten(alt)\r\n \r\n if (\r\n singleTokensTypes.length === 1 &&\r\n isEmpty(singleTokensTypes[0].categoryMatches)\r\n ) {\r\n const expectedTokenType = singleTokensTypes[0]\r\n const expectedTokenUniqueKey = expectedTokenType.tokenTypeIdx\r\n \r\n return function (this: BaseParser): boolean {\r\n return this.LA(1).tokenTypeIdx === expectedTokenUniqueKey\r\n }\r\n } else {\r\n const choiceToAlt = reduce(\r\n singleTokensTypes,\r\n (result, currTokType) => {\r\n if (currTokType !== undefined) {\r\n result[currTokType.tokenTypeIdx!] = true\r\n forEach(currTokType.categoryMatches, (currExtendingType) => {\r\n result[currExtendingType] = true\r\n })\r\n }\r\n return result\r\n },\r\n {} as Record\r\n )\r\n \r\n return function (this: BaseParser): boolean {\r\n const nextToken = this.LA(1)\r\n return choiceToAlt[nextToken.tokenTypeIdx] === true\r\n }\r\n }\r\n }\r\n return function (this: BaseParser) {\r\n const result = adaptivePredict.call(this, dfas, decisionIndex, EMPTY_PREDICATES, logging)\r\n return typeof result === \"object\" ? false : result === 0;\r\n }\r\n }\r\n\r\n}\r\n\r\nfunction isLL1Sequence(sequences: (TokenType | undefined)[][], allowEmpty = true): boolean {\r\n const fullSet = new Set()\r\n\r\n for (const alt of sequences) {\r\n const altSet = new Set()\r\n for (const tokType of alt) {\r\n if (tokType === undefined) {\r\n if (allowEmpty) {\r\n // Epsilon production encountered\r\n break\r\n } else {\r\n return false;\r\n }\r\n }\r\n const indices = [tokType.tokenTypeIdx!].concat(tokType.categoryMatches!)\r\n for (const index of indices) {\r\n if (fullSet.has(index)) {\r\n if (!altSet.has(index)) {\r\n return false\r\n }\r\n } else {\r\n fullSet.add(index)\r\n altSet.add(index)\r\n }\r\n }\r\n }\r\n }\r\n return true\r\n}\r\n\r\nfunction initATNSimulator(atn: ATN): DFACache[] {\r\n const decisionLength = atn.decisionStates.length\r\n const decisionToDFA: DFACache[] = Array(decisionLength)\r\n for (let i = 0; i < decisionLength; i++) {\r\n decisionToDFA[i] = createDFACache(atn.decisionStates[i], i)\r\n }\r\n return decisionToDFA;\r\n}\r\n\r\nfunction adaptivePredict(\r\n this: BaseParser,\r\n dfaCaches: DFACache[],\r\n decision: number,\r\n predicateSet: PredicateSet,\r\n logging: AmbiguityReport\r\n): number | AdaptivePredictError {\r\n const dfa = dfaCaches[decision](predicateSet)\r\n let start = dfa.start\r\n if (start === undefined) {\r\n const closure = computeStartState(dfa.atnStartState as ATNState)\r\n start = addDFAState(dfa, newDFAState(closure))\r\n dfa.start = start\r\n }\r\n\r\n const alt = performLookahead.apply(this, [dfa, start, predicateSet, logging])\r\n return alt\r\n}\r\n\r\nfunction performLookahead(\r\n this: BaseParser,\r\n dfa: DFA,\r\n s0: DFAState,\r\n predicateSet: PredicateSet,\r\n logging: AmbiguityReport\r\n): number | AdaptivePredictError {\r\n let previousD = s0\r\n\r\n let i = 1\r\n const path: IToken[] = []\r\n let t = this.LA(i++)\r\n\r\n while (true) {\r\n let d = getExistingTargetState(previousD, t)\r\n if (d === undefined) {\r\n d = computeLookaheadTarget.apply(this, [dfa, previousD, t, i, predicateSet, logging])\r\n }\r\n\r\n if (d === DFA_ERROR) {\r\n return buildAdaptivePredictError(path, previousD, t)\r\n }\r\n\r\n if (d.isAcceptState === true) {\r\n return d.prediction\r\n }\r\n\r\n previousD = d\r\n path.push(t)\r\n t = this.LA(i++)\r\n }\r\n}\r\n\r\nfunction computeLookaheadTarget(\r\n this: BaseParser,\r\n dfa: DFA,\r\n previousD: DFAState,\r\n token: IToken,\r\n lookahead: number,\r\n predicateSet: PredicateSet,\r\n logging: AmbiguityReport\r\n): DFAState {\r\n const reach = computeReachSet(previousD.configs, token, predicateSet)\r\n if (reach.size === 0) {\r\n addDFAEdge(dfa, previousD, token, DFA_ERROR)\r\n return DFA_ERROR\r\n }\r\n\r\n let newState = newDFAState(reach)\r\n const predictedAlt = getUniqueAlt(reach, predicateSet)\r\n\r\n if (predictedAlt !== undefined) {\r\n newState.isAcceptState = true\r\n newState.prediction = predictedAlt\r\n newState.configs.uniqueAlt = predictedAlt\r\n } else if (hasConflictTerminatingPrediction(reach)) {\r\n const prediction = min(reach.alts)!\r\n newState.isAcceptState = true\r\n newState.prediction = prediction\r\n newState.configs.uniqueAlt = prediction\r\n reportLookaheadAmbiguity.apply(this, [dfa, lookahead, reach.alts, logging])\r\n }\r\n\r\n newState = addDFAEdge(dfa, previousD, token, newState)\r\n return newState\r\n}\r\n\r\nfunction reportLookaheadAmbiguity(\r\n this: BaseParser,\r\n dfa: DFA,\r\n lookahead: number,\r\n ambiguityIndices: number[],\r\n logging: AmbiguityReport\r\n) {\r\n const prefixPath: TokenType[] = []\r\n for (let i = 1; i <= lookahead; i++) {\r\n prefixPath.push(this.LA(i).tokenType)\r\n }\r\n const atnState = dfa.atnStartState\r\n const topLevelRule = atnState.rule\r\n const production = atnState.production\r\n const message = buildAmbiguityError({\r\n topLevelRule,\r\n ambiguityIndices,\r\n production,\r\n prefixPath\r\n })\r\n logging(message)\r\n}\r\n\r\nfunction buildAmbiguityError(options: {\r\n topLevelRule: Rule\r\n prefixPath: TokenType[]\r\n ambiguityIndices: number[]\r\n production: IProductionWithOccurrence\r\n}): string {\r\n const pathMsg = map(options.prefixPath, (currtok) =>\r\n tokenLabel(currtok)\r\n ).join(\", \")\r\n const occurrence =\r\n options.production.idx === 0 ? \"\" : options.production.idx\r\n let currMessage =\r\n `Ambiguous Alternatives Detected: <${options.ambiguityIndices.join(\r\n \", \"\r\n )}> in <${getProductionDslName(options.production)}${occurrence}>` +\r\n ` inside <${options.topLevelRule.name}> Rule,\\n` +\r\n `<${pathMsg}> may appears as a prefix path in all these alternatives.\\n`\r\n\r\n currMessage =\r\n currMessage +\r\n `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES\\n` +\r\n `For Further details.`\r\n return currMessage\r\n}\r\n\r\nfunction getProductionDslName(prod: IProductionWithOccurrence): string {\r\n if (prod instanceof NonTerminal) {\r\n return \"SUBRULE\"\r\n } else if (prod instanceof Option) {\r\n return \"OPTION\"\r\n } else if (prod instanceof Alternation) {\r\n return \"OR\"\r\n } else if (prod instanceof RepetitionMandatory) {\r\n return \"AT_LEAST_ONE\"\r\n } else if (prod instanceof RepetitionMandatoryWithSeparator) {\r\n return \"AT_LEAST_ONE_SEP\"\r\n } else if (prod instanceof RepetitionWithSeparator) {\r\n return \"MANY_SEP\"\r\n } else if (prod instanceof Repetition) {\r\n return \"MANY\"\r\n } else if (prod instanceof Terminal) {\r\n return \"CONSUME\"\r\n } else {\r\n throw Error(\"non exhaustive match\")\r\n }\r\n}\r\n\r\nfunction buildAdaptivePredictError(\r\n path: IToken[],\r\n previous: DFAState,\r\n current: IToken\r\n): AdaptivePredictError {\r\n const nextTransitions = flatMap(\r\n previous.configs.elements,\r\n (e) => e.state.transitions\r\n )\r\n const nextTokenTypes = uniqBy(\r\n nextTransitions\r\n .filter((e): e is AtomTransition => e instanceof AtomTransition)\r\n .map((e) => e.tokenType),\r\n (e) => e.tokenTypeIdx\r\n )\r\n return {\r\n actualToken: current,\r\n possibleTokenTypes: nextTokenTypes,\r\n tokenPath: path\r\n }\r\n}\r\n\r\nfunction getExistingTargetState(\r\n state: DFAState,\r\n token: IToken\r\n): DFAState | undefined {\r\n return state.edges[token.tokenTypeIdx]\r\n}\r\n\r\nfunction computeReachSet(\r\n configs: ATNConfigSet,\r\n token: IToken,\r\n predicateSet: PredicateSet\r\n): ATNConfigSet {\r\n const intermediate = new ATNConfigSet()\r\n const skippedStopStates: ATNConfig[] = []\r\n\r\n for (const c of configs.elements) {\r\n if (predicateSet.is(c.alt) === false) {\r\n continue\r\n }\r\n if (c.state.type === ATN_RULE_STOP) {\r\n skippedStopStates.push(c)\r\n continue\r\n }\r\n const transitionLength = c.state.transitions.length\r\n for (let i = 0; i < transitionLength; i++) {\r\n const transition = c.state.transitions[i]\r\n const target = getReachableTarget(transition, token)\r\n if (target !== undefined) {\r\n intermediate.add({\r\n state: target,\r\n alt: c.alt,\r\n stack: c.stack\r\n })\r\n }\r\n }\r\n }\r\n\r\n let reach: ATNConfigSet | undefined\r\n\r\n if (skippedStopStates.length === 0 && intermediate.size === 1) {\r\n reach = intermediate\r\n }\r\n\r\n if (reach === undefined) {\r\n reach = new ATNConfigSet()\r\n for (const c of intermediate.elements) {\r\n closure(c, reach)\r\n }\r\n }\r\n\r\n if (skippedStopStates.length > 0 && !hasConfigInRuleStopState(reach)) {\r\n for (const c of skippedStopStates) {\r\n reach.add(c)\r\n }\r\n }\r\n\r\n return reach\r\n}\r\n\r\nfunction getReachableTarget(\r\n transition: Transition,\r\n token: IToken\r\n): ATNState | undefined {\r\n if (\r\n transition instanceof AtomTransition &&\r\n tokenMatcher(token, transition.tokenType)\r\n ) {\r\n return transition.target\r\n }\r\n return undefined\r\n}\r\n\r\nfunction getUniqueAlt(\r\n configs: ATNConfigSet,\r\n predicateSet: PredicateSet\r\n): number | undefined {\r\n let alt: number | undefined\r\n for (const c of configs.elements) {\r\n if (predicateSet.is(c.alt) === true) {\r\n if (alt === undefined) {\r\n alt = c.alt\r\n } else if (alt !== c.alt) {\r\n return undefined\r\n }\r\n }\r\n }\r\n return alt\r\n}\r\n\r\nfunction newDFAState(closure: ATNConfigSet): DFAState {\r\n return {\r\n configs: closure,\r\n edges: {},\r\n isAcceptState: false,\r\n prediction: -1\r\n }\r\n}\r\n\r\nfunction addDFAEdge(\r\n dfa: DFA,\r\n from: DFAState,\r\n token: IToken,\r\n to: DFAState\r\n): DFAState {\r\n to = addDFAState(dfa, to)\r\n from.edges[token.tokenTypeIdx] = to\r\n return to\r\n}\r\n\r\nfunction addDFAState(dfa: DFA, state: DFAState): DFAState {\r\n if (state === DFA_ERROR) {\r\n return state\r\n }\r\n // Repetitions have the same config set\r\n // Therefore, storing the key of the config in a map allows us to create a loop in our DFA\r\n const mapKey = state.configs.key\r\n const existing = dfa.states[mapKey]\r\n if (existing !== undefined) {\r\n return existing\r\n }\r\n state.configs.finalize()\r\n dfa.states[mapKey] = state\r\n return state\r\n}\r\n\r\nfunction computeStartState(atnState: ATNState): ATNConfigSet {\r\n const configs = new ATNConfigSet()\r\n\r\n const numberOfTransitions = atnState.transitions.length\r\n for (let i = 0; i < numberOfTransitions; i++) {\r\n const target = atnState.transitions[i].target\r\n const config: ATNConfig = {\r\n state: target,\r\n alt: i,\r\n stack: []\r\n }\r\n closure(config, configs)\r\n }\r\n\r\n return configs\r\n}\r\n\r\nfunction closure(config: ATNConfig, configs: ATNConfigSet): void {\r\n const p = config.state\r\n\r\n if (p.type === ATN_RULE_STOP) {\r\n if (config.stack.length > 0) {\r\n const atnStack = [...config.stack]\r\n const followState = atnStack.pop()!\r\n const followConfig: ATNConfig = {\r\n state: followState,\r\n alt: config.alt,\r\n stack: atnStack\r\n }\r\n closure(followConfig, configs)\r\n } else {\r\n // Dipping into outer context, simply add the config\r\n // This will stop computation once every config is at the rule stop state\r\n configs.add(config)\r\n }\r\n return\r\n }\r\n\r\n if (!p.epsilonOnlyTransitions) {\r\n configs.add(config)\r\n }\r\n\r\n const transitionLength = p.transitions.length\r\n for (let i = 0; i < transitionLength; i++) {\r\n const transition = p.transitions[i]\r\n const c = getEpsilonTarget(config, transition)\r\n\r\n if (c !== undefined) {\r\n closure(c, configs)\r\n }\r\n }\r\n}\r\n\r\nfunction getEpsilonTarget(\r\n config: ATNConfig,\r\n transition: Transition\r\n): ATNConfig | undefined {\r\n if (transition instanceof EpsilonTransition) {\r\n return {\r\n state: transition.target,\r\n alt: config.alt,\r\n stack: config.stack\r\n }\r\n } else if (transition instanceof RuleTransition) {\r\n const stack = [...config.stack, transition.followState]\r\n return {\r\n state: transition.target,\r\n alt: config.alt,\r\n stack\r\n }\r\n }\r\n return undefined\r\n}\r\n\r\nfunction hasConfigInRuleStopState(configs: ATNConfigSet): boolean {\r\n for (const c of configs.elements) {\r\n if (c.state.type === ATN_RULE_STOP) {\r\n return true\r\n }\r\n }\r\n return false\r\n}\r\n\r\nfunction allConfigsInRuleStopStates(configs: ATNConfigSet): boolean {\r\n for (const c of configs.elements) {\r\n if (c.state.type !== ATN_RULE_STOP) {\r\n return false\r\n }\r\n }\r\n return true\r\n}\r\n\r\nfunction hasConflictTerminatingPrediction(configs: ATNConfigSet): boolean {\r\n if (allConfigsInRuleStopStates(configs)) {\r\n return true\r\n }\r\n const altSets = getConflictingAltSets(configs.elements)\r\n const heuristic =\r\n hasConflictingAltSet(altSets) && !hasStateAssociatedWithOneAlt(altSets)\r\n return heuristic\r\n}\r\n\r\nfunction getConflictingAltSets(\r\n configs: readonly ATNConfig[]\r\n): Map> {\r\n const configToAlts = new Map>()\r\n for (const c of configs) {\r\n const key = getATNConfigKey(c, false)\r\n let alts = configToAlts.get(key)\r\n if (alts === undefined) {\r\n alts = {}\r\n configToAlts.set(key, alts)\r\n }\r\n alts[c.alt] = true\r\n }\r\n return configToAlts\r\n}\r\n\r\nfunction hasConflictingAltSet(\r\n altSets: Map>\r\n): boolean {\r\n for (const value of Array.from(altSets.values())) {\r\n if (Object.keys(value).length > 1) {\r\n return true\r\n }\r\n }\r\n return false\r\n}\r\n\r\nfunction hasStateAssociatedWithOneAlt(\r\n altSets: Map>\r\n): boolean {\r\n for (const value of Array.from(altSets.values())) {\r\n if (Object.keys(value).length === 1) {\r\n return true\r\n }\r\n }\r\n return false\r\n}\r\n", "/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\n'use strict';\nexport var DocumentUri;\n(function (DocumentUri) {\n function is(value) {\n return typeof value === 'string';\n }\n DocumentUri.is = is;\n})(DocumentUri || (DocumentUri = {}));\nexport var URI;\n(function (URI) {\n function is(value) {\n return typeof value === 'string';\n }\n URI.is = is;\n})(URI || (URI = {}));\nexport var integer;\n(function (integer) {\n integer.MIN_VALUE = -2147483648;\n integer.MAX_VALUE = 2147483647;\n function is(value) {\n return typeof value === 'number' && integer.MIN_VALUE <= value && value <= integer.MAX_VALUE;\n }\n integer.is = is;\n})(integer || (integer = {}));\nexport var uinteger;\n(function (uinteger) {\n uinteger.MIN_VALUE = 0;\n uinteger.MAX_VALUE = 2147483647;\n function is(value) {\n return typeof value === 'number' && uinteger.MIN_VALUE <= value && value <= uinteger.MAX_VALUE;\n }\n uinteger.is = is;\n})(uinteger || (uinteger = {}));\n/**\n * The Position namespace provides helper functions to work with\n * {@link Position} literals.\n */\nexport var Position;\n(function (Position) {\n /**\n * Creates a new Position literal from the given line and character.\n * @param line The position's line.\n * @param character The position's character.\n */\n function create(line, character) {\n if (line === Number.MAX_VALUE) {\n line = uinteger.MAX_VALUE;\n }\n if (character === Number.MAX_VALUE) {\n character = uinteger.MAX_VALUE;\n }\n return { line, character };\n }\n Position.create = create;\n /**\n * Checks whether the given literal conforms to the {@link Position} interface.\n */\n function is(value) {\n let candidate = value;\n return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character);\n }\n Position.is = is;\n})(Position || (Position = {}));\n/**\n * The Range namespace provides helper functions to work with\n * {@link Range} literals.\n */\nexport var Range;\n(function (Range) {\n function create(one, two, three, four) {\n if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) {\n return { start: Position.create(one, two), end: Position.create(three, four) };\n }\n else if (Position.is(one) && Position.is(two)) {\n return { start: one, end: two };\n }\n else {\n throw new Error(`Range#create called with invalid arguments[${one}, ${two}, ${three}, ${four}]`);\n }\n }\n Range.create = create;\n /**\n * Checks whether the given literal conforms to the {@link Range} interface.\n */\n function is(value) {\n let candidate = value;\n return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);\n }\n Range.is = is;\n})(Range || (Range = {}));\n/**\n * The Location namespace provides helper functions to work with\n * {@link Location} literals.\n */\nexport var Location;\n(function (Location) {\n /**\n * Creates a Location literal.\n * @param uri The location's uri.\n * @param range The location's range.\n */\n function create(uri, range) {\n return { uri, range };\n }\n Location.create = create;\n /**\n * Checks whether the given literal conforms to the {@link Location} interface.\n */\n function is(value) {\n let candidate = value;\n return Is.objectLiteral(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));\n }\n Location.is = is;\n})(Location || (Location = {}));\n/**\n * The LocationLink namespace provides helper functions to work with\n * {@link LocationLink} literals.\n */\nexport var LocationLink;\n(function (LocationLink) {\n /**\n * Creates a LocationLink literal.\n * @param targetUri The definition's uri.\n * @param targetRange The full range of the definition.\n * @param targetSelectionRange The span of the symbol definition at the target.\n * @param originSelectionRange The span of the symbol being defined in the originating source file.\n */\n function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {\n return { targetUri, targetRange, targetSelectionRange, originSelectionRange };\n }\n LocationLink.create = create;\n /**\n * Checks whether the given literal conforms to the {@link LocationLink} interface.\n */\n function is(value) {\n let candidate = value;\n return Is.objectLiteral(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)\n && Range.is(candidate.targetSelectionRange)\n && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));\n }\n LocationLink.is = is;\n})(LocationLink || (LocationLink = {}));\n/**\n * The Color namespace provides helper functions to work with\n * {@link Color} literals.\n */\nexport var Color;\n(function (Color) {\n /**\n * Creates a new Color literal.\n */\n function create(red, green, blue, alpha) {\n return {\n red,\n green,\n blue,\n alpha,\n };\n }\n Color.create = create;\n /**\n * Checks whether the given literal conforms to the {@link Color} interface.\n */\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate) && Is.numberRange(candidate.red, 0, 1)\n && Is.numberRange(candidate.green, 0, 1)\n && Is.numberRange(candidate.blue, 0, 1)\n && Is.numberRange(candidate.alpha, 0, 1);\n }\n Color.is = is;\n})(Color || (Color = {}));\n/**\n * The ColorInformation namespace provides helper functions to work with\n * {@link ColorInformation} literals.\n */\nexport var ColorInformation;\n(function (ColorInformation) {\n /**\n * Creates a new ColorInformation literal.\n */\n function create(range, color) {\n return {\n range,\n color,\n };\n }\n ColorInformation.create = create;\n /**\n * Checks whether the given literal conforms to the {@link ColorInformation} interface.\n */\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate) && Range.is(candidate.range) && Color.is(candidate.color);\n }\n ColorInformation.is = is;\n})(ColorInformation || (ColorInformation = {}));\n/**\n * The Color namespace provides helper functions to work with\n * {@link ColorPresentation} literals.\n */\nexport var ColorPresentation;\n(function (ColorPresentation) {\n /**\n * Creates a new ColorInformation literal.\n */\n function create(label, textEdit, additionalTextEdits) {\n return {\n label,\n textEdit,\n additionalTextEdits,\n };\n }\n ColorPresentation.create = create;\n /**\n * Checks whether the given literal conforms to the {@link ColorInformation} interface.\n */\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate) && Is.string(candidate.label)\n && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))\n && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));\n }\n ColorPresentation.is = is;\n})(ColorPresentation || (ColorPresentation = {}));\n/**\n * A set of predefined range kinds.\n */\nexport var FoldingRangeKind;\n(function (FoldingRangeKind) {\n /**\n * Folding range for a comment\n */\n FoldingRangeKind.Comment = 'comment';\n /**\n * Folding range for an import or include\n */\n FoldingRangeKind.Imports = 'imports';\n /**\n * Folding range for a region (e.g. `#region`)\n */\n FoldingRangeKind.Region = 'region';\n})(FoldingRangeKind || (FoldingRangeKind = {}));\n/**\n * The folding range namespace provides helper functions to work with\n * {@link FoldingRange} literals.\n */\nexport var FoldingRange;\n(function (FoldingRange) {\n /**\n * Creates a new FoldingRange literal.\n */\n function create(startLine, endLine, startCharacter, endCharacter, kind, collapsedText) {\n const result = {\n startLine,\n endLine\n };\n if (Is.defined(startCharacter)) {\n result.startCharacter = startCharacter;\n }\n if (Is.defined(endCharacter)) {\n result.endCharacter = endCharacter;\n }\n if (Is.defined(kind)) {\n result.kind = kind;\n }\n if (Is.defined(collapsedText)) {\n result.collapsedText = collapsedText;\n }\n return result;\n }\n FoldingRange.create = create;\n /**\n * Checks whether the given literal conforms to the {@link FoldingRange} interface.\n */\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate) && Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine)\n && (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter))\n && (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter))\n && (Is.undefined(candidate.kind) || Is.string(candidate.kind));\n }\n FoldingRange.is = is;\n})(FoldingRange || (FoldingRange = {}));\n/**\n * The DiagnosticRelatedInformation namespace provides helper functions to work with\n * {@link DiagnosticRelatedInformation} literals.\n */\nexport var DiagnosticRelatedInformation;\n(function (DiagnosticRelatedInformation) {\n /**\n * Creates a new DiagnosticRelatedInformation literal.\n */\n function create(location, message) {\n return {\n location,\n message\n };\n }\n DiagnosticRelatedInformation.create = create;\n /**\n * Checks whether the given literal conforms to the {@link DiagnosticRelatedInformation} interface.\n */\n function is(value) {\n let candidate = value;\n return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);\n }\n DiagnosticRelatedInformation.is = is;\n})(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));\n/**\n * The diagnostic's severity.\n */\nexport var DiagnosticSeverity;\n(function (DiagnosticSeverity) {\n /**\n * Reports an error.\n */\n DiagnosticSeverity.Error = 1;\n /**\n * Reports a warning.\n */\n DiagnosticSeverity.Warning = 2;\n /**\n * Reports an information.\n */\n DiagnosticSeverity.Information = 3;\n /**\n * Reports a hint.\n */\n DiagnosticSeverity.Hint = 4;\n})(DiagnosticSeverity || (DiagnosticSeverity = {}));\n/**\n * The diagnostic tags.\n *\n * @since 3.15.0\n */\nexport var DiagnosticTag;\n(function (DiagnosticTag) {\n /**\n * Unused or unnecessary code.\n *\n * Clients are allowed to render diagnostics with this tag faded out instead of having\n * an error squiggle.\n */\n DiagnosticTag.Unnecessary = 1;\n /**\n * Deprecated or obsolete code.\n *\n * Clients are allowed to rendered diagnostics with this tag strike through.\n */\n DiagnosticTag.Deprecated = 2;\n})(DiagnosticTag || (DiagnosticTag = {}));\n/**\n * The CodeDescription namespace provides functions to deal with descriptions for diagnostic codes.\n *\n * @since 3.16.0\n */\nexport var CodeDescription;\n(function (CodeDescription) {\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate) && Is.string(candidate.href);\n }\n CodeDescription.is = is;\n})(CodeDescription || (CodeDescription = {}));\n/**\n * The Diagnostic namespace provides helper functions to work with\n * {@link Diagnostic} literals.\n */\nexport var Diagnostic;\n(function (Diagnostic) {\n /**\n * Creates a new Diagnostic literal.\n */\n function create(range, message, severity, code, source, relatedInformation) {\n let result = { range, message };\n if (Is.defined(severity)) {\n result.severity = severity;\n }\n if (Is.defined(code)) {\n result.code = code;\n }\n if (Is.defined(source)) {\n result.source = source;\n }\n if (Is.defined(relatedInformation)) {\n result.relatedInformation = relatedInformation;\n }\n return result;\n }\n Diagnostic.create = create;\n /**\n * Checks whether the given literal conforms to the {@link Diagnostic} interface.\n */\n function is(value) {\n var _a;\n let candidate = value;\n return Is.defined(candidate)\n && Range.is(candidate.range)\n && Is.string(candidate.message)\n && (Is.number(candidate.severity) || Is.undefined(candidate.severity))\n && (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))\n && (Is.undefined(candidate.codeDescription) || (Is.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href)))\n && (Is.string(candidate.source) || Is.undefined(candidate.source))\n && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));\n }\n Diagnostic.is = is;\n})(Diagnostic || (Diagnostic = {}));\n/**\n * The Command namespace provides helper functions to work with\n * {@link Command} literals.\n */\nexport var Command;\n(function (Command) {\n /**\n * Creates a new Command literal.\n */\n function create(title, command, ...args) {\n let result = { title, command };\n if (Is.defined(args) && args.length > 0) {\n result.arguments = args;\n }\n return result;\n }\n Command.create = create;\n /**\n * Checks whether the given literal conforms to the {@link Command} interface.\n */\n function is(value) {\n let candidate = value;\n return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);\n }\n Command.is = is;\n})(Command || (Command = {}));\n/**\n * The TextEdit namespace provides helper function to create replace,\n * insert and delete edits more easily.\n */\nexport var TextEdit;\n(function (TextEdit) {\n /**\n * Creates a replace text edit.\n * @param range The range of text to be replaced.\n * @param newText The new text.\n */\n function replace(range, newText) {\n return { range, newText };\n }\n TextEdit.replace = replace;\n /**\n * Creates an insert text edit.\n * @param position The position to insert the text at.\n * @param newText The text to be inserted.\n */\n function insert(position, newText) {\n return { range: { start: position, end: position }, newText };\n }\n TextEdit.insert = insert;\n /**\n * Creates a delete text edit.\n * @param range The range of text to be deleted.\n */\n function del(range) {\n return { range, newText: '' };\n }\n TextEdit.del = del;\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate)\n && Is.string(candidate.newText)\n && Range.is(candidate.range);\n }\n TextEdit.is = is;\n})(TextEdit || (TextEdit = {}));\nexport var ChangeAnnotation;\n(function (ChangeAnnotation) {\n function create(label, needsConfirmation, description) {\n const result = { label };\n if (needsConfirmation !== undefined) {\n result.needsConfirmation = needsConfirmation;\n }\n if (description !== undefined) {\n result.description = description;\n }\n return result;\n }\n ChangeAnnotation.create = create;\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate) && Is.string(candidate.label) &&\n (Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === undefined) &&\n (Is.string(candidate.description) || candidate.description === undefined);\n }\n ChangeAnnotation.is = is;\n})(ChangeAnnotation || (ChangeAnnotation = {}));\nexport var ChangeAnnotationIdentifier;\n(function (ChangeAnnotationIdentifier) {\n function is(value) {\n const candidate = value;\n return Is.string(candidate);\n }\n ChangeAnnotationIdentifier.is = is;\n})(ChangeAnnotationIdentifier || (ChangeAnnotationIdentifier = {}));\nexport var AnnotatedTextEdit;\n(function (AnnotatedTextEdit) {\n /**\n * Creates an annotated replace text edit.\n *\n * @param range The range of text to be replaced.\n * @param newText The new text.\n * @param annotation The annotation.\n */\n function replace(range, newText, annotation) {\n return { range, newText, annotationId: annotation };\n }\n AnnotatedTextEdit.replace = replace;\n /**\n * Creates an annotated insert text edit.\n *\n * @param position The position to insert the text at.\n * @param newText The text to be inserted.\n * @param annotation The annotation.\n */\n function insert(position, newText, annotation) {\n return { range: { start: position, end: position }, newText, annotationId: annotation };\n }\n AnnotatedTextEdit.insert = insert;\n /**\n * Creates an annotated delete text edit.\n *\n * @param range The range of text to be deleted.\n * @param annotation The annotation.\n */\n function del(range, annotation) {\n return { range, newText: '', annotationId: annotation };\n }\n AnnotatedTextEdit.del = del;\n function is(value) {\n const candidate = value;\n return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId));\n }\n AnnotatedTextEdit.is = is;\n})(AnnotatedTextEdit || (AnnotatedTextEdit = {}));\n/**\n * The TextDocumentEdit namespace provides helper function to create\n * an edit that manipulates a text document.\n */\nexport var TextDocumentEdit;\n(function (TextDocumentEdit) {\n /**\n * Creates a new `TextDocumentEdit`\n */\n function create(textDocument, edits) {\n return { textDocument, edits };\n }\n TextDocumentEdit.create = create;\n function is(value) {\n let candidate = value;\n return Is.defined(candidate)\n && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument)\n && Array.isArray(candidate.edits);\n }\n TextDocumentEdit.is = is;\n})(TextDocumentEdit || (TextDocumentEdit = {}));\nexport var CreateFile;\n(function (CreateFile) {\n function create(uri, options, annotation) {\n let result = {\n kind: 'create',\n uri\n };\n if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) {\n result.options = options;\n }\n if (annotation !== undefined) {\n result.annotationId = annotation;\n }\n return result;\n }\n CreateFile.create = create;\n function is(value) {\n let candidate = value;\n return candidate && candidate.kind === 'create' && Is.string(candidate.uri) && (candidate.options === undefined ||\n ((candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));\n }\n CreateFile.is = is;\n})(CreateFile || (CreateFile = {}));\nexport var RenameFile;\n(function (RenameFile) {\n function create(oldUri, newUri, options, annotation) {\n let result = {\n kind: 'rename',\n oldUri,\n newUri\n };\n if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) {\n result.options = options;\n }\n if (annotation !== undefined) {\n result.annotationId = annotation;\n }\n return result;\n }\n RenameFile.create = create;\n function is(value) {\n let candidate = value;\n return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === undefined ||\n ((candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));\n }\n RenameFile.is = is;\n})(RenameFile || (RenameFile = {}));\nexport var DeleteFile;\n(function (DeleteFile) {\n function create(uri, options, annotation) {\n let result = {\n kind: 'delete',\n uri\n };\n if (options !== undefined && (options.recursive !== undefined || options.ignoreIfNotExists !== undefined)) {\n result.options = options;\n }\n if (annotation !== undefined) {\n result.annotationId = annotation;\n }\n return result;\n }\n DeleteFile.create = create;\n function is(value) {\n let candidate = value;\n return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) && (candidate.options === undefined ||\n ((candidate.options.recursive === undefined || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === undefined || Is.boolean(candidate.options.ignoreIfNotExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));\n }\n DeleteFile.is = is;\n})(DeleteFile || (DeleteFile = {}));\nexport var WorkspaceEdit;\n(function (WorkspaceEdit) {\n function is(value) {\n let candidate = value;\n return candidate &&\n (candidate.changes !== undefined || candidate.documentChanges !== undefined) &&\n (candidate.documentChanges === undefined || candidate.documentChanges.every((change) => {\n if (Is.string(change.kind)) {\n return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);\n }\n else {\n return TextDocumentEdit.is(change);\n }\n }));\n }\n WorkspaceEdit.is = is;\n})(WorkspaceEdit || (WorkspaceEdit = {}));\nclass TextEditChangeImpl {\n constructor(edits, changeAnnotations) {\n this.edits = edits;\n this.changeAnnotations = changeAnnotations;\n }\n insert(position, newText, annotation) {\n let edit;\n let id;\n if (annotation === undefined) {\n edit = TextEdit.insert(position, newText);\n }\n else if (ChangeAnnotationIdentifier.is(annotation)) {\n id = annotation;\n edit = AnnotatedTextEdit.insert(position, newText, annotation);\n }\n else {\n this.assertChangeAnnotations(this.changeAnnotations);\n id = this.changeAnnotations.manage(annotation);\n edit = AnnotatedTextEdit.insert(position, newText, id);\n }\n this.edits.push(edit);\n if (id !== undefined) {\n return id;\n }\n }\n replace(range, newText, annotation) {\n let edit;\n let id;\n if (annotation === undefined) {\n edit = TextEdit.replace(range, newText);\n }\n else if (ChangeAnnotationIdentifier.is(annotation)) {\n id = annotation;\n edit = AnnotatedTextEdit.replace(range, newText, annotation);\n }\n else {\n this.assertChangeAnnotations(this.changeAnnotations);\n id = this.changeAnnotations.manage(annotation);\n edit = AnnotatedTextEdit.replace(range, newText, id);\n }\n this.edits.push(edit);\n if (id !== undefined) {\n return id;\n }\n }\n delete(range, annotation) {\n let edit;\n let id;\n if (annotation === undefined) {\n edit = TextEdit.del(range);\n }\n else if (ChangeAnnotationIdentifier.is(annotation)) {\n id = annotation;\n edit = AnnotatedTextEdit.del(range, annotation);\n }\n else {\n this.assertChangeAnnotations(this.changeAnnotations);\n id = this.changeAnnotations.manage(annotation);\n edit = AnnotatedTextEdit.del(range, id);\n }\n this.edits.push(edit);\n if (id !== undefined) {\n return id;\n }\n }\n add(edit) {\n this.edits.push(edit);\n }\n all() {\n return this.edits;\n }\n clear() {\n this.edits.splice(0, this.edits.length);\n }\n assertChangeAnnotations(value) {\n if (value === undefined) {\n throw new Error(`Text edit change is not configured to manage change annotations.`);\n }\n }\n}\n/**\n * A helper class\n */\nclass ChangeAnnotations {\n constructor(annotations) {\n this._annotations = annotations === undefined ? Object.create(null) : annotations;\n this._counter = 0;\n this._size = 0;\n }\n all() {\n return this._annotations;\n }\n get size() {\n return this._size;\n }\n manage(idOrAnnotation, annotation) {\n let id;\n if (ChangeAnnotationIdentifier.is(idOrAnnotation)) {\n id = idOrAnnotation;\n }\n else {\n id = this.nextId();\n annotation = idOrAnnotation;\n }\n if (this._annotations[id] !== undefined) {\n throw new Error(`Id ${id} is already in use.`);\n }\n if (annotation === undefined) {\n throw new Error(`No annotation provided for id ${id}`);\n }\n this._annotations[id] = annotation;\n this._size++;\n return id;\n }\n nextId() {\n this._counter++;\n return this._counter.toString();\n }\n}\n/**\n * A workspace change helps constructing changes to a workspace.\n */\nexport class WorkspaceChange {\n constructor(workspaceEdit) {\n this._textEditChanges = Object.create(null);\n if (workspaceEdit !== undefined) {\n this._workspaceEdit = workspaceEdit;\n if (workspaceEdit.documentChanges) {\n this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations);\n workspaceEdit.changeAnnotations = this._changeAnnotations.all();\n workspaceEdit.documentChanges.forEach((change) => {\n if (TextDocumentEdit.is(change)) {\n const textEditChange = new TextEditChangeImpl(change.edits, this._changeAnnotations);\n this._textEditChanges[change.textDocument.uri] = textEditChange;\n }\n });\n }\n else if (workspaceEdit.changes) {\n Object.keys(workspaceEdit.changes).forEach((key) => {\n const textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);\n this._textEditChanges[key] = textEditChange;\n });\n }\n }\n else {\n this._workspaceEdit = {};\n }\n }\n /**\n * Returns the underlying {@link WorkspaceEdit} literal\n * use to be returned from a workspace edit operation like rename.\n */\n get edit() {\n this.initDocumentChanges();\n if (this._changeAnnotations !== undefined) {\n if (this._changeAnnotations.size === 0) {\n this._workspaceEdit.changeAnnotations = undefined;\n }\n else {\n this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();\n }\n }\n return this._workspaceEdit;\n }\n getTextEditChange(key) {\n if (OptionalVersionedTextDocumentIdentifier.is(key)) {\n this.initDocumentChanges();\n if (this._workspaceEdit.documentChanges === undefined) {\n throw new Error('Workspace edit is not configured for document changes.');\n }\n const textDocument = { uri: key.uri, version: key.version };\n let result = this._textEditChanges[textDocument.uri];\n if (!result) {\n const edits = [];\n const textDocumentEdit = {\n textDocument,\n edits\n };\n this._workspaceEdit.documentChanges.push(textDocumentEdit);\n result = new TextEditChangeImpl(edits, this._changeAnnotations);\n this._textEditChanges[textDocument.uri] = result;\n }\n return result;\n }\n else {\n this.initChanges();\n if (this._workspaceEdit.changes === undefined) {\n throw new Error('Workspace edit is not configured for normal text edit changes.');\n }\n let result = this._textEditChanges[key];\n if (!result) {\n let edits = [];\n this._workspaceEdit.changes[key] = edits;\n result = new TextEditChangeImpl(edits);\n this._textEditChanges[key] = result;\n }\n return result;\n }\n }\n initDocumentChanges() {\n if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) {\n this._changeAnnotations = new ChangeAnnotations();\n this._workspaceEdit.documentChanges = [];\n this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();\n }\n }\n initChanges() {\n if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) {\n this._workspaceEdit.changes = Object.create(null);\n }\n }\n createFile(uri, optionsOrAnnotation, options) {\n this.initDocumentChanges();\n if (this._workspaceEdit.documentChanges === undefined) {\n throw new Error('Workspace edit is not configured for document changes.');\n }\n let annotation;\n if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {\n annotation = optionsOrAnnotation;\n }\n else {\n options = optionsOrAnnotation;\n }\n let operation;\n let id;\n if (annotation === undefined) {\n operation = CreateFile.create(uri, options);\n }\n else {\n id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);\n operation = CreateFile.create(uri, options, id);\n }\n this._workspaceEdit.documentChanges.push(operation);\n if (id !== undefined) {\n return id;\n }\n }\n renameFile(oldUri, newUri, optionsOrAnnotation, options) {\n this.initDocumentChanges();\n if (this._workspaceEdit.documentChanges === undefined) {\n throw new Error('Workspace edit is not configured for document changes.');\n }\n let annotation;\n if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {\n annotation = optionsOrAnnotation;\n }\n else {\n options = optionsOrAnnotation;\n }\n let operation;\n let id;\n if (annotation === undefined) {\n operation = RenameFile.create(oldUri, newUri, options);\n }\n else {\n id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);\n operation = RenameFile.create(oldUri, newUri, options, id);\n }\n this._workspaceEdit.documentChanges.push(operation);\n if (id !== undefined) {\n return id;\n }\n }\n deleteFile(uri, optionsOrAnnotation, options) {\n this.initDocumentChanges();\n if (this._workspaceEdit.documentChanges === undefined) {\n throw new Error('Workspace edit is not configured for document changes.');\n }\n let annotation;\n if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {\n annotation = optionsOrAnnotation;\n }\n else {\n options = optionsOrAnnotation;\n }\n let operation;\n let id;\n if (annotation === undefined) {\n operation = DeleteFile.create(uri, options);\n }\n else {\n id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);\n operation = DeleteFile.create(uri, options, id);\n }\n this._workspaceEdit.documentChanges.push(operation);\n if (id !== undefined) {\n return id;\n }\n }\n}\n/**\n * The TextDocumentIdentifier namespace provides helper functions to work with\n * {@link TextDocumentIdentifier} literals.\n */\nexport var TextDocumentIdentifier;\n(function (TextDocumentIdentifier) {\n /**\n * Creates a new TextDocumentIdentifier literal.\n * @param uri The document's uri.\n */\n function create(uri) {\n return { uri };\n }\n TextDocumentIdentifier.create = create;\n /**\n * Checks whether the given literal conforms to the {@link TextDocumentIdentifier} interface.\n */\n function is(value) {\n let candidate = value;\n return Is.defined(candidate) && Is.string(candidate.uri);\n }\n TextDocumentIdentifier.is = is;\n})(TextDocumentIdentifier || (TextDocumentIdentifier = {}));\n/**\n * The VersionedTextDocumentIdentifier namespace provides helper functions to work with\n * {@link VersionedTextDocumentIdentifier} literals.\n */\nexport var VersionedTextDocumentIdentifier;\n(function (VersionedTextDocumentIdentifier) {\n /**\n * Creates a new VersionedTextDocumentIdentifier literal.\n * @param uri The document's uri.\n * @param version The document's version.\n */\n function create(uri, version) {\n return { uri, version };\n }\n VersionedTextDocumentIdentifier.create = create;\n /**\n * Checks whether the given literal conforms to the {@link VersionedTextDocumentIdentifier} interface.\n */\n function is(value) {\n let candidate = value;\n return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version);\n }\n VersionedTextDocumentIdentifier.is = is;\n})(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));\n/**\n * The OptionalVersionedTextDocumentIdentifier namespace provides helper functions to work with\n * {@link OptionalVersionedTextDocumentIdentifier} literals.\n */\nexport var OptionalVersionedTextDocumentIdentifier;\n(function (OptionalVersionedTextDocumentIdentifier) {\n /**\n * Creates a new OptionalVersionedTextDocumentIdentifier literal.\n * @param uri The document's uri.\n * @param version The document's version.\n */\n function create(uri, version) {\n return { uri, version };\n }\n OptionalVersionedTextDocumentIdentifier.create = create;\n /**\n * Checks whether the given literal conforms to the {@link OptionalVersionedTextDocumentIdentifier} interface.\n */\n function is(value) {\n let candidate = value;\n return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version));\n }\n OptionalVersionedTextDocumentIdentifier.is = is;\n})(OptionalVersionedTextDocumentIdentifier || (OptionalVersionedTextDocumentIdentifier = {}));\n/**\n * The TextDocumentItem namespace provides helper functions to work with\n * {@link TextDocumentItem} literals.\n */\nexport var TextDocumentItem;\n(function (TextDocumentItem) {\n /**\n * Creates a new TextDocumentItem literal.\n * @param uri The document's uri.\n * @param languageId The document's language identifier.\n * @param version The document's version number.\n * @param text The document's text.\n */\n function create(uri, languageId, version, text) {\n return { uri, languageId, version, text };\n }\n TextDocumentItem.create = create;\n /**\n * Checks whether the given literal conforms to the {@link TextDocumentItem} interface.\n */\n function is(value) {\n let candidate = value;\n return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text);\n }\n TextDocumentItem.is = is;\n})(TextDocumentItem || (TextDocumentItem = {}));\n/**\n * Describes the content type that a client supports in various\n * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.\n *\n * Please note that `MarkupKinds` must not start with a `$`. This kinds\n * are reserved for internal usage.\n */\nexport var MarkupKind;\n(function (MarkupKind) {\n /**\n * Plain text is supported as a content format\n */\n MarkupKind.PlainText = 'plaintext';\n /**\n * Markdown is supported as a content format\n */\n MarkupKind.Markdown = 'markdown';\n /**\n * Checks whether the given value is a value of the {@link MarkupKind} type.\n */\n function is(value) {\n const candidate = value;\n return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;\n }\n MarkupKind.is = is;\n})(MarkupKind || (MarkupKind = {}));\nexport var MarkupContent;\n(function (MarkupContent) {\n /**\n * Checks whether the given value conforms to the {@link MarkupContent} interface.\n */\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);\n }\n MarkupContent.is = is;\n})(MarkupContent || (MarkupContent = {}));\n/**\n * The kind of a completion entry.\n */\nexport var CompletionItemKind;\n(function (CompletionItemKind) {\n CompletionItemKind.Text = 1;\n CompletionItemKind.Method = 2;\n CompletionItemKind.Function = 3;\n CompletionItemKind.Constructor = 4;\n CompletionItemKind.Field = 5;\n CompletionItemKind.Variable = 6;\n CompletionItemKind.Class = 7;\n CompletionItemKind.Interface = 8;\n CompletionItemKind.Module = 9;\n CompletionItemKind.Property = 10;\n CompletionItemKind.Unit = 11;\n CompletionItemKind.Value = 12;\n CompletionItemKind.Enum = 13;\n CompletionItemKind.Keyword = 14;\n CompletionItemKind.Snippet = 15;\n CompletionItemKind.Color = 16;\n CompletionItemKind.File = 17;\n CompletionItemKind.Reference = 18;\n CompletionItemKind.Folder = 19;\n CompletionItemKind.EnumMember = 20;\n CompletionItemKind.Constant = 21;\n CompletionItemKind.Struct = 22;\n CompletionItemKind.Event = 23;\n CompletionItemKind.Operator = 24;\n CompletionItemKind.TypeParameter = 25;\n})(CompletionItemKind || (CompletionItemKind = {}));\n/**\n * Defines whether the insert text in a completion item should be interpreted as\n * plain text or a snippet.\n */\nexport var InsertTextFormat;\n(function (InsertTextFormat) {\n /**\n * The primary text to be inserted is treated as a plain string.\n */\n InsertTextFormat.PlainText = 1;\n /**\n * The primary text to be inserted is treated as a snippet.\n *\n * A snippet can define tab stops and placeholders with `$1`, `$2`\n * and `${3:foo}`. `$0` defines the final tab stop, it defaults to\n * the end of the snippet. Placeholders with equal identifiers are linked,\n * that is typing in one will update others too.\n *\n * See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax\n */\n InsertTextFormat.Snippet = 2;\n})(InsertTextFormat || (InsertTextFormat = {}));\n/**\n * Completion item tags are extra annotations that tweak the rendering of a completion\n * item.\n *\n * @since 3.15.0\n */\nexport var CompletionItemTag;\n(function (CompletionItemTag) {\n /**\n * Render a completion as obsolete, usually using a strike-out.\n */\n CompletionItemTag.Deprecated = 1;\n})(CompletionItemTag || (CompletionItemTag = {}));\n/**\n * The InsertReplaceEdit namespace provides functions to deal with insert / replace edits.\n *\n * @since 3.16.0\n */\nexport var InsertReplaceEdit;\n(function (InsertReplaceEdit) {\n /**\n * Creates a new insert / replace edit\n */\n function create(newText, insert, replace) {\n return { newText, insert, replace };\n }\n InsertReplaceEdit.create = create;\n /**\n * Checks whether the given literal conforms to the {@link InsertReplaceEdit} interface.\n */\n function is(value) {\n const candidate = value;\n return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace);\n }\n InsertReplaceEdit.is = is;\n})(InsertReplaceEdit || (InsertReplaceEdit = {}));\n/**\n * How whitespace and indentation is handled during completion\n * item insertion.\n *\n * @since 3.16.0\n */\nexport var InsertTextMode;\n(function (InsertTextMode) {\n /**\n * The insertion or replace strings is taken as it is. If the\n * value is multi line the lines below the cursor will be\n * inserted using the indentation defined in the string value.\n * The client will not apply any kind of adjustments to the\n * string.\n */\n InsertTextMode.asIs = 1;\n /**\n * The editor adjusts leading whitespace of new lines so that\n * they match the indentation up to the cursor of the line for\n * which the item is accepted.\n *\n * Consider a line like this: <2tabs><3tabs>foo. Accepting a\n * multi line completion item is indented using 2 tabs and all\n * following lines inserted will be indented using 2 tabs as well.\n */\n InsertTextMode.adjustIndentation = 2;\n})(InsertTextMode || (InsertTextMode = {}));\nexport var CompletionItemLabelDetails;\n(function (CompletionItemLabelDetails) {\n function is(value) {\n const candidate = value;\n return candidate && (Is.string(candidate.detail) || candidate.detail === undefined) &&\n (Is.string(candidate.description) || candidate.description === undefined);\n }\n CompletionItemLabelDetails.is = is;\n})(CompletionItemLabelDetails || (CompletionItemLabelDetails = {}));\n/**\n * The CompletionItem namespace provides functions to deal with\n * completion items.\n */\nexport var CompletionItem;\n(function (CompletionItem) {\n /**\n * Create a completion item and seed it with a label.\n * @param label The completion item's label\n */\n function create(label) {\n return { label };\n }\n CompletionItem.create = create;\n})(CompletionItem || (CompletionItem = {}));\n/**\n * The CompletionList namespace provides functions to deal with\n * completion lists.\n */\nexport var CompletionList;\n(function (CompletionList) {\n /**\n * Creates a new completion list.\n *\n * @param items The completion items.\n * @param isIncomplete The list is not complete.\n */\n function create(items, isIncomplete) {\n return { items: items ? items : [], isIncomplete: !!isIncomplete };\n }\n CompletionList.create = create;\n})(CompletionList || (CompletionList = {}));\nexport var MarkedString;\n(function (MarkedString) {\n /**\n * Creates a marked string from plain text.\n *\n * @param plainText The plain text.\n */\n function fromPlainText(plainText) {\n return plainText.replace(/[\\\\`*_{}[\\]()#+\\-.!]/g, '\\\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash\n }\n MarkedString.fromPlainText = fromPlainText;\n /**\n * Checks whether the given value conforms to the {@link MarkedString} type.\n */\n function is(value) {\n const candidate = value;\n return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));\n }\n MarkedString.is = is;\n})(MarkedString || (MarkedString = {}));\nexport var Hover;\n(function (Hover) {\n /**\n * Checks whether the given value conforms to the {@link Hover} interface.\n */\n function is(value) {\n let candidate = value;\n return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||\n MarkedString.is(candidate.contents) ||\n Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === undefined || Range.is(value.range));\n }\n Hover.is = is;\n})(Hover || (Hover = {}));\n/**\n * The ParameterInformation namespace provides helper functions to work with\n * {@link ParameterInformation} literals.\n */\nexport var ParameterInformation;\n(function (ParameterInformation) {\n /**\n * Creates a new parameter information literal.\n *\n * @param label A label string.\n * @param documentation A doc string.\n */\n function create(label, documentation) {\n return documentation ? { label, documentation } : { label };\n }\n ParameterInformation.create = create;\n})(ParameterInformation || (ParameterInformation = {}));\n/**\n * The SignatureInformation namespace provides helper functions to work with\n * {@link SignatureInformation} literals.\n */\nexport var SignatureInformation;\n(function (SignatureInformation) {\n function create(label, documentation, ...parameters) {\n let result = { label };\n if (Is.defined(documentation)) {\n result.documentation = documentation;\n }\n if (Is.defined(parameters)) {\n result.parameters = parameters;\n }\n else {\n result.parameters = [];\n }\n return result;\n }\n SignatureInformation.create = create;\n})(SignatureInformation || (SignatureInformation = {}));\n/**\n * A document highlight kind.\n */\nexport var DocumentHighlightKind;\n(function (DocumentHighlightKind) {\n /**\n * A textual occurrence.\n */\n DocumentHighlightKind.Text = 1;\n /**\n * Read-access of a symbol, like reading a variable.\n */\n DocumentHighlightKind.Read = 2;\n /**\n * Write-access of a symbol, like writing to a variable.\n */\n DocumentHighlightKind.Write = 3;\n})(DocumentHighlightKind || (DocumentHighlightKind = {}));\n/**\n * DocumentHighlight namespace to provide helper functions to work with\n * {@link DocumentHighlight} literals.\n */\nexport var DocumentHighlight;\n(function (DocumentHighlight) {\n /**\n * Create a DocumentHighlight object.\n * @param range The range the highlight applies to.\n * @param kind The highlight kind\n */\n function create(range, kind) {\n let result = { range };\n if (Is.number(kind)) {\n result.kind = kind;\n }\n return result;\n }\n DocumentHighlight.create = create;\n})(DocumentHighlight || (DocumentHighlight = {}));\n/**\n * A symbol kind.\n */\nexport var SymbolKind;\n(function (SymbolKind) {\n SymbolKind.File = 1;\n SymbolKind.Module = 2;\n SymbolKind.Namespace = 3;\n SymbolKind.Package = 4;\n SymbolKind.Class = 5;\n SymbolKind.Method = 6;\n SymbolKind.Property = 7;\n SymbolKind.Field = 8;\n SymbolKind.Constructor = 9;\n SymbolKind.Enum = 10;\n SymbolKind.Interface = 11;\n SymbolKind.Function = 12;\n SymbolKind.Variable = 13;\n SymbolKind.Constant = 14;\n SymbolKind.String = 15;\n SymbolKind.Number = 16;\n SymbolKind.Boolean = 17;\n SymbolKind.Array = 18;\n SymbolKind.Object = 19;\n SymbolKind.Key = 20;\n SymbolKind.Null = 21;\n SymbolKind.EnumMember = 22;\n SymbolKind.Struct = 23;\n SymbolKind.Event = 24;\n SymbolKind.Operator = 25;\n SymbolKind.TypeParameter = 26;\n})(SymbolKind || (SymbolKind = {}));\n/**\n * Symbol tags are extra annotations that tweak the rendering of a symbol.\n *\n * @since 3.16\n */\nexport var SymbolTag;\n(function (SymbolTag) {\n /**\n * Render a symbol as obsolete, usually using a strike-out.\n */\n SymbolTag.Deprecated = 1;\n})(SymbolTag || (SymbolTag = {}));\nexport var SymbolInformation;\n(function (SymbolInformation) {\n /**\n * Creates a new symbol information literal.\n *\n * @param name The name of the symbol.\n * @param kind The kind of the symbol.\n * @param range The range of the location of the symbol.\n * @param uri The resource of the location of symbol.\n * @param containerName The name of the symbol containing the symbol.\n */\n function create(name, kind, range, uri, containerName) {\n let result = {\n name,\n kind,\n location: { uri, range }\n };\n if (containerName) {\n result.containerName = containerName;\n }\n return result;\n }\n SymbolInformation.create = create;\n})(SymbolInformation || (SymbolInformation = {}));\nexport var WorkspaceSymbol;\n(function (WorkspaceSymbol) {\n /**\n * Create a new workspace symbol.\n *\n * @param name The name of the symbol.\n * @param kind The kind of the symbol.\n * @param uri The resource of the location of the symbol.\n * @param range An options range of the location.\n * @returns A WorkspaceSymbol.\n */\n function create(name, kind, uri, range) {\n return range !== undefined\n ? { name, kind, location: { uri, range } }\n : { name, kind, location: { uri } };\n }\n WorkspaceSymbol.create = create;\n})(WorkspaceSymbol || (WorkspaceSymbol = {}));\nexport var DocumentSymbol;\n(function (DocumentSymbol) {\n /**\n * Creates a new symbol information literal.\n *\n * @param name The name of the symbol.\n * @param detail The detail of the symbol.\n * @param kind The kind of the symbol.\n * @param range The range of the symbol.\n * @param selectionRange The selectionRange of the symbol.\n * @param children Children of the symbol.\n */\n function create(name, detail, kind, range, selectionRange, children) {\n let result = {\n name,\n detail,\n kind,\n range,\n selectionRange\n };\n if (children !== undefined) {\n result.children = children;\n }\n return result;\n }\n DocumentSymbol.create = create;\n /**\n * Checks whether the given literal conforms to the {@link DocumentSymbol} interface.\n */\n function is(value) {\n let candidate = value;\n return candidate &&\n Is.string(candidate.name) && Is.number(candidate.kind) &&\n Range.is(candidate.range) && Range.is(candidate.selectionRange) &&\n (candidate.detail === undefined || Is.string(candidate.detail)) &&\n (candidate.deprecated === undefined || Is.boolean(candidate.deprecated)) &&\n (candidate.children === undefined || Array.isArray(candidate.children)) &&\n (candidate.tags === undefined || Array.isArray(candidate.tags));\n }\n DocumentSymbol.is = is;\n})(DocumentSymbol || (DocumentSymbol = {}));\n/**\n * A set of predefined code action kinds\n */\nexport var CodeActionKind;\n(function (CodeActionKind) {\n /**\n * Empty kind.\n */\n CodeActionKind.Empty = '';\n /**\n * Base kind for quickfix actions: 'quickfix'\n */\n CodeActionKind.QuickFix = 'quickfix';\n /**\n * Base kind for refactoring actions: 'refactor'\n */\n CodeActionKind.Refactor = 'refactor';\n /**\n * Base kind for refactoring extraction actions: 'refactor.extract'\n *\n * Example extract actions:\n *\n * - Extract method\n * - Extract function\n * - Extract variable\n * - Extract interface from class\n * - ...\n */\n CodeActionKind.RefactorExtract = 'refactor.extract';\n /**\n * Base kind for refactoring inline actions: 'refactor.inline'\n *\n * Example inline actions:\n *\n * - Inline function\n * - Inline variable\n * - Inline constant\n * - ...\n */\n CodeActionKind.RefactorInline = 'refactor.inline';\n /**\n * Base kind for refactoring rewrite actions: 'refactor.rewrite'\n *\n * Example rewrite actions:\n *\n * - Convert JavaScript function to class\n * - Add or remove parameter\n * - Encapsulate field\n * - Make method static\n * - Move method to base class\n * - ...\n */\n CodeActionKind.RefactorRewrite = 'refactor.rewrite';\n /**\n * Base kind for source actions: `source`\n *\n * Source code actions apply to the entire file.\n */\n CodeActionKind.Source = 'source';\n /**\n * Base kind for an organize imports source action: `source.organizeImports`\n */\n CodeActionKind.SourceOrganizeImports = 'source.organizeImports';\n /**\n * Base kind for auto-fix source actions: `source.fixAll`.\n *\n * Fix all actions automatically fix errors that have a clear fix that do not require user input.\n * They should not suppress errors or perform unsafe fixes such as generating new types or classes.\n *\n * @since 3.15.0\n */\n CodeActionKind.SourceFixAll = 'source.fixAll';\n})(CodeActionKind || (CodeActionKind = {}));\n/**\n * The reason why code actions were requested.\n *\n * @since 3.17.0\n */\nexport var CodeActionTriggerKind;\n(function (CodeActionTriggerKind) {\n /**\n * Code actions were explicitly requested by the user or by an extension.\n */\n CodeActionTriggerKind.Invoked = 1;\n /**\n * Code actions were requested automatically.\n *\n * This typically happens when current selection in a file changes, but can\n * also be triggered when file content changes.\n */\n CodeActionTriggerKind.Automatic = 2;\n})(CodeActionTriggerKind || (CodeActionTriggerKind = {}));\n/**\n * The CodeActionContext namespace provides helper functions to work with\n * {@link CodeActionContext} literals.\n */\nexport var CodeActionContext;\n(function (CodeActionContext) {\n /**\n * Creates a new CodeActionContext literal.\n */\n function create(diagnostics, only, triggerKind) {\n let result = { diagnostics };\n if (only !== undefined && only !== null) {\n result.only = only;\n }\n if (triggerKind !== undefined && triggerKind !== null) {\n result.triggerKind = triggerKind;\n }\n return result;\n }\n CodeActionContext.create = create;\n /**\n * Checks whether the given literal conforms to the {@link CodeActionContext} interface.\n */\n function is(value) {\n let candidate = value;\n return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is)\n && (candidate.only === undefined || Is.typedArray(candidate.only, Is.string))\n && (candidate.triggerKind === undefined || candidate.triggerKind === CodeActionTriggerKind.Invoked || candidate.triggerKind === CodeActionTriggerKind.Automatic);\n }\n CodeActionContext.is = is;\n})(CodeActionContext || (CodeActionContext = {}));\nexport var CodeAction;\n(function (CodeAction) {\n function create(title, kindOrCommandOrEdit, kind) {\n let result = { title };\n let checkKind = true;\n if (typeof kindOrCommandOrEdit === 'string') {\n checkKind = false;\n result.kind = kindOrCommandOrEdit;\n }\n else if (Command.is(kindOrCommandOrEdit)) {\n result.command = kindOrCommandOrEdit;\n }\n else {\n result.edit = kindOrCommandOrEdit;\n }\n if (checkKind && kind !== undefined) {\n result.kind = kind;\n }\n return result;\n }\n CodeAction.create = create;\n function is(value) {\n let candidate = value;\n return candidate && Is.string(candidate.title) &&\n (candidate.diagnostics === undefined || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&\n (candidate.kind === undefined || Is.string(candidate.kind)) &&\n (candidate.edit !== undefined || candidate.command !== undefined) &&\n (candidate.command === undefined || Command.is(candidate.command)) &&\n (candidate.isPreferred === undefined || Is.boolean(candidate.isPreferred)) &&\n (candidate.edit === undefined || WorkspaceEdit.is(candidate.edit));\n }\n CodeAction.is = is;\n})(CodeAction || (CodeAction = {}));\n/**\n * The CodeLens namespace provides helper functions to work with\n * {@link CodeLens} literals.\n */\nexport var CodeLens;\n(function (CodeLens) {\n /**\n * Creates a new CodeLens literal.\n */\n function create(range, data) {\n let result = { range };\n if (Is.defined(data)) {\n result.data = data;\n }\n return result;\n }\n CodeLens.create = create;\n /**\n * Checks whether the given literal conforms to the {@link CodeLens} interface.\n */\n function is(value) {\n let candidate = value;\n return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));\n }\n CodeLens.is = is;\n})(CodeLens || (CodeLens = {}));\n/**\n * The FormattingOptions namespace provides helper functions to work with\n * {@link FormattingOptions} literals.\n */\nexport var FormattingOptions;\n(function (FormattingOptions) {\n /**\n * Creates a new FormattingOptions literal.\n */\n function create(tabSize, insertSpaces) {\n return { tabSize, insertSpaces };\n }\n FormattingOptions.create = create;\n /**\n * Checks whether the given literal conforms to the {@link FormattingOptions} interface.\n */\n function is(value) {\n let candidate = value;\n return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces);\n }\n FormattingOptions.is = is;\n})(FormattingOptions || (FormattingOptions = {}));\n/**\n * The DocumentLink namespace provides helper functions to work with\n * {@link DocumentLink} literals.\n */\nexport var DocumentLink;\n(function (DocumentLink) {\n /**\n * Creates a new DocumentLink literal.\n */\n function create(range, target, data) {\n return { range, target, data };\n }\n DocumentLink.create = create;\n /**\n * Checks whether the given literal conforms to the {@link DocumentLink} interface.\n */\n function is(value) {\n let candidate = value;\n return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));\n }\n DocumentLink.is = is;\n})(DocumentLink || (DocumentLink = {}));\n/**\n * The SelectionRange namespace provides helper function to work with\n * SelectionRange literals.\n */\nexport var SelectionRange;\n(function (SelectionRange) {\n /**\n * Creates a new SelectionRange\n * @param range the range.\n * @param parent an optional parent.\n */\n function create(range, parent) {\n return { range, parent };\n }\n SelectionRange.create = create;\n function is(value) {\n let candidate = value;\n return Is.objectLiteral(candidate) && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));\n }\n SelectionRange.is = is;\n})(SelectionRange || (SelectionRange = {}));\n/**\n * A set of predefined token types. This set is not fixed\n * an clients can specify additional token types via the\n * corresponding client capabilities.\n *\n * @since 3.16.0\n */\nexport var SemanticTokenTypes;\n(function (SemanticTokenTypes) {\n SemanticTokenTypes[\"namespace\"] = \"namespace\";\n /**\n * Represents a generic type. Acts as a fallback for types which can't be mapped to\n * a specific type like class or enum.\n */\n SemanticTokenTypes[\"type\"] = \"type\";\n SemanticTokenTypes[\"class\"] = \"class\";\n SemanticTokenTypes[\"enum\"] = \"enum\";\n SemanticTokenTypes[\"interface\"] = \"interface\";\n SemanticTokenTypes[\"struct\"] = \"struct\";\n SemanticTokenTypes[\"typeParameter\"] = \"typeParameter\";\n SemanticTokenTypes[\"parameter\"] = \"parameter\";\n SemanticTokenTypes[\"variable\"] = \"variable\";\n SemanticTokenTypes[\"property\"] = \"property\";\n SemanticTokenTypes[\"enumMember\"] = \"enumMember\";\n SemanticTokenTypes[\"event\"] = \"event\";\n SemanticTokenTypes[\"function\"] = \"function\";\n SemanticTokenTypes[\"method\"] = \"method\";\n SemanticTokenTypes[\"macro\"] = \"macro\";\n SemanticTokenTypes[\"keyword\"] = \"keyword\";\n SemanticTokenTypes[\"modifier\"] = \"modifier\";\n SemanticTokenTypes[\"comment\"] = \"comment\";\n SemanticTokenTypes[\"string\"] = \"string\";\n SemanticTokenTypes[\"number\"] = \"number\";\n SemanticTokenTypes[\"regexp\"] = \"regexp\";\n SemanticTokenTypes[\"operator\"] = \"operator\";\n /**\n * @since 3.17.0\n */\n SemanticTokenTypes[\"decorator\"] = \"decorator\";\n})(SemanticTokenTypes || (SemanticTokenTypes = {}));\n/**\n * A set of predefined token modifiers. This set is not fixed\n * an clients can specify additional token types via the\n * corresponding client capabilities.\n *\n * @since 3.16.0\n */\nexport var SemanticTokenModifiers;\n(function (SemanticTokenModifiers) {\n SemanticTokenModifiers[\"declaration\"] = \"declaration\";\n SemanticTokenModifiers[\"definition\"] = \"definition\";\n SemanticTokenModifiers[\"readonly\"] = \"readonly\";\n SemanticTokenModifiers[\"static\"] = \"static\";\n SemanticTokenModifiers[\"deprecated\"] = \"deprecated\";\n SemanticTokenModifiers[\"abstract\"] = \"abstract\";\n SemanticTokenModifiers[\"async\"] = \"async\";\n SemanticTokenModifiers[\"modification\"] = \"modification\";\n SemanticTokenModifiers[\"documentation\"] = \"documentation\";\n SemanticTokenModifiers[\"defaultLibrary\"] = \"defaultLibrary\";\n})(SemanticTokenModifiers || (SemanticTokenModifiers = {}));\n/**\n * @since 3.16.0\n */\nexport var SemanticTokens;\n(function (SemanticTokens) {\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate) && (candidate.resultId === undefined || typeof candidate.resultId === 'string') &&\n Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number');\n }\n SemanticTokens.is = is;\n})(SemanticTokens || (SemanticTokens = {}));\n/**\n * The InlineValueText namespace provides functions to deal with InlineValueTexts.\n *\n * @since 3.17.0\n */\nexport var InlineValueText;\n(function (InlineValueText) {\n /**\n * Creates a new InlineValueText literal.\n */\n function create(range, text) {\n return { range, text };\n }\n InlineValueText.create = create;\n function is(value) {\n const candidate = value;\n return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.string(candidate.text);\n }\n InlineValueText.is = is;\n})(InlineValueText || (InlineValueText = {}));\n/**\n * The InlineValueVariableLookup namespace provides functions to deal with InlineValueVariableLookups.\n *\n * @since 3.17.0\n */\nexport var InlineValueVariableLookup;\n(function (InlineValueVariableLookup) {\n /**\n * Creates a new InlineValueText literal.\n */\n function create(range, variableName, caseSensitiveLookup) {\n return { range, variableName, caseSensitiveLookup };\n }\n InlineValueVariableLookup.create = create;\n function is(value) {\n const candidate = value;\n return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.boolean(candidate.caseSensitiveLookup)\n && (Is.string(candidate.variableName) || candidate.variableName === undefined);\n }\n InlineValueVariableLookup.is = is;\n})(InlineValueVariableLookup || (InlineValueVariableLookup = {}));\n/**\n * The InlineValueEvaluatableExpression namespace provides functions to deal with InlineValueEvaluatableExpression.\n *\n * @since 3.17.0\n */\nexport var InlineValueEvaluatableExpression;\n(function (InlineValueEvaluatableExpression) {\n /**\n * Creates a new InlineValueEvaluatableExpression literal.\n */\n function create(range, expression) {\n return { range, expression };\n }\n InlineValueEvaluatableExpression.create = create;\n function is(value) {\n const candidate = value;\n return candidate !== undefined && candidate !== null && Range.is(candidate.range)\n && (Is.string(candidate.expression) || candidate.expression === undefined);\n }\n InlineValueEvaluatableExpression.is = is;\n})(InlineValueEvaluatableExpression || (InlineValueEvaluatableExpression = {}));\n/**\n * The InlineValueContext namespace provides helper functions to work with\n * {@link InlineValueContext} literals.\n *\n * @since 3.17.0\n */\nexport var InlineValueContext;\n(function (InlineValueContext) {\n /**\n * Creates a new InlineValueContext literal.\n */\n function create(frameId, stoppedLocation) {\n return { frameId, stoppedLocation };\n }\n InlineValueContext.create = create;\n /**\n * Checks whether the given literal conforms to the {@link InlineValueContext} interface.\n */\n function is(value) {\n const candidate = value;\n return Is.defined(candidate) && Range.is(value.stoppedLocation);\n }\n InlineValueContext.is = is;\n})(InlineValueContext || (InlineValueContext = {}));\n/**\n * Inlay hint kinds.\n *\n * @since 3.17.0\n */\nexport var InlayHintKind;\n(function (InlayHintKind) {\n /**\n * An inlay hint that for a type annotation.\n */\n InlayHintKind.Type = 1;\n /**\n * An inlay hint that is for a parameter.\n */\n InlayHintKind.Parameter = 2;\n function is(value) {\n return value === 1 || value === 2;\n }\n InlayHintKind.is = is;\n})(InlayHintKind || (InlayHintKind = {}));\nexport var InlayHintLabelPart;\n(function (InlayHintLabelPart) {\n function create(value) {\n return { value };\n }\n InlayHintLabelPart.create = create;\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate)\n && (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip))\n && (candidate.location === undefined || Location.is(candidate.location))\n && (candidate.command === undefined || Command.is(candidate.command));\n }\n InlayHintLabelPart.is = is;\n})(InlayHintLabelPart || (InlayHintLabelPart = {}));\nexport var InlayHint;\n(function (InlayHint) {\n function create(position, label, kind) {\n const result = { position, label };\n if (kind !== undefined) {\n result.kind = kind;\n }\n return result;\n }\n InlayHint.create = create;\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate) && Position.is(candidate.position)\n && (Is.string(candidate.label) || Is.typedArray(candidate.label, InlayHintLabelPart.is))\n && (candidate.kind === undefined || InlayHintKind.is(candidate.kind))\n && (candidate.textEdits === undefined) || Is.typedArray(candidate.textEdits, TextEdit.is)\n && (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip))\n && (candidate.paddingLeft === undefined || Is.boolean(candidate.paddingLeft))\n && (candidate.paddingRight === undefined || Is.boolean(candidate.paddingRight));\n }\n InlayHint.is = is;\n})(InlayHint || (InlayHint = {}));\nexport var StringValue;\n(function (StringValue) {\n function createSnippet(value) {\n return { kind: 'snippet', value };\n }\n StringValue.createSnippet = createSnippet;\n})(StringValue || (StringValue = {}));\nexport var InlineCompletionItem;\n(function (InlineCompletionItem) {\n function create(insertText, filterText, range, command) {\n return { insertText, filterText, range, command };\n }\n InlineCompletionItem.create = create;\n})(InlineCompletionItem || (InlineCompletionItem = {}));\nexport var InlineCompletionList;\n(function (InlineCompletionList) {\n function create(items) {\n return { items };\n }\n InlineCompletionList.create = create;\n})(InlineCompletionList || (InlineCompletionList = {}));\n/**\n * Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered.\n *\n * @since 3.18.0\n * @proposed\n */\nexport var InlineCompletionTriggerKind;\n(function (InlineCompletionTriggerKind) {\n /**\n * Completion was triggered explicitly by a user gesture.\n */\n InlineCompletionTriggerKind.Invoked = 0;\n /**\n * Completion was triggered automatically while editing.\n */\n InlineCompletionTriggerKind.Automatic = 1;\n})(InlineCompletionTriggerKind || (InlineCompletionTriggerKind = {}));\nexport var SelectedCompletionInfo;\n(function (SelectedCompletionInfo) {\n function create(range, text) {\n return { range, text };\n }\n SelectedCompletionInfo.create = create;\n})(SelectedCompletionInfo || (SelectedCompletionInfo = {}));\nexport var InlineCompletionContext;\n(function (InlineCompletionContext) {\n function create(triggerKind, selectedCompletionInfo) {\n return { triggerKind, selectedCompletionInfo };\n }\n InlineCompletionContext.create = create;\n})(InlineCompletionContext || (InlineCompletionContext = {}));\nexport var WorkspaceFolder;\n(function (WorkspaceFolder) {\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate) && URI.is(candidate.uri) && Is.string(candidate.name);\n }\n WorkspaceFolder.is = is;\n})(WorkspaceFolder || (WorkspaceFolder = {}));\nexport const EOL = ['\\n', '\\r\\n', '\\r'];\n/**\n * @deprecated Use the text document from the new vscode-languageserver-textdocument package.\n */\nexport var TextDocument;\n(function (TextDocument) {\n /**\n * Creates a new ITextDocument literal from the given uri and content.\n * @param uri The document's uri.\n * @param languageId The document's language Id.\n * @param version The document's version.\n * @param content The document's content.\n */\n function create(uri, languageId, version, content) {\n return new FullTextDocument(uri, languageId, version, content);\n }\n TextDocument.create = create;\n /**\n * Checks whether the given literal conforms to the {@link ITextDocument} interface.\n */\n function is(value) {\n let candidate = value;\n return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount)\n && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;\n }\n TextDocument.is = is;\n function applyEdits(document, edits) {\n let text = document.getText();\n let sortedEdits = mergeSort(edits, (a, b) => {\n let diff = a.range.start.line - b.range.start.line;\n if (diff === 0) {\n return a.range.start.character - b.range.start.character;\n }\n return diff;\n });\n let lastModifiedOffset = text.length;\n for (let i = sortedEdits.length - 1; i >= 0; i--) {\n let e = sortedEdits[i];\n let startOffset = document.offsetAt(e.range.start);\n let endOffset = document.offsetAt(e.range.end);\n if (endOffset <= lastModifiedOffset) {\n text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);\n }\n else {\n throw new Error('Overlapping edit');\n }\n lastModifiedOffset = startOffset;\n }\n return text;\n }\n TextDocument.applyEdits = applyEdits;\n function mergeSort(data, compare) {\n if (data.length <= 1) {\n // sorted\n return data;\n }\n const p = (data.length / 2) | 0;\n const left = data.slice(0, p);\n const right = data.slice(p);\n mergeSort(left, compare);\n mergeSort(right, compare);\n let leftIdx = 0;\n let rightIdx = 0;\n let i = 0;\n while (leftIdx < left.length && rightIdx < right.length) {\n let ret = compare(left[leftIdx], right[rightIdx]);\n if (ret <= 0) {\n // smaller_equal -> take left to preserve order\n data[i++] = left[leftIdx++];\n }\n else {\n // greater -> take right\n data[i++] = right[rightIdx++];\n }\n }\n while (leftIdx < left.length) {\n data[i++] = left[leftIdx++];\n }\n while (rightIdx < right.length) {\n data[i++] = right[rightIdx++];\n }\n return data;\n }\n})(TextDocument || (TextDocument = {}));\n/**\n * @deprecated Use the text document from the new vscode-languageserver-textdocument package.\n */\nclass FullTextDocument {\n constructor(uri, languageId, version, content) {\n this._uri = uri;\n this._languageId = languageId;\n this._version = version;\n this._content = content;\n this._lineOffsets = undefined;\n }\n get uri() {\n return this._uri;\n }\n get languageId() {\n return this._languageId;\n }\n get version() {\n return this._version;\n }\n getText(range) {\n if (range) {\n let start = this.offsetAt(range.start);\n let end = this.offsetAt(range.end);\n return this._content.substring(start, end);\n }\n return this._content;\n }\n update(event, version) {\n this._content = event.text;\n this._version = version;\n this._lineOffsets = undefined;\n }\n getLineOffsets() {\n if (this._lineOffsets === undefined) {\n let lineOffsets = [];\n let text = this._content;\n let isLineStart = true;\n for (let i = 0; i < text.length; i++) {\n if (isLineStart) {\n lineOffsets.push(i);\n isLineStart = false;\n }\n let ch = text.charAt(i);\n isLineStart = (ch === '\\r' || ch === '\\n');\n if (ch === '\\r' && i + 1 < text.length && text.charAt(i + 1) === '\\n') {\n i++;\n }\n }\n if (isLineStart && text.length > 0) {\n lineOffsets.push(text.length);\n }\n this._lineOffsets = lineOffsets;\n }\n return this._lineOffsets;\n }\n positionAt(offset) {\n offset = Math.max(Math.min(offset, this._content.length), 0);\n let lineOffsets = this.getLineOffsets();\n let low = 0, high = lineOffsets.length;\n if (high === 0) {\n return Position.create(0, offset);\n }\n while (low < high) {\n let mid = Math.floor((low + high) / 2);\n if (lineOffsets[mid] > offset) {\n high = mid;\n }\n else {\n low = mid + 1;\n }\n }\n // low is the least x for which the line offset is larger than the current offset\n // or array.length if no line offset is larger than the current offset\n let line = low - 1;\n return Position.create(line, offset - lineOffsets[line]);\n }\n offsetAt(position) {\n let lineOffsets = this.getLineOffsets();\n if (position.line >= lineOffsets.length) {\n return this._content.length;\n }\n else if (position.line < 0) {\n return 0;\n }\n let lineOffset = lineOffsets[position.line];\n let nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;\n return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);\n }\n get lineCount() {\n return this.getLineOffsets().length;\n }\n}\nvar Is;\n(function (Is) {\n const toString = Object.prototype.toString;\n function defined(value) {\n return typeof value !== 'undefined';\n }\n Is.defined = defined;\n function undefined(value) {\n return typeof value === 'undefined';\n }\n Is.undefined = undefined;\n function boolean(value) {\n return value === true || value === false;\n }\n Is.boolean = boolean;\n function string(value) {\n return toString.call(value) === '[object String]';\n }\n Is.string = string;\n function number(value) {\n return toString.call(value) === '[object Number]';\n }\n Is.number = number;\n function numberRange(value, min, max) {\n return toString.call(value) === '[object Number]' && min <= value && value <= max;\n }\n Is.numberRange = numberRange;\n function integer(value) {\n return toString.call(value) === '[object Number]' && -2147483648 <= value && value <= 2147483647;\n }\n Is.integer = integer;\n function uinteger(value) {\n return toString.call(value) === '[object Number]' && 0 <= value && value <= 2147483647;\n }\n Is.uinteger = uinteger;\n function func(value) {\n return toString.call(value) === '[object Function]';\n }\n Is.func = func;\n function objectLiteral(value) {\n // Strictly speaking class instances pass this check as well. Since the LSP\n // doesn't use classes we ignore this for now. If we do we need to add something\n // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`\n return value !== null && typeof value === 'object';\n }\n Is.objectLiteral = objectLiteral;\n function typedArray(value, check) {\n return Array.isArray(value) && value.every(check);\n }\n Is.typedArray = typedArray;\n})(Is || (Is = {}));\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { IToken, TokenType } from 'chevrotain';\r\nimport type { Range } from 'vscode-languageserver-types';\r\nimport type { AbstractElement } from '../languages/generated/ast.js';\r\nimport type { AstNode, CompositeCstNode, CstNode, LeafCstNode, RootCstNode } from '../syntax-tree.js';\r\nimport { Position } from 'vscode-languageserver-types';\r\nimport { tokenToRange } from '../utils/cst-utils.js';\r\n\r\nexport class CstNodeBuilder {\r\n\r\n private rootNode!: RootCstNodeImpl;\r\n private nodeStack: CompositeCstNodeImpl[] = [];\r\n\r\n get current(): CompositeCstNodeImpl {\r\n return this.nodeStack[this.nodeStack.length - 1] ?? this.rootNode;\r\n }\r\n\r\n buildRootNode(input: string): RootCstNode {\r\n this.rootNode = new RootCstNodeImpl(input);\r\n this.rootNode.root = this.rootNode;\r\n this.nodeStack = [this.rootNode];\r\n return this.rootNode;\r\n }\r\n\r\n buildCompositeNode(feature: AbstractElement): CompositeCstNode {\r\n const compositeNode = new CompositeCstNodeImpl();\r\n compositeNode.grammarSource = feature;\r\n compositeNode.root = this.rootNode;\r\n this.current.content.push(compositeNode);\r\n this.nodeStack.push(compositeNode);\r\n return compositeNode;\r\n }\r\n\r\n buildLeafNode(token: IToken, feature?: AbstractElement): LeafCstNode {\r\n const leafNode = new LeafCstNodeImpl(token.startOffset, token.image.length, tokenToRange(token), token.tokenType, !feature);\r\n leafNode.grammarSource = feature;\r\n leafNode.root = this.rootNode;\r\n this.current.content.push(leafNode);\r\n return leafNode;\r\n }\r\n\r\n removeNode(node: CstNode): void {\r\n const parent = node.container;\r\n if (parent) {\r\n const index = parent.content.indexOf(node);\r\n if (index >= 0) {\r\n parent.content.splice(index, 1);\r\n }\r\n }\r\n }\r\n\r\n addHiddenNodes(tokens: IToken[]): void {\r\n const nodes: LeafCstNode[] = [];\r\n for (const token of tokens) {\r\n const leafNode = new LeafCstNodeImpl(token.startOffset, token.image.length, tokenToRange(token), token.tokenType, true);\r\n leafNode.root = this.rootNode;\r\n nodes.push(leafNode);\r\n }\r\n let current: CompositeCstNode = this.current;\r\n let added = false;\r\n // If we are within a composite node, we add the hidden nodes to the content\r\n if (current.content.length > 0) {\r\n current.content.push(...nodes);\r\n return;\r\n }\r\n // Otherwise we are at a newly created node\r\n // Instead of adding the hidden nodes here, we search for the first parent node with content\r\n while (current.container) {\r\n const index = current.container.content.indexOf(current);\r\n if (index > 0) {\r\n // Add the hidden nodes before the current node\r\n current.container.content.splice(index, 0, ...nodes);\r\n added = true;\r\n break;\r\n }\r\n current = current.container;\r\n }\r\n // If we arrive at the root node, we add the hidden nodes at the beginning\r\n // This is the case if the hidden nodes are the first nodes in the tree\r\n if (!added) {\r\n this.rootNode.content.unshift(...nodes);\r\n }\r\n }\r\n\r\n construct(item: { $type: string | symbol | undefined, $cstNode: CstNode }): void {\r\n const current: CstNode = this.current;\r\n // The specified item could be a datatype ($type is symbol) or a fragment ($type is undefined)\r\n // Only if the $type is a string, we actually assign the element\r\n if (typeof item.$type === 'string') {\r\n this.current.astNode = item;\r\n }\r\n item.$cstNode = current;\r\n const node = this.nodeStack.pop();\r\n // Empty composite nodes are not valid\r\n // Simply remove the node from the tree\r\n if (node?.content.length === 0) {\r\n this.removeNode(node);\r\n }\r\n }\r\n}\r\n\r\nexport abstract class AbstractCstNode implements CstNode {\r\n abstract get offset(): number;\r\n abstract get length(): number;\r\n abstract get end(): number;\r\n abstract get range(): Range;\r\n\r\n container?: CompositeCstNode;\r\n grammarSource?: AbstractElement;\r\n root: RootCstNode;\r\n private _astNode?: AstNode;\r\n\r\n /** @deprecated use `container` instead. */\r\n get parent(): CompositeCstNode | undefined {\r\n return this.container;\r\n }\r\n\r\n /** @deprecated use `grammarSource` instead. */\r\n get feature(): AbstractElement | undefined {\r\n return this.grammarSource;\r\n }\r\n\r\n get hidden(): boolean {\r\n return false;\r\n }\r\n\r\n get astNode(): AstNode {\r\n const node = typeof this._astNode?.$type === 'string' ? this._astNode : this.container?.astNode;\r\n if (!node) {\r\n throw new Error('This node has no associated AST element');\r\n }\r\n return node;\r\n }\r\n\r\n set astNode(value: AstNode | undefined) {\r\n this._astNode = value;\r\n }\r\n\r\n /** @deprecated use `astNode` instead. */\r\n get element(): AstNode {\r\n return this.astNode;\r\n }\r\n\r\n get text(): string {\r\n return this.root.fullText.substring(this.offset, this.end);\r\n }\r\n}\r\n\r\nexport class LeafCstNodeImpl extends AbstractCstNode implements LeafCstNode {\r\n get offset(): number {\r\n return this._offset;\r\n }\r\n\r\n get length(): number {\r\n return this._length;\r\n }\r\n\r\n get end(): number {\r\n return this._offset + this._length;\r\n }\r\n\r\n override get hidden(): boolean {\r\n return this._hidden;\r\n }\r\n\r\n get tokenType(): TokenType {\r\n return this._tokenType;\r\n }\r\n\r\n get range(): Range {\r\n return this._range;\r\n }\r\n\r\n private _hidden: boolean;\r\n private _offset: number;\r\n private _length: number;\r\n private _range: Range;\r\n private _tokenType: TokenType;\r\n\r\n constructor(offset: number, length: number, range: Range, tokenType: TokenType, hidden = false) {\r\n super();\r\n this._hidden = hidden;\r\n this._offset = offset;\r\n this._tokenType = tokenType;\r\n this._length = length;\r\n this._range = range;\r\n }\r\n}\r\n\r\nexport class CompositeCstNodeImpl extends AbstractCstNode implements CompositeCstNode {\r\n readonly content: CstNode[] = new CstNodeContainer(this);\r\n private _rangeCache?: Range;\r\n\r\n /** @deprecated use `content` instead. */\r\n get children(): CstNode[] {\r\n return this.content;\r\n }\r\n\r\n get offset(): number {\r\n return this.firstNonHiddenNode?.offset ?? 0;\r\n }\r\n\r\n get length(): number {\r\n return this.end - this.offset;\r\n }\r\n\r\n get end(): number {\r\n return this.lastNonHiddenNode?.end ?? 0;\r\n }\r\n\r\n get range(): Range {\r\n const firstNode = this.firstNonHiddenNode;\r\n const lastNode = this.lastNonHiddenNode;\r\n if (firstNode && lastNode) {\r\n if (this._rangeCache === undefined) {\r\n const { range: firstRange } = firstNode;\r\n const { range: lastRange } = lastNode;\r\n this._rangeCache = { start: firstRange.start, end: lastRange.end.line < firstRange.start.line ? firstRange.start : lastRange.end };\r\n }\r\n return this._rangeCache;\r\n } else {\r\n return { start: Position.create(0, 0), end: Position.create(0, 0) };\r\n }\r\n }\r\n\r\n private get firstNonHiddenNode(): CstNode | undefined {\r\n for (const child of this.content) {\r\n if (!child.hidden) {\r\n return child;\r\n }\r\n }\r\n return this.content[0];\r\n }\r\n\r\n private get lastNonHiddenNode(): CstNode | undefined {\r\n for (let i = this.content.length - 1; i >= 0; i--) {\r\n const child = this.content[i];\r\n if (!child.hidden) {\r\n return child;\r\n }\r\n }\r\n return this.content[this.content.length - 1];\r\n }\r\n}\r\n\r\nclass CstNodeContainer extends Array {\r\n readonly parent: CompositeCstNode;\r\n\r\n constructor(parent: CompositeCstNode) {\r\n super();\r\n this.parent = parent;\r\n Object.setPrototypeOf(this, CstNodeContainer.prototype);\r\n }\r\n\r\n override push(...items: CstNode[]): number {\r\n this.addParents(items);\r\n return super.push(...items);\r\n }\r\n\r\n override unshift(...items: CstNode[]): number {\r\n this.addParents(items);\r\n return super.unshift(...items);\r\n }\r\n\r\n override splice(start: number, count: number, ...items: CstNode[]): CstNode[] {\r\n this.addParents(items);\r\n return super.splice(start, count, ...items);\r\n }\r\n\r\n private addParents(items: CstNode[]): void {\r\n for (const item of items) {\r\n (item).container = this.parent;\r\n }\r\n }\r\n}\r\n\r\nexport class RootCstNodeImpl extends CompositeCstNodeImpl implements RootCstNode {\r\n private _text = '';\r\n\r\n override get text(): string {\r\n return this._text.substring(this.offset, this.end);\r\n }\r\n\r\n get fullText(): string {\r\n return this._text;\r\n }\r\n\r\n constructor(input?: string) {\r\n super();\r\n this._text = input ?? '';\r\n }\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\n/* eslint-disable @typescript-eslint/no-explicit-any */\r\nimport type { DSLMethodOpts, ILexingError, IOrAlt, IParserErrorMessageProvider, IRecognitionException, IToken, TokenType, TokenVocabulary } from 'chevrotain';\r\nimport type { AbstractElement, Action, Assignment, ParserRule } from '../languages/generated/ast.js';\r\nimport type { Linker } from '../references/linker.js';\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport type { AstNode, AstReflection, CompositeCstNode, CstNode } from '../syntax-tree.js';\r\nimport type { Lexer, LexerResult } from './lexer.js';\r\nimport type { IParserConfig } from './parser-config.js';\r\nimport type { ValueConverter } from './value-converter.js';\r\nimport { defaultParserErrorProvider, EmbeddedActionsParser, LLkLookaheadStrategy } from 'chevrotain';\r\nimport { LLStarLookaheadStrategy } from 'chevrotain-allstar';\r\nimport { isAssignment, isCrossReference, isKeyword } from '../languages/generated/ast.js';\r\nimport { getExplicitRuleType, isDataTypeRule } from '../utils/grammar-utils.js';\r\nimport { assignMandatoryProperties, getContainerOfType, linkContentToContainer } from '../utils/ast-utils.js';\r\nimport { CstNodeBuilder } from './cst-node-builder.js';\r\nimport type { LexingReport } from './token-builder.js';\r\n\r\nexport type ParseResult = {\r\n value: T,\r\n parserErrors: IRecognitionException[],\r\n lexerErrors: ILexingError[],\r\n lexerReport?: LexingReport\r\n}\r\n\r\nexport const DatatypeSymbol = Symbol('Datatype');\r\n\r\ninterface DataTypeNode {\r\n $cstNode: CompositeCstNode\r\n /** Instead of a string, this node is uniquely identified by the `Datatype` symbol */\r\n $type: symbol\r\n /** Used as a storage for all parsed terminals, keywords and sub-datatype rules */\r\n value: string\r\n}\r\n\r\nfunction isDataTypeNode(node: { $type: string | symbol | undefined }): node is DataTypeNode {\r\n return node.$type === DatatypeSymbol;\r\n}\r\n\r\ntype RuleResult = (args: Args) => any;\r\n\r\ntype Args = Record;\r\n\r\ntype RuleImpl = (args: Args) => any;\r\n\r\ninterface AssignmentElement {\r\n assignment?: Assignment\r\n isCrossRef: boolean\r\n}\r\n\r\n/**\r\n * Base interface for all parsers. Mainly used by the `parser-builder-base.ts` to perform work on different kinds of parsers.\r\n * The main use cases are:\r\n * * AST parser: Based on a string, create an AST for the current grammar\r\n * * Completion parser: Based on a partial string, identify the current position of the input within the grammar\r\n */\r\nexport interface BaseParser {\r\n /**\r\n * Adds a new parser rule to the parser\r\n */\r\n rule(rule: ParserRule, impl: RuleImpl): RuleResult;\r\n /**\r\n * Returns the executable rule function for the specified rule name\r\n */\r\n getRule(name: string): RuleResult | undefined;\r\n /**\r\n * Performs alternatives parsing (the `|` operation in EBNF/Langium)\r\n */\r\n alternatives(idx: number, choices: Array>): void;\r\n /**\r\n * Parses the callback as optional (the `?` operation in EBNF/Langium)\r\n */\r\n optional(idx: number, callback: DSLMethodOpts): void;\r\n /**\r\n * Parses the callback 0 or more times (the `*` operation in EBNF/Langium)\r\n */\r\n many(idx: number, callback: DSLMethodOpts): void;\r\n /**\r\n * Parses the callback 1 or more times (the `+` operation in EBNF/Langium)\r\n */\r\n atLeastOne(idx: number, callback: DSLMethodOpts): void;\r\n /**\r\n * Consumes a specific token type from the token input stream.\r\n * Requires a unique index within the rule for a specific token type.\r\n */\r\n consume(idx: number, tokenType: TokenType, feature: AbstractElement): void;\r\n /**\r\n * Invokes the executable function for a given parser rule.\r\n * Requires a unique index within the rule for a specific sub rule.\r\n * Arguments can be supplied to the rule invocation for semantic predicates\r\n */\r\n subrule(idx: number, rule: RuleResult, fragment: boolean, feature: AbstractElement, args: Args): void;\r\n /**\r\n * Executes a grammar action that modifies the currently active AST node\r\n */\r\n action($type: string, action: Action): void;\r\n /**\r\n * Finishes construction of the current AST node. Only used by the AST parser.\r\n */\r\n construct(): unknown;\r\n /**\r\n * Whether the parser is currently actually in use or in \"recording mode\".\r\n * Recording mode is activated once when the parser is analyzing itself.\r\n * During this phase, no input exists and therefore no AST should be constructed\r\n */\r\n isRecording(): boolean;\r\n /**\r\n * Current state of the unordered groups\r\n */\r\n get unorderedGroups(): Map;\r\n /**\r\n * The rule stack indicates the indices of rules that are currently invoked,\r\n * in order of their invocation.\r\n */\r\n getRuleStack(): number[];\r\n}\r\n\r\nconst ruleSuffix = '\\u200B';\r\nconst withRuleSuffix = (name: string): string => name.endsWith(ruleSuffix) ? name : name + ruleSuffix;\r\n\r\nexport abstract class AbstractLangiumParser implements BaseParser {\r\n\r\n protected readonly lexer: Lexer;\r\n protected readonly wrapper: ChevrotainWrapper;\r\n protected _unorderedGroups: Map = new Map();\r\n\r\n protected allRules = new Map();\r\n protected mainRule!: RuleResult;\r\n\r\n constructor(services: LangiumCoreServices) {\r\n this.lexer = services.parser.Lexer;\r\n const tokens = this.lexer.definition;\r\n const production = services.LanguageMetaData.mode === 'production';\r\n this.wrapper = new ChevrotainWrapper(tokens, {\r\n ...services.parser.ParserConfig,\r\n skipValidations: production,\r\n errorMessageProvider: services.parser.ParserErrorMessageProvider\r\n });\r\n }\r\n\r\n alternatives(idx: number, choices: Array>): void {\r\n this.wrapper.wrapOr(idx, choices);\r\n }\r\n\r\n optional(idx: number, callback: DSLMethodOpts): void {\r\n this.wrapper.wrapOption(idx, callback);\r\n }\r\n\r\n many(idx: number, callback: DSLMethodOpts): void {\r\n this.wrapper.wrapMany(idx, callback);\r\n }\r\n\r\n atLeastOne(idx: number, callback: DSLMethodOpts): void {\r\n this.wrapper.wrapAtLeastOne(idx, callback);\r\n }\r\n\r\n abstract rule(rule: ParserRule, impl: RuleImpl): RuleResult;\r\n abstract consume(idx: number, tokenType: TokenType, feature: AbstractElement): void;\r\n abstract subrule(idx: number, rule: RuleResult, fragment: boolean, feature: AbstractElement, args: Args): void;\r\n abstract action($type: string, action: Action): void;\r\n abstract construct(): unknown;\r\n\r\n getRule(name: string): RuleResult | undefined {\r\n return this.allRules.get(name);\r\n }\r\n\r\n isRecording(): boolean {\r\n return this.wrapper.IS_RECORDING;\r\n }\r\n\r\n get unorderedGroups(): Map {\r\n return this._unorderedGroups;\r\n }\r\n\r\n getRuleStack(): number[] {\r\n return (this.wrapper as any).RULE_STACK;\r\n }\r\n\r\n finalize(): void {\r\n this.wrapper.wrapSelfAnalysis();\r\n }\r\n}\r\n\r\nexport interface ParserOptions {\r\n rule?: string\r\n}\r\n\r\nexport class LangiumParser extends AbstractLangiumParser {\r\n private readonly linker: Linker;\r\n private readonly converter: ValueConverter;\r\n private readonly astReflection: AstReflection;\r\n private readonly nodeBuilder = new CstNodeBuilder();\r\n private lexerResult?: LexerResult;\r\n private stack: any[] = [];\r\n private assignmentMap = new Map();\r\n\r\n private get current(): any {\r\n return this.stack[this.stack.length - 1];\r\n }\r\n\r\n constructor(services: LangiumCoreServices) {\r\n super(services);\r\n this.linker = services.references.Linker;\r\n this.converter = services.parser.ValueConverter;\r\n this.astReflection = services.shared.AstReflection;\r\n }\r\n\r\n rule(rule: ParserRule, impl: RuleImpl): RuleResult {\r\n const type = this.computeRuleType(rule);\r\n const ruleMethod = this.wrapper.DEFINE_RULE(withRuleSuffix(rule.name), this.startImplementation(type, impl).bind(this));\r\n this.allRules.set(rule.name, ruleMethod);\r\n if (rule.entry) {\r\n this.mainRule = ruleMethod;\r\n }\r\n return ruleMethod;\r\n }\r\n\r\n private computeRuleType(rule: ParserRule): string | symbol | undefined {\r\n if (rule.fragment) {\r\n return undefined;\r\n } else if (isDataTypeRule(rule)) {\r\n return DatatypeSymbol;\r\n } else {\r\n const explicit = getExplicitRuleType(rule);\r\n return explicit ?? rule.name;\r\n }\r\n }\r\n\r\n parse(input: string, options: ParserOptions = {}): ParseResult {\r\n this.nodeBuilder.buildRootNode(input);\r\n const lexerResult = this.lexerResult = this.lexer.tokenize(input);\r\n this.wrapper.input = lexerResult.tokens;\r\n const ruleMethod = options.rule ? this.allRules.get(options.rule) : this.mainRule;\r\n if (!ruleMethod) {\r\n throw new Error(options.rule ? `No rule found with name '${options.rule}'` : 'No main rule available.');\r\n }\r\n const result = ruleMethod.call(this.wrapper, {});\r\n this.nodeBuilder.addHiddenNodes(lexerResult.hidden);\r\n this.unorderedGroups.clear();\r\n this.lexerResult = undefined;\r\n return {\r\n value: result,\r\n lexerErrors: lexerResult.errors,\r\n lexerReport: lexerResult.report,\r\n parserErrors: this.wrapper.errors\r\n };\r\n }\r\n\r\n private startImplementation($type: string | symbol | undefined, implementation: RuleImpl): RuleImpl {\r\n return (args) => {\r\n // Only create a new AST node in case the calling rule is not a fragment rule\r\n const createNode = !this.isRecording() && $type !== undefined;\r\n if (createNode) {\r\n const node: any = { $type };\r\n this.stack.push(node);\r\n if ($type === DatatypeSymbol) {\r\n node.value = '';\r\n }\r\n }\r\n let result: unknown;\r\n try {\r\n result = implementation(args);\r\n } catch (err) {\r\n result = undefined;\r\n }\r\n if (result === undefined && createNode) {\r\n result = this.construct();\r\n }\r\n return result;\r\n };\r\n }\r\n\r\n private extractHiddenTokens(token: IToken): IToken[] {\r\n const hiddenTokens = this.lexerResult!.hidden;\r\n if (!hiddenTokens.length) {\r\n return [];\r\n }\r\n const offset = token.startOffset;\r\n for (let i = 0; i < hiddenTokens.length; i++) {\r\n const token = hiddenTokens[i];\r\n if (token.startOffset > offset) {\r\n return hiddenTokens.splice(0, i);\r\n }\r\n }\r\n return hiddenTokens.splice(0, hiddenTokens.length);\r\n }\r\n\r\n consume(idx: number, tokenType: TokenType, feature: AbstractElement): void {\r\n const token = this.wrapper.wrapConsume(idx, tokenType);\r\n if (!this.isRecording() && this.isValidToken(token)) {\r\n const hiddenTokens = this.extractHiddenTokens(token);\r\n this.nodeBuilder.addHiddenNodes(hiddenTokens);\r\n const leafNode = this.nodeBuilder.buildLeafNode(token, feature);\r\n const { assignment, isCrossRef } = this.getAssignment(feature);\r\n const current = this.current;\r\n if (assignment) {\r\n const convertedValue = isKeyword(feature) ? token.image : this.converter.convert(token.image, leafNode);\r\n this.assign(assignment.operator, assignment.feature, convertedValue, leafNode, isCrossRef);\r\n } else if (isDataTypeNode(current)) {\r\n let text = token.image;\r\n if (!isKeyword(feature)) {\r\n text = this.converter.convert(text, leafNode).toString();\r\n }\r\n current.value += text;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Most consumed parser tokens are valid. However there are two cases in which they are not valid:\r\n *\r\n * 1. They were inserted during error recovery by the parser. These tokens don't really exist and should not be further processed\r\n * 2. They contain invalid token ranges. This might include the special EOF token, or other tokens produced by invalid token builders.\r\n */\r\n private isValidToken(token: IToken): boolean {\r\n return !token.isInsertedInRecovery && !isNaN(token.startOffset) && typeof token.endOffset === 'number' && !isNaN(token.endOffset);\r\n }\r\n\r\n subrule(idx: number, rule: RuleResult, fragment: boolean, feature: AbstractElement, args: Args): void {\r\n let cstNode: CompositeCstNode | undefined;\r\n if (!this.isRecording() && !fragment) {\r\n // We only want to create a new CST node if the subrule actually creates a new AST node.\r\n // In other cases like calls of fragment rules the current CST/AST is populated further.\r\n // Note that skipping this initialization and leaving cstNode unassigned also skips the subrule assignment later on.\r\n // This is intended, as fragment rules only enrich the current AST node\r\n cstNode = this.nodeBuilder.buildCompositeNode(feature);\r\n }\r\n const subruleResult = this.wrapper.wrapSubrule(idx, rule, args) as any;\r\n if (!this.isRecording() && cstNode && cstNode.length > 0) {\r\n this.performSubruleAssignment(subruleResult, feature, cstNode);\r\n }\r\n }\r\n\r\n private performSubruleAssignment(result: any, feature: AbstractElement, cstNode: CompositeCstNode): void {\r\n const { assignment, isCrossRef } = this.getAssignment(feature);\r\n if (assignment) {\r\n this.assign(assignment.operator, assignment.feature, result, cstNode, isCrossRef);\r\n } else if (!assignment) {\r\n // If we call a subrule without an assignment we either:\r\n // 1. append the result of the subrule (data type rule)\r\n // 2. override the current object with the newly parsed object\r\n // If the current element is an AST node and the result of the subrule\r\n // is a data type rule, we can safely discard the results.\r\n const current = this.current;\r\n if (isDataTypeNode(current)) {\r\n current.value += result.toString();\r\n } else if (typeof result === 'object' && result) {\r\n const object = this.assignWithoutOverride(result, current);\r\n const newItem = object;\r\n this.stack.pop();\r\n this.stack.push(newItem);\r\n }\r\n }\r\n }\r\n\r\n action($type: string, action: Action): void {\r\n if (!this.isRecording()) {\r\n let last = this.current;\r\n if (action.feature && action.operator) {\r\n last = this.construct();\r\n this.nodeBuilder.removeNode(last.$cstNode);\r\n const node = this.nodeBuilder.buildCompositeNode(action);\r\n node.content.push(last.$cstNode);\r\n const newItem = { $type };\r\n this.stack.push(newItem);\r\n this.assign(action.operator, action.feature, last, last.$cstNode, false);\r\n } else {\r\n last.$type = $type;\r\n }\r\n }\r\n }\r\n\r\n construct(): unknown {\r\n if (this.isRecording()) {\r\n return undefined;\r\n }\r\n const obj = this.current;\r\n linkContentToContainer(obj);\r\n this.nodeBuilder.construct(obj);\r\n this.stack.pop();\r\n if (isDataTypeNode(obj)) {\r\n return this.converter.convert(obj.value, obj.$cstNode);\r\n } else {\r\n assignMandatoryProperties(this.astReflection, obj);\r\n }\r\n return obj;\r\n }\r\n\r\n private getAssignment(feature: AbstractElement): AssignmentElement {\r\n if (!this.assignmentMap.has(feature)) {\r\n const assignment = getContainerOfType(feature, isAssignment);\r\n this.assignmentMap.set(feature, {\r\n assignment: assignment,\r\n isCrossRef: assignment ? isCrossReference(assignment.terminal) : false\r\n });\r\n }\r\n return this.assignmentMap.get(feature)!;\r\n }\r\n\r\n private assign(operator: string, feature: string, value: unknown, cstNode: CstNode, isCrossRef: boolean): void {\r\n const obj = this.current;\r\n let item: unknown;\r\n if (isCrossRef && typeof value === 'string') {\r\n item = this.linker.buildReference(obj, feature, cstNode, value);\r\n } else {\r\n item = value;\r\n }\r\n switch (operator) {\r\n case '=': {\r\n obj[feature] = item;\r\n break;\r\n }\r\n case '?=': {\r\n obj[feature] = true;\r\n break;\r\n }\r\n case '+=': {\r\n if (!Array.isArray(obj[feature])) {\r\n obj[feature] = [];\r\n }\r\n obj[feature].push(item);\r\n }\r\n }\r\n }\r\n\r\n private assignWithoutOverride(target: any, source: any): any {\r\n for (const [name, existingValue] of Object.entries(source)) {\r\n const newValue = target[name];\r\n if (newValue === undefined) {\r\n target[name] = existingValue;\r\n } else if (Array.isArray(newValue) && Array.isArray(existingValue)) {\r\n existingValue.push(...newValue);\r\n target[name] = existingValue;\r\n }\r\n }\r\n // The target was parsed from a unassigned subrule\r\n // After the subrule construction, it received a cst node\r\n // This CST node will later be overriden by the cst node builder\r\n // To prevent references to stale AST nodes in the CST,\r\n // we need to remove the reference here\r\n const targetCstNode = target.$cstNode;\r\n if (targetCstNode) {\r\n targetCstNode.astNode = undefined;\r\n target.$cstNode = undefined;\r\n }\r\n return target;\r\n }\r\n\r\n get definitionErrors(): IParserDefinitionError[] {\r\n return this.wrapper.definitionErrors;\r\n }\r\n}\r\n\r\nexport interface IParserDefinitionError {\r\n message: string\r\n type: number\r\n ruleName?: string\r\n}\r\n\r\nexport abstract class AbstractParserErrorMessageProvider implements IParserErrorMessageProvider {\r\n\r\n buildMismatchTokenMessage(options: {\r\n expected: TokenType\r\n actual: IToken\r\n previous: IToken\r\n ruleName: string\r\n }): string {\r\n return defaultParserErrorProvider.buildMismatchTokenMessage(options);\r\n }\r\n\r\n buildNotAllInputParsedMessage(options: {\r\n firstRedundant: IToken\r\n ruleName: string\r\n }): string {\r\n return defaultParserErrorProvider.buildNotAllInputParsedMessage(options);\r\n }\r\n\r\n buildNoViableAltMessage(options: {\r\n expectedPathsPerAlt: TokenType[][][]\r\n actual: IToken[]\r\n previous: IToken\r\n customUserDescription: string\r\n ruleName: string\r\n }): string {\r\n return defaultParserErrorProvider.buildNoViableAltMessage(options);\r\n }\r\n\r\n buildEarlyExitMessage(options: {\r\n expectedIterationPaths: TokenType[][]\r\n actual: IToken[]\r\n previous: IToken\r\n customUserDescription: string\r\n ruleName: string\r\n }): string {\r\n return defaultParserErrorProvider.buildEarlyExitMessage(options);\r\n }\r\n\r\n}\r\n\r\nexport class LangiumParserErrorMessageProvider extends AbstractParserErrorMessageProvider {\r\n\r\n override buildMismatchTokenMessage({ expected, actual }: {\r\n expected: TokenType\r\n actual: IToken\r\n previous: IToken\r\n ruleName: string\r\n }): string {\r\n const expectedMsg = expected.LABEL\r\n ? '`' + expected.LABEL + '`'\r\n : expected.name.endsWith(':KW')\r\n ? `keyword '${expected.name.substring(0, expected.name.length - 3)}'`\r\n : `token of type '${expected.name}'`;\r\n return `Expecting ${expectedMsg} but found \\`${actual.image}\\`.`;\r\n }\r\n\r\n override buildNotAllInputParsedMessage({ firstRedundant }: {\r\n firstRedundant: IToken\r\n ruleName: string\r\n }): string {\r\n return `Expecting end of file but found \\`${firstRedundant.image}\\`.`;\r\n }\r\n}\r\n\r\nexport interface CompletionParserResult {\r\n tokens: IToken[]\r\n elementStack: AbstractElement[]\r\n tokenIndex: number\r\n}\r\n\r\nexport class LangiumCompletionParser extends AbstractLangiumParser {\r\n private tokens: IToken[] = [];\r\n\r\n private elementStack: AbstractElement[] = [];\r\n private lastElementStack: AbstractElement[] = [];\r\n private nextTokenIndex = 0;\r\n private stackSize = 0;\r\n\r\n action(): void {\r\n // NOOP\r\n }\r\n\r\n construct(): unknown {\r\n // NOOP\r\n return undefined;\r\n }\r\n\r\n parse(input: string): CompletionParserResult {\r\n this.resetState();\r\n const tokens = this.lexer.tokenize(input, { mode: 'partial' });\r\n this.tokens = tokens.tokens;\r\n this.wrapper.input = [...this.tokens];\r\n this.mainRule.call(this.wrapper, {});\r\n this.unorderedGroups.clear();\r\n return {\r\n tokens: this.tokens,\r\n elementStack: [...this.lastElementStack],\r\n tokenIndex: this.nextTokenIndex\r\n };\r\n }\r\n\r\n rule(rule: ParserRule, impl: RuleImpl): RuleResult {\r\n const ruleMethod = this.wrapper.DEFINE_RULE(withRuleSuffix(rule.name), this.startImplementation(impl).bind(this));\r\n this.allRules.set(rule.name, ruleMethod);\r\n if (rule.entry) {\r\n this.mainRule = ruleMethod;\r\n }\r\n return ruleMethod;\r\n }\r\n\r\n private resetState(): void {\r\n this.elementStack = [];\r\n this.lastElementStack = [];\r\n this.nextTokenIndex = 0;\r\n this.stackSize = 0;\r\n }\r\n\r\n private startImplementation(implementation: RuleImpl): RuleImpl {\r\n return (args) => {\r\n const size = this.keepStackSize();\r\n try {\r\n implementation(args);\r\n } finally {\r\n this.resetStackSize(size);\r\n }\r\n };\r\n }\r\n\r\n private removeUnexpectedElements(): void {\r\n this.elementStack.splice(this.stackSize);\r\n }\r\n\r\n keepStackSize(): number {\r\n const size = this.elementStack.length;\r\n this.stackSize = size;\r\n return size;\r\n }\r\n\r\n resetStackSize(size: number): void {\r\n this.removeUnexpectedElements();\r\n this.stackSize = size;\r\n }\r\n\r\n consume(idx: number, tokenType: TokenType, feature: AbstractElement): void {\r\n this.wrapper.wrapConsume(idx, tokenType);\r\n if (!this.isRecording()) {\r\n this.lastElementStack = [...this.elementStack, feature];\r\n this.nextTokenIndex = this.currIdx + 1;\r\n }\r\n }\r\n\r\n subrule(idx: number, rule: RuleResult, fragment: boolean, feature: AbstractElement, args: Args): void {\r\n this.before(feature);\r\n this.wrapper.wrapSubrule(idx, rule, args);\r\n this.after(feature);\r\n }\r\n\r\n before(element: AbstractElement): void {\r\n if (!this.isRecording()) {\r\n this.elementStack.push(element);\r\n }\r\n }\r\n\r\n after(element: AbstractElement): void {\r\n if (!this.isRecording()) {\r\n const index = this.elementStack.lastIndexOf(element);\r\n if (index >= 0) {\r\n this.elementStack.splice(index);\r\n }\r\n }\r\n }\r\n\r\n get currIdx(): number {\r\n return (this.wrapper as any).currIdx;\r\n }\r\n}\r\n\r\nconst defaultConfig: IParserConfig = {\r\n recoveryEnabled: true,\r\n nodeLocationTracking: 'full',\r\n skipValidations: true,\r\n errorMessageProvider: new LangiumParserErrorMessageProvider()\r\n};\r\n\r\n/**\r\n * This class wraps the embedded actions parser of chevrotain and exposes protected methods.\r\n * This way, we can build the `LangiumParser` as a composition.\r\n */\r\nclass ChevrotainWrapper extends EmbeddedActionsParser {\r\n\r\n // This array is set in the base implementation of Chevrotain.\r\n definitionErrors: IParserDefinitionError[];\r\n\r\n constructor(tokens: TokenVocabulary, config: IParserConfig) {\r\n const useDefaultLookahead = config && 'maxLookahead' in config;\r\n super(tokens, {\r\n ...defaultConfig,\r\n lookaheadStrategy: useDefaultLookahead\r\n ? new LLkLookaheadStrategy({ maxLookahead: config.maxLookahead })\r\n : new LLStarLookaheadStrategy({\r\n // If validations are skipped, don't log the lookahead warnings\r\n logging: config.skipValidations ? () => { } : undefined\r\n }),\r\n ...config,\r\n });\r\n }\r\n\r\n get IS_RECORDING(): boolean {\r\n return this.RECORDING_PHASE;\r\n }\r\n\r\n DEFINE_RULE(name: string, impl: RuleImpl): RuleResult {\r\n return this.RULE(name, impl);\r\n }\r\n\r\n wrapSelfAnalysis(): void {\r\n this.performSelfAnalysis();\r\n }\r\n\r\n wrapConsume(idx: number, tokenType: TokenType): IToken {\r\n return this.consume(idx, tokenType);\r\n }\r\n\r\n wrapSubrule(idx: number, rule: RuleResult, args: Args): unknown {\r\n return this.subrule(idx, rule, {\r\n ARGS: [args]\r\n });\r\n }\r\n\r\n wrapOr(idx: number, choices: Array>): void {\r\n this.or(idx, choices);\r\n }\r\n\r\n wrapOption(idx: number, callback: DSLMethodOpts): void {\r\n this.option(idx, callback);\r\n }\r\n\r\n wrapMany(idx: number, callback: DSLMethodOpts): void {\r\n this.many(idx, callback);\r\n }\r\n\r\n wrapAtLeastOne(idx: number, callback: DSLMethodOpts): void {\r\n this.atLeastOne(idx, callback);\r\n }\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2022 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { IOrAlt, TokenType, TokenTypeDictionary } from 'chevrotain';\r\nimport type { AbstractElement, Action, Alternatives, Condition, CrossReference, Grammar, Group, Keyword, NamedArgument, ParserRule, RuleCall, UnorderedGroup } from '../languages/generated/ast.js';\r\nimport type { BaseParser } from './langium-parser.js';\r\nimport type { AstNode } from '../syntax-tree.js';\r\nimport type { Cardinality } from '../utils/grammar-utils.js';\r\nimport { EMPTY_ALT, EOF } from 'chevrotain';\r\nimport { isAction, isAlternatives, isEndOfFile, isAssignment, isConjunction, isCrossReference, isDisjunction, isGroup, isKeyword, isNegation, isParameterReference, isParserRule, isRuleCall, isTerminalRule, isUnorderedGroup, isBooleanLiteral } from '../languages/generated/ast.js';\r\nimport { assertUnreachable, ErrorWithLocation } from '../utils/errors.js';\r\nimport { stream } from '../utils/stream.js';\r\nimport { findNameAssignment, getAllReachableRules, getTypeName } from '../utils/grammar-utils.js';\r\n\r\ntype RuleContext = {\r\n optional: number,\r\n consume: number,\r\n subrule: number,\r\n many: number,\r\n or: number\r\n} & ParserContext;\r\n\r\ntype ParserContext = {\r\n parser: BaseParser\r\n tokens: TokenTypeDictionary\r\n ruleNames: Map\r\n}\r\n\r\ntype Rule = (args: Args) => unknown;\r\n\r\ntype Args = Record;\r\n\r\ntype Predicate = (args: Args) => boolean;\r\n\r\ntype Method = (args: Args) => void;\r\n\r\nexport function createParser(grammar: Grammar, parser: T, tokens: TokenTypeDictionary): T {\r\n const parserContext: ParserContext = {\r\n parser,\r\n tokens,\r\n ruleNames: new Map()\r\n };\r\n buildRules(parserContext, grammar);\r\n return parser;\r\n}\r\n\r\nfunction buildRules(parserContext: ParserContext, grammar: Grammar): void {\r\n const reachable = getAllReachableRules(grammar, false);\r\n const parserRules = stream(grammar.rules).filter(isParserRule).filter(rule => reachable.has(rule));\r\n for (const rule of parserRules) {\r\n const ctx: RuleContext = {\r\n ...parserContext,\r\n consume: 1,\r\n optional: 1,\r\n subrule: 1,\r\n many: 1,\r\n or: 1\r\n };\r\n parserContext.parser.rule(rule, buildElement(ctx, rule.definition));\r\n }\r\n}\r\n\r\nfunction buildElement(ctx: RuleContext, element: AbstractElement, ignoreGuard = false): Method {\r\n let method: Method;\r\n if (isKeyword(element)) {\r\n method = buildKeyword(ctx, element);\r\n } else if (isAction(element)) {\r\n method = buildAction(ctx, element);\r\n } else if (isAssignment(element)) {\r\n method = buildElement(ctx, element.terminal);\r\n } else if (isCrossReference(element)) {\r\n method = buildCrossReference(ctx, element);\r\n } else if (isRuleCall(element)) {\r\n method = buildRuleCall(ctx, element);\r\n } else if (isAlternatives(element)) {\r\n method = buildAlternatives(ctx, element);\r\n } else if (isUnorderedGroup(element)) {\r\n method = buildUnorderedGroup(ctx, element);\r\n } else if (isGroup(element)) {\r\n method = buildGroup(ctx, element);\r\n } else if(isEndOfFile(element)) {\r\n const idx = ctx.consume++;\r\n method = () => ctx.parser.consume(idx, EOF, element);\r\n } else {\r\n throw new ErrorWithLocation(element.$cstNode, `Unexpected element type: ${element.$type}`);\r\n }\r\n return wrap(ctx, ignoreGuard ? undefined : getGuardCondition(element), method, element.cardinality);\r\n}\r\n\r\nfunction buildAction(ctx: RuleContext, action: Action): Method {\r\n const actionType = getTypeName(action);\r\n return () => ctx.parser.action(actionType, action);\r\n}\r\n\r\nfunction buildRuleCall(ctx: RuleContext, ruleCall: RuleCall): Method {\r\n const rule = ruleCall.rule.ref;\r\n if (isParserRule(rule)) {\r\n const idx = ctx.subrule++;\r\n const fragment = rule.fragment;\r\n const predicate = ruleCall.arguments.length > 0 ? buildRuleCallPredicate(rule, ruleCall.arguments) : () => ({});\r\n return (args) => ctx.parser.subrule(idx, getRule(ctx, rule), fragment, ruleCall, predicate(args));\r\n } else if (isTerminalRule(rule)) {\r\n const idx = ctx.consume++;\r\n const method = getToken(ctx, rule.name);\r\n return () => ctx.parser.consume(idx, method, ruleCall);\r\n } else if (!rule) {\r\n throw new ErrorWithLocation(ruleCall.$cstNode, `Undefined rule: ${ruleCall.rule.$refText}`);\r\n } else {\r\n assertUnreachable(rule);\r\n }\r\n}\r\n\r\nfunction buildRuleCallPredicate(rule: ParserRule, namedArgs: NamedArgument[]): (args: Args) => Args {\r\n const predicates = namedArgs.map(e => buildPredicate(e.value));\r\n return (args) => {\r\n const ruleArgs: Args = {};\r\n for (let i = 0; i < predicates.length; i++) {\r\n const ruleTarget = rule.parameters[i];\r\n const predicate = predicates[i];\r\n ruleArgs[ruleTarget.name] = predicate(args);\r\n }\r\n return ruleArgs;\r\n };\r\n}\r\n\r\ninterface PredicatedMethod {\r\n ALT: Method,\r\n GATE?: Predicate\r\n}\r\n\r\nfunction buildPredicate(condition: Condition): Predicate {\r\n if (isDisjunction(condition)) {\r\n const left = buildPredicate(condition.left);\r\n const right = buildPredicate(condition.right);\r\n return (args) => (left(args) || right(args));\r\n } else if (isConjunction(condition)) {\r\n const left = buildPredicate(condition.left);\r\n const right = buildPredicate(condition.right);\r\n return (args) => (left(args) && right(args));\r\n } else if (isNegation(condition)) {\r\n const value = buildPredicate(condition.value);\r\n return (args) => !value(args);\r\n } else if (isParameterReference(condition)) {\r\n const name = condition.parameter.ref!.name;\r\n return (args) => args !== undefined && args[name] === true;\r\n } else if (isBooleanLiteral(condition)) {\r\n const value = Boolean(condition.true);\r\n return () => value;\r\n }\r\n assertUnreachable(condition);\r\n}\r\n\r\nfunction buildAlternatives(ctx: RuleContext, alternatives: Alternatives): Method {\r\n if (alternatives.elements.length === 1) {\r\n return buildElement(ctx, alternatives.elements[0]);\r\n } else {\r\n const methods: PredicatedMethod[] = [];\r\n\r\n for (const element of alternatives.elements) {\r\n const predicatedMethod: PredicatedMethod = {\r\n // Since we handle the guard condition in the alternative already\r\n // We can ignore the group guard condition inside\r\n ALT: buildElement(ctx, element, true)\r\n };\r\n const guard = getGuardCondition(element);\r\n if (guard) {\r\n predicatedMethod.GATE = buildPredicate(guard);\r\n }\r\n methods.push(predicatedMethod);\r\n }\r\n\r\n const idx = ctx.or++;\r\n return (args) => ctx.parser.alternatives(idx, methods.map(method => {\r\n const alt: IOrAlt = {\r\n ALT: () => method.ALT(args)\r\n };\r\n const gate = method.GATE;\r\n if (gate) {\r\n alt.GATE = () => gate(args);\r\n }\r\n return alt;\r\n }));\r\n }\r\n}\r\n\r\nfunction buildUnorderedGroup(ctx: RuleContext, group: UnorderedGroup): Method {\r\n if (group.elements.length === 1) {\r\n return buildElement(ctx, group.elements[0]);\r\n }\r\n const methods: PredicatedMethod[] = [];\r\n\r\n for (const element of group.elements) {\r\n const predicatedMethod: PredicatedMethod = {\r\n // Since we handle the guard condition in the alternative already\r\n // We can ignore the group guard condition inside\r\n ALT: buildElement(ctx, element, true)\r\n };\r\n const guard = getGuardCondition(element);\r\n if (guard) {\r\n predicatedMethod.GATE = buildPredicate(guard);\r\n }\r\n methods.push(predicatedMethod);\r\n }\r\n\r\n const orIdx = ctx.or++;\r\n\r\n const idFunc = (groupIdx: number, lParser: BaseParser) => {\r\n const stackId = lParser.getRuleStack().join('-');\r\n return `uGroup_${groupIdx}_${stackId}`;\r\n };\r\n const alternatives: Method = (args) => ctx.parser.alternatives(orIdx, methods.map((method, idx) => {\r\n const alt: IOrAlt = { ALT: () => true };\r\n const parser = ctx.parser;\r\n alt.ALT = () => {\r\n method.ALT(args);\r\n if (!parser.isRecording()) {\r\n const key = idFunc(orIdx, parser);\r\n if (!parser.unorderedGroups.get(key)) {\r\n // init after clear state\r\n parser.unorderedGroups.set(key, []);\r\n }\r\n const groupState = parser.unorderedGroups.get(key)!;\r\n if (typeof groupState?.[idx] === 'undefined') {\r\n // Not accessed yet\r\n groupState[idx] = true;\r\n }\r\n }\r\n };\r\n const gate = method.GATE;\r\n if (gate) {\r\n alt.GATE = () => gate(args);\r\n } else {\r\n alt.GATE = () => {\r\n const trackedAlternatives = parser.unorderedGroups.get(idFunc(orIdx, parser));\r\n const allow = !trackedAlternatives?.[idx];\r\n return allow;\r\n };\r\n }\r\n return alt;\r\n }));\r\n const wrapped = wrap(ctx, getGuardCondition(group), alternatives, '*');\r\n return (args) => {\r\n wrapped(args);\r\n if (!ctx.parser.isRecording()) {\r\n ctx.parser.unorderedGroups.delete(idFunc(orIdx, ctx.parser));\r\n }\r\n };\r\n}\r\n\r\nfunction buildGroup(ctx: RuleContext, group: Group): Method {\r\n const methods = group.elements.map(e => buildElement(ctx, e));\r\n return (args) => methods.forEach(method => method(args));\r\n}\r\n\r\nfunction getGuardCondition(element: AbstractElement): Condition | undefined {\r\n if (isGroup(element)) {\r\n return element.guardCondition;\r\n }\r\n return undefined;\r\n}\r\n\r\nfunction buildCrossReference(ctx: RuleContext, crossRef: CrossReference, terminal = crossRef.terminal): Method {\r\n if (!terminal) {\r\n if (!crossRef.type.ref) {\r\n throw new Error('Could not resolve reference to type: ' + crossRef.type.$refText);\r\n }\r\n const assignment = findNameAssignment(crossRef.type.ref);\r\n const assignTerminal = assignment?.terminal;\r\n if (!assignTerminal) {\r\n throw new Error('Could not find name assignment for type: ' + getTypeName(crossRef.type.ref));\r\n }\r\n return buildCrossReference(ctx, crossRef, assignTerminal);\r\n } else if (isRuleCall(terminal) && isParserRule(terminal.rule.ref)) {\r\n // The terminal is a data type rule here. Everything else will result in a validation error.\r\n const rule = terminal.rule.ref;\r\n const idx = ctx.subrule++;\r\n return (args) => ctx.parser.subrule(idx, getRule(ctx, rule), false, crossRef, args);\r\n } else if (isRuleCall(terminal) && isTerminalRule(terminal.rule.ref)) {\r\n const idx = ctx.consume++;\r\n const terminalRule = getToken(ctx, terminal.rule.ref.name);\r\n return () => ctx.parser.consume(idx, terminalRule, crossRef);\r\n } else if (isKeyword(terminal)) {\r\n const idx = ctx.consume++;\r\n const keyword = getToken(ctx, terminal.value);\r\n return () => ctx.parser.consume(idx, keyword, crossRef);\r\n }\r\n else {\r\n throw new Error('Could not build cross reference parser');\r\n }\r\n}\r\n\r\nfunction buildKeyword(ctx: RuleContext, keyword: Keyword): Method {\r\n const idx = ctx.consume++;\r\n const token = ctx.tokens[keyword.value];\r\n if (!token) {\r\n throw new Error('Could not find token for keyword: ' + keyword.value);\r\n }\r\n return () => ctx.parser.consume(idx, token, keyword);\r\n}\r\n\r\nfunction wrap(ctx: RuleContext, guard: Condition | undefined, method: Method, cardinality: Cardinality): Method {\r\n const gate = guard && buildPredicate(guard);\r\n\r\n if (!cardinality) {\r\n if (gate) {\r\n const idx = ctx.or++;\r\n return (args) => ctx.parser.alternatives(idx, [\r\n {\r\n ALT: () => method(args),\r\n GATE: () => gate(args)\r\n },\r\n {\r\n ALT: EMPTY_ALT(),\r\n GATE: () => !gate(args)\r\n }\r\n ]);\r\n } else {\r\n return method;\r\n }\r\n }\r\n\r\n if (cardinality === '*') {\r\n const idx = ctx.many++;\r\n return (args) => ctx.parser.many(idx, {\r\n DEF: () => method(args),\r\n GATE: gate ? () => gate(args) : undefined\r\n });\r\n } else if (cardinality === '+') {\r\n const idx = ctx.many++;\r\n if (gate) {\r\n const orIdx = ctx.or++;\r\n // In the case of a guard condition for the `+` group\r\n // We combine it with an empty alternative\r\n // If the condition returns true, it needs to parse at least a single iteration\r\n // If its false, it is not allowed to parse anything\r\n return (args) => ctx.parser.alternatives(orIdx, [\r\n {\r\n ALT: () => ctx.parser.atLeastOne(idx, {\r\n DEF: () => method(args)\r\n }),\r\n GATE: () => gate(args)\r\n },\r\n {\r\n ALT: EMPTY_ALT(),\r\n GATE: () => !gate(args)\r\n }\r\n ]);\r\n } else {\r\n return (args) => ctx.parser.atLeastOne(idx, {\r\n DEF: () => method(args),\r\n });\r\n }\r\n } else if (cardinality === '?') {\r\n const idx = ctx.optional++;\r\n return (args) => ctx.parser.optional(idx, {\r\n DEF: () => method(args),\r\n GATE: gate ? () => gate(args) : undefined\r\n });\r\n } else {\r\n assertUnreachable(cardinality);\r\n }\r\n}\r\n\r\nfunction getRule(ctx: ParserContext, element: ParserRule | AbstractElement): Rule {\r\n const name = getRuleName(ctx, element);\r\n const rule = ctx.parser.getRule(name);\r\n if (!rule) throw new Error(`Rule \"${name}\" not found.\"`);\r\n return rule;\r\n}\r\n\r\nfunction getRuleName(ctx: ParserContext, element: ParserRule | AbstractElement): string {\r\n if (isParserRule(element)) {\r\n return element.name;\r\n } else if (ctx.ruleNames.has(element)) {\r\n return ctx.ruleNames.get(element)!;\r\n } else {\r\n let item: AstNode = element;\r\n let parent: AstNode = item.$container!;\r\n let ruleName: string = element.$type;\r\n while (!isParserRule(parent)) {\r\n if (isGroup(parent) || isAlternatives(parent) || isUnorderedGroup(parent)) {\r\n const index = parent.elements.indexOf(item as AbstractElement);\r\n ruleName = index.toString() + ':' + ruleName;\r\n }\r\n item = parent;\r\n parent = parent.$container!;\r\n }\r\n const rule = parent as ParserRule;\r\n ruleName = rule.name + ':' + ruleName;\r\n ctx.ruleNames.set(element, ruleName);\r\n return ruleName;\r\n }\r\n}\r\n\r\nfunction getToken(ctx: ParserContext, name: string): TokenType {\r\n const token = ctx.tokens[name];\r\n if (!token) throw new Error(`Token \"${name}\" not found.\"`);\r\n return token;\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2022 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport { LangiumCompletionParser } from './langium-parser.js';\r\nimport { createParser } from './parser-builder-base.js';\r\n\r\nexport function createCompletionParser(services: LangiumCoreServices): LangiumCompletionParser {\r\n const grammar = services.Grammar;\r\n const lexer = services.parser.Lexer;\r\n const parser = new LangiumCompletionParser(services);\r\n createParser(grammar, parser, lexer.definition);\r\n parser.finalize();\r\n return parser;\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport { LangiumParser } from './langium-parser.js';\r\nimport { createParser } from './parser-builder-base.js';\r\n\r\n/**\r\n * Create and finalize a Langium parser. The parser rules are derived from the grammar, which is\r\n * available at `services.Grammar`.\r\n */\r\nexport function createLangiumParser(services: LangiumCoreServices): LangiumParser {\r\n const parser = prepareLangiumParser(services);\r\n parser.finalize();\r\n return parser;\r\n}\r\n\r\n/**\r\n * Create a Langium parser without finalizing it. This is used to extract more detailed error\r\n * information when the parser is initially validated.\r\n */\r\nexport function prepareLangiumParser(services: LangiumCoreServices): LangiumParser {\r\n const grammar = services.Grammar;\r\n const lexer = services.parser.Lexer;\r\n const parser = new LangiumParser(services);\r\n return createParser(grammar, parser, lexer.definition);\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { CustomPatternMatcherFunc, ILexingError, TokenPattern, TokenType, TokenVocabulary } from 'chevrotain';\r\nimport type { AbstractRule, Grammar, Keyword, TerminalRule } from '../languages/generated/ast.js';\r\nimport type { Stream } from '../utils/stream.js';\r\nimport { Lexer } from 'chevrotain';\r\nimport { isKeyword, isParserRule, isTerminalRule } from '../languages/generated/ast.js';\r\nimport { streamAllContents } from '../utils/ast-utils.js';\r\nimport { getAllReachableRules, terminalRegex } from '../utils/grammar-utils.js';\r\nimport { getCaseInsensitivePattern, isWhitespace, partialMatches } from '../utils/regexp-utils.js';\r\nimport { stream } from '../utils/stream.js';\r\n\r\nexport interface TokenBuilderOptions {\r\n caseInsensitive?: boolean\r\n}\r\n\r\nexport interface TokenBuilder {\r\n buildTokens(grammar: Grammar, options?: TokenBuilderOptions): TokenVocabulary;\r\n /**\r\n * Produces a lexing report for the given text that was just tokenized using the tokens provided by this builder.\r\n *\r\n * @param text The text that was tokenized.\r\n */\r\n flushLexingReport?(text: string): LexingReport;\r\n}\r\n\r\n/**\r\n * A custom lexing report that can be produced by the token builder during the lexing process.\r\n * Adopters need to ensure that the any custom fields are serializable so they can be sent across worker threads.\r\n */\r\nexport interface LexingReport {\r\n diagnostics: LexingDiagnostic[];\r\n}\r\n\r\nexport type LexingDiagnosticSeverity = 'error' | 'warning' | 'info' | 'hint';\r\n\r\nexport interface LexingDiagnostic extends ILexingError {\r\n severity?: LexingDiagnosticSeverity;\r\n}\r\n\r\nexport class DefaultTokenBuilder implements TokenBuilder {\r\n /**\r\n * The list of diagnostics stored during the lexing process of a single text.\r\n */\r\n protected diagnostics: LexingDiagnostic[] = [];\r\n\r\n buildTokens(grammar: Grammar, options?: TokenBuilderOptions): TokenVocabulary {\r\n const reachableRules = stream(getAllReachableRules(grammar, false));\r\n const terminalTokens: TokenType[] = this.buildTerminalTokens(reachableRules);\r\n const tokens: TokenType[] = this.buildKeywordTokens(reachableRules, terminalTokens, options);\r\n\r\n terminalTokens.forEach(terminalToken => {\r\n const pattern = terminalToken.PATTERN;\r\n if (typeof pattern === 'object' && pattern && 'test' in pattern && isWhitespace(pattern)) {\r\n tokens.unshift(terminalToken);\r\n } else {\r\n tokens.push(terminalToken);\r\n }\r\n });\r\n // We don't need to add the EOF token explicitly.\r\n // It is automatically available at the end of the token stream.\r\n return tokens;\r\n }\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n flushLexingReport(text: string): LexingReport {\r\n return { diagnostics: this.popDiagnostics() };\r\n }\r\n\r\n protected popDiagnostics(): LexingDiagnostic[] {\r\n const diagnostics = [...this.diagnostics];\r\n this.diagnostics = [];\r\n return diagnostics;\r\n }\r\n\r\n protected buildTerminalTokens(rules: Stream): TokenType[] {\r\n return rules.filter(isTerminalRule).filter(e => !e.fragment)\r\n .map(terminal => this.buildTerminalToken(terminal)).toArray();\r\n }\r\n\r\n protected buildTerminalToken(terminal: TerminalRule): TokenType {\r\n const regex = terminalRegex(terminal);\r\n const pattern = this.requiresCustomPattern(regex) ? this.regexPatternFunction(regex) : regex;\r\n const tokenType: TokenType = {\r\n name: terminal.name,\r\n PATTERN: pattern,\r\n };\r\n if (typeof pattern === 'function') {\r\n tokenType.LINE_BREAKS = true;\r\n }\r\n if (terminal.hidden) {\r\n // Only skip tokens that are able to accept whitespace\r\n tokenType.GROUP = isWhitespace(regex) ? Lexer.SKIPPED : 'hidden';\r\n }\r\n return tokenType;\r\n }\r\n\r\n protected requiresCustomPattern(regex: RegExp): boolean {\r\n if (regex.flags.includes('u') || regex.flags.includes('s')) {\r\n // Unicode and dotall regexes are not supported by Chevrotain.\r\n return true;\r\n } else if (regex.source.includes('?<=') || regex.source.includes('? {\r\n stickyRegex.lastIndex = offset;\r\n const execResult = stickyRegex.exec(text);\r\n return execResult;\r\n };\r\n }\r\n\r\n protected buildKeywordTokens(rules: Stream, terminalTokens: TokenType[], options?: TokenBuilderOptions): TokenType[] {\r\n return rules\r\n // We filter by parser rules, since keywords in terminal rules get transformed into regex and are not actual tokens\r\n .filter(isParserRule)\r\n .flatMap(rule => streamAllContents(rule).filter(isKeyword))\r\n .distinct(e => e.value).toArray()\r\n // Sort keywords by descending length\r\n .sort((a, b) => b.value.length - a.value.length)\r\n .map(keyword => this.buildKeywordToken(keyword, terminalTokens, Boolean(options?.caseInsensitive)));\r\n }\r\n\r\n protected buildKeywordToken(keyword: Keyword, terminalTokens: TokenType[], caseInsensitive: boolean): TokenType {\r\n const keywordPattern = this.buildKeywordPattern(keyword, caseInsensitive);\r\n const tokenType: TokenType = {\r\n name: keyword.value,\r\n PATTERN: keywordPattern,\r\n LONGER_ALT: this.findLongerAlt(keyword, terminalTokens)\r\n };\r\n\r\n if (typeof keywordPattern === 'function') {\r\n tokenType.LINE_BREAKS = true;\r\n }\r\n\r\n return tokenType;\r\n }\r\n\r\n protected buildKeywordPattern(keyword: Keyword, caseInsensitive: boolean): TokenPattern {\r\n return caseInsensitive ?\r\n new RegExp(getCaseInsensitivePattern(keyword.value)) :\r\n keyword.value;\r\n }\r\n\r\n protected findLongerAlt(keyword: Keyword, terminalTokens: TokenType[]): TokenType[] {\r\n return terminalTokens.reduce((longerAlts: TokenType[], token) => {\r\n const pattern = token?.PATTERN as RegExp;\r\n if (pattern?.source && partialMatches('^' + pattern.source + '$', keyword.value)) {\r\n longerAlts.push(token);\r\n }\r\n return longerAlts;\r\n }, []);\r\n }\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { AbstractElement, AbstractRule } from '../languages/generated/ast.js';\r\nimport type { CstNode } from '../syntax-tree.js';\r\nimport { isCrossReference, isRuleCall } from '../languages/generated/ast.js';\r\nimport { getCrossReferenceTerminal, getRuleType } from '../utils/grammar-utils.js';\r\n\r\n/**\r\n * Language-specific service for converting string values from the source text format into a value to be held in the AST.\r\n */\r\nexport interface ValueConverter {\r\n /**\r\n * Converts a string value from the source text format into a value to be held in the AST.\r\n */\r\n convert(input: string, cstNode: CstNode): ValueType;\r\n}\r\n\r\nexport type ValueType = string | number | boolean | bigint | Date;\r\n\r\nexport class DefaultValueConverter implements ValueConverter {\r\n\r\n convert(input: string, cstNode: CstNode): ValueType {\r\n let feature: AbstractElement | undefined = cstNode.grammarSource;\r\n if (isCrossReference(feature)) {\r\n feature = getCrossReferenceTerminal(feature);\r\n }\r\n if (isRuleCall(feature)) {\r\n const rule = feature.rule.ref;\r\n if (!rule) {\r\n throw new Error('This cst node was not parsed by a rule.');\r\n }\r\n return this.runConverter(rule, input, cstNode);\r\n }\r\n return input;\r\n }\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n protected runConverter(rule: AbstractRule, input: string, cstNode: CstNode): ValueType {\r\n switch (rule.name.toUpperCase()) {\r\n case 'INT': return ValueConverter.convertInt(input);\r\n case 'STRING': return ValueConverter.convertString(input);\r\n case 'ID': return ValueConverter.convertID(input);\r\n }\r\n switch (getRuleType(rule)?.toLowerCase()) {\r\n case 'number': return ValueConverter.convertNumber(input);\r\n case 'boolean': return ValueConverter.convertBoolean(input);\r\n case 'bigint': return ValueConverter.convertBigint(input);\r\n case 'date': return ValueConverter.convertDate(input);\r\n default: return input;\r\n }\r\n }\r\n}\r\n\r\nexport namespace ValueConverter {\r\n\r\n export function convertString(input: string): string {\r\n let result = '';\r\n for (let i = 1; i < input.length - 1; i++) {\r\n const c = input.charAt(i);\r\n if (c === '\\\\') {\r\n const c1 = input.charAt(++i);\r\n result += convertEscapeCharacter(c1);\r\n } else {\r\n result += c;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n function convertEscapeCharacter(char: string): string {\r\n switch (char) {\r\n case 'b': return '\\b';\r\n case 'f': return '\\f';\r\n case 'n': return '\\n';\r\n case 'r': return '\\r';\r\n case 't': return '\\t';\r\n case 'v': return '\\v';\r\n case '0': return '\\0';\r\n default: return char;\r\n }\r\n }\r\n\r\n export function convertID(input: string): string {\r\n if (input.charAt(0) === '^') {\r\n return input.substring(1);\r\n } else {\r\n return input;\r\n }\r\n }\r\n\r\n export function convertInt(input: string): number {\r\n return parseInt(input);\r\n }\r\n\r\n export function convertBigint(input: string): bigint {\r\n return BigInt(input);\r\n }\r\n\r\n export function convertDate(input: string): Date {\r\n return new Date(input);\r\n }\r\n\r\n export function convertNumber(input: string): number {\r\n return Number(input);\r\n }\r\n\r\n export function convertBoolean(input: string): boolean {\r\n return input.toLowerCase() === 'true';\r\n }\r\n\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2024 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\n// eslint-disable-next-line no-restricted-imports\r\nexport * from 'vscode-jsonrpc/lib/common/cancellation.js';\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport { CancellationToken, CancellationTokenSource, type AbstractCancellationTokenSource } from '../utils/cancellation.js';\r\n\r\nexport type MaybePromise = T | Promise\r\n\r\n/**\r\n * Delays the execution of the current code to the next tick of the event loop.\r\n * Don't call this method directly in a tight loop to prevent too many promises from being created.\r\n */\r\nexport function delayNextTick(): Promise {\r\n return new Promise(resolve => {\r\n // In case we are running in a non-node environment, `setImmediate` isn't available.\r\n // Using `setTimeout` of the browser API accomplishes the same result.\r\n if (typeof setImmediate === 'undefined') {\r\n setTimeout(resolve, 0);\r\n } else {\r\n setImmediate(resolve);\r\n }\r\n });\r\n}\r\n\r\nlet lastTick = 0;\r\nlet globalInterruptionPeriod = 10;\r\n\r\n/**\r\n * Reset the global interruption period and create a cancellation token source.\r\n */\r\nexport function startCancelableOperation(): AbstractCancellationTokenSource {\r\n lastTick = performance.now();\r\n return new CancellationTokenSource();\r\n}\r\n\r\n/**\r\n * Change the period duration for `interruptAndCheck` to the given number of milliseconds.\r\n * The default value is 10ms.\r\n */\r\nexport function setInterruptionPeriod(period: number): void {\r\n globalInterruptionPeriod = period;\r\n}\r\n\r\n/**\r\n * This symbol may be thrown in an asynchronous context by any Langium service that receives\r\n * a `CancellationToken`. This means that the promise returned by such a service is rejected with\r\n * this symbol as rejection reason.\r\n */\r\nexport const OperationCancelled = Symbol('OperationCancelled');\r\n\r\n/**\r\n * Use this in a `catch` block to check whether the thrown object indicates that the operation\r\n * has been cancelled.\r\n */\r\nexport function isOperationCancelled(err: unknown): err is typeof OperationCancelled {\r\n return err === OperationCancelled;\r\n}\r\n\r\n/**\r\n * This function does two things:\r\n * 1. Check the elapsed time since the last call to this function or to `startCancelableOperation`. If the predefined\r\n * period (configured with `setInterruptionPeriod`) is exceeded, execution is delayed with `delayNextTick`.\r\n * 2. If the predefined period is not met yet or execution is resumed after an interruption, the given cancellation\r\n * token is checked, and if cancellation is requested, `OperationCanceled` is thrown.\r\n *\r\n * All services in Langium that receive a `CancellationToken` may potentially call this function, so the\r\n * `CancellationToken` must be caught (with an `async` try-catch block or a `catch` callback attached to\r\n * the promise) to avoid that event being exposed as an error.\r\n */\r\nexport async function interruptAndCheck(token: CancellationToken): Promise {\r\n if (token === CancellationToken.None) {\r\n // Early exit in case cancellation was disabled by the caller\r\n return;\r\n }\r\n const current = performance.now();\r\n if (current - lastTick >= globalInterruptionPeriod) {\r\n lastTick = current;\r\n await delayNextTick();\r\n // prevent calling delayNextTick every iteration of loop\r\n // where delayNextTick takes up the majority or all of the\r\n // globalInterruptionPeriod itself\r\n lastTick = performance.now();\r\n }\r\n if (token.isCancellationRequested) {\r\n throw OperationCancelled;\r\n }\r\n}\r\n\r\n/**\r\n * Simple implementation of the deferred pattern.\r\n * An object that exposes a promise and functions to resolve and reject it.\r\n */\r\nexport class Deferred {\r\n resolve: (value: T) => this;\r\n reject: (err?: unknown) => this;\r\n\r\n promise = new Promise((resolve, reject) => {\r\n this.resolve = (arg) => {\r\n resolve(arg);\r\n return this;\r\n };\r\n this.reject = (err) => {\r\n reject(err);\r\n return this;\r\n };\r\n });\r\n}\r\n", "/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\n'use strict';\nclass FullTextDocument {\n constructor(uri, languageId, version, content) {\n this._uri = uri;\n this._languageId = languageId;\n this._version = version;\n this._content = content;\n this._lineOffsets = undefined;\n }\n get uri() {\n return this._uri;\n }\n get languageId() {\n return this._languageId;\n }\n get version() {\n return this._version;\n }\n getText(range) {\n if (range) {\n const start = this.offsetAt(range.start);\n const end = this.offsetAt(range.end);\n return this._content.substring(start, end);\n }\n return this._content;\n }\n update(changes, version) {\n for (const change of changes) {\n if (FullTextDocument.isIncremental(change)) {\n // makes sure start is before end\n const range = getWellformedRange(change.range);\n // update content\n const startOffset = this.offsetAt(range.start);\n const endOffset = this.offsetAt(range.end);\n this._content = this._content.substring(0, startOffset) + change.text + this._content.substring(endOffset, this._content.length);\n // update the offsets\n const startLine = Math.max(range.start.line, 0);\n const endLine = Math.max(range.end.line, 0);\n let lineOffsets = this._lineOffsets;\n const addedLineOffsets = computeLineOffsets(change.text, false, startOffset);\n if (endLine - startLine === addedLineOffsets.length) {\n for (let i = 0, len = addedLineOffsets.length; i < len; i++) {\n lineOffsets[i + startLine + 1] = addedLineOffsets[i];\n }\n }\n else {\n if (addedLineOffsets.length < 10000) {\n lineOffsets.splice(startLine + 1, endLine - startLine, ...addedLineOffsets);\n }\n else { // avoid too many arguments for splice\n this._lineOffsets = lineOffsets = lineOffsets.slice(0, startLine + 1).concat(addedLineOffsets, lineOffsets.slice(endLine + 1));\n }\n }\n const diff = change.text.length - (endOffset - startOffset);\n if (diff !== 0) {\n for (let i = startLine + 1 + addedLineOffsets.length, len = lineOffsets.length; i < len; i++) {\n lineOffsets[i] = lineOffsets[i] + diff;\n }\n }\n }\n else if (FullTextDocument.isFull(change)) {\n this._content = change.text;\n this._lineOffsets = undefined;\n }\n else {\n throw new Error('Unknown change event received');\n }\n }\n this._version = version;\n }\n getLineOffsets() {\n if (this._lineOffsets === undefined) {\n this._lineOffsets = computeLineOffsets(this._content, true);\n }\n return this._lineOffsets;\n }\n positionAt(offset) {\n offset = Math.max(Math.min(offset, this._content.length), 0);\n const lineOffsets = this.getLineOffsets();\n let low = 0, high = lineOffsets.length;\n if (high === 0) {\n return { line: 0, character: offset };\n }\n while (low < high) {\n const mid = Math.floor((low + high) / 2);\n if (lineOffsets[mid] > offset) {\n high = mid;\n }\n else {\n low = mid + 1;\n }\n }\n // low is the least x for which the line offset is larger than the current offset\n // or array.length if no line offset is larger than the current offset\n const line = low - 1;\n offset = this.ensureBeforeEOL(offset, lineOffsets[line]);\n return { line, character: offset - lineOffsets[line] };\n }\n offsetAt(position) {\n const lineOffsets = this.getLineOffsets();\n if (position.line >= lineOffsets.length) {\n return this._content.length;\n }\n else if (position.line < 0) {\n return 0;\n }\n const lineOffset = lineOffsets[position.line];\n if (position.character <= 0) {\n return lineOffset;\n }\n const nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;\n const offset = Math.min(lineOffset + position.character, nextLineOffset);\n return this.ensureBeforeEOL(offset, lineOffset);\n }\n ensureBeforeEOL(offset, lineOffset) {\n while (offset > lineOffset && isEOL(this._content.charCodeAt(offset - 1))) {\n offset--;\n }\n return offset;\n }\n get lineCount() {\n return this.getLineOffsets().length;\n }\n static isIncremental(event) {\n const candidate = event;\n return candidate !== undefined && candidate !== null &&\n typeof candidate.text === 'string' && candidate.range !== undefined &&\n (candidate.rangeLength === undefined || typeof candidate.rangeLength === 'number');\n }\n static isFull(event) {\n const candidate = event;\n return candidate !== undefined && candidate !== null &&\n typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined;\n }\n}\nexport var TextDocument;\n(function (TextDocument) {\n /**\n * Creates a new text document.\n *\n * @param uri The document's uri.\n * @param languageId The document's language Id.\n * @param version The document's initial version number.\n * @param content The document's content.\n */\n function create(uri, languageId, version, content) {\n return new FullTextDocument(uri, languageId, version, content);\n }\n TextDocument.create = create;\n /**\n * Updates a TextDocument by modifying its content.\n *\n * @param document the document to update. Only documents created by TextDocument.create are valid inputs.\n * @param changes the changes to apply to the document.\n * @param version the changes version for the document.\n * @returns The updated TextDocument. Note: That's the same document instance passed in as first parameter.\n *\n */\n function update(document, changes, version) {\n if (document instanceof FullTextDocument) {\n document.update(changes, version);\n return document;\n }\n else {\n throw new Error('TextDocument.update: document must be created by TextDocument.create');\n }\n }\n TextDocument.update = update;\n function applyEdits(document, edits) {\n const text = document.getText();\n const sortedEdits = mergeSort(edits.map(getWellformedEdit), (a, b) => {\n const diff = a.range.start.line - b.range.start.line;\n if (diff === 0) {\n return a.range.start.character - b.range.start.character;\n }\n return diff;\n });\n let lastModifiedOffset = 0;\n const spans = [];\n for (const e of sortedEdits) {\n const startOffset = document.offsetAt(e.range.start);\n if (startOffset < lastModifiedOffset) {\n throw new Error('Overlapping edit');\n }\n else if (startOffset > lastModifiedOffset) {\n spans.push(text.substring(lastModifiedOffset, startOffset));\n }\n if (e.newText.length) {\n spans.push(e.newText);\n }\n lastModifiedOffset = document.offsetAt(e.range.end);\n }\n spans.push(text.substr(lastModifiedOffset));\n return spans.join('');\n }\n TextDocument.applyEdits = applyEdits;\n})(TextDocument || (TextDocument = {}));\nfunction mergeSort(data, compare) {\n if (data.length <= 1) {\n // sorted\n return data;\n }\n const p = (data.length / 2) | 0;\n const left = data.slice(0, p);\n const right = data.slice(p);\n mergeSort(left, compare);\n mergeSort(right, compare);\n let leftIdx = 0;\n let rightIdx = 0;\n let i = 0;\n while (leftIdx < left.length && rightIdx < right.length) {\n const ret = compare(left[leftIdx], right[rightIdx]);\n if (ret <= 0) {\n // smaller_equal -> take left to preserve order\n data[i++] = left[leftIdx++];\n }\n else {\n // greater -> take right\n data[i++] = right[rightIdx++];\n }\n }\n while (leftIdx < left.length) {\n data[i++] = left[leftIdx++];\n }\n while (rightIdx < right.length) {\n data[i++] = right[rightIdx++];\n }\n return data;\n}\nfunction computeLineOffsets(text, isAtLineStart, textOffset = 0) {\n const result = isAtLineStart ? [textOffset] : [];\n for (let i = 0; i < text.length; i++) {\n const ch = text.charCodeAt(i);\n if (isEOL(ch)) {\n if (ch === 13 /* CharCode.CarriageReturn */ && i + 1 < text.length && text.charCodeAt(i + 1) === 10 /* CharCode.LineFeed */) {\n i++;\n }\n result.push(textOffset + i + 1);\n }\n }\n return result;\n}\nfunction isEOL(char) {\n return char === 13 /* CharCode.CarriageReturn */ || char === 10 /* CharCode.LineFeed */;\n}\nfunction getWellformedRange(range) {\n const start = range.start;\n const end = range.end;\n if (start.line > end.line || (start.line === end.line && start.character > end.character)) {\n return { start: end, end: start };\n }\n return range;\n}\nfunction getWellformedEdit(textEdit) {\n const range = getWellformedRange(textEdit.range);\n if (range !== textEdit.range) {\n return { newText: textEdit.newText, range };\n }\n return textEdit;\n}\n", "// 'path' module extracted from Node.js v8.11.1 (only the posix part)\n// transplited with Babel\n\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nfunction assertPath(path) {\n if (typeof path !== 'string') {\n throw new TypeError('Path must be a string. Received ' + JSON.stringify(path));\n }\n}\n\n// Resolves . and .. elements in a path with directory names\nfunction normalizeStringPosix(path, allowAboveRoot) {\n var res = '';\n var lastSegmentLength = 0;\n var lastSlash = -1;\n var dots = 0;\n var code;\n for (var i = 0; i <= path.length; ++i) {\n if (i < path.length)\n code = path.charCodeAt(i);\n else if (code === 47 /*/*/)\n break;\n else\n code = 47 /*/*/;\n if (code === 47 /*/*/) {\n if (lastSlash === i - 1 || dots === 1) {\n // NOOP\n } else if (lastSlash !== i - 1 && dots === 2) {\n if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) {\n if (res.length > 2) {\n var lastSlashIndex = res.lastIndexOf('/');\n if (lastSlashIndex !== res.length - 1) {\n if (lastSlashIndex === -1) {\n res = '';\n lastSegmentLength = 0;\n } else {\n res = res.slice(0, lastSlashIndex);\n lastSegmentLength = res.length - 1 - res.lastIndexOf('/');\n }\n lastSlash = i;\n dots = 0;\n continue;\n }\n } else if (res.length === 2 || res.length === 1) {\n res = '';\n lastSegmentLength = 0;\n lastSlash = i;\n dots = 0;\n continue;\n }\n }\n if (allowAboveRoot) {\n if (res.length > 0)\n res += '/..';\n else\n res = '..';\n lastSegmentLength = 2;\n }\n } else {\n if (res.length > 0)\n res += '/' + path.slice(lastSlash + 1, i);\n else\n res = path.slice(lastSlash + 1, i);\n lastSegmentLength = i - lastSlash - 1;\n }\n lastSlash = i;\n dots = 0;\n } else if (code === 46 /*.*/ && dots !== -1) {\n ++dots;\n } else {\n dots = -1;\n }\n }\n return res;\n}\n\nfunction _format(sep, pathObject) {\n var dir = pathObject.dir || pathObject.root;\n var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || '');\n if (!dir) {\n return base;\n }\n if (dir === pathObject.root) {\n return dir + base;\n }\n return dir + sep + base;\n}\n\nvar posix = {\n // path.resolve([from ...], to)\n resolve: function resolve() {\n var resolvedPath = '';\n var resolvedAbsolute = false;\n var cwd;\n\n for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n var path;\n if (i >= 0)\n path = arguments[i];\n else {\n if (cwd === undefined)\n cwd = process.cwd();\n path = cwd;\n }\n\n assertPath(path);\n\n // Skip empty entries\n if (path.length === 0) {\n continue;\n }\n\n resolvedPath = path + '/' + resolvedPath;\n resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);\n\n if (resolvedAbsolute) {\n if (resolvedPath.length > 0)\n return '/' + resolvedPath;\n else\n return '/';\n } else if (resolvedPath.length > 0) {\n return resolvedPath;\n } else {\n return '.';\n }\n },\n\n normalize: function normalize(path) {\n assertPath(path);\n\n if (path.length === 0) return '.';\n\n var isAbsolute = path.charCodeAt(0) === 47 /*/*/;\n var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/;\n\n // Normalize the path\n path = normalizeStringPosix(path, !isAbsolute);\n\n if (path.length === 0 && !isAbsolute) path = '.';\n if (path.length > 0 && trailingSeparator) path += '/';\n\n if (isAbsolute) return '/' + path;\n return path;\n },\n\n isAbsolute: function isAbsolute(path) {\n assertPath(path);\n return path.length > 0 && path.charCodeAt(0) === 47 /*/*/;\n },\n\n join: function join() {\n if (arguments.length === 0)\n return '.';\n var joined;\n for (var i = 0; i < arguments.length; ++i) {\n var arg = arguments[i];\n assertPath(arg);\n if (arg.length > 0) {\n if (joined === undefined)\n joined = arg;\n else\n joined += '/' + arg;\n }\n }\n if (joined === undefined)\n return '.';\n return posix.normalize(joined);\n },\n\n relative: function relative(from, to) {\n assertPath(from);\n assertPath(to);\n\n if (from === to) return '';\n\n from = posix.resolve(from);\n to = posix.resolve(to);\n\n if (from === to) return '';\n\n // Trim any leading backslashes\n var fromStart = 1;\n for (; fromStart < from.length; ++fromStart) {\n if (from.charCodeAt(fromStart) !== 47 /*/*/)\n break;\n }\n var fromEnd = from.length;\n var fromLen = fromEnd - fromStart;\n\n // Trim any leading backslashes\n var toStart = 1;\n for (; toStart < to.length; ++toStart) {\n if (to.charCodeAt(toStart) !== 47 /*/*/)\n break;\n }\n var toEnd = to.length;\n var toLen = toEnd - toStart;\n\n // Compare paths to find the longest common path from root\n var length = fromLen < toLen ? fromLen : toLen;\n var lastCommonSep = -1;\n var i = 0;\n for (; i <= length; ++i) {\n if (i === length) {\n if (toLen > length) {\n if (to.charCodeAt(toStart + i) === 47 /*/*/) {\n // We get here if `from` is the exact base path for `to`.\n // For example: from='/foo/bar'; to='/foo/bar/baz'\n return to.slice(toStart + i + 1);\n } else if (i === 0) {\n // We get here if `from` is the root\n // For example: from='/'; to='/foo'\n return to.slice(toStart + i);\n }\n } else if (fromLen > length) {\n if (from.charCodeAt(fromStart + i) === 47 /*/*/) {\n // We get here if `to` is the exact base path for `from`.\n // For example: from='/foo/bar/baz'; to='/foo/bar'\n lastCommonSep = i;\n } else if (i === 0) {\n // We get here if `to` is the root.\n // For example: from='/foo'; to='/'\n lastCommonSep = 0;\n }\n }\n break;\n }\n var fromCode = from.charCodeAt(fromStart + i);\n var toCode = to.charCodeAt(toStart + i);\n if (fromCode !== toCode)\n break;\n else if (fromCode === 47 /*/*/)\n lastCommonSep = i;\n }\n\n var out = '';\n // Generate the relative path based on the path difference between `to`\n // and `from`\n for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {\n if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {\n if (out.length === 0)\n out += '..';\n else\n out += '/..';\n }\n }\n\n // Lastly, append the rest of the destination (`to`) path that comes after\n // the common path parts\n if (out.length > 0)\n return out + to.slice(toStart + lastCommonSep);\n else {\n toStart += lastCommonSep;\n if (to.charCodeAt(toStart) === 47 /*/*/)\n ++toStart;\n return to.slice(toStart);\n }\n },\n\n _makeLong: function _makeLong(path) {\n return path;\n },\n\n dirname: function dirname(path) {\n assertPath(path);\n if (path.length === 0) return '.';\n var code = path.charCodeAt(0);\n var hasRoot = code === 47 /*/*/;\n var end = -1;\n var matchedSlash = true;\n for (var i = path.length - 1; i >= 1; --i) {\n code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n if (!matchedSlash) {\n end = i;\n break;\n }\n } else {\n // We saw the first non-path separator\n matchedSlash = false;\n }\n }\n\n if (end === -1) return hasRoot ? '/' : '.';\n if (hasRoot && end === 1) return '//';\n return path.slice(0, end);\n },\n\n basename: function basename(path, ext) {\n if (ext !== undefined && typeof ext !== 'string') throw new TypeError('\"ext\" argument must be a string');\n assertPath(path);\n\n var start = 0;\n var end = -1;\n var matchedSlash = true;\n var i;\n\n if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {\n if (ext.length === path.length && ext === path) return '';\n var extIdx = ext.length - 1;\n var firstNonSlashEnd = -1;\n for (i = path.length - 1; i >= 0; --i) {\n var code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else {\n if (firstNonSlashEnd === -1) {\n // We saw the first non-path separator, remember this index in case\n // we need it if the extension ends up not matching\n matchedSlash = false;\n firstNonSlashEnd = i + 1;\n }\n if (extIdx >= 0) {\n // Try to match the explicit extension\n if (code === ext.charCodeAt(extIdx)) {\n if (--extIdx === -1) {\n // We matched the extension, so mark this as the end of our path\n // component\n end = i;\n }\n } else {\n // Extension does not match, so our result is the entire path\n // component\n extIdx = -1;\n end = firstNonSlashEnd;\n }\n }\n }\n }\n\n if (start === end) end = firstNonSlashEnd;else if (end === -1) end = path.length;\n return path.slice(start, end);\n } else {\n for (i = path.length - 1; i >= 0; --i) {\n if (path.charCodeAt(i) === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // path component\n matchedSlash = false;\n end = i + 1;\n }\n }\n\n if (end === -1) return '';\n return path.slice(start, end);\n }\n },\n\n extname: function extname(path) {\n assertPath(path);\n var startDot = -1;\n var startPart = 0;\n var end = -1;\n var matchedSlash = true;\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n var preDotState = 0;\n for (var i = path.length - 1; i >= 0; --i) {\n var code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (code === 46 /*.*/) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1)\n startDot = i;\n else if (preDotState !== 1)\n preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (startDot === -1 || end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n return '';\n }\n return path.slice(startDot, end);\n },\n\n format: function format(pathObject) {\n if (pathObject === null || typeof pathObject !== 'object') {\n throw new TypeError('The \"pathObject\" argument must be of type Object. Received type ' + typeof pathObject);\n }\n return _format('/', pathObject);\n },\n\n parse: function parse(path) {\n assertPath(path);\n\n var ret = { root: '', dir: '', base: '', ext: '', name: '' };\n if (path.length === 0) return ret;\n var code = path.charCodeAt(0);\n var isAbsolute = code === 47 /*/*/;\n var start;\n if (isAbsolute) {\n ret.root = '/';\n start = 1;\n } else {\n start = 0;\n }\n var startDot = -1;\n var startPart = 0;\n var end = -1;\n var matchedSlash = true;\n var i = path.length - 1;\n\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n var preDotState = 0;\n\n // Get non-dir info\n for (; i >= start; --i) {\n code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (code === 46 /*.*/) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1) startDot = i;else if (preDotState !== 1) preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (startDot === -1 || end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n if (end !== -1) {\n if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);else ret.base = ret.name = path.slice(startPart, end);\n }\n } else {\n if (startPart === 0 && isAbsolute) {\n ret.name = path.slice(1, startDot);\n ret.base = path.slice(1, end);\n } else {\n ret.name = path.slice(startPart, startDot);\n ret.base = path.slice(startPart, end);\n }\n ret.ext = path.slice(startDot, end);\n }\n\n if (startPart > 0) ret.dir = path.slice(0, startPart - 1);else if (isAbsolute) ret.dir = '/';\n\n return ret;\n },\n\n sep: '/',\n delimiter: ':',\n win32: null,\n posix: null\n};\n\nposix.posix = posix;\n\nmodule.exports = posix;\n", "// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n", "// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};", "__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))", "// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\n\n// !!!!!\n// SEE https://github.com/microsoft/vscode/blob/master/src/vs/base/common/platform.ts\n// !!!!!\n\ndeclare const process: { platform: 'win32' };\ndeclare const navigator: { userAgent: string };\n\nexport let isWindows: boolean;\n\nif (typeof process === 'object') {\n\tisWindows = process.platform === 'win32';\n} else if (typeof navigator === 'object') {\n\tlet userAgent = navigator.userAgent;\n\tisWindows = userAgent.indexOf('Windows') >= 0;\n}\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\n\nimport { CharCode } from './charCode'\nimport { isWindows } from './platform';\n\nconst _schemePattern = /^\\w[\\w\\d+.-]*$/;\nconst _singleSlashStart = /^\\//;\nconst _doubleSlashStart = /^\\/\\//;\n\nfunction _validateUri(ret: URI, _strict?: boolean): void {\n\n\t// scheme, must be set\n\tif (!ret.scheme && _strict) {\n\t\tthrow new Error(`[UriError]: Scheme is missing: {scheme: \"\", authority: \"${ret.authority}\", path: \"${ret.path}\", query: \"${ret.query}\", fragment: \"${ret.fragment}\"}`);\n\t}\n\n\t// scheme, https://tools.ietf.org/html/rfc3986#section-3.1\n\t// ALPHA *( ALPHA / DIGIT / \"+\" / \"-\" / \".\" )\n\tif (ret.scheme && !_schemePattern.test(ret.scheme)) {\n\t\tthrow new Error('[UriError]: Scheme contains illegal characters.');\n\t}\n\n\t// path, http://tools.ietf.org/html/rfc3986#section-3.3\n\t// If a URI contains an authority component, then the path component\n\t// must either be empty or begin with a slash (\"/\") character. If a URI\n\t// does not contain an authority component, then the path cannot begin\n\t// with two slash characters (\"//\").\n\tif (ret.path) {\n\t\tif (ret.authority) {\n\t\t\tif (!_singleSlashStart.test(ret.path)) {\n\t\t\t\tthrow new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash (\"/\") character');\n\t\t\t}\n\t\t} else {\n\t\t\tif (_doubleSlashStart.test(ret.path)) {\n\t\t\t\tthrow new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters (\"//\")');\n\t\t\t}\n\t\t}\n\t}\n}\n\n// for a while we allowed uris *without* schemes and this is the migration\n// for them, e.g. an uri without scheme and without strict-mode warns and falls\n// back to the file-scheme. that should cause the least carnage and still be a\n// clear warning\nfunction _schemeFix(scheme: string, _strict: boolean): string {\n\tif (!scheme && !_strict) {\n\t\treturn 'file';\n\t}\n\treturn scheme;\n}\n\n// implements a bit of https://tools.ietf.org/html/rfc3986#section-5\nfunction _referenceResolution(scheme: string, path: string): string {\n\n\t// the slash-character is our 'default base' as we don't\n\t// support constructing URIs relative to other URIs. This\n\t// also means that we alter and potentially break paths.\n\t// see https://tools.ietf.org/html/rfc3986#section-5.1.4\n\tswitch (scheme) {\n\t\tcase 'https':\n\t\tcase 'http':\n\t\tcase 'file':\n\t\t\tif (!path) {\n\t\t\t\tpath = _slash;\n\t\t\t} else if (path[0] !== _slash) {\n\t\t\t\tpath = _slash + path;\n\t\t\t}\n\t\t\tbreak;\n\t}\n\treturn path;\n}\n\nconst _empty = '';\nconst _slash = '/';\nconst _regexp = /^(([^:/?#]+?):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?/;\n\n/**\n * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986.\n * This class is a simple parser which creates the basic component parts\n * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation\n * and encoding.\n *\n * ```txt\n * foo://example.com:8042/over/there?name=ferret#nose\n * \\_/ \\______________/\\_________/ \\_________/ \\__/\n * | | | | |\n * scheme authority path query fragment\n * | _____________________|__\n * / \\ / \\\n * urn:example:animal:ferret:nose\n * ```\n */\nexport class URI implements UriComponents {\n\n\tstatic isUri(thing: any): thing is URI {\n\t\tif (thing instanceof URI) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!thing) {\n\t\t\treturn false;\n\t\t}\n\t\treturn typeof (thing).authority === 'string'\n\t\t\t&& typeof (thing).fragment === 'string'\n\t\t\t&& typeof (thing).path === 'string'\n\t\t\t&& typeof (thing).query === 'string'\n\t\t\t&& typeof (thing).scheme === 'string'\n\t\t\t&& typeof (thing).fsPath === 'string'\n\t\t\t&& typeof (thing).with === 'function'\n\t\t\t&& typeof (thing).toString === 'function';\n\t}\n\n\t/**\n\t * scheme is the 'http' part of 'http://www.example.com/some/path?query#fragment'.\n\t * The part before the first colon.\n\t */\n\treadonly scheme: string;\n\n\t/**\n\t * authority is the 'www.example.com' part of 'http://www.example.com/some/path?query#fragment'.\n\t * The part between the first double slashes and the next slash.\n\t */\n\treadonly authority: string;\n\n\t/**\n\t * path is the '/some/path' part of 'http://www.example.com/some/path?query#fragment'.\n\t */\n\treadonly path: string;\n\n\t/**\n\t * query is the 'query' part of 'http://www.example.com/some/path?query#fragment'.\n\t */\n\treadonly query: string;\n\n\t/**\n\t * fragment is the 'fragment' part of 'http://www.example.com/some/path?query#fragment'.\n\t */\n\treadonly fragment: string;\n\n\t/**\n\t * @internal\n\t */\n\tprotected constructor(scheme: string, authority?: string, path?: string, query?: string, fragment?: string, _strict?: boolean);\n\n\t/**\n\t * @internal\n\t */\n\tprotected constructor(components: UriComponents);\n\n\t/**\n\t * @internal\n\t */\n\tprotected constructor(schemeOrData: string | UriComponents, authority?: string, path?: string, query?: string, fragment?: string, _strict: boolean = false) {\n\n\t\tif (typeof schemeOrData === 'object') {\n\t\t\tthis.scheme = schemeOrData.scheme || _empty;\n\t\t\tthis.authority = schemeOrData.authority || _empty;\n\t\t\tthis.path = schemeOrData.path || _empty;\n\t\t\tthis.query = schemeOrData.query || _empty;\n\t\t\tthis.fragment = schemeOrData.fragment || _empty;\n\t\t\t// no validation because it's this URI\n\t\t\t// that creates uri components.\n\t\t\t// _validateUri(this);\n\t\t} else {\n\t\t\tthis.scheme = _schemeFix(schemeOrData, _strict);\n\t\t\tthis.authority = authority || _empty;\n\t\t\tthis.path = _referenceResolution(this.scheme, path || _empty);\n\t\t\tthis.query = query || _empty;\n\t\t\tthis.fragment = fragment || _empty;\n\n\t\t\t_validateUri(this, _strict);\n\t\t}\n\t}\n\n\t// ---- filesystem path -----------------------\n\n\t/**\n\t * Returns a string representing the corresponding file system path of this URI.\n\t * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the\n\t * platform specific path separator.\n\t *\n\t * * Will *not* validate the path for invalid characters and semantics.\n\t * * Will *not* look at the scheme of this URI.\n\t * * The result shall *not* be used for display purposes but for accessing a file on disk.\n\t *\n\t *\n\t * The *difference* to `URI#path` is the use of the platform specific separator and the handling\n\t * of UNC paths. See the below sample of a file-uri with an authority (UNC path).\n\t *\n\t * ```ts\n\t\tconst u = URI.parse('file://server/c$/folder/file.txt')\n\t\tu.authority === 'server'\n\t\tu.path === '/shares/c$/file.txt'\n\t\tu.fsPath === '\\\\server\\c$\\folder\\file.txt'\n\t```\n\t *\n\t * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path,\n\t * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working\n\t * with URIs that represent files on disk (`file` scheme).\n\t */\n\tget fsPath(): string {\n\t\t// if (this.scheme !== 'file') {\n\t\t// \tconsole.warn(`[UriError] calling fsPath with scheme ${this.scheme}`);\n\t\t// }\n\t\treturn uriToFsPath(this, false);\n\t}\n\n\t// ---- modify to new -------------------------\n\n\twith(change: { scheme?: string; authority?: string | null; path?: string | null; query?: string | null; fragment?: string | null }): URI {\n\n\t\tif (!change) {\n\t\t\treturn this;\n\t\t}\n\n\t\tlet { scheme, authority, path, query, fragment } = change;\n\t\tif (scheme === undefined) {\n\t\t\tscheme = this.scheme;\n\t\t} else if (scheme === null) {\n\t\t\tscheme = _empty;\n\t\t}\n\t\tif (authority === undefined) {\n\t\t\tauthority = this.authority;\n\t\t} else if (authority === null) {\n\t\t\tauthority = _empty;\n\t\t}\n\t\tif (path === undefined) {\n\t\t\tpath = this.path;\n\t\t} else if (path === null) {\n\t\t\tpath = _empty;\n\t\t}\n\t\tif (query === undefined) {\n\t\t\tquery = this.query;\n\t\t} else if (query === null) {\n\t\t\tquery = _empty;\n\t\t}\n\t\tif (fragment === undefined) {\n\t\t\tfragment = this.fragment;\n\t\t} else if (fragment === null) {\n\t\t\tfragment = _empty;\n\t\t}\n\n\t\tif (scheme === this.scheme\n\t\t\t&& authority === this.authority\n\t\t\t&& path === this.path\n\t\t\t&& query === this.query\n\t\t\t&& fragment === this.fragment) {\n\n\t\t\treturn this;\n\t\t}\n\n\t\treturn new Uri(scheme, authority, path, query, fragment);\n\t}\n\n\t// ---- parse & validate ------------------------\n\n\t/**\n\t * Creates a new URI from a string, e.g. `http://www.example.com/some/path`,\n\t * `file:///usr/home`, or `scheme:with/path`.\n\t *\n\t * @param value A string which represents an URI (see `URI#toString`).\n\t */\n\tstatic parse(value: string, _strict: boolean = false): URI {\n\t\tconst match = _regexp.exec(value);\n\t\tif (!match) {\n\t\t\treturn new Uri(_empty, _empty, _empty, _empty, _empty);\n\t\t}\n\t\treturn new Uri(\n\t\t\tmatch[2] || _empty,\n\t\t\tpercentDecode(match[4] || _empty),\n\t\t\tpercentDecode(match[5] || _empty),\n\t\t\tpercentDecode(match[7] || _empty),\n\t\t\tpercentDecode(match[9] || _empty),\n\t\t\t_strict\n\t\t);\n\t}\n\n\t/**\n\t * Creates a new URI from a file system path, e.g. `c:\\my\\files`,\n\t * `/usr/home`, or `\\\\server\\share\\some\\path`.\n\t *\n\t * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument\n\t * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as**\n\t * `URI.parse('file://' + path)` because the path might contain characters that are\n\t * interpreted (# and ?). See the following sample:\n\t * ```ts\n\tconst good = URI.file('/coding/c#/project1');\n\tgood.scheme === 'file';\n\tgood.path === '/coding/c#/project1';\n\tgood.fragment === '';\n\tconst bad = URI.parse('file://' + '/coding/c#/project1');\n\tbad.scheme === 'file';\n\tbad.path === '/coding/c'; // path is now broken\n\tbad.fragment === '/project1';\n\t```\n\t *\n\t * @param path A file system path (see `URI#fsPath`)\n\t */\n\tstatic file(path: string): URI {\n\n\t\tlet authority = _empty;\n\n\t\t// normalize to fwd-slashes on windows,\n\t\t// on other systems bwd-slashes are valid\n\t\t// filename character, eg /f\\oo/ba\\r.txt\n\t\tif (isWindows) {\n\t\t\tpath = path.replace(/\\\\/g, _slash);\n\t\t}\n\n\t\t// check for authority as used in UNC shares\n\t\t// or use the path as given\n\t\tif (path[0] === _slash && path[1] === _slash) {\n\t\t\tconst idx = path.indexOf(_slash, 2);\n\t\t\tif (idx === -1) {\n\t\t\t\tauthority = path.substring(2);\n\t\t\t\tpath = _slash;\n\t\t\t} else {\n\t\t\t\tauthority = path.substring(2, idx);\n\t\t\t\tpath = path.substring(idx) || _slash;\n\t\t\t}\n\t\t}\n\n\t\treturn new Uri('file', authority, path, _empty, _empty);\n\t}\n\n\tstatic from(components: { scheme: string; authority?: string; path?: string; query?: string; fragment?: string }): URI {\n\t\tconst result = new Uri(\n\t\t\tcomponents.scheme,\n\t\t\tcomponents.authority,\n\t\t\tcomponents.path,\n\t\t\tcomponents.query,\n\t\t\tcomponents.fragment,\n\t\t);\n\t\t_validateUri(result, true);\n\t\treturn result;\n\t}\n\n\t// ---- printing/externalize ---------------------------\n\n\t/**\n\t * Creates a string representation for this URI. It's guaranteed that calling\n\t * `URI.parse` with the result of this function creates an URI which is equal\n\t * to this URI.\n\t *\n\t * * The result shall *not* be used for display purposes but for externalization or transport.\n\t * * The result will be encoded using the percentage encoding and encoding happens mostly\n\t * ignore the scheme-specific encoding rules.\n\t *\n\t * @param skipEncoding Do not encode the result, default is `false`\n\t */\n\ttoString(skipEncoding: boolean = false): string {\n\t\treturn _asFormatted(this, skipEncoding);\n\t}\n\n\ttoJSON(): UriComponents {\n\t\treturn this;\n\t}\n\n\tstatic revive(data: UriComponents | URI): URI;\n\tstatic revive(data: UriComponents | URI | undefined): URI | undefined;\n\tstatic revive(data: UriComponents | URI | null): URI | null;\n\tstatic revive(data: UriComponents | URI | undefined | null): URI | undefined | null;\n\tstatic revive(data: UriComponents | URI | undefined | null): URI | undefined | null {\n\t\tif (!data) {\n\t\t\treturn data;\n\t\t} else if (data instanceof URI) {\n\t\t\treturn data;\n\t\t} else {\n\t\t\tconst result = new Uri(data);\n\t\t\tresult._formatted = (data).external;\n\t\t\tresult._fsPath = (data)._sep === _pathSepMarker ? (data).fsPath : null;\n\t\t\treturn result;\n\t\t}\n\t}\n}\n\nexport interface UriComponents {\n\tscheme: string;\n\tauthority: string;\n\tpath: string;\n\tquery: string;\n\tfragment: string;\n}\n\ninterface UriState extends UriComponents {\n\t$mid: number;\n\texternal: string;\n\tfsPath: string;\n\t_sep: 1 | undefined;\n}\n\nconst _pathSepMarker = isWindows ? 1 : undefined;\n\n// This class exists so that URI is compatible with vscode.Uri (API).\nclass Uri extends URI {\n\n\t_formatted: string | null = null;\n\t_fsPath: string | null = null;\n\n\toverride get fsPath(): string {\n\t\tif (!this._fsPath) {\n\t\t\tthis._fsPath = uriToFsPath(this, false);\n\t\t}\n\t\treturn this._fsPath;\n\t}\n\n\toverride toString(skipEncoding: boolean = false): string {\n\t\tif (!skipEncoding) {\n\t\t\tif (!this._formatted) {\n\t\t\t\tthis._formatted = _asFormatted(this, false);\n\t\t\t}\n\t\t\treturn this._formatted;\n\t\t} else {\n\t\t\t// we don't cache that\n\t\t\treturn _asFormatted(this, true);\n\t\t}\n\t}\n\n\toverride toJSON(): UriComponents {\n\t\tconst res = {\n\t\t\t$mid: 1\n\t\t};\n\t\t// cached state\n\t\tif (this._fsPath) {\n\t\t\tres.fsPath = this._fsPath;\n\t\t\tres._sep = _pathSepMarker;\n\t\t}\n\t\tif (this._formatted) {\n\t\t\tres.external = this._formatted;\n\t\t}\n\t\t// uri components\n\t\tif (this.path) {\n\t\t\tres.path = this.path;\n\t\t}\n\t\tif (this.scheme) {\n\t\t\tres.scheme = this.scheme;\n\t\t}\n\t\tif (this.authority) {\n\t\t\tres.authority = this.authority;\n\t\t}\n\t\tif (this.query) {\n\t\t\tres.query = this.query;\n\t\t}\n\t\tif (this.fragment) {\n\t\t\tres.fragment = this.fragment;\n\t\t}\n\t\treturn res;\n\t}\n}\n\n// reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2\nconst encodeTable: { [ch: number]: string } = {\n\t[CharCode.Colon]: '%3A', // gen-delims\n\t[CharCode.Slash]: '%2F',\n\t[CharCode.QuestionMark]: '%3F',\n\t[CharCode.Hash]: '%23',\n\t[CharCode.OpenSquareBracket]: '%5B',\n\t[CharCode.CloseSquareBracket]: '%5D',\n\t[CharCode.AtSign]: '%40',\n\n\t[CharCode.ExclamationMark]: '%21', // sub-delims\n\t[CharCode.DollarSign]: '%24',\n\t[CharCode.Ampersand]: '%26',\n\t[CharCode.SingleQuote]: '%27',\n\t[CharCode.OpenParen]: '%28',\n\t[CharCode.CloseParen]: '%29',\n\t[CharCode.Asterisk]: '%2A',\n\t[CharCode.Plus]: '%2B',\n\t[CharCode.Comma]: '%2C',\n\t[CharCode.Semicolon]: '%3B',\n\t[CharCode.Equals]: '%3D',\n\n\t[CharCode.Space]: '%20',\n};\n\nfunction encodeURIComponentFast(uriComponent: string, isPath: boolean, isAuthority: boolean): string {\n\tlet res: string | undefined = undefined;\n\tlet nativeEncodePos = -1;\n\n\tfor (let pos = 0; pos < uriComponent.length; pos++) {\n\t\tconst code = uriComponent.charCodeAt(pos);\n\n\t\t// unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3\n\t\tif (\n\t\t\t(code >= CharCode.a && code <= CharCode.z)\n\t\t\t|| (code >= CharCode.A && code <= CharCode.Z)\n\t\t\t|| (code >= CharCode.Digit0 && code <= CharCode.Digit9)\n\t\t\t|| code === CharCode.Dash\n\t\t\t|| code === CharCode.Period\n\t\t\t|| code === CharCode.Underline\n\t\t\t|| code === CharCode.Tilde\n\t\t\t|| (isPath && code === CharCode.Slash)\n\t\t\t|| (isAuthority && code === CharCode.OpenSquareBracket)\n\t\t\t|| (isAuthority && code === CharCode.CloseSquareBracket)\n\t\t\t|| (isAuthority && code === CharCode.Colon)\n\t\t) {\n\t\t\t// check if we are delaying native encode\n\t\t\tif (nativeEncodePos !== -1) {\n\t\t\t\tres += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));\n\t\t\t\tnativeEncodePos = -1;\n\t\t\t}\n\t\t\t// check if we write into a new string (by default we try to return the param)\n\t\t\tif (res !== undefined) {\n\t\t\t\tres += uriComponent.charAt(pos);\n\t\t\t}\n\n\t\t} else {\n\t\t\t// encoding needed, we need to allocate a new string\n\t\t\tif (res === undefined) {\n\t\t\t\tres = uriComponent.substr(0, pos);\n\t\t\t}\n\n\t\t\t// check with default table first\n\t\t\tconst escaped = encodeTable[code];\n\t\t\tif (escaped !== undefined) {\n\n\t\t\t\t// check if we are delaying native encode\n\t\t\t\tif (nativeEncodePos !== -1) {\n\t\t\t\t\tres += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));\n\t\t\t\t\tnativeEncodePos = -1;\n\t\t\t\t}\n\n\t\t\t\t// append escaped variant to result\n\t\t\t\tres += escaped;\n\n\t\t\t} else if (nativeEncodePos === -1) {\n\t\t\t\t// use native encode only when needed\n\t\t\t\tnativeEncodePos = pos;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (nativeEncodePos !== -1) {\n\t\tres += encodeURIComponent(uriComponent.substring(nativeEncodePos));\n\t}\n\n\treturn res !== undefined ? res : uriComponent;\n}\n\nfunction encodeURIComponentMinimal(path: string): string {\n\tlet res: string | undefined = undefined;\n\tfor (let pos = 0; pos < path.length; pos++) {\n\t\tconst code = path.charCodeAt(pos);\n\t\tif (code === CharCode.Hash || code === CharCode.QuestionMark) {\n\t\t\tif (res === undefined) {\n\t\t\t\tres = path.substr(0, pos);\n\t\t\t}\n\t\t\tres += encodeTable[code];\n\t\t} else {\n\t\t\tif (res !== undefined) {\n\t\t\t\tres += path[pos];\n\t\t\t}\n\t\t}\n\t}\n\treturn res !== undefined ? res : path;\n}\n\n/**\n * Compute `fsPath` for the given uri\n */\nexport function uriToFsPath(uri: URI, keepDriveLetterCasing: boolean): string {\n\n\tlet value: string;\n\tif (uri.authority && uri.path.length > 1 && uri.scheme === 'file') {\n\t\t// unc path: file://shares/c$/far/boo\n\t\tvalue = `//${uri.authority}${uri.path}`;\n\t} else if (\n\t\turi.path.charCodeAt(0) === CharCode.Slash\n\t\t&& (uri.path.charCodeAt(1) >= CharCode.A && uri.path.charCodeAt(1) <= CharCode.Z || uri.path.charCodeAt(1) >= CharCode.a && uri.path.charCodeAt(1) <= CharCode.z)\n\t\t&& uri.path.charCodeAt(2) === CharCode.Colon\n\t) {\n\t\tif (!keepDriveLetterCasing) {\n\t\t\t// windows drive letter: file:///c:/far/boo\n\t\t\tvalue = uri.path[1].toLowerCase() + uri.path.substr(2);\n\t\t} else {\n\t\t\tvalue = uri.path.substr(1);\n\t\t}\n\t} else {\n\t\t// other path\n\t\tvalue = uri.path;\n\t}\n\tif (isWindows) {\n\t\tvalue = value.replace(/\\//g, '\\\\');\n\t}\n\treturn value;\n}\n\n/**\n * Create the external version of a uri\n */\nfunction _asFormatted(uri: URI, skipEncoding: boolean): string {\n\n\tconst encoder = !skipEncoding\n\t\t? encodeURIComponentFast\n\t\t: encodeURIComponentMinimal;\n\n\tlet res = '';\n\tlet { scheme, authority, path, query, fragment } = uri;\n\tif (scheme) {\n\t\tres += scheme;\n\t\tres += ':';\n\t}\n\tif (authority || scheme === 'file') {\n\t\tres += _slash;\n\t\tres += _slash;\n\t}\n\tif (authority) {\n\t\tlet idx = authority.indexOf('@');\n\t\tif (idx !== -1) {\n\t\t\t// @\n\t\t\tconst userinfo = authority.substr(0, idx);\n\t\t\tauthority = authority.substr(idx + 1);\n\t\t\tidx = userinfo.lastIndexOf(':');\n\t\t\tif (idx === -1) {\n\t\t\t\tres += encoder(userinfo, false, false);\n\t\t\t} else {\n\t\t\t\t// :@\n\t\t\t\tres += encoder(userinfo.substr(0, idx), false, false);\n\t\t\t\tres += ':';\n\t\t\t\tres += encoder(userinfo.substr(idx + 1), false, true);\n\t\t\t}\n\t\t\tres += '@';\n\t\t}\n\t\tauthority = authority.toLowerCase();\n\t\tidx = authority.lastIndexOf(':');\n\t\tif (idx === -1) {\n\t\t\tres += encoder(authority, false, true);\n\t\t} else {\n\t\t\t// :\n\t\t\tres += encoder(authority.substr(0, idx), false, true);\n\t\t\tres += authority.substr(idx);\n\t\t}\n\t}\n\tif (path) {\n\t\t// lower-case windows drive letters in /C:/fff or C:/fff\n\t\tif (path.length >= 3 && path.charCodeAt(0) === CharCode.Slash && path.charCodeAt(2) === CharCode.Colon) {\n\t\t\tconst code = path.charCodeAt(1);\n\t\t\tif (code >= CharCode.A && code <= CharCode.Z) {\n\t\t\t\tpath = `/${String.fromCharCode(code + 32)}:${path.substr(3)}`; // \"/c:\".length === 3\n\t\t\t}\n\t\t} else if (path.length >= 2 && path.charCodeAt(1) === CharCode.Colon) {\n\t\t\tconst code = path.charCodeAt(0);\n\t\t\tif (code >= CharCode.A && code <= CharCode.Z) {\n\t\t\t\tpath = `${String.fromCharCode(code + 32)}:${path.substr(2)}`; // \"/c:\".length === 3\n\t\t\t}\n\t\t}\n\t\t// encode the rest of the path\n\t\tres += encoder(path, true, false);\n\t}\n\tif (query) {\n\t\tres += '?';\n\t\tres += encoder(query, false, false);\n\t}\n\tif (fragment) {\n\t\tres += '#';\n\t\tres += !skipEncoding ? encodeURIComponentFast(fragment, false, false) : fragment;\n\t}\n\treturn res;\n}\n\n// --- decode\n\nfunction decodeURIComponentGraceful(str: string): string {\n\ttry {\n\t\treturn decodeURIComponent(str);\n\t} catch {\n\t\tif (str.length > 3) {\n\t\t\treturn str.substr(0, 3) + decodeURIComponentGraceful(str.substr(3));\n\t\t} else {\n\t\t\treturn str;\n\t\t}\n\t}\n}\n\nconst _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g;\n\nfunction percentDecode(str: string): string {\n\tif (!str.match(_rEncodedAsHex)) {\n\t\treturn str;\n\t}\n\treturn str.replace(_rEncodedAsHex, (match) => decodeURIComponentGraceful(match));\n}\n\n/**\n * Mapped-type that replaces all occurrences of URI with UriComponents\n */\nexport type UriDto = { [K in keyof T]: T[K] extends URI\n\t? UriComponents\n\t: UriDto };\n", "/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n'use strict';\n\nimport { CharCode } from './charCode';\nimport { URI } from './uri';\nimport * as nodePath from 'path';\n\nconst posixPath = nodePath.posix || nodePath;\nconst slash = '/';\n\nexport namespace Utils {\n\n /**\n * Joins one or more input paths to the path of URI. \n * '/' is used as the directory separation character. \n * \n * The resolved path will be normalized. That means:\n * - all '..' and '.' segments are resolved.\n * - multiple, sequential occurences of '/' are replaced by a single instance of '/'.\n * - trailing separators are preserved.\n * \n * @param uri The input URI.\n * @param paths The paths to be joined with the path of URI.\n * @returns A URI with the joined path. All other properties of the URI (scheme, authority, query, fragments, ...) will be taken from the input URI.\n */\n export function joinPath(uri: URI, ...paths: string[]): URI {\n return uri.with({ path: posixPath.join(uri.path, ...paths) });\n }\n\n\n /**\n * Resolves one or more paths against the path of a URI. \n * '/' is used as the directory separation character. \n * \n * The resolved path will be normalized. That means:\n * - all '..' and '.' segments are resolved. \n * - multiple, sequential occurences of '/' are replaced by a single instance of '/'.\n * - trailing separators are removed.\n * \n * @param uri The input URI.\n * @param paths The paths to resolve against the path of URI.\n * @returns A URI with the resolved path. All other properties of the URI (scheme, authority, query, fragments, ...) will be taken from the input URI.\n */\n export function resolvePath(uri: URI, ...paths: string[]): URI {\n let path = uri.path; \n let slashAdded = false;\n if (path[0] !== slash) {\n path = slash + path; // make the path abstract: for posixPath.resolve the first segments has to be absolute or cwd is used.\n slashAdded = true;\n }\n let resolvedPath = posixPath.resolve(path, ...paths);\n if (slashAdded && resolvedPath[0] === slash && !uri.authority) {\n resolvedPath = resolvedPath.substring(1);\n }\n return uri.with({ path: resolvedPath });\n }\n\n /**\n * Returns a URI where the path is the directory name of the input uri, similar to the Unix dirname command. \n * In the path, '/' is recognized as the directory separation character. Trailing directory separators are ignored.\n * The orignal URI is returned if the URIs path is empty or does not contain any path segments.\n * \n * @param uri The input URI.\n * @return The last segment of the URIs path.\n */\n export function dirname(uri: URI): URI {\n if (uri.path.length === 0 || uri.path === slash) {\n return uri;\n }\n let path = posixPath.dirname(uri.path);\n if (path.length === 1 && path.charCodeAt(0) === CharCode.Period) {\n path = '';\n }\n return uri.with({ path });\n }\n\n /**\n * Returns the last segment of the path of a URI, similar to the Unix basename command. \n * In the path, '/' is recognized as the directory separation character. Trailing directory separators are ignored.\n * The empty string is returned if the URIs path is empty or does not contain any path segments.\n * \n * @param uri The input URI.\n * @return The base name of the URIs path.\n */\n export function basename(uri: URI): string {\n return posixPath.basename(uri.path);\n }\n\n /**\n * Returns the extension name of the path of a URI, similar to the Unix extname command. \n * In the path, '/' is recognized as the directory separation character. Trailing directory separators are ignored.\n * The empty string is returned if the URIs path is empty or does not contain any path segments.\n * \n * @param uri The input URI.\n * @return The extension name of the URIs path.\n */\n export function extname(uri: URI): string {\n return posixPath.extname(uri.path);\n }\n}", "/******************************************************************************\r\n * Copyright 2022 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport { URI, Utils } from 'vscode-uri';\r\n\r\nexport { URI };\r\n\r\nexport namespace UriUtils {\r\n\r\n export const basename = Utils.basename;\r\n export const dirname = Utils.dirname;\r\n export const extname = Utils.extname;\r\n export const joinPath = Utils.joinPath;\r\n export const resolvePath = Utils.resolvePath;\r\n\r\n export function equals(a?: URI | string, b?: URI | string): boolean {\r\n return a?.toString() === b?.toString();\r\n }\r\n\r\n export function relative(from: URI | string, to: URI | string): string {\r\n const fromPath = typeof from === 'string' ? from : from.path;\r\n const toPath = typeof to === 'string' ? to : to.path;\r\n const fromParts = fromPath.split('/').filter(e => e.length > 0);\r\n const toParts = toPath.split('/').filter(e => e.length > 0);\r\n let i = 0;\r\n for (; i < fromParts.length; i++) {\r\n if (fromParts[i] !== toParts[i]) {\r\n break;\r\n }\r\n }\r\n const backPart = '../'.repeat(fromParts.length - i);\r\n const toPart = toParts.slice(i).join('/');\r\n return backPart + toPart;\r\n }\r\n\r\n export function normalize(uri: URI | string): string {\r\n return URI.parse(uri.toString()).toString();\r\n }\r\n\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\n/**\r\n * Re-export 'TextDocument' from 'vscode-languageserver-textdocument' for convenience,\r\n * including both type _and_ symbol (namespace), as we here and there also refer to the symbol,\r\n * the overhead is very small, just a few kilobytes.\r\n * Everything else of that package (at the time contributing) is also defined\r\n * in 'vscode-languageserver-protocol' or 'vscode-languageserver-types'.\r\n */\r\nexport { TextDocument } from 'vscode-languageserver-textdocument';\r\n\r\nimport type { Diagnostic, Range } from 'vscode-languageserver-types';\r\nimport type { FileSystemProvider } from './file-system-provider.js';\r\nimport type { ParseResult, ParserOptions } from '../parser/langium-parser.js';\r\nimport type { ServiceRegistry } from '../service-registry.js';\r\nimport type { LangiumSharedCoreServices } from '../services.js';\r\nimport type { AstNode, AstNodeDescription, Mutable, Reference } from '../syntax-tree.js';\r\nimport type { MultiMap } from '../utils/collections.js';\r\nimport type { Stream } from '../utils/stream.js';\r\nimport { TextDocument } from './documents.js';\r\nimport { CancellationToken } from '../utils/cancellation.js';\r\nimport { stream } from '../utils/stream.js';\r\nimport { URI } from '../utils/uri-utils.js';\r\n\r\n/**\r\n * A Langium document holds the parse result (AST and CST) and any additional state that is derived\r\n * from the AST, e.g. the result of scope precomputation.\r\n */\r\nexport interface LangiumDocument {\r\n /** The Uniform Resource Identifier (URI) of the document */\r\n readonly uri: URI;\r\n /** The text document used to convert between offsets and positions */\r\n readonly textDocument: TextDocument;\r\n /** The current state of the document */\r\n state: DocumentState;\r\n /** The parse result holds the Abstract Syntax Tree (AST) and potentially also parser / lexer errors */\r\n parseResult: ParseResult;\r\n /** Result of the scope precomputation phase */\r\n precomputedScopes?: PrecomputedScopes;\r\n /** An array of all cross-references found in the AST while linking */\r\n references: Reference[];\r\n /** Result of the validation phase */\r\n diagnostics?: Diagnostic[]\r\n}\r\n\r\n/**\r\n * A document is subject to several phases that are run in predefined order. Any state value implies that\r\n * smaller state values are finished as well.\r\n */\r\nexport enum DocumentState {\r\n /**\r\n * The text content has changed and needs to be parsed again. The AST held by this outdated\r\n * document instance is no longer valid.\r\n */\r\n Changed = 0,\r\n /**\r\n * An AST has been created from the text content. The document structure can be traversed,\r\n * but cross-references cannot be resolved yet. If necessary, the structure can be manipulated\r\n * at this stage as a preprocessing step.\r\n */\r\n Parsed = 1,\r\n /**\r\n * The `IndexManager` service has processed AST nodes of this document. This means the\r\n * exported symbols are available in the global scope and can be resolved from other documents.\r\n */\r\n IndexedContent = 2,\r\n /**\r\n * The `ScopeComputation` service has processed this document. This means the local symbols\r\n * are stored in a MultiMap so they can be looked up by the `ScopeProvider` service.\r\n * Once a document has reached this state, you may follow every reference - it will lazily\r\n * resolve its `ref` property and yield either the target AST node or `undefined` in case\r\n * the target is not in scope.\r\n */\r\n ComputedScopes = 3,\r\n /**\r\n * The `Linker` service has processed this document. All outgoing references have been\r\n * resolved or marked as erroneous.\r\n */\r\n Linked = 4,\r\n /**\r\n * The `IndexManager` service has processed AST node references of this document. This is\r\n * necessary to determine which documents are affected by a change in one of the workspace\r\n * documents.\r\n */\r\n IndexedReferences = 5,\r\n /**\r\n * The `DocumentValidator` service has processed this document. The language server listens\r\n * to the results of this phase and sends diagnostics to the client.\r\n */\r\n Validated = 6\r\n}\r\n\r\n/**\r\n * Result of the scope precomputation phase (`ScopeComputation` service).\r\n * It maps every AST node to the set of symbols that are visible in the subtree of that node.\r\n */\r\nexport type PrecomputedScopes = MultiMap\r\n\r\nexport interface DocumentSegment {\r\n readonly range: Range\r\n readonly offset: number\r\n readonly length: number\r\n readonly end: number\r\n}\r\n\r\n/**\r\n * Surrogate definition of the `TextDocuments` interface from the `vscode-languageserver` package.\r\n * No implementation object is expected to be offered by `LangiumCoreServices`, but only by `LangiumLSPServices`.\r\n */\r\nexport type TextDocumentProvider = {\r\n get(uri: string | URI): TextDocument | undefined\r\n}\r\n\r\n/**\r\n * Shared service for creating `LangiumDocument` instances.\r\n *\r\n * Register a custom implementation if special (additional) behavior is required for your language(s).\r\n * Note: If you specialize {@link fromString} or {@link fromTextDocument} you probably might want to\r\n * specialize {@link update}, too!\r\n */\r\nexport interface LangiumDocumentFactory {\r\n /**\r\n * Create a Langium document from a `TextDocument` (usually associated with a file).\r\n */\r\n fromTextDocument(textDocument: TextDocument, uri?: URI, options?: ParserOptions): LangiumDocument;\r\n /**\r\n * Create a Langium document from a `TextDocument` asynchronously. This action can be cancelled if a cancellable parser implementation has been provided.\r\n */\r\n fromTextDocument(textDocument: TextDocument, uri: URI | undefined, cancellationToken: CancellationToken): Promise>;\r\n\r\n /**\r\n * Create an Langium document from an in-memory string.\r\n */\r\n fromString(text: string, uri: URI, options?: ParserOptions): LangiumDocument;\r\n /**\r\n * Create a Langium document from an in-memory string asynchronously. This action can be cancelled if a cancellable parser implementation has been provided.\r\n */\r\n fromString(text: string, uri: URI, cancellationToken: CancellationToken): Promise>;\r\n\r\n /**\r\n * Create an Langium document from a model that has been constructed in memory.\r\n */\r\n fromModel(model: T, uri: URI): LangiumDocument;\r\n\r\n /**\r\n * Create an Langium document from a specified `URI`. The factory will use the `FileSystemAccess` service to read the file.\r\n */\r\n fromUri(uri: URI, cancellationToken?: CancellationToken): Promise>;\r\n\r\n /**\r\n * Update the given document after changes in the corresponding textual representation.\r\n * Method is called by the document builder after it has been requested to build an existing\r\n * document and the document's state is {@link DocumentState.Changed}.\r\n * The text parsing is expected to be done the same way as in {@link fromTextDocument}\r\n * and {@link fromString}.\r\n */\r\n update(document: LangiumDocument, cancellationToken: CancellationToken): Promise>\r\n}\r\n\r\nexport class DefaultLangiumDocumentFactory implements LangiumDocumentFactory {\r\n\r\n protected readonly serviceRegistry: ServiceRegistry;\r\n protected readonly textDocuments?: TextDocumentProvider;\r\n protected readonly fileSystemProvider: FileSystemProvider;\r\n\r\n constructor(services: LangiumSharedCoreServices) {\r\n this.serviceRegistry = services.ServiceRegistry;\r\n this.textDocuments = services.workspace.TextDocuments;\r\n this.fileSystemProvider = services.workspace.FileSystemProvider;\r\n }\r\n\r\n async fromUri(uri: URI, cancellationToken = CancellationToken.None): Promise> {\r\n const content = await this.fileSystemProvider.readFile(uri);\r\n return this.createAsync(uri, content, cancellationToken);\r\n }\r\n\r\n fromTextDocument(textDocument: TextDocument, uri?: URI, options?: ParserOptions): LangiumDocument;\r\n fromTextDocument(textDocument: TextDocument, uri: URI | undefined, cancellationToken: CancellationToken): Promise>;\r\n fromTextDocument(textDocument: TextDocument, uri?: URI, token?: CancellationToken | ParserOptions): LangiumDocument | Promise> {\r\n uri = uri ?? URI.parse(textDocument.uri);\r\n if (CancellationToken.is(token)) {\r\n return this.createAsync(uri, textDocument, token);\r\n } else {\r\n return this.create(uri, textDocument, token);\r\n }\r\n }\r\n\r\n fromString(text: string, uri: URI, options?: ParserOptions): LangiumDocument;\r\n fromString(text: string, uri: URI, cancellationToken: CancellationToken): Promise>;\r\n fromString(text: string, uri: URI, token?: CancellationToken | ParserOptions): LangiumDocument | Promise> {\r\n if (CancellationToken.is(token)) {\r\n return this.createAsync(uri, text, token);\r\n } else {\r\n return this.create(uri, text, token);\r\n }\r\n }\r\n\r\n fromModel(model: T, uri: URI): LangiumDocument {\r\n return this.create(uri, { $model: model });\r\n }\r\n\r\n protected create(uri: URI, content: string | TextDocument | { $model: T }, options?: ParserOptions): LangiumDocument {\r\n if (typeof content === 'string') {\r\n const parseResult = this.parse(uri, content, options);\r\n return this.createLangiumDocument(parseResult, uri, undefined, content);\r\n\r\n } else if ('$model' in content) {\r\n const parseResult = { value: content.$model, parserErrors: [], lexerErrors: [] };\r\n return this.createLangiumDocument(parseResult, uri);\r\n\r\n } else {\r\n const parseResult = this.parse(uri, content.getText(), options);\r\n return this.createLangiumDocument(parseResult, uri, content);\r\n }\r\n }\r\n\r\n protected async createAsync(uri: URI, content: string | TextDocument, cancelToken: CancellationToken): Promise> {\r\n if (typeof content === 'string') {\r\n const parseResult = await this.parseAsync(uri, content, cancelToken);\r\n return this.createLangiumDocument(parseResult, uri, undefined, content);\r\n } else {\r\n const parseResult = await this.parseAsync(uri, content.getText(), cancelToken);\r\n return this.createLangiumDocument(parseResult, uri, content);\r\n }\r\n }\r\n\r\n /**\r\n * Create a LangiumDocument from a given parse result.\r\n *\r\n * A TextDocument is created on demand if it is not provided as argument here. Usually this\r\n * should not be necessary because the main purpose of the TextDocument is to convert between\r\n * text ranges and offsets, which is done solely in LSP request handling.\r\n *\r\n * With the introduction of {@link update} below this method is supposed to be mainly called\r\n * during workspace initialization and on addition/recognition of new files, while changes in\r\n * existing documents are processed via {@link update}.\r\n */\r\n protected createLangiumDocument(parseResult: ParseResult, uri: URI, textDocument?: TextDocument, text?: string): LangiumDocument {\r\n let document: LangiumDocument;\r\n if (textDocument) {\r\n document = {\r\n parseResult,\r\n uri,\r\n state: DocumentState.Parsed,\r\n references: [],\r\n textDocument\r\n };\r\n } else {\r\n const textDocumentGetter = this.createTextDocumentGetter(uri, text);\r\n document = {\r\n parseResult,\r\n uri,\r\n state: DocumentState.Parsed,\r\n references: [],\r\n get textDocument() {\r\n return textDocumentGetter();\r\n }\r\n };\r\n }\r\n (parseResult.value as Mutable).$document = document;\r\n return document;\r\n }\r\n\r\n async update(document: Mutable>, cancellationToken: CancellationToken): Promise> {\r\n // The CST full text property contains the original text that was used to create the AST.\r\n const oldText = document.parseResult.value.$cstNode?.root.fullText;\r\n const textDocument = this.textDocuments?.get(document.uri.toString());\r\n const text = textDocument ? textDocument.getText() : await this.fileSystemProvider.readFile(document.uri);\r\n\r\n if (textDocument) {\r\n Object.defineProperty(\r\n document,\r\n 'textDocument',\r\n {\r\n value: textDocument\r\n }\r\n );\r\n } else {\r\n const textDocumentGetter = this.createTextDocumentGetter(document.uri, text);\r\n Object.defineProperty(\r\n document,\r\n 'textDocument',\r\n {\r\n get: textDocumentGetter\r\n }\r\n );\r\n }\r\n\r\n // Some of these documents can be pretty large, so parsing them again can be quite expensive.\r\n // Therefore, we only parse if the text has actually changed.\r\n if (oldText !== text) {\r\n document.parseResult = await this.parseAsync(document.uri, text, cancellationToken);\r\n (document.parseResult.value as Mutable).$document = document;\r\n }\r\n document.state = DocumentState.Parsed;\r\n return document;\r\n }\r\n\r\n protected parse(uri: URI, text: string, options?: ParserOptions): ParseResult {\r\n const services = this.serviceRegistry.getServices(uri);\r\n return services.parser.LangiumParser.parse(text, options);\r\n }\r\n\r\n protected parseAsync(uri: URI, text: string, cancellationToken: CancellationToken): Promise> {\r\n const services = this.serviceRegistry.getServices(uri);\r\n return services.parser.AsyncParser.parse(text, cancellationToken);\r\n }\r\n\r\n protected createTextDocumentGetter(uri: URI, text?: string): () => TextDocument {\r\n const serviceRegistry = this.serviceRegistry;\r\n let textDoc: TextDocument | undefined = undefined;\r\n return () => {\r\n return textDoc ??= TextDocument.create(\r\n uri.toString(), serviceRegistry.getServices(uri).LanguageMetaData.languageId, 0, text ?? ''\r\n );\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Shared service for managing Langium documents.\r\n */\r\nexport interface LangiumDocuments {\r\n\r\n /**\r\n * A stream of all documents managed under this service.\r\n */\r\n readonly all: Stream\r\n\r\n /**\r\n * Manage a new document under this service.\r\n * @throws an error if a document with the same URI is already present.\r\n */\r\n addDocument(document: LangiumDocument): void;\r\n\r\n /**\r\n * Retrieve the document with the given URI, if present. Otherwise returns `undefined`.\r\n */\r\n getDocument(uri: URI): LangiumDocument | undefined;\r\n\r\n /**\r\n * Retrieve the document with the given URI. If not present, a new one will be created using the file system access.\r\n * The new document will be added to the list of documents managed under this service.\r\n */\r\n getOrCreateDocument(uri: URI, cancellationToken?: CancellationToken): Promise;\r\n\r\n /**\r\n * Creates a new document with the given URI and text content.\r\n * The new document is automatically added to this service and can be retrieved using {@link getDocument}.\r\n *\r\n * @throws an error if a document with the same URI is already present.\r\n */\r\n createDocument(uri: URI, text: string): LangiumDocument;\r\n\r\n /**\r\n * Creates a new document with the given URI and text content asynchronously.\r\n * The process can be interrupted with a cancellation token.\r\n * The new document is automatically added to this service and can be retrieved using {@link getDocument}.\r\n *\r\n * @throws an error if a document with the same URI is already present.\r\n */\r\n createDocument(uri: URI, text: string, cancellationToken: CancellationToken): Promise;\r\n\r\n /**\r\n * Returns `true` if a document with the given URI is managed under this service.\r\n */\r\n hasDocument(uri: URI): boolean;\r\n\r\n /**\r\n * Flag the document with the given URI as `Changed`, if present, meaning that its content\r\n * is no longer valid. The content (parseResult) stays untouched, while internal data may\r\n * be dropped to reduce memory footprint.\r\n *\r\n * @returns the affected {@link LangiumDocument} if existing for convenience\r\n */\r\n invalidateDocument(uri: URI): LangiumDocument | undefined;\r\n\r\n /**\r\n * Remove the document with the given URI, if present, and mark it as `Changed`, meaning\r\n * that its content is no longer valid. The next call to `getOrCreateDocument` with the same\r\n * URI will create a new document instance.\r\n *\r\n * @returns the affected {@link LangiumDocument} if existing for convenience\r\n */\r\n deleteDocument(uri: URI): LangiumDocument | undefined;\r\n}\r\n\r\nexport class DefaultLangiumDocuments implements LangiumDocuments {\r\n\r\n protected readonly langiumDocumentFactory: LangiumDocumentFactory;\r\n protected readonly serviceRegistry: ServiceRegistry;\r\n\r\n protected readonly documentMap: Map = new Map();\r\n\r\n constructor(services: LangiumSharedCoreServices) {\r\n this.langiumDocumentFactory = services.workspace.LangiumDocumentFactory;\r\n this.serviceRegistry = services.ServiceRegistry;\r\n }\r\n\r\n get all(): Stream {\r\n return stream(this.documentMap.values());\r\n }\r\n\r\n addDocument(document: LangiumDocument): void {\r\n const uriString = document.uri.toString();\r\n if (this.documentMap.has(uriString)) {\r\n throw new Error(`A document with the URI '${uriString}' is already present.`);\r\n }\r\n this.documentMap.set(uriString, document);\r\n }\r\n\r\n getDocument(uri: URI): LangiumDocument | undefined {\r\n const uriString = uri.toString();\r\n return this.documentMap.get(uriString);\r\n }\r\n\r\n async getOrCreateDocument(uri: URI, cancellationToken?: CancellationToken): Promise {\r\n let document = this.getDocument(uri);\r\n if (document) {\r\n return document;\r\n }\r\n document = await this.langiumDocumentFactory.fromUri(uri, cancellationToken);\r\n this.addDocument(document);\r\n return document;\r\n }\r\n\r\n createDocument(uri: URI, text: string): LangiumDocument;\r\n createDocument(uri: URI, text: string, cancellationToken: CancellationToken): Promise;\r\n createDocument(uri: URI, text: string, cancellationToken?: CancellationToken): LangiumDocument | Promise {\r\n if (cancellationToken) {\r\n return this.langiumDocumentFactory.fromString(text, uri, cancellationToken).then(document => {\r\n this.addDocument(document);\r\n return document;\r\n });\r\n } else {\r\n const document = this.langiumDocumentFactory.fromString(text, uri);\r\n this.addDocument(document);\r\n return document;\r\n }\r\n }\r\n\r\n hasDocument(uri: URI): boolean {\r\n return this.documentMap.has(uri.toString());\r\n }\r\n\r\n invalidateDocument(uri: URI): LangiumDocument | undefined {\r\n const uriString = uri.toString();\r\n const langiumDoc = this.documentMap.get(uriString);\r\n if (langiumDoc) {\r\n const linker = this.serviceRegistry.getServices(uri).references.Linker;\r\n linker.unlink(langiumDoc);\r\n langiumDoc.state = DocumentState.Changed;\r\n langiumDoc.precomputedScopes = undefined;\r\n langiumDoc.diagnostics = undefined;\r\n }\r\n return langiumDoc;\r\n }\r\n\r\n deleteDocument(uri: URI): LangiumDocument | undefined {\r\n const uriString = uri.toString();\r\n const langiumDoc = this.documentMap.get(uriString);\r\n if (langiumDoc) {\r\n langiumDoc.state = DocumentState.Changed;\r\n this.documentMap.delete(uriString);\r\n }\r\n return langiumDoc;\r\n }\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport type { AstNode, AstNodeDescription, AstReflection, CstNode, LinkingError, Reference, ReferenceInfo } from '../syntax-tree.js';\r\nimport type { AstNodeLocator } from '../workspace/ast-node-locator.js';\r\nimport type { LangiumDocument, LangiumDocuments } from '../workspace/documents.js';\r\nimport type { ScopeProvider } from './scope-provider.js';\r\nimport { CancellationToken } from '../utils/cancellation.js';\r\nimport { isAstNode, isAstNodeDescription, isLinkingError } from '../syntax-tree.js';\r\nimport { findRootNode, streamAst, streamReferences } from '../utils/ast-utils.js';\r\nimport { interruptAndCheck } from '../utils/promise-utils.js';\r\nimport { DocumentState } from '../workspace/documents.js';\r\n\r\n/**\r\n * Language-specific service for resolving cross-references in the AST.\r\n */\r\nexport interface Linker {\r\n\r\n /**\r\n * Links all cross-references within the specified document. The default implementation loads only target\r\n * elements from documents that are present in the `LangiumDocuments` service. The linked references are\r\n * stored in the document's `references` property.\r\n *\r\n * @param document A LangiumDocument that shall be linked.\r\n * @param cancelToken A token for cancelling the operation.\r\n *\r\n * @throws `OperationCancelled` if a cancellation event is detected\r\n */\r\n link(document: LangiumDocument, cancelToken?: CancellationToken): Promise;\r\n\r\n /**\r\n * Unlinks all references within the specified document and removes them from the list of `references`.\r\n *\r\n * @param document A LangiumDocument that shall be unlinked.\r\n */\r\n unlink(document: LangiumDocument): void;\r\n\r\n /**\r\n * Determines a candidate AST node description for linking the given reference.\r\n *\r\n * @param refInfo Information about the reference.\r\n */\r\n getCandidate(refInfo: ReferenceInfo): AstNodeDescription | LinkingError;\r\n\r\n /**\r\n * Creates a cross reference node being aware of its containing AstNode, the corresponding CstNode,\r\n * the cross reference text denoting the target AstNode being already extracted of the document text,\r\n * as well as the unique cross reference identifier.\r\n *\r\n * Default behavior:\r\n * - The returned Reference's 'ref' property pointing to the target AstNode is populated lazily on its\r\n * first visit.\r\n * - If the target AstNode cannot be resolved on the first visit, an error indicator will be installed\r\n * and further resolution attempts will *not* be performed.\r\n *\r\n * @param node The containing AST node\r\n * @param property The AST node property being referenced\r\n * @param refNode The corresponding CST node\r\n * @param refText The cross reference text denoting the target AstNode\r\n * @returns the desired Reference node, whose behavior wrt. resolving the cross reference is implementation specific.\r\n */\r\n buildReference(node: AstNode, property: string, refNode: CstNode | undefined, refText: string): Reference;\r\n\r\n}\r\n\r\nconst ref_resolving = Symbol('ref_resolving');\r\n\r\ninterface DefaultReference extends Reference {\r\n _ref?: AstNode | LinkingError | typeof ref_resolving;\r\n _nodeDescription?: AstNodeDescription;\r\n}\r\n\r\nexport class DefaultLinker implements Linker {\r\n protected readonly reflection: AstReflection;\r\n protected readonly scopeProvider: ScopeProvider;\r\n protected readonly astNodeLocator: AstNodeLocator;\r\n protected readonly langiumDocuments: () => LangiumDocuments;\r\n\r\n constructor(services: LangiumCoreServices) {\r\n this.reflection = services.shared.AstReflection;\r\n this.langiumDocuments = () => services.shared.workspace.LangiumDocuments;\r\n this.scopeProvider = services.references.ScopeProvider;\r\n this.astNodeLocator = services.workspace.AstNodeLocator;\r\n }\r\n\r\n async link(document: LangiumDocument, cancelToken = CancellationToken.None): Promise {\r\n for (const node of streamAst(document.parseResult.value)) {\r\n await interruptAndCheck(cancelToken);\r\n streamReferences(node).forEach(ref => this.doLink(ref, document));\r\n }\r\n }\r\n\r\n protected doLink(refInfo: ReferenceInfo, document: LangiumDocument): void {\r\n const ref = refInfo.reference as DefaultReference;\r\n // The reference may already have been resolved lazily by accessing its `ref` property.\r\n if (ref._ref === undefined) {\r\n ref._ref = ref_resolving;\r\n try {\r\n const description = this.getCandidate(refInfo);\r\n if (isLinkingError(description)) {\r\n ref._ref = description;\r\n } else {\r\n ref._nodeDescription = description;\r\n if (this.langiumDocuments().hasDocument(description.documentUri)) {\r\n // The target document is already loaded\r\n const linkedNode = this.loadAstNode(description);\r\n ref._ref = linkedNode ?? this.createLinkingError(refInfo, description);\r\n } else {\r\n // Try to load the target AST node later using the already provided description\r\n ref._ref = undefined;\r\n }\r\n }\r\n } catch (err) {\r\n console.error(`An error occurred while resolving reference to '${ref.$refText}':`, err);\r\n const errorMessage = (err as Error).message ?? String(err);\r\n ref._ref = {\r\n ...refInfo,\r\n message: `An error occurred while resolving reference to '${ref.$refText}': ${errorMessage}`\r\n };\r\n }\r\n // Add the reference to the document's array of references\r\n // Only add if the reference has been not been resolved earlier\r\n // Otherwise we end up with duplicates\r\n // See also implementation of `buildReference`\r\n document.references.push(ref);\r\n }\r\n }\r\n\r\n unlink(document: LangiumDocument): void {\r\n for (const ref of document.references) {\r\n delete (ref as DefaultReference)._ref;\r\n delete (ref as DefaultReference)._nodeDescription;\r\n }\r\n document.references = [];\r\n }\r\n\r\n getCandidate(refInfo: ReferenceInfo): AstNodeDescription | LinkingError {\r\n const scope = this.scopeProvider.getScope(refInfo);\r\n const description = scope.getElement(refInfo.reference.$refText);\r\n return description ?? this.createLinkingError(refInfo);\r\n }\r\n\r\n buildReference(node: AstNode, property: string, refNode: CstNode | undefined, refText: string): Reference {\r\n // See behavior description in doc of Linker, update that on changes in here.\r\n // eslint-disable-next-line @typescript-eslint/no-this-alias\r\n const linker = this;\r\n const reference: DefaultReference = {\r\n $refNode: refNode,\r\n $refText: refText,\r\n\r\n get ref() {\r\n if (isAstNode(this._ref)) {\r\n // Most frequent case: the target is already resolved.\r\n return this._ref;\r\n } else if (isAstNodeDescription(this._nodeDescription)) {\r\n // A candidate has been found before, but it is not loaded yet.\r\n const linkedNode = linker.loadAstNode(this._nodeDescription);\r\n this._ref = linkedNode ??\r\n linker.createLinkingError({ reference, container: node, property }, this._nodeDescription);\r\n } else if (this._ref === undefined) {\r\n // The reference has not been linked yet, so do that now.\r\n this._ref = ref_resolving;\r\n const document = findRootNode(node).$document;\r\n const refData = linker.getLinkedNode({ reference, container: node, property });\r\n if (refData.error && document && document.state < DocumentState.ComputedScopes) {\r\n // Document scope is not ready, don't set `this._ref` so linker can retry later.\r\n return this._ref = undefined;\r\n }\r\n this._ref = refData.node ?? refData.error;\r\n this._nodeDescription = refData.descr;\r\n document?.references.push(this);\r\n } else if (this._ref === ref_resolving) {\r\n throw new Error(`Cyclic reference resolution detected: ${linker.astNodeLocator.getAstNodePath(node)}/${property} (symbol '${refText}')`);\r\n }\r\n return isAstNode(this._ref) ? this._ref : undefined;\r\n },\r\n get $nodeDescription() {\r\n return this._nodeDescription;\r\n },\r\n get error() {\r\n return isLinkingError(this._ref) ? this._ref : undefined;\r\n }\r\n };\r\n return reference;\r\n }\r\n\r\n protected getLinkedNode(refInfo: ReferenceInfo): { node?: AstNode, descr?: AstNodeDescription, error?: LinkingError } {\r\n try {\r\n const description = this.getCandidate(refInfo);\r\n if (isLinkingError(description)) {\r\n return { error: description };\r\n }\r\n const linkedNode = this.loadAstNode(description);\r\n if (linkedNode) {\r\n return { node: linkedNode, descr: description };\r\n }\r\n else {\r\n return {\r\n descr: description,\r\n error:\r\n this.createLinkingError(refInfo, description)\r\n };\r\n }\r\n } catch (err) {\r\n console.error(`An error occurred while resolving reference to '${refInfo.reference.$refText}':`, err);\r\n const errorMessage = (err as Error).message ?? String(err);\r\n return {\r\n error: {\r\n ...refInfo,\r\n message: `An error occurred while resolving reference to '${refInfo.reference.$refText}': ${errorMessage}`\r\n }\r\n };\r\n }\r\n }\r\n\r\n protected loadAstNode(nodeDescription: AstNodeDescription): AstNode | undefined {\r\n if (nodeDescription.node) {\r\n return nodeDescription.node;\r\n }\r\n const doc = this.langiumDocuments().getDocument(nodeDescription.documentUri);\r\n if (!doc) {\r\n return undefined;\r\n }\r\n return this.astNodeLocator.getAstNode(doc.parseResult.value, nodeDescription.path);\r\n }\r\n\r\n protected createLinkingError(refInfo: ReferenceInfo, targetDescription?: AstNodeDescription): LinkingError {\r\n // Check whether the document is sufficiently processed by the DocumentBuilder. If not, this is a hint for a bug\r\n // in the language implementation.\r\n const document = findRootNode(refInfo.container).$document;\r\n if (document && document.state < DocumentState.ComputedScopes) {\r\n console.warn(`Attempted reference resolution before document reached ComputedScopes state (${document.uri}).`);\r\n }\r\n const referenceType = this.reflection.getReferenceType(refInfo);\r\n return {\r\n ...refInfo,\r\n message: `Could not resolve reference to ${referenceType} named '${refInfo.reference.$refText}'.`,\r\n targetDescription\r\n };\r\n }\r\n\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { AstNode, CstNode } from '../syntax-tree.js';\r\nimport { findNodeForProperty } from '../utils/grammar-utils.js';\r\n\r\nexport interface NamedAstNode extends AstNode {\r\n name: string;\r\n}\r\n\r\nexport function isNamed(node: AstNode): node is NamedAstNode {\r\n return typeof (node as NamedAstNode).name === 'string';\r\n}\r\n\r\n/**\r\n * Utility service for retrieving the `name` of an `AstNode` or the `CstNode` containing a `name`.\r\n */\r\nexport interface NameProvider {\r\n /**\r\n * Returns the `name` of a given AstNode.\r\n * @param node Specified `AstNode` whose name node shall be retrieved.\r\n */\r\n getName(node: AstNode): string | undefined;\r\n /**\r\n * Returns the `CstNode` which contains the parsed value of the `name` assignment.\r\n * @param node Specified `AstNode` whose name node shall be retrieved.\r\n */\r\n getNameNode(node: AstNode): CstNode | undefined;\r\n}\r\n\r\nexport class DefaultNameProvider implements NameProvider {\r\n getName(node: AstNode): string | undefined {\r\n if (isNamed(node)) {\r\n return node.name;\r\n }\r\n return undefined;\r\n }\r\n\r\n getNameNode(node: AstNode): CstNode | undefined {\r\n return findNodeForProperty(node.$cstNode, 'name');\r\n }\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport type { AstNode, CstNode, GenericAstNode } from '../syntax-tree.js';\r\nimport type { Stream } from '../utils/stream.js';\r\nimport type { ReferenceDescription } from '../workspace/ast-descriptions.js';\r\nimport type { AstNodeLocator } from '../workspace/ast-node-locator.js';\r\nimport type { IndexManager } from '../workspace/index-manager.js';\r\nimport type { NameProvider } from './name-provider.js';\r\nimport type { URI } from '../utils/uri-utils.js';\r\nimport { findAssignment } from '../utils/grammar-utils.js';\r\nimport { isReference } from '../syntax-tree.js';\r\nimport { getDocument } from '../utils/ast-utils.js';\r\nimport { isChildNode, toDocumentSegment } from '../utils/cst-utils.js';\r\nimport { stream } from '../utils/stream.js';\r\nimport { UriUtils } from '../utils/uri-utils.js';\r\n\r\n/**\r\n * Language-specific service for finding references and declaration of a given `CstNode`.\r\n */\r\nexport interface References {\r\n\r\n /**\r\n * If the CstNode is a reference node the target CstNode will be returned.\r\n * If the CstNode is a significant node of the CstNode this CstNode will be returned.\r\n *\r\n * @param sourceCstNode CstNode that points to a AstNode\r\n */\r\n findDeclaration(sourceCstNode: CstNode): AstNode | undefined;\r\n\r\n /**\r\n * If the CstNode is a reference node the target CstNode will be returned.\r\n * If the CstNode is a significant node of the CstNode this CstNode will be returned.\r\n *\r\n * @param sourceCstNode CstNode that points to a AstNode\r\n */\r\n findDeclarationNode(sourceCstNode: CstNode): CstNode | undefined;\r\n\r\n /**\r\n * Finds all references to the target node as references (local references) or reference descriptions.\r\n *\r\n * @param targetNode Specified target node whose references should be returned\r\n */\r\n findReferences(targetNode: AstNode, options: FindReferencesOptions): Stream;\r\n}\r\n\r\nexport interface FindReferencesOptions {\r\n /**\r\n * @deprecated Since v1.2.0. Please use `documentUri` instead.\r\n */\r\n onlyLocal?: boolean;\r\n /**\r\n * When set, the `findReferences` method will only return references/declarations from the specified document.\r\n */\r\n documentUri?: URI;\r\n /**\r\n * Whether the returned list of references should include the declaration.\r\n */\r\n includeDeclaration?: boolean;\r\n}\r\n\r\nexport class DefaultReferences implements References {\r\n protected readonly nameProvider: NameProvider;\r\n protected readonly index: IndexManager;\r\n protected readonly nodeLocator: AstNodeLocator;\r\n\r\n constructor(services: LangiumCoreServices) {\r\n this.nameProvider = services.references.NameProvider;\r\n this.index = services.shared.workspace.IndexManager;\r\n this.nodeLocator = services.workspace.AstNodeLocator;\r\n }\r\n\r\n findDeclaration(sourceCstNode: CstNode): AstNode | undefined {\r\n if (sourceCstNode) {\r\n const assignment = findAssignment(sourceCstNode);\r\n const nodeElem = sourceCstNode.astNode;\r\n if (assignment && nodeElem) {\r\n const reference = (nodeElem as GenericAstNode)[assignment.feature];\r\n\r\n if (isReference(reference)) {\r\n return reference.ref;\r\n } else if (Array.isArray(reference)) {\r\n for (const ref of reference) {\r\n if (isReference(ref) && ref.$refNode\r\n && ref.$refNode.offset <= sourceCstNode.offset\r\n && ref.$refNode.end >= sourceCstNode.end) {\r\n return ref.ref;\r\n }\r\n }\r\n }\r\n }\r\n if (nodeElem) {\r\n const nameNode = this.nameProvider.getNameNode(nodeElem);\r\n // Only return the targeted node in case the targeted cst node is the name node or part of it\r\n if (nameNode && (nameNode === sourceCstNode || isChildNode(sourceCstNode, nameNode))) {\r\n return nodeElem;\r\n }\r\n }\r\n }\r\n return undefined;\r\n }\r\n\r\n findDeclarationNode(sourceCstNode: CstNode): CstNode | undefined {\r\n const astNode = this.findDeclaration(sourceCstNode);\r\n if (astNode?.$cstNode) {\r\n const targetNode = this.nameProvider.getNameNode(astNode);\r\n return targetNode ?? astNode.$cstNode;\r\n }\r\n return undefined;\r\n }\r\n\r\n findReferences(targetNode: AstNode, options: FindReferencesOptions): Stream {\r\n const refs: ReferenceDescription[] = [];\r\n if (options.includeDeclaration) {\r\n const ref = this.getReferenceToSelf(targetNode);\r\n if (ref) {\r\n refs.push(ref);\r\n }\r\n }\r\n let indexReferences = this.index.findAllReferences(targetNode, this.nodeLocator.getAstNodePath(targetNode));\r\n if (options.documentUri) {\r\n indexReferences = indexReferences.filter(ref => UriUtils.equals(ref.sourceUri, options.documentUri));\r\n }\r\n refs.push(...indexReferences);\r\n return stream(refs);\r\n }\r\n\r\n protected getReferenceToSelf(targetNode: AstNode): ReferenceDescription | undefined {\r\n const nameNode = this.nameProvider.getNameNode(targetNode);\r\n if (nameNode) {\r\n const doc = getDocument(targetNode);\r\n const path = this.nodeLocator.getAstNodePath(targetNode);\r\n return {\r\n sourceUri: doc.uri,\r\n sourcePath: path,\r\n targetUri: doc.uri,\r\n targetPath: path,\r\n segment: toDocumentSegment(nameNode),\r\n local: true\r\n };\r\n }\r\n return undefined;\r\n }\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { Stream } from './stream.js';\r\nimport { Reduction, stream } from './stream.js';\r\n\r\n/**\r\n * A multimap is a variation of a Map that has potentially multiple values for every key.\r\n */\r\nexport class MultiMap {\r\n\r\n private map = new Map();\r\n\r\n constructor()\r\n constructor(elements: Array<[K, V]>)\r\n constructor(elements?: Array<[K, V]>) {\r\n if (elements) {\r\n for (const [key, value] of elements) {\r\n this.add(key, value);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * The total number of values in the multimap.\r\n */\r\n get size(): number {\r\n return Reduction.sum(stream(this.map.values()).map(a => a.length));\r\n }\r\n\r\n /**\r\n * Clear all entries in the multimap.\r\n */\r\n clear(): void {\r\n this.map.clear();\r\n }\r\n\r\n /**\r\n * Operates differently depending on whether a `value` is given:\r\n * * With a value, this method deletes the specific key / value pair from the multimap.\r\n * * Without a value, all values associated with the given key are deleted.\r\n *\r\n * @returns `true` if a value existed and has been removed, or `false` if the specified\r\n * key / value does not exist.\r\n */\r\n delete(key: K, value?: V): boolean {\r\n if (value === undefined) {\r\n return this.map.delete(key);\r\n } else {\r\n const values = this.map.get(key);\r\n if (values) {\r\n const index = values.indexOf(value);\r\n if (index >= 0) {\r\n if (values.length === 1) {\r\n this.map.delete(key);\r\n } else {\r\n values.splice(index, 1);\r\n }\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Returns an array of all values associated with the given key. If no value exists,\r\n * an empty array is returned.\r\n *\r\n * _Note:_ The returned array is assumed not to be modified. Use the `set` method to add a\r\n * value and `delete` to remove a value from the multimap.\r\n */\r\n get(key: K): readonly V[] {\r\n return this.map.get(key) ?? [];\r\n }\r\n\r\n /**\r\n * Operates differently depending on whether a `value` is given:\r\n * * With a value, this method returns `true` if the specific key / value pair is present in the multimap.\r\n * * Without a value, this method returns `true` if the given key is present in the multimap.\r\n */\r\n has(key: K, value?: V): boolean {\r\n if (value === undefined) {\r\n return this.map.has(key);\r\n } else {\r\n const values = this.map.get(key);\r\n if (values) {\r\n return values.indexOf(value) >= 0;\r\n }\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Add the given key / value pair to the multimap.\r\n */\r\n add(key: K, value: V): this {\r\n if (this.map.has(key)) {\r\n this.map.get(key)!.push(value);\r\n } else {\r\n this.map.set(key, [value]);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Add the given set of key / value pairs to the multimap.\r\n */\r\n addAll(key: K, values: Iterable): this {\r\n if (this.map.has(key)) {\r\n this.map.get(key)!.push(...values);\r\n } else {\r\n this.map.set(key, Array.from(values));\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Invokes the given callback function for every key / value pair in the multimap.\r\n */\r\n forEach(callbackfn: (value: V, key: K, map: this) => void): void {\r\n this.map.forEach((array, key) =>\r\n array.forEach(value => callbackfn(value, key, this))\r\n );\r\n }\r\n\r\n /**\r\n * Returns an iterator of key, value pairs for every entry in the map.\r\n */\r\n [Symbol.iterator](): Iterator<[K, V]> {\r\n return this.entries().iterator();\r\n }\r\n\r\n /**\r\n * Returns a stream of key, value pairs for every entry in the map.\r\n */\r\n entries(): Stream<[K, V]> {\r\n return stream(this.map.entries())\r\n .flatMap(([key, array]) => array.map(value => [key, value] as [K, V]));\r\n }\r\n\r\n /**\r\n * Returns a stream of keys in the map.\r\n */\r\n keys(): Stream {\r\n return stream(this.map.keys());\r\n }\r\n\r\n /**\r\n * Returns a stream of values in the map.\r\n */\r\n values(): Stream {\r\n return stream(this.map.values()).flat();\r\n }\r\n\r\n /**\r\n * Returns a stream of key, value set pairs for every key in the map.\r\n */\r\n entriesGroupedByKey(): Stream<[K, V[]]> {\r\n return stream(this.map.entries());\r\n }\r\n\r\n}\r\n\r\nexport class BiMap {\r\n\r\n private map = new Map();\r\n private inverse = new Map();\r\n\r\n get size(): number {\r\n return this.map.size;\r\n }\r\n\r\n constructor()\r\n constructor(elements: Array<[K, V]>)\r\n constructor(elements?: Array<[K, V]>) {\r\n if (elements) {\r\n for (const [key, value] of elements) {\r\n this.set(key, value);\r\n }\r\n }\r\n }\r\n\r\n clear(): void {\r\n this.map.clear();\r\n this.inverse.clear();\r\n }\r\n\r\n set(key: K, value: V): this {\r\n this.map.set(key, value);\r\n this.inverse.set(value, key);\r\n return this;\r\n }\r\n\r\n get(key: K): V | undefined {\r\n return this.map.get(key);\r\n }\r\n\r\n getKey(value: V): K | undefined {\r\n return this.inverse.get(value);\r\n }\r\n\r\n delete(key: K): boolean {\r\n const value = this.map.get(key);\r\n if (value !== undefined) {\r\n this.map.delete(key);\r\n this.inverse.delete(value);\r\n return true;\r\n }\r\n return false;\r\n }\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021-2022 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport type { AstNode, AstNodeDescription } from '../syntax-tree.js';\r\nimport type { AstNodeDescriptionProvider } from '../workspace/ast-descriptions.js';\r\nimport type { LangiumDocument, PrecomputedScopes } from '../workspace/documents.js';\r\nimport type { NameProvider } from './name-provider.js';\r\nimport { CancellationToken } from '../utils/cancellation.js';\r\nimport { streamAllContents, streamContents } from '../utils/ast-utils.js';\r\nimport { MultiMap } from '../utils/collections.js';\r\nimport { interruptAndCheck } from '../utils/promise-utils.js';\r\n\r\n/**\r\n * Language-specific service for precomputing global and local scopes. The service methods are executed\r\n * as the first and second phase in the `DocumentBuilder`.\r\n */\r\nexport interface ScopeComputation {\r\n\r\n /**\r\n * Creates descriptions of all AST nodes that shall be exported into the _global_ scope from the given\r\n * document. These descriptions are gathered by the `IndexManager` and stored in the global index so\r\n * they can be referenced from other documents.\r\n *\r\n * _Note:_ You should not resolve any cross-references in this service method. Cross-reference resolution\r\n * depends on the scope computation phase to be completed (`computeScope` method), which runs after the\r\n * initial indexing where this method is used.\r\n *\r\n * @param document The document from which to gather exported AST nodes.\r\n * @param cancelToken Indicates when to cancel the current operation.\r\n * @throws `OperationCanceled` if a user action occurs during execution\r\n */\r\n computeExports(document: LangiumDocument, cancelToken?: CancellationToken): Promise;\r\n\r\n /**\r\n * Precomputes the _local_ scopes for a document, which are necessary for the default way of\r\n * resolving references to symbols in the same document. The result is a multimap assigning a\r\n * set of AST node descriptions to every level of the AST. These data are used by the `ScopeProvider`\r\n * service to determine which target nodes are visible in the context of a specific cross-reference.\r\n *\r\n * _Note:_ You should not resolve any cross-references in this service method. Cross-reference\r\n * resolution depends on the scope computation phase to be completed.\r\n *\r\n * @param document The document in which to compute scopes.\r\n * @param cancelToken Indicates when to cancel the current operation.\r\n * @throws `OperationCanceled` if a user action occurs during execution\r\n */\r\n computeLocalScopes(document: LangiumDocument, cancelToken?: CancellationToken): Promise;\r\n\r\n}\r\n\r\n/**\r\n * The default scope computation creates and collectes descriptions of the AST nodes to be exported into the\r\n * _global_ scope from the given document. By default those are the document's root AST node and its directly\r\n * contained child nodes.\r\n *\r\n * Besides, it gathers all AST nodes that have a name (according to the `NameProvider` service) and includes them\r\n * in the local scope of their particular container nodes. As a result, for every cross-reference in the AST,\r\n * target elements from the same level (siblings) and further up towards the root (parents and siblings of parents)\r\n * are visible. Elements being nested inside lower levels (children, children of siblings and parents' siblings)\r\n * are _invisible_ by default, but that can be changed by customizing this service.\r\n */\r\nexport class DefaultScopeComputation implements ScopeComputation {\r\n\r\n protected readonly nameProvider: NameProvider;\r\n protected readonly descriptions: AstNodeDescriptionProvider;\r\n\r\n constructor(services: LangiumCoreServices) {\r\n this.nameProvider = services.references.NameProvider;\r\n this.descriptions = services.workspace.AstNodeDescriptionProvider;\r\n }\r\n\r\n async computeExports(document: LangiumDocument, cancelToken = CancellationToken.None): Promise {\r\n return this.computeExportsForNode(document.parseResult.value, document, undefined, cancelToken);\r\n }\r\n\r\n /**\r\n * Creates {@link AstNodeDescription AstNodeDescriptions} for the given {@link AstNode parentNode} and its children.\r\n * The list of children to be considered is determined by the function parameter {@link children}.\r\n * By default only the direct children of {@link parentNode} are visited, nested nodes are not exported.\r\n *\r\n * @param parentNode AST node to be exported, i.e., of which an {@link AstNodeDescription} shall be added to the returned list.\r\n * @param document The document containing the AST node to be exported.\r\n * @param children A function called with {@link parentNode} as single argument and returning an {@link Iterable} supplying the children to be visited, which must be directly or transitively contained in {@link parentNode}.\r\n * @param cancelToken Indicates when to cancel the current operation.\r\n * @throws `OperationCancelled` if a user action occurs during execution.\r\n * @returns A list of {@link AstNodeDescription AstNodeDescriptions} to be published to index.\r\n */\r\n async computeExportsForNode(parentNode: AstNode, document: LangiumDocument, children: (root: AstNode) => Iterable = streamContents, cancelToken: CancellationToken = CancellationToken.None): Promise {\r\n const exports: AstNodeDescription[] = [];\r\n\r\n this.exportNode(parentNode, exports, document);\r\n for (const node of children(parentNode)) {\r\n await interruptAndCheck(cancelToken);\r\n this.exportNode(node, exports, document);\r\n }\r\n return exports;\r\n }\r\n\r\n /**\r\n * Add a single node to the list of exports if it has a name. Override this method to change how\r\n * symbols are exported, e.g. by modifying their exported name.\r\n */\r\n protected exportNode(node: AstNode, exports: AstNodeDescription[], document: LangiumDocument): void {\r\n const name = this.nameProvider.getName(node);\r\n if (name) {\r\n exports.push(this.descriptions.createDescription(node, name, document));\r\n }\r\n }\r\n\r\n async computeLocalScopes(document: LangiumDocument, cancelToken = CancellationToken.None): Promise {\r\n const rootNode = document.parseResult.value;\r\n const scopes = new MultiMap();\r\n // Here we navigate the full AST - local scopes shall be available in the whole document\r\n for (const node of streamAllContents(rootNode)) {\r\n await interruptAndCheck(cancelToken);\r\n this.processNode(node, document, scopes);\r\n }\r\n return scopes;\r\n }\r\n\r\n /**\r\n * Process a single node during scopes computation. The default implementation makes the node visible\r\n * in the subtree of its container (if the node has a name). Override this method to change this,\r\n * e.g. by increasing the visibility to a higher level in the AST.\r\n */\r\n protected processNode(node: AstNode, document: LangiumDocument, scopes: PrecomputedScopes): void {\r\n const container = node.$container;\r\n if (container) {\r\n const name = this.nameProvider.getName(node);\r\n if (name) {\r\n scopes.add(container, this.descriptions.createDescription(node, name, document));\r\n }\r\n }\r\n }\r\n\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2023 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { AstNodeDescription } from '../syntax-tree.js';\r\nimport type { Stream } from '../utils/stream.js';\r\nimport { EMPTY_STREAM, stream } from '../utils/stream.js';\r\n\r\n/**\r\n * A scope describes what target elements are visible from a specific cross-reference context.\r\n */\r\nexport interface Scope {\r\n\r\n /**\r\n * Find a target element matching the given name. If no element is found, `undefined` is returned.\r\n * If multiple matching elements are present, the selection of the returned element should be done\r\n * according to the semantics of your language. Usually it is the element that is most closely defined.\r\n *\r\n * @param name Name of the cross-reference target as it appears in the source text.\r\n */\r\n getElement(name: string): AstNodeDescription | undefined;\r\n\r\n /**\r\n * Create a stream of all elements in the scope. This is used to compute completion proposals to be\r\n * shown in the editor.\r\n */\r\n getAllElements(): Stream;\r\n\r\n}\r\n\r\nexport interface ScopeOptions {\r\n caseInsensitive?: boolean;\r\n}\r\n\r\n/**\r\n * The default scope implementation is based on a `Stream`. It has an optional _outer scope_ describing\r\n * the next level of elements, which are queried when a target element is not found in the stream provided\r\n * to this scope.\r\n */\r\nexport class StreamScope implements Scope {\r\n readonly elements: Stream;\r\n readonly outerScope?: Scope;\r\n readonly caseInsensitive: boolean;\r\n\r\n constructor(elements: Stream, outerScope?: Scope, options?: ScopeOptions) {\r\n this.elements = elements;\r\n this.outerScope = outerScope;\r\n this.caseInsensitive = options?.caseInsensitive ?? false;\r\n }\r\n\r\n getAllElements(): Stream {\r\n if (this.outerScope) {\r\n return this.elements.concat(this.outerScope.getAllElements());\r\n } else {\r\n return this.elements;\r\n }\r\n }\r\n\r\n getElement(name: string): AstNodeDescription | undefined {\r\n const local = this.caseInsensitive\r\n ? this.elements.find(e => e.name.toLowerCase() === name.toLowerCase())\r\n : this.elements.find(e => e.name === name);\r\n if (local) {\r\n return local;\r\n }\r\n if (this.outerScope) {\r\n return this.outerScope.getElement(name);\r\n }\r\n return undefined;\r\n }\r\n}\r\n\r\nexport class MapScope implements Scope {\r\n readonly elements: Map;\r\n readonly outerScope?: Scope;\r\n readonly caseInsensitive: boolean;\r\n\r\n constructor(elements: Iterable, outerScope?: Scope, options?: ScopeOptions) {\r\n this.elements = new Map();\r\n this.caseInsensitive = options?.caseInsensitive ?? false;\r\n for (const element of elements) {\r\n const name = this.caseInsensitive\r\n ? element.name.toLowerCase()\r\n : element.name;\r\n this.elements.set(name, element);\r\n }\r\n this.outerScope = outerScope;\r\n }\r\n\r\n getElement(name: string): AstNodeDescription | undefined {\r\n const localName = this.caseInsensitive ? name.toLowerCase() : name;\r\n const local = this.elements.get(localName);\r\n if (local) {\r\n return local;\r\n }\r\n if (this.outerScope) {\r\n return this.outerScope.getElement(name);\r\n }\r\n return undefined;\r\n }\r\n\r\n getAllElements(): Stream {\r\n let elementStream = stream(this.elements.values());\r\n if (this.outerScope) {\r\n elementStream = elementStream.concat(this.outerScope.getAllElements());\r\n }\r\n return elementStream;\r\n }\r\n\r\n}\r\n\r\nexport const EMPTY_SCOPE: Scope = {\r\n getElement(): undefined {\r\n return undefined;\r\n },\r\n getAllElements(): Stream {\r\n return EMPTY_STREAM;\r\n }\r\n};\r\n", "/******************************************************************************\r\n * Copyright 2023 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { Disposable } from './disposable.js';\r\nimport type { URI } from './uri-utils.js';\r\nimport type { LangiumSharedCoreServices } from '../services.js';\r\nimport type { DocumentState } from '../workspace/documents.js';\r\n\r\nexport abstract class DisposableCache implements Disposable {\r\n\r\n protected toDispose: Disposable[] = [];\r\n protected isDisposed = false;\r\n\r\n onDispose(disposable: Disposable): void {\r\n this.toDispose.push(disposable);\r\n }\r\n\r\n dispose(): void {\r\n this.throwIfDisposed();\r\n this.clear();\r\n this.isDisposed = true;\r\n this.toDispose.forEach(disposable => disposable.dispose());\r\n }\r\n\r\n protected throwIfDisposed(): void {\r\n if (this.isDisposed) {\r\n throw new Error('This cache has already been disposed');\r\n }\r\n }\r\n\r\n abstract clear(): void;\r\n}\r\n\r\nexport class SimpleCache extends DisposableCache {\r\n protected readonly cache = new Map();\r\n\r\n has(key: K): boolean {\r\n this.throwIfDisposed();\r\n return this.cache.has(key);\r\n }\r\n\r\n set(key: K, value: V): void {\r\n this.throwIfDisposed();\r\n this.cache.set(key, value);\r\n }\r\n\r\n get(key: K): V | undefined;\r\n get(key: K, provider: () => V): V;\r\n get(key: K, provider?: () => V): V | undefined {\r\n this.throwIfDisposed();\r\n if (this.cache.has(key)) {\r\n return this.cache.get(key);\r\n } else if (provider) {\r\n const value = provider();\r\n this.cache.set(key, value);\r\n return value;\r\n } else {\r\n return undefined;\r\n }\r\n }\r\n\r\n delete(key: K): boolean {\r\n this.throwIfDisposed();\r\n return this.cache.delete(key);\r\n }\r\n\r\n clear(): void {\r\n this.throwIfDisposed();\r\n this.cache.clear();\r\n }\r\n}\r\n\r\nexport class ContextCache extends DisposableCache {\r\n\r\n private readonly cache = new Map>();\r\n private readonly converter: (input: Context) => ContextKey | Context;\r\n\r\n constructor(converter?: (input: Context) => ContextKey) {\r\n super();\r\n this.converter = converter ?? (value => value);\r\n }\r\n\r\n has(contextKey: Context, key: Key): boolean {\r\n this.throwIfDisposed();\r\n return this.cacheForContext(contextKey).has(key);\r\n }\r\n\r\n set(contextKey: Context, key: Key, value: Value): void {\r\n this.throwIfDisposed();\r\n this.cacheForContext(contextKey).set(key, value);\r\n }\r\n\r\n get(contextKey: Context, key: Key): Value | undefined;\r\n get(contextKey: Context, key: Key, provider: () => Value): Value;\r\n get(contextKey: Context, key: Key, provider?: () => Value): Value | undefined {\r\n this.throwIfDisposed();\r\n const contextCache = this.cacheForContext(contextKey);\r\n if (contextCache.has(key)) {\r\n return contextCache.get(key);\r\n } else if (provider) {\r\n const value = provider();\r\n contextCache.set(key, value);\r\n return value;\r\n } else {\r\n return undefined;\r\n }\r\n }\r\n\r\n delete(contextKey: Context, key: Key): boolean {\r\n this.throwIfDisposed();\r\n return this.cacheForContext(contextKey).delete(key);\r\n }\r\n\r\n clear(): void;\r\n clear(contextKey: Context): void;\r\n clear(contextKey?: Context): void {\r\n this.throwIfDisposed();\r\n if (contextKey) {\r\n const mapKey = this.converter(contextKey);\r\n this.cache.delete(mapKey);\r\n } else {\r\n this.cache.clear();\r\n }\r\n }\r\n\r\n protected cacheForContext(contextKey: Context): Map {\r\n const mapKey = this.converter(contextKey);\r\n let documentCache = this.cache.get(mapKey);\r\n if (!documentCache) {\r\n documentCache = new Map();\r\n this.cache.set(mapKey, documentCache);\r\n }\r\n return documentCache;\r\n }\r\n}\r\n\r\n/**\r\n * Every key/value pair in this cache is scoped to a document.\r\n * If this document is changed or deleted, all associated key/value pairs are deleted.\r\n */\r\nexport class DocumentCache extends ContextCache {\r\n\r\n /**\r\n * Creates a new document cache.\r\n *\r\n * @param sharedServices Service container instance to hook into document lifecycle events.\r\n * @param state Optional document state on which the cache should evict.\r\n * If not provided, the cache will evict on `DocumentBuilder#onUpdate`.\r\n * *Deleted* documents are considered in both cases.\r\n *\r\n * Providing a state here will use `DocumentBuilder#onDocumentPhase` instead,\r\n * which triggers on all documents that have been affected by this change, assuming that the\r\n * state is `DocumentState.Linked` or a later state.\r\n */\r\n constructor(sharedServices: LangiumSharedCoreServices, state?: DocumentState) {\r\n super(uri => uri.toString());\r\n if (state) {\r\n this.toDispose.push(sharedServices.workspace.DocumentBuilder.onDocumentPhase(state, document => {\r\n this.clear(document.uri.toString());\r\n }));\r\n this.toDispose.push(sharedServices.workspace.DocumentBuilder.onUpdate((_changed, deleted) => {\r\n for (const uri of deleted) { // react only on deleted documents\r\n this.clear(uri);\r\n }\r\n }));\r\n } else {\r\n this.toDispose.push(sharedServices.workspace.DocumentBuilder.onUpdate((changed, deleted) => {\r\n const allUris = changed.concat(deleted); // react on both changed and deleted documents\r\n for (const uri of allUris) {\r\n this.clear(uri);\r\n }\r\n }));\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Every key/value pair in this cache is scoped to the whole workspace.\r\n * If any document in the workspace is added, changed or deleted, the whole cache is evicted.\r\n */\r\nexport class WorkspaceCache extends SimpleCache {\r\n\r\n /**\r\n * Creates a new workspace cache.\r\n *\r\n * @param sharedServices Service container instance to hook into document lifecycle events.\r\n * @param state Optional document state on which the cache should evict.\r\n * If not provided, the cache will evict on `DocumentBuilder#onUpdate`.\r\n * *Deleted* documents are considered in both cases.\r\n */\r\n constructor(sharedServices: LangiumSharedCoreServices, state?: DocumentState) {\r\n super();\r\n if (state) {\r\n this.toDispose.push(sharedServices.workspace.DocumentBuilder.onBuildPhase(state, () => {\r\n this.clear();\r\n }));\r\n this.toDispose.push(sharedServices.workspace.DocumentBuilder.onUpdate((_changed, deleted) => {\r\n if (deleted.length > 0) { // react only on deleted documents\r\n this.clear();\r\n }\r\n }));\r\n } else {\r\n this.toDispose.push(sharedServices.workspace.DocumentBuilder.onUpdate(() => { // react on both changed and deleted documents\r\n this.clear();\r\n }));\r\n }\r\n }\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021-2022 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport type { AstNode, AstNodeDescription, AstReflection, ReferenceInfo } from '../syntax-tree.js';\r\nimport type { Stream } from '../utils/stream.js';\r\nimport type { AstNodeDescriptionProvider } from '../workspace/ast-descriptions.js';\r\nimport type { IndexManager } from '../workspace/index-manager.js';\r\nimport type { NameProvider } from './name-provider.js';\r\nimport type { Scope, ScopeOptions} from './scope.js';\r\nimport { MapScope, StreamScope } from './scope.js';\r\nimport { getDocument } from '../utils/ast-utils.js';\r\nimport { stream } from '../utils/stream.js';\r\nimport { WorkspaceCache } from '../utils/caching.js';\r\n\r\n/**\r\n * Language-specific service for determining the scope of target elements visible in a specific cross-reference context.\r\n */\r\nexport interface ScopeProvider {\r\n\r\n /**\r\n * Return a scope describing what elements are visible for the given AST node and cross-reference\r\n * identifier.\r\n *\r\n * @param context Information about the reference for which a scope is requested.\r\n */\r\n getScope(context: ReferenceInfo): Scope;\r\n\r\n}\r\n\r\nexport class DefaultScopeProvider implements ScopeProvider {\r\n\r\n protected readonly reflection: AstReflection;\r\n protected readonly nameProvider: NameProvider;\r\n protected readonly descriptions: AstNodeDescriptionProvider;\r\n protected readonly indexManager: IndexManager;\r\n\r\n protected readonly globalScopeCache: WorkspaceCache;\r\n\r\n constructor(services: LangiumCoreServices) {\r\n this.reflection = services.shared.AstReflection;\r\n this.nameProvider = services.references.NameProvider;\r\n this.descriptions = services.workspace.AstNodeDescriptionProvider;\r\n this.indexManager = services.shared.workspace.IndexManager;\r\n this.globalScopeCache = new WorkspaceCache(services.shared);\r\n }\r\n\r\n getScope(context: ReferenceInfo): Scope {\r\n const scopes: Array> = [];\r\n const referenceType = this.reflection.getReferenceType(context);\r\n\r\n const precomputed = getDocument(context.container).precomputedScopes;\r\n if (precomputed) {\r\n let currentNode: AstNode | undefined = context.container;\r\n do {\r\n const allDescriptions = precomputed.get(currentNode);\r\n if (allDescriptions.length > 0) {\r\n scopes.push(stream(allDescriptions).filter(\r\n desc => this.reflection.isSubtype(desc.type, referenceType)));\r\n }\r\n currentNode = currentNode.$container;\r\n } while (currentNode);\r\n }\r\n\r\n let result: Scope = this.getGlobalScope(referenceType, context);\r\n for (let i = scopes.length - 1; i >= 0; i--) {\r\n result = this.createScope(scopes[i], result);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Create a scope for the given collection of AST node descriptions.\r\n */\r\n protected createScope(elements: Iterable, outerScope?: Scope, options?: ScopeOptions): Scope {\r\n return new StreamScope(stream(elements), outerScope, options);\r\n }\r\n\r\n /**\r\n * Create a scope for the given collection of AST nodes, which need to be transformed into respective\r\n * descriptions first. This is done using the `NameProvider` and `AstNodeDescriptionProvider` services.\r\n */\r\n protected createScopeForNodes(elements: Iterable, outerScope?: Scope, options?: ScopeOptions): Scope {\r\n const s = stream(elements).map(e => {\r\n const name = this.nameProvider.getName(e);\r\n if (name) {\r\n return this.descriptions.createDescription(e, name);\r\n }\r\n return undefined;\r\n }).nonNullable();\r\n return new StreamScope(s, outerScope, options);\r\n }\r\n\r\n /**\r\n * Create a global scope filtered for the given reference type.\r\n */\r\n protected getGlobalScope(referenceType: string, _context: ReferenceInfo): Scope {\r\n return this.globalScopeCache.get(referenceType, () => new MapScope(this.indexManager.allElements(referenceType)));\r\n }\r\n\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport { URI } from 'vscode-uri';\r\nimport type { CommentProvider } from '../documentation/comment-provider.js';\r\nimport type { NameProvider } from '../references/name-provider.js';\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport type { AstNode, CstNode, GenericAstNode, Mutable, Reference } from '../syntax-tree.js';\r\nimport { isAstNode, isReference } from '../syntax-tree.js';\r\nimport { getDocument } from '../utils/ast-utils.js';\r\nimport { findNodesForProperty } from '../utils/grammar-utils.js';\r\nimport type { AstNodeLocator } from '../workspace/ast-node-locator.js';\r\nimport type { DocumentSegment, LangiumDocument, LangiumDocuments } from '../workspace/documents.js';\r\n\r\nexport interface JsonSerializeOptions {\r\n /** The space parameter for `JSON.stringify`, controlling whether and how to pretty-print the output. */\r\n space?: string | number;\r\n /** Whether to include the `$refText` property for references (the name used to identify the target node). */\r\n refText?: boolean;\r\n /** Whether to include the `$sourceText` property, which holds the full source text from which an AST node was parsed. */\r\n sourceText?: boolean;\r\n /** Whether to include the `$textRegion` property, which holds information to trace AST node properties to their respective source text regions. */\r\n textRegions?: boolean;\r\n /** Whether to include the `$comment` property, which holds comments according to the CommentProvider service. */\r\n comments?: boolean;\r\n /** The replacer parameter for `JSON.stringify`; the default replacer given as parameter should be used to apply basic replacements. */\r\n replacer?: (key: string, value: unknown, defaultReplacer: (key: string, value: unknown) => unknown) => unknown\r\n /** Used to convert and serialize URIs when the target of a cross-reference is in a different document. */\r\n uriConverter?: (uri: URI, reference: Reference) => string\r\n}\r\n\r\nexport interface JsonDeserializeOptions {\r\n /** Used to parse and convert URIs when the target of a cross-reference is in a different document. */\r\n uriConverter?: (uri: string) => URI\r\n}\r\n\r\n/**\r\n * {@link AstNode}s that may carry information on their definition area within the DSL text.\r\n */\r\nexport interface AstNodeWithTextRegion extends AstNode {\r\n $sourceText?: string;\r\n $textRegion?: AstNodeRegionWithAssignments;\r\n}\r\n\r\n/**\r\n * {@link AstNode}s that may carry a semantically relevant comment.\r\n */\r\nexport interface AstNodeWithComment extends AstNode {\r\n $comment?: string;\r\n}\r\n\r\nexport function isAstNodeWithComment(node: AstNode): node is AstNodeWithComment {\r\n return typeof (node as AstNodeWithComment).$comment === 'string';\r\n}\r\n\r\n/**\r\n * A {@link DocumentSegment} representing the definition area of an AstNode within the DSL text.\r\n * Usually contains text region information on all assigned property values of the AstNode,\r\n * and may contain the defining file's URI as string.\r\n */\r\nexport interface AstNodeRegionWithAssignments extends DocumentSegment {\r\n /**\r\n * A record containing an entry for each assigned property of the AstNode.\r\n * The key is equal to the property name and the value is an array of the property values'\r\n * text regions, regardless of whether the property is a single value or list property.\r\n */\r\n assignments?: Record;\r\n /**\r\n * The AstNode defining file's URI as string\r\n */\r\n documentURI?: string;\r\n}\r\n\r\n/**\r\n * Utility service for transforming an `AstNode` into a JSON string and vice versa.\r\n */\r\nexport interface JsonSerializer {\r\n /**\r\n * Serialize an `AstNode` into a JSON `string`.\r\n * @param node The `AstNode` to be serialized.\r\n * @param options Serialization options\r\n */\r\n serialize(node: AstNode, options?: JsonSerializeOptions): string;\r\n /**\r\n * Deserialize (parse) a JSON `string` into an `AstNode`.\r\n */\r\n deserialize(content: string, options?: JsonDeserializeOptions): T;\r\n}\r\n\r\n/**\r\n * A cross-reference in the serialized JSON representation of an AstNode.\r\n */\r\ninterface IntermediateReference {\r\n /** URI pointing to the target element. This is either `#${path}` if the target is in the same document, or `${documentURI}#${path}` otherwise. */\r\n $ref?: string\r\n /** The actual text used to look up the reference target in the surrounding scope. */\r\n $refText?: string\r\n /** If any problem occurred while resolving the reference, it is described by this property. */\r\n $error?: string\r\n}\r\n\r\nfunction isIntermediateReference(obj: unknown): obj is IntermediateReference {\r\n return typeof obj === 'object' && !!obj && ('$ref' in obj || '$error' in obj);\r\n}\r\n\r\nexport class DefaultJsonSerializer implements JsonSerializer {\r\n\r\n /** The set of AstNode properties to be ignored by the serializer. */\r\n ignoreProperties = new Set(['$container', '$containerProperty', '$containerIndex', '$document', '$cstNode']);\r\n\r\n /** The document that is currently processed by the serializer; this is used by the replacer function. */\r\n protected currentDocument: LangiumDocument | undefined;\r\n\r\n protected readonly langiumDocuments: LangiumDocuments;\r\n protected readonly astNodeLocator: AstNodeLocator;\r\n protected readonly nameProvider: NameProvider;\r\n protected readonly commentProvider: CommentProvider;\r\n\r\n constructor(services: LangiumCoreServices) {\r\n this.langiumDocuments = services.shared.workspace.LangiumDocuments;\r\n this.astNodeLocator = services.workspace.AstNodeLocator;\r\n this.nameProvider = services.references.NameProvider;\r\n this.commentProvider = services.documentation.CommentProvider;\r\n }\r\n\r\n serialize(node: AstNode, options?: JsonSerializeOptions): string {\r\n const serializeOptions = options ?? {};\r\n const specificReplacer = options?.replacer;\r\n const defaultReplacer = (key: string, value: unknown) => this.replacer(key, value, serializeOptions);\r\n const replacer = specificReplacer ? (key: string, value: unknown) => specificReplacer(key, value, defaultReplacer) : defaultReplacer;\r\n\r\n try {\r\n this.currentDocument = getDocument(node);\r\n return JSON.stringify(node, replacer, options?.space);\r\n } finally {\r\n this.currentDocument = undefined;\r\n }\r\n }\r\n\r\n deserialize(content: string, options?: JsonDeserializeOptions): T {\r\n const deserializeOptions = options ?? {};\r\n const root = JSON.parse(content);\r\n this.linkNode(root, root, deserializeOptions);\r\n return root;\r\n }\r\n\r\n protected replacer(key: string, value: unknown, { refText, sourceText, textRegions, comments, uriConverter }: JsonSerializeOptions): unknown {\r\n if (this.ignoreProperties.has(key)) {\r\n return undefined;\r\n } else if (isReference(value)) {\r\n const refValue = value.ref;\r\n const $refText = refText ? value.$refText : undefined;\r\n if (refValue) {\r\n const targetDocument = getDocument(refValue);\r\n let targetUri = '';\r\n if (this.currentDocument && this.currentDocument !== targetDocument) {\r\n if (uriConverter) {\r\n targetUri = uriConverter(targetDocument.uri, value);\r\n } else {\r\n targetUri = targetDocument.uri.toString();\r\n }\r\n }\r\n const targetPath = this.astNodeLocator.getAstNodePath(refValue);\r\n return {\r\n $ref: `${targetUri}#${targetPath}`,\r\n $refText\r\n } satisfies IntermediateReference;\r\n } else {\r\n return {\r\n $error: value.error?.message ?? 'Could not resolve reference',\r\n $refText\r\n } satisfies IntermediateReference;\r\n }\r\n } else if (isAstNode(value)) {\r\n let astNode: AstNodeWithTextRegion | undefined = undefined;\r\n if (textRegions) {\r\n astNode = this.addAstNodeRegionWithAssignmentsTo({ ...value });\r\n if ((!key || value.$document) && astNode?.$textRegion) {\r\n // The document URI is added to the root node of the resulting JSON tree\r\n astNode.$textRegion.documentURI = this.currentDocument?.uri.toString();\r\n }\r\n }\r\n if (sourceText && !key) {\r\n astNode ??= { ...value };\r\n astNode.$sourceText = value.$cstNode?.text;\r\n }\r\n if (comments) {\r\n astNode ??= { ...value };\r\n const comment = this.commentProvider.getComment(value);\r\n if (comment) {\r\n (astNode as AstNodeWithComment).$comment = comment.replace(/\\r/g, '');\r\n }\r\n }\r\n return astNode ?? value;\r\n } else {\r\n return value;\r\n }\r\n }\r\n\r\n protected addAstNodeRegionWithAssignmentsTo(node: AstNodeWithTextRegion) {\r\n const createDocumentSegment: (cstNode: CstNode) => AstNodeRegionWithAssignments = cstNode => {\r\n offset: cstNode.offset,\r\n end: cstNode.end,\r\n length: cstNode.length,\r\n range: cstNode.range,\r\n };\r\n\r\n if (node.$cstNode) {\r\n const textRegion = node.$textRegion = createDocumentSegment(node.$cstNode);\r\n const assignments: Record = textRegion.assignments = {};\r\n\r\n Object.keys(node).filter(key => !key.startsWith('$')).forEach(key => {\r\n const propertyAssignments = findNodesForProperty(node.$cstNode, key).map(createDocumentSegment);\r\n if (propertyAssignments.length !== 0) {\r\n assignments[key] = propertyAssignments;\r\n }\r\n });\r\n\r\n return node;\r\n }\r\n return undefined;\r\n }\r\n\r\n protected linkNode(node: GenericAstNode, root: AstNode, options: JsonDeserializeOptions, container?: AstNode, containerProperty?: string, containerIndex?: number) {\r\n for (const [propertyName, item] of Object.entries(node)) {\r\n if (Array.isArray(item)) {\r\n for (let index = 0; index < item.length; index++) {\r\n const element = item[index];\r\n if (isIntermediateReference(element)) {\r\n item[index] = this.reviveReference(node, propertyName, root, element, options);\r\n } else if (isAstNode(element)) {\r\n this.linkNode(element as GenericAstNode, root, options, node, propertyName, index);\r\n }\r\n }\r\n } else if (isIntermediateReference(item)) {\r\n node[propertyName] = this.reviveReference(node, propertyName, root, item, options);\r\n } else if (isAstNode(item)) {\r\n this.linkNode(item as GenericAstNode, root, options, node, propertyName);\r\n }\r\n }\r\n const mutable = node as Mutable;\r\n mutable.$container = container;\r\n mutable.$containerProperty = containerProperty;\r\n mutable.$containerIndex = containerIndex;\r\n }\r\n\r\n protected reviveReference(container: AstNode, property: string, root: AstNode, reference: IntermediateReference, options: JsonDeserializeOptions): Reference | undefined {\r\n let refText = reference.$refText;\r\n let error = reference.$error;\r\n if (reference.$ref) {\r\n const ref = this.getRefNode(root, reference.$ref, options.uriConverter);\r\n if (isAstNode(ref)) {\r\n if (!refText) {\r\n refText = this.nameProvider.getName(ref);\r\n }\r\n return {\r\n $refText: refText ?? '',\r\n ref\r\n };\r\n } else {\r\n error = ref;\r\n }\r\n }\r\n if (error) {\r\n const ref: Mutable = {\r\n $refText: refText ?? ''\r\n };\r\n ref.error = {\r\n container,\r\n property,\r\n message: error,\r\n reference: ref\r\n };\r\n return ref;\r\n } else {\r\n return undefined;\r\n }\r\n }\r\n\r\n protected getRefNode(root: AstNode, uri: string, uriConverter?: (uri: string) => URI): AstNode | string {\r\n try {\r\n const fragmentIndex = uri.indexOf('#');\r\n if (fragmentIndex === 0) {\r\n const node = this.astNodeLocator.getAstNode(root, uri.substring(1));\r\n if (!node) {\r\n return 'Could not resolve path: ' + uri;\r\n }\r\n return node;\r\n }\r\n if (fragmentIndex < 0) {\r\n const documentUri = uriConverter ? uriConverter(uri) : URI.parse(uri);\r\n const document = this.langiumDocuments.getDocument(documentUri);\r\n if (!document) {\r\n return 'Could not find document for URI: ' + uri;\r\n }\r\n return document.parseResult.value;\r\n }\r\n const documentUri = uriConverter ? uriConverter(uri.substring(0, fragmentIndex)) : URI.parse(uri.substring(0, fragmentIndex));\r\n const document = this.langiumDocuments.getDocument(documentUri);\r\n if (!document) {\r\n return 'Could not find document for URI: ' + uri;\r\n }\r\n if (fragmentIndex === uri.length - 1) {\r\n return document.parseResult.value;\r\n }\r\n const node = this.astNodeLocator.getAstNode(document.parseResult.value, uri.substring(fragmentIndex + 1));\r\n if (!node) {\r\n return 'Could not resolve URI: ' + uri;\r\n }\r\n return node;\r\n } catch (err) {\r\n return String(err);\r\n }\r\n }\r\n\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { LangiumCoreServices, LangiumSharedCoreServices } from './services.js';\r\nimport type { TextDocumentProvider } from './workspace/documents.js';\r\nimport { UriUtils, type URI } from './utils/uri-utils.js';\r\n\r\n/**\r\n * The service registry provides access to the language-specific {@link LangiumCoreServices} optionally including LSP-related services.\r\n * These are resolved via the URI of a text document.\r\n */\r\nexport interface ServiceRegistry {\r\n\r\n /**\r\n * Register a language via its injected services.\r\n */\r\n register(language: LangiumCoreServices): void;\r\n\r\n /**\r\n * Retrieve the language-specific services for the given URI. In case only one language is\r\n * registered, it may be used regardless of the URI format.\r\n */\r\n getServices(uri: URI): LangiumCoreServices;\r\n\r\n /**\r\n * Check whether services are available for the given URI.\r\n */\r\n hasServices(uri: URI): boolean;\r\n\r\n /**\r\n * The full set of registered language services.\r\n */\r\n readonly all: readonly LangiumCoreServices[];\r\n}\r\n\r\n/**\r\n * Generic registry for Langium services, but capable of being used with extending service sets as well (such as the lsp-complete LangiumCoreServices set)\r\n */\r\nexport class DefaultServiceRegistry implements ServiceRegistry {\r\n\r\n protected singleton?: LangiumCoreServices;\r\n protected readonly languageIdMap = new Map();\r\n protected readonly fileExtensionMap = new Map();\r\n\r\n /**\r\n * @deprecated Use the new `fileExtensionMap` (or `languageIdMap`) property instead.\r\n */\r\n protected get map(): Map | undefined {\r\n return this.fileExtensionMap;\r\n }\r\n\r\n protected readonly textDocuments?: TextDocumentProvider;\r\n\r\n constructor(services?: LangiumSharedCoreServices) {\r\n this.textDocuments = services?.workspace.TextDocuments;\r\n }\r\n\r\n register(language: LangiumCoreServices): void {\r\n const data = language.LanguageMetaData;\r\n for (const ext of data.fileExtensions) {\r\n if (this.fileExtensionMap.has(ext)) {\r\n console.warn(`The file extension ${ext} is used by multiple languages. It is now assigned to '${data.languageId}'.`);\r\n }\r\n this.fileExtensionMap.set(ext, language);\r\n }\r\n this.languageIdMap.set(data.languageId, language);\r\n if (this.languageIdMap.size === 1) {\r\n this.singleton = language;\r\n } else {\r\n this.singleton = undefined;\r\n }\r\n }\r\n\r\n getServices(uri: URI): LangiumCoreServices {\r\n if (this.singleton !== undefined) {\r\n return this.singleton;\r\n }\r\n if (this.languageIdMap.size === 0) {\r\n throw new Error('The service registry is empty. Use `register` to register the services of a language.');\r\n }\r\n const languageId = this.textDocuments?.get(uri)?.languageId;\r\n if (languageId !== undefined) {\r\n const services = this.languageIdMap.get(languageId);\r\n if (services) {\r\n return services;\r\n }\r\n }\r\n const ext = UriUtils.extname(uri);\r\n const services = this.fileExtensionMap.get(ext);\r\n if (!services) {\r\n if (languageId) {\r\n throw new Error(`The service registry contains no services for the extension '${ext}' for language '${languageId}'.`);\r\n } else {\r\n throw new Error(`The service registry contains no services for the extension '${ext}'.`);\r\n }\r\n }\r\n return services;\r\n }\r\n\r\n hasServices(uri: URI): boolean {\r\n try {\r\n this.getServices(uri);\r\n return true;\r\n } catch {\r\n return false;\r\n }\r\n }\r\n\r\n get all(): readonly LangiumCoreServices[] {\r\n return Array.from(this.languageIdMap.values());\r\n }\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { CodeDescription, DiagnosticRelatedInformation, DiagnosticTag, integer, Range } from 'vscode-languageserver-types';\r\nimport { assertUnreachable } from '../index.js';\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport type { AstNode, AstReflection, Properties } from '../syntax-tree.js';\r\nimport type { CancellationToken } from '../utils/cancellation.js';\r\nimport { MultiMap } from '../utils/collections.js';\r\nimport type { MaybePromise } from '../utils/promise-utils.js';\r\nimport { isOperationCancelled } from '../utils/promise-utils.js';\r\nimport type { Stream } from '../utils/stream.js';\r\nimport { stream } from '../utils/stream.js';\r\nimport type { DocumentSegment } from '../workspace/documents.js';\r\n\r\nexport type DiagnosticInfo> = {\r\n /** The AST node to which the diagnostic is attached. */\r\n node: N;\r\n /** If a property name is given, the diagnostic is restricted to the corresponding text region. */\r\n property?: P;\r\n /** If the value of a keyword is given, the diagnostic will appear at its corresponding text region */\r\n keyword?: string;\r\n /** In case of a multi-value property (array), an index can be given to select a specific element. */\r\n index?: number;\r\n /** If you want to create a diagnostic independent to any property, use the range property. */\r\n range?: Range;\r\n /** The diagnostic's code, which usually appear in the user interface. */\r\n code?: integer | string;\r\n /** An optional property to describe the error code. */\r\n codeDescription?: CodeDescription;\r\n /** Additional metadata about the diagnostic. */\r\n tags?: DiagnosticTag[];\r\n /** An array of related diagnostic information, e.g. when symbol-names within a scope collide all definitions can be marked via this property. */\r\n relatedInformation?: DiagnosticRelatedInformation[];\r\n /** A data entry field that is preserved between a `textDocument/publishDiagnostics` notification and `textDocument/codeAction` request. */\r\n data?: unknown;\r\n}\r\n\r\n/**\r\n * Shape of information commonly used in the `data` field of diagnostics.\r\n */\r\nexport interface DiagnosticData {\r\n /** Diagnostic code for identifying which code action to apply. This code is _not_ shown in the user interface. */\r\n code: string\r\n /** Specifies where to apply the code action in the form of a `DocumentSegment`. */\r\n actionSegment?: DocumentSegment\r\n /** Specifies where to apply the code action in the form of a `Range`. */\r\n actionRange?: Range\r\n}\r\n\r\n/**\r\n * Create DiagnosticData for a given diagnostic code. The result can be put into the `data` field of a DiagnosticInfo.\r\n */\r\nexport function diagnosticData(code: string): DiagnosticData {\r\n return { code };\r\n}\r\n\r\nexport type ValidationSeverity = 'error' | 'warning' | 'info' | 'hint';\r\n\r\nexport type ValidationAcceptor = (severity: ValidationSeverity, message: string, info: DiagnosticInfo) => void\r\n\r\nexport type ValidationCheck = (node: T, accept: ValidationAcceptor, cancelToken: CancellationToken) => MaybePromise;\r\n\r\n/**\r\n * A utility type for describing functions which will be called once before or after all the AstNodes of an AST/Langium document are validated.\r\n *\r\n * The AST is represented by its root AstNode.\r\n *\r\n * The given validation acceptor helps to report some early or lately detected issues.\r\n *\r\n * The 'categories' indicate, which validation categories are executed for all the AstNodes.\r\n * This helps to tailor the preparations/tear-down logic to the actually executed checks on the nodes.\r\n *\r\n * It is recommended to support interrupts during long-running logic with 'interruptAndCheck(cancelToken)'.\r\n */\r\nexport type ValidationPreparation = (rootNode: AstNode, accept: ValidationAcceptor, categories: ValidationCategory[], cancelToken: CancellationToken) => MaybePromise;\r\n\r\n/**\r\n * A utility type for associating non-primitive AST types to corresponding validation checks. For example:\r\n *\r\n * ```ts\r\n * const checks: ValidationChecks = {\r\n * State: validator.checkStateNameStartsWithCapital\r\n * };\r\n * ```\r\n *\r\n * If an AST type does not extend AstNode, e.g. if it describes a union of string literals, that type's name must not occur as a key in objects of type `ValidationCheck<...>`.\r\n *\r\n * @param T a type definition mapping language specific type names (keys) to the corresponding types (values)\r\n */\r\nexport type ValidationChecks = {\r\n [K in keyof T]?: T[K] extends AstNode ? ValidationCheck | Array> : never\r\n} & {\r\n AstNode?: ValidationCheck | Array>;\r\n}\r\n\r\n/**\r\n * `fast` checks can be executed after every document change (i.e. as the user is typing). If a check\r\n * is too slow it can delay the response to document changes, yielding bad user experience. By marking\r\n * it as `slow`, it will be skipped for normal as-you-type validation. Then it's up to you when to\r\n * schedule these long-running checks: after the fast checks are done, or after saving a document,\r\n * or with an explicit command, etc.\r\n *\r\n * `built-in` checks are errors produced by the lexer, the parser, or the linker. They cannot be used\r\n * for custom validation checks.\r\n */\r\nexport type ValidationCategory = 'fast' | 'slow' | 'built-in'\r\n\r\nexport namespace ValidationCategory {\r\n export const all: readonly ValidationCategory[] = ['fast', 'slow', 'built-in'];\r\n}\r\n\r\ntype ValidationCheckEntry = {\r\n check: ValidationCheck\r\n category: ValidationCategory\r\n}\r\n\r\n/**\r\n * Manages a set of `ValidationCheck`s to be applied when documents are validated.\r\n */\r\nexport class ValidationRegistry {\r\n private readonly entries = new MultiMap();\r\n private readonly reflection: AstReflection;\r\n\r\n private entriesBefore: ValidationPreparation[] = [];\r\n private entriesAfter: ValidationPreparation[] = [];\r\n\r\n constructor(services: LangiumCoreServices) {\r\n this.reflection = services.shared.AstReflection;\r\n }\r\n\r\n /**\r\n * Register a set of validation checks. Each value in the record can be either a single validation check (i.e. a function)\r\n * or an array of validation checks.\r\n *\r\n * @param checksRecord Set of validation checks to register.\r\n * @param category Optional category for the validation checks (defaults to `'fast'`).\r\n * @param thisObj Optional object to be used as `this` when calling the validation check functions.\r\n */\r\n register(checksRecord: ValidationChecks, thisObj: ThisParameterType = this, category: ValidationCategory = 'fast'): void {\r\n if (category === 'built-in') {\r\n throw new Error(\"The 'built-in' category is reserved for lexer, parser, and linker errors.\");\r\n }\r\n for (const [type, ch] of Object.entries(checksRecord)) {\r\n const callbacks = ch as ValidationCheck | ValidationCheck[];\r\n if (Array.isArray(callbacks)) {\r\n for (const check of callbacks) {\r\n const entry: ValidationCheckEntry = {\r\n check: this.wrapValidationException(check, thisObj),\r\n category\r\n };\r\n this.addEntry(type, entry);\r\n }\r\n } else if (typeof callbacks === 'function') {\r\n const entry: ValidationCheckEntry = {\r\n check: this.wrapValidationException(callbacks, thisObj),\r\n category\r\n };\r\n this.addEntry(type, entry);\r\n } else {\r\n assertUnreachable(callbacks);\r\n }\r\n }\r\n }\r\n\r\n protected wrapValidationException(check: ValidationCheck, thisObj: unknown): ValidationCheck {\r\n return async (node, accept, cancelToken) => {\r\n await this.handleException(() => check.call(thisObj, node, accept, cancelToken), 'An error occurred during validation', accept, node);\r\n };\r\n }\r\n\r\n protected async handleException(functionality: () => MaybePromise, messageContext: string, accept: ValidationAcceptor, node: AstNode): Promise {\r\n try {\r\n await functionality();\r\n } catch (err) {\r\n if (isOperationCancelled(err)) {\r\n throw err;\r\n }\r\n console.error(`${messageContext}:`, err);\r\n if (err instanceof Error && err.stack) {\r\n console.error(err.stack);\r\n }\r\n const messageDetails = err instanceof Error ? err.message : String(err);\r\n accept('error', `${messageContext}: ${messageDetails}`, { node });\r\n }\r\n }\r\n\r\n protected addEntry(type: string, entry: ValidationCheckEntry): void {\r\n if (type === 'AstNode') {\r\n this.entries.add('AstNode', entry);\r\n return;\r\n }\r\n for (const subtype of this.reflection.getAllSubTypes(type)) {\r\n this.entries.add(subtype, entry);\r\n }\r\n }\r\n\r\n getChecks(type: string, categories?: ValidationCategory[]): Stream {\r\n let checks = stream(this.entries.get(type))\r\n .concat(this.entries.get('AstNode'));\r\n if (categories) {\r\n checks = checks.filter(entry => categories.includes(entry.category));\r\n }\r\n return checks.map(entry => entry.check);\r\n }\r\n\r\n /**\r\n * Register logic which will be executed once before validating all the nodes of an AST/Langium document.\r\n * This helps to prepare or initialize some information which are required or reusable for the following checks on the AstNodes.\r\n *\r\n * As an example, for validating unique fully-qualified names of nodes in the AST,\r\n * here the map for mapping names to nodes could be established.\r\n * During the usual checks on the nodes, they are put into this map with their name.\r\n *\r\n * Note that this approach makes validations stateful, which is relevant e.g. when cancelling the validation.\r\n * Therefore it is recommended to clear stored information\r\n * _before_ validating an AST to validate each AST unaffected from other ASTs\r\n * AND _after_ validating the AST to free memory by information which are no longer used.\r\n *\r\n * @param checkBefore a set-up function which will be called once before actually validating an AST\r\n * @param thisObj Optional object to be used as `this` when calling the validation check functions.\r\n */\r\n registerBeforeDocument(checkBefore: ValidationPreparation, thisObj: ThisParameterType = this): void {\r\n this.entriesBefore.push(this.wrapPreparationException(checkBefore, 'An error occurred during set-up of the validation', thisObj));\r\n }\r\n\r\n /**\r\n * Register logic which will be executed once after validating all the nodes of an AST/Langium document.\r\n * This helps to finally evaluate information which are collected during the checks on the AstNodes.\r\n *\r\n * As an example, for validating unique fully-qualified names of nodes in the AST,\r\n * here the map with all the collected nodes and their names is checked\r\n * and validation hints are created for all nodes with the same name.\r\n *\r\n * Note that this approach makes validations stateful, which is relevant e.g. when cancelling the validation.\r\n * Therefore it is recommended to clear stored information\r\n * _before_ validating an AST to validate each AST unaffected from other ASTs\r\n * AND _after_ validating the AST to free memory by information which are no longer used.\r\n *\r\n * @param checkBefore a set-up function which will be called once before actually validating an AST\r\n * @param thisObj Optional object to be used as `this` when calling the validation check functions.\r\n */\r\n registerAfterDocument(checkAfter: ValidationPreparation, thisObj: ThisParameterType = this): void {\r\n this.entriesAfter.push(this.wrapPreparationException(checkAfter, 'An error occurred during tear-down of the validation', thisObj));\r\n }\r\n\r\n protected wrapPreparationException(check: ValidationPreparation, messageContext: string, thisObj: unknown): ValidationPreparation {\r\n return async (rootNode, accept, categories, cancelToken) => {\r\n await this.handleException(() => check.call(thisObj, rootNode, accept, categories, cancelToken), messageContext, accept, rootNode);\r\n };\r\n }\r\n\r\n get checksBefore(): ValidationPreparation[] {\r\n return this.entriesBefore;\r\n }\r\n\r\n get checksAfter(): ValidationPreparation[] {\r\n return this.entriesAfter;\r\n }\r\n\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { MismatchedTokenException } from 'chevrotain';\r\nimport type { DiagnosticSeverity, Position, Range, Diagnostic } from 'vscode-languageserver-types';\r\nimport type { LanguageMetaData } from '../languages/language-meta-data.js';\r\nimport type { ParseResult } from '../parser/langium-parser.js';\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport type { AstNode, CstNode } from '../syntax-tree.js';\r\nimport type { LangiumDocument } from '../workspace/documents.js';\r\nimport type { DiagnosticData, DiagnosticInfo, ValidationAcceptor, ValidationCategory, ValidationRegistry, ValidationSeverity } from './validation-registry.js';\r\nimport { CancellationToken } from '../utils/cancellation.js';\r\nimport { findNodeForKeyword, findNodeForProperty } from '../utils/grammar-utils.js';\r\nimport { streamAst } from '../utils/ast-utils.js';\r\nimport { tokenToRange } from '../utils/cst-utils.js';\r\nimport { interruptAndCheck, isOperationCancelled } from '../utils/promise-utils.js';\r\nimport { diagnosticData } from './validation-registry.js';\r\nimport type { LexingDiagnostic, LexingDiagnosticSeverity } from '../parser/token-builder.js';\r\n\r\nexport interface ValidationOptions {\r\n /**\r\n * If this is set, only the checks associated with these categories are executed; otherwise\r\n * all checks are executed. The default category if not specified to the registry is `'fast'`.\r\n */\r\n categories?: ValidationCategory[];\r\n /** If true, no further diagnostics are reported if there are lexing errors. */\r\n stopAfterLexingErrors?: boolean\r\n /** If true, no further diagnostics are reported if there are parsing errors. */\r\n stopAfterParsingErrors?: boolean\r\n /** If true, no further diagnostics are reported if there are linking errors. */\r\n stopAfterLinkingErrors?: boolean\r\n}\r\n\r\n/**\r\n * Language-specific service for validating `LangiumDocument`s.\r\n */\r\nexport interface DocumentValidator {\r\n /**\r\n * Validates the whole specified document.\r\n *\r\n * @param document specified document to validate\r\n * @param options options to control the validation process\r\n * @param cancelToken allows to cancel the current operation\r\n * @throws `OperationCanceled` if a user action occurs during execution\r\n */\r\n validateDocument(document: LangiumDocument, options?: ValidationOptions, cancelToken?: CancellationToken): Promise;\r\n}\r\n\r\nexport class DefaultDocumentValidator implements DocumentValidator {\r\n\r\n protected readonly validationRegistry: ValidationRegistry;\r\n protected readonly metadata: LanguageMetaData;\r\n\r\n constructor(services: LangiumCoreServices) {\r\n this.validationRegistry = services.validation.ValidationRegistry;\r\n this.metadata = services.LanguageMetaData;\r\n }\r\n\r\n async validateDocument(document: LangiumDocument, options: ValidationOptions = {}, cancelToken = CancellationToken.None): Promise {\r\n const parseResult = document.parseResult;\r\n const diagnostics: Diagnostic[] = [];\r\n\r\n await interruptAndCheck(cancelToken);\r\n\r\n if (!options.categories || options.categories.includes('built-in')) {\r\n this.processLexingErrors(parseResult, diagnostics, options);\r\n if (options.stopAfterLexingErrors && diagnostics.some(d => d.data?.code === DocumentValidator.LexingError)) {\r\n return diagnostics;\r\n }\r\n\r\n this.processParsingErrors(parseResult, diagnostics, options);\r\n if (options.stopAfterParsingErrors && diagnostics.some(d => d.data?.code === DocumentValidator.ParsingError)) {\r\n return diagnostics;\r\n }\r\n\r\n this.processLinkingErrors(document, diagnostics, options);\r\n if (options.stopAfterLinkingErrors && diagnostics.some(d => d.data?.code === DocumentValidator.LinkingError)) {\r\n return diagnostics;\r\n }\r\n }\r\n\r\n // Process custom validations\r\n try {\r\n diagnostics.push(...await this.validateAst(parseResult.value, options, cancelToken));\r\n } catch (err) {\r\n if (isOperationCancelled(err)) {\r\n throw err;\r\n }\r\n console.error('An error occurred during validation:', err);\r\n }\r\n\r\n await interruptAndCheck(cancelToken);\r\n\r\n return diagnostics;\r\n }\r\n\r\n protected processLexingErrors(parseResult: ParseResult, diagnostics: Diagnostic[], _options: ValidationOptions): void {\r\n const lexerDiagnostics = [...parseResult.lexerErrors, ...parseResult.lexerReport?.diagnostics ?? []] as LexingDiagnostic[];\r\n for (const lexerDiagnostic of lexerDiagnostics) {\r\n const severity = lexerDiagnostic.severity ?? 'error';\r\n const diagnostic: Diagnostic = {\r\n severity: toDiagnosticSeverity(severity),\r\n range: {\r\n start: {\r\n line: lexerDiagnostic.line! - 1,\r\n character: lexerDiagnostic.column! - 1\r\n },\r\n end: {\r\n line: lexerDiagnostic.line! - 1,\r\n character: lexerDiagnostic.column! + lexerDiagnostic.length - 1\r\n }\r\n },\r\n message: lexerDiagnostic.message,\r\n data: toDiagnosticData(severity),\r\n source: this.getSource()\r\n };\r\n diagnostics.push(diagnostic);\r\n }\r\n }\r\n\r\n protected processParsingErrors(parseResult: ParseResult, diagnostics: Diagnostic[], _options: ValidationOptions): void {\r\n for (const parserError of parseResult.parserErrors) {\r\n let range: Range | undefined = undefined;\r\n // We can run into the chevrotain error recovery here\r\n // The token contained in the parser error might be automatically inserted\r\n // In this case every position value will be `NaN`\r\n if (isNaN(parserError.token.startOffset)) {\r\n // Some special parser error types contain a `previousToken`\r\n // We can simply append our diagnostic to that token\r\n if ('previousToken' in parserError) {\r\n const token = (parserError as MismatchedTokenException).previousToken;\r\n if (!isNaN(token.startOffset)) {\r\n const position: Position = { line: token.endLine! - 1, character: token.endColumn! };\r\n range = { start: position, end: position};\r\n } else {\r\n // No valid prev token. Might be empty document or containing only hidden tokens.\r\n // Point to document start\r\n const position: Position = { line: 0, character: 0 };\r\n range = { start: position, end: position};\r\n }\r\n }\r\n } else {\r\n range = tokenToRange(parserError.token);\r\n }\r\n if (range) {\r\n const diagnostic: Diagnostic = {\r\n severity: toDiagnosticSeverity('error'),\r\n range,\r\n message: parserError.message,\r\n data: diagnosticData(DocumentValidator.ParsingError),\r\n source: this.getSource()\r\n };\r\n diagnostics.push(diagnostic);\r\n }\r\n }\r\n }\r\n\r\n protected processLinkingErrors(document: LangiumDocument, diagnostics: Diagnostic[], _options: ValidationOptions): void {\r\n for (const reference of document.references) {\r\n const linkingError = reference.error;\r\n if (linkingError) {\r\n const info: DiagnosticInfo = {\r\n node: linkingError.container,\r\n property: linkingError.property,\r\n index: linkingError.index,\r\n data: {\r\n code: DocumentValidator.LinkingError,\r\n containerType: linkingError.container.$type,\r\n property: linkingError.property,\r\n refText: linkingError.reference.$refText\r\n } satisfies LinkingErrorData\r\n };\r\n diagnostics.push(this.toDiagnostic('error', linkingError.message, info));\r\n }\r\n }\r\n }\r\n\r\n protected async validateAst(rootNode: AstNode, options: ValidationOptions, cancelToken = CancellationToken.None): Promise {\r\n const validationItems: Diagnostic[] = [];\r\n const acceptor: ValidationAcceptor = (severity: ValidationSeverity, message: string, info: DiagnosticInfo) => {\r\n validationItems.push(this.toDiagnostic(severity, message, info));\r\n };\r\n\r\n await this.validateAstBefore(rootNode, options, acceptor, cancelToken);\r\n await this.validateAstNodes(rootNode, options, acceptor, cancelToken);\r\n await this.validateAstAfter(rootNode, options, acceptor, cancelToken);\r\n\r\n return validationItems;\r\n }\r\n\r\n protected async validateAstBefore(rootNode: AstNode, options: ValidationOptions, acceptor: ValidationAcceptor, cancelToken = CancellationToken.None): Promise {\r\n const checksBefore = this.validationRegistry.checksBefore;\r\n for (const checkBefore of checksBefore) {\r\n await interruptAndCheck(cancelToken);\r\n await checkBefore(rootNode, acceptor, options.categories ?? [], cancelToken);\r\n }\r\n }\r\n\r\n protected async validateAstNodes(rootNode: AstNode, options: ValidationOptions, acceptor: ValidationAcceptor, cancelToken = CancellationToken.None): Promise {\r\n await Promise.all(streamAst(rootNode).map(async node => {\r\n await interruptAndCheck(cancelToken);\r\n const checks = this.validationRegistry.getChecks(node.$type, options.categories);\r\n for (const check of checks) {\r\n await check(node, acceptor, cancelToken);\r\n }\r\n }));\r\n }\r\n\r\n protected async validateAstAfter(rootNode: AstNode, options: ValidationOptions, acceptor: ValidationAcceptor, cancelToken = CancellationToken.None): Promise {\r\n const checksAfter = this.validationRegistry.checksAfter;\r\n for (const checkAfter of checksAfter) {\r\n await interruptAndCheck(cancelToken);\r\n await checkAfter(rootNode, acceptor, options.categories ?? [], cancelToken);\r\n }\r\n }\r\n\r\n protected toDiagnostic(severity: ValidationSeverity, message: string, info: DiagnosticInfo): Diagnostic {\r\n return {\r\n message,\r\n range: getDiagnosticRange(info),\r\n severity: toDiagnosticSeverity(severity),\r\n code: info.code,\r\n codeDescription: info.codeDescription,\r\n tags: info.tags,\r\n relatedInformation: info.relatedInformation,\r\n data: info.data,\r\n source: this.getSource()\r\n };\r\n }\r\n\r\n protected getSource(): string | undefined {\r\n return this.metadata.languageId;\r\n }\r\n}\r\n\r\nexport function getDiagnosticRange(info: DiagnosticInfo): Range {\r\n if (info.range) {\r\n return info.range;\r\n }\r\n let cstNode: CstNode | undefined;\r\n if (typeof info.property === 'string') {\r\n cstNode = findNodeForProperty(info.node.$cstNode, info.property, info.index);\r\n } else if (typeof info.keyword === 'string') {\r\n cstNode = findNodeForKeyword(info.node.$cstNode, info.keyword, info.index);\r\n }\r\n cstNode ??= info.node.$cstNode;\r\n if (!cstNode) {\r\n return {\r\n start: { line: 0, character: 0 },\r\n end: { line: 0, character: 0 }\r\n };\r\n }\r\n return cstNode.range;\r\n}\r\n\r\n/**\r\n * Transforms the diagnostic severity from the {@link LexingDiagnosticSeverity} format to LSP's `DiagnosticSeverity` format.\r\n *\r\n * @param severity The lexing diagnostic severity\r\n * @returns Diagnostic severity according to `vscode-languageserver-types/lib/esm/main.js#DiagnosticSeverity`\r\n */\r\nexport function toDiagnosticSeverity(severity: LexingDiagnosticSeverity): DiagnosticSeverity {\r\n switch (severity) {\r\n case 'error':\r\n return 1 satisfies typeof DiagnosticSeverity.Error;\r\n case 'warning':\r\n return 2 satisfies typeof DiagnosticSeverity.Warning;\r\n case 'info':\r\n return 3 satisfies typeof DiagnosticSeverity.Information;\r\n case 'hint':\r\n return 4 satisfies typeof DiagnosticSeverity.Hint;\r\n default:\r\n throw new Error('Invalid diagnostic severity: ' + severity);\r\n }\r\n}\r\n\r\nexport function toDiagnosticData(severity: LexingDiagnosticSeverity): DiagnosticData {\r\n switch (severity) {\r\n case 'error':\r\n return diagnosticData(DocumentValidator.LexingError);\r\n case 'warning':\r\n return diagnosticData(DocumentValidator.LexingWarning);\r\n case 'info':\r\n return diagnosticData(DocumentValidator.LexingInfo);\r\n case 'hint':\r\n return diagnosticData(DocumentValidator.LexingHint);\r\n default:\r\n throw new Error('Invalid diagnostic severity: ' + severity);\r\n }\r\n}\r\n\r\nexport namespace DocumentValidator {\r\n export const LexingError = 'lexing-error';\r\n export const LexingWarning = 'lexing-warning';\r\n export const LexingInfo = 'lexing-info';\r\n export const LexingHint = 'lexing-hint';\r\n export const ParsingError = 'parsing-error';\r\n export const LinkingError = 'linking-error';\r\n}\r\n\r\nexport interface LinkingErrorData extends DiagnosticData {\r\n containerType: string\r\n property: string\r\n refText: string\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { URI } from '../utils/uri-utils.js';\r\nimport type { NameProvider } from '../references/name-provider.js';\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport type { AstNode, AstNodeDescription, ReferenceInfo } from '../syntax-tree.js';\r\nimport type { AstNodeLocator } from './ast-node-locator.js';\r\nimport type { DocumentSegment, LangiumDocument } from './documents.js';\r\nimport { CancellationToken } from '../utils/cancellation.js';\r\nimport { isLinkingError } from '../syntax-tree.js';\r\nimport { getDocument, streamAst, streamReferences } from '../utils/ast-utils.js';\r\nimport { toDocumentSegment } from '../utils/cst-utils.js';\r\nimport { interruptAndCheck } from '../utils/promise-utils.js';\r\nimport { UriUtils } from '../utils/uri-utils.js';\r\n\r\n/**\r\n * Language-specific service for creating descriptions of AST nodes to be used for cross-reference resolutions.\r\n */\r\nexport interface AstNodeDescriptionProvider {\r\n\r\n /**\r\n * Create a description for the given AST node. This service method is typically used while indexing\r\n * the contents of a document and during scope computation.\r\n *\r\n * @param node An AST node.\r\n * @param name The name to be used to refer to the AST node. By default, this is determined by the\r\n * `NameProvider` service, but alternative names may be provided according to the semantics\r\n * of your language.\r\n * @param document The document containing the AST node. If omitted, it is taken from the root AST node.\r\n */\r\n createDescription(node: AstNode, name: string | undefined, document?: LangiumDocument): AstNodeDescription;\r\n\r\n}\r\n\r\nexport class DefaultAstNodeDescriptionProvider implements AstNodeDescriptionProvider {\r\n\r\n protected readonly astNodeLocator: AstNodeLocator;\r\n protected readonly nameProvider: NameProvider;\r\n\r\n constructor(services: LangiumCoreServices) {\r\n this.astNodeLocator = services.workspace.AstNodeLocator;\r\n this.nameProvider = services.references.NameProvider;\r\n }\r\n\r\n createDescription(node: AstNode, name: string | undefined, document?: LangiumDocument): AstNodeDescription {\r\n const doc = document ?? getDocument(node);\r\n name ??= this.nameProvider.getName(node);\r\n const path = this.astNodeLocator.getAstNodePath(node);\r\n if (!name) {\r\n throw new Error(`Node at path ${path} has no name.`);\r\n }\r\n let nameNodeSegment: DocumentSegment | undefined;\r\n const nameSegmentGetter = () => nameNodeSegment ??= toDocumentSegment(this.nameProvider.getNameNode(node) ?? node.$cstNode);\r\n return {\r\n node,\r\n name,\r\n get nameSegment() {\r\n return nameSegmentGetter();\r\n },\r\n selectionSegment: toDocumentSegment(node.$cstNode),\r\n type: node.$type,\r\n documentUri: doc.uri,\r\n path\r\n };\r\n }\r\n\r\n}\r\n\r\n/**\r\n * Describes a cross-reference within a document or between two documents.\r\n */\r\nexport interface ReferenceDescription {\r\n /** URI of the document that holds a reference */\r\n sourceUri: URI\r\n /** Path to AstNode that holds a reference */\r\n sourcePath: string\r\n /** Target document uri */\r\n targetUri: URI\r\n /** Path to the target AstNode inside the document */\r\n targetPath: string\r\n /** Segment of the reference text. */\r\n segment: DocumentSegment\r\n /** Marks a local reference i.e. a cross reference inside a document. */\r\n local?: boolean\r\n}\r\n\r\n/**\r\n * Language-specific service to create descriptions of all cross-references in a document. These are used by the `IndexManager`\r\n * to determine which documents are affected and should be rebuilt when a document is changed.\r\n */\r\nexport interface ReferenceDescriptionProvider {\r\n /**\r\n * Create descriptions of all cross-references found in the given document. These descriptions are\r\n * gathered by the `IndexManager` and stored in the global index so they can be considered when\r\n * a document change is reported by the client.\r\n *\r\n * @param document The document in which to gather cross-references.\r\n * @param cancelToken Indicates when to cancel the current operation.\r\n * @throws `OperationCanceled` if a user action occurs during execution\r\n */\r\n createDescriptions(document: LangiumDocument, cancelToken?: CancellationToken): Promise;\r\n}\r\n\r\nexport class DefaultReferenceDescriptionProvider implements ReferenceDescriptionProvider {\r\n\r\n protected readonly nodeLocator: AstNodeLocator;\r\n\r\n constructor(services: LangiumCoreServices) {\r\n this.nodeLocator = services.workspace.AstNodeLocator;\r\n }\r\n\r\n async createDescriptions(document: LangiumDocument, cancelToken = CancellationToken.None): Promise {\r\n const descr: ReferenceDescription[] = [];\r\n const rootNode = document.parseResult.value;\r\n for (const astNode of streamAst(rootNode)) {\r\n await interruptAndCheck(cancelToken);\r\n streamReferences(astNode).filter(refInfo => !isLinkingError(refInfo)).forEach(refInfo => {\r\n // TODO: Consider logging a warning or throw an exception when DocumentState is < than Linked\r\n const description = this.createDescription(refInfo);\r\n if (description) {\r\n descr.push(description);\r\n }\r\n });\r\n }\r\n return descr;\r\n }\r\n\r\n protected createDescription(refInfo: ReferenceInfo): ReferenceDescription | undefined {\r\n const targetNodeDescr = refInfo.reference.$nodeDescription;\r\n const refCstNode = refInfo.reference.$refNode;\r\n if (!targetNodeDescr || !refCstNode) {\r\n return undefined;\r\n }\r\n const docUri = getDocument(refInfo.container).uri;\r\n return {\r\n sourceUri: docUri,\r\n sourcePath: this.nodeLocator.getAstNodePath(refInfo.container),\r\n targetUri: targetNodeDescr.documentUri,\r\n targetPath: targetNodeDescr.path,\r\n segment: toDocumentSegment(refCstNode),\r\n local: UriUtils.equals(targetNodeDescr.documentUri, docUri)\r\n };\r\n }\r\n\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { AstNode } from '../syntax-tree.js';\r\n\r\n/**\r\n * Language-specific service for locating an `AstNode` in a document.\r\n */\r\nexport interface AstNodeLocator {\r\n\r\n /**\r\n * Creates a path represented by a `string` that identifies an `AstNode` inside its document.\r\n * It must be possible to retrieve exactly the same `AstNode` from the document using this path.\r\n *\r\n * @param node The `AstNode` for which to create the path.\r\n * @returns a path represented by a `string` that identifies `node` inside its document.\r\n * @see AstNodeLocator.getAstNode\r\n */\r\n getAstNodePath(node: AstNode): string;\r\n\r\n /**\r\n * Locates an `AstNode` inside another node by following the given path.\r\n *\r\n * @param node Parent element.\r\n * @param path Describes how to locate the `AstNode` inside the given `node`.\r\n * @returns The `AstNode` located under the given path, or `undefined` if the path cannot be resolved.\r\n * @see AstNodeLocator.getAstNodePath\r\n */\r\n getAstNode(node: AstNode, path: string): T | undefined;\r\n\r\n}\r\n\r\nexport class DefaultAstNodeLocator implements AstNodeLocator {\r\n protected segmentSeparator = '/';\r\n protected indexSeparator = '@';\r\n\r\n getAstNodePath(node: AstNode): string {\r\n if (node.$container) {\r\n const containerPath = this.getAstNodePath(node.$container);\r\n const newSegment = this.getPathSegment(node);\r\n const nodePath = containerPath + this.segmentSeparator + newSegment;\r\n return nodePath;\r\n }\r\n return '';\r\n }\r\n\r\n protected getPathSegment({ $containerProperty, $containerIndex }: AstNode): string {\r\n if (!$containerProperty) {\r\n throw new Error(\"Missing '$containerProperty' in AST node.\");\r\n }\r\n if ($containerIndex !== undefined) {\r\n return $containerProperty + this.indexSeparator + $containerIndex;\r\n }\r\n return $containerProperty;\r\n }\r\n\r\n getAstNode(node: AstNode, path: string): T | undefined {\r\n const segments = path.split(this.segmentSeparator);\r\n return segments.reduce((previousValue, currentValue) => {\r\n if (!previousValue || currentValue.length === 0) {\r\n return previousValue;\r\n }\r\n const propertyIndex = currentValue.indexOf(this.indexSeparator);\r\n if (propertyIndex > 0) {\r\n const property = currentValue.substring(0, propertyIndex);\r\n const arrayIndex = parseInt(currentValue.substring(propertyIndex + 1));\r\n const array = (previousValue as unknown as Record)[property];\r\n return array?.[arrayIndex];\r\n }\r\n return (previousValue as unknown as Record)[currentValue];\r\n }, node) as T;\r\n }\r\n\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2024 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\n// eslint-disable-next-line no-restricted-imports\r\nexport * from 'vscode-jsonrpc/lib/common/events.js';\r\n", "/******************************************************************************\r\n * Copyright 2022 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport { Emitter } from '../utils/event.js';\r\nimport type {\r\n ConfigurationItem,\r\n DidChangeConfigurationParams,\r\n DidChangeConfigurationRegistrationOptions,\r\n Disposable,\r\n Event,\r\n InitializeParams,\r\n InitializedParams\r\n} from 'vscode-languageserver-protocol';\r\nimport type { ServiceRegistry } from '../service-registry.js';\r\nimport type { LangiumSharedCoreServices } from '../services.js';\r\nimport { Deferred } from '../utils/promise-utils.js';\r\n\r\n/* eslint-disable @typescript-eslint/no-explicit-any */\r\n\r\nexport interface ConfigurationProvider {\r\n\r\n /**\r\n * A promise that resolves when the configuration provider is ready to be used.\r\n */\r\n readonly ready: Promise;\r\n\r\n /**\r\n * When used in a language server context, this method is called when the server receives\r\n * the `initialize` request.\r\n */\r\n initialize(params: InitializeParams): void;\r\n\r\n /**\r\n * When used in a language server context, this method is called when the server receives\r\n * the `initialized` notification.\r\n */\r\n initialized(params: ConfigurationInitializedParams): Promise;\r\n\r\n /**\r\n * Returns a configuration value stored for the given language.\r\n *\r\n * @param language The language id\r\n * @param configuration Configuration name\r\n */\r\n getConfiguration(language: string, configuration: string): Promise;\r\n\r\n /**\r\n * Updates the cached configurations using the `change` notification parameters.\r\n *\r\n * @param change The parameters of a change configuration notification.\r\n * `settings` property of the change object could be expressed as `Record>`\r\n */\r\n updateConfiguration(change: DidChangeConfigurationParams): void;\r\n\r\n /**\r\n * Get notified after a configuration section has been updated.\r\n */\r\n onConfigurationSectionUpdate(callback: ConfigurationSectionUpdateListener): Disposable\r\n}\r\n\r\nexport interface ConfigurationInitializedParams extends InitializedParams {\r\n register?: (params: DidChangeConfigurationRegistrationOptions) => void,\r\n fetchConfiguration?: (configuration: ConfigurationItem[]) => Promise\r\n}\r\n\r\nexport interface ConfigurationSectionUpdate {\r\n /**\r\n * The name of the configuration section that has been updated.\r\n */\r\n section: string;\r\n\r\n /**\r\n * The updated configuration section.\r\n */\r\n configuration: any;\r\n}\r\n\r\nexport type ConfigurationSectionUpdateListener = (update: ConfigurationSectionUpdate) => void;\r\n\r\n/**\r\n * Base configuration provider for building up other configuration providers\r\n */\r\nexport class DefaultConfigurationProvider implements ConfigurationProvider {\r\n\r\n protected readonly serviceRegistry: ServiceRegistry;\r\n protected readonly _ready = new Deferred();\r\n protected settings: Record> = {};\r\n protected workspaceConfig = false;\r\n protected onConfigurationSectionUpdateEmitter = new Emitter();\r\n\r\n constructor(services: LangiumSharedCoreServices) {\r\n this.serviceRegistry = services.ServiceRegistry;\r\n }\r\n\r\n get ready(): Promise {\r\n return this._ready.promise;\r\n }\r\n\r\n initialize(params: InitializeParams): void {\r\n this.workspaceConfig = params.capabilities.workspace?.configuration ?? false;\r\n }\r\n\r\n async initialized(params: ConfigurationInitializedParams): Promise {\r\n if (this.workspaceConfig) {\r\n if (params.register) {\r\n // params.register(...) is a function to be provided by the calling language server for the sake of\r\n // decoupling this implementation from the concrete LSP implementations, specifically the LSP Connection\r\n\r\n const languages = this.serviceRegistry.all;\r\n params.register({\r\n // Listen to configuration changes for all languages\r\n section: languages.map(lang => this.toSectionName(lang.LanguageMetaData.languageId))\r\n });\r\n }\r\n\r\n if (params.fetchConfiguration) {\r\n // params.fetchConfiguration(...) is a function to be provided by the calling language server for the sake of\r\n // decoupling this implementation from the concrete LSP implementations, specifically the LSP Connection\r\n const configToUpdate = this.serviceRegistry.all.map(lang => {\r\n // Fetch the configuration changes for all languages\r\n section: this.toSectionName(lang.LanguageMetaData.languageId)\r\n });\r\n\r\n // get workspace configurations (default scope URI)\r\n const configs = await params.fetchConfiguration(configToUpdate);\r\n configToUpdate.forEach((conf, idx) => {\r\n this.updateSectionConfiguration(conf.section!, configs[idx]);\r\n });\r\n }\r\n }\r\n this._ready.resolve();\r\n }\r\n\r\n /**\r\n * Updates the cached configurations using the `change` notification parameters.\r\n *\r\n * @param change The parameters of a change configuration notification.\r\n * `settings` property of the change object could be expressed as `Record>`\r\n */\r\n updateConfiguration(change: DidChangeConfigurationParams): void {\r\n if (!change.settings) {\r\n return;\r\n }\r\n Object.keys(change.settings).forEach(section => {\r\n const configuration = change.settings[section];\r\n this.updateSectionConfiguration(section, configuration);\r\n this.onConfigurationSectionUpdateEmitter.fire({ section, configuration });\r\n });\r\n }\r\n\r\n protected updateSectionConfiguration(section: string, configuration: any): void {\r\n this.settings[section] = configuration;\r\n }\r\n\r\n /**\r\n * Returns a configuration value stored for the given language.\r\n *\r\n * @param language The language id\r\n * @param configuration Configuration name\r\n */\r\n async getConfiguration(language: string, configuration: string): Promise {\r\n await this.ready;\r\n\r\n const sectionName = this.toSectionName(language);\r\n if (this.settings[sectionName]) {\r\n return this.settings[sectionName][configuration];\r\n }\r\n }\r\n\r\n protected toSectionName(languageId: string): string {\r\n return `${languageId}`;\r\n }\r\n\r\n get onConfigurationSectionUpdate(): Event {\r\n return this.onConfigurationSectionUpdateEmitter.event;\r\n }\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nexport interface Disposable {\r\n /**\r\n * Dispose this object.\r\n */\r\n dispose(): void;\r\n}\r\n\r\nexport interface AsyncDisposable {\r\n /**\r\n * Dispose this object.\r\n */\r\n dispose(): Promise;\r\n}\r\n\r\nexport namespace Disposable {\r\n export function create(callback: () => Promise): AsyncDisposable;\r\n export function create(callback: () => void): Disposable;\r\n export function create(callback: () => void | Promise): Disposable | AsyncDisposable {\r\n return {\r\n dispose: async () => await callback()\r\n };\r\n }\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport { CancellationToken } from '../utils/cancellation.js';\r\nimport { Disposable } from '../utils/disposable.js';\r\nimport type { ServiceRegistry } from '../service-registry.js';\r\nimport type { LangiumSharedCoreServices } from '../services.js';\r\nimport type { AstNode } from '../syntax-tree.js';\r\nimport type { MaybePromise } from '../utils/promise-utils.js';\r\nimport type { Deferred } from '../utils/promise-utils.js';\r\nimport type { ValidationOptions } from '../validation/document-validator.js';\r\nimport type { IndexManager } from '../workspace/index-manager.js';\r\nimport type { LangiumDocument, LangiumDocuments, LangiumDocumentFactory, TextDocumentProvider } from './documents.js';\r\nimport { MultiMap } from '../utils/collections.js';\r\nimport { OperationCancelled, interruptAndCheck, isOperationCancelled } from '../utils/promise-utils.js';\r\nimport { stream } from '../utils/stream.js';\r\nimport type { URI } from '../utils/uri-utils.js';\r\nimport { ValidationCategory } from '../validation/validation-registry.js';\r\nimport { DocumentState } from './documents.js';\r\n\r\nexport interface BuildOptions {\r\n /**\r\n * Control the validation phase with this option:\r\n * - `true` enables all validation checks and forces revalidating the documents\r\n * - `false` or `undefined` disables all validation checks\r\n * - An object runs only the necessary validation checks; the `categories` property restricts this to a specific subset\r\n */\r\n validation?: boolean | ValidationOptions\r\n}\r\n\r\nexport interface DocumentBuildState {\r\n /** Whether a document has completed its last build process. */\r\n completed: boolean\r\n /** The options used for the last build process. */\r\n options: BuildOptions\r\n /** Additional information about the last build result. */\r\n result?: {\r\n validationChecks?: ValidationCategory[]\r\n }\r\n}\r\n\r\n/**\r\n * Shared-service for building and updating `LangiumDocument`s.\r\n */\r\nexport interface DocumentBuilder {\r\n\r\n /** The options used for rebuilding documents after an update. */\r\n updateBuildOptions: BuildOptions;\r\n\r\n /**\r\n * Execute all necessary build steps for the given documents.\r\n *\r\n * @param documents Set of documents to be built.\r\n * @param options Options for the document builder.\r\n * @param cancelToken Indicates when to cancel the current operation.\r\n * @throws `OperationCanceled` if a user action occurs during execution\r\n */\r\n build(documents: Array>, options?: BuildOptions, cancelToken?: CancellationToken): Promise;\r\n\r\n /**\r\n * This method is called when a document change is detected. It updates the state of all\r\n * affected documents, including those with references to the changed ones, so they are rebuilt.\r\n *\r\n * @param changed URIs of changed or created documents\r\n * @param deleted URIs of deleted documents\r\n * @param cancelToken allows to cancel the current operation\r\n * @throws `OperationCancelled` if cancellation is detected during execution\r\n */\r\n update(changed: URI[], deleted: URI[], cancelToken?: CancellationToken): Promise;\r\n\r\n /**\r\n * Notify the given callback when a document update was triggered, but before any document\r\n * is rebuilt. Listeners to this event should not perform any long-running task.\r\n */\r\n onUpdate(callback: DocumentUpdateListener): Disposable;\r\n\r\n /**\r\n * Notify the given callback when a set of documents has been built reaching the specified target state.\r\n */\r\n onBuildPhase(targetState: DocumentState, callback: DocumentBuildListener): Disposable;\r\n\r\n /**\r\n * Notify the specified callback when a document has been built reaching the specified target state.\r\n * Unlike {@link onBuildPhase} the listener is called for every single document.\r\n *\r\n * There are two main advantages compared to {@link onBuildPhase}:\r\n * 1. If the build is cancelled, {@link onDocumentPhase} will still fire for documents that have reached a specific state.\r\n * Meanwhile, {@link onBuildPhase} won't fire for that state.\r\n * 2. The {@link DocumentBuilder} ensures that all {@link DocumentPhaseListener} instances are called for a built document.\r\n * Even if the build is cancelled before those listeners were called.\r\n */\r\n onDocumentPhase(targetState: DocumentState, callback: DocumentPhaseListener): Disposable;\r\n\r\n /**\r\n * Wait until the workspace has reached the specified state for all documents.\r\n *\r\n * @param state The desired state. The promise won't resolve until all documents have reached this state\r\n * @param cancelToken Optionally allows to cancel the wait operation, disposing any listeners in the process\r\n * @throws `OperationCancelled` if cancellation has been requested before the state has been reached\r\n */\r\n waitUntil(state: DocumentState, cancelToken?: CancellationToken): Promise;\r\n\r\n /**\r\n * Wait until the document specified by the {@link uri} has reached the specified state.\r\n *\r\n * @param state The desired state. The promise won't resolve until the document has reached this state.\r\n * @param uri The specified URI that points to the document. If the URI does not exist, the promise will resolve once the workspace has reached the specified state.\r\n * @param cancelToken Optionally allows to cancel the wait operation, disposing any listeners in the process.\r\n * @return The URI of the document that has reached the desired state, or `undefined` if the document does not exist.\r\n * @throws `OperationCancelled` if cancellation has been requested before the state has been reached\r\n */\r\n waitUntil(state: DocumentState, uri?: URI, cancelToken?: CancellationToken): Promise;\r\n}\r\n\r\nexport type DocumentUpdateListener = (changed: URI[], deleted: URI[]) => void | Promise\r\nexport type DocumentBuildListener = (built: LangiumDocument[], cancelToken: CancellationToken) => void | Promise\r\nexport type DocumentPhaseListener = (built: LangiumDocument, cancelToken: CancellationToken) => void | Promise\r\nexport class DefaultDocumentBuilder implements DocumentBuilder {\r\n\r\n updateBuildOptions: BuildOptions = {\r\n // Default: run only the built-in validation checks and those in the _fast_ category (includes those without category)\r\n validation: {\r\n categories: ['built-in', 'fast']\r\n }\r\n };\r\n\r\n protected readonly langiumDocuments: LangiumDocuments;\r\n protected readonly langiumDocumentFactory: LangiumDocumentFactory;\r\n protected readonly textDocuments: TextDocumentProvider | undefined;\r\n protected readonly indexManager: IndexManager;\r\n protected readonly serviceRegistry: ServiceRegistry;\r\n protected readonly updateListeners: DocumentUpdateListener[] = [];\r\n protected readonly buildPhaseListeners = new MultiMap();\r\n protected readonly documentPhaseListeners = new MultiMap();\r\n protected readonly buildState = new Map();\r\n protected readonly documentBuildWaiters = new Map>();\r\n protected currentState = DocumentState.Changed;\r\n\r\n constructor(services: LangiumSharedCoreServices) {\r\n this.langiumDocuments = services.workspace.LangiumDocuments;\r\n this.langiumDocumentFactory = services.workspace.LangiumDocumentFactory;\r\n this.textDocuments = services.workspace.TextDocuments;\r\n this.indexManager = services.workspace.IndexManager;\r\n this.serviceRegistry = services.ServiceRegistry;\r\n }\r\n\r\n async build(documents: Array>, options: BuildOptions = {}, cancelToken = CancellationToken.None): Promise {\r\n for (const document of documents) {\r\n const key = document.uri.toString();\r\n if (document.state === DocumentState.Validated) {\r\n if (typeof options.validation === 'boolean' && options.validation) {\r\n // Force re-running all validation checks\r\n document.state = DocumentState.IndexedReferences;\r\n document.diagnostics = undefined;\r\n this.buildState.delete(key);\r\n } else if (typeof options.validation === 'object') {\r\n const buildState = this.buildState.get(key);\r\n const previousCategories = buildState?.result?.validationChecks;\r\n if (previousCategories) {\r\n // Validation with explicit options was requested for a document that has already been partly validated.\r\n // In this case, we need to merge the previous validation categories with the new ones.\r\n const newCategories = options.validation.categories ?? ValidationCategory.all as ValidationCategory[];\r\n const categories = newCategories.filter(c => !previousCategories.includes(c));\r\n if (categories.length > 0) {\r\n this.buildState.set(key, {\r\n completed: false,\r\n options: {\r\n validation: {\r\n ...options.validation,\r\n categories\r\n }\r\n },\r\n result: buildState.result\r\n });\r\n document.state = DocumentState.IndexedReferences;\r\n }\r\n }\r\n }\r\n } else {\r\n // Default: forget any previous build options\r\n this.buildState.delete(key);\r\n }\r\n }\r\n this.currentState = DocumentState.Changed;\r\n await this.emitUpdate(documents.map(e => e.uri), []);\r\n await this.buildDocuments(documents, options, cancelToken);\r\n }\r\n\r\n async update(changed: URI[], deleted: URI[], cancelToken = CancellationToken.None): Promise {\r\n this.currentState = DocumentState.Changed;\r\n // Remove all metadata of documents that are reported as deleted\r\n for (const deletedUri of deleted) {\r\n this.langiumDocuments.deleteDocument(deletedUri);\r\n this.buildState.delete(deletedUri.toString());\r\n this.indexManager.remove(deletedUri);\r\n }\r\n // Set the state of all changed documents to `Changed` so they are completely rebuilt\r\n for (const changedUri of changed) {\r\n const invalidated = this.langiumDocuments.invalidateDocument(changedUri);\r\n if (!invalidated) {\r\n // We create an unparsed, invalid document.\r\n // This will be parsed as soon as we reach the first document builder phase.\r\n // This allows to cancel the parsing process later in case we need it.\r\n const newDocument = this.langiumDocumentFactory.fromModel({ $type: 'INVALID' }, changedUri);\r\n newDocument.state = DocumentState.Changed;\r\n this.langiumDocuments.addDocument(newDocument);\r\n }\r\n this.buildState.delete(changedUri.toString());\r\n }\r\n // Set the state of all documents that should be relinked to `ComputedScopes` (if not already lower)\r\n const allChangedUris = stream(changed).concat(deleted).map(uri => uri.toString()).toSet();\r\n this.langiumDocuments.all\r\n .filter(doc => !allChangedUris.has(doc.uri.toString()) && this.shouldRelink(doc, allChangedUris))\r\n .forEach(doc => {\r\n const linker = this.serviceRegistry.getServices(doc.uri).references.Linker;\r\n linker.unlink(doc);\r\n doc.state = Math.min(doc.state, DocumentState.ComputedScopes);\r\n doc.diagnostics = undefined;\r\n });\r\n // Notify listeners of the update\r\n await this.emitUpdate(changed, deleted);\r\n // Only allow interrupting the execution after all state changes are done\r\n await interruptAndCheck(cancelToken);\r\n\r\n // Collect and sort all documents that we should rebuild\r\n const rebuildDocuments = this.sortDocuments(\r\n this.langiumDocuments.all\r\n .filter(doc =>\r\n // This includes those that were reported as changed and those that we selected for relinking\r\n doc.state < DocumentState.Linked\r\n // This includes those for which a previous build has been cancelled\r\n || !this.buildState.get(doc.uri.toString())?.completed\r\n )\r\n .toArray()\r\n );\r\n await this.buildDocuments(rebuildDocuments, this.updateBuildOptions, cancelToken);\r\n }\r\n\r\n protected async emitUpdate(changed: URI[], deleted: URI[]): Promise {\r\n await Promise.all(this.updateListeners.map(listener => listener(changed, deleted)));\r\n }\r\n\r\n /**\r\n * Sort the given documents by priority. By default, documents with an open text document are prioritized.\r\n * This is useful to ensure that visible documents show their diagnostics before all other documents.\r\n *\r\n * This improves the responsiveness in large workspaces as users usually don't care about diagnostics\r\n * in files that are currently not opened in the editor.\r\n */\r\n protected sortDocuments(documents: LangiumDocument[]): LangiumDocument[] {\r\n let left = 0;\r\n let right = documents.length - 1;\r\n\r\n while (left < right) {\r\n while (left < documents.length && this.hasTextDocument(documents[left])) {\r\n left++;\r\n }\r\n\r\n while (right >= 0 && !this.hasTextDocument(documents[right])) {\r\n right--;\r\n }\r\n\r\n if (left < right) {\r\n [documents[left], documents[right]] = [documents[right], documents[left]];\r\n }\r\n }\r\n\r\n return documents;\r\n }\r\n\r\n private hasTextDocument(doc: LangiumDocument): boolean {\r\n return Boolean(this.textDocuments?.get(doc.uri));\r\n }\r\n\r\n /**\r\n * Check whether the given document should be relinked after changes were found in the given URIs.\r\n */\r\n protected shouldRelink(document: LangiumDocument, changedUris: Set): boolean {\r\n // Relink documents with linking errors -- maybe those references can be resolved now\r\n if (document.references.some(ref => ref.error !== undefined)) {\r\n return true;\r\n }\r\n // Check whether the document is affected by any of the changed URIs\r\n return this.indexManager.isAffected(document, changedUris);\r\n }\r\n\r\n onUpdate(callback: DocumentUpdateListener): Disposable {\r\n this.updateListeners.push(callback);\r\n return Disposable.create(() => {\r\n const index = this.updateListeners.indexOf(callback);\r\n if (index >= 0) {\r\n this.updateListeners.splice(index, 1);\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Build the given documents by stepping through all build phases. If a document's state indicates\r\n * that a certain build phase is already done, the phase is skipped for that document.\r\n *\r\n * @param documents The documents to build.\r\n * @param options the {@link BuildOptions} to use.\r\n * @param cancelToken A cancellation token that can be used to cancel the build.\r\n * @returns A promise that resolves when the build is done.\r\n */\r\n protected async buildDocuments(documents: LangiumDocument[], options: BuildOptions, cancelToken: CancellationToken): Promise {\r\n this.prepareBuild(documents, options);\r\n // 0. Parse content\r\n await this.runCancelable(documents, DocumentState.Parsed, cancelToken, doc =>\r\n this.langiumDocumentFactory.update(doc, cancelToken)\r\n );\r\n // 1. Index content\r\n await this.runCancelable(documents, DocumentState.IndexedContent, cancelToken, doc =>\r\n this.indexManager.updateContent(doc, cancelToken)\r\n );\r\n // 2. Compute scopes\r\n await this.runCancelable(documents, DocumentState.ComputedScopes, cancelToken, async doc => {\r\n const scopeComputation = this.serviceRegistry.getServices(doc.uri).references.ScopeComputation;\r\n doc.precomputedScopes = await scopeComputation.computeLocalScopes(doc, cancelToken);\r\n });\r\n // 3. Linking\r\n await this.runCancelable(documents, DocumentState.Linked, cancelToken, doc => {\r\n const linker = this.serviceRegistry.getServices(doc.uri).references.Linker;\r\n return linker.link(doc, cancelToken);\r\n });\r\n // 4. Index references\r\n await this.runCancelable(documents, DocumentState.IndexedReferences, cancelToken, doc =>\r\n this.indexManager.updateReferences(doc, cancelToken)\r\n );\r\n // 5. Validation\r\n const toBeValidated = documents.filter(doc => this.shouldValidate(doc));\r\n await this.runCancelable(toBeValidated, DocumentState.Validated, cancelToken, doc =>\r\n this.validate(doc, cancelToken)\r\n );\r\n\r\n // If we've made it to this point without being cancelled, we can mark the build state as completed.\r\n for (const doc of documents) {\r\n const state = this.buildState.get(doc.uri.toString());\r\n if (state) {\r\n state.completed = true;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Runs prior to beginning the build process to update the {@link DocumentBuildState} for each document\r\n *\r\n * @param documents collection of documents to be built\r\n * @param options the {@link BuildOptions} to use\r\n */\r\n protected prepareBuild(documents: LangiumDocument[], options: BuildOptions): void {\r\n for (const doc of documents) {\r\n const key = doc.uri.toString();\r\n const state = this.buildState.get(key);\r\n // If the document has no previous build state, we set it. If it has one, but it's already marked\r\n // as completed, we overwrite it. If the previous build was not completed, we keep its state\r\n // and continue where it was cancelled.\r\n if (!state || state.completed) {\r\n this.buildState.set(key, {\r\n completed: false,\r\n options,\r\n result: state?.result\r\n });\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Runs a cancelable operation on a set of documents to bring them to a specified {@link DocumentState}.\r\n *\r\n * @param documents The array of documents to process.\r\n * @param targetState The target {@link DocumentState} to bring the documents to.\r\n * @param cancelToken A token that can be used to cancel the operation.\r\n * @param callback A function to be called for each document.\r\n * @returns A promise that resolves when all documents have been processed or the operation is canceled.\r\n * @throws Will throw `OperationCancelled` if the operation is canceled via a `CancellationToken`.\r\n */\r\n protected async runCancelable(documents: LangiumDocument[], targetState: DocumentState, cancelToken: CancellationToken,\r\n callback: (document: LangiumDocument) => MaybePromise): Promise {\r\n const filtered = documents.filter(doc => doc.state < targetState);\r\n for (const document of filtered) {\r\n await interruptAndCheck(cancelToken);\r\n await callback(document);\r\n document.state = targetState;\r\n await this.notifyDocumentPhase(document, targetState, cancelToken);\r\n }\r\n\r\n // Do not use `filtered` here, as that will miss documents that have previously reached the current target state\r\n // For example, this happens in case the cancellation triggers between the processing of two documents\r\n // Or files that were picked up during the workspace initialization\r\n const targetStateDocs = documents.filter(doc => doc.state === targetState);\r\n await this.notifyBuildPhase(targetStateDocs, targetState, cancelToken);\r\n this.currentState = targetState;\r\n }\r\n\r\n onBuildPhase(targetState: DocumentState, callback: DocumentBuildListener): Disposable {\r\n this.buildPhaseListeners.add(targetState, callback);\r\n return Disposable.create(() => {\r\n this.buildPhaseListeners.delete(targetState, callback);\r\n });\r\n }\r\n\r\n onDocumentPhase(targetState: DocumentState, callback: DocumentPhaseListener): Disposable {\r\n this.documentPhaseListeners.add(targetState, callback);\r\n return Disposable.create(() => {\r\n this.documentPhaseListeners.delete(targetState, callback);\r\n });\r\n }\r\n\r\n waitUntil(state: DocumentState, cancelToken?: CancellationToken): Promise;\r\n waitUntil(state: DocumentState, uri?: URI, cancelToken?: CancellationToken): Promise;\r\n waitUntil(state: DocumentState, uriOrToken?: URI | CancellationToken, cancelToken?: CancellationToken): Promise {\r\n let uri: URI | undefined = undefined;\r\n if (uriOrToken && 'path' in uriOrToken) {\r\n uri = uriOrToken;\r\n } else {\r\n cancelToken = uriOrToken;\r\n }\r\n cancelToken ??= CancellationToken.None;\r\n if (uri) {\r\n const document = this.langiumDocuments.getDocument(uri);\r\n if (document && document.state > state) {\r\n return Promise.resolve(uri);\r\n }\r\n }\r\n if (this.currentState >= state) {\r\n return Promise.resolve(undefined);\r\n } else if (cancelToken.isCancellationRequested) {\r\n return Promise.reject(OperationCancelled);\r\n }\r\n return new Promise((resolve, reject) => {\r\n const buildDisposable = this.onBuildPhase(state, () => {\r\n buildDisposable.dispose();\r\n cancelDisposable.dispose();\r\n if (uri) {\r\n const document = this.langiumDocuments.getDocument(uri);\r\n resolve(document?.uri);\r\n } else {\r\n resolve(undefined);\r\n }\r\n });\r\n const cancelDisposable = cancelToken!.onCancellationRequested(() => {\r\n buildDisposable.dispose();\r\n cancelDisposable.dispose();\r\n reject(OperationCancelled);\r\n });\r\n });\r\n }\r\n\r\n protected async notifyDocumentPhase(document: LangiumDocument, state: DocumentState, cancelToken: CancellationToken): Promise {\r\n const listeners = this.documentPhaseListeners.get(state);\r\n const listenersCopy = listeners.slice();\r\n for (const listener of listenersCopy) {\r\n try {\r\n await listener(document, cancelToken);\r\n } catch (err) {\r\n // Ignore cancellation errors\r\n // We want to finish the listeners before throwing\r\n if (!isOperationCancelled(err)) {\r\n throw err;\r\n }\r\n }\r\n }\r\n }\r\n\r\n protected async notifyBuildPhase(documents: LangiumDocument[], state: DocumentState, cancelToken: CancellationToken): Promise {\r\n if (documents.length === 0) {\r\n // Don't notify when no document has been processed\r\n return;\r\n }\r\n const listeners = this.buildPhaseListeners.get(state);\r\n const listenersCopy = listeners.slice();\r\n for (const listener of listenersCopy) {\r\n await interruptAndCheck(cancelToken);\r\n await listener(documents, cancelToken);\r\n }\r\n }\r\n\r\n /**\r\n * Determine whether the given document should be validated during a build. The default\r\n * implementation checks the `validation` property of the build options. If it's set to `true`\r\n * or a `ValidationOptions` object, the document is included in the validation phase.\r\n */\r\n protected shouldValidate(document: LangiumDocument): boolean {\r\n return Boolean(this.getBuildOptions(document).validation);\r\n }\r\n\r\n /**\r\n * Run validation checks on the given document and store the resulting diagnostics in the document.\r\n * If the document already contains diagnostics, the new ones are added to the list.\r\n */\r\n protected async validate(document: LangiumDocument, cancelToken: CancellationToken): Promise {\r\n const validator = this.serviceRegistry.getServices(document.uri).validation.DocumentValidator;\r\n const validationSetting = this.getBuildOptions(document).validation;\r\n const options = typeof validationSetting === 'object' ? validationSetting : undefined;\r\n const diagnostics = await validator.validateDocument(document, options, cancelToken);\r\n if (document.diagnostics) {\r\n document.diagnostics.push(...diagnostics);\r\n } else {\r\n document.diagnostics = diagnostics;\r\n }\r\n\r\n // Store information about the executed validation in the build state\r\n const state = this.buildState.get(document.uri.toString());\r\n if (state) {\r\n state.result ??= {};\r\n const newCategories = options?.categories ?? ValidationCategory.all;\r\n if (state.result.validationChecks) {\r\n state.result.validationChecks.push(...newCategories);\r\n } else {\r\n state.result.validationChecks = [...newCategories];\r\n }\r\n }\r\n }\r\n\r\n protected getBuildOptions(document: LangiumDocument): BuildOptions {\r\n return this.buildState.get(document.uri.toString())?.options ?? {};\r\n }\r\n\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { ServiceRegistry } from '../service-registry.js';\r\nimport type { LangiumSharedCoreServices } from '../services.js';\r\nimport type { AstNode, AstNodeDescription, AstReflection } from '../syntax-tree.js';\r\nimport { getDocument } from '../utils/ast-utils.js';\r\nimport { ContextCache } from '../utils/caching.js';\r\nimport { CancellationToken } from '../utils/cancellation.js';\r\nimport type { Stream } from '../utils/stream.js';\r\nimport { stream } from '../utils/stream.js';\r\nimport type { URI } from '../utils/uri-utils.js';\r\nimport { UriUtils } from '../utils/uri-utils.js';\r\nimport type { ReferenceDescription } from './ast-descriptions.js';\r\nimport type { LangiumDocument, LangiumDocuments } from './documents.js';\r\n\r\n/**\r\n * The index manager is responsible for keeping metadata about symbols and cross-references\r\n * in the workspace. It is used to look up symbols in the global scope, mostly during linking\r\n * and completion. This service is shared between all languages of a language server.\r\n */\r\nexport interface IndexManager {\r\n\r\n /**\r\n * Removes the specified document URI from the index.\r\n * Necessary when documents are deleted and not referenceable anymore.\r\n *\r\n * @param uri The URI of the document for which index data shall be removed\r\n */\r\n remove(uri: URI): void;\r\n\r\n /**\r\n * Updates the information about the exportable content of a document inside the index.\r\n *\r\n * @param document Document to be updated\r\n * @param cancelToken Indicates when to cancel the current operation.\r\n * @throws `OperationCanceled` if a user action occurs during execution\r\n */\r\n updateContent(document: LangiumDocument, cancelToken?: CancellationToken): Promise;\r\n\r\n /**\r\n * Updates the information about the cross-references of a document inside the index.\r\n *\r\n * @param document Document to be updated\r\n * @param cancelToken Indicates when to cancel the current operation.\r\n * @throws `OperationCanceled` if a user action occurs during execution\r\n */\r\n updateReferences(document: LangiumDocument, cancelToken?: CancellationToken): Promise;\r\n\r\n /**\r\n * Determine whether the given document could be affected by changes of the documents\r\n * identified by the given URIs (second parameter). The document is typically regarded as\r\n * affected if it contains a reference to any of the changed files.\r\n *\r\n * @param document Document to check whether it's affected\r\n * @param changedUris URIs of the changed documents\r\n */\r\n isAffected(document: LangiumDocument, changedUris: Set): boolean;\r\n\r\n /**\r\n * Compute a list of all exported elements, optionally filtered using a type identifier and document URIs.\r\n *\r\n * @param nodeType The type to filter with, or `undefined` to return descriptions of all types.\r\n * @param uris If specified, only returns elements from the given URIs.\r\n * @returns a `Stream` containing all globally visible nodes (of a given type).\r\n */\r\n allElements(nodeType?: string, uris?: Set): Stream;\r\n\r\n /**\r\n * Returns all known references that are pointing to the given `targetNode`.\r\n *\r\n * @param targetNode the `AstNode` to look up references for\r\n * @param astNodePath the path that points to the `targetNode` inside the document. See also `AstNodeLocator`\r\n *\r\n * @returns a `Stream` of references that are targeting the `targetNode`\r\n */\r\n findAllReferences(targetNode: AstNode, astNodePath: string): Stream;\r\n\r\n}\r\n\r\nexport class DefaultIndexManager implements IndexManager {\r\n\r\n protected readonly serviceRegistry: ServiceRegistry;\r\n protected readonly documents: LangiumDocuments;\r\n protected readonly astReflection: AstReflection;\r\n\r\n /**\r\n * The symbol index stores all `AstNodeDescription` items exported by a document.\r\n * The key used in this map is the string representation of the specific document URI.\r\n */\r\n protected readonly symbolIndex = new Map();\r\n /**\r\n * This is a cache for the `allElements()` method.\r\n * It caches the descriptions from `symbolIndex` grouped by types.\r\n */\r\n protected readonly symbolByTypeIndex = new ContextCache();\r\n /**\r\n * This index keeps track of all `ReferenceDescription` items exported by a document.\r\n * This is used to compute which elements are affected by a document change\r\n * and for finding references to an AST node.\r\n */\r\n protected readonly referenceIndex = new Map();\r\n\r\n constructor(services: LangiumSharedCoreServices) {\r\n this.documents = services.workspace.LangiumDocuments;\r\n this.serviceRegistry = services.ServiceRegistry;\r\n this.astReflection = services.AstReflection;\r\n }\r\n\r\n findAllReferences(targetNode: AstNode, astNodePath: string): Stream {\r\n const targetDocUri = getDocument(targetNode).uri;\r\n const result: ReferenceDescription[] = [];\r\n this.referenceIndex.forEach(docRefs => {\r\n docRefs.forEach(refDescr => {\r\n if (UriUtils.equals(refDescr.targetUri, targetDocUri) && refDescr.targetPath === astNodePath) {\r\n result.push(refDescr);\r\n }\r\n });\r\n });\r\n return stream(result);\r\n }\r\n\r\n allElements(nodeType?: string, uris?: Set): Stream {\r\n let documentUris = stream(this.symbolIndex.keys());\r\n if (uris) {\r\n documentUris = documentUris.filter(uri => !uris || uris.has(uri));\r\n }\r\n return documentUris\r\n .map(uri => this.getFileDescriptions(uri, nodeType))\r\n .flat();\r\n }\r\n\r\n protected getFileDescriptions(uri: string, nodeType?: string): AstNodeDescription[] {\r\n if (!nodeType) {\r\n return this.symbolIndex.get(uri) ?? [];\r\n }\r\n const descriptions = this.symbolByTypeIndex.get(uri, nodeType, () => {\r\n const allFileDescriptions = this.symbolIndex.get(uri) ?? [];\r\n return allFileDescriptions.filter(e => this.astReflection.isSubtype(e.type, nodeType));\r\n });\r\n return descriptions;\r\n }\r\n\r\n remove(uri: URI): void {\r\n const uriString = uri.toString();\r\n this.symbolIndex.delete(uriString);\r\n this.symbolByTypeIndex.clear(uriString);\r\n this.referenceIndex.delete(uriString);\r\n }\r\n\r\n async updateContent(document: LangiumDocument, cancelToken = CancellationToken.None): Promise {\r\n const services = this.serviceRegistry.getServices(document.uri);\r\n const exports = await services.references.ScopeComputation.computeExports(document, cancelToken);\r\n const uri = document.uri.toString();\r\n this.symbolIndex.set(uri, exports);\r\n this.symbolByTypeIndex.clear(uri);\r\n }\r\n\r\n async updateReferences(document: LangiumDocument, cancelToken = CancellationToken.None): Promise {\r\n const services = this.serviceRegistry.getServices(document.uri);\r\n const indexData = await services.workspace.ReferenceDescriptionProvider.createDescriptions(document, cancelToken);\r\n this.referenceIndex.set(document.uri.toString(), indexData);\r\n }\r\n\r\n isAffected(document: LangiumDocument, changedUris: Set): boolean {\r\n const references = this.referenceIndex.get(document.uri.toString());\r\n if (!references) {\r\n return false;\r\n }\r\n return references.some(ref => !ref.local && changedUris.has(ref.targetUri.toString()));\r\n }\r\n\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2022 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { InitializeParams, InitializedParams } from 'vscode-languageserver-protocol';\r\nimport type { WorkspaceFolder } from 'vscode-languageserver-types';\r\nimport type { ServiceRegistry } from '../service-registry.js';\r\nimport type { LangiumSharedCoreServices } from '../services.js';\r\nimport { CancellationToken } from '../utils/cancellation.js';\r\nimport { Deferred, interruptAndCheck } from '../utils/promise-utils.js';\r\nimport { URI, UriUtils } from '../utils/uri-utils.js';\r\nimport type { BuildOptions, DocumentBuilder } from './document-builder.js';\r\nimport type { LangiumDocument, LangiumDocuments } from './documents.js';\r\nimport type { FileSystemNode, FileSystemProvider } from './file-system-provider.js';\r\nimport type { WorkspaceLock } from './workspace-lock.js';\r\n\r\n// export type WorkspaceFolder from 'vscode-languageserver-types' for convenience,\r\n// is supposed to avoid confusion as 'WorkspaceFolder' might accidentally be imported via 'vscode-languageclient'\r\nexport type { WorkspaceFolder };\r\n\r\n/**\r\n * The workspace manager is responsible for finding source files in the workspace.\r\n * This service is shared between all languages of a language server.\r\n */\r\nexport interface WorkspaceManager {\r\n\r\n /** The options used for the initial workspace build. */\r\n initialBuildOptions: BuildOptions | undefined;\r\n\r\n /**\r\n * A promise that resolves when the workspace manager is ready to be used.\r\n * Use this to ensure that the workspace manager has finished its initialization.\r\n */\r\n readonly ready: Promise;\r\n\r\n /**\r\n * The workspace folders of the current workspace.\r\n * Available only after the `ready` promise resolves.\r\n */\r\n get workspaceFolders(): readonly WorkspaceFolder[] | undefined;\r\n\r\n /**\r\n * When used in a language server context, this method is called when the server receives\r\n * the `initialize` request.\r\n */\r\n initialize(params: InitializeParams): void;\r\n\r\n /**\r\n * When used in a language server context, this method is called when the server receives\r\n * the `initialized` notification.\r\n */\r\n initialized(params: InitializedParams): Promise;\r\n\r\n /**\r\n * Does the initial indexing of workspace folders.\r\n * Collects information about exported and referenced AstNodes in\r\n * each language file and stores it locally.\r\n *\r\n * @param folders The set of workspace folders to be indexed.\r\n * @param cancelToken A cancellation token that can be used to cancel the operation.\r\n *\r\n * @throws OperationCancelled if a cancellation event has been detected\r\n */\r\n initializeWorkspace(folders: WorkspaceFolder[], cancelToken?: CancellationToken): Promise;\r\n\r\n}\r\n\r\nexport class DefaultWorkspaceManager implements WorkspaceManager {\r\n\r\n initialBuildOptions: BuildOptions = {};\r\n\r\n protected readonly serviceRegistry: ServiceRegistry;\r\n protected readonly langiumDocuments: LangiumDocuments;\r\n protected readonly documentBuilder: DocumentBuilder;\r\n protected readonly fileSystemProvider: FileSystemProvider;\r\n protected readonly mutex: WorkspaceLock;\r\n protected readonly _ready = new Deferred();\r\n protected folders?: WorkspaceFolder[];\r\n\r\n constructor(services: LangiumSharedCoreServices) {\r\n this.serviceRegistry = services.ServiceRegistry;\r\n this.langiumDocuments = services.workspace.LangiumDocuments;\r\n this.documentBuilder = services.workspace.DocumentBuilder;\r\n this.fileSystemProvider = services.workspace.FileSystemProvider;\r\n this.mutex = services.workspace.WorkspaceLock;\r\n }\r\n\r\n get ready(): Promise {\r\n return this._ready.promise;\r\n }\r\n\r\n get workspaceFolders(): readonly WorkspaceFolder[] | undefined {\r\n return this.folders;\r\n }\r\n\r\n initialize(params: InitializeParams): void {\r\n this.folders = params.workspaceFolders ?? undefined;\r\n }\r\n\r\n initialized(_params: InitializedParams): Promise {\r\n // Initialize the workspace even if there are no workspace folders\r\n // We still want to load additional documents (language library or similar) during initialization\r\n return this.mutex.write(token => this.initializeWorkspace(this.folders ?? [], token));\r\n }\r\n\r\n async initializeWorkspace(folders: WorkspaceFolder[], cancelToken = CancellationToken.None): Promise {\r\n const documents = await this.performStartup(folders);\r\n // Only after creating all documents do we check whether we need to cancel the initialization\r\n // The document builder will later pick up on all unprocessed documents\r\n await interruptAndCheck(cancelToken);\r\n await this.documentBuilder.build(documents, this.initialBuildOptions, cancelToken);\r\n }\r\n\r\n /**\r\n * Performs the uninterruptable startup sequence of the workspace manager.\r\n * This methods loads all documents in the workspace and other documents and returns them.\r\n */\r\n protected async performStartup(folders: WorkspaceFolder[]): Promise {\r\n const fileExtensions = this.serviceRegistry.all.flatMap(e => e.LanguageMetaData.fileExtensions);\r\n const documents: LangiumDocument[] = [];\r\n const collector = (document: LangiumDocument) => {\r\n documents.push(document);\r\n if (!this.langiumDocuments.hasDocument(document.uri)) {\r\n this.langiumDocuments.addDocument(document);\r\n }\r\n };\r\n // Even though we don't await the initialization of the workspace manager,\r\n // we can still assume that all library documents and file documents are loaded by the time we start building documents.\r\n // The mutex prevents anything from performing a workspace build until we check the cancellation token\r\n await this.loadAdditionalDocuments(folders, collector);\r\n await Promise.all(\r\n folders.map(wf => [wf, this.getRootFolder(wf)] as [WorkspaceFolder, URI])\r\n .map(async entry => this.traverseFolder(...entry, fileExtensions, collector))\r\n );\r\n this._ready.resolve();\r\n return documents;\r\n }\r\n\r\n /**\r\n * Load all additional documents that shall be visible in the context of the given workspace\r\n * folders and add them to the collector. This can be used to include built-in libraries of\r\n * your language, which can be either loaded from provided files or constructed in memory.\r\n */\r\n protected loadAdditionalDocuments(_folders: WorkspaceFolder[], _collector: (document: LangiumDocument) => void): Promise {\r\n return Promise.resolve();\r\n }\r\n\r\n /**\r\n * Determine the root folder of the source documents in the given workspace folder.\r\n * The default implementation returns the URI of the workspace folder, but you can override\r\n * this to return a subfolder like `src` instead.\r\n */\r\n protected getRootFolder(workspaceFolder: WorkspaceFolder): URI {\r\n return URI.parse(workspaceFolder.uri);\r\n }\r\n\r\n /**\r\n * Traverse the file system folder identified by the given URI and its subfolders. All\r\n * contained files that match the file extensions are added to the collector.\r\n */\r\n protected async traverseFolder(workspaceFolder: WorkspaceFolder, folderPath: URI, fileExtensions: string[], collector: (document: LangiumDocument) => void): Promise {\r\n const content = await this.fileSystemProvider.readDirectory(folderPath);\r\n await Promise.all(content.map(async entry => {\r\n if (this.includeEntry(workspaceFolder, entry, fileExtensions)) {\r\n if (entry.isDirectory) {\r\n await this.traverseFolder(workspaceFolder, entry.uri, fileExtensions, collector);\r\n } else if (entry.isFile) {\r\n const document = await this.langiumDocuments.getOrCreateDocument(entry.uri);\r\n collector(document);\r\n }\r\n }\r\n }));\r\n }\r\n\r\n /**\r\n * Determine whether the given folder entry shall be included while indexing the workspace.\r\n */\r\n protected includeEntry(_workspaceFolder: WorkspaceFolder, entry: FileSystemNode, fileExtensions: string[]): boolean {\r\n const name = UriUtils.basename(entry.uri);\r\n if (name.startsWith('.')) {\r\n return false;\r\n }\r\n if (entry.isDirectory) {\r\n return name !== 'node_modules' && name !== 'out';\r\n } else if (entry.isFile) {\r\n const extname = UriUtils.extname(entry.uri);\r\n return fileExtensions.includes(extname);\r\n }\r\n return false;\r\n }\r\n\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2022 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { ILexerErrorMessageProvider, ILexingError, IMultiModeLexerDefinition, IToken, TokenType, TokenTypeDictionary, TokenVocabulary } from 'chevrotain';\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport { Lexer as ChevrotainLexer, defaultLexerErrorProvider } from 'chevrotain';\r\nimport type { LexingReport, TokenBuilder } from './token-builder.js';\r\n\r\nexport class DefaultLexerErrorMessageProvider implements ILexerErrorMessageProvider {\r\n\r\n buildUnexpectedCharactersMessage(fullText: string, startOffset: number, length: number, line?: number, column?: number): string {\r\n return defaultLexerErrorProvider.buildUnexpectedCharactersMessage(fullText, startOffset, length, line, column);\r\n }\r\n\r\n buildUnableToPopLexerModeMessage(token: IToken): string {\r\n return defaultLexerErrorProvider.buildUnableToPopLexerModeMessage(token);\r\n }\r\n}\r\n\r\nexport interface LexerResult {\r\n /**\r\n * A list of all tokens that were lexed from the input.\r\n *\r\n * Note that Langium requires the optional properties\r\n * `startLine`, `startColumn`, `endOffset`, `endLine` and `endColumn` to be set on each token.\r\n */\r\n tokens: IToken[];\r\n /**\r\n * Contains hidden tokens, usually comments.\r\n */\r\n hidden: IToken[];\r\n errors: ILexingError[];\r\n report?: LexingReport;\r\n}\r\n\r\nexport type TokenizeMode = 'full' | 'partial';\r\n\r\nexport interface TokenizeOptions {\r\n mode?: TokenizeMode;\r\n}\r\n\r\nexport const DEFAULT_TOKENIZE_OPTIONS: TokenizeOptions = { mode: 'full' };\r\n\r\nexport interface Lexer {\r\n readonly definition: TokenTypeDictionary;\r\n tokenize(text: string, options?: TokenizeOptions): LexerResult;\r\n}\r\n\r\nexport class DefaultLexer implements Lexer {\r\n\r\n protected readonly tokenBuilder: TokenBuilder;\r\n protected readonly errorMessageProvider: ILexerErrorMessageProvider;\r\n protected tokenTypes: TokenTypeDictionary;\r\n protected chevrotainLexer: ChevrotainLexer;\r\n\r\n constructor(services: LangiumCoreServices) {\r\n this.errorMessageProvider = services.parser.LexerErrorMessageProvider;\r\n this.tokenBuilder = services.parser.TokenBuilder;\r\n const tokens = this.tokenBuilder.buildTokens(services.Grammar, {\r\n caseInsensitive: services.LanguageMetaData.caseInsensitive\r\n });\r\n this.tokenTypes = this.toTokenTypeDictionary(tokens);\r\n const lexerTokens = isTokenTypeDictionary(tokens) ? Object.values(tokens) : tokens;\r\n const production = services.LanguageMetaData.mode === 'production';\r\n this.chevrotainLexer = new ChevrotainLexer(lexerTokens, {\r\n positionTracking: 'full',\r\n skipValidations: production,\r\n errorMessageProvider: this.errorMessageProvider\r\n });\r\n }\r\n\r\n get definition(): TokenTypeDictionary {\r\n return this.tokenTypes;\r\n }\r\n\r\n tokenize(text: string, _options: TokenizeOptions = DEFAULT_TOKENIZE_OPTIONS): LexerResult {\r\n const chevrotainResult = this.chevrotainLexer.tokenize(text);\r\n return {\r\n tokens: chevrotainResult.tokens,\r\n errors: chevrotainResult.errors,\r\n hidden: chevrotainResult.groups.hidden ?? [],\r\n report: this.tokenBuilder.flushLexingReport?.(text)\r\n };\r\n }\r\n\r\n protected toTokenTypeDictionary(buildTokens: TokenVocabulary): TokenTypeDictionary {\r\n if (isTokenTypeDictionary(buildTokens)) return buildTokens;\r\n const tokens = isIMultiModeLexerDefinition(buildTokens) ? Object.values(buildTokens.modes).flat() : buildTokens;\r\n const res: TokenTypeDictionary = {};\r\n tokens.forEach(token => res[token.name] = token);\r\n return res;\r\n }\r\n}\r\n\r\n/**\r\n * Returns a check whether the given TokenVocabulary is TokenType array\r\n */\r\nexport function isTokenTypeArray(tokenVocabulary: TokenVocabulary): tokenVocabulary is TokenType[] {\r\n return Array.isArray(tokenVocabulary) && (tokenVocabulary.length === 0 || 'name' in tokenVocabulary[0]);\r\n}\r\n\r\n/**\r\n * Returns a check whether the given TokenVocabulary is IMultiModeLexerDefinition\r\n */\r\nexport function isIMultiModeLexerDefinition(tokenVocabulary: TokenVocabulary): tokenVocabulary is IMultiModeLexerDefinition {\r\n return tokenVocabulary && 'modes' in tokenVocabulary && 'defaultMode' in tokenVocabulary;\r\n}\r\n\r\n/**\r\n * Returns a check whether the given TokenVocabulary is TokenTypeDictionary\r\n */\r\nexport function isTokenTypeDictionary(tokenVocabulary: TokenVocabulary): tokenVocabulary is TokenTypeDictionary {\r\n return !isTokenTypeArray(tokenVocabulary) && !isIMultiModeLexerDefinition(tokenVocabulary);\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2023 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport { Position, Range } from 'vscode-languageserver-types';\r\nimport type { CstNode } from '../syntax-tree.js';\r\nimport { NEWLINE_REGEXP, escapeRegExp } from '../utils/regexp-utils.js';\r\nimport { URI } from '../utils/uri-utils.js';\r\n\r\nexport interface JSDocComment extends JSDocValue {\r\n readonly elements: JSDocElement[]\r\n getTag(name: string): JSDocTag | undefined\r\n getTags(name: string): JSDocTag[]\r\n}\r\n\r\nexport type JSDocElement = JSDocParagraph | JSDocTag;\r\n\r\nexport type JSDocInline = JSDocTag | JSDocLine;\r\n\r\nexport interface JSDocValue {\r\n /**\r\n * Represents the range that this JSDoc element occupies.\r\n * If the JSDoc was parsed from a `CstNode`, the range will represent the location in the source document.\r\n */\r\n readonly range: Range\r\n /**\r\n * Renders this JSDoc element to a plain text representation.\r\n */\r\n toString(): string\r\n /**\r\n * Renders this JSDoc element to a markdown representation.\r\n *\r\n * @param options Rendering options to customize the markdown result.\r\n */\r\n toMarkdown(options?: JSDocRenderOptions): string\r\n}\r\n\r\nexport interface JSDocParagraph extends JSDocValue {\r\n readonly inlines: JSDocInline[]\r\n}\r\n\r\nexport interface JSDocLine extends JSDocValue {\r\n readonly text: string\r\n}\r\n\r\nexport interface JSDocTag extends JSDocValue {\r\n readonly name: string\r\n readonly content: JSDocParagraph\r\n readonly inline: boolean\r\n}\r\n\r\nexport interface JSDocParseOptions {\r\n /**\r\n * The start symbol of your comment format. Defaults to `/**`.\r\n */\r\n readonly start?: RegExp | string\r\n /**\r\n * The symbol that start a line of your comment format. Defaults to `*`.\r\n */\r\n readonly line?: RegExp | string\r\n /**\r\n * The end symbol of your comment format. Defaults to `*\\/`.\r\n */\r\n readonly end?: RegExp | string\r\n}\r\n\r\nexport interface JSDocRenderOptions {\r\n /**\r\n * Determines the style for rendering tags. Defaults to `italic`.\r\n */\r\n tag?: 'plain' | 'italic' | 'bold' | 'bold-italic'\r\n /**\r\n * Determines the default for rendering `@link` tags. Defaults to `plain`.\r\n */\r\n link?: 'code' | 'plain'\r\n /**\r\n * Custom tag rendering function.\r\n * Return a markdown formatted tag or `undefined` to fall back to the default rendering.\r\n */\r\n renderTag?(tag: JSDocTag): string | undefined\r\n /**\r\n * Custom link rendering function. Accepts a link target and a display value for the link.\r\n * Return a markdown formatted link with the format `[$display]($link)` or `undefined` if the link is not a valid target.\r\n */\r\n renderLink?(link: string, display: string): string | undefined\r\n}\r\n\r\n/**\r\n * Parses a JSDoc from a `CstNode` containing a comment.\r\n *\r\n * @param node A `CstNode` from a parsed Langium document.\r\n * @param options Parsing options specialized to your language. See {@link JSDocParseOptions}.\r\n */\r\nexport function parseJSDoc(node: CstNode, options?: JSDocParseOptions): JSDocComment;\r\n/**\r\n * Parses a JSDoc from a string comment.\r\n *\r\n * @param content A string containing the source of the JSDoc comment.\r\n * @param start The start position the comment occupies in the source document.\r\n * @param options Parsing options specialized to your language. See {@link JSDocParseOptions}.\r\n */\r\nexport function parseJSDoc(content: string, start?: Position, options?: JSDocParseOptions): JSDocComment;\r\nexport function parseJSDoc(node: CstNode | string, start?: Position | JSDocParseOptions, options?: JSDocParseOptions): JSDocComment {\r\n let opts: JSDocParseOptions | undefined;\r\n let position: Position | undefined;\r\n if (typeof node === 'string') {\r\n position = start as Position | undefined;\r\n opts = options as JSDocParseOptions | undefined;\r\n } else {\r\n position = node.range.start;\r\n opts = start as JSDocParseOptions | undefined;\r\n }\r\n if (!position) {\r\n position = Position.create(0, 0);\r\n }\r\n\r\n const lines = getLines(node);\r\n const normalizedOptions = normalizeOptions(opts);\r\n\r\n const tokens = tokenize({\r\n lines,\r\n position,\r\n options: normalizedOptions\r\n });\r\n\r\n return parseJSDocComment({\r\n index: 0,\r\n tokens,\r\n position\r\n });\r\n}\r\n\r\nexport function isJSDoc(node: CstNode | string, options?: JSDocParseOptions): boolean {\r\n const normalizedOptions = normalizeOptions(options);\r\n const lines = getLines(node);\r\n if (lines.length === 0) {\r\n return false;\r\n }\r\n\r\n const first = lines[0];\r\n const last = lines[lines.length - 1];\r\n const firstRegex = normalizedOptions.start;\r\n const lastRegex = normalizedOptions.end;\r\n\r\n return Boolean(firstRegex?.exec(first)) && Boolean(lastRegex?.exec(last));\r\n}\r\n\r\nfunction getLines(node: CstNode | string): string[] {\r\n let content = '';\r\n if (typeof node === 'string') {\r\n content = node;\r\n } else {\r\n content = node.text;\r\n }\r\n const lines = content.split(NEWLINE_REGEXP);\r\n return lines;\r\n}\r\n\r\n// Tokenization\r\n\r\ninterface JSDocToken {\r\n type: 'text' | 'tag' | 'inline-tag' | 'break'\r\n content: string\r\n range: Range\r\n}\r\n\r\nconst tagRegex = /\\s*(@([\\p{L}][\\p{L}\\p{N}]*)?)/uy;\r\nconst inlineTagRegex = /\\{(@[\\p{L}][\\p{L}\\p{N}]*)(\\s*)([^\\r\\n}]+)?\\}/gu;\r\n\r\nfunction tokenize(context: TokenizationContext): JSDocToken[] {\r\n const tokens: JSDocToken[] = [];\r\n let currentLine = context.position.line;\r\n let currentCharacter = context.position.character;\r\n for (let i = 0; i < context.lines.length; i++) {\r\n const first = i === 0;\r\n const last = i === context.lines.length - 1;\r\n let line = context.lines[i];\r\n let index = 0;\r\n\r\n if (first && context.options.start) {\r\n const match = context.options.start?.exec(line);\r\n if (match) {\r\n index = match.index + match[0].length;\r\n }\r\n } else {\r\n const match = context.options.line?.exec(line);\r\n if (match) {\r\n index = match.index + match[0].length;\r\n }\r\n }\r\n if (last) {\r\n const match = context.options.end?.exec(line);\r\n if (match) {\r\n line = line.substring(0, match.index);\r\n }\r\n }\r\n\r\n line = line.substring(0, lastCharacter(line));\r\n const whitespaceEnd = skipWhitespace(line, index);\r\n\r\n if (whitespaceEnd >= line.length) {\r\n // Only create a break token when we already have previous tokens\r\n if (tokens.length > 0) {\r\n const position = Position.create(currentLine, currentCharacter);\r\n tokens.push({\r\n type: 'break',\r\n content: '',\r\n range: Range.create(position, position)\r\n });\r\n }\r\n } else {\r\n tagRegex.lastIndex = index;\r\n const tagMatch = tagRegex.exec(line);\r\n if (tagMatch) {\r\n const fullMatch = tagMatch[0];\r\n const value = tagMatch[1];\r\n const start = Position.create(currentLine, currentCharacter + index);\r\n const end = Position.create(currentLine, currentCharacter + index + fullMatch.length);\r\n tokens.push({\r\n type: 'tag',\r\n content: value,\r\n range: Range.create(start, end)\r\n });\r\n index += fullMatch.length;\r\n index = skipWhitespace(line, index);\r\n }\r\n\r\n if (index < line.length) {\r\n const rest = line.substring(index);\r\n const inlineTagMatches = Array.from(rest.matchAll(inlineTagRegex));\r\n tokens.push(...buildInlineTokens(inlineTagMatches, rest, currentLine, currentCharacter + index));\r\n }\r\n }\r\n\r\n currentLine++;\r\n currentCharacter = 0;\r\n }\r\n\r\n // Remove last break token if there is one\r\n if (tokens.length > 0 && tokens[tokens.length - 1].type === 'break') {\r\n return tokens.slice(0, -1);\r\n }\r\n\r\n return tokens;\r\n}\r\n\r\nfunction buildInlineTokens(tags: RegExpMatchArray[], line: string, lineIndex: number, characterIndex: number): JSDocToken[] {\r\n const tokens: JSDocToken[] = [];\r\n\r\n if (tags.length === 0) {\r\n const start = Position.create(lineIndex, characterIndex);\r\n const end = Position.create(lineIndex, characterIndex + line.length);\r\n tokens.push({\r\n type: 'text',\r\n content: line,\r\n range: Range.create(start, end)\r\n });\r\n } else {\r\n let lastIndex = 0;\r\n for (const match of tags) {\r\n const matchIndex = match.index!;\r\n const startContent = line.substring(lastIndex, matchIndex);\r\n if (startContent.length > 0) {\r\n tokens.push({\r\n type: 'text',\r\n content: line.substring(lastIndex, matchIndex),\r\n range: Range.create(\r\n Position.create(lineIndex, lastIndex + characterIndex),\r\n Position.create(lineIndex, matchIndex + characterIndex)\r\n )\r\n });\r\n }\r\n let offset = startContent.length + 1;\r\n const tagName = match[1];\r\n tokens.push({\r\n type: 'inline-tag',\r\n content: tagName,\r\n range: Range.create(\r\n Position.create(lineIndex, lastIndex + offset + characterIndex),\r\n Position.create(lineIndex, lastIndex + offset + tagName.length + characterIndex)\r\n )\r\n });\r\n offset += tagName.length;\r\n if (match.length === 4) {\r\n offset += match[2].length;\r\n const value = match[3];\r\n tokens.push({\r\n type: 'text',\r\n content: value,\r\n range: Range.create(\r\n Position.create(lineIndex, lastIndex + offset + characterIndex),\r\n Position.create(lineIndex, lastIndex + offset + value.length + characterIndex)\r\n )\r\n });\r\n } else {\r\n tokens.push({\r\n type: 'text',\r\n content: '',\r\n range: Range.create(\r\n Position.create(lineIndex, lastIndex + offset + characterIndex),\r\n Position.create(lineIndex, lastIndex + offset + characterIndex)\r\n )\r\n });\r\n }\r\n lastIndex = matchIndex + match[0].length;\r\n }\r\n const endContent = line.substring(lastIndex);\r\n if (endContent.length > 0) {\r\n tokens.push({\r\n type: 'text',\r\n content: endContent,\r\n range: Range.create(\r\n Position.create(lineIndex, lastIndex + characterIndex),\r\n Position.create(lineIndex, lastIndex + characterIndex + endContent.length)\r\n )\r\n });\r\n }\r\n }\r\n\r\n return tokens;\r\n}\r\n\r\nconst nonWhitespaceRegex = /\\S/;\r\nconst whitespaceEndRegex = /\\s*$/;\r\n\r\nfunction skipWhitespace(line: string, index: number): number {\r\n const match = line.substring(index).match(nonWhitespaceRegex);\r\n if (match) {\r\n return index + match.index!;\r\n } else {\r\n return line.length;\r\n }\r\n}\r\n\r\nfunction lastCharacter(line: string): number | undefined {\r\n const match = line.match(whitespaceEndRegex);\r\n if (match && typeof match.index === 'number') {\r\n return match.index;\r\n }\r\n return undefined;\r\n}\r\n\r\n// Parsing\r\n\r\nfunction parseJSDocComment(context: ParseContext): JSDocComment {\r\n const startPosition: Position = Position.create(context.position.line, context.position.character);\r\n if (context.tokens.length === 0) {\r\n return new JSDocCommentImpl([], Range.create(startPosition, startPosition));\r\n }\r\n const elements: JSDocElement[] = [];\r\n while (context.index < context.tokens.length) {\r\n const element = parseJSDocElement(context, elements[elements.length - 1]);\r\n if (element) {\r\n elements.push(element);\r\n }\r\n }\r\n const start = elements[0]?.range.start ?? startPosition;\r\n const end = elements[elements.length - 1]?.range.end ?? startPosition;\r\n return new JSDocCommentImpl(elements, Range.create(start, end));\r\n}\r\n\r\nfunction parseJSDocElement(context: ParseContext, last?: JSDocElement): JSDocElement | undefined {\r\n const next = context.tokens[context.index];\r\n if (next.type === 'tag') {\r\n return parseJSDocTag(context, false);\r\n } else if (next.type === 'text' || next.type === 'inline-tag') {\r\n return parseJSDocText(context);\r\n } else {\r\n appendEmptyLine(next, last);\r\n context.index++;\r\n return undefined;\r\n }\r\n}\r\n\r\nfunction appendEmptyLine(token: JSDocToken, element?: JSDocElement): void {\r\n if (element) {\r\n const line = new JSDocLineImpl('', token.range);\r\n if ('inlines' in element) {\r\n element.inlines.push(line);\r\n } else {\r\n element.content.inlines.push(line);\r\n }\r\n }\r\n}\r\n\r\nfunction parseJSDocText(context: ParseContext): JSDocParagraph {\r\n let token = context.tokens[context.index];\r\n const firstToken = token;\r\n let lastToken = token;\r\n const lines: JSDocInline[] = [];\r\n while (token && token.type !== 'break' && token.type !== 'tag') {\r\n lines.push(parseJSDocInline(context));\r\n lastToken = token;\r\n token = context.tokens[context.index];\r\n }\r\n return new JSDocTextImpl(lines, Range.create(firstToken.range.start, lastToken.range.end));\r\n}\r\n\r\nfunction parseJSDocInline(context: ParseContext): JSDocInline {\r\n const token = context.tokens[context.index];\r\n if (token.type === 'inline-tag') {\r\n return parseJSDocTag(context, true);\r\n } else {\r\n return parseJSDocLine(context);\r\n }\r\n}\r\n\r\nfunction parseJSDocTag(context: ParseContext, inline: boolean): JSDocTag {\r\n const tagToken = context.tokens[context.index++];\r\n const name = tagToken.content.substring(1);\r\n const nextToken = context.tokens[context.index];\r\n if (nextToken?.type === 'text') {\r\n if (inline) {\r\n const docLine = parseJSDocLine(context);\r\n return new JSDocTagImpl(\r\n name,\r\n new JSDocTextImpl([docLine], docLine.range),\r\n inline,\r\n Range.create(tagToken.range.start, docLine.range.end)\r\n );\r\n } else {\r\n const textDoc = parseJSDocText(context);\r\n return new JSDocTagImpl(\r\n name,\r\n textDoc,\r\n inline,\r\n Range.create(tagToken.range.start, textDoc.range.end)\r\n );\r\n }\r\n } else {\r\n const range = tagToken.range;\r\n return new JSDocTagImpl(name, new JSDocTextImpl([], range), inline, range);\r\n }\r\n}\r\n\r\nfunction parseJSDocLine(context: ParseContext): JSDocLine {\r\n const token = context.tokens[context.index++];\r\n return new JSDocLineImpl(token.content, token.range);\r\n}\r\n\r\ninterface NormalizedOptions {\r\n start?: RegExp\r\n end?: RegExp\r\n line?: RegExp\r\n}\r\n\r\ninterface TokenizationContext {\r\n position: Position\r\n lines: string[]\r\n options: NormalizedOptions\r\n}\r\n\r\ninterface ParseContext {\r\n position: Position\r\n tokens: JSDocToken[]\r\n index: number\r\n}\r\n\r\nfunction normalizeOptions(options?: JSDocParseOptions): NormalizedOptions {\r\n if (!options) {\r\n return normalizeOptions({\r\n start: '/**',\r\n end: '*/',\r\n line: '*'\r\n });\r\n }\r\n const { start, end, line } = options;\r\n return {\r\n start: normalizeOption(start, true),\r\n end: normalizeOption(end, false),\r\n line: normalizeOption(line, true)\r\n };\r\n}\r\n\r\nfunction normalizeOption(option: RegExp | string | undefined, start: boolean): RegExp | undefined {\r\n if (typeof option === 'string' || typeof option === 'object') {\r\n const escaped = typeof option === 'string' ? escapeRegExp(option) : option.source;\r\n if (start) {\r\n return new RegExp(`^\\\\s*${escaped}`);\r\n } else {\r\n return new RegExp(`\\\\s*${escaped}\\\\s*$`);\r\n }\r\n } else {\r\n return option;\r\n }\r\n}\r\n\r\nclass JSDocCommentImpl implements JSDocComment {\r\n\r\n readonly elements: JSDocElement[];\r\n readonly range: Range;\r\n\r\n constructor(elements: JSDocElement[], range: Range) {\r\n this.elements = elements;\r\n this.range = range;\r\n }\r\n\r\n getTag(name: string): JSDocTag | undefined {\r\n return this.getAllTags().find(e => e.name === name);\r\n }\r\n\r\n getTags(name: string): JSDocTag[] {\r\n return this.getAllTags().filter(e => e.name === name);\r\n }\r\n\r\n private getAllTags(): JSDocTag[] {\r\n return this.elements.filter((e): e is JSDocTag => 'name' in e);\r\n }\r\n\r\n toString(): string {\r\n let value = '';\r\n for (const element of this.elements) {\r\n if (value.length === 0) {\r\n value = element.toString();\r\n } else {\r\n const text = element.toString();\r\n value += fillNewlines(value) + text;\r\n }\r\n }\r\n return value.trim();\r\n }\r\n\r\n toMarkdown(options?: JSDocRenderOptions): string {\r\n let value = '';\r\n for (const element of this.elements) {\r\n if (value.length === 0) {\r\n value = element.toMarkdown(options);\r\n } else {\r\n const text = element.toMarkdown(options);\r\n value += fillNewlines(value) + text;\r\n }\r\n }\r\n return value.trim();\r\n }\r\n}\r\n\r\nclass JSDocTagImpl implements JSDocTag {\r\n name: string;\r\n content: JSDocParagraph;\r\n range: Range;\r\n inline: boolean;\r\n\r\n constructor(name: string, content: JSDocParagraph, inline: boolean, range: Range) {\r\n this.name = name;\r\n this.content = content;\r\n this.inline = inline;\r\n this.range = range;\r\n }\r\n\r\n toString(): string {\r\n let text = `@${this.name}`;\r\n const content = this.content.toString();\r\n if (this.content.inlines.length === 1) {\r\n text = `${text} ${content}`;\r\n } else if (this.content.inlines.length > 1) {\r\n text = `${text}\\n${content}`;\r\n }\r\n if (this.inline) {\r\n // Inline tags are surrounded by curly braces\r\n return `{${text}}`;\r\n } else {\r\n return text;\r\n }\r\n }\r\n\r\n toMarkdown(options?: JSDocRenderOptions): string {\r\n return options?.renderTag?.(this) ?? this.toMarkdownDefault(options);\r\n }\r\n\r\n private toMarkdownDefault(options?: JSDocRenderOptions): string {\r\n const content = this.content.toMarkdown(options);\r\n if (this.inline) {\r\n const rendered = renderInlineTag(this.name, content, options ?? {});\r\n if (typeof rendered === 'string') {\r\n return rendered;\r\n }\r\n }\r\n let marker = '';\r\n if (options?.tag === 'italic' || options?.tag === undefined) {\r\n marker = '*';\r\n } else if (options?.tag === 'bold') {\r\n marker = '**';\r\n } else if (options?.tag === 'bold-italic') {\r\n marker = '***';\r\n }\r\n let text = `${marker}@${this.name}${marker}`;\r\n if (this.content.inlines.length === 1) {\r\n text = `${text} \u2014 ${content}`;\r\n } else if (this.content.inlines.length > 1) {\r\n text = `${text}\\n${content}`;\r\n }\r\n if (this.inline) {\r\n // Inline tags are surrounded by curly braces\r\n return `{${text}}`;\r\n } else {\r\n return text;\r\n }\r\n }\r\n}\r\n\r\nfunction renderInlineTag(tag: string, content: string, options: JSDocRenderOptions): string | undefined {\r\n if (tag === 'linkplain' || tag === 'linkcode' || tag === 'link') {\r\n const index = content.indexOf(' ');\r\n let display = content;\r\n if (index > 0) {\r\n const displayStart = skipWhitespace(content, index);\r\n display = content.substring(displayStart);\r\n content = content.substring(0, index);\r\n }\r\n if (tag === 'linkcode' || (tag === 'link' && options.link === 'code')) {\r\n // Surround the display value in a markdown inline code block\r\n display = `\\`${display}\\``;\r\n }\r\n const renderedLink = options.renderLink?.(content, display) ?? renderLinkDefault(content, display);\r\n return renderedLink;\r\n }\r\n return undefined;\r\n}\r\n\r\nfunction renderLinkDefault(content: string, display: string): string {\r\n try {\r\n URI.parse(content, true);\r\n return `[${display}](${content})`;\r\n } catch {\r\n return content;\r\n }\r\n}\r\n\r\nclass JSDocTextImpl implements JSDocParagraph {\r\n inlines: JSDocInline[];\r\n range: Range;\r\n\r\n constructor(lines: JSDocInline[], range: Range) {\r\n this.inlines = lines;\r\n this.range = range;\r\n }\r\n\r\n toString(): string {\r\n let text = '';\r\n for (let i = 0; i < this.inlines.length; i++) {\r\n const inline = this.inlines[i];\r\n const next = this.inlines[i + 1];\r\n text += inline.toString();\r\n if (next && next.range.start.line > inline.range.start.line) {\r\n text += '\\n';\r\n }\r\n }\r\n return text;\r\n }\r\n\r\n toMarkdown(options?: JSDocRenderOptions): string {\r\n let text = '';\r\n for (let i = 0; i < this.inlines.length; i++) {\r\n const inline = this.inlines[i];\r\n const next = this.inlines[i + 1];\r\n text += inline.toMarkdown(options);\r\n if (next && next.range.start.line > inline.range.start.line) {\r\n text += '\\n';\r\n }\r\n }\r\n return text;\r\n }\r\n}\r\n\r\nclass JSDocLineImpl implements JSDocLine {\r\n text: string;\r\n range: Range;\r\n\r\n constructor(text: string, range: Range) {\r\n this.text = text;\r\n this.range = range;\r\n }\r\n\r\n toString(): string {\r\n return this.text;\r\n }\r\n toMarkdown(): string {\r\n return this.text;\r\n }\r\n\r\n}\r\n\r\nfunction fillNewlines(text: string): string {\r\n if (text.endsWith('\\n')) {\r\n return '\\n';\r\n } else {\r\n return '\\n\\n';\r\n }\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2023 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport type { AstNode, AstNodeDescription } from '../syntax-tree.js';\r\nimport type { IndexManager } from '../workspace/index-manager.js';\r\nimport type { CommentProvider } from './comment-provider.js';\r\nimport type { JSDocTag } from './jsdoc.js';\r\nimport { getDocument } from '../utils/ast-utils.js';\r\nimport { isJSDoc, parseJSDoc } from './jsdoc.js';\r\n\r\n/**\r\n * Provides documentation for AST nodes.\r\n */\r\nexport interface DocumentationProvider {\r\n /**\r\n * Returns a markdown documentation string for the specified AST node.\r\n *\r\n * The default implementation `JSDocDocumentationProvider` will inspect the comment associated with the specified node.\r\n */\r\n getDocumentation(node: AstNode): string | undefined;\r\n}\r\n\r\nexport class JSDocDocumentationProvider implements DocumentationProvider {\r\n\r\n protected readonly indexManager: IndexManager;\r\n protected readonly commentProvider: CommentProvider;\r\n\r\n constructor(services: LangiumCoreServices) {\r\n this.indexManager = services.shared.workspace.IndexManager;\r\n this.commentProvider = services.documentation.CommentProvider;\r\n }\r\n\r\n getDocumentation(node: AstNode): string | undefined {\r\n const comment = this.commentProvider.getComment(node);\r\n if (comment && isJSDoc(comment)) {\r\n const parsedJSDoc = parseJSDoc(comment);\r\n return parsedJSDoc.toMarkdown({\r\n renderLink: (link, display) => {\r\n return this.documentationLinkRenderer(node, link, display);\r\n },\r\n renderTag: (tag) => {\r\n return this.documentationTagRenderer(node, tag);\r\n }\r\n });\r\n }\r\n return undefined;\r\n }\r\n\r\n protected documentationLinkRenderer(node: AstNode, name: string, display: string): string | undefined {\r\n const description = this.findNameInPrecomputedScopes(node, name) ?? this.findNameInGlobalScope(node, name);\r\n if (description && description.nameSegment) {\r\n const line = description.nameSegment.range.start.line + 1;\r\n const character = description.nameSegment.range.start.character + 1;\r\n const uri = description.documentUri.with({ fragment: `L${line},${character}` });\r\n return `[${display}](${uri.toString()})`;\r\n } else {\r\n return undefined;\r\n }\r\n }\r\n\r\n protected documentationTagRenderer(_node: AstNode, _tag: JSDocTag): string | undefined {\r\n // Fall back to the default tag rendering\r\n return undefined;\r\n }\r\n\r\n protected findNameInPrecomputedScopes(node: AstNode, name: string): AstNodeDescription | undefined {\r\n const document = getDocument(node);\r\n const precomputed = document.precomputedScopes;\r\n if (!precomputed) {\r\n return undefined;\r\n }\r\n let currentNode: AstNode | undefined = node;\r\n do {\r\n const allDescriptions = precomputed.get(currentNode);\r\n const description = allDescriptions.find(e => e.name === name);\r\n if (description) {\r\n return description;\r\n }\r\n currentNode = currentNode.$container;\r\n } while (currentNode);\r\n\r\n return undefined;\r\n }\r\n\r\n protected findNameInGlobalScope(node: AstNode, name: string): AstNodeDescription | undefined {\r\n const description = this.indexManager.allElements().find(e => e.name === name);\r\n return description;\r\n }\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2023 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { GrammarConfig } from '../languages/grammar-config.js';\r\nimport { isAstNodeWithComment } from '../serializer/json-serializer.js';\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport type { AstNode } from '../syntax-tree.js';\r\nimport { findCommentNode } from '../utils/cst-utils.js';\r\n\r\n/**\r\n * Provides comments for AST nodes.\r\n */\r\nexport interface CommentProvider {\r\n /**\r\n * Returns the comment associated with the specified AST node.\r\n * @param node The AST node to get the comment for.\r\n * @returns The comment associated with the specified AST node or `undefined` if there is no comment.\r\n */\r\n getComment(node: AstNode): string | undefined;\r\n}\r\n\r\nexport class DefaultCommentProvider implements CommentProvider {\r\n protected readonly grammarConfig: () => GrammarConfig;\r\n constructor(services: LangiumCoreServices) {\r\n this.grammarConfig = () => services.parser.GrammarConfig;\r\n }\r\n getComment(node: AstNode): string | undefined {\r\n if(isAstNodeWithComment(node)) {\r\n return node.$comment;\r\n }\r\n return findCommentNode(node.$cstNode, this.grammarConfig().multilineCommentRules)?.text;\r\n }\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2023 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { CancellationToken } from '../utils/cancellation.js';\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport type { AstNode } from '../syntax-tree.js';\r\nimport type { LangiumParser, ParseResult } from './langium-parser.js';\r\nimport type { Hydrator } from '../serializer/hydrator.js';\r\nimport type { Event } from '../utils/event.js';\r\nimport { Deferred, OperationCancelled } from '../utils/promise-utils.js';\r\nimport { Emitter } from '../utils/event.js';\r\n\r\n/**\r\n * Async parser that allows cancellation of the current parsing process.\r\n *\r\n * @remarks\r\n * The sync parser implementation is blocking the event loop, which can become quite problematic for large files.\r\n * The default implementation is not actually async. It just wraps the sync parser in a promise. A real implementation would create worker threads or web workers to offload the parsing work.\r\n */\r\nexport interface AsyncParser {\r\n /**\r\n * Parses the given text and returns the parse result.\r\n *\r\n * @param text The text to parse.\r\n * @param cancelToken A cancellation token that can be used to cancel the parsing process.\r\n * @returns A promise that resolves to the parse result.\r\n *\r\n * @throws `OperationCancelled` if the parsing process is cancelled.\r\n */\r\n parse(text: string, cancelToken: CancellationToken): Promise>;\r\n}\r\n\r\n/**\r\n * Default implementation of the async parser which simply wraps the sync parser in a promise.\r\n *\r\n * @remarks\r\n * A real implementation would create worker threads or web workers to offload the parsing work.\r\n */\r\nexport class DefaultAsyncParser implements AsyncParser {\r\n\r\n protected readonly syncParser: LangiumParser;\r\n\r\n constructor(services: LangiumCoreServices) {\r\n this.syncParser = services.parser.LangiumParser;\r\n }\r\n\r\n parse(text: string, _cancelToken: CancellationToken): Promise> {\r\n return Promise.resolve(this.syncParser.parse(text));\r\n }\r\n}\r\n\r\nexport abstract class AbstractThreadedAsyncParser implements AsyncParser {\r\n\r\n /**\r\n * The thread count determines how many threads are used to parse files in parallel.\r\n * The default value is 8. Decreasing this value increases startup performance, but decreases parallel parsing performance.\r\n */\r\n protected threadCount = 8;\r\n /**\r\n * The termination delay determines how long the parser waits for a thread to finish after a cancellation request.\r\n * The default value is 200(ms).\r\n */\r\n protected terminationDelay = 200;\r\n protected workerPool: ParserWorker[] = [];\r\n protected queue: Array> = [];\r\n\r\n protected readonly hydrator: Hydrator;\r\n\r\n constructor(services: LangiumCoreServices) {\r\n this.hydrator = services.serializer.Hydrator;\r\n }\r\n\r\n protected initializeWorkers(): void {\r\n while (this.workerPool.length < this.threadCount) {\r\n const worker = this.createWorker();\r\n worker.onReady(() => {\r\n if (this.queue.length > 0) {\r\n const deferred = this.queue.shift();\r\n if (deferred) {\r\n worker.lock();\r\n deferred.resolve(worker);\r\n }\r\n }\r\n });\r\n this.workerPool.push(worker);\r\n }\r\n }\r\n\r\n async parse(text: string, cancelToken: CancellationToken): Promise> {\r\n const worker = await this.acquireParserWorker(cancelToken);\r\n const deferred = new Deferred>();\r\n let timeout: NodeJS.Timeout | undefined;\r\n // If the cancellation token is requested, we wait for a certain time before terminating the worker.\r\n // Since the cancellation token lives longer than the parsing process, we need to dispose the event listener.\r\n // Otherwise, we might accidentally terminate the worker after the parsing process has finished.\r\n const cancellation = cancelToken.onCancellationRequested(() => {\r\n timeout = setTimeout(() => {\r\n this.terminateWorker(worker);\r\n }, this.terminationDelay);\r\n });\r\n worker.parse(text).then(result => {\r\n const hydrated = this.hydrator.hydrate(result);\r\n deferred.resolve(hydrated);\r\n }).catch(err => {\r\n deferred.reject(err);\r\n }).finally(() => {\r\n cancellation.dispose();\r\n clearTimeout(timeout);\r\n });\r\n return deferred.promise;\r\n }\r\n\r\n protected terminateWorker(worker: ParserWorker): void {\r\n worker.terminate();\r\n const index = this.workerPool.indexOf(worker);\r\n if (index >= 0) {\r\n this.workerPool.splice(index, 1);\r\n }\r\n }\r\n\r\n protected async acquireParserWorker(cancelToken: CancellationToken): Promise {\r\n this.initializeWorkers();\r\n for (const worker of this.workerPool) {\r\n if (worker.ready) {\r\n worker.lock();\r\n return worker;\r\n }\r\n }\r\n const deferred = new Deferred();\r\n cancelToken.onCancellationRequested(() => {\r\n const index = this.queue.indexOf(deferred);\r\n if (index >= 0) {\r\n this.queue.splice(index, 1);\r\n }\r\n deferred.reject(OperationCancelled);\r\n });\r\n this.queue.push(deferred);\r\n return deferred.promise;\r\n }\r\n\r\n protected abstract createWorker(): ParserWorker;\r\n}\r\n\r\nexport type WorkerMessagePost = (message: unknown) => void;\r\nexport type WorkerMessageCallback = (cb: (message: unknown) => void) => void;\r\n\r\nexport class ParserWorker {\r\n\r\n protected readonly sendMessage: WorkerMessagePost;\r\n protected readonly _terminate: () => void;\r\n protected readonly onReadyEmitter = new Emitter();\r\n\r\n protected deferred = new Deferred();\r\n protected _ready = true;\r\n protected _parsing = false;\r\n\r\n get ready(): boolean {\r\n return this._ready;\r\n }\r\n\r\n get onReady(): Event {\r\n return this.onReadyEmitter.event;\r\n }\r\n\r\n constructor(sendMessage: WorkerMessagePost, onMessage: WorkerMessageCallback, onError: WorkerMessageCallback, terminate: () => void) {\r\n this.sendMessage = sendMessage;\r\n this._terminate = terminate;\r\n onMessage(result => {\r\n const parseResult = result as ParseResult;\r\n this.deferred.resolve(parseResult);\r\n this.unlock();\r\n });\r\n onError(error => {\r\n this.deferred.reject(error);\r\n this.unlock();\r\n });\r\n }\r\n\r\n terminate(): void {\r\n this.deferred.reject(OperationCancelled);\r\n this._terminate();\r\n }\r\n\r\n lock(): void {\r\n this._ready = false;\r\n }\r\n\r\n unlock(): void {\r\n this._parsing = false;\r\n this._ready = true;\r\n this.onReadyEmitter.fire();\r\n }\r\n\r\n parse(text: string): Promise {\r\n if (this._parsing) {\r\n throw new Error('Parser worker is busy');\r\n }\r\n this._parsing = true;\r\n this.deferred = new Deferred();\r\n this.sendMessage(text);\r\n return this.deferred.promise;\r\n }\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2023 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport { type AbstractCancellationTokenSource, CancellationToken, CancellationTokenSource } from '../utils/cancellation.js';\r\nimport { Deferred, isOperationCancelled, startCancelableOperation, type MaybePromise } from '../utils/promise-utils.js';\r\n\r\n/**\r\n * Utility service to execute mutually exclusive actions.\r\n */\r\nexport interface WorkspaceLock {\r\n /**\r\n * Performs a single async action, like initializing the workspace or processing document changes.\r\n * Only one action will be executed at a time.\r\n *\r\n * When another action is queued up, the token provided for the action will be cancelled.\r\n * Assuming the action makes use of this token, the next action only has to wait for the current action to finish cancellation.\r\n */\r\n write(action: (token: CancellationToken) => MaybePromise): Promise;\r\n\r\n /**\r\n * Performs a single action, like computing completion results or providing workspace symbols.\r\n * Read actions will only be executed after all write actions have finished. They will be executed in parallel if possible.\r\n *\r\n * If a write action is currently running, the read action will be queued up and executed afterwards.\r\n * If a new write action is queued up while a read action is waiting, the write action will receive priority and will be handled before the read action.\r\n *\r\n * Note that read actions are not allowed to modify anything in the workspace. Please use {@link write} instead.\r\n */\r\n read(action: () => MaybePromise): Promise;\r\n\r\n /**\r\n * Cancels the last queued write action. All previous write actions already have been cancelled.\r\n */\r\n cancelWrite(): void;\r\n}\r\n\r\ntype LockAction = (token: CancellationToken) => MaybePromise;\r\n\r\ninterface LockEntry {\r\n action: LockAction;\r\n deferred: Deferred;\r\n cancellationToken: CancellationToken;\r\n}\r\n\r\nexport class DefaultWorkspaceLock implements WorkspaceLock {\r\n\r\n private previousTokenSource: AbstractCancellationTokenSource = new CancellationTokenSource();\r\n private writeQueue: LockEntry[] = [];\r\n private readQueue: LockEntry[] = [];\r\n private done = true;\r\n\r\n write(action: (token: CancellationToken) => MaybePromise): Promise {\r\n this.cancelWrite();\r\n const tokenSource = startCancelableOperation();\r\n this.previousTokenSource = tokenSource;\r\n return this.enqueue(this.writeQueue, action, tokenSource.token);\r\n }\r\n\r\n read(action: () => MaybePromise): Promise {\r\n return this.enqueue(this.readQueue, action);\r\n }\r\n\r\n private enqueue(queue: LockEntry[], action: LockAction, cancellationToken = CancellationToken.None): Promise {\r\n const deferred = new Deferred();\r\n const entry: LockEntry = {\r\n action,\r\n deferred,\r\n cancellationToken\r\n };\r\n queue.push(entry);\r\n this.performNextOperation();\r\n return deferred.promise as Promise;\r\n }\r\n\r\n private async performNextOperation(): Promise {\r\n if (!this.done) {\r\n return;\r\n }\r\n const entries: LockEntry[] = [];\r\n if (this.writeQueue.length > 0) {\r\n // Just perform the next write action\r\n entries.push(this.writeQueue.shift()!);\r\n } else if (this.readQueue.length > 0) {\r\n // Empty the read queue and perform all actions in parallel\r\n entries.push(...this.readQueue.splice(0, this.readQueue.length));\r\n } else {\r\n return;\r\n }\r\n this.done = false;\r\n await Promise.all(entries.map(async ({ action, deferred, cancellationToken }) => {\r\n try {\r\n // Move the execution of the action to the next event loop tick via `Promise.resolve()`\r\n const result = await Promise.resolve().then(() => action(cancellationToken));\r\n deferred.resolve(result);\r\n } catch (err) {\r\n if (isOperationCancelled(err)) {\r\n // If the operation was cancelled, we don't want to reject the promise\r\n deferred.resolve(undefined);\r\n } else {\r\n deferred.reject(err);\r\n }\r\n }\r\n }));\r\n this.done = true;\r\n this.performNextOperation();\r\n }\r\n\r\n cancelWrite(): void {\r\n this.previousTokenSource.cancel();\r\n }\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2024 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\n/* eslint-disable @typescript-eslint/no-explicit-any */\r\n\r\nimport type { TokenType } from 'chevrotain';\r\nimport { CompositeCstNodeImpl, LeafCstNodeImpl, RootCstNodeImpl } from '../parser/cst-node-builder.js';\r\nimport { isAbstractElement, type AbstractElement, type Grammar } from '../languages/generated/ast.js';\r\nimport type { Linker } from '../references/linker.js';\r\nimport type { Lexer } from '../parser/lexer.js';\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport type { ParseResult } from '../parser/langium-parser.js';\r\nimport type { Reference, AstNode, CstNode, LeafCstNode, GenericAstNode, Mutable, RootCstNode } from '../syntax-tree.js';\r\nimport { isRootCstNode, isCompositeCstNode, isLeafCstNode, isAstNode, isReference } from '../syntax-tree.js';\r\nimport { streamAst } from '../utils/ast-utils.js';\r\nimport { BiMap } from '../utils/collections.js';\r\nimport { streamCst } from '../utils/cst-utils.js';\r\nimport type { LexingReport } from '../parser/token-builder.js';\r\n\r\n/**\r\n * The hydrator service is responsible for allowing AST parse results to be sent across worker threads.\r\n */\r\nexport interface Hydrator {\r\n /**\r\n * Converts a parse result to a plain object. The resulting object can be sent across worker threads.\r\n */\r\n dehydrate(result: ParseResult): ParseResult;\r\n /**\r\n * Converts a plain object to a parse result. The included AST node can then be used in the main thread.\r\n * Calling this method on objects that have not been dehydrated first will result in undefined behavior.\r\n */\r\n hydrate(result: ParseResult): ParseResult;\r\n}\r\n\r\nexport interface DehydrateContext {\r\n astNodes: Map;\r\n cstNodes: Map;\r\n}\r\n\r\nexport interface HydrateContext {\r\n astNodes: Map;\r\n cstNodes: Map;\r\n}\r\n\r\nexport class DefaultHydrator implements Hydrator {\r\n\r\n protected readonly grammar: Grammar;\r\n protected readonly lexer: Lexer;\r\n protected readonly linker: Linker;\r\n\r\n protected readonly grammarElementIdMap = new BiMap();\r\n protected readonly tokenTypeIdMap = new BiMap();\r\n\r\n constructor(services: LangiumCoreServices) {\r\n this.grammar = services.Grammar;\r\n this.lexer = services.parser.Lexer;\r\n this.linker = services.references.Linker;\r\n }\r\n\r\n dehydrate(result: ParseResult): ParseResult {\r\n return {\r\n lexerErrors: result.lexerErrors,\r\n lexerReport: result.lexerReport ? this.dehydrateLexerReport(result.lexerReport) : undefined,\r\n // We need to create shallow copies of the errors\r\n // The original errors inherit from the `Error` class, which is not transferable across worker threads\r\n parserErrors: result.parserErrors.map(e => ({ ...e, message: e.message })),\r\n value: this.dehydrateAstNode(result.value, this.createDehyrationContext(result.value))\r\n };\r\n }\r\n\r\n protected dehydrateLexerReport(lexerReport: LexingReport): LexingReport {\r\n // By default, lexer reports are serializable\r\n return lexerReport;\r\n }\r\n\r\n protected createDehyrationContext(node: AstNode): DehydrateContext {\r\n const astNodes = new Map();\r\n const cstNodes = new Map();\r\n for (const astNode of streamAst(node)) {\r\n astNodes.set(astNode, {});\r\n }\r\n if (node.$cstNode) {\r\n for (const cstNode of streamCst(node.$cstNode)) {\r\n cstNodes.set(cstNode, {});\r\n }\r\n }\r\n return {\r\n astNodes,\r\n cstNodes\r\n };\r\n }\r\n\r\n protected dehydrateAstNode(node: AstNode, context: DehydrateContext): object {\r\n const obj = context.astNodes.get(node) as Record;\r\n obj.$type = node.$type;\r\n obj.$containerIndex = node.$containerIndex;\r\n obj.$containerProperty = node.$containerProperty;\r\n if (node.$cstNode !== undefined) {\r\n obj.$cstNode = this.dehydrateCstNode(node.$cstNode, context);\r\n }\r\n for (const [name, value] of Object.entries(node)) {\r\n if (name.startsWith('$')) {\r\n continue;\r\n }\r\n if (Array.isArray(value)) {\r\n const arr: any[] = [];\r\n obj[name] = arr;\r\n for (const item of value) {\r\n if (isAstNode(item)) {\r\n arr.push(this.dehydrateAstNode(item, context));\r\n } else if (isReference(item)) {\r\n arr.push(this.dehydrateReference(item, context));\r\n } else {\r\n arr.push(item);\r\n }\r\n }\r\n } else if (isAstNode(value)) {\r\n obj[name] = this.dehydrateAstNode(value, context);\r\n } else if (isReference(value)) {\r\n obj[name] = this.dehydrateReference(value, context);\r\n } else if (value !== undefined) {\r\n obj[name] = value;\r\n }\r\n }\r\n return obj;\r\n }\r\n\r\n protected dehydrateReference(reference: Reference, context: DehydrateContext): any {\r\n const obj: Record = {};\r\n obj.$refText = reference.$refText;\r\n if (reference.$refNode) {\r\n obj.$refNode = context.cstNodes.get(reference.$refNode);\r\n }\r\n return obj;\r\n }\r\n\r\n protected dehydrateCstNode(node: CstNode, context: DehydrateContext): any {\r\n const cstNode = context.cstNodes.get(node) as Record;\r\n if (isRootCstNode(node)) {\r\n cstNode.fullText = node.fullText;\r\n } else {\r\n // Note: This returns undefined for hidden nodes (i.e. comments)\r\n cstNode.grammarSource = this.getGrammarElementId(node.grammarSource);\r\n }\r\n cstNode.hidden = node.hidden;\r\n cstNode.astNode = context.astNodes.get(node.astNode);\r\n if (isCompositeCstNode(node)) {\r\n cstNode.content = node.content.map(child => this.dehydrateCstNode(child, context));\r\n } else if (isLeafCstNode(node)) {\r\n cstNode.tokenType = node.tokenType.name;\r\n cstNode.offset = node.offset;\r\n cstNode.length = node.length;\r\n cstNode.startLine = node.range.start.line;\r\n cstNode.startColumn = node.range.start.character;\r\n cstNode.endLine = node.range.end.line;\r\n cstNode.endColumn = node.range.end.character;\r\n }\r\n return cstNode;\r\n }\r\n\r\n hydrate(result: ParseResult): ParseResult {\r\n const node = result.value;\r\n const context = this.createHydrationContext(node);\r\n if ('$cstNode' in node) {\r\n this.hydrateCstNode(node.$cstNode, context);\r\n }\r\n return {\r\n lexerErrors: result.lexerErrors,\r\n lexerReport: result.lexerReport,\r\n parserErrors: result.parserErrors,\r\n value: this.hydrateAstNode(node, context) as T\r\n };\r\n }\r\n\r\n protected createHydrationContext(node: any): HydrateContext {\r\n const astNodes = new Map();\r\n const cstNodes = new Map();\r\n for (const astNode of streamAst(node)) {\r\n astNodes.set(astNode, {} as AstNode);\r\n }\r\n let root: RootCstNode;\r\n if (node.$cstNode) {\r\n for (const cstNode of streamCst(node.$cstNode)) {\r\n let cst: Mutable | undefined;\r\n if ('fullText' in cstNode) {\r\n cst = new RootCstNodeImpl(cstNode.fullText as string);\r\n root = cst as RootCstNode;\r\n } else if ('content' in cstNode) {\r\n cst = new CompositeCstNodeImpl();\r\n } else if ('tokenType' in cstNode) {\r\n cst = this.hydrateCstLeafNode(cstNode);\r\n }\r\n if (cst) {\r\n cstNodes.set(cstNode, cst);\r\n cst.root = root!;\r\n }\r\n }\r\n }\r\n return {\r\n astNodes,\r\n cstNodes\r\n };\r\n }\r\n\r\n protected hydrateAstNode(node: any, context: HydrateContext): AstNode {\r\n const astNode = context.astNodes.get(node) as Mutable;\r\n astNode.$type = node.$type;\r\n astNode.$containerIndex = node.$containerIndex;\r\n astNode.$containerProperty = node.$containerProperty;\r\n if (node.$cstNode) {\r\n astNode.$cstNode = context.cstNodes.get(node.$cstNode);\r\n }\r\n for (const [name, value] of Object.entries(node)) {\r\n if (name.startsWith('$')) {\r\n continue;\r\n }\r\n if (Array.isArray(value)) {\r\n const arr: unknown[] = [];\r\n astNode[name] = arr;\r\n for (const item of value) {\r\n if (isAstNode(item)) {\r\n arr.push(this.setParent(this.hydrateAstNode(item, context), astNode));\r\n } else if (isReference(item)) {\r\n arr.push(this.hydrateReference(item, astNode, name, context));\r\n } else {\r\n arr.push(item);\r\n }\r\n }\r\n } else if (isAstNode(value)) {\r\n astNode[name] = this.setParent(this.hydrateAstNode(value, context), astNode);\r\n } else if (isReference(value)) {\r\n astNode[name] = this.hydrateReference(value, astNode, name, context);\r\n } else if (value !== undefined) {\r\n astNode[name] = value;\r\n }\r\n }\r\n return astNode;\r\n }\r\n\r\n protected setParent(node: any, parent: any): any {\r\n node.$container = parent as AstNode;\r\n return node;\r\n }\r\n\r\n protected hydrateReference(reference: any, node: AstNode, name: string, context: HydrateContext): Reference {\r\n return this.linker.buildReference(node, name, context.cstNodes.get(reference.$refNode)!, reference.$refText);\r\n }\r\n\r\n protected hydrateCstNode(cstNode: any, context: HydrateContext, num = 0): CstNode {\r\n const cstNodeObj = context.cstNodes.get(cstNode) as Mutable;\r\n if (typeof cstNode.grammarSource === 'number') {\r\n cstNodeObj.grammarSource = this.getGrammarElement(cstNode.grammarSource);\r\n }\r\n cstNodeObj.astNode = context.astNodes.get(cstNode.astNode)!;\r\n if (isCompositeCstNode(cstNodeObj)) {\r\n for (const child of cstNode.content) {\r\n const hydrated = this.hydrateCstNode(child, context, num++);\r\n cstNodeObj.content.push(hydrated);\r\n }\r\n }\r\n return cstNodeObj;\r\n }\r\n\r\n protected hydrateCstLeafNode(cstNode: any): LeafCstNode {\r\n const tokenType = this.getTokenType(cstNode.tokenType);\r\n const offset = cstNode.offset;\r\n const length = cstNode.length;\r\n const startLine = cstNode.startLine;\r\n const startColumn = cstNode.startColumn;\r\n const endLine = cstNode.endLine;\r\n const endColumn = cstNode.endColumn;\r\n const hidden = cstNode.hidden;\r\n const node = new LeafCstNodeImpl(\r\n offset,\r\n length,\r\n {\r\n start: {\r\n line: startLine,\r\n character: startColumn\r\n },\r\n end: {\r\n line: endLine,\r\n character: endColumn\r\n }\r\n },\r\n tokenType,\r\n hidden\r\n );\r\n return node;\r\n }\r\n\r\n protected getTokenType(name: string): TokenType {\r\n return this.lexer.definition[name];\r\n }\r\n\r\n protected getGrammarElementId(node: AbstractElement | undefined): number | undefined {\r\n if (!node) {\r\n return undefined;\r\n }\r\n if (this.grammarElementIdMap.size === 0) {\r\n this.createGrammarElementIdMap();\r\n }\r\n return this.grammarElementIdMap.get(node);\r\n }\r\n\r\n protected getGrammarElement(id: number): AbstractElement | undefined {\r\n if (this.grammarElementIdMap.size === 0) {\r\n this.createGrammarElementIdMap();\r\n }\r\n const element = this.grammarElementIdMap.getKey(id);\r\n return element;\r\n }\r\n\r\n protected createGrammarElementIdMap(): void {\r\n let id = 0;\r\n for (const element of streamAst(this.grammar)) {\r\n if (isAbstractElement(element)) {\r\n this.grammarElementIdMap.set(element, id++);\r\n }\r\n }\r\n }\r\n\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n******************************************************************************/\r\n\r\nimport type { Module } from './dependency-injection.js';\r\nimport type { LangiumDefaultCoreServices, LangiumDefaultSharedCoreServices, LangiumCoreServices, LangiumSharedCoreServices } from './services.js';\r\nimport type { FileSystemProvider } from './workspace/file-system-provider.js';\r\nimport { createGrammarConfig } from './languages/grammar-config.js';\r\nimport { createCompletionParser } from './parser/completion-parser-builder.js';\r\nimport { createLangiumParser } from './parser/langium-parser-builder.js';\r\nimport { DefaultTokenBuilder } from './parser/token-builder.js';\r\nimport { DefaultValueConverter } from './parser/value-converter.js';\r\nimport { DefaultLinker } from './references/linker.js';\r\nimport { DefaultNameProvider } from './references/name-provider.js';\r\nimport { DefaultReferences } from './references/references.js';\r\nimport { DefaultScopeComputation } from './references/scope-computation.js';\r\nimport { DefaultScopeProvider } from './references/scope-provider.js';\r\nimport { DefaultJsonSerializer } from './serializer/json-serializer.js';\r\nimport { DefaultServiceRegistry } from './service-registry.js';\r\nimport { DefaultDocumentValidator } from './validation/document-validator.js';\r\nimport { ValidationRegistry } from './validation/validation-registry.js';\r\nimport { DefaultAstNodeDescriptionProvider, DefaultReferenceDescriptionProvider } from './workspace/ast-descriptions.js';\r\nimport { DefaultAstNodeLocator } from './workspace/ast-node-locator.js';\r\nimport { DefaultConfigurationProvider } from './workspace/configuration.js';\r\nimport { DefaultDocumentBuilder } from './workspace/document-builder.js';\r\nimport { DefaultLangiumDocumentFactory, DefaultLangiumDocuments } from './workspace/documents.js';\r\nimport { DefaultIndexManager } from './workspace/index-manager.js';\r\nimport { DefaultWorkspaceManager } from './workspace/workspace-manager.js';\r\nimport { DefaultLexer, DefaultLexerErrorMessageProvider } from './parser/lexer.js';\r\nimport { JSDocDocumentationProvider } from './documentation/documentation-provider.js';\r\nimport { DefaultCommentProvider } from './documentation/comment-provider.js';\r\nimport { LangiumParserErrorMessageProvider } from './parser/langium-parser.js';\r\nimport { DefaultAsyncParser } from './parser/async-parser.js';\r\nimport { DefaultWorkspaceLock } from './workspace/workspace-lock.js';\r\nimport { DefaultHydrator } from './serializer/hydrator.js';\r\n\r\n/**\r\n * Context required for creating the default language-specific dependency injection module.\r\n */\r\nexport interface DefaultCoreModuleContext {\r\n shared: LangiumSharedCoreServices;\r\n}\r\n\r\n/**\r\n * Creates a dependency injection module configuring the default core services.\r\n * This is a set of services that are dedicated to a specific language.\r\n */\r\nexport function createDefaultCoreModule(context: DefaultCoreModuleContext): Module {\r\n return {\r\n documentation: {\r\n CommentProvider: (services) => new DefaultCommentProvider(services),\r\n DocumentationProvider: (services) => new JSDocDocumentationProvider(services)\r\n },\r\n parser: {\r\n AsyncParser: (services) => new DefaultAsyncParser(services),\r\n GrammarConfig: (services) => createGrammarConfig(services),\r\n LangiumParser: (services) => createLangiumParser(services),\r\n CompletionParser: (services) => createCompletionParser(services),\r\n ValueConverter: () => new DefaultValueConverter(),\r\n TokenBuilder: () => new DefaultTokenBuilder(),\r\n Lexer: (services) => new DefaultLexer(services),\r\n ParserErrorMessageProvider: () => new LangiumParserErrorMessageProvider(),\r\n LexerErrorMessageProvider: () => new DefaultLexerErrorMessageProvider()\r\n },\r\n workspace: {\r\n AstNodeLocator: () => new DefaultAstNodeLocator(),\r\n AstNodeDescriptionProvider: (services) => new DefaultAstNodeDescriptionProvider(services),\r\n ReferenceDescriptionProvider: (services) => new DefaultReferenceDescriptionProvider(services)\r\n },\r\n references: {\r\n Linker: (services) => new DefaultLinker(services),\r\n NameProvider: () => new DefaultNameProvider(),\r\n ScopeProvider: (services) => new DefaultScopeProvider(services),\r\n ScopeComputation: (services) => new DefaultScopeComputation(services),\r\n References: (services) => new DefaultReferences(services)\r\n },\r\n serializer: {\r\n Hydrator: (services) => new DefaultHydrator(services),\r\n JsonSerializer: (services) => new DefaultJsonSerializer(services)\r\n },\r\n validation: {\r\n DocumentValidator: (services) => new DefaultDocumentValidator(services),\r\n ValidationRegistry: (services) => new ValidationRegistry(services)\r\n },\r\n shared: () => context.shared\r\n };\r\n}\r\n\r\n/**\r\n * Context required for creating the default shared dependency injection module.\r\n */\r\nexport interface DefaultSharedCoreModuleContext {\r\n /**\r\n * Factory function to create a {@link FileSystemProvider}.\r\n *\r\n * Langium exposes an `EmptyFileSystem` and `NodeFileSystem`, exported through `langium/node`.\r\n * When running Langium as part of a vscode language server or a Node.js app, using the `NodeFileSystem` is recommended,\r\n * the `EmptyFileSystem` in every other use case.\r\n */\r\n fileSystemProvider: (services: LangiumSharedCoreServices) => FileSystemProvider;\r\n}\r\n\r\n/**\r\n * Creates a dependency injection module configuring the default shared core services.\r\n * This is the set of services that are shared between multiple languages.\r\n */\r\nexport function createDefaultSharedCoreModule(context: DefaultSharedCoreModuleContext): Module {\r\n return {\r\n ServiceRegistry: (services) => new DefaultServiceRegistry(services),\r\n workspace: {\r\n LangiumDocuments: (services) => new DefaultLangiumDocuments(services),\r\n LangiumDocumentFactory: (services) => new DefaultLangiumDocumentFactory(services),\r\n DocumentBuilder: (services) => new DefaultDocumentBuilder(services),\r\n IndexManager: (services) => new DefaultIndexManager(services),\r\n WorkspaceManager: (services) => new DefaultWorkspaceManager(services),\r\n FileSystemProvider: (services) => context.fileSystemProvider(services),\r\n WorkspaceLock: () => new DefaultWorkspaceLock(),\r\n ConfigurationProvider: (services) => new DefaultConfigurationProvider(services)\r\n }\r\n };\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2021 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\n/* eslint-disable @typescript-eslint/no-explicit-any */\r\n\r\n/**\r\n * A `Module` is a description of possibly grouped service factories.\r\n *\r\n * Given a type I = { group: { service: A } },\r\n * Module := { group: { service: (injector: I) => A } }\r\n *\r\n * Making `I` available during the creation of `I` allows us to create cyclic\r\n * dependencies.\r\n */\r\nexport type Module = {\r\n [K in keyof T]: Module | ((injector: I) => T[K])\r\n}\r\n\r\nexport namespace Module {\r\n export const merge = (m1: Module, m2: Module) => (_merge(_merge({}, m1), m2) as Module);\r\n}\r\n\r\n/**\r\n * Given a set of modules, the inject function returns a lazily evaluated injector\r\n * that injects dependencies into the requested service when it is requested the\r\n * first time. Subsequent requests will return the same service.\r\n *\r\n * In the case of cyclic dependencies, an Error will be thrown. This can be fixed\r\n * by injecting a provider `() => T` instead of a `T`.\r\n *\r\n * Please note that the arguments may be objects or arrays. However, the result will\r\n * be an object. Using it with for..of will have no effect.\r\n *\r\n * @param module1 first Module\r\n * @param module2 (optional) second Module\r\n * @param module3 (optional) third Module\r\n * @param module4 (optional) fourth Module\r\n * @param module5 (optional) fifth Module\r\n * @param module6 (optional) sixth Module\r\n * @param module7 (optional) seventh Module\r\n * @param module8 (optional) eighth Module\r\n * @param module9 (optional) ninth Module\r\n * @returns a new object of type I\r\n */\r\nexport function inject(\r\n module1: Module, module2?: Module, module3?: Module, module4?: Module, module5?: Module, module6?: Module, module7?: Module, module8?: Module, module9?: Module\r\n): I {\r\n const module = [module1, module2, module3, module4, module5, module6, module7, module8, module9].reduce(_merge, {}) as Module;\r\n return _inject(module);\r\n}\r\n\r\nconst isProxy = Symbol('isProxy');\r\n\r\n/**\r\n * Eagerly load all services in the given dependency injection container. This is sometimes\r\n * necessary because services can register event listeners in their constructors.\r\n */\r\nexport function eagerLoad(item: T): T {\r\n if (item && (item as any)[isProxy]) {\r\n for (const value of Object.values(item)) {\r\n eagerLoad(value);\r\n }\r\n }\r\n return item;\r\n}\r\n\r\n/**\r\n * Helper function that returns an injector by creating a proxy.\r\n * Invariant: injector is of type I. If injector is undefined, then T = I.\r\n */\r\nfunction _inject(module: Module, injector?: any): T {\r\n const proxy: any = new Proxy({} as any, {\r\n deleteProperty: () => false,\r\n set: () => {\r\n throw new Error('Cannot set property on injected service container');\r\n },\r\n get: (obj, prop) => {\r\n if (prop === isProxy) {\r\n return true;\r\n } else {\r\n return _resolve(obj, prop, module, injector || proxy);\r\n }\r\n },\r\n getOwnPropertyDescriptor: (obj, prop) => (_resolve(obj, prop, module, injector || proxy), Object.getOwnPropertyDescriptor(obj, prop)), // used by for..in\r\n has: (_, prop) => prop in module, // used by ..in..\r\n ownKeys: () => [...Object.getOwnPropertyNames(module)] // used by for..in\r\n });\r\n return proxy;\r\n}\r\n\r\n/**\r\n * Internally used to tag a requested dependency, directly before calling the factory.\r\n * This allows us to find cycles during instance creation.\r\n */\r\nconst __requested__ = Symbol();\r\n\r\n/**\r\n * Returns the value `obj[prop]`. If the value does not exist, yet, it is resolved from\r\n * the module description. The result of service factories is cached. Groups are\r\n * recursively proxied.\r\n *\r\n * @param obj an object holding all group proxies and services\r\n * @param prop the key of a value within obj\r\n * @param module an object containing groups and service factories\r\n * @param injector the first level proxy that provides access to all values\r\n * @returns the requested value `obj[prop]`\r\n * @throws Error if a dependency cycle is detected\r\n */\r\nfunction _resolve(obj: any, prop: string | symbol | number, module: Module, injector: I): T[keyof T] | undefined {\r\n if (prop in obj) {\r\n if (obj[prop] instanceof Error) {\r\n throw new Error('Construction failure. Please make sure that your dependencies are constructable.', {cause: obj[prop]});\r\n }\r\n if (obj[prop] === __requested__) {\r\n throw new Error('Cycle detected. Please make \"' + String(prop) + '\" lazy. Visit https://langium.org/docs/reference/configuration-services/#resolving-cyclic-dependencies');\r\n }\r\n return obj[prop];\r\n } else if (prop in module) {\r\n const value: Module | ((injector: I) => T[keyof T]) = module[prop as keyof T];\r\n obj[prop] = __requested__;\r\n try {\r\n obj[prop] = (typeof value === 'function') ? value(injector) : _inject(value, injector);\r\n } catch (error) {\r\n obj[prop] = error instanceof Error ? error : undefined;\r\n throw error;\r\n }\r\n return obj[prop];\r\n } else {\r\n return undefined;\r\n }\r\n}\r\n\r\n/**\r\n * Performs a deep-merge of two modules by writing source entries into the target module.\r\n *\r\n * @param target the module which is written\r\n * @param source the module which is read\r\n * @returns the target module\r\n */\r\nfunction _merge(target: Module, source?: Module): Module {\r\n if (source) {\r\n for (const [key, value2] of Object.entries(source)) {\r\n if (value2 !== undefined) {\r\n const value1 = target[key];\r\n if (value1 !== null && value2 !== null && typeof value1 === 'object' && typeof value2 === 'object') {\r\n target[key] = _merge(value1, value2);\r\n } else {\r\n target[key] = value2;\r\n }\r\n }\r\n }\r\n }\r\n return target;\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2024 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { CustomPatternMatcherFunc, TokenType, IToken, IMultiModeLexerDefinition, TokenVocabulary } from 'chevrotain';\r\nimport type { Grammar, TerminalRule } from '../languages/generated/ast.js';\r\nimport type { LexingReport, TokenBuilderOptions } from './token-builder.js';\r\nimport type { LexerResult, TokenizeOptions } from './lexer.js';\r\nimport type { LangiumCoreServices } from '../services.js';\r\nimport { createToken, createTokenInstance, Lexer } from 'chevrotain';\r\nimport { DefaultTokenBuilder } from './token-builder.js';\r\nimport { DEFAULT_TOKENIZE_OPTIONS, DefaultLexer, isTokenTypeArray } from './lexer.js';\r\n\r\ntype IndentationAwareDelimiter = [begin: TokenName, end: TokenName];\r\n\r\nexport interface IndentationTokenBuilderOptions {\r\n /**\r\n * The name of the token used to denote indentation in the grammar.\r\n * A possible definition in the grammar could look like this:\r\n * ```langium\r\n * terminal INDENT: ':synthetic-indent:';\r\n * ```\r\n *\r\n * @default 'INDENT'\r\n */\r\n indentTokenName: TerminalName;\r\n /**\r\n * The name of the token used to denote deindentation in the grammar.\r\n * A possible definition in the grammar could look like this:\r\n * ```langium\r\n * terminal DEDENT: ':synthetic-dedent:';\r\n * ```\r\n *\r\n * @default 'DEDENT'\r\n */\r\n dedentTokenName: TerminalName;\r\n /**\r\n * The name of the token used to denote whitespace other than indentation and newlines in the grammar.\r\n * A possible definition in the grammar could look like this:\r\n * ```langium\r\n * hidden terminal WS: /[ \\t]+/;\r\n * ```\r\n *\r\n * @default 'WS'\r\n */\r\n whitespaceTokenName: TerminalName;\r\n /**\r\n * The delimiter tokens inside of which indentation should be ignored and treated as normal whitespace.\r\n * For example, Python doesn't treat any whitespace between `(` and `)` as significant.\r\n *\r\n * Can be either terminal tokens or keyword tokens.\r\n *\r\n * @default []\r\n */\r\n ignoreIndentationDelimiters: Array>\r\n}\r\n\r\nexport const indentationBuilderDefaultOptions: IndentationTokenBuilderOptions = {\r\n indentTokenName: 'INDENT',\r\n dedentTokenName: 'DEDENT',\r\n whitespaceTokenName: 'WS',\r\n ignoreIndentationDelimiters: [],\r\n};\r\n\r\nexport enum LexingMode {\r\n REGULAR = 'indentation-sensitive',\r\n IGNORE_INDENTATION = 'ignore-indentation',\r\n}\r\n\r\nexport interface IndentationLexingReport extends LexingReport {\r\n /** Dedent tokens that are necessary to close the remaining indents. */\r\n remainingDedents: IToken[];\r\n}\r\n\r\n/**\r\n * A token builder that is sensitive to indentation in the input text.\r\n * It will generate tokens for indentation and dedentation based on the indentation level.\r\n *\r\n * The first generic parameter corresponds to the names of terminal tokens,\r\n * while the second one corresponds to the names of keyword tokens.\r\n * Both parameters are optional and can be imported from `./generated/ast.js`.\r\n *\r\n * Inspired by https://github.com/chevrotain/chevrotain/blob/master/examples/lexer/python_indentation/python_indentation.js\r\n */\r\nexport class IndentationAwareTokenBuilder extends DefaultTokenBuilder {\r\n /**\r\n * The stack stores all the previously matched indentation levels to understand how deeply the next tokens are nested.\r\n * The stack is valid for lexing\r\n */\r\n protected indentationStack: number[] = [0];\r\n\r\n readonly options: IndentationTokenBuilderOptions;\r\n\r\n /**\r\n * The token type to be used for indentation tokens\r\n */\r\n readonly indentTokenType: TokenType;\r\n\r\n /**\r\n * The token type to be used for dedentation tokens\r\n */\r\n readonly dedentTokenType: TokenType;\r\n\r\n /**\r\n * A regular expression to match a series of tabs and/or spaces.\r\n * Override this to customize what the indentation is allowed to consist of.\r\n */\r\n protected whitespaceRegExp = /[ \\t]+/y;\r\n\r\n constructor(options: Partial, NoInfer>> = indentationBuilderDefaultOptions as IndentationTokenBuilderOptions) {\r\n super();\r\n this.options = {\r\n ...indentationBuilderDefaultOptions as IndentationTokenBuilderOptions,\r\n ...options,\r\n };\r\n\r\n this.indentTokenType = createToken({\r\n name: this.options.indentTokenName,\r\n pattern: this.indentMatcher.bind(this),\r\n line_breaks: false,\r\n });\r\n\r\n this.dedentTokenType = createToken({\r\n name: this.options.dedentTokenName,\r\n pattern: this.dedentMatcher.bind(this),\r\n line_breaks: false,\r\n });\r\n }\r\n\r\n override buildTokens(grammar: Grammar, options?: TokenBuilderOptions | undefined): TokenVocabulary {\r\n const tokenTypes = super.buildTokens(grammar, options);\r\n if (!isTokenTypeArray(tokenTypes)) {\r\n throw new Error('Invalid tokens built by default builder');\r\n }\r\n\r\n const { indentTokenName, dedentTokenName, whitespaceTokenName, ignoreIndentationDelimiters } = this.options;\r\n\r\n // Rearrange tokens because whitespace (which is ignored) goes to the beginning by default, consuming indentation as well\r\n // Order should be: dedent, indent, spaces\r\n let dedent: TokenType | undefined;\r\n let indent: TokenType | undefined;\r\n let ws: TokenType | undefined;\r\n const otherTokens: TokenType[] = [];\r\n for (const tokenType of tokenTypes) {\r\n for (const [begin, end] of ignoreIndentationDelimiters) {\r\n if (tokenType.name === begin) {\r\n tokenType.PUSH_MODE = LexingMode.IGNORE_INDENTATION;\r\n } else if (tokenType.name === end) {\r\n tokenType.POP_MODE = true;\r\n }\r\n }\r\n if (tokenType.name === dedentTokenName) {\r\n dedent = tokenType;\r\n } else if (tokenType.name === indentTokenName) {\r\n indent = tokenType;\r\n } else if (tokenType.name === whitespaceTokenName) {\r\n ws = tokenType;\r\n } else {\r\n otherTokens.push(tokenType);\r\n }\r\n }\r\n if (!dedent || !indent || !ws) {\r\n throw new Error('Some indentation/whitespace tokens not found!');\r\n }\r\n\r\n if (ignoreIndentationDelimiters.length > 0) {\r\n const multiModeLexerDef: IMultiModeLexerDefinition = {\r\n modes: {\r\n [LexingMode.REGULAR]: [dedent, indent, ...otherTokens, ws],\r\n [LexingMode.IGNORE_INDENTATION]: [...otherTokens, ws],\r\n },\r\n defaultMode: LexingMode.REGULAR,\r\n };\r\n return multiModeLexerDef;\r\n } else {\r\n return [dedent, indent, ws, ...otherTokens];\r\n }\r\n }\r\n\r\n override flushLexingReport(text: string): IndentationLexingReport {\r\n const result = super.flushLexingReport(text);\r\n return {\r\n ...result,\r\n remainingDedents: this.flushRemainingDedents(text),\r\n };\r\n }\r\n\r\n /**\r\n * Helper function to check if the current position is the start of a new line.\r\n *\r\n * @param text The full input string.\r\n * @param offset The current position at which to check\r\n * @returns Whether the current position is the start of a new line\r\n */\r\n protected isStartOfLine(text: string, offset: number): boolean {\r\n return offset === 0 || '\\r\\n'.includes(text[offset - 1]);\r\n }\r\n\r\n /**\r\n * A helper function used in matching both indents and dedents.\r\n *\r\n * @param text The full input string.\r\n * @param offset The current position at which to attempt a match\r\n * @param tokens Previously scanned tokens\r\n * @param groups Token Groups\r\n * @returns The current and previous indentation levels and the matched whitespace\r\n */\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n protected matchWhitespace(text: string, offset: number, tokens: IToken[], groups: Record): { currIndentLevel: number, prevIndentLevel: number, match: RegExpExecArray | null } {\r\n this.whitespaceRegExp.lastIndex = offset;\r\n const match = this.whitespaceRegExp.exec(text);\r\n return {\r\n currIndentLevel: match?.[0].length ?? 0,\r\n prevIndentLevel: this.indentationStack.at(-1)!,\r\n match,\r\n };\r\n }\r\n\r\n /**\r\n * Helper function to create an instance of an indentation token.\r\n *\r\n * @param tokenType Indent or dedent token type\r\n * @param text Full input string, used to calculate the line number\r\n * @param image The original image of the token (tabs or spaces)\r\n * @param offset Current position in the input string\r\n * @returns The indentation token instance\r\n */\r\n protected createIndentationTokenInstance(tokenType: TokenType, text: string, image: string, offset: number): IToken {\r\n const lineNumber = this.getLineNumber(text, offset);\r\n return createTokenInstance(\r\n tokenType,\r\n image,\r\n offset, offset + image.length,\r\n lineNumber, lineNumber,\r\n 1, image.length,\r\n );\r\n }\r\n\r\n /**\r\n * Helper function to get the line number at a given offset.\r\n *\r\n * @param text Full input string, used to calculate the line number\r\n * @param offset Current position in the input string\r\n * @returns The line number at the given offset\r\n */\r\n protected getLineNumber(text: string, offset: number): number {\r\n return text.substring(0, offset).split(/\\r\\n|\\r|\\n/).length;\r\n }\r\n\r\n /**\r\n * A custom pattern for matching indents\r\n *\r\n * @param text The full input string.\r\n * @param offset The offset at which to attempt a match\r\n * @param tokens Previously scanned tokens\r\n * @param groups Token Groups\r\n */\r\n protected indentMatcher(text: string, offset: number, tokens: IToken[], groups: Record): ReturnType {\r\n if (!this.isStartOfLine(text, offset)) {\r\n return null;\r\n }\r\n\r\n const { currIndentLevel, prevIndentLevel, match } = this.matchWhitespace(text, offset, tokens, groups);\r\n\r\n if (currIndentLevel <= prevIndentLevel) {\r\n // shallower indentation (should be matched by dedent)\r\n // or same indentation level (should be matched by whitespace and ignored)\r\n return null;\r\n }\r\n\r\n this.indentationStack.push(currIndentLevel);\r\n\r\n return match;\r\n }\r\n\r\n /**\r\n * A custom pattern for matching dedents\r\n *\r\n * @param text The full input string.\r\n * @param offset The offset at which to attempt a match\r\n * @param tokens Previously scanned tokens\r\n * @param groups Token Groups\r\n */\r\n protected dedentMatcher(text: string, offset: number, tokens: IToken[], groups: Record): ReturnType {\r\n if (!this.isStartOfLine(text, offset)) {\r\n return null;\r\n }\r\n\r\n const { currIndentLevel, prevIndentLevel, match } = this.matchWhitespace(text, offset, tokens, groups);\r\n\r\n if (currIndentLevel >= prevIndentLevel) {\r\n // bigger indentation (should be matched by indent)\r\n // or same indentation level (should be matched by whitespace and ignored)\r\n return null;\r\n }\r\n\r\n const matchIndentIndex = this.indentationStack.lastIndexOf(currIndentLevel);\r\n\r\n // Any dedent must match some previous indentation level.\r\n if (matchIndentIndex === -1) {\r\n this.diagnostics.push({\r\n severity: 'error',\r\n message: `Invalid dedent level ${currIndentLevel} at offset: ${offset}. Current indentation stack: ${this.indentationStack}`,\r\n offset,\r\n length: match?.[0]?.length ?? 0,\r\n line: this.getLineNumber(text, offset),\r\n column: 1\r\n });\r\n return null;\r\n }\r\n\r\n const numberOfDedents = this.indentationStack.length - matchIndentIndex - 1;\r\n const newlinesBeforeDedent = text.substring(0, offset).match(/[\\r\\n]+$/)?.[0].length ?? 1;\r\n\r\n for (let i = 0; i < numberOfDedents; i++) {\r\n const token = this.createIndentationTokenInstance(\r\n this.dedentTokenType,\r\n text,\r\n '', // Dedents are 0-width tokens\r\n offset - (newlinesBeforeDedent - 1), // Place the dedent after the first new line character\r\n );\r\n tokens.push(token);\r\n this.indentationStack.pop();\r\n }\r\n\r\n // Token already added, let the dedentation now be consumed as whitespace (if any) and ignored\r\n return null;\r\n }\r\n\r\n protected override buildTerminalToken(terminal: TerminalRule): TokenType {\r\n const tokenType = super.buildTerminalToken(terminal);\r\n const { indentTokenName, dedentTokenName, whitespaceTokenName } = this.options;\r\n\r\n if (tokenType.name === indentTokenName) {\r\n return this.indentTokenType;\r\n } else if (tokenType.name === dedentTokenName) {\r\n return this.dedentTokenType;\r\n } else if (tokenType.name === whitespaceTokenName) {\r\n return createToken({\r\n name: whitespaceTokenName,\r\n pattern: this.whitespaceRegExp,\r\n group: Lexer.SKIPPED,\r\n });\r\n }\r\n return tokenType;\r\n }\r\n\r\n /**\r\n * Resets the indentation stack between different runs of the lexer\r\n *\r\n * @param text Full text that was tokenized\r\n * @returns Remaining dedent tokens to match all previous indents at the end of the file\r\n */\r\n flushRemainingDedents(text: string): IToken[] {\r\n const remainingDedents: IToken[] = [];\r\n while (this.indentationStack.length > 1) {\r\n remainingDedents.push(\r\n this.createIndentationTokenInstance(this.dedentTokenType, text, '', text.length)\r\n );\r\n this.indentationStack.pop();\r\n }\r\n\r\n this.indentationStack = [0];\r\n return remainingDedents;\r\n }\r\n}\r\n\r\n/**\r\n * A lexer that is aware of indentation in the input text.\r\n * The only purpose of this lexer is to reset the internal state of the {@link IndentationAwareTokenBuilder}\r\n * between the tokenization of different text inputs.\r\n *\r\n * In your module, you can override the default lexer with this one as such:\r\n * ```ts\r\n * parser: {\r\n * TokenBuilder: () => new IndentationAwareTokenBuilder(),\r\n * Lexer: (services) => new IndentationAwareLexer(services),\r\n * }\r\n * ```\r\n */\r\nexport class IndentationAwareLexer extends DefaultLexer {\r\n\r\n protected readonly indentationTokenBuilder: IndentationAwareTokenBuilder;\r\n\r\n constructor(services: LangiumCoreServices) {\r\n super(services);\r\n if (services.parser.TokenBuilder instanceof IndentationAwareTokenBuilder) {\r\n this.indentationTokenBuilder = services.parser.TokenBuilder;\r\n } else {\r\n throw new Error('IndentationAwareLexer requires an accompanying IndentationAwareTokenBuilder');\r\n }\r\n }\r\n\r\n override tokenize(text: string, options: TokenizeOptions = DEFAULT_TOKENIZE_OPTIONS): LexerResult {\r\n const result = super.tokenize(text);\r\n\r\n // consuming all remaining dedents and remove them as they might not be serializable\r\n const report = result.report as IndentationLexingReport;\r\n if (options?.mode === 'full') {\r\n // auto-complete document with remaining dedents\r\n result.tokens.push(...report.remainingDedents);\r\n }\r\n report.remainingDedents = [];\r\n\r\n // remove any \"indent-dedent\" pair with an empty body as these are typically\r\n // added by comments or lines with just whitespace but have no real value\r\n const { indentTokenType, dedentTokenType } = this.indentationTokenBuilder;\r\n // Use tokenTypeIdx for fast comparison\r\n const indentTokenIdx = indentTokenType.tokenTypeIdx;\r\n const dedentTokenIdx = dedentTokenType.tokenTypeIdx;\r\n const cleanTokens: IToken[] = [];\r\n const length = result.tokens.length - 1;\r\n for (let i = 0; i < length; i++) {\r\n const token = result.tokens[i];\r\n const nextToken = result.tokens[i + 1];\r\n if (token.tokenTypeIdx === indentTokenIdx && nextToken.tokenTypeIdx === dedentTokenIdx) {\r\n i++;\r\n continue;\r\n }\r\n\r\n cleanTokens.push(token);\r\n }\r\n // Push last token separately\r\n if (length >= 0) {\r\n cleanTokens.push(result.tokens[length]);\r\n }\r\n result.tokens = cleanTokens;\r\n\r\n return result;\r\n }\r\n}\r\n", "/******************************************************************************\r\n * Copyright 2023 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nexport * from './caching.js';\r\nexport * from './event.js';\r\nexport * from './collections.js';\r\nexport * from './disposable.js';\r\nexport * from './errors.js';\r\nexport * from './grammar-loader.js';\r\nexport * from './promise-utils.js';\r\nexport * from './stream.js';\r\nexport * from './uri-utils.js';\r\n\r\nimport * as AstUtils from './ast-utils.js';\r\nimport * as Cancellation from './cancellation.js';\r\nimport * as CstUtils from './cst-utils.js';\r\nimport * as GrammarUtils from './grammar-utils.js';\r\nimport * as RegExpUtils from './regexp-utils.js';\r\nexport { AstUtils, Cancellation, CstUtils, GrammarUtils, RegExpUtils };\r\n", "/******************************************************************************\r\n * Copyright 2022 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport type { URI } from '../utils/uri-utils.js';\r\n\r\nexport interface FileSystemNode {\r\n readonly isFile: boolean;\r\n readonly isDirectory: boolean;\r\n readonly uri: URI;\r\n}\r\n\r\nexport type FileSystemFilter = (node: FileSystemNode) => boolean;\r\n\r\n/**\r\n * Provides methods to interact with an abstract file system. The default implementation is based on the node.js `fs` API.\r\n */\r\nexport interface FileSystemProvider {\r\n /**\r\n * Reads a document asynchronously from a given URI.\r\n * @returns The string content of the file with the specified URI.\r\n */\r\n readFile(uri: URI): Promise;\r\n /**\r\n * Reads the directory information for the given URI.\r\n * @returns The list of file system entries that are contained within the specified directory.\r\n */\r\n readDirectory(uri: URI): Promise;\r\n}\r\n\r\nexport class EmptyFileSystemProvider implements FileSystemProvider {\r\n\r\n readFile(): Promise {\r\n throw new Error('No file system is available.');\r\n }\r\n\r\n async readDirectory(): Promise {\r\n return [];\r\n }\r\n\r\n}\r\n\r\nexport const EmptyFileSystem = {\r\n fileSystemProvider: () => new EmptyFileSystemProvider()\r\n};\r\n", "/******************************************************************************\r\n * Copyright 2023 TypeFox GmbH\r\n * This program and the accompanying materials are made available under the\r\n * terms of the MIT License, which is available in the project root.\r\n ******************************************************************************/\r\n\r\nimport { createDefaultCoreModule, createDefaultSharedCoreModule } from '../default-module.js';\r\nimport type { Module } from '../dependency-injection.js';\r\nimport { inject } from '../dependency-injection.js';\r\nimport * as ast from '../languages/generated/ast.js';\r\nimport type { LangiumCoreServices, LangiumSharedCoreServices, PartialLangiumCoreServices, PartialLangiumSharedCoreServices } from '../services.js';\r\nimport type { Mutable } from '../syntax-tree.js';\r\nimport { EmptyFileSystem } from '../workspace/file-system-provider.js';\r\nimport { URI } from './uri-utils.js';\r\n\r\nconst minimalGrammarModule: Module = {\r\n Grammar: () => undefined as unknown as ast.Grammar,\r\n LanguageMetaData: () => ({\r\n caseInsensitive: false,\r\n fileExtensions: ['.langium'],\r\n languageId: 'langium'\r\n })\r\n};\r\n\r\nconst minimalSharedGrammarModule: Module = {\r\n AstReflection: () => new ast.LangiumGrammarAstReflection()\r\n};\r\n\r\nfunction createMinimalGrammarServices(): LangiumCoreServices {\r\n const shared = inject(\r\n createDefaultSharedCoreModule(EmptyFileSystem),\r\n minimalSharedGrammarModule\r\n );\r\n const grammar = inject(\r\n createDefaultCoreModule({ shared }),\r\n minimalGrammarModule\r\n );\r\n shared.ServiceRegistry.register(grammar);\r\n return grammar;\r\n}\r\n\r\n/**\r\n * Load a Langium grammar for your language from a JSON string. This is used by several services,\r\n * most notably the parser builder which interprets the grammar to create a parser.\r\n */\r\nexport function loadGrammarFromJson(json: string): ast.Grammar {\r\n const services = createMinimalGrammarServices();\r\n const astNode = services.serializer.JsonSerializer.deserialize(json) as Mutable;\r\n services.shared.workspace.LangiumDocumentFactory.fromModel(astNode, URI.parse(`memory://${astNode.name ?? 'grammar'}.langium`));\r\n return astNode;\r\n}\r\n", "var __defProp = Object.defineProperty;\nvar __name = (target, value) => __defProp(target, \"name\", { value, configurable: true });\n\n// src/language/generated/ast.ts\nimport { AbstractAstReflection } from \"langium\";\nvar Statement = \"Statement\";\nvar Architecture = \"Architecture\";\nfunction isArchitecture(item) {\n return reflection.isInstance(item, Architecture);\n}\n__name(isArchitecture, \"isArchitecture\");\nvar Axis = \"Axis\";\nvar Branch = \"Branch\";\nfunction isBranch(item) {\n return reflection.isInstance(item, Branch);\n}\n__name(isBranch, \"isBranch\");\nvar Checkout = \"Checkout\";\nvar CherryPicking = \"CherryPicking\";\nvar ClassDefStatement = \"ClassDefStatement\";\nvar Commit = \"Commit\";\nfunction isCommit(item) {\n return reflection.isInstance(item, Commit);\n}\n__name(isCommit, \"isCommit\");\nvar Curve = \"Curve\";\nvar Edge = \"Edge\";\nvar Entry = \"Entry\";\nvar GitGraph = \"GitGraph\";\nfunction isGitGraph(item) {\n return reflection.isInstance(item, GitGraph);\n}\n__name(isGitGraph, \"isGitGraph\");\nvar Group = \"Group\";\nvar Info = \"Info\";\nfunction isInfo(item) {\n return reflection.isInstance(item, Info);\n}\n__name(isInfo, \"isInfo\");\nvar Item = \"Item\";\nvar Junction = \"Junction\";\nvar Merge = \"Merge\";\nfunction isMerge(item) {\n return reflection.isInstance(item, Merge);\n}\n__name(isMerge, \"isMerge\");\nvar Option = \"Option\";\nvar Packet = \"Packet\";\nfunction isPacket(item) {\n return reflection.isInstance(item, Packet);\n}\n__name(isPacket, \"isPacket\");\nvar PacketBlock = \"PacketBlock\";\nfunction isPacketBlock(item) {\n return reflection.isInstance(item, PacketBlock);\n}\n__name(isPacketBlock, \"isPacketBlock\");\nvar Pie = \"Pie\";\nfunction isPie(item) {\n return reflection.isInstance(item, Pie);\n}\n__name(isPie, \"isPie\");\nvar PieSection = \"PieSection\";\nfunction isPieSection(item) {\n return reflection.isInstance(item, PieSection);\n}\n__name(isPieSection, \"isPieSection\");\nvar Radar = \"Radar\";\nvar Service = \"Service\";\nvar Treemap = \"Treemap\";\nfunction isTreemap(item) {\n return reflection.isInstance(item, Treemap);\n}\n__name(isTreemap, \"isTreemap\");\nvar TreemapRow = \"TreemapRow\";\nvar Direction = \"Direction\";\nvar Leaf = \"Leaf\";\nvar Section = \"Section\";\nvar MermaidAstReflection = class extends AbstractAstReflection {\n static {\n __name(this, \"MermaidAstReflection\");\n }\n getAllTypes() {\n return [Architecture, Axis, Branch, Checkout, CherryPicking, ClassDefStatement, Commit, Curve, Direction, Edge, Entry, GitGraph, Group, Info, Item, Junction, Leaf, Merge, Option, Packet, PacketBlock, Pie, PieSection, Radar, Section, Service, Statement, Treemap, TreemapRow];\n }\n computeIsSubtype(subtype, supertype) {\n switch (subtype) {\n case Branch:\n case Checkout:\n case CherryPicking:\n case Commit:\n case Merge: {\n return this.isSubtype(Statement, supertype);\n }\n case Direction: {\n return this.isSubtype(GitGraph, supertype);\n }\n case Leaf:\n case Section: {\n return this.isSubtype(Item, supertype);\n }\n default: {\n return false;\n }\n }\n }\n getReferenceType(refInfo) {\n const referenceId = `${refInfo.container.$type}:${refInfo.property}`;\n switch (referenceId) {\n case \"Entry:axis\": {\n return Axis;\n }\n default: {\n throw new Error(`${referenceId} is not a valid reference id.`);\n }\n }\n }\n getTypeMetaData(type) {\n switch (type) {\n case Architecture: {\n return {\n name: Architecture,\n properties: [\n { name: \"accDescr\" },\n { name: \"accTitle\" },\n { name: \"edges\", defaultValue: [] },\n { name: \"groups\", defaultValue: [] },\n { name: \"junctions\", defaultValue: [] },\n { name: \"services\", defaultValue: [] },\n { name: \"title\" }\n ]\n };\n }\n case Axis: {\n return {\n name: Axis,\n properties: [\n { name: \"label\" },\n { name: \"name\" }\n ]\n };\n }\n case Branch: {\n return {\n name: Branch,\n properties: [\n { name: \"name\" },\n { name: \"order\" }\n ]\n };\n }\n case Checkout: {\n return {\n name: Checkout,\n properties: [\n { name: \"branch\" }\n ]\n };\n }\n case CherryPicking: {\n return {\n name: CherryPicking,\n properties: [\n { name: \"id\" },\n { name: \"parent\" },\n { name: \"tags\", defaultValue: [] }\n ]\n };\n }\n case ClassDefStatement: {\n return {\n name: ClassDefStatement,\n properties: [\n { name: \"className\" },\n { name: \"styleText\" }\n ]\n };\n }\n case Commit: {\n return {\n name: Commit,\n properties: [\n { name: \"id\" },\n { name: \"message\" },\n { name: \"tags\", defaultValue: [] },\n { name: \"type\" }\n ]\n };\n }\n case Curve: {\n return {\n name: Curve,\n properties: [\n { name: \"entries\", defaultValue: [] },\n { name: \"label\" },\n { name: \"name\" }\n ]\n };\n }\n case Edge: {\n return {\n name: Edge,\n properties: [\n { name: \"lhsDir\" },\n { name: \"lhsGroup\", defaultValue: false },\n { name: \"lhsId\" },\n { name: \"lhsInto\", defaultValue: false },\n { name: \"rhsDir\" },\n { name: \"rhsGroup\", defaultValue: false },\n { name: \"rhsId\" },\n { name: \"rhsInto\", defaultValue: false },\n { name: \"title\" }\n ]\n };\n }\n case Entry: {\n return {\n name: Entry,\n properties: [\n { name: \"axis\" },\n { name: \"value\" }\n ]\n };\n }\n case GitGraph: {\n return {\n name: GitGraph,\n properties: [\n { name: \"accDescr\" },\n { name: \"accTitle\" },\n { name: \"statements\", defaultValue: [] },\n { name: \"title\" }\n ]\n };\n }\n case Group: {\n return {\n name: Group,\n properties: [\n { name: \"icon\" },\n { name: \"id\" },\n { name: \"in\" },\n { name: \"title\" }\n ]\n };\n }\n case Info: {\n return {\n name: Info,\n properties: [\n { name: \"accDescr\" },\n { name: \"accTitle\" },\n { name: \"title\" }\n ]\n };\n }\n case Item: {\n return {\n name: Item,\n properties: [\n { name: \"classSelector\" },\n { name: \"name\" }\n ]\n };\n }\n case Junction: {\n return {\n name: Junction,\n properties: [\n { name: \"id\" },\n { name: \"in\" }\n ]\n };\n }\n case Merge: {\n return {\n name: Merge,\n properties: [\n { name: \"branch\" },\n { name: \"id\" },\n { name: \"tags\", defaultValue: [] },\n { name: \"type\" }\n ]\n };\n }\n case Option: {\n return {\n name: Option,\n properties: [\n { name: \"name\" },\n { name: \"value\", defaultValue: false }\n ]\n };\n }\n case Packet: {\n return {\n name: Packet,\n properties: [\n { name: \"accDescr\" },\n { name: \"accTitle\" },\n { name: \"blocks\", defaultValue: [] },\n { name: \"title\" }\n ]\n };\n }\n case PacketBlock: {\n return {\n name: PacketBlock,\n properties: [\n { name: \"bits\" },\n { name: \"end\" },\n { name: \"label\" },\n { name: \"start\" }\n ]\n };\n }\n case Pie: {\n return {\n name: Pie,\n properties: [\n { name: \"accDescr\" },\n { name: \"accTitle\" },\n { name: \"sections\", defaultValue: [] },\n { name: \"showData\", defaultValue: false },\n { name: \"title\" }\n ]\n };\n }\n case PieSection: {\n return {\n name: PieSection,\n properties: [\n { name: \"label\" },\n { name: \"value\" }\n ]\n };\n }\n case Radar: {\n return {\n name: Radar,\n properties: [\n { name: \"accDescr\" },\n { name: \"accTitle\" },\n { name: \"axes\", defaultValue: [] },\n { name: \"curves\", defaultValue: [] },\n { name: \"options\", defaultValue: [] },\n { name: \"title\" }\n ]\n };\n }\n case Service: {\n return {\n name: Service,\n properties: [\n { name: \"icon\" },\n { name: \"iconText\" },\n { name: \"id\" },\n { name: \"in\" },\n { name: \"title\" }\n ]\n };\n }\n case Treemap: {\n return {\n name: Treemap,\n properties: [\n { name: \"accDescr\" },\n { name: \"accTitle\" },\n { name: \"title\" },\n { name: \"TreemapRows\", defaultValue: [] }\n ]\n };\n }\n case TreemapRow: {\n return {\n name: TreemapRow,\n properties: [\n { name: \"indent\" },\n { name: \"item\" }\n ]\n };\n }\n case Direction: {\n return {\n name: Direction,\n properties: [\n { name: \"accDescr\" },\n { name: \"accTitle\" },\n { name: \"dir\" },\n { name: \"statements\", defaultValue: [] },\n { name: \"title\" }\n ]\n };\n }\n case Leaf: {\n return {\n name: Leaf,\n properties: [\n { name: \"classSelector\" },\n { name: \"name\" },\n { name: \"value\" }\n ]\n };\n }\n case Section: {\n return {\n name: Section,\n properties: [\n { name: \"classSelector\" },\n { name: \"name\" }\n ]\n };\n }\n default: {\n return {\n name: type,\n properties: []\n };\n }\n }\n }\n};\nvar reflection = new MermaidAstReflection();\n\n// src/language/generated/grammar.ts\nimport { loadGrammarFromJson } from \"langium\";\nvar loadedInfoGrammar;\nvar InfoGrammar = /* @__PURE__ */ __name(() => loadedInfoGrammar ?? (loadedInfoGrammar = loadGrammarFromJson(`{\"$type\":\"Grammar\",\"isDeclared\":true,\"name\":\"Info\",\"imports\":[],\"rules\":[{\"$type\":\"ParserRule\",\"entry\":true,\"name\":\"Info\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@12\"},\"arguments\":[],\"cardinality\":\"*\"},{\"$type\":\"Keyword\",\"value\":\"info\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@12\"},\"arguments\":[],\"cardinality\":\"*\"},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"showInfo\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@12\"},\"arguments\":[],\"cardinality\":\"*\"}],\"cardinality\":\"?\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@2\"},\"arguments\":[],\"cardinality\":\"?\"}]},\"definesHiddenTokens\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"EOL\",\"dataType\":\"string\",\"definition\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@12\"},\"arguments\":[],\"cardinality\":\"+\"},{\"$type\":\"EndOfFile\"}]},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"TitleAndAccessibilities\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"accDescr\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@4\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"accTitle\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@5\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"title\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@6\"},\"arguments\":[]}}]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@1\"},\"arguments\":[]}],\"cardinality\":\"+\"},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"TerminalRule\",\"name\":\"BOOLEAN\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"boolean\"},\"definition\":{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"true\"}},{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"false\"}}]},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ACC_DESCR\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*accDescr(?:[\\\\\\\\t ]*:([^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[^\\\\\\\\n\\\\\\\\r]*)|\\\\\\\\s*{([^}]*)})/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ACC_TITLE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*accTitle[\\\\\\\\t ]*:(?:[^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[^\\\\\\\\n\\\\\\\\r]*)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"TITLE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*title(?:[\\\\\\\\t ][^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[\\\\\\\\t ][^\\\\\\\\n\\\\\\\\r]*|)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"FLOAT\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[0-9]+\\\\\\\\.[0-9]+(?!\\\\\\\\.)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"INT\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/0|[1-9][0-9]*(?!\\\\\\\\.)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"NUMBER\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"TerminalRuleCall\",\"rule\":{\"$ref\":\"#/rules@7\"}},{\"$type\":\"TerminalRuleCall\",\"rule\":{\"$ref\":\"#/rules@8\"}}]},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"STRING\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"string\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\"([^\\\\\"\\\\\\\\\\\\\\\\]|\\\\\\\\\\\\\\\\.)*\\\\\"|'([^'\\\\\\\\\\\\\\\\]|\\\\\\\\\\\\\\\\.)*'/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ID\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"string\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\w]([-\\\\\\\\w]*\\\\\\\\w)?/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"NEWLINE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\\\\r?\\\\\\\\n/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"WHITESPACE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]+/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"YAML\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/---[\\\\\\\\t ]*\\\\\\\\r?\\\\\\\\n(?:[\\\\\\\\S\\\\\\\\s]*?\\\\\\\\r?\\\\\\\\n)?---(?:\\\\\\\\r?\\\\\\\\n|(?!\\\\\\\\S))/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"DIRECTIVE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*%%{[\\\\\\\\S\\\\\\\\s]*?}%%(?:\\\\\\\\r?\\\\\\\\n|(?!\\\\\\\\S))/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"SINGLE_LINE_COMMENT\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*%%[^\\\\\\\\n\\\\\\\\r]*/\"},\"fragment\":false}],\"definesHiddenTokens\":false,\"hiddenTokens\":[],\"interfaces\":[],\"types\":[],\"usedGrammars\":[]}`)), \"InfoGrammar\");\nvar loadedPacketGrammar;\nvar PacketGrammar = /* @__PURE__ */ __name(() => loadedPacketGrammar ?? (loadedPacketGrammar = loadGrammarFromJson(`{\"$type\":\"Grammar\",\"isDeclared\":true,\"name\":\"Packet\",\"imports\":[],\"rules\":[{\"$type\":\"ParserRule\",\"entry\":true,\"name\":\"Packet\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@13\"},\"arguments\":[],\"cardinality\":\"*\"},{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"packet\"},{\"$type\":\"Keyword\",\"value\":\"packet-beta\"}]},{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@3\"},\"arguments\":[]},{\"$type\":\"Assignment\",\"feature\":\"blocks\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@1\"},\"arguments\":[]}},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@13\"},\"arguments\":[]}],\"cardinality\":\"*\"}]},\"definesHiddenTokens\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"PacketBlock\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"start\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@9\"},\"arguments\":[]}},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"-\"},{\"$type\":\"Assignment\",\"feature\":\"end\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@9\"},\"arguments\":[]}}],\"cardinality\":\"?\"}]},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"+\"},{\"$type\":\"Assignment\",\"feature\":\"bits\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@9\"},\"arguments\":[]}}]}]},{\"$type\":\"Keyword\",\"value\":\":\"},{\"$type\":\"Assignment\",\"feature\":\"label\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@11\"},\"arguments\":[]}},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@2\"},\"arguments\":[]}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"EOL\",\"dataType\":\"string\",\"definition\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@13\"},\"arguments\":[],\"cardinality\":\"+\"},{\"$type\":\"EndOfFile\"}]},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"TitleAndAccessibilities\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"accDescr\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@5\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"accTitle\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@6\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"title\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@7\"},\"arguments\":[]}}]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@2\"},\"arguments\":[]}],\"cardinality\":\"+\"},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"TerminalRule\",\"name\":\"BOOLEAN\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"boolean\"},\"definition\":{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"true\"}},{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"false\"}}]},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ACC_DESCR\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*accDescr(?:[\\\\\\\\t ]*:([^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[^\\\\\\\\n\\\\\\\\r]*)|\\\\\\\\s*{([^}]*)})/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ACC_TITLE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*accTitle[\\\\\\\\t ]*:(?:[^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[^\\\\\\\\n\\\\\\\\r]*)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"TITLE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*title(?:[\\\\\\\\t ][^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[\\\\\\\\t ][^\\\\\\\\n\\\\\\\\r]*|)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"FLOAT\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[0-9]+\\\\\\\\.[0-9]+(?!\\\\\\\\.)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"INT\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/0|[1-9][0-9]*(?!\\\\\\\\.)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"NUMBER\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"TerminalRuleCall\",\"rule\":{\"$ref\":\"#/rules@8\"}},{\"$type\":\"TerminalRuleCall\",\"rule\":{\"$ref\":\"#/rules@9\"}}]},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"STRING\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"string\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\"([^\\\\\"\\\\\\\\\\\\\\\\]|\\\\\\\\\\\\\\\\.)*\\\\\"|'([^'\\\\\\\\\\\\\\\\]|\\\\\\\\\\\\\\\\.)*'/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ID\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"string\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\w]([-\\\\\\\\w]*\\\\\\\\w)?/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"NEWLINE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\\\\r?\\\\\\\\n/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"WHITESPACE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]+/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"YAML\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/---[\\\\\\\\t ]*\\\\\\\\r?\\\\\\\\n(?:[\\\\\\\\S\\\\\\\\s]*?\\\\\\\\r?\\\\\\\\n)?---(?:\\\\\\\\r?\\\\\\\\n|(?!\\\\\\\\S))/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"DIRECTIVE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*%%{[\\\\\\\\S\\\\\\\\s]*?}%%(?:\\\\\\\\r?\\\\\\\\n|(?!\\\\\\\\S))/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"SINGLE_LINE_COMMENT\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*%%[^\\\\\\\\n\\\\\\\\r]*/\"},\"fragment\":false}],\"definesHiddenTokens\":false,\"hiddenTokens\":[],\"interfaces\":[],\"types\":[],\"usedGrammars\":[]}`)), \"PacketGrammar\");\nvar loadedPieGrammar;\nvar PieGrammar = /* @__PURE__ */ __name(() => loadedPieGrammar ?? (loadedPieGrammar = loadGrammarFromJson(`{\"$type\":\"Grammar\",\"isDeclared\":true,\"name\":\"Pie\",\"imports\":[],\"rules\":[{\"$type\":\"ParserRule\",\"entry\":true,\"name\":\"Pie\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@13\"},\"arguments\":[],\"cardinality\":\"*\"},{\"$type\":\"Keyword\",\"value\":\"pie\"},{\"$type\":\"Assignment\",\"feature\":\"showData\",\"operator\":\"?=\",\"terminal\":{\"$type\":\"Keyword\",\"value\":\"showData\"},\"cardinality\":\"?\"},{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@3\"},\"arguments\":[]},{\"$type\":\"Assignment\",\"feature\":\"sections\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@1\"},\"arguments\":[]}},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@13\"},\"arguments\":[]}],\"cardinality\":\"*\"}]},\"definesHiddenTokens\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"PieSection\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"label\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@11\"},\"arguments\":[]}},{\"$type\":\"Keyword\",\"value\":\":\"},{\"$type\":\"Assignment\",\"feature\":\"value\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@10\"},\"arguments\":[]}},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@2\"},\"arguments\":[]}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"EOL\",\"dataType\":\"string\",\"definition\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@13\"},\"arguments\":[],\"cardinality\":\"+\"},{\"$type\":\"EndOfFile\"}]},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"TitleAndAccessibilities\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"accDescr\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@5\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"accTitle\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@6\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"title\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@7\"},\"arguments\":[]}}]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@2\"},\"arguments\":[]}],\"cardinality\":\"+\"},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"TerminalRule\",\"name\":\"BOOLEAN\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"boolean\"},\"definition\":{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"true\"}},{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"false\"}}]},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ACC_DESCR\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*accDescr(?:[\\\\\\\\t ]*:([^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[^\\\\\\\\n\\\\\\\\r]*)|\\\\\\\\s*{([^}]*)})/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ACC_TITLE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*accTitle[\\\\\\\\t ]*:(?:[^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[^\\\\\\\\n\\\\\\\\r]*)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"TITLE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*title(?:[\\\\\\\\t ][^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[\\\\\\\\t ][^\\\\\\\\n\\\\\\\\r]*|)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"FLOAT\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[0-9]+\\\\\\\\.[0-9]+(?!\\\\\\\\.)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"INT\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/0|[1-9][0-9]*(?!\\\\\\\\.)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"NUMBER\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"TerminalRuleCall\",\"rule\":{\"$ref\":\"#/rules@8\"}},{\"$type\":\"TerminalRuleCall\",\"rule\":{\"$ref\":\"#/rules@9\"}}]},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"STRING\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"string\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\"([^\\\\\"\\\\\\\\\\\\\\\\]|\\\\\\\\\\\\\\\\.)*\\\\\"|'([^'\\\\\\\\\\\\\\\\]|\\\\\\\\\\\\\\\\.)*'/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ID\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"string\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\w]([-\\\\\\\\w]*\\\\\\\\w)?/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"NEWLINE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\\\\r?\\\\\\\\n/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"WHITESPACE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]+/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"YAML\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/---[\\\\\\\\t ]*\\\\\\\\r?\\\\\\\\n(?:[\\\\\\\\S\\\\\\\\s]*?\\\\\\\\r?\\\\\\\\n)?---(?:\\\\\\\\r?\\\\\\\\n|(?!\\\\\\\\S))/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"DIRECTIVE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*%%{[\\\\\\\\S\\\\\\\\s]*?}%%(?:\\\\\\\\r?\\\\\\\\n|(?!\\\\\\\\S))/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"SINGLE_LINE_COMMENT\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*%%[^\\\\\\\\n\\\\\\\\r]*/\"},\"fragment\":false}],\"definesHiddenTokens\":false,\"hiddenTokens\":[],\"interfaces\":[],\"types\":[],\"usedGrammars\":[]}`)), \"PieGrammar\");\nvar loadedArchitectureGrammar;\nvar ArchitectureGrammar = /* @__PURE__ */ __name(() => loadedArchitectureGrammar ?? (loadedArchitectureGrammar = loadGrammarFromJson(`{\"$type\":\"Grammar\",\"isDeclared\":true,\"name\":\"Architecture\",\"imports\":[],\"rules\":[{\"$type\":\"ParserRule\",\"entry\":true,\"name\":\"Architecture\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@23\"},\"arguments\":[],\"cardinality\":\"*\"},{\"$type\":\"Keyword\",\"value\":\"architecture-beta\"},{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@23\"},\"arguments\":[]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@13\"},\"arguments\":[]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@1\"},\"arguments\":[]}],\"cardinality\":\"*\"}]},\"definesHiddenTokens\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"Statement\",\"definition\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"groups\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@5\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"services\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@6\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"junctions\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@7\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"edges\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@8\"},\"arguments\":[]}}]},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"LeftPort\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\":\"},{\"$type\":\"Assignment\",\"feature\":\"lhsDir\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@9\"},\"arguments\":[]}}]},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"RightPort\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"rhsDir\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@9\"},\"arguments\":[]}},{\"$type\":\"Keyword\",\"value\":\":\"}]},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"Arrow\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@2\"},\"arguments\":[]},{\"$type\":\"Assignment\",\"feature\":\"lhsInto\",\"operator\":\"?=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@11\"},\"arguments\":[]},\"cardinality\":\"?\"},{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"--\"},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"-\"},{\"$type\":\"Assignment\",\"feature\":\"title\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@29\"},\"arguments\":[]}},{\"$type\":\"Keyword\",\"value\":\"-\"}]}]},{\"$type\":\"Assignment\",\"feature\":\"rhsInto\",\"operator\":\"?=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@11\"},\"arguments\":[]},\"cardinality\":\"?\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@3\"},\"arguments\":[]}]},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"Group\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"group\"},{\"$type\":\"Assignment\",\"feature\":\"id\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@22\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"icon\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@28\"},\"arguments\":[]},\"cardinality\":\"?\"},{\"$type\":\"Assignment\",\"feature\":\"title\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@29\"},\"arguments\":[]},\"cardinality\":\"?\"},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"in\"},{\"$type\":\"Assignment\",\"feature\":\"in\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@22\"},\"arguments\":[]}}],\"cardinality\":\"?\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@12\"},\"arguments\":[]}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"Service\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"service\"},{\"$type\":\"Assignment\",\"feature\":\"id\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@22\"},\"arguments\":[]}},{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"iconText\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@21\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"icon\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@28\"},\"arguments\":[]}}],\"cardinality\":\"?\"},{\"$type\":\"Assignment\",\"feature\":\"title\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@29\"},\"arguments\":[]},\"cardinality\":\"?\"},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"in\"},{\"$type\":\"Assignment\",\"feature\":\"in\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@22\"},\"arguments\":[]}}],\"cardinality\":\"?\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@12\"},\"arguments\":[]}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"Junction\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"junction\"},{\"$type\":\"Assignment\",\"feature\":\"id\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@22\"},\"arguments\":[]}},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"in\"},{\"$type\":\"Assignment\",\"feature\":\"in\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@22\"},\"arguments\":[]}}],\"cardinality\":\"?\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@12\"},\"arguments\":[]}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"Edge\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"lhsId\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@22\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"lhsGroup\",\"operator\":\"?=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@10\"},\"arguments\":[]},\"cardinality\":\"?\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@4\"},\"arguments\":[]},{\"$type\":\"Assignment\",\"feature\":\"rhsId\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@22\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"rhsGroup\",\"operator\":\"?=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@10\"},\"arguments\":[]},\"cardinality\":\"?\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@12\"},\"arguments\":[]}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"TerminalRule\",\"name\":\"ARROW_DIRECTION\",\"definition\":{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"L\"}},{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"R\"}}]},{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"T\"}}]},{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"B\"}}]},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ARROW_GROUP\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\\\\{group\\\\\\\\}/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ARROW_INTO\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/<|>/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"EOL\",\"dataType\":\"string\",\"definition\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@23\"},\"arguments\":[],\"cardinality\":\"+\"},{\"$type\":\"EndOfFile\"}]},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"TitleAndAccessibilities\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"accDescr\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@15\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"accTitle\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@16\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"title\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}}]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@12\"},\"arguments\":[]}],\"cardinality\":\"+\"},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"TerminalRule\",\"name\":\"BOOLEAN\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"boolean\"},\"definition\":{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"true\"}},{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"false\"}}]},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ACC_DESCR\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*accDescr(?:[\\\\\\\\t ]*:([^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[^\\\\\\\\n\\\\\\\\r]*)|\\\\\\\\s*{([^}]*)})/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ACC_TITLE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*accTitle[\\\\\\\\t ]*:(?:[^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[^\\\\\\\\n\\\\\\\\r]*)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"TITLE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*title(?:[\\\\\\\\t ][^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[\\\\\\\\t ][^\\\\\\\\n\\\\\\\\r]*|)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"FLOAT\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[0-9]+\\\\\\\\.[0-9]+(?!\\\\\\\\.)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"INT\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/0|[1-9][0-9]*(?!\\\\\\\\.)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"NUMBER\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"TerminalRuleCall\",\"rule\":{\"$ref\":\"#/rules@18\"}},{\"$type\":\"TerminalRuleCall\",\"rule\":{\"$ref\":\"#/rules@19\"}}]},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"STRING\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"string\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\"([^\\\\\"\\\\\\\\\\\\\\\\]|\\\\\\\\\\\\\\\\.)*\\\\\"|'([^'\\\\\\\\\\\\\\\\]|\\\\\\\\\\\\\\\\.)*'/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ID\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"string\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\w]([-\\\\\\\\w]*\\\\\\\\w)?/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"NEWLINE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\\\\r?\\\\\\\\n/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"WHITESPACE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]+/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"YAML\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/---[\\\\\\\\t ]*\\\\\\\\r?\\\\\\\\n(?:[\\\\\\\\S\\\\\\\\s]*?\\\\\\\\r?\\\\\\\\n)?---(?:\\\\\\\\r?\\\\\\\\n|(?!\\\\\\\\S))/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"DIRECTIVE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*%%{[\\\\\\\\S\\\\\\\\s]*?}%%(?:\\\\\\\\r?\\\\\\\\n|(?!\\\\\\\\S))/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"SINGLE_LINE_COMMENT\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*%%[^\\\\\\\\n\\\\\\\\r]*/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"name\":\"ARCH_ICON\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\\\\([\\\\\\\\w-:]+\\\\\\\\)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ARCH_TITLE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\\\\[[\\\\\\\\w ]+\\\\\\\\]/\"},\"fragment\":false,\"hidden\":false}],\"definesHiddenTokens\":false,\"hiddenTokens\":[],\"interfaces\":[],\"types\":[],\"usedGrammars\":[]}`)), \"ArchitectureGrammar\");\nvar loadedGitGraphGrammar;\nvar GitGraphGrammar = /* @__PURE__ */ __name(() => loadedGitGraphGrammar ?? (loadedGitGraphGrammar = loadGrammarFromJson(`{\"$type\":\"Grammar\",\"isDeclared\":true,\"name\":\"GitGraph\",\"imports\":[],\"rules\":[{\"$type\":\"ParserRule\",\"entry\":true,\"name\":\"GitGraph\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@19\"},\"arguments\":[],\"cardinality\":\"*\"},{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"gitGraph\"},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"gitGraph\"},{\"$type\":\"Keyword\",\"value\":\":\"}]},{\"$type\":\"Keyword\",\"value\":\"gitGraph:\"},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"gitGraph\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@2\"},\"arguments\":[]},{\"$type\":\"Keyword\",\"value\":\":\"}]}]},{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@19\"},\"arguments\":[]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@9\"},\"arguments\":[]},{\"$type\":\"Assignment\",\"feature\":\"statements\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@1\"},\"arguments\":[]}}],\"cardinality\":\"*\"}]},\"definesHiddenTokens\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"Statement\",\"definition\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@3\"},\"arguments\":[]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@4\"},\"arguments\":[]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@5\"},\"arguments\":[]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@6\"},\"arguments\":[]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@7\"},\"arguments\":[]}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"Direction\",\"definition\":{\"$type\":\"Assignment\",\"feature\":\"dir\",\"operator\":\"=\",\"terminal\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"LR\"},{\"$type\":\"Keyword\",\"value\":\"TB\"},{\"$type\":\"Keyword\",\"value\":\"BT\"}]}},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"Commit\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"commit\"},{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"id:\"},{\"$type\":\"Assignment\",\"feature\":\"id\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}}]},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"msg:\",\"cardinality\":\"?\"},{\"$type\":\"Assignment\",\"feature\":\"message\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}}]},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"tag:\"},{\"$type\":\"Assignment\",\"feature\":\"tags\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}}]},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"type:\"},{\"$type\":\"Assignment\",\"feature\":\"type\",\"operator\":\"=\",\"terminal\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"NORMAL\"},{\"$type\":\"Keyword\",\"value\":\"REVERSE\"},{\"$type\":\"Keyword\",\"value\":\"HIGHLIGHT\"}]}}]}],\"cardinality\":\"*\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@8\"},\"arguments\":[]}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"Branch\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"branch\"},{\"$type\":\"Assignment\",\"feature\":\"name\",\"operator\":\"=\",\"terminal\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@24\"},\"arguments\":[]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}]}},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"order:\"},{\"$type\":\"Assignment\",\"feature\":\"order\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@15\"},\"arguments\":[]}}],\"cardinality\":\"?\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@8\"},\"arguments\":[]}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"Merge\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"merge\"},{\"$type\":\"Assignment\",\"feature\":\"branch\",\"operator\":\"=\",\"terminal\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@24\"},\"arguments\":[]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}]}},{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"id:\"},{\"$type\":\"Assignment\",\"feature\":\"id\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}}]},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"tag:\"},{\"$type\":\"Assignment\",\"feature\":\"tags\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}}]},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"type:\"},{\"$type\":\"Assignment\",\"feature\":\"type\",\"operator\":\"=\",\"terminal\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"NORMAL\"},{\"$type\":\"Keyword\",\"value\":\"REVERSE\"},{\"$type\":\"Keyword\",\"value\":\"HIGHLIGHT\"}]}}]}],\"cardinality\":\"*\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@8\"},\"arguments\":[]}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"Checkout\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"checkout\"},{\"$type\":\"Keyword\",\"value\":\"switch\"}]},{\"$type\":\"Assignment\",\"feature\":\"branch\",\"operator\":\"=\",\"terminal\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@24\"},\"arguments\":[]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}]}},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@8\"},\"arguments\":[]}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"CherryPicking\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"cherry-pick\"},{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"id:\"},{\"$type\":\"Assignment\",\"feature\":\"id\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}}]},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"tag:\"},{\"$type\":\"Assignment\",\"feature\":\"tags\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}}]},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"parent:\"},{\"$type\":\"Assignment\",\"feature\":\"parent\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}}]}],\"cardinality\":\"*\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@8\"},\"arguments\":[]}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"EOL\",\"dataType\":\"string\",\"definition\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@19\"},\"arguments\":[],\"cardinality\":\"+\"},{\"$type\":\"EndOfFile\"}]},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"TitleAndAccessibilities\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"accDescr\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@11\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"accTitle\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@12\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"title\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@13\"},\"arguments\":[]}}]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@8\"},\"arguments\":[]}],\"cardinality\":\"+\"},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"TerminalRule\",\"name\":\"BOOLEAN\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"boolean\"},\"definition\":{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"true\"}},{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"false\"}}]},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ACC_DESCR\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*accDescr(?:[\\\\\\\\t ]*:([^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[^\\\\\\\\n\\\\\\\\r]*)|\\\\\\\\s*{([^}]*)})/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ACC_TITLE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*accTitle[\\\\\\\\t ]*:(?:[^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[^\\\\\\\\n\\\\\\\\r]*)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"TITLE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*title(?:[\\\\\\\\t ][^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[\\\\\\\\t ][^\\\\\\\\n\\\\\\\\r]*|)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"FLOAT\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[0-9]+\\\\\\\\.[0-9]+(?!\\\\\\\\.)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"INT\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/0|[1-9][0-9]*(?!\\\\\\\\.)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"NUMBER\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"TerminalRuleCall\",\"rule\":{\"$ref\":\"#/rules@14\"}},{\"$type\":\"TerminalRuleCall\",\"rule\":{\"$ref\":\"#/rules@15\"}}]},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"STRING\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"string\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\"([^\\\\\"\\\\\\\\\\\\\\\\]|\\\\\\\\\\\\\\\\.)*\\\\\"|'([^'\\\\\\\\\\\\\\\\]|\\\\\\\\\\\\\\\\.)*'/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ID\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"string\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\w]([-\\\\\\\\w]*\\\\\\\\w)?/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"NEWLINE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\\\\r?\\\\\\\\n/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"WHITESPACE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]+/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"YAML\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/---[\\\\\\\\t ]*\\\\\\\\r?\\\\\\\\n(?:[\\\\\\\\S\\\\\\\\s]*?\\\\\\\\r?\\\\\\\\n)?---(?:\\\\\\\\r?\\\\\\\\n|(?!\\\\\\\\S))/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"DIRECTIVE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*%%{[\\\\\\\\S\\\\\\\\s]*?}%%(?:\\\\\\\\r?\\\\\\\\n|(?!\\\\\\\\S))/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"SINGLE_LINE_COMMENT\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*%%[^\\\\\\\\n\\\\\\\\r]*/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"name\":\"REFERENCE\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"string\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\\\\w([-\\\\\\\\./\\\\\\\\w]*[-\\\\\\\\w])?/\"},\"fragment\":false,\"hidden\":false}],\"definesHiddenTokens\":false,\"hiddenTokens\":[],\"interfaces\":[],\"types\":[],\"usedGrammars\":[]}`)), \"GitGraphGrammar\");\nvar loadedRadarGrammar;\nvar RadarGrammar = /* @__PURE__ */ __name(() => loadedRadarGrammar ?? (loadedRadarGrammar = loadGrammarFromJson(`{\"$type\":\"Grammar\",\"isDeclared\":true,\"name\":\"Radar\",\"imports\":[],\"rules\":[{\"$type\":\"ParserRule\",\"entry\":true,\"name\":\"Radar\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@20\"},\"arguments\":[],\"cardinality\":\"*\"},{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"radar-beta\"},{\"$type\":\"Keyword\",\"value\":\"radar-beta:\"},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"radar-beta\"},{\"$type\":\"Keyword\",\"value\":\":\"}]}]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@20\"},\"arguments\":[],\"cardinality\":\"*\"},{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@10\"},\"arguments\":[]},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"axis\"},{\"$type\":\"Assignment\",\"feature\":\"axes\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@2\"},\"arguments\":[]}},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\",\"},{\"$type\":\"Assignment\",\"feature\":\"axes\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@2\"},\"arguments\":[]}}],\"cardinality\":\"*\"}]},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"curve\"},{\"$type\":\"Assignment\",\"feature\":\"curves\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@3\"},\"arguments\":[]}},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\",\"},{\"$type\":\"Assignment\",\"feature\":\"curves\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@3\"},\"arguments\":[]}}],\"cardinality\":\"*\"}]},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"options\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@7\"},\"arguments\":[]}},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\",\"},{\"$type\":\"Assignment\",\"feature\":\"options\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@7\"},\"arguments\":[]}}],\"cardinality\":\"*\"}]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@20\"},\"arguments\":[]}],\"cardinality\":\"*\"}]},\"definesHiddenTokens\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"Label\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\"[\"},{\"$type\":\"Assignment\",\"feature\":\"label\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@18\"},\"arguments\":[]}},{\"$type\":\"Keyword\",\"value\":\"]\"}]},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"Axis\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"name\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@19\"},\"arguments\":[]}},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@1\"},\"arguments\":[],\"cardinality\":\"?\"}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"Curve\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"name\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@19\"},\"arguments\":[]}},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@1\"},\"arguments\":[],\"cardinality\":\"?\"},{\"$type\":\"Keyword\",\"value\":\"{\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@4\"},\"arguments\":[]},{\"$type\":\"Keyword\",\"value\":\"}\"}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"Entries\",\"definition\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Group\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@20\"},\"arguments\":[],\"cardinality\":\"*\"},{\"$type\":\"Assignment\",\"feature\":\"entries\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@6\"},\"arguments\":[]}},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\",\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@20\"},\"arguments\":[],\"cardinality\":\"*\"},{\"$type\":\"Assignment\",\"feature\":\"entries\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@6\"},\"arguments\":[]}}],\"cardinality\":\"*\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@20\"},\"arguments\":[],\"cardinality\":\"*\"}]},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@20\"},\"arguments\":[],\"cardinality\":\"*\"},{\"$type\":\"Assignment\",\"feature\":\"entries\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@5\"},\"arguments\":[]}},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Keyword\",\"value\":\",\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@20\"},\"arguments\":[],\"cardinality\":\"*\"},{\"$type\":\"Assignment\",\"feature\":\"entries\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@5\"},\"arguments\":[]}}],\"cardinality\":\"*\"},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@20\"},\"arguments\":[],\"cardinality\":\"*\"}]}]},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"DetailedEntry\",\"returnType\":{\"$ref\":\"#/interfaces@0\"},\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"axis\",\"operator\":\"=\",\"terminal\":{\"$type\":\"CrossReference\",\"type\":{\"$ref\":\"#/rules@2\"},\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@19\"},\"arguments\":[]},\"deprecatedSyntax\":false}},{\"$type\":\"Keyword\",\"value\":\":\",\"cardinality\":\"?\"},{\"$type\":\"Assignment\",\"feature\":\"value\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"NumberEntry\",\"returnType\":{\"$ref\":\"#/interfaces@0\"},\"definition\":{\"$type\":\"Assignment\",\"feature\":\"value\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"Option\",\"definition\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"name\",\"operator\":\"=\",\"terminal\":{\"$type\":\"Keyword\",\"value\":\"showLegend\"}},{\"$type\":\"Assignment\",\"feature\":\"value\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@11\"},\"arguments\":[]}}]},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"name\",\"operator\":\"=\",\"terminal\":{\"$type\":\"Keyword\",\"value\":\"ticks\"}},{\"$type\":\"Assignment\",\"feature\":\"value\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}}]},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"name\",\"operator\":\"=\",\"terminal\":{\"$type\":\"Keyword\",\"value\":\"max\"}},{\"$type\":\"Assignment\",\"feature\":\"value\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}}]},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"name\",\"operator\":\"=\",\"terminal\":{\"$type\":\"Keyword\",\"value\":\"min\"}},{\"$type\":\"Assignment\",\"feature\":\"value\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}}]},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"name\",\"operator\":\"=\",\"terminal\":{\"$type\":\"Keyword\",\"value\":\"graticule\"}},{\"$type\":\"Assignment\",\"feature\":\"value\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@8\"},\"arguments\":[]}}]}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"TerminalRule\",\"name\":\"GRATICULE\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"string\"},\"definition\":{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"circle\"}},{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"polygon\"}}]},\"fragment\":false,\"hidden\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"EOL\",\"dataType\":\"string\",\"definition\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@20\"},\"arguments\":[],\"cardinality\":\"+\"},{\"$type\":\"EndOfFile\"}]},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"TitleAndAccessibilities\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"accDescr\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@12\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"accTitle\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@13\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"title\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@14\"},\"arguments\":[]}}]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@9\"},\"arguments\":[]}],\"cardinality\":\"+\"},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"TerminalRule\",\"name\":\"BOOLEAN\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"boolean\"},\"definition\":{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"true\"}},{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"false\"}}]},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ACC_DESCR\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*accDescr(?:[\\\\\\\\t ]*:([^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[^\\\\\\\\n\\\\\\\\r]*)|\\\\\\\\s*{([^}]*)})/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ACC_TITLE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*accTitle[\\\\\\\\t ]*:(?:[^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[^\\\\\\\\n\\\\\\\\r]*)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"TITLE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*title(?:[\\\\\\\\t ][^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[\\\\\\\\t ][^\\\\\\\\n\\\\\\\\r]*|)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"FLOAT\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[0-9]+\\\\\\\\.[0-9]+(?!\\\\\\\\.)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"INT\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/0|[1-9][0-9]*(?!\\\\\\\\.)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"NUMBER\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"number\"},\"definition\":{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"TerminalRuleCall\",\"rule\":{\"$ref\":\"#/rules@15\"}},{\"$type\":\"TerminalRuleCall\",\"rule\":{\"$ref\":\"#/rules@16\"}}]},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"STRING\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"string\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\"([^\\\\\"\\\\\\\\\\\\\\\\]|\\\\\\\\\\\\\\\\.)*\\\\\"|'([^'\\\\\\\\\\\\\\\\]|\\\\\\\\\\\\\\\\.)*'/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ID\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"string\"},\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\w]([-\\\\\\\\w]*\\\\\\\\w)?/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"NEWLINE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\\\\r?\\\\\\\\n/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"WHITESPACE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]+/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"YAML\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/---[\\\\\\\\t ]*\\\\\\\\r?\\\\\\\\n(?:[\\\\\\\\S\\\\\\\\s]*?\\\\\\\\r?\\\\\\\\n)?---(?:\\\\\\\\r?\\\\\\\\n|(?!\\\\\\\\S))/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"DIRECTIVE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*%%{[\\\\\\\\S\\\\\\\\s]*?}%%(?:\\\\\\\\r?\\\\\\\\n|(?!\\\\\\\\S))/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"SINGLE_LINE_COMMENT\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*%%[^\\\\\\\\n\\\\\\\\r]*/\"},\"fragment\":false}],\"interfaces\":[{\"$type\":\"Interface\",\"name\":\"Entry\",\"attributes\":[{\"$type\":\"TypeAttribute\",\"name\":\"axis\",\"isOptional\":true,\"type\":{\"$type\":\"ReferenceType\",\"referenceType\":{\"$type\":\"SimpleType\",\"typeRef\":{\"$ref\":\"#/rules@2\"}}}},{\"$type\":\"TypeAttribute\",\"name\":\"value\",\"type\":{\"$type\":\"SimpleType\",\"primitiveType\":\"number\"},\"isOptional\":false}],\"superTypes\":[]}],\"definesHiddenTokens\":false,\"hiddenTokens\":[],\"types\":[],\"usedGrammars\":[]}`)), \"RadarGrammar\");\nvar loadedTreemapGrammar;\nvar TreemapGrammar = /* @__PURE__ */ __name(() => loadedTreemapGrammar ?? (loadedTreemapGrammar = loadGrammarFromJson(`{\"$type\":\"Grammar\",\"isDeclared\":true,\"name\":\"Treemap\",\"rules\":[{\"$type\":\"ParserRule\",\"fragment\":true,\"name\":\"TitleAndAccessibilities\",\"definition\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"accDescr\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@2\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"accTitle\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@3\"},\"arguments\":[]}},{\"$type\":\"Assignment\",\"feature\":\"title\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@4\"},\"arguments\":[]}}],\"cardinality\":\"+\"},\"definesHiddenTokens\":false,\"entry\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"TerminalRule\",\"name\":\"BOOLEAN\",\"type\":{\"$type\":\"ReturnType\",\"name\":\"boolean\"},\"definition\":{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"true\"}},{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"false\"}}]},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ACC_DESCR\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*accDescr(?:[\\\\\\\\t ]*:([^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[^\\\\\\\\n\\\\\\\\r]*)|\\\\\\\\s*{([^}]*)})/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ACC_TITLE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*accTitle[\\\\\\\\t ]*:(?:[^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[^\\\\\\\\n\\\\\\\\r]*)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"TITLE\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[\\\\\\\\t ]*title(?:[\\\\\\\\t ][^\\\\\\\\n\\\\\\\\r]*?(?=%%)|[\\\\\\\\t ][^\\\\\\\\n\\\\\\\\r]*|)/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"ParserRule\",\"entry\":true,\"name\":\"Treemap\",\"returnType\":{\"$ref\":\"#/interfaces@4\"},\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@6\"},\"arguments\":[]},{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@0\"},\"arguments\":[]},{\"$type\":\"Assignment\",\"feature\":\"TreemapRows\",\"operator\":\"+=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@14\"},\"arguments\":[]}}],\"cardinality\":\"*\"}]},\"definesHiddenTokens\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"TerminalRule\",\"name\":\"TREEMAP_KEYWORD\",\"definition\":{\"$type\":\"TerminalAlternatives\",\"elements\":[{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"treemap-beta\"}},{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\"treemap\"}}]},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"CLASS_DEF\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/classDef\\\\\\\\s+([a-zA-Z_][a-zA-Z0-9_]+)(?:\\\\\\\\s+([^;\\\\\\\\r\\\\\\\\n]*))?(?:;)?/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"STYLE_SEPARATOR\",\"definition\":{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\":::\"}},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"SEPARATOR\",\"definition\":{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\":\"}},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"COMMA\",\"definition\":{\"$type\":\"CharacterRange\",\"left\":{\"$type\":\"Keyword\",\"value\":\",\"}},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"WS\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[ \\\\\\\\t]+/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"ML_COMMENT\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\\\\%\\\\\\\\%[^\\\\\\\\n]*/\"},\"fragment\":false},{\"$type\":\"TerminalRule\",\"hidden\":true,\"name\":\"NL\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\\\\r?\\\\\\\\n/\"},\"fragment\":false},{\"$type\":\"ParserRule\",\"name\":\"TreemapRow\",\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"indent\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@19\"},\"arguments\":[]},\"cardinality\":\"?\"},{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"item\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@16\"},\"arguments\":[]}},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@15\"},\"arguments\":[]}]}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"ClassDef\",\"dataType\":\"string\",\"definition\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@7\"},\"arguments\":[]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"Item\",\"returnType\":{\"$ref\":\"#/interfaces@0\"},\"definition\":{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@18\"},\"arguments\":[]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@17\"},\"arguments\":[]}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"Section\",\"returnType\":{\"$ref\":\"#/interfaces@1\"},\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"name\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@23\"},\"arguments\":[]}},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@8\"},\"arguments\":[]},{\"$type\":\"Assignment\",\"feature\":\"classSelector\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@20\"},\"arguments\":[]}}],\"cardinality\":\"?\"}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"ParserRule\",\"name\":\"Leaf\",\"returnType\":{\"$ref\":\"#/interfaces@2\"},\"definition\":{\"$type\":\"Group\",\"elements\":[{\"$type\":\"Assignment\",\"feature\":\"name\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@23\"},\"arguments\":[]}},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@19\"},\"arguments\":[],\"cardinality\":\"?\"},{\"$type\":\"Alternatives\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@9\"},\"arguments\":[]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@10\"},\"arguments\":[]}]},{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@19\"},\"arguments\":[],\"cardinality\":\"?\"},{\"$type\":\"Assignment\",\"feature\":\"value\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@22\"},\"arguments\":[]}},{\"$type\":\"Group\",\"elements\":[{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@8\"},\"arguments\":[]},{\"$type\":\"Assignment\",\"feature\":\"classSelector\",\"operator\":\"=\",\"terminal\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@20\"},\"arguments\":[]}}],\"cardinality\":\"?\"}]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"TerminalRule\",\"name\":\"INDENTATION\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[ \\\\\\\\t]{1,}/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"ID2\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[a-zA-Z_][a-zA-Z0-9_]*/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"TerminalRule\",\"name\":\"NUMBER2\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/[0-9_\\\\\\\\.\\\\\\\\,]+/\"},\"fragment\":false,\"hidden\":false},{\"$type\":\"ParserRule\",\"name\":\"MyNumber\",\"dataType\":\"number\",\"definition\":{\"$type\":\"RuleCall\",\"rule\":{\"$ref\":\"#/rules@21\"},\"arguments\":[]},\"definesHiddenTokens\":false,\"entry\":false,\"fragment\":false,\"hiddenTokens\":[],\"parameters\":[],\"wildcard\":false},{\"$type\":\"TerminalRule\",\"name\":\"STRING2\",\"definition\":{\"$type\":\"RegexToken\",\"regex\":\"/\\\\\"[^\\\\\"]*\\\\\"|'[^']*'/\"},\"fragment\":false,\"hidden\":false}],\"interfaces\":[{\"$type\":\"Interface\",\"name\":\"Item\",\"attributes\":[{\"$type\":\"TypeAttribute\",\"name\":\"name\",\"type\":{\"$type\":\"SimpleType\",\"primitiveType\":\"string\"},\"isOptional\":false},{\"$type\":\"TypeAttribute\",\"name\":\"classSelector\",\"isOptional\":true,\"type\":{\"$type\":\"SimpleType\",\"primitiveType\":\"string\"}}],\"superTypes\":[]},{\"$type\":\"Interface\",\"name\":\"Section\",\"superTypes\":[{\"$ref\":\"#/interfaces@0\"}],\"attributes\":[]},{\"$type\":\"Interface\",\"name\":\"Leaf\",\"superTypes\":[{\"$ref\":\"#/interfaces@0\"}],\"attributes\":[{\"$type\":\"TypeAttribute\",\"name\":\"value\",\"type\":{\"$type\":\"SimpleType\",\"primitiveType\":\"number\"},\"isOptional\":false}]},{\"$type\":\"Interface\",\"name\":\"ClassDefStatement\",\"attributes\":[{\"$type\":\"TypeAttribute\",\"name\":\"className\",\"type\":{\"$type\":\"SimpleType\",\"primitiveType\":\"string\"},\"isOptional\":false},{\"$type\":\"TypeAttribute\",\"name\":\"styleText\",\"type\":{\"$type\":\"SimpleType\",\"primitiveType\":\"string\"},\"isOptional\":false}],\"superTypes\":[]},{\"$type\":\"Interface\",\"name\":\"Treemap\",\"attributes\":[{\"$type\":\"TypeAttribute\",\"name\":\"TreemapRows\",\"type\":{\"$type\":\"ArrayType\",\"elementType\":{\"$type\":\"SimpleType\",\"typeRef\":{\"$ref\":\"#/rules@14\"}}},\"isOptional\":false},{\"$type\":\"TypeAttribute\",\"name\":\"title\",\"isOptional\":true,\"type\":{\"$type\":\"SimpleType\",\"primitiveType\":\"string\"}},{\"$type\":\"TypeAttribute\",\"name\":\"accTitle\",\"isOptional\":true,\"type\":{\"$type\":\"SimpleType\",\"primitiveType\":\"string\"}},{\"$type\":\"TypeAttribute\",\"name\":\"accDescr\",\"isOptional\":true,\"type\":{\"$type\":\"SimpleType\",\"primitiveType\":\"string\"}}],\"superTypes\":[]}],\"definesHiddenTokens\":false,\"hiddenTokens\":[],\"imports\":[],\"types\":[],\"usedGrammars\":[],\"$comment\":\"/**\\\\n * Treemap grammar for Langium\\\\n * Converted from mindmap grammar\\\\n *\\\\n * The ML_COMMENT and NL hidden terminals handle whitespace, comments, and newlines\\\\n * before the treemap keyword, allowing for empty lines and comments before the\\\\n * treemap declaration.\\\\n */\"}`)), \"TreemapGrammar\");\n\n// src/language/generated/module.ts\nvar InfoLanguageMetaData = {\n languageId: \"info\",\n fileExtensions: [\".mmd\", \".mermaid\"],\n caseInsensitive: false,\n mode: \"production\"\n};\nvar PacketLanguageMetaData = {\n languageId: \"packet\",\n fileExtensions: [\".mmd\", \".mermaid\"],\n caseInsensitive: false,\n mode: \"production\"\n};\nvar PieLanguageMetaData = {\n languageId: \"pie\",\n fileExtensions: [\".mmd\", \".mermaid\"],\n caseInsensitive: false,\n mode: \"production\"\n};\nvar ArchitectureLanguageMetaData = {\n languageId: \"architecture\",\n fileExtensions: [\".mmd\", \".mermaid\"],\n caseInsensitive: false,\n mode: \"production\"\n};\nvar GitGraphLanguageMetaData = {\n languageId: \"gitGraph\",\n fileExtensions: [\".mmd\", \".mermaid\"],\n caseInsensitive: false,\n mode: \"production\"\n};\nvar RadarLanguageMetaData = {\n languageId: \"radar\",\n fileExtensions: [\".mmd\", \".mermaid\"],\n caseInsensitive: false,\n mode: \"production\"\n};\nvar TreemapLanguageMetaData = {\n languageId: \"treemap\",\n fileExtensions: [\".mmd\", \".mermaid\"],\n caseInsensitive: false,\n mode: \"production\"\n};\nvar MermaidGeneratedSharedModule = {\n AstReflection: /* @__PURE__ */ __name(() => new MermaidAstReflection(), \"AstReflection\")\n};\nvar InfoGeneratedModule = {\n Grammar: /* @__PURE__ */ __name(() => InfoGrammar(), \"Grammar\"),\n LanguageMetaData: /* @__PURE__ */ __name(() => InfoLanguageMetaData, \"LanguageMetaData\"),\n parser: {}\n};\nvar PacketGeneratedModule = {\n Grammar: /* @__PURE__ */ __name(() => PacketGrammar(), \"Grammar\"),\n LanguageMetaData: /* @__PURE__ */ __name(() => PacketLanguageMetaData, \"LanguageMetaData\"),\n parser: {}\n};\nvar PieGeneratedModule = {\n Grammar: /* @__PURE__ */ __name(() => PieGrammar(), \"Grammar\"),\n LanguageMetaData: /* @__PURE__ */ __name(() => PieLanguageMetaData, \"LanguageMetaData\"),\n parser: {}\n};\nvar ArchitectureGeneratedModule = {\n Grammar: /* @__PURE__ */ __name(() => ArchitectureGrammar(), \"Grammar\"),\n LanguageMetaData: /* @__PURE__ */ __name(() => ArchitectureLanguageMetaData, \"LanguageMetaData\"),\n parser: {}\n};\nvar GitGraphGeneratedModule = {\n Grammar: /* @__PURE__ */ __name(() => GitGraphGrammar(), \"Grammar\"),\n LanguageMetaData: /* @__PURE__ */ __name(() => GitGraphLanguageMetaData, \"LanguageMetaData\"),\n parser: {}\n};\nvar RadarGeneratedModule = {\n Grammar: /* @__PURE__ */ __name(() => RadarGrammar(), \"Grammar\"),\n LanguageMetaData: /* @__PURE__ */ __name(() => RadarLanguageMetaData, \"LanguageMetaData\"),\n parser: {}\n};\nvar TreemapGeneratedModule = {\n Grammar: /* @__PURE__ */ __name(() => TreemapGrammar(), \"Grammar\"),\n LanguageMetaData: /* @__PURE__ */ __name(() => TreemapLanguageMetaData, \"LanguageMetaData\"),\n parser: {}\n};\n\n// src/language/common/valueConverter.ts\nimport { DefaultValueConverter } from \"langium\";\n\n// src/language/common/matcher.ts\nvar accessibilityDescrRegex = /accDescr(?:[\\t ]*:([^\\n\\r]*)|\\s*{([^}]*)})/;\nvar accessibilityTitleRegex = /accTitle[\\t ]*:([^\\n\\r]*)/;\nvar titleRegex = /title([\\t ][^\\n\\r]*|)/;\n\n// src/language/common/valueConverter.ts\nvar rulesRegexes = {\n ACC_DESCR: accessibilityDescrRegex,\n ACC_TITLE: accessibilityTitleRegex,\n TITLE: titleRegex\n};\nvar AbstractMermaidValueConverter = class extends DefaultValueConverter {\n static {\n __name(this, \"AbstractMermaidValueConverter\");\n }\n runConverter(rule, input, cstNode) {\n let value = this.runCommonConverter(rule, input, cstNode);\n if (value === void 0) {\n value = this.runCustomConverter(rule, input, cstNode);\n }\n if (value === void 0) {\n return super.runConverter(rule, input, cstNode);\n }\n return value;\n }\n runCommonConverter(rule, input, _cstNode) {\n const regex = rulesRegexes[rule.name];\n if (regex === void 0) {\n return void 0;\n }\n const match = regex.exec(input);\n if (match === null) {\n return void 0;\n }\n if (match[1] !== void 0) {\n return match[1].trim().replace(/[\\t ]{2,}/gm, \" \");\n }\n if (match[2] !== void 0) {\n return match[2].replace(/^\\s*/gm, \"\").replace(/\\s+$/gm, \"\").replace(/[\\t ]{2,}/gm, \" \").replace(/[\\n\\r]{2,}/gm, \"\\n\");\n }\n return void 0;\n }\n};\nvar CommonValueConverter = class extends AbstractMermaidValueConverter {\n static {\n __name(this, \"CommonValueConverter\");\n }\n runCustomConverter(_rule, _input, _cstNode) {\n return void 0;\n }\n};\n\n// src/language/common/tokenBuilder.ts\nimport { DefaultTokenBuilder } from \"langium\";\nvar AbstractMermaidTokenBuilder = class extends DefaultTokenBuilder {\n static {\n __name(this, \"AbstractMermaidTokenBuilder\");\n }\n constructor(keywords) {\n super();\n this.keywords = new Set(keywords);\n }\n buildKeywordTokens(rules, terminalTokens, options) {\n const tokenTypes = super.buildKeywordTokens(rules, terminalTokens, options);\n tokenTypes.forEach((tokenType) => {\n if (this.keywords.has(tokenType.name) && tokenType.PATTERN !== void 0) {\n tokenType.PATTERN = new RegExp(tokenType.PATTERN.toString() + \"(?:(?=%%)|(?!\\\\S))\");\n }\n });\n return tokenTypes;\n }\n};\nvar CommonTokenBuilder = class extends AbstractMermaidTokenBuilder {\n static {\n __name(this, \"CommonTokenBuilder\");\n }\n};\n\nexport {\n __name,\n Statement,\n Architecture,\n isArchitecture,\n Branch,\n isBranch,\n Commit,\n isCommit,\n GitGraph,\n isGitGraph,\n Info,\n isInfo,\n Merge,\n isMerge,\n Packet,\n isPacket,\n PacketBlock,\n isPacketBlock,\n Pie,\n isPie,\n PieSection,\n isPieSection,\n Radar,\n Treemap,\n isTreemap,\n MermaidGeneratedSharedModule,\n InfoGeneratedModule,\n PacketGeneratedModule,\n PieGeneratedModule,\n ArchitectureGeneratedModule,\n GitGraphGeneratedModule,\n RadarGeneratedModule,\n TreemapGeneratedModule,\n AbstractMermaidValueConverter,\n CommonValueConverter,\n AbstractMermaidTokenBuilder,\n CommonTokenBuilder\n};\n"], + "mappings": "+dAAA,IAAAA,GAAAC,GAAAC,IAAA,cAKA,OAAO,eAAeA,GAAS,aAAc,CAAE,MAAO,EAAK,CAAC,EAC5D,IAAIC,GACJ,SAASC,IAAM,CACX,GAAID,KAAS,OACT,MAAM,IAAI,MAAM,wCAAwC,EAE5D,OAAOA,EACX,EACC,SAAUC,EAAK,CACZ,SAASC,EAAQC,EAAK,CAClB,GAAIA,IAAQ,OACR,MAAM,IAAI,MAAM,uCAAuC,EAE3DH,GAAOG,CACX,CACAF,EAAI,QAAUC,CAClB,GAAGD,KAAQA,GAAM,CAAC,EAAE,EACpBF,GAAQ,QAAUE,KCtBlB,IAAAG,GAAAC,GAAAC,IAAA,cAKA,OAAO,eAAeA,GAAS,aAAc,CAAE,MAAO,EAAK,CAAC,EAC5DA,GAAQ,YAAcA,GAAQ,MAAQA,GAAQ,KAAOA,GAAQ,MAAQA,GAAQ,OAASA,GAAQ,OAASA,GAAQ,QAAU,OACzH,SAASC,GAA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AS,EAAI,oBAAoB,EAEtF,CAAC,EACMD,CACT,CACF,EACIE,GAAqB,cAAcR,EAA4B,CACjE,MAAO,CACLjG,EAAO,KAAM,oBAAoB,CACnC,CACF", + "names": ["require_ral", "__commonJSMin", "exports", "_ral", "RAL", "install", "ral", "require_is", "__commonJSMin", "exports", "boolean", "value", "string", "number", "error", "func", "array", "stringArray", "elem", "require_events", "__commonJSMin", "exports", "ral_1", "Event", "_disposable", "CallbackList", "callback", "context", "bucket", "foundCallbackWithDifferentContext", "len", "args", "ret", "callbacks", "contexts", "i", "e", "Emitter", "_Emitter", "_options", "listener", "thisArgs", "disposables", "result", "event", "require_cancellation", "__commonJSMin", "exports", "ral_1", "Is", "events_1", "CancellationToken", "is", "value", "candidate", "shortcutEvent", "callback", "context", "handle", "MutableToken", "CancellationTokenSource", "lib_exports", "__export", "AbstractAstReflection", "AbstractCstNode", "AbstractLangiumParser", "AbstractParserErrorMessageProvider", "AbstractThreadedAsyncParser", "ast_utils_exports", "BiMap", "cancellation_exports", "CompositeCstNodeImpl", "ContextCache", "CstNodeBuilder", "cst_utils_exports", "DEFAULT_TOKENIZE_OPTIONS", "DONE_RESULT", "DatatypeSymbol", "DefaultAstNodeDescriptionProvider", "DefaultAstNodeLocator", "DefaultAsyncParser", "DefaultCommentProvider", "DefaultConfigurationProvider", "DefaultDocumentBuilder", "DefaultDocumentValidator", "DefaultHydrator", "DefaultIndexManager", "DefaultJsonSerializer", "DefaultLangiumDocumentFactory", "DefaultLangiumDocuments", "DefaultLexer", "DefaultLexerErrorMessageProvider", "DefaultLinker", "DefaultNameProvider", "DefaultReferenceDescriptionProvider", "DefaultReferences", "DefaultScopeComputation", "DefaultScopeProvider", "DefaultServiceRegistry", "DefaultTokenBuilder", "DefaultValueConverter", "DefaultWorkspaceLock", "DefaultWorkspaceManager", "Deferred", "Disposable", "DisposableCache", "DocumentCache", "DocumentState", "DocumentValidator", "EMPTY_SCOPE", "EMPTY_STREAM", "EmptyFileSystem", "EmptyFileSystemProvider", "ErrorWithLocation", "ast_exports", "grammar_utils_exports", "IndentationAwareLexer", "IndentationAwareTokenBuilder", "JSDocDocumentationProvider", "LangiumCompletionParser", "LangiumParser", "LangiumParserErrorMessageProvider", "LeafCstNodeImpl", "LexingMode", "MapScope", "Module", "MultiMap", "OperationCancelled", "ParserWorker", "Reduction", "regexp_utils_exports", "RootCstNodeImpl", "SimpleCache", "StreamImpl", "StreamScope", "TextDocument", "TreeStreamImpl", "URI", "UriUtils", "ValidationCategory", "ValidationRegistry", "ValueConverter", "WorkspaceCache", "assertUnreachable", "createCompletionParser", "createDefaultCoreModule", "createDefaultSharedCoreModule", "createGrammarConfig", "createLangiumParser", "createParser", "delayNextTick", "diagnosticData", "eagerLoad", "getDiagnosticRange", "indentationBuilderDefaultOptions", "inject", "interruptAndCheck", "isAstNode", "isAstNodeDescription", "isAstNodeWithComment", "isCompositeCstNode", "isIMultiModeLexerDefinition", "isJSDoc", "isLeafCstNode", "isLinkingError", "isNamed", "isOperationCancelled", "isReference", "isRootCstNode", "isTokenTypeArray", "isTokenTypeDictionary", "loadGrammarFromJson", "parseJSDoc", "prepareLangiumParser", "setInterruptionPeriod", "startCancelableOperation", "stream", "toDiagnosticData", "toDiagnosticSeverity", "cst_utils_exports", "__export", "DefaultNameRegexp", "RangeComparison", "compareRange", "findCommentNode", "findDeclarationNodeAtOffset", "findLeafNodeAtOffset", "findLeafNodeBeforeOffset", "flattenCst", "getInteriorNodes", "getNextNode", "getPreviousNode", "getStartlineNode", "inRange", "isChildNode", "isCommentNode", "streamCst", "toDocumentSegment", "tokenToRange", "isAstNode", "obj", "isReference", "isAstNodeDescription", "isLinkingError", "AbstractAstReflection", "node", "type", "subtype", "supertype", "nested", "existing", "result", "allTypes", "types", "possibleSubType", "isCompositeCstNode", "isLeafCstNode", "isRootCstNode", "StreamImpl", "_StreamImpl", "startFn", "nextFn", "iterator", "count", "next", "result", "keyFn", "valueFn", "entryStream", "element", "other", "state", "DONE_RESULT", "separator", "value", "addSeparator", "toString", "searchElement", "fromIndex", "index", "predicate", "callbackfn", "done", "initialValue", "previousValue", "mapped", "isIterable", "depth", "stream", "skipCount", "i", "maxSize", "by", "key", "otherKeySet", "item", "e", "ownKey", "obj", "EMPTY_STREAM", "collections", "collection", "TreeStreamImpl", "root", "children", "options", "Reduction", "sum", "b", "product", "min", "max", "streamCst", "node", "TreeStreamImpl", "element", "isCompositeCstNode", "flattenCst", "isLeafCstNode", "isChildNode", "child", "parent", "tokenToRange", "token", "toDocumentSegment", "offset", "end", "range", "RangeComparison", "compareRange", "to", "startInside", "endInside", "inRange", "DefaultNameRegexp", "findDeclarationNodeAtOffset", "cstNode", "nameRegexp", "localOffset", "textAtOffset", "findLeafNodeAtOffset", "findCommentNode", "commentNames", "previous", "getPreviousNode", "isCommentNode", "isRootCstNode", "endIndex", "e", "searchResult", "binarySearch", "findLeafNodeBeforeOffset", "closest", "left", "right", "closestNode", "middle", "middleNode", "hidden", "index", "getNextNode", "last", "next", "getStartlineNode", "line", "selfIndex", "getInteriorNodes", "start", "commonParent", "getCommonParent", "a", "b", "aParents", "getParentChain", "bParents", "current", "i", "aParent", "bParent", "chain", "grammar_utils_exports", "__export", "findAssignment", "findNameAssignment", "findNodeForKeyword", "findNodeForProperty", "findNodesForKeyword", "findNodesForKeywordInternal", "findNodesForProperty", "getActionAtElement", "getActionType", "getAllReachableRules", "getCrossReferenceTerminal", "getEntryRule", "getExplicitRuleType", "getHiddenRules", "getRuleType", "getRuleTypeName", "getTypeName", "isArrayCardinality", "isArrayOperator", "isCommentTerminal", "isDataType", "isDataTypeRule", "isOptionalCardinality", "terminalRegex", "ErrorWithLocation", "node", "message", "assertUnreachable", "_", "ast_exports", "__export", "AbstractElement", "AbstractRule", "AbstractType", "Action", "Alternatives", "ArrayLiteral", "ArrayType", "Assignment", "BooleanLiteral", "CharacterRange", "Condition", "Conjunction", "CrossReference", "Disjunction", "EndOfFile", "Grammar", "GrammarImport", "Group", "InferredType", "Interface", "Keyword", "LangiumGrammarAstReflection", "LangiumGrammarTerminals", "NamedArgument", "NegatedToken", "Negation", "NumberLiteral", "Parameter", "ParameterReference", "ParserRule", "ReferenceType", "RegexToken", "ReturnType", "RuleCall", "SimpleType", "StringLiteral", "TerminalAlternatives", "TerminalGroup", "TerminalRule", "TerminalRuleCall", "Type", "TypeAttribute", "TypeDefinition", "UnionType", "UnorderedGroup", "UntilToken", "ValueLiteral", "Wildcard", "isAbstractElement", "isAbstractRule", "isAbstractType", "isAction", "isAlternatives", "isArrayLiteral", "isArrayType", "isAssignment", "isBooleanLiteral", "isCharacterRange", "isCondition", "isConjunction", "isCrossReference", "isDisjunction", "isEndOfFile", "isFeatureName", "isGrammar", "isGrammarImport", "isGroup", "isInferredType", "isInterface", "isKeyword", "isNamedArgument", "isNegatedToken", "isNegation", "isNumberLiteral", "isParameter", "isParameterReference", "isParserRule", "isPrimitiveType", "isReferenceType", "isRegexToken", "isReturnType", "isRuleCall", "isSimpleType", "isStringLiteral", "isTerminalAlternatives", "isTerminalGroup", "isTerminalRule", "isTerminalRuleCall", "isType", "isTypeAttribute", "isTypeDefinition", "isUnionType", "isUnorderedGroup", "isUntilToken", "isValueLiteral", "isWildcard", "reflection", "LangiumGrammarTerminals", "AbstractRule", "isAbstractRule", "item", "reflection", "AbstractType", "isAbstractType", "Condition", "isCondition", "isFeatureName", "isPrimitiveType", "TypeDefinition", "isTypeDefinition", "ValueLiteral", "isValueLiteral", "AbstractElement", "isAbstractElement", "ArrayLiteral", "isArrayLiteral", "ArrayType", "isArrayType", "BooleanLiteral", "isBooleanLiteral", "Conjunction", "isConjunction", "Disjunction", "isDisjunction", "Grammar", "isGrammar", "GrammarImport", "isGrammarImport", "InferredType", "isInferredType", "Interface", "isInterface", "NamedArgument", "isNamedArgument", "Negation", "isNegation", "NumberLiteral", "isNumberLiteral", "Parameter", "isParameter", "ParameterReference", "isParameterReference", "ParserRule", "isParserRule", "ReferenceType", "isReferenceType", "ReturnType", "isReturnType", "SimpleType", "isSimpleType", "StringLiteral", "isStringLiteral", "TerminalRule", "isTerminalRule", "Type", "isType", "TypeAttribute", "isTypeAttribute", "UnionType", "isUnionType", "Action", "isAction", "Alternatives", "isAlternatives", "Assignment", "isAssignment", "CharacterRange", "isCharacterRange", "CrossReference", "isCrossReference", "EndOfFile", "isEndOfFile", "Group", "isGroup", "Keyword", "isKeyword", "NegatedToken", "isNegatedToken", "RegexToken", "isRegexToken", "RuleCall", "isRuleCall", "TerminalAlternatives", "isTerminalAlternatives", "TerminalGroup", "isTerminalGroup", "TerminalRuleCall", "isTerminalRuleCall", "UnorderedGroup", "isUnorderedGroup", "UntilToken", "isUntilToken", "Wildcard", "isWildcard", "LangiumGrammarAstReflection", "AbstractAstReflection", "subtype", "supertype", "refInfo", "referenceId", "type", "ast_utils_exports", "__export", "assignMandatoryProperties", "copyAstNode", "findLocalReferences", "findRootNode", "getContainerOfType", "getDocument", "hasContainerOfType", "linkContentToContainer", "streamAllContents", "streamAst", "streamContents", "streamReferences", "linkContentToContainer", "node", "name", "value", "item", "index", "isAstNode", "getContainerOfType", "typePredicate", "hasContainerOfType", "predicate", "getDocument", "result", "findRootNode", "streamContents", "options", "range", "StreamImpl", "state", "property", "isAstNodeInRange", "element", "DONE_RESULT", "streamAllContents", "root", "TreeStreamImpl", "streamAst", "astNode", "nodeRange", "_a", "inRange", "streamReferences", "isReference", "findLocalReferences", "targetNode", "lookup", "refs", "refInfo", "stream", "assignMandatoryProperties", "reflection", "typeMetaData", "genericNode", "copyDefaultValue", "propertyType", "copyAstNode", "buildReference", "copy", "copiedArray", "regexp_utils_exports", "__export", "NEWLINE_REGEXP", "escapeRegExp", "getCaseInsensitivePattern", "getTerminalParts", "isMultilineComment", "isWhitespace", "partialMatches", "partialRegExp", "whitespaceCharacters", "cc", "char", "insertToSet", "item", "set", "subItem", "addFlag", "flagObj", "flagKey", "x", "ASSERT_EXISTS", "obj", "ASSERT_NEVER_REACH_HERE", "isCharacter", "digitsCharCodes", "i", "cc", "wordCharCodes", "whitespaceCodes", "hexDigitPattern", "decimalPattern", "decimalPatternNoZero", "RegExpParser", "newState", "input", "value", "flags", "addFlag", "alts", "begin", "terms", "type", "ASSERT_EXISTS", "disjunction", "ASSERT_NEVER_REACH_HERE", "isBacktracking", "range", "atLeast", "atMost", "atom", "cc", "set", "complement", "digitsCharCodes", "whitespaceCodes", "wordCharCodes", "escapeCode", "letter", "escapedChar", "nextChar", "from", "isFromSingleChar", "isCharacter", "to", "isToSingleChar", "insertToSet", "capturing", "groupAst", "number", "howMuch", "prevState", "howMany", "hexString", "hexChar", "char", "BaseRegExpVisitor", "node", "key", "child", "subChild", "NEWLINE_REGEXP", "regexpParser", "RegExpParser", "TerminalRegExpVisitor", "BaseRegExpVisitor", "regex", "node", "char", "escapedChar", "escapeRegExp", "set", "visitor", "getTerminalParts", "regexp", "pattern", "parts", "alternative", "isMultilineComment", "whitespaceCharacters", "isWhitespace", "value", "ws", "getCaseInsensitivePattern", "keyword", "letter", "partialMatches", "input", "partial", "partialRegExp", "match", "re", "source", "i", "process", "result", "tmp", "appendRaw", "nbChars", "appendOptional", "getEntryRule", "grammar", "isParserRule", "getHiddenRules", "isTerminalRule", "getAllReachableRules", "allTerminals", "ruleNames", "entryRule", "topMostRules", "rule", "ruleDfs", "rules", "visitedSet", "streamAllContents", "node", "isRuleCall", "isTerminalRuleCall", "refRule", "getCrossReferenceTerminal", "crossRef", "nameAssigment", "findNameAssignment", "isCommentTerminal", "terminalRule", "isWhitespace", "terminalRegex", "findNodesForProperty", "property", "findNodesForPropertyInternal", "findNodeForProperty", "index", "nodes", "element", "first", "nodeFeature", "getContainerOfType", "isAssignment", "isCompositeCstNode", "e", "findNodesForKeyword", "keyword", "findNodesForKeywordInternal", "findNodeForKeyword", "isKeyword", "treeIterator", "streamCst", "result", "keywordNodes", "childNode", "findAssignment", "cstNode", "astNode", "_a", "assignment", "type", "startNode", "isInferredType", "isAction", "assertUnreachable", "findNameAssignmentInternal", "cache", "go", "refType", "childAssignment", "isSimpleType", "getActionAtElement", "parent", "isGroup", "elements", "item", "action", "isAbstractElement", "isOptionalCardinality", "cardinality", "isArrayCardinality", "isArrayOperator", "operator", "isDataTypeRule", "isDataTypeRuleInternal", "visited", "isDataType", "isDataTypeInternal", "isArrayType", "isReferenceType", "isUnionType", "ref", "isType", "getExplicitRuleType", "isInterface", "getTypeName", "isReturnType", "actionType", "getActionType", "getRuleTypeName", "_b", "_c", "getRuleType", "flags", "source", "abstractElementToRegex", "flagText", "value", "name", "WILDCARD", "isTerminalAlternatives", "terminalAlternativesToRegex", "isTerminalGroup", "terminalGroupToRegex", "isCharacterRange", "characterRangeToRegex", "withCardinality", "isNegatedToken", "negateTokenToRegex", "isUntilToken", "untilTokenToRegex", "isRegexToken", "lastSlash", "regexFlags", "isWildcard", "alternatives", "group", "until", "negate", "range", "keywordToRegex", "escapeRegExp", "regex", "options", "createGrammarConfig", "services", "rules", "grammar", "rule", "isTerminalRule", "isCommentTerminal", "isMultilineComment", "terminalRegex", "DefaultNameRegexp", "PRINT_ERROR", "msg", "PRINT_WARNING", "timer", "func", "start", "val", "toFastProperties", "toBecomeFast", "FakeConstructor", "fakeInstance", "fakeAccess", "tokenLabel", "tokType", "hasTokenLabel", "obj", "isString_default", "AbstractProduction", "value", "_definition", "visitor", "forEach_default", "prod", "NonTerminal", "options", "assign_default", "pickBy_default", "v", "definition", "Rule", "Alternative", "Option", "RepetitionMandatory", "RepetitionMandatoryWithSeparator", "Repetition", "RepetitionWithSeparator", "Alternation", "Terminal", "serializeGrammar", "topRules", "map_default", "serializeProduction", "node", "convertDefinition", "serializedNonTerminal", "serializedTerminal", "pattern", "isRegExp_default", "GAstVisitor", "node", "nodeAny", "NonTerminal", "Alternative", "Option", "RepetitionMandatory", "RepetitionMandatoryWithSeparator", "RepetitionWithSeparator", "Repetition", "Alternation", "Terminal", "Rule", "isSequenceProd", "prod", "Alternative", "Option", "Repetition", "RepetitionMandatory", "RepetitionMandatoryWithSeparator", "RepetitionWithSeparator", "Terminal", "Rule", "isOptionalProd", "alreadyVisited", "Alternation", "some_default", "subProd", "NonTerminal", "includes_default", "AbstractProduction", "every_default", "isBranchingProd", "getProductionDslName", "RestWalker", "prod", "prevRest", "forEach_default", "subProd", "index", "currRest", "drop_default", "NonTerminal", "Terminal", "Alternative", "Option", "RepetitionMandatory", "RepetitionMandatoryWithSeparator", "RepetitionWithSeparator", "Repetition", "Alternation", "terminal", "refProd", "flatProd", "fullOrRest", "optionProd", "atLeastOneProd", "fullAtLeastOneRest", "atLeastOneSepProd", "fullAtLeastOneSepRest", "restForRepetitionWithSeparator", "manyProd", "fullManyRest", "manySepProd", "fullManySepRest", "orProd", "alt", "prodWrapper", "repSepProd", "first", "prod", "NonTerminal", "Terminal", "firstForTerminal", "isSequenceProd", "firstForSequence", "isBranchingProd", "firstForBranching", "firstSet", "seq", "nextSubProdIdx", "hasInnerProdsRemaining", "currSubProd", "isLastInnerProdOptional", "isOptionalProd", "uniq_default", "allAlternativesFirsts", "map_default", "innerProd", "flatten_default", "terminal", "IN", "ResyncFollowsWalker", "RestWalker", "topProd", "terminal", "currRest", "prevRest", "refProd", "followName", "buildBetweenProdsFollowPrefix", "fullRest", "restProd", "Alternative", "t_in_topProd_follows", "first", "computeAllProdsFollows", "topProductions", "reSyncFollows", "forEach_default", "currRefsFollow", "assign_default", "inner", "occurenceInParent", "IN", "regExpAstCache", "regExpParser", "RegExpParser", "getRegExpAst", "regExp", "regExpStr", "regExpAst", "clearRegExpParserCache", "complementErrorMessage", "failedOptimizationPrefixMsg", "getOptimizedStartCodesIndices", "regExp", "ensureOptimizations", "ast", "getRegExpAst", "firstCharOptimizedIndices", "e", "PRINT_WARNING", "msgSuffix", "PRINT_ERROR", "result", "ignoreCase", "terms", "term", "atom", "addOptimizedIdxToResult", "forEach_default", "code", "range", "rangeCode", "minOptimizationVal", "minUnOptVal", "maxUnOptVal", "minOptIdx", "charCodeToOptimizedIndex", "maxOptIdx", "currOptIdx", "isOptionalQuantifier", "isWholeOptional", "values_default", "optimizedCharIdx", "handleIgnoreCase", "char", "upperChar", "lowerChar", "findCode", "setNode", "targetCharCodes", "find_default", "codeOrRange", "includes_default", "targetCode", "quantifier", "isArray_default", "every_default", "CharCodeFinder", "BaseRegExpVisitor", "node", "canMatchCharCode", "charCodes", "pattern", "charCodeFinder", "PATTERN", "DEFAULT_MODE", "MODES", "SUPPORT_STICKY", "analyzeTokenTypes", "tokenTypes", "options", "defaults_default", "SUPPORT_STICKY", "msg", "action", "tracer", "initCharCodeToOptimizedIndexMap", "onlyRelevantTypes", "reject_default", "currType", "PATTERN", "Lexer", "hasCustom", "allTransformedPatterns", "map_default", "currPattern", "isRegExp_default", "regExpSource", "includes_default", "addStickyFlag", "addStartOfInput", "isFunction_default", "escapedRegExpString", "wrappedRegExp", "patternIdxToType", "patternIdxToGroup", "patternIdxToLongerAltIdxArr", "patternIdxToPushMode", "patternIdxToPopMode", "clazz", "groupName", "isString_default", "isUndefined_default", "longerAltType", "isArray_default", "type", "indexOf_default", "has_default", "patternIdxToCanLineTerminator", "lineTerminatorCharCodes", "getCharCodes", "tokType", "checkLineBreaksIssues", "canMatchCharCode", "patternIdxToIsCustom", "patternIdxToShort", "emptyGroups", "patternIdxToConfig", "isCustomPattern", "isShortPattern", "reduce_default", "acc", "x", "idx", "canBeOptimized", "charCodeToPatternIdxToConfig", "result", "currTokType", "charCode", "optimizedIdx", "charCodeToOptimizedIndex", "addToMapOfArrays", "lastOptimizedIdx", "forEach_default", "charOrInt", "currOptimizedIdx", "PRINT_ERROR", "failedOptimizationPrefixMsg", "optimizedCodes", "getOptimizedStartCodesIndices", "isEmpty_default", "code", "validatePatterns", "validModesNames", "errors", "missingResult", "findMissingPatterns", "invalidResult", "findInvalidPatterns", "validTokenTypes", "validateRegExpPattern", "findInvalidGroupType", "findModesThatDoNotExist", "findUnreachablePatterns", "withRegExpPatterns", "filter_default", "findEndOfInputAnchor", "findStartOfInputAnchor", "findUnsupportedFlags", "findDuplicatePatterns", "findEmptyMatchRegExps", "tokenTypesWithMissingPattern", "LexerDefinitionErrorType", "valid", "difference_default", "tokenTypesWithInvalidPattern", "pattern", "end_of_input", "EndAnchorFinder", "BaseRegExpVisitor", "node", "invalidRegex", "regexpAst", "getRegExpAst", "endAnchorVisitor", "matchesEmptyString", "start_of_input", "StartAnchorFinder", "startAnchorVisitor", "invalidFlags", "found", "identicalPatterns", "outerType", "innerType", "compact_default", "duplicatePatterns", "currIdenticalSet", "setOfIdentical", "tokenTypeNames", "head_default", "invalidTypes", "group", "validModes", "invalidModes", "canBeTested", "noMetaChar", "testIdx", "str", "tokenType", "testTokenType", "regExpArray", "regExp", "find_default", "char", "flags", "performRuntimeChecks", "lexerDefinition", "trackLines", "lineTerminatorCharacters", "DEFAULT_MODE", "MODES", "currModeValue", "currModeName", "currIdx", "longerAlt", "currLongerAlt", "performWarningRuntimeChecks", "warnings", "hasAnyLineBreak", "allTokenTypes", "flatten_default", "values_default", "concreteTokenTypes", "terminatorCharCodes", "currIssue", "warningDescriptor", "buildLineBreakIssueMessage", "cloneEmptyGroups", "clonedResult", "groupKeys", "keys_default", "currKey", "currGroupValue", "LineTerminatorOptimizedTester", "text", "len", "i", "c", "e", "details", "charsOrCodes", "numOrString", "map", "key", "value", "minOptimizationVal", "charCodeToOptimizedIdxMap", "tokenStructuredMatcher", "tokInstance", "tokConstructor", "instanceType", "tokenStructuredMatcherNoCategories", "token", "tokType", "tokenShortNameIdx", "tokenIdxToClass", "augmentTokenTypes", "tokenTypes", "tokenTypesAndParents", "expandCategories", "assignTokenDefaultProps", "assignCategoriesMapProp", "assignCategoriesTokensProp", "forEach_default", "result", "clone_default", "categories", "searching", "compact_default", "flatten_default", "map_default", "currTokType", "newCategories", "difference_default", "isEmpty_default", "hasShortKeyProperty", "hasCategoriesProperty", "isArray_default", "hasExtendingTokensTypesProperty", "hasExtendingTokensTypesMapProperty", "val", "key", "singleAssignCategoriesToksMap", "path", "nextNode", "pathNode", "nextCategory", "newPath", "includes_default", "has_default", "isTokenType", "defaultLexerErrorProvider", "token", "fullText", "startOffset", "length", "line", "column", "LexerDefinitionErrorType", "DEFAULT_LEXER_CONFIG", "defaultLexerErrorProvider", "Lexer", "lexerDefinition", "config", "phaseDesc", "phaseImpl", "indent", "time", "value", "timer", "traceMethod", "assign_default", "traceInitVal", "actualDefinition", "hasOnlySingleMode", "LineTerminatorOptimizedTester", "isArray_default", "clone_default", "DEFAULT_MODE", "performRuntimeChecks", "performWarningRuntimeChecks", "forEach_default", "currModeValue", "currModeName", "reject_default", "currTokType", "isUndefined_default", "allModeNames", "keys_default", "currModDef", "currModName", "validatePatterns", "isEmpty_default", "augmentTokenTypes", "currAnalyzeResult", "analyzeTokenTypes", "allErrMessagesString", "map_default", "error", "warningDescriptor", "PRINT_WARNING", "SUPPORT_STICKY", "identity_default", "noop_default", "unOptimizedModes", "reduce_default", "cannotBeOptimized", "canBeOptimized", "modeName", "clearRegExpParserCache", "toFastProperties", "text", "initialMode", "i", "j", "k", "matchAltImage", "longerAlt", "matchedImage", "payload", "altPayload", "imageLength", "group", "tokType", "newToken", "errLength", "droppedChar", "msg", "match", "orgText", "orgLength", "offset", "matchedTokensIndex", "guessedNumberOfTokens", "matchedTokens", "errors", "line", "column", "groups", "cloneEmptyGroups", "trackLines", "lineTerminatorPattern", "currModePatternsLength", "patternIdxToConfig", "currCharCodeToPatternIdxToConfig", "modeStack", "emptyArray", "getPossiblePatterns", "getPossiblePatternsSlow", "getPossiblePatternsOptimized", "charCode", "optimizedCharIdx", "charCodeToOptimizedIndex", "possiblePatterns", "pop_mode", "popToken", "newMode", "last_default", "modeCanBeOptimized", "push_mode", "currConfig", "recoveryEnabled", "nextCharCode", "chosenPatternIdxToConfig", "chosenPatternsLength", "currPattern", "singleCharCode", "longerAltLength", "longerAltConfig", "longerAltPattern", "numOfLTsInMatch", "foundTerminator", "lastLTEndOffset", "errorStartOffset", "errorLine", "errorColumn", "foundResyncPoint", "pushMode", "length", "regExp", "newLastIndex", "lastLTIdx", "lastCharIsLT", "fixForEndingInLT", "oldColumn", "image", "startOffset", "tokenTypeIdx", "tokenType", "startLine", "startColumn", "tokenVector", "index", "tokenToAdd", "token", "pattern", "regExpArray", "tokenLabel", "tokType", "hasTokenLabel", "hasTokenLabel", "obj", "isString_default", "PARENT", "CATEGORIES", "LABEL", "GROUP", "PUSH_MODE", "POP_MODE", "LONGER_ALT", "LINE_BREAKS", "START_CHARS_HINT", "createToken", "config", "createTokenInternal", "pattern", "tokenType", "isUndefined_default", "has_default", "augmentTokenTypes", "EOF", "Lexer", "createTokenInstance", "tokType", "image", "startOffset", "endOffset", "startLine", "endLine", "startColumn", "endColumn", "tokenMatcher", "token", "tokenStructuredMatcher", "defaultParserErrorProvider", "expected", "actual", "previous", "ruleName", "hasTokenLabel", "tokenLabel", "firstRedundant", "expectedPathsPerAlt", "customUserDescription", "errPrefix", "errSuffix", "head_default", "allLookAheadPaths", "reduce_default", "result", "currAltPaths", "nextValidTokenSequences", "map_default", "currPath", "currTokenType", "calculatedDescription", "itemMsg", "idx", "expectedIterationPaths", "defaultGrammarResolverErrorProvider", "topLevelRule", "undefinedRule", "defaultGrammarValidatorErrorProvider", "duplicateProds", "getExtraProductionArgument", "prod", "Terminal", "NonTerminal", "topLevelName", "duplicateProd", "index", "dslName", "getProductionDslName", "extraArgument", "hasExplicitIndex", "msg", "rule", "options", "pathMsg", "currTok", "occurrence", "currtok", "currMessage", "pathNames", "currRule", "leftRecursivePath", "Rule", "resolveGrammar", "topLevels", "errMsgProvider", "refResolver", "GastRefResolverVisitor", "GAstVisitor", "nameToTopRule", "forEach_default", "values_default", "prod", "node", "ref", "msg", "ParserDefinitionErrorType", "AbstractNextPossibleTokensWalker", "RestWalker", "topProd", "path", "clone_default", "prod", "prevRest", "refProd", "currRest", "fullRest", "isEmpty_default", "NextAfterTokenWalker", "terminal", "restProd", "Alternative", "first", "AbstractNextTerminalAfterProductionWalker", "topRule", "occurrence", "NextTerminalAfterManyWalker", "manyProd", "firstAfterMany", "head_default", "Terminal", "NextTerminalAfterManySepWalker", "manySepProd", "firstAfterManySep", "NextTerminalAfterAtLeastOneWalker", "atLeastOneProd", "firstAfterAtLeastOne", "NextTerminalAfterAtLeastOneSepWalker", "atleastOneSepProd", "firstAfterfirstAfterAtLeastOneSep", "possiblePathsFrom", "targetDef", "maxLength", "currPath", "result", "remainingPathWith", "nextDef", "drop_default", "getAlternativesForProd", "definition", "alternatives", "NonTerminal", "Option", "RepetitionMandatory", "newDef", "Repetition", "RepetitionMandatoryWithSeparator", "RepetitionWithSeparator", "Alternation", "forEach_default", "currAlt", "nextPossibleTokensAfter", "initialDef", "tokenVector", "tokMatcher", "maxLookAhead", "EXIT_NON_TERMINAL", "EXIT_NON_TERMINAL_ARR", "EXIT_ALTERNATIVE", "foundCompletePath", "tokenVectorLength", "minimalAlternativesIndex", "possiblePaths", "last_default", "currDef", "currIdx", "currRuleStack", "currOccurrenceStack", "nextPath", "dropRight_default", "nextIdx", "actualToken", "newRuleStack", "newOccurrenceStack", "nextPathWithout", "nextPathWith", "secondIteration", "separatorGast", "nthRepetition", "i", "currAltPath", "Rule", "expandTopLevelRule", "newCurrOccurrenceStack", "PROD_TYPE", "getProdType", "prod", "Option", "Repetition", "RepetitionMandatory", "RepetitionMandatoryWithSeparator", "RepetitionWithSeparator", "Alternation", "getLookaheadPaths", "options", "occurrence", "rule", "prodType", "maxLookahead", "type", "getLookaheadPathsForOr", "getLookaheadPathsForOptionalProd", "buildLookaheadFuncForOr", "ruleGrammar", "hasPredicates", "dynamicTokensEnabled", "laFuncBuilder", "lookAheadPaths", "tokenMatcher", "areTokenCategoriesNotUsed", "tokenStructuredMatcherNoCategories", "tokenStructuredMatcher", "buildLookaheadFuncForOptionalProd", "k", "lookaheadBuilder", "buildAlternativesLookAheadFunc", "alts", "numOfAlts", "areAllOneTokenLookahead", "every_default", "currAlt", "currPath", "orAlts", "predicates", "map_default", "t", "currNumOfPaths", "currPredicate", "nextPath", "j", "currPathLength", "i", "nextToken", "singleTokenAlts", "flatten_default", "choiceToAlt", "reduce_default", "result", "idx", "forEach_default", "currTokType", "has_default", "currExtendingType", "buildSingleAlternativeLookaheadFunction", "alt", "numOfPaths", "singleTokensTypes", "isEmpty_default", "expectedTokenUniqueKey", "RestDefinitionFinderWalker", "RestWalker", "topProd", "targetOccurrence", "targetProdType", "node", "expectedProdType", "currRest", "prevRest", "optionProd", "atLeastOneProd", "atLeastOneSepProd", "manyProd", "manySepProd", "InsideDefinitionFinderVisitor", "GAstVisitor", "targetRef", "expectedProdName", "initializeArrayOfArrays", "size", "pathToHashKeys", "path", "keys", "tokType", "longerKeys", "currShorterKey", "categoriesKeySuffix", "isUniquePrefixHash", "altKnownPathsKeys", "searchPathKeys", "currAltIdx", "otherAltKnownPathsKeys", "searchIdx", "searchKey", "lookAheadSequenceFromAlternatives", "altsDefs", "partialAlts", "possiblePathsFrom", "finalResult", "altsHashes", "currAltPaths", "dict", "item", "currKey", "newData", "pathLength", "currDataset", "altIdx", "currAltPathsAndSuffixes", "currPathIdx", "currPathPrefix", "suffixDef", "prefixKeys", "currAltResult", "containsPath", "newPartialPathsAndSuffixes", "key", "orProd", "visitor", "insideDefVisitor", "insideDef", "afterDef", "insideFlat", "Alternative", "afterFlat", "alternative", "searchPath", "compareOtherPath", "otherPath", "searchTok", "otherTok", "isStrictPrefixOfPath", "prefix", "other", "otherTokType", "singleAltPaths", "singlePath", "token", "validateLookahead", "options", "lookaheadValidationErrorMessages", "map_default", "errorMessage", "ParserDefinitionErrorType", "validateGrammar", "topLevels", "tokenTypes", "errMsgProvider", "grammarName", "duplicateErrors", "flatMap_default", "currTopLevel", "validateDuplicateProductions", "termsNamespaceConflictErrors", "checkTerminalAndNoneTerminalsNameSpace", "tooManyAltsErrors", "curRule", "validateTooManyAlts", "duplicateRulesError", "validateRuleDoesNotAlreadyExist", "topLevelRule", "collectorVisitor", "OccurrenceValidationCollector", "allRuleProductions", "productionGroups", "groupBy_default", "identifyProductionForDuplicates", "duplicates", "pickBy_default", "currGroup", "values_default", "currDuplicates", "firstProd", "head_default", "msg", "dslName", "getProductionDslName", "defError", "param", "getExtraProductionArgument", "prod", "Terminal", "NonTerminal", "GAstVisitor", "subrule", "option", "manySep", "atLeastOne", "atLeastOneSep", "many", "or", "terminal", "rule", "allRules", "className", "errors", "reduce_default", "result", "errMsg", "validateRuleIsOverridden", "ruleName", "definedRulesNames", "includes_default", "validateNoLeftRecursion", "topRule", "currRule", "path", "nextNonTerminals", "getFirstNoneTerminal", "isEmpty_default", "validNextSteps", "difference_default", "errorsFromNextSteps", "currRefRule", "newPath", "clone_default", "definition", "Alternative", "Option", "RepetitionMandatory", "RepetitionMandatoryWithSeparator", "RepetitionWithSeparator", "Repetition", "Alternation", "flatten_default", "currSubDef", "isFirstOptional", "isOptionalProd", "hasMore", "rest", "drop_default", "OrCollector", "node", "validateEmptyOrAlternative", "orCollector", "ors", "currOr", "exceptLast", "dropRight_default", "currAlternative", "currAltIdx", "possibleFirstInAlt", "nextPossibleTokensAfter", "tokenStructuredMatcher", "validateAmbiguousAlternationAlternatives", "globalMaxLookahead", "reject_default", "currOccurrence", "actualMaxLookahead", "alternatives", "getLookaheadPathsForOr", "altsAmbiguityErrors", "checkAlternativesAmbiguities", "altsPrefixAmbiguityErrors", "checkPrefixAlternativesAmbiguities", "RepetitionCollector", "validateSomeNonEmptyLookaheadPath", "topLevelRules", "maxLookahead", "forEach_default", "currTopRule", "currProd", "prodType", "getProdType", "pathsInsideProduction", "getLookaheadPathsForOptionalProd", "alternation", "foundAmbiguousPaths", "identicalAmbiguities", "currAlt", "currPath", "altsCurrPathAppearsIn", "currOtherAlt", "currOtherAltIdx", "containsPath", "currAmbDescriptor", "ambgIndices", "pathsAndIndices", "idx", "currPathsAndIdx", "compact_default", "currPathAndIdx", "targetIdx", "targetPath", "prefixAmbiguitiesPathsAndIndices", "filter_default", "searchPathAndIdx", "isStrictPrefixOfPath", "currAmbPathAndIdx", "occurrence", "tokenNames", "currToken", "currRuleName", "resolveGrammar", "options", "actualOptions", "defaults_default", "defaultGrammarResolverErrorProvider", "topRulesTable", "forEach_default", "rule", "validateGrammar", "defaultGrammarValidatorErrorProvider", "MISMATCHED_TOKEN_EXCEPTION", "NO_VIABLE_ALT_EXCEPTION", "EARLY_EXIT_EXCEPTION", "NOT_ALL_INPUT_PARSED_EXCEPTION", "RECOGNITION_EXCEPTION_NAMES", "isRecognitionException", "error", "includes_default", "RecognitionException", "message", "token", "MismatchedTokenException", "previousToken", "NoViableAltException", "NotAllInputParsedException", "EarlyExitException", "EOF_FOLLOW_KEY", "IN_RULE_RECOVERY_EXCEPTION", "InRuleRecoveryException", "message", "Recoverable", "config", "has_default", "DEFAULT_PARSER_CONFIG", "attemptInRepetitionRecovery", "tokType", "tokToInsert", "createTokenInstance", "grammarRule", "grammarRuleArgs", "lookAheadFunc", "expectedTokType", "reSyncTokType", "savedLexerState", "resyncedTokens", "passedResyncPoint", "nextTokenWithoutResync", "currToken", "generateErrorMessage", "previousToken", "msg", "error", "MismatchedTokenException", "dropRight_default", "expectTokAfterLastMatch", "nextTokIdx", "notStuck", "tokIdxInRule", "grammarPath", "follows", "nextTok", "expectedToken", "isEmpty_default", "mismatchedTok", "find_default", "possibleFollowsTokType", "tokenTypeIdx", "followKey", "currentRuleReSyncSet", "includes_default", "allPossibleReSyncTokTypes", "nextToken", "k", "foundMatch", "resyncTokType", "tokenMatcher", "currRuleShortName", "currRuleIdx", "prevRuleShortName", "explicitRuleStack", "explicitOccurrenceStack", "map_default", "ruleName", "idx", "followStack", "currKey", "flatten_default", "EOF", "followName", "IN", "token", "resyncTokens", "prodFunc", "args", "lookaheadFunc", "dslMethodIdx", "prodOccurrence", "nextToksWalker", "pathRuleStack", "pathOccurrenceStack", "clone_default", "currShortName", "key", "firstAfterRepInfo", "currRuleName", "ruleGrammar", "isEndOfRule", "getKeyForAutomaticLookahead", "ruleIdx", "dslMethodIdx", "occurrence", "LLkLookaheadStrategy", "options", "_a", "DEFAULT_PARSER_CONFIG", "leftRecursionErrors", "isEmpty_default", "emptyAltErrors", "ambiguousAltsErrors", "emptyRepetitionErrors", "rules", "flatMap_default", "currTopRule", "validateNoLeftRecursion", "defaultGrammarValidatorErrorProvider", "validateEmptyOrAlternative", "maxLookahead", "validateAmbiguousAlternationAlternatives", "validateSomeNonEmptyLookaheadPath", "buildLookaheadFuncForOr", "buildAlternativesLookAheadFunc", "buildLookaheadFuncForOptionalProd", "getProdType", "buildSingleAlternativeLookaheadFunction", "LooksAhead", "config", "has_default", "DEFAULT_PARSER_CONFIG", "LLkLookaheadStrategy", "rules", "forEach_default", "currRule", "alternation", "repetition", "option", "repetitionMandatory", "repetitionMandatoryWithSeparator", "repetitionWithSeparator", "collectMethods", "currProd", "prodIdx", "getProductionDslName", "laFunc", "key", "getKeyForAutomaticLookahead", "rule", "prodOccurrence", "prodKey", "prodType", "prodMaxLookahead", "dslMethodName", "dslMethodIdx", "occurrence", "currRuleShortName", "value", "DslMethodsCollectorVisitor", "GAstVisitor", "manySep", "atLeastOne", "atLeastOneSep", "many", "or", "collectorVisitor", "dslMethods", "setNodeLocationOnlyOffset", "currNodeLocation", "newLocationInfo", "setNodeLocationFull", "addTerminalToCst", "node", "token", "tokenTypeName", "addNoneTerminalToCst", "ruleName", "ruleResult", "NAME", "defineNameProp", "obj", "nameValue", "defaultVisit", "ctx", "param", "childrenNames", "keys_default", "childrenNamesLength", "currChildName", "currChildArray", "currChildArrayLength", "j", "currChild", "createBaseSemanticVisitorConstructor", "grammarName", "ruleNames", "derivedConstructor", "defineNameProp", "semanticProto", "cstNode", "isArray_default", "isUndefined_default", "semanticDefinitionErrors", "validateVisitor", "isEmpty_default", "errorMessages", "map_default", "currDefError", "createBaseVisitorConstructorWithDefaults", "baseConstructor", "withDefaultsProto", "forEach_default", "ruleName", "CstVisitorDefinitionError", "visitorInstance", "validateMissingCstMethods", "missingRuleNames", "filter_default", "currRuleName", "isFunction_default", "errors", "compact_default", "TreeBuilder", "config", "has_default", "DEFAULT_PARSER_CONFIG", "noop_default", "setNodeLocationFull", "setNodeLocationOnlyOffset", "cstNode", "nextToken", "fullRuleName", "ruleCstNode", "prevToken", "loc", "key", "consumedToken", "rootCst", "addTerminalToCst", "ruleCstResult", "ruleName", "preCstNode", "addNoneTerminalToCst", "isUndefined_default", "newBaseCstVisitorConstructor", "createBaseSemanticVisitorConstructor", "keys_default", "newConstructor", "createBaseVisitorConstructorWithDefaults", "ruleStack", "occurrenceStack", "LexerAdapter", "newInput", "END_OF_FILE", "howMuch", "soughtIdx", "newState", "RecognizerApi", "impl", "idx", "tokType", "options", "ruleToCall", "actionORMethodDef", "altsOrOpts", "name", "implementation", "config", "DEFAULT_RULE_CONFIG", "includes_default", "error", "defaultGrammarValidatorErrorProvider", "ParserDefinitionErrorType", "ruleImplementation", "ruleErrors", "validateRuleIsOverridden", "grammarRule", "args", "orgState", "e", "isRecognitionException", "serializeGrammar", "values_default", "RecognizerEngine", "tokenVocabulary", "config", "tokenStructuredMatcherNoCategories", "has_default", "isArray_default", "isEmpty_default", "reduce_default", "acc", "tokType", "every_default", "flatten_default", "values_default", "isTokenType", "allTokenTypes", "uniqueTokens", "uniq_default", "isObject_default", "clone_default", "EOF", "noTokenCategoriesUsed", "tokenConstructor", "tokenStructuredMatcher", "augmentTokenTypes", "ruleName", "impl", "resyncEnabled", "DEFAULT_RULE_CONFIG", "recoveryValueFunc", "shortName", "invokeRuleWithTry", "args", "cst", "e", "resyncEnabledConfig", "isFirstInvokedRule", "reSyncEnabled", "isRecognitionException", "recogError", "reSyncTokType", "partialCstResult", "actionORMethodDef", "occurrence", "key", "lookAheadFunc", "action", "predicate", "orgLookaheadFunction", "prodOccurrence", "laKey", "notStuck", "PROD_TYPE", "NextTerminalAfterAtLeastOneWalker", "options", "separator", "separatorLookAheadFunc", "NextTerminalAfterAtLeastOneSepWalker", "lookaheadFunction", "NextTerminalAfterManyWalker", "NextTerminalAfterManySepWalker", "nextTerminalAfterWalker", "beforeIteration", "altsOrOpts", "alts", "altIdxToTake", "firstRedundantTok", "errMsg", "NotAllInputParsedException", "ruleToCall", "idx", "ruleResult", "consumedToken", "nextToken", "eFromConsumption", "msg", "previousToken", "MismatchedTokenException", "follows", "eFromInRuleRecovery", "IN_RULE_RECOVERY_EXCEPTION", "savedErrors", "savedRuleStack", "newState", "fullName", "idxInCallingRule", "ErrorHandler", "config", "has_default", "DEFAULT_PARSER_CONFIG", "error", "isRecognitionException", "clone_default", "newErrors", "occurrence", "prodType", "userDefinedErrMsg", "ruleName", "ruleGrammar", "insideProdPaths", "getLookaheadPathsForOptionalProd", "actualTokens", "i", "msg", "EarlyExitException", "errMsgTypes", "lookAheadPathsPerAlternative", "getLookaheadPathsForOr", "previousToken", "errMsg", "NoViableAltException", "ContentAssist", "startRuleName", "precedingInput", "startRuleGast", "isUndefined_default", "nextPossibleTokensAfter", "grammarPath", "topRuleName", "head_default", "topProduction", "NextAfterTokenWalker", "RECORDING_NULL_OBJECT", "HANDLE_SEPARATOR", "MAX_METHOD_IDX", "RFT", "createToken", "Lexer", "augmentTokenTypes", "RECORDING_PHASE_TOKEN", "createTokenInstance", "RECORDING_PHASE_CSTNODE", "GastRecorder", "config", "i", "idx", "arg1", "arg2", "that", "impl", "grammarRule", "args", "howMuch", "END_OF_FILE", "name", "def", "newTopLevelRule", "Rule", "originalError", "actionORMethodDef", "occurrence", "recordProd", "Option", "RepetitionMandatory", "options", "RepetitionMandatoryWithSeparator", "Repetition", "RepetitionWithSeparator", "altsOrOpts", "recordOrProd", "ruleToCall", "assertMethodIdxIsValid", "has_default", "error", "getIdxSuffix", "prevProd", "last_default", "ruleName", "newNoneTerminal", "NonTerminal", "tokType", "hasShortKeyProperty", "Terminal", "prodConstructor", "mainProdArg", "handleSep", "grammarAction", "isFunction_default", "newProd", "hasOptions", "isArray_default", "alts", "newOrProd", "Alternation", "hasPredicates", "some_default", "currAlt", "forEach_default", "currAltFlat", "Alternative", "PerformanceTracer", "config", "has_default", "userTraceInitPerf", "traceIsNumber", "DEFAULT_PARSER_CONFIG", "phaseDesc", "phaseImpl", "indent", "time", "value", "timer", "traceMethod", "applyMixins", "derivedCtor", "baseCtors", "baseCtor", "baseProto", "propName", "basePropDescriptor", "END_OF_FILE", "createTokenInstance", "EOF", "DEFAULT_PARSER_CONFIG", "defaultParserErrorProvider", "DEFAULT_RULE_CONFIG", "ParserDefinitionErrorType", "EMPTY_ALT", "value", "Parser", "_Parser", "parserInstance", "defErrorsMsgs", "className", "toFastProperties", "forEach_default", "currRuleName", "originalGrammarAction", "recordedRuleGast", "resolverErrors", "resolveGrammar", "values_default", "isEmpty_default", "validationErrors", "validateGrammar", "defaultGrammarValidatorErrorProvider", "lookaheadValidationErrors", "validateLookahead", "allFollows", "computeAllProdsFollows", "_b", "_a", "map_default", "defError", "tokenVocabulary", "config", "that", "has_default", "applyMixins", "Recoverable", "LooksAhead", "TreeBuilder", "LexerAdapter", "RecognizerEngine", "RecognizerApi", "ErrorHandler", "ContentAssist", "GastRecorder", "PerformanceTracer", "EmbeddedActionsParser", "Parser", "tokenVocabulary", "config", "DEFAULT_PARSER_CONFIG", "configClone", "clone_default", "buildATNKey", "rule", "type", "occurrence", "ATN_BASIC", "ATN_RULE_START", "ATN_PLUS_BLOCK_START", "ATN_STAR_BLOCK_START", "ATN_RULE_STOP", "ATN_BLOCK_END", "ATN_STAR_LOOP_BACK", "ATN_STAR_LOOP_ENTRY", "ATN_PLUS_LOOP_BACK", "ATN_LOOP_END", "AbstractTransition", "target", "AtomTransition", "tokenType", "EpsilonTransition", "RuleTransition", "ruleStart", "rule", "followState", "createATN", "rules", "atn", "createRuleStartAndStopATNStates", "ruleLength", "i", "ruleBlock", "block", "buildRuleHandle", "start", "newState", "ATN_RULE_START", "stop", "atom", "production", "Terminal", "tokenRef", "NonTerminal", "ruleRef", "Alternation", "alternation", "Option", "option", "Repetition", "repetition", "RepetitionWithSeparator", "repetitionSep", "RepetitionMandatory", "repetitionMandatory", "RepetitionMandatoryWithSeparator", "repetitionMandatorySep", "starState", "ATN_STAR_BLOCK_START", "defineDecisionState", "handle", "makeAlts", "star", "sep", "plusState", "ATN_PLUS_BLOCK_START", "plus", "ATN_BASIC", "alts", "map_default", "e", "optional", "handles", "filter_default", "makeBlock", "blkStart", "blkEnd", "loop", "end", "buildATNKey", "epsilon", "entry", "loopEnd", "state", "alt", "getProdType", "altsLength", "transition", "isRuleTransition", "ruleTransition", "next", "removeState", "first", "last", "left", "right", "addTransition", "currentRule", "nonTerminal", "call", "a", "b", "partial", "t", "DFA_ERROR", "ATNConfigSet", "config", "key", "getATNConfigKey", "map_default", "value", "k", "alt", "e", "createDFACache", "startState", "decision", "map", "predicateSet", "key", "existing", "PredicateSet", "index", "value", "size", "i", "EMPTY_PREDICATES", "LLStarLookaheadStrategy", "LLkLookaheadStrategy", "options", "_a", "message", "createATN", "initATNSimulator", "prodOccurrence", "rule", "hasPredicates", "dynamicTokensEnabled", "dfas", "logging", "buildATNKey", "decisionIndex", "partialAlts", "map_default", "getLookaheadPaths", "currAlt", "path", "isLL1Sequence", "choiceToAlt", "reduce_default", "result", "idx", "forEach_default", "currTokType", "currExtendingType", "orAlts", "nextToken", "prediction", "gate", "predicates", "length", "adaptivePredict", "prodType", "alts", "e", "g", "alt", "singleTokensTypes", "flatten_default", "isEmpty_default", "expectedTokenUniqueKey", "sequences", "allowEmpty", "fullSet", "altSet", "tokType", "indices", "atn", "decisionLength", "decisionToDFA", "dfaCaches", "dfa", "start", "closure", "computeStartState", "addDFAState", "newDFAState", "performLookahead", "s0", "previousD", "t", "d", "getExistingTargetState", "computeLookaheadTarget", "DFA_ERROR", "buildAdaptivePredictError", "token", "lookahead", "reach", "computeReachSet", "addDFAEdge", "newState", "predictedAlt", "getUniqueAlt", "hasConflictTerminatingPrediction", "min_default", "reportLookaheadAmbiguity", "ambiguityIndices", "prefixPath", "atnState", "topLevelRule", "production", "buildAmbiguityError", "pathMsg", "currtok", "tokenLabel", "occurrence", "currMessage", "getProductionDslName", "prod", "NonTerminal", "Option", "Alternation", "RepetitionMandatory", "RepetitionMandatoryWithSeparator", "RepetitionWithSeparator", "Repetition", "Terminal", "previous", "current", "nextTransitions", "flatMap_default", "nextTokenTypes", "uniqBy_default", "AtomTransition", "state", "configs", "intermediate", "ATNConfigSet", "skippedStopStates", "c", "ATN_RULE_STOP", "transitionLength", "transition", "target", "getReachableTarget", "hasConfigInRuleStopState", "tokenMatcher", "from", "to", "mapKey", "numberOfTransitions", "config", "p", "atnStack", "followConfig", "getEpsilonTarget", "EpsilonTransition", "RuleTransition", "stack", "allConfigsInRuleStopStates", "altSets", "getConflictingAltSets", "hasConflictingAltSet", "hasStateAssociatedWithOneAlt", "configToAlts", "getATNConfigKey", "DocumentUri", "is", "value", "URI", "integer", "uinteger", "Position", "create", "line", "character", "candidate", "Is", "Range", "one", "two", "three", "four", "Location", "uri", "range", "LocationLink", "targetUri", "targetRange", "targetSelectionRange", "originSelectionRange", "Color", "red", "green", "blue", "alpha", "ColorInformation", "color", "ColorPresentation", "label", "textEdit", "additionalTextEdits", "TextEdit", "FoldingRangeKind", "FoldingRange", "startLine", "endLine", "startCharacter", "endCharacter", "kind", "collapsedText", "result", "DiagnosticRelatedInformation", "location", "message", "DiagnosticSeverity", "DiagnosticTag", "CodeDescription", "Diagnostic", "severity", "code", "source", "relatedInformation", "_a", "Command", "title", "command", "args", "replace", "newText", "insert", "position", "del", "ChangeAnnotation", "needsConfirmation", "description", "ChangeAnnotationIdentifier", "AnnotatedTextEdit", "annotation", "TextDocumentEdit", "textDocument", "edits", "OptionalVersionedTextDocumentIdentifier", "CreateFile", "options", "RenameFile", "oldUri", "newUri", "DeleteFile", "WorkspaceEdit", "change", "TextDocumentIdentifier", "create", "uri", "is", "value", "candidate", "Is", "VersionedTextDocumentIdentifier", "version", "OptionalVersionedTextDocumentIdentifier", "TextDocumentItem", "languageId", "text", "MarkupKind", "MarkupContent", "CompletionItemKind", "InsertTextFormat", "CompletionItemTag", "InsertReplaceEdit", "newText", "insert", "replace", "Range", "InsertTextMode", "CompletionItemLabelDetails", "CompletionItem", "label", "CompletionList", "items", "isIncomplete", "MarkedString", "fromPlainText", "plainText", "Hover", "ParameterInformation", "documentation", "SignatureInformation", "parameters", "result", "DocumentHighlightKind", "DocumentHighlight", "range", "kind", "SymbolKind", "SymbolTag", "SymbolInformation", "name", "containerName", "WorkspaceSymbol", "DocumentSymbol", "detail", "selectionRange", "children", "CodeActionKind", "CodeActionTriggerKind", "CodeActionContext", "diagnostics", "only", "triggerKind", "Diagnostic", "CodeAction", "title", "kindOrCommandOrEdit", "checkKind", "Command", "WorkspaceEdit", "CodeLens", "data", "FormattingOptions", "tabSize", "insertSpaces", "DocumentLink", "target", "SelectionRange", "parent", "SemanticTokenTypes", "SemanticTokenModifiers", "SemanticTokens", "InlineValueText", "InlineValueVariableLookup", "variableName", "caseSensitiveLookup", "InlineValueEvaluatableExpression", "expression", "InlineValueContext", "frameId", "stoppedLocation", "InlayHintKind", "InlayHintLabelPart", "Location", "InlayHint", "position", "Position", "TextEdit", "StringValue", "createSnippet", "InlineCompletionItem", "insertText", "filterText", "command", "InlineCompletionList", "InlineCompletionTriggerKind", "SelectedCompletionInfo", "InlineCompletionContext", "selectedCompletionInfo", "WorkspaceFolder", "URI", "TextDocument", "create", "uri", "languageId", "version", "content", "FullTextDocument", "is", "value", "candidate", "Is", "applyEdits", "document", "edits", "text", "sortedEdits", "mergeSort", "a", "b", "diff", "lastModifiedOffset", "i", "e", "startOffset", "endOffset", "data", "compare", "p", "left", "right", "leftIdx", "rightIdx", "range", "start", "end", "event", "lineOffsets", "isLineStart", "ch", "offset", "low", "high", "Position", "mid", "line", "position", "lineOffset", "nextLineOffset", "toString", "defined", "undefined", "boolean", "string", "number", "numberRange", "min", "max", "integer", "uinteger", "func", "objectLiteral", "typedArray", "check", "CstNodeBuilder", "_a", "input", "RootCstNodeImpl", "feature", "compositeNode", "CompositeCstNodeImpl", "token", "leafNode", "LeafCstNodeImpl", "tokenToRange", "node", "parent", "index", "tokens", "nodes", "current", "added", "item", "AbstractCstNode", "_b", "value", "offset", "length", "range", "tokenType", "hidden", "CstNodeContainer", "firstNode", "lastNode", "firstRange", "lastRange", "Position", "child", "i", "_CstNodeContainer", "items", "start", "count", "DatatypeSymbol", "isDataTypeNode", "node", "ruleSuffix", "withRuleSuffix", "name", "AbstractLangiumParser", "services", "tokens", "production", "ChevrotainWrapper", "idx", "choices", "callback", "LangiumParser", "CstNodeBuilder", "rule", "impl", "type", "ruleMethod", "isDataTypeRule", "explicit", "getExplicitRuleType", "input", "options", "lexerResult", "result", "$type", "implementation", "args", "createNode", "token", "hiddenTokens", "offset", "tokenType", "feature", "leafNode", "assignment", "isCrossRef", "current", "convertedValue", "isKeyword", "text", "fragment", "cstNode", "subruleResult", "newItem", "action", "last", "obj", "linkContentToContainer", "assignMandatoryProperties", "getContainerOfType", "isAssignment", "isCrossReference", "operator", "value", "item", "target", "source", "existingValue", "newValue", "targetCstNode", "AbstractParserErrorMessageProvider", "defaultParserErrorProvider", "LangiumParserErrorMessageProvider", "expected", "actual", "firstRedundant", "LangiumCompletionParser", "size", "element", "index", "defaultConfig", "EmbeddedActionsParser", "config", "useDefaultLookahead", "LLkLookaheadStrategy", "LLStarLookaheadStrategy", "createParser", "grammar", "parser", "tokens", "buildRules", "parserContext", "reachable", "getAllReachableRules", "parserRules", "stream", "isParserRule", "rule", "ctx", "buildElement", "element", "ignoreGuard", "method", "isKeyword", "buildKeyword", "isAction", "buildAction", "isAssignment", "isCrossReference", "buildCrossReference", "isRuleCall", "buildRuleCall", "isAlternatives", "buildAlternatives", "isUnorderedGroup", "buildUnorderedGroup", "isGroup", "buildGroup", "isEndOfFile", "idx", "EOF", "ErrorWithLocation", "wrap", "getGuardCondition", "action", "actionType", "getTypeName", "ruleCall", "fragment", "predicate", "buildRuleCallPredicate", "args", "getRule", "isTerminalRule", "getToken", "assertUnreachable", "namedArgs", "predicates", "e", "buildPredicate", "ruleArgs", "i", "ruleTarget", "condition", "isDisjunction", "left", "right", "isConjunction", "isNegation", "value", "isParameterReference", "name", "isBooleanLiteral", "alternatives", "methods", "predicatedMethod", "guard", "alt", "gate", "group", "orIdx", "idFunc", "groupIdx", "lParser", "stackId", "key", "groupState", "trackedAlternatives", "wrapped", "crossRef", "terminal", "terminalRule", "keyword", "assignment", "findNameAssignment", "assignTerminal", "token", "cardinality", "EMPTY_ALT", "getRuleName", "item", "parent", "ruleName", "createCompletionParser", "services", "grammar", "lexer", "parser", "LangiumCompletionParser", "createParser", "createLangiumParser", "services", "parser", "prepareLangiumParser", "grammar", "lexer", "LangiumParser", "createParser", "DefaultTokenBuilder", "grammar", "options", "reachableRules", "stream", "getAllReachableRules", "terminalTokens", "tokens", "terminalToken", "pattern", "isWhitespace", "text", "diagnostics", "rules", "isTerminalRule", "e", "terminal", "regex", "terminalRegex", "tokenType", "Lexer", "stickyRegex", "offset", "isParserRule", "rule", "streamAllContents", "isKeyword", "a", "b", "keyword", "caseInsensitive", "keywordPattern", "getCaseInsensitivePattern", "longerAlts", "token", "partialMatches", "DefaultValueConverter", "input", "cstNode", "feature", "isCrossReference", "getCrossReferenceTerminal", "isRuleCall", "rule", "ValueConverter", "_a", "getRuleType", "convertString", "result", "i", "c", "c1", "convertEscapeCharacter", "char", "convertID", "convertInt", "convertBigint", "convertDate", "convertNumber", "convertBoolean", "cancellation_exports", "__reExport", "delayNextTick", "resolve", "lastTick", "globalInterruptionPeriod", "startCancelableOperation", "setInterruptionPeriod", "period", "OperationCancelled", "isOperationCancelled", "err", "interruptAndCheck", "token", "current", "Deferred", "reject", "arg", "FullTextDocument", "_FullTextDocument", "uri", "languageId", "version", "content", "range", "start", "end", "changes", "change", "getWellformedRange", "startOffset", "endOffset", "startLine", "endLine", "lineOffsets", "addedLineOffsets", "computeLineOffsets", "i", "len", "diff", "offset", "low", "high", "mid", "line", "position", "lineOffset", "nextLineOffset", "isEOL", "event", "candidate", "TextDocument", "create", "update", "document", "applyEdits", "edits", "text", "sortedEdits", "mergeSort", "getWellformedEdit", "a", "b", "lastModifiedOffset", "spans", "e", "data", "compare", "p", "left", "right", "leftIdx", "rightIdx", "isAtLineStart", "textOffset", "result", "ch", "char", "textEdit", "assertPath", "path", "TypeError", "JSON", "stringify", "normalizeStringPosix", "allowAboveRoot", "code", "res", "lastSegmentLength", "lastSlash", "dots", "i", "length", "charCodeAt", "lastSlashIndex", "lastIndexOf", "slice", "posix", "resolve", "cwd", "resolvedPath", "resolvedAbsolute", "arguments", "process", "normalize", "isAbsolute", "trailingSeparator", "join", "joined", "arg", "relative", "from", "to", "fromStart", "fromEnd", "fromLen", "toStart", "toLen", "lastCommonSep", "fromCode", "out", "_makeLong", "dirname", "hasRoot", "end", "matchedSlash", "basename", "ext", "start", "extIdx", "firstNonSlashEnd", "extname", "startDot", "startPart", "preDotState", "format", "pathObject", "sep", "dir", "root", "base", "name", "parse", "ret", "delimiter", "win32", "module", "exports", "__webpack_module_cache__", "__webpack_require__", "moduleId", "cachedModule", "__webpack_modules__", "d", "definition", "key", "o", "Object", "defineProperty", "enumerable", "get", "obj", "prop", "prototype", "hasOwnProperty", "call", "r", "Symbol", "toStringTag", "value", "isWindows", "f", "P", "platform", "navigator", "userAgent", "indexOf", "_schemePattern", "_singleSlashStart", "_doubleSlashStart", "_validateUri", "_strict", "scheme", "Error", "authority", "query", "fragment", "test", "_empty", "_slash", "_regexp", "URI", "thing", "fsPath", "with", "toString", "schemeOrData", "this", "uriToFsPath", "change", "Uri", "match", "exec", "percentDecode", "replace", "idx", "substring", "components", "result", "skipEncoding", "_asFormatted", "toJSON", "data", "_formatted", "external", "_fsPath", "_sep", "_pathSepMarker", "$mid", "encodeTable", "encodeURIComponentFast", "uriComponent", "isPath", "isAuthority", "nativeEncodePos", "pos", "encodeURIComponent", "charAt", "substr", "escaped", "encodeURIComponentMinimal", "uri", "keepDriveLetterCasing", "toLowerCase", "encoder", "userinfo", "String", "fromCharCode", "decodeURIComponentGraceful", "str", "decodeURIComponent", "_rEncodedAsHex", "A", "posixPath", "slash", "Utils", "t", "joinPath", "paths", "resolvePath", "slashAdded", "LIB", "UriUtils", "Utils", "equals", "a", "b", "relative", "from", "to", "fromPath", "toPath", "fromParts", "e", "toParts", "i", "backPart", "toPart", "normalize", "uri", "URI", "DocumentState", "DefaultLangiumDocumentFactory", "services", "uri", "cancellationToken", "content", "textDocument", "token", "URI", "text", "model", "options", "parseResult", "cancelToken", "document", "textDocumentGetter", "oldText", "_a", "_b", "serviceRegistry", "textDoc", "TextDocument", "DefaultLangiumDocuments", "stream", "uriString", "langiumDoc", "ref_resolving", "DefaultLinker", "services", "document", "cancelToken", "node", "streamAst", "interruptAndCheck", "streamReferences", "ref", "refInfo", "description", "isLinkingError", "linkedNode", "err", "errorMessage", "_a", "property", "refNode", "refText", "linker", "reference", "isAstNode", "isAstNodeDescription", "findRootNode", "refData", "DocumentState", "nodeDescription", "doc", "targetDescription", "referenceType", "isNamed", "node", "DefaultNameProvider", "findNodeForProperty", "DefaultReferences", "services", "sourceCstNode", "assignment", "findAssignment", "nodeElem", "reference", "isReference", "ref", "nameNode", "isChildNode", "astNode", "targetNode", "options", "refs", "indexReferences", "UriUtils", "stream", "doc", "getDocument", "path", "toDocumentSegment", "MultiMap", "elements", "key", "value", "Reduction", "stream", "a", "values", "index", "_a", "callbackfn", "array", "BiMap", "DefaultScopeComputation", "services", "document", "cancelToken", "parentNode", "children", "streamContents", "exports", "node", "interruptAndCheck", "name", "rootNode", "scopes", "MultiMap", "streamAllContents", "container", "StreamScope", "elements", "outerScope", "options", "_a", "name", "local", "e", "MapScope", "element", "localName", "elementStream", "stream", "EMPTY_SCOPE", "EMPTY_STREAM", "DisposableCache", "disposable", "SimpleCache", "key", "value", "provider", "ContextCache", "converter", "contextKey", "contextCache", "mapKey", "documentCache", "DocumentCache", "sharedServices", "state", "uri", "document", "_changed", "deleted", "changed", "allUris", "WorkspaceCache", "DefaultScopeProvider", "services", "WorkspaceCache", "context", "scopes", "referenceType", "precomputed", "getDocument", "currentNode", "allDescriptions", "stream", "desc", "result", "i", "elements", "outerScope", "options", "StreamScope", "s", "e", "name", "_context", "MapScope", "isAstNodeWithComment", "node", "isIntermediateReference", "obj", "DefaultJsonSerializer", "services", "options", "serializeOptions", "specificReplacer", "defaultReplacer", "key", "value", "replacer", "getDocument", "content", "deserializeOptions", "root", "refText", "sourceText", "textRegions", "comments", "uriConverter", "isReference", "refValue", "$refText", "targetDocument", "targetUri", "targetPath", "_b", "_a", "isAstNode", "astNode", "_c", "_d", "comment", "createDocumentSegment", "cstNode", "textRegion", "assignments", "propertyAssignments", "findNodesForProperty", "container", "containerProperty", "containerIndex", "propertyName", "item", "index", "element", "mutable", "property", "reference", "error", "ref", "uri", "fragmentIndex", "documentUri", "URI", "document", "err", "DefaultServiceRegistry", "services", "language", "data", "ext", "uri", "languageId", "_b", "_a", "UriUtils", "diagnosticData", "code", "ValidationCategory", "ValidationRegistry", "services", "MultiMap", "checksRecord", "thisObj", "category", "type", "ch", "callbacks", "check", "entry", "assertUnreachable", "node", "accept", "cancelToken", "functionality", "messageContext", "err", "isOperationCancelled", "messageDetails", "subtype", "categories", "checks", "stream", "checkBefore", "checkAfter", "rootNode", "DefaultDocumentValidator", "services", "document", "options", "cancelToken", "parseResult", "diagnostics", "interruptAndCheck", "d", "_a", "DocumentValidator", "err", "isOperationCancelled", "_options", "lexerDiagnostics", "_b", "lexerDiagnostic", "severity", "_c", "diagnostic", "toDiagnosticSeverity", "toDiagnosticData", "parserError", "range", "token", "position", "tokenToRange", "diagnosticData", "reference", "linkingError", "info", "rootNode", "validationItems", "acceptor", "message", "checksBefore", "checkBefore", "streamAst", "node", "checks", "check", "checksAfter", "checkAfter", "getDiagnosticRange", "cstNode", "findNodeForProperty", "findNodeForKeyword", "DefaultAstNodeDescriptionProvider", "services", "node", "name", "document", "doc", "getDocument", "path", "nameNodeSegment", "nameSegmentGetter", "_a", "toDocumentSegment", "DefaultReferenceDescriptionProvider", "cancelToken", "descr", "rootNode", "astNode", "streamAst", "interruptAndCheck", "streamReferences", "refInfo", "isLinkingError", "description", "targetNodeDescr", "refCstNode", "docUri", "UriUtils", "DefaultAstNodeLocator", "node", "containerPath", "newSegment", "$containerProperty", "$containerIndex", "path", "previousValue", "currentValue", "propertyIndex", "property", "arrayIndex", "array", "event_exports", "__reExport", "DefaultConfigurationProvider", "services", "Deferred", "params", "_b", "_a", "languages", "lang", "configToUpdate", "configs", "conf", "idx", "change", "section", "configuration", "language", "sectionName", "languageId", "Disposable", "create", "callback", "DefaultDocumentBuilder", "services", "MultiMap", "DocumentState", "documents", "options", "cancelToken", "document", "key", "buildState", "previousCategories", "_a", "categories", "_b", "ValidationCategory", "c", "e", "changed", "deleted", "deletedUri", "changedUri", "newDocument", "allChangedUris", "stream", "uri", "doc", "interruptAndCheck", "rebuildDocuments", "listener", "left", "right", "changedUris", "ref", "callback", "Disposable", "index", "scopeComputation", "toBeValidated", "state", "targetState", "filtered", "targetStateDocs", "uriOrToken", "OperationCancelled", "resolve", "reject", "buildDisposable", "cancelDisposable", "listenersCopy", "err", "isOperationCancelled", "validator", "validationSetting", "diagnostics", "newCategories", "DefaultIndexManager", "services", "ContextCache", "targetNode", "astNodePath", "targetDocUri", "getDocument", "result", "docRefs", "refDescr", "UriUtils", "stream", "nodeType", "uris", "documentUris", "uri", "_a", "e", "uriString", "document", "cancelToken", "exports", "indexData", "changedUris", "references", "ref", "DefaultWorkspaceManager", "services", "Deferred", "params", "_a", "_params", "token", "folders", "cancelToken", "documents", "interruptAndCheck", "fileExtensions", "e", "collector", "document", "wf", "entry", "_folders", "_collector", "workspaceFolder", "URI", "folderPath", "content", "_workspaceFolder", "name", "UriUtils", "extname", "DefaultLexerErrorMessageProvider", "fullText", "startOffset", "length", "line", "column", "defaultLexerErrorProvider", "token", "DEFAULT_TOKENIZE_OPTIONS", "DefaultLexer", "services", "tokens", "lexerTokens", "isTokenTypeDictionary", "production", "Lexer", "text", "_options", "chevrotainResult", "_a", "_c", "_b", "buildTokens", "isIMultiModeLexerDefinition", "res", "isTokenTypeArray", "tokenVocabulary", "parseJSDoc", "node", "start", "options", "opts", "position", "Position", "lines", "getLines", "normalizedOptions", "normalizeOptions", "tokens", "tokenize", "parseJSDocComment", "isJSDoc", "first", "last", "firstRegex", "lastRegex", "content", "NEWLINE_REGEXP", "tagRegex", "inlineTagRegex", "context", "currentLine", "currentCharacter", "i", "line", "index", "match", "_a", "_b", "_c", "lastCharacter", "skipWhitespace", "Range", "tagMatch", "fullMatch", "value", "end", "rest", "inlineTagMatches", "buildInlineTokens", "tags", "lineIndex", "characterIndex", "lastIndex", "matchIndex", "startContent", "offset", "tagName", "endContent", "nonWhitespaceRegex", "whitespaceEndRegex", "startPosition", "JSDocCommentImpl", "elements", "element", "parseJSDocElement", "_d", "next", "parseJSDocTag", "parseJSDocText", "appendEmptyLine", "token", "JSDocLineImpl", "firstToken", "lastToken", "parseJSDocInline", "JSDocTextImpl", "parseJSDocLine", "inline", "tagToken", "name", "nextToken", "docLine", "JSDocTagImpl", "textDoc", "range", "normalizeOption", "option", "escaped", "escapeRegExp", "e", "text", "fillNewlines", "rendered", "renderInlineTag", "marker", "tag", "display", "displayStart", "renderLinkDefault", "URI", "JSDocDocumentationProvider", "services", "node", "comment", "isJSDoc", "parseJSDoc", "link", "display", "tag", "name", "description", "_a", "line", "character", "uri", "_node", "_tag", "precomputed", "getDocument", "currentNode", "e", "DefaultCommentProvider", "services", "node", "isAstNodeWithComment", "_a", "findCommentNode", "DefaultAsyncParser", "services", "text", "_cancelToken", "AbstractThreadedAsyncParser", "worker", "deferred", "cancelToken", "Deferred", "timeout", "cancellation", "result", "hydrated", "err", "index", "OperationCancelled", "ParserWorker", "sendMessage", "onMessage", "onError", "terminate", "parseResult", "error", "DefaultWorkspaceLock", "action", "tokenSource", "startCancelableOperation", "queue", "cancellationToken", "deferred", "Deferred", "entry", "entries", "result", "err", "isOperationCancelled", "DefaultHydrator", "services", "BiMap", "result", "e", "lexerReport", "node", "astNodes", "cstNodes", "astNode", "streamAst", "cstNode", "streamCst", "context", "obj", "name", "value", "arr", "item", "isAstNode", "isReference", "reference", "isRootCstNode", "isCompositeCstNode", "child", "isLeafCstNode", "root", "cst", "RootCstNodeImpl", "CompositeCstNodeImpl", "parent", "num", "cstNodeObj", "hydrated", "tokenType", "offset", "length", "startLine", "startColumn", "endLine", "endColumn", "hidden", "LeafCstNodeImpl", "id", "element", "isAbstractElement", "createDefaultCoreModule", "context", "services", "DefaultCommentProvider", "JSDocDocumentationProvider", "DefaultAsyncParser", "createGrammarConfig", "createLangiumParser", "createCompletionParser", "DefaultValueConverter", "DefaultTokenBuilder", "DefaultLexer", "LangiumParserErrorMessageProvider", "DefaultLexerErrorMessageProvider", "DefaultAstNodeLocator", "DefaultAstNodeDescriptionProvider", "DefaultReferenceDescriptionProvider", "DefaultLinker", "DefaultNameProvider", "DefaultScopeProvider", "DefaultScopeComputation", "DefaultReferences", "DefaultHydrator", "DefaultJsonSerializer", "DefaultDocumentValidator", "ValidationRegistry", "createDefaultSharedCoreModule", "DefaultServiceRegistry", "DefaultLangiumDocuments", "DefaultLangiumDocumentFactory", "DefaultDocumentBuilder", "DefaultIndexManager", "DefaultWorkspaceManager", "DefaultWorkspaceLock", "DefaultConfigurationProvider", "Module", "m1", "m2", "_merge", "inject", "module1", "module2", "module3", "module4", "module5", "module6", "module7", "module8", "module9", "module", "_inject", "isProxy", "eagerLoad", "item", "value", "injector", "proxy", "obj", "prop", "_resolve", "_", "__requested__", "error", "target", "source", "key", "value2", "value1", "indentationBuilderDefaultOptions", "LexingMode", "IndentationAwareTokenBuilder", "DefaultTokenBuilder", "options", "createToken", "grammar", "tokenTypes", "isTokenTypeArray", "indentTokenName", "dedentTokenName", "whitespaceTokenName", "ignoreIndentationDelimiters", "dedent", "indent", "ws", "otherTokens", "tokenType", "begin", "end", "text", "result", "offset", "tokens", "groups", "match", "_a", "image", "lineNumber", "createTokenInstance", "currIndentLevel", "prevIndentLevel", "matchIndentIndex", "_b", "numberOfDedents", "newlinesBeforeDedent", "_d", "_c", "i", "token", "terminal", "Lexer", "remainingDedents", "IndentationAwareLexer", "DefaultLexer", "services", "DEFAULT_TOKENIZE_OPTIONS", "report", "indentTokenType", "dedentTokenType", "indentTokenIdx", "dedentTokenIdx", "cleanTokens", "length", "nextToken", "utils_exports", "__export", "ast_utils_exports", "BiMap", "cancellation_exports", "ContextCache", "cst_utils_exports", "DONE_RESULT", "Deferred", "Disposable", "DisposableCache", "DocumentCache", "EMPTY_STREAM", "ErrorWithLocation", "grammar_utils_exports", "MultiMap", "OperationCancelled", "Reduction", "regexp_utils_exports", "SimpleCache", "StreamImpl", "TreeStreamImpl", "URI", "UriUtils", "WorkspaceCache", "assertUnreachable", "delayNextTick", "interruptAndCheck", "isOperationCancelled", "loadGrammarFromJson", "setInterruptionPeriod", "startCancelableOperation", "stream", "__reExport", "event_exports", "EmptyFileSystemProvider", "EmptyFileSystem", "minimalGrammarModule", "minimalSharedGrammarModule", "LangiumGrammarAstReflection", "createMinimalGrammarServices", "shared", "inject", "createDefaultSharedCoreModule", "EmptyFileSystem", "grammar", "createDefaultCoreModule", "loadGrammarFromJson", "json", "services", "astNode", "URI", "_a", "__reExport", "lib_exports", "utils_exports", "__defProp", "__name", "target", "value", "Statement", "Architecture", "isArchitecture", "item", "reflection", "Axis", "Branch", "isBranch", "Checkout", "CherryPicking", "ClassDefStatement", "Commit", "isCommit", "Curve", "Edge", "Entry", "GitGraph", "isGitGraph", "Group", "Info", "isInfo", "Item", "Junction", "Merge", "isMerge", "Option", "Packet", "isPacket", "PacketBlock", "isPacketBlock", "Pie", "isPie", "PieSection", "isPieSection", "Radar", "Service", "Treemap", "isTreemap", "TreemapRow", "Direction", "Leaf", "Section", "MermaidAstReflection", "AbstractAstReflection", "subtype", "supertype", "refInfo", "referenceId", "type", "loadedInfoGrammar", "InfoGrammar", "loadGrammarFromJson", "loadedPacketGrammar", "PacketGrammar", "loadedPieGrammar", "PieGrammar", "loadedArchitectureGrammar", "ArchitectureGrammar", "loadedGitGraphGrammar", "GitGraphGrammar", "loadedRadarGrammar", "RadarGrammar", "loadedTreemapGrammar", "TreemapGrammar", "InfoLanguageMetaData", "PacketLanguageMetaData", "PieLanguageMetaData", "ArchitectureLanguageMetaData", "GitGraphLanguageMetaData", "RadarLanguageMetaData", "TreemapLanguageMetaData", "MermaidGeneratedSharedModule", "InfoGeneratedModule", "PacketGeneratedModule", "PieGeneratedModule", "ArchitectureGeneratedModule", "GitGraphGeneratedModule", "RadarGeneratedModule", "TreemapGeneratedModule", "accessibilityDescrRegex", "accessibilityTitleRegex", "titleRegex", "rulesRegexes", "AbstractMermaidValueConverter", "DefaultValueConverter", "rule", "input", "cstNode", "_cstNode", "regex", "match", "CommonValueConverter", "_rule", "_input", "AbstractMermaidTokenBuilder", "DefaultTokenBuilder", "keywords", "rules", "terminalTokens", "options", "tokenTypes", "tokenType", "CommonTokenBuilder"] +} diff --git a/docs/website/public/chunk-LGVO22YL.min.js b/docs/website/public/chunk-LGVO22YL.min.js new file mode 100644 index 000000000..88b1c202f --- /dev/null +++ b/docs/website/public/chunk-LGVO22YL.min.js @@ -0,0 +1,2 @@ +import{a as o,b as c,c as t,d as n,e as k,f as e,g as i,i as u,p as d,q as l}from"./chunk-LBFZT66H.min.js";var m=class extends l{static{e(this,"PacketTokenBuilder")}constructor(){super(["packet"])}},v={parser:{TokenBuilder:e(()=>new m,"TokenBuilder"),ValueConverter:e(()=>new d,"ValueConverter")}};function p(s=n){let r=t(c(s),i),a=t(o({shared:r}),u,v);return r.ServiceRegistry.register(a),{shared:r,Packet:a}}e(p,"createPacketServices");export{v as a,p as b}; +//# sourceMappingURL=chunk-LGVO22YL.min.js.map diff --git a/docs/website/public/chunk-LGVO22YL.min.js.map b/docs/website/public/chunk-LGVO22YL.min.js.map new file mode 100644 index 000000000..19843a74a --- /dev/null +++ b/docs/website/public/chunk-LGVO22YL.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/@mermaid-js/parser/dist/chunks/mermaid-parser.core/chunk-KMC2YHZD.mjs"], + "sourcesContent": ["import {\n AbstractMermaidTokenBuilder,\n CommonValueConverter,\n MermaidGeneratedSharedModule,\n PacketGeneratedModule,\n __name\n} from \"./chunk-4KMFLZZN.mjs\";\n\n// src/language/packet/module.ts\nimport {\n EmptyFileSystem,\n createDefaultCoreModule,\n createDefaultSharedCoreModule,\n inject\n} from \"langium\";\n\n// src/language/packet/tokenBuilder.ts\nvar PacketTokenBuilder = class extends AbstractMermaidTokenBuilder {\n static {\n __name(this, \"PacketTokenBuilder\");\n }\n constructor() {\n super([\"packet\"]);\n }\n};\n\n// src/language/packet/module.ts\nvar PacketModule = {\n parser: {\n TokenBuilder: /* @__PURE__ */ __name(() => new PacketTokenBuilder(), \"TokenBuilder\"),\n ValueConverter: /* @__PURE__ */ __name(() => new CommonValueConverter(), \"ValueConverter\")\n }\n};\nfunction createPacketServices(context = EmptyFileSystem) {\n const shared = inject(\n createDefaultSharedCoreModule(context),\n MermaidGeneratedSharedModule\n );\n const Packet = inject(\n createDefaultCoreModule({ shared }),\n PacketGeneratedModule,\n PacketModule\n );\n shared.ServiceRegistry.register(Packet);\n return { shared, Packet };\n}\n__name(createPacketServices, \"createPacketServices\");\n\nexport {\n PacketModule,\n createPacketServices\n};\n"], + "mappings": "2GAiBA,IAAIA,EAAqB,cAAcC,CAA4B,CACjE,MAAO,CACLC,EAAO,KAAM,oBAAoB,CACnC,CACA,aAAc,CACZ,MAAM,CAAC,QAAQ,CAAC,CAClB,CACF,EAGIC,EAAe,CACjB,OAAQ,CACN,aAA8BD,EAAO,IAAM,IAAIF,EAAsB,cAAc,EACnF,eAAgCE,EAAO,IAAM,IAAIE,EAAwB,gBAAgB,CAC3F,CACF,EACA,SAASC,EAAqBC,EAAUC,EAAiB,CACvD,IAAMC,EAASC,EACbC,EAA8BJ,CAAO,EACrCK,CACF,EACMC,EAASH,EACbI,EAAwB,CAAE,OAAAL,CAAO,CAAC,EAClCM,EACAX,CACF,EACA,OAAAK,EAAO,gBAAgB,SAASI,CAAM,EAC/B,CAAE,OAAAJ,EAAQ,OAAAI,CAAO,CAC1B,CACAV,EAAOG,EAAsB,sBAAsB", + "names": ["PacketTokenBuilder", "AbstractMermaidTokenBuilder", "__name", "PacketModule", "CommonValueConverter", "createPacketServices", "context", "EmptyFileSystem", "shared", "inject", "createDefaultSharedCoreModule", "MermaidGeneratedSharedModule", "Packet", "createDefaultCoreModule", "PacketGeneratedModule"] +} diff --git a/docs/website/public/chunk-LK7NMYKK.min.js b/docs/website/public/chunk-LK7NMYKK.min.js new file mode 100644 index 000000000..5a49e5bd9 --- /dev/null +++ b/docs/website/public/chunk-LK7NMYKK.min.js @@ -0,0 +1,2 @@ +import{a as n,b as s,c as i,d as l,e as f,f as o,g as d,n as m,o as c,q as p}from"./chunk-LBFZT66H.min.js";var u=class extends p{static{o(this,"TreemapTokenBuilder")}constructor(){super(["treemap"])}},v=/classDef\s+([A-Z_a-z]\w+)(?:\s+([^\n\r;]*))?;?/,g=class extends c{static{o(this,"TreemapValueConverter")}runCustomConverter(r,e,t){if(r.name==="NUMBER2")return parseFloat(e.replace(/,/g,""));if(r.name==="SEPARATOR")return e.substring(1,e.length-1);if(r.name==="STRING2")return e.substring(1,e.length-1);if(r.name==="INDENTATION")return e.length;if(r.name==="ClassDef"){if(typeof e!="string")return e;let a=v.exec(e);if(a)return{$type:"ClassDefStatement",className:a[1],styleText:a[2]||void 0}}}};function T(r){let e=r.validation.TreemapValidator,t=r.validation.ValidationRegistry;if(t){let a={Treemap:e.checkSingleRoot.bind(e)};t.register(a,e)}}o(T,"registerValidationChecks");var h=class{static{o(this,"TreemapValidator")}checkSingleRoot(r,e){let t;for(let a of r.TreemapRows)a.item&&(t===void 0&&a.indent===void 0?t=0:a.indent===void 0?e("error","Multiple root nodes are not allowed in a treemap.",{node:a,property:"item"}):t!==void 0&&t>=parseInt(a.indent,10)&&e("error","Multiple root nodes are not allowed in a treemap.",{node:a,property:"item"}))}},C={parser:{TokenBuilder:o(()=>new u,"TokenBuilder"),ValueConverter:o(()=>new g,"ValueConverter")},validation:{TreemapValidator:o(()=>new h,"TreemapValidator")}};function V(r=l){let e=i(s(r),d),t=i(n({shared:e}),m,C);return e.ServiceRegistry.register(t),T(t),{shared:e,Treemap:t}}o(V,"createTreemapServices");export{C as a,V as b}; +//# sourceMappingURL=chunk-LK7NMYKK.min.js.map diff --git a/docs/website/public/chunk-LK7NMYKK.min.js.map b/docs/website/public/chunk-LK7NMYKK.min.js.map new file mode 100644 index 000000000..4c3442fc8 --- /dev/null +++ b/docs/website/public/chunk-LK7NMYKK.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/@mermaid-js/parser/dist/chunks/mermaid-parser.core/chunk-XRWGC2XP.mjs"], + "sourcesContent": ["import {\n AbstractMermaidTokenBuilder,\n AbstractMermaidValueConverter,\n MermaidGeneratedSharedModule,\n TreemapGeneratedModule,\n __name\n} from \"./chunk-4KMFLZZN.mjs\";\n\n// src/language/treemap/module.ts\nimport {\n EmptyFileSystem,\n createDefaultCoreModule,\n createDefaultSharedCoreModule,\n inject\n} from \"langium\";\n\n// src/language/treemap/tokenBuilder.ts\nvar TreemapTokenBuilder = class extends AbstractMermaidTokenBuilder {\n static {\n __name(this, \"TreemapTokenBuilder\");\n }\n constructor() {\n super([\"treemap\"]);\n }\n};\n\n// src/language/treemap/valueConverter.ts\nvar classDefRegex = /classDef\\s+([A-Z_a-z]\\w+)(?:\\s+([^\\n\\r;]*))?;?/;\nvar TreemapValueConverter = class extends AbstractMermaidValueConverter {\n static {\n __name(this, \"TreemapValueConverter\");\n }\n runCustomConverter(rule, input, _cstNode) {\n if (rule.name === \"NUMBER2\") {\n return parseFloat(input.replace(/,/g, \"\"));\n } else if (rule.name === \"SEPARATOR\") {\n return input.substring(1, input.length - 1);\n } else if (rule.name === \"STRING2\") {\n return input.substring(1, input.length - 1);\n } else if (rule.name === \"INDENTATION\") {\n return input.length;\n } else if (rule.name === \"ClassDef\") {\n if (typeof input !== \"string\") {\n return input;\n }\n const match = classDefRegex.exec(input);\n if (match) {\n return {\n $type: \"ClassDefStatement\",\n className: match[1],\n styleText: match[2] || void 0\n };\n }\n }\n return void 0;\n }\n};\n\n// src/language/treemap/treemap-validator.ts\nfunction registerValidationChecks(services) {\n const validator = services.validation.TreemapValidator;\n const registry = services.validation.ValidationRegistry;\n if (registry) {\n const checks = {\n Treemap: validator.checkSingleRoot.bind(validator)\n // Remove unused validation for TreemapRow\n };\n registry.register(checks, validator);\n }\n}\n__name(registerValidationChecks, \"registerValidationChecks\");\nvar TreemapValidator = class {\n static {\n __name(this, \"TreemapValidator\");\n }\n /**\n * Validates that a treemap has only one root node.\n * A root node is defined as a node that has no indentation.\n */\n checkSingleRoot(doc, accept) {\n let rootNodeIndentation;\n for (const row of doc.TreemapRows) {\n if (!row.item) {\n continue;\n }\n if (rootNodeIndentation === void 0 && // Check if this is a root node (no indentation)\n row.indent === void 0) {\n rootNodeIndentation = 0;\n } else if (row.indent === void 0) {\n accept(\"error\", \"Multiple root nodes are not allowed in a treemap.\", {\n node: row,\n property: \"item\"\n });\n } else if (rootNodeIndentation !== void 0 && rootNodeIndentation >= parseInt(row.indent, 10)) {\n accept(\"error\", \"Multiple root nodes are not allowed in a treemap.\", {\n node: row,\n property: \"item\"\n });\n }\n }\n }\n};\n\n// src/language/treemap/module.ts\nvar TreemapModule = {\n parser: {\n TokenBuilder: /* @__PURE__ */ __name(() => new TreemapTokenBuilder(), \"TokenBuilder\"),\n ValueConverter: /* @__PURE__ */ __name(() => new TreemapValueConverter(), \"ValueConverter\")\n },\n validation: {\n TreemapValidator: /* @__PURE__ */ __name(() => new TreemapValidator(), \"TreemapValidator\")\n }\n};\nfunction createTreemapServices(context = EmptyFileSystem) {\n const shared = inject(\n createDefaultSharedCoreModule(context),\n MermaidGeneratedSharedModule\n );\n const Treemap = inject(\n createDefaultCoreModule({ shared }),\n TreemapGeneratedModule,\n TreemapModule\n );\n shared.ServiceRegistry.register(Treemap);\n registerValidationChecks(Treemap);\n return { shared, Treemap };\n}\n__name(createTreemapServices, \"createTreemapServices\");\n\nexport {\n TreemapModule,\n createTreemapServices\n};\n"], + "mappings": "2GAiBA,IAAIA,EAAsB,cAAcC,CAA4B,CAClE,MAAO,CACLC,EAAO,KAAM,qBAAqB,CACpC,CACA,aAAc,CACZ,MAAM,CAAC,SAAS,CAAC,CACnB,CACF,EAGIC,EAAgB,iDAChBC,EAAwB,cAAcC,CAA8B,CACtE,MAAO,CACLH,EAAO,KAAM,uBAAuB,CACtC,CACA,mBAAmBI,EAAMC,EAAOC,EAAU,CACxC,GAAIF,EAAK,OAAS,UAChB,OAAO,WAAWC,EAAM,QAAQ,KAAM,EAAE,CAAC,EACpC,GAAID,EAAK,OAAS,YACvB,OAAOC,EAAM,UAAU,EAAGA,EAAM,OAAS,CAAC,EACrC,GAAID,EAAK,OAAS,UACvB,OAAOC,EAAM,UAAU,EAAGA,EAAM,OAAS,CAAC,EACrC,GAAID,EAAK,OAAS,cACvB,OAAOC,EAAM,OACR,GAAID,EAAK,OAAS,WAAY,CACnC,GAAI,OAAOC,GAAU,SACnB,OAAOA,EAET,IAAME,EAAQN,EAAc,KAAKI,CAAK,EACtC,GAAIE,EACF,MAAO,CACL,MAAO,oBACP,UAAWA,EAAM,CAAC,EAClB,UAAWA,EAAM,CAAC,GAAK,MACzB,CAEJ,CAEF,CACF,EAGA,SAASC,EAAyBC,EAAU,CAC1C,IAAMC,EAAYD,EAAS,WAAW,iBAChCE,EAAWF,EAAS,WAAW,mBACrC,GAAIE,EAAU,CACZ,IAAMC,EAAS,CACb,QAASF,EAAU,gBAAgB,KAAKA,CAAS,CAEnD,EACAC,EAAS,SAASC,EAAQF,CAAS,CACrC,CACF,CACAV,EAAOQ,EAA0B,0BAA0B,EAC3D,IAAIK,EAAmB,KAAM,CAC3B,MAAO,CACLb,EAAO,KAAM,kBAAkB,CACjC,CAKA,gBAAgBc,EAAKC,EAAQ,CAC3B,IAAIC,EACJ,QAAWC,KAAOH,EAAI,YACfG,EAAI,OAGLD,IAAwB,QAC5BC,EAAI,SAAW,OACbD,EAAsB,EACbC,EAAI,SAAW,OACxBF,EAAO,QAAS,oDAAqD,CACnE,KAAME,EACN,SAAU,MACZ,CAAC,EACQD,IAAwB,QAAUA,GAAuB,SAASC,EAAI,OAAQ,EAAE,GACzFF,EAAO,QAAS,oDAAqD,CACnE,KAAME,EACN,SAAU,MACZ,CAAC,EAGP,CACF,EAGIC,EAAgB,CAClB,OAAQ,CACN,aAA8BlB,EAAO,IAAM,IAAIF,EAAuB,cAAc,EACpF,eAAgCE,EAAO,IAAM,IAAIE,EAAyB,gBAAgB,CAC5F,EACA,WAAY,CACV,iBAAkCF,EAAO,IAAM,IAAIa,EAAoB,kBAAkB,CAC3F,CACF,EACA,SAASM,EAAsBC,EAAUC,EAAiB,CACxD,IAAMC,EAASC,EACbC,EAA8BJ,CAAO,EACrCK,CACF,EACMC,EAAUH,EACdI,EAAwB,CAAE,OAAAL,CAAO,CAAC,EAClCM,EACAV,CACF,EACA,OAAAI,EAAO,gBAAgB,SAASI,CAAO,EACvClB,EAAyBkB,CAAO,EACzB,CAAE,OAAAJ,EAAQ,QAAAI,CAAQ,CAC3B,CACA1B,EAAOmB,EAAuB,uBAAuB", + "names": ["TreemapTokenBuilder", "AbstractMermaidTokenBuilder", "__name", "classDefRegex", "TreemapValueConverter", "AbstractMermaidValueConverter", "rule", "input", "_cstNode", "match", "registerValidationChecks", "services", "validator", "registry", "checks", "TreemapValidator", "doc", "accept", "rootNodeIndentation", "row", "TreemapModule", "createTreemapServices", "context", "EmptyFileSystem", "shared", "inject", "createDefaultSharedCoreModule", "MermaidGeneratedSharedModule", "Treemap", "createDefaultCoreModule", "TreemapGeneratedModule"] +} diff --git a/docs/website/public/chunk-M2IB7NIX.min.js b/docs/website/public/chunk-M2IB7NIX.min.js new file mode 100644 index 000000000..b3ba15d09 --- /dev/null +++ b/docs/website/public/chunk-M2IB7NIX.min.js @@ -0,0 +1,42 @@ +import{b as f}from"./chunk-6TVUEPFY.min.js";function Ae(e){return typeof e>"u"||e===null}f(Ae,"isNothing");function Ee(e){return typeof e=="object"&&e!==null}f(Ee,"isObject");function Oe(e){return Array.isArray(e)?e:Ae(e)?[]:[e]}f(Oe,"toArray");function Ie(e,n){var i,l,r,u;if(n)for(u=Object.keys(n),i=0,l=u.length;ic&&(u=" ... ",n=l-c+u.length),i-l>c&&(o=" ...",i=l+c-o.length),{str:u+e.slice(n,i).replace(/\t/g,"\u2192")+o,pos:l-n+u.length}}f(W,"getLine");function G(e,n){return w.repeat(" ",n-e.length)+e}f(G,"padStart");function Ne(e,n){if(n=Object.create(n||null),!e.buffer)return null;n.maxLength||(n.maxLength=79),typeof n.indent!="number"&&(n.indent=1),typeof n.linesBefore!="number"&&(n.linesBefore=3),typeof n.linesAfter!="number"&&(n.linesAfter=2);for(var i=/\r?\n|\r|\0/g,l=[0],r=[],u,o=-1;u=i.exec(e.buffer);)r.push(u.index),l.push(u.index+u[0].length),e.position<=u.index&&o<0&&(o=l.length-2);o<0&&(o=l.length-1);var c="",a,t,d=Math.min(e.line+n.linesAfter,r.length).toString().length,p=n.maxLength-(n.indent+d+3);for(a=1;a<=n.linesBefore&&!(o-a<0);a++)t=W(e.buffer,l[o-a],r[o-a],e.position-(l[o]-l[o-a]),p),c=w.repeat(" ",n.indent)+G((e.line-a+1).toString(),d)+" | "+t.str+` +`+c;for(t=W(e.buffer,l[o],r[o],e.position,p),c+=w.repeat(" ",n.indent)+G((e.line+1).toString(),d)+" | "+t.str+` +`,c+=w.repeat("-",n.indent+d+3+t.pos)+`^ +`,a=1;a<=n.linesAfter&&!(o+a>=r.length);a++)t=W(e.buffer,l[o+a],r[o+a],e.position-(l[o]-l[o+a]),p),c+=w.repeat(" ",n.indent)+G((e.line+a+1).toString(),d)+" | "+t.str+` +`;return c.replace(/\n$/,"")}f(Ne,"makeSnippet");var Ai=Ne,yi=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],_i=["scalar","sequence","mapping"];function Re(e){var n={};return e!==null&&Object.keys(e).forEach(function(i){e[i].forEach(function(l){n[String(l)]=i})}),n}f(Re,"compileStyleAliases");function Me(e,n){if(n=n||{},Object.keys(n).forEach(function(i){if(yi.indexOf(i)===-1)throw new x('Unknown option "'+i+'" is met in definition of "'+e+'" YAML type.')}),this.options=n,this.tag=e,this.kind=n.kind||null,this.resolve=n.resolve||function(){return!0},this.construct=n.construct||function(i){return i},this.instanceOf=n.instanceOf||null,this.predicate=n.predicate||null,this.represent=n.represent||null,this.representName=n.representName||null,this.defaultStyle=n.defaultStyle||null,this.multi=n.multi||!1,this.styleAliases=Re(n.styleAliases||null),_i.indexOf(this.kind)===-1)throw new x('Unknown kind "'+this.kind+'" is specified for "'+e+'" YAML type.')}f(Me,"Type$1");var C=Me;function re(e,n){var i=[];return e[n].forEach(function(l){var r=i.length;i.forEach(function(u,o){u.tag===l.tag&&u.kind===l.kind&&u.multi===l.multi&&(r=o)}),i[r]=l}),i}f(re,"compileList");function Ye(){var e={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}},n,i;function l(r){r.multi?(e.multi[r.kind].push(r),e.multi.fallback.push(r)):e[r.kind][r.tag]=e.fallback[r.tag]=r}for(f(l,"collectType"),n=0,i=arguments.length;n=0?"0b"+e.toString(2):"-0b"+e.toString(2).slice(1)},"binary"),octal:f(function(e){return e>=0?"0o"+e.toString(8):"-0o"+e.toString(8).slice(1)},"octal"),decimal:f(function(e){return e.toString(10)},"decimal"),hexadecimal:f(function(e){return e>=0?"0x"+e.toString(16).toUpperCase():"-0x"+e.toString(16).toUpperCase().slice(1)},"hexadecimal")},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),Ii=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function Qe(e){return!(e===null||!Ii.test(e)||e[e.length-1]==="_")}f(Qe,"resolveYamlFloat");function Ve(e){var n,i;return n=e.replace(/_/g,"").toLowerCase(),i=n[0]==="-"?-1:1,"+-".indexOf(n[0])>=0&&(n=n.slice(1)),n===".inf"?i===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:n===".nan"?NaN:i*parseFloat(n,10)}f(Ve,"constructYamlFloat");var ki=/^[-+]?[0-9]+e/;function Xe(e,n){var i;if(isNaN(e))switch(n){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(n){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(n){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(w.isNegativeZero(e))return"-0.0";return i=e.toString(10),ki.test(i)?i.replace("e",".e"):i}f(Xe,"representYamlFloat");function Ze(e){return Object.prototype.toString.call(e)==="[object Number]"&&(e%1!==0||w.isNegativeZero(e))}f(Ze,"isFloat");var Li=new C("tag:yaml.org,2002:float",{kind:"scalar",resolve:Qe,construct:Ve,predicate:Ze,represent:Xe,defaultStyle:"lowercase"}),ze=xi.extend({implicit:[Ti,Ei,Oi,Li]}),Ni=ze,Je=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),en=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function nn(e){return e===null?!1:Je.exec(e)!==null||en.exec(e)!==null}f(nn,"resolveYamlTimestamp");function rn(e){var n,i,l,r,u,o,c,a=0,t=null,d,p,s;if(n=Je.exec(e),n===null&&(n=en.exec(e)),n===null)throw new Error("Date resolve error");if(i=+n[1],l=+n[2]-1,r=+n[3],!n[4])return new Date(Date.UTC(i,l,r));if(u=+n[4],o=+n[5],c=+n[6],n[7]){for(a=n[7].slice(0,3);a.length<3;)a+="0";a=+a}return n[9]&&(d=+n[10],p=+(n[11]||0),t=(d*60+p)*6e4,n[9]==="-"&&(t=-t)),s=new Date(Date.UTC(i,l,r,u,o,c,a)),t&&s.setTime(s.getTime()-t),s}f(rn,"constructYamlTimestamp");function ln(e){return e.toISOString()}f(ln,"representYamlTimestamp");var Ri=new C("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:nn,construct:rn,instanceOf:Date,represent:ln});function on(e){return e==="<<"||e===null}f(on,"resolveYamlMerge");var Mi=new C("tag:yaml.org,2002:merge",{kind:"scalar",resolve:on}),_e=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/= +\r`;function un(e){if(e===null)return!1;var n,i,l=0,r=e.length,u=_e;for(i=0;i64)){if(n<0)return!1;l+=6}return l%8===0}f(un,"resolveYamlBinary");function cn(e){var n,i,l=e.replace(/[\r\n=]/g,""),r=l.length,u=_e,o=0,c=[];for(n=0;n>16&255),c.push(o>>8&255),c.push(o&255)),o=o<<6|u.indexOf(l.charAt(n));return i=r%4*6,i===0?(c.push(o>>16&255),c.push(o>>8&255),c.push(o&255)):i===18?(c.push(o>>10&255),c.push(o>>2&255)):i===12&&c.push(o>>4&255),new Uint8Array(c)}f(cn,"constructYamlBinary");function fn(e){var n="",i=0,l,r,u=e.length,o=_e;for(l=0;l>18&63],n+=o[i>>12&63],n+=o[i>>6&63],n+=o[i&63]),i=(i<<8)+e[l];return r=u%3,r===0?(n+=o[i>>18&63],n+=o[i>>12&63],n+=o[i>>6&63],n+=o[i&63]):r===2?(n+=o[i>>10&63],n+=o[i>>4&63],n+=o[i<<2&63],n+=o[64]):r===1&&(n+=o[i>>2&63],n+=o[i<<4&63],n+=o[64],n+=o[64]),n}f(fn,"representYamlBinary");function an(e){return Object.prototype.toString.call(e)==="[object Uint8Array]"}f(an,"isBinary");var Yi=new C("tag:yaml.org,2002:binary",{kind:"scalar",resolve:un,construct:cn,predicate:an,represent:fn}),Fi=Object.prototype.hasOwnProperty,Pi=Object.prototype.toString;function tn(e){if(e===null)return!0;var n=[],i,l,r,u,o,c=e;for(i=0,l=c.length;i>10)+55296,(e-65536&1023)+56320)}f(bn,"charFromCodepoint");var xn=new Array(256),Tn=new Array(256);for(N=0;N<256;N++)xn[N]=oe(N)?1:0,Tn[N]=oe(N);var N;function En(e,n){this.input=e,this.filename=n.filename||null,this.schema=n.schema||gn,this.onWarning=n.onWarning||null,this.legacy=n.legacy||!1,this.json=n.json||!1,this.listener=n.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.firstTabInLine=-1,this.documents=[]}f(En,"State$1");function we(e,n){var i={name:e.filename,buffer:e.input.slice(0,-1),position:e.position,line:e.line,column:e.position-e.lineStart};return i.snippet=Ai(i),new x(n,i)}f(we,"generateError");function h(e,n){throw we(e,n)}f(h,"throwError");function H(e,n){e.onWarning&&e.onWarning.call(null,we(e,n))}f(H,"throwWarning");var Te={YAML:f(function(n,i,l){var r,u,o;n.version!==null&&h(n,"duplication of %YAML directive"),l.length!==1&&h(n,"YAML directive accepts exactly one argument"),r=/^([0-9]+)\.([0-9]+)$/.exec(l[0]),r===null&&h(n,"ill-formed argument of the YAML directive"),u=parseInt(r[1],10),o=parseInt(r[2],10),u!==1&&h(n,"unacceptable YAML version of the document"),n.version=l[0],n.checkLineBreaks=o<2,o!==1&&o!==2&&H(n,"unsupported YAML version of the document")},"handleYamlDirective"),TAG:f(function(n,i,l){var r,u;l.length!==2&&h(n,"TAG directive accepts exactly two arguments"),r=l[0],u=l[1],yn.test(r)||h(n,"ill-formed tag handle (first argument) of the TAG directive"),L.call(n.tagMap,r)&&h(n,'there is a previously declared suffix for "'+r+'" tag handle'),_n.test(u)||h(n,"ill-formed tag prefix (second argument) of the TAG directive");try{u=decodeURIComponent(u)}catch{h(n,"tag prefix is malformed: "+u)}n.tagMap[r]=u},"handleTagDirective")};function I(e,n,i,l){var r,u,o,c;if(n1&&(e.result+=w.repeat(` +`,n-1))}f(ee,"writeFoldedLines");function On(e,n,i){var l,r,u,o,c,a,t,d,p=e.kind,s=e.result,m;if(m=e.input.charCodeAt(e.position),b(m)||R(m)||m===35||m===38||m===42||m===33||m===124||m===62||m===39||m===34||m===37||m===64||m===96||(m===63||m===45)&&(r=e.input.charCodeAt(e.position+1),b(r)||i&&R(r)))return!1;for(e.kind="scalar",e.result="",u=o=e.position,c=!1;m!==0;){if(m===58){if(r=e.input.charCodeAt(e.position+1),b(r)||i&&R(r))break}else if(m===35){if(l=e.input.charCodeAt(e.position-1),b(l))break}else{if(e.position===e.lineStart&&q(e)||i&&R(m))break;if(E(m))if(a=e.line,t=e.lineStart,d=e.lineIndent,_(e,!1,-1),e.lineIndent>=n){c=!0,m=e.input.charCodeAt(e.position);continue}else{e.position=o,e.line=a,e.lineStart=t,e.lineIndent=d;break}}c&&(I(e,u,o,!1),ee(e,e.line-a),u=o=e.position,c=!1),k(m)||(o=e.position+1),m=e.input.charCodeAt(++e.position)}return I(e,u,o,!1),e.result?!0:(e.kind=p,e.result=s,!1)}f(On,"readPlainScalar");function In(e,n){var i,l,r;if(i=e.input.charCodeAt(e.position),i!==39)return!1;for(e.kind="scalar",e.result="",e.position++,l=r=e.position;(i=e.input.charCodeAt(e.position))!==0;)if(i===39)if(I(e,l,e.position,!0),i=e.input.charCodeAt(++e.position),i===39)l=e.position,e.position++,r=e.position;else return!0;else E(i)?(I(e,l,r,!0),ee(e,_(e,!1,n)),l=r=e.position):e.position===e.lineStart&&q(e)?h(e,"unexpected end of the document within a single quoted scalar"):(e.position++,r=e.position);h(e,"unexpected end of the stream within a single quoted scalar")}f(In,"readSingleQuotedScalar");function kn(e,n){var i,l,r,u,o,c;if(c=e.input.charCodeAt(e.position),c!==34)return!1;for(e.kind="scalar",e.result="",e.position++,i=l=e.position;(c=e.input.charCodeAt(e.position))!==0;){if(c===34)return I(e,i,e.position,!0),e.position++,!0;if(c===92){if(I(e,i,e.position,!0),c=e.input.charCodeAt(++e.position),E(c))_(e,!1,n);else if(c<256&&xn[c])e.result+=Tn[c],e.position++;else if((o=Cn(c))>0){for(r=o,u=0;r>0;r--)c=e.input.charCodeAt(++e.position),(o=wn(c))>=0?u=(u<<4)+o:h(e,"expected hexadecimal character");e.result+=bn(u),e.position++}else h(e,"unknown escape sequence");i=l=e.position}else E(c)?(I(e,i,l,!0),ee(e,_(e,!1,n)),i=l=e.position):e.position===e.lineStart&&q(e)?h(e,"unexpected end of the document within a double quoted scalar"):(e.position++,l=e.position)}h(e,"unexpected end of the stream within a double quoted scalar")}f(kn,"readDoubleQuotedScalar");function Ln(e,n){var i=!0,l,r,u,o=e.tag,c,a=e.anchor,t,d,p,s,m,g=Object.create(null),A,y,T,v;if(v=e.input.charCodeAt(e.position),v===91)d=93,m=!1,c=[];else if(v===123)d=125,m=!0,c={};else return!1;for(e.anchor!==null&&(e.anchorMap[e.anchor]=c),v=e.input.charCodeAt(++e.position);v!==0;){if(_(e,!0,n),v=e.input.charCodeAt(e.position),v===d)return e.position++,e.tag=o,e.anchor=a,e.kind=m?"mapping":"sequence",e.result=c,!0;i?v===44&&h(e,"expected the node content, but found ','"):h(e,"missed comma between flow collection entries"),y=A=T=null,p=s=!1,v===63&&(t=e.input.charCodeAt(e.position+1),b(t)&&(p=s=!0,e.position++,_(e,!0,n))),l=e.line,r=e.lineStart,u=e.position,Y(e,n,Q,!1,!0),y=e.tag,A=e.result,_(e,!0,n),v=e.input.charCodeAt(e.position),(s||e.line===l)&&v===58&&(p=!0,v=e.input.charCodeAt(++e.position),_(e,!0,n),Y(e,n,Q,!1,!0),T=e.result),m?M(e,c,g,y,A,T,l,r,u):p?c.push(M(e,null,g,y,A,T,l,r,u)):c.push(A),_(e,!0,n),v=e.input.charCodeAt(e.position),v===44?(i=!0,v=e.input.charCodeAt(++e.position)):i=!1}h(e,"unexpected end of the stream within a flow collection")}f(Ln,"readFlowCollection");function Nn(e,n){var i,l,r=ie,u=!1,o=!1,c=n,a=0,t=!1,d,p;if(p=e.input.charCodeAt(e.position),p===124)l=!1;else if(p===62)l=!0;else return!1;for(e.kind="scalar",e.result="";p!==0;)if(p=e.input.charCodeAt(++e.position),p===43||p===45)ie===r?r=p===43?xe:Ki:h(e,"repeat of a chomping mode identifier");else if((d=Sn(p))>=0)d===0?h(e,"bad explicit indentation width of a block scalar; it cannot be less than one"):o?h(e,"repeat of an indentation width identifier"):(c=n+d-1,o=!0);else break;if(k(p)){do p=e.input.charCodeAt(++e.position);while(k(p));if(p===35)do p=e.input.charCodeAt(++e.position);while(!E(p)&&p!==0)}for(;p!==0;){for(J(e),e.lineIndent=0,p=e.input.charCodeAt(e.position);(!o||e.lineIndentc&&(c=e.lineIndent),E(p)){a++;continue}if(e.lineIndentn)&&a!==0)h(e,"bad indentation of a sequence entry");else if(e.lineIndentn)&&(y&&(o=e.line,c=e.lineStart,a=e.position),Y(e,n,V,!0,r)&&(y?g=e.result:A=e.result),y||(M(e,p,s,m,g,A,o,c,a),m=g=A=null),_(e,!0,-1),v=e.input.charCodeAt(e.position)),(e.line===u||e.lineIndent>n)&&v!==0)h(e,"bad indentation of a mapping entry");else if(e.lineIndentn?a=1:e.lineIndent===n?a=0:e.lineIndentn?a=1:e.lineIndent===n?a=0:e.lineIndent tag; it should be "scalar", not "'+e.kind+'"'),p=0,s=e.implicitTypes.length;p"),e.result!==null&&g.kind!==e.kind&&h(e,"unacceptable node kind for !<"+e.tag+'> tag; it should be "'+g.kind+'", not "'+e.kind+'"'),g.resolve(e.result,e.tag)?(e.result=g.construct(e.result,e.tag),e.anchor!==null&&(e.anchorMap[e.anchor]=e.result)):h(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")}return e.listener!==null&&e.listener("close",e),e.tag!==null||e.anchor!==null||d}f(Y,"composeNode");function Pn(e){var n=e.position,i,l,r,u=!1,o;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap=Object.create(null),e.anchorMap=Object.create(null);(o=e.input.charCodeAt(e.position))!==0&&(_(e,!0,-1),o=e.input.charCodeAt(e.position),!(e.lineIndent>0||o!==37));){for(u=!0,o=e.input.charCodeAt(++e.position),i=e.position;o!==0&&!b(o);)o=e.input.charCodeAt(++e.position);for(l=e.input.slice(i,e.position),r=[],l.length<1&&h(e,"directive name must not be less than one character in length");o!==0;){for(;k(o);)o=e.input.charCodeAt(++e.position);if(o===35){do o=e.input.charCodeAt(++e.position);while(o!==0&&!E(o));break}if(E(o))break;for(i=e.position;o!==0&&!b(o);)o=e.input.charCodeAt(++e.position);r.push(e.input.slice(i,e.position))}o!==0&&J(e),L.call(Te,l)?Te[l](e,l,r):H(e,'unknown document directive "'+l+'"')}if(_(e,!0,-1),e.lineIndent===0&&e.input.charCodeAt(e.position)===45&&e.input.charCodeAt(e.position+1)===45&&e.input.charCodeAt(e.position+2)===45?(e.position+=3,_(e,!0,-1)):u&&h(e,"directives end mark is expected"),Y(e,e.lineIndent-1,V,!1,!0),_(e,!0,-1),e.checkLineBreaks&&Wi.test(e.input.slice(n,e.position))&&H(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&q(e)){e.input.charCodeAt(e.position)===46&&(e.position+=3,_(e,!0,-1));return}if(e.position"u"&&(i=n,n=null);var l=Ce(e,i);if(typeof n!="function")return l;for(var r=0,u=l.length;r=55296&&i<=56319&&n+1=56320&&l<=57343)?(i-55296)*1024+l-56320+65536:i}f(P,"codePointAt");function be(e){var n=/^\n* /;return n.test(e)}f(be,"needIndentIndicator");var ei=1,he=2,ni=3,ii=4,F=5;function ri(e,n,i,l,r,u,o,c){var a,t=0,d=null,p=!1,s=!1,m=l!==-1,g=-1,A=zn(P(e,0))&&Jn(P(e,e.length-1));if(n||o)for(a=0;a=65536?a+=2:a++){if(t=P(e,a),!D(t))return F;A=A&&pe(t,d,c),d=t}else{for(a=0;a=65536?a+=2:a++){if(t=P(e,a),t===j)p=!0,m&&(s=s||a-g-1>l&&e[g+1]!==" ",g=a);else if(!D(t))return F;A=A&&pe(t,d,c),d=t}s=s||m&&a-g-1>l&&e[g+1]!==" "}return!p&&!s?A&&!o&&!r(e)?ei:u===U?F:he:i>9&&be(e)?F:o?u===U?F:he:s?ii:ni}f(ri,"chooseScalarStyle");function li(e,n,i,l,r){e.dump=(function(){if(n.length===0)return e.quotingType===U?'""':"''";if(!e.noCompatMode&&(pr.indexOf(n)!==-1||hr.test(n)))return e.quotingType===U?'"'+n+'"':"'"+n+"'";var u=e.indent*Math.max(1,i),o=e.lineWidth===-1?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-u),c=l||e.flowLevel>-1&&i>=e.flowLevel;function a(t){return Zn(e,t)}switch(f(a,"testAmbiguity"),ri(n,c,e.indent,o,a,e.quotingType,e.forceQuotes&&!l,r)){case ei:return n;case he:return"'"+n.replace(/'/g,"''")+"'";case ni:return"|"+de(n,e.indent)+se(ae(n,u));case ii:return">"+de(n,e.indent)+se(ae(oi(n,o),u));case F:return'"'+ui(n)+'"';default:throw new x("impossible error: invalid scalar style")}})()}f(li,"writeScalar");function de(e,n){var i=be(e)?String(n):"",l=e[e.length-1]===` +`,r=l&&(e[e.length-2]===` +`||e===` +`),u=r?"+":l?"":"-";return i+u+` +`}f(de,"blockHeader");function se(e){return e[e.length-1]===` +`?e.slice(0,-1):e}f(se,"dropEndingNewline");function oi(e,n){for(var i=/(\n+)([^\n]*)/g,l=(function(){var t=e.indexOf(` +`);return t=t!==-1?t:e.length,i.lastIndex=t,me(e.slice(0,t),n)})(),r=e[0]===` +`||e[0]===" ",u,o;o=i.exec(e);){var c=o[1],a=o[2];u=a[0]===" ",l+=c+(!r&&!u&&a!==""?` +`:"")+me(a,n),r=u}return l}f(oi,"foldString");function me(e,n){if(e===""||e[0]===" ")return e;for(var i=/ [^ ]/g,l,r=0,u,o=0,c=0,a="";l=i.exec(e);)c=l.index,c-r>n&&(u=o>r?o:c,a+=` +`+e.slice(r,u),r=u+1),o=c;return a+=` +`,e.length-r>n&&o>r?a+=e.slice(r,o)+` +`+e.slice(o+1):a+=e.slice(r),a.slice(1)}f(me,"foldLine");function ui(e){for(var n="",i=0,l,r=0;r=65536?r+=2:r++)i=P(e,r),l=S[i],!l&&D(i)?(n+=e[r],i>=65536&&(n+=e[r+1])):n+=l||Vn(i);return n}f(ui,"escapeString");function ci(e,n,i){var l="",r=e.tag,u,o,c;for(u=0,o=i.length;u"u"&&O(e,n,null,!1,!1))&&(l!==""&&(l+=","+(e.condenseFlow?"":" ")),l+=e.dump);e.tag=r,e.dump="["+l+"]"}f(ci,"writeFlowSequence");function ge(e,n,i,l){var r="",u=e.tag,o,c,a;for(o=0,c=i.length;o"u"&&O(e,n+1,null,!0,!0,!1,!0))&&((!l||r!=="")&&(r+=Z(e,n)),e.dump&&j===e.dump.charCodeAt(0)?r+="-":r+="- ",r+=e.dump);e.tag=u,e.dump=r||"[]"}f(ge,"writeBlockSequence");function fi(e,n,i){var l="",r=e.tag,u=Object.keys(i),o,c,a,t,d;for(o=0,c=u.length;o1024&&(d+="? "),d+=e.dump+(e.condenseFlow?'"':"")+":"+(e.condenseFlow?"":" "),O(e,n,t,!1,!1)&&(d+=e.dump,l+=d));e.tag=r,e.dump="{"+l+"}"}f(fi,"writeFlowMapping");function ai(e,n,i,l){var r="",u=e.tag,o=Object.keys(i),c,a,t,d,p,s;if(e.sortKeys===!0)o.sort();else if(typeof e.sortKeys=="function")o.sort(e.sortKeys);else if(e.sortKeys)throw new x("sortKeys must be a boolean or a function");for(c=0,a=o.length;c1024,p&&(e.dump&&j===e.dump.charCodeAt(0)?s+="?":s+="? "),s+=e.dump,p&&(s+=Z(e,n)),O(e,n+1,d,!0,p)&&(e.dump&&j===e.dump.charCodeAt(0)?s+=":":s+=": ",s+=e.dump,r+=s));e.tag=u,e.dump=r||"{}"}f(ai,"writeBlockMapping");function ve(e,n,i){var l,r,u,o,c,a;for(r=i?e.explicitTypes:e.implicitTypes,u=0,o=r.length;u tag resolver accepts not "'+a+'" style');e.dump=l}return!0}return!1}f(ve,"detectType");function O(e,n,i,l,r,u,o){e.tag=null,e.dump=i,ve(e,i,!1)||ve(e,i,!0);var c=jn.call(e.dump),a=l,t;l&&(l=e.flowLevel<0||e.flowLevel>n);var d=c==="[object Object]"||c==="[object Array]",p,s;if(d&&(p=e.duplicates.indexOf(i),s=p!==-1),(e.tag!==null&&e.tag!=="?"||s||e.indent!==2&&n>0)&&(r=!1),s&&e.usedDuplicates[p])e.dump="*ref_"+p;else{if(d&&s&&!e.usedDuplicates[p]&&(e.usedDuplicates[p]=!0),c==="[object Object]")l&&Object.keys(e.dump).length!==0?(ai(e,n,e.dump,r),s&&(e.dump="&ref_"+p+e.dump)):(fi(e,n,e.dump),s&&(e.dump="&ref_"+p+" "+e.dump));else if(c==="[object Array]")l&&e.dump.length!==0?(e.noArrayIndent&&!o&&n>0?ge(e,n-1,e.dump,r):ge(e,n,e.dump,r),s&&(e.dump="&ref_"+p+e.dump)):(ci(e,n,e.dump),s&&(e.dump="&ref_"+p+" "+e.dump));else if(c==="[object String]")e.tag!=="?"&&li(e,e.dump,n,u,a);else{if(c==="[object Undefined]")return!1;if(e.skipInvalid)return!1;throw new x("unacceptable kind of an object to dump "+c)}e.tag!==null&&e.tag!=="?"&&(t=encodeURI(e.tag[0]==="!"?e.tag.slice(1):e.tag).replace(/!/g,"%21"),e.tag[0]==="!"?t="!"+t:t.slice(0,18)==="tag:yaml.org,2002:"?t="!!"+t.slice(18):t="!<"+t+">",e.dump=t+" "+e.dump)}return!0}f(O,"writeNode");function ti(e,n){var i=[],l=[],r,u;for(z(e,i,l),r=0,u=l.length;r maxHalfLength) {\n head = \" ... \";\n lineStart = position - maxHalfLength + head.length;\n }\n if (lineEnd - position > maxHalfLength) {\n tail = \" ...\";\n lineEnd = position + maxHalfLength - tail.length;\n }\n return {\n str: head + buffer.slice(lineStart, lineEnd).replace(/\\t/g, \"\\u2192\") + tail,\n pos: position - lineStart + head.length\n // relative position\n };\n}\n__name(getLine, \"getLine\");\nfunction padStart(string, max) {\n return common.repeat(\" \", max - string.length) + string;\n}\n__name(padStart, \"padStart\");\nfunction makeSnippet(mark, options) {\n options = Object.create(options || null);\n if (!mark.buffer) return null;\n if (!options.maxLength) options.maxLength = 79;\n if (typeof options.indent !== \"number\") options.indent = 1;\n if (typeof options.linesBefore !== \"number\") options.linesBefore = 3;\n if (typeof options.linesAfter !== \"number\") options.linesAfter = 2;\n var re = /\\r?\\n|\\r|\\0/g;\n var lineStarts = [0];\n var lineEnds = [];\n var match;\n var foundLineNo = -1;\n while (match = re.exec(mark.buffer)) {\n lineEnds.push(match.index);\n lineStarts.push(match.index + match[0].length);\n if (mark.position <= match.index && foundLineNo < 0) {\n foundLineNo = lineStarts.length - 2;\n }\n }\n if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;\n var result = \"\", i, line;\n var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;\n var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);\n for (i = 1; i <= options.linesBefore; i++) {\n if (foundLineNo - i < 0) break;\n line = getLine(\n mark.buffer,\n lineStarts[foundLineNo - i],\n lineEnds[foundLineNo - i],\n mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),\n maxLineLength\n );\n result = common.repeat(\" \", options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + \" | \" + line.str + \"\\n\" + result;\n }\n line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);\n result += common.repeat(\" \", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + \" | \" + line.str + \"\\n\";\n result += common.repeat(\"-\", options.indent + lineNoLength + 3 + line.pos) + \"^\\n\";\n for (i = 1; i <= options.linesAfter; i++) {\n if (foundLineNo + i >= lineEnds.length) break;\n line = getLine(\n mark.buffer,\n lineStarts[foundLineNo + i],\n lineEnds[foundLineNo + i],\n mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),\n maxLineLength\n );\n result += common.repeat(\" \", options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + \" | \" + line.str + \"\\n\";\n }\n return result.replace(/\\n$/, \"\");\n}\n__name(makeSnippet, \"makeSnippet\");\nvar snippet = makeSnippet;\nvar TYPE_CONSTRUCTOR_OPTIONS = [\n \"kind\",\n \"multi\",\n \"resolve\",\n \"construct\",\n \"instanceOf\",\n \"predicate\",\n \"represent\",\n \"representName\",\n \"defaultStyle\",\n \"styleAliases\"\n];\nvar YAML_NODE_KINDS = [\n \"scalar\",\n \"sequence\",\n \"mapping\"\n];\nfunction compileStyleAliases(map2) {\n var result = {};\n if (map2 !== null) {\n Object.keys(map2).forEach(function(style) {\n map2[style].forEach(function(alias) {\n result[String(alias)] = style;\n });\n });\n }\n return result;\n}\n__name(compileStyleAliases, \"compileStyleAliases\");\nfunction Type$1(tag, options) {\n options = options || {};\n Object.keys(options).forEach(function(name) {\n if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {\n throw new exception('Unknown option \"' + name + '\" is met in definition of \"' + tag + '\" YAML type.');\n }\n });\n this.options = options;\n this.tag = tag;\n this.kind = options[\"kind\"] || null;\n this.resolve = options[\"resolve\"] || function() {\n return true;\n };\n this.construct = options[\"construct\"] || function(data) {\n return data;\n };\n this.instanceOf = options[\"instanceOf\"] || null;\n this.predicate = options[\"predicate\"] || null;\n this.represent = options[\"represent\"] || null;\n this.representName = options[\"representName\"] || null;\n this.defaultStyle = options[\"defaultStyle\"] || null;\n this.multi = options[\"multi\"] || false;\n this.styleAliases = compileStyleAliases(options[\"styleAliases\"] || null);\n if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {\n throw new exception('Unknown kind \"' + this.kind + '\" is specified for \"' + tag + '\" YAML type.');\n }\n}\n__name(Type$1, \"Type$1\");\nvar type = Type$1;\nfunction compileList(schema2, name) {\n var result = [];\n schema2[name].forEach(function(currentType) {\n var newIndex = result.length;\n result.forEach(function(previousType, previousIndex) {\n if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) {\n newIndex = previousIndex;\n }\n });\n result[newIndex] = currentType;\n });\n return result;\n}\n__name(compileList, \"compileList\");\nfunction compileMap() {\n var result = {\n scalar: {},\n sequence: {},\n mapping: {},\n fallback: {},\n multi: {\n scalar: [],\n sequence: [],\n mapping: [],\n fallback: []\n }\n }, index, length;\n function collectType(type2) {\n if (type2.multi) {\n result.multi[type2.kind].push(type2);\n result.multi[\"fallback\"].push(type2);\n } else {\n result[type2.kind][type2.tag] = result[\"fallback\"][type2.tag] = type2;\n }\n }\n __name(collectType, \"collectType\");\n for (index = 0, length = arguments.length; index < length; index += 1) {\n arguments[index].forEach(collectType);\n }\n return result;\n}\n__name(compileMap, \"compileMap\");\nfunction Schema$1(definition) {\n return this.extend(definition);\n}\n__name(Schema$1, \"Schema$1\");\nSchema$1.prototype.extend = /* @__PURE__ */ __name(function extend2(definition) {\n var implicit = [];\n var explicit = [];\n if (definition instanceof type) {\n explicit.push(definition);\n } else if (Array.isArray(definition)) {\n explicit = explicit.concat(definition);\n } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {\n if (definition.implicit) implicit = implicit.concat(definition.implicit);\n if (definition.explicit) explicit = explicit.concat(definition.explicit);\n } else {\n throw new exception(\"Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })\");\n }\n implicit.forEach(function(type$1) {\n if (!(type$1 instanceof type)) {\n throw new exception(\"Specified list of YAML types (or a single Type object) contains a non-Type object.\");\n }\n if (type$1.loadKind && type$1.loadKind !== \"scalar\") {\n throw new exception(\"There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.\");\n }\n if (type$1.multi) {\n throw new exception(\"There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.\");\n }\n });\n explicit.forEach(function(type$1) {\n if (!(type$1 instanceof type)) {\n throw new exception(\"Specified list of YAML types (or a single Type object) contains a non-Type object.\");\n }\n });\n var result = Object.create(Schema$1.prototype);\n result.implicit = (this.implicit || []).concat(implicit);\n result.explicit = (this.explicit || []).concat(explicit);\n result.compiledImplicit = compileList(result, \"implicit\");\n result.compiledExplicit = compileList(result, \"explicit\");\n result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);\n return result;\n}, \"extend\");\nvar schema = Schema$1;\nvar str = new type(\"tag:yaml.org,2002:str\", {\n kind: \"scalar\",\n construct: /* @__PURE__ */ __name(function(data) {\n return data !== null ? data : \"\";\n }, \"construct\")\n});\nvar seq = new type(\"tag:yaml.org,2002:seq\", {\n kind: \"sequence\",\n construct: /* @__PURE__ */ __name(function(data) {\n return data !== null ? data : [];\n }, \"construct\")\n});\nvar map = new type(\"tag:yaml.org,2002:map\", {\n kind: \"mapping\",\n construct: /* @__PURE__ */ __name(function(data) {\n return data !== null ? data : {};\n }, \"construct\")\n});\nvar failsafe = new schema({\n explicit: [\n str,\n seq,\n map\n ]\n});\nfunction resolveYamlNull(data) {\n if (data === null) return true;\n var max = data.length;\n return max === 1 && data === \"~\" || max === 4 && (data === \"null\" || data === \"Null\" || data === \"NULL\");\n}\n__name(resolveYamlNull, \"resolveYamlNull\");\nfunction constructYamlNull() {\n return null;\n}\n__name(constructYamlNull, \"constructYamlNull\");\nfunction isNull(object) {\n return object === null;\n}\n__name(isNull, \"isNull\");\nvar _null = new type(\"tag:yaml.org,2002:null\", {\n kind: \"scalar\",\n resolve: resolveYamlNull,\n construct: constructYamlNull,\n predicate: isNull,\n represent: {\n canonical: /* @__PURE__ */ __name(function() {\n return \"~\";\n }, \"canonical\"),\n lowercase: /* @__PURE__ */ __name(function() {\n return \"null\";\n }, \"lowercase\"),\n uppercase: /* @__PURE__ */ __name(function() {\n return \"NULL\";\n }, \"uppercase\"),\n camelcase: /* @__PURE__ */ __name(function() {\n return \"Null\";\n }, \"camelcase\"),\n empty: /* @__PURE__ */ __name(function() {\n return \"\";\n }, \"empty\")\n },\n defaultStyle: \"lowercase\"\n});\nfunction resolveYamlBoolean(data) {\n if (data === null) return false;\n var max = data.length;\n return max === 4 && (data === \"true\" || data === \"True\" || data === \"TRUE\") || max === 5 && (data === \"false\" || data === \"False\" || data === \"FALSE\");\n}\n__name(resolveYamlBoolean, \"resolveYamlBoolean\");\nfunction constructYamlBoolean(data) {\n return data === \"true\" || data === \"True\" || data === \"TRUE\";\n}\n__name(constructYamlBoolean, \"constructYamlBoolean\");\nfunction isBoolean(object) {\n return Object.prototype.toString.call(object) === \"[object Boolean]\";\n}\n__name(isBoolean, \"isBoolean\");\nvar bool = new type(\"tag:yaml.org,2002:bool\", {\n kind: \"scalar\",\n resolve: resolveYamlBoolean,\n construct: constructYamlBoolean,\n predicate: isBoolean,\n represent: {\n lowercase: /* @__PURE__ */ __name(function(object) {\n return object ? \"true\" : \"false\";\n }, \"lowercase\"),\n uppercase: /* @__PURE__ */ __name(function(object) {\n return object ? \"TRUE\" : \"FALSE\";\n }, \"uppercase\"),\n camelcase: /* @__PURE__ */ __name(function(object) {\n return object ? \"True\" : \"False\";\n }, \"camelcase\")\n },\n defaultStyle: \"lowercase\"\n});\nfunction isHexCode(c) {\n return 48 <= c && c <= 57 || 65 <= c && c <= 70 || 97 <= c && c <= 102;\n}\n__name(isHexCode, \"isHexCode\");\nfunction isOctCode(c) {\n return 48 <= c && c <= 55;\n}\n__name(isOctCode, \"isOctCode\");\nfunction isDecCode(c) {\n return 48 <= c && c <= 57;\n}\n__name(isDecCode, \"isDecCode\");\nfunction resolveYamlInteger(data) {\n if (data === null) return false;\n var max = data.length, index = 0, hasDigits = false, ch;\n if (!max) return false;\n ch = data[index];\n if (ch === \"-\" || ch === \"+\") {\n ch = data[++index];\n }\n if (ch === \"0\") {\n if (index + 1 === max) return true;\n ch = data[++index];\n if (ch === \"b\") {\n index++;\n for (; index < max; index++) {\n ch = data[index];\n if (ch === \"_\") continue;\n if (ch !== \"0\" && ch !== \"1\") return false;\n hasDigits = true;\n }\n return hasDigits && ch !== \"_\";\n }\n if (ch === \"x\") {\n index++;\n for (; index < max; index++) {\n ch = data[index];\n if (ch === \"_\") continue;\n if (!isHexCode(data.charCodeAt(index))) return false;\n hasDigits = true;\n }\n return hasDigits && ch !== \"_\";\n }\n if (ch === \"o\") {\n index++;\n for (; index < max; index++) {\n ch = data[index];\n if (ch === \"_\") continue;\n if (!isOctCode(data.charCodeAt(index))) return false;\n hasDigits = true;\n }\n return hasDigits && ch !== \"_\";\n }\n }\n if (ch === \"_\") return false;\n for (; index < max; index++) {\n ch = data[index];\n if (ch === \"_\") continue;\n if (!isDecCode(data.charCodeAt(index))) {\n return false;\n }\n hasDigits = true;\n }\n if (!hasDigits || ch === \"_\") return false;\n return true;\n}\n__name(resolveYamlInteger, \"resolveYamlInteger\");\nfunction constructYamlInteger(data) {\n var value = data, sign = 1, ch;\n if (value.indexOf(\"_\") !== -1) {\n value = value.replace(/_/g, \"\");\n }\n ch = value[0];\n if (ch === \"-\" || ch === \"+\") {\n if (ch === \"-\") sign = -1;\n value = value.slice(1);\n ch = value[0];\n }\n if (value === \"0\") return 0;\n if (ch === \"0\") {\n if (value[1] === \"b\") return sign * parseInt(value.slice(2), 2);\n if (value[1] === \"x\") return sign * parseInt(value.slice(2), 16);\n if (value[1] === \"o\") return sign * parseInt(value.slice(2), 8);\n }\n return sign * parseInt(value, 10);\n}\n__name(constructYamlInteger, \"constructYamlInteger\");\nfunction isInteger(object) {\n return Object.prototype.toString.call(object) === \"[object Number]\" && (object % 1 === 0 && !common.isNegativeZero(object));\n}\n__name(isInteger, \"isInteger\");\nvar int = new type(\"tag:yaml.org,2002:int\", {\n kind: \"scalar\",\n resolve: resolveYamlInteger,\n construct: constructYamlInteger,\n predicate: isInteger,\n represent: {\n binary: /* @__PURE__ */ __name(function(obj) {\n return obj >= 0 ? \"0b\" + obj.toString(2) : \"-0b\" + obj.toString(2).slice(1);\n }, \"binary\"),\n octal: /* @__PURE__ */ __name(function(obj) {\n return obj >= 0 ? \"0o\" + obj.toString(8) : \"-0o\" + obj.toString(8).slice(1);\n }, \"octal\"),\n decimal: /* @__PURE__ */ __name(function(obj) {\n return obj.toString(10);\n }, \"decimal\"),\n /* eslint-disable max-len */\n hexadecimal: /* @__PURE__ */ __name(function(obj) {\n return obj >= 0 ? \"0x\" + obj.toString(16).toUpperCase() : \"-0x\" + obj.toString(16).toUpperCase().slice(1);\n }, \"hexadecimal\")\n },\n defaultStyle: \"decimal\",\n styleAliases: {\n binary: [2, \"bin\"],\n octal: [8, \"oct\"],\n decimal: [10, \"dec\"],\n hexadecimal: [16, \"hex\"]\n }\n});\nvar YAML_FLOAT_PATTERN = new RegExp(\n // 2.5e4, 2.5 and integers\n \"^(?:[-+]?(?:[0-9][0-9_]*)(?:\\\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\\\.(?:inf|Inf|INF)|\\\\.(?:nan|NaN|NAN))$\"\n);\nfunction resolveYamlFloat(data) {\n if (data === null) return false;\n if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_`\n // Probably should update regexp & check speed\n data[data.length - 1] === \"_\") {\n return false;\n }\n return true;\n}\n__name(resolveYamlFloat, \"resolveYamlFloat\");\nfunction constructYamlFloat(data) {\n var value, sign;\n value = data.replace(/_/g, \"\").toLowerCase();\n sign = value[0] === \"-\" ? -1 : 1;\n if (\"+-\".indexOf(value[0]) >= 0) {\n value = value.slice(1);\n }\n if (value === \".inf\") {\n return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;\n } else if (value === \".nan\") {\n return NaN;\n }\n return sign * parseFloat(value, 10);\n}\n__name(constructYamlFloat, \"constructYamlFloat\");\nvar SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;\nfunction representYamlFloat(object, style) {\n var res;\n if (isNaN(object)) {\n switch (style) {\n case \"lowercase\":\n return \".nan\";\n case \"uppercase\":\n return \".NAN\";\n case \"camelcase\":\n return \".NaN\";\n }\n } else if (Number.POSITIVE_INFINITY === object) {\n switch (style) {\n case \"lowercase\":\n return \".inf\";\n case \"uppercase\":\n return \".INF\";\n case \"camelcase\":\n return \".Inf\";\n }\n } else if (Number.NEGATIVE_INFINITY === object) {\n switch (style) {\n case \"lowercase\":\n return \"-.inf\";\n case \"uppercase\":\n return \"-.INF\";\n case \"camelcase\":\n return \"-.Inf\";\n }\n } else if (common.isNegativeZero(object)) {\n return \"-0.0\";\n }\n res = object.toString(10);\n return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace(\"e\", \".e\") : res;\n}\n__name(representYamlFloat, \"representYamlFloat\");\nfunction isFloat(object) {\n return Object.prototype.toString.call(object) === \"[object Number]\" && (object % 1 !== 0 || common.isNegativeZero(object));\n}\n__name(isFloat, \"isFloat\");\nvar float = new type(\"tag:yaml.org,2002:float\", {\n kind: \"scalar\",\n resolve: resolveYamlFloat,\n construct: constructYamlFloat,\n predicate: isFloat,\n represent: representYamlFloat,\n defaultStyle: \"lowercase\"\n});\nvar json = failsafe.extend({\n implicit: [\n _null,\n bool,\n int,\n float\n ]\n});\nvar core = json;\nvar YAML_DATE_REGEXP = new RegExp(\n \"^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$\"\n);\nvar YAML_TIMESTAMP_REGEXP = new RegExp(\n \"^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\\\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\\\.([0-9]*))?(?:[ \\\\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$\"\n);\nfunction resolveYamlTimestamp(data) {\n if (data === null) return false;\n if (YAML_DATE_REGEXP.exec(data) !== null) return true;\n if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;\n return false;\n}\n__name(resolveYamlTimestamp, \"resolveYamlTimestamp\");\nfunction constructYamlTimestamp(data) {\n var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date;\n match = YAML_DATE_REGEXP.exec(data);\n if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);\n if (match === null) throw new Error(\"Date resolve error\");\n year = +match[1];\n month = +match[2] - 1;\n day = +match[3];\n if (!match[4]) {\n return new Date(Date.UTC(year, month, day));\n }\n hour = +match[4];\n minute = +match[5];\n second = +match[6];\n if (match[7]) {\n fraction = match[7].slice(0, 3);\n while (fraction.length < 3) {\n fraction += \"0\";\n }\n fraction = +fraction;\n }\n if (match[9]) {\n tz_hour = +match[10];\n tz_minute = +(match[11] || 0);\n delta = (tz_hour * 60 + tz_minute) * 6e4;\n if (match[9] === \"-\") delta = -delta;\n }\n date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));\n if (delta) date.setTime(date.getTime() - delta);\n return date;\n}\n__name(constructYamlTimestamp, \"constructYamlTimestamp\");\nfunction representYamlTimestamp(object) {\n return object.toISOString();\n}\n__name(representYamlTimestamp, \"representYamlTimestamp\");\nvar timestamp = new type(\"tag:yaml.org,2002:timestamp\", {\n kind: \"scalar\",\n resolve: resolveYamlTimestamp,\n construct: constructYamlTimestamp,\n instanceOf: Date,\n represent: representYamlTimestamp\n});\nfunction resolveYamlMerge(data) {\n return data === \"<<\" || data === null;\n}\n__name(resolveYamlMerge, \"resolveYamlMerge\");\nvar merge = new type(\"tag:yaml.org,2002:merge\", {\n kind: \"scalar\",\n resolve: resolveYamlMerge\n});\nvar BASE64_MAP = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\\n\\r\";\nfunction resolveYamlBinary(data) {\n if (data === null) return false;\n var code, idx, bitlen = 0, max = data.length, map2 = BASE64_MAP;\n for (idx = 0; idx < max; idx++) {\n code = map2.indexOf(data.charAt(idx));\n if (code > 64) continue;\n if (code < 0) return false;\n bitlen += 6;\n }\n return bitlen % 8 === 0;\n}\n__name(resolveYamlBinary, \"resolveYamlBinary\");\nfunction constructYamlBinary(data) {\n var idx, tailbits, input = data.replace(/[\\r\\n=]/g, \"\"), max = input.length, map2 = BASE64_MAP, bits = 0, result = [];\n for (idx = 0; idx < max; idx++) {\n if (idx % 4 === 0 && idx) {\n result.push(bits >> 16 & 255);\n result.push(bits >> 8 & 255);\n result.push(bits & 255);\n }\n bits = bits << 6 | map2.indexOf(input.charAt(idx));\n }\n tailbits = max % 4 * 6;\n if (tailbits === 0) {\n result.push(bits >> 16 & 255);\n result.push(bits >> 8 & 255);\n result.push(bits & 255);\n } else if (tailbits === 18) {\n result.push(bits >> 10 & 255);\n result.push(bits >> 2 & 255);\n } else if (tailbits === 12) {\n result.push(bits >> 4 & 255);\n }\n return new Uint8Array(result);\n}\n__name(constructYamlBinary, \"constructYamlBinary\");\nfunction representYamlBinary(object) {\n var result = \"\", bits = 0, idx, tail, max = object.length, map2 = BASE64_MAP;\n for (idx = 0; idx < max; idx++) {\n if (idx % 3 === 0 && idx) {\n result += map2[bits >> 18 & 63];\n result += map2[bits >> 12 & 63];\n result += map2[bits >> 6 & 63];\n result += map2[bits & 63];\n }\n bits = (bits << 8) + object[idx];\n }\n tail = max % 3;\n if (tail === 0) {\n result += map2[bits >> 18 & 63];\n result += map2[bits >> 12 & 63];\n result += map2[bits >> 6 & 63];\n result += map2[bits & 63];\n } else if (tail === 2) {\n result += map2[bits >> 10 & 63];\n result += map2[bits >> 4 & 63];\n result += map2[bits << 2 & 63];\n result += map2[64];\n } else if (tail === 1) {\n result += map2[bits >> 2 & 63];\n result += map2[bits << 4 & 63];\n result += map2[64];\n result += map2[64];\n }\n return result;\n}\n__name(representYamlBinary, \"representYamlBinary\");\nfunction isBinary(obj) {\n return Object.prototype.toString.call(obj) === \"[object Uint8Array]\";\n}\n__name(isBinary, \"isBinary\");\nvar binary = new type(\"tag:yaml.org,2002:binary\", {\n kind: \"scalar\",\n resolve: resolveYamlBinary,\n construct: constructYamlBinary,\n predicate: isBinary,\n represent: representYamlBinary\n});\nvar _hasOwnProperty$3 = Object.prototype.hasOwnProperty;\nvar _toString$2 = Object.prototype.toString;\nfunction resolveYamlOmap(data) {\n if (data === null) return true;\n var objectKeys = [], index, length, pair, pairKey, pairHasKey, object = data;\n for (index = 0, length = object.length; index < length; index += 1) {\n pair = object[index];\n pairHasKey = false;\n if (_toString$2.call(pair) !== \"[object Object]\") return false;\n for (pairKey in pair) {\n if (_hasOwnProperty$3.call(pair, pairKey)) {\n if (!pairHasKey) pairHasKey = true;\n else return false;\n }\n }\n if (!pairHasKey) return false;\n if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);\n else return false;\n }\n return true;\n}\n__name(resolveYamlOmap, \"resolveYamlOmap\");\nfunction constructYamlOmap(data) {\n return data !== null ? data : [];\n}\n__name(constructYamlOmap, \"constructYamlOmap\");\nvar omap = new type(\"tag:yaml.org,2002:omap\", {\n kind: \"sequence\",\n resolve: resolveYamlOmap,\n construct: constructYamlOmap\n});\nvar _toString$1 = Object.prototype.toString;\nfunction resolveYamlPairs(data) {\n if (data === null) return true;\n var index, length, pair, keys, result, object = data;\n result = new Array(object.length);\n for (index = 0, length = object.length; index < length; index += 1) {\n pair = object[index];\n if (_toString$1.call(pair) !== \"[object Object]\") return false;\n keys = Object.keys(pair);\n if (keys.length !== 1) return false;\n result[index] = [keys[0], pair[keys[0]]];\n }\n return true;\n}\n__name(resolveYamlPairs, \"resolveYamlPairs\");\nfunction constructYamlPairs(data) {\n if (data === null) return [];\n var index, length, pair, keys, result, object = data;\n result = new Array(object.length);\n for (index = 0, length = object.length; index < length; index += 1) {\n pair = object[index];\n keys = Object.keys(pair);\n result[index] = [keys[0], pair[keys[0]]];\n }\n return result;\n}\n__name(constructYamlPairs, \"constructYamlPairs\");\nvar pairs = new type(\"tag:yaml.org,2002:pairs\", {\n kind: \"sequence\",\n resolve: resolveYamlPairs,\n construct: constructYamlPairs\n});\nvar _hasOwnProperty$2 = Object.prototype.hasOwnProperty;\nfunction resolveYamlSet(data) {\n if (data === null) return true;\n var key, object = data;\n for (key in object) {\n if (_hasOwnProperty$2.call(object, key)) {\n if (object[key] !== null) return false;\n }\n }\n return true;\n}\n__name(resolveYamlSet, \"resolveYamlSet\");\nfunction constructYamlSet(data) {\n return data !== null ? data : {};\n}\n__name(constructYamlSet, \"constructYamlSet\");\nvar set = new type(\"tag:yaml.org,2002:set\", {\n kind: \"mapping\",\n resolve: resolveYamlSet,\n construct: constructYamlSet\n});\nvar _default = core.extend({\n implicit: [\n timestamp,\n merge\n ],\n explicit: [\n binary,\n omap,\n pairs,\n set\n ]\n});\nvar _hasOwnProperty$1 = Object.prototype.hasOwnProperty;\nvar CONTEXT_FLOW_IN = 1;\nvar CONTEXT_FLOW_OUT = 2;\nvar CONTEXT_BLOCK_IN = 3;\nvar CONTEXT_BLOCK_OUT = 4;\nvar CHOMPING_CLIP = 1;\nvar CHOMPING_STRIP = 2;\nvar CHOMPING_KEEP = 3;\nvar PATTERN_NON_PRINTABLE = /[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F-\\x84\\x86-\\x9F\\uFFFE\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]/;\nvar PATTERN_NON_ASCII_LINE_BREAKS = /[\\x85\\u2028\\u2029]/;\nvar PATTERN_FLOW_INDICATORS = /[,\\[\\]\\{\\}]/;\nvar PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\\-]+!)$/i;\nvar PATTERN_TAG_URI = /^(?:!|[^,\\[\\]\\{\\}])(?:%[0-9a-f]{2}|[0-9a-z\\-#;\\/\\?:@&=\\+\\$,_\\.!~\\*'\\(\\)\\[\\]])*$/i;\nfunction _class(obj) {\n return Object.prototype.toString.call(obj);\n}\n__name(_class, \"_class\");\nfunction is_EOL(c) {\n return c === 10 || c === 13;\n}\n__name(is_EOL, \"is_EOL\");\nfunction is_WHITE_SPACE(c) {\n return c === 9 || c === 32;\n}\n__name(is_WHITE_SPACE, \"is_WHITE_SPACE\");\nfunction is_WS_OR_EOL(c) {\n return c === 9 || c === 32 || c === 10 || c === 13;\n}\n__name(is_WS_OR_EOL, \"is_WS_OR_EOL\");\nfunction is_FLOW_INDICATOR(c) {\n return c === 44 || c === 91 || c === 93 || c === 123 || c === 125;\n}\n__name(is_FLOW_INDICATOR, \"is_FLOW_INDICATOR\");\nfunction fromHexCode(c) {\n var lc;\n if (48 <= c && c <= 57) {\n return c - 48;\n }\n lc = c | 32;\n if (97 <= lc && lc <= 102) {\n return lc - 97 + 10;\n }\n return -1;\n}\n__name(fromHexCode, \"fromHexCode\");\nfunction escapedHexLen(c) {\n if (c === 120) {\n return 2;\n }\n if (c === 117) {\n return 4;\n }\n if (c === 85) {\n return 8;\n }\n return 0;\n}\n__name(escapedHexLen, \"escapedHexLen\");\nfunction fromDecimalCode(c) {\n if (48 <= c && c <= 57) {\n return c - 48;\n }\n return -1;\n}\n__name(fromDecimalCode, \"fromDecimalCode\");\nfunction simpleEscapeSequence(c) {\n return c === 48 ? \"\\0\" : c === 97 ? \"\\x07\" : c === 98 ? \"\\b\" : c === 116 ? \"\t\" : c === 9 ? \"\t\" : c === 110 ? \"\\n\" : c === 118 ? \"\\v\" : c === 102 ? \"\\f\" : c === 114 ? \"\\r\" : c === 101 ? \"\\x1B\" : c === 32 ? \" \" : c === 34 ? '\"' : c === 47 ? \"/\" : c === 92 ? \"\\\\\" : c === 78 ? \"\\x85\" : c === 95 ? \"\\xA0\" : c === 76 ? \"\\u2028\" : c === 80 ? \"\\u2029\" : \"\";\n}\n__name(simpleEscapeSequence, \"simpleEscapeSequence\");\nfunction charFromCodepoint(c) {\n if (c <= 65535) {\n return String.fromCharCode(c);\n }\n return String.fromCharCode(\n (c - 65536 >> 10) + 55296,\n (c - 65536 & 1023) + 56320\n );\n}\n__name(charFromCodepoint, \"charFromCodepoint\");\nvar simpleEscapeCheck = new Array(256);\nvar simpleEscapeMap = new Array(256);\nfor (i = 0; i < 256; i++) {\n simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;\n simpleEscapeMap[i] = simpleEscapeSequence(i);\n}\nvar i;\nfunction State$1(input, options) {\n this.input = input;\n this.filename = options[\"filename\"] || null;\n this.schema = options[\"schema\"] || _default;\n this.onWarning = options[\"onWarning\"] || null;\n this.legacy = options[\"legacy\"] || false;\n this.json = options[\"json\"] || false;\n this.listener = options[\"listener\"] || null;\n this.implicitTypes = this.schema.compiledImplicit;\n this.typeMap = this.schema.compiledTypeMap;\n this.length = input.length;\n this.position = 0;\n this.line = 0;\n this.lineStart = 0;\n this.lineIndent = 0;\n this.firstTabInLine = -1;\n this.documents = [];\n}\n__name(State$1, \"State$1\");\nfunction generateError(state, message) {\n var mark = {\n name: state.filename,\n buffer: state.input.slice(0, -1),\n // omit trailing \\0\n position: state.position,\n line: state.line,\n column: state.position - state.lineStart\n };\n mark.snippet = snippet(mark);\n return new exception(message, mark);\n}\n__name(generateError, \"generateError\");\nfunction throwError(state, message) {\n throw generateError(state, message);\n}\n__name(throwError, \"throwError\");\nfunction throwWarning(state, message) {\n if (state.onWarning) {\n state.onWarning.call(null, generateError(state, message));\n }\n}\n__name(throwWarning, \"throwWarning\");\nvar directiveHandlers = {\n YAML: /* @__PURE__ */ __name(function handleYamlDirective(state, name, args) {\n var match, major, minor;\n if (state.version !== null) {\n throwError(state, \"duplication of %YAML directive\");\n }\n if (args.length !== 1) {\n throwError(state, \"YAML directive accepts exactly one argument\");\n }\n match = /^([0-9]+)\\.([0-9]+)$/.exec(args[0]);\n if (match === null) {\n throwError(state, \"ill-formed argument of the YAML directive\");\n }\n major = parseInt(match[1], 10);\n minor = parseInt(match[2], 10);\n if (major !== 1) {\n throwError(state, \"unacceptable YAML version of the document\");\n }\n state.version = args[0];\n state.checkLineBreaks = minor < 2;\n if (minor !== 1 && minor !== 2) {\n throwWarning(state, \"unsupported YAML version of the document\");\n }\n }, \"handleYamlDirective\"),\n TAG: /* @__PURE__ */ __name(function handleTagDirective(state, name, args) {\n var handle, prefix;\n if (args.length !== 2) {\n throwError(state, \"TAG directive accepts exactly two arguments\");\n }\n handle = args[0];\n prefix = args[1];\n if (!PATTERN_TAG_HANDLE.test(handle)) {\n throwError(state, \"ill-formed tag handle (first argument) of the TAG directive\");\n }\n if (_hasOwnProperty$1.call(state.tagMap, handle)) {\n throwError(state, 'there is a previously declared suffix for \"' + handle + '\" tag handle');\n }\n if (!PATTERN_TAG_URI.test(prefix)) {\n throwError(state, \"ill-formed tag prefix (second argument) of the TAG directive\");\n }\n try {\n prefix = decodeURIComponent(prefix);\n } catch (err) {\n throwError(state, \"tag prefix is malformed: \" + prefix);\n }\n state.tagMap[handle] = prefix;\n }, \"handleTagDirective\")\n};\nfunction captureSegment(state, start, end, checkJson) {\n var _position, _length, _character, _result;\n if (start < end) {\n _result = state.input.slice(start, end);\n if (checkJson) {\n for (_position = 0, _length = _result.length; _position < _length; _position += 1) {\n _character = _result.charCodeAt(_position);\n if (!(_character === 9 || 32 <= _character && _character <= 1114111)) {\n throwError(state, \"expected valid JSON character\");\n }\n }\n } else if (PATTERN_NON_PRINTABLE.test(_result)) {\n throwError(state, \"the stream contains non-printable characters\");\n }\n state.result += _result;\n }\n}\n__name(captureSegment, \"captureSegment\");\nfunction mergeMappings(state, destination, source, overridableKeys) {\n var sourceKeys, key, index, quantity;\n if (!common.isObject(source)) {\n throwError(state, \"cannot merge mappings; the provided source object is unacceptable\");\n }\n sourceKeys = Object.keys(source);\n for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {\n key = sourceKeys[index];\n if (!_hasOwnProperty$1.call(destination, key)) {\n destination[key] = source[key];\n overridableKeys[key] = true;\n }\n }\n}\n__name(mergeMappings, \"mergeMappings\");\nfunction storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) {\n var index, quantity;\n if (Array.isArray(keyNode)) {\n keyNode = Array.prototype.slice.call(keyNode);\n for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {\n if (Array.isArray(keyNode[index])) {\n throwError(state, \"nested arrays are not supported inside keys\");\n }\n if (typeof keyNode === \"object\" && _class(keyNode[index]) === \"[object Object]\") {\n keyNode[index] = \"[object Object]\";\n }\n }\n }\n if (typeof keyNode === \"object\" && _class(keyNode) === \"[object Object]\") {\n keyNode = \"[object Object]\";\n }\n keyNode = String(keyNode);\n if (_result === null) {\n _result = {};\n }\n if (keyTag === \"tag:yaml.org,2002:merge\") {\n if (Array.isArray(valueNode)) {\n for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {\n mergeMappings(state, _result, valueNode[index], overridableKeys);\n }\n } else {\n mergeMappings(state, _result, valueNode, overridableKeys);\n }\n } else {\n if (!state.json && !_hasOwnProperty$1.call(overridableKeys, keyNode) && _hasOwnProperty$1.call(_result, keyNode)) {\n state.line = startLine || state.line;\n state.lineStart = startLineStart || state.lineStart;\n state.position = startPos || state.position;\n throwError(state, \"duplicated mapping key\");\n }\n if (keyNode === \"__proto__\") {\n Object.defineProperty(_result, keyNode, {\n configurable: true,\n enumerable: true,\n writable: true,\n value: valueNode\n });\n } else {\n _result[keyNode] = valueNode;\n }\n delete overridableKeys[keyNode];\n }\n return _result;\n}\n__name(storeMappingPair, \"storeMappingPair\");\nfunction readLineBreak(state) {\n var ch;\n ch = state.input.charCodeAt(state.position);\n if (ch === 10) {\n state.position++;\n } else if (ch === 13) {\n state.position++;\n if (state.input.charCodeAt(state.position) === 10) {\n state.position++;\n }\n } else {\n throwError(state, \"a line break is expected\");\n }\n state.line += 1;\n state.lineStart = state.position;\n state.firstTabInLine = -1;\n}\n__name(readLineBreak, \"readLineBreak\");\nfunction skipSeparationSpace(state, allowComments, checkIndent) {\n var lineBreaks = 0, ch = state.input.charCodeAt(state.position);\n while (ch !== 0) {\n while (is_WHITE_SPACE(ch)) {\n if (ch === 9 && state.firstTabInLine === -1) {\n state.firstTabInLine = state.position;\n }\n ch = state.input.charCodeAt(++state.position);\n }\n if (allowComments && ch === 35) {\n do {\n ch = state.input.charCodeAt(++state.position);\n } while (ch !== 10 && ch !== 13 && ch !== 0);\n }\n if (is_EOL(ch)) {\n readLineBreak(state);\n ch = state.input.charCodeAt(state.position);\n lineBreaks++;\n state.lineIndent = 0;\n while (ch === 32) {\n state.lineIndent++;\n ch = state.input.charCodeAt(++state.position);\n }\n } else {\n break;\n }\n }\n if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {\n throwWarning(state, \"deficient indentation\");\n }\n return lineBreaks;\n}\n__name(skipSeparationSpace, \"skipSeparationSpace\");\nfunction testDocumentSeparator(state) {\n var _position = state.position, ch;\n ch = state.input.charCodeAt(_position);\n if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) {\n _position += 3;\n ch = state.input.charCodeAt(_position);\n if (ch === 0 || is_WS_OR_EOL(ch)) {\n return true;\n }\n }\n return false;\n}\n__name(testDocumentSeparator, \"testDocumentSeparator\");\nfunction writeFoldedLines(state, count) {\n if (count === 1) {\n state.result += \" \";\n } else if (count > 1) {\n state.result += common.repeat(\"\\n\", count - 1);\n }\n}\n__name(writeFoldedLines, \"writeFoldedLines\");\nfunction readPlainScalar(state, nodeIndent, withinFlowCollection) {\n var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch;\n ch = state.input.charCodeAt(state.position);\n if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) {\n return false;\n }\n if (ch === 63 || ch === 45) {\n following = state.input.charCodeAt(state.position + 1);\n if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {\n return false;\n }\n }\n state.kind = \"scalar\";\n state.result = \"\";\n captureStart = captureEnd = state.position;\n hasPendingContent = false;\n while (ch !== 0) {\n if (ch === 58) {\n following = state.input.charCodeAt(state.position + 1);\n if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {\n break;\n }\n } else if (ch === 35) {\n preceding = state.input.charCodeAt(state.position - 1);\n if (is_WS_OR_EOL(preceding)) {\n break;\n }\n } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && is_FLOW_INDICATOR(ch)) {\n break;\n } else if (is_EOL(ch)) {\n _line = state.line;\n _lineStart = state.lineStart;\n _lineIndent = state.lineIndent;\n skipSeparationSpace(state, false, -1);\n if (state.lineIndent >= nodeIndent) {\n hasPendingContent = true;\n ch = state.input.charCodeAt(state.position);\n continue;\n } else {\n state.position = captureEnd;\n state.line = _line;\n state.lineStart = _lineStart;\n state.lineIndent = _lineIndent;\n break;\n }\n }\n if (hasPendingContent) {\n captureSegment(state, captureStart, captureEnd, false);\n writeFoldedLines(state, state.line - _line);\n captureStart = captureEnd = state.position;\n hasPendingContent = false;\n }\n if (!is_WHITE_SPACE(ch)) {\n captureEnd = state.position + 1;\n }\n ch = state.input.charCodeAt(++state.position);\n }\n captureSegment(state, captureStart, captureEnd, false);\n if (state.result) {\n return true;\n }\n state.kind = _kind;\n state.result = _result;\n return false;\n}\n__name(readPlainScalar, \"readPlainScalar\");\nfunction readSingleQuotedScalar(state, nodeIndent) {\n var ch, captureStart, captureEnd;\n ch = state.input.charCodeAt(state.position);\n if (ch !== 39) {\n return false;\n }\n state.kind = \"scalar\";\n state.result = \"\";\n state.position++;\n captureStart = captureEnd = state.position;\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n if (ch === 39) {\n captureSegment(state, captureStart, state.position, true);\n ch = state.input.charCodeAt(++state.position);\n if (ch === 39) {\n captureStart = state.position;\n state.position++;\n captureEnd = state.position;\n } else {\n return true;\n }\n } else if (is_EOL(ch)) {\n captureSegment(state, captureStart, captureEnd, true);\n writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));\n captureStart = captureEnd = state.position;\n } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n throwError(state, \"unexpected end of the document within a single quoted scalar\");\n } else {\n state.position++;\n captureEnd = state.position;\n }\n }\n throwError(state, \"unexpected end of the stream within a single quoted scalar\");\n}\n__name(readSingleQuotedScalar, \"readSingleQuotedScalar\");\nfunction readDoubleQuotedScalar(state, nodeIndent) {\n var captureStart, captureEnd, hexLength, hexResult, tmp, ch;\n ch = state.input.charCodeAt(state.position);\n if (ch !== 34) {\n return false;\n }\n state.kind = \"scalar\";\n state.result = \"\";\n state.position++;\n captureStart = captureEnd = state.position;\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n if (ch === 34) {\n captureSegment(state, captureStart, state.position, true);\n state.position++;\n return true;\n } else if (ch === 92) {\n captureSegment(state, captureStart, state.position, true);\n ch = state.input.charCodeAt(++state.position);\n if (is_EOL(ch)) {\n skipSeparationSpace(state, false, nodeIndent);\n } else if (ch < 256 && simpleEscapeCheck[ch]) {\n state.result += simpleEscapeMap[ch];\n state.position++;\n } else if ((tmp = escapedHexLen(ch)) > 0) {\n hexLength = tmp;\n hexResult = 0;\n for (; hexLength > 0; hexLength--) {\n ch = state.input.charCodeAt(++state.position);\n if ((tmp = fromHexCode(ch)) >= 0) {\n hexResult = (hexResult << 4) + tmp;\n } else {\n throwError(state, \"expected hexadecimal character\");\n }\n }\n state.result += charFromCodepoint(hexResult);\n state.position++;\n } else {\n throwError(state, \"unknown escape sequence\");\n }\n captureStart = captureEnd = state.position;\n } else if (is_EOL(ch)) {\n captureSegment(state, captureStart, captureEnd, true);\n writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));\n captureStart = captureEnd = state.position;\n } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n throwError(state, \"unexpected end of the document within a double quoted scalar\");\n } else {\n state.position++;\n captureEnd = state.position;\n }\n }\n throwError(state, \"unexpected end of the stream within a double quoted scalar\");\n}\n__name(readDoubleQuotedScalar, \"readDoubleQuotedScalar\");\nfunction readFlowCollection(state, nodeIndent) {\n var readNext = true, _line, _lineStart, _pos, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = /* @__PURE__ */ Object.create(null), keyNode, keyTag, valueNode, ch;\n ch = state.input.charCodeAt(state.position);\n if (ch === 91) {\n terminator = 93;\n isMapping = false;\n _result = [];\n } else if (ch === 123) {\n terminator = 125;\n isMapping = true;\n _result = {};\n } else {\n return false;\n }\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = _result;\n }\n ch = state.input.charCodeAt(++state.position);\n while (ch !== 0) {\n skipSeparationSpace(state, true, nodeIndent);\n ch = state.input.charCodeAt(state.position);\n if (ch === terminator) {\n state.position++;\n state.tag = _tag;\n state.anchor = _anchor;\n state.kind = isMapping ? \"mapping\" : \"sequence\";\n state.result = _result;\n return true;\n } else if (!readNext) {\n throwError(state, \"missed comma between flow collection entries\");\n } else if (ch === 44) {\n throwError(state, \"expected the node content, but found ','\");\n }\n keyTag = keyNode = valueNode = null;\n isPair = isExplicitPair = false;\n if (ch === 63) {\n following = state.input.charCodeAt(state.position + 1);\n if (is_WS_OR_EOL(following)) {\n isPair = isExplicitPair = true;\n state.position++;\n skipSeparationSpace(state, true, nodeIndent);\n }\n }\n _line = state.line;\n _lineStart = state.lineStart;\n _pos = state.position;\n composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);\n keyTag = state.tag;\n keyNode = state.result;\n skipSeparationSpace(state, true, nodeIndent);\n ch = state.input.charCodeAt(state.position);\n if ((isExplicitPair || state.line === _line) && ch === 58) {\n isPair = true;\n ch = state.input.charCodeAt(++state.position);\n skipSeparationSpace(state, true, nodeIndent);\n composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);\n valueNode = state.result;\n }\n if (isMapping) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);\n } else if (isPair) {\n _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));\n } else {\n _result.push(keyNode);\n }\n skipSeparationSpace(state, true, nodeIndent);\n ch = state.input.charCodeAt(state.position);\n if (ch === 44) {\n readNext = true;\n ch = state.input.charCodeAt(++state.position);\n } else {\n readNext = false;\n }\n }\n throwError(state, \"unexpected end of the stream within a flow collection\");\n}\n__name(readFlowCollection, \"readFlowCollection\");\nfunction readBlockScalar(state, nodeIndent) {\n var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch;\n ch = state.input.charCodeAt(state.position);\n if (ch === 124) {\n folding = false;\n } else if (ch === 62) {\n folding = true;\n } else {\n return false;\n }\n state.kind = \"scalar\";\n state.result = \"\";\n while (ch !== 0) {\n ch = state.input.charCodeAt(++state.position);\n if (ch === 43 || ch === 45) {\n if (CHOMPING_CLIP === chomping) {\n chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP;\n } else {\n throwError(state, \"repeat of a chomping mode identifier\");\n }\n } else if ((tmp = fromDecimalCode(ch)) >= 0) {\n if (tmp === 0) {\n throwError(state, \"bad explicit indentation width of a block scalar; it cannot be less than one\");\n } else if (!detectedIndent) {\n textIndent = nodeIndent + tmp - 1;\n detectedIndent = true;\n } else {\n throwError(state, \"repeat of an indentation width identifier\");\n }\n } else {\n break;\n }\n }\n if (is_WHITE_SPACE(ch)) {\n do {\n ch = state.input.charCodeAt(++state.position);\n } while (is_WHITE_SPACE(ch));\n if (ch === 35) {\n do {\n ch = state.input.charCodeAt(++state.position);\n } while (!is_EOL(ch) && ch !== 0);\n }\n }\n while (ch !== 0) {\n readLineBreak(state);\n state.lineIndent = 0;\n ch = state.input.charCodeAt(state.position);\n while ((!detectedIndent || state.lineIndent < textIndent) && ch === 32) {\n state.lineIndent++;\n ch = state.input.charCodeAt(++state.position);\n }\n if (!detectedIndent && state.lineIndent > textIndent) {\n textIndent = state.lineIndent;\n }\n if (is_EOL(ch)) {\n emptyLines++;\n continue;\n }\n if (state.lineIndent < textIndent) {\n if (chomping === CHOMPING_KEEP) {\n state.result += common.repeat(\"\\n\", didReadContent ? 1 + emptyLines : emptyLines);\n } else if (chomping === CHOMPING_CLIP) {\n if (didReadContent) {\n state.result += \"\\n\";\n }\n }\n break;\n }\n if (folding) {\n if (is_WHITE_SPACE(ch)) {\n atMoreIndented = true;\n state.result += common.repeat(\"\\n\", didReadContent ? 1 + emptyLines : emptyLines);\n } else if (atMoreIndented) {\n atMoreIndented = false;\n state.result += common.repeat(\"\\n\", emptyLines + 1);\n } else if (emptyLines === 0) {\n if (didReadContent) {\n state.result += \" \";\n }\n } else {\n state.result += common.repeat(\"\\n\", emptyLines);\n }\n } else {\n state.result += common.repeat(\"\\n\", didReadContent ? 1 + emptyLines : emptyLines);\n }\n didReadContent = true;\n detectedIndent = true;\n emptyLines = 0;\n captureStart = state.position;\n while (!is_EOL(ch) && ch !== 0) {\n ch = state.input.charCodeAt(++state.position);\n }\n captureSegment(state, captureStart, state.position, false);\n }\n return true;\n}\n__name(readBlockScalar, \"readBlockScalar\");\nfunction readBlockSequence(state, nodeIndent) {\n var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch;\n if (state.firstTabInLine !== -1) return false;\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = _result;\n }\n ch = state.input.charCodeAt(state.position);\n while (ch !== 0) {\n if (state.firstTabInLine !== -1) {\n state.position = state.firstTabInLine;\n throwError(state, \"tab characters must not be used in indentation\");\n }\n if (ch !== 45) {\n break;\n }\n following = state.input.charCodeAt(state.position + 1);\n if (!is_WS_OR_EOL(following)) {\n break;\n }\n detected = true;\n state.position++;\n if (skipSeparationSpace(state, true, -1)) {\n if (state.lineIndent <= nodeIndent) {\n _result.push(null);\n ch = state.input.charCodeAt(state.position);\n continue;\n }\n }\n _line = state.line;\n composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);\n _result.push(state.result);\n skipSeparationSpace(state, true, -1);\n ch = state.input.charCodeAt(state.position);\n if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {\n throwError(state, \"bad indentation of a sequence entry\");\n } else if (state.lineIndent < nodeIndent) {\n break;\n }\n }\n if (detected) {\n state.tag = _tag;\n state.anchor = _anchor;\n state.kind = \"sequence\";\n state.result = _result;\n return true;\n }\n return false;\n}\n__name(readBlockSequence, \"readBlockSequence\");\nfunction readBlockMapping(state, nodeIndent, flowIndent) {\n var following, allowCompact, _line, _keyLine, _keyLineStart, _keyPos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = /* @__PURE__ */ Object.create(null), keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch;\n if (state.firstTabInLine !== -1) return false;\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = _result;\n }\n ch = state.input.charCodeAt(state.position);\n while (ch !== 0) {\n if (!atExplicitKey && state.firstTabInLine !== -1) {\n state.position = state.firstTabInLine;\n throwError(state, \"tab characters must not be used in indentation\");\n }\n following = state.input.charCodeAt(state.position + 1);\n _line = state.line;\n if ((ch === 63 || ch === 58) && is_WS_OR_EOL(following)) {\n if (ch === 63) {\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);\n keyTag = keyNode = valueNode = null;\n }\n detected = true;\n atExplicitKey = true;\n allowCompact = true;\n } else if (atExplicitKey) {\n atExplicitKey = false;\n allowCompact = true;\n } else {\n throwError(state, \"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line\");\n }\n state.position += 1;\n ch = following;\n } else {\n _keyLine = state.line;\n _keyLineStart = state.lineStart;\n _keyPos = state.position;\n if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {\n break;\n }\n if (state.line === _line) {\n ch = state.input.charCodeAt(state.position);\n while (is_WHITE_SPACE(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n if (ch === 58) {\n ch = state.input.charCodeAt(++state.position);\n if (!is_WS_OR_EOL(ch)) {\n throwError(state, \"a whitespace character is expected after the key-value separator within a block mapping\");\n }\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);\n keyTag = keyNode = valueNode = null;\n }\n detected = true;\n atExplicitKey = false;\n allowCompact = false;\n keyTag = state.tag;\n keyNode = state.result;\n } else if (detected) {\n throwError(state, \"can not read an implicit mapping pair; a colon is missed\");\n } else {\n state.tag = _tag;\n state.anchor = _anchor;\n return true;\n }\n } else if (detected) {\n throwError(state, \"can not read a block mapping entry; a multiline key may not be an implicit key\");\n } else {\n state.tag = _tag;\n state.anchor = _anchor;\n return true;\n }\n }\n if (state.line === _line || state.lineIndent > nodeIndent) {\n if (atExplicitKey) {\n _keyLine = state.line;\n _keyLineStart = state.lineStart;\n _keyPos = state.position;\n }\n if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {\n if (atExplicitKey) {\n keyNode = state.result;\n } else {\n valueNode = state.result;\n }\n }\n if (!atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);\n keyTag = keyNode = valueNode = null;\n }\n skipSeparationSpace(state, true, -1);\n ch = state.input.charCodeAt(state.position);\n }\n if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {\n throwError(state, \"bad indentation of a mapping entry\");\n } else if (state.lineIndent < nodeIndent) {\n break;\n }\n }\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);\n }\n if (detected) {\n state.tag = _tag;\n state.anchor = _anchor;\n state.kind = \"mapping\";\n state.result = _result;\n }\n return detected;\n}\n__name(readBlockMapping, \"readBlockMapping\");\nfunction readTagProperty(state) {\n var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch;\n ch = state.input.charCodeAt(state.position);\n if (ch !== 33) return false;\n if (state.tag !== null) {\n throwError(state, \"duplication of a tag property\");\n }\n ch = state.input.charCodeAt(++state.position);\n if (ch === 60) {\n isVerbatim = true;\n ch = state.input.charCodeAt(++state.position);\n } else if (ch === 33) {\n isNamed = true;\n tagHandle = \"!!\";\n ch = state.input.charCodeAt(++state.position);\n } else {\n tagHandle = \"!\";\n }\n _position = state.position;\n if (isVerbatim) {\n do {\n ch = state.input.charCodeAt(++state.position);\n } while (ch !== 0 && ch !== 62);\n if (state.position < state.length) {\n tagName = state.input.slice(_position, state.position);\n ch = state.input.charCodeAt(++state.position);\n } else {\n throwError(state, \"unexpected end of the stream within a verbatim tag\");\n }\n } else {\n while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n if (ch === 33) {\n if (!isNamed) {\n tagHandle = state.input.slice(_position - 1, state.position + 1);\n if (!PATTERN_TAG_HANDLE.test(tagHandle)) {\n throwError(state, \"named tag handle cannot contain such characters\");\n }\n isNamed = true;\n _position = state.position + 1;\n } else {\n throwError(state, \"tag suffix cannot contain exclamation marks\");\n }\n }\n ch = state.input.charCodeAt(++state.position);\n }\n tagName = state.input.slice(_position, state.position);\n if (PATTERN_FLOW_INDICATORS.test(tagName)) {\n throwError(state, \"tag suffix cannot contain flow indicator characters\");\n }\n }\n if (tagName && !PATTERN_TAG_URI.test(tagName)) {\n throwError(state, \"tag name cannot contain such characters: \" + tagName);\n }\n try {\n tagName = decodeURIComponent(tagName);\n } catch (err) {\n throwError(state, \"tag name is malformed: \" + tagName);\n }\n if (isVerbatim) {\n state.tag = tagName;\n } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) {\n state.tag = state.tagMap[tagHandle] + tagName;\n } else if (tagHandle === \"!\") {\n state.tag = \"!\" + tagName;\n } else if (tagHandle === \"!!\") {\n state.tag = \"tag:yaml.org,2002:\" + tagName;\n } else {\n throwError(state, 'undeclared tag handle \"' + tagHandle + '\"');\n }\n return true;\n}\n__name(readTagProperty, \"readTagProperty\");\nfunction readAnchorProperty(state) {\n var _position, ch;\n ch = state.input.charCodeAt(state.position);\n if (ch !== 38) return false;\n if (state.anchor !== null) {\n throwError(state, \"duplication of an anchor property\");\n }\n ch = state.input.charCodeAt(++state.position);\n _position = state.position;\n while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n if (state.position === _position) {\n throwError(state, \"name of an anchor node must contain at least one character\");\n }\n state.anchor = state.input.slice(_position, state.position);\n return true;\n}\n__name(readAnchorProperty, \"readAnchorProperty\");\nfunction readAlias(state) {\n var _position, alias, ch;\n ch = state.input.charCodeAt(state.position);\n if (ch !== 42) return false;\n ch = state.input.charCodeAt(++state.position);\n _position = state.position;\n while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n if (state.position === _position) {\n throwError(state, \"name of an alias node must contain at least one character\");\n }\n alias = state.input.slice(_position, state.position);\n if (!_hasOwnProperty$1.call(state.anchorMap, alias)) {\n throwError(state, 'unidentified alias \"' + alias + '\"');\n }\n state.result = state.anchorMap[alias];\n skipSeparationSpace(state, true, -1);\n return true;\n}\n__name(readAlias, \"readAlias\");\nfunction composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {\n var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, typeIndex, typeQuantity, typeList, type2, flowIndent, blockIndent;\n if (state.listener !== null) {\n state.listener(\"open\", state);\n }\n state.tag = null;\n state.anchor = null;\n state.kind = null;\n state.result = null;\n allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;\n if (allowToSeek) {\n if (skipSeparationSpace(state, true, -1)) {\n atNewLine = true;\n if (state.lineIndent > parentIndent) {\n indentStatus = 1;\n } else if (state.lineIndent === parentIndent) {\n indentStatus = 0;\n } else if (state.lineIndent < parentIndent) {\n indentStatus = -1;\n }\n }\n }\n if (indentStatus === 1) {\n while (readTagProperty(state) || readAnchorProperty(state)) {\n if (skipSeparationSpace(state, true, -1)) {\n atNewLine = true;\n allowBlockCollections = allowBlockStyles;\n if (state.lineIndent > parentIndent) {\n indentStatus = 1;\n } else if (state.lineIndent === parentIndent) {\n indentStatus = 0;\n } else if (state.lineIndent < parentIndent) {\n indentStatus = -1;\n }\n } else {\n allowBlockCollections = false;\n }\n }\n }\n if (allowBlockCollections) {\n allowBlockCollections = atNewLine || allowCompact;\n }\n if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {\n if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {\n flowIndent = parentIndent;\n } else {\n flowIndent = parentIndent + 1;\n }\n blockIndent = state.position - state.lineStart;\n if (indentStatus === 1) {\n if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) {\n hasContent = true;\n } else {\n if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) {\n hasContent = true;\n } else if (readAlias(state)) {\n hasContent = true;\n if (state.tag !== null || state.anchor !== null) {\n throwError(state, \"alias node should not have any properties\");\n }\n } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {\n hasContent = true;\n if (state.tag === null) {\n state.tag = \"?\";\n }\n }\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n }\n } else if (indentStatus === 0) {\n hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);\n }\n }\n if (state.tag === null) {\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n } else if (state.tag === \"?\") {\n if (state.result !== null && state.kind !== \"scalar\") {\n throwError(state, 'unacceptable node kind for ! tag; it should be \"scalar\", not \"' + state.kind + '\"');\n }\n for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {\n type2 = state.implicitTypes[typeIndex];\n if (type2.resolve(state.result)) {\n state.result = type2.construct(state.result);\n state.tag = type2.tag;\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n break;\n }\n }\n } else if (state.tag !== \"!\") {\n if (_hasOwnProperty$1.call(state.typeMap[state.kind || \"fallback\"], state.tag)) {\n type2 = state.typeMap[state.kind || \"fallback\"][state.tag];\n } else {\n type2 = null;\n typeList = state.typeMap.multi[state.kind || \"fallback\"];\n for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {\n if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {\n type2 = typeList[typeIndex];\n break;\n }\n }\n }\n if (!type2) {\n throwError(state, \"unknown tag !<\" + state.tag + \">\");\n }\n if (state.result !== null && type2.kind !== state.kind) {\n throwError(state, \"unacceptable node kind for !<\" + state.tag + '> tag; it should be \"' + type2.kind + '\", not \"' + state.kind + '\"');\n }\n if (!type2.resolve(state.result, state.tag)) {\n throwError(state, \"cannot resolve a node with !<\" + state.tag + \"> explicit tag\");\n } else {\n state.result = type2.construct(state.result, state.tag);\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n }\n }\n if (state.listener !== null) {\n state.listener(\"close\", state);\n }\n return state.tag !== null || state.anchor !== null || hasContent;\n}\n__name(composeNode, \"composeNode\");\nfunction readDocument(state) {\n var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch;\n state.version = null;\n state.checkLineBreaks = state.legacy;\n state.tagMap = /* @__PURE__ */ Object.create(null);\n state.anchorMap = /* @__PURE__ */ Object.create(null);\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n skipSeparationSpace(state, true, -1);\n ch = state.input.charCodeAt(state.position);\n if (state.lineIndent > 0 || ch !== 37) {\n break;\n }\n hasDirectives = true;\n ch = state.input.charCodeAt(++state.position);\n _position = state.position;\n while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n directiveName = state.input.slice(_position, state.position);\n directiveArgs = [];\n if (directiveName.length < 1) {\n throwError(state, \"directive name must not be less than one character in length\");\n }\n while (ch !== 0) {\n while (is_WHITE_SPACE(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n if (ch === 35) {\n do {\n ch = state.input.charCodeAt(++state.position);\n } while (ch !== 0 && !is_EOL(ch));\n break;\n }\n if (is_EOL(ch)) break;\n _position = state.position;\n while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n directiveArgs.push(state.input.slice(_position, state.position));\n }\n if (ch !== 0) readLineBreak(state);\n if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) {\n directiveHandlers[directiveName](state, directiveName, directiveArgs);\n } else {\n throwWarning(state, 'unknown document directive \"' + directiveName + '\"');\n }\n }\n skipSeparationSpace(state, true, -1);\n if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) {\n state.position += 3;\n skipSeparationSpace(state, true, -1);\n } else if (hasDirectives) {\n throwError(state, \"directives end mark is expected\");\n }\n composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);\n skipSeparationSpace(state, true, -1);\n if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {\n throwWarning(state, \"non-ASCII line breaks are interpreted as content\");\n }\n state.documents.push(state.result);\n if (state.position === state.lineStart && testDocumentSeparator(state)) {\n if (state.input.charCodeAt(state.position) === 46) {\n state.position += 3;\n skipSeparationSpace(state, true, -1);\n }\n return;\n }\n if (state.position < state.length - 1) {\n throwError(state, \"end of the stream or a document separator is expected\");\n } else {\n return;\n }\n}\n__name(readDocument, \"readDocument\");\nfunction loadDocuments(input, options) {\n input = String(input);\n options = options || {};\n if (input.length !== 0) {\n if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) {\n input += \"\\n\";\n }\n if (input.charCodeAt(0) === 65279) {\n input = input.slice(1);\n }\n }\n var state = new State$1(input, options);\n var nullpos = input.indexOf(\"\\0\");\n if (nullpos !== -1) {\n state.position = nullpos;\n throwError(state, \"null byte is not allowed in input\");\n }\n state.input += \"\\0\";\n while (state.input.charCodeAt(state.position) === 32) {\n state.lineIndent += 1;\n state.position += 1;\n }\n while (state.position < state.length - 1) {\n readDocument(state);\n }\n return state.documents;\n}\n__name(loadDocuments, \"loadDocuments\");\nfunction loadAll$1(input, iterator, options) {\n if (iterator !== null && typeof iterator === \"object\" && typeof options === \"undefined\") {\n options = iterator;\n iterator = null;\n }\n var documents = loadDocuments(input, options);\n if (typeof iterator !== \"function\") {\n return documents;\n }\n for (var index = 0, length = documents.length; index < length; index += 1) {\n iterator(documents[index]);\n }\n}\n__name(loadAll$1, \"loadAll$1\");\nfunction load$1(input, options) {\n var documents = loadDocuments(input, options);\n if (documents.length === 0) {\n return void 0;\n } else if (documents.length === 1) {\n return documents[0];\n }\n throw new exception(\"expected a single document in the stream, but found more\");\n}\n__name(load$1, \"load$1\");\nvar loadAll_1 = loadAll$1;\nvar load_1 = load$1;\nvar loader = {\n loadAll: loadAll_1,\n load: load_1\n};\nvar _toString = Object.prototype.toString;\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\nvar CHAR_BOM = 65279;\nvar CHAR_TAB = 9;\nvar CHAR_LINE_FEED = 10;\nvar CHAR_CARRIAGE_RETURN = 13;\nvar CHAR_SPACE = 32;\nvar CHAR_EXCLAMATION = 33;\nvar CHAR_DOUBLE_QUOTE = 34;\nvar CHAR_SHARP = 35;\nvar CHAR_PERCENT = 37;\nvar CHAR_AMPERSAND = 38;\nvar CHAR_SINGLE_QUOTE = 39;\nvar CHAR_ASTERISK = 42;\nvar CHAR_COMMA = 44;\nvar CHAR_MINUS = 45;\nvar CHAR_COLON = 58;\nvar CHAR_EQUALS = 61;\nvar CHAR_GREATER_THAN = 62;\nvar CHAR_QUESTION = 63;\nvar CHAR_COMMERCIAL_AT = 64;\nvar CHAR_LEFT_SQUARE_BRACKET = 91;\nvar CHAR_RIGHT_SQUARE_BRACKET = 93;\nvar CHAR_GRAVE_ACCENT = 96;\nvar CHAR_LEFT_CURLY_BRACKET = 123;\nvar CHAR_VERTICAL_LINE = 124;\nvar CHAR_RIGHT_CURLY_BRACKET = 125;\nvar ESCAPE_SEQUENCES = {};\nESCAPE_SEQUENCES[0] = \"\\\\0\";\nESCAPE_SEQUENCES[7] = \"\\\\a\";\nESCAPE_SEQUENCES[8] = \"\\\\b\";\nESCAPE_SEQUENCES[9] = \"\\\\t\";\nESCAPE_SEQUENCES[10] = \"\\\\n\";\nESCAPE_SEQUENCES[11] = \"\\\\v\";\nESCAPE_SEQUENCES[12] = \"\\\\f\";\nESCAPE_SEQUENCES[13] = \"\\\\r\";\nESCAPE_SEQUENCES[27] = \"\\\\e\";\nESCAPE_SEQUENCES[34] = '\\\\\"';\nESCAPE_SEQUENCES[92] = \"\\\\\\\\\";\nESCAPE_SEQUENCES[133] = \"\\\\N\";\nESCAPE_SEQUENCES[160] = \"\\\\_\";\nESCAPE_SEQUENCES[8232] = \"\\\\L\";\nESCAPE_SEQUENCES[8233] = \"\\\\P\";\nvar DEPRECATED_BOOLEANS_SYNTAX = [\n \"y\",\n \"Y\",\n \"yes\",\n \"Yes\",\n \"YES\",\n \"on\",\n \"On\",\n \"ON\",\n \"n\",\n \"N\",\n \"no\",\n \"No\",\n \"NO\",\n \"off\",\n \"Off\",\n \"OFF\"\n];\nvar DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\\.[0-9_]*)?$/;\nfunction compileStyleMap(schema2, map2) {\n var result, keys, index, length, tag, style, type2;\n if (map2 === null) return {};\n result = {};\n keys = Object.keys(map2);\n for (index = 0, length = keys.length; index < length; index += 1) {\n tag = keys[index];\n style = String(map2[tag]);\n if (tag.slice(0, 2) === \"!!\") {\n tag = \"tag:yaml.org,2002:\" + tag.slice(2);\n }\n type2 = schema2.compiledTypeMap[\"fallback\"][tag];\n if (type2 && _hasOwnProperty.call(type2.styleAliases, style)) {\n style = type2.styleAliases[style];\n }\n result[tag] = style;\n }\n return result;\n}\n__name(compileStyleMap, \"compileStyleMap\");\nfunction encodeHex(character) {\n var string, handle, length;\n string = character.toString(16).toUpperCase();\n if (character <= 255) {\n handle = \"x\";\n length = 2;\n } else if (character <= 65535) {\n handle = \"u\";\n length = 4;\n } else if (character <= 4294967295) {\n handle = \"U\";\n length = 8;\n } else {\n throw new exception(\"code point within a string may not be greater than 0xFFFFFFFF\");\n }\n return \"\\\\\" + handle + common.repeat(\"0\", length - string.length) + string;\n}\n__name(encodeHex, \"encodeHex\");\nvar QUOTING_TYPE_SINGLE = 1;\nvar QUOTING_TYPE_DOUBLE = 2;\nfunction State(options) {\n this.schema = options[\"schema\"] || _default;\n this.indent = Math.max(1, options[\"indent\"] || 2);\n this.noArrayIndent = options[\"noArrayIndent\"] || false;\n this.skipInvalid = options[\"skipInvalid\"] || false;\n this.flowLevel = common.isNothing(options[\"flowLevel\"]) ? -1 : options[\"flowLevel\"];\n this.styleMap = compileStyleMap(this.schema, options[\"styles\"] || null);\n this.sortKeys = options[\"sortKeys\"] || false;\n this.lineWidth = options[\"lineWidth\"] || 80;\n this.noRefs = options[\"noRefs\"] || false;\n this.noCompatMode = options[\"noCompatMode\"] || false;\n this.condenseFlow = options[\"condenseFlow\"] || false;\n this.quotingType = options[\"quotingType\"] === '\"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;\n this.forceQuotes = options[\"forceQuotes\"] || false;\n this.replacer = typeof options[\"replacer\"] === \"function\" ? options[\"replacer\"] : null;\n this.implicitTypes = this.schema.compiledImplicit;\n this.explicitTypes = this.schema.compiledExplicit;\n this.tag = null;\n this.result = \"\";\n this.duplicates = [];\n this.usedDuplicates = null;\n}\n__name(State, \"State\");\nfunction indentString(string, spaces) {\n var ind = common.repeat(\" \", spaces), position = 0, next = -1, result = \"\", line, length = string.length;\n while (position < length) {\n next = string.indexOf(\"\\n\", position);\n if (next === -1) {\n line = string.slice(position);\n position = length;\n } else {\n line = string.slice(position, next + 1);\n position = next + 1;\n }\n if (line.length && line !== \"\\n\") result += ind;\n result += line;\n }\n return result;\n}\n__name(indentString, \"indentString\");\nfunction generateNextLine(state, level) {\n return \"\\n\" + common.repeat(\" \", state.indent * level);\n}\n__name(generateNextLine, \"generateNextLine\");\nfunction testImplicitResolving(state, str2) {\n var index, length, type2;\n for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {\n type2 = state.implicitTypes[index];\n if (type2.resolve(str2)) {\n return true;\n }\n }\n return false;\n}\n__name(testImplicitResolving, \"testImplicitResolving\");\nfunction isWhitespace(c) {\n return c === CHAR_SPACE || c === CHAR_TAB;\n}\n__name(isWhitespace, \"isWhitespace\");\nfunction isPrintable(c) {\n return 32 <= c && c <= 126 || 161 <= c && c <= 55295 && c !== 8232 && c !== 8233 || 57344 <= c && c <= 65533 && c !== CHAR_BOM || 65536 <= c && c <= 1114111;\n}\n__name(isPrintable, \"isPrintable\");\nfunction isNsCharOrWhitespace(c) {\n return isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;\n}\n__name(isNsCharOrWhitespace, \"isNsCharOrWhitespace\");\nfunction isPlainSafe(c, prev, inblock) {\n var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);\n var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);\n return (\n // ns-plain-safe\n (inblock ? (\n // c = flow-in\n cIsNsCharOrWhitespace\n ) : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar\n );\n}\n__name(isPlainSafe, \"isPlainSafe\");\nfunction isPlainSafeFirst(c) {\n return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;\n}\n__name(isPlainSafeFirst, \"isPlainSafeFirst\");\nfunction isPlainSafeLast(c) {\n return !isWhitespace(c) && c !== CHAR_COLON;\n}\n__name(isPlainSafeLast, \"isPlainSafeLast\");\nfunction codePointAt(string, pos) {\n var first = string.charCodeAt(pos), second;\n if (first >= 55296 && first <= 56319 && pos + 1 < string.length) {\n second = string.charCodeAt(pos + 1);\n if (second >= 56320 && second <= 57343) {\n return (first - 55296) * 1024 + second - 56320 + 65536;\n }\n }\n return first;\n}\n__name(codePointAt, \"codePointAt\");\nfunction needIndentIndicator(string) {\n var leadingSpaceRe = /^\\n* /;\n return leadingSpaceRe.test(string);\n}\n__name(needIndentIndicator, \"needIndentIndicator\");\nvar STYLE_PLAIN = 1;\nvar STYLE_SINGLE = 2;\nvar STYLE_LITERAL = 3;\nvar STYLE_FOLDED = 4;\nvar STYLE_DOUBLE = 5;\nfunction chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) {\n var i;\n var char = 0;\n var prevChar = null;\n var hasLineBreak = false;\n var hasFoldableLine = false;\n var shouldTrackWidth = lineWidth !== -1;\n var previousLineBreak = -1;\n var plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));\n if (singleLineOnly || forceQuotes) {\n for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {\n char = codePointAt(string, i);\n if (!isPrintable(char)) {\n return STYLE_DOUBLE;\n }\n plain = plain && isPlainSafe(char, prevChar, inblock);\n prevChar = char;\n }\n } else {\n for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {\n char = codePointAt(string, i);\n if (char === CHAR_LINE_FEED) {\n hasLineBreak = true;\n if (shouldTrackWidth) {\n hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented.\n i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== \" \";\n previousLineBreak = i;\n }\n } else if (!isPrintable(char)) {\n return STYLE_DOUBLE;\n }\n plain = plain && isPlainSafe(char, prevChar, inblock);\n prevChar = char;\n }\n hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== \" \");\n }\n if (!hasLineBreak && !hasFoldableLine) {\n if (plain && !forceQuotes && !testAmbiguousType(string)) {\n return STYLE_PLAIN;\n }\n return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;\n }\n if (indentPerLevel > 9 && needIndentIndicator(string)) {\n return STYLE_DOUBLE;\n }\n if (!forceQuotes) {\n return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;\n }\n return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;\n}\n__name(chooseScalarStyle, \"chooseScalarStyle\");\nfunction writeScalar(state, string, level, iskey, inblock) {\n state.dump = (function() {\n if (string.length === 0) {\n return state.quotingType === QUOTING_TYPE_DOUBLE ? '\"\"' : \"''\";\n }\n if (!state.noCompatMode) {\n if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {\n return state.quotingType === QUOTING_TYPE_DOUBLE ? '\"' + string + '\"' : \"'\" + string + \"'\";\n }\n }\n var indent = state.indent * Math.max(1, level);\n var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);\n var singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel;\n function testAmbiguity(string2) {\n return testImplicitResolving(state, string2);\n }\n __name(testAmbiguity, \"testAmbiguity\");\n switch (chooseScalarStyle(\n string,\n singleLineOnly,\n state.indent,\n lineWidth,\n testAmbiguity,\n state.quotingType,\n state.forceQuotes && !iskey,\n inblock\n )) {\n case STYLE_PLAIN:\n return string;\n case STYLE_SINGLE:\n return \"'\" + string.replace(/'/g, \"''\") + \"'\";\n case STYLE_LITERAL:\n return \"|\" + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));\n case STYLE_FOLDED:\n return \">\" + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));\n case STYLE_DOUBLE:\n return '\"' + escapeString(string) + '\"';\n default:\n throw new exception(\"impossible error: invalid scalar style\");\n }\n })();\n}\n__name(writeScalar, \"writeScalar\");\nfunction blockHeader(string, indentPerLevel) {\n var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : \"\";\n var clip = string[string.length - 1] === \"\\n\";\n var keep = clip && (string[string.length - 2] === \"\\n\" || string === \"\\n\");\n var chomp = keep ? \"+\" : clip ? \"\" : \"-\";\n return indentIndicator + chomp + \"\\n\";\n}\n__name(blockHeader, \"blockHeader\");\nfunction dropEndingNewline(string) {\n return string[string.length - 1] === \"\\n\" ? string.slice(0, -1) : string;\n}\n__name(dropEndingNewline, \"dropEndingNewline\");\nfunction foldString(string, width) {\n var lineRe = /(\\n+)([^\\n]*)/g;\n var result = (function() {\n var nextLF = string.indexOf(\"\\n\");\n nextLF = nextLF !== -1 ? nextLF : string.length;\n lineRe.lastIndex = nextLF;\n return foldLine(string.slice(0, nextLF), width);\n })();\n var prevMoreIndented = string[0] === \"\\n\" || string[0] === \" \";\n var moreIndented;\n var match;\n while (match = lineRe.exec(string)) {\n var prefix = match[1], line = match[2];\n moreIndented = line[0] === \" \";\n result += prefix + (!prevMoreIndented && !moreIndented && line !== \"\" ? \"\\n\" : \"\") + foldLine(line, width);\n prevMoreIndented = moreIndented;\n }\n return result;\n}\n__name(foldString, \"foldString\");\nfunction foldLine(line, width) {\n if (line === \"\" || line[0] === \" \") return line;\n var breakRe = / [^ ]/g;\n var match;\n var start = 0, end, curr = 0, next = 0;\n var result = \"\";\n while (match = breakRe.exec(line)) {\n next = match.index;\n if (next - start > width) {\n end = curr > start ? curr : next;\n result += \"\\n\" + line.slice(start, end);\n start = end + 1;\n }\n curr = next;\n }\n result += \"\\n\";\n if (line.length - start > width && curr > start) {\n result += line.slice(start, curr) + \"\\n\" + line.slice(curr + 1);\n } else {\n result += line.slice(start);\n }\n return result.slice(1);\n}\n__name(foldLine, \"foldLine\");\nfunction escapeString(string) {\n var result = \"\";\n var char = 0;\n var escapeSeq;\n for (var i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {\n char = codePointAt(string, i);\n escapeSeq = ESCAPE_SEQUENCES[char];\n if (!escapeSeq && isPrintable(char)) {\n result += string[i];\n if (char >= 65536) result += string[i + 1];\n } else {\n result += escapeSeq || encodeHex(char);\n }\n }\n return result;\n}\n__name(escapeString, \"escapeString\");\nfunction writeFlowSequence(state, level, object) {\n var _result = \"\", _tag = state.tag, index, length, value;\n for (index = 0, length = object.length; index < length; index += 1) {\n value = object[index];\n if (state.replacer) {\n value = state.replacer.call(object, String(index), value);\n }\n if (writeNode(state, level, value, false, false) || typeof value === \"undefined\" && writeNode(state, level, null, false, false)) {\n if (_result !== \"\") _result += \",\" + (!state.condenseFlow ? \" \" : \"\");\n _result += state.dump;\n }\n }\n state.tag = _tag;\n state.dump = \"[\" + _result + \"]\";\n}\n__name(writeFlowSequence, \"writeFlowSequence\");\nfunction writeBlockSequence(state, level, object, compact) {\n var _result = \"\", _tag = state.tag, index, length, value;\n for (index = 0, length = object.length; index < length; index += 1) {\n value = object[index];\n if (state.replacer) {\n value = state.replacer.call(object, String(index), value);\n }\n if (writeNode(state, level + 1, value, true, true, false, true) || typeof value === \"undefined\" && writeNode(state, level + 1, null, true, true, false, true)) {\n if (!compact || _result !== \"\") {\n _result += generateNextLine(state, level);\n }\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n _result += \"-\";\n } else {\n _result += \"- \";\n }\n _result += state.dump;\n }\n }\n state.tag = _tag;\n state.dump = _result || \"[]\";\n}\n__name(writeBlockSequence, \"writeBlockSequence\");\nfunction writeFlowMapping(state, level, object) {\n var _result = \"\", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, pairBuffer;\n for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n pairBuffer = \"\";\n if (_result !== \"\") pairBuffer += \", \";\n if (state.condenseFlow) pairBuffer += '\"';\n objectKey = objectKeyList[index];\n objectValue = object[objectKey];\n if (state.replacer) {\n objectValue = state.replacer.call(object, objectKey, objectValue);\n }\n if (!writeNode(state, level, objectKey, false, false)) {\n continue;\n }\n if (state.dump.length > 1024) pairBuffer += \"? \";\n pairBuffer += state.dump + (state.condenseFlow ? '\"' : \"\") + \":\" + (state.condenseFlow ? \"\" : \" \");\n if (!writeNode(state, level, objectValue, false, false)) {\n continue;\n }\n pairBuffer += state.dump;\n _result += pairBuffer;\n }\n state.tag = _tag;\n state.dump = \"{\" + _result + \"}\";\n}\n__name(writeFlowMapping, \"writeFlowMapping\");\nfunction writeBlockMapping(state, level, object, compact) {\n var _result = \"\", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, explicitPair, pairBuffer;\n if (state.sortKeys === true) {\n objectKeyList.sort();\n } else if (typeof state.sortKeys === \"function\") {\n objectKeyList.sort(state.sortKeys);\n } else if (state.sortKeys) {\n throw new exception(\"sortKeys must be a boolean or a function\");\n }\n for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n pairBuffer = \"\";\n if (!compact || _result !== \"\") {\n pairBuffer += generateNextLine(state, level);\n }\n objectKey = objectKeyList[index];\n objectValue = object[objectKey];\n if (state.replacer) {\n objectValue = state.replacer.call(object, objectKey, objectValue);\n }\n if (!writeNode(state, level + 1, objectKey, true, true, true)) {\n continue;\n }\n explicitPair = state.tag !== null && state.tag !== \"?\" || state.dump && state.dump.length > 1024;\n if (explicitPair) {\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n pairBuffer += \"?\";\n } else {\n pairBuffer += \"? \";\n }\n }\n pairBuffer += state.dump;\n if (explicitPair) {\n pairBuffer += generateNextLine(state, level);\n }\n if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {\n continue;\n }\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n pairBuffer += \":\";\n } else {\n pairBuffer += \": \";\n }\n pairBuffer += state.dump;\n _result += pairBuffer;\n }\n state.tag = _tag;\n state.dump = _result || \"{}\";\n}\n__name(writeBlockMapping, \"writeBlockMapping\");\nfunction detectType(state, object, explicit) {\n var _result, typeList, index, length, type2, style;\n typeList = explicit ? state.explicitTypes : state.implicitTypes;\n for (index = 0, length = typeList.length; index < length; index += 1) {\n type2 = typeList[index];\n if ((type2.instanceOf || type2.predicate) && (!type2.instanceOf || typeof object === \"object\" && object instanceof type2.instanceOf) && (!type2.predicate || type2.predicate(object))) {\n if (explicit) {\n if (type2.multi && type2.representName) {\n state.tag = type2.representName(object);\n } else {\n state.tag = type2.tag;\n }\n } else {\n state.tag = \"?\";\n }\n if (type2.represent) {\n style = state.styleMap[type2.tag] || type2.defaultStyle;\n if (_toString.call(type2.represent) === \"[object Function]\") {\n _result = type2.represent(object, style);\n } else if (_hasOwnProperty.call(type2.represent, style)) {\n _result = type2.represent[style](object, style);\n } else {\n throw new exception(\"!<\" + type2.tag + '> tag resolver accepts not \"' + style + '\" style');\n }\n state.dump = _result;\n }\n return true;\n }\n }\n return false;\n}\n__name(detectType, \"detectType\");\nfunction writeNode(state, level, object, block, compact, iskey, isblockseq) {\n state.tag = null;\n state.dump = object;\n if (!detectType(state, object, false)) {\n detectType(state, object, true);\n }\n var type2 = _toString.call(state.dump);\n var inblock = block;\n var tagStr;\n if (block) {\n block = state.flowLevel < 0 || state.flowLevel > level;\n }\n var objectOrArray = type2 === \"[object Object]\" || type2 === \"[object Array]\", duplicateIndex, duplicate;\n if (objectOrArray) {\n duplicateIndex = state.duplicates.indexOf(object);\n duplicate = duplicateIndex !== -1;\n }\n if (state.tag !== null && state.tag !== \"?\" || duplicate || state.indent !== 2 && level > 0) {\n compact = false;\n }\n if (duplicate && state.usedDuplicates[duplicateIndex]) {\n state.dump = \"*ref_\" + duplicateIndex;\n } else {\n if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {\n state.usedDuplicates[duplicateIndex] = true;\n }\n if (type2 === \"[object Object]\") {\n if (block && Object.keys(state.dump).length !== 0) {\n writeBlockMapping(state, level, state.dump, compact);\n if (duplicate) {\n state.dump = \"&ref_\" + duplicateIndex + state.dump;\n }\n } else {\n writeFlowMapping(state, level, state.dump);\n if (duplicate) {\n state.dump = \"&ref_\" + duplicateIndex + \" \" + state.dump;\n }\n }\n } else if (type2 === \"[object Array]\") {\n if (block && state.dump.length !== 0) {\n if (state.noArrayIndent && !isblockseq && level > 0) {\n writeBlockSequence(state, level - 1, state.dump, compact);\n } else {\n writeBlockSequence(state, level, state.dump, compact);\n }\n if (duplicate) {\n state.dump = \"&ref_\" + duplicateIndex + state.dump;\n }\n } else {\n writeFlowSequence(state, level, state.dump);\n if (duplicate) {\n state.dump = \"&ref_\" + duplicateIndex + \" \" + state.dump;\n }\n }\n } else if (type2 === \"[object String]\") {\n if (state.tag !== \"?\") {\n writeScalar(state, state.dump, level, iskey, inblock);\n }\n } else if (type2 === \"[object Undefined]\") {\n return false;\n } else {\n if (state.skipInvalid) return false;\n throw new exception(\"unacceptable kind of an object to dump \" + type2);\n }\n if (state.tag !== null && state.tag !== \"?\") {\n tagStr = encodeURI(\n state.tag[0] === \"!\" ? state.tag.slice(1) : state.tag\n ).replace(/!/g, \"%21\");\n if (state.tag[0] === \"!\") {\n tagStr = \"!\" + tagStr;\n } else if (tagStr.slice(0, 18) === \"tag:yaml.org,2002:\") {\n tagStr = \"!!\" + tagStr.slice(18);\n } else {\n tagStr = \"!<\" + tagStr + \">\";\n }\n state.dump = tagStr + \" \" + state.dump;\n }\n }\n return true;\n}\n__name(writeNode, \"writeNode\");\nfunction getDuplicateReferences(object, state) {\n var objects = [], duplicatesIndexes = [], index, length;\n inspectNode(object, objects, duplicatesIndexes);\n for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {\n state.duplicates.push(objects[duplicatesIndexes[index]]);\n }\n state.usedDuplicates = new Array(length);\n}\n__name(getDuplicateReferences, \"getDuplicateReferences\");\nfunction inspectNode(object, objects, duplicatesIndexes) {\n var objectKeyList, index, length;\n if (object !== null && typeof object === \"object\") {\n index = objects.indexOf(object);\n if (index !== -1) {\n if (duplicatesIndexes.indexOf(index) === -1) {\n duplicatesIndexes.push(index);\n }\n } else {\n objects.push(object);\n if (Array.isArray(object)) {\n for (index = 0, length = object.length; index < length; index += 1) {\n inspectNode(object[index], objects, duplicatesIndexes);\n }\n } else {\n objectKeyList = Object.keys(object);\n for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);\n }\n }\n }\n }\n}\n__name(inspectNode, \"inspectNode\");\nfunction dump$1(input, options) {\n options = options || {};\n var state = new State(options);\n if (!state.noRefs) getDuplicateReferences(input, state);\n var value = input;\n if (state.replacer) {\n value = state.replacer.call({ \"\": value }, \"\", value);\n }\n if (writeNode(state, 0, value, true, true)) return state.dump + \"\\n\";\n return \"\";\n}\n__name(dump$1, \"dump$1\");\nvar dump_1 = dump$1;\nvar dumper = {\n dump: dump_1\n};\nfunction renamed(from, to) {\n return function() {\n throw new Error(\"Function yaml.\" + from + \" is removed in js-yaml 4. Use yaml.\" + to + \" instead, which is now safe by default.\");\n };\n}\n__name(renamed, \"renamed\");\nvar JSON_SCHEMA = json;\nvar load = loader.load;\nvar loadAll = loader.loadAll;\nvar dump = dumper.dump;\nvar safeLoad = renamed(\"safeLoad\", \"load\");\nvar safeLoadAll = renamed(\"safeLoadAll\", \"loadAll\");\nvar safeDump = renamed(\"safeDump\", \"dump\");\n\nexport {\n JSON_SCHEMA,\n load\n};\n/*! Bundled license information:\n\njs-yaml/dist/js-yaml.mjs:\n (*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT *)\n*/\n"], + "mappings": "4CAKA,SAASA,GAAUC,EAAS,CAC1B,OAAO,OAAOA,EAAY,KAAeA,IAAY,IACvD,CACAC,EAAOF,GAAW,WAAW,EAC7B,SAASG,GAASF,EAAS,CACzB,OAAO,OAAOA,GAAY,UAAYA,IAAY,IACpD,CACAC,EAAOC,GAAU,UAAU,EAC3B,SAASC,GAAQC,EAAU,CACzB,OAAI,MAAM,QAAQA,CAAQ,EAAUA,EAC3BL,GAAUK,CAAQ,EAAU,CAAC,EAC/B,CAACA,CAAQ,CAClB,CACAH,EAAOE,GAAS,SAAS,EACzB,SAASE,GAAOC,EAAQC,EAAQ,CAC9B,IAAIC,EAAOC,EAAQC,EAAKC,EACxB,GAAIJ,EAEF,IADAI,EAAa,OAAO,KAAKJ,CAAM,EAC1BC,EAAQ,EAAGC,EAASE,EAAW,OAAQH,EAAQC,EAAQD,GAAS,EACnEE,EAAMC,EAAWH,CAAK,EACtBF,EAAOI,CAAG,EAAIH,EAAOG,CAAG,EAG5B,OAAOJ,CACT,CACAL,EAAOI,GAAQ,QAAQ,EACvB,S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GAAUlI,GAAO,QACjBmI,GAAOP,GAAO,KACdQ,GAAWP,GAAQ,WAAY,MAAM,EACrCQ,GAAcR,GAAQ,cAAe,SAAS,EAC9CS,GAAWT,GAAQ,WAAY,MAAM", + "names": ["isNothing", "subject", "__name", "isObject", "toArray", "sequence", "extend", "target", "source", "index", "length", "key", "sourceKeys", "repeat", "string", "count", "result", "cycle", "isNegativeZero", "number", "isNothing_1", "isObject_1", "toArray_1", "repeat_1", "isNegativeZero_1", "extend_1", "common", "formatError", "exception2", "compact", "where", "message", "YAMLException$1", "reason", "mark", "exception", "getLine", "buffer", "lineStart", "lineEnd", "position", "maxLineLength", "head", "tail", "maxHalfLength", "padStart", "max", "makeSnippet", "options", "re", "lineStarts", "lineEnds", "match", "foundLineNo", "i", "line", "lineNoLength", "snippet", "TYPE_CONSTRUCTOR_OPTIONS", "YAML_NODE_KINDS", "compileStyleAliases", "map2", "style", "alias", "Type$1", "tag", "name", "data", "type", "compileList", "schema2", "currentType", "newIndex", "previousType", "previousIndex", "compileMap", "collectType", "type2", "Schema$1", "definition", "implicit", "explicit", "type$1", "schema", "str", "seq", "map", "failsafe", "resolveYamlNull", "constructYamlNull", "isNull", "object", "_null", "resolveYamlBoolean", "constructYamlBoolean", "isBoolean", "bool", "isHexCode", "c", "isOctCode", "isDecCode", "resolveYamlInteger", "hasDigits", "ch", "constructYamlInteger", "value", "sign", "isInteger", "int", "obj", "YAML_FLOAT_PATTERN", "resolveYamlFloat", "constructYamlFloat", "SCIENTIFIC_WITHOUT_DOT", "representYamlFloat", "res", "isFloat", "float", "json", "core", "YAML_DATE_REGEXP", "YAML_TIMESTAMP_REGEXP", "resolveYamlTimestamp", "constructYamlTimestamp", "year", "month", "day", "hour", "minute", "second", "fraction", "delta", "tz_hour", "tz_minute", "date", "representYamlTimestamp", "timestamp", "resolveYamlMerge", "merge", "BASE64_MAP", "resolveYamlBinary", "code", "idx", "bitlen", "constructYamlBinary", "tailbits", "input", "bits", "representYamlBinary", "isBinary", "binary", "_hasOwnProperty$3", "_toString$2", "resolveYamlOmap", "objectKeys", "pair", "pairKey", "pairHasKey", "constructYamlOmap", "omap", "_toString$1", "resolveYamlPairs", "keys", "constructYamlPairs", "pairs", "_hasOwnProperty$2", "resolveYamlSet", "constructYamlSet", "set", "_default", "_hasOwnProperty$1", "CONTEXT_FLOW_IN", "CONTEXT_FLOW_OUT", "CONTEXT_BLOCK_IN", "CONTEXT_BLOCK_OUT", "CHOMPING_CLIP", "CHOMPING_STRIP", "CHOMPING_KEEP", "PATTERN_NON_PRINTABLE", "PATTERN_NON_ASCII_LINE_BREAKS", "PATTERN_FLOW_INDICATORS", "PATTERN_TAG_HANDLE", "PATTERN_TAG_URI", "_class", "is_EOL", "is_WHITE_SPACE", "is_WS_OR_EOL", "is_FLOW_INDICATOR", "fromHexCode", "lc", "escapedHexLen", "fromDecimalCode", "simpleEscapeSequence", "charFromCodepoint", "simpleEscapeCheck", "simpleEscapeMap", "State$1", "generateError", "state", "throwError", "throwWarning", "directiveHandlers", "args", "major", "minor", "handle", "prefix", "captureSegment", "start", "end", "checkJson", "_position", "_length", "_character", "_result", "mergeMappings", "destination", "overridableKeys", "quantity", "storeMappingPair", "keyTag", "keyNode", "valueNode", "startLine", "startLineStart", "startPos", "readLineBreak", "skipSeparationSpace", "allowComments", "checkIndent", "lineBreaks", "testDocumentSeparator", "writeFoldedLines", "readPlainScalar", "nodeIndent", "withinFlowCollection", "preceding", "following", "captureStart", "captureEnd", "hasPendingContent", "_line", "_lineStart", "_lineIndent", "_kind", "readSingleQuotedScalar", "readDoubleQuotedScalar", "hexLength", "hexResult", "tmp", "readFlowCollection", "readNext", "_pos", "_tag", "_anchor", "terminator", "isPair", "isExplicitPair", "isMapping", "composeNode", "readBlockScalar", "folding", "chomping", "didReadContent", "detectedIndent", "textIndent", "emptyLines", "atMoreIndented", "readBlockSequence", "detected", "readBlockMapping", "flowIndent", "allowCompact", "_keyLine", "_keyLineStart", "_keyPos", "atExplicitKey", "readTagProperty", "isVerbatim", "isNamed", "tagHandle", "tagName", "readAnchorProperty", "readAlias", "parentIndent", "nodeContext", "allowToSeek", "allowBlockStyles", "allowBlockScalars", "allowBlockCollections", "indentStatus", "atNewLine", "hasContent", "typeIndex", "typeQuantity", "typeList", "blockIndent", "readDocument", "documentStart", "directiveName", "directiveArgs", "hasDirectives", "loadDocuments", "nullpos", "loadAll$1", "iterator", "documents", "load$1", "loadAll_1", "load_1", "loader", "_toString", "_hasOwnProperty", "CHAR_BOM", "CHAR_TAB", "CHAR_LINE_FEED", "CHAR_CARRIAGE_RETURN", "CHAR_SPACE", "CHAR_EXCLAMATION", "CHAR_DOUBLE_QUOTE", "CHAR_SHARP", "CHAR_PERCENT", "CHAR_AMPERSAND", "CHAR_SINGLE_QUOTE", "CHAR_ASTERISK", "CHAR_COMMA", "CHAR_MINUS", "CHAR_COLON", "CHAR_EQUALS", "CHAR_GREATER_THAN", "CHAR_QUESTION", "CHAR_COMMERCIAL_AT", "CHAR_LEFT_SQUARE_BRACKET", "CHAR_RIGHT_SQUARE_BRACKET", "CHAR_GRAVE_ACCENT", "CHAR_LEFT_CURLY_BRACKET", "CHAR_VERTICAL_LINE", "CHAR_RIGHT_CURLY_BRACKET", "ESCAPE_SEQUENCES", "DEPRECATED_BOOLEANS_SYNTAX", "DEPRECATED_BASE60_SYNTAX", "compileStyleMap", "encodeHex", "character", "QUOTING_TYPE_SINGLE", "QUOTING_TYPE_DOUBLE", "State", "indentString", "spaces", "ind", "next", "generateNextLine", "level", "testImplicitResolving", "str2", "isWhitespace", "isPrintable", "isNsCharOrWhitespace", "isPlainSafe", "prev", "inblock", "cIsNsCharOrWhitespace", "cIsNsChar", "isPlainSafeFirst", "isPlainSafeLast", "codePointAt", "pos", "first", "needIndentIndicator", "leadingSpaceRe", "STYLE_PLAIN", "STYLE_SINGLE", "STYLE_LITERAL", "STYLE_FOLDED", "STYLE_DOUBLE", "chooseScalarStyle", "singleLineOnly", "indentPerLevel", "lineWidth", "testAmbiguousType", "quotingType", "forceQuotes", "char", "prevChar", "hasLineBreak", "hasFoldableLine", "shouldTrackWidth", "previousLineBreak", "plain", "writeScalar", "iskey", "indent", "testAmbiguity", "string2", "blockHeader", "dropEndingNewline", "foldString", "escapeString", "indentIndicator", "clip", "keep", "chomp", "width", "lineRe", "nextLF", "foldLine", "prevMoreIndented", "moreIndented", "breakRe", "curr", "escapeSeq", "writeFlowSequence", "writeNode", "writeBlockSequence", "writeFlowMapping", "objectKeyList", "objectKey", "objectValue", "pairBuffer", "writeBlockMapping", "explicitPair", "detectType", "block", "isblockseq", "tagStr", "objectOrArray", "duplicateIndex", "duplicate", "getDuplicateReferences", "objects", "duplicatesIndexes", "inspectNode", "dump$1", "dump_1", "dumper", "renamed", "from", "to", "JSON_SCHEMA", "load", "loadAll", "dump", "safeLoad", "safeLoadAll", "safeDump"] +} diff --git a/docs/website/public/chunk-MSQ5HOTG.min.js b/docs/website/public/chunk-MSQ5HOTG.min.js new file mode 100644 index 000000000..8d633a661 --- /dev/null +++ b/docs/website/public/chunk-MSQ5HOTG.min.js @@ -0,0 +1,2 @@ +var s={name:"mermaid",version:"11.12.0",description:"Markdown-ish syntax for generating flowcharts, mindmaps, sequence diagrams, class diagrams, gantt charts, git graphs and more.",type:"module",module:"./dist/mermaid.core.mjs",types:"./dist/mermaid.d.ts",exports:{".":{types:"./dist/mermaid.d.ts",import:"./dist/mermaid.core.mjs",default:"./dist/mermaid.core.mjs"},"./*":"./*"},keywords:["diagram","markdown","flowchart","sequence diagram","gantt","class diagram","git graph","mindmap","packet diagram","c4 diagram","er diagram","pie chart","pie diagram","quadrant chart","requirement diagram","graph"],scripts:{clean:"rimraf dist",dev:"pnpm -w dev","docs:code":"typedoc src/defaultConfig.ts src/config.ts src/mermaid.ts && prettier --write ./src/docs/config/setup","docs:build":"rimraf ../../docs && pnpm docs:code && pnpm docs:spellcheck && tsx scripts/docs.cli.mts","docs:verify":"pnpm docs:code && pnpm docs:spellcheck && tsx scripts/docs.cli.mts --verify","docs:pre:vitepress":"pnpm --filter ./src/docs prefetch && rimraf src/vitepress && pnpm docs:code && tsx scripts/docs.cli.mts --vitepress && pnpm --filter ./src/vitepress install --no-frozen-lockfile --ignore-scripts","docs:build:vitepress":"pnpm docs:pre:vitepress && (cd src/vitepress && pnpm run build) && cpy --flat src/docs/landing/ ./src/vitepress/.vitepress/dist/landing","docs:dev":'pnpm docs:pre:vitepress && concurrently "pnpm --filter ./src/vitepress dev" "tsx scripts/docs.cli.mts --watch --vitepress"',"docs:dev:docker":'pnpm docs:pre:vitepress && concurrently "pnpm --filter ./src/vitepress dev:docker" "tsx scripts/docs.cli.mts --watch --vitepress"',"docs:serve":"pnpm docs:build:vitepress && vitepress serve src/vitepress","docs:spellcheck":'cspell "src/docs/**/*.md"',"docs:release-version":"tsx scripts/update-release-version.mts","docs:verify-version":"tsx scripts/update-release-version.mts --verify","types:build-config":"tsx scripts/create-types-from-json-schema.mts","types:verify-config":"tsx scripts/create-types-from-json-schema.mts --verify",checkCircle:"npx madge --circular ./src",prepublishOnly:"pnpm docs:verify-version"},repository:{type:"git",url:"https://github.com/mermaid-js/mermaid"},author:"Knut Sveidqvist",license:"MIT",standard:{ignore:["**/parser/*.js","dist/**/*.js","cypress/**/*.js"],globals:["page"]},dependencies:{"@braintree/sanitize-url":"^7.1.1","@iconify/utils":"^3.0.1","@mermaid-js/parser":"workspace:^","@types/d3":"^7.4.3",cytoscape:"^3.29.3","cytoscape-cose-bilkent":"^4.1.0","cytoscape-fcose":"^2.2.0",d3:"^7.9.0","d3-sankey":"^0.12.3","dagre-d3-es":"7.0.11",dayjs:"^1.11.18",dompurify:"^3.2.5",katex:"^0.16.22",khroma:"^2.1.0","lodash-es":"^4.17.21",marked:"^16.2.1",roughjs:"^4.6.6",stylis:"^4.3.6","ts-dedent":"^2.2.0",uuid:"^11.1.0"},devDependencies:{"@adobe/jsonschema2md":"^8.0.5","@iconify/types":"^2.0.0","@types/cytoscape":"^3.21.9","@types/cytoscape-fcose":"^2.2.4","@types/d3-sankey":"^0.12.4","@types/d3-scale":"^4.0.9","@types/d3-scale-chromatic":"^3.1.0","@types/d3-selection":"^3.0.11","@types/d3-shape":"^3.1.7","@types/jsdom":"^21.1.7","@types/katex":"^0.16.7","@types/lodash-es":"^4.17.12","@types/micromatch":"^4.0.9","@types/stylis":"^4.2.7","@types/uuid":"^10.0.0",ajv:"^8.17.1",canvas:"^3.1.2",chokidar:"3.6.0",concurrently:"^9.1.2","csstree-validator":"^4.0.1",globby:"^14.1.0",jison:"^0.4.18","js-base64":"^3.7.8",jsdom:"^26.1.0","json-schema-to-typescript":"^15.0.4",micromatch:"^4.0.8","path-browserify":"^1.0.1",prettier:"^3.5.3",remark:"^15.0.1","remark-frontmatter":"^5.0.0","remark-gfm":"^4.0.1",rimraf:"^6.0.1","start-server-and-test":"^2.0.13","type-fest":"^4.35.0",typedoc:"^0.28.12","typedoc-plugin-markdown":"^4.8.1",typescript:"~5.7.3","unist-util-flatmap":"^1.0.0","unist-util-visit":"^5.0.0",vitepress:"^1.6.4","vitepress-plugin-search":"1.0.4-alpha.22"},files:["dist/","README.md"],publishConfig:{access:"public"}};export{s as a}; +//# sourceMappingURL=chunk-MSQ5HOTG.min.js.map diff --git a/docs/website/public/chunk-MSQ5HOTG.min.js.map b/docs/website/public/chunk-MSQ5HOTG.min.js.map new file mode 100644 index 000000000..3eab6e395 --- /dev/null +++ b/docs/website/public/chunk-MSQ5HOTG.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/mermaid/dist/chunks/mermaid.core/chunk-KS23V3DP.mjs"], + "sourcesContent": ["// package.json\nvar package_default = {\n name: \"mermaid\",\n version: \"11.12.0\",\n description: \"Markdown-ish syntax for generating flowcharts, mindmaps, sequence diagrams, class diagrams, gantt charts, git graphs and more.\",\n type: \"module\",\n module: \"./dist/mermaid.core.mjs\",\n types: \"./dist/mermaid.d.ts\",\n exports: {\n \".\": {\n types: \"./dist/mermaid.d.ts\",\n import: \"./dist/mermaid.core.mjs\",\n default: \"./dist/mermaid.core.mjs\"\n },\n \"./*\": \"./*\"\n },\n keywords: [\n \"diagram\",\n \"markdown\",\n \"flowchart\",\n \"sequence diagram\",\n \"gantt\",\n \"class diagram\",\n \"git graph\",\n \"mindmap\",\n \"packet diagram\",\n \"c4 diagram\",\n \"er diagram\",\n \"pie chart\",\n \"pie diagram\",\n \"quadrant chart\",\n \"requirement diagram\",\n \"graph\"\n ],\n scripts: {\n clean: \"rimraf dist\",\n dev: \"pnpm -w dev\",\n \"docs:code\": \"typedoc src/defaultConfig.ts src/config.ts src/mermaid.ts && prettier --write ./src/docs/config/setup\",\n \"docs:build\": \"rimraf ../../docs && pnpm docs:code && pnpm docs:spellcheck && tsx scripts/docs.cli.mts\",\n \"docs:verify\": \"pnpm docs:code && pnpm docs:spellcheck && tsx scripts/docs.cli.mts --verify\",\n \"docs:pre:vitepress\": \"pnpm --filter ./src/docs prefetch && rimraf src/vitepress && pnpm docs:code && tsx scripts/docs.cli.mts --vitepress && pnpm --filter ./src/vitepress install --no-frozen-lockfile --ignore-scripts\",\n \"docs:build:vitepress\": \"pnpm docs:pre:vitepress && (cd src/vitepress && pnpm run build) && cpy --flat src/docs/landing/ ./src/vitepress/.vitepress/dist/landing\",\n \"docs:dev\": 'pnpm docs:pre:vitepress && concurrently \"pnpm --filter ./src/vitepress dev\" \"tsx scripts/docs.cli.mts --watch --vitepress\"',\n \"docs:dev:docker\": 'pnpm docs:pre:vitepress && concurrently \"pnpm --filter ./src/vitepress dev:docker\" \"tsx scripts/docs.cli.mts --watch --vitepress\"',\n \"docs:serve\": \"pnpm docs:build:vitepress && vitepress serve src/vitepress\",\n \"docs:spellcheck\": 'cspell \"src/docs/**/*.md\"',\n \"docs:release-version\": \"tsx scripts/update-release-version.mts\",\n \"docs:verify-version\": \"tsx scripts/update-release-version.mts --verify\",\n \"types:build-config\": \"tsx scripts/create-types-from-json-schema.mts\",\n \"types:verify-config\": \"tsx scripts/create-types-from-json-schema.mts --verify\",\n checkCircle: \"npx madge --circular ./src\",\n prepublishOnly: \"pnpm docs:verify-version\"\n },\n repository: {\n type: \"git\",\n url: \"https://github.com/mermaid-js/mermaid\"\n },\n author: \"Knut Sveidqvist\",\n license: \"MIT\",\n standard: {\n ignore: [\n \"**/parser/*.js\",\n \"dist/**/*.js\",\n \"cypress/**/*.js\"\n ],\n globals: [\n \"page\"\n ]\n },\n dependencies: {\n \"@braintree/sanitize-url\": \"^7.1.1\",\n \"@iconify/utils\": \"^3.0.1\",\n \"@mermaid-js/parser\": \"workspace:^\",\n \"@types/d3\": \"^7.4.3\",\n cytoscape: \"^3.29.3\",\n \"cytoscape-cose-bilkent\": \"^4.1.0\",\n \"cytoscape-fcose\": \"^2.2.0\",\n d3: \"^7.9.0\",\n \"d3-sankey\": \"^0.12.3\",\n \"dagre-d3-es\": \"7.0.11\",\n dayjs: \"^1.11.18\",\n dompurify: \"^3.2.5\",\n katex: \"^0.16.22\",\n khroma: \"^2.1.0\",\n \"lodash-es\": \"^4.17.21\",\n marked: \"^16.2.1\",\n roughjs: \"^4.6.6\",\n stylis: \"^4.3.6\",\n \"ts-dedent\": \"^2.2.0\",\n uuid: \"^11.1.0\"\n },\n devDependencies: {\n \"@adobe/jsonschema2md\": \"^8.0.5\",\n \"@iconify/types\": \"^2.0.0\",\n \"@types/cytoscape\": \"^3.21.9\",\n \"@types/cytoscape-fcose\": \"^2.2.4\",\n \"@types/d3-sankey\": \"^0.12.4\",\n \"@types/d3-scale\": \"^4.0.9\",\n \"@types/d3-scale-chromatic\": \"^3.1.0\",\n \"@types/d3-selection\": \"^3.0.11\",\n \"@types/d3-shape\": \"^3.1.7\",\n \"@types/jsdom\": \"^21.1.7\",\n \"@types/katex\": \"^0.16.7\",\n \"@types/lodash-es\": \"^4.17.12\",\n \"@types/micromatch\": \"^4.0.9\",\n \"@types/stylis\": \"^4.2.7\",\n \"@types/uuid\": \"^10.0.0\",\n ajv: \"^8.17.1\",\n canvas: \"^3.1.2\",\n chokidar: \"3.6.0\",\n concurrently: \"^9.1.2\",\n \"csstree-validator\": \"^4.0.1\",\n globby: \"^14.1.0\",\n jison: \"^0.4.18\",\n \"js-base64\": \"^3.7.8\",\n jsdom: \"^26.1.0\",\n \"json-schema-to-typescript\": \"^15.0.4\",\n micromatch: \"^4.0.8\",\n \"path-browserify\": \"^1.0.1\",\n prettier: \"^3.5.3\",\n remark: \"^15.0.1\",\n \"remark-frontmatter\": \"^5.0.0\",\n \"remark-gfm\": \"^4.0.1\",\n rimraf: \"^6.0.1\",\n \"start-server-and-test\": \"^2.0.13\",\n \"type-fest\": \"^4.35.0\",\n typedoc: \"^0.28.12\",\n \"typedoc-plugin-markdown\": \"^4.8.1\",\n typescript: \"~5.7.3\",\n \"unist-util-flatmap\": \"^1.0.0\",\n \"unist-util-visit\": \"^5.0.0\",\n vitepress: \"^1.6.4\",\n \"vitepress-plugin-search\": \"1.0.4-alpha.22\"\n },\n files: [\n \"dist/\",\n \"README.md\"\n ],\n publishConfig: {\n access: \"public\"\n }\n};\n\nexport {\n package_default\n};\n"], + "mappings": "AACA,IAAIA,EAAkB,CACpB,KAAM,UACN,QAAS,UACT,YAAa,iIACb,KAAM,SACN,OAAQ,0BACR,MAAO,sBACP,QAAS,CACP,IAAK,CACH,MAAO,sBACP,OAAQ,0BACR,QAAS,yBACX,EACA,MAAO,KACT,EACA,SAAU,CACR,UACA,WACA,YACA,mBACA,QACA,gBACA,YACA,UACA,iBACA,aACA,aACA,YACA,cACA,iBACA,sBACA,OACF,EACA,QAAS,CACP,MAAO,cACP,IAAK,cACL,YAAa,wGACb,aAAc,0FACd,cAAe,8EACf,qBAAsB,qMACtB,uBAAwB,0IACxB,WAAY,6HACZ,kBAAmB,oIACnB,aAAc,6DACd,kBAAmB,4BACnB,uBAAwB,yCACxB,sBAAuB,kDACvB,qBAAsB,gDACtB,sBAAuB,yDACvB,YAAa,6BACb,eAAgB,0BAClB,EACA,WAAY,CACV,KAAM,MACN,IAAK,uCACP,EACA,OAAQ,kBACR,QAAS,MACT,SAAU,CACR,OAAQ,CACN,iBACA,eACA,iBACF,EACA,QAAS,CACP,MACF,CACF,EACA,aAAc,CACZ,0BAA2B,SAC3B,iBAAkB,SAClB,qBAAsB,cACtB,YAAa,SACb,UAAW,UACX,yBAA0B,SAC1B,kBAAmB,SACnB,GAAI,SACJ,YAAa,UACb,cAAe,SACf,MAAO,WACP,UAAW,SACX,MAAO,WACP,OAAQ,SACR,YAAa,WACb,OAAQ,UACR,QAAS,SACT,OAAQ,SACR,YAAa,SACb,KAAM,SACR,EACA,gBAAiB,CACf,uBAAwB,SACxB,iBAAkB,SAClB,mBAAoB,UACpB,yBAA0B,SAC1B,mBAAoB,UACpB,kBAAmB,SACnB,4BAA6B,SAC7B,sBAAuB,UACvB,kBAAmB,SACnB,eAAgB,UAChB,eAAgB,UAChB,mBAAoB,WACpB,oBAAqB,SACrB,gBAAiB,SACjB,cAAe,UACf,IAAK,UACL,OAAQ,SACR,SAAU,QACV,aAAc,SACd,oBAAqB,SACrB,OAAQ,UACR,MAAO,UACP,YAAa,SACb,MAAO,UACP,4BAA6B,UAC7B,WAAY,SACZ,kBAAmB,SACnB,SAAU,SACV,OAAQ,UACR,qBAAsB,SACtB,aAAc,SACd,OAAQ,SACR,wBAAyB,UACzB,YAAa,UACb,QAAS,WACT,0BAA2B,SAC3B,WAAY,SACZ,qBAAsB,SACtB,mBAAoB,SACpB,UAAW,SACX,0BAA2B,gBAC7B,EACA,MAAO,CACL,QACA,WACF,EACA,cAAe,CACb,OAAQ,QACV,CACF", + "names": ["package_default"] +} diff --git a/docs/website/public/chunk-OEBO5CRK.min.js b/docs/website/public/chunk-OEBO5CRK.min.js new file mode 100644 index 000000000..27ac9c7e7 --- /dev/null +++ b/docs/website/public/chunk-OEBO5CRK.min.js @@ -0,0 +1,2 @@ +import{W as c}from"./chunk-3EE2TK35.min.js";import{b as l}from"./chunk-6TVUEPFY.min.js";var m=l(t=>{let{handDrawnSeed:e}=c();return{fill:t,hachureAngle:120,hachureGap:4,fillWeight:2,roughness:.7,stroke:t,seed:e}},"solidStateFill"),h=l(t=>{let e=p([...t.cssCompiledStyles||[],...t.cssStyles||[],...t.labelStyle||[]]);return{stylesMap:e,stylesArray:[...e]}},"compileStyles"),p=l(t=>{let e=new Map;return t.forEach(o=>{let[a,r]=o.split(":");e.set(a.trim(),r?.trim())}),e},"styles2Map"),d=l(t=>t==="color"||t==="font-size"||t==="font-family"||t==="font-weight"||t==="font-style"||t==="text-decoration"||t==="text-align"||t==="text-transform"||t==="line-height"||t==="letter-spacing"||t==="word-spacing"||t==="text-shadow"||t==="text-overflow"||t==="white-space"||t==="word-wrap"||t==="word-break"||t==="overflow-wrap"||t==="hyphens","isLabelStyle"),S=l(t=>{let{stylesArray:e}=h(t),o=[],a=[],r=[],n=[];return e.forEach(s=>{let i=s[0];d(i)?o.push(s.join(":")+" !important"):(a.push(s.join(":")+" !important"),i.includes("stroke")&&r.push(s.join(":")+" !important"),i==="fill"&&n.push(s.join(":")+" !important"))}),{labelStyles:o.join(";"),nodeStyles:a.join(";"),stylesArray:e,borderStyles:r,backgroundStyles:n}},"styles2String"),w=l((t,e)=>{let{themeVariables:o,handDrawnSeed:a}=c(),{nodeBorder:r,mainBkg:n}=o,{stylesMap:s}=h(t);return Object.assign({roughness:.7,fill:s.get("fill")||n,fillStyle:"hachure",fillWeight:4,hachureGap:5.2,stroke:s.get("stroke")||r,seed:a,strokeWidth:s.get("stroke-width")?.replace("px","")||1.3,fillLineDash:[0,0],strokeLineDash:f(s.get("stroke-dasharray"))},e)},"userNodeOverrides"),f=l(t=>{if(!t)return[0,0];let e=t.trim().split(/\s+/).map(Number);if(e.length===1){let r=isNaN(e[0])?0:e[0];return[r,r]}let o=isNaN(e[0])?0:e[0],a=isNaN(e[1])?0:e[1];return[o,a]},"getStrokeDashArray");export{m as a,h as b,d as c,S as d,w as e}; +//# sourceMappingURL=chunk-OEBO5CRK.min.js.map diff --git a/docs/website/public/chunk-OEBO5CRK.min.js.map b/docs/website/public/chunk-OEBO5CRK.min.js.map new file mode 100644 index 000000000..ea431760e --- /dev/null +++ b/docs/website/public/chunk-OEBO5CRK.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/mermaid/dist/chunks/mermaid.core/chunk-ATLVNIR6.mjs"], + "sourcesContent": ["import {\n getConfig2 as getConfig\n} from \"./chunk-ABZYJK2D.mjs\";\nimport {\n __name\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/rendering-util/rendering-elements/shapes/handDrawnShapeStyles.ts\nvar solidStateFill = /* @__PURE__ */ __name((color) => {\n const { handDrawnSeed } = getConfig();\n return {\n fill: color,\n hachureAngle: 120,\n // angle of hachure,\n hachureGap: 4,\n fillWeight: 2,\n roughness: 0.7,\n stroke: color,\n seed: handDrawnSeed\n };\n}, \"solidStateFill\");\nvar compileStyles = /* @__PURE__ */ __name((node) => {\n const stylesMap = styles2Map([\n ...node.cssCompiledStyles || [],\n ...node.cssStyles || [],\n ...node.labelStyle || []\n ]);\n return { stylesMap, stylesArray: [...stylesMap] };\n}, \"compileStyles\");\nvar styles2Map = /* @__PURE__ */ __name((styles) => {\n const styleMap = /* @__PURE__ */ new Map();\n styles.forEach((style) => {\n const [key, value] = style.split(\":\");\n styleMap.set(key.trim(), value?.trim());\n });\n return styleMap;\n}, \"styles2Map\");\nvar isLabelStyle = /* @__PURE__ */ __name((key) => {\n return key === \"color\" || key === \"font-size\" || key === \"font-family\" || key === \"font-weight\" || key === \"font-style\" || key === \"text-decoration\" || key === \"text-align\" || key === \"text-transform\" || key === \"line-height\" || key === \"letter-spacing\" || key === \"word-spacing\" || key === \"text-shadow\" || key === \"text-overflow\" || key === \"white-space\" || key === \"word-wrap\" || key === \"word-break\" || key === \"overflow-wrap\" || key === \"hyphens\";\n}, \"isLabelStyle\");\nvar styles2String = /* @__PURE__ */ __name((node) => {\n const { stylesArray } = compileStyles(node);\n const labelStyles = [];\n const nodeStyles = [];\n const borderStyles = [];\n const backgroundStyles = [];\n stylesArray.forEach((style) => {\n const key = style[0];\n if (isLabelStyle(key)) {\n labelStyles.push(style.join(\":\") + \" !important\");\n } else {\n nodeStyles.push(style.join(\":\") + \" !important\");\n if (key.includes(\"stroke\")) {\n borderStyles.push(style.join(\":\") + \" !important\");\n }\n if (key === \"fill\") {\n backgroundStyles.push(style.join(\":\") + \" !important\");\n }\n }\n });\n return {\n labelStyles: labelStyles.join(\";\"),\n nodeStyles: nodeStyles.join(\";\"),\n stylesArray,\n borderStyles,\n backgroundStyles\n };\n}, \"styles2String\");\nvar userNodeOverrides = /* @__PURE__ */ __name((node, options) => {\n const { themeVariables, handDrawnSeed } = getConfig();\n const { nodeBorder, mainBkg } = themeVariables;\n const { stylesMap } = compileStyles(node);\n const result = Object.assign(\n {\n roughness: 0.7,\n fill: stylesMap.get(\"fill\") || mainBkg,\n fillStyle: \"hachure\",\n // solid fill\n fillWeight: 4,\n hachureGap: 5.2,\n stroke: stylesMap.get(\"stroke\") || nodeBorder,\n seed: handDrawnSeed,\n strokeWidth: stylesMap.get(\"stroke-width\")?.replace(\"px\", \"\") || 1.3,\n fillLineDash: [0, 0],\n strokeLineDash: getStrokeDashArray(stylesMap.get(\"stroke-dasharray\"))\n },\n options\n );\n return result;\n}, \"userNodeOverrides\");\nvar getStrokeDashArray = /* @__PURE__ */ __name((strokeDasharrayStyle) => {\n if (!strokeDasharrayStyle) {\n return [0, 0];\n }\n const dashArray = strokeDasharrayStyle.trim().split(/\\s+/).map(Number);\n if (dashArray.length === 1) {\n const val = isNaN(dashArray[0]) ? 0 : dashArray[0];\n return [val, val];\n }\n const first = isNaN(dashArray[0]) ? 0 : dashArray[0];\n const second = isNaN(dashArray[1]) ? 0 : dashArray[1];\n return [first, second];\n}, \"getStrokeDashArray\");\n\nexport {\n solidStateFill,\n compileStyles,\n isLabelStyle,\n styles2String,\n userNodeOverrides\n};\n"], + "mappings": "wFAQA,IAAIA,EAAiCC,EAAQC,GAAU,CAC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CAAC,CAAC,EAAI,EAAIA,EAAU,CAAC,EAC7CG,EAAS,MAAMH,EAAU,CAAC,CAAC,EAAI,EAAIA,EAAU,CAAC,EACpD,MAAO,CAACE,EAAOC,CAAM,CACvB,EAAG,oBAAoB", + "names": ["solidStateFill", "__name", "color", "handDrawnSeed", "getConfig2", "compileStyles", "node", "stylesMap", "styles2Map", "styles", "styleMap", "style", "key", "value", "isLabelStyle", "styles2String", "stylesArray", "labelStyles", "nodeStyles", "borderStyles", "backgroundStyles", "userNodeOverrides", "options", "themeVariables", "nodeBorder", "mainBkg", "getStrokeDashArray", "strokeDasharrayStyle", "dashArray", "val", "first", "second"] +} diff --git a/docs/website/public/chunk-ORLGEIQN.min.js b/docs/website/public/chunk-ORLGEIQN.min.js new file mode 100644 index 000000000..2c67fb915 --- /dev/null +++ b/docs/website/public/chunk-ORLGEIQN.min.js @@ -0,0 +1,2 @@ +import{L as w}from"./chunk-3EE2TK35.min.js";import{b as r,d as c}from"./chunk-6TVUEPFY.min.js";var g=r((t,e,i,h)=>{t.attr("class",i);let{width:o,height:n,x,y:u}=s(t,e);w(t,n,o,h);let a=m(x,u,o,n,e);t.attr("viewBox",a),c.debug(`viewBox configured: ${a} with padding: ${e}`)},"setupViewPortForSVG"),s=r((t,e)=>{let i=t.node()?.getBBox()||{width:0,height:0,x:0,y:0};return{width:i.width+e*2,height:i.height+e*2,x:i.x,y:i.y}},"calculateDimensionsWithPadding"),m=r((t,e,i,h,o)=>`${t-o} ${e-o} ${i} ${h}`,"createViewBox");export{g as a}; +//# sourceMappingURL=chunk-ORLGEIQN.min.js.map diff --git a/docs/website/public/chunk-ORLGEIQN.min.js.map b/docs/website/public/chunk-ORLGEIQN.min.js.map new file mode 100644 index 000000000..28ae6d602 --- /dev/null +++ b/docs/website/public/chunk-ORLGEIQN.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/mermaid/dist/chunks/mermaid.core/chunk-QN33PNHL.mjs"], + "sourcesContent": ["import {\n configureSvgSize\n} from \"./chunk-ABZYJK2D.mjs\";\nimport {\n __name,\n log\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/rendering-util/setupViewPortForSVG.ts\nvar setupViewPortForSVG = /* @__PURE__ */ __name((svg, padding, cssDiagram, useMaxWidth) => {\n svg.attr(\"class\", cssDiagram);\n const { width, height, x, y } = calculateDimensionsWithPadding(svg, padding);\n configureSvgSize(svg, height, width, useMaxWidth);\n const viewBox = createViewBox(x, y, width, height, padding);\n svg.attr(\"viewBox\", viewBox);\n log.debug(`viewBox configured: ${viewBox} with padding: ${padding}`);\n}, \"setupViewPortForSVG\");\nvar calculateDimensionsWithPadding = /* @__PURE__ */ __name((svg, padding) => {\n const bounds = svg.node()?.getBBox() || { width: 0, height: 0, x: 0, y: 0 };\n return {\n width: bounds.width + padding * 2,\n height: bounds.height + padding * 2,\n x: bounds.x,\n y: bounds.y\n };\n}, \"calculateDimensionsWithPadding\");\nvar createViewBox = /* @__PURE__ */ __name((x, y, width, height, padding) => {\n return `${x - padding} ${y - padding} ${width} ${height}`;\n}, \"createViewBox\");\n\nexport {\n setupViewPortForSVG\n};\n"], + "mappings": "+FASA,IAAIA,EAAsCC,EAAO,CAACC,EAAKC,EAASC,EAAYC,IAAgB,CAC1FH,EAAI,KAAK,QAASE,CAAU,EAC5B,GAAM,CAAE,MAAAE,EAAO,OAAAC,EAAQ,EAAG,EAAAC,CAAE,EAAIC,EAA+BP,EAAKC,CAAO,EAC3EO,EAAiBR,EAAKK,EAAQD,EAAOD,CAAW,EAChD,IAAMM,EAAUC,EAAc,EAAGJ,EAAGF,EAAOC,EAAQJ,CAAO,EAC1DD,EAAI,KAAK,UAAWS,CAAO,EAC3BE,EAAI,MAAM,uBAAuBF,CAAO,kBAAkBR,CAAO,EAAE,CACrE,EAAG,qBAAqB,EACpBM,EAAiDR,EAAO,CAACC,EAAKC,IAAY,CAC5E,IAAMW,EAASZ,EAAI,KAAK,GAAG,QAAQ,GAAK,CAAE,MAAO,EAAG,OAAQ,EAAG,EAAG,EAAG,EAAG,CAAE,EAC1E,MAAO,CACL,MAAOY,EAAO,MAAQX,EAAU,EAChC,OAAQW,EAAO,OAASX,EAAU,EAClC,EAAGW,EAAO,EACV,EAAGA,EAAO,CACZ,CACF,EAAG,gCAAgC,EAC/BF,EAAgCX,EAAO,CAACc,EAAGP,EAAGF,EAAOC,EAAQJ,IACxD,GAAGY,EAAIZ,CAAO,IAAIK,EAAIL,CAAO,IAAIG,CAAK,IAAIC,CAAM,GACtD,eAAe", + "names": ["setupViewPortForSVG", "__name", "svg", "padding", "cssDiagram", "useMaxWidth", "width", "height", "y", "calculateDimensionsWithPadding", "configureSvgSize", "viewBox", "createViewBox", "log", "bounds", "x"] +} diff --git a/docs/website/public/chunk-OSRY5VT3.min.js b/docs/website/public/chunk-OSRY5VT3.min.js new file mode 100644 index 000000000..3a86c6b2b --- /dev/null +++ b/docs/website/public/chunk-OSRY5VT3.min.js @@ -0,0 +1,2 @@ +var h=Object.create;var f=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var k=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty;var m=(b,a)=>()=>(a||b((a={exports:{}}).exports,a),a.exports),n=(b,a)=>{for(var c in a)f(b,c,{get:a[c],enumerable:!0})},e=(b,a,c,g)=>{if(a&&typeof a=="object"||typeof a=="function")for(let d of j(a))!l.call(b,d)&&d!==c&&f(b,d,{get:()=>a[d],enumerable:!(g=i(a,d))||g.enumerable});return b},o=(b,a,c)=>(e(b,a,"default"),c&&e(c,a,"default")),p=(b,a,c)=>(c=b!=null?h(k(b)):{},e(a||!b||!b.__esModule?f(c,"default",{value:b,enumerable:!0}):c,b));export{m as a,n as b,o as c,p as d}; +//# sourceMappingURL=chunk-OSRY5VT3.min.js.map diff --git a/docs/website/public/chunk-OSRY5VT3.min.js.map b/docs/website/public/chunk-OSRY5VT3.min.js.map new file mode 100644 index 000000000..98652118b --- /dev/null +++ b/docs/website/public/chunk-OSRY5VT3.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": [], + "sourcesContent": [], + "mappings": "", + "names": [] +} diff --git a/docs/website/public/chunk-PPPUQLJ3.min.js b/docs/website/public/chunk-PPPUQLJ3.min.js new file mode 100644 index 000000000..fdf87c3fb --- /dev/null +++ b/docs/website/public/chunk-PPPUQLJ3.min.js @@ -0,0 +1,16 @@ +import{b as e}from"./chunk-6TVUEPFY.min.js";var l=e(()=>` + /* Font Awesome icon styling - consolidated */ + .label-icon { + display: inline-block; + height: 1em; + overflow: visible; + vertical-align: -0.125em; + } + + .node .label-icon path { + fill: currentColor; + stroke: revert; + stroke-width: revert; + } +`,"getIconStyles");export{l as a}; +//# sourceMappingURL=chunk-PPPUQLJ3.min.js.map diff --git a/docs/website/public/chunk-PPPUQLJ3.min.js.map b/docs/website/public/chunk-PPPUQLJ3.min.js.map new file mode 100644 index 000000000..cd53a8851 --- /dev/null +++ b/docs/website/public/chunk-PPPUQLJ3.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/mermaid/dist/chunks/mermaid.core/chunk-FMBD7UC4.mjs"], + "sourcesContent": ["import {\n __name\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/diagrams/globalStyles.ts\nvar getIconStyles = /* @__PURE__ */ __name(() => `\n /* Font Awesome icon styling - consolidated */\n .label-icon {\n display: inline-block;\n height: 1em;\n overflow: visible;\n vertical-align: -0.125em;\n }\n \n .node .label-icon path {\n fill: currentColor;\n stroke: revert;\n stroke-width: revert;\n }\n`, \"getIconStyles\");\n\nexport {\n getIconStyles\n};\n"], + "mappings": "4CAKA,IAAIA,EAAgCC,EAAO,IAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAc9C,eAAe", + "names": ["getIconStyles", "__name"] +} diff --git a/docs/website/public/chunk-PTL4EUOE.min.js b/docs/website/public/chunk-PTL4EUOE.min.js new file mode 100644 index 000000000..815ff15ac --- /dev/null +++ b/docs/website/public/chunk-PTL4EUOE.min.js @@ -0,0 +1,2 @@ +import{B as d,D as v,G as P,a as e,c as u,f as i,g as a,i as m,t as w,v as f,y as b,z as j}from"./chunk-E5F23VE2.min.js";var A=w(Object.keys,Object),S=A;var C=Object.prototype,V=C.hasOwnProperty;function D(r){if(!f(r))return S(r);var t=[];for(var o in Object(r))V.call(r,o)&&o!="constructor"&&t.push(o);return t}var T=D;var K=a(e,"DataView"),n=K;var N=a(e,"Promise"),s=N;var W=a(e,"Set"),c=W;var B=a(e,"WeakMap"),g=B;var O="[object Map]",z="[object Object]",M="[object Promise]",h="[object Set]",x="[object WeakMap]",k="[object DataView]",E=i(n),G=i(m),L=i(s),q=i(c),F=i(g),p=u;(n&&p(new n(new ArrayBuffer(1)))!=k||m&&p(new m)!=O||s&&p(s.resolve())!=M||c&&p(new c)!=h||g&&p(new g)!=x)&&(p=function(r){var t=u(r),o=t==z?r.constructor:void 0,y=o?i(o):"";if(y)switch(y){case E:return k;case G:return O;case L:return M;case q:return h;case F:return x}return t});var l=p;var H="[object Map]",I="[object Set]",J=Object.prototype,Q=J.hasOwnProperty;function R(r){if(r==null)return!0;if(d(r)&&(j(r)||typeof r=="string"||typeof r.splice=="function"||v(r)||P(r)||b(r)))return!r.length;var t=l(r);if(t==H||t==I)return!r.size;if(f(r))return!T(r).length;for(var o in r)if(Q.call(r,o))return!1;return!0}var kr=R;export{T as a,c as b,l as c,kr as d}; +//# sourceMappingURL=chunk-PTL4EUOE.min.js.map diff --git a/docs/website/public/chunk-PTL4EUOE.min.js.map b/docs/website/public/chunk-PTL4EUOE.min.js.map new file mode 100644 index 000000000..ed2cb6648 --- /dev/null +++ b/docs/website/public/chunk-PTL4EUOE.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/lodash-es/_nativeKeys.js", "../../node_modules/lodash-es/_baseKeys.js", "../../node_modules/lodash-es/_DataView.js", "../../node_modules/lodash-es/_Promise.js", "../../node_modules/lodash-es/_Set.js", "../../node_modules/lodash-es/_WeakMap.js", "../../node_modules/lodash-es/_getTag.js", "../../node_modules/lodash-es/isEmpty.js"], + "sourcesContent": ["import overArg from './_overArg.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nexport default nativeKeys;\n", "import isPrototype from './_isPrototype.js';\nimport nativeKeys from './_nativeKeys.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\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 */\nfunction 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\nexport default baseKeys;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nexport default DataView;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nexport default Promise;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nexport default Set;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nexport default WeakMap;\n", "import DataView from './_DataView.js';\nimport Map from './_Map.js';\nimport Promise from './_Promise.js';\nimport Set from './_Set.js';\nimport WeakMap from './_WeakMap.js';\nimport baseGetTag from './_baseGetTag.js';\nimport toSource from './_toSource.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\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 */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((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\nexport default getTag;\n", "import baseKeys from './_baseKeys.js';\nimport getTag from './_getTag.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isArrayLike from './isArrayLike.js';\nimport isBuffer from './isBuffer.js';\nimport isPrototype from './_isPrototype.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n setTag = '[object Set]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\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 */\nfunction 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\nexport default isEmpty;\n"], + "mappings": "yHAGA,IAAIA,EAAaC,EAAQ,OAAO,KAAM,MAAM,EAErCC,EAAQF,ECDf,IAAIG,EAAc,OAAO,UAGrBC,EAAiBD,EAAY,eASjC,SAASE,EAASC,EAAQ,CACxB,GAAI,CAACC,EAAYD,CAAM,EACrB,OAAOE,EAAWF,CAAM,EAE1B,IAAIG,EAAS,CAAC,EACd,QAASC,KAAO,OAAOJ,CAAM,EACvBF,EAAe,KAAKE,EAAQI,CAAG,GAAKA,GAAO,eAC7CD,EAAO,KAAKC,CAAG,EAGnB,OAAOD,CACT,CAEA,IAAOE,EAAQN,ECzBf,IAAIO,EAAWC,EAAUC,EAAM,UAAU,EAElCC,EAAQH,ECFf,IAAII,EAAUC,EAAUC,EAAM,SAAS,EAEhCC,EAAQH,ECFf,IAAII,EAAMC,EAAUC,EAAM,KAAK,EAExBC,EAAQH,ECFf,IAAII,EAAUC,EAAUC,EAAM,SAAS,E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W,GAAOV,EAC1B,MAAO,CAACI,EAAM,KAEhB,GAAIQ,EAAYR,CAAK,EACnB,MAAO,CAACS,EAAST,CAAK,EAAE,OAE1B,QAASU,KAAOV,EACd,GAAIF,EAAe,KAAKE,EAAOU,CAAG,EAChC,MAAO,GAGX,MAAO,EACT,CAEA,IAAOC,GAAQZ", + "names": ["nativeKeys", "overArg_default", "nativeKeys_default", "objectProto", "hasOwnProperty", "baseKeys", "object", "isPrototype_default", "nativeKeys_default", "result", "key", "baseKeys_default", "DataView", "getNative_default", "root_default", "DataView_default", "Promise", "getNative_default", "root_default", "Promise_default", "Set", "getNative_default", "root_default", "Set_default", "WeakMap", "getNative_default", "root_default", "WeakMap_default", "mapTag", "objectTag", "promiseTag", "setTag", "weakMapTag", "dataViewTag", "dataViewCtorString", "toSource_default", "DataView_default", "mapCtorString", "Map_default", "promiseCtorString", "Promise_default", "setCtorString", "Set_default", "weakMapCtorString", "WeakMap_default", "getTag", "baseGetTag_default", "value", "result", "Ctor", "ctorString", "getTag_default", "mapTag", "setTag", "objectProto", "hasOwnProperty", "isEmpty", "value", "isArrayLike_default", "isArray_default", "isBuffer_default", "isTypedArray_default", "isArguments_default", "tag", "getTag_default", "isPrototype_default", "baseKeys_default", "key", "isEmpty_default"] +} diff --git a/docs/website/public/chunk-QZZKR5JD.min.js b/docs/website/public/chunk-QZZKR5JD.min.js new file mode 100644 index 000000000..1a12a732e --- /dev/null +++ b/docs/website/public/chunk-QZZKR5JD.min.js @@ -0,0 +1,3 @@ +import{a as vt}from"./chunk-CM5D5KZN.min.js";import{K as M,h as m,k as L,n as b,r as T}from"./chunk-3EE2TK35.min.js";import{T as V,k as $}from"./chunk-E5F23VE2.min.js";import{$ as Z,I as F,L as _,M as A,N,O as R,P as D,Q as H,R as O,S as z,T as j,U,V as k,W as X,X as Y,Y as G,Z as J,_ as q,aa as K,b as s,ba as Q,d as f,j as E}from"./chunk-6TVUEPFY.min.js";import{d as mt}from"./chunk-OSRY5VT3.min.js";var nt=mt(vt(),1);var yt="\u200B",xt={curveBasis:N,curveBasisClosed:R,curveBasisOpen:D,curveBumpX:_,curveBumpY:A,curveBundle:H,curveCardinalClosed:z,curveCardinalOpen:j,curveCardinal:O,curveCatmullRomClosed:k,curveCatmullRomOpen:X,curveCatmullRom:U,curveLinear:F,curveLinearClosed:Y,curveMonotoneX:G,curveMonotoneY:J,curveNatural:q,curveStep:Z,curveStepAfter:Q,curveStepBefore:K},pt=/\s*(?:(\w+)(?=:):|(\w+))\s*(?:(\w+)|((?:(?!}%{2}).|\r?\n)*))?\s*(?:}%{2})?/gi,Mt=s(function(e,t){let r=rt(e,/(?:init\b)|(?:initialize\b)/),n={};if(Array.isArray(r)){let a=r.map(l=>l.args);T(a),n=b(n,[...a])}else n=r.args;if(!n)return;let i=L(e,t),o="config";return n[o]!==void 0&&(i==="flowchart-v2"&&(i="flowchart"),n[i]=n[o],delete n[o]),n},"detectInit"),rt=s(function(e,t=null){try{let r=new RegExp(`[%]{2}(?![{]${pt.source})(?=[}][%]{2}).* +`,"ig");e=e.trim().replace(r,"").replace(/'/gm,'"'),f.debug(`Detecting diagram directive${t!==null?" type:"+t:""} based on the text:${e}`);let n,i=[];for(;(n=m.exec(e))!==null;)if(n.index===m.lastIndex&&m.lastIndex++,n&&!t||t&&n[1]?.match(t)||t&&n[2]?.match(t)){let o=n[1]?n[1]:n[2],a=n[3]?n[3].trim():n[4]?JSON.parse(n[4].trim()):null;i.push({type:o,args:a})}return i.length===0?{type:e,args:null}:i.length===1?i[0]:i}catch(r){return f.error(`ERROR: ${r.message} - Unable to parse directive type: '${t}' based on the text: '${e}'`),{type:void 0,args:null}}},"detectDirective"),Ot=s(function(e){return e.replace(m,"")},"removeDirectives"),$t=s(function(e,t){for(let[r,n]of t.entries())if(n.match(e))return r;return-1},"isSubstringInArray");function it(e,t){if(!e)return t;let r=`curve${e.charAt(0).toUpperCase()+e.slice(1)}`;return xt[r]??t}s(it,"interpolateToCurve");function ot(e,t){let r=e.trim();if(r)return t.securityLevel!=="loose"?(0,nt.sanitizeUrl)(r):r}s(ot,"formatUrl");var wt=s((e,...t)=>{let r=e.split("."),n=r.length-1,i=r[n],o=window;for(let a=0;a{r+=S(i,t),t=i});let n=r/2;return B(e,n)}s(at,"traverseEdge");function st(e){return e.length===1?e[0]:at(e)}s(st,"calcLabelPosition");var tt=s((e,t=2)=>{let r=Math.pow(10,t);return Math.round(e*r)/r},"roundNumber"),B=s((e,t)=>{let r,n=t;for(let i of e){if(r){let o=S(i,r);if(o===0)return r;if(o=1)return{x:i.x,y:i.y};if(a>0&&a<1)return{x:tt((1-a)*r.x+a*i.x,5),y:tt((1-a)*r.y+a*i.y,5)}}}r=i}throw new Error("Could not find a suitable point for the given distance")},"calculatePoint"),bt=s((e,t,r)=>{f.info(`our points ${JSON.stringify(t)}`),t[0]!==r&&(t=t.reverse());let i=B(t,25),o=e?10:5,a=Math.atan2(t[0].y-i.y,t[0].x-i.x),l={x:0,y:0};return l.x=Math.sin(a)*o+(t[0].x+i.x)/2,l.y=-Math.cos(a)*o+(t[0].y+i.y)/2,l},"calcCardinalityPosition");function ct(e,t,r){let n=structuredClone(r);f.info("our points",n),t!=="start_left"&&t!=="start_right"&&n.reverse();let i=25+e,o=B(n,i),a=10+e*.5,l=Math.atan2(n[0].y-o.y,n[0].x-o.x),c={x:0,y:0};return t==="start_left"?(c.x=Math.sin(l+Math.PI)*a+(n[0].x+o.x)/2,c.y=-Math.cos(l+Math.PI)*a+(n[0].y+o.y)/2):t==="end_right"?(c.x=Math.sin(l-Math.PI)*a+(n[0].x+o.x)/2-5,c.y=-Math.cos(l-Math.PI)*a+(n[0].y+o.y)/2-5):t==="end_left"?(c.x=Math.sin(l)*a+(n[0].x+o.x)/2-5,c.y=-Math.cos(l)*a+(n[0].y+o.y)/2-5):(c.x=Math.sin(l)*a+(n[0].x+o.x)/2,c.y=-Math.cos(l)*a+(n[0].y+o.y)/2),c}s(ct,"calcTerminalLabelPosition");function lt(e){let t="",r="";for(let n of e)n!==void 0&&(n.startsWith("color:")||n.startsWith("text-align:")?r=r+n+";":t=t+n+";");return{style:t,labelStyle:r}}s(lt,"getStylesFromArray");var et=0,St=s(()=>(et++,"id-"+Math.random().toString(36).substr(2,12)+"-"+et),"generateId");function ut(e){let t="",r="0123456789abcdef",n=r.length;for(let i=0;iut(e.length),"random"),Ct=s(function(){return{x:0,y:0,fill:void 0,anchor:"start",style:"#666",width:100,height:100,textMargin:0,rx:0,ry:0,valign:void 0,text:""}},"getTextObj"),Pt=s(function(e,t){let r=t.text.replace(M.lineBreakRegex," "),[,n]=P(t.fontSize),i=e.append("text");i.attr("x",t.x),i.attr("y",t.y),i.style("text-anchor",t.anchor),i.style("font-family",t.fontFamily),i.style("font-size",n),i.style("font-weight",t.fontWeight),i.attr("fill",t.fill),t.class!==void 0&&i.attr("class",t.class);let o=i.append("tspan");return o.attr("x",t.x+t.textMargin*2),o.attr("fill",t.fill),o.text(r),i},"drawSimpleText"),Wt=$((e,t,r)=>{if(!e||(r=Object.assign({fontSize:12,fontWeight:400,fontFamily:"Arial",joinWith:"
"},r),M.lineBreakRegex.test(e)))return e;let n=e.split(" ").filter(Boolean),i=[],o="";return n.forEach((a,l)=>{let c=v(`${a} `,r),u=v(o,r);if(c>t){let{hyphenatedStrings:g,remainingWord:h}=It(a,t,"-",r);i.push(o,...g),o=h}else u+c>=t?(i.push(o),o=a):o=[o,a].filter(Boolean).join(" ");l+1===n.length&&i.push(o)}),i.filter(a=>a!=="").join(r.joinWith)},(e,t,r)=>`${e}${t}${r.fontSize}${r.fontWeight}${r.fontFamily}${r.joinWith}`),It=$((e,t,r="-",n)=>{n=Object.assign({fontSize:12,fontWeight:400,fontFamily:"Arial",margin:0},n);let i=[...e],o=[],a="";return i.forEach((l,c)=>{let u=`${a}${l}`;if(v(u,n)>=t){let x=c+1,g=i.length===x,h=`${u}${r}`;o.push(g?u:h),a=""}else a=u}),{hyphenatedStrings:o,remainingWord:a}},(e,t,r="-",n)=>`${e}${t}${r}${n.fontSize}${n.fontWeight}${n.fontFamily}`);function ht(e,t){return C(e,t).height}s(ht,"calculateTextHeight");function v(e,t){return C(e,t).width}s(v,"calculateTextWidth");var C=$((e,t)=>{let{fontSize:r=12,fontFamily:n="Arial",fontWeight:i=400}=t;if(!e)return{width:0,height:0};let[,o]=P(r),a=["sans-serif",n],l=e.split(M.lineBreakRegex),c=[],u=E("body");if(!u.remove)return{width:0,height:0,lineHeight:0};let y=u.append("svg");for(let g of a){let h=0,d={width:0,height:0,lineHeight:0};for(let gt of l){let W=Ct();W.text=gt||yt;let I=Pt(y,W).style("font-size",o).style("font-weight",i).style("font-family",g),p=(I._groups||I)[0][0].getBBox();if(p.width===0&&p.height===0)throw new Error("svg element not in render tree");d.width=Math.round(Math.max(d.width,p.width)),h=Math.round(p.height),d.height+=h,d.lineHeight=Math.round(Math.max(d.lineHeight,h))}c.push(d)}y.remove();let x=isNaN(c[1].height)||isNaN(c[1].width)||isNaN(c[1].lineHeight)||c[0].height>c[1].height&&c[0].width>c[1].width&&c[0].lineHeight>c[1].lineHeight?0:1;return c[x]},(e,t)=>`${e}${t.fontSize}${t.fontWeight}${t.fontFamily}`),Lt=class{constructor(e=!1,t){this.count=0,this.count=t?t.length:0,this.next=e?()=>this.count++:()=>Date.now()}static{s(this,"InitIDGenerator")}},w,Tt=s(function(e){return w=w||document.createElement("div"),e=escape(e).replace(/%26/g,"&").replace(/%23/g,"#").replace(/%3B/g,";"),w.innerHTML=e,unescape(w.textContent)},"entityDecode");function Et(e){return"str"in e}s(Et,"isDetailedError");var Ft=s((e,t,r,n)=>{if(!n)return;let i=e.node()?.getBBox();i&&e.append("text").text(n).attr("text-anchor","middle").attr("x",i.x+i.width/2).attr("y",-r).attr("class",t)},"insertTitle"),P=s(e=>{if(typeof e=="number")return[e,e+"px"];let t=parseInt(e??"",10);return Number.isNaN(t)?[void 0,void 0]:e===String(t)?[t,e+"px"]:[t,e]},"parseFontSize");function dt(e,t){return V({},e,t)}s(dt,"cleanAndMerge");var zt={assignWithDepth:b,wrapLabel:Wt,calculateTextHeight:ht,calculateTextWidth:v,calculateTextDimensions:C,cleanAndMerge:dt,detectInit:Mt,detectDirective:rt,isSubstringInArray:$t,interpolateToCurve:it,calcLabelPosition:st,calcCardinalityPosition:bt,calcTerminalLabelPosition:ct,formatUrl:ot,getStylesFromArray:lt,generateId:St,random:Bt,runFunc:wt,entityDecode:Tt,insertTitle:Ft,isLabelCoordinateInPath:ft,parseFontSize:P,InitIDGenerator:Lt},jt=s(function(e){let t=e;return t=t.replace(/style.*:\S*#.*;/g,function(r){return r.substring(0,r.length-1)}),t=t.replace(/classDef.*:\S*#.*;/g,function(r){return r.substring(0,r.length-1)}),t=t.replace(/#\w+;/g,function(r){let n=r.substring(1,r.length-1);return/^\+?\d+$/.test(n)?"\uFB02\xB0\xB0"+n+"\xB6\xDF":"\uFB02\xB0"+n+"\xB6\xDF"}),t},"encodeEntities"),Ut=s(function(e){return e.replace(/fl°°/g,"&#").replace(/fl°/g,"&").replace(/¶ß/g,";")},"decodeEntities"),kt=s((e,t,{counter:r=0,prefix:n,suffix:i},o)=>o||`${n?`${n}_`:""}${e}_${t}_${r}${i?`_${i}`:""}`,"getEdgeId");function _t(e){return e??null}s(_t,"handleUndefinedAttr");function ft(e,t){let r=Math.round(e.x),n=Math.round(e.y),i=t.replace(/(\d+\.\d+)/g,o=>Math.round(parseFloat(o)).toString());return i.includes(r.toString())||i.includes(n.toString())}s(ft,"isLabelCoordinateInPath");export{yt as a,Ot as b,it as c,lt as d,St as e,Bt as f,Wt as g,ht as h,v as i,Et as j,P as k,dt as l,zt as m,jt as n,Ut as o,kt as p,_t as q}; +//# sourceMappingURL=chunk-QZZKR5JD.min.js.map diff --git a/docs/website/public/chunk-QZZKR5JD.min.js.map b/docs/website/public/chunk-QZZKR5JD.min.js.map new file mode 100644 index 000000000..0a5aef798 --- /dev/null +++ b/docs/website/public/chunk-QZZKR5JD.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/mermaid/dist/chunks/mermaid.core/chunk-S3R3BYOJ.mjs"], + "sourcesContent": ["import {\n assignWithDepth_default,\n common_default,\n detectType,\n directiveRegex,\n sanitizeDirective\n} from \"./chunk-ABZYJK2D.mjs\";\nimport {\n __name,\n log\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/utils.ts\nimport { sanitizeUrl } from \"@braintree/sanitize-url\";\nimport {\n curveBasis,\n curveBasisClosed,\n curveBasisOpen,\n curveBumpX,\n curveBumpY,\n curveBundle,\n curveCardinalClosed,\n curveCardinalOpen,\n curveCardinal,\n curveCatmullRomClosed,\n curveCatmullRomOpen,\n curveCatmullRom,\n curveLinear,\n curveLinearClosed,\n curveMonotoneX,\n curveMonotoneY,\n curveNatural,\n curveStep,\n curveStepAfter,\n curveStepBefore,\n select\n} from \"d3\";\nimport memoize from \"lodash-es/memoize.js\";\nimport merge from \"lodash-es/merge.js\";\nvar ZERO_WIDTH_SPACE = \"\\u200B\";\nvar d3CurveTypes = {\n curveBasis,\n curveBasisClosed,\n curveBasisOpen,\n curveBumpX,\n curveBumpY,\n curveBundle,\n curveCardinalClosed,\n curveCardinalOpen,\n curveCardinal,\n curveCatmullRomClosed,\n curveCatmullRomOpen,\n curveCatmullRom,\n curveLinear,\n curveLinearClosed,\n curveMonotoneX,\n curveMonotoneY,\n curveNatural,\n curveStep,\n curveStepAfter,\n curveStepBefore\n};\nvar directiveWithoutOpen = /\\s*(?:(\\w+)(?=:):|(\\w+))\\s*(?:(\\w+)|((?:(?!}%{2}).|\\r?\\n)*))?\\s*(?:}%{2})?/gi;\nvar detectInit = /* @__PURE__ */ __name(function(text, config) {\n const inits = detectDirective(text, /(?:init\\b)|(?:initialize\\b)/);\n let results = {};\n if (Array.isArray(inits)) {\n const args = inits.map((init) => init.args);\n sanitizeDirective(args);\n results = assignWithDepth_default(results, [...args]);\n } else {\n results = inits.args;\n }\n if (!results) {\n return;\n }\n let type = detectType(text, config);\n const prop = \"config\";\n if (results[prop] !== void 0) {\n if (type === \"flowchart-v2\") {\n type = \"flowchart\";\n }\n results[type] = results[prop];\n delete results[prop];\n }\n return results;\n}, \"detectInit\");\nvar detectDirective = /* @__PURE__ */ __name(function(text, type = null) {\n try {\n const commentWithoutDirectives = new RegExp(\n `[%]{2}(?![{]${directiveWithoutOpen.source})(?=[}][%]{2}).*\n`,\n \"ig\"\n );\n text = text.trim().replace(commentWithoutDirectives, \"\").replace(/'/gm, '\"');\n log.debug(\n `Detecting diagram directive${type !== null ? \" type:\" + type : \"\"} based on the text:${text}`\n );\n let match;\n const result = [];\n while ((match = directiveRegex.exec(text)) !== null) {\n if (match.index === directiveRegex.lastIndex) {\n directiveRegex.lastIndex++;\n }\n if (match && !type || type && match[1]?.match(type) || type && match[2]?.match(type)) {\n const type2 = match[1] ? match[1] : match[2];\n const args = match[3] ? match[3].trim() : match[4] ? JSON.parse(match[4].trim()) : null;\n result.push({ type: type2, args });\n }\n }\n if (result.length === 0) {\n return { type: text, args: null };\n }\n return result.length === 1 ? result[0] : result;\n } catch (error) {\n log.error(\n `ERROR: ${error.message} - Unable to parse directive type: '${type}' based on the text: '${text}'`\n );\n return { type: void 0, args: null };\n }\n}, \"detectDirective\");\nvar removeDirectives = /* @__PURE__ */ __name(function(text) {\n return text.replace(directiveRegex, \"\");\n}, \"removeDirectives\");\nvar isSubstringInArray = /* @__PURE__ */ __name(function(str, arr) {\n for (const [i, element] of arr.entries()) {\n if (element.match(str)) {\n return i;\n }\n }\n return -1;\n}, \"isSubstringInArray\");\nfunction interpolateToCurve(interpolate, defaultCurve) {\n if (!interpolate) {\n return defaultCurve;\n }\n const curveName = `curve${interpolate.charAt(0).toUpperCase() + interpolate.slice(1)}`;\n return d3CurveTypes[curveName] ?? defaultCurve;\n}\n__name(interpolateToCurve, \"interpolateToCurve\");\nfunction formatUrl(linkStr, config) {\n const url = linkStr.trim();\n if (!url) {\n return void 0;\n }\n if (config.securityLevel !== \"loose\") {\n return sanitizeUrl(url);\n }\n return url;\n}\n__name(formatUrl, \"formatUrl\");\nvar runFunc = /* @__PURE__ */ __name((functionName, ...params) => {\n const arrPaths = functionName.split(\".\");\n const len = arrPaths.length - 1;\n const fnName = arrPaths[len];\n let obj = window;\n for (let i = 0; i < len; i++) {\n obj = obj[arrPaths[i]];\n if (!obj) {\n log.error(`Function name: ${functionName} not found in window`);\n return;\n }\n }\n obj[fnName](...params);\n}, \"runFunc\");\nfunction distance(p1, p2) {\n if (!p1 || !p2) {\n return 0;\n }\n return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));\n}\n__name(distance, \"distance\");\nfunction traverseEdge(points) {\n let prevPoint;\n let totalDistance = 0;\n points.forEach((point) => {\n totalDistance += distance(point, prevPoint);\n prevPoint = point;\n });\n const remainingDistance = totalDistance / 2;\n return calculatePoint(points, remainingDistance);\n}\n__name(traverseEdge, \"traverseEdge\");\nfunction calcLabelPosition(points) {\n if (points.length === 1) {\n return points[0];\n }\n return traverseEdge(points);\n}\n__name(calcLabelPosition, \"calcLabelPosition\");\nvar roundNumber = /* @__PURE__ */ __name((num, precision = 2) => {\n const factor = Math.pow(10, precision);\n return Math.round(num * factor) / factor;\n}, \"roundNumber\");\nvar calculatePoint = /* @__PURE__ */ __name((points, distanceToTraverse) => {\n let prevPoint = void 0;\n let remainingDistance = distanceToTraverse;\n for (const point of points) {\n if (prevPoint) {\n const vectorDistance = distance(point, prevPoint);\n if (vectorDistance === 0) {\n return prevPoint;\n }\n if (vectorDistance < remainingDistance) {\n remainingDistance -= vectorDistance;\n } else {\n const distanceRatio = remainingDistance / vectorDistance;\n if (distanceRatio <= 0) {\n return prevPoint;\n }\n if (distanceRatio >= 1) {\n return { x: point.x, y: point.y };\n }\n if (distanceRatio > 0 && distanceRatio < 1) {\n return {\n x: roundNumber((1 - distanceRatio) * prevPoint.x + distanceRatio * point.x, 5),\n y: roundNumber((1 - distanceRatio) * prevPoint.y + distanceRatio * point.y, 5)\n };\n }\n }\n }\n prevPoint = point;\n }\n throw new Error(\"Could not find a suitable point for the given distance\");\n}, \"calculatePoint\");\nvar calcCardinalityPosition = /* @__PURE__ */ __name((isRelationTypePresent, points, initialPosition) => {\n log.info(`our points ${JSON.stringify(points)}`);\n if (points[0] !== initialPosition) {\n points = points.reverse();\n }\n const distanceToCardinalityPoint = 25;\n const center = calculatePoint(points, distanceToCardinalityPoint);\n const d = isRelationTypePresent ? 10 : 5;\n const angle = Math.atan2(points[0].y - center.y, points[0].x - center.x);\n const cardinalityPosition = { x: 0, y: 0 };\n cardinalityPosition.x = Math.sin(angle) * d + (points[0].x + center.x) / 2;\n cardinalityPosition.y = -Math.cos(angle) * d + (points[0].y + center.y) / 2;\n return cardinalityPosition;\n}, \"calcCardinalityPosition\");\nfunction calcTerminalLabelPosition(terminalMarkerSize, position, _points) {\n const points = structuredClone(_points);\n log.info(\"our points\", points);\n if (position !== \"start_left\" && position !== \"start_right\") {\n points.reverse();\n }\n const distanceToCardinalityPoint = 25 + terminalMarkerSize;\n const center = calculatePoint(points, distanceToCardinalityPoint);\n const d = 10 + terminalMarkerSize * 0.5;\n const angle = Math.atan2(points[0].y - center.y, points[0].x - center.x);\n const cardinalityPosition = { x: 0, y: 0 };\n if (position === \"start_left\") {\n cardinalityPosition.x = Math.sin(angle + Math.PI) * d + (points[0].x + center.x) / 2;\n cardinalityPosition.y = -Math.cos(angle + Math.PI) * d + (points[0].y + center.y) / 2;\n } else if (position === \"end_right\") {\n cardinalityPosition.x = Math.sin(angle - Math.PI) * d + (points[0].x + center.x) / 2 - 5;\n cardinalityPosition.y = -Math.cos(angle - Math.PI) * d + (points[0].y + center.y) / 2 - 5;\n } else if (position === \"end_left\") {\n cardinalityPosition.x = Math.sin(angle) * d + (points[0].x + center.x) / 2 - 5;\n cardinalityPosition.y = -Math.cos(angle) * d + (points[0].y + center.y) / 2 - 5;\n } else {\n cardinalityPosition.x = Math.sin(angle) * d + (points[0].x + center.x) / 2;\n cardinalityPosition.y = -Math.cos(angle) * d + (points[0].y + center.y) / 2;\n }\n return cardinalityPosition;\n}\n__name(calcTerminalLabelPosition, \"calcTerminalLabelPosition\");\nfunction getStylesFromArray(arr) {\n let style = \"\";\n let labelStyle = \"\";\n for (const element of arr) {\n if (element !== void 0) {\n if (element.startsWith(\"color:\") || element.startsWith(\"text-align:\")) {\n labelStyle = labelStyle + element + \";\";\n } else {\n style = style + element + \";\";\n }\n }\n }\n return { style, labelStyle };\n}\n__name(getStylesFromArray, \"getStylesFromArray\");\nvar cnt = 0;\nvar generateId = /* @__PURE__ */ __name(() => {\n cnt++;\n return \"id-\" + Math.random().toString(36).substr(2, 12) + \"-\" + cnt;\n}, \"generateId\");\nfunction makeRandomHex(length) {\n let result = \"\";\n const characters = \"0123456789abcdef\";\n const charactersLength = characters.length;\n for (let i = 0; i < length; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n}\n__name(makeRandomHex, \"makeRandomHex\");\nvar random = /* @__PURE__ */ __name((options) => {\n return makeRandomHex(options.length);\n}, \"random\");\nvar getTextObj = /* @__PURE__ */ __name(function() {\n return {\n x: 0,\n y: 0,\n fill: void 0,\n anchor: \"start\",\n style: \"#666\",\n width: 100,\n height: 100,\n textMargin: 0,\n rx: 0,\n ry: 0,\n valign: void 0,\n text: \"\"\n };\n}, \"getTextObj\");\nvar drawSimpleText = /* @__PURE__ */ __name(function(elem, textData) {\n const nText = textData.text.replace(common_default.lineBreakRegex, \" \");\n const [, _fontSizePx] = parseFontSize(textData.fontSize);\n const textElem = elem.append(\"text\");\n textElem.attr(\"x\", textData.x);\n textElem.attr(\"y\", textData.y);\n textElem.style(\"text-anchor\", textData.anchor);\n textElem.style(\"font-family\", textData.fontFamily);\n textElem.style(\"font-size\", _fontSizePx);\n textElem.style(\"font-weight\", textData.fontWeight);\n textElem.attr(\"fill\", textData.fill);\n if (textData.class !== void 0) {\n textElem.attr(\"class\", textData.class);\n }\n const span = textElem.append(\"tspan\");\n span.attr(\"x\", textData.x + textData.textMargin * 2);\n span.attr(\"fill\", textData.fill);\n span.text(nText);\n return textElem;\n}, \"drawSimpleText\");\nvar wrapLabel = memoize(\n (label, maxWidth, config) => {\n if (!label) {\n return label;\n }\n config = Object.assign(\n { fontSize: 12, fontWeight: 400, fontFamily: \"Arial\", joinWith: \"
\" },\n config\n );\n if (common_default.lineBreakRegex.test(label)) {\n return label;\n }\n const words = label.split(\" \").filter(Boolean);\n const completedLines = [];\n let nextLine = \"\";\n words.forEach((word, index) => {\n const wordLength = calculateTextWidth(`${word} `, config);\n const nextLineLength = calculateTextWidth(nextLine, config);\n if (wordLength > maxWidth) {\n const { hyphenatedStrings, remainingWord } = breakString(word, maxWidth, \"-\", config);\n completedLines.push(nextLine, ...hyphenatedStrings);\n nextLine = remainingWord;\n } else if (nextLineLength + wordLength >= maxWidth) {\n completedLines.push(nextLine);\n nextLine = word;\n } else {\n nextLine = [nextLine, word].filter(Boolean).join(\" \");\n }\n const currentWord = index + 1;\n const isLastWord = currentWord === words.length;\n if (isLastWord) {\n completedLines.push(nextLine);\n }\n });\n return completedLines.filter((line) => line !== \"\").join(config.joinWith);\n },\n (label, maxWidth, config) => `${label}${maxWidth}${config.fontSize}${config.fontWeight}${config.fontFamily}${config.joinWith}`\n);\nvar breakString = memoize(\n (word, maxWidth, hyphenCharacter = \"-\", config) => {\n config = Object.assign(\n { fontSize: 12, fontWeight: 400, fontFamily: \"Arial\", margin: 0 },\n config\n );\n const characters = [...word];\n const lines = [];\n let currentLine = \"\";\n characters.forEach((character, index) => {\n const nextLine = `${currentLine}${character}`;\n const lineWidth = calculateTextWidth(nextLine, config);\n if (lineWidth >= maxWidth) {\n const currentCharacter = index + 1;\n const isLastLine = characters.length === currentCharacter;\n const hyphenatedNextLine = `${nextLine}${hyphenCharacter}`;\n lines.push(isLastLine ? nextLine : hyphenatedNextLine);\n currentLine = \"\";\n } else {\n currentLine = nextLine;\n }\n });\n return { hyphenatedStrings: lines, remainingWord: currentLine };\n },\n (word, maxWidth, hyphenCharacter = \"-\", config) => `${word}${maxWidth}${hyphenCharacter}${config.fontSize}${config.fontWeight}${config.fontFamily}`\n);\nfunction calculateTextHeight(text, config) {\n return calculateTextDimensions(text, config).height;\n}\n__name(calculateTextHeight, \"calculateTextHeight\");\nfunction calculateTextWidth(text, config) {\n return calculateTextDimensions(text, config).width;\n}\n__name(calculateTextWidth, \"calculateTextWidth\");\nvar calculateTextDimensions = memoize(\n (text, config) => {\n const { fontSize = 12, fontFamily = \"Arial\", fontWeight = 400 } = config;\n if (!text) {\n return { width: 0, height: 0 };\n }\n const [, _fontSizePx] = parseFontSize(fontSize);\n const fontFamilies = [\"sans-serif\", fontFamily];\n const lines = text.split(common_default.lineBreakRegex);\n const dims = [];\n const body = select(\"body\");\n if (!body.remove) {\n return { width: 0, height: 0, lineHeight: 0 };\n }\n const g = body.append(\"svg\");\n for (const fontFamily2 of fontFamilies) {\n let cHeight = 0;\n const dim = { width: 0, height: 0, lineHeight: 0 };\n for (const line of lines) {\n const textObj = getTextObj();\n textObj.text = line || ZERO_WIDTH_SPACE;\n const textElem = drawSimpleText(g, textObj).style(\"font-size\", _fontSizePx).style(\"font-weight\", fontWeight).style(\"font-family\", fontFamily2);\n const bBox = (textElem._groups || textElem)[0][0].getBBox();\n if (bBox.width === 0 && bBox.height === 0) {\n throw new Error(\"svg element not in render tree\");\n }\n dim.width = Math.round(Math.max(dim.width, bBox.width));\n cHeight = Math.round(bBox.height);\n dim.height += cHeight;\n dim.lineHeight = Math.round(Math.max(dim.lineHeight, cHeight));\n }\n dims.push(dim);\n }\n g.remove();\n const index = isNaN(dims[1].height) || isNaN(dims[1].width) || isNaN(dims[1].lineHeight) || dims[0].height > dims[1].height && dims[0].width > dims[1].width && dims[0].lineHeight > dims[1].lineHeight ? 0 : 1;\n return dims[index];\n },\n (text, config) => `${text}${config.fontSize}${config.fontWeight}${config.fontFamily}`\n);\nvar InitIDGenerator = class {\n constructor(deterministic = false, seed) {\n this.count = 0;\n this.count = seed ? seed.length : 0;\n this.next = deterministic ? () => this.count++ : () => Date.now();\n }\n static {\n __name(this, \"InitIDGenerator\");\n }\n};\nvar decoder;\nvar entityDecode = /* @__PURE__ */ __name(function(html) {\n decoder = decoder || document.createElement(\"div\");\n html = escape(html).replace(/%26/g, \"&\").replace(/%23/g, \"#\").replace(/%3B/g, \";\");\n decoder.innerHTML = html;\n return unescape(decoder.textContent);\n}, \"entityDecode\");\nfunction isDetailedError(error) {\n return \"str\" in error;\n}\n__name(isDetailedError, \"isDetailedError\");\nvar insertTitle = /* @__PURE__ */ __name((parent, cssClass, titleTopMargin, title) => {\n if (!title) {\n return;\n }\n const bounds = parent.node()?.getBBox();\n if (!bounds) {\n return;\n }\n parent.append(\"text\").text(title).attr(\"text-anchor\", \"middle\").attr(\"x\", bounds.x + bounds.width / 2).attr(\"y\", -titleTopMargin).attr(\"class\", cssClass);\n}, \"insertTitle\");\nvar parseFontSize = /* @__PURE__ */ __name((fontSize) => {\n if (typeof fontSize === \"number\") {\n return [fontSize, fontSize + \"px\"];\n }\n const fontSizeNumber = parseInt(fontSize ?? \"\", 10);\n if (Number.isNaN(fontSizeNumber)) {\n return [void 0, void 0];\n } else if (fontSize === String(fontSizeNumber)) {\n return [fontSizeNumber, fontSize + \"px\"];\n } else {\n return [fontSizeNumber, fontSize];\n }\n}, \"parseFontSize\");\nfunction cleanAndMerge(defaultData, data) {\n return merge({}, defaultData, data);\n}\n__name(cleanAndMerge, \"cleanAndMerge\");\nvar utils_default = {\n assignWithDepth: assignWithDepth_default,\n wrapLabel,\n calculateTextHeight,\n calculateTextWidth,\n calculateTextDimensions,\n cleanAndMerge,\n detectInit,\n detectDirective,\n isSubstringInArray,\n interpolateToCurve,\n calcLabelPosition,\n calcCardinalityPosition,\n calcTerminalLabelPosition,\n formatUrl,\n getStylesFromArray,\n generateId,\n random,\n runFunc,\n entityDecode,\n insertTitle,\n isLabelCoordinateInPath,\n parseFontSize,\n InitIDGenerator\n};\nvar encodeEntities = /* @__PURE__ */ __name(function(text) {\n let txt = text;\n txt = txt.replace(/style.*:\\S*#.*;/g, function(s) {\n return s.substring(0, s.length - 1);\n });\n txt = txt.replace(/classDef.*:\\S*#.*;/g, function(s) {\n return s.substring(0, s.length - 1);\n });\n txt = txt.replace(/#\\w+;/g, function(s) {\n const innerTxt = s.substring(1, s.length - 1);\n const isInt = /^\\+?\\d+$/.test(innerTxt);\n if (isInt) {\n return \"\\uFB02\\xB0\\xB0\" + innerTxt + \"\\xB6\\xDF\";\n } else {\n return \"\\uFB02\\xB0\" + innerTxt + \"\\xB6\\xDF\";\n }\n });\n return txt;\n}, \"encodeEntities\");\nvar decodeEntities = /* @__PURE__ */ __name(function(text) {\n return text.replace(/\uFB02\u00B0\u00B0/g, \"&#\").replace(/\uFB02\u00B0/g, \"&\").replace(/\u00B6\u00DF/g, \";\");\n}, \"decodeEntities\");\nvar getEdgeId = /* @__PURE__ */ __name((from, to, {\n counter = 0,\n prefix,\n suffix\n}, id) => {\n if (id) {\n return id;\n }\n return `${prefix ? `${prefix}_` : \"\"}${from}_${to}_${counter}${suffix ? `_${suffix}` : \"\"}`;\n}, \"getEdgeId\");\nfunction handleUndefinedAttr(attrValue) {\n return attrValue ?? null;\n}\n__name(handleUndefinedAttr, \"handleUndefinedAttr\");\nfunction isLabelCoordinateInPath(point, dAttr) {\n const roundedX = Math.round(point.x);\n const roundedY = Math.round(point.y);\n const sanitizedD = dAttr.replace(\n /(\\d+\\.\\d+)/g,\n (match) => Math.round(parseFloat(match)).toString()\n );\n return sanitizedD.includes(roundedX.toString()) || sanitizedD.includes(roundedY.toString());\n}\n__name(isLabelCoordinateInPath, \"isLabelCoordinateInPath\");\n\nexport {\n ZERO_WIDTH_SPACE,\n removeDirectives,\n interpolateToCurve,\n getStylesFromArray,\n generateId,\n random,\n wrapLabel,\n calculateTextHeight,\n calculateTextWidth,\n isDetailedError,\n parseFontSize,\n cleanAndMerge,\n utils_default,\n encodeEntities,\n decodeEntities,\n getEdgeId,\n handle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en_default", "bumpX", "bumpY", "bundle_default", "cardinalClosed_default", "cardinalOpen_default", "cardinal_default", "catmullRomClosed_default", "catmullRomOpen_default", "catmullRom_default", "linear_default", "linearClosed_default", "monotoneX", "monotoneY", "natural_default", "step_default", "stepAfter", "stepBefore", "directiveWithoutOpen", "detectInit", "__name", "text", "config", "inits", "detectDirective", "results", "args", "init", "sanitizeDirective", "assignWithDepth_default", "type", "detectType", "prop", "commentWithoutDirectives", "log", "match", "result", "directiveRegex", "type2", "error", "removeDirectives", "isSubstringInArray", "str", "arr", "i", "element", "interpolateToCurve", "interpolate", "defaultCurve", "curveName", "formatUrl", "linkStr", "url", "runFunc", "functionName", "params", "arrPaths", "len", "fnName", "obj", "distance", "p1", "p2", "traverseEdge", "points", "prevPoint", "totalDistance", "point", "remainingDistance", "calculatePoint", "calcLabelPosition", "roundNumber", "num", "precision", "factor", "distanceToTraverse", "vectorDistance", "distanceRatio", "calcCardinalityPosition", "isRelationTypePresent", "initialPosition", "center", "d", "angle", "cardinalityPosition", "calcTerminalLabelPosition", "terminalMarkerSize", "position", "_points", "distanceToCardinalityPoint", "getStylesFromArray", "style", "labelStyle", "cnt", "generateId", "makeRandomHex", "length", "characters", "charactersLength", "random", "options", "getTextObj", "drawSimpleText", "elem", "textData", "nText", "common_default", "_fontSizePx", "parseFontSize", "textElem", "span", "wrapLabel", "memoize_default", "label", "maxWidth", "words", "completedLines", "nextLine", "word", "index", "wordLength", "calculateTextWidth", "nextLineLength", "hyphenatedStrings", "remainingWord", "breakString", "line", "hyphenCharacter", "lines", "currentLine", "character", "currentCharacter", "isLastLine", "hyphenatedNextLine", "calculateTextHeight", "calculateTextDimensions", "fontSize", "fontFamily", "fontWeight", "fontFamilies", "dims", "body", "select_default", "g", "fontFamily2", "cHeight", "dim", "textObj", "bBox", "InitIDGenerator", "deterministic", "seed", "decoder", "entityDecode", "html", "isDetailedError", "insertTitle", "parent", "cssClass", "titleTopMargin", "title", "bounds", "fontSizeNumber", "cleanAndMerge", "defaultData", "data", "merge_default", "utils_default", "isLabelCoordinateInPath", "encodeEntities", "txt", "s", "innerTxt", "decodeEntities", "getEdgeId", "from", "to", "counter", "prefix", "suffix", "id", "handleUndefinedAttr", "attrValue", "dAttr", "roundedX", "roundedY", "sanitizedD"] +} diff --git a/docs/website/public/chunk-R5JLOOQ4.min.js b/docs/website/public/chunk-R5JLOOQ4.min.js new file mode 100644 index 000000000..6c08e694c --- /dev/null +++ b/docs/website/public/chunk-R5JLOOQ4.min.js @@ -0,0 +1,15 @@ +import{a as br,b as hr,c as M}from"./chunk-PTL4EUOE.min.js";import{A as ut,B as O,C as ar,D as nr,E as C,F as D,G as st,H as W,I as _,J as cr,K as lt,L as F,M as R,N as dt,P as xt,Q as q,R as L,S as gt,a as tt,b as E,c as z,d as P,h as sr,j as et,k as ot,l as G,m as lr,n as dr,o as ft,p as zr,q as xr,r as at,s as nt,u as it,v as mt,w as pt,x as S,y as gr,z as u}from"./chunk-E5F23VE2.min.js";function no(r,t){for(var e=-1,o=r==null?0:r.length;++e2?t[2]:void 0;for(f&&L(t[0],t[1],f)&&(o=1);++ei))return!1;var p=a.get(r),s=a.get(t);if(p&&s)return p==t&&s==r;var l=-1,d=!0,w=e&Xf?new Q:void 0;for(a.set(r,t),a.set(t,r);++lt}var se=xn;function gn(r){return r&&r.length?tr(r,R,se):void 0}var cn=gn;function bn(r,t,e,o){if(!P(r))return r;t=K(t,r);for(var f=-1,a=t.length,n=a-1,i=r;i!=null&&++f0&&e(i)?t>1?ce(i,t-1,e,o,f):$(f,i):o||(f[f.length]=i)}return f}var N=ce;function On(r){var t=r==null?0:r.length;return t?N(r,1):[]}var Xr=On;function In(r){return xt(dt(r,void 0,Xr),r+"")}var be=In;var vn=be(function(r,t){return r==null?{}:de(r,t)}),Sn=vn;function Tn(r,t,e,o){var f=-1,a=r==null?0:r.length;for(o&&a&&(e=r[++f]);++f-1}var qr=_n;function Fn(r,t,e){for(var o=-1,f=r==null?0:r.length;++o=Dn){var p=t?null:Ie(r);if(p)return V(p);n=!1,f=k,m=new Q}else m=t?[]:i;r:for(;++of?0:f+t),e=e>f?f:e,e<0&&(e+=f),f=t>e?0:e-t>>>0,t>>>=0;for(var a=Array(f);++o=Ti&&(a=k,n=!1,t=new Q(t));r:for(;++f-1?f[a?t[n]:n]:void 0}}var Be=Ui;var Di=Math.max;function Gi(r,t,e){var o=r==null?0:r.length;if(!o)return-1;var f=e==null?0:U(e);return f<0&&(f=Di(o+f,0)),Wr(r,x(t,3),f)}var Ne=Gi;var Wi=Be(Ne),qi=Wi;function Ki(r){return r&&r.length?r[0]:void 0}var Ue=Ki;function ji(r,t){return N($r(r,t),1)}var Hi=ji;function zi(r,t){return r==null?r:dr(r,X(t),F)}var Yi=zi;function Zi(r,t){return r&&J(r,X(t))}var $i=Zi;var Ji=Object.prototype,Xi=Ji.hasOwnProperty,Qi=Me(function(r,t,e){Xi.call(r,e)?r[e].push(t):lr(r,e,[t])}),ki=Qi;var Vi=Object.prototype,rm=Vi.hasOwnProperty;function tm(r,t){return r!=null&&rm.call(r,t)}var De=tm;function em(r,t){return r!=null&&Br(r,t,De)}var om=em;var fm="[object String]";function am(r){return typeof r=="string"||!u(r)&&S(r)&&z(r)==fm}var mr=am;var nm=Math.max;function im(r,t,e,o){r=O(r)?r:Jr(r),e=e&&!o?U(e):0;var f=r.length;return e<0&&(e=nm(f+e,0)),mr(r)?e<=f&&r.indexOf(t,e)>-1:!!f&&er(r,t,e)>-1}var mm=im;var pm=Math.max;function um(r,t,e){var o=r==null?0:r.length;if(!o)return-1;var f=e==null?0:U(e);return f<0&&(f=pm(o+f,0)),er(r,t,f)}var sm=um;var lm="[object RegExp]";function dm(r){return S(r)&&z(r)==lm}var Ge=dm;var We=D&&D.isRegExp,xm=We?C(We):Ge,gm=xm;function cm(r,t){return rt||a&&n&&m&&!i&&!p||o&&n&&m||!e&&m||!f)return 1;if(!o&&!a&&!p&&r=i)return m;var p=e[o];return m*(p=="desc"?-1:1)}}return r.index-t.index}var He=Em;function Pm(r,t,e){t.length?t=v(t,function(a){return u(a)?function(n){return j(n,a.length===1?a[0]:a)}:a}):t=[R];var o=-1;t=v(t,C(x));var f=Dr(r,function(a,n,i){var m=v(t,function(p){return p(a)});return{criteria:m,index:++o,value:a}});return Ke(f,function(a,n){return He(a,n,e)})}var ze=Pm;var Rm=Ur("length"),Ye=Rm;var $e="\\ud800-\\udfff",Lm="\\u0300-\\u036f",Mm="\\ufe20-\\ufe2f",Cm="\\u20d0-\\u20ff",_m=Lm+Mm+Cm,Fm="\\ufe0e\\ufe0f",Bm="["+$e+"]",kr="["+_m+"]",Vr="\\ud83c[\\udffb-\\udfff]",Nm="(?:"+kr+"|"+Vr+")",Je="[^"+$e+"]",Xe="(?:\\ud83c[\\udde6-\\uddff]){2}",Qe="[\\ud800-\\udbff][\\udc00-\\udfff]",Um="\\u200d",ke=Nm+"?",Ve="["+Fm+"]?",Dm="(?:"+Um+"(?:"+[Je,Xe,Qe].join("|")+")"+Ve+ke+")*",Gm=Ve+ke+Dm,Wm="(?:"+[Je+kr+"?",kr,Xe,Qe,Bm].join("|")+")",Ze=RegExp(Vr+"(?="+Vr+")|"+Wm+Gm,"g");function qm(r){for(var t=Ze.lastIndex=0;Ze.test(r);)++t;return t}var ro=qm;function Km(r){return Pe(r)?ro(r):Ye(r)}var to=Km;var jm=Math.ceil,Hm=Math.max;function zm(r,t,e,o){for(var f=-1,a=Hm(jm((t-r)/(e||1)),0),n=Array(a);a--;)n[o?a:++f]=r,r+=e;return n}var eo=zm;function Ym(r){return function(t,e,o){return o&&typeof o!="number"&&L(t,e,o)&&(e=o=void 0),t=fr(t),e===void 0?(e=t,t=0):e=fr(e),o=o===void 0?t1&&L(r,t[0],t[1])?t=[]:e>2&&L(t[0],t[1],t[2])&&(t=[t[0]]),ze(r,N(t,1),[])}),ap=fp;function np(r){return r&&r.length?or(r):[]}var ip=np;function mp(r,t){return r&&r.length?or(r,x(t,2)):[]}var _h=mp;var pp=0;function up(r){var t=++pp;return Fr(r)+t}var sp=up;function lp(r,t,e){for(var o=-1,f=r.length,a=t.length,n={};++o + * Build: `lodash modularize exports="es" -o ./` + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + *) +*/ +//# sourceMappingURL=chunk-R5JLOOQ4.min.js.map diff --git a/docs/website/public/chunk-R5JLOOQ4.min.js.map b/docs/website/public/chunk-R5JLOOQ4.min.js.map new file mode 100644 index 000000000..3b14bea8e --- /dev/null +++ b/docs/website/public/chunk-R5JLOOQ4.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/lodash-es/_arrayEach.js", "../../node_modules/lodash-es/keys.js", "../../node_modules/lodash-es/_baseAssign.js", "../../node_modules/lodash-es/_baseAssignIn.js", "../../node_modules/lodash-es/_arrayFilter.js", "../../node_modules/lodash-es/stubArray.js", "../../node_modules/lodash-es/_getSymbols.js", "../../node_modules/lodash-es/_copySymbols.js", "../../node_modules/lodash-es/_arrayPush.js", "../../node_modules/lodash-es/_getSymbolsIn.js", "../../node_modules/lodash-es/_copySymbolsIn.js", "../../node_modules/lodash-es/_baseGetAllKeys.js", "../../node_modules/lodash-es/_getAllKeys.js", "../../node_modules/lodash-es/_getAllKeysIn.js", "../../node_modules/lodash-es/_initCloneArray.js", "../../node_modules/lodash-es/_cloneDataView.js", "../../node_modules/lodash-es/_cloneRegExp.js", "../../node_modules/lodash-es/_cloneSymbol.js", "../../node_modules/lodash-es/_initCloneByTag.js", "../../node_modules/lodash-es/_baseIsMap.js", "../../node_modules/lodash-es/isMap.js", "../../node_modules/lodash-es/_baseIsSet.js", "../../node_modules/lodash-es/isSet.js", "../../node_modules/lodash-es/_baseClone.js", "../../node_modules/lodash-es/clone.js", "../../node_modules/lodash-es/defaults.js", "../../node_modules/lodash-es/last.js", "../../node_modules/lodash-es/_baseForOwn.js", "../../node_modules/lodash-es/_createBaseEach.js", "../../node_modules/lodash-es/_baseEach.js", "../../node_modules/lodash-es/_castFunction.js", "../../node_modules/lodash-es/forEach.js", "../../node_modules/lodash-es/_baseFilter.js", "../../node_modules/lodash-es/_setCacheAdd.js", "../../node_modules/lodash-es/_setCacheHas.js", "../../node_modules/lodash-es/_SetCache.js", "../../node_modules/lodash-es/_arraySome.js", "../../node_modules/lodash-es/_cacheHas.js", "../../node_modules/lodash-es/_equalArrays.js", "../../node_modules/lodash-es/_mapToArray.js", "../../node_modules/lodash-es/_setToArray.js", "../../node_modules/lodash-es/_equalByTag.js", "../../node_modules/lodash-es/_equalObjects.js", "../../node_modules/lodash-es/_baseIsEqualDeep.js", "../../node_modules/lodash-es/_baseIsEqual.js", "../../node_modules/lodash-es/_baseIsMatch.js", "../../node_modules/lodash-es/_isStrictComparable.js", "../../node_modules/lodash-es/_getMatchData.js", "../../node_modules/lodash-es/_matchesStrictComparable.js", "../../node_modules/lodash-es/_baseMatches.js", "../../node_modules/lodash-es/isSymbol.js", "../../node_modules/lodash-es/_isKey.js", "../../node_modules/lodash-es/_memoizeCapped.js", "../../node_modules/lodash-es/_stringToPath.js", "../../node_modules/lodash-es/_arrayMap.js", "../../node_modules/lodash-es/_baseToString.js", "../../node_modules/lodash-es/toString.js", "../../node_modules/lodash-es/_castPath.js", "../../node_modules/lodash-es/_toKey.js", "../../node_modules/lodash-es/_baseGet.js", "../../node_modules/lodash-es/get.js", "../../node_modules/lodash-es/_baseHasIn.js", "../../node_modules/lodash-es/_hasPath.js", "../../node_modules/lodash-es/hasIn.js", "../../node_modules/lodash-es/_baseMatchesProperty.js", "../../node_modules/lodash-es/_baseProperty.js", "../../node_modules/lodash-es/_basePropertyDeep.js", "../../node_modules/lodash-es/property.js", "../../node_modules/lodash-es/_baseIteratee.js", "../../node_modules/lodash-es/filter.js", "../../node_modules/lodash-es/_baseMap.js", "../../node_modules/lodash-es/map.js", "../../node_modules/lodash-es/_baseValues.js", "../../node_modules/lodash-es/values.js", "../../node_modules/lodash-es/isUndefined.js", "../../node_modules/lodash-es/mapValues.js", "../../node_modules/lodash-es/_baseExtremum.js", "../../node_modules/lodash-es/_baseGt.js", "../../node_modules/lodash-es/max.js", "../../node_modules/lodash-es/_baseSet.js", "../../node_modules/lodash-es/_basePickBy.js", "../../node_modules/lodash-es/_basePick.js", "../../node_modules/lodash-es/_isFlattenable.js", "../../node_modules/lodash-es/_baseFlatten.js", "../../node_modules/lodash-es/flatten.js", "../../node_modules/lodash-es/_flatRest.js", "../../node_modules/lodash-es/pick.js", "../../node_modules/lodash-es/_arrayReduce.js", "../../node_modules/lodash-es/_baseReduce.js", "../../node_modules/lodash-es/reduce.js", "../../node_modules/lodash-es/_baseFindIndex.js", "../../node_modules/lodash-es/_baseIsNaN.js", "../../node_modules/lodash-es/_strictIndexOf.js", "../../node_modules/lodash-es/_baseIndexOf.js", "../../node_modules/lodash-es/_arrayIncludes.js", "../../node_modules/lodash-es/_arrayIncludesWith.js", "../../node_modules/lodash-es/noop.js", "../../node_modules/lodash-es/_createSet.js", "../../node_modules/lodash-es/_baseUniq.js", "../../node_modules/lodash-es/union.js", "../../node_modules/lodash-es/_trimmedEndIndex.js", "../../node_modules/lodash-es/_baseTrim.js", "../../node_modules/lodash-es/toNumber.js", "../../node_modules/lodash-es/toFinite.js", "../../node_modules/lodash-es/toInteger.js", "../../node_modules/lodash-es/assign.js", "../../node_modules/lodash-es/_baseSlice.js", "../../node_modules/lodash-es/_hasUnicode.js", "../../node_modules/lodash-es/cloneDeep.js", "../../node_modules/lodash-es/compact.js", "../../node_modules/lodash-es/_arrayAggregator.js", "../../node_modules/lodash-es/_baseAggregator.js", "../../node_modules/lodash-es/_createAggregator.js", "../../node_modules/lodash-es/now.js", "../../node_modules/lodash-es/_baseDifference.js", "../../node_modules/lodash-es/difference.js", "../../node_modules/lodash-es/drop.js", "../../node_modules/lodash-es/dropRight.js", "../../node_modules/lodash-es/_arrayEvery.js", "../../node_modules/lodash-es/_baseEvery.js", "../../node_modules/lodash-es/every.js", "../../node_modules/lodash-es/_createFind.js", "../../node_modules/lodash-es/findIndex.js", "../../node_modules/lodash-es/find.js", "../../node_modules/lodash-es/head.js", "../../node_modules/lodash-es/flatMap.js", "../../node_modules/lodash-es/forIn.js", "../../node_modules/lodash-es/forOwn.js", "../../node_modules/lodash-es/groupBy.js", "../../node_modules/lodash-es/_baseHas.js", "../../node_modules/lodash-es/has.js", "../../node_modules/lodash-es/isString.js", "../../node_modules/lodash-es/includes.js", "../../node_modules/lodash-es/indexOf.js", "../../node_modules/lodash-es/_baseIsRegExp.js", "../../node_modules/lodash-es/isRegExp.js", "../../node_modules/lodash-es/_baseLt.js", "../../node_modules/lodash-es/min.js", "../../node_modules/lodash-es/minBy.js", "../../node_modules/lodash-es/negate.js", "../../node_modules/lodash-es/pickBy.js", "../../node_modules/lodash-es/_baseSortBy.js", "../../node_modules/lodash-es/_compareAscending.js", "../../node_modules/lodash-es/_compareMultiple.js", "../../node_modules/lodash-es/_baseOrderBy.js", "../../node_modules/lodash-es/_asciiSize.js", "../../node_modules/lodash-es/_unicodeSize.js", "../../node_modules/lodash-es/_stringSize.js", "../../node_modules/lodash-es/_baseRange.js", "../../node_modules/lodash-es/_createRange.js", "../../node_modules/lodash-es/range.js", "../../node_modules/lodash-es/reject.js", "../../node_modules/lodash-es/size.js", "../../node_modules/lodash-es/_baseSome.js", "../../node_modules/lodash-es/some.js", "../../node_modules/lodash-es/sortBy.js", "../../node_modules/lodash-es/uniq.js", "../../node_modules/lodash-es/uniqBy.js", "../../node_modules/lodash-es/uniqueId.js", "../../node_modules/lodash-es/_baseZipObject.js", "../../node_modules/lodash-es/zipObject.js"], + "sourcesContent": ["/**\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 */\nfunction 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\nexport default arrayEach;\n", "import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeys from './_baseKeys.js';\nimport isArrayLike from './isArrayLike.js';\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 */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nexport default keys;\n", "import copyObject from './_copyObject.js';\nimport keys from './keys.js';\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 */\nfunction baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n}\n\nexport default baseAssign;\n", "import copyObject from './_copyObject.js';\nimport keysIn from './keysIn.js';\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 */\nfunction baseAssignIn(object, source) {\n return object && copyObject(source, keysIn(source), object);\n}\n\nexport default baseAssignIn;\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 */\nfunction 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\nexport default arrayFilter;\n", "/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n", "import arrayFilter from './_arrayFilter.js';\nimport stubArray from './stubArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\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 */\nvar 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\nexport default getSymbols;\n", "import copyObject from './_copyObject.js';\nimport getSymbols from './_getSymbols.js';\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 */\nfunction copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n}\n\nexport default copySymbols;\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 */\nfunction 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\nexport default arrayPush;\n", "import arrayPush from './_arrayPush.js';\nimport getPrototype from './_getPrototype.js';\nimport getSymbols from './_getSymbols.js';\nimport stubArray from './stubArray.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\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 */\nvar 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\nexport default getSymbolsIn;\n", "import copyObject from './_copyObject.js';\nimport getSymbolsIn from './_getSymbolsIn.js';\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 */\nfunction copySymbolsIn(source, object) {\n return copyObject(source, getSymbolsIn(source), object);\n}\n\nexport default copySymbolsIn;\n", "import arrayPush from './_arrayPush.js';\nimport isArray from './isArray.js';\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 */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nexport default baseGetAllKeys;\n", "import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbols from './_getSymbols.js';\nimport keys from './keys.js';\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 */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nexport default getAllKeys;\n", "import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbolsIn from './_getSymbolsIn.js';\nimport keysIn from './keysIn.js';\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 */\nfunction getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n}\n\nexport default getAllKeysIn;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\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 */\nfunction 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\nexport default initCloneArray;\n", "import cloneArrayBuffer from './_cloneArrayBuffer.js';\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 */\nfunction cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n}\n\nexport default cloneDataView;\n", "/** Used to match `RegExp` flags from their coerced string values. */\nvar reFlags = /\\w*$/;\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 */\nfunction cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n}\n\nexport default cloneRegExp;\n", "import Symbol from './_Symbol.js';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\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 */\nfunction cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n}\n\nexport default cloneSymbol;\n", "import cloneArrayBuffer from './_cloneArrayBuffer.js';\nimport cloneDataView from './_cloneDataView.js';\nimport cloneRegExp from './_cloneRegExp.js';\nimport cloneSymbol from './_cloneSymbol.js';\nimport cloneTypedArray from './_cloneTypedArray.js';\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar 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/**\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 */\nfunction 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\nexport default initCloneByTag;\n", "import getTag from './_getTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]';\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 */\nfunction baseIsMap(value) {\n return isObjectLike(value) && getTag(value) == mapTag;\n}\n\nexport default baseIsMap;\n", "import baseIsMap from './_baseIsMap.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsMap = nodeUtil && nodeUtil.isMap;\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 */\nvar isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\nexport default isMap;\n", "import getTag from './_getTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar setTag = '[object Set]';\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 */\nfunction baseIsSet(value) {\n return isObjectLike(value) && getTag(value) == setTag;\n}\n\nexport default baseIsSet;\n", "import baseIsSet from './_baseIsSet.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsSet = nodeUtil && nodeUtil.isSet;\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 */\nvar isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\nexport default isSet;\n", "import Stack from './_Stack.js';\nimport arrayEach from './_arrayEach.js';\nimport assignValue from './_assignValue.js';\nimport baseAssign from './_baseAssign.js';\nimport baseAssignIn from './_baseAssignIn.js';\nimport cloneBuffer from './_cloneBuffer.js';\nimport copyArray from './_copyArray.js';\nimport copySymbols from './_copySymbols.js';\nimport copySymbolsIn from './_copySymbolsIn.js';\nimport getAllKeys from './_getAllKeys.js';\nimport getAllKeysIn from './_getAllKeysIn.js';\nimport getTag from './_getTag.js';\nimport initCloneArray from './_initCloneArray.js';\nimport initCloneByTag from './_initCloneByTag.js';\nimport initCloneObject from './_initCloneObject.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isMap from './isMap.js';\nimport isObject from './isObject.js';\nimport isSet from './isSet.js';\nimport keys from './keys.js';\nimport keysIn from './keysIn.js';\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n weakMapTag = '[object WeakMap]';\n\nvar 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 identify `toStringTag` values supported by `_.clone`. */\nvar cloneableTags = {};\ncloneableTags[argsTag] = cloneableTags[arrayTag] =\ncloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\ncloneableTags[boolTag] = cloneableTags[dateTag] =\ncloneableTags[float32Tag] = cloneableTags[float64Tag] =\ncloneableTags[int8Tag] = cloneableTags[int16Tag] =\ncloneableTags[int32Tag] = cloneableTags[mapTag] =\ncloneableTags[numberTag] = cloneableTags[objectTag] =\ncloneableTags[regexpTag] = cloneableTags[setTag] =\ncloneableTags[stringTag] = cloneableTags[symbolTag] =\ncloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\ncloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\ncloneableTags[errorTag] = cloneableTags[funcTag] =\ncloneableTags[weakMapTag] = false;\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 */\nfunction 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\nexport default baseClone;\n", "import baseClone from './_baseClone.js';\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_SYMBOLS_FLAG = 4;\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 */\nfunction clone(value) {\n return baseClone(value, CLONE_SYMBOLS_FLAG);\n}\n\nexport default clone;\n", "import baseRest from './_baseRest.js';\nimport eq from './eq.js';\nimport isIterateeCall from './_isIterateeCall.js';\nimport keysIn from './keysIn.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\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 */\nvar 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\nexport default defaults;\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 */\nfunction last(array) {\n var length = array == null ? 0 : array.length;\n return length ? array[length - 1] : undefined;\n}\n\nexport default last;\n", "import baseFor from './_baseFor.js';\nimport keys from './keys.js';\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 */\nfunction baseForOwn(object, iteratee) {\n return object && baseFor(object, iteratee, keys);\n}\n\nexport default baseForOwn;\n", "import isArrayLike from './isArrayLike.js';\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 */\nfunction 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\nexport default createBaseEach;\n", "import baseForOwn from './_baseForOwn.js';\nimport createBaseEach from './_createBaseEach.js';\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 */\nvar baseEach = createBaseEach(baseForOwn);\n\nexport default baseEach;\n", "import identity from './identity.js';\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 */\nfunction castFunction(value) {\n return typeof value == 'function' ? value : identity;\n}\n\nexport default castFunction;\n", "import arrayEach from './_arrayEach.js';\nimport baseEach from './_baseEach.js';\nimport castFunction from './_castFunction.js';\nimport isArray from './isArray.js';\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 */\nfunction forEach(collection, iteratee) {\n var func = isArray(collection) ? arrayEach : baseEach;\n return func(collection, castFunction(iteratee));\n}\n\nexport default forEach;\n", "import baseEach from './_baseEach.js';\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 */\nfunction 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\nexport default baseFilter;\n", "/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\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 */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\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 */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n", "import MapCache from './_MapCache.js';\nimport setCacheAdd from './_setCacheAdd.js';\nimport setCacheHas from './_setCacheHas.js';\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 */\nfunction 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// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nexport default SetCache;\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 */\nfunction 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\nexport default arraySome;\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 */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n", "import SetCache from './_SetCache.js';\nimport arraySome from './_arraySome.js';\nimport cacheHas from './_cacheHas.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\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 */\nfunction 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\nexport default equalArrays;\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 */\nfunction 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\nexport default mapToArray;\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 */\nfunction 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\nexport default setToArray;\n", "import Symbol from './_Symbol.js';\nimport Uint8Array from './_Uint8Array.js';\nimport eq from './eq.js';\nimport equalArrays from './_equalArrays.js';\nimport mapToArray from './_mapToArray.js';\nimport setToArray from './_setToArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\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 */\nfunction 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\nexport default equalByTag;\n", "import getAllKeys from './_getAllKeys.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\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 */\nfunction 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\nexport default equalObjects;\n", "import Stack from './_Stack.js';\nimport equalArrays from './_equalArrays.js';\nimport equalByTag from './_equalByTag.js';\nimport equalObjects from './_equalObjects.js';\nimport getTag from './_getTag.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\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 */\nfunction 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\nexport default baseIsEqualDeep;\n", "import baseIsEqualDeep from './_baseIsEqualDeep.js';\nimport isObjectLike from './isObjectLike.js';\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 */\nfunction 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\nexport default baseIsEqual;\n", "import Stack from './_Stack.js';\nimport baseIsEqual from './_baseIsEqual.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\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 */\nfunction 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\nexport default baseIsMatch;\n", "import isObject from './isObject.js';\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 */\nfunction isStrictComparable(value) {\n return value === value && !isObject(value);\n}\n\nexport default isStrictComparable;\n", "import isStrictComparable from './_isStrictComparable.js';\nimport keys from './keys.js';\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 */\nfunction 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\nexport default getMatchData;\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 */\nfunction 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\nexport default matchesStrictComparable;\n", "import baseIsMatch from './_baseIsMatch.js';\nimport getMatchData from './_getMatchData.js';\nimport matchesStrictComparable from './_matchesStrictComparable.js';\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 */\nfunction 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\nexport default baseMatches;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\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 */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nexport default isSymbol;\n", "import isArray from './isArray.js';\nimport isSymbol from './isSymbol.js';\n\n/** Used to match property names within property paths. */\nvar reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/;\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 */\nfunction 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\nexport default isKey;\n", "import memoize from './memoize.js';\n\n/** Used as the maximum memoize cache size. */\nvar MAX_MEMOIZE_SIZE = 500;\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 */\nfunction 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\nexport default memoizeCapped;\n", "import memoizeCapped from './_memoizeCapped.js';\n\n/** Used to match property names within property paths. */\nvar rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n/** Used to match backslashes in property paths. */\nvar reEscapeChar = /\\\\(\\\\)?/g;\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 */\nvar 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\nexport default stringToPath;\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 */\nfunction 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\nexport default arrayMap;\n", "import Symbol from './_Symbol.js';\nimport arrayMap from './_arrayMap.js';\nimport isArray from './isArray.js';\nimport isSymbol from './isSymbol.js';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\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 */\nfunction 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\nexport default baseToString;\n", "import baseToString from './_baseToString.js';\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 */\nfunction toString(value) {\n return value == null ? '' : baseToString(value);\n}\n\nexport default toString;\n", "import isArray from './isArray.js';\nimport isKey from './_isKey.js';\nimport stringToPath from './_stringToPath.js';\nimport toString from './toString.js';\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 */\nfunction castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n}\n\nexport default castPath;\n", "import isSymbol from './isSymbol.js';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\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 */\nfunction 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\nexport default toKey;\n", "import castPath from './_castPath.js';\nimport toKey from './_toKey.js';\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 */\nfunction 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\nexport default baseGet;\n", "import baseGet from './_baseGet.js';\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 */\nfunction get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n}\n\nexport default get;\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 */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nexport default baseHasIn;\n", "import castPath from './_castPath.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isIndex from './_isIndex.js';\nimport isLength from './isLength.js';\nimport toKey from './_toKey.js';\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 */\nfunction 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\nexport default hasPath;\n", "import baseHasIn from './_baseHasIn.js';\nimport hasPath from './_hasPath.js';\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 */\nfunction hasIn(object, path) {\n return object != null && hasPath(object, path, baseHasIn);\n}\n\nexport default hasIn;\n", "import baseIsEqual from './_baseIsEqual.js';\nimport get from './get.js';\nimport hasIn from './hasIn.js';\nimport isKey from './_isKey.js';\nimport isStrictComparable from './_isStrictComparable.js';\nimport matchesStrictComparable from './_matchesStrictComparable.js';\nimport toKey from './_toKey.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\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 */\nfunction 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\nexport default baseMatchesProperty;\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 */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nexport default baseProperty;\n", "import baseGet from './_baseGet.js';\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 */\nfunction basePropertyDeep(path) {\n return function(object) {\n return baseGet(object, path);\n };\n}\n\nexport default basePropertyDeep;\n", "import baseProperty from './_baseProperty.js';\nimport basePropertyDeep from './_basePropertyDeep.js';\nimport isKey from './_isKey.js';\nimport toKey from './_toKey.js';\n\n/**\n * Creates a function that returns the value at `path` of a given object.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n * @example\n *\n * var objects = [\n * { 'a': { 'b': 2 } },\n * { 'a': { 'b': 1 } }\n * ];\n *\n * _.map(objects, _.property('a.b'));\n * // => [2, 1]\n *\n * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');\n * // => [1, 2]\n */\nfunction property(path) {\n return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);\n}\n\nexport default property;\n", "import baseMatches from './_baseMatches.js';\nimport baseMatchesProperty from './_baseMatchesProperty.js';\nimport identity from './identity.js';\nimport isArray from './isArray.js';\nimport property from './property.js';\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 */\nfunction 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\nexport default baseIteratee;\n", "import arrayFilter from './_arrayFilter.js';\nimport baseFilter from './_baseFilter.js';\nimport baseIteratee from './_baseIteratee.js';\nimport isArray from './isArray.js';\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 */\nfunction filter(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, baseIteratee(predicate, 3));\n}\n\nexport default filter;\n", "import baseEach from './_baseEach.js';\nimport isArrayLike from './isArrayLike.js';\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 */\nfunction 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\nexport default baseMap;\n", "import arrayMap from './_arrayMap.js';\nimport baseIteratee from './_baseIteratee.js';\nimport baseMap from './_baseMap.js';\nimport isArray from './isArray.js';\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 */\nfunction map(collection, iteratee) {\n var func = isArray(collection) ? arrayMap : baseMap;\n return func(collection, baseIteratee(iteratee, 3));\n}\n\nexport default map;\n", "import arrayMap from './_arrayMap.js';\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 */\nfunction baseValues(object, props) {\n return arrayMap(props, function(key) {\n return object[key];\n });\n}\n\nexport default baseValues;\n", "import baseValues from './_baseValues.js';\nimport keys from './keys.js';\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 */\nfunction values(object) {\n return object == null ? [] : baseValues(object, keys(object));\n}\n\nexport default values;\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 */\nfunction isUndefined(value) {\n return value === undefined;\n}\n\nexport default isUndefined;\n", "import baseAssignValue from './_baseAssignValue.js';\nimport baseForOwn from './_baseForOwn.js';\nimport baseIteratee from './_baseIteratee.js';\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 */\nfunction mapValues(object, iteratee) {\n var result = {};\n iteratee = baseIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, key, iteratee(value, key, object));\n });\n return result;\n}\n\nexport default mapValues;\n", "import isSymbol from './isSymbol.js';\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 */\nfunction 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\nexport default baseExtremum;\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 */\nfunction baseGt(value, other) {\n return value > other;\n}\n\nexport default baseGt;\n", "import baseExtremum from './_baseExtremum.js';\nimport baseGt from './_baseGt.js';\nimport identity from './identity.js';\n\n/**\n * Computes the maximum value of `array`. If `array` is empty or falsey,\n * `undefined` is returned.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Math\n * @param {Array} array The array to iterate over.\n * @returns {*} Returns the maximum value.\n * @example\n *\n * _.max([4, 2, 8, 6]);\n * // => 8\n *\n * _.max([]);\n * // => undefined\n */\nfunction max(array) {\n return (array && array.length)\n ? baseExtremum(array, identity, baseGt)\n : undefined;\n}\n\nexport default max;\n", "import assignValue from './_assignValue.js';\nimport castPath from './_castPath.js';\nimport isIndex from './_isIndex.js';\nimport isObject from './isObject.js';\nimport toKey from './_toKey.js';\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 */\nfunction 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\nexport default baseSet;\n", "import baseGet from './_baseGet.js';\nimport baseSet from './_baseSet.js';\nimport castPath from './_castPath.js';\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 */\nfunction 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\nexport default basePickBy;\n", "import basePickBy from './_basePickBy.js';\nimport hasIn from './hasIn.js';\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 */\nfunction basePick(object, paths) {\n return basePickBy(object, paths, function(value, path) {\n return hasIn(object, path);\n });\n}\n\nexport default basePick;\n", "import Symbol from './_Symbol.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\n\n/** Built-in value references. */\nvar spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;\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 */\nfunction isFlattenable(value) {\n return isArray(value) || isArguments(value) ||\n !!(spreadableSymbol && value && value[spreadableSymbol]);\n}\n\nexport default isFlattenable;\n", "import arrayPush from './_arrayPush.js';\nimport isFlattenable from './_isFlattenable.js';\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 */\nfunction 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\nexport default baseFlatten;\n", "import baseFlatten from './_baseFlatten.js';\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 */\nfunction flatten(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, 1) : [];\n}\n\nexport default flatten;\n", "import flatten from './flatten.js';\nimport overRest from './_overRest.js';\nimport setToString from './_setToString.js';\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 */\nfunction flatRest(func) {\n return setToString(overRest(func, undefined, flatten), func + '');\n}\n\nexport default flatRest;\n", "import basePick from './_basePick.js';\nimport flatRest from './_flatRest.js';\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 */\nvar pick = flatRest(function(object, paths) {\n return object == null ? {} : basePick(object, paths);\n});\n\nexport default pick;\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 */\nfunction 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\nexport default arrayReduce;\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 */\nfunction 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\nexport default baseReduce;\n", "import arrayReduce from './_arrayReduce.js';\nimport baseEach from './_baseEach.js';\nimport baseIteratee from './_baseIteratee.js';\nimport baseReduce from './_baseReduce.js';\nimport isArray from './isArray.js';\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 */\nfunction reduce(collection, iteratee, accumulator) {\n var func = isArray(collection) ? arrayReduce : baseReduce,\n initAccum = arguments.length < 3;\n\n return func(collection, baseIteratee(iteratee, 4), accumulator, initAccum, baseEach);\n}\n\nexport default reduce;\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 */\nfunction 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\nexport default baseFindIndex;\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 */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nexport default baseIsNaN;\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 */\nfunction 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\nexport default strictIndexOf;\n", "import baseFindIndex from './_baseFindIndex.js';\nimport baseIsNaN from './_baseIsNaN.js';\nimport strictIndexOf from './_strictIndexOf.js';\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 */\nfunction baseIndexOf(array, value, fromIndex) {\n return value === value\n ? strictIndexOf(array, value, fromIndex)\n : baseFindIndex(array, baseIsNaN, fromIndex);\n}\n\nexport default baseIndexOf;\n", "import baseIndexOf from './_baseIndexOf.js';\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 */\nfunction arrayIncludes(array, value) {\n var length = array == null ? 0 : array.length;\n return !!length && baseIndexOf(array, value, 0) > -1;\n}\n\nexport default arrayIncludes;\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 */\nfunction 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\nexport default arrayIncludesWith;\n", "/**\n * This method returns `undefined`.\n *\n * @static\n * @memberOf _\n * @since 2.3.0\n * @category Util\n * @example\n *\n * _.times(2, _.noop);\n * // => [undefined, undefined]\n */\nfunction noop() {\n // No operation performed.\n}\n\nexport default noop;\n", "import Set from './_Set.js';\nimport noop from './noop.js';\nimport setToArray from './_setToArray.js';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\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 */\nvar createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {\n return new Set(values);\n};\n\nexport default createSet;\n", "import SetCache from './_SetCache.js';\nimport arrayIncludes from './_arrayIncludes.js';\nimport arrayIncludesWith from './_arrayIncludesWith.js';\nimport cacheHas from './_cacheHas.js';\nimport createSet from './_createSet.js';\nimport setToArray from './_setToArray.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\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 */\nfunction 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\nexport default baseUniq;\n", "import baseFlatten from './_baseFlatten.js';\nimport baseRest from './_baseRest.js';\nimport baseUniq from './_baseUniq.js';\nimport isArrayLikeObject from './isArrayLikeObject.js';\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 */\nvar union = baseRest(function(arrays) {\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));\n});\n\nexport default union;\n", "/** Used to match a single whitespace character. */\nvar reWhitespace = /\\s/;\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 */\nfunction trimmedEndIndex(string) {\n var index = string.length;\n\n while (index-- && reWhitespace.test(string.charAt(index))) {}\n return index;\n}\n\nexport default trimmedEndIndex;\n", "import trimmedEndIndex from './_trimmedEndIndex.js';\n\n/** Used to match leading whitespace. */\nvar reTrimStart = /^\\s+/;\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 */\nfunction baseTrim(string) {\n return string\n ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n : string;\n}\n\nexport default baseTrim;\n", "import baseTrim from './_baseTrim.js';\nimport isObject from './isObject.js';\nimport isSymbol from './isSymbol.js';\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\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 */\nfunction 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\nexport default toNumber;\n", "import toNumber from './toNumber.js';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0,\n MAX_INTEGER = 1.7976931348623157e+308;\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 */\nfunction 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\nexport default toFinite;\n", "import toFinite from './toFinite.js';\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 */\nfunction toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n}\n\nexport default toInteger;\n", "import assignValue from './_assignValue.js';\nimport copyObject from './_copyObject.js';\nimport createAssigner from './_createAssigner.js';\nimport isArrayLike from './isArrayLike.js';\nimport isPrototype from './_isPrototype.js';\nimport keys from './keys.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\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 */\nvar 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\nexport default assign;\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 */\nfunction 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\nexport default baseSlice;\n", "/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\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/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\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 */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n", "import baseClone from './_baseClone.js';\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_SYMBOLS_FLAG = 4;\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 */\nfunction cloneDeep(value) {\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n}\n\nexport default cloneDeep;\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 */\nfunction 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\nexport default compact;\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 */\nfunction 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\nexport default arrayAggregator;\n", "import baseEach from './_baseEach.js';\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 */\nfunction 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\nexport default baseAggregator;\n", "import arrayAggregator from './_arrayAggregator.js';\nimport baseAggregator from './_baseAggregator.js';\nimport baseIteratee from './_baseIteratee.js';\nimport isArray from './isArray.js';\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 */\nfunction 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, baseIteratee(iteratee, 2), accumulator);\n };\n}\n\nexport default createAggregator;\n", "import root from './_root.js';\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 */\nvar now = function() {\n return root.Date.now();\n};\n\nexport default now;\n", "import SetCache from './_SetCache.js';\nimport arrayIncludes from './_arrayIncludes.js';\nimport arrayIncludesWith from './_arrayIncludesWith.js';\nimport arrayMap from './_arrayMap.js';\nimport baseUnary from './_baseUnary.js';\nimport cacheHas from './_cacheHas.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\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 */\nfunction 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\nexport default baseDifference;\n", "import baseDifference from './_baseDifference.js';\nimport baseFlatten from './_baseFlatten.js';\nimport baseRest from './_baseRest.js';\nimport isArrayLikeObject from './isArrayLikeObject.js';\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 */\nvar difference = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))\n : [];\n});\n\nexport default difference;\n", "import baseSlice from './_baseSlice.js';\nimport toInteger from './toInteger.js';\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 */\nfunction 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\nexport default drop;\n", "import baseSlice from './_baseSlice.js';\nimport toInteger from './toInteger.js';\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 */\nfunction 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\nexport default dropRight;\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 */\nfunction 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\nexport default arrayEvery;\n", "import baseEach from './_baseEach.js';\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 */\nfunction 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\nexport default baseEvery;\n", "import arrayEvery from './_arrayEvery.js';\nimport baseEvery from './_baseEvery.js';\nimport baseIteratee from './_baseIteratee.js';\nimport isArray from './isArray.js';\nimport isIterateeCall from './_isIterateeCall.js';\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 */\nfunction 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, baseIteratee(predicate, 3));\n}\n\nexport default every;\n", "import baseIteratee from './_baseIteratee.js';\nimport isArrayLike from './isArrayLike.js';\nimport keys from './keys.js';\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 */\nfunction createFind(findIndexFunc) {\n return function(collection, predicate, fromIndex) {\n var iterable = Object(collection);\n if (!isArrayLike(collection)) {\n var iteratee = baseIteratee(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\nexport default createFind;\n", "import baseFindIndex from './_baseFindIndex.js';\nimport baseIteratee from './_baseIteratee.js';\nimport toInteger from './toInteger.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\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 */\nfunction 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, baseIteratee(predicate, 3), index);\n}\n\nexport default findIndex;\n", "import createFind from './_createFind.js';\nimport findIndex from './findIndex.js';\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 */\nvar find = createFind(findIndex);\n\nexport default find;\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 */\nfunction head(array) {\n return (array && array.length) ? array[0] : undefined;\n}\n\nexport default head;\n", "import baseFlatten from './_baseFlatten.js';\nimport map from './map.js';\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 */\nfunction flatMap(collection, iteratee) {\n return baseFlatten(map(collection, iteratee), 1);\n}\n\nexport default flatMap;\n", "import baseFor from './_baseFor.js';\nimport castFunction from './_castFunction.js';\nimport keysIn from './keysIn.js';\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 */\nfunction forIn(object, iteratee) {\n return object == null\n ? object\n : baseFor(object, castFunction(iteratee), keysIn);\n}\n\nexport default forIn;\n", "import baseForOwn from './_baseForOwn.js';\nimport castFunction from './_castFunction.js';\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 */\nfunction forOwn(object, iteratee) {\n return object && baseForOwn(object, castFunction(iteratee));\n}\n\nexport default forOwn;\n", "import baseAssignValue from './_baseAssignValue.js';\nimport createAggregator from './_createAggregator.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\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 */\nvar 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\nexport default groupBy;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\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 */\nfunction baseHas(object, key) {\n return object != null && hasOwnProperty.call(object, key);\n}\n\nexport default baseHas;\n", "import baseHas from './_baseHas.js';\nimport hasPath from './_hasPath.js';\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 */\nfunction has(object, path) {\n return object != null && hasPath(object, path, baseHas);\n}\n\nexport default has;\n", "import baseGetTag from './_baseGetTag.js';\nimport isArray from './isArray.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar stringTag = '[object String]';\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 */\nfunction isString(value) {\n return typeof value == 'string' ||\n (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);\n}\n\nexport default isString;\n", "import baseIndexOf from './_baseIndexOf.js';\nimport isArrayLike from './isArrayLike.js';\nimport isString from './isString.js';\nimport toInteger from './toInteger.js';\nimport values from './values.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\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 */\nfunction 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\nexport default includes;\n", "import baseIndexOf from './_baseIndexOf.js';\nimport toInteger from './toInteger.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\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 */\nfunction 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\nexport default indexOf;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar regexpTag = '[object RegExp]';\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 */\nfunction baseIsRegExp(value) {\n return isObjectLike(value) && baseGetTag(value) == regexpTag;\n}\n\nexport default baseIsRegExp;\n", "import baseIsRegExp from './_baseIsRegExp.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsRegExp = nodeUtil && nodeUtil.isRegExp;\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 */\nvar isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;\n\nexport default isRegExp;\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 */\nfunction baseLt(value, other) {\n return value < other;\n}\n\nexport default baseLt;\n", "import baseExtremum from './_baseExtremum.js';\nimport baseLt from './_baseLt.js';\nimport identity from './identity.js';\n\n/**\n * Computes the minimum value of `array`. If `array` is empty or falsey,\n * `undefined` is returned.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Math\n * @param {Array} array The array to iterate over.\n * @returns {*} Returns the minimum value.\n * @example\n *\n * _.min([4, 2, 8, 6]);\n * // => 2\n *\n * _.min([]);\n * // => undefined\n */\nfunction min(array) {\n return (array && array.length)\n ? baseExtremum(array, identity, baseLt)\n : undefined;\n}\n\nexport default min;\n", "import baseExtremum from './_baseExtremum.js';\nimport baseIteratee from './_baseIteratee.js';\nimport baseLt from './_baseLt.js';\n\n/**\n * This method is like `_.min` except that it accepts `iteratee` which is\n * invoked for each element in `array` to generate the criterion by which\n * the value is ranked. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Math\n * @param {Array} array The array to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {*} Returns the minimum value.\n * @example\n *\n * var objects = [{ 'n': 1 }, { 'n': 2 }];\n *\n * _.minBy(objects, function(o) { return o.n; });\n * // => { 'n': 1 }\n *\n * // The `_.property` iteratee shorthand.\n * _.minBy(objects, 'n');\n * // => { 'n': 1 }\n */\nfunction minBy(array, iteratee) {\n return (array && array.length)\n ? baseExtremum(array, baseIteratee(iteratee, 2), baseLt)\n : undefined;\n}\n\nexport default minBy;\n", "/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\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 */\nfunction 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\nexport default negate;\n", "import arrayMap from './_arrayMap.js';\nimport baseIteratee from './_baseIteratee.js';\nimport basePickBy from './_basePickBy.js';\nimport getAllKeysIn from './_getAllKeysIn.js';\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 */\nfunction pickBy(object, predicate) {\n if (object == null) {\n return {};\n }\n var props = arrayMap(getAllKeysIn(object), function(prop) {\n return [prop];\n });\n predicate = baseIteratee(predicate);\n return basePickBy(object, props, function(value, path) {\n return predicate(value, path[0]);\n });\n}\n\nexport default pickBy;\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 */\nfunction 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\nexport default baseSortBy;\n", "import isSymbol from './isSymbol.js';\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 */\nfunction 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\nexport default compareAscending;\n", "import compareAscending from './_compareAscending.js';\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 */\nfunction 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\nexport default compareMultiple;\n", "import arrayMap from './_arrayMap.js';\nimport baseGet from './_baseGet.js';\nimport baseIteratee from './_baseIteratee.js';\nimport baseMap from './_baseMap.js';\nimport baseSortBy from './_baseSortBy.js';\nimport baseUnary from './_baseUnary.js';\nimport compareMultiple from './_compareMultiple.js';\nimport identity from './identity.js';\nimport isArray from './isArray.js';\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 */\nfunction 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(baseIteratee));\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\nexport default baseOrderBy;\n", "import baseProperty from './_baseProperty.js';\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 */\nvar asciiSize = baseProperty('length');\n\nexport default asciiSize;\n", "/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\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 rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\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 */\nfunction unicodeSize(string) {\n var result = reUnicode.lastIndex = 0;\n while (reUnicode.test(string)) {\n ++result;\n }\n return result;\n}\n\nexport default unicodeSize;\n", "import asciiSize from './_asciiSize.js';\nimport hasUnicode from './_hasUnicode.js';\nimport unicodeSize from './_unicodeSize.js';\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 */\nfunction stringSize(string) {\n return hasUnicode(string)\n ? unicodeSize(string)\n : asciiSize(string);\n}\n\nexport default stringSize;\n", "/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeCeil = Math.ceil,\n nativeMax = Math.max;\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 */\nfunction 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\nexport default baseRange;\n", "import baseRange from './_baseRange.js';\nimport isIterateeCall from './_isIterateeCall.js';\nimport toFinite from './toFinite.js';\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 */\nfunction 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\nexport default createRange;\n", "import createRange from './_createRange.js';\n\n/**\n * Creates an array of numbers (positive and/or negative) progressing from\n * `start` up to, but not including, `end`. A step of `-1` is used if a negative\n * `start` is specified without an `end` or `step`. If `end` is not specified,\n * it's set to `start` with `start` then set to `0`.\n *\n * **Note:** JavaScript follows the IEEE-754 standard for resolving\n * floating-point values which can produce unexpected results.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {number} [start=0] The start of the range.\n * @param {number} end The end of the range.\n * @param {number} [step=1] The value to increment or decrement by.\n * @returns {Array} Returns the range of numbers.\n * @see _.inRange, _.rangeRight\n * @example\n *\n * _.range(4);\n * // => [0, 1, 2, 3]\n *\n * _.range(-4);\n * // => [0, -1, -2, -3]\n *\n * _.range(1, 5);\n * // => [1, 2, 3, 4]\n *\n * _.range(0, 20, 5);\n * // => [0, 5, 10, 15]\n *\n * _.range(0, -4, -1);\n * // => [0, -1, -2, -3]\n *\n * _.range(1, 4, 0);\n * // => [1, 1, 1]\n *\n * _.range(0);\n * // => []\n */\nvar range = createRange();\n\nexport default range;\n", "import arrayFilter from './_arrayFilter.js';\nimport baseFilter from './_baseFilter.js';\nimport baseIteratee from './_baseIteratee.js';\nimport isArray from './isArray.js';\nimport negate from './negate.js';\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 */\nfunction reject(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, negate(baseIteratee(predicate, 3)));\n}\n\nexport default reject;\n", "import baseKeys from './_baseKeys.js';\nimport getTag from './_getTag.js';\nimport isArrayLike from './isArrayLike.js';\nimport isString from './isString.js';\nimport stringSize from './_stringSize.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n setTag = '[object Set]';\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 */\nfunction 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\nexport default size;\n", "import baseEach from './_baseEach.js';\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 */\nfunction 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\nexport default baseSome;\n", "import arraySome from './_arraySome.js';\nimport baseIteratee from './_baseIteratee.js';\nimport baseSome from './_baseSome.js';\nimport isArray from './isArray.js';\nimport isIterateeCall from './_isIterateeCall.js';\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 */\nfunction 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, baseIteratee(predicate, 3));\n}\n\nexport default some;\n", "import baseFlatten from './_baseFlatten.js';\nimport baseOrderBy from './_baseOrderBy.js';\nimport baseRest from './_baseRest.js';\nimport isIterateeCall from './_isIterateeCall.js';\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 */\nvar 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\nexport default sortBy;\n", "import baseUniq from './_baseUniq.js';\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 */\nfunction uniq(array) {\n return (array && array.length) ? baseUniq(array) : [];\n}\n\nexport default uniq;\n", "import baseIteratee from './_baseIteratee.js';\nimport baseUniq from './_baseUniq.js';\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 */\nfunction uniqBy(array, iteratee) {\n return (array && array.length) ? baseUniq(array, baseIteratee(iteratee, 2)) : [];\n}\n\nexport default uniqBy;\n", "import toString from './toString.js';\n\n/** Used to generate unique IDs. */\nvar idCounter = 0;\n\n/**\n * Generates a unique ID. If `prefix` is given, the ID is appended to it.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {string} [prefix=''] The value to prefix the ID with.\n * @returns {string} Returns the unique ID.\n * @example\n *\n * _.uniqueId('contact_');\n * // => 'contact_104'\n *\n * _.uniqueId();\n * // => '105'\n */\nfunction uniqueId(prefix) {\n var id = ++idCounter;\n return toString(prefix) + id;\n}\n\nexport default uniqueId;\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 */\nfunction 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\nexport default baseZipObject;\n", "import assignValue from './_assignValue.js';\nimport baseZipObject from './_baseZipObject.js';\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 */\nfunction zipObject(props, values) {\n return baseZipObject(props || [], values || [], assignValue);\n}\n\nexport default zipObject;\n"], + "mappings": "0YASA,SAASA,GAAUC,EAAOC,EAAU,CAIlC,QAHIC,EAAQ,GACRC,EAASH,GAAS,KAAO,EAAIA,EAAM,OAEhC,EAAEE,EAAQC,GACXF,EAASD,EAAME,CAAK,EAAGA,EAAOF,CAAK,IAAM,IAA7C,CAIF,OAAOA,CACT,CAEA,IAAOI,GAAQL,GCWf,SAASM,GAAKC,EAAQ,CACpB,OAAOC,EAAYD,CAAM,EAAIE,GAAcF,CAAM,EAAIG,GAASH,CAAM,CACtE,CAEA,IAAOI,EAAQL,GCxBf,SAASM,GAAWC,EAAQC,EAAQ,CAClC,OAAOD,GAAUE,EAAWD,EAAQE,EAAKF,CAAM,EAAGD,CAAM,CAC1D,CAEA,IAAOI,GAAQL,GCJf,SAASM,GAAaC,EAAQC,EAAQ,CACpC,OAAOD,GAAUE,EAAWD,EAAQE,EAAOF,CAAM,EAAGD,CAAM,CAC5D,CAEA,IAAOI,GAAQL,GCPf,SAASM,GAAYC,EAAOC,EAAW,CAMrC,QALIC,EAAQ,GACRC,EAASH,GAAS,KAAO,EAAIA,EAAM,OACnCI,EAAW,EACXC,EAAS,CAAC,EAEP,EAAEH,EAAQC,GAAQ,CACvB,IAAIG,EAAQN,EAAME,CAAK,EACnBD,EAAUK,EAAOJ,EAAOF,CAAK,IAC/BK,EAAOD,GAAU,EAAIE,EAEzB,CACA,OAAOD,CACT,CAEA,IAAOE,EAAQR,GCNf,SAASS,IAAY,CACnB,MAAO,CAAC,CACV,CAEA,IAAOC,GAAQD,GClBf,IAAIE,GAAc,OAAO,UAGrBC,GAAuBD,GAAY,qBAGnCE,GAAmB,OAAO,sBAS1BC,GAAcD,GAA+B,SAASE,EAAQ,CAChE,OAAIA,GAAU,KACL,CAAC,GAEVA,EAAS,OAAOA,CAAM,EACfC,EAAYH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AOI,GAASF,CAAM,EAAIC,CAC5B,CAEA,IAAOE,GAAQJ,GClBf,SAASK,GAAcC,EAAOC,EAAQC,EAAY,CAMhD,QALIC,EAAQ,GACRC,EAASJ,EAAM,OACfK,EAAaJ,EAAO,OACpBK,EAAS,CAAC,EAEP,EAAEH,EAAQC,GAAQ,CACvB,IAAIG,EAAQJ,EAAQE,EAAaJ,EAAOE,CAAK,EAAI,OACjDD,EAAWI,EAAQN,EAAMG,CAAK,EAAGI,CAAK,CACxC,CACA,OAAOD,CACT,CAEA,IAAOE,GAAQT,GCHf,SAASU,GAAUC,EAAOC,EAAQ,CAChC,OAAOC,GAAcF,GAAS,CAAC,EAAGC,GAAU,CAAC,EAAGE,CAAW,CAC7D,CAEA,IAAOC,GAAQL", + "names": ["arrayEach", "array", "iteratee", "index", "length", "arrayEach_default", "keys", "object", "isArrayLike_default", "arrayLikeKeys_default", "baseKeys_default", "keys_default", "baseAssign", "object", "source", "copyObject_default", "keys_default", "baseAssign_default", "baseAssignIn", "object", "source", "copyObject_default", "keysIn_default", "baseAssignIn_default", "arrayFilter", "array", "predicate", "index", "length", "resIndex", "result", "value", "arrayFilter_default", "stubArray", "stubArray_default", "objectProto", "propertyIsEnumerable", "nativeGetSymbols", "getSymbols", "object", "arrayFilter_default", "symbol", "stubArray_default", "getSymbols_default", "copySymbols", "source", "object", "copyObject_default", "getSymbols_default", "copySymbols_default", "arrayPush", "array", "values", "index", "length", "offset", "arrayPush_default", "nativeGetSymbols", "getSymbolsIn", "object", "result", "arrayPush_default", "getSymbols_default", "getPrototype_default", "stubArray_default", "getSymbolsIn_default", "copySymbolsIn", "source", "object", "copyObject_default", "getSymbolsIn_default", "copySymbolsIn_default", "baseGetAllKeys", "object", "keysFunc", "symbolsFunc", "result", "isArray_default", "arrayPush_default", "baseGetAllKeys_default", "getAllKeys", "object", "baseGetAllKeys_default", "keys_default", "getSymbols_default", "getAllKeys_default", "getAllKeysIn", "object", "baseGetAllKeys_default", "keysIn_default", "getSymbolsIn_default", "getAllKeysIn_default", "objectProto", "hasOwnProperty", "initCloneArray", "array", "length", "result", "initCloneArray_default", "cloneDataView", "dataView", "isDeep", "buffer", "cloneArrayBuffer_default", "cloneDataView_default", "reFlags", "cloneRegExp", "regexp", "result", "cloneRegExp_default", "symbolProto", "Symbol_default", "symbolValueOf", "cloneSymbol", "symbol", "cloneSymbol_default", "boolTag", "dateTag", "mapTag", "numberTag", "regexpTag", "setTag", "stringTag", "symbolTag", "arrayBufferTag", "dataViewTag", "float32Tag", "float64Tag", "int8Tag", "int16Tag", "int32Tag", "uint8Tag", "uint8ClampedTag", "uint16Tag", "uint32Tag", "initCloneByTag", "object", "tag", "isDeep", "Ctor", "cloneArrayBuffer_default", "cloneDataView_default", "cloneTypedArray_default", "cloneRegExp_default", "cloneSymbol_default", "initCloneByTag_default", "mapTag", "baseIsMap", "value", "isObjectLike_default", "getTag_default", "baseIsMap_default", "nodeIsMap", "nodeUtil_default", "isMap", "baseUnary_default", "baseIsMap_default", "isMap_default", "setTag", "baseIsSet", "value", "isObjectLike_default", "getTag_default", "baseIsSet_default", "nodeIsSet", "nodeUtil_default", "isSet", "baseUnary_default", "baseIsSet_default", "isSet_default", "CLONE_DEEP_FLAG", "CLONE_FLAT_FLAG", "CLONE_SYMBOLS_FLAG", "argsTag", "arrayTag", "boolTag", "dateTag", "errorTag", "funcTag", "genTag", "mapTag", "numberTag", "objectTag", "regexpTag", "setTag", "stringTag", "symbolTag", "weakMapTag", "arrayBufferTag", "dataViewTag", "float32Tag", "float64Tag", "int8Tag", "int16Tag", "int32Tag", "uint8Tag", "uint8ClampedTag", "uint16Tag", "uint32Tag", "cloneableTags", "baseClone", "value", "bitmask", "customizer", "key", "object", "stack", "result", "isDeep", "isFlat", "isFull", "isObject_default", "isArr", "isArray_default", "initCloneArray_default", "copyArray_default", "tag", "getTag_default", "isFunc", "isBuffer_default", "cloneBuffer_default", "initCloneObject_default", "copySymbolsIn_default", "baseAssignIn_default", "copySymbols_default", "baseAssign_default", "initCloneByTag_default", "Stack_default", "stacked", "isSet_default", "subValue", "isMap_default", "keysFunc", "getAllKeysIn_default", "getAllKeys_default", "keysIn_default", "keys_default", "props", "arrayEach_default", "assignValue_default", "baseClone_default", "CLONE_SYMBOLS_FLAG", "clone", "value", "baseClone_default", "clone_default", "objectProto", "hasOwnProperty", "defaults", "baseRest_default", "object", "sources", "index", "length", "guard", "isIterateeCall_default", "source", "props", "keysIn_default", "propsIndex", "propsLength", "key", "value", "eq_default", "defaults_default", "last", "array", "length", "last_default", "baseForOwn", "object", "iteratee", "baseFor_default", "keys_default", "baseForOwn_default", "createBaseEach", "eachFunc", "fromRight", "collection", "iteratee", "isArrayLike_default", "length", "index", "iterable", "createBaseEach_default", "baseEach", "createBaseEach_default", "baseForOwn_default", "baseEach_default", "castFunction", "value", "identity_default", "castFunction_default", "forEach", "collection", "iteratee", "func", "isArray_default", "arrayEach_default", "baseEach_default", "castFunction_default", "forEach_default", "baseFilter", "collection", "predicate", "result", "baseEach_default", "value", "index", "baseFilter_default", "HASH_UNDEFINED", "setCacheAdd", "value", "setCacheAdd_default", "setCacheHas", "value", "setCacheHas_default", "SetCache", "values", "index", "length", "MapCache_default", "setCacheAdd_default", "setCacheHas_default", "SetCache_default", "arraySome", "array", "predicate", "index", "length", "arraySome_default", "cacheHas", "cache", "key", "cacheHas_default", "COMPARE_PARTIAL_FLAG", "COMPARE_UNORDERED_FLAG", "equalArrays", "array", "other", "bitmask", "customizer", "equalFunc", "stack", "isPartial", "arrLength", "othLength", "arrStacked", "othStacked", "index", "result", "seen", "SetCache_default", "arrValue", "othValue", "compared", "arraySome_default", "othIndex", "cacheHas_default", "equalArrays_default", "mapToArray", "map", "index", "result", "value", "key", "mapToArray_default", "setToArray", "set", "index", "result", "value", "setToArray_default", "COMPARE_PARTIAL_FLAG", "COMPARE_UNORDERED_FLAG", "boolTag", "dateTag", "errorTag", "mapTag", "numberTag", "regexpTag", "setTag", "stringTag", "symbolTag", "arrayBufferTag", "dataViewTag", "symbolProto", "Symbol_default", "symbolValueOf", "equalByTag", "object", "other", "tag", "bitmask", "customizer", "equalFunc", "stack", "Uint8Array_default", "eq_default", "convert", "mapToArray_default", "isPartial", "setToArray_default", "stacked", "result", "equalArrays_default", "equalByTag_default", "COMPARE_PARTIAL_FLAG", "objectProto", "hasOwnProperty", "equalObjects", "object", "other", "bitmask", "customizer", "equalFunc", "stack", "isPartial", "objProps", "getAllKeys_default", "objLength", "othProps", "othLength", "index", "key", "objStacked", "othStacked", "result", "skipCtor", "objValue", "othValue", "compared", "objCtor", "othCtor", "equalObjects_default", "COMPARE_PARTIAL_FLAG", "argsTag", "arrayTag", "objectTag", "objectProto", "hasOwnProperty", "baseIsEqualDeep", "object", "other", "bitmask", "customizer", "equalFunc", "stack", "objIsArr", "isArray_default", "othIsArr", "objTag", "getTag_default", "othTag", "objIsObj", "othIsObj", "isSameTag", "isBuffer_default", "Stack_default", "isTypedArray_default", "equalArrays_default", "equalByTag_default", "objIsWrapped", "othIsWrapped", "objUnwrapped", "othUnwrapped", "equalObjects_default", "baseIsEqualDeep_default", "baseIsEqual", "value", "other", "bitmask", "customizer", "stack", "isObjectLike_default", "baseIsEqualDeep_default", "baseIsEqual_default", "COMPARE_PARTIAL_FLAG", "COMPARE_UNORDERED_FLAG", "baseIsMatch", "object", "source", "matchData", "customizer", "index", "length", "noCustomizer", "data", "key", "objValue", "srcValue", "stack", "Stack_default", "result", "baseIsEqual_default", "baseIsMatch_default", "isStrictComparable", "value", "isObject_default", "isStrictComparable_default", "getMatchData", "object", "result", "keys_default", "length", "key", "value", "isStrictComparable_default", "getMatchData_default", "matchesStrictComparable", "key", "srcValue", "object", "matchesStrictComparable_default", "baseMatches", "source", "matchData", "getMatchData_default", "matchesStrictComparable_default", "object", "baseIsMatch_default", "baseMatches_default", "symbolTag", "isSymbol", "value", "isObjectLike_default", "baseGetTag_default", "isSymbol_default", "reIsDeepProp", "reIsPlainProp", "isKey", "value", "object", "isArray_default", "type", "isSymbol_default", "isKey_default", "MAX_MEMOIZE_SIZE", "memoizeCapped", "func", "result", "memoize_default", "key", "cache", "memoizeCapped_default", "rePropName", "reEscapeChar", "stringToPath", "memoizeCapped_default", "string", "result", "match", "number", "quote", "subString", "stringToPath_default", "arrayMap", "array", "iteratee", "index", "length", "result", "arrayMap_default", "INFINITY", "symbolProto", "Symbol_default", "symbolToString", "baseToString", "value", "isArray_default", "arrayMap_default", "isSymbol_default", "result", "baseToString_default", "toString", "value", "baseToString_default", "toString_default", "castPath", "value", "object", "isArray_default", "isKey_default", "stringToPath_default", "toString_default", "castPath_default", "INFINITY", "toKey", "value", "isSymbol_default", "result", "toKey_default", "baseGet", "object", "path", "castPath_default", "index", "length", "toKey_default", "baseGet_default", "get", "object", "path", "defaultValue", "result", "baseGet_default", "get_default", "baseHasIn", "object", "key", "baseHasIn_default", "hasPath", "object", "path", "hasFunc", "castPath_default", "index", "length", "result", "key", "toKey_default", "isLength_default", "isIndex_default", "isArray_default", "isArguments_default", "hasPath_default", "hasIn", "object", "path", "hasPath_default", "baseHasIn_default", "hasIn_default", "COMPARE_PARTIAL_FLAG", "COMPARE_UNORDERED_FLAG", "baseMatchesProperty", "path", "srcValue", "isKey_default", "isStrictComparable_default", "matchesStrictComparable_default", "toKey_default", "object", "objValue", "get_default", "hasIn_default", "baseIsEqual_default", "baseMatchesProperty_default", "baseProperty", "key", "object", "baseProperty_default", "basePropertyDeep", "path", "object", "baseGet_default", "basePropertyDeep_default", "property", "path", "isKey_default", "baseProperty_default", "toKey_default", "basePropertyDeep_default", "property_default", "baseIteratee", "value", "identity_default", "isArray_default", "baseMatchesProperty_default", "baseMatches_default", "property_default", "baseIteratee_default", "filter", "collection", "predicate", "func", "isArray_default", "arrayFilter_default", "baseFilter_default", "baseIteratee_default", "filter_default", "baseMap", "collection", "iteratee", "index", "result", "isArrayLike_default", "baseEach_default", "value", "key", "baseMap_default", "map", "collection", "iteratee", "func", "isArray_default", "arrayMap_default", "baseMap_default", "baseIteratee_default", "map_default", "baseValues", "object", "props", "arrayMap_default", "key", "baseValues_default", "values", "object", "baseValues_default", "keys_default", "values_default", "isUndefined", "value", "isUndefined_default", "mapValues", "object", "iteratee", "result", "baseIteratee_default", "baseForOwn_default", "value", "key", "baseAssignValue_default", "mapValues_default", "baseExtremum", "array", "iteratee", "comparator", "index", "length", "value", "current", "computed", "isSymbol_default", "result", "baseExtremum_default", "baseGt", "value", "other", "baseGt_default", "max", "array", "baseExtremum_default", "identity_default", "baseGt_default", "max_default", "baseSet", "object", "path", "value", "customizer", "isObject_default", "castPath_default", "index", "length", "lastIndex", "nested", "key", "toKey_default", "newValue", "objValue", "isIndex_default", "assignValue_default", "baseSet_default", "basePickBy", "object", "paths", "predicate", "index", "length", "result", "path", "value", "baseGet_default", "baseSet_default", "castPath_default", "basePickBy_default", "basePick", "object", "paths", "basePickBy_default", "value", "path", "hasIn_default", "basePick_default", "spreadableSymbol", "Symbol_default", "isFlattenable", "value", "isArray_default", "isArguments_default", "isFlattenable_default", "baseFlatten", "array", "depth", "predicate", "isStrict", "result", "index", "length", "isFlattenable_default", "value", "arrayPush_default", "baseFlatten_default", "flatten", "array", "length", "baseFlatten_default", "flatten_default", "flatRest", "func", "setToString_default", "overRest_default", "flatten_default", "flatRest_default", "pick", "flatRest_default", "object", "paths", "basePick_default", "pick_default", "arrayReduce", "array", "iteratee", "accumulator", "initAccum", "index", "length", "arrayReduce_default", "baseReduce", "collection", "iteratee", "accumulator", "initAccum", "eachFunc", "value", "index", "baseReduce_default", "reduce", "collection", "iteratee", "accumulator", "func", "isArray_default", "arrayReduce_default", "baseReduce_default", "initAccum", "baseIteratee_default", "baseEach_default", "reduce_default", "baseFindIndex", "array", "predicate", "fromIndex", "fromRight", "length", "index", "baseFindIndex_default", "baseIsNaN", "value", "baseIsNaN_default", "strictIndexOf", "array", "value", "fromIndex", "index", "length", "strictIndexOf_default", "baseIndexOf", "array", "value", "fromIndex", "strictIndexOf_default", "baseFindIndex_default", "baseIsNaN_default", "baseIndexOf_default", "arrayIncludes", "array", "value", "length", "baseIndexOf_default", "arrayIncludes_default", "arrayIncludesWith", "array", "value", "comparator", "index", "length", "arrayIncludesWith_default", "noop", "noop_default", "INFINITY", "createSet", "Set_default", "setToArray_default", "values", "noop_default", "createSet_default", "LARGE_ARRAY_SIZE", "baseUniq", "array", "iteratee", "comparator", "index", "includes", "arrayIncludes_default", "length", "isCommon", "result", "seen", "arrayIncludesWith_default", "set", "createSet_default", "setToArray_default", "cacheHas_default", "SetCache_default", "outer", "value", "computed", "seenIndex", "baseUniq_default", "union", "baseRest_default", "arrays", "baseUniq_default", "baseFlatten_default", "isArrayLikeObject_default", "union_default", "reWhitespace", "trimmedEndIndex", "string", "index", "trimmedEndIndex_default", "reTrimStart", "baseTrim", "string", "trimmedEndIndex_default", "baseTrim_default", "NAN", "reIsBadHex", "reIsBinary", "reIsOctal", "freeParseInt", "toNumber", "value", "isSymbol_default", "isObject_default", "other", "baseTrim_default", "isBinary", "toNumber_default", "INFINITY", "MAX_INTEGER", "toFinite", "value", "toNumber_default", "sign", "toFinite_default", "toInteger", "value", "result", "toFinite_default", "remainder", "toInteger_default", "objectProto", "hasOwnProperty", "assign", "createAssigner_default", "object", "source", "isPrototype_default", "isArrayLike_default", "copyObject_default", "keys_default", "key", "assignValue_default", "assign_default", "baseSlice", "array", "start", "end", "index", "length", "result", "baseSlice_default", "rsAstralRange", "rsComboMarksRange", "reComboHalfMarksRange", "rsComboSymbolsRange", "rsComboRange", "rsVarRange", "rsZWJ", "reHasUnicode", "hasUnicode", "string", "hasUnicode_default", "CLONE_DEEP_FLAG", "CLONE_SYMBOLS_FLAG", "cloneDeep", "value", "baseClone_default", "cloneDeep_default", "compact", "array", "index", "length", "resIndex", "result", "value", "compact_default", "arrayAggregator", "array", "setter", "iteratee", "accumulator", "index", "length", "value", "arrayAggregator_default", "baseAggregator", "collection", "setter", "iteratee", "accumulator", "baseEach_default", "value", "key", "baseAggregator_default", "createAggregator", "setter", "initializer", "collection", "iteratee", "func", "isArray_default", "arrayAggregator_default", "baseAggregator_default", "accumulator", "baseIteratee_default", "createAggregator_default", "now", "root_default", "now_default", "LARGE_ARRAY_SIZE", "baseDifference", "array", "values", "iteratee", "comparator", "index", "includes", "arrayIncludes_default", "isCommon", "length", "result", "valuesLength", "arrayMap_default", "baseUnary_default", "arrayIncludesWith_default", "cacheHas_default", "SetCache_default", "outer", "value", "computed", "valuesIndex", "baseDifference_default", "difference", "baseRest_default", "array", "values", "isArrayLikeObject_default", "baseDifference_default", "baseFlatten_default", "difference_default", "drop", "array", "n", "guard", "length", "toInteger_default", "baseSlice_default", "drop_default", "dropRight", "array", "n", "guard", "length", "toInteger_default", "baseSlice_default", "dropRight_default", "arrayEvery", "array", "predicate", "index", "length", "arrayEvery_default", "baseEvery", "collection", "predicate", "result", "baseEach_default", "value", "index", "baseEvery_default", "every", "collection", "predicate", "guard", "func", "isArray_default", "arrayEvery_default", "baseEvery_default", "isIterateeCall_default", "baseIteratee_default", "every_default", "createFind", "findIndexFunc", "collection", "predicate", "fromIndex", "iterable", "isArrayLike_default", "iteratee", "baseIteratee_default", "keys_default", "key", "index", "createFind_default", "nativeMax", "findIndex", "array", "predicate", "fromIndex", "length", "index", "toInteger_default", "baseFindIndex_default", "baseIteratee_default", "findIndex_default", "find", "createFind_default", "findIndex_default", "find_default", "head", "array", "head_default", "flatMap", "collection", "iteratee", "baseFlatten_default", "map_default", "flatMap_default", "forIn", "object", "iteratee", "baseFor_default", "castFunction_default", "keysIn_default", "forIn_default", "forOwn", "object", "iteratee", "baseForOwn_default", "castFunction_default", "forOwn_default", "objectProto", "hasOwnProperty", "groupBy", "createAggregator_default", "result", "value", "key", "baseAssignValue_default", "groupBy_default", "objectProto", "hasOwnProperty", "baseHas", "object", "key", "baseHas_default", "has", "object", "path", "hasPath_default", "baseHas_default", "has_default", "stringTag", "isString", "value", "isArray_default", "isObjectLike_default", "baseGetTag_default", "isString_default", "nativeMax", "includes", "collection", "value", "fromIndex", "guard", "isArrayLike_default", "values_default", "toInteger_default", "length", "isString_default", "baseIndexOf_default", "includes_default", "nativeMax", "indexOf", "array", "value", "fromIndex", "length", "index", "toInteger_default", "baseIndexOf_default", "indexOf_default", "regexpTag", "baseIsRegExp", "value", "isObjectLike_default", "baseGetTag_default", "baseIsRegExp_default", "nodeIsRegExp", "nodeUtil_default", "isRegExp", "baseUnary_default", "baseIsRegExp_default", "isRegExp_default", "baseLt", "value", "other", "baseLt_default", "min", "array", "baseExtremum_default", "identity_default", "baseLt_default", "min_default", "minBy", "array", "iteratee", "baseExtremum_default", "baseIteratee_default", "baseLt_default", "minBy_default", "FUNC_ERROR_TEXT", "negate", "predicate", "args", "negate_default", "pickBy", "object", "predicate", "props", "arrayMap_default", "getAllKeysIn_default", "prop", "baseIteratee_default", "basePickBy_default", "value", "path", "pickBy_default", "baseSortBy", "array", "comparer", "length", "baseSortBy_default", "compareAscending", "value", "other", "valIsDefined", "valIsNull", "valIsReflexive", "valIsSymbol", "isSymbol_default", "othIsDefined", "othIsNull", "othIsReflexive", "othIsSymbol", "compareAscending_default", "compareMultiple", "object", "other", "orders", "index", "objCriteria", "othCriteria", "length", "ordersLength", "result", "compareAscending_default", "order", "compareMultiple_default", "baseOrderBy", "collection", "iteratees", "orders", "arrayMap_default", "iteratee", "isArray_default", "value", "baseGet_default", "identity_default", "index", "baseUnary_default", "baseIteratee_default", "result", "baseMap_default", "key", "criteria", "baseSortBy_default", "object", "other", "compareMultiple_default", "baseOrderBy_default", "asciiSize", "baseProperty_default", "asciiSize_default", "rsAstralRange", "rsComboMarksRange", "reComboHalfMarksRange", "rsComboSymbolsRange", "rsComboRange", "rsVarRange", "rsAstral", "rsCombo", "rsFitz", "rsModifier", "rsNonAstral", "rsRegional", "rsSurrPair", "rsZWJ", "reOptMod", "rsOptVar", "rsOptJoin", "rsSeq", "rsSymbol", "reUnicode", "unicodeSize", "string", "result", "unicodeSize_default", "stringSize", "string", "hasUnicode_default", "unicodeSize_default", "asciiSize_default", "stringSize_default", "nativeCeil", "nativeMax", "baseRange", "start", "end", "step", "fromRight", "index", "length", "result", "baseRange_default", "createRange", "fromRight", "start", "end", "step", "isIterateeCall_default", "toFinite_default", "baseRange_default", "createRange_default", "range", "createRange_default", "range_default", "reject", "collection", "predicate", "func", "isArray_default", "arrayFilter_default", "baseFilter_default", "negate_default", "baseIteratee_default", "reject_default", "mapTag", "setTag", "size", "collection", "isArrayLike_default", "isString_default", "stringSize_default", "tag", "getTag_default", "baseKeys_default", "size_default", "baseSome", "collection", "predicate", "result", "baseEach_default", "value", "index", "baseSome_default", "some", "collection", "predicate", "guard", "func", "isArray_default", "arraySome_default", "baseSome_default", "isIterateeCall_default", "baseIteratee_default", "some_default", "sortBy", "baseRest_default", "collection", "iteratees", "length", "isIterateeCall_default", "baseOrderBy_default", "baseFlatten_default", "sortBy_default", "uniq", "array", "baseUniq_default", "uniq_default", "uniqBy", "array", "iteratee", "baseUniq_default", "baseIteratee_default", "uniqBy_default", "idCounter", "uniqueId", "prefix", "id", "toString_default", "uniqueId_default", "baseZipObject", "props", "values", "assignFunc", "index", "length", "valsLength", "result", "value", "baseZipObject_default", "zipObject", "props", "values", "baseZipObject_default", "assignValue_default", "zipObject_default"] +} diff --git a/docs/website/public/chunk-RSZXG5PP.min.js b/docs/website/public/chunk-RSZXG5PP.min.js new file mode 100644 index 000000000..9c0687cb8 --- /dev/null +++ b/docs/website/public/chunk-RSZXG5PP.min.js @@ -0,0 +1,8 @@ +import{a as kt,d as X}from"./chunk-IDQ2RCY2.min.js";import{a as T,b as V,c as pt}from"./chunk-77XMBG7U.min.js";import{a as ft}from"./chunk-ANLQN3B7.min.js";import{c as ht,d as mt}from"./chunk-OEBO5CRK.min.js";import{g as yt}from"./chunk-XCAVDAZC.min.js";import{m as $}from"./chunk-QZZKR5JD.min.js";import{F as K,W as v}from"./chunk-3EE2TK35.min.js";import{$ as lt,I as J,J as tt,L as rt,M as at,N as U,R as et,U as nt,Y as st,Z as ot,_ as it,aa as ct,b as h,ba as dt,d as m,j as D}from"./chunk-6TVUEPFY.min.js";var vt=h((r,t,a,s,i,n)=>{t.arrowTypeStart&&ut(r,"start",t.arrowTypeStart,a,s,i,n),t.arrowTypeEnd&&ut(r,"end",t.arrowTypeEnd,a,s,i,n)},"addEdgeMarkers"),$t={arrow_cross:{type:"cross",fill:!1},arrow_point:{type:"point",fill:!0},arrow_barb:{type:"barb",fill:!0},arrow_circle:{type:"circle",fill:!1},aggregation:{type:"aggregation",fill:!1},extension:{type:"extension",fill:!1},composition:{type:"composition",fill:!0},dependency:{type:"dependency",fill:!0},lollipop:{type:"lollipop",fill:!1},only_one:{type:"onlyOne",fill:!1},zero_or_one:{type:"zeroOrOne",fill:!1},one_or_more:{type:"oneOrMore",fill:!1},zero_or_more:{type:"zeroOrMore",fill:!1},requirement_arrow:{type:"requirement_arrow",fill:!1},requirement_contains:{type:"requirement_contains",fill:!1}},ut=h((r,t,a,s,i,n,e)=>{let o=$t[a];if(!o){m.warn(`Unknown arrow type: ${a}`);return}let c=o.type,d=`${i}_${n}-${c}${t==="start"?"Start":"End"}`;if(e&&e.trim()!==""){let f=e.replace(/[^\dA-Za-z]/g,"_"),p=`${d}_${f}`;if(!document.getElementById(p)){let y=document.getElementById(d);if(y){let L=y.cloneNode(!0);L.id=p,L.querySelectorAll("path, circle, line").forEach(k=>{k.setAttribute("stroke",e),o.fill&&k.setAttribute("fill",e)}),y.parentNode?.appendChild(L)}}r.attr(`marker-${t}`,`url(${s}#${p})`)}else r.attr(`marker-${t}`,`url(${s}#${d})`)},"addEdgeMarker"),P=new Map,x=new Map,nr=h(()=>{P.clear(),x.clear()},"clear"),I=h(r=>r?r.reduce((a,s)=>a+";"+s,""):"","getLabelStyles"),sr=h(async(r,t)=>{let a=K(v().flowchart.htmlLabels),{labelStyles:s}=mt(t);t.labelStyle=s;let i=await yt(r,t.label,{style:t.labelStyle,useHtmlLabels:a,addSvgBackground:!0,isNode:!1});m.info("abc82",t,t.labelType);let n=r.insert("g").attr("class","edgeLabel"),e=n.insert("g").attr("class","label").attr("data-id",t.id);e.node().appendChild(i);let o=i.getBBox();if(a){let l=i.children[0],d=D(i);o=l.getBoundingClientRect(),d.attr("width",o.width),d.attr("height",o.height)}e.attr("transform","translate("+-o.width/2+", "+-o.height/2+")"),P.set(t.id,n),t.width=o.width,t.height=o.height;let c;if(t.startLabelLeft){let l=await X(t.startLabelLeft,I(t.labelStyle)),d=r.insert("g").attr("class","edgeTerminals"),f=d.insert("g").attr("class","inner");c=f.node().appendChild(l);let p=l.getBBox();f.attr("transform","translate("+-p.width/2+", "+-p.height/2+")"),x.get(t.id)||x.set(t.id,{}),x.get(t.id).startLeft=d,Y(c,t.startLabelLeft)}if(t.startLabelRight){let l=await X(t.startLabelRight,I(t.labelStyle)),d=r.insert("g").attr("class","edgeTerminals"),f=d.insert("g").attr("class","inner");c=d.node().appendChild(l),f.node().appendChild(l);let p=l.getBBox();f.attr("transform","translate("+-p.width/2+", "+-p.height/2+")"),x.get(t.id)||x.set(t.id,{}),x.get(t.id).startRight=d,Y(c,t.startLabelRight)}if(t.endLabelLeft){let l=await X(t.endLabelLeft,I(t.labelStyle)),d=r.insert("g").attr("class","edgeTerminals"),f=d.insert("g").attr("class","inner");c=f.node().appendChild(l);let p=l.getBBox();f.attr("transform","translate("+-p.width/2+", "+-p.height/2+")"),d.node().appendChild(l),x.get(t.id)||x.set(t.id,{}),x.get(t.id).endLeft=d,Y(c,t.endLabelLeft)}if(t.endLabelRight){let l=await X(t.endLabelRight,I(t.labelStyle)),d=r.insert("g").attr("class","edgeTerminals"),f=d.insert("g").attr("class","inner");c=f.node().appendChild(l);let p=l.getBBox();f.attr("transform","translate("+-p.width/2+", "+-p.height/2+")"),d.node().appendChild(l),x.get(t.id)||x.set(t.id,{}),x.get(t.id).endRight=d,Y(c,t.endLabelRight)}return i},"insertEdgeLabel");function Y(r,t){v().flowchart.htmlLabels&&r&&(r.style.width=t.length*9+"px",r.style.height="12px")}h(Y,"setTerminalWidth");var or=h((r,t)=>{m.debug("Moving label abc88 ",r.id,r.label,P.get(r.id),t);let a=t.updatedPath?t.updatedPath:t.originalPath,s=v(),{subGraphTitleTotalMargin:i}=ft(s);if(r.label){let n=P.get(r.id),e=r.x,o=r.y;if(a){let c=$.calcLabelPosition(a);m.debug("Moving label "+r.label+" from (",e,",",o,") to (",c.x,",",c.y,") abc88"),t.updatedPath&&(e=c.x,o=c.y)}n.attr("transform",`translate(${e}, ${o+i/2})`)}if(r.startLabelLeft){let n=x.get(r.id).startLeft,e=r.x,o=r.y;if(a){let c=$.calcTerminalLabelPosition(r.arrowTypeStart?10:0,"start_left",a);e=c.x,o=c.y}n.attr("transform",`translate(${e}, ${o})`)}if(r.startLabelRight){let n=x.get(r.id).startRight,e=r.x,o=r.y;if(a){let c=$.calcTerminalLabelPosition(r.arrowTypeStart?10:0,"start_right",a);e=c.x,o=c.y}n.attr("transform",`translate(${e}, ${o})`)}if(r.endLabelLeft){let n=x.get(r.id).endLeft,e=r.x,o=r.y;if(a){let c=$.calcTerminalLabelPosition(r.arrowTypeEnd?10:0,"end_left",a);e=c.x,o=c.y}n.attr("transform",`translate(${e}, ${o})`)}if(r.endLabelRight){let n=x.get(r.id).endRight,e=r.x,o=r.y;if(a){let c=$.calcTerminalLabelPosition(r.arrowTypeEnd?10:0,"end_right",a);e=c.x,o=c.y}n.attr("transform",`translate(${e}, ${o})`)}},"positionEdgeLabel"),St=h((r,t)=>{let a=r.x,s=r.y,i=Math.abs(t.x-a),n=Math.abs(t.y-s),e=r.width/2,o=r.height/2;return i>=e||n>=o},"outsideNode"),Et=h((r,t,a)=>{m.debug(`intersection calc abc89: + outsidePoint: ${JSON.stringify(t)} + insidePoint : ${JSON.stringify(a)} + node : x:${r.x} y:${r.y} w:${r.width} h:${r.height}`);let s=r.x,i=r.y,n=Math.abs(s-a.x),e=r.width/2,o=a.xMath.abs(s-t.x)*c){let f=a.y{m.warn("abc88 cutPathAtIntersect",r,t);let a=[],s=r[0],i=!1;return r.forEach(n=>{if(m.info("abc88 checking point",n,t),!St(t,n)&&!i){let e=Et(t,s,n);m.debug("abc88 inside",n,s,e),m.debug("abc88 intersection",e,t);let o=!1;a.forEach(c=>{o=o||c.x===e.x&&c.y===e.y}),a.some(c=>c.x===e.x&&c.y===e.y)?m.warn("abc88 no intersect",e,a):a.push(e),i=!0}else m.warn("abc88 outside",n,s),s=n,i||a.push(n)}),m.debug("returning points",a),a},"cutPathAtIntersect");function gt(r){let t=[],a=[];for(let s=1;s5&&Math.abs(n.y-i.y)>5||i.y===n.y&&n.x===e.x&&Math.abs(n.x-i.x)>5&&Math.abs(n.y-e.y)>5)&&(t.push(n),a.push(s))}return{cornerPoints:t,cornerPointPositions:a}}h(gt,"extractCornerPoints");var bt=h(function(r,t,a){let s=t.x-r.x,i=t.y-r.y,n=Math.sqrt(s*s+i*i),e=a/n;return{x:t.x-e*s,y:t.y-e*i}},"findAdjacentPoint"),Ot=h(function(r){let{cornerPointPositions:t}=gt(r),a=[];for(let s=0;s10&&Math.abs(n.y-i.y)>=10){m.debug("Corner point fixing",Math.abs(n.x-i.x),Math.abs(n.y-i.y));let y=5;e.x===o.x?p={x:l<0?o.x-y+f:o.x+y-f,y:d<0?o.y-f:o.y+f}:p={x:l<0?o.x-f:o.x+f,y:d<0?o.y-y+f:o.y+y-f}}else m.debug("Corner point skipping fixing",Math.abs(n.x-i.x),Math.abs(n.y-i.y));a.push(p,c)}else a.push(r[s]);return a},"fixCorners"),Tt=h((r,t,a)=>{let s=r-t-a,i=2,n=2,e=i+n,o=Math.floor(s/e),c=Array(o).fill(`${i} ${n}`).join(" ");return`0 ${t} ${c} ${a}`},"generateDashArray"),ir=h(function(r,t,a,s,i,n,e,o=!1){let{handDrawnSeed:c}=v(),l=t.points,d=!1,f=i;var p=n;let y=[];for(let b in t.cssCompiledStyles)ht(b)||y.push(t.cssCompiledStyles[b]);m.debug("UIO intersect check",t.points,p.x,f.x),p.intersect&&f.intersect&&!o&&(l=l.slice(1,t.points.length-1),l.unshift(f.intersect(l[0])),m.debug("Last point UIO",t.start,"-->",t.end,l[l.length-1],p,p.intersect(l[l.length-1])),l.push(p.intersect(l[l.length-1])));let L=btoa(JSON.stringify(l));t.toCluster&&(m.info("to cluster abc88",a.get(t.toCluster)),l=xt(t.points,a.get(t.toCluster).node),d=!0),t.fromCluster&&(m.debug("from cluster abc88",a.get(t.fromCluster),JSON.stringify(l,null,2)),l=xt(l.reverse(),a.get(t.fromCluster).node).reverse(),d=!0);let M=l.filter(b=>!Number.isNaN(b.y));M=Ot(M);let k=U;switch(k=J,t.curve){case"linear":k=J;break;case"basis":k=U;break;case"cardinal":k=et;break;case"bumpX":k=rt;break;case"bumpY":k=at;break;case"catmullRom":k=nt;break;case"monotoneX":k=st;break;case"monotoneY":k=ot;break;case"natural":k=it;break;case"step":k=lt;break;case"stepAfter":k=dt;break;case"stepBefore":k=ct;break;default:k=U}let{x:C,y:W}=pt(t),N=tt().x(C).y(W).curve(k),g;switch(t.thickness){case"normal":g="edge-thickness-normal";break;case"thick":g="edge-thickness-thick";break;case"invisible":g="edge-thickness-invisible";break;default:g="edge-thickness-normal"}switch(t.pattern){case"solid":g+=" edge-pattern-solid";break;case"dotted":g+=" edge-pattern-dotted";break;case"dashed":g+=" edge-pattern-dashed";break;default:g+=" edge-pattern-solid"}let u,_=t.curve==="rounded"?Lt(Mt(M,t),5):N(M),w=Array.isArray(t.style)?t.style:[t.style],H=w.find(b=>b?.startsWith("stroke:")),B=!1;if(t.look==="handDrawn"){let b=kt.svg(r);Object.assign([],M);let A=b.path(_,{roughness:.3,seed:c});g+=" transition",u=D(A).select("path").attr("id",t.id).attr("class"," "+g+(t.classes?" "+t.classes:"")).attr("style",w?w.reduce((R,z)=>R+";"+z,""):"");let E=u.attr("d");u.attr("d",E),r.node().appendChild(u.node())}else{let b=y.join(";"),A=w?w.reduce((q,O)=>q+O+";",""):"",E="";t.animate&&(E=" edge-animation-fast"),t.animation&&(E=" edge-animation-"+t.animation);let R=(b?b+";"+A+";":A)+";"+(w?w.reduce((q,O)=>q+";"+O,""):"");u=r.append("path").attr("d",_).attr("id",t.id).attr("class"," "+g+(t.classes?" "+t.classes:"")+(E??"")).attr("style",R),H=R.match(/stroke:([^;]+)/)?.[1],B=t.animate===!0||!!t.animation||b.includes("animation");let z=u.node(),G=typeof z.getTotalLength=="function"?z.getTotalLength():0,Z=V[t.arrowTypeStart]||0,j=V[t.arrowTypeEnd]||0;if(t.look==="neo"&&!B){let O=`stroke-dasharray: ${t.pattern==="dotted"||t.pattern==="dashed"?Tt(G,Z,j):`0 ${Z} ${G-Z-j} ${j}`}; stroke-dashoffset: 0;`;u.attr("style",O+u.attr("style"))}}u.attr("data-edge",!0),u.attr("data-et","edge"),u.attr("data-id",t.id),u.attr("data-points",L),t.showPoints&&M.forEach(b=>{r.append("circle").style("stroke","red").style("fill","red").attr("r",1).attr("cx",b.x).attr("cy",b.y)});let S="";(v().flowchart.arrowMarkerAbsolute||v().state.arrowMarkerAbsolute)&&(S=window.location.protocol+"//"+window.location.host+window.location.pathname+window.location.search,S=S.replace(/\(/g,"\\(").replace(/\)/g,"\\)")),m.info("arrowTypeStart",t.arrowTypeStart),m.info("arrowTypeEnd",t.arrowTypeEnd),vt(u,t,S,e,s,H);let wt=Math.floor(l.length/2),_t=l[wt];$.isLabelCoordinateInPath(_t,u.attr("d"))||(d=!0);let Q={};return d&&(Q.updatedPath=l),Q.originalPath=t.points,Q},"insertEdge");function Lt(r,t){if(r.length<2)return"";let a="",s=r.length,i=1e-5;for(let n=0;n({...i}));if(r.length>=2&&T[t.arrowTypeStart]){let i=T[t.arrowTypeStart],n=r[0],e=r[1],{angle:o}=F(n,e),c=i*Math.cos(o),l=i*Math.sin(o);a[0].x=n.x+c,a[0].y=n.y+l}let s=r.length;if(s>=2&&T[t.arrowTypeEnd]){let i=T[t.arrowTypeEnd],n=r[s-1],e=r[s-2],{angle:o}=F(e,n),c=i*Math.cos(o),l=i*Math.sin(o);a[s-1].x=n.x-c,a[s-1].y=n.y-l}return a}h(Mt,"applyMarkerOffsetsToPoints");var Xt=h((r,t,a,s)=>{t.forEach(i=>{jt[i](r,a,s)})},"insertMarkers"),Yt=h((r,t,a)=>{m.trace("Making markers for ",a),r.append("defs").append("marker").attr("id",a+"_"+t+"-extensionStart").attr("class","marker extension "+t).attr("refX",18).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 1,7 L18,13 V 1 Z"),r.append("defs").append("marker").attr("id",a+"_"+t+"-extensionEnd").attr("class","marker extension "+t).attr("refX",1).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 1,1 V 13 L18,7 Z")},"extension"),Ct=h((r,t,a)=>{r.append("defs").append("marker").attr("id",a+"_"+t+"-compositionStart").attr("class","marker composition "+t).attr("refX",18).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),r.append("defs").append("marker").attr("id",a+"_"+t+"-compositionEnd").attr("class","marker composition "+t).attr("refX",1).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z")},"composition"),Wt=h((r,t,a)=>{r.append("defs").append("marker").attr("id",a+"_"+t+"-aggregationStart").attr("class","marker aggregation "+t).attr("refX",18).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),r.append("defs").append("marker").attr("id",a+"_"+t+"-aggregationEnd").attr("class","marker aggregation "+t).attr("refX",1).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z")},"aggregation"),Ht=h((r,t,a)=>{r.append("defs").append("marker").attr("id",a+"_"+t+"-dependencyStart").attr("class","marker dependency "+t).attr("refX",6).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 5,7 L9,13 L1,7 L9,1 Z"),r.append("defs").append("marker").attr("id",a+"_"+t+"-dependencyEnd").attr("class","marker dependency "+t).attr("refX",13).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L14,7 L9,1 Z")},"dependency"),Bt=h((r,t,a)=>{r.append("defs").append("marker").attr("id",a+"_"+t+"-lollipopStart").attr("class","marker lollipop "+t).attr("refX",13).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("circle").attr("stroke","black").attr("fill","transparent").attr("cx",7).attr("cy",7).attr("r",6),r.append("defs").append("marker").attr("id",a+"_"+t+"-lollipopEnd").attr("class","marker lollipop "+t).attr("refX",1).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("circle").attr("stroke","black").attr("fill","transparent").attr("cx",7).attr("cy",7).attr("r",6)},"lollipop"),At=h((r,t,a)=>{r.append("marker").attr("id",a+"_"+t+"-pointEnd").attr("class","marker "+t).attr("viewBox","0 0 10 10").attr("refX",5).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",8).attr("markerHeight",8).attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 z").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0"),r.append("marker").attr("id",a+"_"+t+"-pointStart").attr("class","marker "+t).attr("viewBox","0 0 10 10").attr("refX",4.5).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",8).attr("markerHeight",8).attr("orient","auto").append("path").attr("d","M 0 5 L 10 10 L 10 0 z").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0")},"point"),Rt=h((r,t,a)=>{r.append("marker").attr("id",a+"_"+t+"-circleEnd").attr("class","marker "+t).attr("viewBox","0 0 10 10").attr("refX",11).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("circle").attr("cx","5").attr("cy","5").attr("r","5").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0"),r.append("marker").attr("id",a+"_"+t+"-circleStart").attr("class","marker "+t).attr("viewBox","0 0 10 10").attr("refX",-1).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("circle").attr("cx","5").attr("cy","5").attr("r","5").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0")},"circle"),zt=h((r,t,a)=>{r.append("marker").attr("id",a+"_"+t+"-crossEnd").attr("class","marker cross "+t).attr("viewBox","0 0 11 11").attr("refX",12).attr("refY",5.2).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("path").attr("d","M 1,1 l 9,9 M 10,1 l -9,9").attr("class","arrowMarkerPath").style("stroke-width",2).style("stroke-dasharray","1,0"),r.append("marker").attr("id",a+"_"+t+"-crossStart").attr("class","marker cross "+t).attr("viewBox","0 0 11 11").attr("refX",-1).attr("refY",5.2).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("path").attr("d","M 1,1 l 9,9 M 10,1 l -9,9").attr("class","arrowMarkerPath").style("stroke-width",2).style("stroke-dasharray","1,0")},"cross"),qt=h((r,t,a)=>{r.append("defs").append("marker").attr("id",a+"_"+t+"-barbEnd").attr("refX",19).attr("refY",7).attr("markerWidth",20).attr("markerHeight",14).attr("markerUnits","userSpaceOnUse").attr("orient","auto").append("path").attr("d","M 19,7 L9,13 L14,7 L9,1 Z")},"barb"),Ut=h((r,t,a)=>{r.append("defs").append("marker").attr("id",a+"_"+t+"-onlyOneStart").attr("class","marker onlyOne "+t).attr("refX",0).attr("refY",9).attr("markerWidth",18).attr("markerHeight",18).attr("orient","auto").append("path").attr("d","M9,0 L9,18 M15,0 L15,18"),r.append("defs").append("marker").attr("id",a+"_"+t+"-onlyOneEnd").attr("class","marker onlyOne "+t).attr("refX",18).attr("refY",9).attr("markerWidth",18).attr("markerHeight",18).attr("orient","auto").append("path").attr("d","M3,0 L3,18 M9,0 L9,18")},"only_one"),It=h((r,t,a)=>{let s=r.append("defs").append("marker").attr("id",a+"_"+t+"-zeroOrOneStart").attr("class","marker zeroOrOne "+t).attr("refX",0).attr("refY",9).attr("markerWidth",30).attr("markerHeight",18).attr("orient","auto");s.append("circle").attr("fill","white").attr("cx",21).attr("cy",9).attr("r",6),s.append("path").attr("d","M9,0 L9,18");let i=r.append("defs").append("marker").attr("id",a+"_"+t+"-zeroOrOneEnd").attr("class","marker zeroOrOne "+t).attr("refX",30).attr("refY",9).attr("markerWidth",30).attr("markerHeight",18).attr("orient","auto");i.append("circle").attr("fill","white").attr("cx",9).attr("cy",9).attr("r",6),i.append("path").attr("d","M21,0 L21,18")},"zero_or_one"),Pt=h((r,t,a)=>{r.append("defs").append("marker").attr("id",a+"_"+t+"-oneOrMoreStart").attr("class","marker oneOrMore "+t).attr("refX",18).attr("refY",18).attr("markerWidth",45).attr("markerHeight",36).attr("orient","auto").append("path").attr("d","M0,18 Q 18,0 36,18 Q 18,36 0,18 M42,9 L42,27"),r.append("defs").append("marker").attr("id",a+"_"+t+"-oneOrMoreEnd").attr("class","marker oneOrMore "+t).attr("refX",27).attr("refY",18).attr("markerWidth",45).attr("markerHeight",36).attr("orient","auto").append("path").attr("d","M3,9 L3,27 M9,18 Q27,0 45,18 Q27,36 9,18")},"one_or_more"),Nt=h((r,t,a)=>{let s=r.append("defs").append("marker").attr("id",a+"_"+t+"-zeroOrMoreStart").attr("class","marker zeroOrMore "+t).attr("refX",18).attr("refY",18).attr("markerWidth",57).attr("markerHeight",36).attr("orient","auto");s.append("circle").attr("fill","white").attr("cx",48).attr("cy",18).attr("r",6),s.append("path").attr("d","M0,18 Q18,0 36,18 Q18,36 0,18");let i=r.append("defs").append("marker").attr("id",a+"_"+t+"-zeroOrMoreEnd").attr("class","marker zeroOrMore "+t).attr("refX",39).attr("refY",18).attr("markerWidth",57).attr("markerHeight",36).attr("orient","auto");i.append("circle").attr("fill","white").attr("cx",9).attr("cy",18).attr("r",6),i.append("path").attr("d","M21,18 Q39,0 57,18 Q39,36 21,18")},"zero_or_more"),Qt=h((r,t,a)=>{r.append("defs").append("marker").attr("id",a+"_"+t+"-requirement_arrowEnd").attr("refX",20).attr("refY",10).attr("markerWidth",20).attr("markerHeight",20).attr("orient","auto").append("path").attr("d",`M0,0 + L20,10 + M20,10 + L0,20`)},"requirement_arrow"),Zt=h((r,t,a)=>{let s=r.append("defs").append("marker").attr("id",a+"_"+t+"-requirement_containsStart").attr("refX",0).attr("refY",10).attr("markerWidth",20).attr("markerHeight",20).attr("orient","auto").append("g");s.append("circle").attr("cx",10).attr("cy",10).attr("r",9).attr("fill","none"),s.append("line").attr("x1",1).attr("x2",19).attr("y1",10).attr("y2",10),s.append("line").attr("y1",1).attr("y2",19).attr("x1",10).attr("x2",10)},"requirement_contains"),jt={extension:Yt,composition:Ct,aggregation:Wt,dependency:Ht,lollipop:Bt,point:At,circle:Rt,cross:zt,barb:qt,only_one:Ut,zero_or_one:It,one_or_more:Pt,zero_or_more:Nt,requirement_arrow:Qt,requirement_contains:Zt},lr=Xt;export{nr as a,sr as b,or as c,ir as d,lr as e}; +//# sourceMappingURL=chunk-RSZXG5PP.min.js.map diff --git a/docs/website/public/chunk-RSZXG5PP.min.js.map b/docs/website/public/chunk-RSZXG5PP.min.js.map new file mode 100644 index 000000000..008912712 --- /dev/null +++ b/docs/website/public/chunk-RSZXG5PP.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/mermaid/dist/chunks/mermaid.core/chunk-QXUST7PY.mjs"], + "sourcesContent": ["import {\n getLineFunctionsWithOffset,\n markerOffsets,\n markerOffsets2\n} from \"./chunk-HN2XXSSU.mjs\";\nimport {\n createLabel_default\n} from \"./chunk-JZLCHNYA.mjs\";\nimport {\n getSubGraphTitleMargins\n} from \"./chunk-CVBHYZKI.mjs\";\nimport {\n isLabelStyle,\n styles2String\n} from \"./chunk-ATLVNIR6.mjs\";\nimport {\n createText\n} from \"./chunk-JA3XYJ7Z.mjs\";\nimport {\n utils_default\n} from \"./chunk-S3R3BYOJ.mjs\";\nimport {\n evaluate,\n getConfig2 as getConfig\n} from \"./chunk-ABZYJK2D.mjs\";\nimport {\n __name,\n log\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/rendering-util/rendering-elements/edges.js\nimport {\n curveBasis,\n curveLinear,\n curveCardinal,\n curveBumpX,\n curveBumpY,\n curveCatmullRom,\n curveMonotoneX,\n curveMonotoneY,\n curveNatural,\n curveStep,\n curveStepAfter,\n curveStepBefore,\n line,\n select\n} from \"d3\";\nimport rough from \"roughjs\";\n\n// src/rendering-util/rendering-elements/edgeMarker.ts\nvar addEdgeMarkers = /* @__PURE__ */ __name((svgPath, edge, url, id, diagramType, strokeColor) => {\n if (edge.arrowTypeStart) {\n addEdgeMarker(svgPath, \"start\", edge.arrowTypeStart, url, id, diagramType, strokeColor);\n }\n if (edge.arrowTypeEnd) {\n addEdgeMarker(svgPath, \"end\", edge.arrowTypeEnd, url, id, diagramType, strokeColor);\n }\n}, \"addEdgeMarkers\");\nvar arrowTypesMap = {\n arrow_cross: { type: \"cross\", fill: false },\n arrow_point: { type: \"point\", fill: true },\n arrow_barb: { type: \"barb\", fill: true },\n arrow_circle: { type: \"circle\", fill: false },\n aggregation: { type: \"aggregation\", fill: false },\n extension: { type: \"extension\", fill: false },\n composition: { type: \"composition\", fill: true },\n dependency: { type: \"dependency\", fill: true },\n lollipop: { type: \"lollipop\", fill: false },\n only_one: { type: \"onlyOne\", fill: false },\n zero_or_one: { type: \"zeroOrOne\", fill: false },\n one_or_more: { type: \"oneOrMore\", fill: false },\n zero_or_more: { type: \"zeroOrMore\", fill: false },\n requirement_arrow: { type: \"requirement_arrow\", fill: false },\n requirement_contains: { type: \"requirement_contains\", fill: false }\n};\nvar addEdgeMarker = /* @__PURE__ */ __name((svgPath, position, arrowType, url, id, diagramType, strokeColor) => {\n const arrowTypeInfo = arrowTypesMap[arrowType];\n if (!arrowTypeInfo) {\n log.warn(`Unknown arrow type: ${arrowType}`);\n return;\n }\n const endMarkerType = arrowTypeInfo.type;\n const suffix = position === \"start\" ? \"Start\" : \"End\";\n const originalMarkerId = `${id}_${diagramType}-${endMarkerType}${suffix}`;\n if (strokeColor && strokeColor.trim() !== \"\") {\n const colorId = strokeColor.replace(/[^\\dA-Za-z]/g, \"_\");\n const coloredMarkerId = `${originalMarkerId}_${colorId}`;\n if (!document.getElementById(coloredMarkerId)) {\n const originalMarker = document.getElementById(originalMarkerId);\n if (originalMarker) {\n const coloredMarker = originalMarker.cloneNode(true);\n coloredMarker.id = coloredMarkerId;\n const paths = coloredMarker.querySelectorAll(\"path, circle, line\");\n paths.forEach((path) => {\n path.setAttribute(\"stroke\", strokeColor);\n if (arrowTypeInfo.fill) {\n path.setAttribute(\"fill\", strokeColor);\n }\n });\n originalMarker.parentNode?.appendChild(coloredMarker);\n }\n }\n svgPath.attr(`marker-${position}`, `url(${url}#${coloredMarkerId})`);\n } else {\n svgPath.attr(`marker-${position}`, `url(${url}#${originalMarkerId})`);\n }\n}, \"addEdgeMarker\");\n\n// src/rendering-util/rendering-elements/edges.js\nvar edgeLabels = /* @__PURE__ */ new Map();\nvar terminalLabels = /* @__PURE__ */ new Map();\nvar clear = /* @__PURE__ */ __name(() => {\n edgeLabels.clear();\n terminalLabels.clear();\n}, \"clear\");\nvar getLabelStyles = /* @__PURE__ */ __name((styleArray) => {\n let styles = styleArray ? styleArray.reduce((acc, style) => acc + \";\" + style, \"\") : \"\";\n return styles;\n}, \"getLabelStyles\");\nvar insertEdgeLabel = /* @__PURE__ */ __name(async (elem, edge) => {\n let useHtmlLabels = evaluate(getConfig().flowchart.htmlLabels);\n const { labelStyles } = styles2String(edge);\n edge.labelStyle = labelStyles;\n const labelElement = await createText(elem, edge.label, {\n style: edge.labelStyle,\n useHtmlLabels,\n addSvgBackground: true,\n isNode: false\n });\n log.info(\"abc82\", edge, edge.labelType);\n const edgeLabel = elem.insert(\"g\").attr(\"class\", \"edgeLabel\");\n const label = edgeLabel.insert(\"g\").attr(\"class\", \"label\").attr(\"data-id\", edge.id);\n label.node().appendChild(labelElement);\n let bbox = labelElement.getBBox();\n if (useHtmlLabels) {\n const div = labelElement.children[0];\n const dv = select(labelElement);\n bbox = div.getBoundingClientRect();\n dv.attr(\"width\", bbox.width);\n dv.attr(\"height\", bbox.height);\n }\n label.attr(\"transform\", \"translate(\" + -bbox.width / 2 + \", \" + -bbox.height / 2 + \")\");\n edgeLabels.set(edge.id, edgeLabel);\n edge.width = bbox.width;\n edge.height = bbox.height;\n let fo;\n if (edge.startLabelLeft) {\n const startLabelElement = await createLabel_default(\n edge.startLabelLeft,\n getLabelStyles(edge.labelStyle)\n );\n const startEdgeLabelLeft = elem.insert(\"g\").attr(\"class\", \"edgeTerminals\");\n const inner = startEdgeLabelLeft.insert(\"g\").attr(\"class\", \"inner\");\n fo = inner.node().appendChild(startLabelElement);\n const slBox = startLabelElement.getBBox();\n inner.attr(\"transform\", \"translate(\" + -slBox.width / 2 + \", \" + -slBox.height / 2 + \")\");\n if (!terminalLabels.get(edge.id)) {\n terminalLabels.set(edge.id, {});\n }\n terminalLabels.get(edge.id).startLeft = startEdgeLabelLeft;\n setTerminalWidth(fo, edge.startLabelLeft);\n }\n if (edge.startLabelRight) {\n const startLabelElement = await createLabel_default(\n edge.startLabelRight,\n getLabelStyles(edge.labelStyle)\n );\n const startEdgeLabelRight = elem.insert(\"g\").attr(\"class\", \"edgeTerminals\");\n const inner = startEdgeLabelRight.insert(\"g\").attr(\"class\", \"inner\");\n fo = startEdgeLabelRight.node().appendChild(startLabelElement);\n inner.node().appendChild(startLabelElement);\n const slBox = startLabelElement.getBBox();\n inner.attr(\"transform\", \"translate(\" + -slBox.width / 2 + \", \" + -slBox.height / 2 + \")\");\n if (!terminalLabels.get(edge.id)) {\n terminalLabels.set(edge.id, {});\n }\n terminalLabels.get(edge.id).startRight = startEdgeLabelRight;\n setTerminalWidth(fo, edge.startLabelRight);\n }\n if (edge.endLabelLeft) {\n const endLabelElement = await createLabel_default(edge.endLabelLeft, getLabelStyles(edge.labelStyle));\n const endEdgeLabelLeft = elem.insert(\"g\").attr(\"class\", \"edgeTerminals\");\n const inner = endEdgeLabelLeft.insert(\"g\").attr(\"class\", \"inner\");\n fo = inner.node().appendChild(endLabelElement);\n const slBox = endLabelElement.getBBox();\n inner.attr(\"transform\", \"translate(\" + -slBox.width / 2 + \", \" + -slBox.height / 2 + \")\");\n endEdgeLabelLeft.node().appendChild(endLabelElement);\n if (!terminalLabels.get(edge.id)) {\n terminalLabels.set(edge.id, {});\n }\n terminalLabels.get(edge.id).endLeft = endEdgeLabelLeft;\n setTerminalWidth(fo, edge.endLabelLeft);\n }\n if (edge.endLabelRight) {\n const endLabelElement = await createLabel_default(edge.endLabelRight, getLabelStyles(edge.labelStyle));\n const endEdgeLabelRight = elem.insert(\"g\").attr(\"class\", \"edgeTerminals\");\n const inner = endEdgeLabelRight.insert(\"g\").attr(\"class\", \"inner\");\n fo = inner.node().appendChild(endLabelElement);\n const slBox = endLabelElement.getBBox();\n inner.attr(\"transform\", \"translate(\" + -slBox.width / 2 + \", \" + -slBox.height / 2 + \")\");\n endEdgeLabelRight.node().appendChild(endLabelElement);\n if (!terminalLabels.get(edge.id)) {\n terminalLabels.set(edge.id, {});\n }\n terminalLabels.get(edge.id).endRight = endEdgeLabelRight;\n setTerminalWidth(fo, edge.endLabelRight);\n }\n return labelElement;\n}, \"insertEdgeLabel\");\nfunction setTerminalWidth(fo, value) {\n if (getConfig().flowchart.htmlLabels && fo) {\n fo.style.width = value.length * 9 + \"px\";\n fo.style.height = \"12px\";\n }\n}\n__name(setTerminalWidth, \"setTerminalWidth\");\nvar positionEdgeLabel = /* @__PURE__ */ __name((edge, paths) => {\n log.debug(\"Moving label abc88 \", edge.id, edge.label, edgeLabels.get(edge.id), paths);\n let path = paths.updatedPath ? paths.updatedPath : paths.originalPath;\n const siteConfig = getConfig();\n const { subGraphTitleTotalMargin } = getSubGraphTitleMargins(siteConfig);\n if (edge.label) {\n const el = edgeLabels.get(edge.id);\n let x = edge.x;\n let y = edge.y;\n if (path) {\n const pos = utils_default.calcLabelPosition(path);\n log.debug(\n \"Moving label \" + edge.label + \" from (\",\n x,\n \",\",\n y,\n \") to (\",\n pos.x,\n \",\",\n pos.y,\n \") abc88\"\n );\n if (paths.updatedPath) {\n x = pos.x;\n y = pos.y;\n }\n }\n el.attr(\"transform\", `translate(${x}, ${y + subGraphTitleTotalMargin / 2})`);\n }\n if (edge.startLabelLeft) {\n const el = terminalLabels.get(edge.id).startLeft;\n let x = edge.x;\n let y = edge.y;\n if (path) {\n const pos = utils_default.calcTerminalLabelPosition(edge.arrowTypeStart ? 10 : 0, \"start_left\", path);\n x = pos.x;\n y = pos.y;\n }\n el.attr(\"transform\", `translate(${x}, ${y})`);\n }\n if (edge.startLabelRight) {\n const el = terminalLabels.get(edge.id).startRight;\n let x = edge.x;\n let y = edge.y;\n if (path) {\n const pos = utils_default.calcTerminalLabelPosition(\n edge.arrowTypeStart ? 10 : 0,\n \"start_right\",\n path\n );\n x = pos.x;\n y = pos.y;\n }\n el.attr(\"transform\", `translate(${x}, ${y})`);\n }\n if (edge.endLabelLeft) {\n const el = terminalLabels.get(edge.id).endLeft;\n let x = edge.x;\n let y = edge.y;\n if (path) {\n const pos = utils_default.calcTerminalLabelPosition(edge.arrowTypeEnd ? 10 : 0, \"end_left\", path);\n x = pos.x;\n y = pos.y;\n }\n el.attr(\"transform\", `translate(${x}, ${y})`);\n }\n if (edge.endLabelRight) {\n const el = terminalLabels.get(edge.id).endRight;\n let x = edge.x;\n let y = edge.y;\n if (path) {\n const pos = utils_default.calcTerminalLabelPosition(edge.arrowTypeEnd ? 10 : 0, \"end_right\", path);\n x = pos.x;\n y = pos.y;\n }\n el.attr(\"transform\", `translate(${x}, ${y})`);\n }\n}, \"positionEdgeLabel\");\nvar outsideNode = /* @__PURE__ */ __name((node, point2) => {\n const x = node.x;\n const y = node.y;\n const dx = Math.abs(point2.x - x);\n const dy = Math.abs(point2.y - y);\n const w = node.width / 2;\n const h = node.height / 2;\n return dx >= w || dy >= h;\n}, \"outsideNode\");\nvar intersection = /* @__PURE__ */ __name((node, outsidePoint, insidePoint) => {\n log.debug(`intersection calc abc89:\n outsidePoint: ${JSON.stringify(outsidePoint)}\n insidePoint : ${JSON.stringify(insidePoint)}\n node : x:${node.x} y:${node.y} w:${node.width} h:${node.height}`);\n const x = node.x;\n const y = node.y;\n const dx = Math.abs(x - insidePoint.x);\n const w = node.width / 2;\n let r = insidePoint.x < outsidePoint.x ? w - dx : w + dx;\n const h = node.height / 2;\n const Q = Math.abs(outsidePoint.y - insidePoint.y);\n const R = Math.abs(outsidePoint.x - insidePoint.x);\n if (Math.abs(y - outsidePoint.y) * w > Math.abs(x - outsidePoint.x) * h) {\n let q = insidePoint.y < outsidePoint.y ? outsidePoint.y - h - y : y - h - outsidePoint.y;\n r = R * q / Q;\n const res = {\n x: insidePoint.x < outsidePoint.x ? insidePoint.x + r : insidePoint.x - R + r,\n y: insidePoint.y < outsidePoint.y ? insidePoint.y + Q - q : insidePoint.y - Q + q\n };\n if (r === 0) {\n res.x = outsidePoint.x;\n res.y = outsidePoint.y;\n }\n if (R === 0) {\n res.x = outsidePoint.x;\n }\n if (Q === 0) {\n res.y = outsidePoint.y;\n }\n log.debug(`abc89 top/bottom calc, Q ${Q}, q ${q}, R ${R}, r ${r}`, res);\n return res;\n } else {\n if (insidePoint.x < outsidePoint.x) {\n r = outsidePoint.x - w - x;\n } else {\n r = x - w - outsidePoint.x;\n }\n let q = Q * r / R;\n let _x = insidePoint.x < outsidePoint.x ? insidePoint.x + R - r : insidePoint.x - R + r;\n let _y = insidePoint.y < outsidePoint.y ? insidePoint.y + q : insidePoint.y - q;\n log.debug(`sides calc abc89, Q ${Q}, q ${q}, R ${R}, r ${r}`, { _x, _y });\n if (r === 0) {\n _x = outsidePoint.x;\n _y = outsidePoint.y;\n }\n if (R === 0) {\n _x = outsidePoint.x;\n }\n if (Q === 0) {\n _y = outsidePoint.y;\n }\n return { x: _x, y: _y };\n }\n}, \"intersection\");\nvar cutPathAtIntersect = /* @__PURE__ */ __name((_points, boundaryNode) => {\n log.warn(\"abc88 cutPathAtIntersect\", _points, boundaryNode);\n let points = [];\n let lastPointOutside = _points[0];\n let isInside = false;\n _points.forEach((point2) => {\n log.info(\"abc88 checking point\", point2, boundaryNode);\n if (!outsideNode(boundaryNode, point2) && !isInside) {\n const inter = intersection(boundaryNode, lastPointOutside, point2);\n log.debug(\"abc88 inside\", point2, lastPointOutside, inter);\n log.debug(\"abc88 intersection\", inter, boundaryNode);\n let pointPresent = false;\n points.forEach((p) => {\n pointPresent = pointPresent || p.x === inter.x && p.y === inter.y;\n });\n if (!points.some((e) => e.x === inter.x && e.y === inter.y)) {\n points.push(inter);\n } else {\n log.warn(\"abc88 no intersect\", inter, points);\n }\n isInside = true;\n } else {\n log.warn(\"abc88 outside\", point2, lastPointOutside);\n lastPointOutside = point2;\n if (!isInside) {\n points.push(point2);\n }\n }\n });\n log.debug(\"returning points\", points);\n return points;\n}, \"cutPathAtIntersect\");\nfunction extractCornerPoints(points) {\n const cornerPoints = [];\n const cornerPointPositions = [];\n for (let i = 1; i < points.length - 1; i++) {\n const prev = points[i - 1];\n const curr = points[i];\n const next = points[i + 1];\n if (prev.x === curr.x && curr.y === next.y && Math.abs(curr.x - next.x) > 5 && Math.abs(curr.y - prev.y) > 5) {\n cornerPoints.push(curr);\n cornerPointPositions.push(i);\n } else if (prev.y === curr.y && curr.x === next.x && Math.abs(curr.x - prev.x) > 5 && Math.abs(curr.y - next.y) > 5) {\n cornerPoints.push(curr);\n cornerPointPositions.push(i);\n }\n }\n return { cornerPoints, cornerPointPositions };\n}\n__name(extractCornerPoints, \"extractCornerPoints\");\nvar findAdjacentPoint = /* @__PURE__ */ __name(function(pointA, pointB, distance) {\n const xDiff = pointB.x - pointA.x;\n const yDiff = pointB.y - pointA.y;\n const length = Math.sqrt(xDiff * xDiff + yDiff * yDiff);\n const ratio = distance / length;\n return { x: pointB.x - ratio * xDiff, y: pointB.y - ratio * yDiff };\n}, \"findAdjacentPoint\");\nvar fixCorners = /* @__PURE__ */ __name(function(lineData) {\n const { cornerPointPositions } = extractCornerPoints(lineData);\n const newLineData = [];\n for (let i = 0; i < lineData.length; i++) {\n if (cornerPointPositions.includes(i)) {\n const prevPoint = lineData[i - 1];\n const nextPoint = lineData[i + 1];\n const cornerPoint = lineData[i];\n const newPrevPoint = findAdjacentPoint(prevPoint, cornerPoint, 5);\n const newNextPoint = findAdjacentPoint(nextPoint, cornerPoint, 5);\n const xDiff = newNextPoint.x - newPrevPoint.x;\n const yDiff = newNextPoint.y - newPrevPoint.y;\n newLineData.push(newPrevPoint);\n const a = Math.sqrt(2) * 2;\n let newCornerPoint = { x: cornerPoint.x, y: cornerPoint.y };\n if (Math.abs(nextPoint.x - prevPoint.x) > 10 && Math.abs(nextPoint.y - prevPoint.y) >= 10) {\n log.debug(\n \"Corner point fixing\",\n Math.abs(nextPoint.x - prevPoint.x),\n Math.abs(nextPoint.y - prevPoint.y)\n );\n const r = 5;\n if (cornerPoint.x === newPrevPoint.x) {\n newCornerPoint = {\n x: xDiff < 0 ? newPrevPoint.x - r + a : newPrevPoint.x + r - a,\n y: yDiff < 0 ? newPrevPoint.y - a : newPrevPoint.y + a\n };\n } else {\n newCornerPoint = {\n x: xDiff < 0 ? newPrevPoint.x - a : newPrevPoint.x + a,\n y: yDiff < 0 ? newPrevPoint.y - r + a : newPrevPoint.y + r - a\n };\n }\n } else {\n log.debug(\n \"Corner point skipping fixing\",\n Math.abs(nextPoint.x - prevPoint.x),\n Math.abs(nextPoint.y - prevPoint.y)\n );\n }\n newLineData.push(newCornerPoint, newNextPoint);\n } else {\n newLineData.push(lineData[i]);\n }\n }\n return newLineData;\n}, \"fixCorners\");\nvar generateDashArray = /* @__PURE__ */ __name((len, oValueS, oValueE) => {\n const middleLength = len - oValueS - oValueE;\n const dashLength = 2;\n const gapLength = 2;\n const dashGapPairLength = dashLength + gapLength;\n const numberOfPairs = Math.floor(middleLength / dashGapPairLength);\n const middlePattern = Array(numberOfPairs).fill(`${dashLength} ${gapLength}`).join(\" \");\n const dashArray = `0 ${oValueS} ${middlePattern} ${oValueE}`;\n return dashArray;\n}, \"generateDashArray\");\nvar insertEdge = /* @__PURE__ */ __name(function(elem, edge, clusterDb, diagramType, startNode, endNode, id, skipIntersect = false) {\n const { handDrawnSeed } = getConfig();\n let points = edge.points;\n let pointsHasChanged = false;\n const tail = startNode;\n var head = endNode;\n const edgeClassStyles = [];\n for (const key in edge.cssCompiledStyles) {\n if (isLabelStyle(key)) {\n continue;\n }\n edgeClassStyles.push(edge.cssCompiledStyles[key]);\n }\n log.debug(\"UIO intersect check\", edge.points, head.x, tail.x);\n if (head.intersect && tail.intersect && !skipIntersect) {\n points = points.slice(1, edge.points.length - 1);\n points.unshift(tail.intersect(points[0]));\n log.debug(\n \"Last point UIO\",\n edge.start,\n \"-->\",\n edge.end,\n points[points.length - 1],\n head,\n head.intersect(points[points.length - 1])\n );\n points.push(head.intersect(points[points.length - 1]));\n }\n const pointsStr = btoa(JSON.stringify(points));\n if (edge.toCluster) {\n log.info(\"to cluster abc88\", clusterDb.get(edge.toCluster));\n points = cutPathAtIntersect(edge.points, clusterDb.get(edge.toCluster).node);\n pointsHasChanged = true;\n }\n if (edge.fromCluster) {\n log.debug(\n \"from cluster abc88\",\n clusterDb.get(edge.fromCluster),\n JSON.stringify(points, null, 2)\n );\n points = cutPathAtIntersect(points.reverse(), clusterDb.get(edge.fromCluster).node).reverse();\n pointsHasChanged = true;\n }\n let lineData = points.filter((p) => !Number.isNaN(p.y));\n lineData = fixCorners(lineData);\n let curve = curveBasis;\n curve = curveLinear;\n switch (edge.curve) {\n case \"linear\":\n curve = curveLinear;\n break;\n case \"basis\":\n curve = curveBasis;\n break;\n case \"cardinal\":\n curve = curveCardinal;\n break;\n case \"bumpX\":\n curve = curveBumpX;\n break;\n case \"bumpY\":\n curve = curveBumpY;\n break;\n case \"catmullRom\":\n curve = curveCatmullRom;\n break;\n case \"monotoneX\":\n curve = curveMonotoneX;\n break;\n case \"monotoneY\":\n curve = curveMonotoneY;\n break;\n case \"natural\":\n curve = curveNatural;\n break;\n case \"step\":\n curve = curveStep;\n break;\n case \"stepAfter\":\n curve = curveStepAfter;\n break;\n case \"stepBefore\":\n curve = curveStepBefore;\n break;\n default:\n curve = curveBasis;\n }\n const { x, y } = getLineFunctionsWithOffset(edge);\n const lineFunction = line().x(x).y(y).curve(curve);\n let strokeClasses;\n switch (edge.thickness) {\n case \"normal\":\n strokeClasses = \"edge-thickness-normal\";\n break;\n case \"thick\":\n strokeClasses = \"edge-thickness-thick\";\n break;\n case \"invisible\":\n strokeClasses = \"edge-thickness-invisible\";\n break;\n default:\n strokeClasses = \"edge-thickness-normal\";\n }\n switch (edge.pattern) {\n case \"solid\":\n strokeClasses += \" edge-pattern-solid\";\n break;\n case \"dotted\":\n strokeClasses += \" edge-pattern-dotted\";\n break;\n case \"dashed\":\n strokeClasses += \" edge-pattern-dashed\";\n break;\n default:\n strokeClasses += \" edge-pattern-solid\";\n }\n let svgPath;\n let linePath = edge.curve === \"rounded\" ? generateRoundedPath(applyMarkerOffsetsToPoints(lineData, edge), 5) : lineFunction(lineData);\n const edgeStyles = Array.isArray(edge.style) ? edge.style : [edge.style];\n let strokeColor = edgeStyles.find((style) => style?.startsWith(\"stroke:\"));\n let animatedEdge = false;\n if (edge.look === \"handDrawn\") {\n const rc = rough.svg(elem);\n Object.assign([], lineData);\n const svgPathNode = rc.path(linePath, {\n roughness: 0.3,\n seed: handDrawnSeed\n });\n strokeClasses += \" transition\";\n svgPath = select(svgPathNode).select(\"path\").attr(\"id\", edge.id).attr(\"class\", \" \" + strokeClasses + (edge.classes ? \" \" + edge.classes : \"\")).attr(\"style\", edgeStyles ? edgeStyles.reduce((acc, style) => acc + \";\" + style, \"\") : \"\");\n let d = svgPath.attr(\"d\");\n svgPath.attr(\"d\", d);\n elem.node().appendChild(svgPath.node());\n } else {\n const stylesFromClasses = edgeClassStyles.join(\";\");\n const styles = edgeStyles ? edgeStyles.reduce((acc, style) => acc + style + \";\", \"\") : \"\";\n let animationClass = \"\";\n if (edge.animate) {\n animationClass = \" edge-animation-fast\";\n }\n if (edge.animation) {\n animationClass = \" edge-animation-\" + edge.animation;\n }\n const pathStyle = (stylesFromClasses ? stylesFromClasses + \";\" + styles + \";\" : styles) + \";\" + (edgeStyles ? edgeStyles.reduce((acc, style) => acc + \";\" + style, \"\") : \"\");\n svgPath = elem.append(\"path\").attr(\"d\", linePath).attr(\"id\", edge.id).attr(\n \"class\",\n \" \" + strokeClasses + (edge.classes ? \" \" + edge.classes : \"\") + (animationClass ?? \"\")\n ).attr(\"style\", pathStyle);\n strokeColor = pathStyle.match(/stroke:([^;]+)/)?.[1];\n animatedEdge = edge.animate === true || !!edge.animation || stylesFromClasses.includes(\"animation\");\n const pathNode = svgPath.node();\n const len = typeof pathNode.getTotalLength === \"function\" ? pathNode.getTotalLength() : 0;\n const oValueS = markerOffsets2[edge.arrowTypeStart] || 0;\n const oValueE = markerOffsets2[edge.arrowTypeEnd] || 0;\n if (edge.look === \"neo\" && !animatedEdge) {\n const dashArray = edge.pattern === \"dotted\" || edge.pattern === \"dashed\" ? generateDashArray(len, oValueS, oValueE) : `0 ${oValueS} ${len - oValueS - oValueE} ${oValueE}`;\n const mOffset = `stroke-dasharray: ${dashArray}; stroke-dashoffset: 0;`;\n svgPath.attr(\"style\", mOffset + svgPath.attr(\"style\"));\n }\n }\n svgPath.attr(\"data-edge\", true);\n svgPath.attr(\"data-et\", \"edge\");\n svgPath.attr(\"data-id\", edge.id);\n svgPath.attr(\"data-points\", pointsStr);\n if (edge.showPoints) {\n lineData.forEach((point3) => {\n elem.append(\"circle\").style(\"stroke\", \"red\").style(\"fill\", \"red\").attr(\"r\", 1).attr(\"cx\", point3.x).attr(\"cy\", point3.y);\n });\n }\n let url = \"\";\n if (getConfig().flowchart.arrowMarkerAbsolute || getConfig().state.arrowMarkerAbsolute) {\n url = window.location.protocol + \"//\" + window.location.host + window.location.pathname + window.location.search;\n url = url.replace(/\\(/g, \"\\\\(\").replace(/\\)/g, \"\\\\)\");\n }\n log.info(\"arrowTypeStart\", edge.arrowTypeStart);\n log.info(\"arrowTypeEnd\", edge.arrowTypeEnd);\n addEdgeMarkers(svgPath, edge, url, id, diagramType, strokeColor);\n const midIndex = Math.floor(points.length / 2);\n const point2 = points[midIndex];\n if (!utils_default.isLabelCoordinateInPath(point2, svgPath.attr(\"d\"))) {\n pointsHasChanged = true;\n }\n let paths = {};\n if (pointsHasChanged) {\n paths.updatedPath = points;\n }\n paths.originalPath = edge.points;\n return paths;\n}, \"insertEdge\");\nfunction generateRoundedPath(points, radius) {\n if (points.length < 2) {\n return \"\";\n }\n let path = \"\";\n const size = points.length;\n const epsilon = 1e-5;\n for (let i = 0; i < size; i++) {\n const currPoint = points[i];\n const prevPoint = points[i - 1];\n const nextPoint = points[i + 1];\n if (i === 0) {\n path += `M${currPoint.x},${currPoint.y}`;\n } else if (i === size - 1) {\n path += `L${currPoint.x},${currPoint.y}`;\n } else {\n const dx1 = currPoint.x - prevPoint.x;\n const dy1 = currPoint.y - prevPoint.y;\n const dx2 = nextPoint.x - currPoint.x;\n const dy2 = nextPoint.y - currPoint.y;\n const len1 = Math.hypot(dx1, dy1);\n const len2 = Math.hypot(dx2, dy2);\n if (len1 < epsilon || len2 < epsilon) {\n path += `L${currPoint.x},${currPoint.y}`;\n continue;\n }\n const nx1 = dx1 / len1;\n const ny1 = dy1 / len1;\n const nx2 = dx2 / len2;\n const ny2 = dy2 / len2;\n const dot = nx1 * nx2 + ny1 * ny2;\n const clampedDot = Math.max(-1, Math.min(1, dot));\n const angle = Math.acos(clampedDot);\n if (angle < epsilon || Math.abs(Math.PI - angle) < epsilon) {\n path += `L${currPoint.x},${currPoint.y}`;\n continue;\n }\n const cutLen = Math.min(radius / Math.sin(angle / 2), len1 / 2, len2 / 2);\n const startX = currPoint.x - nx1 * cutLen;\n const startY = currPoint.y - ny1 * cutLen;\n const endX = currPoint.x + nx2 * cutLen;\n const endY = currPoint.y + ny2 * cutLen;\n path += `L${startX},${startY}`;\n path += `Q${currPoint.x},${currPoint.y} ${endX},${endY}`;\n }\n }\n return path;\n}\n__name(generateRoundedPath, \"generateRoundedPath\");\nfunction calculateDeltaAndAngle(point1, point2) {\n if (!point1 || !point2) {\n return { angle: 0, deltaX: 0, deltaY: 0 };\n }\n const deltaX = point2.x - point1.x;\n const deltaY = point2.y - point1.y;\n const angle = Math.atan2(deltaY, deltaX);\n return { angle, deltaX, deltaY };\n}\n__name(calculateDeltaAndAngle, \"calculateDeltaAndAngle\");\nfunction applyMarkerOffsetsToPoints(points, edge) {\n const newPoints = points.map((point2) => ({ ...point2 }));\n if (points.length >= 2 && markerOffsets[edge.arrowTypeStart]) {\n const offsetValue = markerOffsets[edge.arrowTypeStart];\n const point1 = points[0];\n const point2 = points[1];\n const { angle } = calculateDeltaAndAngle(point1, point2);\n const offsetX = offsetValue * Math.cos(angle);\n const offsetY = offsetValue * Math.sin(angle);\n newPoints[0].x = point1.x + offsetX;\n newPoints[0].y = point1.y + offsetY;\n }\n const n = points.length;\n if (n >= 2 && markerOffsets[edge.arrowTypeEnd]) {\n const offsetValue = markerOffsets[edge.arrowTypeEnd];\n const point1 = points[n - 1];\n const point2 = points[n - 2];\n const { angle } = calculateDeltaAndAngle(point2, point1);\n const offsetX = offsetValue * Math.cos(angle);\n const offsetY = offsetValue * Math.sin(angle);\n newPoints[n - 1].x = point1.x - offsetX;\n newPoints[n - 1].y = point1.y - offsetY;\n }\n return newPoints;\n}\n__name(applyMarkerOffsetsToPoints, \"applyMarkerOffsetsToPoints\");\n\n// src/rendering-util/rendering-elements/markers.js\nvar insertMarkers = /* @__PURE__ */ __name((elem, markerArray, type, id) => {\n markerArray.forEach((markerName) => {\n markers[markerName](elem, type, id);\n });\n}, \"insertMarkers\");\nvar extension = /* @__PURE__ */ __name((elem, type, id) => {\n log.trace(\"Making markers for \", id);\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-extensionStart\").attr(\"class\", \"marker extension \" + type).attr(\"refX\", 18).attr(\"refY\", 7).attr(\"markerWidth\", 190).attr(\"markerHeight\", 240).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 1,7 L18,13 V 1 Z\");\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-extensionEnd\").attr(\"class\", \"marker extension \" + type).attr(\"refX\", 1).attr(\"refY\", 7).attr(\"markerWidth\", 20).attr(\"markerHeight\", 28).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 1,1 V 13 L18,7 Z\");\n}, \"extension\");\nvar composition = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-compositionStart\").attr(\"class\", \"marker composition \" + type).attr(\"refX\", 18).attr(\"refY\", 7).attr(\"markerWidth\", 190).attr(\"markerHeight\", 240).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 18,7 L9,13 L1,7 L9,1 Z\");\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-compositionEnd\").attr(\"class\", \"marker composition \" + type).attr(\"refX\", 1).attr(\"refY\", 7).attr(\"markerWidth\", 20).attr(\"markerHeight\", 28).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 18,7 L9,13 L1,7 L9,1 Z\");\n}, \"composition\");\nvar aggregation = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-aggregationStart\").attr(\"class\", \"marker aggregation \" + type).attr(\"refX\", 18).attr(\"refY\", 7).attr(\"markerWidth\", 190).attr(\"markerHeight\", 240).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 18,7 L9,13 L1,7 L9,1 Z\");\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-aggregationEnd\").attr(\"class\", \"marker aggregation \" + type).attr(\"refX\", 1).attr(\"refY\", 7).attr(\"markerWidth\", 20).attr(\"markerHeight\", 28).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 18,7 L9,13 L1,7 L9,1 Z\");\n}, \"aggregation\");\nvar dependency = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-dependencyStart\").attr(\"class\", \"marker dependency \" + type).attr(\"refX\", 6).attr(\"refY\", 7).attr(\"markerWidth\", 190).attr(\"markerHeight\", 240).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 5,7 L9,13 L1,7 L9,1 Z\");\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-dependencyEnd\").attr(\"class\", \"marker dependency \" + type).attr(\"refX\", 13).attr(\"refY\", 7).attr(\"markerWidth\", 20).attr(\"markerHeight\", 28).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 18,7 L9,13 L14,7 L9,1 Z\");\n}, \"dependency\");\nvar lollipop = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-lollipopStart\").attr(\"class\", \"marker lollipop \" + type).attr(\"refX\", 13).attr(\"refY\", 7).attr(\"markerWidth\", 190).attr(\"markerHeight\", 240).attr(\"orient\", \"auto\").append(\"circle\").attr(\"stroke\", \"black\").attr(\"fill\", \"transparent\").attr(\"cx\", 7).attr(\"cy\", 7).attr(\"r\", 6);\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-lollipopEnd\").attr(\"class\", \"marker lollipop \" + type).attr(\"refX\", 1).attr(\"refY\", 7).attr(\"markerWidth\", 190).attr(\"markerHeight\", 240).attr(\"orient\", \"auto\").append(\"circle\").attr(\"stroke\", \"black\").attr(\"fill\", \"transparent\").attr(\"cx\", 7).attr(\"cy\", 7).attr(\"r\", 6);\n}, \"lollipop\");\nvar point = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"marker\").attr(\"id\", id + \"_\" + type + \"-pointEnd\").attr(\"class\", \"marker \" + type).attr(\"viewBox\", \"0 0 10 10\").attr(\"refX\", 5).attr(\"refY\", 5).attr(\"markerUnits\", \"userSpaceOnUse\").attr(\"markerWidth\", 8).attr(\"markerHeight\", 8).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 0 0 L 10 5 L 0 10 z\").attr(\"class\", \"arrowMarkerPath\").style(\"stroke-width\", 1).style(\"stroke-dasharray\", \"1,0\");\n elem.append(\"marker\").attr(\"id\", id + \"_\" + type + \"-pointStart\").attr(\"class\", \"marker \" + type).attr(\"viewBox\", \"0 0 10 10\").attr(\"refX\", 4.5).attr(\"refY\", 5).attr(\"markerUnits\", \"userSpaceOnUse\").attr(\"markerWidth\", 8).attr(\"markerHeight\", 8).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 0 5 L 10 10 L 10 0 z\").attr(\"class\", \"arrowMarkerPath\").style(\"stroke-width\", 1).style(\"stroke-dasharray\", \"1,0\");\n}, \"point\");\nvar circle = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"marker\").attr(\"id\", id + \"_\" + type + \"-circleEnd\").attr(\"class\", \"marker \" + type).attr(\"viewBox\", \"0 0 10 10\").attr(\"refX\", 11).attr(\"refY\", 5).attr(\"markerUnits\", \"userSpaceOnUse\").attr(\"markerWidth\", 11).attr(\"markerHeight\", 11).attr(\"orient\", \"auto\").append(\"circle\").attr(\"cx\", \"5\").attr(\"cy\", \"5\").attr(\"r\", \"5\").attr(\"class\", \"arrowMarkerPath\").style(\"stroke-width\", 1).style(\"stroke-dasharray\", \"1,0\");\n elem.append(\"marker\").attr(\"id\", id + \"_\" + type + \"-circleStart\").attr(\"class\", \"marker \" + type).attr(\"viewBox\", \"0 0 10 10\").attr(\"refX\", -1).attr(\"refY\", 5).attr(\"markerUnits\", \"userSpaceOnUse\").attr(\"markerWidth\", 11).attr(\"markerHeight\", 11).attr(\"orient\", \"auto\").append(\"circle\").attr(\"cx\", \"5\").attr(\"cy\", \"5\").attr(\"r\", \"5\").attr(\"class\", \"arrowMarkerPath\").style(\"stroke-width\", 1).style(\"stroke-dasharray\", \"1,0\");\n}, \"circle\");\nvar cross = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"marker\").attr(\"id\", id + \"_\" + type + \"-crossEnd\").attr(\"class\", \"marker cross \" + type).attr(\"viewBox\", \"0 0 11 11\").attr(\"refX\", 12).attr(\"refY\", 5.2).attr(\"markerUnits\", \"userSpaceOnUse\").attr(\"markerWidth\", 11).attr(\"markerHeight\", 11).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 1,1 l 9,9 M 10,1 l -9,9\").attr(\"class\", \"arrowMarkerPath\").style(\"stroke-width\", 2).style(\"stroke-dasharray\", \"1,0\");\n elem.append(\"marker\").attr(\"id\", id + \"_\" + type + \"-crossStart\").attr(\"class\", \"marker cross \" + type).attr(\"viewBox\", \"0 0 11 11\").attr(\"refX\", -1).attr(\"refY\", 5.2).attr(\"markerUnits\", \"userSpaceOnUse\").attr(\"markerWidth\", 11).attr(\"markerHeight\", 11).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 1,1 l 9,9 M 10,1 l -9,9\").attr(\"class\", \"arrowMarkerPath\").style(\"stroke-width\", 2).style(\"stroke-dasharray\", \"1,0\");\n}, \"cross\");\nvar barb = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-barbEnd\").attr(\"refX\", 19).attr(\"refY\", 7).attr(\"markerWidth\", 20).attr(\"markerHeight\", 14).attr(\"markerUnits\", \"userSpaceOnUse\").attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M 19,7 L9,13 L14,7 L9,1 Z\");\n}, \"barb\");\nvar only_one = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-onlyOneStart\").attr(\"class\", \"marker onlyOne \" + type).attr(\"refX\", 0).attr(\"refY\", 9).attr(\"markerWidth\", 18).attr(\"markerHeight\", 18).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M9,0 L9,18 M15,0 L15,18\");\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-onlyOneEnd\").attr(\"class\", \"marker onlyOne \" + type).attr(\"refX\", 18).attr(\"refY\", 9).attr(\"markerWidth\", 18).attr(\"markerHeight\", 18).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M3,0 L3,18 M9,0 L9,18\");\n}, \"only_one\");\nvar zero_or_one = /* @__PURE__ */ __name((elem, type, id) => {\n const startMarker = elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-zeroOrOneStart\").attr(\"class\", \"marker zeroOrOne \" + type).attr(\"refX\", 0).attr(\"refY\", 9).attr(\"markerWidth\", 30).attr(\"markerHeight\", 18).attr(\"orient\", \"auto\");\n startMarker.append(\"circle\").attr(\"fill\", \"white\").attr(\"cx\", 21).attr(\"cy\", 9).attr(\"r\", 6);\n startMarker.append(\"path\").attr(\"d\", \"M9,0 L9,18\");\n const endMarker = elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-zeroOrOneEnd\").attr(\"class\", \"marker zeroOrOne \" + type).attr(\"refX\", 30).attr(\"refY\", 9).attr(\"markerWidth\", 30).attr(\"markerHeight\", 18).attr(\"orient\", \"auto\");\n endMarker.append(\"circle\").attr(\"fill\", \"white\").attr(\"cx\", 9).attr(\"cy\", 9).attr(\"r\", 6);\n endMarker.append(\"path\").attr(\"d\", \"M21,0 L21,18\");\n}, \"zero_or_one\");\nvar one_or_more = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-oneOrMoreStart\").attr(\"class\", \"marker oneOrMore \" + type).attr(\"refX\", 18).attr(\"refY\", 18).attr(\"markerWidth\", 45).attr(\"markerHeight\", 36).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M0,18 Q 18,0 36,18 Q 18,36 0,18 M42,9 L42,27\");\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-oneOrMoreEnd\").attr(\"class\", \"marker oneOrMore \" + type).attr(\"refX\", 27).attr(\"refY\", 18).attr(\"markerWidth\", 45).attr(\"markerHeight\", 36).attr(\"orient\", \"auto\").append(\"path\").attr(\"d\", \"M3,9 L3,27 M9,18 Q27,0 45,18 Q27,36 9,18\");\n}, \"one_or_more\");\nvar zero_or_more = /* @__PURE__ */ __name((elem, type, id) => {\n const startMarker = elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-zeroOrMoreStart\").attr(\"class\", \"marker zeroOrMore \" + type).attr(\"refX\", 18).attr(\"refY\", 18).attr(\"markerWidth\", 57).attr(\"markerHeight\", 36).attr(\"orient\", \"auto\");\n startMarker.append(\"circle\").attr(\"fill\", \"white\").attr(\"cx\", 48).attr(\"cy\", 18).attr(\"r\", 6);\n startMarker.append(\"path\").attr(\"d\", \"M0,18 Q18,0 36,18 Q18,36 0,18\");\n const endMarker = elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-zeroOrMoreEnd\").attr(\"class\", \"marker zeroOrMore \" + type).attr(\"refX\", 39).attr(\"refY\", 18).attr(\"markerWidth\", 57).attr(\"markerHeight\", 36).attr(\"orient\", \"auto\");\n endMarker.append(\"circle\").attr(\"fill\", \"white\").attr(\"cx\", 9).attr(\"cy\", 18).attr(\"r\", 6);\n endMarker.append(\"path\").attr(\"d\", \"M21,18 Q39,0 57,18 Q39,36 21,18\");\n}, \"zero_or_more\");\nvar requirement_arrow = /* @__PURE__ */ __name((elem, type, id) => {\n elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-requirement_arrowEnd\").attr(\"refX\", 20).attr(\"refY\", 10).attr(\"markerWidth\", 20).attr(\"markerHeight\", 20).attr(\"orient\", \"auto\").append(\"path\").attr(\n \"d\",\n `M0,0\n L20,10\n M20,10\n L0,20`\n );\n}, \"requirement_arrow\");\nvar requirement_contains = /* @__PURE__ */ __name((elem, type, id) => {\n const containsNode = elem.append(\"defs\").append(\"marker\").attr(\"id\", id + \"_\" + type + \"-requirement_containsStart\").attr(\"refX\", 0).attr(\"refY\", 10).attr(\"markerWidth\", 20).attr(\"markerHeight\", 20).attr(\"orient\", \"auto\").append(\"g\");\n containsNode.append(\"circle\").attr(\"cx\", 10).attr(\"cy\", 10).attr(\"r\", 9).attr(\"fill\", \"none\");\n containsNode.append(\"line\").attr(\"x1\", 1).attr(\"x2\", 19).attr(\"y1\", 10).attr(\"y2\", 10);\n containsNode.append(\"line\").attr(\"y1\", 1).attr(\"y2\", 19).attr(\"x1\", 10).attr(\"x2\", 10);\n}, \"requirement_contains\");\nvar markers = {\n extension,\n composition,\n aggregation,\n dependency,\n lollipop,\n point,\n circle,\n cross,\n barb,\n only_one,\n zero_or_one,\n one_or_more,\n zero_or_more,\n requirement_arrow,\n requirement_contains\n};\nvar markers_default = insertMarkers;\n\nexport {\n clear,\n insertEdgeLabel,\n positionEdgeLabel,\n insertEdge,\n markers_default\n};\n"], + "mappings": "+fAkDA,IAAIA,GAAiCC,EAAO,CAACC,EAASC,EAAMC,EAAKC,EAAIC,EAAaC,IAAgB,CAC5FJ,EAAK,gBACPK,GAAcN,EAAS,QAASC,EAAK,eAAgBC,EAAKC,EAAIC,EAAaC,CAAW,EAEpFJ,EAAK,cACPK,GAAcN,EAAS,MAAOC,EAAK,aAAcC,EAAKC,EAAIC,EAAaC,CAAW,CAEtF,EAAG,gBAAgB,EACfE,GAAgB,CAClB,YAAa,CAAE,KAAM,QAAS,KAAM,EAAM,EAC1C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AC,EAAE,KAAK,OAAQ,EAAE,EAAE,KAAK,cAAe,EAAE,EAAE,KAAK,eAAgB,EAAE,EAAE,KAAK,SAAU,MAAM,EAAE,OAAO,GAAG,EACxOoB,EAAa,OAAO,QAAQ,EAAE,KAAK,KAAM,EAAE,EAAE,KAAK,KAAM,EAAE,EAAE,KAAK,IAAK,CAAC,EAAE,KAAK,OAAQ,MAAM,EAC5FA,EAAa,OAAO,MAAM,EAAE,KAAK,KAAM,CAAC,EAAE,KAAK,KAAM,EAAE,EAAE,KAAK,KAAM,EAAE,EAAE,KAAK,KAAM,EAAE,EACrFA,EAAa,OAAO,MAAM,EAAE,KAAK,KAAM,CAAC,EAAE,KAAK,KAAM,EAAE,EAAE,KAAK,KAAM,EAAE,EAAE,KAAK,KAAM,EAAE,CACvF,EAAG,sBAAsB,EACrBlB,GAAU,CACZ,UAAAC,GACA,YAAAC,GACA,YAAAC,GACA,WAAAC,GACA,SAAAC,GACA,MAAAC,GACA,OAAAC,GACA,MAAAC,GACA,KAAAC,GACA,SAAAC,GACA,YAAAC,GACA,YAAAG,GACA,aAAAC,GACA,kBAAAC,GACA,qBAAAC,EACF,EACIE,GAAkBvB", + "names": ["addEdgeMarkers", "__name", "svgPath", "edge", "url", "id", "diagramType", "strokeColor", "addEdgeMarker", "arrowTypesMap", "position", "arrowType", "arrowTypeInfo", "log", "endMarkerType", "originalMarkerId", "colorId", "coloredMarkerId", "originalMarker", "coloredMarker", "path", "edgeLabels", "terminalLabels", "clear", "getLabelStyles", "styleArray", "acc", "style", "insertEdgeLabel", "elem", "useHtmlLabels", "evaluate", "getConfig2", "labelStyles", "styles2String", "labelElement", "createText", "edgeLabel", "label", "bbox", "div", "dv", "select_default", "fo", "startLabelElement", "createLabel_default", "startEdgeLabelLeft", "inner", "slBox", "setTerminalWidth", "startEdgeLabelRight", "endLabelElement", "endEdgeLabelLeft", "endEdgeLabelRight", "value", "positionEdgeLabel", "paths", "siteConfig", "subGraphTitleTotalMargin", "getSubGraphTitleMargins", "el", "x", "y", "pos", "utils_default", "outsideNode", "node", "point2", "dx", "dy", "w", "h", "intersection", "outsidePoint", "insidePoint", "r", "Q", "R", "q", "res", "_x", "_y", "cutPathAtIntersect", "_points", "boundaryNode", "points", "lastPointOutside", "isInside", "inter", "pointPresent", "p", "e", "extractCornerPoints", "cornerPoints", "cornerPointPositions", "i", "prev", "curr", "next", "findAdjacentPoint", "pointA", "pointB", "distance", "xDiff", "yDiff", "length", "ratio", "fixCorners", "lineData", "newLineData", "prevPoint", "nextPoint", "cornerPoint", "newPrevPoint", "newNextPoint", "a", "newCornerPoint", "generateDashArray", "len", "oValueS", "oValueE", "middleLength", "dashLength", "gapLength", "dashGapPairLength", "numberOfPairs", "middlePattern", "insertEdge", "clusterDb", "startNode", "endNode", "skipIntersect", "handDrawnSeed", "pointsHasChanged", "tail", "head", "edgeClassStyles", "key", "isLabelStyle", "pointsStr", "curve", "basis_default", "linear_default", "cardinal_default", "bumpX", "bumpY", "catmullRom_default", "monotoneX", "monotoneY", "natural_default", "step_default", "stepAfter", "stepBefore", "getLineFunctionsWithOffset", "lineFunction", "line_default", "strokeClasses", "linePath", "generateRoundedPath", "applyMarkerOffsetsToPoints", "edgeStyles", "animatedEdge", "rc", "at", "svgPathNode", "d", "stylesFromClasses", "styles", "animationClass", "pathStyle", "pathNode", "markerOffsets2", "mOffset", "point3", "midIndex", "radius", "size", "epsilon", "currPoint", "dx1", "dy1", "dx2", "dy2", "len1", "len2", "nx1", "ny1", "nx2", "ny2", "dot", "clampedDot", "angle", "cutLen", "startX", "startY", "endX", "endY", "calculateDeltaAndAngle", "point1", "deltaX", "deltaY", "newPoints", "markerOffsets", "offsetValue", "offsetX", "offsetY", "n", "insertMarkers", "markerArray", "type", "markerName", "markers", "extension", "composition", "aggregation", "dependency", "lollipop", "point", "circle", "cross", "barb", "only_one", "zero_or_one", "startMarker", "endMarker", "one_or_more", "zero_or_more", "requirement_arrow", "requirement_contains", "containsNode", "markers_default"] +} diff --git a/docs/website/public/chunk-RW2M4WKC.min.js b/docs/website/public/chunk-RW2M4WKC.min.js new file mode 100644 index 000000000..3118e89c5 --- /dev/null +++ b/docs/website/public/chunk-RW2M4WKC.min.js @@ -0,0 +1,2 @@ +import{b as t}from"./chunk-6TVUEPFY.min.js";var s=class{constructor(i){this.init=i,this.records=this.init()}static{t(this,"ImperativeState")}reset(){this.records=this.init()}};export{s as a}; +//# sourceMappingURL=chunk-RW2M4WKC.min.js.map diff --git a/docs/website/public/chunk-RW2M4WKC.min.js.map b/docs/website/public/chunk-RW2M4WKC.min.js.map new file mode 100644 index 000000000..a708c7f42 --- /dev/null +++ b/docs/website/public/chunk-RW2M4WKC.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/mermaid/dist/chunks/mermaid.core/chunk-QZHKN3VN.mjs"], + "sourcesContent": ["import {\n __name\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/utils/imperativeState.ts\nvar ImperativeState = class {\n /**\n * @param init - Function that creates the default state.\n */\n constructor(init) {\n this.init = init;\n this.records = this.init();\n }\n static {\n __name(this, \"ImperativeState\");\n }\n reset() {\n this.records = this.init();\n }\n};\n\nexport {\n ImperativeState\n};\n"], + "mappings": "4CAKA,IAAIA,EAAkB,KAAM,CAI1B,YAAYC,EAAM,CAChB,KAAK,KAAOA,EACZ,KAAK,QAAU,KAAK,KAAK,CAC3B,CACA,MAAO,CACLC,EAAO,KAAM,iBAAiB,CAChC,CACA,OAAQ,CACN,KAAK,QAAU,KAAK,KAAK,CAC3B,CACF", + "names": ["ImperativeState", "init", "__name"] +} diff --git a/docs/website/public/chunk-V3WVIUUL.min.js b/docs/website/public/chunk-V3WVIUUL.min.js new file mode 100644 index 000000000..27fcebd23 --- /dev/null +++ b/docs/website/public/chunk-V3WVIUUL.min.js @@ -0,0 +1,2 @@ +import{b as i}from"./chunk-6TVUEPFY.min.js";function t(c,e){c.accDescr&&e.setAccDescription?.(c.accDescr),c.accTitle&&e.setAccTitle?.(c.accTitle),c.title&&e.setDiagramTitle?.(c.title)}i(t,"populateCommonDb");export{t as a}; +//# sourceMappingURL=chunk-V3WVIUUL.min.js.map diff --git a/docs/website/public/chunk-V3WVIUUL.min.js.map b/docs/website/public/chunk-V3WVIUUL.min.js.map new file mode 100644 index 000000000..acb6a7e4f --- /dev/null +++ b/docs/website/public/chunk-V3WVIUUL.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/mermaid/dist/chunks/mermaid.core/chunk-4BX2VUAB.mjs"], + "sourcesContent": ["import {\n __name\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/diagrams/common/populateCommonDb.ts\nfunction populateCommonDb(ast, db) {\n if (ast.accDescr) {\n db.setAccDescription?.(ast.accDescr);\n }\n if (ast.accTitle) {\n db.setAccTitle?.(ast.accTitle);\n }\n if (ast.title) {\n db.setDiagramTitle?.(ast.title);\n }\n}\n__name(populateCommonDb, \"populateCommonDb\");\n\nexport {\n populateCommonDb\n};\n"], + "mappings": "4CAKA,SAASA,EAAiBC,EAAKC,EAAI,CAC7BD,EAAI,UACNC,EAAG,oBAAoBD,EAAI,QAAQ,EAEjCA,EAAI,UACNC,EAAG,cAAcD,EAAI,QAAQ,EAE3BA,EAAI,OACNC,EAAG,kBAAkBD,EAAI,KAAK,CAElC,CACAE,EAAOH,EAAkB,kBAAkB", + "names": ["populateCommonDb", "ast", "db", "__name"] +} diff --git a/docs/website/public/chunk-VTDY5BYI.min.js b/docs/website/public/chunk-VTDY5BYI.min.js new file mode 100644 index 000000000..8e836ba6f --- /dev/null +++ b/docs/website/public/chunk-VTDY5BYI.min.js @@ -0,0 +1,2 @@ +import{b as u,c as y,d as f,e as p}from"./chunk-RSZXG5PP.min.js";import{b as m,e as g,h as d}from"./chunk-IDQ2RCY2.min.js";import{c as s}from"./chunk-QZZKR5JD.min.js";import{K as l,y as n}from"./chunk-3EE2TK35.min.js";import{b as o,d as a}from"./chunk-6TVUEPFY.min.js";var h={common:l,getConfig:n,insertCluster:g,insertEdge:f,insertEdgeLabel:u,insertMarkers:p,insertNode:d,interpolateToCurve:s,labelHelper:m,log:a,positionEdgeLabel:y},t={},L=o(r=>{for(let e of r)t[e.name]=e},"registerLayoutLoaders"),w=o(()=>{L([{name:"dagre",loader:o(async()=>await import("./dagre-6UL2VRFP-I4QKSU5B.min.js"),"loader")},{name:"cose-bilkent",loader:o(async()=>await import("./cose-bilkent-S5V4N54A-HENZWBLB.min.js"),"loader")}])},"registerDefaultLayoutLoaders");w();var _=o(async(r,e)=>{if(!(r.layoutAlgorithm in t))throw new Error(`Unknown layout algorithm: ${r.layoutAlgorithm}`);let i=t[r.layoutAlgorithm];return(await i.loader()).render(r,e,h,{algorithm:i.algorithm})},"render"),C=o((r="",{fallback:e="dagre"}={})=>{if(r in t)return r;if(e in t)return a.warn(`Layout algorithm ${r} is not registered. Using ${e} as fallback.`),e;throw new Error(`Both layout algorithms ${r} and ${e} are not registered.`)},"getRegisteredLayoutAlgorithm");export{L as a,_ as b,C as c}; +//# sourceMappingURL=chunk-VTDY5BYI.min.js.map diff --git a/docs/website/public/chunk-VTDY5BYI.min.js.map b/docs/website/public/chunk-VTDY5BYI.min.js.map new file mode 100644 index 000000000..6e3049909 --- /dev/null +++ b/docs/website/public/chunk-VTDY5BYI.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/mermaid/dist/chunks/mermaid.core/chunk-N4CR4FBY.mjs"], + "sourcesContent": ["import {\n insertEdge,\n insertEdgeLabel,\n markers_default,\n positionEdgeLabel\n} from \"./chunk-QXUST7PY.mjs\";\nimport {\n insertCluster,\n insertNode,\n labelHelper\n} from \"./chunk-JZLCHNYA.mjs\";\nimport {\n interpolateToCurve\n} from \"./chunk-S3R3BYOJ.mjs\";\nimport {\n common_default,\n getConfig\n} from \"./chunk-ABZYJK2D.mjs\";\nimport {\n __name,\n log\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/internals.ts\nvar internalHelpers = {\n common: common_default,\n getConfig,\n insertCluster,\n insertEdge,\n insertEdgeLabel,\n insertMarkers: markers_default,\n insertNode,\n interpolateToCurve,\n labelHelper,\n log,\n positionEdgeLabel\n};\n\n// src/rendering-util/render.ts\nvar layoutAlgorithms = {};\nvar registerLayoutLoaders = /* @__PURE__ */ __name((loaders) => {\n for (const loader of loaders) {\n layoutAlgorithms[loader.name] = loader;\n }\n}, \"registerLayoutLoaders\");\nvar registerDefaultLayoutLoaders = /* @__PURE__ */ __name(() => {\n registerLayoutLoaders([\n {\n name: \"dagre\",\n loader: /* @__PURE__ */ __name(async () => await import(\"./dagre-6UL2VRFP.mjs\"), \"loader\")\n },\n ...true ? [\n {\n name: \"cose-bilkent\",\n loader: /* @__PURE__ */ __name(async () => await import(\"./cose-bilkent-S5V4N54A.mjs\"), \"loader\")\n }\n ] : []\n ]);\n}, \"registerDefaultLayoutLoaders\");\nregisterDefaultLayoutLoaders();\nvar render = /* @__PURE__ */ __name(async (data4Layout, svg) => {\n if (!(data4Layout.layoutAlgorithm in layoutAlgorithms)) {\n throw new Error(`Unknown layout algorithm: ${data4Layout.layoutAlgorithm}`);\n }\n const layoutDefinition = layoutAlgorithms[data4Layout.layoutAlgorithm];\n const layoutRenderer = await layoutDefinition.loader();\n return layoutRenderer.render(data4Layout, svg, internalHelpers, {\n algorithm: layoutDefinition.algorithm\n });\n}, \"render\");\nvar getRegisteredLayoutAlgorithm = /* @__PURE__ */ __name((algorithm = \"\", { fallback = \"dagre\" } = {}) => {\n if (algorithm in layoutAlgorithms) {\n return algorithm;\n }\n if (fallback in layoutAlgorithms) {\n log.warn(`Layout algorithm ${algorithm} is not registered. Using ${fallback} as fallback.`);\n return fallback;\n }\n throw new Error(`Both layout algorithms ${algorithm} and ${fallback} are not registered.`);\n}, \"getRegisteredLayoutAlgorithm\");\n\nexport {\n registerLayoutLoaders,\n render,\n getRegisteredLayoutAlgorithm\n};\n"], + "mappings": "6QAwBA,IAAIA,EAAkB,CACpB,OAAQC,EACR,UAAAC,EACA,cAAAC,EACA,WAAAC,EACA,gBAAAC,EACA,cAAeC,EACf,WAAAC,EACA,mBAAAC,EACA,YAAAC,EACA,IAAAC,EACA,kBAAAC,CACF,EAGIC,EAAmB,CAAC,EACpBC,EAAwCC,EAAQC,GAAY,CAC9D,QAAWC,KAAUD,EACnBH,EAAiBI,EAAO,IAAI,EAAIA,CAEpC,EAAG,uBAAuB,EACtBC,EAA+CH,EAAO,IAAM,CAC9DD,EAAsB,CACpB,CACE,KAAM,QACN,OAAwBC,EAAO,SAAY,KAAM,QAAO,kCAAsB,EAAG,QAAQ,CAC3F,EAEE,CACE,KAAM,eACN,OAAwBA,EAAO,SAAY,KAAM,QAAO,yCAA6B,EAAG,QAAQ,CAClG,CAEJ,CAAC,CACH,EAAG,8BAA8B,EACjCG,EAA6B,EAC7B,IAAIC,EAAyBJ,EAAO,MAAOK,EAAaC,IAAQ,CAC9D,GAAI,EAAED,EAAY,mBAAmBP,GACnC,MAAM,IAAI,MAAM,6BAA6BO,EAAY,eAAe,EAAE,EAE5E,IAAME,EAAmBT,EAAiBO,EAAY,eAAe,EAErE,OADuB,MAAME,EAAiB,OAAO,GAC/B,OAAOF,EAAaC,EAAKpB,EAAiB,CAC9D,UAAWqB,EAAiB,SAC9B,CAAC,CACH,EAAG,QAAQ,EACPC,EAA+CR,EAAO,CAACS,EAAY,GAAI,CAAE,SAAAC,EAAW,OAAQ,EAAI,CAAC,IAAM,CACzG,GAAID,KAAaX,EACf,OAAOW,EAET,GAAIC,KAAYZ,EACd,OAAAF,EAAI,KAAK,oBAAoBa,CAAS,6BAA6BC,CAAQ,eAAe,EACnFA,EAET,MAAM,IAAI,MAAM,0BAA0BD,CAAS,QAAQC,CAAQ,sBAAsB,CAC3F,EAAG,8BAA8B", + "names": ["internalHelpers", "common_default", "getConfig", "insertCluster", "insertEdge", "insertEdgeLabel", "markers_default", "insertNode", "interpolateToCurve", "labelHelper", "log", "positionEdgeLabel", "layoutAlgorithms", "registerLayoutLoaders", "__name", "loaders", "loader", "registerDefaultLayoutLoaders", "render", "data4Layout", "svg", "layoutDefinition", "getRegisteredLayoutAlgorithm", "algorithm", "fallback"] +} diff --git a/docs/website/public/chunk-VUATWGGE.min.js b/docs/website/public/chunk-VUATWGGE.min.js new file mode 100644 index 000000000..2cf2de5b3 --- /dev/null +++ b/docs/website/public/chunk-VUATWGGE.min.js @@ -0,0 +1,2 @@ +import{D as a,L as O,Q as C,b as u,n as o,p as f,z as m}from"./chunk-R5JLOOQ4.min.js";import{d as E}from"./chunk-PTL4EUOE.min.js";import{O as c,e as b}from"./chunk-E5F23VE2.min.js";var j="\0",_="\0",N="",p=class{constructor(e={}){this._isDirected=Object.prototype.hasOwnProperty.call(e,"directed")?e.directed:!0,this._isMultigraph=Object.prototype.hasOwnProperty.call(e,"multigraph")?e.multigraph:!1,this._isCompound=Object.prototype.hasOwnProperty.call(e,"compound")?e.compound:!1,this._label=void 0,this._defaultNodeLabelFn=c(void 0),this._defaultEdgeLabelFn=c(void 0),this._nodes={},this._isCompound&&(this._parent={},this._children={},this._children[_]={}),this._in={},this._preds={},this._out={},this._sucs={},this._edgeObjs={},this._edgeLabels={}}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(e){return this._label=e,this}graph(){return this._label}setDefaultNodeLabel(e){return b(e)||(e=c(e)),this._defaultNodeLabelFn=e,this}nodeCount(){return this._nodeCount}nodes(){return u(this._nodes)}sources(){var e=this;return f(this.nodes(),function(t){return E(e._in[t])})}sinks(){var e=this;return f(this.nodes(),function(t){return E(e._out[t])})}setNodes(e,t){var s=arguments,i=this;return o(e,function(r){s.length>1?i.setNode(r,t):i.setNode(r)}),this}setNode(e,t){return Object.prototype.hasOwnProperty.call(this._nodes,e)?(arguments.length>1&&(this._nodes[e]=t),this):(this._nodes[e]=arguments.length>1?t:this._defaultNodeLabelFn(e),this._isCompound&&(this._parent[e]=_,this._children[e]={},this._children[_][e]=!0),this._in[e]={},this._preds[e]={},this._out[e]={},this._sucs[e]={},++this._nodeCount,this)}node(e){return this._nodes[e]}hasNode(e){return Object.prototype.hasOwnProperty.call(this._nodes,e)}removeNode(e){if(Object.prototype.hasOwnProperty.call(this._nodes,e)){var t=s=>this.removeEdge(this._edgeObjs[s]);delete this._nodes[e],this._isCompound&&(this._removeFromParentsChildList(e),delete this._parent[e],o(this.children(e),s=>{this.setParent(s)}),delete this._children[e]),o(u(this._in[e]),t),delete this._in[e],delete this._preds[e],o(u(this._out[e]),t),delete this._out[e],delete this._sucs[e],--this._nodeCount}return this}setParent(e,t){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(a(t))t=_;else{t+="";for(var s=t;!a(s);s=this.parent(s))if(s===e)throw new Error("Setting "+t+" as parent of "+e+" would create a cycle");this.setNode(t)}return this.setNode(e),this._removeFromParentsChildList(e),this._parent[e]=t,this._children[t][e]=!0,this}_removeFromParentsChildList(e){delete this._children[this._parent[e]][e]}parent(e){if(this._isCompound){var t=this._parent[e];if(t!==_)return t}}children(e){if(a(e)&&(e=_),this._isCompound){var t=this._children[e];if(t)return u(t)}else{if(e===_)return this.nodes();if(this.hasNode(e))return[]}}predecessors(e){var t=this._preds[e];if(t)return u(t)}successors(e){var t=this._sucs[e];if(t)return u(t)}neighbors(e){var t=this.predecessors(e);if(t)return C(t,this.successors(e))}isLeaf(e){var t;return this.isDirected()?t=this.successors(e):t=this.neighbors(e),t.length===0}filterNodes(e){var t=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});t.setGraph(this.graph());var s=this;o(this._nodes,function(n,h){e(h)&&t.setNode(h,n)}),o(this._edgeObjs,function(n){t.hasNode(n.v)&&t.hasNode(n.w)&&t.setEdge(n,s.edge(n))});var i={};function r(n){var h=s.parent(n);return h===void 0||t.hasNode(h)?(i[n]=h,h):h in i?i[h]:r(h)}return this._isCompound&&o(t.nodes(),function(n){t.setParent(n,r(n))}),t}setDefaultEdgeLabel(e){return b(e)||(e=c(e)),this._defaultEdgeLabelFn=e,this}edgeCount(){return this._edgeCount}edges(){return m(this._edgeObjs)}setPath(e,t){var s=this,i=arguments;return O(e,function(r,n){return i.length>1?s.setEdge(r,n,t):s.setEdge(r,n),n}),this}setEdge(){var e,t,s,i,r=!1,n=arguments[0];typeof n=="object"&&n!==null&&"v"in n?(e=n.v,t=n.w,s=n.name,arguments.length===2&&(i=arguments[1],r=!0)):(e=n,t=arguments[1],s=arguments[3],arguments.length>2&&(i=arguments[2],r=!0)),e=""+e,t=""+t,a(s)||(s=""+s);var h=g(this._isDirected,e,t,s);if(Object.prototype.hasOwnProperty.call(this._edgeLabels,h))return r&&(this._edgeLabels[h]=i),this;if(!a(s)&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(e),this.setNode(t),this._edgeLabels[h]=r?i:this._defaultEdgeLabelFn(e,t,s);var l=P(this._isDirected,e,t,s);return e=l.v,t=l.w,Object.freeze(l),this._edgeObjs[h]=l,v(this._preds[t],e),v(this._sucs[e],t),this._in[t][h]=l,this._out[e][h]=l,this._edgeCount++,this}edge(e,t,s){var i=arguments.length===1?y(this._isDirected,arguments[0]):g(this._isDirected,e,t,s);return this._edgeLabels[i]}hasEdge(e,t,s){var i=arguments.length===1?y(this._isDirected,arguments[0]):g(this._isDirected,e,t,s);return Object.prototype.hasOwnProperty.call(this._edgeLabels,i)}removeEdge(e,t,s){var i=arguments.length===1?y(this._isDirected,arguments[0]):g(this._isDirected,e,t,s),r=this._edgeObjs[i];return r&&(e=r.v,t=r.w,delete this._edgeLabels[i],delete this._edgeObjs[i],L(this._preds[t],e),L(this._sucs[e],t),delete this._in[t][i],delete this._out[e][i],this._edgeCount--),this}inEdges(e,t){var s=this._in[e];if(s){var i=m(s);return t?f(i,function(r){return r.v===t}):i}}outEdges(e,t){var s=this._out[e];if(s){var i=m(s);return t?f(i,function(r){return r.w===t}):i}}nodeEdges(e,t){var s=this.inEdges(e,t);if(s)return s.concat(this.outEdges(e,t))}};p.prototype._nodeCount=0;p.prototype._edgeCount=0;function v(d,e){d[e]?d[e]++:d[e]=1}function L(d,e){--d[e]||delete d[e]}function g(d,e,t,s){var i=""+e,r=""+t;if(!d&&i>r){var n=i;i=r,r=n}return i+N+r+N+(a(s)?j:s)}function P(d,e,t,s){var i=""+e,r=""+t;if(!d&&i>r){var n=i;i=r,r=n}var h={v:i,w:r};return s&&(h.name=s),h}function y(d,e){return g(d,e.v,e.w,e.name)}export{p as a}; +//# sourceMappingURL=chunk-VUATWGGE.min.js.map diff --git a/docs/website/public/chunk-VUATWGGE.min.js.map b/docs/website/public/chunk-VUATWGGE.min.js.map new file mode 100644 index 000000000..dd5e35131 --- /dev/null +++ b/docs/website/public/chunk-VUATWGGE.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/dagre-d3-es/src/graphlib/graph.js"], + "sourcesContent": ["import * as _ from 'lodash-es';\n\nvar DEFAULT_EDGE_NAME = '\\x00';\nvar GRAPH_NODE = '\\x00';\nvar EDGE_KEY_DELIM = '\\x01';\n\n// Implementation notes:\n//\n// * Node id query functions should return string ids for the nodes\n// * Edge id query functions should return an \"edgeObj\", edge object, that is\n// composed of enough information to uniquely identify an edge: {v, w, name}.\n// * Internally we use an \"edgeId\", a stringified form of the edgeObj, to\n// reference edges. This is because we need a performant way to look these\n// edges up and, object properties, which have string keys, are the closest\n// we're going to get to a performant hashtable in JavaScript.\n\n// Implementation notes:\n//\n// * Node id query functions should return string ids for the nodes\n// * Edge id query functions should return an \"edgeObj\", edge object, that is\n// composed of enough information to uniquely identify an edge: {v, w, name}.\n// * Internally we use an \"edgeId\", a stringified form of the edgeObj, to\n// reference edges. This is because we need a performant way to look these\n// edges up and, object properties, which have string keys, are the closest\n// we're going to get to a performant hashtable in JavaScript.\nexport class Graph {\n constructor(opts = {}) {\n this._isDirected = Object.prototype.hasOwnProperty.call(opts, 'directed')\n ? opts.directed\n : true;\n this._isMultigraph = Object.prototype.hasOwnProperty.call(opts, 'multigraph')\n ? opts.multigraph\n : false;\n this._isCompound = Object.prototype.hasOwnProperty.call(opts, 'compound')\n ? opts.compound\n : false;\n\n // Label for the graph itself\n this._label = undefined;\n\n // Defaults to be set when creating a new node\n this._defaultNodeLabelFn = _.constant(undefined);\n\n // Defaults to be set when creating a new edge\n this._defaultEdgeLabelFn = _.constant(undefined);\n\n // v -> label\n this._nodes = {};\n\n if (this._isCompound) {\n // v -> parent\n this._parent = {};\n\n // v -> children\n this._children = {};\n this._children[GRAPH_NODE] = {};\n }\n\n // v -> edgeObj\n this._in = {};\n\n // u -> v -> Number\n this._preds = {};\n\n // v -> edgeObj\n this._out = {};\n\n // v -> w -> Number\n this._sucs = {};\n\n // e -> edgeObj\n this._edgeObjs = {};\n\n // e -> label\n this._edgeLabels = {};\n }\n /* === Graph functions ========= */\n isDirected() {\n return this._isDirected;\n }\n isMultigraph() {\n return this._isMultigraph;\n }\n isCompound() {\n return this._isCompound;\n }\n setGraph(label) {\n this._label = label;\n return this;\n }\n graph() {\n return this._label;\n }\n /* === Node functions ========== */\n setDefaultNodeLabel(newDefault) {\n if (!_.isFunction(newDefault)) {\n newDefault = _.constant(newDefault);\n }\n this._defaultNodeLabelFn = newDefault;\n return this;\n }\n nodeCount() {\n return this._nodeCount;\n }\n nodes() {\n return _.keys(this._nodes);\n }\n sources() {\n var self = this;\n return _.filter(this.nodes(), function (v) {\n return _.isEmpty(self._in[v]);\n });\n }\n sinks() {\n var self = this;\n return _.filter(this.nodes(), function (v) {\n return _.isEmpty(self._out[v]);\n });\n }\n setNodes(vs, value) {\n var args = arguments;\n var self = this;\n _.each(vs, function (v) {\n if (args.length > 1) {\n self.setNode(v, value);\n } else {\n self.setNode(v);\n }\n });\n return this;\n }\n setNode(v, value) {\n if (Object.prototype.hasOwnProperty.call(this._nodes, v)) {\n if (arguments.length > 1) {\n this._nodes[v] = value;\n }\n return this;\n }\n\n // @ts-expect-error\n this._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v);\n if (this._isCompound) {\n this._parent[v] = GRAPH_NODE;\n this._children[v] = {};\n this._children[GRAPH_NODE][v] = true;\n }\n this._in[v] = {};\n this._preds[v] = {};\n this._out[v] = {};\n this._sucs[v] = {};\n ++this._nodeCount;\n return this;\n }\n node(v) {\n return this._nodes[v];\n }\n hasNode(v) {\n return Object.prototype.hasOwnProperty.call(this._nodes, v);\n }\n removeNode(v) {\n if (Object.prototype.hasOwnProperty.call(this._nodes, v)) {\n var removeEdge = (e) => this.removeEdge(this._edgeObjs[e]);\n delete this._nodes[v];\n if (this._isCompound) {\n this._removeFromParentsChildList(v);\n delete this._parent[v];\n _.each(this.children(v), (child) => {\n this.setParent(child);\n });\n delete this._children[v];\n }\n _.each(_.keys(this._in[v]), removeEdge);\n delete this._in[v];\n delete this._preds[v];\n _.each(_.keys(this._out[v]), removeEdge);\n delete this._out[v];\n delete this._sucs[v];\n --this._nodeCount;\n }\n return this;\n }\n setParent(v, parent) {\n if (!this._isCompound) {\n throw new Error('Cannot set parent in a non-compound graph');\n }\n\n if (_.isUndefined(parent)) {\n parent = GRAPH_NODE;\n } else {\n // Coerce parent to string\n parent += '';\n for (var ancestor = parent; !_.isUndefined(ancestor); ancestor = this.parent(ancestor)) {\n if (ancestor === v) {\n throw new Error('Setting ' + parent + ' as parent of ' + v + ' would create a cycle');\n }\n }\n\n this.setNode(parent);\n }\n\n this.setNode(v);\n this._removeFromParentsChildList(v);\n this._parent[v] = parent;\n this._children[parent][v] = true;\n return this;\n }\n _removeFromParentsChildList(v) {\n delete this._children[this._parent[v]][v];\n }\n parent(v) {\n if (this._isCompound) {\n var parent = this._parent[v];\n if (parent !== GRAPH_NODE) {\n return parent;\n }\n }\n }\n children(v) {\n if (_.isUndefined(v)) {\n v = GRAPH_NODE;\n }\n\n if (this._isCompound) {\n var children = this._children[v];\n if (children) {\n return _.keys(children);\n }\n } else if (v === GRAPH_NODE) {\n return this.nodes();\n } else if (this.hasNode(v)) {\n return [];\n }\n }\n predecessors(v) {\n var predsV = this._preds[v];\n if (predsV) {\n return _.keys(predsV);\n }\n }\n successors(v) {\n var sucsV = this._sucs[v];\n if (sucsV) {\n return _.keys(sucsV);\n }\n }\n neighbors(v) {\n var preds = this.predecessors(v);\n if (preds) {\n return _.union(preds, this.successors(v));\n }\n }\n isLeaf(v) {\n var neighbors;\n if (this.isDirected()) {\n neighbors = this.successors(v);\n } else {\n neighbors = this.neighbors(v);\n }\n return neighbors.length === 0;\n }\n filterNodes(filter) {\n // @ts-expect-error\n var copy = new this.constructor({\n directed: this._isDirected,\n multigraph: this._isMultigraph,\n compound: this._isCompound,\n });\n\n copy.setGraph(this.graph());\n\n var self = this;\n _.each(this._nodes, function (value, v) {\n if (filter(v)) {\n copy.setNode(v, value);\n }\n });\n\n _.each(this._edgeObjs, function (e) {\n // @ts-expect-error\n if (copy.hasNode(e.v) && copy.hasNode(e.w)) {\n copy.setEdge(e, self.edge(e));\n }\n });\n\n var parents = {};\n function findParent(v) {\n var parent = self.parent(v);\n if (parent === undefined || copy.hasNode(parent)) {\n parents[v] = parent;\n return parent;\n } else if (parent in parents) {\n return parents[parent];\n } else {\n return findParent(parent);\n }\n }\n\n if (this._isCompound) {\n _.each(copy.nodes(), function (v) {\n copy.setParent(v, findParent(v));\n });\n }\n\n return copy;\n }\n /* === Edge functions ========== */\n setDefaultEdgeLabel(newDefault) {\n if (!_.isFunction(newDefault)) {\n newDefault = _.constant(newDefault);\n }\n this._defaultEdgeLabelFn = newDefault;\n return this;\n }\n edgeCount() {\n return this._edgeCount;\n }\n edges() {\n return _.values(this._edgeObjs);\n }\n setPath(vs, value) {\n var self = this;\n var args = arguments;\n _.reduce(vs, function (v, w) {\n if (args.length > 1) {\n self.setEdge(v, w, value);\n } else {\n self.setEdge(v, w);\n }\n return w;\n });\n return this;\n }\n /*\n * setEdge(v, w, [value, [name]])\n * setEdge({ v, w, [name] }, [value])\n */\n setEdge() {\n var v, w, name, value;\n var valueSpecified = false;\n var arg0 = arguments[0];\n\n if (typeof arg0 === 'object' && arg0 !== null && 'v' in arg0) {\n v = arg0.v;\n w = arg0.w;\n name = arg0.name;\n if (arguments.length === 2) {\n value = arguments[1];\n valueSpecified = true;\n }\n } else {\n v = arg0;\n w = arguments[1];\n name = arguments[3];\n if (arguments.length > 2) {\n value = arguments[2];\n valueSpecified = true;\n }\n }\n\n v = '' + v;\n w = '' + w;\n if (!_.isUndefined(name)) {\n name = '' + name;\n }\n\n var e = edgeArgsToId(this._isDirected, v, w, name);\n if (Object.prototype.hasOwnProperty.call(this._edgeLabels, e)) {\n if (valueSpecified) {\n this._edgeLabels[e] = value;\n }\n return this;\n }\n\n if (!_.isUndefined(name) && !this._isMultigraph) {\n throw new Error('Cannot set a named edge when isMultigraph = false');\n }\n\n // It didn't exist, so we need to create it.\n // First ensure the nodes exist.\n this.setNode(v);\n this.setNode(w);\n\n // @ts-expect-error\n this._edgeLabels[e] = valueSpecified ? value : this._defaultEdgeLabelFn(v, w, name);\n\n var edgeObj = edgeArgsToObj(this._isDirected, v, w, name);\n // Ensure we add undirected edges in a consistent way.\n v = edgeObj.v;\n w = edgeObj.w;\n\n Object.freeze(edgeObj);\n this._edgeObjs[e] = edgeObj;\n incrementOrInitEntry(this._preds[w], v);\n incrementOrInitEntry(this._sucs[v], w);\n this._in[w][e] = edgeObj;\n this._out[v][e] = edgeObj;\n this._edgeCount++;\n return this;\n }\n edge(v, w, name) {\n var e =\n arguments.length === 1\n ? edgeObjToId(this._isDirected, arguments[0])\n : edgeArgsToId(this._isDirected, v, w, name);\n return this._edgeLabels[e];\n }\n hasEdge(v, w, name) {\n var e =\n arguments.length === 1\n ? edgeObjToId(this._isDirected, arguments[0])\n : edgeArgsToId(this._isDirected, v, w, name);\n return Object.prototype.hasOwnProperty.call(this._edgeLabels, e);\n }\n removeEdge(v, w, name) {\n var e =\n arguments.length === 1\n ? edgeObjToId(this._isDirected, arguments[0])\n : edgeArgsToId(this._isDirected, v, w, name);\n var edge = this._edgeObjs[e];\n if (edge) {\n v = edge.v;\n w = edge.w;\n delete this._edgeLabels[e];\n delete this._edgeObjs[e];\n decrementOrRemoveEntry(this._preds[w], v);\n decrementOrRemoveEntry(this._sucs[v], w);\n delete this._in[w][e];\n delete this._out[v][e];\n this._edgeCount--;\n }\n return this;\n }\n inEdges(v, u) {\n var inV = this._in[v];\n if (inV) {\n var edges = _.values(inV);\n if (!u) {\n return edges;\n }\n return _.filter(edges, function (edge) {\n return edge.v === u;\n });\n }\n }\n outEdges(v, w) {\n var outV = this._out[v];\n if (outV) {\n var edges = _.values(outV);\n if (!w) {\n return edges;\n }\n return _.filter(edges, function (edge) {\n return edge.w === w;\n });\n }\n }\n nodeEdges(v, w) {\n var inEdges = this.inEdges(v, w);\n if (inEdges) {\n return inEdges.concat(this.outEdges(v, w));\n }\n }\n}\n\n/* Number of nodes in the graph. Should only be changed by the implementation. */\nGraph.prototype._nodeCount = 0;\n\n/* Number of edges in the graph. Should only be changed by the implementation. */\nGraph.prototype._edgeCount = 0;\n\nfunction incrementOrInitEntry(map, k) {\n if (map[k]) {\n map[k]++;\n } else {\n map[k] = 1;\n }\n}\n\nfunction decrementOrRemoveEntry(map, k) {\n if (!--map[k]) {\n delete map[k];\n }\n}\n\nfunction edgeArgsToId(isDirected, v_, w_, name) {\n var v = '' + v_;\n var w = '' + w_;\n if (!isDirected && v > w) {\n var tmp = v;\n v = w;\n w = tmp;\n }\n return v + EDGE_KEY_DELIM + w + EDGE_KEY_DELIM + (_.isUndefined(name) ? DEFAULT_EDGE_NAME : name);\n}\n\nfunction edgeArgsToObj(isDirected, v_, w_, name) {\n var v = '' + v_;\n var w = '' + w_;\n if (!isDirected && v > w) {\n var tmp = v;\n v = w;\n w = tmp;\n }\n var edgeObj = { v: v, w: w };\n if (name) {\n edgeObj.name = name;\n }\n return edgeObj;\n}\n\nfunction edgeObjToId(isDirected, edgeObj) {\n return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name);\n}\n"], + "mappings": "qLAEA,IAAIA,EA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,EAAIC,EAAInB,EAAM,CAC9C,IAAIzB,EAAI,GAAK2C,EACTnB,EAAI,GAAKoB,EACb,GAAI,CAACF,GAAc1C,EAAIwB,EAAG,CACxB,IAAIqB,EAAM7C,EACVA,EAAIwB,EACJA,EAAIqB,CACN,CACA,OAAO7C,EAAIV,EAAiBkC,EAAIlC,GAAoBoB,EAAYe,CAAI,EAAIrC,EAAoBqC,EAC9F,CAEA,SAASK,EAAcY,EAAYC,EAAIC,EAAInB,EAAM,CAC/C,IAAIzB,EAAI,GAAK2C,EACTnB,EAAI,GAAKoB,EACb,GAAI,CAACF,GAAc1C,EAAIwB,EAAG,CACxB,IAAIqB,EAAM7C,EACVA,EAAIwB,EACJA,EAAIqB,CACN,CACA,IAAIhB,EAAU,CAAE,EAAG7B,EAAG,EAAGwB,CAAE,EAC3B,OAAIC,IACFI,EAAQ,KAAOJ,GAEVI,CACT,CAEA,SAASG,EAAYU,EAAYb,EAAS,CACxC,OAAOD,EAAac,EAAYb,EAAQ,EAAGA,EAAQ,EAAGA,EAAQ,IAAI,CACpE", + "names": ["DEFAULT_EDGE_NAME", "GRAPH_NODE", "EDGE_KEY_DELIM", "Graph", "opts", "constant_default", "label", "newDefault", "isFunction_default", "keys_default", "self", "filter_default", "v", "isEmpty_default", "vs", "value", "args", "forEach_default", "removeEdge", "e", "child", "parent", "isUndefined_default", "ancestor", "children", "predsV", "sucsV", "preds", "union_default", "neighbors", "filter", "copy", "parents", "findParent", "values_default", "reduce_default", "w", "name", "valueSpecified", "arg0", "edgeArgsToId", "edgeObj", "edgeArgsToObj", "incrementOrInitEntry", "edgeObjToId", "edge", "decrementOrRemoveEntry", "u", "inV", "edges", "outV", "inEdges", "map", "k", "isDirected", "v_", "w_", "tmp"] +} diff --git a/docs/website/public/chunk-WNTLZBBZ.min.js b/docs/website/public/chunk-WNTLZBBZ.min.js new file mode 100644 index 000000000..73ebf7854 --- /dev/null +++ b/docs/website/public/chunk-WNTLZBBZ.min.js @@ -0,0 +1,2 @@ +import{b as m,j as o}from"./chunk-6TVUEPFY.min.js";var g=m((t,e)=>{let n;return e==="sandbox"&&(n=o("#i"+t)),(e==="sandbox"?o(n.nodes()[0].contentDocument.body):o("body")).select(`[id="${t}"]`)},"getDiagramElement");export{g as a}; +//# sourceMappingURL=chunk-WNTLZBBZ.min.js.map diff --git a/docs/website/public/chunk-WNTLZBBZ.min.js.map b/docs/website/public/chunk-WNTLZBBZ.min.js.map new file mode 100644 index 000000000..765a4dbb4 --- /dev/null +++ b/docs/website/public/chunk-WNTLZBBZ.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/mermaid/dist/chunks/mermaid.core/chunk-55IACEB6.mjs"], + "sourcesContent": ["import {\n __name\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/rendering-util/insertElementsForSize.js\nimport { select } from \"d3\";\nvar getDiagramElement = /* @__PURE__ */ __name((id, securityLevel) => {\n let sandboxElement;\n if (securityLevel === \"sandbox\") {\n sandboxElement = select(\"#i\" + id);\n }\n const root = securityLevel === \"sandbox\" ? select(sandboxElement.nodes()[0].contentDocument.body) : select(\"body\");\n const svg = root.select(`[id=\"${id}\"]`);\n return svg;\n}, \"getDiagramElement\");\n\nexport {\n getDiagramElement\n};\n"], + "mappings": "mDAMA,IAAIA,EAAoCC,EAAO,CAACC,EAAIC,IAAkB,CACpE,IAAIC,EACJ,OAAID,IAAkB,YACpBC,EAAiBC,EAAO,KAAOH,CAAE,IAEtBC,IAAkB,UAAYE,EAAOD,EAAe,MAAM,EAAE,CAAC,EAAE,gBAAgB,IAAI,EAAIC,EAAO,MAAM,GAChG,OAAO,QAAQH,CAAE,IAAI,CAExC,EAAG,mBAAmB", + "names": ["getDiagramElement", "__name", "id", "securityLevel", "sandboxElement", "select_default"] +} diff --git a/docs/website/public/chunk-X6BGXIUN.min.js b/docs/website/public/chunk-X6BGXIUN.min.js new file mode 100644 index 000000000..5f857b061 --- /dev/null +++ b/docs/website/public/chunk-X6BGXIUN.min.js @@ -0,0 +1,166 @@ +import{a as it}from"./chunk-PPPUQLJ3.min.js";import{a as at}from"./chunk-WNTLZBBZ.min.js";import{a as rt}from"./chunk-ORLGEIQN.min.js";import{b as tt,c as st}from"./chunk-VTDY5BYI.min.js";import{m as he,p as et}from"./chunk-QZZKR5JD.min.js";import{D as We,G as w,K as L,P as je,Q as Xe,R as He,S as qe,T as Je,U as Ze,V as $e,W as T}from"./chunk-3EE2TK35.min.js";import{b as p,d as ce,j as R}from"./chunk-6TVUEPFY.min.js";var we=(function(){var e=p(function(v,l,o,d){for(o=o||{},d=v.length;d--;o[v[d]]=l);return o},"o"),i=[1,18],n=[1,19],u=[1,20],a=[1,41],c=[1,42],A=[1,26],b=[1,24],D=[1,25],_=[1,32],pe=[1,33],Ae=[1,34],k=[1,45],be=[1,35],fe=[1,36],ke=[1,37],ge=[1,38],me=[1,27],Ce=[1,28],Ee=[1,29],ye=[1,30],Te=[1,31],g=[1,44],m=[1,46],C=[1,43],E=[1,47],De=[1,9],h=[1,8,9],Z=[1,58],$=[1,59],ee=[1,60],te=[1,61],se=[1,62],Fe=[1,63],Be=[1,64],G=[1,8,9,41],Ve=[1,76],P=[1,8,9,12,13,22,39,41,44,68,69,70,71,72,73,74,79,81],ie=[1,8,9,12,13,18,20,22,39,41,44,50,60,68,69,70,71,72,73,74,79,81,86,100,102,103],ae=[13,60,86,100,102,103],U=[13,60,73,74,86,100,102,103],Pe=[13,60,68,69,70,71,72,86,100,102,103],_e=[1,100],z=[1,117],K=[1,113],Y=[1,109],Q=[1,115],W=[1,110],j=[1,111],X=[1,112],H=[1,114],q=[1,116],Me=[22,48,60,61,82,86,87,88,89,90],Se=[1,8,9,39,41,44],re=[1,8,9,22],Re=[1,145],Ge=[1,8,9,61],N=[1,8,9,22,48,60,61,82,86,87,88,89,90],Ne={trace:p(function(){},"trace"),yy:{},symbols_:{error:2,start:3,mermaidDoc:4,statements:5,graphConfig:6,CLASS_DIAGRAM:7,NEWLINE:8,EOF:9,statement:10,classLabel:11,SQS:12,STR:13,SQE:14,namespaceName:15,alphaNumToken:16,classLiteralName:17,DOT:18,className:19,GENERICTYPE:20,relationStatement:21,LABEL:22,namespaceStatement:23,classStatement:24,memberStatement:25,annotationStatement:26,clickStatement:27,styleStatement:28,cssClassStatement:29,noteStatement:30,classDefStatement:31,direction:32,acc_title:33,acc_title_value:34,acc_descr:35,acc_descr_value:36,acc_descr_multiline_value:37,namespaceIdentifier:38,STRUCT_START:39,classStatements:40,STRUCT_STOP:41,NAMESPACE:42,classIdentifier:43,STYLE_SEPARATOR:44,members:45,CLASS:46,emptyBody:47,SPACE:48,ANNOTATION_START:49,ANNOTATION_END:50,MEMBER:51,SEPARATOR:52,relation:53,NOTE_FOR:54,noteText:55,NOTE:56,CLASSDEF:57,classList:58,stylesOpt:59,ALPHA:60,COMMA:61,direction_tb:62,direction_bt:63,direction_rl:64,direction_lr:65,relationType:66,lineType:67,AGGREGATION:68,EXTENSION:69,COMPOSITION:70,DEPENDENCY:71,LOLLIPOP:72,LINE:73,DOTTED_LINE:74,CALLBACK:75,LINK:76,LINK_TARGET:77,CLICK:78,CALLBACK_NAME:79,CALLBACK_ARGS:80,HREF:81,STYLE:82,CSSCLASS:83,style:84,styleComponent:85,NUM:86,COLON:87,UNIT:88,BRKT:89,PCT:90,commentToken:91,textToken:92,graphCodeTokens:93,textNoTagsToken:94,TAGSTART:95,TAGEND:96,"==":97,"--":98,DEFAULT:99,MINUS:100,keywords:101,UNICODE_TEXT:102,BQUOTE_STR:103,$accept:0,$end:1},terminals_:{2:"error",7:"CLASS_DIAGRAM",8:"NEWLINE",9:"EOF",12:"SQS",13:"STR",14:"SQE",18:"DOT",20:"GENERICTYPE",22:"LABEL",33:"acc_title",34:"acc_title_value",35:"acc_descr",36:"acc_descr_value",37:"acc_descr_multiline_value",39:"STRUCT_START",41:"STRUCT_STOP",42:"NAMESPACE",44:"STYLE_SEPARATOR",46:"CLASS",48:"SPACE",49:"ANNOTATION_START",50:"ANNOTATION_END",51:"MEMBER",52:"SEPARATOR",54:"NOTE_FOR",56:"NOTE",57:"CLASSDEF",60:"ALPHA",61:"COMMA",62:"direction_tb",63:"direction_bt",64:"direction_rl",65:"direction_lr",68:"AGGREGATION",69:"EXTENSION",70:"COMPOSITION",71:"DEPENDENCY",72:"LOLLIPOP",73:"LINE",74:"DOTTED_LINE",75:"CALLBACK",76:"LINK",77:"LINK_TARGET",78:"CLICK",79:"CALLBACK_NAME",80:"CALLBACK_ARGS",81:"HREF",82:"STYLE",83:"CSSCLASS",86:"NUM",87:"COLON",88:"UNIT",89:"BRKT",90:"PCT",93:"graphCodeTokens",95:"TAGSTART",96:"TAGEND",97:"==",98:"--",99:"DEFAULT",100:"MINUS",101:"keywords",102:"UNICODE_TEXT",103:"BQUOTE_STR"},productions_:[0,[3,1],[3,1],[4,1],[6,4],[5,1],[5,2],[5,3],[11,3],[15,1],[15,1],[15,3],[15,2],[19,1],[19,3],[19,1],[19,2],[19,2],[19,2],[10,1],[10,2],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,2],[10,2],[10,1],[23,4],[23,5],[38,2],[40,1],[40,2],[40,3],[24,1],[24,3],[24,4],[24,3],[24,6],[43,2],[43,3],[47,0],[47,2],[47,2],[26,4],[45,1],[45,2],[25,1],[25,2],[25,1],[25,1],[21,3],[21,4],[21,4],[21,5],[30,3],[30,2],[31,3],[58,1],[58,3],[32,1],[32,1],[32,1],[32,1],[53,3],[53,2],[53,2],[53,1],[66,1],[66,1],[66,1],[66,1],[66,1],[67,1],[67,1],[27,3],[27,4],[27,3],[27,4],[27,4],[27,5],[27,3],[27,4],[27,4],[27,5],[27,4],[27,5],[27,5],[27,6],[28,3],[29,3],[59,1],[59,3],[84,1],[84,2],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[91,1],[91,1],[92,1],[92,1],[92,1],[92,1],[92,1],[92,1],[92,1],[94,1],[94,1],[94,1],[94,1],[16,1],[16,1],[16,1],[16,1],[17,1],[55,1]],performAction:p(function(l,o,d,r,f,t,J){var s=t.length-1;switch(f){case 8:this.$=t[s-1];break;case 9:case 10:case 13:case 15:this.$=t[s];break;case 11:case 14:this.$=t[s-2]+"."+t[s];break;case 12:case 16:this.$=t[s-1]+t[s];break;case 17:case 18:this.$=t[s-1]+"~"+t[s]+"~";break;case 19:r.addRelation(t[s]);break;case 20:t[s-1].title=r.cleanupLabel(t[s]),r.addRelation(t[s-1]);break;case 31:this.$=t[s].trim(),r.setAccTitle(this.$);break;case 32:case 33:this.$=t[s].trim(),r.setAccDescription(this.$);break;case 34:r.addClassesToNamespace(t[s-3],t[s-1]);break;case 35:r.addClassesToNamespace(t[s-4],t[s-1]);break;case 36:this.$=t[s],r.addNamespace(t[s]);break;case 37:this.$=[t[s]];break;case 38:this.$=[t[s-1]];break;case 39:t[s].unshift(t[s-2]),this.$=t[s];break;case 41:r.setCssClass(t[s-2],t[s]);break;case 42:r.addMembers(t[s-3],t[s-1]);break;case 44:r.setCssClass(t[s-5],t[s-3]),r.addMembers(t[s-5],t[s-1]);break;case 45:this.$=t[s],r.addClass(t[s]);break;case 46:this.$=t[s-1],r.addClass(t[s-1]),r.setClassLabel(t[s-1],t[s]);break;case 50:r.addAnnotation(t[s],t[s-2]);break;case 51:case 64:this.$=[t[s]];break;case 52:t[s].push(t[s-1]),this.$=t[s];break;case 53:break;case 54:r.addMember(t[s-1],r.cleanupLabel(t[s]));break;case 55:break;case 56:break;case 57:this.$={id1:t[s-2],id2:t[s],relation:t[s-1],relationTitle1:"none",relationTitle2:"none"};break;case 58:this.$={id1:t[s-3],id2:t[s],relation:t[s-1],relationTitle1:t[s-2],relationTitle2:"none"};break;case 59:this.$={id1:t[s-3],id2:t[s],relation:t[s-2],relationTitle1:"none",relationTitle2:t[s-1]};break;case 60:this.$={id1:t[s-4],id2:t[s],relation:t[s-2],relationTitle1:t[s-3],relationTitle2:t[s-1]};break;case 61:r.addNote(t[s],t[s-1]);break;case 62:r.addNote(t[s]);break;case 63:this.$=t[s-2],r.defineClass(t[s-1],t[s]);break;case 65:this.$=t[s-2].concat([t[s]]);break;case 66:r.setDirection("TB");break;case 67:r.setDirection("BT");break;case 68:r.setDirection("RL");break;case 69:r.setDirection("LR");break;case 70:this.$={type1:t[s-2],type2:t[s],lineType:t[s-1]};break;case 71:this.$={type1:"none",type2:t[s],lineType:t[s-1]};break;case 72:this.$={type1:t[s-1],type2:"none",lineType:t[s]};break;case 73:this.$={type1:"none",type2:"none",lineType:t[s]};break;case 74:this.$=r.relationType.AGGREGATION;break;case 75:this.$=r.relationType.EXTENSION;break;case 76:this.$=r.relationType.COMPOSITION;break;case 77:this.$=r.relationType.DEPENDENCY;break;case 78:this.$=r.relationType.LOLLIPOP;break;case 79:this.$=r.lineType.LINE;break;case 80:this.$=r.lineType.DOTTED_LINE;break;case 81:case 87:this.$=t[s-2],r.setClickEvent(t[s-1],t[s]);break;case 82:case 88:this.$=t[s-3],r.setClickEvent(t[s-2],t[s-1]),r.setTooltip(t[s-2],t[s]);break;case 83:this.$=t[s-2],r.setLink(t[s-1],t[s]);break;case 84:this.$=t[s-3],r.setLink(t[s-2],t[s-1],t[s]);break;case 85:this.$=t[s-3],r.setLink(t[s-2],t[s-1]),r.setTooltip(t[s-2],t[s]);break;case 86:this.$=t[s-4],r.setLink(t[s-3],t[s-2],t[s]),r.setTooltip(t[s-3],t[s-1]);break;case 89:this.$=t[s-3],r.setClickEvent(t[s-2],t[s-1],t[s]);break;case 90:this.$=t[s-4],r.setClickEvent(t[s-3],t[s-2],t[s-1]),r.setTooltip(t[s-3],t[s]);break;case 91:this.$=t[s-3],r.setLink(t[s-2],t[s]);break;case 92:this.$=t[s-4],r.setLink(t[s-3],t[s-1],t[s]);break;case 93:this.$=t[s-4],r.setLink(t[s-3],t[s-1]),r.setTooltip(t[s-3],t[s]);break;case 94:this.$=t[s-5],r.setLink(t[s-4],t[s-2],t[s]),r.setTooltip(t[s-4],t[s-1]);break;case 95:this.$=t[s-2],r.setCssStyle(t[s-1],t[s]);break;case 96:r.setCssClass(t[s-1],t[s]);break;case 97:this.$=[t[s]];break;case 98:t[s-2].push(t[s]),this.$=t[s-2];break;case 100:this.$=t[s-1]+t[s];break}},"anonymous"),table:[{3:1,4:2,5:3,6:4,7:[1,6],10:5,16:39,17:40,19:21,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,33:i,35:n,37:u,38:22,42:a,43:23,46:c,49:A,51:b,52:D,54:_,56:pe,57:Ae,60:k,62:be,63:fe,64:ke,65:ge,75:me,76:Ce,78:Ee,82:ye,83:Te,86:g,100:m,102:C,103:E},{1:[3]},{1:[2,1]},{1:[2,2]},{1:[2,3]},e(De,[2,5],{8:[1,48]}),{8:[1,49]},e(h,[2,19],{22:[1,50]}),e(h,[2,21]),e(h,[2,22]),e(h,[2,23]),e(h,[2,24]),e(h,[2,25]),e(h,[2,26]),e(h,[2,27]),e(h,[2,28]),e(h,[2,29]),e(h,[2,30]),{34:[1,51]},{36:[1,52]},e(h,[2,33]),e(h,[2,53],{53:53,66:56,67:57,13:[1,54],22:[1,55],68:Z,69:$,70:ee,71:te,72:se,73:Fe,74:Be}),{39:[1,65]},e(G,[2,40],{39:[1,67],44:[1,66]}),e(h,[2,55]),e(h,[2,56]),{16:68,60:k,86:g,100:m,102:C},{16:39,17:40,19:69,60:k,86:g,100:m,102:C,103:E},{16:39,17:40,19:70,60:k,86:g,100:m,102:C,103:E},{16:39,17:40,19:71,60:k,86:g,100:m,102:C,103:E},{60:[1,72]},{13:[1,73]},{16:39,17:40,19:74,60:k,86:g,100:m,102:C,103:E},{13:Ve,55:75},{58:77,60:[1,78]},e(h,[2,66]),e(h,[2,67]),e(h,[2,68]),e(h,[2,69]),e(P,[2,13],{16:39,17:40,19:80,18:[1,79],20:[1,81],60:k,86:g,100:m,102:C,103:E}),e(P,[2,15],{20:[1,82]}),{15:83,16:84,17:85,60:k,86:g,100:m,102:C,103:E},{16:39,17:40,19:86,60:k,86:g,100:m,102:C,103:E},e(ie,[2,123]),e(ie,[2,124]),e(ie,[2,125]),e(ie,[2,126]),e([1,8,9,12,13,20,22,39,41,44,68,69,70,71,72,73,74,79,81],[2,127]),e(De,[2,6],{10:5,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,19:21,38:22,43:23,16:39,17:40,5:87,33:i,35:n,37:u,42:a,46:c,49:A,51:b,52:D,54:_,56:pe,57:Ae,60:k,62:be,63:fe,64:ke,65:ge,75:me,76:Ce,78:Ee,82:ye,83:Te,86:g,100:m,102:C,103:E}),{5:88,10:5,16:39,17:40,19:21,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,33:i,35:n,37:u,38:22,42:a,43:23,46:c,49:A,51:b,52:D,54:_,56:pe,57:Ae,60:k,62:be,63:fe,64:ke,65:ge,75:me,76:Ce,78:Ee,82:ye,83:Te,86:g,100:m,102:C,103:E},e(h,[2,20]),e(h,[2,31]),e(h,[2,32]),{13:[1,90],16:39,17:40,19:89,60:k,86:g,100:m,102:C,103:E},{53:91,66:56,67:57,68:Z,69:$,70:ee,71:te,72:se,73:Fe,74:Be},e(h,[2,54]),{67:92,73:Fe,74:Be},e(ae,[2,73],{66:93,68:Z,69:$,70:ee,71:te,72:se}),e(U,[2,74]),e(U,[2,75]),e(U,[2,76]),e(U,[2,77]),e(U,[2,78]),e(Pe,[2,79]),e(Pe,[2,80]),{8:[1,95],24:96,40:94,43:23,46:c},{16:97,60:k,86:g,100:m,102:C},{41:[1,99],45:98,51:_e},{50:[1,101]},{13:[1,102]},{13:[1,103]},{79:[1,104],81:[1,105]},{22:z,48:K,59:106,60:Y,82:Q,84:107,85:108,86:W,87:j,88:X,89:H,90:q},{60:[1,118]},{13:Ve,55:119},e(h,[2,62]),e(h,[2,128]),{22:z,48:K,59:120,60:Y,61:[1,121],82:Q,84:107,85:108,86:W,87:j,88:X,89:H,90:q},e(Me,[2,64]),{16:39,17:40,19:122,60:k,86:g,100:m,102:C,103:E},e(P,[2,16]),e(P,[2,17]),e(P,[2,18]),{39:[2,36]},{15:124,16:84,17:85,18:[1,123],39:[2,9],60:k,86:g,100:m,102:C,103:E},{39:[2,10]},e(Se,[2,45],{11:125,12:[1,126]}),e(De,[2,7]),{9:[1,127]},e(re,[2,57]),{16:39,17:40,19:128,60:k,86:g,100:m,102:C,103:E},{13:[1,130],16:39,17:40,19:129,60:k,86:g,100:m,102:C,103:E},e(ae,[2,72],{66:131,68:Z,69:$,70:ee,71:te,72:se}),e(ae,[2,71]),{41:[1,132]},{24:96,40:133,43:23,46:c},{8:[1,134],41:[2,37]},e(G,[2,41],{39:[1,135]}),{41:[1,136]},e(G,[2,43]),{41:[2,51],45:137,51:_e},{16:39,17:40,19:138,60:k,86:g,100:m,102:C,103:E},e(h,[2,81],{13:[1,139]}),e(h,[2,83],{13:[1,141],77:[1,140]}),e(h,[2,87],{13:[1,142],80:[1,143]}),{13:[1,144]},e(h,[2,95],{61:Re}),e(Ge,[2,97],{85:146,22:z,48:K,60:Y,82:Q,86:W,87:j,88:X,89:H,90:q}),e(N,[2,99]),e(N,[2,101]),e(N,[2,102]),e(N,[2,103]),e(N,[2,104]),e(N,[2,105]),e(N,[2,106]),e(N,[2,107]),e(N,[2,108]),e(N,[2,109]),e(h,[2,96]),e(h,[2,61]),e(h,[2,63],{61:Re}),{60:[1,147]},e(P,[2,14]),{15:148,16:84,17:85,60:k,86:g,100:m,102:C,103:E},{39:[2,12]},e(Se,[2,46]),{13:[1,149]},{1:[2,4]},e(re,[2,59]),e(re,[2,58]),{16:39,17:40,19:150,60:k,86:g,100:m,102:C,103:E},e(ae,[2,70]),e(h,[2,34]),{41:[1,151]},{24:96,40:152,41:[2,38],43:23,46:c},{45:153,51:_e},e(G,[2,42]),{41:[2,52]},e(h,[2,50]),e(h,[2,82]),e(h,[2,84]),e(h,[2,85],{77:[1,154]}),e(h,[2,88]),e(h,[2,89],{13:[1,155]}),e(h,[2,91],{13:[1,157],77:[1,156]}),{22:z,48:K,60:Y,82:Q,84:158,85:108,86:W,87:j,88:X,89:H,90:q},e(N,[2,100]),e(Me,[2,65]),{39:[2,11]},{14:[1,159]},e(re,[2,60]),e(h,[2,35]),{41:[2,39]},{41:[1,160]},e(h,[2,86]),e(h,[2,90]),e(h,[2,92]),e(h,[2,93],{77:[1,161]}),e(Ge,[2,98],{85:146,22:z,48:K,60:Y,82:Q,86:W,87:j,88:X,89:H,90:q}),e(Se,[2,8]),e(G,[2,44]),e(h,[2,94])],defaultActions:{2:[2,1],3:[2,2],4:[2,3],83:[2,36],85:[2,10],124:[2,12],127:[2,4],137:[2,52],148:[2,11],152:[2,39]},parseError:p(function(l,o){if(o.recoverable)this.trace(l);else{var d=new Error(l);throw d.hash=o,d}},"parseError"),parse:p(function(l){var o=this,d=[0],r=[],f=[null],t=[],J=this.table,s="",ue=0,Ue=0,ze=0,ct=2,Ke=1,ht=t.slice.call(arguments,1),y=Object.create(this.lexer),I={yy:{}};for(var Le in this.yy)Object.prototype.hasOwnProperty.call(this.yy,Le)&&(I.yy[Le]=this.yy[Le]);y.setInput(l,I.yy),I.yy.lexer=y,I.yy.parser=this,typeof y.yylloc>"u"&&(y.yylloc={});var xe=y.yylloc;t.push(xe);var dt=y.options&&y.options.ranges;typeof I.yy.parseError=="function"?this.parseError=I.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function pt(B){d.length=d.length-2*B,f.length=f.length-B,t.length=t.length-B}p(pt,"popStack");function Ye(){var B;return B=r.pop()||y.lex()||Ke,typeof B!="number"&&(B instanceof Array&&(r=B,B=r.pop()),B=o.symbols_[B]||B),B}p(Ye,"lex");for(var F,ve,O,S,gt,Ie,M={},le,x,Qe,oe;;){if(O=d[d.length-1],this.defaultActions[O]?S=this.defaultActions[O]:((F===null||typeof F>"u")&&(F=Ye()),S=J[O]&&J[O][F]),typeof S>"u"||!S.length||!S[0]){var Oe="";oe=[];for(le in J[O])this.terminals_[le]&&le>ct&&oe.push("'"+this.terminals_[le]+"'");y.showPosition?Oe="Parse error on line "+(ue+1)+`: +`+y.showPosition()+` +Expecting `+oe.join(", ")+", got '"+(this.terminals_[F]||F)+"'":Oe="Parse error on line "+(ue+1)+": Unexpected "+(F==Ke?"end of input":"'"+(this.terminals_[F]||F)+"'"),this.parseError(Oe,{text:y.match,token:this.terminals_[F]||F,line:y.yylineno,loc:xe,expected:oe})}if(S[0]instanceof Array&&S.length>1)throw new Error("Parse Error: multiple actions possible at state: "+O+", token: "+F);switch(S[0]){case 1:d.push(F),f.push(y.yytext),t.push(y.yylloc),d.push(S[1]),F=null,ve?(F=ve,ve=null):(Ue=y.yyleng,s=y.yytext,ue=y.yylineno,xe=y.yylloc,ze>0&&ze--);break;case 2:if(x=this.productions_[S[1]][1],M.$=f[f.length-x],M._$={first_line:t[t.length-(x||1)].first_line,last_line:t[t.length-1].last_line,first_column:t[t.length-(x||1)].first_column,last_column:t[t.length-1].last_column},dt&&(M._$.range=[t[t.length-(x||1)].range[0],t[t.length-1].range[1]]),Ie=this.performAction.apply(M,[s,Ue,ue,I.yy,S[1],f,t].concat(ht)),typeof Ie<"u")return Ie;x&&(d=d.slice(0,-1*x*2),f=f.slice(0,-1*x),t=t.slice(0,-1*x)),d.push(this.productions_[S[1]][0]),f.push(M.$),t.push(M._$),Qe=J[d[d.length-2]][d[d.length-1]],d.push(Qe);break;case 3:return!0}}return!0},"parse")},ot=(function(){var v={EOF:1,parseError:p(function(o,d){if(this.yy.parser)this.yy.parser.parseError(o,d);else throw new Error(o)},"parseError"),setInput:p(function(l,o){return this.yy=o||this.yy||{},this._input=l,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:p(function(){var l=this._input[0];this.yytext+=l,this.yyleng++,this.offset++,this.match+=l,this.matched+=l;var o=l.match(/(?:\r\n?|\n).*/g);return o?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),l},"input"),unput:p(function(l){var o=l.length,d=l.split(/(?:\r\n?|\n)/g);this._input=l+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-o),this.offset-=o;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),d.length-1&&(this.yylineno-=d.length-1);var f=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:d?(d.length===r.length?this.yylloc.first_column:0)+r[r.length-d.length].length-d[0].length:this.yylloc.first_column-o},this.options.ranges&&(this.yylloc.range=[f[0],f[0]+this.yyleng-o]),this.yyleng=this.yytext.length,this},"unput"),more:p(function(){return this._more=!0,this},"more"),reject:p(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:p(function(l){this.unput(this.match.slice(l))},"less"),pastInput:p(function(){var l=this.matched.substr(0,this.matched.length-this.match.length);return(l.length>20?"...":"")+l.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:p(function(){var l=this.match;return l.length<20&&(l+=this._input.substr(0,20-l.length)),(l.substr(0,20)+(l.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:p(function(){var l=this.pastInput(),o=new Array(l.length+1).join("-");return l+this.upcomingInput()+` +`+o+"^"},"showPosition"),test_match:p(function(l,o){var d,r,f;if(this.options.backtrack_lexer&&(f={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(f.yylloc.range=this.yylloc.range.slice(0))),r=l[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+l[0].length},this.yytext+=l[0],this.match+=l[0],this.matches=l,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(l[0].length),this.matched+=l[0],d=this.performAction.call(this,this.yy,this,o,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),d)return d;if(this._backtrack){for(var t in f)this[t]=f[t];return!1}return!1},"test_match"),next:p(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var l,o,d,r;this._more||(this.yytext="",this.match="");for(var f=this._currentRules(),t=0;to[0].length)){if(o=d,r=t,this.options.backtrack_lexer){if(l=this.test_match(d,f[t]),l!==!1)return l;if(this._backtrack){o=!1;continue}else return!1}else if(!this.options.flex)break}return o?(l=this.test_match(o,f[r]),l!==!1?l:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:p(function(){var o=this.next();return o||this.lex()},"lex"),begin:p(function(o){this.conditionStack.push(o)},"begin"),popState:p(function(){var o=this.conditionStack.length-1;return o>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:p(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:p(function(o){return o=this.conditionStack.length-1-Math.abs(o||0),o>=0?this.conditionStack[o]:"INITIAL"},"topState"),pushState:p(function(o){this.begin(o)},"pushState"),stateStackSize:p(function(){return this.conditionStack.length},"stateStackSize"),options:{},performAction:p(function(o,d,r,f){var t=f;switch(r){case 0:return 62;case 1:return 63;case 2:return 64;case 3:return 65;case 4:break;case 5:break;case 6:return this.begin("acc_title"),33;break;case 7:return this.popState(),"acc_title_value";break;case 8:return this.begin("acc_descr"),35;break;case 9:return this.popState(),"acc_descr_value";break;case 10:this.begin("acc_descr_multiline");break;case 11:this.popState();break;case 12:return"acc_descr_multiline_value";case 13:return 8;case 14:break;case 15:return 7;case 16:return 7;case 17:return"EDGE_STATE";case 18:this.begin("callback_name");break;case 19:this.popState();break;case 20:this.popState(),this.begin("callback_args");break;case 21:return 79;case 22:this.popState();break;case 23:return 80;case 24:this.popState();break;case 25:return"STR";case 26:this.begin("string");break;case 27:return 82;case 28:return 57;case 29:return this.begin("namespace"),42;break;case 30:return this.popState(),8;break;case 31:break;case 32:return this.begin("namespace-body"),39;break;case 33:return this.popState(),41;break;case 34:return"EOF_IN_STRUCT";case 35:return 8;case 36:break;case 37:return"EDGE_STATE";case 38:return this.begin("class"),46;break;case 39:return this.popState(),8;break;case 40:break;case 41:return this.popState(),this.popState(),41;break;case 42:return this.begin("class-body"),39;break;case 43:return this.popState(),41;break;case 44:return"EOF_IN_STRUCT";case 45:return"EDGE_STATE";case 46:return"OPEN_IN_STRUCT";case 47:break;case 48:return"MEMBER";case 49:return 83;case 50:return 75;case 51:return 76;case 52:return 78;case 53:return 54;case 54:return 56;case 55:return 49;case 56:return 50;case 57:return 81;case 58:this.popState();break;case 59:return"GENERICTYPE";case 60:this.begin("generic");break;case 61:this.popState();break;case 62:return"BQUOTE_STR";case 63:this.begin("bqstring");break;case 64:return 77;case 65:return 77;case 66:return 77;case 67:return 77;case 68:return 69;case 69:return 69;case 70:return 71;case 71:return 71;case 72:return 70;case 73:return 68;case 74:return 72;case 75:return 73;case 76:return 74;case 77:return 22;case 78:return 44;case 79:return 100;case 80:return 18;case 81:return"PLUS";case 82:return 87;case 83:return 61;case 84:return 89;case 85:return 89;case 86:return 90;case 87:return"EQUALS";case 88:return"EQUALS";case 89:return 60;case 90:return 12;case 91:return 14;case 92:return"PUNCTUATION";case 93:return 86;case 94:return 102;case 95:return 48;case 96:return 48;case 97:return 9}},"anonymous"),rules:[/^(?:.*direction\s+TB[^\n]*)/,/^(?:.*direction\s+BT[^\n]*)/,/^(?:.*direction\s+RL[^\n]*)/,/^(?:.*direction\s+LR[^\n]*)/,/^(?:%%(?!\{)*[^\n]*(\r?\n?)+)/,/^(?:%%[^\n]*(\r?\n)*)/,/^(?:accTitle\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*\{\s*)/,/^(?:[\}])/,/^(?:[^\}]*)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:classDiagram-v2\b)/,/^(?:classDiagram\b)/,/^(?:\[\*\])/,/^(?:call[\s]+)/,/^(?:\([\s]*\))/,/^(?:\()/,/^(?:[^(]*)/,/^(?:\))/,/^(?:[^)]*)/,/^(?:["])/,/^(?:[^"]*)/,/^(?:["])/,/^(?:style\b)/,/^(?:classDef\b)/,/^(?:namespace\b)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:[{])/,/^(?:[}])/,/^(?:$)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:\[\*\])/,/^(?:class\b)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:[}])/,/^(?:[{])/,/^(?:[}])/,/^(?:$)/,/^(?:\[\*\])/,/^(?:[{])/,/^(?:[\n])/,/^(?:[^{}\n]*)/,/^(?:cssClass\b)/,/^(?:callback\b)/,/^(?:link\b)/,/^(?:click\b)/,/^(?:note for\b)/,/^(?:note\b)/,/^(?:<<)/,/^(?:>>)/,/^(?:href\b)/,/^(?:[~])/,/^(?:[^~]*)/,/^(?:~)/,/^(?:[`])/,/^(?:[^`]+)/,/^(?:[`])/,/^(?:_self\b)/,/^(?:_blank\b)/,/^(?:_parent\b)/,/^(?:_top\b)/,/^(?:\s*<\|)/,/^(?:\s*\|>)/,/^(?:\s*>)/,/^(?:\s*<)/,/^(?:\s*\*)/,/^(?:\s*o\b)/,/^(?:\s*\(\))/,/^(?:--)/,/^(?:\.\.)/,/^(?::{1}[^:\n;]+)/,/^(?::{3})/,/^(?:-)/,/^(?:\.)/,/^(?:\+)/,/^(?::)/,/^(?:,)/,/^(?:#)/,/^(?:#)/,/^(?:%)/,/^(?:=)/,/^(?:=)/,/^(?:\w+)/,/^(?:\[)/,/^(?:\])/,/^(?:[!"#$%&'*+,-.`?\\/])/,/^(?:[0-9]+)/,/^(?:[\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6]|[\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377]|[\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5]|[\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA]|[\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE]|[\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA]|[\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0]|[\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977]|[\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2]|[\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A]|[\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39]|[\u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C-\u1248\u124A-\u124D]|[\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0]|[\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310]|[\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C]|[\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711]|[\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7]|[\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C]|[\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16]|[\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF]|[\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC]|[\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D]|[\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D]|[\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3]|[\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F]|[\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128]|[\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184]|[\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3]|[\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6]|[\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE]|[\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C]|[\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D]|[\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC]|[\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B]|[\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788]|[\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805]|[\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB]|[\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28]|[\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5]|[\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4]|[\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E]|[\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D]|[\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36]|[\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D]|[\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC]|[\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF]|[\uFFD2-\uFFD7\uFFDA-\uFFDC])/,/^(?:\s)/,/^(?:\s)/,/^(?:$)/],conditions:{"namespace-body":{rules:[26,33,34,35,36,37,38,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},namespace:{rules:[26,29,30,31,32,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},"class-body":{rules:[26,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},class:{rules:[26,39,40,41,42,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},acc_descr_multiline:{rules:[11,12,26,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},acc_descr:{rules:[9,26,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},acc_title:{rules:[7,26,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},callback_args:{rules:[22,23,26,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},callback_name:{rules:[19,20,21,26,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},href:{rules:[26,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},struct:{rules:[26,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},generic:{rules:[26,49,50,51,52,53,54,55,56,57,58,59,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},bqstring:{rules:[26,49,50,51,52,53,54,55,56,57,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},string:{rules:[24,25,26,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,8,10,13,14,15,16,17,18,26,27,28,29,38,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97],inclusive:!0}}};return v})();Ne.lexer=ot;function ne(){this.yy={}}return p(ne,"Parser"),ne.prototype=Ne,Ne.Parser=ne,new ne})();we.parser=we;var Bt=we,nt=["#","+","~","-",""],ut=class{static{p(this,"ClassMember")}constructor(e,i){this.memberType=i,this.visibility="",this.classifier="",this.text="";let n=We(e,T());this.parseMember(n)}getDisplayDetails(){let e=this.visibility+w(this.id);this.memberType==="method"&&(e+=`(${w(this.parameters.trim())})`,this.returnType&&(e+=" : "+w(this.returnType))),e=e.trim();let i=this.parseClassifier();return{displayText:e,cssStyle:i}}parseMember(e){let i="";if(this.memberType==="method"){let a=/([#+~-])?(.+)\((.*)\)([\s$*])?(.*)([$*])?/.exec(e);if(a){let c=a[1]?a[1].trim():"";if(nt.includes(c)&&(this.visibility=c),this.id=a[2],this.parameters=a[3]?a[3].trim():"",i=a[4]?a[4].trim():"",this.returnType=a[5]?a[5].trim():"",i===""){let A=this.returnType.substring(this.returnType.length-1);/[$*]/.exec(A)&&(i=A,this.returnType=this.returnType.substring(0,this.returnType.length-1))}}}else{let u=e.length,a=e.substring(0,1),c=e.substring(u-1);nt.includes(a)&&(this.visibility=a),/[$*]/.exec(c)&&(i=c),this.id=e.substring(this.visibility===""?0:1,i===""?u:u-1)}this.classifier=i,this.id=this.id.startsWith(" ")?" "+this.id.trim():this.id.trim();let n=`${this.visibility?"\\"+this.visibility:""}${w(this.id)}${this.memberType==="method"?`(${w(this.parameters)})${this.returnType?" : "+w(this.returnType):""}`:""}`;this.text=n.replaceAll("<","<").replaceAll(">",">"),this.text.startsWith("\\<")&&(this.text=this.text.replace("\\<","~"))}parseClassifier(){switch(this.classifier){case"*":return"font-style:italic;";case"$":return"text-decoration:underline;";default:return""}}},de="classId-",lt=0,V=p(e=>L.sanitizeText(e,T()),"sanitizeText"),St=class{constructor(){this.relations=[],this.classes=new Map,this.styleClasses=new Map,this.notes=[],this.interfaces=[],this.namespaces=new Map,this.namespaceCounter=0,this.functions=[],this.lineType={LINE:0,DOTTED_LINE:1},this.relationType={AGGREGATION:0,EXTENSION:1,COMPOSITION:2,DEPENDENCY:3,LOLLIPOP:4},this.setupToolTips=p(e=>{let i=R(".mermaidTooltip");(i._groups||i)[0][0]===null&&(i=R("body").append("div").attr("class","mermaidTooltip").style("opacity",0)),R(e).select("svg").selectAll("g.node").on("mouseover",a=>{let c=R(a.currentTarget);if(c.attr("title")===null)return;let b=this.getBoundingClientRect();i.transition().duration(200).style("opacity",".9"),i.text(c.attr("title")).style("left",window.scrollX+b.left+(b.right-b.left)/2+"px").style("top",window.scrollY+b.top-14+document.body.scrollTop+"px"),i.html(i.html().replace(/<br\/>/g,"
")),c.classed("hover",!0)}).on("mouseout",a=>{i.transition().duration(500).style("opacity",0),R(a.currentTarget).classed("hover",!1)})},"setupToolTips"),this.direction="TB",this.setAccTitle=Xe,this.getAccTitle=He,this.setAccDescription=qe,this.getAccDescription=Je,this.setDiagramTitle=Ze,this.getDiagramTitle=$e,this.getConfig=p(()=>T().class,"getConfig"),this.functions.push(this.setupToolTips.bind(this)),this.clear(),this.addRelation=this.addRelation.bind(this),this.addClassesToNamespace=this.addClassesToNamespace.bind(this),this.addNamespace=this.addNamespace.bind(this),this.setCssClass=this.setCssClass.bind(this),this.addMembers=this.addMembers.bind(this),this.addClass=this.addClass.bind(this),this.setClassLabel=this.setClassLabel.bind(this),this.addAnnotation=this.addAnnotation.bind(this),this.addMember=this.addMember.bind(this),this.cleanupLabel=this.cleanupLabel.bind(this),this.addNote=this.addNote.bind(this),this.defineClass=this.defineClass.bind(this),this.setDirection=this.setDirection.bind(this),this.setLink=this.setLink.bind(this),this.bindFunctions=this.bindFunctions.bind(this),this.clear=this.clear.bind(this),this.setTooltip=this.setTooltip.bind(this),this.setClickEvent=this.setClickEvent.bind(this),this.setCssStyle=this.setCssStyle.bind(this)}static{p(this,"ClassDB")}splitClassNameAndType(e){let i=L.sanitizeText(e,T()),n="",u=i;if(i.indexOf("~")>0){let a=i.split("~");u=V(a[0]),n=V(a[1])}return{className:u,type:n}}setClassLabel(e,i){let n=L.sanitizeText(e,T());i&&(i=V(i));let{className:u}=this.splitClassNameAndType(n);this.classes.get(u).label=i,this.classes.get(u).text=`${i}${this.classes.get(u).type?`<${this.classes.get(u).type}>`:""}`}addClass(e){let i=L.sanitizeText(e,T()),{className:n,type:u}=this.splitClassNameAndType(i);if(this.classes.has(n))return;let a=L.sanitizeText(n,T());this.classes.set(a,{id:a,type:u,label:a,text:`${a}${u?`<${u}>`:""}`,shape:"classBox",cssClasses:"default",methods:[],members:[],annotations:[],styles:[],domId:de+a+"-"+lt}),lt++}addInterface(e,i){let n={id:`interface${this.interfaces.length}`,label:e,classId:i};this.interfaces.push(n)}lookUpDomId(e){let i=L.sanitizeText(e,T());if(this.classes.has(i))return this.classes.get(i).domId;throw new Error("Class not found: "+i)}clear(){this.relations=[],this.classes=new Map,this.notes=[],this.interfaces=[],this.functions=[],this.functions.push(this.setupToolTips.bind(this)),this.namespaces=new Map,this.namespaceCounter=0,this.direction="TB",je()}getClass(e){return this.classes.get(e)}getClasses(){return this.classes}getRelations(){return this.relations}getNotes(){return this.notes}addRelation(e){ce.debug("Adding relation: "+JSON.stringify(e));let i=[this.relationType.LOLLIPOP,this.relationType.AGGREGATION,this.relationType.COMPOSITION,this.relationType.DEPENDENCY,this.relationType.EXTENSION];e.relation.type1===this.relationType.LOLLIPOP&&!i.includes(e.relation.type2)?(this.addClass(e.id2),this.addInterface(e.id1,e.id2),e.id1=`interface${this.interfaces.length-1}`):e.relation.type2===this.relationType.LOLLIPOP&&!i.includes(e.relation.type1)?(this.addClass(e.id1),this.addInterface(e.id2,e.id1),e.id2=`interface${this.interfaces.length-1}`):(this.addClass(e.id1),this.addClass(e.id2)),e.id1=this.splitClassNameAndType(e.id1).className,e.id2=this.splitClassNameAndType(e.id2).className,e.relationTitle1=L.sanitizeText(e.relationTitle1.trim(),T()),e.relationTitle2=L.sanitizeText(e.relationTitle2.trim(),T()),this.relations.push(e)}addAnnotation(e,i){let n=this.splitClassNameAndType(e).className;this.classes.get(n).annotations.push(i)}addMember(e,i){this.addClass(e);let n=this.splitClassNameAndType(e).className,u=this.classes.get(n);if(typeof i=="string"){let a=i.trim();a.startsWith("<<")&&a.endsWith(">>")?u.annotations.push(V(a.substring(2,a.length-2))):a.indexOf(")")>0?u.methods.push(new ut(a,"method")):a&&u.members.push(new ut(a,"attribute"))}}addMembers(e,i){Array.isArray(i)&&(i.reverse(),i.forEach(n=>this.addMember(e,n)))}addNote(e,i){let n={id:`note${this.notes.length}`,class:i,text:e};this.notes.push(n)}cleanupLabel(e){return e.startsWith(":")&&(e=e.substring(1)),V(e.trim())}setCssClass(e,i){e.split(",").forEach(n=>{let u=n;/\d/.exec(n[0])&&(u=de+u);let a=this.classes.get(u);a&&(a.cssClasses+=" "+i)})}defineClass(e,i){for(let n of e){let u=this.styleClasses.get(n);u===void 0&&(u={id:n,styles:[],textStyles:[]},this.styleClasses.set(n,u)),i&&i.forEach(a=>{if(/color/.exec(a)){let c=a.replace("fill","bgFill");u.textStyles.push(c)}u.styles.push(a)}),this.classes.forEach(a=>{a.cssClasses.includes(n)&&a.styles.push(...i.flatMap(c=>c.split(",")))})}}setTooltip(e,i){e.split(",").forEach(n=>{i!==void 0&&(this.classes.get(n).tooltip=V(i))})}getTooltip(e,i){return i&&this.namespaces.has(i)?this.namespaces.get(i).classes.get(e).tooltip:this.classes.get(e).tooltip}setLink(e,i,n){let u=T();e.split(",").forEach(a=>{let c=a;/\d/.exec(a[0])&&(c=de+c);let A=this.classes.get(c);A&&(A.link=he.formatUrl(i,u),u.securityLevel==="sandbox"?A.linkTarget="_top":typeof n=="string"?A.linkTarget=V(n):A.linkTarget="_blank")}),this.setCssClass(e,"clickable")}setClickEvent(e,i,n){e.split(",").forEach(u=>{this.setClickFunc(u,i,n),this.classes.get(u).haveCallback=!0}),this.setCssClass(e,"clickable")}setClickFunc(e,i,n){let u=L.sanitizeText(e,T());if(T().securityLevel!=="loose"||i===void 0)return;let c=u;if(this.classes.has(c)){let A=this.lookUpDomId(c),b=[];if(typeof n=="string"){b=n.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);for(let D=0;D{let D=document.querySelector(`[id="${A}"]`);D!==null&&D.addEventListener("click",()=>{he.runFunc(i,...b)},!1)})}}bindFunctions(e){this.functions.forEach(i=>{i(e)})}getDirection(){return this.direction}setDirection(e){this.direction=e}addNamespace(e){this.namespaces.has(e)||(this.namespaces.set(e,{id:e,classes:new Map,children:{},domId:de+e+"-"+this.namespaceCounter}),this.namespaceCounter++)}getNamespace(e){return this.namespaces.get(e)}getNamespaces(){return this.namespaces}addClassesToNamespace(e,i){if(this.namespaces.has(e))for(let n of i){let{className:u}=this.splitClassNameAndType(n);this.classes.get(u).parent=e,this.namespaces.get(e).classes.set(u,this.classes.get(u))}}setCssStyle(e,i){let n=this.classes.get(e);if(!(!i||!n))for(let u of i)u.includes(",")?n.styles.push(...u.split(",")):n.styles.push(u)}getArrowMarker(e){let i;switch(e){case 0:i="aggregation";break;case 1:i="extension";break;case 2:i="composition";break;case 3:i="dependency";break;case 4:i="lollipop";break;default:i="none"}return i}getData(){let e=[],i=[],n=T();for(let a of this.namespaces.keys()){let c=this.namespaces.get(a);if(c){let A={id:c.id,label:c.id,isGroup:!0,padding:n.class.padding??16,shape:"rect",cssStyles:["fill: none","stroke: black"],look:n.look};e.push(A)}}for(let a of this.classes.keys()){let c=this.classes.get(a);if(c){let A=c;A.parentId=c.parent,A.look=n.look,e.push(A)}}let u=0;for(let a of this.notes){u++;let c={id:a.id,label:a.text,isGroup:!1,shape:"note",padding:n.class.padding??6,cssStyles:["text-align: left","white-space: nowrap",`fill: ${n.themeVariables.noteBkgColor}`,`stroke: ${n.themeVariables.noteBorderColor}`],look:n.look};e.push(c);let A=this.classes.get(a.class)?.id??"";if(A){let b={id:`edgeNote${u}`,start:a.id,end:A,type:"normal",thickness:"normal",classes:"relation",arrowTypeStart:"none",arrowTypeEnd:"none",arrowheadStyle:"",labelStyle:[""],style:["fill: none"],pattern:"dotted",look:n.look};i.push(b)}}for(let a of this.interfaces){let c={id:a.id,label:a.label,isGroup:!1,shape:"rect",cssStyles:["opacity: 0;"],look:n.look};e.push(c)}u=0;for(let a of this.relations){u++;let c={id:et(a.id1,a.id2,{prefix:"id",counter:u}),start:a.id1,end:a.id2,type:"normal",label:a.title,labelpos:"c",thickness:"normal",classes:"relation",arrowTypeStart:this.getArrowMarker(a.relation.type1),arrowTypeEnd:this.getArrowMarker(a.relation.type2),startLabelRight:a.relationTitle1==="none"?"":a.relationTitle1,endLabelLeft:a.relationTitle2==="none"?"":a.relationTitle2,arrowheadStyle:"",labelStyle:["display: inline-block"],style:a.style||"",pattern:a.relation.lineType==1?"dashed":"solid",look:n.look};i.push(c)}return{nodes:e,edges:i,other:{},config:n,direction:this.getDirection()}}},At=p(e=>`g.classGroup text { + fill: ${e.nodeBorder||e.classText}; + stroke: none; + font-family: ${e.fontFamily}; + font-size: 10px; + + .title { + font-weight: bolder; + } + +} + +.nodeLabel, .edgeLabel { + color: ${e.classText}; +} +.edgeLabel .label rect { + fill: ${e.mainBkg}; +} +.label text { + fill: ${e.classText}; +} + +.labelBkg { + background: ${e.mainBkg}; +} +.edgeLabel .label span { + background: ${e.mainBkg}; +} + +.classTitle { + font-weight: bolder; +} +.node rect, + .node circle, + .node ellipse, + .node polygon, + .node path { + fill: ${e.mainBkg}; + stroke: ${e.nodeBorder}; + stroke-width: 1px; + } + + +.divider { + stroke: ${e.nodeBorder}; + stroke-width: 1; +} + +g.clickable { + cursor: pointer; +} + +g.classGroup rect { + fill: ${e.mainBkg}; + stroke: ${e.nodeBorder}; +} + +g.classGroup line { + stroke: ${e.nodeBorder}; + stroke-width: 1; +} + +.classLabel .box { + stroke: none; + stroke-width: 0; + fill: ${e.mainBkg}; + opacity: 0.5; +} + +.classLabel .label { + fill: ${e.nodeBorder}; + font-size: 10px; +} + +.relation { + stroke: ${e.lineColor}; + stroke-width: 1; + fill: none; +} + +.dashed-line{ + stroke-dasharray: 3; +} + +.dotted-line{ + stroke-dasharray: 1 2; +} + +#compositionStart, .composition { + fill: ${e.lineColor} !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +#compositionEnd, .composition { + fill: ${e.lineColor} !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +#dependencyStart, .dependency { + fill: ${e.lineColor} !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +#dependencyStart, .dependency { + fill: ${e.lineColor} !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +#extensionStart, .extension { + fill: transparent !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +#extensionEnd, .extension { + fill: transparent !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +#aggregationStart, .aggregation { + fill: transparent !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +#aggregationEnd, .aggregation { + fill: transparent !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +#lollipopStart, .lollipop { + fill: ${e.mainBkg} !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +#lollipopEnd, .lollipop { + fill: ${e.mainBkg} !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +.edgeTerminals { + font-size: 11px; + line-height: initial; +} + +.classTitleText { + text-anchor: middle; + font-size: 18px; + fill: ${e.textColor}; +} + ${it()} +`,"getStyles"),Nt=At,bt=p((e,i="TB")=>{if(!e.doc)return i;let n=i;for(let u of e.doc)u.stmt==="dir"&&(n=u.value);return n},"getDir"),ft=p(function(e,i){return i.db.getClasses()},"getClasses"),kt=p(async function(e,i,n,u){ce.info("REF0:"),ce.info("Drawing class diagram (v3)",i);let{securityLevel:a,state:c,layout:A}=T(),b=u.db.getData(),D=at(i,a);b.type=u.type,b.layoutAlgorithm=st(A),b.nodeSpacing=c?.nodeSpacing||50,b.rankSpacing=c?.rankSpacing||50,b.markers=["aggregation","extension","composition","dependency","lollipop"],b.diagramId=i,await tt(b,D);let _=8;he.insertTitle(D,"classDiagramTitleText",c?.titleTopMargin??25,u.db.getDiagramTitle()),rt(D,_,"classDiagram",c?.useMaxWidth??!0)},"draw"),Lt={getClasses:ft,draw:kt,getDir:bt};export{Bt as a,St as b,Nt as c,Lt as d}; +//# sourceMappingURL=chunk-X6BGXIUN.min.js.map diff --git a/docs/website/public/chunk-X6BGXIUN.min.js.map b/docs/website/public/chunk-X6BGXIUN.min.js.map new file mode 100644 index 000000000..9a2434c2a --- /dev/null +++ b/docs/website/public/chunk-X6BGXIUN.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/mermaid/dist/chunks/mermaid.core/chunk-B4BG7PRW.mjs"], + "sourcesContent": ["import {\n getIconStyles\n} from \"./chunk-FMBD7UC4.mjs\";\nimport {\n getDiagramElement\n} from \"./chunk-55IACEB6.mjs\";\nimport {\n setupViewPortForSVG\n} from \"./chunk-QN33PNHL.mjs\";\nimport {\n getRegisteredLayoutAlgorithm,\n render\n} from \"./chunk-N4CR4FBY.mjs\";\nimport {\n getEdgeId,\n utils_default\n} from \"./chunk-S3R3BYOJ.mjs\";\nimport {\n clear,\n common_default,\n getAccDescription,\n getAccTitle,\n getConfig2 as getConfig,\n getDiagramTitle,\n parseGenericTypes,\n sanitizeText,\n setAccDescription,\n setAccTitle,\n setDiagramTitle\n} from \"./chunk-ABZYJK2D.mjs\";\nimport {\n __name,\n log\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/diagrams/class/parser/classDiagram.jison\nvar parser = (function() {\n var o = /* @__PURE__ */ __name(function(k, v, o2, l) {\n for (o2 = o2 || {}, l = k.length; l--; o2[k[l]] = v) ;\n return o2;\n }, \"o\"), $V0 = [1, 18], $V1 = [1, 19], $V2 = [1, 20], $V3 = [1, 41], $V4 = [1, 42], $V5 = [1, 26], $V6 = [1, 24], $V7 = [1, 25], $V8 = [1, 32], $V9 = [1, 33], $Va = [1, 34], $Vb = [1, 45], $Vc = [1, 35], $Vd = [1, 36], $Ve = [1, 37], $Vf = [1, 38], $Vg = [1, 27], $Vh = [1, 28], $Vi = [1, 29], $Vj = [1, 30], $Vk = [1, 31], $Vl = [1, 44], $Vm = [1, 46], $Vn = [1, 43], $Vo = [1, 47], $Vp = [1, 9], $Vq = [1, 8, 9], $Vr = [1, 58], $Vs = [1, 59], $Vt = [1, 60], $Vu = [1, 61], $Vv = [1, 62], $Vw = [1, 63], $Vx = [1, 64], $Vy = [1, 8, 9, 41], $Vz = [1, 76], $VA = [1, 8, 9, 12, 13, 22, 39, 41, 44, 68, 69, 70, 71, 72, 73, 74, 79, 81], $VB = [1, 8, 9, 12, 13, 18, 20, 22, 39, 41, 44, 50, 60, 68, 69, 70, 71, 72, 73, 74, 79, 81, 86, 100, 102, 103], $VC = [13, 60, 86, 100, 102, 103], $VD = [13, 60, 73, 74, 86, 100, 102, 103], $VE = [13, 60, 68, 69, 70, 71, 72, 86, 100, 102, 103], $VF = [1, 100], $VG = [1, 117], $VH = [1, 113], $VI = [1, 109], $VJ = [1, 115], $VK = [1, 110], $VL = [1, 111], $VM = [1, 112], $VN = [1, 114], $VO = [1, 116], $VP = [22, 48, 60, 61, 82, 86, 87, 88, 89, 90], $VQ = [1, 8, 9, 39, 41, 44], $VR = [1, 8, 9, 22], $VS = [1, 145], $VT = [1, 8, 9, 61], $VU = [1, 8, 9, 22, 48, 60, 61, 82, 86, 87, 88, 89, 90];\n var parser2 = {\n trace: /* @__PURE__ */ __name(function trace() {\n }, \"trace\"),\n yy: {},\n symbols_: { \"error\": 2, \"start\": 3, \"mermaidDoc\": 4, \"statements\": 5, \"graphConfig\": 6, \"CLASS_DIAGRAM\": 7, \"NEWLINE\": 8, \"EOF\": 9, \"statement\": 10, \"classLabel\": 11, \"SQS\": 12, \"STR\": 13, \"SQE\": 14, \"namespaceName\": 15, \"alphaNumToken\": 16, \"classLiteralName\": 17, \"DOT\": 18, \"className\": 19, \"GENERICTYPE\": 20, \"relationStatement\": 21, \"LABEL\": 22, \"namespaceStatement\": 23, \"classStatement\": 24, \"memberStatement\": 25, \"annotationStatement\": 26, \"clickStatement\": 27, \"styleStatement\": 28, \"cssClassStatement\": 29, \"noteStatement\": 30, \"classDefStatement\": 31, \"direction\": 32, \"acc_title\": 33, \"acc_title_value\": 34, \"acc_descr\": 35, \"acc_descr_value\": 36, \"acc_descr_multiline_value\": 37, \"namespaceIdentifier\": 38, \"STRUCT_START\": 39, \"classStatements\": 40, \"STRUCT_STOP\": 41, \"NAMESPACE\": 42, \"classIdentifier\": 43, \"STYLE_SEPARATOR\": 44, \"members\": 45, \"CLASS\": 46, \"emptyBody\": 47, \"SPACE\": 48, \"ANNOTATION_START\": 49, \"ANNOTATION_END\": 50, \"MEMBER\": 51, \"SEPARATOR\": 52, \"relation\": 53, \"NOTE_FOR\": 54, \"noteText\": 55, \"NOTE\": 56, \"CLASSDEF\": 57, \"classList\": 58, \"stylesOpt\": 59, \"ALPHA\": 60, \"COMMA\": 61, \"direction_tb\": 62, \"direction_bt\": 63, \"direction_rl\": 64, \"direction_lr\": 65, \"relationType\": 66, \"lineType\": 67, \"AGGREGATION\": 68, \"EXTENSION\": 69, \"COMPOSITION\": 70, \"DEPENDENCY\": 71, \"LOLLIPOP\": 72, \"LINE\": 73, \"DOTTED_LINE\": 74, \"CALLBACK\": 75, \"LINK\": 76, \"LINK_TARGET\": 77, \"CLICK\": 78, \"CALLBACK_NAME\": 79, \"CALLBACK_ARGS\": 80, \"HREF\": 81, \"STYLE\": 82, \"CSSCLASS\": 83, \"style\": 84, \"styleComponent\": 85, \"NUM\": 86, \"COLON\": 87, \"UNIT\": 88, \"BRKT\": 89, \"PCT\": 90, \"commentToken\": 91, \"textToken\": 92, \"graphCodeTokens\": 93, \"textNoTagsToken\": 94, \"TAGSTART\": 95, \"TAGEND\": 96, \"==\": 97, \"--\": 98, \"DEFAULT\": 99, \"MINUS\": 100, \"keywords\": 101, \"UNICODE_TEXT\": 102, \"BQUOTE_STR\": 103, \"$accept\": 0, \"$end\": 1 },\n terminals_: { 2: \"error\", 7: \"CLASS_DIAGRAM\", 8: \"NEWLINE\", 9: \"EOF\", 12: \"SQS\", 13: \"STR\", 14: \"SQE\", 18: \"DOT\", 20: \"GENERICTYPE\", 22: \"LABEL\", 33: \"acc_title\", 34: \"acc_title_value\", 35: \"acc_descr\", 36: \"acc_descr_value\", 37: \"acc_descr_multiline_value\", 39: \"STRUCT_START\", 41: \"STRUCT_STOP\", 42: \"NAMESPACE\", 44: \"STYLE_SEPARATOR\", 46: \"CLASS\", 48: \"SPACE\", 49: \"ANNOTATION_START\", 50: \"ANNOTATION_END\", 51: \"MEMBER\", 52: \"SEPARATOR\", 54: \"NOTE_FOR\", 56: \"NOTE\", 57: \"CLASSDEF\", 60: \"ALPHA\", 61: \"COMMA\", 62: \"direction_tb\", 63: \"direction_bt\", 64: \"direction_rl\", 65: \"direction_lr\", 68: \"AGGREGATION\", 69: \"EXTENSION\", 70: \"COMPOSITION\", 71: \"DEPENDENCY\", 72: \"LOLLIPOP\", 73: \"LINE\", 74: \"DOTTED_LINE\", 75: \"CALLBACK\", 76: \"LINK\", 77: \"LINK_TARGET\", 78: \"CLICK\", 79: \"CALLBACK_NAME\", 80: \"CALLBACK_ARGS\", 81: \"HREF\", 82: \"STYLE\", 83: \"CSSCLASS\", 86: \"NUM\", 87: \"COLON\", 88: \"UNIT\", 89: \"BRKT\", 90: \"PCT\", 93: \"graphCodeTokens\", 95: \"TAGSTART\", 96: \"TAGEND\", 97: \"==\", 98: \"--\", 99: \"DEFAULT\", 100: \"MINUS\", 101: \"keywords\", 102: \"UNICODE_TEXT\", 103: \"BQUOTE_STR\" },\n productions_: [0, [3, 1], [3, 1], [4, 1], [6, 4], [5, 1], [5, 2], [5, 3], [11, 3], [15, 1], [15, 1], [15, 3], [15, 2], [19, 1], [19, 3], [19, 1], [19, 2], [19, 2], [19, 2], [10, 1], [10, 2], [10, 1], [10, 1], [10, 1], [10, 1], [10, 1], [10, 1], [10, 1], [10, 1], [10, 1], [10, 1], [10, 2], [10, 2], [10, 1], [23, 4], [23, 5], [38, 2], [40, 1], [40, 2], [40, 3], [24, 1], [24, 3], [24, 4], [24, 3], [24, 6], [43, 2], [43, 3], [47, 0], [47, 2], [47, 2], [26, 4], [45, 1], [45, 2], [25, 1], [25, 2], [25, 1], [25, 1], [21, 3], [21, 4], [21, 4], [21, 5], [30, 3], [30, 2], [31, 3], [58, 1], [58, 3], [32, 1], [32, 1], [32, 1], [32, 1], [53, 3], [53, 2], [53, 2], [53, 1], [66, 1], [66, 1], [66, 1], [66, 1], [66, 1], [67, 1], [67, 1], [27, 3], [27, 4], [27, 3], [27, 4], [27, 4], [27, 5], [27, 3], [27, 4], [27, 4], [27, 5], [27, 4], [27, 5], [27, 5], [27, 6], [28, 3], [29, 3], [59, 1], [59, 3], [84, 1], [84, 2], [85, 1], [85, 1], [85, 1], [85, 1], [85, 1], [85, 1], [85, 1], [85, 1], [85, 1], [91, 1], [91, 1], [92, 1], [92, 1], [92, 1], [92, 1], [92, 1], [92, 1], [92, 1], [94, 1], [94, 1], [94, 1], [94, 1], [16, 1], [16, 1], [16, 1], [16, 1], [17, 1], [55, 1]],\n performAction: /* @__PURE__ */ __name(function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$) {\n var $0 = $$.length - 1;\n switch (yystate) {\n case 8:\n this.$ = $$[$0 - 1];\n break;\n case 9:\n case 10:\n case 13:\n case 15:\n this.$ = $$[$0];\n break;\n case 11:\n case 14:\n this.$ = $$[$0 - 2] + \".\" + $$[$0];\n break;\n case 12:\n case 16:\n this.$ = $$[$0 - 1] + $$[$0];\n break;\n case 17:\n case 18:\n this.$ = $$[$0 - 1] + \"~\" + $$[$0] + \"~\";\n break;\n case 19:\n yy.addRelation($$[$0]);\n break;\n case 20:\n $$[$0 - 1].title = yy.cleanupLabel($$[$0]);\n yy.addRelation($$[$0 - 1]);\n break;\n case 31:\n this.$ = $$[$0].trim();\n yy.setAccTitle(this.$);\n break;\n case 32:\n case 33:\n this.$ = $$[$0].trim();\n yy.setAccDescription(this.$);\n break;\n case 34:\n yy.addClassesToNamespace($$[$0 - 3], $$[$0 - 1]);\n break;\n case 35:\n yy.addClassesToNamespace($$[$0 - 4], $$[$0 - 1]);\n break;\n case 36:\n this.$ = $$[$0];\n yy.addNamespace($$[$0]);\n break;\n case 37:\n this.$ = [$$[$0]];\n break;\n case 38:\n this.$ = [$$[$0 - 1]];\n break;\n case 39:\n $$[$0].unshift($$[$0 - 2]);\n this.$ = $$[$0];\n break;\n case 41:\n yy.setCssClass($$[$0 - 2], $$[$0]);\n break;\n case 42:\n yy.addMembers($$[$0 - 3], $$[$0 - 1]);\n break;\n case 44:\n yy.setCssClass($$[$0 - 5], $$[$0 - 3]);\n yy.addMembers($$[$0 - 5], $$[$0 - 1]);\n break;\n case 45:\n this.$ = $$[$0];\n yy.addClass($$[$0]);\n break;\n case 46:\n this.$ = $$[$0 - 1];\n yy.addClass($$[$0 - 1]);\n yy.setClassLabel($$[$0 - 1], $$[$0]);\n break;\n case 50:\n yy.addAnnotation($$[$0], $$[$0 - 2]);\n break;\n case 51:\n case 64:\n this.$ = [$$[$0]];\n break;\n case 52:\n $$[$0].push($$[$0 - 1]);\n this.$ = $$[$0];\n break;\n case 53:\n break;\n case 54:\n yy.addMember($$[$0 - 1], yy.cleanupLabel($$[$0]));\n break;\n case 55:\n break;\n case 56:\n break;\n case 57:\n this.$ = { \"id1\": $$[$0 - 2], \"id2\": $$[$0], relation: $$[$0 - 1], relationTitle1: \"none\", relationTitle2: \"none\" };\n break;\n case 58:\n this.$ = { id1: $$[$0 - 3], id2: $$[$0], relation: $$[$0 - 1], relationTitle1: $$[$0 - 2], relationTitle2: \"none\" };\n break;\n case 59:\n this.$ = { id1: $$[$0 - 3], id2: $$[$0], relation: $$[$0 - 2], relationTitle1: \"none\", relationTitle2: $$[$0 - 1] };\n break;\n case 60:\n this.$ = { id1: $$[$0 - 4], id2: $$[$0], relation: $$[$0 - 2], relationTitle1: $$[$0 - 3], relationTitle2: $$[$0 - 1] };\n break;\n case 61:\n yy.addNote($$[$0], $$[$0 - 1]);\n break;\n case 62:\n yy.addNote($$[$0]);\n break;\n case 63:\n this.$ = $$[$0 - 2];\n yy.defineClass($$[$0 - 1], $$[$0]);\n break;\n case 65:\n this.$ = $$[$0 - 2].concat([$$[$0]]);\n break;\n case 66:\n yy.setDirection(\"TB\");\n break;\n case 67:\n yy.setDirection(\"BT\");\n break;\n case 68:\n yy.setDirection(\"RL\");\n break;\n case 69:\n yy.setDirection(\"LR\");\n break;\n case 70:\n this.$ = { type1: $$[$0 - 2], type2: $$[$0], lineType: $$[$0 - 1] };\n break;\n case 71:\n this.$ = { type1: \"none\", type2: $$[$0], lineType: $$[$0 - 1] };\n break;\n case 72:\n this.$ = { type1: $$[$0 - 1], type2: \"none\", lineType: $$[$0] };\n break;\n case 73:\n this.$ = { type1: \"none\", type2: \"none\", lineType: $$[$0] };\n break;\n case 74:\n this.$ = yy.relationType.AGGREGATION;\n break;\n case 75:\n this.$ = yy.relationType.EXTENSION;\n break;\n case 76:\n this.$ = yy.relationType.COMPOSITION;\n break;\n case 77:\n this.$ = yy.relationType.DEPENDENCY;\n break;\n case 78:\n this.$ = yy.relationType.LOLLIPOP;\n break;\n case 79:\n this.$ = yy.lineType.LINE;\n break;\n case 80:\n this.$ = yy.lineType.DOTTED_LINE;\n break;\n case 81:\n case 87:\n this.$ = $$[$0 - 2];\n yy.setClickEvent($$[$0 - 1], $$[$0]);\n break;\n case 82:\n case 88:\n this.$ = $$[$0 - 3];\n yy.setClickEvent($$[$0 - 2], $$[$0 - 1]);\n yy.setTooltip($$[$0 - 2], $$[$0]);\n break;\n case 83:\n this.$ = $$[$0 - 2];\n yy.setLink($$[$0 - 1], $$[$0]);\n break;\n case 84:\n this.$ = $$[$0 - 3];\n yy.setLink($$[$0 - 2], $$[$0 - 1], $$[$0]);\n break;\n case 85:\n this.$ = $$[$0 - 3];\n yy.setLink($$[$0 - 2], $$[$0 - 1]);\n yy.setTooltip($$[$0 - 2], $$[$0]);\n break;\n case 86:\n this.$ = $$[$0 - 4];\n yy.setLink($$[$0 - 3], $$[$0 - 2], $$[$0]);\n yy.setTooltip($$[$0 - 3], $$[$0 - 1]);\n break;\n case 89:\n this.$ = $$[$0 - 3];\n yy.setClickEvent($$[$0 - 2], $$[$0 - 1], $$[$0]);\n break;\n case 90:\n this.$ = $$[$0 - 4];\n yy.setClickEvent($$[$0 - 3], $$[$0 - 2], $$[$0 - 1]);\n yy.setTooltip($$[$0 - 3], $$[$0]);\n break;\n case 91:\n this.$ = $$[$0 - 3];\n yy.setLink($$[$0 - 2], $$[$0]);\n break;\n case 92:\n this.$ = $$[$0 - 4];\n yy.setLink($$[$0 - 3], $$[$0 - 1], $$[$0]);\n break;\n case 93:\n this.$ = $$[$0 - 4];\n yy.setLink($$[$0 - 3], $$[$0 - 1]);\n yy.setTooltip($$[$0 - 3], $$[$0]);\n break;\n case 94:\n this.$ = $$[$0 - 5];\n yy.setLink($$[$0 - 4], $$[$0 - 2], $$[$0]);\n yy.setTooltip($$[$0 - 4], $$[$0 - 1]);\n break;\n case 95:\n this.$ = $$[$0 - 2];\n yy.setCssStyle($$[$0 - 1], $$[$0]);\n break;\n case 96:\n yy.setCssClass($$[$0 - 1], $$[$0]);\n break;\n case 97:\n this.$ = [$$[$0]];\n break;\n case 98:\n $$[$0 - 2].push($$[$0]);\n this.$ = $$[$0 - 2];\n break;\n case 100:\n this.$ = $$[$0 - 1] + $$[$0];\n break;\n }\n }, \"anonymous\"),\n table: [{ 3: 1, 4: 2, 5: 3, 6: 4, 7: [1, 6], 10: 5, 16: 39, 17: 40, 19: 21, 21: 7, 23: 8, 24: 9, 25: 10, 26: 11, 27: 12, 28: 13, 29: 14, 30: 15, 31: 16, 32: 17, 33: $V0, 35: $V1, 37: $V2, 38: 22, 42: $V3, 43: 23, 46: $V4, 49: $V5, 51: $V6, 52: $V7, 54: $V8, 56: $V9, 57: $Va, 60: $Vb, 62: $Vc, 63: $Vd, 64: $Ve, 65: $Vf, 75: $Vg, 76: $Vh, 78: $Vi, 82: $Vj, 83: $Vk, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }, { 1: [3] }, { 1: [2, 1] }, { 1: [2, 2] }, { 1: [2, 3] }, o($Vp, [2, 5], { 8: [1, 48] }), { 8: [1, 49] }, o($Vq, [2, 19], { 22: [1, 50] }), o($Vq, [2, 21]), o($Vq, [2, 22]), o($Vq, [2, 23]), o($Vq, [2, 24]), o($Vq, [2, 25]), o($Vq, [2, 26]), o($Vq, [2, 27]), o($Vq, [2, 28]), o($Vq, [2, 29]), o($Vq, [2, 30]), { 34: [1, 51] }, { 36: [1, 52] }, o($Vq, [2, 33]), o($Vq, [2, 53], { 53: 53, 66: 56, 67: 57, 13: [1, 54], 22: [1, 55], 68: $Vr, 69: $Vs, 70: $Vt, 71: $Vu, 72: $Vv, 73: $Vw, 74: $Vx }), { 39: [1, 65] }, o($Vy, [2, 40], { 39: [1, 67], 44: [1, 66] }), o($Vq, [2, 55]), o($Vq, [2, 56]), { 16: 68, 60: $Vb, 86: $Vl, 100: $Vm, 102: $Vn }, { 16: 39, 17: 40, 19: 69, 60: $Vb, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }, { 16: 39, 17: 40, 19: 70, 60: $Vb, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }, { 16: 39, 17: 40, 19: 71, 60: $Vb, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }, { 60: [1, 72] }, { 13: [1, 73] }, { 16: 39, 17: 40, 19: 74, 60: $Vb, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }, { 13: $Vz, 55: 75 }, { 58: 77, 60: [1, 78] }, o($Vq, [2, 66]), o($Vq, [2, 67]), o($Vq, [2, 68]), o($Vq, [2, 69]), o($VA, [2, 13], { 16: 39, 17: 40, 19: 80, 18: [1, 79], 20: [1, 81], 60: $Vb, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }), o($VA, [2, 15], { 20: [1, 82] }), { 15: 83, 16: 84, 17: 85, 60: $Vb, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }, { 16: 39, 17: 40, 19: 86, 60: $Vb, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }, o($VB, [2, 123]), o($VB, [2, 124]), o($VB, [2, 125]), o($VB, [2, 126]), o([1, 8, 9, 12, 13, 20, 22, 39, 41, 44, 68, 69, 70, 71, 72, 73, 74, 79, 81], [2, 127]), o($Vp, [2, 6], { 10: 5, 21: 7, 23: 8, 24: 9, 25: 10, 26: 11, 27: 12, 28: 13, 29: 14, 30: 15, 31: 16, 32: 17, 19: 21, 38: 22, 43: 23, 16: 39, 17: 40, 5: 87, 33: $V0, 35: $V1, 37: $V2, 42: $V3, 46: $V4, 49: $V5, 51: $V6, 52: $V7, 54: $V8, 56: $V9, 57: $Va, 60: $Vb, 62: $Vc, 63: $Vd, 64: $Ve, 65: $Vf, 75: $Vg, 76: $Vh, 78: $Vi, 82: $Vj, 83: $Vk, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }), { 5: 88, 10: 5, 16: 39, 17: 40, 19: 21, 21: 7, 23: 8, 24: 9, 25: 10, 26: 11, 27: 12, 28: 13, 29: 14, 30: 15, 31: 16, 32: 17, 33: $V0, 35: $V1, 37: $V2, 38: 22, 42: $V3, 43: 23, 46: $V4, 49: $V5, 51: $V6, 52: $V7, 54: $V8, 56: $V9, 57: $Va, 60: $Vb, 62: $Vc, 63: $Vd, 64: $Ve, 65: $Vf, 75: $Vg, 76: $Vh, 78: $Vi, 82: $Vj, 83: $Vk, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }, o($Vq, [2, 20]), o($Vq, [2, 31]), o($Vq, [2, 32]), { 13: [1, 90], 16: 39, 17: 40, 19: 89, 60: $Vb, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }, { 53: 91, 66: 56, 67: 57, 68: $Vr, 69: $Vs, 70: $Vt, 71: $Vu, 72: $Vv, 73: $Vw, 74: $Vx }, o($Vq, [2, 54]), { 67: 92, 73: $Vw, 74: $Vx }, o($VC, [2, 73], { 66: 93, 68: $Vr, 69: $Vs, 70: $Vt, 71: $Vu, 72: $Vv }), o($VD, [2, 74]), o($VD, [2, 75]), o($VD, [2, 76]), o($VD, [2, 77]), o($VD, [2, 78]), o($VE, [2, 79]), o($VE, [2, 80]), { 8: [1, 95], 24: 96, 40: 94, 43: 23, 46: $V4 }, { 16: 97, 60: $Vb, 86: $Vl, 100: $Vm, 102: $Vn }, { 41: [1, 99], 45: 98, 51: $VF }, { 50: [1, 101] }, { 13: [1, 102] }, { 13: [1, 103] }, { 79: [1, 104], 81: [1, 105] }, { 22: $VG, 48: $VH, 59: 106, 60: $VI, 82: $VJ, 84: 107, 85: 108, 86: $VK, 87: $VL, 88: $VM, 89: $VN, 90: $VO }, { 60: [1, 118] }, { 13: $Vz, 55: 119 }, o($Vq, [2, 62]), o($Vq, [2, 128]), { 22: $VG, 48: $VH, 59: 120, 60: $VI, 61: [1, 121], 82: $VJ, 84: 107, 85: 108, 86: $VK, 87: $VL, 88: $VM, 89: $VN, 90: $VO }, o($VP, [2, 64]), { 16: 39, 17: 40, 19: 122, 60: $Vb, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }, o($VA, [2, 16]), o($VA, [2, 17]), o($VA, [2, 18]), { 39: [2, 36] }, { 15: 124, 16: 84, 17: 85, 18: [1, 123], 39: [2, 9], 60: $Vb, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }, { 39: [2, 10] }, o($VQ, [2, 45], { 11: 125, 12: [1, 126] }), o($Vp, [2, 7]), { 9: [1, 127] }, o($VR, [2, 57]), { 16: 39, 17: 40, 19: 128, 60: $Vb, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }, { 13: [1, 130], 16: 39, 17: 40, 19: 129, 60: $Vb, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }, o($VC, [2, 72], { 66: 131, 68: $Vr, 69: $Vs, 70: $Vt, 71: $Vu, 72: $Vv }), o($VC, [2, 71]), { 41: [1, 132] }, { 24: 96, 40: 133, 43: 23, 46: $V4 }, { 8: [1, 134], 41: [2, 37] }, o($Vy, [2, 41], { 39: [1, 135] }), { 41: [1, 136] }, o($Vy, [2, 43]), { 41: [2, 51], 45: 137, 51: $VF }, { 16: 39, 17: 40, 19: 138, 60: $Vb, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }, o($Vq, [2, 81], { 13: [1, 139] }), o($Vq, [2, 83], { 13: [1, 141], 77: [1, 140] }), o($Vq, [2, 87], { 13: [1, 142], 80: [1, 143] }), { 13: [1, 144] }, o($Vq, [2, 95], { 61: $VS }), o($VT, [2, 97], { 85: 146, 22: $VG, 48: $VH, 60: $VI, 82: $VJ, 86: $VK, 87: $VL, 88: $VM, 89: $VN, 90: $VO }), o($VU, [2, 99]), o($VU, [2, 101]), o($VU, [2, 102]), o($VU, [2, 103]), o($VU, [2, 104]), o($VU, [2, 105]), o($VU, [2, 106]), o($VU, [2, 107]), o($VU, [2, 108]), o($VU, [2, 109]), o($Vq, [2, 96]), o($Vq, [2, 61]), o($Vq, [2, 63], { 61: $VS }), { 60: [1, 147] }, o($VA, [2, 14]), { 15: 148, 16: 84, 17: 85, 60: $Vb, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }, { 39: [2, 12] }, o($VQ, [2, 46]), { 13: [1, 149] }, { 1: [2, 4] }, o($VR, [2, 59]), o($VR, [2, 58]), { 16: 39, 17: 40, 19: 150, 60: $Vb, 86: $Vl, 100: $Vm, 102: $Vn, 103: $Vo }, o($VC, [2, 70]), o($Vq, [2, 34]), { 41: [1, 151] }, { 24: 96, 40: 152, 41: [2, 38], 43: 23, 46: $V4 }, { 45: 153, 51: $VF }, o($Vy, [2, 42]), { 41: [2, 52] }, o($Vq, [2, 50]), o($Vq, [2, 82]), o($Vq, [2, 84]), o($Vq, [2, 85], { 77: [1, 154] }), o($Vq, [2, 88]), o($Vq, [2, 89], { 13: [1, 155] }), o($Vq, [2, 91], { 13: [1, 157], 77: [1, 156] }), { 22: $VG, 48: $VH, 60: $VI, 82: $VJ, 84: 158, 85: 108, 86: $VK, 87: $VL, 88: $VM, 89: $VN, 90: $VO }, o($VU, [2, 100]), o($VP, [2, 65]), { 39: [2, 11] }, { 14: [1, 159] }, o($VR, [2, 60]), o($Vq, [2, 35]), { 41: [2, 39] }, { 41: [1, 160] }, o($Vq, [2, 86]), o($Vq, [2, 90]), o($Vq, [2, 92]), o($Vq, [2, 93], { 77: [1, 161] }), o($VT, [2, 98], { 85: 146, 22: $VG, 48: $VH, 60: $VI, 82: $VJ, 86: $VK, 87: $VL, 88: $VM, 89: $VN, 90: $VO }), o($VQ, [2, 8]), o($Vy, [2, 44]), o($Vq, [2, 94])],\n defaultActions: { 2: [2, 1], 3: [2, 2], 4: [2, 3], 83: [2, 36], 85: [2, 10], 124: [2, 12], 127: [2, 4], 137: [2, 52], 148: [2, 11], 152: [2, 39] },\n parseError: /* @__PURE__ */ __name(function parseError(str, hash) {\n if (hash.recoverable) {\n this.trace(str);\n } else {\n var error = new Error(str);\n error.hash = hash;\n throw error;\n }\n }, \"parseError\"),\n parse: /* @__PURE__ */ __name(function parse(input) {\n var self = this, stack = [0], tstack = [], vstack = [null], lstack = [], table = this.table, yytext = \"\", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;\n var args = lstack.slice.call(arguments, 1);\n var lexer2 = Object.create(this.lexer);\n var sharedState = { yy: {} };\n for (var k in this.yy) {\n if (Object.prototype.hasOwnProperty.call(this.yy, k)) {\n sharedState.yy[k] = this.yy[k];\n }\n }\n lexer2.setInput(input, sharedState.yy);\n sharedState.yy.lexer = lexer2;\n sharedState.yy.parser = this;\n if (typeof lexer2.yylloc == \"undefined\") {\n lexer2.yylloc = {};\n }\n var yyloc = lexer2.yylloc;\n lstack.push(yyloc);\n var ranges = lexer2.options && lexer2.options.ranges;\n if (typeof sharedState.yy.parseError === \"function\") {\n this.parseError = sharedState.yy.parseError;\n } else {\n this.parseError = Object.getPrototypeOf(this).parseError;\n }\n function popStack(n) {\n stack.length = stack.length - 2 * n;\n vstack.length = vstack.length - n;\n lstack.length = lstack.length - n;\n }\n __name(popStack, \"popStack\");\n function lex() {\n var token;\n token = tstack.pop() || lexer2.lex() || EOF;\n if (typeof token !== \"number\") {\n if (token instanceof Array) {\n tstack = token;\n token = tstack.pop();\n }\n token = self.symbols_[token] || token;\n }\n return token;\n }\n __name(lex, \"lex\");\n var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;\n while (true) {\n state = stack[stack.length - 1];\n if (this.defaultActions[state]) {\n action = this.defaultActions[state];\n } else {\n if (symbol === null || typeof symbol == \"undefined\") {\n symbol = lex();\n }\n action = table[state] && table[state][symbol];\n }\n if (typeof action === \"undefined\" || !action.length || !action[0]) {\n var errStr = \"\";\n expected = [];\n for (p in table[state]) {\n if (this.terminals_[p] && p > TERROR) {\n expected.push(\"'\" + this.terminals_[p] + \"'\");\n }\n }\n if (lexer2.showPosition) {\n errStr = \"Parse error on line \" + (yylineno + 1) + \":\\n\" + lexer2.showPosition() + \"\\nExpecting \" + expected.join(\", \") + \", got '\" + (this.terminals_[symbol] || symbol) + \"'\";\n } else {\n errStr = \"Parse error on line \" + (yylineno + 1) + \": Unexpected \" + (symbol == EOF ? \"end of input\" : \"'\" + (this.terminals_[symbol] || symbol) + \"'\");\n }\n this.parseError(errStr, {\n text: lexer2.match,\n token: this.terminals_[symbol] || symbol,\n line: lexer2.yylineno,\n loc: yyloc,\n expected\n });\n }\n if (action[0] instanceof Array && action.length > 1) {\n throw new Error(\"Parse Error: multiple actions possible at state: \" + state + \", token: \" + symbol);\n }\n switch (action[0]) {\n case 1:\n stack.push(symbol);\n vstack.push(lexer2.yytext);\n lstack.push(lexer2.yylloc);\n stack.push(action[1]);\n symbol = null;\n if (!preErrorSymbol) {\n yyleng = lexer2.yyleng;\n yytext = lexer2.yytext;\n yylineno = lexer2.yylineno;\n yyloc = lexer2.yylloc;\n if (recovering > 0) {\n recovering--;\n }\n } else {\n symbol = preErrorSymbol;\n preErrorSymbol = null;\n }\n break;\n case 2:\n len = this.productions_[action[1]][1];\n yyval.$ = vstack[vstack.length - len];\n yyval._$ = {\n first_line: lstack[lstack.length - (len || 1)].first_line,\n last_line: lstack[lstack.length - 1].last_line,\n first_column: lstack[lstack.length - (len || 1)].first_column,\n last_column: lstack[lstack.length - 1].last_column\n };\n if (ranges) {\n yyval._$.range = [\n lstack[lstack.length - (len || 1)].range[0],\n lstack[lstack.length - 1].range[1]\n ];\n }\n r = this.performAction.apply(yyval, [\n yytext,\n yyleng,\n yylineno,\n sharedState.yy,\n action[1],\n vstack,\n lstack\n ].concat(args));\n if (typeof r !== \"undefined\") {\n return r;\n }\n if (len) {\n stack = stack.slice(0, -1 * len * 2);\n vstack = vstack.slice(0, -1 * len);\n lstack = lstack.slice(0, -1 * len);\n }\n stack.push(this.productions_[action[1]][0]);\n vstack.push(yyval.$);\n lstack.push(yyval._$);\n newState = table[stack[stack.length - 2]][stack[stack.length - 1]];\n stack.push(newState);\n break;\n case 3:\n return true;\n }\n }\n return true;\n }, \"parse\")\n };\n var lexer = /* @__PURE__ */ (function() {\n var lexer2 = {\n EOF: 1,\n parseError: /* @__PURE__ */ __name(function parseError(str, hash) {\n if (this.yy.parser) {\n this.yy.parser.parseError(str, hash);\n } else {\n throw new Error(str);\n }\n }, \"parseError\"),\n // resets the lexer, sets new input\n setInput: /* @__PURE__ */ __name(function(input, yy) {\n this.yy = yy || this.yy || {};\n this._input = input;\n this._more = this._backtrack = this.done = false;\n this.yylineno = this.yyleng = 0;\n this.yytext = this.matched = this.match = \"\";\n this.conditionStack = [\"INITIAL\"];\n this.yylloc = {\n first_line: 1,\n first_column: 0,\n last_line: 1,\n last_column: 0\n };\n if (this.options.ranges) {\n this.yylloc.range = [0, 0];\n }\n this.offset = 0;\n return this;\n }, \"setInput\"),\n // consumes and returns one char from the input\n input: /* @__PURE__ */ __name(function() {\n var ch = this._input[0];\n this.yytext += ch;\n this.yyleng++;\n this.offset++;\n this.match += ch;\n this.matched += ch;\n var lines = ch.match(/(?:\\r\\n?|\\n).*/g);\n if (lines) {\n this.yylineno++;\n this.yylloc.last_line++;\n } else {\n this.yylloc.last_column++;\n }\n if (this.options.ranges) {\n this.yylloc.range[1]++;\n }\n this._input = this._input.slice(1);\n return ch;\n }, \"input\"),\n // unshifts one char (or a string) into the input\n unput: /* @__PURE__ */ __name(function(ch) {\n var len = ch.length;\n var lines = ch.split(/(?:\\r\\n?|\\n)/g);\n this._input = ch + this._input;\n this.yytext = this.yytext.substr(0, this.yytext.length - len);\n this.offset -= len;\n var oldLines = this.match.split(/(?:\\r\\n?|\\n)/g);\n this.match = this.match.substr(0, this.match.length - 1);\n this.matched = this.matched.substr(0, this.matched.length - 1);\n if (lines.length - 1) {\n this.yylineno -= lines.length - 1;\n }\n var r = this.yylloc.range;\n this.yylloc = {\n first_line: this.yylloc.first_line,\n last_line: this.yylineno + 1,\n first_column: this.yylloc.first_column,\n last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len\n };\n if (this.options.ranges) {\n this.yylloc.range = [r[0], r[0] + this.yyleng - len];\n }\n this.yyleng = this.yytext.length;\n return this;\n }, \"unput\"),\n // When called from action, caches matched text and appends it on next action\n more: /* @__PURE__ */ __name(function() {\n this._more = true;\n return this;\n }, \"more\"),\n // When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead.\n reject: /* @__PURE__ */ __name(function() {\n if (this.options.backtrack_lexer) {\n this._backtrack = true;\n } else {\n return this.parseError(\"Lexical error on line \" + (this.yylineno + 1) + \". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\\n\" + this.showPosition(), {\n text: \"\",\n token: null,\n line: this.yylineno\n });\n }\n return this;\n }, \"reject\"),\n // retain first n characters of the match\n less: /* @__PURE__ */ __name(function(n) {\n this.unput(this.match.slice(n));\n }, \"less\"),\n // displays already matched input, i.e. for error messages\n pastInput: /* @__PURE__ */ __name(function() {\n var past = this.matched.substr(0, this.matched.length - this.match.length);\n return (past.length > 20 ? \"...\" : \"\") + past.substr(-20).replace(/\\n/g, \"\");\n }, \"pastInput\"),\n // displays upcoming input, i.e. for error messages\n upcomingInput: /* @__PURE__ */ __name(function() {\n var next = this.match;\n if (next.length < 20) {\n next += this._input.substr(0, 20 - next.length);\n }\n return (next.substr(0, 20) + (next.length > 20 ? \"...\" : \"\")).replace(/\\n/g, \"\");\n }, \"upcomingInput\"),\n // displays the character position where the lexing error occurred, i.e. for error messages\n showPosition: /* @__PURE__ */ __name(function() {\n var pre = this.pastInput();\n var c = new Array(pre.length + 1).join(\"-\");\n return pre + this.upcomingInput() + \"\\n\" + c + \"^\";\n }, \"showPosition\"),\n // test the lexed token: return FALSE when not a match, otherwise return token\n test_match: /* @__PURE__ */ __name(function(match, indexed_rule) {\n var token, lines, backup;\n if (this.options.backtrack_lexer) {\n backup = {\n yylineno: this.yylineno,\n yylloc: {\n first_line: this.yylloc.first_line,\n last_line: this.last_line,\n first_column: this.yylloc.first_column,\n last_column: this.yylloc.last_column\n },\n yytext: this.yytext,\n match: this.match,\n matches: this.matches,\n matched: this.matched,\n yyleng: this.yyleng,\n offset: this.offset,\n _more: this._more,\n _input: this._input,\n yy: this.yy,\n conditionStack: this.conditionStack.slice(0),\n done: this.done\n };\n if (this.options.ranges) {\n backup.yylloc.range = this.yylloc.range.slice(0);\n }\n }\n lines = match[0].match(/(?:\\r\\n?|\\n).*/g);\n if (lines) {\n this.yylineno += lines.length;\n }\n this.yylloc = {\n first_line: this.yylloc.last_line,\n last_line: this.yylineno + 1,\n first_column: this.yylloc.last_column,\n last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\\r?\\n?/)[0].length : this.yylloc.last_column + match[0].length\n };\n this.yytext += match[0];\n this.match += match[0];\n this.matches = match;\n this.yyleng = this.yytext.length;\n if (this.options.ranges) {\n this.yylloc.range = [this.offset, this.offset += this.yyleng];\n }\n this._more = false;\n this._backtrack = false;\n this._input = this._input.slice(match[0].length);\n this.matched += match[0];\n token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]);\n if (this.done && this._input) {\n this.done = false;\n }\n if (token) {\n return token;\n } else if (this._backtrack) {\n for (var k in backup) {\n this[k] = backup[k];\n }\n return false;\n }\n return false;\n }, \"test_match\"),\n // return next match in input\n next: /* @__PURE__ */ __name(function() {\n if (this.done) {\n return this.EOF;\n }\n if (!this._input) {\n this.done = true;\n }\n var token, match, tempMatch, index;\n if (!this._more) {\n this.yytext = \"\";\n this.match = \"\";\n }\n var rules = this._currentRules();\n for (var i = 0; i < rules.length; i++) {\n tempMatch = this._input.match(this.rules[rules[i]]);\n if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {\n match = tempMatch;\n index = i;\n if (this.options.backtrack_lexer) {\n token = this.test_match(tempMatch, rules[i]);\n if (token !== false) {\n return token;\n } else if (this._backtrack) {\n match = false;\n continue;\n } else {\n return false;\n }\n } else if (!this.options.flex) {\n break;\n }\n }\n }\n if (match) {\n token = this.test_match(match, rules[index]);\n if (token !== false) {\n return token;\n }\n return false;\n }\n if (this._input === \"\") {\n return this.EOF;\n } else {\n return this.parseError(\"Lexical error on line \" + (this.yylineno + 1) + \". Unrecognized text.\\n\" + this.showPosition(), {\n text: \"\",\n token: null,\n line: this.yylineno\n });\n }\n }, \"next\"),\n // return next match that has a token\n lex: /* @__PURE__ */ __name(function lex() {\n var r = this.next();\n if (r) {\n return r;\n } else {\n return this.lex();\n }\n }, \"lex\"),\n // activates a new lexer condition state (pushes the new lexer condition state onto the condition stack)\n begin: /* @__PURE__ */ __name(function begin(condition) {\n this.conditionStack.push(condition);\n }, \"begin\"),\n // pop the previously active lexer condition state off the condition stack\n popState: /* @__PURE__ */ __name(function popState() {\n var n = this.conditionStack.length - 1;\n if (n > 0) {\n return this.conditionStack.pop();\n } else {\n return this.conditionStack[0];\n }\n }, \"popState\"),\n // produce the lexer rule set which is active for the currently active lexer condition state\n _currentRules: /* @__PURE__ */ __name(function _currentRules() {\n if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) {\n return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;\n } else {\n return this.conditions[\"INITIAL\"].rules;\n }\n }, \"_currentRules\"),\n // return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available\n topState: /* @__PURE__ */ __name(function topState(n) {\n n = this.conditionStack.length - 1 - Math.abs(n || 0);\n if (n >= 0) {\n return this.conditionStack[n];\n } else {\n return \"INITIAL\";\n }\n }, \"topState\"),\n // alias for begin(condition)\n pushState: /* @__PURE__ */ __name(function pushState(condition) {\n this.begin(condition);\n }, \"pushState\"),\n // return the number of states currently on the stack\n stateStackSize: /* @__PURE__ */ __name(function stateStackSize() {\n return this.conditionStack.length;\n }, \"stateStackSize\"),\n options: {},\n performAction: /* @__PURE__ */ __name(function anonymous(yy, yy_, $avoiding_name_collisions, YY_START) {\n var YYSTATE = YY_START;\n switch ($avoiding_name_collisions) {\n case 0:\n return 62;\n break;\n case 1:\n return 63;\n break;\n case 2:\n return 64;\n break;\n case 3:\n return 65;\n break;\n case 4:\n break;\n case 5:\n break;\n case 6:\n this.begin(\"acc_title\");\n return 33;\n break;\n case 7:\n this.popState();\n return \"acc_title_value\";\n break;\n case 8:\n this.begin(\"acc_descr\");\n return 35;\n break;\n case 9:\n this.popState();\n return \"acc_descr_value\";\n break;\n case 10:\n this.begin(\"acc_descr_multiline\");\n break;\n case 11:\n this.popState();\n break;\n case 12:\n return \"acc_descr_multiline_value\";\n break;\n case 13:\n return 8;\n break;\n case 14:\n break;\n case 15:\n return 7;\n break;\n case 16:\n return 7;\n break;\n case 17:\n return \"EDGE_STATE\";\n break;\n case 18:\n this.begin(\"callback_name\");\n break;\n case 19:\n this.popState();\n break;\n case 20:\n this.popState();\n this.begin(\"callback_args\");\n break;\n case 21:\n return 79;\n break;\n case 22:\n this.popState();\n break;\n case 23:\n return 80;\n break;\n case 24:\n this.popState();\n break;\n case 25:\n return \"STR\";\n break;\n case 26:\n this.begin(\"string\");\n break;\n case 27:\n return 82;\n break;\n case 28:\n return 57;\n break;\n case 29:\n this.begin(\"namespace\");\n return 42;\n break;\n case 30:\n this.popState();\n return 8;\n break;\n case 31:\n break;\n case 32:\n this.begin(\"namespace-body\");\n return 39;\n break;\n case 33:\n this.popState();\n return 41;\n break;\n case 34:\n return \"EOF_IN_STRUCT\";\n break;\n case 35:\n return 8;\n break;\n case 36:\n break;\n case 37:\n return \"EDGE_STATE\";\n break;\n case 38:\n this.begin(\"class\");\n return 46;\n break;\n case 39:\n this.popState();\n return 8;\n break;\n case 40:\n break;\n case 41:\n this.popState();\n this.popState();\n return 41;\n break;\n case 42:\n this.begin(\"class-body\");\n return 39;\n break;\n case 43:\n this.popState();\n return 41;\n break;\n case 44:\n return \"EOF_IN_STRUCT\";\n break;\n case 45:\n return \"EDGE_STATE\";\n break;\n case 46:\n return \"OPEN_IN_STRUCT\";\n break;\n case 47:\n break;\n case 48:\n return \"MEMBER\";\n break;\n case 49:\n return 83;\n break;\n case 50:\n return 75;\n break;\n case 51:\n return 76;\n break;\n case 52:\n return 78;\n break;\n case 53:\n return 54;\n break;\n case 54:\n return 56;\n break;\n case 55:\n return 49;\n break;\n case 56:\n return 50;\n break;\n case 57:\n return 81;\n break;\n case 58:\n this.popState();\n break;\n case 59:\n return \"GENERICTYPE\";\n break;\n case 60:\n this.begin(\"generic\");\n break;\n case 61:\n this.popState();\n break;\n case 62:\n return \"BQUOTE_STR\";\n break;\n case 63:\n this.begin(\"bqstring\");\n break;\n case 64:\n return 77;\n break;\n case 65:\n return 77;\n break;\n case 66:\n return 77;\n break;\n case 67:\n return 77;\n break;\n case 68:\n return 69;\n break;\n case 69:\n return 69;\n break;\n case 70:\n return 71;\n break;\n case 71:\n return 71;\n break;\n case 72:\n return 70;\n break;\n case 73:\n return 68;\n break;\n case 74:\n return 72;\n break;\n case 75:\n return 73;\n break;\n case 76:\n return 74;\n break;\n case 77:\n return 22;\n break;\n case 78:\n return 44;\n break;\n case 79:\n return 100;\n break;\n case 80:\n return 18;\n break;\n case 81:\n return \"PLUS\";\n break;\n case 82:\n return 87;\n break;\n case 83:\n return 61;\n break;\n case 84:\n return 89;\n break;\n case 85:\n return 89;\n break;\n case 86:\n return 90;\n break;\n case 87:\n return \"EQUALS\";\n break;\n case 88:\n return \"EQUALS\";\n break;\n case 89:\n return 60;\n break;\n case 90:\n return 12;\n break;\n case 91:\n return 14;\n break;\n case 92:\n return \"PUNCTUATION\";\n break;\n case 93:\n return 86;\n break;\n case 94:\n return 102;\n break;\n case 95:\n return 48;\n break;\n case 96:\n return 48;\n break;\n case 97:\n return 9;\n break;\n }\n }, \"anonymous\"),\n rules: [/^(?:.*direction\\s+TB[^\\n]*)/, /^(?:.*direction\\s+BT[^\\n]*)/, /^(?:.*direction\\s+RL[^\\n]*)/, /^(?:.*direction\\s+LR[^\\n]*)/, /^(?:%%(?!\\{)*[^\\n]*(\\r?\\n?)+)/, /^(?:%%[^\\n]*(\\r?\\n)*)/, /^(?:accTitle\\s*:\\s*)/, /^(?:(?!\\n||)*[^\\n]*)/, /^(?:accDescr\\s*:\\s*)/, /^(?:(?!\\n||)*[^\\n]*)/, /^(?:accDescr\\s*\\{\\s*)/, /^(?:[\\}])/, /^(?:[^\\}]*)/, /^(?:\\s*(\\r?\\n)+)/, /^(?:\\s+)/, /^(?:classDiagram-v2\\b)/, /^(?:classDiagram\\b)/, /^(?:\\[\\*\\])/, /^(?:call[\\s]+)/, /^(?:\\([\\s]*\\))/, /^(?:\\()/, /^(?:[^(]*)/, /^(?:\\))/, /^(?:[^)]*)/, /^(?:[\"])/, /^(?:[^\"]*)/, /^(?:[\"])/, /^(?:style\\b)/, /^(?:classDef\\b)/, /^(?:namespace\\b)/, /^(?:\\s*(\\r?\\n)+)/, /^(?:\\s+)/, /^(?:[{])/, /^(?:[}])/, /^(?:$)/, /^(?:\\s*(\\r?\\n)+)/, /^(?:\\s+)/, /^(?:\\[\\*\\])/, /^(?:class\\b)/, /^(?:\\s*(\\r?\\n)+)/, /^(?:\\s+)/, /^(?:[}])/, /^(?:[{])/, /^(?:[}])/, /^(?:$)/, /^(?:\\[\\*\\])/, /^(?:[{])/, /^(?:[\\n])/, /^(?:[^{}\\n]*)/, /^(?:cssClass\\b)/, /^(?:callback\\b)/, /^(?:link\\b)/, /^(?:click\\b)/, /^(?:note for\\b)/, /^(?:note\\b)/, /^(?:<<)/, /^(?:>>)/, /^(?:href\\b)/, /^(?:[~])/, /^(?:[^~]*)/, /^(?:~)/, /^(?:[`])/, /^(?:[^`]+)/, /^(?:[`])/, /^(?:_self\\b)/, /^(?:_blank\\b)/, /^(?:_parent\\b)/, /^(?:_top\\b)/, /^(?:\\s*<\\|)/, /^(?:\\s*\\|>)/, /^(?:\\s*>)/, /^(?:\\s*<)/, /^(?:\\s*\\*)/, /^(?:\\s*o\\b)/, /^(?:\\s*\\(\\))/, /^(?:--)/, /^(?:\\.\\.)/, /^(?::{1}[^:\\n;]+)/, /^(?::{3})/, /^(?:-)/, /^(?:\\.)/, /^(?:\\+)/, /^(?::)/, /^(?:,)/, /^(?:#)/, /^(?:#)/, /^(?:%)/, /^(?:=)/, /^(?:=)/, /^(?:\\w+)/, /^(?:\\[)/, /^(?:\\])/, /^(?:[!\"#$%&'*+,-.`?\\\\/])/, /^(?:[0-9]+)/, /^(?:[\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6]|[\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377]|[\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5]|[\\u03F7-\\u0481\\u048A-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA]|[\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE]|[\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA]|[\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0]|[\\u08A2-\\u08AC\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0977]|[\\u0979-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2]|[\\u09B6-\\u09B9\\u09B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E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3]|[\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6]|[\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A]|[\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081]|[\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D]|[\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0]|[\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310]|[\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C]|[\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u1700-\\u170C\\u170E-\\u1711]|[\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7]|[\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C]|[\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16]|[\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF]|[\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC]|[\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D]|[\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D]|[\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3]|[\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F]|[\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128]|[\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184]|[\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3]|[\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6]|[\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE]|[\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C]|[\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D]|[\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC]|[\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B]|[\\uA640-\\uA66E\\uA67F-\\uA697\\uA6A0-\\uA6E5\\uA717-\\uA71F\\uA722-\\uA788]|[\\uA78B-\\uA78E\\uA790-\\uA793\\uA7A0-\\uA7AA\\uA7F8-\\uA801\\uA803-\\uA805]|[\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB]|[\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uAA00-\\uAA28]|[\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA80-\\uAAAF\\uAAB1\\uAAB5]|[\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4]|[\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E]|[\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D]|[\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36]|[\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D]|[\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC]|[\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF]|[\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC])/, /^(?:\\s)/, /^(?:\\s)/, /^(?:$)/],\n conditions: { \"namespace-body\": { \"rules\": [26, 33, 34, 35, 36, 37, 38, 49, 50, 51, 52, 53, 54, 55, 56, 57, 60, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97], \"inclusive\": false }, \"namespace\": { \"rules\": [26, 29, 30, 31, 32, 49, 50, 51, 52, 53, 54, 55, 56, 57, 60, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97], \"inclusive\": false }, \"class-body\": { \"rules\": [26, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 60, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97], \"inclusive\": false }, \"class\": { \"rules\": [26, 39, 40, 41, 42, 49, 50, 51, 52, 53, 54, 55, 56, 57, 60, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97], \"inclusive\": false }, \"acc_descr_multiline\": { \"rules\": [11, 12, 26, 49, 50, 51, 52, 53, 54, 55, 56, 57, 60, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97], \"inclusive\": false }, \"acc_descr\": { \"rules\": [9, 26, 49, 50, 51, 52, 53, 54, 55, 56, 57, 60, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97], \"inclusive\": false }, \"acc_title\": { \"rules\": [7, 26, 49, 50, 51, 52, 53, 54, 55, 56, 57, 60, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97], \"inclusive\": false }, \"callback_args\": { \"rules\": [22, 23, 26, 49, 50, 51, 52, 53, 54, 55, 56, 57, 60, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97], \"inclusive\": false }, \"callback_name\": { \"rules\": [19, 20, 21, 26, 49, 50, 51, 52, 53, 54, 55, 56, 57, 60, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97], \"inclusive\": false }, \"href\": { \"rules\": [26, 49, 50, 51, 52, 53, 54, 55, 56, 57, 60, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97], \"inclusive\": false }, \"struct\": { \"rules\": [26, 49, 50, 51, 52, 53, 54, 55, 56, 57, 60, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97], \"inclusive\": false }, \"generic\": { \"rules\": [26, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97], \"inclusive\": false }, \"bqstring\": { \"rules\": [26, 49, 50, 51, 52, 53, 54, 55, 56, 57, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97], \"inclusive\": false }, \"string\": { \"rules\": [24, 25, 26, 49, 50, 51, 52, 53, 54, 55, 56, 57, 60, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97], \"inclusive\": false }, \"INITIAL\": { \"rules\": [0, 1, 2, 3, 4, 5, 6, 8, 10, 13, 14, 15, 16, 17, 18, 26, 27, 28, 29, 38, 49, 50, 51, 52, 53, 54, 55, 56, 57, 60, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97], \"inclusive\": true } }\n };\n return lexer2;\n })();\n parser2.lexer = lexer;\n function Parser() {\n this.yy = {};\n }\n __name(Parser, \"Parser\");\n Parser.prototype = parser2;\n parser2.Parser = Parser;\n return new Parser();\n})();\nparser.parser = parser;\nvar classDiagram_default = parser;\n\n// src/diagrams/class/classDb.ts\nimport { select } from \"d3\";\n\n// src/diagrams/class/classTypes.ts\nvar visibilityValues = [\"#\", \"+\", \"~\", \"-\", \"\"];\nvar ClassMember = class {\n static {\n __name(this, \"ClassMember\");\n }\n constructor(input, memberType) {\n this.memberType = memberType;\n this.visibility = \"\";\n this.classifier = \"\";\n this.text = \"\";\n const sanitizedInput = sanitizeText(input, getConfig());\n this.parseMember(sanitizedInput);\n }\n getDisplayDetails() {\n let displayText = this.visibility + parseGenericTypes(this.id);\n if (this.memberType === \"method\") {\n displayText += `(${parseGenericTypes(this.parameters.trim())})`;\n if (this.returnType) {\n displayText += \" : \" + parseGenericTypes(this.returnType);\n }\n }\n displayText = displayText.trim();\n const cssStyle = this.parseClassifier();\n return {\n displayText,\n cssStyle\n };\n }\n parseMember(input) {\n let potentialClassifier = \"\";\n if (this.memberType === \"method\") {\n const methodRegEx = /([#+~-])?(.+)\\((.*)\\)([\\s$*])?(.*)([$*])?/;\n const match = methodRegEx.exec(input);\n if (match) {\n const detectedVisibility = match[1] ? match[1].trim() : \"\";\n if (visibilityValues.includes(detectedVisibility)) {\n this.visibility = detectedVisibility;\n }\n this.id = match[2];\n this.parameters = match[3] ? match[3].trim() : \"\";\n potentialClassifier = match[4] ? match[4].trim() : \"\";\n this.returnType = match[5] ? match[5].trim() : \"\";\n if (potentialClassifier === \"\") {\n const lastChar = this.returnType.substring(this.returnType.length - 1);\n if (/[$*]/.exec(lastChar)) {\n potentialClassifier = lastChar;\n this.returnType = this.returnType.substring(0, this.returnType.length - 1);\n }\n }\n }\n } else {\n const length = input.length;\n const firstChar = input.substring(0, 1);\n const lastChar = input.substring(length - 1);\n if (visibilityValues.includes(firstChar)) {\n this.visibility = firstChar;\n }\n if (/[$*]/.exec(lastChar)) {\n potentialClassifier = lastChar;\n }\n this.id = input.substring(\n this.visibility === \"\" ? 0 : 1,\n potentialClassifier === \"\" ? length : length - 1\n );\n }\n this.classifier = potentialClassifier;\n this.id = this.id.startsWith(\" \") ? \" \" + this.id.trim() : this.id.trim();\n const combinedText = `${this.visibility ? \"\\\\\" + this.visibility : \"\"}${parseGenericTypes(this.id)}${this.memberType === \"method\" ? `(${parseGenericTypes(this.parameters)})${this.returnType ? \" : \" + parseGenericTypes(this.returnType) : \"\"}` : \"\"}`;\n this.text = combinedText.replaceAll(\"<\", \"<\").replaceAll(\">\", \">\");\n if (this.text.startsWith(\"\\\\<\")) {\n this.text = this.text.replace(\"\\\\<\", \"~\");\n }\n }\n parseClassifier() {\n switch (this.classifier) {\n case \"*\":\n return \"font-style:italic;\";\n case \"$\":\n return \"text-decoration:underline;\";\n default:\n return \"\";\n }\n }\n};\n\n// src/diagrams/class/classDb.ts\nvar MERMAID_DOM_ID_PREFIX = \"classId-\";\nvar classCounter = 0;\nvar sanitizeText2 = /* @__PURE__ */ __name((txt) => common_default.sanitizeText(txt, getConfig()), \"sanitizeText\");\nvar ClassDB = class {\n constructor() {\n this.relations = [];\n this.classes = /* @__PURE__ */ new Map();\n this.styleClasses = /* @__PURE__ */ new Map();\n this.notes = [];\n this.interfaces = [];\n // private static classCounter = 0;\n this.namespaces = /* @__PURE__ */ new Map();\n this.namespaceCounter = 0;\n this.functions = [];\n this.lineType = {\n LINE: 0,\n DOTTED_LINE: 1\n };\n this.relationType = {\n AGGREGATION: 0,\n EXTENSION: 1,\n COMPOSITION: 2,\n DEPENDENCY: 3,\n LOLLIPOP: 4\n };\n this.setupToolTips = /* @__PURE__ */ __name((element) => {\n let tooltipElem = select(\".mermaidTooltip\");\n if ((tooltipElem._groups || tooltipElem)[0][0] === null) {\n tooltipElem = select(\"body\").append(\"div\").attr(\"class\", \"mermaidTooltip\").style(\"opacity\", 0);\n }\n const svg = select(element).select(\"svg\");\n const nodes = svg.selectAll(\"g.node\");\n nodes.on(\"mouseover\", (event) => {\n const el = select(event.currentTarget);\n const title = el.attr(\"title\");\n if (title === null) {\n return;\n }\n const rect = this.getBoundingClientRect();\n tooltipElem.transition().duration(200).style(\"opacity\", \".9\");\n tooltipElem.text(el.attr(\"title\")).style(\"left\", window.scrollX + rect.left + (rect.right - rect.left) / 2 + \"px\").style(\"top\", window.scrollY + rect.top - 14 + document.body.scrollTop + \"px\");\n tooltipElem.html(tooltipElem.html().replace(/<br\\/>/g, \"
\"));\n el.classed(\"hover\", true);\n }).on(\"mouseout\", (event) => {\n tooltipElem.transition().duration(500).style(\"opacity\", 0);\n const el = select(event.currentTarget);\n el.classed(\"hover\", false);\n });\n }, \"setupToolTips\");\n this.direction = \"TB\";\n this.setAccTitle = setAccTitle;\n this.getAccTitle = getAccTitle;\n this.setAccDescription = setAccDescription;\n this.getAccDescription = getAccDescription;\n this.setDiagramTitle = setDiagramTitle;\n this.getDiagramTitle = getDiagramTitle;\n this.getConfig = /* @__PURE__ */ __name(() => getConfig().class, \"getConfig\");\n this.functions.push(this.setupToolTips.bind(this));\n this.clear();\n this.addRelation = this.addRelation.bind(this);\n this.addClassesToNamespace = this.addClassesToNamespace.bind(this);\n this.addNamespace = this.addNamespace.bind(this);\n this.setCssClass = this.setCssClass.bind(this);\n this.addMembers = this.addMembers.bind(this);\n this.addClass = this.addClass.bind(this);\n this.setClassLabel = this.setClassLabel.bind(this);\n this.addAnnotation = this.addAnnotation.bind(this);\n this.addMember = this.addMember.bind(this);\n this.cleanupLabel = this.cleanupLabel.bind(this);\n this.addNote = this.addNote.bind(this);\n this.defineClass = this.defineClass.bind(this);\n this.setDirection = this.setDirection.bind(this);\n this.setLink = this.setLink.bind(this);\n this.bindFunctions = this.bindFunctions.bind(this);\n this.clear = this.clear.bind(this);\n this.setTooltip = this.setTooltip.bind(this);\n this.setClickEvent = this.setClickEvent.bind(this);\n this.setCssStyle = this.setCssStyle.bind(this);\n }\n static {\n __name(this, \"ClassDB\");\n }\n splitClassNameAndType(_id) {\n const id = common_default.sanitizeText(_id, getConfig());\n let genericType = \"\";\n let className = id;\n if (id.indexOf(\"~\") > 0) {\n const split = id.split(\"~\");\n className = sanitizeText2(split[0]);\n genericType = sanitizeText2(split[1]);\n }\n return { className, type: genericType };\n }\n setClassLabel(_id, label) {\n const id = common_default.sanitizeText(_id, getConfig());\n if (label) {\n label = sanitizeText2(label);\n }\n const { className } = this.splitClassNameAndType(id);\n this.classes.get(className).label = label;\n this.classes.get(className).text = `${label}${this.classes.get(className).type ? `<${this.classes.get(className).type}>` : \"\"}`;\n }\n /**\n * Function called by parser when a node definition has been found.\n *\n * @param id - ID of the class to add\n * @public\n */\n addClass(_id) {\n const id = common_default.sanitizeText(_id, getConfig());\n const { className, type } = this.splitClassNameAndType(id);\n if (this.classes.has(className)) {\n return;\n }\n const name = common_default.sanitizeText(className, getConfig());\n this.classes.set(name, {\n id: name,\n type,\n label: name,\n text: `${name}${type ? `<${type}>` : \"\"}`,\n shape: \"classBox\",\n cssClasses: \"default\",\n methods: [],\n members: [],\n annotations: [],\n styles: [],\n domId: MERMAID_DOM_ID_PREFIX + name + \"-\" + classCounter\n });\n classCounter++;\n }\n addInterface(label, classId) {\n const classInterface = {\n id: `interface${this.interfaces.length}`,\n label,\n classId\n };\n this.interfaces.push(classInterface);\n }\n /**\n * Function to lookup domId from id in the graph definition.\n *\n * @param id - class ID to lookup\n * @public\n */\n lookUpDomId(_id) {\n const id = common_default.sanitizeText(_id, getConfig());\n if (this.classes.has(id)) {\n return this.classes.get(id).domId;\n }\n throw new Error(\"Class not found: \" + id);\n }\n clear() {\n this.relations = [];\n this.classes = /* @__PURE__ */ new Map();\n this.notes = [];\n this.interfaces = [];\n this.functions = [];\n this.functions.push(this.setupToolTips.bind(this));\n this.namespaces = /* @__PURE__ */ new Map();\n this.namespaceCounter = 0;\n this.direction = \"TB\";\n clear();\n }\n getClass(id) {\n return this.classes.get(id);\n }\n getClasses() {\n return this.classes;\n }\n getRelations() {\n return this.relations;\n }\n getNotes() {\n return this.notes;\n }\n addRelation(classRelation) {\n log.debug(\"Adding relation: \" + JSON.stringify(classRelation));\n const invalidTypes = [\n this.relationType.LOLLIPOP,\n this.relationType.AGGREGATION,\n this.relationType.COMPOSITION,\n this.relationType.DEPENDENCY,\n this.relationType.EXTENSION\n ];\n if (classRelation.relation.type1 === this.relationType.LOLLIPOP && !invalidTypes.includes(classRelation.relation.type2)) {\n this.addClass(classRelation.id2);\n this.addInterface(classRelation.id1, classRelation.id2);\n classRelation.id1 = `interface${this.interfaces.length - 1}`;\n } else if (classRelation.relation.type2 === this.relationType.LOLLIPOP && !invalidTypes.includes(classRelation.relation.type1)) {\n this.addClass(classRelation.id1);\n this.addInterface(classRelation.id2, classRelation.id1);\n classRelation.id2 = `interface${this.interfaces.length - 1}`;\n } else {\n this.addClass(classRelation.id1);\n this.addClass(classRelation.id2);\n }\n classRelation.id1 = this.splitClassNameAndType(classRelation.id1).className;\n classRelation.id2 = this.splitClassNameAndType(classRelation.id2).className;\n classRelation.relationTitle1 = common_default.sanitizeText(\n classRelation.relationTitle1.trim(),\n getConfig()\n );\n classRelation.relationTitle2 = common_default.sanitizeText(\n classRelation.relationTitle2.trim(),\n getConfig()\n );\n this.relations.push(classRelation);\n }\n /**\n * Adds an annotation to the specified class Annotations mark special properties of the given type\n * (like 'interface' or 'service')\n *\n * @param className - The class name\n * @param annotation - The name of the annotation without any brackets\n * @public\n */\n addAnnotation(className, annotation) {\n const validatedClassName = this.splitClassNameAndType(className).className;\n this.classes.get(validatedClassName).annotations.push(annotation);\n }\n /**\n * Adds a member to the specified class\n *\n * @param className - The class name\n * @param member - The full name of the member. If the member is enclosed in `<>` it is\n * treated as an annotation If the member is ending with a closing bracket ) it is treated as a\n * method Otherwise the member will be treated as a normal property\n * @public\n */\n addMember(className, member) {\n this.addClass(className);\n const validatedClassName = this.splitClassNameAndType(className).className;\n const theClass = this.classes.get(validatedClassName);\n if (typeof member === \"string\") {\n const memberString = member.trim();\n if (memberString.startsWith(\"<<\") && memberString.endsWith(\">>\")) {\n theClass.annotations.push(sanitizeText2(memberString.substring(2, memberString.length - 2)));\n } else if (memberString.indexOf(\")\") > 0) {\n theClass.methods.push(new ClassMember(memberString, \"method\"));\n } else if (memberString) {\n theClass.members.push(new ClassMember(memberString, \"attribute\"));\n }\n }\n }\n addMembers(className, members) {\n if (Array.isArray(members)) {\n members.reverse();\n members.forEach((member) => this.addMember(className, member));\n }\n }\n addNote(text, className) {\n const note = {\n id: `note${this.notes.length}`,\n class: className,\n text\n };\n this.notes.push(note);\n }\n cleanupLabel(label) {\n if (label.startsWith(\":\")) {\n label = label.substring(1);\n }\n return sanitizeText2(label.trim());\n }\n /**\n * Called by parser when assigning cssClass to a class\n *\n * @param ids - Comma separated list of ids\n * @param className - Class to add\n */\n setCssClass(ids, className) {\n ids.split(\",\").forEach((_id) => {\n let id = _id;\n if (/\\d/.exec(_id[0])) {\n id = MERMAID_DOM_ID_PREFIX + id;\n }\n const classNode = this.classes.get(id);\n if (classNode) {\n classNode.cssClasses += \" \" + className;\n }\n });\n }\n defineClass(ids, style) {\n for (const id of ids) {\n let styleClass = this.styleClasses.get(id);\n if (styleClass === void 0) {\n styleClass = { id, styles: [], textStyles: [] };\n this.styleClasses.set(id, styleClass);\n }\n if (style) {\n style.forEach((s) => {\n if (/color/.exec(s)) {\n const newStyle = s.replace(\"fill\", \"bgFill\");\n styleClass.textStyles.push(newStyle);\n }\n styleClass.styles.push(s);\n });\n }\n this.classes.forEach((value) => {\n if (value.cssClasses.includes(id)) {\n value.styles.push(...style.flatMap((s) => s.split(\",\")));\n }\n });\n }\n }\n /**\n * Called by parser when a tooltip is found, e.g. a clickable element.\n *\n * @param ids - Comma separated list of ids\n * @param tooltip - Tooltip to add\n */\n setTooltip(ids, tooltip) {\n ids.split(\",\").forEach((id) => {\n if (tooltip !== void 0) {\n this.classes.get(id).tooltip = sanitizeText2(tooltip);\n }\n });\n }\n getTooltip(id, namespace) {\n if (namespace && this.namespaces.has(namespace)) {\n return this.namespaces.get(namespace).classes.get(id).tooltip;\n }\n return this.classes.get(id).tooltip;\n }\n /**\n * Called by parser when a link is found. Adds the URL to the vertex data.\n *\n * @param ids - Comma separated list of ids\n * @param linkStr - URL to create a link for\n * @param target - Target of the link, _blank by default as originally defined in the svgDraw.js file\n */\n setLink(ids, linkStr, target) {\n const config = getConfig();\n ids.split(\",\").forEach((_id) => {\n let id = _id;\n if (/\\d/.exec(_id[0])) {\n id = MERMAID_DOM_ID_PREFIX + id;\n }\n const theClass = this.classes.get(id);\n if (theClass) {\n theClass.link = utils_default.formatUrl(linkStr, config);\n if (config.securityLevel === \"sandbox\") {\n theClass.linkTarget = \"_top\";\n } else if (typeof target === \"string\") {\n theClass.linkTarget = sanitizeText2(target);\n } else {\n theClass.linkTarget = \"_blank\";\n }\n }\n });\n this.setCssClass(ids, \"clickable\");\n }\n /**\n * Called by parser when a click definition is found. Registers an event handler.\n *\n * @param ids - Comma separated list of ids\n * @param functionName - Function to be called on click\n * @param functionArgs - Function args the function should be called with\n */\n setClickEvent(ids, functionName, functionArgs) {\n ids.split(\",\").forEach((id) => {\n this.setClickFunc(id, functionName, functionArgs);\n this.classes.get(id).haveCallback = true;\n });\n this.setCssClass(ids, \"clickable\");\n }\n setClickFunc(_domId, functionName, functionArgs) {\n const domId = common_default.sanitizeText(_domId, getConfig());\n const config = getConfig();\n if (config.securityLevel !== \"loose\") {\n return;\n }\n if (functionName === void 0) {\n return;\n }\n const id = domId;\n if (this.classes.has(id)) {\n const elemId = this.lookUpDomId(id);\n let argList = [];\n if (typeof functionArgs === \"string\") {\n argList = functionArgs.split(/,(?=(?:(?:[^\"]*\"){2})*[^\"]*$)/);\n for (let i = 0; i < argList.length; i++) {\n let item = argList[i].trim();\n if (item.startsWith('\"') && item.endsWith('\"')) {\n item = item.substr(1, item.length - 2);\n }\n argList[i] = item;\n }\n }\n if (argList.length === 0) {\n argList.push(elemId);\n }\n this.functions.push(() => {\n const elem = document.querySelector(`[id=\"${elemId}\"]`);\n if (elem !== null) {\n elem.addEventListener(\n \"click\",\n () => {\n utils_default.runFunc(functionName, ...argList);\n },\n false\n );\n }\n });\n }\n }\n bindFunctions(element) {\n this.functions.forEach((fun) => {\n fun(element);\n });\n }\n getDirection() {\n return this.direction;\n }\n setDirection(dir) {\n this.direction = dir;\n }\n /**\n * Function called by parser when a namespace definition has been found.\n *\n * @param id - ID of the namespace to add\n * @public\n */\n addNamespace(id) {\n if (this.namespaces.has(id)) {\n return;\n }\n this.namespaces.set(id, {\n id,\n classes: /* @__PURE__ */ new Map(),\n children: {},\n domId: MERMAID_DOM_ID_PREFIX + id + \"-\" + this.namespaceCounter\n });\n this.namespaceCounter++;\n }\n getNamespace(name) {\n return this.namespaces.get(name);\n }\n getNamespaces() {\n return this.namespaces;\n }\n /**\n * Function called by parser when a namespace definition has been found.\n *\n * @param id - ID of the namespace to add\n * @param classNames - IDs of the class to add\n * @public\n */\n addClassesToNamespace(id, classNames) {\n if (!this.namespaces.has(id)) {\n return;\n }\n for (const name of classNames) {\n const { className } = this.splitClassNameAndType(name);\n this.classes.get(className).parent = id;\n this.namespaces.get(id).classes.set(className, this.classes.get(className));\n }\n }\n setCssStyle(id, styles) {\n const thisClass = this.classes.get(id);\n if (!styles || !thisClass) {\n return;\n }\n for (const s of styles) {\n if (s.includes(\",\")) {\n thisClass.styles.push(...s.split(\",\"));\n } else {\n thisClass.styles.push(s);\n }\n }\n }\n /**\n * Gets the arrow marker for a type index\n *\n * @param type - The type to look for\n * @returns The arrow marker\n */\n getArrowMarker(type) {\n let marker;\n switch (type) {\n case 0:\n marker = \"aggregation\";\n break;\n case 1:\n marker = \"extension\";\n break;\n case 2:\n marker = \"composition\";\n break;\n case 3:\n marker = \"dependency\";\n break;\n case 4:\n marker = \"lollipop\";\n break;\n default:\n marker = \"none\";\n }\n return marker;\n }\n getData() {\n const nodes = [];\n const edges = [];\n const config = getConfig();\n for (const namespaceKey of this.namespaces.keys()) {\n const namespace = this.namespaces.get(namespaceKey);\n if (namespace) {\n const node = {\n id: namespace.id,\n label: namespace.id,\n isGroup: true,\n padding: config.class.padding ?? 16,\n // parent node must be one of [rect, roundedWithTitle, noteGroup, divider]\n shape: \"rect\",\n cssStyles: [\"fill: none\", \"stroke: black\"],\n look: config.look\n };\n nodes.push(node);\n }\n }\n for (const classKey of this.classes.keys()) {\n const classNode = this.classes.get(classKey);\n if (classNode) {\n const node = classNode;\n node.parentId = classNode.parent;\n node.look = config.look;\n nodes.push(node);\n }\n }\n let cnt = 0;\n for (const note of this.notes) {\n cnt++;\n const noteNode = {\n id: note.id,\n label: note.text,\n isGroup: false,\n shape: \"note\",\n padding: config.class.padding ?? 6,\n cssStyles: [\n \"text-align: left\",\n \"white-space: nowrap\",\n `fill: ${config.themeVariables.noteBkgColor}`,\n `stroke: ${config.themeVariables.noteBorderColor}`\n ],\n look: config.look\n };\n nodes.push(noteNode);\n const noteClassId = this.classes.get(note.class)?.id ?? \"\";\n if (noteClassId) {\n const edge = {\n id: `edgeNote${cnt}`,\n start: note.id,\n end: noteClassId,\n type: \"normal\",\n thickness: \"normal\",\n classes: \"relation\",\n arrowTypeStart: \"none\",\n arrowTypeEnd: \"none\",\n arrowheadStyle: \"\",\n labelStyle: [\"\"],\n style: [\"fill: none\"],\n pattern: \"dotted\",\n look: config.look\n };\n edges.push(edge);\n }\n }\n for (const _interface of this.interfaces) {\n const interfaceNode = {\n id: _interface.id,\n label: _interface.label,\n isGroup: false,\n shape: \"rect\",\n cssStyles: [\"opacity: 0;\"],\n look: config.look\n };\n nodes.push(interfaceNode);\n }\n cnt = 0;\n for (const classRelation of this.relations) {\n cnt++;\n const edge = {\n id: getEdgeId(classRelation.id1, classRelation.id2, {\n prefix: \"id\",\n counter: cnt\n }),\n start: classRelation.id1,\n end: classRelation.id2,\n type: \"normal\",\n label: classRelation.title,\n labelpos: \"c\",\n thickness: \"normal\",\n classes: \"relation\",\n arrowTypeStart: this.getArrowMarker(classRelation.relation.type1),\n arrowTypeEnd: this.getArrowMarker(classRelation.relation.type2),\n startLabelRight: classRelation.relationTitle1 === \"none\" ? \"\" : classRelation.relationTitle1,\n endLabelLeft: classRelation.relationTitle2 === \"none\" ? \"\" : classRelation.relationTitle2,\n arrowheadStyle: \"\",\n labelStyle: [\"display: inline-block\"],\n style: classRelation.style || \"\",\n pattern: classRelation.relation.lineType == 1 ? \"dashed\" : \"solid\",\n look: config.look\n };\n edges.push(edge);\n }\n return { nodes, edges, other: {}, config, direction: this.getDirection() };\n }\n};\n\n// src/diagrams/class/styles.js\nvar getStyles = /* @__PURE__ */ __name((options) => `g.classGroup text {\n fill: ${options.nodeBorder || options.classText};\n stroke: none;\n font-family: ${options.fontFamily};\n font-size: 10px;\n\n .title {\n font-weight: bolder;\n }\n\n}\n\n.nodeLabel, .edgeLabel {\n color: ${options.classText};\n}\n.edgeLabel .label rect {\n fill: ${options.mainBkg};\n}\n.label text {\n fill: ${options.classText};\n}\n\n.labelBkg {\n background: ${options.mainBkg};\n}\n.edgeLabel .label span {\n background: ${options.mainBkg};\n}\n\n.classTitle {\n font-weight: bolder;\n}\n.node rect,\n .node circle,\n .node ellipse,\n .node polygon,\n .node path {\n fill: ${options.mainBkg};\n stroke: ${options.nodeBorder};\n stroke-width: 1px;\n }\n\n\n.divider {\n stroke: ${options.nodeBorder};\n stroke-width: 1;\n}\n\ng.clickable {\n cursor: pointer;\n}\n\ng.classGroup rect {\n fill: ${options.mainBkg};\n stroke: ${options.nodeBorder};\n}\n\ng.classGroup line {\n stroke: ${options.nodeBorder};\n stroke-width: 1;\n}\n\n.classLabel .box {\n stroke: none;\n stroke-width: 0;\n fill: ${options.mainBkg};\n opacity: 0.5;\n}\n\n.classLabel .label {\n fill: ${options.nodeBorder};\n font-size: 10px;\n}\n\n.relation {\n stroke: ${options.lineColor};\n stroke-width: 1;\n fill: none;\n}\n\n.dashed-line{\n stroke-dasharray: 3;\n}\n\n.dotted-line{\n stroke-dasharray: 1 2;\n}\n\n#compositionStart, .composition {\n fill: ${options.lineColor} !important;\n stroke: ${options.lineColor} !important;\n stroke-width: 1;\n}\n\n#compositionEnd, .composition {\n fill: ${options.lineColor} !important;\n stroke: ${options.lineColor} !important;\n stroke-width: 1;\n}\n\n#dependencyStart, .dependency {\n fill: ${options.lineColor} !important;\n stroke: ${options.lineColor} !important;\n stroke-width: 1;\n}\n\n#dependencyStart, .dependency {\n fill: ${options.lineColor} !important;\n stroke: ${options.lineColor} !important;\n stroke-width: 1;\n}\n\n#extensionStart, .extension {\n fill: transparent !important;\n stroke: ${options.lineColor} !important;\n stroke-width: 1;\n}\n\n#extensionEnd, .extension {\n fill: transparent !important;\n stroke: ${options.lineColor} !important;\n stroke-width: 1;\n}\n\n#aggregationStart, .aggregation {\n fill: transparent !important;\n stroke: ${options.lineColor} !important;\n stroke-width: 1;\n}\n\n#aggregationEnd, .aggregation {\n fill: transparent !important;\n stroke: ${options.lineColor} !important;\n stroke-width: 1;\n}\n\n#lollipopStart, .lollipop {\n fill: ${options.mainBkg} !important;\n stroke: ${options.lineColor} !important;\n stroke-width: 1;\n}\n\n#lollipopEnd, .lollipop {\n fill: ${options.mainBkg} !important;\n stroke: ${options.lineColor} !important;\n stroke-width: 1;\n}\n\n.edgeTerminals {\n font-size: 11px;\n line-height: initial;\n}\n\n.classTitleText {\n text-anchor: middle;\n font-size: 18px;\n fill: ${options.textColor};\n}\n ${getIconStyles()}\n`, \"getStyles\");\nvar styles_default = getStyles;\n\n// src/diagrams/class/classRenderer-v3-unified.ts\nvar getDir = /* @__PURE__ */ __name((parsedItem, defaultDir = \"TB\") => {\n if (!parsedItem.doc) {\n return defaultDir;\n }\n let dir = defaultDir;\n for (const parsedItemDoc of parsedItem.doc) {\n if (parsedItemDoc.stmt === \"dir\") {\n dir = parsedItemDoc.value;\n }\n }\n return dir;\n}, \"getDir\");\nvar getClasses = /* @__PURE__ */ __name(function(text, diagramObj) {\n return diagramObj.db.getClasses();\n}, \"getClasses\");\nvar draw = /* @__PURE__ */ __name(async function(text, id, _version, diag) {\n log.info(\"REF0:\");\n log.info(\"Drawing class diagram (v3)\", id);\n const { securityLevel, state: conf, layout } = getConfig();\n const data4Layout = diag.db.getData();\n const svg = getDiagramElement(id, securityLevel);\n data4Layout.type = diag.type;\n data4Layout.layoutAlgorithm = getRegisteredLayoutAlgorithm(layout);\n data4Layout.nodeSpacing = conf?.nodeSpacing || 50;\n data4Layout.rankSpacing = conf?.rankSpacing || 50;\n data4Layout.markers = [\"aggregation\", \"extension\", \"composition\", \"dependency\", \"lollipop\"];\n data4Layout.diagramId = id;\n await render(data4Layout, svg);\n const padding = 8;\n utils_default.insertTitle(\n svg,\n \"classDiagramTitleText\",\n conf?.titleTopMargin ?? 25,\n diag.db.getDiagramTitle()\n );\n setupViewPortForSVG(svg, padding, \"classDiagram\", conf?.useMaxWidth ?? true);\n}, \"draw\");\nvar classRenderer_v3_unified_default = {\n getClasses,\n draw,\n getDir\n};\n\nexport {\n classDiagram_default,\n ClassDB,\n styles_default,\n classRenderer_v3_unified_default\n};\n"], + "mappings": "saAoCA,IAAIA,IAAU,UAAW,CACvB,IAAIC,EAAoBC,EAAO,SAASC,EAAGC,EAAGC,EAAIC,EAAG,CACnD,IAAKD,EAAKA,GAAM,CAAC,EAAGC,EAAIH,EAAE,OAAQG,IAAKD,EAAGF,EAAEG,CAAC,CAAC,EAAIF,EAAG,CACrD,OAAOC,CACT,EAAG,GAAG,EAAGE,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAAC,EAAG,EAAE,EAAGC,EAAM,CAA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IAAK,IACH,MACF,IAAK,IACH,MAAO,GAET,IAAK,IACH,MAAO,GAET,IAAK,IACH,MAAO,aAET,IAAK,IACH,KAAK,MAAM,eAAe,EAC1B,MACF,IAAK,IACH,KAAK,SAAS,EACd,MACF,IAAK,IACH,KAAK,SAAS,EACd,KAAK,MAAM,eAAe,EAC1B,MACF,IAAK,IACH,MAAO,IAET,IAAK,IACH,KAAK,SAAS,EACd,MACF,IAAK,IACH,MAAO,IAET,IAAK,IACH,KAAK,SAAS,EACd,MACF,IAAK,IACH,MAAO,MAET,IAAK,IACH,KAAK,MAAM,QAAQ,EACnB,MACF,IAAK,IACH,MAAO,IAET,IAAK,IACH,MAAO,IAET,IAAK,IACH,YAAK,MAAM,WAAW,EACf,GACP,MACF,IAAK,IACH,YAAK,SAAS,EACP,EACP,MACF,IAAK,IACH,MACF,IAAK,IACH,YAAK,MAAM,gBAAgB,EACpB,GACP,MACF,IAAK,IACH,YAAK,SAAS,EACP,GACP,MACF,IAAK,IACH,MAAO,gBAET,IAAK,IACH,MAAO,GAET,IAAK,IACH,MACF,IAAK,IACH,MAAO,aAET,IAAK,IACH,YAAK,MAAM,OAAO,EACX,GACP,MACF,IAAK,IACH,YAAK,SAAS,EACP,EACP,MACF,IAAK,IACH,MACF,IAAK,IACH,YAAK,SAAS,EACd,KAAK,SAAS,EACP,GACP,MACF,IAAK,IACH,YAAK,MAAM,YAAY,EAChB,GACP,MACF,IAAK,IACH,YAAK,SAAS,EACP,GACP,MACF,IAAK,IACH,MAAO,gBAET,IAAK,IACH,MAAO,aAET,IAAK,IACH,MAAO,iBAET,IAAK,IACH,MACF,IAAK,IACH,MAAO,SAET,IAAK,IACH,MAAO,IAET,IAAK,IACH,MAAO,IAET,IAAK,IACH,MAAO,IAET,IAAK,IACH,MAAO,IAET,IAAK,IACH,MAAO,IAET,IAAK,IACH,MAAO,IAET,IAAK,IACH,MAAO,IAET,IAAK,IACH,MAAO,IAET,IAAK,IACH,MAAO,IAET,IAAK,IACH,K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"$Vd", "$Ve", "$Vf", "$Vg", "$Vh", "$Vi", "$Vj", "$Vk", "$Vl", "$Vm", "$Vn", "$Vo", "$Vp", "$Vq", "$Vr", "$Vs", "$Vt", "$Vu", "$Vv", "$Vw", "$Vx", "$Vy", "$Vz", "$VA", "$VB", "$VC", "$VD", "$VE", "$VF", "$VG", "$VH", "$VI", "$VJ", "$VK", "$VL", "$VM", "$VN", "$VO", "$VP", "$VQ", "$VR", "$VS", "$VT", "$VU", "parser2", "yytext", "yyleng", "yylineno", "yy", "yystate", "$$", "_$", "$0", "str", "hash", "error", "input", "self", "stack", "tstack", "vstack", "lstack", "table", "recovering", "TERROR", "EOF", "args", "lexer2", "sharedState", "yyloc", "ranges", "popStack", "n", "lex", "token", "symbol", "preErrorSymbol", "state", "action", "a", "r", "yyval", "p", "len", "newState", "expected", "errStr", "lexer", "ch", "lines", "oldLines", "past", "next", "pre", "c", "match", "indexed_rule", "backup", "tempMatch", "index", "rules", "i", "condition", "yy_", "$avoiding_name_collisions", "YY_START", "YYSTATE", "Parser", "classDiagram_default", "visibilityValues", "ClassMember", "memberType", "sanitizedInput", "sanitizeText", "getConfig2", "displayText", "parseGenericTypes", "cssStyle", "potentialClassifier", "detectedVisibility", "lastChar", "length", "firstChar", "combinedText", "MERMAID_DOM_ID_PREFIX", "classCounter", "sanitizeText2", "txt", "common_default", "ClassDB", "element", "tooltipElem", "select_default", "event", "el", "rect", "setAccTitle", "getAccTitle", "setAccDescription", "getAccDescription", "setDiagramTitle", "getDiagramTitle", "_id", "id", "genericType", "className", "split", "label", "type", "name", "classId", "classInterface", "clear", "classRelation", "log", "invalidTypes", "annotation", "validatedClassName", "member", "theClass", "memberString", "members", "text", "note", "ids", "classNode", "style", "styleClass", "s", "newStyle", "value", "tooltip", "namespace", "linkStr", "target", "config", "utils_default", "functionName", "functionArgs", "_domId", "domId", "elemId", "argList", "item", "elem", "fun", "dir", "classNames", "styles", "thisClass", "marker", "nodes", "edges", "namespaceKey", "node", "classKey", "cnt", "noteNode", "noteClassId", "edge", "_interface", "interfaceNode", "getEdgeId", "getStyles", "options", "getIconStyles", "styles_default", "getDir", "parsedItem", "defaultDir", "parsedItemDoc", "getClasses", "diagramObj", "draw", "_version", "diag", "securityLevel", "conf", "layout", "data4Layout", "svg", "getDiagramElement", "getRegisteredLayoutAlgorithm", "render", "padding", "setupViewPortForSVG", "classRenderer_v3_unified_default"] +} diff --git a/docs/website/public/chunk-XCAVDAZC.min.js b/docs/website/public/chunk-XCAVDAZC.min.js new file mode 100644 index 000000000..a2fe9ce04 --- /dev/null +++ b/docs/website/public/chunk-XCAVDAZC.min.js @@ -0,0 +1,71 @@ +import{o as $e}from"./chunk-QZZKR5JD.min.js";import{D as q,H as J,J as Se,K as Te,y as X}from"./chunk-3EE2TK35.min.js";import{b as k,d as R,j as F}from"./chunk-6TVUEPFY.min.js";function Ie(n){for(var e=[],r=1;r{let t=n.split(":");if(n.slice(0,1)==="@"){if(t.length<2||t.length>3)return null;s=t.shift().slice(1)}if(t.length>3||!t.length)return null;if(t.length>1){let o=t.pop(),a=t.pop(),c={provider:t.length>0?t[0]:s,prefix:a,name:o};return e&&!M(c)?null:c}let l=t[0],i=l.split("-");if(i.length>1){let o={provider:s,prefix:i.shift(),name:i.join("-")};return e&&!M(o)?null:o}if(r&&s===""){let o={provider:s,prefix:"",name:l};return e&&!M(o,r)?null:o}return null},M=(n,e)=>n?!!((e&&n.prefix===""||n.prefix)&&n.name):!1;function ve(n,e){let r={};!n.hFlip!=!e.hFlip&&(r.hFlip=!0),!n.vFlip!=!e.vFlip&&(r.vFlip=!0);let s=((n.rotate||0)+(e.rotate||0))%4;return s&&(r.rotate=s),r}function te(n,e){let r=ve(n,e);for(let s in Re)s in A?s in n&&!(s in r)&&(r[s]=A[s]):s in e?r[s]=e[s]:s in n&&(r[s]=n[s]);return r}function Ae(n,e){let r=n.icons,s=n.aliases||Object.create(null),t=Object.create(null);function l(i){if(r[i])return t[i]=[];if(!(i in t)){t[i]=null;let o=s[i]&&s[i].parent,a=o&&l(o);a&&(t[i]=[o].concat(a))}return t[i]}return(e||Object.keys(r).concat(Object.keys(s))).forEach(l),t}function Ee(n,e,r){let s=n.icons,t=n.aliases||Object.create(null),l={};function i(o){l=te(s[o]||t[o],l)}return i(e),r.forEach(i),te(n,l)}function ne(n,e){if(n.icons[e])return Ee(n,e,[]);let r=Ae(n,[e])[e];return r?Ee(n,e,r):null}var ct=/(-?[0-9.]*[0-9]+[0-9.]*)/g,pt=/^-?[0-9.]*[0-9]+[0-9.]*$/g;function re(n,e,r){if(e===1)return n;if(r=r||100,typeof n=="number")return Math.ceil(n*e*r)/r;if(typeof n!="string")return n;let s=n.split(ct);if(s===null||!s.length)return n;let t=[],l=s.shift(),i=pt.test(l);for(;;){if(i){let o=parseFloat(l);isNaN(o)?t.push(l):t.push(Math.ceil(o*e*r)/r)}else t.push(l);if(l=s.shift(),l===void 0)return t.join("");i=!i}}function ht(n,e="defs"){let r="",s=n.indexOf("<"+e);for(;s>=0;){let t=n.indexOf(">",s),l=n.indexOf("",l);if(i===-1)break;r+=n.slice(t+1,l).trim(),n=n.slice(0,s).trim()+n.slice(i+1)}return{defs:r,content:n}}function ut(n,e){return n?""+n+""+e:e}function Ce(n,e,r){let s=ht(n);return ut(s.defs,e+s.content+r)}var ft=n=>n==="unset"||n==="undefined"||n==="none";function se(n,e){let r={...Y,...n},s={...ze,...e},t={left:r.left,top:r.top,width:r.width,height:r.height},l=r.body;[r,s].forEach(x=>{let b=[],E=x.hFlip,C=x.vFlip,S=x.rotate;E?C?S+=2:(b.push("translate("+(t.width+t.left).toString()+" "+(0-t.top).toString()+")"),b.push("scale(-1 1)"),t.top=t.left=0):C&&(b.push("translate("+(0-t.left).toString()+" "+(t.height+t.top).toString()+")"),b.push("scale(1 -1)"),t.top=t.left=0);let y;switch(S<0&&(S-=Math.floor(S/4)*4),S=S%4,S){case 1:y=t.height/2+t.top,b.unshift("rotate(90 "+y.toString()+" "+y.toString()+")");break;case 2:b.unshift("rotate(180 "+(t.width/2+t.left).toString()+" "+(t.height/2+t.top).toString()+")");break;case 3:y=t.width/2+t.left,b.unshift("rotate(-90 "+y.toString()+" "+y.toString()+")");break}S%2===1&&(t.left!==t.top&&(y=t.left,t.left=t.top,t.top=y),t.width!==t.height&&(y=t.width,t.width=t.height,t.height=y)),b.length&&(l=Ce(l,'',""))});let i=s.width,o=s.height,a=t.width,c=t.height,p,u;i===null?(u=o===null?"1em":o==="auto"?c:o,p=re(u,a/c)):(p=i==="auto"?a:i,u=o===null?re(p,c/a):o==="auto"?c:o);let h={},d=(x,b)=>{ft(b)||(h[x]=b.toString())};d("width",p),d("height",u);let m=[t.left,t.top,a,c];return h.viewBox=m.join(" "),{attributes:h,viewBox:m,body:l}}var gt=/\sid="(\S+)"/g,dt="IconifyId"+Date.now().toString(16)+(Math.random()*16777216|0).toString(16),mt=0;function ie(n,e=dt){let r=[],s;for(;s=gt.exec(n);)r.push(s[1]);if(!r.length)return n;let t="suffix"+(Math.random()*16777216|Date.now()).toString(16);return r.forEach(l=>{let i=typeof e=="function"?e(l):e+(mt++).toString(),o=l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp('([#;"])('+o+')([")]|\\.[a-z])',"g"),"$1"+i+t+"$3")}),n=n.replace(new RegExp(t,"g"),""),n}function oe(n,e){let r=n.indexOf("xlink:")===-1?"":' xmlns:xlink="http://www.w3.org/1999/xlink"';for(let s in e)r+=" "+s+'="'+e[s]+'"';return'"+n+""}function pe(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var v=pe();function De(n){v=n}var B={exec:()=>null};function g(n,e=""){let r=typeof n=="string"?n:n.source,s={replace:(t,l)=>{let i=typeof l=="string"?l:l.source;return i=i.replace(w.caret,"$1"),r=r.replace(t,i),s},getRegex:()=>new RegExp(r,e)};return s}var w={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:n=>new RegExp(`^( {0,3}${n})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}#`),htmlBeginRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}<(?:[a-z].*>|!--)`,"i")},kt=/^(?:[ \t]*(?:\n|$))+/,xt=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,bt=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,D=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,wt=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,he=/(?:[*+-]|\d{1,9}[.)])/,qe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Fe=g(qe).replace(/bull/g,he).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),yt=g(qe).replace(/bull/g,he).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),ue=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,St=/^[^\n]+/,fe=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Tt=g(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",fe).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),$t=g(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,he).getRegex(),H="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",ge=/|$))/,It=g("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",ge).replace("tag",H).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Me=g(ue).replace("hr",D).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex(),Rt=g(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Me).getRegex(),de={blockquote:Rt,code:xt,def:Tt,fences:bt,heading:wt,hr:D,html:It,lheading:Fe,list:$t,newline:kt,paragraph:Me,table:B,text:St},Le=g("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",D).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex(),zt={...de,lheading:yt,table:Le,paragraph:g(ue).replace("hr",D).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Le).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex()},vt={...de,html:g(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",ge).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:B,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:g(ue).replace("hr",D).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",Fe).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},At=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Et=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Oe=/^( {2,}|\\)\n(?!\s*$)/,Ct=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\]*?>/g,Ze=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,Bt=g(Ze,"u").replace(/punct/g,N).getRegex(),Dt=g(Ze,"u").replace(/punct/g,We).getRegex(),He="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",qt=g(He,"gu").replace(/notPunctSpace/g,Ge).replace(/punctSpace/g,me).replace(/punct/g,N).getRegex(),Ft=g(He,"gu").replace(/notPunctSpace/g,_t).replace(/punctSpace/g,Pt).replace(/punct/g,We).getRegex(),Mt=g("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Ge).replace(/punctSpace/g,me).replace(/punct/g,N).getRegex(),Ot=g(/\\(punct)/,"gu").replace(/punct/g,N).getRegex(),Gt=g(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Wt=g(ge).replace("(?:-->|$)","-->").getRegex(),Zt=g("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",Wt).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),G=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`[^`]*`|[^\[\]\\`])*?/,Ht=g(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",G).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Ne=g(/^!?\[(label)\]\[(ref)\]/).replace("label",G).replace("ref",fe).getRegex(),Ve=g(/^!?\[(ref)\](?:\[\])?/).replace("ref",fe).getRegex(),Nt=g("reflink|nolink(?!\\()","g").replace("reflink",Ne).replace("nolink",Ve).getRegex(),ke={_backpedal:B,anyPunctuation:Ot,autolink:Gt,blockSkip:jt,br:Oe,code:Et,del:B,emStrongLDelim:Bt,emStrongRDelimAst:qt,emStrongRDelimUnd:Mt,escape:At,link:Ht,nolink:Ve,punctuation:Lt,reflink:Ne,reflinkSearch:Nt,tag:Zt,text:Ct,url:B},Vt={...ke,link:g(/^!?\[(label)\]\((.*?)\)/).replace("label",G).getRegex(),reflink:g(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",G).getRegex()},le={...ke,emStrongRDelimAst:Ft,emStrongLDelim:Dt,url:g(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},Pe=n=>Qt[n];function T(n,e){if(e){if(w.escapeTest.test(n))return n.replace(w.escapeReplace,Pe)}else if(w.escapeTestNoEncode.test(n))return n.replace(w.escapeReplaceNoEncode,Pe);return n}function _e(n){try{n=encodeURI(n).replace(w.percentDecode,"%")}catch{return null}return n}function je(n,e){let r=n.replace(w.findPipe,(l,i,o)=>{let a=!1,c=i;for(;--c>=0&&o[c]==="\\";)a=!a;return a?"|":" |"}),s=r.split(w.splitPipe),t=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),e)if(s.length>e)s.splice(e);else for(;s.length0?-2:-1}function Be(n,e,r,s,t){let l=e.href,i=e.title||null,o=n[1].replace(t.other.outputLinkReplace,"$1");s.state.inLink=!0;let a={type:n[0].charAt(0)==="!"?"image":"link",raw:r,href:l,title:i,text:o,tokens:s.inlineTokens(o)};return s.state.inLink=!1,a}function Xt(n,e,r){let s=n.match(r.other.indentCodeCompensation);if(s===null)return e;let t=s[1];return e.split(` +`).map(l=>{let i=l.match(r.other.beginningSpace);if(i===null)return l;let[o]=i;return o.length>=t.length?l.slice(t.length):l}).join(` +`)}var W=class{options;rules;lexer;constructor(n){this.options=n||v}space(n){let e=this.rules.block.newline.exec(n);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(n){let e=this.rules.block.code.exec(n);if(e){let r=e[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?r:_(r,` +`)}}}fences(n){let e=this.rules.block.fences.exec(n);if(e){let r=e[0],s=Xt(r,e[3]||"",this.rules);return{type:"code",raw:r,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:s}}}heading(n){let e=this.rules.block.heading.exec(n);if(e){let r=e[2].trim();if(this.rules.other.endingHash.test(r)){let s=_(r,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(r=s.trim())}return{type:"heading",raw:e[0],depth:e[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(n){let e=this.rules.block.hr.exec(n);if(e)return{type:"hr",raw:_(e[0],` +`)}}blockquote(n){let e=this.rules.block.blockquote.exec(n);if(e){let r=_(e[0],` +`).split(` +`),s="",t="",l=[];for(;r.length>0;){let i=!1,o=[],a;for(a=0;a1,t={type:"list",raw:"",ordered:s,start:s?+r.slice(0,-1):"",loose:!1,items:[]};r=s?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=s?r:"[*+-]");let l=this.rules.other.listItemRegex(r),i=!1;for(;n;){let a=!1,c="",p="";if(!(e=l.exec(n))||this.rules.block.hr.test(n))break;c=e[0],n=n.substring(c.length);let u=e[2].split(` +`,1)[0].replace(this.rules.other.listReplaceTabs,E=>" ".repeat(3*E.length)),h=n.split(` +`,1)[0],d=!u.trim(),m=0;if(this.options.pedantic?(m=2,p=u.trimStart()):d?m=e[1].length+1:(m=e[2].search(this.rules.other.nonSpaceChar),m=m>4?1:m,p=u.slice(m),m+=e[1].length),d&&this.rules.other.blankLine.test(h)&&(c+=h+` +`,n=n.substring(h.length+1),a=!0),!a){let E=this.rules.other.nextBulletRegex(m),C=this.rules.other.hrRegex(m),S=this.rules.other.fencesBeginRegex(m),y=this.rules.other.headingBeginRegex(m),ot=this.rules.other.htmlBeginRegex(m);for(;n;){let K=n.split(` +`,1)[0],L;if(h=K,this.options.pedantic?(h=h.replace(this.rules.other.listReplaceNesting," "),L=h):L=h.replace(this.rules.other.tabCharGlobal," "),S.test(h)||y.test(h)||ot.test(h)||E.test(h)||C.test(h))break;if(L.search(this.rules.other.nonSpaceChar)>=m||!h.trim())p+=` +`+L.slice(m);else{if(d||u.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||S.test(u)||y.test(u)||C.test(u))break;p+=` +`+h}!d&&!h.trim()&&(d=!0),c+=K+` +`,n=n.substring(K.length+1),u=L.slice(m)}}t.loose||(i?t.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(i=!0));let x=null,b;this.options.gfm&&(x=this.rules.other.listIsTask.exec(p),x&&(b=x[0]!=="[ ] ",p=p.replace(this.rules.other.listReplaceTask,""))),t.items.push({type:"list_item",raw:c,task:!!x,checked:b,loose:!1,text:p,tokens:[]}),t.raw+=c}let o=t.items.at(-1);if(o)o.raw=o.raw.trimEnd(),o.text=o.text.trimEnd();else return;t.raw=t.raw.trimEnd();for(let a=0;au.type==="space"),p=c.length>0&&c.some(u=>this.rules.other.anyLine.test(u.raw));t.loose=p}if(t.loose)for(let a=0;a({text:o,tokens:this.lexer.inline(o),header:!1,align:l.align[a]})));return l}}lheading(n){let e=this.rules.block.lheading.exec(n);if(e)return{type:"heading",raw:e[0],depth:e[2].charAt(0)==="="?1:2,text:e[1],tokens:this.lexer.inline(e[1])}}paragraph(n){let e=this.rules.block.paragraph.exec(n);if(e){let r=e[1].charAt(e[1].length-1)===` +`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:r,tokens:this.lexer.inline(r)}}}text(n){let e=this.rules.block.text.exec(n);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(n){let e=this.rules.inline.escape.exec(n);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(n){let e=this.rules.inline.tag.exec(n);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(n){let e=this.rules.inline.link.exec(n);if(e){let r=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let l=_(r.slice(0,-1),"\\");if((r.length-l.length)%2===0)return}else{let l=Kt(e[2],"()");if(l===-2)return;if(l>-1){let i=(e[0].indexOf("!")===0?5:4)+e[1].length+l;e[2]=e[2].substring(0,l),e[0]=e[0].substring(0,i).trim(),e[3]=""}}let s=e[2],t="";if(this.options.pedantic){let l=this.rules.other.pedanticHrefTitle.exec(s);l&&(s=l[1],t=l[3])}else t=e[3]?e[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?s=s.slice(1):s=s.slice(1,-1)),Be(e,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:t&&t.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(n,e){let r;if((r=this.rules.inline.reflink.exec(n))||(r=this.rules.inline.nolink.exec(n))){let s=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),t=e[s.toLowerCase()];if(!t){let l=r[0].charAt(0);return{type:"text",raw:l,text:l}}return Be(r,t,r[0],this.lexer,this.rules)}}emStrong(n,e,r=""){let s=this.rules.inline.emStrongLDelim.exec(n);if(!(!s||s[3]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[2])||!r||this.rules.inline.punctuation.exec(r))){let t=[...s[0]].length-1,l,i,o=t,a=0,c=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,e=e.slice(-1*n.length+t);(s=c.exec(e))!=null;){if(l=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!l)continue;if(i=[...l].length,s[3]||s[4]){o+=i;continue}else if((s[5]||s[6])&&t%3&&!((t+i)%3)){a+=i;continue}if(o-=i,o>0)continue;i=Math.min(i,i+o+a);let p=[...s[0]][0].length,u=n.slice(0,t+s.index+p+i);if(Math.min(t,i)%2){let d=u.slice(1,-1);return{type:"em",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}let h=u.slice(2,-2);return{type:"strong",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}codespan(n){let e=this.rules.inline.code.exec(n);if(e){let r=e[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(r),t=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return s&&t&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:e[0],text:r}}}br(n){let e=this.rules.inline.br.exec(n);if(e)return{type:"br",raw:e[0]}}del(n){let e=this.rules.inline.del.exec(n);if(e)return{type:"del",raw:e[0],text:e[2],tokens:this.lexer.inlineTokens(e[2])}}autolink(n){let e=this.rules.inline.autolink.exec(n);if(e){let r,s;return e[2]==="@"?(r=e[1],s="mailto:"+r):(r=e[1],s=r),{type:"link",raw:e[0],text:r,href:s,tokens:[{type:"text",raw:r,text:r}]}}}url(n){let e;if(e=this.rules.inline.url.exec(n)){let r,s;if(e[2]==="@")r=e[0],s="mailto:"+r;else{let t;do t=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(t!==e[0]);r=e[0],e[1]==="www."?s="http://"+e[0]:s=e[0]}return{type:"link",raw:e[0],text:r,href:s,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(n){let e=this.rules.inline.text.exec(n);if(e){let r=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:r}}}},$=class ae{tokens;options;state;tokenizer;inlineQueue;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||v,this.options.tokenizer=this.options.tokenizer||new W,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let r={other:w,block:O.normal,inline:P.normal};this.options.pedantic?(r.block=O.pedantic,r.inline=P.pedantic):this.options.gfm&&(r.block=O.gfm,this.options.breaks?r.inline=P.breaks:r.inline=P.gfm),this.tokenizer.rules=r}static get rules(){return{block:O,inline:P}}static lex(e,r){return new ae(r).lex(e)}static lexInline(e,r){return new ae(r).inlineTokens(e)}lex(e){e=e.replace(w.carriageReturn,` +`),this.blockTokens(e,this.tokens);for(let r=0;r(t=i.call({lexer:this},e,r))?(e=e.substring(t.raw.length),r.push(t),!0):!1))continue;if(t=this.tokenizer.space(e)){e=e.substring(t.raw.length);let i=r.at(-1);t.raw.length===1&&i!==void 0?i.raw+=` +`:r.push(t);continue}if(t=this.tokenizer.code(e)){e=e.substring(t.raw.length);let i=r.at(-1);i?.type==="paragraph"||i?.type==="text"?(i.raw+=(i.raw.endsWith(` +`)?"":` +`)+t.raw,i.text+=` +`+t.text,this.inlineQueue.at(-1).src=i.text):r.push(t);continue}if(t=this.tokenizer.fences(e)){e=e.substring(t.raw.length),r.push(t);continue}if(t=this.tokenizer.heading(e)){e=e.substring(t.raw.length),r.push(t);continue}if(t=this.tokenizer.hr(e)){e=e.substring(t.raw.length),r.push(t);continue}if(t=this.tokenizer.blockquote(e)){e=e.substring(t.raw.length),r.push(t);continue}if(t=this.tokenizer.list(e)){e=e.substring(t.raw.length),r.push(t);continue}if(t=this.tokenizer.html(e)){e=e.substring(t.raw.length),r.push(t);continue}if(t=this.tokenizer.def(e)){e=e.substring(t.raw.length);let i=r.at(-1);i?.type==="paragraph"||i?.type==="text"?(i.raw+=(i.raw.endsWith(` +`)?"":` +`)+t.raw,i.text+=` +`+t.raw,this.inlineQueue.at(-1).src=i.text):this.tokens.links[t.tag]||(this.tokens.links[t.tag]={href:t.href,title:t.title},r.push(t));continue}if(t=this.tokenizer.table(e)){e=e.substring(t.raw.length),r.push(t);continue}if(t=this.tokenizer.lheading(e)){e=e.substring(t.raw.length),r.push(t);continue}let l=e;if(this.options.extensions?.startBlock){let i=1/0,o=e.slice(1),a;this.options.extensions.startBlock.forEach(c=>{a=c.call({lexer:this},o),typeof a=="number"&&a>=0&&(i=Math.min(i,a))}),i<1/0&&i>=0&&(l=e.substring(0,i+1))}if(this.state.top&&(t=this.tokenizer.paragraph(l))){let i=r.at(-1);s&&i?.type==="paragraph"?(i.raw+=(i.raw.endsWith(` +`)?"":` +`)+t.raw,i.text+=` +`+t.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=i.text):r.push(t),s=l.length!==e.length,e=e.substring(t.raw.length);continue}if(t=this.tokenizer.text(e)){e=e.substring(t.raw.length);let i=r.at(-1);i?.type==="text"?(i.raw+=(i.raw.endsWith(` +`)?"":` +`)+t.raw,i.text+=` +`+t.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=i.text):r.push(t);continue}if(e){let i="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(i);break}else throw new Error(i)}}return this.state.top=!0,r}inline(e,r=[]){return this.inlineQueue.push({src:e,tokens:r}),r}inlineTokens(e,r=[]){let s=e,t=null;if(this.tokens.links){let o=Object.keys(this.tokens.links);if(o.length>0)for(;(t=this.tokenizer.rules.inline.reflinkSearch.exec(s))!=null;)o.includes(t[0].slice(t[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,t.index)+"["+"a".repeat(t[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(t=this.tokenizer.rules.inline.anyPunctuation.exec(s))!=null;)s=s.slice(0,t.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;(t=this.tokenizer.rules.inline.blockSkip.exec(s))!=null;)s=s.slice(0,t.index)+"["+"a".repeat(t[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let l=!1,i="";for(;e;){l||(i=""),l=!1;let o;if(this.options.extensions?.inline?.some(c=>(o=c.call({lexer:this},e,r))?(e=e.substring(o.raw.length),r.push(o),!0):!1))continue;if(o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.tag(e)){e=e.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);let c=r.at(-1);o.type==="text"&&c?.type==="text"?(c.raw+=o.raw,c.text+=o.text):r.push(o);continue}if(o=this.tokenizer.emStrong(e,s,i)){e=e.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.br(e)){e=e.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.del(e)){e=e.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.autolink(e)){e=e.substring(o.raw.length),r.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),r.push(o);continue}let a=e;if(this.options.extensions?.startInline){let c=1/0,p=e.slice(1),u;this.options.extensions.startInline.forEach(h=>{u=h.call({lexer:this},p),typeof u=="number"&&u>=0&&(c=Math.min(c,u))}),c<1/0&&c>=0&&(a=e.substring(0,c+1))}if(o=this.tokenizer.inlineText(a)){e=e.substring(o.raw.length),o.raw.slice(-1)!=="_"&&(i=o.raw.slice(-1)),l=!0;let c=r.at(-1);c?.type==="text"?(c.raw+=o.raw,c.text+=o.text):r.push(o);continue}if(e){let c="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(c);break}else throw new Error(c)}}return r}},Z=class{options;parser;constructor(n){this.options=n||v}space(n){return""}code({text:n,lang:e,escaped:r}){let s=(e||"").match(w.notSpaceStart)?.[0],t=n.replace(w.endingNewline,"")+` +`;return s?'
'+(r?t:T(t,!0))+`
+`:"
"+(r?t:T(t,!0))+`
+`}blockquote({tokens:n}){return`
+${this.parser.parse(n)}
+`}html({text:n}){return n}def(n){return""}heading({tokens:n,depth:e}){return`${this.parser.parseInline(n)} +`}hr(n){return`
+`}list(n){let e=n.ordered,r=n.start,s="";for(let i=0;i +`+s+" +`}listitem(n){let e="";if(n.task){let r=this.checkbox({checked:!!n.checked});n.loose?n.tokens[0]?.type==="paragraph"?(n.tokens[0].text=r+" "+n.tokens[0].text,n.tokens[0].tokens&&n.tokens[0].tokens.length>0&&n.tokens[0].tokens[0].type==="text"&&(n.tokens[0].tokens[0].text=r+" "+T(n.tokens[0].tokens[0].text),n.tokens[0].tokens[0].escaped=!0)):n.tokens.unshift({type:"text",raw:r+" ",text:r+" ",escaped:!0}):e+=r+" "}return e+=this.parser.parse(n.tokens,!!n.loose),`
  • ${e}
  • +`}checkbox({checked:n}){return"'}paragraph({tokens:n}){return`

    ${this.parser.parseInline(n)}

    +`}table(n){let e="",r="";for(let t=0;t${s}`),` + +`+e+` +`+s+`
    +`}tablerow({text:n}){return` +${n} +`}tablecell(n){let e=this.parser.parseInline(n.tokens),r=n.header?"th":"td";return(n.align?`<${r} align="${n.align}">`:`<${r}>`)+e+` +`}strong({tokens:n}){return`${this.parser.parseInline(n)}`}em({tokens:n}){return`${this.parser.parseInline(n)}`}codespan({text:n}){return`${T(n,!0)}`}br(n){return"
    "}del({tokens:n}){return`${this.parser.parseInline(n)}`}link({href:n,title:e,tokens:r}){let s=this.parser.parseInline(r),t=_e(n);if(t===null)return s;n=t;let l='
    ",l}image({href:n,title:e,text:r,tokens:s}){s&&(r=this.parser.parseInline(s,this.parser.textRenderer));let t=_e(n);if(t===null)return T(r);n=t;let l=`${r}{let i=t[l].flat(1/0);r=r.concat(this.walkTokens(i,e))}):t.tokens&&(r=r.concat(this.walkTokens(t.tokens,e)))}}return r}use(...n){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return n.forEach(r=>{let s={...r};if(s.async=this.defaults.async||s.async||!1,r.extensions&&(r.extensions.forEach(t=>{if(!t.name)throw new Error("extension name required");if("renderer"in t){let l=e.renderers[t.name];l?e.renderers[t.name]=function(...i){let o=t.renderer.apply(this,i);return o===!1&&(o=l.apply(this,i)),o}:e.renderers[t.name]=t.renderer}if("tokenizer"in t){if(!t.level||t.level!=="block"&&t.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let l=e[t.level];l?l.unshift(t.tokenizer):e[t.level]=[t.tokenizer],t.start&&(t.level==="block"?e.startBlock?e.startBlock.push(t.start):e.startBlock=[t.start]:t.level==="inline"&&(e.startInline?e.startInline.push(t.start):e.startInline=[t.start]))}"childTokens"in t&&t.childTokens&&(e.childTokens[t.name]=t.childTokens)}),s.extensions=e),r.renderer){let t=this.defaults.renderer||new Z(this.defaults);for(let l in r.renderer){if(!(l in t))throw new Error(`renderer '${l}' does not exist`);if(["options","parser"].includes(l))continue;let i=l,o=r.renderer[i],a=t[i];t[i]=(...c)=>{let p=o.apply(t,c);return p===!1&&(p=a.apply(t,c)),p||""}}s.renderer=t}if(r.tokenizer){let t=this.defaults.tokenizer||new W(this.defaults);for(let l in r.tokenizer){if(!(l in t))throw new Error(`tokenizer '${l}' does not exist`);if(["options","rules","lexer"].includes(l))continue;let i=l,o=r.tokenizer[i],a=t[i];t[i]=(...c)=>{let p=o.apply(t,c);return p===!1&&(p=a.apply(t,c)),p}}s.tokenizer=t}if(r.hooks){let t=this.defaults.hooks||new j;for(let l in r.hooks){if(!(l in t))throw new Error(`hook '${l}' does not exist`);if(["options","block"].includes(l))continue;let i=l,o=r.hooks[i],a=t[i];j.passThroughHooks.has(l)?t[i]=c=>{if(this.defaults.async&&j.passThroughHooksRespectAsync.has(l))return Promise.resolve(o.call(t,c)).then(u=>a.call(t,u));let p=o.call(t,c);return a.call(t,p)}:t[i]=(...c)=>{let p=o.apply(t,c);return p===!1&&(p=a.apply(t,c)),p}}s.hooks=t}if(r.walkTokens){let t=this.defaults.walkTokens,l=r.walkTokens;s.walkTokens=function(i){let o=[];return o.push(l.call(this,i)),t&&(o=o.concat(t.call(this,i))),o}}this.defaults={...this.defaults,...s}}),this}setOptions(n){return this.defaults={...this.defaults,...n},this}lexer(n,e){return $.lex(n,e??this.defaults)}parser(n,e){return I.parse(n,e??this.defaults)}parseMarkdown(n){return(e,r)=>{let s={...r},t={...this.defaults,...s},l=this.onError(!!t.silent,!!t.async);if(this.defaults.async===!0&&s.async===!1)return l(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return l(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return l(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));t.hooks&&(t.hooks.options=t,t.hooks.block=n);let i=t.hooks?t.hooks.provideLexer():n?$.lex:$.lexInline,o=t.hooks?t.hooks.provideParser():n?I.parse:I.parseInline;if(t.async)return Promise.resolve(t.hooks?t.hooks.preprocess(e):e).then(a=>i(a,t)).then(a=>t.hooks?t.hooks.processAllTokens(a):a).then(a=>t.walkTokens?Promise.all(this.walkTokens(a,t.walkTokens)).then(()=>a):a).then(a=>o(a,t)).then(a=>t.hooks?t.hooks.postprocess(a):a).catch(l);try{t.hooks&&(e=t.hooks.preprocess(e));let a=i(e,t);t.hooks&&(a=t.hooks.processAllTokens(a)),t.walkTokens&&this.walkTokens(a,t.walkTokens);let c=o(a,t);return t.hooks&&(c=t.hooks.postprocess(c)),c}catch(a){return l(a)}}}onError(n,e){return r=>{if(r.message+=` +Please report this to https://github.com/markedjs/marked.`,n){let s="

    An error occurred:

    "+T(r.message+"",!0)+"
    ";return e?Promise.resolve(s):s}if(e)return Promise.reject(r);throw r}}},z=new Jt;function f(n,e){return z.parse(n,e)}f.options=f.setOptions=function(n){return z.setOptions(n),f.defaults=z.defaults,De(f.defaults),f};f.getDefaults=pe;f.defaults=v;f.use=function(...n){return z.use(...n),f.defaults=z.defaults,De(f.defaults),f};f.walkTokens=function(n,e){return z.walkTokens(n,e)};f.parseInline=z.parseInline;f.Parser=I;f.parser=I.parse;f.Renderer=Z;f.TextRenderer=xe;f.Lexer=$;f.lexer=$.lex;f.Tokenizer=W;f.Hooks=j;f.parse=f;var Pn=f.options,_n=f.setOptions,jn=f.use,Bn=f.walkTokens,Dn=f.parseInline;var qn=I.parse,Fn=$.lex;var Yt={body:'?',height:80,width:80},be=new Map,Ue=new Map,Kn=k(n=>{for(let e of n){if(!e.name)throw new Error('Invalid icon loader. Must have a "name" property with non-empty string value.');if(R.debug("Registering icon pack:",e.name),"loader"in e)Ue.set(e.name,e.loader);else if("icons"in e)be.set(e.name,e.icons);else throw R.error("Invalid icon loader:",e),new Error('Invalid icon loader. Must have either "icons" or "loader" property.')}},"registerIconPacks"),Qe=k(async(n,e)=>{let r=ee(n,!0,e!==void 0);if(!r)throw new Error(`Invalid icon name: ${n}`);let s=r.prefix||e;if(!s)throw new Error(`Icon name must contain a prefix: ${n}`);let t=be.get(s);if(!t){let i=Ue.get(s);if(!i)throw new Error(`Icon set not found: ${r.prefix}`);try{t={...await i(),prefix:s},be.set(s,t)}catch(o){throw R.error(o),new Error(`Failed to load icon set: ${r.prefix}`)}}let l=ne(t,r.name);if(!l)throw new Error(`Icon not found: ${n}`);return l},"getRegisteredIconData"),en=k(async n=>{try{return await Qe(n),!0}catch{return!1}},"isIconAvailable"),tn=k(async(n,e,r)=>{let s;try{s=await Qe(n,e?.fallbackPrefix)}catch(i){R.error(i),s=Yt}let t=se(s,e),l=oe(ie(t.body),{...t.attributes,...r});return q(l,X())},"getIconSVG");function Ke(n,{markdownAutoWrap:e}){let s=n.replace(//g,` +`).replace(/\n{2,}/g,` +`),t=Ie(s);return e===!1?t.replace(/ /g," "):t}k(Ke,"preprocessMarkdown");function Xe(n,e={}){let r=Ke(n,e),s=f.lexer(r),t=[[]],l=0;function i(o,a="normal"){o.type==="text"?o.text.split(` +`).forEach((p,u)=>{u!==0&&(l++,t.push([])),p.split(" ").forEach(h=>{h=h.replace(/'/g,"'"),h&&t[l].push({content:h,type:a})})}):o.type==="strong"||o.type==="em"?o.tokens.forEach(c=>{i(c,o.type)}):o.type==="html"&&t[l].push({content:o.text,type:"normal"})}return k(i,"processNode"),s.forEach(o=>{o.type==="paragraph"?o.tokens?.forEach(a=>{i(a)}):o.type==="html"?t[l].push({content:o.text,type:"normal"}):t[l].push({content:o.raw,type:"normal"})}),t}k(Xe,"markdownToLines");function Je(n,{markdownAutoWrap:e}={}){let r=f.lexer(n);function s(t){return t.type==="text"?e===!1?t.text.replace(/\n */g,"
    ").replace(/ /g," "):t.text.replace(/\n */g,"
    "):t.type==="strong"?`${t.tokens?.map(s).join("")}`:t.type==="em"?`${t.tokens?.map(s).join("")}`:t.type==="paragraph"?`

    ${t.tokens?.map(s).join("")}

    `:t.type==="space"?"":t.type==="html"?`${t.text}`:t.type==="escape"?t.text:(R.warn(`Unsupported markdown: ${t.type}`),t.raw)}return k(s,"output"),r.map(s).join("")}k(Je,"markdownToHTML");function Ye(n){return Intl.Segmenter?[...new Intl.Segmenter().segment(n)].map(e=>e.segment):[...n]}k(Ye,"splitTextToChars");function et(n,e){let r=Ye(e.content);return ye(n,[],r,e.type)}k(et,"splitWordToFitWidth");function ye(n,e,r,s){if(r.length===0)return[{content:e.join(""),type:s},{content:"",type:s}];let[t,...l]=r,i=[...e,t];return n([{content:i.join(""),type:s}])?ye(n,i,l,s):(e.length===0&&t&&(e.push(t),r.shift()),[{content:e.join(""),type:s},{content:r.join(""),type:s}])}k(ye,"splitWordToFitWidthRecursion");function tt(n,e){if(n.some(({content:r})=>r.includes(` +`)))throw new Error("splitLineToFitWidth does not support newlines in the line");return V(n,e)}k(tt,"splitLineToFitWidth");function V(n,e,r=[],s=[]){if(n.length===0)return s.length>0&&r.push(s),r.length>0?r:[];let t="";n[0].content===" "&&(t=" ",n.shift());let l=n.shift()??{content:" ",type:"normal"},i=[...s];if(t!==""&&i.push({content:t,type:"normal"}),i.push(l),e(i))return V(n,e,r,i);if(s.length>0)r.push(s),n.unshift(l);else if(l.content){let[o,a]=et(e,l);r.push([o]),a.content&&n.unshift(a)}return V(n,e,r)}k(V,"splitLineToFitWidthRecursion");function we(n,e){e&&n.attr("style",e)}k(we,"applyStyle");async function nt(n,e,r,s,t=!1,l=X()){let i=n.append("foreignObject");i.attr("width",`${10*r}px`),i.attr("height",`${10*r}px`);let o=i.append("xhtml:div"),a=J(e.label)?await Se(e.label.replace(Te.lineBreakRegex,` +`),l):q(e.label,l),c=e.isNode?"nodeLabel":"edgeLabel",p=o.append("span");p.html(a),we(p,e.labelStyle),p.attr("class",`${c} ${s}`),we(o,e.labelStyle),o.style("display","table-cell"),o.style("white-space","nowrap"),o.style("line-height","1.5"),o.style("max-width",r+"px"),o.style("text-align","center"),o.attr("xmlns","http://www.w3.org/1999/xhtml"),t&&o.attr("class","labelBkg");let u=o.node().getBoundingClientRect();return u.width===r&&(o.style("display","table"),o.style("white-space","break-spaces"),o.style("width",r+"px"),u=o.node().getBoundingClientRect()),i.node()}k(nt,"addHtmlSpan");function U(n,e,r){return n.append("tspan").attr("class","text-outer-tspan").attr("x",0).attr("y",e*r-.1+"em").attr("dy",r+"em")}k(U,"createTspan");function rt(n,e,r){let s=n.append("text"),t=U(s,1,e);Q(t,r);let l=t.node().getComputedTextLength();return s.remove(),l}k(rt,"computeWidthOfText");function nn(n,e,r){let s=n.append("text"),t=U(s,1,e);Q(t,[{content:r,type:"normal"}]);let l=t.node()?.getBoundingClientRect();return l&&s.remove(),l}k(nn,"computeDimensionOfText");function st(n,e,r,s=!1){let l=e.append("g"),i=l.insert("rect").attr("class","background").attr("style","stroke: none"),o=l.append("text").attr("y","-10.1"),a=0;for(let c of r){let p=k(h=>rt(l,1.1,h)<=n,"checkWidth"),u=p(c)?[c]:tt(c,p);for(let h of u){let d=U(o,a,1.1);Q(d,h),a++}}if(s){let c=o.node().getBBox(),p=2;return i.attr("x",c.x-p).attr("y",c.y-p).attr("width",c.width+2*p).attr("height",c.height+2*p),l.node()}else return o.node()}k(st,"createFormattedText");function Q(n,e){n.text(""),e.forEach((r,s)=>{let t=n.append("tspan").attr("font-style",r.type==="em"?"italic":"normal").attr("class","text-inner-tspan").attr("font-weight",r.type==="strong"?"bold":"normal");s===0?t.text(r.content):t.text(" "+r.content)})}k(Q,"updateTextContentAndStyles");async function it(n,e={}){let r=[];n.replace(/(fa[bklrs]?):fa-([\w-]+)/g,(t,l,i)=>(r.push((async()=>{let o=`${l}:${i}`;return await en(o)?await tn(o,void 0,{class:"label-icon"}):``})()),t));let s=await Promise.all(r);return n.replace(/(fa[bklrs]?):fa-([\w-]+)/g,()=>s.shift()??"")}k(it,"replaceIconSubstring");var er=k(async(n,e="",{style:r="",isTitle:s=!1,classes:t="",useHtmlLabels:l=!0,isNode:i=!0,width:o=200,addSvgBackground:a=!1}={},c)=>{if(R.debug("XYZ createText",e,r,s,t,l,i,"addSvgBackground: ",a),l){let p=Je(e,c),u=await it($e(p),c),h=e.replace(/\\\\/g,"\\"),d={isNode:i,label:J(e)?h:u,labelStyle:r.replace("fill:","color:")};return await nt(n,d,o,t,a,c)}else{let p=e.replace(//g,"
    "),u=Xe(p.replace("
    ","
    "),c),h=st(o,n,u,e?a:!1);if(i){/stroke:/.exec(r)&&(r=r.replace("stroke:","lineColor:"));let d=r.replace(/stroke:[^;]+;?/g,"").replace(/stroke-width:[^;]+;?/g,"").replace(/fill:[^;]+;?/g,"").replace(/color:/g,"fill:");F(h).attr("style",d)}else{let d=r.replace(/stroke:[^;]+;?/g,"").replace(/stroke-width:[^;]+;?/g,"").replace(/fill:[^;]+;?/g,"").replace(/background:/g,"fill:");F(h).select("rect").attr("style",d.replace(/background:/g,"fill:"));let m=r.replace(/stroke:[^;]+;?/g,"").replace(/stroke-width:[^;]+;?/g,"").replace(/fill:[^;]+;?/g,"").replace(/color:/g,"fill:");F(h).select("text").attr("style",m)}return h}},"createText");export{Ie as a,Yt as b,Kn as c,tn as d,nn as e,it as f,er as g}; +//# sourceMappingURL=chunk-XCAVDAZC.min.js.map diff --git a/docs/website/public/chunk-XCAVDAZC.min.js.map b/docs/website/public/chunk-XCAVDAZC.min.js.map new file mode 100644 index 000000000..424d49653 --- /dev/null +++ b/docs/website/public/chunk-XCAVDAZC.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/ts-dedent/src/index.ts", "../../node_modules/@iconify/utils/lib/icon/defaults.js", "../../node_modules/@iconify/utils/lib/customisations/defaults.js", "../../node_modules/@iconify/utils/lib/icon/name.js", "../../node_modules/@iconify/utils/lib/icon/transformations.js", "../../node_modules/@iconify/utils/lib/icon/merge.js", "../../node_modules/@iconify/utils/lib/icon-set/tree.js", "../../node_modules/@iconify/utils/lib/icon-set/get-icon.js", "../../node_modules/@iconify/utils/lib/svg/size.js", "../../node_modules/@iconify/utils/lib/svg/defs.js", "../../node_modules/@iconify/utils/lib/svg/build.js", "../../node_modules/@iconify/utils/lib/svg/id.js", "../../node_modules/@iconify/utils/lib/svg/html.js", "../../node_modules/marked/src/defaults.ts", "../../node_modules/marked/src/rules.ts", "../../node_modules/marked/src/helpers.ts", "../../node_modules/marked/src/Tokenizer.ts", "../../node_modules/marked/src/Lexer.ts", "../../node_modules/marked/src/Renderer.ts", "../../node_modules/marked/src/TextRenderer.ts", "../../node_modules/marked/src/Parser.ts", "../../node_modules/marked/src/Hooks.ts", "../../node_modules/marked/src/Instance.ts", "../../node_modules/marked/src/marked.ts", "../../node_modules/mermaid/dist/chunks/mermaid.core/chunk-JA3XYJ7Z.mjs"], + "sourcesContent": ["export function dedent(\n templ: TemplateStringsArray | string,\n ...values: unknown[]\n): string {\n let strings = Array.from(typeof templ === 'string' ? [templ] : templ);\n\n // 1. Remove trailing whitespace.\n strings[strings.length - 1] = strings[strings.length - 1].replace(\n /\\r?\\n([\\t ]*)$/,\n '',\n );\n\n // 2. Find all line breaks to determine the highest common indentation level.\n const indentLengths = strings.reduce((arr, str) => {\n const matches = str.match(/\\n([\\t ]+|(?!\\s).)/g);\n if (matches) {\n return arr.concat(\n matches.map((match) => match.match(/[\\t ]/g)?.length ?? 0),\n );\n }\n return arr;\n }, []);\n\n // 3. Remove the common indentation from all strings.\n if (indentLengths.length) {\n const pattern = new RegExp(`\\n[\\t ]{${Math.min(...indentLengths)}}`, 'g');\n\n strings = strings.map((str) => str.replace(pattern, '\\n'));\n }\n\n // 4. Remove leading whitespace.\n strings[0] = strings[0].replace(/^\\r?\\n/, '');\n\n // 5. Perform interpolation.\n let string = strings[0];\n\n values.forEach((value, i) => {\n // 5.1 Read current indentation level\n const endentations = string.match(/(?:^|\\n)( *)$/)\n const endentation = endentations ? endentations[1] : ''\n let indentedValue = value\n // 5.2 Add indentation to values with multiline strings\n if (typeof value === 'string' && value.includes('\\n')) {\n indentedValue = String(value)\n .split('\\n')\n .map((str, i) => {\n return i === 0 ? str : `${endentation}${str}`\n })\n .join('\\n');\n }\n\n string += indentedValue + strings[i + 1];\n });\n\n return string;\n}\n\nexport default dedent;\n", "/**\n* Default values for dimensions\n*/\nconst defaultIconDimensions = Object.freeze({\n\tleft: 0,\n\ttop: 0,\n\twidth: 16,\n\theight: 16\n});\n/**\n* Default values for transformations\n*/\nconst defaultIconTransformations = Object.freeze({\n\trotate: 0,\n\tvFlip: false,\n\thFlip: false\n});\n/**\n* Default values for all optional IconifyIcon properties\n*/\nconst defaultIconProps = Object.freeze({\n\t...defaultIconDimensions,\n\t...defaultIconTransformations\n});\n/**\n* Default values for all properties used in ExtendedIconifyIcon\n*/\nconst defaultExtendedIconProps = Object.freeze({\n\t...defaultIconProps,\n\tbody: \"\",\n\thidden: false\n});\n\nexport { defaultExtendedIconProps, defaultIconDimensions, defaultIconProps, defaultIconTransformations };", "import { defaultIconTransformations } from \"../icon/defaults.js\";\n\n/**\n* Default icon customisations values\n*/\nconst defaultIconSizeCustomisations = Object.freeze({\n\twidth: null,\n\theight: null\n});\nconst defaultIconCustomisations = Object.freeze({\n\t...defaultIconSizeCustomisations,\n\t...defaultIconTransformations\n});\n\nexport { defaultIconCustomisations, defaultIconSizeCustomisations };", "/**\n* Expression to test part of icon name.\n*\n* Used when loading icons from Iconify API due to project naming convension.\n* Ignored when using custom icon sets - convension does not apply.\n*/\nconst matchIconName = /^[a-z0-9]+(-[a-z0-9]+)*$/;\n/**\n* Convert string icon name to IconifyIconName object.\n*/\nconst stringToIcon = (value, validate, allowSimpleName, provider = \"\") => {\n\tconst colonSeparated = value.split(\":\");\n\tif (value.slice(0, 1) === \"@\") {\n\t\tif (colonSeparated.length < 2 || colonSeparated.length > 3) return null;\n\t\tprovider = colonSeparated.shift().slice(1);\n\t}\n\tif (colonSeparated.length > 3 || !colonSeparated.length) return null;\n\tif (colonSeparated.length > 1) {\n\t\tconst name$1 = colonSeparated.pop();\n\t\tconst prefix = colonSeparated.pop();\n\t\tconst result = {\n\t\t\tprovider: colonSeparated.length > 0 ? colonSeparated[0] : provider,\n\t\t\tprefix,\n\t\t\tname: name$1\n\t\t};\n\t\treturn validate && !validateIconName(result) ? null : result;\n\t}\n\tconst name = colonSeparated[0];\n\tconst dashSeparated = name.split(\"-\");\n\tif (dashSeparated.length > 1) {\n\t\tconst result = {\n\t\t\tprovider,\n\t\t\tprefix: dashSeparated.shift(),\n\t\t\tname: dashSeparated.join(\"-\")\n\t\t};\n\t\treturn validate && !validateIconName(result) ? null : result;\n\t}\n\tif (allowSimpleName && provider === \"\") {\n\t\tconst result = {\n\t\t\tprovider,\n\t\t\tprefix: \"\",\n\t\t\tname\n\t\t};\n\t\treturn validate && !validateIconName(result, allowSimpleName) ? null : result;\n\t}\n\treturn null;\n};\n/**\n* Check if icon is valid.\n*\n* This function is not part of stringToIcon because validation is not needed for most code.\n*/\nconst validateIconName = (icon, allowSimpleName) => {\n\tif (!icon) return false;\n\treturn !!((allowSimpleName && icon.prefix === \"\" || !!icon.prefix) && !!icon.name);\n};\n\nexport { matchIconName, stringToIcon, validateIconName };", "/**\n* Merge transformations\n*/\nfunction mergeIconTransformations(obj1, obj2) {\n\tconst result = {};\n\tif (!obj1.hFlip !== !obj2.hFlip) result.hFlip = true;\n\tif (!obj1.vFlip !== !obj2.vFlip) result.vFlip = true;\n\tconst rotate = ((obj1.rotate || 0) + (obj2.rotate || 0)) % 4;\n\tif (rotate) result.rotate = rotate;\n\treturn result;\n}\n\nexport { mergeIconTransformations };", "import { defaultExtendedIconProps, defaultIconTransformations } from \"./defaults.js\";\nimport { mergeIconTransformations } from \"./transformations.js\";\n\n/**\n* Merge icon and alias\n*\n* Can also be used to merge default values and icon\n*/\nfunction mergeIconData(parent, child) {\n\tconst result = mergeIconTransformations(parent, child);\n\tfor (const key in defaultExtendedIconProps) if (key in defaultIconTransformations) {\n\t\tif (key in parent && !(key in result)) result[key] = defaultIconTransformations[key];\n\t} else if (key in child) result[key] = child[key];\n\telse if (key in parent) result[key] = parent[key];\n\treturn result;\n}\n\nexport { mergeIconData };", "/**\n* Resolve icon set icons\n*\n* Returns parent icon for each icon\n*/\nfunction getIconsTree(data, names) {\n\tconst icons = data.icons;\n\tconst aliases = data.aliases || Object.create(null);\n\tconst resolved = Object.create(null);\n\tfunction resolve(name) {\n\t\tif (icons[name]) return resolved[name] = [];\n\t\tif (!(name in resolved)) {\n\t\t\tresolved[name] = null;\n\t\t\tconst parent = aliases[name] && aliases[name].parent;\n\t\t\tconst value = parent && resolve(parent);\n\t\t\tif (value) resolved[name] = [parent].concat(value);\n\t\t}\n\t\treturn resolved[name];\n\t}\n\t(names || Object.keys(icons).concat(Object.keys(aliases))).forEach(resolve);\n\treturn resolved;\n}\n\nexport { getIconsTree };", "import { mergeIconData } from \"../icon/merge.js\";\nimport { getIconsTree } from \"./tree.js\";\n\n/**\n* Get icon data, using prepared aliases tree\n*/\nfunction internalGetIconData(data, name, tree) {\n\tconst icons = data.icons;\n\tconst aliases = data.aliases || Object.create(null);\n\tlet currentProps = {};\n\tfunction parse(name$1) {\n\t\tcurrentProps = mergeIconData(icons[name$1] || aliases[name$1], currentProps);\n\t}\n\tparse(name);\n\ttree.forEach(parse);\n\treturn mergeIconData(data, currentProps);\n}\n/**\n* Get data for icon\n*/\nfunction getIconData(data, name) {\n\tif (data.icons[name]) return internalGetIconData(data, name, []);\n\tconst tree = getIconsTree(data, [name])[name];\n\treturn tree ? internalGetIconData(data, name, tree) : null;\n}\n\nexport { getIconData, internalGetIconData };", "/**\n* Regular expressions for calculating dimensions\n*/\nconst unitsSplit = /(-?[0-9.]*[0-9]+[0-9.]*)/g;\nconst unitsTest = /^-?[0-9.]*[0-9]+[0-9.]*$/g;\nfunction calculateSize(size, ratio, precision) {\n\tif (ratio === 1) return size;\n\tprecision = precision || 100;\n\tif (typeof size === \"number\") return Math.ceil(size * ratio * precision) / precision;\n\tif (typeof size !== \"string\") return size;\n\tconst oldParts = size.split(unitsSplit);\n\tif (oldParts === null || !oldParts.length) return size;\n\tconst newParts = [];\n\tlet code = oldParts.shift();\n\tlet isNumber = unitsTest.test(code);\n\twhile (true) {\n\t\tif (isNumber) {\n\t\t\tconst num = parseFloat(code);\n\t\t\tif (isNaN(num)) newParts.push(code);\n\t\t\telse newParts.push(Math.ceil(num * ratio * precision) / precision);\n\t\t} else newParts.push(code);\n\t\tcode = oldParts.shift();\n\t\tif (code === void 0) return newParts.join(\"\");\n\t\tisNumber = !isNumber;\n\t}\n}\n\nexport { calculateSize };", "function splitSVGDefs(content, tag = \"defs\") {\n\tlet defs = \"\";\n\tconst index = content.indexOf(\"<\" + tag);\n\twhile (index >= 0) {\n\t\tconst start = content.indexOf(\">\", index);\n\t\tconst end = content.indexOf(\"\", end);\n\t\tif (endEnd === -1) break;\n\t\tdefs += content.slice(start + 1, end).trim();\n\t\tcontent = content.slice(0, index).trim() + content.slice(endEnd + 1);\n\t}\n\treturn {\n\t\tdefs,\n\t\tcontent\n\t};\n}\n/**\n* Merge defs and content\n*/\nfunction mergeDefsAndContent(defs, content) {\n\treturn defs ? \"\" + defs + \"\" + content : content;\n}\n/**\n* Wrap SVG content, without wrapping definitions\n*/\nfunction wrapSVGContent(body, start, end) {\n\tconst split = splitSVGDefs(body);\n\treturn mergeDefsAndContent(split.defs, start + split.content + end);\n}\n\nexport { mergeDefsAndContent, splitSVGDefs, wrapSVGContent };", "import { defaultIconProps } from \"../icon/defaults.js\";\nimport { defaultIconCustomisations } from \"../customisations/defaults.js\";\nimport { calculateSize } from \"./size.js\";\nimport { wrapSVGContent } from \"./defs.js\";\n\n/**\n* Check if value should be unset. Allows multiple keywords\n*/\nconst isUnsetKeyword = (value) => value === \"unset\" || value === \"undefined\" || value === \"none\";\n/**\n* Get SVG attributes and content from icon + customisations\n*\n* Does not generate style to make it compatible with frameworks that use objects for style, such as React.\n* Instead, it generates 'inline' value. If true, rendering engine should add verticalAlign: -0.125em to icon.\n*\n* Customisations should be normalised by platform specific parser.\n* Result should be converted to by platform specific parser.\n* Use replaceIDs to generate unique IDs for body.\n*/\nfunction iconToSVG(icon, customisations) {\n\tconst fullIcon = {\n\t\t...defaultIconProps,\n\t\t...icon\n\t};\n\tconst fullCustomisations = {\n\t\t...defaultIconCustomisations,\n\t\t...customisations\n\t};\n\tconst box = {\n\t\tleft: fullIcon.left,\n\t\ttop: fullIcon.top,\n\t\twidth: fullIcon.width,\n\t\theight: fullIcon.height\n\t};\n\tlet body = fullIcon.body;\n\t[fullIcon, fullCustomisations].forEach((props) => {\n\t\tconst transformations = [];\n\t\tconst hFlip = props.hFlip;\n\t\tconst vFlip = props.vFlip;\n\t\tlet rotation = props.rotate;\n\t\tif (hFlip) if (vFlip) rotation += 2;\n\t\telse {\n\t\t\ttransformations.push(\"translate(\" + (box.width + box.left).toString() + \" \" + (0 - box.top).toString() + \")\");\n\t\t\ttransformations.push(\"scale(-1 1)\");\n\t\t\tbox.top = box.left = 0;\n\t\t}\n\t\telse if (vFlip) {\n\t\t\ttransformations.push(\"translate(\" + (0 - box.left).toString() + \" \" + (box.height + box.top).toString() + \")\");\n\t\t\ttransformations.push(\"scale(1 -1)\");\n\t\t\tbox.top = box.left = 0;\n\t\t}\n\t\tlet tempValue;\n\t\tif (rotation < 0) rotation -= Math.floor(rotation / 4) * 4;\n\t\trotation = rotation % 4;\n\t\tswitch (rotation) {\n\t\t\tcase 1:\n\t\t\t\ttempValue = box.height / 2 + box.top;\n\t\t\t\ttransformations.unshift(\"rotate(90 \" + tempValue.toString() + \" \" + tempValue.toString() + \")\");\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\ttransformations.unshift(\"rotate(180 \" + (box.width / 2 + box.left).toString() + \" \" + (box.height / 2 + box.top).toString() + \")\");\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\ttempValue = box.width / 2 + box.left;\n\t\t\t\ttransformations.unshift(\"rotate(-90 \" + tempValue.toString() + \" \" + tempValue.toString() + \")\");\n\t\t\t\tbreak;\n\t\t}\n\t\tif (rotation % 2 === 1) {\n\t\t\tif (box.left !== box.top) {\n\t\t\t\ttempValue = box.left;\n\t\t\t\tbox.left = box.top;\n\t\t\t\tbox.top = tempValue;\n\t\t\t}\n\t\t\tif (box.width !== box.height) {\n\t\t\t\ttempValue = box.width;\n\t\t\t\tbox.width = box.height;\n\t\t\t\tbox.height = tempValue;\n\t\t\t}\n\t\t}\n\t\tif (transformations.length) body = wrapSVGContent(body, \"\", \"\");\n\t});\n\tconst customisationsWidth = fullCustomisations.width;\n\tconst customisationsHeight = fullCustomisations.height;\n\tconst boxWidth = box.width;\n\tconst boxHeight = box.height;\n\tlet width;\n\tlet height;\n\tif (customisationsWidth === null) {\n\t\theight = customisationsHeight === null ? \"1em\" : customisationsHeight === \"auto\" ? boxHeight : customisationsHeight;\n\t\twidth = calculateSize(height, boxWidth / boxHeight);\n\t} else {\n\t\twidth = customisationsWidth === \"auto\" ? boxWidth : customisationsWidth;\n\t\theight = customisationsHeight === null ? calculateSize(width, boxHeight / boxWidth) : customisationsHeight === \"auto\" ? boxHeight : customisationsHeight;\n\t}\n\tconst attributes = {};\n\tconst setAttr = (prop, value) => {\n\t\tif (!isUnsetKeyword(value)) attributes[prop] = value.toString();\n\t};\n\tsetAttr(\"width\", width);\n\tsetAttr(\"height\", height);\n\tconst viewBox = [\n\t\tbox.left,\n\t\tbox.top,\n\t\tboxWidth,\n\t\tboxHeight\n\t];\n\tattributes.viewBox = viewBox.join(\" \");\n\treturn {\n\t\tattributes,\n\t\tviewBox,\n\t\tbody\n\t};\n}\n\nexport { iconToSVG, isUnsetKeyword };", "/**\n* IDs usage:\n*\n* id=\"{id}\"\n* xlink:href=\"#{id}\"\n* url(#{id})\n*\n* From SVG animations:\n*\n* begin=\"0;{id}.end\"\n* begin=\"{id}.end\"\n* begin=\"{id}.click\"\n*/\n/**\n* Regular expression for finding ids\n*/\nconst regex = /\\sid=\"(\\S+)\"/g;\n/**\n* New random-ish prefix for ids\n*\n* Do not use dash, it cannot be used in SVG 2 animations\n*/\nconst randomPrefix = \"IconifyId\" + Date.now().toString(16) + (Math.random() * 16777216 | 0).toString(16);\n/**\n* Counter for ids, increasing with every replacement\n*/\nlet counter = 0;\n/**\n* Replace IDs in SVG output with unique IDs\n*/\nfunction replaceIDs(body, prefix = randomPrefix) {\n\tconst ids = [];\n\tlet match;\n\twhile (match = regex.exec(body)) ids.push(match[1]);\n\tif (!ids.length) return body;\n\tconst suffix = \"suffix\" + (Math.random() * 16777216 | Date.now()).toString(16);\n\tids.forEach((id) => {\n\t\tconst newID = typeof prefix === \"function\" ? prefix(id) : prefix + (counter++).toString();\n\t\tconst escapedID = id.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\t\tbody = body.replace(new RegExp(\"([#;\\\"])(\" + escapedID + \")([\\\")]|\\\\.[a-z])\", \"g\"), \"$1\" + newID + suffix + \"$3\");\n\t});\n\tbody = body.replace(new RegExp(suffix, \"g\"), \"\");\n\treturn body;\n}\n\nexport { replaceIDs };", "/**\n* Generate \n*/\nfunction iconToHTML(body, attributes) {\n\tlet renderAttribsHTML = body.indexOf(\"xlink:\") === -1 ? \"\" : \" xmlns:xlink=\\\"http://www.w3.org/1999/xlink\\\"\";\n\tfor (const attr in attributes) renderAttribsHTML += \" \" + attr + \"=\\\"\" + attributes[attr] + \"\\\"\";\n\treturn \"\" + body + \"\";\n}\n\nexport { iconToHTML };", "import type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Gets the original marked default options.\n */\nexport function _getDefaults(): MarkedOptions {\n return {\n async: false,\n breaks: false,\n extensions: null,\n gfm: true,\n hooks: null,\n pedantic: false,\n renderer: null,\n silent: false,\n tokenizer: null,\n walkTokens: null,\n };\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport let _defaults: MarkedOptions = _getDefaults();\n\nexport function changeDefaults(newDefaults: MarkedOptions) {\n _defaults = newDefaults;\n}\n", "const noopTest = { exec: () => null } as unknown as RegExp;\n\nfunction edit(regex: string | RegExp, opt = '') {\n let source = typeof regex === 'string' ? regex : regex.source;\n const obj = {\n replace: (name: string | RegExp, val: string | RegExp) => {\n let valSource = typeof val === 'string' ? val : val.source;\n valSource = valSource.replace(other.caret, '$1');\n source = source.replace(name, valSource);\n return obj;\n },\n getRegex: () => {\n return new RegExp(source, opt);\n },\n };\n return obj;\n}\n\nexport const other = {\n codeRemoveIndent: /^(?: {1,4}| {0,3}\\t)/gm,\n outputLinkReplace: /\\\\([\\[\\]])/g,\n indentCodeCompensation: /^(\\s+)(?:```)/,\n beginningSpace: /^\\s+/,\n endingHash: /#$/,\n startingSpaceChar: /^ /,\n endingSpaceChar: / $/,\n nonSpaceChar: /[^ ]/,\n newLineCharGlobal: /\\n/g,\n tabCharGlobal: /\\t/g,\n multipleSpaceGlobal: /\\s+/g,\n blankLine: /^[ \\t]*$/,\n doubleBlankLine: /\\n[ \\t]*\\n[ \\t]*$/,\n blockquoteStart: /^ {0,3}>/,\n blockquoteSetextReplace: /\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g,\n blockquoteSetextReplace2: /^ {0,3}>[ \\t]?/gm,\n listReplaceTabs: /^\\t+/,\n listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,\n listIsTask: /^\\[[ xX]\\] /,\n listReplaceTask: /^\\[[ xX]\\] +/,\n anyLine: /\\n.*\\n/,\n hrefBrackets: /^<(.*)>$/,\n tableDelimiter: /[:|]/,\n tableAlignChars: /^\\||\\| *$/g,\n tableRowBlankLine: /\\n[ \\t]*$/,\n tableAlignRight: /^ *-+: *$/,\n tableAlignCenter: /^ *:-+: *$/,\n tableAlignLeft: /^ *:-+ *$/,\n startATag: /^/i,\n startPreScriptTag: /^<(pre|code|kbd|script)(\\s|>)/i,\n endPreScriptTag: /^<\\/(pre|code|kbd|script)(\\s|>)/i,\n startAngleBracket: /^$/,\n pedanticHrefTitle: /^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/,\n unicodeAlphaNumeric: /[\\p{L}\\p{N}]/u,\n escapeTest: /[&<>\"']/,\n escapeReplace: /[&<>\"']/g,\n escapeTestNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/,\n escapeReplaceNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,\n unescapeTest: /&(#(?:\\d+)|(?:#x[0-9A-Fa-f]+)|(?:\\w+));?/ig,\n caret: /(^|[^\\[])\\^/g,\n percentDecode: /%25/g,\n findPipe: /\\|/g,\n splitPipe: / \\|/,\n slashPipe: /\\\\\\|/g,\n carriageReturn: /\\r\\n|\\r/g,\n spaceLine: /^ +$/gm,\n notSpaceStart: /^\\S*/,\n endingNewline: /\\n$/,\n listItemRegex: (bull: string) => new RegExp(`^( {0,3}${bull})((?:[\\t ][^\\\\n]*)?(?:\\\\n|$))`),\n nextBulletRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \\t][^\\\\n]*)?(?:\\\\n|$))`),\n hrRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`),\n fencesBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\\`\\`\\`|~~~)`),\n headingBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`),\n htmlBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, 'i'),\n};\n\n/**\n * Block-Level Grammar\n */\n\nconst newline = /^(?:[ \\t]*(?:\\n|$))+/;\nconst blockCode = /^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\n|$))*)?)+/;\nconst fences = /^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/;\nconst hr = /^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/;\nconst heading = /^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/;\nconst bullet = /(?:[*+-]|\\d{1,9}[.)])/;\nconst lheadingCore = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/;\nconst lheading = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // indented code blocks can interrupt\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .replace(/\\|table/g, '') // table not in commonmark\n .getRegex();\nconst lheadingGfm = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // indented code blocks can interrupt\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .replace(/table/g, / {0,3}\\|?(?:[:\\- ]*\\|)+[\\:\\- ]*\\n/) // table can interrupt\n .getRegex();\nconst _paragraph = /^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\\n)[^\\n]+)*)/;\nconst blockText = /^[^\\n]+/;\nconst _blockLabel = /(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\])+/;\nconst def = edit(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/)\n .replace('label', _blockLabel)\n .replace('title', /(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/)\n .getRegex();\n\nconst list = edit(/^( {0,3}bull)([ \\t][^\\n]+?)?(?:\\n|$)/)\n .replace(/bull/g, bullet)\n .getRegex();\n\nconst _tag = 'address|article|aside|base|basefont|blockquote|body|caption'\n + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'\n + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'\n + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'\n + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title'\n + '|tr|track|ul';\nconst _comment = /|$))/;\nconst html = edit(\n '^ {0,3}(?:' // optional indentation\n+ '<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:[^\\\\n]*\\\\n+|$)' // (1)\n+ '|comment[^\\\\n]*(\\\\n+|$)' // (2)\n+ '|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>\\\\n*|$)' // (3)\n+ '|\\\\n*|$)' // (4)\n+ '|\\\\n*|$)' // (5)\n+ '|)[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (6)\n+ '|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) open tag\n+ '|(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) closing tag\n+ ')', 'i')\n .replace('comment', _comment)\n .replace('tag', _tag)\n .replace('attribute', / +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/)\n .getRegex();\n\nconst paragraph = edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex();\n\nconst blockquote = edit(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/)\n .replace('paragraph', paragraph)\n .getRegex();\n\n/**\n * Normal Block Grammar\n */\n\nconst blockNormal = {\n blockquote,\n code: blockCode,\n def,\n fences,\n heading,\n hr,\n html,\n lheading,\n list,\n newline,\n paragraph,\n table: noopTest,\n text: blockText,\n};\n\ntype BlockKeys = keyof typeof blockNormal;\n\n/**\n * GFM Block Grammar\n */\n\nconst gfmTable = edit(\n '^ *([^\\\\n ].*)\\\\n' // Header\n+ ' {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)' // Align\n+ '(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)') // Cells\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('blockquote', ' {0,3}>')\n .replace('code', '(?: {4}| {0,3}\\t)[^\\\\n]')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // tables can be interrupted by type (6) html blocks\n .getRegex();\n\nconst blockGfm: Record = {\n ...blockNormal,\n lheading: lheadingGfm,\n table: gfmTable,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('table', gfmTable) // interrupt paragraphs with table\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex(),\n};\n\n/**\n * Pedantic grammar (original John Gruber's loose markdown specification)\n */\n\nconst blockPedantic: Record = {\n ...blockNormal,\n html: edit(\n '^ *(?:comment *(?:\\\\n|\\\\s*$)'\n + '|<(tag)[\\\\s\\\\S]+? *(?:\\\\n{2,}|\\\\s*$)' // closed tag\n + '|\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))')\n .replace('comment', _comment)\n .replace(/tag/g, '(?!(?:'\n + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'\n + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'\n + '\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b')\n .getRegex(),\n def: /^ *\\[([^\\]]+)\\]: *]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,\n heading: /^(#{1,6})(.*)(?:\\n+|$)/,\n fences: noopTest, // fences not supported\n lheading: /^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' *#{1,6} *[^\\n]')\n .replace('lheading', lheading)\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('|fences', '')\n .replace('|list', '')\n .replace('|html', '')\n .replace('|tag', '')\n .getRegex(),\n};\n\n/**\n * Inline-Level Grammar\n */\n\nconst escape = /^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/;\nconst inlineCode = /^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/;\nconst br = /^( {2,}|\\\\)\\n(?!\\s*$)/;\nconst inlineText = /^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\\nconst blockSkip = /\\[[^\\[\\]]*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)|`[^`]*?`|<(?! )[^<>]*?>/g;\n\nconst emStrongLDelimCore = /^(?:\\*+(?:((?!\\*)punct)|[^\\s*]))|^_+(?:((?!_)punct)|([^\\s_]))/;\n\nconst emStrongLDelim = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongLDelimGfm = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\nconst emStrongRDelimAstCore =\n '^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)' // Skip orphan inside strong\n+ '|[^*]+(?=[^*])' // Consume to delim\n+ '|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)' // (1) #*** can only be a Right Delimiter\n+ '|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)' // (2) a***#, a*** can only be a Right Delimiter\n+ '|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)' // (3) #***a, ***a can only be Left Delimiter\n+ '|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)' // (4) ***# can only be Left Delimiter\n+ '|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)' // (5) #***# can be either Left or Right Delimiter\n+ '|notPunctSpace(\\\\*+)(?=notPunctSpace)'; // (6) a***a can be either Left or Right Delimiter\n\nconst emStrongRDelimAst = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm)\n .replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm)\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\n// (6) Not allowed for _\nconst emStrongRDelimUnd = edit(\n '^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)' // Skip orphan inside strong\n+ '|[^_]+(?=[^_])' // Consume to delim\n+ '|(?!_)punct(_+)(?=[\\\\s]|$)' // (1) #___ can only be a Right Delimiter\n+ '|notPunctSpace(_+)(?!_)(?=punctSpace|$)' // (2) a___#, a___ can only be a Right Delimiter\n+ '|(?!_)punctSpace(_+)(?=notPunctSpace)' // (3) #___a, ___a can only be Left Delimiter\n+ '|[\\\\s](_+)(?!_)(?=punct)' // (4) ___# can only be Left Delimiter\n+ '|(?!_)punct(_+)(?!_)(?=punct)', 'gu') // (5) #___# can be either Left or Right Delimiter\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst anyPunctuation = edit(/\\\\(punct)/, 'gu')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst autolink = edit(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/)\n .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/)\n .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/)\n .getRegex();\n\nconst _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();\nconst tag = edit(\n '^comment'\n + '|^' // self-closing tag\n + '|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>' // open tag\n + '|^<\\\\?[\\\\s\\\\S]*?\\\\?>' // processing instruction, e.g. \n + '|^' // declaration, e.g. \n + '|^') // CDATA section\n .replace('comment', _inlineComment)\n .replace('attribute', /\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/)\n .getRegex();\n\nconst _inlineLabel = /(?:\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`[^`]*`|[^\\[\\]\\\\`])*?/;\n\nconst link = edit(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]*(?:\\n[ \\t]*)?)(title))?\\s*\\)/)\n .replace('label', _inlineLabel)\n .replace('href', /<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]*/)\n .replace('title', /\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/)\n .getRegex();\n\nconst reflink = edit(/^!?\\[(label)\\]\\[(ref)\\]/)\n .replace('label', _inlineLabel)\n .replace('ref', _blockLabel)\n .getRegex();\n\nconst nolink = edit(/^!?\\[(ref)\\](?:\\[\\])?/)\n .replace('ref', _blockLabel)\n .getRegex();\n\nconst reflinkSearch = edit('reflink|nolink(?!\\\\()', 'g')\n .replace('reflink', reflink)\n .replace('nolink', nolink)\n .getRegex();\n\n/**\n * Normal Inline Grammar\n */\n\nconst inlineNormal = {\n _backpedal: noopTest, // only used for GFM url\n anyPunctuation,\n autolink,\n blockSkip,\n br,\n code: inlineCode,\n del: noopTest,\n emStrongLDelim,\n emStrongRDelimAst,\n emStrongRDelimUnd,\n escape,\n link,\n nolink,\n punctuation,\n reflink,\n reflinkSearch,\n tag,\n text: inlineText,\n url: noopTest,\n};\n\ntype InlineKeys = keyof typeof inlineNormal;\n\n/**\n * Pedantic Inline Grammar\n */\n\nconst inlinePedantic: Record = {\n ...inlineNormal,\n link: edit(/^!?\\[(label)\\]\\((.*?)\\)/)\n .replace('label', _inlineLabel)\n .getRegex(),\n reflink: edit(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/)\n .replace('label', _inlineLabel)\n .getRegex(),\n};\n\n/**\n * GFM Inline Grammar\n */\n\nconst inlineGfm: Record = {\n ...inlineNormal,\n emStrongRDelimAst: emStrongRDelimAstGfm,\n emStrongLDelim: emStrongLDelimGfm,\n url: edit(/^((?:ftp|https?):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/, 'i')\n .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/)\n .getRegex(),\n _backpedal: /(?:[^?!.,:;*_'\"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'\"~)]+(?!$))+/,\n del: /^(~~?)(?=[^\\s~])((?:\\\\[\\s\\S]|[^\\\\])*?(?:\\\\[\\s\\S]|[^\\s~\\\\]))\\1(?=[^~]|$)/,\n text: /^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\ = {\n ...inlineGfm,\n br: edit(br).replace('{2,}', '*').getRegex(),\n text: edit(inlineGfm.text)\n .replace('\\\\b_', '\\\\b_| {2,}\\\\n')\n .replace(/\\{2,\\}/g, '*')\n .getRegex(),\n};\n\n/**\n * exports\n */\n\nexport const block = {\n normal: blockNormal,\n gfm: blockGfm,\n pedantic: blockPedantic,\n};\n\nexport const inline = {\n normal: inlineNormal,\n gfm: inlineGfm,\n breaks: inlineBreaks,\n pedantic: inlinePedantic,\n};\n\nexport interface Rules {\n other: typeof other\n block: Record\n inline: Record\n}\n", "import { other } from './rules.ts';\n\n/**\n * Helpers\n */\nconst escapeReplacements: { [index: string]: string } = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n};\nconst getEscapeReplacement = (ch: string) => escapeReplacements[ch];\n\nexport function escape(html: string, encode?: boolean) {\n if (encode) {\n if (other.escapeTest.test(html)) {\n return html.replace(other.escapeReplace, getEscapeReplacement);\n }\n } else {\n if (other.escapeTestNoEncode.test(html)) {\n return html.replace(other.escapeReplaceNoEncode, getEscapeReplacement);\n }\n }\n\n return html;\n}\n\nexport function unescape(html: string) {\n // explicitly match decimal, hex, and named HTML entities\n return html.replace(other.unescapeTest, (_, n) => {\n n = n.toLowerCase();\n if (n === 'colon') return ':';\n if (n.charAt(0) === '#') {\n return n.charAt(1) === 'x'\n ? String.fromCharCode(parseInt(n.substring(2), 16))\n : String.fromCharCode(+n.substring(1));\n }\n return '';\n });\n}\n\nexport function cleanUrl(href: string) {\n try {\n href = encodeURI(href).replace(other.percentDecode, '%');\n } catch {\n return null;\n }\n return href;\n}\n\nexport function splitCells(tableRow: string, count?: number) {\n // ensure that every cell-delimiting pipe has a space\n // before it to distinguish it from an escaped pipe\n const row = tableRow.replace(other.findPipe, (match, offset, str) => {\n let escaped = false;\n let curr = offset;\n while (--curr >= 0 && str[curr] === '\\\\') escaped = !escaped;\n if (escaped) {\n // odd number of slashes means | is escaped\n // so we leave it alone\n return '|';\n } else {\n // add space before unescaped |\n return ' |';\n }\n }),\n cells = row.split(other.splitPipe);\n let i = 0;\n\n // First/last cell in a row cannot be empty if it has no leading/trailing pipe\n if (!cells[0].trim()) {\n cells.shift();\n }\n if (cells.length > 0 && !cells.at(-1)?.trim()) {\n cells.pop();\n }\n\n if (count) {\n if (cells.length > count) {\n cells.splice(count);\n } else {\n while (cells.length < count) cells.push('');\n }\n }\n\n for (; i < cells.length; i++) {\n // leading or trailing whitespace is ignored per the gfm spec\n cells[i] = cells[i].trim().replace(other.slashPipe, '|');\n }\n return cells;\n}\n\n/**\n * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').\n * /c*$/ is vulnerable to REDOS.\n *\n * @param str\n * @param c\n * @param invert Remove suffix of non-c chars instead. Default falsey.\n */\nexport function rtrim(str: string, c: string, invert?: boolean) {\n const l = str.length;\n if (l === 0) {\n return '';\n }\n\n // Length of suffix matching the invert condition.\n let suffLen = 0;\n\n // Step left until we fail to match the invert condition.\n while (suffLen < l) {\n const currChar = str.charAt(l - suffLen - 1);\n if (currChar === c && !invert) {\n suffLen++;\n } else if (currChar !== c && invert) {\n suffLen++;\n } else {\n break;\n }\n }\n\n return str.slice(0, l - suffLen);\n}\n\nexport function findClosingBracket(str: string, b: string) {\n if (str.indexOf(b[1]) === -1) {\n return -1;\n }\n\n let level = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '\\\\') {\n i++;\n } else if (str[i] === b[0]) {\n level++;\n } else if (str[i] === b[1]) {\n level--;\n if (level < 0) {\n return i;\n }\n }\n }\n if (level > 0) {\n return -2;\n }\n\n return -1;\n}\n", "import { _defaults } from './defaults.ts';\nimport {\n rtrim,\n splitCells,\n findClosingBracket,\n} from './helpers.ts';\nimport type { Rules } from './rules.ts';\nimport type { _Lexer } from './Lexer.ts';\nimport type { Links, Tokens, Token } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\nfunction outputLink(cap: string[], link: Pick, raw: string, lexer: _Lexer, rules: Rules): Tokens.Link | Tokens.Image {\n const href = link.href;\n const title = link.title || null;\n const text = cap[1].replace(rules.other.outputLinkReplace, '$1');\n\n lexer.state.inLink = true;\n const token: Tokens.Link | Tokens.Image = {\n type: cap[0].charAt(0) === '!' ? 'image' : 'link',\n raw,\n href,\n title,\n text,\n tokens: lexer.inlineTokens(text),\n };\n lexer.state.inLink = false;\n return token;\n}\n\nfunction indentCodeCompensation(raw: string, text: string, rules: Rules) {\n const matchIndentToCode = raw.match(rules.other.indentCodeCompensation);\n\n if (matchIndentToCode === null) {\n return text;\n }\n\n const indentToCode = matchIndentToCode[1];\n\n return text\n .split('\\n')\n .map(node => {\n const matchIndentInNode = node.match(rules.other.beginningSpace);\n if (matchIndentInNode === null) {\n return node;\n }\n\n const [indentInNode] = matchIndentInNode;\n\n if (indentInNode.length >= indentToCode.length) {\n return node.slice(indentToCode.length);\n }\n\n return node;\n })\n .join('\\n');\n}\n\n/**\n * Tokenizer\n */\nexport class _Tokenizer {\n options: MarkedOptions;\n rules!: Rules; // set by the lexer\n lexer!: _Lexer; // set by the lexer\n\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n }\n\n space(src: string): Tokens.Space | undefined {\n const cap = this.rules.block.newline.exec(src);\n if (cap && cap[0].length > 0) {\n return {\n type: 'space',\n raw: cap[0],\n };\n }\n }\n\n code(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.code.exec(src);\n if (cap) {\n const text = cap[0].replace(this.rules.other.codeRemoveIndent, '');\n return {\n type: 'code',\n raw: cap[0],\n codeBlockStyle: 'indented',\n text: !this.options.pedantic\n ? rtrim(text, '\\n')\n : text,\n };\n }\n }\n\n fences(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.fences.exec(src);\n if (cap) {\n const raw = cap[0];\n const text = indentCodeCompensation(raw, cap[3] || '', this.rules);\n\n return {\n type: 'code',\n raw,\n lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],\n text,\n };\n }\n }\n\n heading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.heading.exec(src);\n if (cap) {\n let text = cap[2].trim();\n\n // remove trailing #s\n if (this.rules.other.endingHash.test(text)) {\n const trimmed = rtrim(text, '#');\n if (this.options.pedantic) {\n text = trimmed.trim();\n } else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) {\n // CommonMark requires space before trailing #s\n text = trimmed.trim();\n }\n }\n\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[1].length,\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n hr(src: string): Tokens.Hr | undefined {\n const cap = this.rules.block.hr.exec(src);\n if (cap) {\n return {\n type: 'hr',\n raw: rtrim(cap[0], '\\n'),\n };\n }\n }\n\n blockquote(src: string): Tokens.Blockquote | undefined {\n const cap = this.rules.block.blockquote.exec(src);\n if (cap) {\n let lines = rtrim(cap[0], '\\n').split('\\n');\n let raw = '';\n let text = '';\n const tokens: Token[] = [];\n\n while (lines.length > 0) {\n let inBlockquote = false;\n const currentLines = [];\n\n let i;\n for (i = 0; i < lines.length; i++) {\n // get lines up to a continuation\n if (this.rules.other.blockquoteStart.test(lines[i])) {\n currentLines.push(lines[i]);\n inBlockquote = true;\n } else if (!inBlockquote) {\n currentLines.push(lines[i]);\n } else {\n break;\n }\n }\n lines = lines.slice(i);\n\n const currentRaw = currentLines.join('\\n');\n const currentText = currentRaw\n // precede setext continuation with 4 spaces so it isn't a setext\n .replace(this.rules.other.blockquoteSetextReplace, '\\n $1')\n .replace(this.rules.other.blockquoteSetextReplace2, '');\n raw = raw ? `${raw}\\n${currentRaw}` : currentRaw;\n text = text ? `${text}\\n${currentText}` : currentText;\n\n // parse blockquote lines as top level tokens\n // merge paragraphs if this is a continuation\n const top = this.lexer.state.top;\n this.lexer.state.top = true;\n this.lexer.blockTokens(currentText, tokens, true);\n this.lexer.state.top = top;\n\n // if there is no continuation then we are done\n if (lines.length === 0) {\n break;\n }\n\n const lastToken = tokens.at(-1);\n\n if (lastToken?.type === 'code') {\n // blockquote continuation cannot be preceded by a code block\n break;\n } else if (lastToken?.type === 'blockquote') {\n // include continuation in nested blockquote\n const oldToken = lastToken as Tokens.Blockquote;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.blockquote(newText)!;\n tokens[tokens.length - 1] = newToken;\n\n raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.text.length) + newToken.text;\n break;\n } else if (lastToken?.type === 'list') {\n // include continuation in nested list\n const oldToken = lastToken as Tokens.List;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.list(newText)!;\n tokens[tokens.length - 1] = newToken;\n\n raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;\n lines = newText.substring(tokens.at(-1)!.raw.length).split('\\n');\n continue;\n }\n }\n\n return {\n type: 'blockquote',\n raw,\n tokens,\n text,\n };\n }\n }\n\n list(src: string): Tokens.List | undefined {\n let cap = this.rules.block.list.exec(src);\n if (cap) {\n let bull = cap[1].trim();\n const isordered = bull.length > 1;\n\n const list: Tokens.List = {\n type: 'list',\n raw: '',\n ordered: isordered,\n start: isordered ? +bull.slice(0, -1) : '',\n loose: false,\n items: [],\n };\n\n bull = isordered ? `\\\\d{1,9}\\\\${bull.slice(-1)}` : `\\\\${bull}`;\n\n if (this.options.pedantic) {\n bull = isordered ? bull : '[*+-]';\n }\n\n // Get next list item\n const itemRegex = this.rules.other.listItemRegex(bull);\n let endsWithBlankLine = false;\n // Check if current bullet point can start a new List Item\n while (src) {\n let endEarly = false;\n let raw = '';\n let itemContents = '';\n if (!(cap = itemRegex.exec(src))) {\n break;\n }\n\n if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)\n break;\n }\n\n raw = cap[0];\n src = src.substring(raw.length);\n\n let line = cap[2].split('\\n', 1)[0].replace(this.rules.other.listReplaceTabs, (t: string) => ' '.repeat(3 * t.length));\n let nextLine = src.split('\\n', 1)[0];\n let blankLine = !line.trim();\n\n let indent = 0;\n if (this.options.pedantic) {\n indent = 2;\n itemContents = line.trimStart();\n } else if (blankLine) {\n indent = cap[1].length + 1;\n } else {\n indent = cap[2].search(this.rules.other.nonSpaceChar); // Find first non-space char\n indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent\n itemContents = line.slice(indent);\n indent += cap[1].length;\n }\n\n if (blankLine && this.rules.other.blankLine.test(nextLine)) { // Items begin with at most one blank line\n raw += nextLine + '\\n';\n src = src.substring(nextLine.length + 1);\n endEarly = true;\n }\n\n if (!endEarly) {\n const nextBulletRegex = this.rules.other.nextBulletRegex(indent);\n const hrRegex = this.rules.other.hrRegex(indent);\n const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent);\n const headingBeginRegex = this.rules.other.headingBeginRegex(indent);\n const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent);\n\n // Check if following lines should be included in List Item\n while (src) {\n const rawLine = src.split('\\n', 1)[0];\n let nextLineWithoutTabs;\n nextLine = rawLine;\n\n // Re-align to follow commonmark nesting rules\n if (this.options.pedantic) {\n nextLine = nextLine.replace(this.rules.other.listReplaceNesting, ' ');\n nextLineWithoutTabs = nextLine;\n } else {\n nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, ' ');\n }\n\n // End list item if found code fences\n if (fencesBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new heading\n if (headingBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of html block\n if (htmlBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new bullet\n if (nextBulletRegex.test(nextLine)) {\n break;\n }\n\n // Horizontal rule found\n if (hrRegex.test(nextLine)) {\n break;\n }\n\n if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) { // Dedent if possible\n itemContents += '\\n' + nextLineWithoutTabs.slice(indent);\n } else {\n // not enough indentation\n if (blankLine) {\n break;\n }\n\n // paragraph continuation unless last line was a different block level element\n if (line.replace(this.rules.other.tabCharGlobal, ' ').search(this.rules.other.nonSpaceChar) >= 4) { // indented code block\n break;\n }\n if (fencesBeginRegex.test(line)) {\n break;\n }\n if (headingBeginRegex.test(line)) {\n break;\n }\n if (hrRegex.test(line)) {\n break;\n }\n\n itemContents += '\\n' + nextLine;\n }\n\n if (!blankLine && !nextLine.trim()) { // Check if current line is blank\n blankLine = true;\n }\n\n raw += rawLine + '\\n';\n src = src.substring(rawLine.length + 1);\n line = nextLineWithoutTabs.slice(indent);\n }\n }\n\n if (!list.loose) {\n // If the previous item ended with a blank line, the list is loose\n if (endsWithBlankLine) {\n list.loose = true;\n } else if (this.rules.other.doubleBlankLine.test(raw)) {\n endsWithBlankLine = true;\n }\n }\n\n let istask: RegExpExecArray | null = null;\n let ischecked: boolean | undefined;\n // Check for task list items\n if (this.options.gfm) {\n istask = this.rules.other.listIsTask.exec(itemContents);\n if (istask) {\n ischecked = istask[0] !== '[ ] ';\n itemContents = itemContents.replace(this.rules.other.listReplaceTask, '');\n }\n }\n\n list.items.push({\n type: 'list_item',\n raw,\n task: !!istask,\n checked: ischecked,\n loose: false,\n text: itemContents,\n tokens: [],\n });\n\n list.raw += raw;\n }\n\n // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic\n const lastItem = list.items.at(-1);\n if (lastItem) {\n lastItem.raw = lastItem.raw.trimEnd();\n lastItem.text = lastItem.text.trimEnd();\n } else {\n // not a list since there were no items\n return;\n }\n list.raw = list.raw.trimEnd();\n\n // Item child tokens handled here at end because we needed to have the final item to trim it first\n for (let i = 0; i < list.items.length; i++) {\n this.lexer.state.top = false;\n list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);\n\n if (!list.loose) {\n // Check if list should be loose\n const spacers = list.items[i].tokens.filter(t => t.type === 'space');\n const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => this.rules.other.anyLine.test(t.raw));\n\n list.loose = hasMultipleLineBreaks;\n }\n }\n\n // Set all items to loose if list is loose\n if (list.loose) {\n for (let i = 0; i < list.items.length; i++) {\n list.items[i].loose = true;\n }\n }\n\n return list;\n }\n }\n\n html(src: string): Tokens.HTML | undefined {\n const cap = this.rules.block.html.exec(src);\n if (cap) {\n const token: Tokens.HTML = {\n type: 'html',\n block: true,\n raw: cap[0],\n pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',\n text: cap[0],\n };\n return token;\n }\n }\n\n def(src: string): Tokens.Def | undefined {\n const cap = this.rules.block.def.exec(src);\n if (cap) {\n const tag = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, ' ');\n const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';\n const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];\n return {\n type: 'def',\n tag,\n raw: cap[0],\n href,\n title,\n };\n }\n }\n\n table(src: string): Tokens.Table | undefined {\n const cap = this.rules.block.table.exec(src);\n if (!cap) {\n return;\n }\n\n if (!this.rules.other.tableDelimiter.test(cap[2])) {\n // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading\n return;\n }\n\n const headers = splitCells(cap[1]);\n const aligns = cap[2].replace(this.rules.other.tableAlignChars, '').split('|');\n const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, '').split('\\n') : [];\n\n const item: Tokens.Table = {\n type: 'table',\n raw: cap[0],\n header: [],\n align: [],\n rows: [],\n };\n\n if (headers.length !== aligns.length) {\n // header and align columns must be equal, rows can be different.\n return;\n }\n\n for (const align of aligns) {\n if (this.rules.other.tableAlignRight.test(align)) {\n item.align.push('right');\n } else if (this.rules.other.tableAlignCenter.test(align)) {\n item.align.push('center');\n } else if (this.rules.other.tableAlignLeft.test(align)) {\n item.align.push('left');\n } else {\n item.align.push(null);\n }\n }\n\n for (let i = 0; i < headers.length; i++) {\n item.header.push({\n text: headers[i],\n tokens: this.lexer.inline(headers[i]),\n header: true,\n align: item.align[i],\n });\n }\n\n for (const row of rows) {\n item.rows.push(splitCells(row, item.header.length).map((cell, i) => {\n return {\n text: cell,\n tokens: this.lexer.inline(cell),\n header: false,\n align: item.align[i],\n };\n }));\n }\n\n return item;\n }\n\n lheading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.lheading.exec(src);\n if (cap) {\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[2].charAt(0) === '=' ? 1 : 2,\n text: cap[1],\n tokens: this.lexer.inline(cap[1]),\n };\n }\n }\n\n paragraph(src: string): Tokens.Paragraph | undefined {\n const cap = this.rules.block.paragraph.exec(src);\n if (cap) {\n const text = cap[1].charAt(cap[1].length - 1) === '\\n'\n ? cap[1].slice(0, -1)\n : cap[1];\n return {\n type: 'paragraph',\n raw: cap[0],\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n text(src: string): Tokens.Text | undefined {\n const cap = this.rules.block.text.exec(src);\n if (cap) {\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n tokens: this.lexer.inline(cap[0]),\n };\n }\n }\n\n escape(src: string): Tokens.Escape | undefined {\n const cap = this.rules.inline.escape.exec(src);\n if (cap) {\n return {\n type: 'escape',\n raw: cap[0],\n text: cap[1],\n };\n }\n }\n\n tag(src: string): Tokens.Tag | undefined {\n const cap = this.rules.inline.tag.exec(src);\n if (cap) {\n if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) {\n this.lexer.state.inLink = true;\n } else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) {\n this.lexer.state.inLink = false;\n }\n if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = true;\n } else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = false;\n }\n\n return {\n type: 'html',\n raw: cap[0],\n inLink: this.lexer.state.inLink,\n inRawBlock: this.lexer.state.inRawBlock,\n block: false,\n text: cap[0],\n };\n }\n }\n\n link(src: string): Tokens.Link | Tokens.Image | undefined {\n const cap = this.rules.inline.link.exec(src);\n if (cap) {\n const trimmedUrl = cap[2].trim();\n if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) {\n // commonmark requires matching angle brackets\n if (!(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n return;\n }\n\n // ending angle bracket cannot be escaped\n const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\\\');\n if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {\n return;\n }\n } else {\n // find closing parenthesis\n const lastParenIndex = findClosingBracket(cap[2], '()');\n if (lastParenIndex === -2) {\n // more open parens than closed\n return;\n }\n\n if (lastParenIndex > -1) {\n const start = cap[0].indexOf('!') === 0 ? 5 : 4;\n const linkLen = start + cap[1].length + lastParenIndex;\n cap[2] = cap[2].substring(0, lastParenIndex);\n cap[0] = cap[0].substring(0, linkLen).trim();\n cap[3] = '';\n }\n }\n let href = cap[2];\n let title = '';\n if (this.options.pedantic) {\n // split pedantic href and title\n const link = this.rules.other.pedanticHrefTitle.exec(href);\n\n if (link) {\n href = link[1];\n title = link[3];\n }\n } else {\n title = cap[3] ? cap[3].slice(1, -1) : '';\n }\n\n href = href.trim();\n if (this.rules.other.startAngleBracket.test(href)) {\n if (this.options.pedantic && !(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n // pedantic allows starting angle bracket without ending angle bracket\n href = href.slice(1);\n } else {\n href = href.slice(1, -1);\n }\n }\n return outputLink(cap, {\n href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,\n title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title,\n }, cap[0], this.lexer, this.rules);\n }\n }\n\n reflink(src: string, links: Links): Tokens.Link | Tokens.Image | Tokens.Text | undefined {\n let cap;\n if ((cap = this.rules.inline.reflink.exec(src))\n || (cap = this.rules.inline.nolink.exec(src))) {\n const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, ' ');\n const link = links[linkString.toLowerCase()];\n if (!link) {\n const text = cap[0].charAt(0);\n return {\n type: 'text',\n raw: text,\n text,\n };\n }\n return outputLink(cap, link, cap[0], this.lexer, this.rules);\n }\n }\n\n emStrong(src: string, maskedSrc: string, prevChar = ''): Tokens.Em | Tokens.Strong | undefined {\n let match = this.rules.inline.emStrongLDelim.exec(src);\n if (!match) return;\n\n // _ can't be between two alphanumerics. \\p{L}\\p{N} includes non-english alphabet/numbers as well\n if (match[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) return;\n\n const nextChar = match[1] || match[2] || '';\n\n if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {\n // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below)\n const lLength = [...match[0]].length - 1;\n let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;\n\n const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;\n endReg.lastIndex = 0;\n\n // Clip maskedSrc to same section of string as src (move to lexer?)\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n\n while ((match = endReg.exec(maskedSrc)) != null) {\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n\n if (!rDelim) continue; // skip single * in __abc*abc__\n\n rLength = [...rDelim].length;\n\n if (match[3] || match[4]) { // found another Left Delim\n delimTotal += rLength;\n continue;\n } else if (match[5] || match[6]) { // either Left or Right Delim\n if (lLength % 3 && !((lLength + rLength) % 3)) {\n midDelimTotal += rLength;\n continue; // CommonMark Emphasis Rules 9-10\n }\n }\n\n delimTotal -= rLength;\n\n if (delimTotal > 0) continue; // Haven't found enough closing delimiters\n\n // Remove extra characters. *a*** -> *a*\n rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);\n // char length can be >1 for unicode characters;\n const lastCharLength = [...match[0]][0].length;\n const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);\n\n // Create `em` if smallest delimiter has odd char count. *a***\n if (Math.min(lLength, rLength) % 2) {\n const text = raw.slice(1, -1);\n return {\n type: 'em',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n\n // Create 'strong' if smallest delimiter has even char count. **a***\n const text = raw.slice(2, -2);\n return {\n type: 'strong',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n }\n }\n\n codespan(src: string): Tokens.Codespan | undefined {\n const cap = this.rules.inline.code.exec(src);\n if (cap) {\n let text = cap[2].replace(this.rules.other.newLineCharGlobal, ' ');\n const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text);\n const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text);\n if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {\n text = text.substring(1, text.length - 1);\n }\n return {\n type: 'codespan',\n raw: cap[0],\n text,\n };\n }\n }\n\n br(src: string): Tokens.Br | undefined {\n const cap = this.rules.inline.br.exec(src);\n if (cap) {\n return {\n type: 'br',\n raw: cap[0],\n };\n }\n }\n\n del(src: string): Tokens.Del | undefined {\n const cap = this.rules.inline.del.exec(src);\n if (cap) {\n return {\n type: 'del',\n raw: cap[0],\n text: cap[2],\n tokens: this.lexer.inlineTokens(cap[2]),\n };\n }\n }\n\n autolink(src: string): Tokens.Link | undefined {\n const cap = this.rules.inline.autolink.exec(src);\n if (cap) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[1];\n href = 'mailto:' + text;\n } else {\n text = cap[1];\n href = text;\n }\n\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text,\n },\n ],\n };\n }\n }\n\n url(src: string): Tokens.Link | undefined {\n let cap;\n if (cap = this.rules.inline.url.exec(src)) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[0];\n href = 'mailto:' + text;\n } else {\n // do extended autolink path validation\n let prevCapZero;\n do {\n prevCapZero = cap[0];\n cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';\n } while (prevCapZero !== cap[0]);\n text = cap[0];\n if (cap[1] === 'www.') {\n href = 'http://' + cap[0];\n } else {\n href = cap[0];\n }\n }\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text,\n },\n ],\n };\n }\n }\n\n inlineText(src: string): Tokens.Text | undefined {\n const cap = this.rules.inline.text.exec(src);\n if (cap) {\n const escaped = this.lexer.state.inRawBlock;\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n escaped,\n };\n }\n }\n}\n", "import { _Tokenizer } from './Tokenizer.ts';\nimport { _defaults } from './defaults.ts';\nimport { other, block, inline } from './rules.ts';\nimport type { Token, TokensList, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Block Lexer\n */\nexport class _Lexer {\n tokens: TokensList;\n options: MarkedOptions;\n state: {\n inLink: boolean;\n inRawBlock: boolean;\n top: boolean;\n };\n\n private tokenizer: _Tokenizer;\n private inlineQueue: { src: string, tokens: Token[] }[];\n\n constructor(options?: MarkedOptions) {\n // TokenList cannot be created in one go\n this.tokens = [] as unknown as TokensList;\n this.tokens.links = Object.create(null);\n this.options = options || _defaults;\n this.options.tokenizer = this.options.tokenizer || new _Tokenizer();\n this.tokenizer = this.options.tokenizer;\n this.tokenizer.options = this.options;\n this.tokenizer.lexer = this;\n this.inlineQueue = [];\n this.state = {\n inLink: false,\n inRawBlock: false,\n top: true,\n };\n\n const rules = {\n other,\n block: block.normal,\n inline: inline.normal,\n };\n\n if (this.options.pedantic) {\n rules.block = block.pedantic;\n rules.inline = inline.pedantic;\n } else if (this.options.gfm) {\n rules.block = block.gfm;\n if (this.options.breaks) {\n rules.inline = inline.breaks;\n } else {\n rules.inline = inline.gfm;\n }\n }\n this.tokenizer.rules = rules;\n }\n\n /**\n * Expose Rules\n */\n static get rules() {\n return {\n block,\n inline,\n };\n }\n\n /**\n * Static Lex Method\n */\n static lex(src: string, options?: MarkedOptions) {\n const lexer = new _Lexer(options);\n return lexer.lex(src);\n }\n\n /**\n * Static Lex Inline Method\n */\n static lexInline(src: string, options?: MarkedOptions) {\n const lexer = new _Lexer(options);\n return lexer.inlineTokens(src);\n }\n\n /**\n * Preprocessing\n */\n lex(src: string) {\n src = src.replace(other.carriageReturn, '\\n');\n\n this.blockTokens(src, this.tokens);\n\n for (let i = 0; i < this.inlineQueue.length; i++) {\n const next = this.inlineQueue[i];\n this.inlineTokens(next.src, next.tokens);\n }\n this.inlineQueue = [];\n\n return this.tokens;\n }\n\n /**\n * Lexing\n */\n blockTokens(src: string, tokens?: Token[], lastParagraphClipped?: boolean): Token[];\n blockTokens(src: string, tokens?: TokensList, lastParagraphClipped?: boolean): TokensList;\n blockTokens(src: string, tokens: Token[] = [], lastParagraphClipped = false) {\n if (this.options.pedantic) {\n src = src.replace(other.tabCharGlobal, ' ').replace(other.spaceLine, '');\n }\n\n while (src) {\n let token: Tokens.Generic | undefined;\n\n if (this.options.extensions?.block?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n\n // newline\n if (token = this.tokenizer.space(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.raw.length === 1 && lastToken !== undefined) {\n // if there's a single \\n as a spacer, it's terminating the last line,\n // so move it there so that we don't get unnecessary paragraph tags\n lastToken.raw += '\\n';\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // code\n if (token = this.tokenizer.code(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n // An indented code block cannot interrupt a paragraph.\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // fences\n if (token = this.tokenizer.fences(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // heading\n if (token = this.tokenizer.heading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // hr\n if (token = this.tokenizer.hr(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // blockquote\n if (token = this.tokenizer.blockquote(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // list\n if (token = this.tokenizer.list(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // html\n if (token = this.tokenizer.html(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // def\n if (token = this.tokenizer.def(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.raw;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else if (!this.tokens.links[token.tag]) {\n this.tokens.links[token.tag] = {\n href: token.href,\n title: token.title,\n };\n tokens.push(token);\n }\n continue;\n }\n\n // table (gfm)\n if (token = this.tokenizer.table(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // lheading\n if (token = this.tokenizer.lheading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // top-level paragraph\n // prevent paragraph consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (this.options.extensions?.startBlock) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startBlock.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {\n const lastToken = tokens.at(-1);\n if (lastParagraphClipped && lastToken?.type === 'paragraph') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n lastParagraphClipped = cutSrc.length !== src.length;\n src = src.substring(token.raw.length);\n continue;\n }\n\n // text\n if (token = this.tokenizer.text(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n\n this.state.top = true;\n return tokens;\n }\n\n inline(src: string, tokens: Token[] = []) {\n this.inlineQueue.push({ src, tokens });\n return tokens;\n }\n\n /**\n * Lexing/Compiling\n */\n inlineTokens(src: string, tokens: Token[] = []): Token[] {\n // String with links masked to avoid interference with em and strong\n let maskedSrc = src;\n let match: RegExpExecArray | null = null;\n\n // Mask out reflinks\n if (this.tokens.links) {\n const links = Object.keys(this.tokens.links);\n if (links.length > 0) {\n while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {\n if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {\n maskedSrc = maskedSrc.slice(0, match.index)\n + '[' + 'a'.repeat(match[0].length - 2) + ']'\n + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);\n }\n }\n }\n }\n\n // Mask out escaped characters\n while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);\n }\n\n // Mask out other blocks\n while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);\n }\n\n // Mask out blocks from extensions\n maskedSrc = this.options.hooks?.emStrongMask?.call({ lexer: this }, maskedSrc) ?? maskedSrc;\n\n let keepPrevChar = false;\n let prevChar = '';\n while (src) {\n if (!keepPrevChar) {\n prevChar = '';\n }\n keepPrevChar = false;\n\n let token: Tokens.Generic | undefined;\n\n // extensions\n if (this.options.extensions?.inline?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n\n // escape\n if (token = this.tokenizer.escape(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // tag\n if (token = this.tokenizer.tag(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // link\n if (token = this.tokenizer.link(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // reflink, nolink\n if (token = this.tokenizer.reflink(src, this.tokens.links)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.type === 'text' && lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // em & strong\n if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // code\n if (token = this.tokenizer.codespan(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // br\n if (token = this.tokenizer.br(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // del (gfm)\n if (token = this.tokenizer.del(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // autolink\n if (token = this.tokenizer.autolink(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // url (gfm)\n if (!this.state.inLink && (token = this.tokenizer.url(src))) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // text\n // prevent inlineText consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (this.options.extensions?.startInline) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startInline.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (token = this.tokenizer.inlineText(cutSrc)) {\n src = src.substring(token.raw.length);\n if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started\n prevChar = token.raw.slice(-1);\n }\n keepPrevChar = true;\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n\n return tokens;\n }\n}\n", "import { _defaults } from './defaults.ts';\nimport {\n cleanUrl,\n escape,\n} from './helpers.ts';\nimport { other } from './rules.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Tokens } from './Tokens.ts';\nimport type { _Parser } from './Parser.ts';\n\n/**\n * Renderer\n */\nexport class _Renderer {\n options: MarkedOptions;\n parser!: _Parser; // set by the parser\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n }\n\n space(token: Tokens.Space): RendererOutput {\n return '' as RendererOutput;\n }\n\n code({ text, lang, escaped }: Tokens.Code): RendererOutput {\n const langString = (lang || '').match(other.notSpaceStart)?.[0];\n\n const code = text.replace(other.endingNewline, '') + '\\n';\n\n if (!langString) {\n return '
    '\n        + (escaped ? code : escape(code, true))\n        + '
    \\n' as RendererOutput;\n }\n\n return '
    '\n      + (escaped ? code : escape(code, true))\n      + '
    \\n' as RendererOutput;\n }\n\n blockquote({ tokens }: Tokens.Blockquote): RendererOutput {\n const body = this.parser.parse(tokens);\n return `
    \\n${body}
    \\n` as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n def(token: Tokens.Def): RendererOutput {\n return '' as RendererOutput;\n }\n\n heading({ tokens, depth }: Tokens.Heading): RendererOutput {\n return `${this.parser.parseInline(tokens)}\\n` as RendererOutput;\n }\n\n hr(token: Tokens.Hr): RendererOutput {\n return '
    \\n' as RendererOutput;\n }\n\n list(token: Tokens.List): RendererOutput {\n const ordered = token.ordered;\n const start = token.start;\n\n let body = '';\n for (let j = 0; j < token.items.length; j++) {\n const item = token.items[j];\n body += this.listitem(item);\n }\n\n const type = ordered ? 'ol' : 'ul';\n const startAttr = (ordered && start !== 1) ? (' start=\"' + start + '\"') : '';\n return '<' + type + startAttr + '>\\n' + body + '\\n' as RendererOutput;\n }\n\n listitem(item: Tokens.ListItem): RendererOutput {\n let itemBody = '';\n if (item.task) {\n const checkbox = this.checkbox({ checked: !!item.checked });\n if (item.loose) {\n if (item.tokens[0]?.type === 'paragraph') {\n item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;\n if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {\n item.tokens[0].tokens[0].text = checkbox + ' ' + escape(item.tokens[0].tokens[0].text);\n item.tokens[0].tokens[0].escaped = true;\n }\n } else {\n item.tokens.unshift({\n type: 'text',\n raw: checkbox + ' ',\n text: checkbox + ' ',\n escaped: true,\n });\n }\n } else {\n itemBody += checkbox + ' ';\n }\n }\n\n itemBody += this.parser.parse(item.tokens, !!item.loose);\n\n return `
  • ${itemBody}
  • \\n` as RendererOutput;\n }\n\n checkbox({ checked }: Tokens.Checkbox): RendererOutput {\n return '' as RendererOutput;\n }\n\n paragraph({ tokens }: Tokens.Paragraph): RendererOutput {\n return `

    ${this.parser.parseInline(tokens)}

    \\n` as RendererOutput;\n }\n\n table(token: Tokens.Table): RendererOutput {\n let header = '';\n\n // header\n let cell = '';\n for (let j = 0; j < token.header.length; j++) {\n cell += this.tablecell(token.header[j]);\n }\n header += this.tablerow({ text: cell as ParserOutput });\n\n let body = '';\n for (let j = 0; j < token.rows.length; j++) {\n const row = token.rows[j];\n\n cell = '';\n for (let k = 0; k < row.length; k++) {\n cell += this.tablecell(row[k]);\n }\n\n body += this.tablerow({ text: cell as ParserOutput });\n }\n if (body) body = `${body}`;\n\n return '\\n'\n + '\\n'\n + header\n + '\\n'\n + body\n + '
    \\n' as RendererOutput;\n }\n\n tablerow({ text }: Tokens.TableRow): RendererOutput {\n return `\\n${text}\\n` as RendererOutput;\n }\n\n tablecell(token: Tokens.TableCell): RendererOutput {\n const content = this.parser.parseInline(token.tokens);\n const type = token.header ? 'th' : 'td';\n const tag = token.align\n ? `<${type} align=\"${token.align}\">`\n : `<${type}>`;\n return tag + content + `\\n` as RendererOutput;\n }\n\n /**\n * span level renderer\n */\n strong({ tokens }: Tokens.Strong): RendererOutput {\n return `${this.parser.parseInline(tokens)}` as RendererOutput;\n }\n\n em({ tokens }: Tokens.Em): RendererOutput {\n return `${this.parser.parseInline(tokens)}` as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return `${escape(text, true)}` as RendererOutput;\n }\n\n br(token: Tokens.Br): RendererOutput {\n return '
    ' as RendererOutput;\n }\n\n del({ tokens }: Tokens.Del): RendererOutput {\n return `${this.parser.parseInline(tokens)}` as RendererOutput;\n }\n\n link({ href, title, tokens }: Tokens.Link): RendererOutput {\n const text = this.parser.parseInline(tokens) as string;\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text as RendererOutput;\n }\n href = cleanHref;\n let out = '
    ';\n return out as RendererOutput;\n }\n\n image({ href, title, text, tokens }: Tokens.Image): RendererOutput {\n if (tokens) {\n text = this.parser.parseInline(tokens, this.parser.textRenderer) as string;\n }\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return escape(text) as RendererOutput;\n }\n href = cleanHref;\n\n let out = `\"${text}\"`;\n {\n // no need for block level renderers\n strong({ text }: Tokens.Strong): RendererOutput {\n return text as RendererOutput;\n }\n\n em({ text }: Tokens.Em): RendererOutput {\n return text as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return text as RendererOutput;\n }\n\n del({ text }: Tokens.Del): RendererOutput {\n return text as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n text({ text }: Tokens.Text | Tokens.Escape | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n link({ text }: Tokens.Link): RendererOutput {\n return '' + text as RendererOutput;\n }\n\n image({ text }: Tokens.Image): RendererOutput {\n return '' + text as RendererOutput;\n }\n\n br(): RendererOutput {\n return '' as RendererOutput;\n }\n}\n", "import { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _defaults } from './defaults.ts';\nimport type { MarkedToken, Token, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Parsing & Compiling\n */\nexport class _Parser {\n options: MarkedOptions;\n renderer: _Renderer;\n textRenderer: _TextRenderer;\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n this.options.renderer = this.options.renderer || new _Renderer();\n this.renderer = this.options.renderer;\n this.renderer.options = this.options;\n this.renderer.parser = this;\n this.textRenderer = new _TextRenderer();\n }\n\n /**\n * Static Parse Method\n */\n static parse(tokens: Token[], options?: MarkedOptions) {\n const parser = new _Parser(options);\n return parser.parse(tokens);\n }\n\n /**\n * Static Parse Inline Method\n */\n static parseInline(tokens: Token[], options?: MarkedOptions) {\n const parser = new _Parser(options);\n return parser.parseInline(tokens);\n }\n\n /**\n * Parse Loop\n */\n parse(tokens: Token[], top = true): ParserOutput {\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const genericToken = anyToken as Tokens.Generic;\n const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);\n if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'def', 'paragraph', 'text'].includes(genericToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'space': {\n out += this.renderer.space(token);\n continue;\n }\n case 'hr': {\n out += this.renderer.hr(token);\n continue;\n }\n case 'heading': {\n out += this.renderer.heading(token);\n continue;\n }\n case 'code': {\n out += this.renderer.code(token);\n continue;\n }\n case 'table': {\n out += this.renderer.table(token);\n continue;\n }\n case 'blockquote': {\n out += this.renderer.blockquote(token);\n continue;\n }\n case 'list': {\n out += this.renderer.list(token);\n continue;\n }\n case 'html': {\n out += this.renderer.html(token);\n continue;\n }\n case 'def': {\n out += this.renderer.def(token);\n continue;\n }\n case 'paragraph': {\n out += this.renderer.paragraph(token);\n continue;\n }\n case 'text': {\n let textToken = token;\n let body = this.renderer.text(textToken) as string;\n while (i + 1 < tokens.length && tokens[i + 1].type === 'text') {\n textToken = tokens[++i] as Tokens.Text;\n body += ('\\n' + this.renderer.text(textToken));\n }\n if (top) {\n out += this.renderer.paragraph({\n type: 'paragraph',\n raw: body,\n text: body,\n tokens: [{ type: 'text', raw: body, text: body, escaped: true }],\n });\n } else {\n out += body;\n }\n continue;\n }\n\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n\n return out as ParserOutput;\n }\n\n /**\n * Parse Inline Tokens\n */\n parseInline(tokens: Token[], renderer: _Renderer | _TextRenderer = this.renderer): ParserOutput {\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);\n if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(anyToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'escape': {\n out += renderer.text(token);\n break;\n }\n case 'html': {\n out += renderer.html(token);\n break;\n }\n case 'link': {\n out += renderer.link(token);\n break;\n }\n case 'image': {\n out += renderer.image(token);\n break;\n }\n case 'strong': {\n out += renderer.strong(token);\n break;\n }\n case 'em': {\n out += renderer.em(token);\n break;\n }\n case 'codespan': {\n out += renderer.codespan(token);\n break;\n }\n case 'br': {\n out += renderer.br(token);\n break;\n }\n case 'del': {\n out += renderer.del(token);\n break;\n }\n case 'text': {\n out += renderer.text(token);\n break;\n }\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n return out as ParserOutput;\n }\n}\n", "import { _defaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\n\nexport class _Hooks {\n options: MarkedOptions;\n block?: boolean;\n\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n }\n\n static passThroughHooks = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n 'emStrongMask',\n ]);\n\n static passThroughHooksRespectAsync = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n ]);\n\n /**\n * Process markdown before marked\n */\n preprocess(markdown: string) {\n return markdown;\n }\n\n /**\n * Process HTML after marked is finished\n */\n postprocess(html: ParserOutput) {\n return html;\n }\n\n /**\n * Process all tokens before walk tokens\n */\n processAllTokens(tokens: Token[] | TokensList) {\n return tokens;\n }\n\n /**\n * Mask contents that should not be interpreted as em/strong delimiters\n */\n emStrongMask(src: string) {\n return src;\n }\n\n /**\n * Provide function to tokenize markdown\n */\n provideLexer() {\n return this.block ? _Lexer.lex : _Lexer.lexInline;\n }\n\n /**\n * Provide function to parse tokens\n */\n provideParser() {\n return this.block ? _Parser.parse : _Parser.parseInline;\n }\n}\n", "import { _getDefaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { escape } from './helpers.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, Tokens, TokensList } from './Tokens.ts';\n\nexport type MaybePromise = void | Promise;\n\ntype UnknownFunction = (...args: unknown[]) => unknown;\ntype GenericRendererFunction = (...args: unknown[]) => string | false;\n\nexport class Marked {\n defaults = _getDefaults();\n options = this.setOptions;\n\n parse = this.parseMarkdown(true);\n parseInline = this.parseMarkdown(false);\n\n Parser = _Parser;\n Renderer = _Renderer;\n TextRenderer = _TextRenderer;\n Lexer = _Lexer;\n Tokenizer = _Tokenizer;\n Hooks = _Hooks;\n\n constructor(...args: MarkedExtension[]) {\n this.use(...args);\n }\n\n /**\n * Run callback for every token\n */\n walkTokens(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n let values: MaybePromise[] = [];\n for (const token of tokens) {\n values = values.concat(callback.call(this, token));\n switch (token.type) {\n case 'table': {\n const tableToken = token as Tokens.Table;\n for (const cell of tableToken.header) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n for (const row of tableToken.rows) {\n for (const cell of row) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n }\n break;\n }\n case 'list': {\n const listToken = token as Tokens.List;\n values = values.concat(this.walkTokens(listToken.items, callback));\n break;\n }\n default: {\n const genericToken = token as Tokens.Generic;\n if (this.defaults.extensions?.childTokens?.[genericToken.type]) {\n this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {\n const tokens = genericToken[childTokens].flat(Infinity) as Token[] | TokensList;\n values = values.concat(this.walkTokens(tokens, callback));\n });\n } else if (genericToken.tokens) {\n values = values.concat(this.walkTokens(genericToken.tokens, callback));\n }\n }\n }\n }\n return values;\n }\n\n use(...args: MarkedExtension[]) {\n const extensions: MarkedOptions['extensions'] = this.defaults.extensions || { renderers: {}, childTokens: {} };\n\n args.forEach((pack) => {\n // copy options to new object\n const opts = { ...pack } as MarkedOptions;\n\n // set async to true if it was set to true before\n opts.async = this.defaults.async || opts.async || false;\n\n // ==-- Parse \"addon\" extensions --== //\n if (pack.extensions) {\n pack.extensions.forEach((ext) => {\n if (!ext.name) {\n throw new Error('extension name required');\n }\n if ('renderer' in ext) { // Renderer extensions\n const prevRenderer = extensions.renderers[ext.name];\n if (prevRenderer) {\n // Replace extension with func to run new extension but fall back if false\n extensions.renderers[ext.name] = function(...args) {\n let ret = ext.renderer.apply(this, args);\n if (ret === false) {\n ret = prevRenderer.apply(this, args);\n }\n return ret;\n };\n } else {\n extensions.renderers[ext.name] = ext.renderer;\n }\n }\n if ('tokenizer' in ext) { // Tokenizer Extensions\n if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {\n throw new Error(\"extension level must be 'block' or 'inline'\");\n }\n const extLevel = extensions[ext.level];\n if (extLevel) {\n extLevel.unshift(ext.tokenizer);\n } else {\n extensions[ext.level] = [ext.tokenizer];\n }\n if (ext.start) { // Function to check for start of token\n if (ext.level === 'block') {\n if (extensions.startBlock) {\n extensions.startBlock.push(ext.start);\n } else {\n extensions.startBlock = [ext.start];\n }\n } else if (ext.level === 'inline') {\n if (extensions.startInline) {\n extensions.startInline.push(ext.start);\n } else {\n extensions.startInline = [ext.start];\n }\n }\n }\n }\n if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens\n extensions.childTokens[ext.name] = ext.childTokens;\n }\n });\n opts.extensions = extensions;\n }\n\n // ==-- Parse \"overwrite\" extensions --== //\n if (pack.renderer) {\n const renderer = this.defaults.renderer || new _Renderer(this.defaults);\n for (const prop in pack.renderer) {\n if (!(prop in renderer)) {\n throw new Error(`renderer '${prop}' does not exist`);\n }\n if (['options', 'parser'].includes(prop)) {\n // ignore options property\n continue;\n }\n const rendererProp = prop as Exclude, 'options' | 'parser'>;\n const rendererFunc = pack.renderer[rendererProp] as GenericRendererFunction;\n const prevRenderer = renderer[rendererProp] as GenericRendererFunction;\n // Replace renderer with func to run extension, but fall back if false\n renderer[rendererProp] = (...args: unknown[]) => {\n let ret = rendererFunc.apply(renderer, args);\n if (ret === false) {\n ret = prevRenderer.apply(renderer, args);\n }\n return (ret || '') as RendererOutput;\n };\n }\n opts.renderer = renderer;\n }\n if (pack.tokenizer) {\n const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);\n for (const prop in pack.tokenizer) {\n if (!(prop in tokenizer)) {\n throw new Error(`tokenizer '${prop}' does not exist`);\n }\n if (['options', 'rules', 'lexer'].includes(prop)) {\n // ignore options, rules, and lexer properties\n continue;\n }\n const tokenizerProp = prop as Exclude, 'options' | 'rules' | 'lexer'>;\n const tokenizerFunc = pack.tokenizer[tokenizerProp] as UnknownFunction;\n const prevTokenizer = tokenizer[tokenizerProp] as UnknownFunction;\n // Replace tokenizer with func to run extension, but fall back if false\n // @ts-expect-error cannot type tokenizer function dynamically\n tokenizer[tokenizerProp] = (...args: unknown[]) => {\n let ret = tokenizerFunc.apply(tokenizer, args);\n if (ret === false) {\n ret = prevTokenizer.apply(tokenizer, args);\n }\n return ret;\n };\n }\n opts.tokenizer = tokenizer;\n }\n\n // ==-- Parse Hooks extensions --== //\n if (pack.hooks) {\n const hooks = this.defaults.hooks || new _Hooks();\n for (const prop in pack.hooks) {\n if (!(prop in hooks)) {\n throw new Error(`hook '${prop}' does not exist`);\n }\n if (['options', 'block'].includes(prop)) {\n // ignore options and block properties\n continue;\n }\n const hooksProp = prop as Exclude, 'options' | 'block'>;\n const hooksFunc = pack.hooks[hooksProp] as UnknownFunction;\n const prevHook = hooks[hooksProp] as UnknownFunction;\n if (_Hooks.passThroughHooks.has(prop)) {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (arg: unknown) => {\n if (this.defaults.async && _Hooks.passThroughHooksRespectAsync.has(prop)) {\n return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => {\n return prevHook.call(hooks, ret);\n });\n }\n\n const ret = hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n };\n } else {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (...args: unknown[]) => {\n let ret = hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = prevHook.apply(hooks, args);\n }\n return ret;\n };\n }\n }\n opts.hooks = hooks;\n }\n\n // ==-- Parse WalkTokens extensions --== //\n if (pack.walkTokens) {\n const walkTokens = this.defaults.walkTokens;\n const packWalktokens = pack.walkTokens;\n opts.walkTokens = function(token) {\n let values: MaybePromise[] = [];\n values.push(packWalktokens.call(this, token));\n if (walkTokens) {\n values = values.concat(walkTokens.call(this, token));\n }\n return values;\n };\n }\n\n this.defaults = { ...this.defaults, ...opts };\n });\n\n return this;\n }\n\n setOptions(opt: MarkedOptions) {\n this.defaults = { ...this.defaults, ...opt };\n return this;\n }\n\n lexer(src: string, options?: MarkedOptions) {\n return _Lexer.lex(src, options ?? this.defaults);\n }\n\n parser(tokens: Token[], options?: MarkedOptions) {\n return _Parser.parse(tokens, options ?? this.defaults);\n }\n\n private parseMarkdown(blockType: boolean) {\n type overloadedParse = {\n (src: string, options: MarkedOptions & { async: true }): Promise;\n (src: string, options: MarkedOptions & { async: false }): ParserOutput;\n (src: string, options?: MarkedOptions | null): ParserOutput | Promise;\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const parse: overloadedParse = (src: string, options?: MarkedOptions | null): any => {\n const origOpt = { ...options };\n const opt = { ...this.defaults, ...origOpt };\n\n const throwError = this.onError(!!opt.silent, !!opt.async);\n\n // throw error if an extension set async to true but parse was called with async: false\n if (this.defaults.async === true && origOpt.async === false) {\n return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.'));\n }\n\n // throw error in case of non string input\n if (typeof src === 'undefined' || src === null) {\n return throwError(new Error('marked(): input parameter is undefined or null'));\n }\n if (typeof src !== 'string') {\n return throwError(new Error('marked(): input parameter is of type '\n + Object.prototype.toString.call(src) + ', string expected'));\n }\n\n if (opt.hooks) {\n opt.hooks.options = opt;\n opt.hooks.block = blockType;\n }\n\n const lexer = opt.hooks ? opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline);\n const parser = opt.hooks ? opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline);\n\n if (opt.async) {\n return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src)\n .then(src => lexer(src, opt))\n .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens)\n .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens)\n .then(tokens => parser(tokens, opt))\n .then(html => opt.hooks ? opt.hooks.postprocess(html) : html)\n .catch(throwError);\n }\n\n try {\n if (opt.hooks) {\n src = opt.hooks.preprocess(src) as string;\n }\n let tokens = lexer(src, opt);\n if (opt.hooks) {\n tokens = opt.hooks.processAllTokens(tokens);\n }\n if (opt.walkTokens) {\n this.walkTokens(tokens, opt.walkTokens);\n }\n let html = parser(tokens, opt);\n if (opt.hooks) {\n html = opt.hooks.postprocess(html);\n }\n return html;\n } catch(e) {\n return throwError(e as Error);\n }\n };\n\n return parse;\n }\n\n private onError(silent: boolean, async: boolean) {\n return (e: Error): string | Promise => {\n e.message += '\\nPlease report this to https://github.com/markedjs/marked.';\n\n if (silent) {\n const msg = '

    An error occurred:

    '\n          + escape(e.message + '', true)\n          + '
    ';\n if (async) {\n return Promise.resolve(msg);\n }\n return msg;\n }\n\n if (async) {\n return Promise.reject(e);\n }\n throw e;\n };\n }\n}\n", "import { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { Marked } from './Instance.ts';\nimport {\n _getDefaults,\n changeDefaults,\n _defaults,\n} from './defaults.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\nimport type { MaybePromise } from './Instance.ts';\n\nconst markedInstance = new Marked();\n\n/**\n * Compiles markdown to HTML asynchronously.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options, having async: true\n * @return Promise of string of compiled HTML\n */\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise;\n\n/**\n * Compiles markdown to HTML.\n *\n * @param src String of markdown source to be compiled\n * @param options Optional hash of options\n * @return String of compiled HTML. Will be a Promise of string if async is set to true by any extensions.\n */\nexport function marked(src: string, options: MarkedOptions & { async: false }): string;\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise;\nexport function marked(src: string, options?: MarkedOptions | null): string | Promise;\nexport function marked(src: string, opt?: MarkedOptions | null): string | Promise {\n return markedInstance.parse(src, opt);\n}\n\n/**\n * Sets the default options.\n *\n * @param options Hash of options\n */\nmarked.options =\nmarked.setOptions = function(options: MarkedOptions) {\n markedInstance.setOptions(options);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\n\n/**\n * Gets the original marked default options.\n */\nmarked.getDefaults = _getDefaults;\n\nmarked.defaults = _defaults;\n\n/**\n * Use Extension\n */\n\nmarked.use = function(...args: MarkedExtension[]) {\n markedInstance.use(...args);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\n\n/**\n * Run callback for every token\n */\n\nmarked.walkTokens = function(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n return markedInstance.walkTokens(tokens, callback);\n};\n\n/**\n * Compiles markdown to HTML without enclosing `p` tag.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options\n * @return String of compiled HTML\n */\nmarked.parseInline = markedInstance.parseInline;\n\n/**\n * Expose\n */\nmarked.Parser = _Parser;\nmarked.parser = _Parser.parse;\nmarked.Renderer = _Renderer;\nmarked.TextRenderer = _TextRenderer;\nmarked.Lexer = _Lexer;\nmarked.lexer = _Lexer.lex;\nmarked.Tokenizer = _Tokenizer;\nmarked.Hooks = _Hooks;\nmarked.parse = marked;\n\nexport const options = marked.options;\nexport const setOptions = marked.setOptions;\nexport const use = marked.use;\nexport const walkTokens = marked.walkTokens;\nexport const parseInline = marked.parseInline;\nexport const parse = marked;\nexport const parser = _Parser.parse;\nexport const lexer = _Lexer.lex;\nexport { _defaults as defaults, _getDefaults as getDefaults } from './defaults.ts';\nexport { _Lexer as Lexer } from './Lexer.ts';\nexport { _Parser as Parser } from './Parser.ts';\nexport { _Tokenizer as Tokenizer } from './Tokenizer.ts';\nexport { _Renderer as Renderer } from './Renderer.ts';\nexport { _TextRenderer as TextRenderer } from './TextRenderer.ts';\nexport { _Hooks as Hooks } from './Hooks.ts';\nexport { Marked } from './Instance.ts';\nexport type * from './MarkedOptions.ts';\nexport type * from './Tokens.ts';\n", "import {\n decodeEntities\n} from \"./chunk-S3R3BYOJ.mjs\";\nimport {\n common_default,\n getConfig,\n hasKatex,\n renderKatexSanitized,\n sanitizeText\n} from \"./chunk-ABZYJK2D.mjs\";\nimport {\n __name,\n log\n} from \"./chunk-AGHRB4JF.mjs\";\n\n// src/rendering-util/icons.ts\nimport { getIconData, iconToHTML, iconToSVG, replaceIDs, stringToIcon } from \"@iconify/utils\";\nvar unknownIcon = {\n body: '?',\n height: 80,\n width: 80\n};\nvar iconsStore = /* @__PURE__ */ new Map();\nvar loaderStore = /* @__PURE__ */ new Map();\nvar registerIconPacks = /* @__PURE__ */ __name((iconLoaders) => {\n for (const iconLoader of iconLoaders) {\n if (!iconLoader.name) {\n throw new Error(\n 'Invalid icon loader. Must have a \"name\" property with non-empty string value.'\n );\n }\n log.debug(\"Registering icon pack:\", iconLoader.name);\n if (\"loader\" in iconLoader) {\n loaderStore.set(iconLoader.name, iconLoader.loader);\n } else if (\"icons\" in iconLoader) {\n iconsStore.set(iconLoader.name, iconLoader.icons);\n } else {\n log.error(\"Invalid icon loader:\", iconLoader);\n throw new Error('Invalid icon loader. Must have either \"icons\" or \"loader\" property.');\n }\n }\n}, \"registerIconPacks\");\nvar getRegisteredIconData = /* @__PURE__ */ __name(async (iconName, fallbackPrefix) => {\n const data = stringToIcon(iconName, true, fallbackPrefix !== void 0);\n if (!data) {\n throw new Error(`Invalid icon name: ${iconName}`);\n }\n const prefix = data.prefix || fallbackPrefix;\n if (!prefix) {\n throw new Error(`Icon name must contain a prefix: ${iconName}`);\n }\n let icons = iconsStore.get(prefix);\n if (!icons) {\n const loader = loaderStore.get(prefix);\n if (!loader) {\n throw new Error(`Icon set not found: ${data.prefix}`);\n }\n try {\n const loaded = await loader();\n icons = { ...loaded, prefix };\n iconsStore.set(prefix, icons);\n } catch (e) {\n log.error(e);\n throw new Error(`Failed to load icon set: ${data.prefix}`);\n }\n }\n const iconData = getIconData(icons, data.name);\n if (!iconData) {\n throw new Error(`Icon not found: ${iconName}`);\n }\n return iconData;\n}, \"getRegisteredIconData\");\nvar isIconAvailable = /* @__PURE__ */ __name(async (iconName) => {\n try {\n await getRegisteredIconData(iconName);\n return true;\n } catch {\n return false;\n }\n}, \"isIconAvailable\");\nvar getIconSVG = /* @__PURE__ */ __name(async (iconName, customisations, extraAttributes) => {\n let iconData;\n try {\n iconData = await getRegisteredIconData(iconName, customisations?.fallbackPrefix);\n } catch (e) {\n log.error(e);\n iconData = unknownIcon;\n }\n const renderData = iconToSVG(iconData, customisations);\n const svg = iconToHTML(replaceIDs(renderData.body), {\n ...renderData.attributes,\n ...extraAttributes\n });\n return sanitizeText(svg, getConfig());\n}, \"getIconSVG\");\n\n// src/rendering-util/createText.ts\nimport { select } from \"d3\";\n\n// src/rendering-util/handle-markdown-text.ts\nimport { marked } from \"marked\";\nimport { dedent } from \"ts-dedent\";\nfunction preprocessMarkdown(markdown, { markdownAutoWrap }) {\n const withoutBR = markdown.replace(//g, \"\\n\");\n const withoutMultipleNewlines = withoutBR.replace(/\\n{2,}/g, \"\\n\");\n const withoutExtraSpaces = dedent(withoutMultipleNewlines);\n if (markdownAutoWrap === false) {\n return withoutExtraSpaces.replace(/ /g, \" \");\n }\n return withoutExtraSpaces;\n}\n__name(preprocessMarkdown, \"preprocessMarkdown\");\nfunction markdownToLines(markdown, config = {}) {\n const preprocessedMarkdown = preprocessMarkdown(markdown, config);\n const nodes = marked.lexer(preprocessedMarkdown);\n const lines = [[]];\n let currentLine = 0;\n function processNode(node, parentType = \"normal\") {\n if (node.type === \"text\") {\n const textLines = node.text.split(\"\\n\");\n textLines.forEach((textLine, index) => {\n if (index !== 0) {\n currentLine++;\n lines.push([]);\n }\n textLine.split(\" \").forEach((word) => {\n word = word.replace(/'/g, `'`);\n if (word) {\n lines[currentLine].push({ content: word, type: parentType });\n }\n });\n });\n } else if (node.type === \"strong\" || node.type === \"em\") {\n node.tokens.forEach((contentNode) => {\n processNode(contentNode, node.type);\n });\n } else if (node.type === \"html\") {\n lines[currentLine].push({ content: node.text, type: \"normal\" });\n }\n }\n __name(processNode, \"processNode\");\n nodes.forEach((treeNode) => {\n if (treeNode.type === \"paragraph\") {\n treeNode.tokens?.forEach((contentNode) => {\n processNode(contentNode);\n });\n } else if (treeNode.type === \"html\") {\n lines[currentLine].push({ content: treeNode.text, type: \"normal\" });\n } else {\n lines[currentLine].push({ content: treeNode.raw, type: \"normal\" });\n }\n });\n return lines;\n}\n__name(markdownToLines, \"markdownToLines\");\nfunction markdownToHTML(markdown, { markdownAutoWrap } = {}) {\n const nodes = marked.lexer(markdown);\n function output(node) {\n if (node.type === \"text\") {\n if (markdownAutoWrap === false) {\n return node.text.replace(/\\n */g, \"
    \").replace(/ /g, \" \");\n }\n return node.text.replace(/\\n */g, \"
    \");\n } else if (node.type === \"strong\") {\n return `${node.tokens?.map(output).join(\"\")}`;\n } else if (node.type === \"em\") {\n return `${node.tokens?.map(output).join(\"\")}`;\n } else if (node.type === \"paragraph\") {\n return `

    ${node.tokens?.map(output).join(\"\")}

    `;\n } else if (node.type === \"space\") {\n return \"\";\n } else if (node.type === \"html\") {\n return `${node.text}`;\n } else if (node.type === \"escape\") {\n return node.text;\n }\n log.warn(`Unsupported markdown: ${node.type}`);\n return node.raw;\n }\n __name(output, \"output\");\n return nodes.map(output).join(\"\");\n}\n__name(markdownToHTML, \"markdownToHTML\");\n\n// src/rendering-util/splitText.ts\nfunction splitTextToChars(text) {\n if (Intl.Segmenter) {\n return [...new Intl.Segmenter().segment(text)].map((s) => s.segment);\n }\n return [...text];\n}\n__name(splitTextToChars, \"splitTextToChars\");\nfunction splitWordToFitWidth(checkFit, word) {\n const characters = splitTextToChars(word.content);\n return splitWordToFitWidthRecursion(checkFit, [], characters, word.type);\n}\n__name(splitWordToFitWidth, \"splitWordToFitWidth\");\nfunction splitWordToFitWidthRecursion(checkFit, usedChars, remainingChars, type) {\n if (remainingChars.length === 0) {\n return [\n { content: usedChars.join(\"\"), type },\n { content: \"\", type }\n ];\n }\n const [nextChar, ...rest] = remainingChars;\n const newWord = [...usedChars, nextChar];\n if (checkFit([{ content: newWord.join(\"\"), type }])) {\n return splitWordToFitWidthRecursion(checkFit, newWord, rest, type);\n }\n if (usedChars.length === 0 && nextChar) {\n usedChars.push(nextChar);\n remainingChars.shift();\n }\n return [\n { content: usedChars.join(\"\"), type },\n { content: remainingChars.join(\"\"), type }\n ];\n}\n__name(splitWordToFitWidthRecursion, \"splitWordToFitWidthRecursion\");\nfunction splitLineToFitWidth(line, checkFit) {\n if (line.some(({ content }) => content.includes(\"\\n\"))) {\n throw new Error(\"splitLineToFitWidth does not support newlines in the line\");\n }\n return splitLineToFitWidthRecursion(line, checkFit);\n}\n__name(splitLineToFitWidth, \"splitLineToFitWidth\");\nfunction splitLineToFitWidthRecursion(words, checkFit, lines = [], newLine = []) {\n if (words.length === 0) {\n if (newLine.length > 0) {\n lines.push(newLine);\n }\n return lines.length > 0 ? lines : [];\n }\n let joiner = \"\";\n if (words[0].content === \" \") {\n joiner = \" \";\n words.shift();\n }\n const nextWord = words.shift() ?? { content: \" \", type: \"normal\" };\n const lineWithNextWord = [...newLine];\n if (joiner !== \"\") {\n lineWithNextWord.push({ content: joiner, type: \"normal\" });\n }\n lineWithNextWord.push(nextWord);\n if (checkFit(lineWithNextWord)) {\n return splitLineToFitWidthRecursion(words, checkFit, lines, lineWithNextWord);\n }\n if (newLine.length > 0) {\n lines.push(newLine);\n words.unshift(nextWord);\n } else if (nextWord.content) {\n const [line, rest] = splitWordToFitWidth(checkFit, nextWord);\n lines.push([line]);\n if (rest.content) {\n words.unshift(rest);\n }\n }\n return splitLineToFitWidthRecursion(words, checkFit, lines);\n}\n__name(splitLineToFitWidthRecursion, \"splitLineToFitWidthRecursion\");\n\n// src/rendering-util/createText.ts\nfunction applyStyle(dom, styleFn) {\n if (styleFn) {\n dom.attr(\"style\", styleFn);\n }\n}\n__name(applyStyle, \"applyStyle\");\nasync function addHtmlSpan(element, node, width, classes, addBackground = false, config = getConfig()) {\n const fo = element.append(\"foreignObject\");\n fo.attr(\"width\", `${10 * width}px`);\n fo.attr(\"height\", `${10 * width}px`);\n const div = fo.append(\"xhtml:div\");\n const sanitizedLabel = hasKatex(node.label) ? await renderKatexSanitized(node.label.replace(common_default.lineBreakRegex, \"\\n\"), config) : sanitizeText(node.label, config);\n const labelClass = node.isNode ? \"nodeLabel\" : \"edgeLabel\";\n const span = div.append(\"span\");\n span.html(sanitizedLabel);\n applyStyle(span, node.labelStyle);\n span.attr(\"class\", `${labelClass} ${classes}`);\n applyStyle(div, node.labelStyle);\n div.style(\"display\", \"table-cell\");\n div.style(\"white-space\", \"nowrap\");\n div.style(\"line-height\", \"1.5\");\n div.style(\"max-width\", width + \"px\");\n div.style(\"text-align\", \"center\");\n div.attr(\"xmlns\", \"http://www.w3.org/1999/xhtml\");\n if (addBackground) {\n div.attr(\"class\", \"labelBkg\");\n }\n let bbox = div.node().getBoundingClientRect();\n if (bbox.width === width) {\n div.style(\"display\", \"table\");\n div.style(\"white-space\", \"break-spaces\");\n div.style(\"width\", width + \"px\");\n bbox = div.node().getBoundingClientRect();\n }\n return fo.node();\n}\n__name(addHtmlSpan, \"addHtmlSpan\");\nfunction createTspan(textElement, lineIndex, lineHeight) {\n return textElement.append(\"tspan\").attr(\"class\", \"text-outer-tspan\").attr(\"x\", 0).attr(\"y\", lineIndex * lineHeight - 0.1 + \"em\").attr(\"dy\", lineHeight + \"em\");\n}\n__name(createTspan, \"createTspan\");\nfunction computeWidthOfText(parentNode, lineHeight, line) {\n const testElement = parentNode.append(\"text\");\n const testSpan = createTspan(testElement, 1, lineHeight);\n updateTextContentAndStyles(testSpan, line);\n const textLength = testSpan.node().getComputedTextLength();\n testElement.remove();\n return textLength;\n}\n__name(computeWidthOfText, \"computeWidthOfText\");\nfunction computeDimensionOfText(parentNode, lineHeight, text) {\n const testElement = parentNode.append(\"text\");\n const testSpan = createTspan(testElement, 1, lineHeight);\n updateTextContentAndStyles(testSpan, [{ content: text, type: \"normal\" }]);\n const textDimension = testSpan.node()?.getBoundingClientRect();\n if (textDimension) {\n testElement.remove();\n }\n return textDimension;\n}\n__name(computeDimensionOfText, \"computeDimensionOfText\");\nfunction createFormattedText(width, g, structuredText, addBackground = false) {\n const lineHeight = 1.1;\n const labelGroup = g.append(\"g\");\n const bkg = labelGroup.insert(\"rect\").attr(\"class\", \"background\").attr(\"style\", \"stroke: none\");\n const textElement = labelGroup.append(\"text\").attr(\"y\", \"-10.1\");\n let lineIndex = 0;\n for (const line of structuredText) {\n const checkWidth = /* @__PURE__ */ __name((line2) => computeWidthOfText(labelGroup, lineHeight, line2) <= width, \"checkWidth\");\n const linesUnderWidth = checkWidth(line) ? [line] : splitLineToFitWidth(line, checkWidth);\n for (const preparedLine of linesUnderWidth) {\n const tspan = createTspan(textElement, lineIndex, lineHeight);\n updateTextContentAndStyles(tspan, preparedLine);\n lineIndex++;\n }\n }\n if (addBackground) {\n const bbox = textElement.node().getBBox();\n const padding = 2;\n bkg.attr(\"x\", bbox.x - padding).attr(\"y\", bbox.y - padding).attr(\"width\", bbox.width + 2 * padding).attr(\"height\", bbox.height + 2 * padding);\n return labelGroup.node();\n } else {\n return textElement.node();\n }\n}\n__name(createFormattedText, \"createFormattedText\");\nfunction updateTextContentAndStyles(tspan, wrappedLine) {\n tspan.text(\"\");\n wrappedLine.forEach((word, index) => {\n const innerTspan = tspan.append(\"tspan\").attr(\"font-style\", word.type === \"em\" ? \"italic\" : \"normal\").attr(\"class\", \"text-inner-tspan\").attr(\"font-weight\", word.type === \"strong\" ? \"bold\" : \"normal\");\n if (index === 0) {\n innerTspan.text(word.content);\n } else {\n innerTspan.text(\" \" + word.content);\n }\n });\n}\n__name(updateTextContentAndStyles, \"updateTextContentAndStyles\");\nasync function replaceIconSubstring(text, config = {}) {\n const pendingReplacements = [];\n text.replace(/(fa[bklrs]?):fa-([\\w-]+)/g, (fullMatch, prefix, iconName) => {\n pendingReplacements.push(\n (async () => {\n const registeredIconName = `${prefix}:${iconName}`;\n if (await isIconAvailable(registeredIconName)) {\n return await getIconSVG(registeredIconName, void 0, { class: \"label-icon\" });\n } else {\n return ``;\n }\n })()\n );\n return fullMatch;\n });\n const replacements = await Promise.all(pendingReplacements);\n return text.replace(/(fa[bklrs]?):fa-([\\w-]+)/g, () => replacements.shift() ?? \"\");\n}\n__name(replaceIconSubstring, \"replaceIconSubstring\");\nvar createText = /* @__PURE__ */ __name(async (el, text = \"\", {\n style = \"\",\n isTitle = false,\n classes = \"\",\n useHtmlLabels = true,\n isNode = true,\n width = 200,\n addSvgBackground = false\n} = {}, config) => {\n log.debug(\n \"XYZ createText\",\n text,\n style,\n isTitle,\n classes,\n useHtmlLabels,\n isNode,\n \"addSvgBackground: \",\n addSvgBackground\n );\n if (useHtmlLabels) {\n const htmlText = markdownToHTML(text, config);\n const decodedReplacedText = await replaceIconSubstring(decodeEntities(htmlText), config);\n const inputForKatex = text.replace(/\\\\\\\\/g, \"\\\\\");\n const node = {\n isNode,\n label: hasKatex(text) ? inputForKatex : decodedReplacedText,\n labelStyle: style.replace(\"fill:\", \"color:\")\n };\n const vertexNode = await addHtmlSpan(el, node, width, classes, addSvgBackground, config);\n return vertexNode;\n } else {\n const sanitizeBR = text.replace(//g, \"
    \");\n const structuredText = markdownToLines(sanitizeBR.replace(\"
    \", \"
    \"), config);\n const svgLabel = createFormattedText(\n width,\n el,\n structuredText,\n text ? addSvgBackground : false\n );\n if (isNode) {\n if (/stroke:/.exec(style)) {\n style = style.replace(\"stroke:\", \"lineColor:\");\n }\n const nodeLabelTextStyle = style.replace(/stroke:[^;]+;?/g, \"\").replace(/stroke-width:[^;]+;?/g, \"\").replace(/fill:[^;]+;?/g, \"\").replace(/color:/g, \"fill:\");\n select(svgLabel).attr(\"style\", nodeLabelTextStyle);\n } else {\n const edgeLabelRectStyle = style.replace(/stroke:[^;]+;?/g, \"\").replace(/stroke-width:[^;]+;?/g, \"\").replace(/fill:[^;]+;?/g, \"\").replace(/background:/g, \"fill:\");\n select(svgLabel).select(\"rect\").attr(\"style\", edgeLabelRectStyle.replace(/background:/g, \"fill:\"));\n const edgeLabelTextStyle = style.replace(/stroke:[^;]+;?/g, \"\").replace(/stroke-width:[^;]+;?/g, \"\").replace(/fill:[^;]+;?/g, \"\").replace(/color:/g, \"fill:\");\n select(svgLabel).select(\"text\").attr(\"style\", edgeLabelTextStyle);\n }\n return svgLabel;\n }\n}, \"createText\");\n\nexport {\n unknownIcon,\n registerIconPacks,\n getIconSVG,\n computeDimensionOfText,\n replaceIconSubstring,\n createText\n};\n"], + "mappings": "iLAAM,SAAUA,GACdC,EA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AAO,CACL,IAAME,EAAqBb,EAAM,QAAQ,kBAAmB,EAAE,EAAE,QAAQ,wBAAyB,EAAE,EAAE,QAAQ,gBAAiB,EAAE,EAAE,QAAQ,eAAgB,OAAO,EACjKY,EAAOF,CAAQ,EAAE,OAAO,MAAM,EAAE,KAAK,QAASG,EAAmB,QAAQ,eAAgB,OAAO,CAAC,EACjG,IAAMC,EAAqBd,EAAM,QAAQ,kBAAmB,EAAE,EAAE,QAAQ,wBAAyB,EAAE,EAAE,QAAQ,gBAAiB,EAAE,EAAE,QAAQ,UAAW,OAAO,EAC5JY,EAAOF,CAAQ,EAAE,OAAO,MAAM,EAAE,KAAK,QAASI,CAAkB,CAClE,CACA,OAAOJ,CACT,CACF,EAAG,YAAY", + "names": ["dedent", "templ", "values", "_i", "strings", "indentLengths", "arr", "str", "matches", "match", "_a", "_b", "pattern_1", "string", "value", "i", "endentations", "endentation", "indentedValue", "defaultIconDimensions", "defaultIconTransformations", "defaultIconProps", "defaultExtendedIconProps", "defaultIconSizeCustomisations", "defaultIconCustomisations", "defaultIconTransformations", "stringToIcon", "value", "validate", "allowSimpleName", "provider", "colonSeparated", "name$1", "prefix", "result", "validateIconName", "name", "dashSeparated", "icon", "mergeIconTransformations", "obj1", "obj2", "result", "rotate", "mergeIconData", "parent", "child", "result", "mergeIconTransformations", "key", "defaultExtendedIconProps", "defaultIconTransformations", "getIconsTree", "data", "names", "icons", "aliases", "resolved", "resolve", "name", "parent", "value", "internalGetIconData", "data", "name", "tree", "icons", "aliases", "currentProps", "parse", "name$1", "mergeIconData", "getIconData", "getIconsTree", "unitsSplit", "unitsTest", "calculateSize", "size", "ratio", "precision", "oldParts", "newParts", "code", "isNumber", "num", "splitSVGDefs", "content", "tag", "defs", "index", "start", "end", "endEnd", "mergeDefsAndContent", "wrapSVGContent", "body", "split", "isUnsetKeyword", "value", "iconToSVG", "icon", "customisations", "fullIcon", "defaultIconProps", "fullCustomisations", "defaultIconCustomisations", "box", "body", "props", "transformations", "hFlip", "vFlip", "rotation", "tempValue", "wrapSVGContent", "customisationsWidth", "customisationsHeight", "boxWidth", "boxHeight", "width", "height", "calculateSize", "attributes", "setAttr", "prop", "viewBox", "regex", "randomPrefix", "counter", "replaceIDs", "body", "prefix", "ids", "match", "suffix", "id", "newID", "escapedID", "iconToHTML", "body", "attributes", "renderAttribsHTML", "attr", "_getDefaults", "_defaults", "changeDefaults", "newDefaults", "noopTest", "edit", "regex", "opt", "source", "obj", "name", "val", "valSource", "other", "bull", "indent", "newline", "blockCode", "fences", "hr", "heading", "bullet", "lheadingCore", "lheading", "lheadingGfm", "_paragraph", "blockText", "_blockLabel", "def", "list", "_tag", "_comment", "html", "paragraph", "blockquote", "blockNormal", "gfmTable", "blockGfm", "blockPedantic", "escape", "inlineCode", "br", "inlineText", "_punctuation", "_punctuationOrSpace", "_notPunctuationOrSpace", "punctuation", "_punctuationGfmStrongEm", "_punctuationOrSpaceGfmStrongEm", "_notPunctuationOrSpaceGfmStrongEm", "blockSkip", "emStrongLDelimCore", "emStrongLDelim", "emStrongLDelimGfm", "emStrongRDelimAstCore", "emStrongRDelimAst", "emStrongRDelimAstGfm", "emStrongRDelimUnd", "anyPunctuation", "autolink", "_inlineComment", "tag", "_inlineLabel", "link", "reflink", "nolink", "reflinkSearch", "inlineNormal", "inlinePedantic", "inlineGfm", "inlineBreaks", "block", "inline", "escapeReplacements", "getEscapeReplacement", "ch", "encode", "cleanUrl", "href", "splitCells", "tableRow", "count", "row", "match", "offset", "str", "escaped", "curr", "cells", "i", "rtrim", "c", "invert", "l", "suffLen", "currChar", "findClosingBracket", "b", "level", "outputLink", "cap", "raw", "lexer", "rules", "title", "text", "token", "indentCodeCompensation", "matchIndentToCode", "indentToCode", "node", "matchIndentInNode", "indentInNode", "_Tokenizer", "options", "src", "trimmed", "lines", "tokens", "inBlockquote", "currentLines", "currentRaw", "currentText", "top", "lastToken", "oldToken", "newText", "newToken", "isordered", "itemRegex", "endsWithBlankLine", "endEarly", "itemContents", "line", "t", "nextLine", "blankLine", "nextBulletRegex", "hrRegex", "fencesBeginRegex", "headingBeginRegex", "htmlBeginRegex", "rawLine", "nextLineWithoutTabs", "istask", "ischecked", "lastItem", "spacers", "hasMultipleLineBreaks", "headers", "aligns", "rows", "item", "align", "cell", "trimmedUrl", "rtrimSlash", "lastParenIndex", "linkLen", "links", "linkString", "maskedSrc", "prevChar", "lLength", "rDelim", "rLength", "delimTotal", "midDelimTotal", "endReg", "lastCharLength", "hasNonSpaceChars", "hasSpaceCharsOnBothEnds", "prevCapZero", "_Lexer", "__Lexer", "next", "lastParagraphClipped", "extTokenizer", "cutSrc", "startIndex", "tempSrc", "tempStart", "getStartIndex", "errMsg", "keepPrevChar", "_Renderer", "lang", "langString", "code", "depth", "ordered", "start", "body", "j", "type", "startAttr", "itemBody", "checkbox", "checked", "header", "k", "content", "cleanHref", "out", "_TextRenderer", "_Parser", "__Parser", "anyToken", "genericToken", "ret", "textToken", "renderer", "_Hooks", "markdown", "Marked", "args", "callback", "values", "tableToken", "listToken", "childTokens", "extensions", "pack", "opts", "ext", "prevRenderer", "extLevel", "prop", "rendererProp", "rendererFunc", "tokenizer", "tokenizerProp", "tokenizerFunc", "prevTokenizer", "hooks", "hooksProp", "hooksFunc", "prevHook", "arg", "walkTokens", "packWalktokens", "blockType", "origOpt", "throwError", "parser", "e", "silent", "async", "msg", "markedInstance", "marked", "setOptions", "use", "parseInline", "parser", "_Parser", "lexer", "_Lexer", "unknownIcon", "iconsStore", "loaderStore", "registerIconPacks", "__name", "iconLoaders", "iconLoader", "log", "getRegisteredIconData", "iconName", "fallbackPrefix", "data", "stringToIcon", "prefix", "icons", "loader", "e", "iconData", "getIconData", "isIconAvailable", "getIconSVG", "customisations", "extraAttributes", "renderData", "iconToSVG", "svg", "iconToHTML", "replaceIDs", "sanitizeText", "getConfig", "preprocessMarkdown", "markdown", "markdownAutoWrap", "withoutMultipleNewlines", "withoutExtraSpaces", "dedent", "markdownToLines", "config", "preprocessedMarkdown", "nodes", "d", "lines", "currentLine", "processNode", "node", "parentType", "textLine", "index", "word", "contentNode", "treeNode", "markdownToHTML", "output", "splitTextToChars", "text", "s", "splitWordToFitWidth", "checkFit", "characters", "splitWordToFitWidthRecursion", "usedChars", "remainingChars", "type", "nextChar", "rest", "newWord", "splitLineToFitWidth", "line", "content", "splitLineToFitWidthRecursion", "words", "newLine", "joiner", "nextWord", "lineWithNextWord", "applyStyle", "dom", "styleFn", "addHtmlSpan", "element", "width", "classes", "addBackground", "fo", "div", "sanitizedLabel", "hasKatex", "renderKatexSanitized", "common_default", "labelClass", "span", "bbox", "createTspan", "textElement", "lineIndex", "lineHeight", "computeWidthOfText", "parentNode", "testElement", "testSpan", "updateTextContentAndStyles", "textLength", "computeDimensionOfText", "textDimension", "createFormattedText", "g", "structuredText", "labelGroup", "bkg", "checkWidth", "line2", "linesUnderWidth", "preparedLine", "tspan", "padding", "wrappedLine", "innerTspan", "replaceIconSubstring", "pendingReplacements", "fullMatch", "registeredIconName", "replacements", "createText", "el", "style", "isTitle", "useHtmlLabels", "isNode", "addSvgBackground", "htmlText", "decodedReplacedText", "decodeEntities", "inputForKatex", "sanitizeBR", "svgLabel", "nodeLabelTextStyle", "select_default", "edgeLabelRectStyle", "edgeLabelTextStyle"] +} diff --git a/docs/website/public/chunk-XXYYAETH.min.js b/docs/website/public/chunk-XXYYAETH.min.js new file mode 100644 index 000000000..ceaa94946 --- /dev/null +++ b/docs/website/public/chunk-XXYYAETH.min.js @@ -0,0 +1,340 @@ +function Bs(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,a=Array(e);t=r.length?{done:!0}:{done:!1,value:r[a++]}},e:function(l){throw l},f:n}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var i,s=!0,o=!1;return{s:function(){t=t.call(r)},n:function(){var l=t.next();return s=l.done,l},e:function(l){o=!0,i=l},f:function(){try{s||t.return==null||t.return()}finally{if(o)throw i}}}}function Jl(r,e,t){return(e=jl(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function ac(r){if(typeof Symbol<"u"&&r[Symbol.iterator]!=null||r["@@iterator"]!=null)return Array.from(r)}function nc(r,e){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var a,n,i,s,o=[],l=!0,u=!1;try{if(i=(t=t.call(r)).next,e===0){if(Object(t)!==t)return;l=!1}else for(;!(l=(a=i.call(t)).done)&&(o.push(a.value),o.length!==e);l=!0);}catch(v){u=!0,n=v}finally{try{if(!l&&t.return!=null&&(s=t.return(),Object(s)!==s))return}finally{if(u)throw n}}return o}}function ic(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function sc(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Je(r,e){return ec(r)||nc(r,e)||Xs(r,e)||ic()}function mn(r){return rc(r)||ac(r)||Xs(r)||sc()}function oc(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var a=t.call(r,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(r)}function jl(r){var e=oc(r,"string");return typeof e=="symbol"?e:e+""}function ar(r){"@babel/helpers - typeof";return ar=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ar(r)}function Xs(r,e){if(r){if(typeof r=="string")return Bs(r,e);var t={}.toString.call(r).slice(8,-1);return t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set"?Array.from(r):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?Bs(r,e):void 0}}var rr=typeof window>"u"?null:window,To=rr?rr.navigator:null;rr&&rr.document;var uc=ar(""),ev=ar({}),lc=ar(function(){}),vc=typeof HTMLElement>"u"?"undefined":ar(HTMLElement),La=function(e){return e&&e.instanceString&&Ue(e.instanceString)?e.instanceString():null},ge=function(e){return e!=null&&ar(e)==uc},Ue=function(e){return e!=null&&ar(e)===lc},_e=function(e){return!Dr(e)&&(Array.isArray?Array.isArray(e):e!=null&&e instanceof Array)},Le=function(e){return e!=null&&ar(e)===ev&&!_e(e)&&e.constructor===Object},fc=function(e){return e!=null&&ar(e)===ev},ae=function(e){return e!=null&&ar(e)===ar(1)&&!isNaN(e)},cc=function(e){return ae(e)&&Math.floor(e)===e},bn=function(e){if(vc!=="undefined")return e!=null&&e instanceof HTMLElement},Dr=function(e){return Ia(e)||rv(e)},Ia=function(e){return La(e)==="collection"&&e._private.single},rv=function(e){return La(e)==="collection"&&!e._private.single},Ys=function(e){return La(e)==="core"},tv=function(e){return La(e)==="stylesheet"},dc=function(e){return La(e)==="event"},ut=function(e){return e==null?!0:!!(e===""||e.match(/^\s+$/))},hc=function(e){return typeof HTMLElement>"u"?!1:e instanceof HTMLElement},gc=function(e){return Le(e)&&ae(e.x1)&&ae(e.x2)&&ae(e.y1)&&ae(e.y2)},pc=function(e){return fc(e)&&Ue(e.then)},yc=function(){return To&&To.userAgent.match(/msie|trident|edge/i)},Qt=function(e,t){t||(t=function(){if(arguments.length===1)return arguments[0];if(arguments.length===0)return"undefined";for(var i=[],s=0;st?1:0},Tc=function(e,t){return-1*nv(e,t)},be=Object.assign!=null?Object.assign.bind(Object):function(r){for(var e=arguments,t=1;t1&&(g-=1),g<1/6?d+(y-d)*6*g:g<1/2?y:g<2/3?d+(y-d)*(2/3-g)*6:d}var f=new RegExp("^"+wc+"$").exec(e);if(f){if(a=parseInt(f[1]),a<0?a=(360- -1*a%360)%360:a>360&&(a=a%360),a/=360,n=parseFloat(f[2]),n<0||n>100||(n=n/100,i=parseFloat(f[3]),i<0||i>100)||(i=i/100,s=f[4],s!==void 0&&(s=parseFloat(s),s<0||s>1)))return;if(n===0)o=l=u=Math.round(i*255);else{var c=i<.5?i*(1+n):i+n-i*n,h=2*i-c;o=Math.round(255*v(h,c,a+1/3)),l=Math.round(255*v(h,c,a)),u=Math.round(255*v(h,c,a-1/3))}t=[o,l,u,s]}return t},Dc=function(e){var t,a=new RegExp("^"+mc+"$").exec(e);if(a){t=[];for(var n=[],i=1;i<=3;i++){var s=a[i];if(s[s.length-1]==="%"&&(n[i]=!0),s=parseFloat(s),n[i]&&(s=s/100*255),s<0||s>255)return;t.push(Math.floor(s))}var o=n[1]||n[2]||n[3],l=n[1]&&n[2]&&n[3];if(o&&!l)return;var u=a[4];if(u!==void 0){if(u=parseFloat(u),u<0||u>1)return;t.push(u)}}return t},Bc=function(e){return Pc[e.toLowerCase()]},iv=function(e){return(_e(e)?e:null)||Bc(e)||Sc(e)||Dc(e)||kc(e)},Pc={transparent:[0,0,0,0],aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],grey:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},sv=function(e){for(var t=e.map,a=e.keys,n=a.length,i=0;i=l||R<0||m&&L>=c}function T(){var A=e();if(x(A))return k(A);d=setTimeout(T,C(A))}function k(A){return d=void 0,b&&v?w(A):(v=f=void 0,h)}function D(){d!==void 0&&clearTimeout(d),g=0,v=y=f=d=void 0}function B(){return d===void 0?h:k(e())}function P(){var A=e(),R=x(A);if(v=arguments,f=this,y=A,R){if(d===void 0)return E(y);if(m)return clearTimeout(d),d=setTimeout(T,l),w(y)}return d===void 0&&(d=setTimeout(T,l)),h}return P.cancel=D,P.flush=B,P}return fi=s,fi}var Vc=Fc(),Fa=Oa(Vc),ci=rr?rr.performance:null,lv=ci&&ci.now?function(){return ci.now()}:function(){return Date.now()},qc=(function(){if(rr){if(rr.requestAnimationFrame)return function(r){rr.requestAnimationFrame(r)};if(rr.mozRequestAnimationFrame)return function(r){rr.mozRequestAnimationFrame(r)};if(rr.webkitRequestAnimationFrame)return function(r){rr.webkitRequestAnimationFrame(r)};if(rr.msRequestAnimationFrame)return function(r){rr.msRequestAnimationFrame(r)}}return function(r){r&&setTimeout(function(){r(lv())},1e3/60)}})(),wn=function(e){return qc(e)},Yr=lv,St=9261,vv=65599,Ht=5381,fv=function(e){for(var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:St,a=t,n;n=e.next(),!n.done;)a=a*vv+n.value|0;return a},Ca=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:St;return t*vv+e|0},Ta=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ht;return(t<<5)+t+e|0},_c=function(e,t){return e*2097152+t},et=function(e){return e[0]*2097152+e[1]},Xa=function(e,t){return[Ca(e[0],t[0]),Ta(e[1],t[1])]},qo=function(e,t){var a={value:0,done:!1},n=0,i=e.length,s={next:function(){return n=0;n--)e[n]===t&&e.splice(n,1)},eo=function(e){e.splice(0,e.length)},Qc=function(e,t){for(var a=0;a"u"?"undefined":ar(Set))!==jc?Set:ed,In=function(e,t){var a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(e===void 0||t===void 0||!Ys(e)){$e("An element must have a core reference and parameters set");return}var n=t.group;if(n==null&&(t.data&&t.data.source!=null&&t.data.target!=null?n="edges":n="nodes"),n!=="nodes"&&n!=="edges"){$e("An element must be of type `nodes` or `edges`; you specified `"+n+"`");return}this.length=1,this[0]=this;var i=this._private={cy:e,single:!0,data:t.data||{},position:t.position||{x:0,y:0},autoWidth:void 0,autoHeight:void 0,autoPadding:void 0,compoundBoundsClean:!1,listeners:[],group:n,style:{},rstyle:{},styleCxts:[],styleKeys:{},removed:!0,selected:!!t.selected,selectable:t.selectable===void 0?!0:!!t.selectable,locked:!!t.locked,grabbed:!1,grabbable:t.grabbable===void 0?!0:!!t.grabbable,pannable:t.pannable===void 0?n==="edges":!!t.pannable,active:!1,classes:new ra,animation:{current:[],queue:[]},rscratch:{},scratch:t.scratch||{},edges:[],children:[],parent:t.parent&&t.parent.isNode()?t.parent:null,traversalCache:{},backgrounding:!1,bbCache:null,bbCacheShift:{x:0,y:0},bodyBounds:null,overlayBounds:null,labelBounds:{all:null,source:null,target:null,main:null},arrowBounds:{source:null,target:null,"mid-source":null,"mid-target":null}};if(i.position.x==null&&(i.position.x=0),i.position.y==null&&(i.position.y=0),t.renderedPosition){var s=t.renderedPosition,o=e.pan(),l=e.zoom();i.position={x:(s.x-o.x)/l,y:(s.y-o.y)/l}}var u=[];_e(t.classes)?u=t.classes:ge(t.classes)&&(u=t.classes.split(/\s+/));for(var v=0,f=u.length;vm?1:0},v=function(p,m,b,w,E){var C;if(b==null&&(b=0),E==null&&(E=a),b<0)throw new Error("lo must be non-negative");for(w==null&&(w=p.length);bD;0<=D?k++:k--)T.push(k);return T}).apply(this).reverse(),x=[],w=0,E=C.length;wB;0<=B?++T:--T)P.push(s(p,b));return P},y=function(p,m,b,w){var E,C,x;for(w==null&&(w=a),E=p[b];b>m;){if(x=b-1>>1,C=p[x],w(E,C)<0){p[b]=C,b=x;continue}break}return p[b]=E},g=function(p,m,b){var w,E,C,x,T;for(b==null&&(b=a),E=p.length,T=m,C=p[m],w=2*m+1;w0;){var C=m.pop(),x=g(C),T=C.id();if(c[T]=x,x!==1/0)for(var k=C.neighborhood().intersect(d),D=0;D0)for(O.unshift(M);f[G];){var N=f[G];O.unshift(N.edge),O.unshift(N.node),V=N.node,G=V.id()}return o.spawn(O)}}}},od={kruskal:function(e){e=e||function(b){return 1};for(var t=this.byGroup(),a=t.nodes,n=t.edges,i=a.length,s=new Array(i),o=a,l=function(w){for(var E=0;E0;){if(E(),x++,w===v){for(var T=[],k=i,D=v,B=p[D];T.unshift(k),B!=null&&T.unshift(B),k=g[D],k!=null;)D=k.id(),B=p[D];return{found:!0,distance:f[w],path:this.spawn(T),steps:x}}h[w]=!0;for(var P=b._private.edges,A=0;AB&&(d[D]=B,m[D]=k,b[D]=E),!i){var P=k*v+T;!i&&d[P]>B&&(d[P]=B,m[P]=T,b[P]=E)}}}for(var A=0;A1&&arguments[1]!==void 0?arguments[1]:s,ie=b(we),de=[],he=ie;;){if(he==null)return t.spawn();var Ee=m(he),pe=Ee.edge,Se=Ee.pred;if(de.unshift(he[0]),he.same(ye)&&de.length>0)break;pe!=null&&de.unshift(pe),he=Se}return l.spawn(de)},C=0;C=0;v--){var f=u[v],c=f[1],h=f[2];(t[c]===o&&t[h]===l||t[c]===l&&t[h]===o)&&u.splice(v,1)}for(var d=0;dn;){var i=Math.floor(Math.random()*t.length);t=gd(i,e,t),a--}return t},pd={kargerStein:function(){var e=this,t=this.byGroup(),a=t.nodes,n=t.edges;n.unmergeBy(function(O){return O.isLoop()});var i=a.length,s=n.length,o=Math.ceil(Math.pow(Math.log(i)/Math.LN2,2)),l=Math.floor(i/hd);if(i<2){$e("At least 2 nodes are required for Karger-Stein algorithm");return}for(var u=[],v=0;v1&&arguments[1]!==void 0?arguments[1]:0,a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length,n=1/0,i=t;i1&&arguments[1]!==void 0?arguments[1]:0,a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length,n=-1/0,i=t;i1&&arguments[1]!==void 0?arguments[1]:0,a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length,n=0,i=0,s=t;s1&&arguments[1]!==void 0?arguments[1]:0,a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!0,i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,s=arguments.length>5&&arguments[5]!==void 0?arguments[5]:!0;n?e=e.slice(t,a):(a0&&e.splice(0,t));for(var o=0,l=e.length-1;l>=0;l--){var u=e[l];s?isFinite(u)||(e[l]=-1/0,o++):e.splice(l,1)}i&&e.sort(function(c,h){return c-h});var v=e.length,f=Math.floor(v/2);return v%2!==0?e[f+1+o]:(e[f-1+o]+e[f+o])/2},Ed=function(e){return Math.PI*e/180},Ya=function(e,t){return Math.atan2(t,e)-Math.PI/2},ro=Math.log2||function(r){return Math.log(r)/Math.log(2)},to=function(e){return e>0?1:e<0?-1:0},Pt=function(e,t){return Math.sqrt(Ct(e,t))},Ct=function(e,t){var a=t.x-e.x,n=t.y-e.y;return a*a+n*n},Cd=function(e){for(var t=e.length,a=0,n=0;n=e.x1&&e.y2>=e.y1)return{x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,w:e.x2-e.x1,h:e.y2-e.y1};if(e.w!=null&&e.h!=null&&e.w>=0&&e.h>=0)return{x1:e.x1,y1:e.y1,x2:e.x1+e.w,y2:e.y1+e.h,w:e.w,h:e.h}}},Sd=function(e){return{x1:e.x1,x2:e.x2,w:e.w,y1:e.y1,y2:e.y2,h:e.h}},kd=function(e){e.x1=1/0,e.y1=1/0,e.x2=-1/0,e.y2=-1/0,e.w=0,e.h=0},Dd=function(e,t){e.x1=Math.min(e.x1,t.x1),e.x2=Math.max(e.x2,t.x2),e.w=e.x2-e.x1,e.y1=Math.min(e.y1,t.y1),e.y2=Math.max(e.y2,t.y2),e.h=e.y2-e.y1},mv=function(e,t,a){e.x1=Math.min(e.x1,t),e.x2=Math.max(e.x2,t),e.w=e.x2-e.x1,e.y1=Math.min(e.y1,a),e.y2=Math.max(e.y2,a),e.h=e.y2-e.y1},un=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return e.x1-=t,e.x2+=t,e.y1-=t,e.y2+=t,e.w=e.x2-e.x1,e.h=e.y2-e.y1,e},ln=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[0],a,n,i,s;if(t.length===1)a=n=i=s=t[0];else if(t.length===2)a=i=t[0],s=n=t[1];else if(t.length===4){var o=Je(t,4);a=o[0],n=o[1],i=o[2],s=o[3]}return e.x1-=s,e.x2+=n,e.y1-=a,e.y2+=i,e.w=e.x2-e.x1,e.h=e.y2-e.y1,e},Uo=function(e,t){e.x1=t.x1,e.y1=t.y1,e.x2=t.x2,e.y2=t.y2,e.w=e.x2-e.x1,e.h=e.y2-e.y1},ao=function(e,t){return!(e.x1>t.x2||t.x1>e.x2||e.x2t.y2||t.y1>e.y2)},nt=function(e,t,a){return e.x1<=t&&t<=e.x2&&e.y1<=a&&a<=e.y2},Ko=function(e,t){return nt(e,t.x,t.y)},bv=function(e,t){return nt(e,t.x1,t.y1)&&nt(e,t.x2,t.y2)},Bd=(gi=Math.hypot)!==null&&gi!==void 0?gi:function(r,e){return Math.sqrt(r*r+e*e)};function Pd(r,e){if(r.length<3)throw new Error("Need at least 3 vertices");var t=function(T,k){return{x:T.x+k.x,y:T.y+k.y}},a=function(T,k){return{x:T.x-k.x,y:T.y-k.y}},n=function(T,k){return{x:T.x*k,y:T.y*k}},i=function(T,k){return T.x*k.y-T.y*k.x},s=function(T){var k=Bd(T.x,T.y);return k===0?{x:0,y:0}:{x:T.x/k,y:T.y/k}},o=function(T){for(var k=0,D=0;D7&&arguments[7]!==void 0?arguments[7]:"auto",u=l==="auto"?vt(i,s):l,v=i/2,f=s/2;u=Math.min(u,v,f);var c=u!==v,h=u!==f,d;if(c){var y=a-v+u-o,g=n-f-o,p=a+v-u+o,m=g;if(d=it(e,t,a,n,y,g,p,m,!1),d.length>0)return d}if(h){var b=a+v+o,w=n-f+u-o,E=b,C=n+f-u+o;if(d=it(e,t,a,n,b,w,E,C,!1),d.length>0)return d}if(c){var x=a-v+u-o,T=n+f+o,k=a+v-u+o,D=T;if(d=it(e,t,a,n,x,T,k,D,!1),d.length>0)return d}if(h){var B=a-v-o,P=n-f+u-o,A=B,R=n+f-u+o;if(d=it(e,t,a,n,B,P,A,R,!1),d.length>0)return d}var L;{var I=a-v+u,M=n-f+u;if(L=ya(e,t,a,n,I,M,u+o),L.length>0&&L[0]<=I&&L[1]<=M)return[L[0],L[1]]}{var O=a+v-u,V=n-f+u;if(L=ya(e,t,a,n,O,V,u+o),L.length>0&&L[0]>=O&&L[1]<=V)return[L[0],L[1]]}{var G=a+v-u,N=n+f-u;if(L=ya(e,t,a,n,G,N,u+o),L.length>0&&L[0]>=G&&L[1]>=N)return[L[0],L[1]]}{var F=a-v+u,U=n+f-u;if(L=ya(e,t,a,n,F,U,u+o),L.length>0&&L[0]<=F&&L[1]>=U)return[L[0],L[1]]}return[]},Rd=function(e,t,a,n,i,s,o){var l=o,u=Math.min(a,i),v=Math.max(a,i),f=Math.min(n,s),c=Math.max(n,s);return u-l<=e&&e<=v+l&&f-l<=t&&t<=c+l},Md=function(e,t,a,n,i,s,o,l,u){var v={x1:Math.min(a,o,i)-u,x2:Math.max(a,o,i)+u,y1:Math.min(n,l,s)-u,y2:Math.max(n,l,s)+u};return!(ev.x2||tv.y2)},Ld=function(e,t,a,n){a-=n;var i=t*t-4*e*a;if(i<0)return[];var s=Math.sqrt(i),o=2*e,l=(-t+s)/o,u=(-t-s)/o;return[l,u]},Id=function(e,t,a,n,i){var s=1e-5;e===0&&(e=s),t/=e,a/=e,n/=e;var o,l,u,v,f,c,h,d;if(l=(3*a-t*t)/9,u=-(27*n)+t*(9*a-2*(t*t)),u/=54,o=l*l*l+u*u,i[1]=0,h=t/3,o>0){f=u+Math.sqrt(o),f=f<0?-Math.pow(-f,1/3):Math.pow(f,1/3),c=u-Math.sqrt(o),c=c<0?-Math.pow(-c,1/3):Math.pow(c,1/3),i[0]=-h+f+c,h+=(f+c)/2,i[4]=i[2]=-h,h=Math.sqrt(3)*(-c+f)/2,i[3]=h,i[5]=-h;return}if(i[5]=i[3]=0,o===0){d=u<0?-Math.pow(-u,1/3):Math.pow(u,1/3),i[0]=-h+2*d,i[4]=i[2]=-(d+h);return}l=-l,v=l*l*l,v=Math.acos(u/Math.sqrt(v)),d=2*Math.sqrt(l),i[0]=-h+d*Math.cos(v/3),i[2]=-h+d*Math.cos((v+2*Math.PI)/3),i[4]=-h+d*Math.cos((v+4*Math.PI)/3)},Od=function(e,t,a,n,i,s,o,l){var u=1*a*a-4*a*i+2*a*o+4*i*i-4*i*o+o*o+n*n-4*n*s+2*n*l+4*s*s-4*s*l+l*l,v=9*a*i-3*a*a-3*a*o-6*i*i+3*i*o+9*n*s-3*n*n-3*n*l-6*s*s+3*s*l,f=3*a*a-6*a*i+a*o-a*e+2*i*i+2*i*e-o*e+3*n*n-6*n*s+n*l-n*t+2*s*s+2*s*t-l*t,c=1*a*i-a*a+a*e-i*e+n*s-n*n+n*t-s*t,h=[];Id(u,v,f,c,h);for(var d=1e-7,y=[],g=0;g<6;g+=2)Math.abs(h[g+1])=0&&h[g]<=1&&y.push(h[g]);y.push(1),y.push(0);for(var p=-1,m,b,w,E=0;E=0?wu?(e-i)*(e-i)+(t-s)*(t-s):v-c},Sr=function(e,t,a){for(var n,i,s,o,l,u=0,v=0;v=e&&e>=s||n<=e&&e<=s)l=(e-n)/(s-n)*(o-i)+i,l>t&&u++;else continue;return u%2!==0},Zr=function(e,t,a,n,i,s,o,l,u){var v=new Array(a.length),f;l[0]!=null?(f=Math.atan(l[1]/l[0]),l[0]<0?f=f+Math.PI/2:f=-f-Math.PI/2):f=l;for(var c=Math.cos(-f),h=Math.sin(-f),d=0;d0){var g=Cn(v,-u);y=En(g)}else y=v;return Sr(e,t,y)},zd=function(e,t,a,n,i,s,o,l){for(var u=new Array(a.length*2),v=0;v=0&&g<=1&&m.push(g),p>=0&&p<=1&&m.push(p),m.length===0)return[];var b=m[0]*l[0]+e,w=m[0]*l[1]+t;if(m.length>1){if(m[0]==m[1])return[b,w];var E=m[1]*l[0]+e,C=m[1]*l[1]+t;return[b,w,E,C]}else return[b,w]},pi=function(e,t,a){return t<=e&&e<=a||a<=e&&e<=t?e:e<=t&&t<=a||a<=t&&t<=e?t:a},it=function(e,t,a,n,i,s,o,l,u){var v=e-i,f=a-e,c=o-i,h=t-s,d=n-t,y=l-s,g=c*h-y*v,p=f*h-d*v,m=y*f-c*d;if(m!==0){var b=g/m,w=p/m,E=.001,C=0-E,x=1+E;return C<=b&&b<=x&&C<=w&&w<=x?[e+b*f,t+b*d]:u?[e+b*f,t+b*d]:[]}else return g===0||p===0?pi(e,a,o)===o?[o,l]:pi(e,a,i)===i?[i,s]:pi(i,o,a)===a?[a,n]:[]:[]},Vd=function(e,t,a,n,i){var s=[],o=n/2,l=i/2,u=t,v=a;s.push({x:u+o*e[0],y:v+l*e[1]});for(var f=1;f0){var y=Cn(f,-l);h=En(y)}else h=f}else h=a;for(var g,p,m,b,w=0;w2){for(var d=[v[0],v[1]],y=Math.pow(d[0]-e,2)+Math.pow(d[1]-t,2),g=1;gv&&(v=w)},get:function(b){return u[b]}},c=0;c0?L=R.edgesTo(A)[0]:L=A.edgesTo(R)[0];var I=n(L);A=A.id(),x[A]>x[B]+I&&(x[A]=x[B]+I,T.nodes.indexOf(A)<0?T.push(A):T.updateItem(A),C[A]=0,E[A]=[]),x[A]==x[B]+I&&(C[A]=C[A]+C[B],E[A].push(B))}else for(var M=0;M0;){for(var N=w.pop(),F=0;F0&&o.push(a[l]);o.length!==0&&i.push(n.collection(o))}return i},eh=function(e,t){for(var a=0;a5&&arguments[5]!==void 0?arguments[5]:ah,o=n,l,u,v=0;v=2?va(e,t,a,0,Jo,nh):va(e,t,a,0,Qo)},squaredEuclidean:function(e,t,a){return va(e,t,a,0,Jo)},manhattan:function(e,t,a){return va(e,t,a,0,Qo)},max:function(e,t,a){return va(e,t,a,-1/0,ih)}};Jt["squared-euclidean"]=Jt.squaredEuclidean;Jt.squaredeuclidean=Jt.squaredEuclidean;function Nn(r,e,t,a,n,i){var s;return Ue(r)?s=r:s=Jt[r]||Jt.euclidean,e===0&&Ue(r)?s(n,i):s(e,t,a,n,i)}var sh=cr({k:2,m:2,sensitivityThreshold:1e-4,distance:"euclidean",maxIterations:10,attributes:[],testMode:!1,testCentroids:null}),io=function(e){return sh(e)},Tn=function(e,t,a,n,i){var s=i!=="kMedoids",o=s?function(f){return a[f]}:function(f){return n[f](a)},l=function(c){return n[c](t)},u=a,v=t;return Nn(e,n.length,o,l,u,v)},mi=function(e,t,a){for(var n=a.length,i=new Array(n),s=new Array(n),o=new Array(t),l=null,u=0;ua)return!1}return!0},lh=function(e,t,a){for(var n=0;no&&(o=t[u][v],l=v);i[l].push(e[u])}for(var f=0;f=i.threshold||i.mode==="dendrogram"&&e.length===1)return!1;var d=t[s],y=t[n[s]],g;i.mode==="dendrogram"?g={left:d,right:y,key:d.key}:g={value:d.value.concat(y.value),key:d.key},e[d.index]=g,e.splice(y.index,1),t[d.key]=g;for(var p=0;pa[y.key][m.key]&&(l=a[y.key][m.key])):i.linkage==="max"?(l=a[d.key][m.key],a[d.key][m.key]0&&n.push(i);return n},nu=function(e,t,a){for(var n=[],i=0;io&&(s=u,o=t[i*e+u])}s>0&&n.push(s)}for(var v=0;vu&&(l=v,u=f)}a[i]=s[l]}return n=nu(e,t,a),n},iu=function(e){for(var t=this.cy(),a=this.nodes(),n=xh(e),i={},s=0;s=B?(P=B,B=R,A=L):R>P&&(P=R);for(var I=0;I0?1:0;x[k%n.minIterations*o+F]=U,N+=U}if(N>0&&(k>=n.minIterations-1||k==n.maxIterations-1)){for(var Q=0,K=0;K1||C>1)&&(o=!0),f[b]=[],m.outgoers().forEach(function(T){T.isEdge()&&f[b].push(T.id())})}else c[b]=[void 0,m.target().id()]}):s.forEach(function(m){var b=m.id();if(m.isNode()){var w=m.degree(!0);w%2&&(l?u?o=!0:u=b:l=b),f[b]=[],m.connectedEdges().forEach(function(E){return f[b].push(E.id())})}else c[b]=[m.source().id(),m.target().id()]});var h={found:!1,trail:void 0};if(o)return h;if(u&&l)if(i){if(v&&u!=v)return h;v=u}else{if(v&&u!=v&&l!=v)return h;v||(v=u)}else v||(v=s[0].id());var d=function(b){for(var w=b,E=[b],C,x,T;f[w].length;)C=f[w].shift(),x=c[C][0],T=c[C][1],w!=T?(f[T]=f[T].filter(function(k){return k!=C}),w=T):!i&&w!=x&&(f[x]=f[x].filter(function(k){return k!=C}),w=x),E.unshift(C),E.unshift(w);return E},y=[],g=[];for(g=d(v);g.length!=1;)f[g[0]].length==0?(y.unshift(s.getElementById(g.shift())),y.unshift(s.getElementById(g.shift()))):g=d(g.shift()).concat(g);y.unshift(s.getElementById(g.shift()));for(var p in f)if(f[p].length)return h;return h.found=!0,h.trail=this.spawn(y,!0),h}},Qa=function(){var e=this,t={},a=0,n=0,i=[],s=[],o={},l=function(c,h){for(var d=s.length-1,y=[],g=e.spawn();s[d].x!=c||s[d].y!=h;)y.push(s.pop().edge),d--;y.push(s.pop().edge),y.forEach(function(p){var m=p.connectedNodes().intersection(e);g.merge(p),m.forEach(function(b){var w=b.id(),E=b.connectedEdges().intersection(e);g.merge(b),t[w].cutVertex?g.merge(E.filter(function(C){return C.isLoop()})):g.merge(E)})}),i.push(g)},u=function(c,h,d){c===d&&(n+=1),t[h]={id:a,low:a++,cutVertex:!1};var y=e.getElementById(h).connectedEdges().intersection(e);if(y.size()===0)i.push(e.spawn(e.getElementById(h)));else{var g,p,m,b;y.forEach(function(w){g=w.source().id(),p=w.target().id(),m=g===h?p:g,m!==d&&(b=w.id(),o[b]||(o[b]=!0,s.push({x:h,y:m,edge:w})),m in t?t[h].low=Math.min(t[h].low,t[m].id):(u(c,m,h),t[h].low=Math.min(t[h].low,t[m].low),t[h].id<=t[m].low&&(t[h].cutVertex=!0,l(h,m))))})}};e.forEach(function(f){if(f.isNode()){var c=f.id();c in t||(n=0,u(c,c),t[c].cutVertex=n>1)}});var v=Object.keys(t).filter(function(f){return t[f].cutVertex}).map(function(f){return e.getElementById(f)});return{cut:e.spawn(v),components:i}},Ph={hopcroftTarjanBiconnected:Qa,htbc:Qa,htb:Qa,hopcroftTarjanBiconnectedComponents:Qa},Ja=function(){var e=this,t={},a=0,n=[],i=[],s=e.spawn(e),o=function(u){i.push(u),t[u]={index:a,low:a++,explored:!1};var v=e.getElementById(u).connectedEdges().intersection(e);if(v.forEach(function(y){var g=y.target().id();g!==u&&(g in t||o(g),t[g].explored||(t[u].low=Math.min(t[u].low,t[g].low)))}),t[u].index===t[u].low){for(var f=e.spawn();;){var c=i.pop();if(f.merge(e.getElementById(c)),t[c].low=t[u].index,t[c].explored=!0,c===u)break}var h=f.edgesWith(f),d=f.merge(h);n.push(d),s=s.difference(d)}};return e.forEach(function(l){if(l.isNode()){var u=l.id();u in t||o(u)}}),{cut:s,components:n}},Ah={tarjanStronglyConnected:Ja,tsc:Ja,tscc:Ja,tarjanStronglyConnectedComponents:Ja},Dv={};[Sa,sd,od,ld,fd,dd,pd,Hd,Xt,Yt,Rs,th,gh,bh,kh,Bh,Ph,Ah].forEach(function(r){be(Dv,r)});var Bv=0,Pv=1,Av=2,Nr=function(e){if(!(this instanceof Nr))return new Nr(e);this.id="Thenable/1.0.7",this.state=Bv,this.fulfillValue=void 0,this.rejectReason=void 0,this.onFulfilled=[],this.onRejected=[],this.proxy={then:this.then.bind(this)},typeof e=="function"&&e.call(this,this.fulfill.bind(this),this.reject.bind(this))};Nr.prototype={fulfill:function(e){return su(this,Pv,"fulfillValue",e)},reject:function(e){return su(this,Av,"rejectReason",e)},then:function(e,t){var a=this,n=new Nr;return a.onFulfilled.push(uu(e,n,"fulfill")),a.onRejected.push(uu(t,n,"reject")),Rv(a),n.proxy}};var su=function(e,t,a,n){return e.state===Bv&&(e.state=t,e[a]=n,Rv(e)),e},Rv=function(e){e.state===Pv?ou(e,"onFulfilled",e.fulfillValue):e.state===Av&&ou(e,"onRejected",e.rejectReason)},ou=function(e,t,a){if(e[t].length!==0){var n=e[t];e[t]=[];var i=function(){for(var o=0;o0}},clearQueue:function(){return function(){var t=this,a=t.length!==void 0,n=a?t:[t],i=this._private.cy||this;if(!i.styleEnabled())return this;for(var s=0;s-1}return qi=e,qi}var _i,Ru;function Yh(){if(Ru)return _i;Ru=1;var r=Vn();function e(t,a){var n=this.__data__,i=r(n,t);return i<0?(++this.size,n.push([t,a])):n[i][1]=a,this}return _i=e,_i}var Gi,Mu;function Zh(){if(Mu)return Gi;Mu=1;var r=$h(),e=Uh(),t=Kh(),a=Xh(),n=Yh();function i(s){var o=-1,l=s==null?0:s.length;for(this.clear();++o-1&&a%1==0&&a0&&this.spawn(n).updateStyle().emit("class"),t},addClass:function(e){return this.toggleClass(e,!0)},hasClass:function(e){var t=this[0];return t!=null&&t._private.classes.has(e)},toggleClass:function(e,t){_e(e)||(e=e.match(/\S+/g)||[]);for(var a=this,n=t===void 0,i=[],s=0,o=a.length;s0&&this.spawn(i).updateStyle().emit("class"),a},removeClass:function(e){return this.toggleClass(e,!1)},flashClass:function(e,t){var a=this;if(t==null)t=250;else if(t===0)return a;return a.addClass(e),setTimeout(function(){a.removeClass(e)},t),a}};vn.className=vn.classNames=vn.classes;var Me={metaChar:"[\\!\\\"\\#\\$\\%\\&\\'\\(\\)\\*\\+\\,\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\]\\^\\`\\{\\|\\}\\~]",comparatorOp:"=|\\!=|>|>=|<|<=|\\$=|\\^=|\\*=",boolOp:"\\?|\\!|\\^",string:`"(?:\\\\"|[^"])*"|'(?:\\\\'|[^'])*'`,number:tr,meta:"degree|indegree|outdegree",separator:"\\s*,\\s*",descendant:"\\s+",child:"\\s+>\\s+",subject:"\\$",group:"node|edge|\\*",directedEdge:"\\s+->\\s+",undirectedEdge:"\\s+<->\\s+"};Me.variable="(?:[\\w-.]|(?:\\\\"+Me.metaChar+"))+";Me.className="(?:[\\w-]|(?:\\\\"+Me.metaChar+"))+";Me.value=Me.string+"|"+Me.number;Me.id=Me.variable;(function(){var r,e,t;for(r=Me.comparatorOp.split("|"),t=0;t=0)&&e!=="="&&(Me.comparatorOp+="|\\!"+e)})();var qe=function(){return{checks:[]}},se={GROUP:0,COLLECTION:1,FILTER:2,DATA_COMPARE:3,DATA_EXIST:4,DATA_BOOL:5,META_COMPARE:6,STATE:7,ID:8,CLASS:9,UNDIRECTED_EDGE:10,DIRECTED_EDGE:11,NODE_SOURCE:12,NODE_TARGET:13,NODE_NEIGHBOR:14,CHILD:15,DESCENDANT:16,PARENT:17,ANCESTOR:18,COMPOUND_SPLIT:19,TRUE:20},Os=[{selector:":selected",matches:function(e){return e.selected()}},{selector:":unselected",matches:function(e){return!e.selected()}},{selector:":selectable",matches:function(e){return e.selectable()}},{selector:":unselectable",matches:function(e){return!e.selectable()}},{selector:":locked",matches:function(e){return e.locked()}},{selector:":unlocked",matches:function(e){return!e.locked()}},{selector:":visible",matches:function(e){return e.visible()}},{selector:":hidden",matches:function(e){return!e.visible()}},{selector:":transparent",matches:function(e){return e.transparent()}},{selector:":grabbed",matches:function(e){return e.grabbed()}},{selector:":free",matches:function(e){return!e.grabbed()}},{selector:":removed",matches:function(e){return e.removed()}},{selector:":inside",matches:function(e){return!e.removed()}},{selector:":grabbable",matches:function(e){return e.grabbable()}},{selector:":ungrabbable",matches:function(e){return!e.grabbable()}},{selector:":animated",matches:function(e){return e.animated()}},{selector:":unanimated",matches:function(e){return!e.animated()}},{selector:":parent",matches:function(e){return e.isParent()}},{selector:":childless",matches:function(e){return e.isChildless()}},{selector:":child",matches:function(e){return e.isChild()}},{selector:":orphan",matches:function(e){return e.isOrphan()}},{selector:":nonorphan",matches:function(e){return e.isChild()}},{selector:":compound",matches:function(e){return e.isNode()?e.isParent():e.source().isParent()||e.target().isParent()}},{selector:":loop",matches:function(e){return e.isLoop()}},{selector:":simple",matches:function(e){return e.isSimple()}},{selector:":active",matches:function(e){return e.active()}},{selector:":inactive",matches:function(e){return!e.active()}},{selector:":backgrounding",matches:function(e){return e.backgrounding()}},{selector:":nonbackgrounding",matches:function(e){return!e.backgrounding()}}].sort(function(r,e){return Tc(r.selector,e.selector)}),Dg=(function(){for(var r={},e,t=0;t0&&v.edgeCount>0)return Ve("The selector `"+e+"` is invalid because it uses both a compound selector and an edge selector"),!1;if(v.edgeCount>1)return Ve("The selector `"+e+"` is invalid because it uses multiple edge selectors"),!1;v.edgeCount===1&&Ve("The selector `"+e+"` is deprecated. Edge selectors do not take effect on changes to source and target nodes after an edge is added, for performance reasons. Use a class or data selector on edges instead, updating the class or data of an edge when your app detects a change in source or target nodes.")}return!0},Lg=function(){if(this.toStringCache!=null)return this.toStringCache;for(var e=function(v){return v??""},t=function(v){return ge(v)?'"'+v+'"':e(v)},a=function(v){return" "+v+" "},n=function(v,f){var c=v.type,h=v.value;switch(c){case se.GROUP:{var d=e(h);return d.substring(0,d.length-1)}case se.DATA_COMPARE:{var y=v.field,g=v.operator;return"["+y+a(e(g))+t(h)+"]"}case se.DATA_BOOL:{var p=v.operator,m=v.field;return"["+e(p)+m+"]"}case se.DATA_EXIST:{var b=v.field;return"["+b+"]"}case se.META_COMPARE:{var w=v.operator,E=v.field;return"[["+E+a(e(w))+t(h)+"]]"}case se.STATE:return h;case se.ID:return"#"+h;case se.CLASS:return"."+h;case se.PARENT:case se.CHILD:return i(v.parent,f)+a(">")+i(v.child,f);case se.ANCESTOR:case se.DESCENDANT:return i(v.ancestor,f)+" "+i(v.descendant,f);case se.COMPOUND_SPLIT:{var C=i(v.left,f),x=i(v.subject,f),T=i(v.right,f);return C+(C.length>0?" ":"")+x+T}case se.TRUE:return""}},i=function(v,f){return v.checks.reduce(function(c,h,d){return c+(f===v&&d===0?"$":"")+n(h,f)},"")},s="",o=0;o1&&o=0&&(t=t.replace("!",""),f=!0),t.indexOf("@")>=0&&(t=t.replace("@",""),v=!0),(i||o||v)&&(l=!i&&!s?"":""+e,u=""+a),v&&(e=l=l.toLowerCase(),a=u=u.toLowerCase()),t){case"*=":n=l.indexOf(u)>=0;break;case"$=":n=l.indexOf(u,l.length-u.length)>=0;break;case"^=":n=l.indexOf(u)===0;break;case"=":n=e===a;break;case">":c=!0,n=e>a;break;case">=":c=!0,n=e>=a;break;case"<":c=!0,n=e0;){var v=n.shift();e(v),i.add(v.id()),o&&a(n,i,v)}return r}function Vv(r,e,t){if(t.isParent())for(var a=t._private.children,n=0;n1&&arguments[1]!==void 0?arguments[1]:!0;return lo(this,r,e,Vv)};function qv(r,e,t){if(t.isChild()){var a=t._private.parent;e.has(a.id())||r.push(a)}}jt.forEachUp=function(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return lo(this,r,e,qv)};function _g(r,e,t){qv(r,e,t),Vv(r,e,t)}jt.forEachUpAndDown=function(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return lo(this,r,e,_g)};jt.ancestors=jt.parents;var Ba,_v;Ba=_v={data:Fe.data({field:"data",bindingEvent:"data",allowBinding:!0,allowSetting:!0,settingEvent:"data",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,immutableKeys:{id:!0,source:!0,target:!0,parent:!0},updateStyle:!0}),removeData:Fe.removeData({field:"data",event:"data",triggerFnName:"trigger",triggerEvent:!0,immutableKeys:{id:!0,source:!0,target:!0,parent:!0},updateStyle:!0}),scratch:Fe.data({field:"scratch",bindingEvent:"scratch",allowBinding:!0,allowSetting:!0,settingEvent:"scratch",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeScratch:Fe.removeData({field:"scratch",event:"scratch",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0}),rscratch:Fe.data({field:"rscratch",allowBinding:!1,allowSetting:!0,settingTriggersEvent:!1,allowGetting:!0}),removeRscratch:Fe.removeData({field:"rscratch",triggerEvent:!1}),id:function(){var e=this[0];if(e)return e._private.data.id}};Ba.attr=Ba.data;Ba.removeAttr=Ba.removeData;var Gg=_v,_n={};function ps(r){return function(e){var t=this;if(e===void 0&&(e=!0),t.length!==0)if(t.isNode()&&!t.removed()){for(var a=0,n=t[0],i=n._private.edges,s=0;se}),minIndegree:zt("indegree",function(r,e){return re}),minOutdegree:zt("outdegree",function(r,e){return re})});be(_n,{totalDegree:function(e){for(var t=0,a=this.nodes(),n=0;n0,c=f;f&&(v=v[0]);var h=c?v.position():{x:0,y:0};t!==void 0?u.position(e,t+h[e]):i!==void 0&&u.position({x:i.x+h.x,y:i.y+h.y})}else{var d=a.position(),y=o?a.parent():null,g=y&&y.length>0,p=g;g&&(y=y[0]);var m=p?y.position():{x:0,y:0};return i={x:d.x-m.x,y:d.y-m.y},e===void 0?i:i[e]}else if(!s)return;return this}};Or.modelPosition=Or.point=Or.position;Or.modelPositions=Or.points=Or.positions;Or.renderedPoint=Or.renderedPosition;Or.relativePoint=Or.relativePosition;var Hg=Gv,Zt,pt;Zt=pt={};pt.renderedBoundingBox=function(r){var e=this.boundingBox(r),t=this.cy(),a=t.zoom(),n=t.pan(),i=e.x1*a+n.x,s=e.x2*a+n.x,o=e.y1*a+n.y,l=e.y2*a+n.y;return{x1:i,x2:s,y1:o,y2:l,w:s-i,h:l-o}};pt.dirtyCompoundBoundsCache=function(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,e=this.cy();return!e.styleEnabled()||!e.hasCompoundNodes()?this:(this.forEachUp(function(t){if(t.isParent()){var a=t._private;a.compoundBoundsClean=!1,a.bbCache=null,r||t.emitAndNotify("bounds")}}),this)};pt.updateCompoundBounds=function(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,e=this.cy();if(!e.styleEnabled()||!e.hasCompoundNodes())return this;if(!r&&e.batching())return this;function t(s){if(!s.isParent())return;var o=s._private,l=s.children(),u=s.pstyle("compound-sizing-wrt-labels").value==="include",v={width:{val:s.pstyle("min-width").pfValue,left:s.pstyle("min-width-bias-left"),right:s.pstyle("min-width-bias-right")},height:{val:s.pstyle("min-height").pfValue,top:s.pstyle("min-height-bias-top"),bottom:s.pstyle("min-height-bias-bottom")}},f=l.boundingBox({includeLabels:u,includeOverlays:!1,useCache:!1}),c=o.position;(f.w===0||f.h===0)&&(f={w:s.pstyle("width").pfValue,h:s.pstyle("height").pfValue},f.x1=c.x-f.w/2,f.x2=c.x+f.w/2,f.y1=c.y-f.h/2,f.y2=c.y+f.h/2);function h(k,D,B){var P=0,A=0,R=D+B;return k>0&&R>0&&(P=D/R*k,A=B/R*k),{biasDiff:P,biasComplementDiff:A}}function d(k,D,B,P){if(B.units==="%")switch(P){case"width":return k>0?B.pfValue*k:0;case"height":return D>0?B.pfValue*D:0;case"average":return k>0&&D>0?B.pfValue*(k+D)/2:0;case"min":return k>0&&D>0?k>D?B.pfValue*D:B.pfValue*k:0;case"max":return k>0&&D>0?k>D?B.pfValue*k:B.pfValue*D:0;default:return 0}else return B.units==="px"?B.pfValue:0}var y=v.width.left.value;v.width.left.units==="px"&&v.width.val>0&&(y=y*100/v.width.val);var g=v.width.right.value;v.width.right.units==="px"&&v.width.val>0&&(g=g*100/v.width.val);var p=v.height.top.value;v.height.top.units==="px"&&v.height.val>0&&(p=p*100/v.height.val);var m=v.height.bottom.value;v.height.bottom.units==="px"&&v.height.val>0&&(m=m*100/v.height.val);var b=h(v.width.val-f.w,y,g),w=b.biasDiff,E=b.biasComplementDiff,C=h(v.height.val-f.h,p,m),x=C.biasDiff,T=C.biasComplementDiff;o.autoPadding=d(f.w,f.h,s.pstyle("padding"),s.pstyle("padding-relative-to").value),o.autoWidth=Math.max(f.w,v.width.val),c.x=(-w+f.x1+f.x2+E)/2,o.autoHeight=Math.max(f.h,v.height.val),c.y=(-x+f.y1+f.y2+T)/2}for(var a=0;ae.x2?n:e.x2,e.y1=ae.y2?i:e.y2,e.w=e.x2-e.x1,e.h=e.y2-e.y1)},tt=function(e,t){return t==null?e:Ir(e,t.x1,t.y1,t.x2,t.y2)},fa=function(e,t,a){return Tr(e,t,a)},ja=function(e,t,a){if(!t.cy().headless()){var n=t._private,i=n.rstyle,s=i.arrowWidth/2,o=t.pstyle(a+"-arrow-shape").value,l,u;if(o!=="none"){a==="source"?(l=i.srcX,u=i.srcY):a==="target"?(l=i.tgtX,u=i.tgtY):(l=i.midX,u=i.midY);var v=n.arrowBounds=n.arrowBounds||{},f=v[a]=v[a]||{};f.x1=l-s,f.y1=u-s,f.x2=l+s,f.y2=u+s,f.w=f.x2-f.x1,f.h=f.y2-f.y1,un(f,1),Ir(e,f.x1,f.y1,f.x2,f.y2)}}},ys=function(e,t,a){if(!t.cy().headless()){var n;a?n=a+"-":n="";var i=t._private,s=i.rstyle,o=t.pstyle(n+"label").strValue;if(o){var l=t.pstyle("text-halign"),u=t.pstyle("text-valign"),v=fa(s,"labelWidth",a),f=fa(s,"labelHeight",a),c=fa(s,"labelX",a),h=fa(s,"labelY",a),d=t.pstyle(n+"text-margin-x").pfValue,y=t.pstyle(n+"text-margin-y").pfValue,g=t.isEdge(),p=t.pstyle(n+"text-rotation"),m=t.pstyle("text-outline-width").pfValue,b=t.pstyle("text-border-width").pfValue,w=b/2,E=t.pstyle("text-background-padding").pfValue,C=2,x=f,T=v,k=T/2,D=x/2,B,P,A,R;if(g)B=c-k,P=c+k,A=h-D,R=h+D;else{switch(l.value){case"left":B=c-T,P=c;break;case"center":B=c-k,P=c+k;break;case"right":B=c,P=c+T;break}switch(u.value){case"top":A=h-x,R=h;break;case"center":A=h-D,R=h+D;break;case"bottom":A=h,R=h+x;break}}var L=d-Math.max(m,w)-E-C,I=d+Math.max(m,w)+E+C,M=y-Math.max(m,w)-E-C,O=y+Math.max(m,w)+E+C;B+=L,P+=I,A+=M,R+=O;var V=a||"main",G=i.labelBounds,N=G[V]=G[V]||{};N.x1=B,N.y1=A,N.x2=P,N.y2=R,N.w=P-B,N.h=R-A,N.leftPad=L,N.rightPad=I,N.topPad=M,N.botPad=O;var F=g&&p.strValue==="autorotate",U=p.pfValue!=null&&p.pfValue!==0;if(F||U){var Q=F?fa(i.rstyle,"labelAngle",a):p.pfValue,K=Math.cos(Q),j=Math.sin(Q),re=(B+P)/2,ne=(A+R)/2;if(!g){switch(l.value){case"left":re=P;break;case"right":re=B;break}switch(u.value){case"top":ne=R;break;case"bottom":ne=A;break}}var J=function(Ce,we){return Ce=Ce-re,we=we-ne,{x:Ce*K-we*j+re,y:Ce*j+we*K+ne}},z=J(B,A),q=J(B,R),H=J(P,A),Y=J(P,R);B=Math.min(z.x,q.x,H.x,Y.x),P=Math.max(z.x,q.x,H.x,Y.x),A=Math.min(z.y,q.y,H.y,Y.y),R=Math.max(z.y,q.y,H.y,Y.y)}var te=V+"Rot",ce=G[te]=G[te]||{};ce.x1=B,ce.y1=A,ce.x2=P,ce.y2=R,ce.w=P-B,ce.h=R-A,Ir(e,B,A,P,R),Ir(i.labelBounds.all,B,A,P,R)}return e}},ol=function(e,t){if(!t.cy().headless()){var a=t.pstyle("outline-opacity").value,n=t.pstyle("outline-width").value,i=t.pstyle("outline-offset").value,s=n+i;Wv(e,t,a,s,"outside",s/2)}},Wv=function(e,t,a,n,i,s){if(!(a===0||n<=0||i==="inside")){var o=t.cy(),l=t.pstyle("shape").value,u=o.renderer().nodeShapes[l],v=t.position(),f=v.x,c=v.y,h=t.width(),d=t.height();if(u.hasMiterBounds){i==="center"&&(n/=2);var y=u.miterBounds(f,c,h,d,n);tt(e,y)}else s!=null&&s>0&&ln(e,[s,s,s,s])}},Wg=function(e,t){if(!t.cy().headless()){var a=t.pstyle("border-opacity").value,n=t.pstyle("border-width").pfValue,i=t.pstyle("border-position").value;Wv(e,t,a,n,i)}},$g=function(e,t){var a=e._private.cy,n=a.styleEnabled(),i=a.headless(),s=wr(),o=e._private,l=e.isNode(),u=e.isEdge(),v,f,c,h,d,y,g=o.rstyle,p=l&&n?e.pstyle("bounds-expansion").pfValue:[0],m=function(Ae){return Ae.pstyle("display").value!=="none"},b=!n||m(e)&&(!u||m(e.source())&&m(e.target()));if(b){var w=0,E=0;n&&t.includeOverlays&&(w=e.pstyle("overlay-opacity").value,w!==0&&(E=e.pstyle("overlay-padding").value));var C=0,x=0;n&&t.includeUnderlays&&(C=e.pstyle("underlay-opacity").value,C!==0&&(x=e.pstyle("underlay-padding").value));var T=Math.max(E,x),k=0,D=0;if(n&&(k=e.pstyle("width").pfValue,D=k/2),l&&t.includeNodes){var B=e.position();d=B.x,y=B.y;var P=e.outerWidth(),A=P/2,R=e.outerHeight(),L=R/2;v=d-A,f=d+A,c=y-L,h=y+L,Ir(s,v,c,f,h),n&&ol(s,e),n&&t.includeOutlines&&!i&&ol(s,e),n&&Wg(s,e)}else if(u&&t.includeEdges)if(n&&!i){var I=e.pstyle("curve-style").strValue;if(v=Math.min(g.srcX,g.midX,g.tgtX),f=Math.max(g.srcX,g.midX,g.tgtX),c=Math.min(g.srcY,g.midY,g.tgtY),h=Math.max(g.srcY,g.midY,g.tgtY),v-=D,f+=D,c-=D,h+=D,Ir(s,v,c,f,h),I==="haystack"){var M=g.haystackPts;if(M&&M.length===2){if(v=M[0].x,c=M[0].y,f=M[1].x,h=M[1].y,v>f){var O=v;v=f,f=O}if(c>h){var V=c;c=h,h=V}Ir(s,v-D,c-D,f+D,h+D)}}else if(I==="bezier"||I==="unbundled-bezier"||at(I,"segments")||at(I,"taxi")){var G;switch(I){case"bezier":case"unbundled-bezier":G=g.bezierPts;break;case"segments":case"taxi":case"round-segments":case"round-taxi":G=g.linePts;break}if(G!=null)for(var N=0;Nf){var re=v;v=f,f=re}if(c>h){var ne=c;c=h,h=ne}v-=D,f+=D,c-=D,h+=D,Ir(s,v,c,f,h)}if(n&&t.includeEdges&&u&&(ja(s,e,"mid-source"),ja(s,e,"mid-target"),ja(s,e,"source"),ja(s,e,"target")),n){var J=e.pstyle("ghost").value==="yes";if(J){var z=e.pstyle("ghost-offset-x").pfValue,q=e.pstyle("ghost-offset-y").pfValue;Ir(s,s.x1+z,s.y1+q,s.x2+z,s.y2+q)}}var H=o.bodyBounds=o.bodyBounds||{};Uo(H,s),ln(H,p),un(H,1),n&&(v=s.x1,f=s.x2,c=s.y1,h=s.y2,Ir(s,v-T,c-T,f+T,h+T));var Y=o.overlayBounds=o.overlayBounds||{};Uo(Y,s),ln(Y,p),un(Y,1);var te=o.labelBounds=o.labelBounds||{};te.all!=null?kd(te.all):te.all=wr(),n&&t.includeLabels&&(t.includeMainLabels&&ys(s,e,null),u&&(t.includeSourceLabels&&ys(s,e,"source"),t.includeTargetLabels&&ys(s,e,"target")))}return s.x1=Ar(s.x1),s.y1=Ar(s.y1),s.x2=Ar(s.x2),s.y2=Ar(s.y2),s.w=Ar(s.x2-s.x1),s.h=Ar(s.y2-s.y1),s.w>0&&s.h>0&&b&&(ln(s,p),un(s,1)),s},$v=function(e){var t=0,a=function(s){return(s?1:0)<0&&arguments[0]!==void 0?arguments[0]:sp,e=arguments.length>1?arguments[1]:void 0,t=0;t=0;o--)s(o);return this};dt.removeAllListeners=function(){return this.removeListener("*")};dt.emit=dt.trigger=function(r,e,t){var a=this.listeners,n=a.length;return this.emitting++,_e(e)||(e=[e]),op(this,function(i,s){t!=null&&(a=[{event:s.event,type:s.type,namespace:s.namespace,callback:t}],n=a.length);for(var o=function(){var v=a[l];if(v.type===s.type&&(!v.namespace||v.namespace===s.namespace||v.namespace===ip)&&i.eventMatches(i.context,v,s)){var f=[s];e!=null&&Qc(f,e),i.beforeEmit(i.context,v,s),v.conf&&v.conf.one&&(i.listeners=i.listeners.filter(function(d){return d!==v}));var c=i.callbackContext(i.context,v,s),h=v.callback.apply(c,f);i.afterEmit(i.context,v,s),h===!1&&(s.stopPropagation(),s.preventDefault())}},l=0;l1&&!s){var o=this.length-1,l=this[o],u=l._private.data.id;this[o]=void 0,this[e]=l,i.set(u,{ele:l,index:e})}return this.length--,this},unmergeOne:function(e){e=e[0];var t=this._private,a=e._private.data.id,n=t.map,i=n.get(a);if(!i)return this;var s=i.index;return this.unmergeAt(s),this},unmerge:function(e){var t=this._private.cy;if(!e)return this;if(e&&ge(e)){var a=e;e=t.mutableElements().filter(a)}for(var n=0;n=0;t--){var a=this[t];e(a)&&this.unmergeAt(t)}return this},map:function(e,t){for(var a=[],n=this,i=0;ia&&(a=l,n=o)}return{value:a,ele:n}},min:function(e,t){for(var a=1/0,n,i=this,s=0;s=0&&i"u"?"undefined":ar(Symbol))!=e&&ar(Symbol.iterator)!=e;t&&(Sn[Symbol.iterator]=function(){var a=this,n={value:void 0,done:!1},i=0,s=this.length;return Jl({next:function(){return i1&&arguments[1]!==void 0?arguments[1]:!0,a=this[0],n=a.cy();if(n.styleEnabled()&&a){a._private.styleDirty&&(a._private.styleDirty=!1,n.style().apply(a));var i=a._private.style[e];return i??(t?n.style().getDefaultProperty(e):null)}},numericStyle:function(e){var t=this[0];if(t.cy().styleEnabled()&&t){var a=t.pstyle(e);return a.pfValue!==void 0?a.pfValue:a.value}},numericStyleUnits:function(e){var t=this[0];if(t.cy().styleEnabled()&&t)return t.pstyle(e).units},renderedStyle:function(e){var t=this.cy();if(!t.styleEnabled())return this;var a=this[0];if(a)return t.style().getRenderedStyle(a,e)},style:function(e,t){var a=this.cy();if(!a.styleEnabled())return this;var n=!1,i=a.style();if(Le(e)){var s=e;i.applyBypass(this,s,n),this.emitAndNotify("style")}else if(ge(e))if(t===void 0){var o=this[0];return o?i.getStylePropertyValue(o,e):void 0}else i.applyBypass(this,e,t,n),this.emitAndNotify("style");else if(e===void 0){var l=this[0];return l?i.getRawStyle(l):void 0}return this},removeStyle:function(e){var t=this.cy();if(!t.styleEnabled())return this;var a=!1,n=t.style(),i=this;if(e===void 0)for(var s=0;s0&&e.push(v[0]),e.push(o[0])}return this.spawn(e,!0).filter(r)},"neighborhood"),closedNeighborhood:function(e){return this.neighborhood().add(this).filter(e)},openNeighborhood:function(e){return this.neighborhood(e)}});gr.neighbourhood=gr.neighborhood;gr.closedNeighbourhood=gr.closedNeighborhood;gr.openNeighbourhood=gr.openNeighborhood;be(gr,{source:Rr(function(e){var t=this[0],a;return t&&(a=t._private.source||t.cy().collection()),a&&e?a.filter(e):a},"source"),target:Rr(function(e){var t=this[0],a;return t&&(a=t._private.target||t.cy().collection()),a&&e?a.filter(e):a},"target"),sources:ml({attr:"source"}),targets:ml({attr:"target"})});function ml(r){return function(t){for(var a=[],n=0;n0);return s},component:function(){var e=this[0];return e.cy().mutableElements().components(e)[0]}});gr.componentsOf=gr.components;var fr=function(e,t){var a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(e===void 0){$e("A collection must have a reference to the core");return}var i=new Xr,s=!1;if(!t)t=[];else if(t.length>0&&Le(t[0])&&!Ia(t[0])){s=!0;for(var o=[],l=new ra,u=0,v=t.length;u0&&arguments[0]!==void 0?arguments[0]:!0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,t=this,a=t.cy(),n=a._private,i=[],s=[],o,l=0,u=t.length;l0){for(var V=o.length===t.length?t:new fr(a,o),G=0;G0&&arguments[0]!==void 0?arguments[0]:!0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,t=this,a=[],n={},i=t._private.cy;function s(R){for(var L=R._private.edges,I=0;I0&&(r?B.emitAndNotify("remove"):e&&B.emit("remove"));for(var P=0;P0?P=R:B=R;while(Math.abs(A)>s&&++L=i?m(D,L):I===0?L:w(D,B,B+u)}var C=!1;function x(){C=!0,(r!==e||t!==a)&&b()}var T=function(B){return C||x(),r===e&&t===a?B:B===0?0:B===1?1:g(E(B),e,a)};T.getControlPoints=function(){return[{x:r,y:e},{x:t,y:a}]};var k="generateBezier("+[r,e,t,a]+")";return T.toString=function(){return k},T}var mp=(function(){function r(a){return-a.tension*a.x-a.friction*a.v}function e(a,n,i){var s={x:a.x+i.dx*n,v:a.v+i.dv*n,tension:a.tension,friction:a.friction};return{dx:s.v,dv:r(s)}}function t(a,n){var i={dx:a.v,dv:r(a)},s=e(a,n*.5,i),o=e(a,n*.5,s),l=e(a,n,o),u=1/6*(i.dx+2*(s.dx+o.dx)+l.dx),v=1/6*(i.dv+2*(s.dv+o.dv)+l.dv);return a.x=a.x+u*n,a.v=a.v+v*n,a}return function a(n,i,s){var o={x:-1,v:0,tension:null,friction:null},l=[0],u=0,v=1/1e4,f=16/1e3,c,h,d;for(n=parseFloat(n)||500,i=parseFloat(i)||20,s=s||null,o.tension=n,o.friction=i,c=s!==null,c?(u=a(n,i),h=u/s*f):h=f;d=t(d||o,h),l.push(1+d.x),u+=16,Math.abs(d.x)>v&&Math.abs(d.v)>v;);return c?function(y){return l[y*(l.length-1)|0]}:u}})(),Ge=function(e,t,a,n){var i=yp(e,t,a,n);return function(s,o,l){return s+(o-s)*i(l)}},cn={linear:function(e,t,a){return e+(t-e)*a},ease:Ge(.25,.1,.25,1),"ease-in":Ge(.42,0,1,1),"ease-out":Ge(0,0,.58,1),"ease-in-out":Ge(.42,0,.58,1),"ease-in-sine":Ge(.47,0,.745,.715),"ease-out-sine":Ge(.39,.575,.565,1),"ease-in-out-sine":Ge(.445,.05,.55,.95),"ease-in-quad":Ge(.55,.085,.68,.53),"ease-out-quad":Ge(.25,.46,.45,.94),"ease-in-out-quad":Ge(.455,.03,.515,.955),"ease-in-cubic":Ge(.55,.055,.675,.19),"ease-out-cubic":Ge(.215,.61,.355,1),"ease-in-out-cubic":Ge(.645,.045,.355,1),"ease-in-quart":Ge(.895,.03,.685,.22),"ease-out-quart":Ge(.165,.84,.44,1),"ease-in-out-quart":Ge(.77,0,.175,1),"ease-in-quint":Ge(.755,.05,.855,.06),"ease-out-quint":Ge(.23,1,.32,1),"ease-in-out-quint":Ge(.86,0,.07,1),"ease-in-expo":Ge(.95,.05,.795,.035),"ease-out-expo":Ge(.19,1,.22,1),"ease-in-out-expo":Ge(1,0,0,1),"ease-in-circ":Ge(.6,.04,.98,.335),"ease-out-circ":Ge(.075,.82,.165,1),"ease-in-out-circ":Ge(.785,.135,.15,.86),spring:function(e,t,a){if(a===0)return cn.linear;var n=mp(e,t,a);return function(i,s,o){return i+(s-i)*n(o)}},"cubic-bezier":Ge};function xl(r,e,t,a,n){if(a===1||e===t)return t;var i=n(e,t,a);return r==null||((r.roundValue||r.color)&&(i=Math.round(i)),r.min!==void 0&&(i=Math.max(i,r.min)),r.max!==void 0&&(i=Math.min(i,r.max))),i}function El(r,e){return r.pfValue!=null||r.value!=null?r.pfValue!=null&&(e==null||e.type.units!=="%")?r.pfValue:r.value:r}function Ft(r,e,t,a,n){var i=n!=null?n.type:null;t<0?t=0:t>1&&(t=1);var s=El(r,n),o=El(e,n);if(ae(s)&&ae(o))return xl(i,s,o,t,a);if(_e(s)&&_e(o)){for(var l=[],u=0;u0?(h==="spring"&&d.push(s.duration),s.easingImpl=cn[h].apply(null,d)):s.easingImpl=cn[h]}var y=s.easingImpl,g;if(s.duration===0?g=1:g=(t-l)/s.duration,s.applying&&(g=s.progress),g<0?g=0:g>1&&(g=1),s.delay==null){var p=s.startPosition,m=s.position;if(m&&n&&!r.locked()){var b={};da(p.x,m.x)&&(b.x=Ft(p.x,m.x,g,y)),da(p.y,m.y)&&(b.y=Ft(p.y,m.y,g,y)),r.position(b)}var w=s.startPan,E=s.pan,C=i.pan,x=E!=null&&a;x&&(da(w.x,E.x)&&(C.x=Ft(w.x,E.x,g,y)),da(w.y,E.y)&&(C.y=Ft(w.y,E.y,g,y)),r.emit("pan"));var T=s.startZoom,k=s.zoom,D=k!=null&&a;D&&(da(T,k)&&(i.zoom=ka(i.minZoom,Ft(T,k,g,y),i.maxZoom)),r.emit("zoom")),(x||D)&&r.emit("viewport");var B=s.style;if(B&&B.length>0&&n){for(var P=0;P=0;x--){var T=C[x];T()}C.splice(0,C.length)},m=h.length-1;m>=0;m--){var b=h[m],w=b._private;if(w.stopped){h.splice(m,1),w.hooked=!1,w.playing=!1,w.started=!1,p(w.frames);continue}!w.playing&&!w.applying||(w.playing&&w.applying&&(w.applying=!1),w.started||wp(v,b,r),bp(v,b,r,f),w.applying&&(w.applying=!1),p(w.frames),w.step!=null&&w.step(r),b.completed()&&(h.splice(m,1),w.hooked=!1,w.playing=!1,w.started=!1,p(w.completes)),y=!0)}return!f&&h.length===0&&d.length===0&&a.push(v),y}for(var i=!1,s=0;s0?e.notify("draw",t):e.notify("draw")),t.unmerge(a),e.emit("step")}var xp={animate:Fe.animate(),animation:Fe.animation(),animated:Fe.animated(),clearQueue:Fe.clearQueue(),delay:Fe.delay(),delayAnimation:Fe.delayAnimation(),stop:Fe.stop(),addToAnimationPool:function(e){var t=this;t.styleEnabled()&&t._private.aniEles.merge(e)},stopAnimationLoop:function(){this._private.animationsRunning=!1},startAnimationLoop:function(){var e=this;if(e._private.animationsRunning=!0,!e.styleEnabled())return;function t(){e._private.animationsRunning&&wn(function(i){Cl(i,e),t()})}var a=e.renderer();a&&a.beforeRender?a.beforeRender(function(i,s){Cl(s,e)},a.beforeRenderPriorities.animations):t()}},Ep={qualifierCompare:function(e,t){return e==null||t==null?e==null&&t==null:e.sameText(t)},eventMatches:function(e,t,a){var n=t.qualifier;return n!=null?e!==a.target&&Ia(a.target)&&n.matches(a.target):!0},addEventFields:function(e,t){t.cy=e,t.target=e},callbackContext:function(e,t,a){return t.qualifier!=null?a.target:e}},tn=function(e){return ge(e)?new ft(e):e},tf={createEmitter:function(){var e=this._private;return e.emitter||(e.emitter=new Gn(Ep,this)),this},emitter:function(){return this._private.emitter},on:function(e,t,a){return this.emitter().on(e,tn(t),a),this},removeListener:function(e,t,a){return this.emitter().removeListener(e,tn(t),a),this},removeAllListeners:function(){return this.emitter().removeAllListeners(),this},one:function(e,t,a){return this.emitter().one(e,tn(t),a),this},once:function(e,t,a){return this.emitter().one(e,tn(t),a),this},emit:function(e,t){return this.emitter().emit(e,t),this},emitAndNotify:function(e,t){return this.emit(e),this.notify(e,t),this}};Fe.eventAliasesOn(tf);var zs={png:function(e){var t=this._private.renderer;return e=e||{},t.png(e)},jpg:function(e){var t=this._private.renderer;return e=e||{},e.bg=e.bg||"#fff",t.jpg(e)}};zs.jpeg=zs.jpg;var dn={layout:function(e){var t=this;if(e==null){$e("Layout options must be specified to make a layout");return}if(e.name==null){$e("A `name` must be specified to make a layout");return}var a=e.name,n=t.extension("layout",a);if(n==null){$e("No such layout `"+a+"` found. Did you forget to import it and `cytoscape.use()` it?");return}var i;ge(e.eles)?i=t.$(e.eles):i=e.eles!=null?e.eles:t.$();var s=new n(be({},e,{cy:t,eles:i}));return s}};dn.createLayout=dn.makeLayout=dn.layout;var Cp={notify:function(e,t){var a=this._private;if(this.batching()){a.batchNotifications=a.batchNotifications||{};var n=a.batchNotifications[e]=a.batchNotifications[e]||this.collection();t!=null&&n.merge(t);return}if(a.notificationsEnabled){var i=this.renderer();this.destroyed()||!i||i.notify(e,t)}},notifications:function(e){var t=this._private;return e===void 0?t.notificationsEnabled:(t.notificationsEnabled=!!e,this)},noNotifications:function(e){this.notifications(!1),e(),this.notifications(!0)},batching:function(){return this._private.batchCount>0},startBatch:function(){var e=this._private;return e.batchCount==null&&(e.batchCount=0),e.batchCount===0&&(e.batchStyleEles=this.collection(),e.batchNotifications={}),e.batchCount++,this},endBatch:function(){var e=this._private;if(e.batchCount===0)return this;if(e.batchCount--,e.batchCount===0){e.batchStyleEles.updateStyle();var t=this.renderer();Object.keys(e.batchNotifications).forEach(function(a){var n=e.batchNotifications[a];n.empty()?t.notify(a):t.notify(a,n)})}return this},batch:function(e){return this.startBatch(),e(),this.endBatch(),this},batchData:function(e){var t=this;return this.batch(function(){for(var a=Object.keys(e),n=0;n0;)t.removeChild(t.childNodes[0]);e._private.renderer=null,e.mutableElements().forEach(function(a){var n=a._private;n.rscratch={},n.rstyle={},n.animation.current=[],n.animation.queue=[]})},onRender:function(e){return this.on("render",e)},offRender:function(e){return this.off("render",e)}};Fs.invalidateDimensions=Fs.resize;var hn={collection:function(e,t){return ge(e)?this.$(e):Dr(e)?e.collection():_e(e)?(t||(t={}),new fr(this,e,t.unique,t.removed)):new fr(this)},nodes:function(e){var t=this.$(function(a){return a.isNode()});return e?t.filter(e):t},edges:function(e){var t=this.$(function(a){return a.isEdge()});return e?t.filter(e):t},$:function(e){var t=this._private.elements;return e?t.filter(e):t.spawnSelf()},mutableElements:function(){return this._private.elements}};hn.elements=hn.filter=hn.$;var ur={},wa="t",Sp="f";ur.apply=function(r){for(var e=this,t=e._private,a=t.cy,n=a.collection(),i=0;i0;if(c||f&&h){var d=void 0;c&&h||c?d=u.properties:h&&(d=u.mappedProperties);for(var y=0;y1&&(w=1),o.color){var C=a.valueMin[0],x=a.valueMax[0],T=a.valueMin[1],k=a.valueMax[1],D=a.valueMin[2],B=a.valueMax[2],P=a.valueMin[3]==null?1:a.valueMin[3],A=a.valueMax[3]==null?1:a.valueMax[3],R=[Math.round(C+(x-C)*w),Math.round(T+(k-T)*w),Math.round(D+(B-D)*w),Math.round(P+(A-P)*w)];i={bypass:a.bypass,name:a.name,value:R,strValue:"rgb("+R[0]+", "+R[1]+", "+R[2]+")"}}else if(o.number){var L=a.valueMin+(a.valueMax-a.valueMin)*w;i=this.parse(a.name,L,a.bypass,c)}else return!1;if(!i)return y(),!1;i.mapping=a,a=i;break}case s.data:{for(var I=a.field.split("."),M=f.data,O=0;O0&&i>0){for(var o={},l=!1,u=0;u0?r.delayAnimation(s).play().promise().then(b):b()}).then(function(){return r.animation({style:o,duration:i,easing:r.pstyle("transition-timing-function").value,queue:!1}).play().promise()}).then(function(){t.removeBypasses(r,n),r.emitAndNotify("style"),a.transitioning=!1})}else a.transitioning&&(this.removeBypasses(r,n),r.emitAndNotify("style"),a.transitioning=!1)};ur.checkTrigger=function(r,e,t,a,n,i){var s=this.properties[e],o=n(s);r.removed()||o!=null&&o(t,a,r)&&i(s)};ur.checkZOrderTrigger=function(r,e,t,a){var n=this;this.checkTrigger(r,e,t,a,function(i){return i.triggersZOrder},function(){n._private.cy.notify("zorder",r)})};ur.checkBoundsTrigger=function(r,e,t,a){this.checkTrigger(r,e,t,a,function(n){return n.triggersBounds},function(n){r.dirtyCompoundBoundsCache(),r.dirtyBoundingBoxCache()})};ur.checkConnectedEdgesBoundsTrigger=function(r,e,t,a){this.checkTrigger(r,e,t,a,function(n){return n.triggersBoundsOfConnectedEdges},function(n){r.connectedEdges().forEach(function(i){i.dirtyBoundingBoxCache()})})};ur.checkParallelEdgesBoundsTrigger=function(r,e,t,a){this.checkTrigger(r,e,t,a,function(n){return n.triggersBoundsOfParallelEdges},function(n){r.parallelEdges().forEach(function(i){i.dirtyBoundingBoxCache()})})};ur.checkTriggers=function(r,e,t,a){r.dirtyStyleCache(),this.checkZOrderTrigger(r,e,t,a),this.checkBoundsTrigger(r,e,t,a),this.checkConnectedEdgesBoundsTrigger(r,e,t,a),this.checkParallelEdgesBoundsTrigger(r,e,t,a)};var _a={};_a.applyBypass=function(r,e,t,a){var n=this,i=[],s=!0;if(e==="*"||e==="**"){if(t!==void 0)for(var o=0;on.length?a=a.substr(n.length):a=""}function l(){i.length>s.length?i=i.substr(s.length):i=""}for(;;){var u=a.match(/^\s*$/);if(u)break;var v=a.match(/^\s*((?:.|\s)+?)\s*\{((?:.|\s)+?)\}/);if(!v){Ve("Halting stylesheet parsing: String stylesheet contains more to parse but no selector and block found in: "+a);break}n=v[0];var f=v[1];if(f!=="core"){var c=new ft(f);if(c.invalid){Ve("Skipping parsing of block: Invalid selector found in string stylesheet: "+f),o();continue}}var h=v[2],d=!1;i=h;for(var y=[];;){var g=i.match(/^\s*$/);if(g)break;var p=i.match(/^\s*(.+?)\s*:\s*(.+?)(?:\s*;|\s*$)/);if(!p){Ve("Skipping parsing of block: Invalid formatting of style property and value definitions found in:"+h),d=!0;break}s=p[0];var m=p[1],b=p[2],w=e.properties[m];if(!w){Ve("Skipping property: Invalid property name in: "+s),l();continue}var E=t.parse(m,b);if(!E){Ve("Skipping property: Invalid property definition in: "+s),l();continue}y.push({name:m,val:b}),l()}if(d){o();break}t.selector(f);for(var C=0;C=7&&e[0]==="d"&&(v=new RegExp(o.data.regex).exec(e))){if(t)return!1;var c=o.data;return{name:r,value:v,strValue:""+e,mapped:c,field:v[1],bypass:t}}else if(e.length>=10&&e[0]==="m"&&(f=new RegExp(o.mapData.regex).exec(e))){if(t||u.multiple)return!1;var h=o.mapData;if(!(u.color||u.number))return!1;var d=this.parse(r,f[4]);if(!d||d.mapped)return!1;var y=this.parse(r,f[5]);if(!y||y.mapped)return!1;if(d.pfValue===y.pfValue||d.strValue===y.strValue)return Ve("`"+r+": "+e+"` is not a valid mapper because the output range is zero; converting to `"+r+": "+d.strValue+"`"),this.parse(r,d.strValue);if(u.color){var g=d.value,p=y.value,m=g[0]===p[0]&&g[1]===p[1]&&g[2]===p[2]&&(g[3]===p[3]||(g[3]==null||g[3]===1)&&(p[3]==null||p[3]===1));if(m)return!1}return{name:r,value:f,strValue:""+e,mapped:h,field:f[1],fieldMin:parseFloat(f[2]),fieldMax:parseFloat(f[3]),valueMin:d.value,valueMax:y.value,bypass:t}}}if(u.multiple&&a!=="multiple"){var b;if(l?b=e.split(/\s+/):_e(e)?b=e:b=[e],u.evenMultiple&&b.length%2!==0)return null;for(var w=[],E=[],C=[],x="",T=!1,k=0;k0?" ":"")+D.strValue}return u.validate&&!u.validate(w,E)?null:u.singleEnum&&T?w.length===1&&ge(w[0])?{name:r,value:w[0],strValue:w[0],bypass:t}:null:{name:r,value:w,pfValue:C,strValue:x,bypass:t,units:E}}var B=function(){for(var J=0;Ju.max||u.strictMax&&e===u.max))return null;var I={name:r,value:e,strValue:""+e+(P||""),units:P,bypass:t};return u.unitless||P!=="px"&&P!=="em"?I.pfValue=e:I.pfValue=P==="px"||!P?e:this.getEmSizeInPixels()*e,(P==="ms"||P==="s")&&(I.pfValue=P==="ms"?e:1e3*e),(P==="deg"||P==="rad")&&(I.pfValue=P==="rad"?e:Ed(e)),P==="%"&&(I.pfValue=e/100),I}else if(u.propList){var M=[],O=""+e;if(O!=="none"){for(var V=O.split(/\s*,\s*|\s+/),G=0;G0&&o>0&&!isNaN(a.w)&&!isNaN(a.h)&&a.w>0&&a.h>0){l=Math.min((s-2*t)/a.w,(o-2*t)/a.h),l=l>this._private.maxZoom?this._private.maxZoom:l,l=l=a.minZoom&&(a.maxZoom=t),this},minZoom:function(e){return e===void 0?this._private.minZoom:this.zoomRange({min:e})},maxZoom:function(e){return e===void 0?this._private.maxZoom:this.zoomRange({max:e})},getZoomedViewport:function(e){var t=this._private,a=t.pan,n=t.zoom,i,s,o=!1;if(t.zoomingEnabled||(o=!0),ae(e)?s=e:Le(e)&&(s=e.level,e.position!=null?i=On(e.position,n,a):e.renderedPosition!=null&&(i=e.renderedPosition),i!=null&&!t.panningEnabled&&(o=!0)),s=s>t.maxZoom?t.maxZoom:s,s=st.maxZoom||!t.zoomingEnabled?s=!0:(t.zoom=l,i.push("zoom"))}if(n&&(!s||!e.cancelOnFailedZoom)&&t.panningEnabled){var u=e.pan;ae(u.x)&&(t.pan.x=u.x,o=!1),ae(u.y)&&(t.pan.y=u.y,o=!1),o||i.push("pan")}return i.length>0&&(i.push("viewport"),this.emit(i.join(" ")),this.notify("viewport")),this},center:function(e){var t=this.getCenterPan(e);return t&&(this._private.pan=t,this.emit("pan viewport"),this.notify("viewport")),this},getCenterPan:function(e,t){if(this._private.panningEnabled){if(ge(e)){var a=e;e=this.mutableElements().filter(a)}else Dr(e)||(e=this.mutableElements());if(e.length!==0){var n=e.boundingBox(),i=this.width(),s=this.height();t=t===void 0?this._private.zoom:t;var o={x:(i-t*(n.x1+n.x2))/2,y:(s-t*(n.y1+n.y2))/2};return o}}},reset:function(){return!this._private.panningEnabled||!this._private.zoomingEnabled?this:(this.viewport({pan:{x:0,y:0},zoom:1}),this)},invalidateSize:function(){this._private.sizeCache=null},size:function(){var e=this._private,t=e.container,a=this;return e.sizeCache=e.sizeCache||(t?(function(){var n=a.window().getComputedStyle(t),i=function(o){return parseFloat(n.getPropertyValue(o))};return{width:t.clientWidth-i("padding-left")-i("padding-right"),height:t.clientHeight-i("padding-top")-i("padding-bottom")}})():{width:1,height:1})},width:function(){return this.size().width},height:function(){return this.size().height},extent:function(){var e=this._private.pan,t=this._private.zoom,a=this.renderedExtent(),n={x1:(a.x1-e.x)/t,x2:(a.x2-e.x)/t,y1:(a.y1-e.y)/t,y2:(a.y2-e.y)/t};return n.w=n.x2-n.x1,n.h=n.y2-n.y1,n},renderedExtent:function(){var e=this.width(),t=this.height();return{x1:0,y1:0,x2:e,y2:t,w:e,h:t}},multiClickDebounceTime:function(e){if(e)this._private.multiClickDebounceTime=e;else return this._private.multiClickDebounceTime;return this}};Rt.centre=Rt.center;Rt.autolockNodes=Rt.autolock;Rt.autoungrabifyNodes=Rt.autoungrabify;var Aa={data:Fe.data({field:"data",bindingEvent:"data",allowBinding:!0,allowSetting:!0,settingEvent:"data",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeData:Fe.removeData({field:"data",event:"data",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0}),scratch:Fe.data({field:"scratch",bindingEvent:"scratch",allowBinding:!0,allowSetting:!0,settingEvent:"scratch",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeScratch:Fe.removeData({field:"scratch",event:"scratch",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0})};Aa.attr=Aa.data;Aa.removeAttr=Aa.removeData;var Ra=function(e){var t=this;e=be({},e);var a=e.container;a&&!bn(a)&&bn(a[0])&&(a=a[0]);var n=a?a._cyreg:null;n=n||{},n&&n.cy&&(n.cy.destroy(),n={});var i=n.readies=n.readies||[];a&&(a._cyreg=n),n.cy=t;var s=rr!==void 0&&a!==void 0&&!e.headless,o=e;o.layout=be({name:s?"grid":"null"},o.layout),o.renderer=be({name:s?"canvas":"null"},o.renderer);var l=function(d,y,g){return y!==void 0?y:g!==void 0?g:d},u=this._private={container:a,ready:!1,options:o,elements:new fr(this),listeners:[],aniEles:new fr(this),data:o.data||{},scratch:{},layout:null,renderer:null,destroyed:!1,notificationsEnabled:!0,minZoom:1e-50,maxZoom:1e50,zoomingEnabled:l(!0,o.zoomingEnabled),userZoomingEnabled:l(!0,o.userZoomingEnabled),panningEnabled:l(!0,o.panningEnabled),userPanningEnabled:l(!0,o.userPanningEnabled),boxSelectionEnabled:l(!0,o.boxSelectionEnabled),autolock:l(!1,o.autolock,o.autolockNodes),autoungrabify:l(!1,o.autoungrabify,o.autoungrabifyNodes),autounselectify:l(!1,o.autounselectify),styleEnabled:o.styleEnabled===void 0?s:o.styleEnabled,zoom:ae(o.zoom)?o.zoom:1,pan:{x:Le(o.pan)&&ae(o.pan.x)?o.pan.x:0,y:Le(o.pan)&&ae(o.pan.y)?o.pan.y:0},animation:{current:[],queue:[]},hasCompoundNodes:!1,multiClickDebounceTime:l(250,o.multiClickDebounceTime)};this.createEmitter(),this.selectionType(o.selectionType),this.zoomRange({min:o.minZoom,max:o.maxZoom});var v=function(d,y){var g=d.some(pc);if(g)return ta.all(d).then(y);y(d)};u.styleEnabled&&t.setStyle([]);var f=be({},o,o.renderer);t.initRenderer(f);var c=function(d,y,g){t.notifications(!1);var p=t.mutableElements();p.length>0&&p.remove(),d!=null&&(Le(d)||_e(d))&&t.add(d),t.one("layoutready",function(b){t.notifications(!0),t.emit(b),t.one("load",y),t.emitAndNotify("load")}).one("layoutstop",function(){t.one("done",g),t.emit("done")});var m=be({},t._private.options.layout);m.eles=t.elements(),t.layout(m).run()};v([o.style,o.elements],function(h){var d=h[0],y=h[1];u.styleEnabled&&t.style().append(d),c(y,function(){t.startAnimationLoop(),u.ready=!0,Ue(o.ready)&&t.on("ready",o.ready);for(var g=0;g0,o=!!r.boundingBox,l=wr(o?r.boundingBox:structuredClone(e.extent())),u;if(Dr(r.roots))u=r.roots;else if(_e(r.roots)){for(var v=[],f=0;f0;){var R=A(),L=k(R,B);if(L)R.outgoers().filter(function(ye){return ye.isNode()&&t.has(ye)}).forEach(P);else if(L===null){Ve("Detected double maximal shift for node `"+R.id()+"`. Bailing maximal adjustment due to cycle. Use `options.maximal: true` only on DAGs.");break}}}var I=0;if(r.avoidOverlap)for(var M=0;M0&&p[0].length<=3?pe/2:0),Re=2*Math.PI/p[he].length*Ee;return he===0&&p[0].length===1&&(Se=1),{x:H.x+Se*Math.cos(Re),y:H.y+Se*Math.sin(Re)}}else{var Oe=p[he].length,Ne=Math.max(Oe===1?0:o?(l.w-r.padding*2-Y.w)/((r.grid?ce:Oe)-1):(l.w-r.padding*2-Y.w)/((r.grid?ce:Oe)+1),I),ze={x:H.x+(Ee+1-(Oe+1)/2)*Ne,y:H.y+(he+1-(K+1)/2)*te};return ze}},Ce={downward:0,leftward:90,upward:180,rightward:-90};Object.keys(Ce).indexOf(r.direction)===-1&&$e("Invalid direction '".concat(r.direction,"' specified for breadthfirst layout. Valid values are: ").concat(Object.keys(Ce).join(", ")));var we=function(ie){return $c(Ae(ie),l,Ce[r.direction])};return t.nodes().layoutPositions(this,r,we),this};var Ap={fit:!0,padding:30,boundingBox:void 0,avoidOverlap:!0,nodeDimensionsIncludeLabels:!1,spacingFactor:void 0,radius:void 0,startAngle:3/2*Math.PI,sweep:void 0,clockwise:!0,sort:void 0,animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function nf(r){this.options=be({},Ap,r)}nf.prototype.run=function(){var r=this.options,e=r,t=r.cy,a=e.eles,n=e.counterclockwise!==void 0?!e.counterclockwise:e.clockwise,i=a.nodes().not(":parent");e.sort&&(i=i.sort(e.sort));for(var s=wr(e.boundingBox?e.boundingBox:{x1:0,y1:0,w:t.width(),h:t.height()}),o={x:s.x1+s.w/2,y:s.y1+s.h/2},l=e.sweep===void 0?2*Math.PI-2*Math.PI/i.length:e.sweep,u=l/Math.max(1,i.length-1),v,f=0,c=0;c1&&e.avoidOverlap){f*=1.75;var p=Math.cos(u)-Math.cos(0),m=Math.sin(u)-Math.sin(0),b=Math.sqrt(f*f/(p*p+m*m));v=Math.max(b,v)}var w=function(C,x){var T=e.startAngle+x*u*(n?1:-1),k=v*Math.cos(T),D=v*Math.sin(T),B={x:o.x+k,y:o.y+D};return B};return a.nodes().layoutPositions(this,e,w),this};var Rp={fit:!0,padding:30,startAngle:3/2*Math.PI,sweep:void 0,clockwise:!0,equidistant:!1,minNodeSpacing:10,boundingBox:void 0,avoidOverlap:!0,nodeDimensionsIncludeLabels:!1,height:void 0,width:void 0,spacingFactor:void 0,concentric:function(e){return e.degree()},levelWidth:function(e){return e.maxDegree()/4},animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function sf(r){this.options=be({},Rp,r)}sf.prototype.run=function(){for(var r=this.options,e=r,t=e.counterclockwise!==void 0?!e.counterclockwise:e.clockwise,a=r.cy,n=e.eles,i=n.nodes().not(":parent"),s=wr(e.boundingBox?e.boundingBox:{x1:0,y1:0,w:a.width(),h:a.height()}),o={x:s.x1+s.w/2,y:s.y1+s.h/2},l=[],u=0,v=0;v0){var E=Math.abs(m[0].value-w.value);E>=g&&(m=[],p.push(m))}m.push(w)}var C=u+e.minNodeSpacing;if(!e.avoidOverlap){var x=p.length>0&&p[0].length>1,T=Math.min(s.w,s.h)/2-C,k=T/(p.length+x?1:0);C=Math.min(C,k)}for(var D=0,B=0;B1&&e.avoidOverlap){var L=Math.cos(R)-Math.cos(0),I=Math.sin(R)-Math.sin(0),M=Math.sqrt(C*C/(L*L+I*I));D=Math.max(M,D)}P.r=D,D+=C}if(e.equidistant){for(var O=0,V=0,G=0;G=r.numIter||(Fp(a,r),a.temperature=a.temperature*r.coolingFactor,a.temperature=r.animationThreshold&&i(),wn(v)}};v()}else{for(;u;)u=s(l),l++;kl(a,r),o()}return this};Kn.prototype.stop=function(){return this.stopped=!0,this.thread&&this.thread.stop(),this.emit("layoutstop"),this};Kn.prototype.destroy=function(){return this.thread&&this.thread.stop(),this};var Lp=function(e,t,a){for(var n=a.eles.edges(),i=a.eles.nodes(),s=wr(a.boundingBox?a.boundingBox:{x1:0,y1:0,w:e.width(),h:e.height()}),o={isCompound:e.hasCompoundNodes(),layoutNodes:[],idToIndex:{},nodeSize:i.size(),graphSet:[],indexToGraph:[],layoutEdges:[],edgeSize:n.size(),temperature:a.initialTemp,clientWidth:s.w,clientHeight:s.h,boundingBox:s},l=a.eles.components(),u={},v=0;v0){o.graphSet.push(T);for(var v=0;vn.count?0:n.graph},of=function(e,t,a,n){var i=n.graphSet[a];if(-10)var f=n.nodeOverlap*v,c=Math.sqrt(o*o+l*l),h=f*o/c,d=f*l/c;else var y=Dn(e,o,l),g=Dn(t,-1*o,-1*l),p=g.x-y.x,m=g.y-y.y,b=p*p+m*m,c=Math.sqrt(b),f=(e.nodeRepulsion+t.nodeRepulsion)/b,h=f*p/c,d=f*m/c;e.isLocked||(e.offsetX-=h,e.offsetY-=d),t.isLocked||(t.offsetX+=h,t.offsetY+=d)}},_p=function(e,t,a,n){if(a>0)var i=e.maxX-t.minX;else var i=t.maxX-e.minX;if(n>0)var s=e.maxY-t.minY;else var s=t.maxY-e.minY;return i>=0&&s>=0?Math.sqrt(i*i+s*s):0},Dn=function(e,t,a){var n=e.positionX,i=e.positionY,s=e.height||1,o=e.width||1,l=a/t,u=s/o,v={};return t===0&&0a?(v.x=n,v.y=i+s/2,v):0t&&-1*u<=l&&l<=u?(v.x=n-o/2,v.y=i-o*a/2/t,v):0=u)?(v.x=n+s*t/2/a,v.y=i+s/2,v):(0>a&&(l<=-1*u||l>=u)&&(v.x=n-s*t/2/a,v.y=i-s/2),v)},Gp=function(e,t){for(var a=0;aa){var g=t.gravity*h/y,p=t.gravity*d/y;c.offsetX+=g,c.offsetY+=p}}}}},Wp=function(e,t){var a=[],n=0,i=-1;for(a.push.apply(a,e.graphSet[0]),i+=e.graphSet[0].length;n<=i;){var s=a[n++],o=e.idToIndex[s],l=e.layoutNodes[o],u=l.children;if(0a)var i={x:a*e/n,y:a*t/n};else var i={x:e,y:t};return i},lf=function(e,t){var a=e.parentId;if(a!=null){var n=t.layoutNodes[t.idToIndex[a]],i=!1;if((n.maxX==null||e.maxX+n.padRight>n.maxX)&&(n.maxX=e.maxX+n.padRight,i=!0),(n.minX==null||e.minX-n.padLeftn.maxY)&&(n.maxY=e.maxY+n.padBottom,i=!0),(n.minY==null||e.minY-n.padTopp&&(d+=g+t.componentSpacing,h=0,y=0,g=0)}}},Kp={fit:!0,padding:30,boundingBox:void 0,avoidOverlap:!0,avoidOverlapPadding:10,nodeDimensionsIncludeLabels:!1,spacingFactor:void 0,condense:!1,rows:void 0,cols:void 0,position:function(e){},sort:void 0,animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function vf(r){this.options=be({},Kp,r)}vf.prototype.run=function(){var r=this.options,e=r,t=r.cy,a=e.eles,n=a.nodes().not(":parent");e.sort&&(n=n.sort(e.sort));var i=wr(e.boundingBox?e.boundingBox:{x1:0,y1:0,w:t.width(),h:t.height()});if(i.h===0||i.w===0)a.nodes().layoutPositions(this,e,function(U){return{x:i.x1,y:i.y1}});else{var s=n.size(),o=Math.sqrt(s*i.h/i.w),l=Math.round(o),u=Math.round(i.w/i.h*o),v=function(Q){if(Q==null)return Math.min(l,u);var K=Math.min(l,u);K==l?l=Q:u=Q},f=function(Q){if(Q==null)return Math.max(l,u);var K=Math.max(l,u);K==l?l=Q:u=Q},c=e.rows,h=e.cols!=null?e.cols:e.columns;if(c!=null&&h!=null)l=c,u=h;else if(c!=null&&h==null)l=c,u=Math.ceil(s/l);else if(c==null&&h!=null)u=h,l=Math.ceil(s/u);else if(u*l>s){var d=v(),y=f();(d-1)*y>=s?v(d-1):(y-1)*d>=s&&f(y-1)}else for(;u*l=s?f(p+1):v(g+1)}var m=i.w/u,b=i.h/l;if(e.condense&&(m=0,b=0),e.avoidOverlap)for(var w=0;w=u&&(L=0,R++)},M={},O=0;O(L=Nd(r,e,I[M],I[M+1],I[M+2],I[M+3])))return g(x,L),!0}else if(k.edgeType==="bezier"||k.edgeType==="multibezier"||k.edgeType==="self"||k.edgeType==="compound"){for(var I=k.allpts,M=0;M+5(L=Od(r,e,I[M],I[M+1],I[M+2],I[M+3],I[M+4],I[M+5])))return g(x,L),!0}for(var O=O||T.source,V=V||T.target,G=n.getArrowWidth(D,B),N=[{name:"source",x:k.arrowStartX,y:k.arrowStartY,angle:k.srcArrowAngle},{name:"target",x:k.arrowEndX,y:k.arrowEndY,angle:k.tgtArrowAngle},{name:"mid-source",x:k.midX,y:k.midY,angle:k.midsrcArrowAngle},{name:"mid-target",x:k.midX,y:k.midY,angle:k.midtgtArrowAngle}],M=0;M0&&(p(O),p(V))}function b(x,T,k){return Tr(x,T,k)}function w(x,T){var k=x._private,D=c,B;T?B=T+"-":B="",x.boundingBox();var P=k.labelBounds[T||"main"],A=x.pstyle(B+"label").value,R=x.pstyle("text-events").strValue==="yes";if(!(!R||!A)){var L=b(k.rscratch,"labelX",T),I=b(k.rscratch,"labelY",T),M=b(k.rscratch,"labelAngle",T),O=x.pstyle(B+"text-margin-x").pfValue,V=x.pstyle(B+"text-margin-y").pfValue,G=P.x1-D-O,N=P.x2+D-O,F=P.y1-D-V,U=P.y2+D-V;if(M){var Q=Math.cos(M),K=Math.sin(M),j=function(Y,te){return Y=Y-L,te=te-I,{x:Y*Q-te*K+L,y:Y*K+te*Q+I}},re=j(G,F),ne=j(G,U),J=j(N,F),z=j(N,U),q=[re.x+O,re.y+V,J.x+O,J.y+V,z.x+O,z.y+V,ne.x+O,ne.y+V];if(Sr(r,e,q))return g(x),!0}else if(nt(P,r,e))return g(x),!0}}for(var E=s.length-1;E>=0;E--){var C=s[E];C.isNode()?p(C)||w(C):m(C)||w(C)||w(C,"source")||w(C,"target")}return o};Lt.getAllInBox=function(r,e,t,a){var n=this.getCachedZSortedEles().interactive,i=this.cy.zoom(),s=2/i,o=[],l=Math.min(r,t),u=Math.max(r,t),v=Math.min(e,a),f=Math.max(e,a);r=l,t=u,e=v,a=f;var c=wr({x1:r,y1:e,x2:t,y2:a}),h=[{x:c.x1,y:c.y1},{x:c.x2,y:c.y1},{x:c.x2,y:c.y2},{x:c.x1,y:c.y2}],d=[[h[0],h[1]],[h[1],h[2]],[h[2],h[3]],[h[3],h[0]]];function y(Y,te,ce){return Tr(Y,te,ce)}function g(Y,te){var ce=Y._private,Ae=s,Ce="";Y.boundingBox();var we=ce.labelBounds.main;if(!we)return null;var ye=y(ce.rscratch,"labelX",te),ie=y(ce.rscratch,"labelY",te),de=y(ce.rscratch,"labelAngle",te),he=Y.pstyle(Ce+"text-margin-x").pfValue,Ee=Y.pstyle(Ce+"text-margin-y").pfValue,pe=we.x1-Ae-he,Se=we.x2+Ae-he,Re=we.y1-Ae-Ee,Oe=we.y2+Ae-Ee;if(de){var Ne=Math.cos(de),ze=Math.sin(de),xe=function(X,S){return X=X-ye,S=S-ie,{x:X*Ne-S*ze+ye,y:X*ze+S*Ne+ie}};return[xe(pe,Re),xe(Se,Re),xe(Se,Oe),xe(pe,Oe)]}else return[{x:pe,y:Re},{x:Se,y:Re},{x:Se,y:Oe},{x:pe,y:Oe}]}function p(Y,te,ce,Ae){function Ce(we,ye,ie){return(ie.y-we.y)*(ye.x-we.x)>(ye.y-we.y)*(ie.x-we.x)}return Ce(Y,ce,Ae)!==Ce(te,ce,Ae)&&Ce(Y,te,ce)!==Ce(Y,te,Ae)}for(var m=0;m0?-(Math.PI-e.ang):Math.PI+e.ang},jp=function(e,t,a,n,i){if(e!==Rl?Ml(t,e,Vr):Jp(Pr,Vr),Ml(t,a,Pr),Pl=Vr.nx*Pr.ny-Vr.ny*Pr.nx,Al=Vr.nx*Pr.nx-Vr.ny*-Pr.ny,Ur=Math.asin(Math.max(-1,Math.min(1,Pl))),Math.abs(Ur)<1e-6){Vs=t.x,qs=t.y,Tt=qt=0;return}kt=1,gn=!1,Al<0?Ur<0?Ur=Math.PI+Ur:(Ur=Math.PI-Ur,kt=-1,gn=!0):Ur>0&&(kt=-1,gn=!0),t.radius!==void 0?qt=t.radius:qt=n,wt=Ur/2,an=Math.min(Vr.len/2,Pr.len/2),i?(zr=Math.abs(Math.cos(wt)*qt/Math.sin(wt)),zr>an?(zr=an,Tt=Math.abs(zr*Math.sin(wt)/Math.cos(wt))):Tt=qt):(zr=Math.min(an,qt),Tt=Math.abs(zr*Math.sin(wt)/Math.cos(wt))),_s=t.x+Pr.nx*zr,Gs=t.y+Pr.ny*zr,Vs=_s-Pr.ny*Tt*kt,qs=Gs+Pr.nx*Tt*kt,hf=t.x+Vr.nx*zr,gf=t.y+Vr.ny*zr,Rl=t};function pf(r,e){e.radius===0?r.lineTo(e.cx,e.cy):r.arc(e.cx,e.cy,e.radius,e.startAngle,e.endAngle,e.counterClockwise)}function po(r,e,t,a){var n=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0;return a===0||e.radius===0?{cx:e.x,cy:e.y,radius:0,startX:e.x,startY:e.y,stopX:e.x,stopY:e.y,startAngle:void 0,endAngle:void 0,counterClockwise:void 0}:(jp(r,e,t,a,n),{cx:Vs,cy:qs,radius:Tt,startX:hf,startY:gf,stopX:_s,stopY:Gs,startAngle:Vr.ang+Math.PI/2*kt,endAngle:Pr.ang-Math.PI/2*kt,counterClockwise:gn})}var Ma=.01,ey=Math.sqrt(2*Ma),yr={};yr.findMidptPtsEtc=function(r,e){var t=e.posPts,a=e.intersectionPts,n=e.vectorNormInverse,i,s=r.pstyle("source-endpoint"),o=r.pstyle("target-endpoint"),l=s.units!=null&&o.units!=null,u=function(E,C,x,T){var k=T-C,D=x-E,B=Math.sqrt(D*D+k*k);return{x:-k/B,y:D/B}},v=r.pstyle("edge-distances").value;switch(v){case"node-position":i=t;break;case"intersection":i=a;break;case"endpoints":{if(l){var f=this.manualEndptToPx(r.source()[0],s),c=Je(f,2),h=c[0],d=c[1],y=this.manualEndptToPx(r.target()[0],o),g=Je(y,2),p=g[0],m=g[1],b={x1:h,y1:d,x2:p,y2:m};n=u(h,d,p,m),i=b}else Ve("Edge ".concat(r.id()," has edge-distances:endpoints specified without manual endpoints specified via source-endpoint and target-endpoint. Falling back on edge-distances:intersection (default).")),i=a;break}}return{midptPts:i,vectorNormInverse:n}};yr.findHaystackPoints=function(r){for(var e=0;e0?Math.max(S-_,0):Math.min(S+_,0)},A=P(D,T),R=P(B,k),L=!1;m===u?p=Math.abs(A)>Math.abs(R)?n:a:m===l||m===o?(p=a,L=!0):(m===i||m===s)&&(p=n,L=!0);var I=p===a,M=I?R:A,O=I?B:D,V=to(O),G=!1;!(L&&(w||C))&&(m===o&&O<0||m===l&&O>0||m===i&&O>0||m===s&&O<0)&&(V*=-1,M=V*Math.abs(M),G=!0);var N;if(w){var F=E<0?1+E:E;N=F*M}else{var U=E<0?M:0;N=U+E*V}var Q=function(S){return Math.abs(S)=Math.abs(M)},K=Q(N),j=Q(Math.abs(M)-Math.abs(N)),re=K||j;if(re&&!G)if(I){var ne=Math.abs(O)<=c/2,J=Math.abs(D)<=h/2;if(ne){var z=(v.x1+v.x2)/2,q=v.y1,H=v.y2;t.segpts=[z,q,z,H]}else if(J){var Y=(v.y1+v.y2)/2,te=v.x1,ce=v.x2;t.segpts=[te,Y,ce,Y]}else t.segpts=[v.x1,v.y2]}else{var Ae=Math.abs(O)<=f/2,Ce=Math.abs(B)<=d/2;if(Ae){var we=(v.y1+v.y2)/2,ye=v.x1,ie=v.x2;t.segpts=[ye,we,ie,we]}else if(Ce){var de=(v.x1+v.x2)/2,he=v.y1,Ee=v.y2;t.segpts=[de,he,de,Ee]}else t.segpts=[v.x2,v.y1]}else if(I){var pe=v.y1+N+(g?c/2*V:0),Se=v.x1,Re=v.x2;t.segpts=[Se,pe,Re,pe]}else{var Oe=v.x1+N+(g?f/2*V:0),Ne=v.y1,ze=v.y2;t.segpts=[Oe,Ne,Oe,ze]}if(t.isRound){var xe=r.pstyle("taxi-radius").value,ue=r.pstyle("radius-type").value[0]==="arc-radius";t.radii=new Array(t.segpts.length/2).fill(xe),t.isArcRadius=new Array(t.segpts.length/2).fill(ue)}};yr.tryToCorrectInvalidPoints=function(r,e){var t=r._private.rscratch;if(t.edgeType==="bezier"){var a=e.srcPos,n=e.tgtPos,i=e.srcW,s=e.srcH,o=e.tgtW,l=e.tgtH,u=e.srcShape,v=e.tgtShape,f=e.srcCornerRadius,c=e.tgtCornerRadius,h=e.srcRs,d=e.tgtRs,y=!ae(t.startX)||!ae(t.startY),g=!ae(t.arrowStartX)||!ae(t.arrowStartY),p=!ae(t.endX)||!ae(t.endY),m=!ae(t.arrowEndX)||!ae(t.arrowEndY),b=3,w=this.getArrowWidth(r.pstyle("width").pfValue,r.pstyle("arrow-scale").value)*this.arrowShapeWidth,E=b*w,C=Pt({x:t.ctrlpts[0],y:t.ctrlpts[1]},{x:t.startX,y:t.startY}),x=CO.poolIndex()){var V=M;M=O,O=V}var G=A.srcPos=M.position(),N=A.tgtPos=O.position(),F=A.srcW=M.outerWidth(),U=A.srcH=M.outerHeight(),Q=A.tgtW=O.outerWidth(),K=A.tgtH=O.outerHeight(),j=A.srcShape=t.nodeShapes[e.getNodeShape(M)],re=A.tgtShape=t.nodeShapes[e.getNodeShape(O)],ne=A.srcCornerRadius=M.pstyle("corner-radius").value==="auto"?"auto":M.pstyle("corner-radius").pfValue,J=A.tgtCornerRadius=O.pstyle("corner-radius").value==="auto"?"auto":O.pstyle("corner-radius").pfValue,z=A.tgtRs=O._private.rscratch,q=A.srcRs=M._private.rscratch;A.dirCounts={north:0,west:0,south:0,east:0,northwest:0,southwest:0,northeast:0,southeast:0};for(var H=0;H=ey||(Re=Math.sqrt(Math.max(Se*Se,Ma)+Math.max(pe*pe,Ma)));var Oe=A.vector={x:Se,y:pe},Ne=A.vectorNorm={x:Oe.x/Re,y:Oe.y/Re},ze={x:-Ne.y,y:Ne.x};A.nodesOverlap=!ae(Re)||re.checkPoint(we[0],we[1],0,Q,K,N.x,N.y,J,z)||j.checkPoint(ie[0],ie[1],0,F,U,G.x,G.y,ne,q),A.vectorNormInverse=ze,R={nodesOverlap:A.nodesOverlap,dirCounts:A.dirCounts,calculatedIntersection:!0,hasBezier:A.hasBezier,hasUnbundled:A.hasUnbundled,eles:A.eles,srcPos:N,srcRs:z,tgtPos:G,tgtRs:q,srcW:Q,srcH:K,tgtW:F,tgtH:U,srcIntn:de,tgtIntn:ye,srcShape:re,tgtShape:j,posPts:{x1:Ee.x2,y1:Ee.y2,x2:Ee.x1,y2:Ee.y1},intersectionPts:{x1:he.x2,y1:he.y2,x2:he.x1,y2:he.y1},vector:{x:-Oe.x,y:-Oe.y},vectorNorm:{x:-Ne.x,y:-Ne.y},vectorNormInverse:{x:-ze.x,y:-ze.y}}}var xe=Ce?R:A;te.nodesOverlap=xe.nodesOverlap,te.srcIntn=xe.srcIntn,te.tgtIntn=xe.tgtIntn,te.isRound=ce.startsWith("round"),n&&(M.isParent()||M.isChild()||O.isParent()||O.isChild())&&(M.parents().anySame(O)||O.parents().anySame(M)||M.same(O)&&M.isParent())?e.findCompoundLoopPoints(Y,xe,H,Ae):M===O?e.findLoopPoints(Y,xe,H,Ae):ce.endsWith("segments")?e.findSegmentsPoints(Y,xe):ce.endsWith("taxi")?e.findTaxiPoints(Y,xe):ce==="straight"||!Ae&&A.eles.length%2===1&&H===Math.floor(A.eles.length/2)?e.findStraightEdgePoints(Y):e.findBezierPoints(Y,xe,H,Ae,Ce),e.findEndpoints(Y),e.tryToCorrectInvalidPoints(Y,xe),e.checkForInvalidEdgeWarning(Y),e.storeAllpts(Y),e.storeEdgeProjections(Y),e.calculateArrowAngles(Y),e.recalculateEdgeLabelProjections(Y),e.calculateLabelAngles(Y)}},x=0;x0){var we=u,ye=Ct(we,Wt(s)),ie=Ct(we,Wt(Ce)),de=ye;if(ie2){var he=Ct(we,{x:Ce[2],y:Ce[3]});he0){var W=v,$=Ct(W,Wt(s)),Z=Ct(W,Wt(_)),oe=$;if(Z<$&&(s=[_[0],_[1]],oe=Z),_.length>2){var ee=Ct(W,{x:_[2],y:_[3]});ee=d||x){g={cp:w,segment:C};break}}if(g)break}var T=g.cp,k=g.segment,D=(d-p)/k.length,B=k.t1-k.t0,P=h?k.t0+B*D:k.t1-B*D;P=ka(0,P,1),e=Kt(T.p0,T.p1,T.p2,P),c=ty(T.p0,T.p1,T.p2,P);break}case"straight":case"segments":case"haystack":{for(var A=0,R,L,I,M,O=a.allpts.length,V=0;V+3=d));V+=2);var G=d-L,N=G/R;N=ka(0,N,1),e=Td(I,M,N),c=bf(I,M);break}}s("labelX",f,e.x),s("labelY",f,e.y),s("labelAutoAngle",f,c)}};u("source"),u("target"),this.applyLabelDimensions(r)}};Gr.applyLabelDimensions=function(r){this.applyPrefixedLabelDimensions(r),r.isEdge()&&(this.applyPrefixedLabelDimensions(r,"source"),this.applyPrefixedLabelDimensions(r,"target"))};Gr.applyPrefixedLabelDimensions=function(r,e){var t=r._private,a=this.getLabelText(r,e),n=Bt(a,r._private.labelDimsKey);if(Tr(t.rscratch,"prefixedLabelDimsKey",e)!==n){Kr(t.rscratch,"prefixedLabelDimsKey",e,n);var i=this.calculateLabelDimensions(r,a),s=r.pstyle("line-height").pfValue,o=r.pstyle("text-wrap").strValue,l=Tr(t.rscratch,"labelWrapCachedLines",e)||[],u=o!=="wrap"?1:Math.max(l.length,1),v=i.height/u,f=v*s,c=i.width,h=i.height+(u-1)*(s-1)*v;Kr(t.rstyle,"labelWidth",e,c),Kr(t.rscratch,"labelWidth",e,c),Kr(t.rstyle,"labelHeight",e,h),Kr(t.rscratch,"labelHeight",e,h),Kr(t.rscratch,"labelLineHeight",e,f)}};Gr.getLabelText=function(r,e){var t=r._private,a=e?e+"-":"",n=r.pstyle(a+"label").strValue,i=r.pstyle("text-transform").value,s=function(U,Q){return Q?(Kr(t.rscratch,U,e,Q),Q):Tr(t.rscratch,U,e)};if(!n)return"";i=="none"||(i=="uppercase"?n=n.toUpperCase():i=="lowercase"&&(n=n.toLowerCase()));var o=r.pstyle("text-wrap").value;if(o==="wrap"){var l=s("labelKey");if(l!=null&&s("labelWrapKey")===l)return s("labelWrapCachedText");for(var u="\u200B",v=n.split(` +`),f=r.pstyle("text-max-width").pfValue,c=r.pstyle("text-overflow-wrap").value,h=c==="anywhere",d=[],y=/[\s\u200b]+|$/g,g=0;gf){var E=p.matchAll(y),C="",x=0,T=kr(E),k;try{for(T.s();!(k=T.n()).done;){var D=k.value,B=D[0],P=p.substring(x,D.index);x=D.index+B.length;var A=C.length===0?P:C+P+B,R=this.calculateLabelDimensions(r,A),L=R.width;L<=f?C+=P+B:(C&&d.push(C),C=P+B)}}catch(F){T.e(F)}finally{T.f()}C.match(/^[\s\u200b]+$/)||d.push(C)}else d.push(p)}s("labelWrapCachedLines",d),n=s("labelWrapCachedText",d.join(` +`)),s("labelWrapKey",l)}else if(o==="ellipsis"){var I=r.pstyle("text-max-width").pfValue,M="",O="\u2026",V=!1;if(this.calculateLabelDimensions(r,n).widthI)break;M+=n[G],G===n.length-1&&(V=!0)}return V||(M+=O),M}return n};Gr.getLabelJustification=function(r){var e=r.pstyle("text-justification").strValue,t=r.pstyle("text-halign").strValue;if(e==="auto")if(r.isNode())switch(t){case"left":return"right";case"right":return"left";default:return"center"}else return"center";else return e};Gr.calculateLabelDimensions=function(r,e){var t=this,a=t.cy.window(),n=a.document,i=0,s=r.pstyle("font-style").strValue,o=r.pstyle("font-size").pfValue,l=r.pstyle("font-family").strValue,u=r.pstyle("font-weight").strValue,v=this.labelCalcCanvas,f=this.labelCalcCanvasContext;if(!v){v=this.labelCalcCanvas=n.createElement("canvas"),f=this.labelCalcCanvasContext=v.getContext("2d");var c=v.style;c.position="absolute",c.left="-9999px",c.top="-9999px",c.zIndex="-1",c.visibility="hidden",c.pointerEvents="none"}f.font="".concat(s," ").concat(u," ").concat(o,"px ").concat(l);for(var h=0,d=0,y=e.split(` +`),g=0;g1&&arguments[1]!==void 0?arguments[1]:!0;if(e.merge(s),o)for(var l=0;l=r.desktopTapThreshold2}var lr=i(S);je&&(r.hoverData.tapholdCancelled=!0);var jr=function(){var Br=r.hoverData.dragDelta=r.hoverData.dragDelta||[];Br.length===0?(Br.push(Pe[0]),Br.push(Pe[1])):(Br[0]+=Pe[0],Br[1]+=Pe[1])};W=!0,n(De,["mousemove","vmousemove","tapdrag"],S,{x:ee[0],y:ee[1]});var Ze=function(Br){return{originalEvent:S,type:Br,position:{x:ee[0],y:ee[1]}}},Wr=function(){r.data.bgActivePosistion=void 0,r.hoverData.selecting||$.emit(Ze("boxstart")),me[4]=1,r.hoverData.selecting=!0,r.redrawHint("select",!0),r.redraw()};if(r.hoverData.which===3){if(je){var $r=Ze("cxtdrag");fe?fe.emit($r):$.emit($r),r.hoverData.cxtDragged=!0,(!r.hoverData.cxtOver||De!==r.hoverData.cxtOver)&&(r.hoverData.cxtOver&&r.hoverData.cxtOver.emit(Ze("cxtdragout")),r.hoverData.cxtOver=De,De&&De.emit(Ze("cxtdragover")))}}else if(r.hoverData.dragging){if(W=!0,$.panningEnabled()&&$.userPanningEnabled()){var Ot;if(r.hoverData.justStartedPan){var $a=r.hoverData.mdownPos;Ot={x:(ee[0]-$a[0])*Z,y:(ee[1]-$a[1])*Z},r.hoverData.justStartedPan=!1}else Ot={x:Pe[0]*Z,y:Pe[1]*Z};$.panBy(Ot),$.emit(Ze("dragpan")),r.hoverData.dragged=!0}ee=r.projectIntoViewport(S.clientX,S.clientY)}else if(me[4]==1&&(fe==null||fe.pannable())){if(je){if(!r.hoverData.dragging&&$.boxSelectionEnabled()&&(lr||!$.panningEnabled()||!$.userPanningEnabled()))Wr();else if(!r.hoverData.selecting&&$.panningEnabled()&&$.userPanningEnabled()){var bt=s(fe,r.hoverData.downs);bt&&(r.hoverData.dragging=!0,r.hoverData.justStartedPan=!0,me[4]=0,r.data.bgActivePosistion=Wt(ve),r.redrawHint("select",!0),r.redraw())}fe&&fe.pannable()&&fe.active()&&fe.unactivate()}}else{if(fe&&fe.pannable()&&fe.active()&&fe.unactivate(),(!fe||!fe.grabbed())&&De!=Te&&(Te&&n(Te,["mouseout","tapdragout"],S,{x:ee[0],y:ee[1]}),De&&n(De,["mouseover","tapdragover"],S,{x:ee[0],y:ee[1]}),r.hoverData.last=De),fe)if(je){if($.boxSelectionEnabled()&&lr)fe&&fe.grabbed()&&(p(Be),fe.emit(Ze("freeon")),Be.emit(Ze("free")),r.dragData.didDrag&&(fe.emit(Ze("dragfreeon")),Be.emit(Ze("dragfree")))),Wr();else if(fe&&fe.grabbed()&&r.nodeIsDraggable(fe)){var Er=!r.dragData.didDrag;Er&&r.redrawHint("eles",!0),r.dragData.didDrag=!0,r.hoverData.draggingEles||y(Be,{inDragLayer:!0});var hr={x:0,y:0};if(ae(Pe[0])&&ae(Pe[1])&&(hr.x+=Pe[0],hr.y+=Pe[1],Er)){var Cr=r.hoverData.dragDelta;Cr&&ae(Cr[0])&&ae(Cr[1])&&(hr.x+=Cr[0],hr.y+=Cr[1])}r.hoverData.draggingEles=!0,Be.silentShift(hr).emit(Ze("position")).emit(Ze("drag")),r.redrawHint("drag",!0),r.redraw()}}else jr();W=!0}if(me[2]=ee[0],me[3]=ee[1],W)return S.stopPropagation&&S.stopPropagation(),S.preventDefault&&S.preventDefault(),!1}},!1);var P,A,R;r.registerBinding(e,"mouseup",function(S){if(!(r.hoverData.which===1&&S.which!==1&&r.hoverData.capture)){var _=r.hoverData.capture;if(_){r.hoverData.capture=!1;var W=r.cy,$=r.projectIntoViewport(S.clientX,S.clientY),Z=r.selection,oe=r.findNearestElement($[0],$[1],!0,!1),ee=r.dragData.possibleDragElements,ve=r.hoverData.down,le=i(S);r.data.bgActivePosistion&&(r.redrawHint("select",!0),r.redraw()),r.hoverData.tapholdCancelled=!0,r.data.bgActivePosistion=void 0,ve&&ve.unactivate();var me=function(Ke){return{originalEvent:S,type:Ke,position:{x:$[0],y:$[1]}}};if(r.hoverData.which===3){var De=me("cxttapend");if(ve?ve.emit(De):W.emit(De),!r.hoverData.cxtDragged){var Te=me("cxttap");ve?ve.emit(Te):W.emit(Te)}r.hoverData.cxtDragged=!1,r.hoverData.which=null}else if(r.hoverData.which===1){if(n(oe,["mouseup","tapend","vmouseup"],S,{x:$[0],y:$[1]}),!r.dragData.didDrag&&!r.hoverData.dragged&&!r.hoverData.selecting&&!r.hoverData.isOverThresholdDrag&&(n(ve,["click","tap","vclick"],S,{x:$[0],y:$[1]}),A=!1,S.timeStamp-R<=W.multiClickDebounceTime()?(P&&clearTimeout(P),A=!0,R=null,n(ve,["dblclick","dbltap","vdblclick"],S,{x:$[0],y:$[1]})):(P=setTimeout(function(){A||n(ve,["oneclick","onetap","voneclick"],S,{x:$[0],y:$[1]})},W.multiClickDebounceTime()),R=S.timeStamp)),ve==null&&!r.dragData.didDrag&&!r.hoverData.selecting&&!r.hoverData.dragged&&!i(S)&&(W.$(t).unselect(["tapunselect"]),ee.length>0&&r.redrawHint("eles",!0),r.dragData.possibleDragElements=ee=W.collection()),oe==ve&&!r.dragData.didDrag&&!r.hoverData.selecting&&oe!=null&&oe._private.selectable&&(r.hoverData.dragging||(W.selectionType()==="additive"||le?oe.selected()?oe.unselect(["tapunselect"]):oe.select(["tapselect"]):le||(W.$(t).unmerge(oe).unselect(["tapunselect"]),oe.select(["tapselect"]))),r.redrawHint("eles",!0)),r.hoverData.selecting){var fe=W.collection(r.getAllInBox(Z[0],Z[1],Z[2],Z[3]));r.redrawHint("select",!0),fe.length>0&&r.redrawHint("eles",!0),W.emit(me("boxend"));var Pe=function(Ke){return Ke.selectable()&&!Ke.selected()};W.selectionType()==="additive"||le||W.$(t).unmerge(fe).unselect(),fe.emit(me("box")).stdFilter(Pe).select().emit(me("boxselect")),r.redraw()}if(r.hoverData.dragging&&(r.hoverData.dragging=!1,r.redrawHint("select",!0),r.redrawHint("eles",!0),r.redraw()),!Z[4]){r.redrawHint("drag",!0),r.redrawHint("eles",!0);var Be=ve&&ve.grabbed();p(ee),Be&&(ve.emit(me("freeon")),ee.emit(me("free")),r.dragData.didDrag&&(ve.emit(me("dragfreeon")),ee.emit(me("dragfree"))))}}Z[4]=0,r.hoverData.down=null,r.hoverData.cxtStarted=!1,r.hoverData.draggingEles=!1,r.hoverData.selecting=!1,r.hoverData.isOverThresholdDrag=!1,r.dragData.didDrag=!1,r.hoverData.dragged=!1,r.hoverData.dragDelta=[],r.hoverData.mdownPos=null,r.hoverData.mdownGPos=null,r.hoverData.which=null}}},!1);var L=[],I=4,M,O=1e5,V=function(S,_){for(var W=0;W=I){var $=L;if(M=V($,5),!M){var Z=Math.abs($[0]);M=G($)&&Z>5}if(M)for(var oe=0;oe<$.length;oe++)O=Math.min(Math.abs($[oe]),O)}else L.push(W),_=!0;else M&&(O=Math.min(Math.abs(W),O));if(!r.scrollingPage){var ee=r.cy,ve=ee.zoom(),le=ee.pan(),me=r.projectIntoViewport(S.clientX,S.clientY),De=[me[0]*ve+le.x,me[1]*ve+le.y];if(r.hoverData.draggingEles||r.hoverData.dragging||r.hoverData.cxtStarted||k()){S.preventDefault();return}if(ee.panningEnabled()&&ee.userPanningEnabled()&&ee.zoomingEnabled()&&ee.userZoomingEnabled()){S.preventDefault(),r.data.wheelZooming=!0,clearTimeout(r.data.wheelTimeout),r.data.wheelTimeout=setTimeout(function(){r.data.wheelZooming=!1,r.redrawHint("eles",!0),r.redraw()},150);var Te;_&&Math.abs(W)>5&&(W=to(W)*5),Te=W/-250,M&&(Te/=O,Te*=3),Te=Te*r.wheelSensitivity;var fe=S.deltaMode===1;fe&&(Te*=33);var Pe=ee.zoom()*Math.pow(10,Te);S.type==="gesturechange"&&(Pe=r.gestureStartZoom*S.scale),ee.zoom({level:Pe,renderedPosition:{x:De[0],y:De[1]}}),ee.emit({type:S.type==="gesturechange"?"pinchzoom":"scrollzoom",originalEvent:S,position:{x:me[0],y:me[1]}})}}}};r.registerBinding(r.container,"wheel",N,!0),r.registerBinding(e,"scroll",function(S){r.scrollingPage=!0,clearTimeout(r.scrollingPageTimeout),r.scrollingPageTimeout=setTimeout(function(){r.scrollingPage=!1},250)},!0),r.registerBinding(r.container,"gesturestart",function(S){r.gestureStartZoom=r.cy.zoom(),r.hasTouchStarted||S.preventDefault()},!0),r.registerBinding(r.container,"gesturechange",function(X){r.hasTouchStarted||N(X)},!0),r.registerBinding(r.container,"mouseout",function(S){var _=r.projectIntoViewport(S.clientX,S.clientY);r.cy.emit({originalEvent:S,type:"mouseout",position:{x:_[0],y:_[1]}})},!1),r.registerBinding(r.container,"mouseover",function(S){var _=r.projectIntoViewport(S.clientX,S.clientY);r.cy.emit({originalEvent:S,type:"mouseover",position:{x:_[0],y:_[1]}})},!1);var F,U,Q,K,j,re,ne,J,z,q,H,Y,te,ce=function(S,_,W,$){return Math.sqrt((W-S)*(W-S)+($-_)*($-_))},Ae=function(S,_,W,$){return(W-S)*(W-S)+($-_)*($-_)},Ce;r.registerBinding(r.container,"touchstart",Ce=function(S){if(r.hasTouchStarted=!0,!!D(S)){b(),r.touchData.capture=!0,r.data.bgActivePosistion=void 0;var _=r.cy,W=r.touchData.now,$=r.touchData.earlier;if(S.touches[0]){var Z=r.projectIntoViewport(S.touches[0].clientX,S.touches[0].clientY);W[0]=Z[0],W[1]=Z[1]}if(S.touches[1]){var Z=r.projectIntoViewport(S.touches[1].clientX,S.touches[1].clientY);W[2]=Z[0],W[3]=Z[1]}if(S.touches[2]){var Z=r.projectIntoViewport(S.touches[2].clientX,S.touches[2].clientY);W[4]=Z[0],W[5]=Z[1]}var oe=function(lr){return{originalEvent:S,type:lr,position:{x:W[0],y:W[1]}}};if(S.touches[1]){r.touchData.singleTouchMoved=!0,p(r.dragData.touchDragEles);var ee=r.findContainerClientCoords();z=ee[0],q=ee[1],H=ee[2],Y=ee[3],F=S.touches[0].clientX-z,U=S.touches[0].clientY-q,Q=S.touches[1].clientX-z,K=S.touches[1].clientY-q,te=0<=F&&F<=H&&0<=Q&&Q<=H&&0<=U&&U<=Y&&0<=K&&K<=Y;var ve=_.pan(),le=_.zoom();j=ce(F,U,Q,K),re=Ae(F,U,Q,K),ne=[(F+Q)/2,(U+K)/2],J=[(ne[0]-ve.x)/le,(ne[1]-ve.y)/le];var me=200,De=me*me;if(re=1){for(var mr=r.touchData.startPosition=[null,null,null,null,null,null],Ye=0;Ye=r.touchTapThreshold2}if(_&&r.touchData.cxt){S.preventDefault();var Ye=S.touches[0].clientX-z,ir=S.touches[0].clientY-q,er=S.touches[1].clientX-z,lr=S.touches[1].clientY-q,jr=Ae(Ye,ir,er,lr),Ze=jr/re,Wr=150,$r=Wr*Wr,Ot=1.5,$a=Ot*Ot;if(Ze>=$a||jr>=$r){r.touchData.cxt=!1,r.data.bgActivePosistion=void 0,r.redrawHint("select",!0);var bt=le("cxttapend");r.touchData.start?(r.touchData.start.unactivate().emit(bt),r.touchData.start=null):$.emit(bt)}}if(_&&r.touchData.cxt){var bt=le("cxtdrag");r.data.bgActivePosistion=void 0,r.redrawHint("select",!0),r.touchData.start?r.touchData.start.emit(bt):$.emit(bt),r.touchData.start&&(r.touchData.start._private.grabbed=!1),r.touchData.cxtDragged=!0;var Er=r.findNearestElement(Z[0],Z[1],!0,!0);(!r.touchData.cxtOver||Er!==r.touchData.cxtOver)&&(r.touchData.cxtOver&&r.touchData.cxtOver.emit(le("cxtdragout")),r.touchData.cxtOver=Er,Er&&Er.emit(le("cxtdragover")))}else if(_&&S.touches[2]&&$.boxSelectionEnabled())S.preventDefault(),r.data.bgActivePosistion=void 0,this.lastThreeTouch=+new Date,r.touchData.selecting||$.emit(le("boxstart")),r.touchData.selecting=!0,r.touchData.didSelect=!0,W[4]=1,!W||W.length===0||W[0]===void 0?(W[0]=(Z[0]+Z[2]+Z[4])/3,W[1]=(Z[1]+Z[3]+Z[5])/3,W[2]=(Z[0]+Z[2]+Z[4])/3+1,W[3]=(Z[1]+Z[3]+Z[5])/3+1):(W[2]=(Z[0]+Z[2]+Z[4])/3,W[3]=(Z[1]+Z[3]+Z[5])/3),r.redrawHint("select",!0),r.redraw();else if(_&&S.touches[1]&&!r.touchData.didSelect&&$.zoomingEnabled()&&$.panningEnabled()&&$.userZoomingEnabled()&&$.userPanningEnabled()){S.preventDefault(),r.data.bgActivePosistion=void 0,r.redrawHint("select",!0);var hr=r.dragData.touchDragEles;if(hr){r.redrawHint("drag",!0);for(var Cr=0;Cr0&&!r.hoverData.draggingEles&&!r.swipePanning&&r.data.bgActivePosistion!=null&&(r.data.bgActivePosistion=void 0,r.redrawHint("select",!0),r.redraw())}},!1);var ye;r.registerBinding(e,"touchcancel",ye=function(S){var _=r.touchData.start;r.touchData.capture=!1,_&&_.unactivate()});var ie,de,he,Ee;if(r.registerBinding(e,"touchend",ie=function(S){var _=r.touchData.start,W=r.touchData.capture;if(W)S.touches.length===0&&(r.touchData.capture=!1),S.preventDefault();else return;var $=r.selection;r.swipePanning=!1,r.hoverData.draggingEles=!1;var Z=r.cy,oe=Z.zoom(),ee=r.touchData.now,ve=r.touchData.earlier;if(S.touches[0]){var le=r.projectIntoViewport(S.touches[0].clientX,S.touches[0].clientY);ee[0]=le[0],ee[1]=le[1]}if(S.touches[1]){var le=r.projectIntoViewport(S.touches[1].clientX,S.touches[1].clientY);ee[2]=le[0],ee[3]=le[1]}if(S.touches[2]){var le=r.projectIntoViewport(S.touches[2].clientX,S.touches[2].clientY);ee[4]=le[0],ee[5]=le[1]}var me=function($r){return{originalEvent:S,type:$r,position:{x:ee[0],y:ee[1]}}};_&&_.unactivate();var De;if(r.touchData.cxt){if(De=me("cxttapend"),_?_.emit(De):Z.emit(De),!r.touchData.cxtDragged){var Te=me("cxttap");_?_.emit(Te):Z.emit(Te)}r.touchData.start&&(r.touchData.start._private.grabbed=!1),r.touchData.cxt=!1,r.touchData.start=null,r.redraw();return}if(!S.touches[2]&&Z.boxSelectionEnabled()&&r.touchData.selecting){r.touchData.selecting=!1;var fe=Z.collection(r.getAllInBox($[0],$[1],$[2],$[3]));$[0]=void 0,$[1]=void 0,$[2]=void 0,$[3]=void 0,$[4]=0,r.redrawHint("select",!0),Z.emit(me("boxend"));var Pe=function($r){return $r.selectable()&&!$r.selected()};fe.emit(me("box")).stdFilter(Pe).select().emit(me("boxselect")),fe.nonempty()&&r.redrawHint("eles",!0),r.redraw()}if(_?.unactivate(),S.touches[2])r.data.bgActivePosistion=void 0,r.redrawHint("select",!0);else if(!S.touches[1]){if(!S.touches[0]){if(!S.touches[0]){r.data.bgActivePosistion=void 0,r.redrawHint("select",!0);var Be=r.dragData.touchDragEles;if(_!=null){var je=_._private.grabbed;p(Be),r.redrawHint("drag",!0),r.redrawHint("eles",!0),je&&(_.emit(me("freeon")),Be.emit(me("free")),r.dragData.didDrag&&(_.emit(me("dragfreeon")),Be.emit(me("dragfree")))),n(_,["touchend","tapend","vmouseup","tapdragout"],S,{x:ee[0],y:ee[1]}),_.unactivate(),r.touchData.start=null}else{var Ke=r.findNearestElement(ee[0],ee[1],!0,!0);n(Ke,["touchend","tapend","vmouseup","tapdragout"],S,{x:ee[0],y:ee[1]})}var mr=r.touchData.startPosition[0]-ee[0],Ye=mr*mr,ir=r.touchData.startPosition[1]-ee[1],er=ir*ir,lr=Ye+er,jr=lr*oe*oe;r.touchData.singleTouchMoved||(_||Z.$(":selected").unselect(["tapunselect"]),n(_,["tap","vclick"],S,{x:ee[0],y:ee[1]}),de=!1,S.timeStamp-Ee<=Z.multiClickDebounceTime()?(he&&clearTimeout(he),de=!0,Ee=null,n(_,["dbltap","vdblclick"],S,{x:ee[0],y:ee[1]})):(he=setTimeout(function(){de||n(_,["onetap","voneclick"],S,{x:ee[0],y:ee[1]})},Z.multiClickDebounceTime()),Ee=S.timeStamp)),_!=null&&!r.dragData.didDrag&&_._private.selectable&&jr"u"){var pe=[],Se=function(S){return{clientX:S.clientX,clientY:S.clientY,force:1,identifier:S.pointerId,pageX:S.pageX,pageY:S.pageY,radiusX:S.width/2,radiusY:S.height/2,screenX:S.screenX,screenY:S.screenY,target:S.target}},Re=function(S){return{event:S,touch:Se(S)}},Oe=function(S){pe.push(Re(S))},Ne=function(S){for(var _=0;_0)return F[0]}return null},d=Object.keys(c),y=0;y0?h:wv(i,s,e,t,a,n,o,l)},checkPoint:function(e,t,a,n,i,s,o,l){l=l==="auto"?vt(n,i):l;var u=2*l;if(Zr(e,t,this.points,s,o,n,i-u,[0,-1],a)||Zr(e,t,this.points,s,o,n-u,i,[0,-1],a))return!0;var v=n/2+2*a,f=i/2+2*a,c=[s-v,o-f,s-v,o,s+v,o,s+v,o-f];return!!(Sr(e,t,c)||Dt(e,t,u,u,s+n/2-l,o+i/2-l,a)||Dt(e,t,u,u,s-n/2+l,o+i/2-l,a))}}};Qr.registerNodeShapes=function(){var r=this.nodeShapes={},e=this;this.generateEllipse(),this.generatePolygon("triangle",br(3,0)),this.generateRoundPolygon("round-triangle",br(3,0)),this.generatePolygon("rectangle",br(4,0)),r.square=r.rectangle,this.generateRoundRectangle(),this.generateCutRectangle(),this.generateBarrel(),this.generateBottomRoundrectangle();{var t=[0,1,1,0,0,-1,-1,0];this.generatePolygon("diamond",t),this.generateRoundPolygon("round-diamond",t)}this.generatePolygon("pentagon",br(5,0)),this.generateRoundPolygon("round-pentagon",br(5,0)),this.generatePolygon("hexagon",br(6,0)),this.generateRoundPolygon("round-hexagon",br(6,0)),this.generatePolygon("heptagon",br(7,0)),this.generateRoundPolygon("round-heptagon",br(7,0)),this.generatePolygon("octagon",br(8,0)),this.generateRoundPolygon("round-octagon",br(8,0));var a=new Array(20);{var n=Ps(5,0),i=Ps(5,Math.PI/5),s=.5*(3-Math.sqrt(5));s*=1.57;for(var o=0;o=e.deqFastCost*w)break}else if(u){if(m>=e.deqCost*h||m>=e.deqAvgCost*c)break}else if(b>=e.deqNoDrawCost*ws)break;var E=e.deq(a,g,y);if(E.length>0)for(var C=0;C0&&(e.onDeqd(a,d),!u&&e.shouldRedraw(a,d,g,y)&&i())},o=e.priority||js;n.beforeRender(s,o(a))}}}},ny=(function(){function r(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:xn;ht(this,r),this.idsByKey=new Xr,this.keyForId=new Xr,this.cachesByLvl=new Xr,this.lvls=[],this.getKey=e,this.doesEleInvalidateKey=t}return gt(r,[{key:"getIdsFor",value:function(t){t==null&&$e("Can not get id list for null key");var a=this.idsByKey,n=this.idsByKey.get(t);return n||(n=new ra,a.set(t,n)),n}},{key:"addIdForKey",value:function(t,a){t!=null&&this.getIdsFor(t).add(a)}},{key:"deleteIdForKey",value:function(t,a){t!=null&&this.getIdsFor(t).delete(a)}},{key:"getNumberOfIdsForKey",value:function(t){return t==null?0:this.getIdsFor(t).size}},{key:"updateKeyMappingFor",value:function(t){var a=t.id(),n=this.keyForId.get(a),i=this.getKey(t);this.deleteIdForKey(n,a),this.addIdForKey(i,a),this.keyForId.set(a,i)}},{key:"deleteKeyMappingFor",value:function(t){var a=t.id(),n=this.keyForId.get(a);this.deleteIdForKey(n,a),this.keyForId.delete(a)}},{key:"keyHasChangedFor",value:function(t){var a=t.id(),n=this.keyForId.get(a),i=this.getKey(t);return n!==i}},{key:"isInvalid",value:function(t){return this.keyHasChangedFor(t)||this.doesEleInvalidateKey(t)}},{key:"getCachesAt",value:function(t){var a=this.cachesByLvl,n=this.lvls,i=a.get(t);return i||(i=new Xr,a.set(t,i),n.push(t)),i}},{key:"getCache",value:function(t,a){return this.getCachesAt(a).get(t)}},{key:"get",value:function(t,a){var n=this.getKey(t),i=this.getCache(n,a);return i!=null&&this.updateKeyMappingFor(t),i}},{key:"getForCachedKey",value:function(t,a){var n=this.keyForId.get(t.id()),i=this.getCache(n,a);return i}},{key:"hasCache",value:function(t,a){return this.getCachesAt(a).has(t)}},{key:"has",value:function(t,a){var n=this.getKey(t);return this.hasCache(n,a)}},{key:"setCache",value:function(t,a,n){n.key=t,this.getCachesAt(a).set(t,n)}},{key:"set",value:function(t,a,n){var i=this.getKey(t);this.setCache(i,a,n),this.updateKeyMappingFor(t)}},{key:"deleteCache",value:function(t,a){this.getCachesAt(a).delete(t)}},{key:"delete",value:function(t,a){var n=this.getKey(t);this.deleteCache(n,a)}},{key:"invalidateKey",value:function(t){var a=this;this.lvls.forEach(function(n){return a.deleteCache(t,n)})}},{key:"invalidate",value:function(t){var a=t.id(),n=this.keyForId.get(a);this.deleteKeyMappingFor(t);var i=this.doesEleInvalidateKey(t);return i&&this.invalidateKey(n),i||this.getNumberOfIdsForKey(n)===0}}])})(),Nl=25,nn=50,pn=-4,Hs=3,Sf=7.99,iy=8,sy=1024,oy=1024,uy=1024,ly=.2,vy=.8,fy=10,cy=.15,dy=.1,hy=.9,gy=.9,py=100,yy=1,Ut={dequeue:"dequeue",downscale:"downscale",highQuality:"highQuality"},my=cr({getKey:null,doesEleInvalidateKey:xn,drawElement:null,getBoundingBox:null,getRotationPoint:null,getRotationOffset:null,isVisible:dv,allowEdgeTxrCaching:!0,allowParentTxrCaching:!0}),ba=function(e,t){var a=this;a.renderer=e,a.onDequeues=[];var n=my(t);be(a,n),a.lookup=new ny(n.getKey,n.doesEleInvalidateKey),a.setupDequeueing()},nr=ba.prototype;nr.reasons=Ut;nr.getTextureQueue=function(r){var e=this;return e.eleImgCaches=e.eleImgCaches||{},e.eleImgCaches[r]=e.eleImgCaches[r]||[]};nr.getRetiredTextureQueue=function(r){var e=this,t=e.eleImgCaches.retired=e.eleImgCaches.retired||{},a=t[r]=t[r]||[];return a};nr.getElementQueue=function(){var r=this,e=r.eleCacheQueue=r.eleCacheQueue||new Va(function(t,a){return a.reqs-t.reqs});return e};nr.getElementKeyToQueue=function(){var r=this,e=r.eleKeyToCacheQueue=r.eleKeyToCacheQueue||{};return e};nr.getElement=function(r,e,t,a,n){var i=this,s=this.renderer,o=s.cy.zoom(),l=this.lookup;if(!e||e.w===0||e.h===0||isNaN(e.w)||isNaN(e.h)||!r.visible()||r.removed()||!i.allowEdgeTxrCaching&&r.isEdge()||!i.allowParentTxrCaching&&r.isParent())return null;if(a==null&&(a=Math.ceil(ro(o*t))),a=Sf||a>Hs)return null;var u=Math.pow(2,a),v=e.h*u,f=e.w*u,c=s.eleTextBiggerThanMin(r,u);if(!this.isVisible(r,c))return null;var h=l.get(r,a);if(h&&h.invalidated&&(h.invalidated=!1,h.texture.invalidatedWidth-=h.width),h)return h;var d;if(v<=Nl?d=Nl:v<=nn?d=nn:d=Math.ceil(v/nn)*nn,v>uy||f>oy)return null;var y=i.getTextureQueue(d),g=y[y.length-2],p=function(){return i.recycleTexture(d,f)||i.addTexture(d,f)};g||(g=y[y.length-1]),g||(g=p()),g.width-g.usedWidtha;B--)k=i.getElement(r,e,t,B,Ut.downscale);D()}else return i.queueElement(r,C.level-1),C;else{var P;if(!b&&!w&&!E)for(var A=a-1;A>=pn;A--){var R=l.get(r,A);if(R){P=R;break}}if(m(P))return i.queueElement(r,a),P;g.context.translate(g.usedWidth,0),g.context.scale(u,u),this.drawElement(g.context,r,e,c,!1),g.context.scale(1/u,1/u),g.context.translate(-g.usedWidth,0)}return h={x:g.usedWidth,texture:g,level:a,scale:u,width:f,height:v,scaledLabelShown:c},g.usedWidth+=Math.ceil(f+iy),g.eleCaches.push(h),l.set(r,a,h),i.checkTextureFullness(g),h};nr.invalidateElements=function(r){for(var e=0;e=ly*r.width&&this.retireTexture(r)};nr.checkTextureFullness=function(r){var e=this,t=e.getTextureQueue(r.height);r.usedWidth/r.width>vy&&r.fullnessChecks>=fy?lt(t,r):r.fullnessChecks++};nr.retireTexture=function(r){var e=this,t=r.height,a=e.getTextureQueue(t),n=this.lookup;lt(a,r),r.retired=!0;for(var i=r.eleCaches,s=0;s=e)return s.retired=!1,s.usedWidth=0,s.invalidatedWidth=0,s.fullnessChecks=0,eo(s.eleCaches),s.context.setTransform(1,0,0,1,0,0),s.context.clearRect(0,0,s.width,s.height),lt(n,s),a.push(s),s}};nr.queueElement=function(r,e){var t=this,a=t.getElementQueue(),n=t.getElementKeyToQueue(),i=this.getKey(r),s=n[i];if(s)s.level=Math.max(s.level,e),s.eles.merge(r),s.reqs++,a.updateItem(s);else{var o={eles:r.spawn().merge(r),level:e,reqs:1,key:i};a.push(o),n[i]=o}};nr.dequeue=function(r){for(var e=this,t=e.getElementQueue(),a=e.getElementKeyToQueue(),n=[],i=e.lookup,s=0;s0;s++){var o=t.pop(),l=o.key,u=o.eles[0],v=i.hasCache(u,o.level);if(a[l]=null,v)continue;n.push(o);var f=e.getBoundingBox(u);e.getElement(u,f,r,o.level,Ut.dequeue)}return n};nr.removeFromQueue=function(r){var e=this,t=e.getElementQueue(),a=e.getElementKeyToQueue(),n=this.getKey(r),i=a[n];i!=null&&(i.eles.length===1?(i.reqs=Js,t.updateItem(i),t.pop(),a[n]=null):i.eles.unmerge(r))};nr.onDequeue=function(r){this.onDequeues.push(r)};nr.offDequeue=function(r){lt(this.onDequeues,r)};nr.setupDequeueing=Tf.setupDequeueing({deqRedrawThreshold:py,deqCost:cy,deqAvgCost:dy,deqNoDrawCost:hy,deqFastCost:gy,deq:function(e,t,a){return e.dequeue(t,a)},onDeqd:function(e,t){for(var a=0;a=wy||t>Pn)return null}a.validateLayersElesOrdering(t,r);var l=a.layersByLevel,u=Math.pow(2,t),v=l[t]=l[t]||[],f,c=a.levelIsComplete(t,r),h,d=function(){var D=function(L){if(a.validateLayersElesOrdering(L,r),a.levelIsComplete(L,r))return h=l[L],!0},B=function(L){if(!h)for(var I=t+L;xa<=I&&I<=Pn&&!D(I);I+=L);};B(1),B(-1);for(var P=v.length-1;P>=0;P--){var A=v[P];A.invalid&<(v,A)}};if(!c)d();else return v;var y=function(){if(!f){f=wr();for(var D=0;DFl||A>Fl)return null;var R=P*A;if(R>By)return null;var L=a.makeLayer(f,t);if(B!=null){var I=v.indexOf(B)+1;v.splice(I,0,L)}else(D.insert===void 0||D.insert)&&v.unshift(L);return L};if(a.skipping&&!o)return null;for(var p=null,m=r.length/by,b=!o,w=0;w=m||!bv(p.bb,E.boundingBox()))&&(p=g({insert:!0,after:p}),!p))return null;h||b?a.queueLayer(p,E):a.drawEleInLayer(p,E,t,e),p.eles.push(E),x[t]=p}return h||(b?null:v)};dr.getEleLevelForLayerLevel=function(r,e){return r};dr.drawEleInLayer=function(r,e,t,a){var n=this,i=this.renderer,s=r.context,o=e.boundingBox();o.w===0||o.h===0||!e.visible()||(t=n.getEleLevelForLayerLevel(t,a),i.setImgSmoothing(s,!1),i.drawCachedElement(s,e,null,null,t,Py),i.setImgSmoothing(s,!0))};dr.levelIsComplete=function(r,e){var t=this,a=t.layersByLevel[r];if(!a||a.length===0)return!1;for(var n=0,i=0;i0||s.invalid)return!1;n+=s.eles.length}return n===e.length};dr.validateLayersElesOrdering=function(r,e){var t=this.layersByLevel[r];if(t)for(var a=0;a0){e=!0;break}}return e};dr.invalidateElements=function(r){var e=this;r.length!==0&&(e.lastInvalidationTime=Yr(),!(r.length===0||!e.haveLayers())&&e.updateElementsInLayers(r,function(a,n,i){e.invalidateLayer(a)}))};dr.invalidateLayer=function(r){if(this.lastInvalidationTime=Yr(),!r.invalid){var e=r.level,t=r.eles,a=this.layersByLevel[e];lt(a,r),r.elesQueue=[],r.invalid=!0,r.replacement&&(r.replacement.invalid=!0);for(var n=0;n3&&arguments[3]!==void 0?arguments[3]:!0,n=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,i=arguments.length>5&&arguments[5]!==void 0?arguments[5]:!0,s=this,o=e._private.rscratch;if(!(i&&!e.visible())&&!(o.badLine||o.allpts==null||isNaN(o.allpts[0]))){var l;t&&(l=t,r.translate(-l.x1,-l.y1));var u=i?e.pstyle("opacity").value:1,v=i?e.pstyle("line-opacity").value:1,f=e.pstyle("curve-style").value,c=e.pstyle("line-style").value,h=e.pstyle("width").pfValue,d=e.pstyle("line-cap").value,y=e.pstyle("line-outline-width").value,g=e.pstyle("line-outline-color").value,p=u*v,m=u*v,b=function(){var L=arguments.length>0&&arguments[0]!==void 0?arguments[0]:p;f==="straight-triangle"?(s.eleStrokeStyle(r,e,L),s.drawEdgeTrianglePath(e,r,o.allpts)):(r.lineWidth=h,r.lineCap=d,s.eleStrokeStyle(r,e,L),s.drawEdgePath(e,r,o.allpts,c),r.lineCap="butt")},w=function(){var L=arguments.length>0&&arguments[0]!==void 0?arguments[0]:p;if(r.lineWidth=h+y,r.lineCap=d,y>0)s.colorStrokeStyle(r,g[0],g[1],g[2],L);else{r.lineCap="butt";return}f==="straight-triangle"?s.drawEdgeTrianglePath(e,r,o.allpts):(s.drawEdgePath(e,r,o.allpts,c),r.lineCap="butt")},E=function(){n&&s.drawEdgeOverlay(r,e)},C=function(){n&&s.drawEdgeUnderlay(r,e)},x=function(){var L=arguments.length>0&&arguments[0]!==void 0?arguments[0]:m;s.drawArrowheads(r,e,L)},T=function(){s.drawElementText(r,e,null,a)};r.lineJoin="round";var k=e.pstyle("ghost").value==="yes";if(k){var D=e.pstyle("ghost-offset-x").pfValue,B=e.pstyle("ghost-offset-y").pfValue,P=e.pstyle("ghost-opacity").value,A=p*P;r.translate(D,B),b(A),x(A),r.translate(-D,-B)}else w();C(),b(),x(),E(),T(),t&&r.translate(l.x1,l.y1)}};var Bf=function(e){if(!["overlay","underlay"].includes(e))throw new Error("Invalid state");return function(t,a){if(a.visible()){var n=a.pstyle("".concat(e,"-opacity")).value;if(n!==0){var i=this,s=i.usePaths(),o=a._private.rscratch,l=a.pstyle("".concat(e,"-padding")).pfValue,u=2*l,v=a.pstyle("".concat(e,"-color")).value;t.lineWidth=u,o.edgeType==="self"&&!s?t.lineCap="butt":t.lineCap="round",i.colorStrokeStyle(t,v[0],v[1],v[2],n),i.drawEdgePath(a,t,o.allpts,"solid")}}}};Jr.drawEdgeOverlay=Bf("overlay");Jr.drawEdgeUnderlay=Bf("underlay");Jr.drawEdgePath=function(r,e,t,a){var n=r._private.rscratch,i=e,s,o=!1,l=this.usePaths(),u=r.pstyle("line-dash-pattern").pfValue,v=r.pstyle("line-dash-offset").pfValue;if(l){var f=t.join("$"),c=n.pathCacheKey&&n.pathCacheKey===f;c?(s=e=n.pathCache,o=!0):(s=e=new Path2D,n.pathCacheKey=f,n.pathCache=s)}if(i.setLineDash)switch(a){case"dotted":i.setLineDash([1,1]);break;case"dashed":i.setLineDash(u),i.lineDashOffset=v;break;case"solid":i.setLineDash([]);break}if(!o&&!n.badLine)switch(e.beginPath&&e.beginPath(),e.moveTo(t[0],t[1]),n.edgeType){case"bezier":case"self":case"compound":case"multibezier":for(var h=2;h+35&&arguments[5]!==void 0?arguments[5]:!0,s=this;if(a==null){if(i&&!s.eleTextBiggerThanMin(e))return}else if(a===!1)return;if(e.isNode()){var o=e.pstyle("label");if(!o||!o.value)return;var l=s.getLabelJustification(e);r.textAlign=l,r.textBaseline="bottom"}else{var u=e.element()._private.rscratch.badLine,v=e.pstyle("label"),f=e.pstyle("source-label"),c=e.pstyle("target-label");if(u||(!v||!v.value)&&(!f||!f.value)&&(!c||!c.value))return;r.textAlign="center",r.textBaseline="bottom"}var h=!t,d;t&&(d=t,r.translate(-d.x1,-d.y1)),n==null?(s.drawText(r,e,null,h,i),e.isEdge()&&(s.drawText(r,e,"source",h,i),s.drawText(r,e,"target",h,i))):s.drawText(r,e,n,h,i),t&&r.translate(d.x1,d.y1)};It.getFontCache=function(r){var e;this.fontCaches=this.fontCaches||[];for(var t=0;t2&&arguments[2]!==void 0?arguments[2]:!0,a=e.pstyle("font-style").strValue,n=e.pstyle("font-size").pfValue+"px",i=e.pstyle("font-family").strValue,s=e.pstyle("font-weight").strValue,o=t?e.effectiveOpacity()*e.pstyle("text-opacity").value:1,l=e.pstyle("text-outline-opacity").value*o,u=e.pstyle("color").value,v=e.pstyle("text-outline-color").value;r.font=a+" "+s+" "+n+" "+i,r.lineJoin="round",this.colorFillStyle(r,u[0],u[1],u[2],o),this.colorStrokeStyle(r,v[0],v[1],v[2],l)};function qy(r,e,t,a,n){var i=Math.min(a,n),s=i/2,o=e+a/2,l=t+n/2;r.beginPath(),r.arc(o,l,s,0,Math.PI*2),r.closePath()}function Gl(r,e,t,a,n){var i=arguments.length>5&&arguments[5]!==void 0?arguments[5]:5,s=Math.min(i,a/2,n/2);r.beginPath(),r.moveTo(e+s,t),r.lineTo(e+a-s,t),r.quadraticCurveTo(e+a,t,e+a,t+s),r.lineTo(e+a,t+n-s),r.quadraticCurveTo(e+a,t+n,e+a-s,t+n),r.lineTo(e+s,t+n),r.quadraticCurveTo(e,t+n,e,t+n-s),r.lineTo(e,t+s),r.quadraticCurveTo(e,t,e+s,t),r.closePath()}It.getTextAngle=function(r,e){var t,a=r._private,n=a.rscratch,i=e?e+"-":"",s=r.pstyle(i+"text-rotation");if(s.strValue==="autorotate"){var o=Tr(n,"labelAngle",e);t=r.isEdge()?o:0}else s.strValue==="none"?t=0:t=s.pfValue;return t};It.drawText=function(r,e,t){var a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!0,n=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,i=e._private,s=i.rscratch,o=n?e.effectiveOpacity():1;if(!(n&&(o===0||e.pstyle("text-opacity").value===0))){t==="main"&&(t=null);var l=Tr(s,"labelX",t),u=Tr(s,"labelY",t),v,f,c=this.getLabelText(e,t);if(c!=null&&c!==""&&!isNaN(l)&&!isNaN(u)){this.setupTextStyle(r,e,n);var h=t?t+"-":"",d=Tr(s,"labelWidth",t),y=Tr(s,"labelHeight",t),g=e.pstyle(h+"text-margin-x").pfValue,p=e.pstyle(h+"text-margin-y").pfValue,m=e.isEdge(),b=e.pstyle("text-halign").value,w=e.pstyle("text-valign").value;m&&(b="center",w="center"),l+=g,u+=p;var E;switch(a?E=this.getTextAngle(e,t):E=0,E!==0&&(v=l,f=u,r.translate(v,f),r.rotate(E),l=0,u=0),w){case"top":break;case"center":u+=y/2;break;case"bottom":u+=y;break}var C=e.pstyle("text-background-opacity").value,x=e.pstyle("text-border-opacity").value,T=e.pstyle("text-border-width").pfValue,k=e.pstyle("text-background-padding").pfValue,D=e.pstyle("text-background-shape").strValue,B=D==="round-rectangle"||D==="roundrectangle",P=D==="circle",A=2;if(C>0||T>0&&x>0){var R=r.fillStyle,L=r.strokeStyle,I=r.lineWidth,M=e.pstyle("text-background-color").value,O=e.pstyle("text-border-color").value,V=e.pstyle("text-border-style").value,G=C>0,N=T>0&&x>0,F=l-k;switch(b){case"left":F-=d;break;case"center":F-=d/2;break}var U=u-y-k,Q=d+2*k,K=y+2*k;if(G&&(r.fillStyle="rgba(".concat(M[0],",").concat(M[1],",").concat(M[2],",").concat(C*o,")")),N&&(r.strokeStyle="rgba(".concat(O[0],",").concat(O[1],",").concat(O[2],",").concat(x*o,")"),r.lineWidth=T,r.setLineDash))switch(V){case"dotted":r.setLineDash([1,1]);break;case"dashed":r.setLineDash([4,2]);break;case"double":r.lineWidth=T/4,r.setLineDash([]);break;case"solid":default:r.setLineDash([]);break}if(B?(r.beginPath(),Gl(r,F,U,Q,K,A)):P?(r.beginPath(),qy(r,F,U,Q,K)):(r.beginPath(),r.rect(F,U,Q,K)),G&&r.fill(),N&&r.stroke(),N&&V==="double"){var j=T/2;r.beginPath(),B?Gl(r,F+j,U+j,Q-2*j,K-2*j,A):r.rect(F+j,U+j,Q-2*j,K-2*j),r.stroke()}r.fillStyle=R,r.strokeStyle=L,r.lineWidth=I,r.setLineDash&&r.setLineDash([])}var re=2*e.pstyle("text-outline-width").pfValue;if(re>0&&(r.lineWidth=re),e.pstyle("text-wrap").value==="wrap"){var ne=Tr(s,"labelWrapCachedLines",t),J=Tr(s,"labelLineHeight",t),z=d/2,q=this.getLabelJustification(e);switch(q==="auto"||(b==="left"?q==="left"?l+=-d:q==="center"&&(l+=-z):b==="center"?q==="left"?l+=-z:q==="right"&&(l+=z):b==="right"&&(q==="center"?l+=z:q==="right"&&(l+=d))),w){case"top":u-=(ne.length-1)*J;break;case"center":case"bottom":u-=(ne.length-1)*J;break}for(var H=0;H0&&r.strokeText(ne[H],l,u),r.fillText(ne[H],l,u),u+=J}else re>0&&r.strokeText(c,l,u),r.fillText(c,l,u);E!==0&&(r.rotate(-E),r.translate(-v,-f))}}};var yt={};yt.drawNode=function(r,e,t){var a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!0,n=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,i=arguments.length>5&&arguments[5]!==void 0?arguments[5]:!0,s=this,o,l,u=e._private,v=u.rscratch,f=e.position();if(!(!ae(f.x)||!ae(f.y))&&!(i&&!e.visible())){var c=i?e.effectiveOpacity():1,h=s.usePaths(),d,y=!1,g=e.padding();o=e.width()+2*g,l=e.height()+2*g;var p;t&&(p=t,r.translate(-p.x1,-p.y1));for(var m=e.pstyle("background-image"),b=m.value,w=new Array(b.length),E=new Array(b.length),C=0,x=0;x0&&arguments[0]!==void 0?arguments[0]:A;s.eleFillStyle(r,e,ue)},J=function(){var ue=arguments.length>0&&arguments[0]!==void 0?arguments[0]:N;s.colorStrokeStyle(r,R[0],R[1],R[2],ue)},z=function(){var ue=arguments.length>0&&arguments[0]!==void 0?arguments[0]:K;s.colorStrokeStyle(r,U[0],U[1],U[2],ue)},q=function(ue,X,S,_){var W=s.nodePathCache=s.nodePathCache||[],$=cv(S==="polygon"?S+","+_.join(","):S,""+X,""+ue,""+re),Z=W[$],oe,ee=!1;return Z!=null?(oe=Z,ee=!0,v.pathCache=oe):(oe=new Path2D,W[$]=v.pathCache=oe),{path:oe,cacheHit:ee}},H=e.pstyle("shape").strValue,Y=e.pstyle("shape-polygon-points").pfValue;if(h){r.translate(f.x,f.y);var te=q(o,l,H,Y);d=te.path,y=te.cacheHit}var ce=function(){if(!y){var ue=f;h&&(ue={x:0,y:0}),s.nodeShapes[s.getNodeShape(e)].draw(d||r,ue.x,ue.y,o,l,re,v)}h?r.fill(d):r.fill()},Ae=function(){for(var ue=arguments.length>0&&arguments[0]!==void 0?arguments[0]:c,X=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,S=u.backgrounding,_=0,W=0;W0&&arguments[0]!==void 0?arguments[0]:!1,X=arguments.length>1&&arguments[1]!==void 0?arguments[1]:c;s.hasPie(e)&&(s.drawPie(r,e,X),ue&&(h||s.nodeShapes[s.getNodeShape(e)].draw(r,f.x,f.y,o,l,re,v)))},we=function(){var ue=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,X=arguments.length>1&&arguments[1]!==void 0?arguments[1]:c;s.hasStripe(e)&&(r.save(),h?r.clip(v.pathCache):(s.nodeShapes[s.getNodeShape(e)].draw(r,f.x,f.y,o,l,re,v),r.clip()),s.drawStripe(r,e,X),r.restore(),ue&&(h||s.nodeShapes[s.getNodeShape(e)].draw(r,f.x,f.y,o,l,re,v)))},ye=function(){var ue=arguments.length>0&&arguments[0]!==void 0?arguments[0]:c,X=(B>0?B:-B)*ue,S=B>0?0:255;B!==0&&(s.colorFillStyle(r,S,S,S,X),h?r.fill(d):r.fill())},ie=function(){if(P>0){if(r.lineWidth=P,r.lineCap=M,r.lineJoin=I,r.setLineDash)switch(L){case"dotted":r.setLineDash([1,1]);break;case"dashed":r.setLineDash(V),r.lineDashOffset=G;break;case"solid":case"double":r.setLineDash([]);break}if(O!=="center"){if(r.save(),r.lineWidth*=2,O==="inside")h?r.clip(d):r.clip();else{var ue=new Path2D;ue.rect(-o/2-P,-l/2-P,o+2*P,l+2*P),ue.addPath(d),r.clip(ue,"evenodd")}h?r.stroke(d):r.stroke(),r.restore()}else h?r.stroke(d):r.stroke();if(L==="double"){r.lineWidth=P/3;var X=r.globalCompositeOperation;r.globalCompositeOperation="destination-out",h?r.stroke(d):r.stroke(),r.globalCompositeOperation=X}r.setLineDash&&r.setLineDash([])}},de=function(){if(F>0){if(r.lineWidth=F,r.lineCap="butt",r.setLineDash)switch(Q){case"dotted":r.setLineDash([1,1]);break;case"dashed":r.setLineDash([4,2]);break;case"solid":case"double":r.setLineDash([]);break}var ue=f;h&&(ue={x:0,y:0});var X=s.getNodeShape(e),S=P;O==="inside"&&(S=0),O==="outside"&&(S*=2);var _=(o+S+(F+j))/o,W=(l+S+(F+j))/l,$=o*_,Z=l*W,oe=s.nodeShapes[X].points,ee;if(h){var ve=q($,Z,X,oe);ee=ve.path}if(X==="ellipse")s.drawEllipsePath(ee||r,ue.x,ue.y,$,Z);else if(["round-diamond","round-heptagon","round-hexagon","round-octagon","round-pentagon","round-polygon","round-triangle","round-tag"].includes(X)){var le=0,me=0,De=0;X==="round-diamond"?le=(S+j+F)*1.4:X==="round-heptagon"?(le=(S+j+F)*1.075,De=-(S/2+j+F)/35):X==="round-hexagon"?le=(S+j+F)*1.12:X==="round-pentagon"?(le=(S+j+F)*1.13,De=-(S/2+j+F)/15):X==="round-tag"?(le=(S+j+F)*1.12,me=(S/2+F+j)*.07):X==="round-triangle"&&(le=(S+j+F)*(Math.PI/2),De=-(S+j/2+F)/Math.PI),le!==0&&(_=(o+le)/o,$=o*_,["round-hexagon","round-tag"].includes(X)||(W=(l+le)/l,Z=l*W)),re=re==="auto"?Ev($,Z):re;for(var Te=$/2,fe=Z/2,Pe=re+(S+F+j)/2,Be=new Array(oe.length/2),je=new Array(oe.length/2),Ke=0;Ke0){if(n=n||a.position(),i==null||s==null){var h=a.padding();i=a.width()+2*h,s=a.height()+2*h}o.colorFillStyle(t,v[0],v[1],v[2],u),o.nodeShapes[f].draw(t,n.x,n.y,i+l*2,s+l*2,c),t.fill()}}}};yt.drawNodeOverlay=Pf("overlay");yt.drawNodeUnderlay=Pf("underlay");yt.hasPie=function(r){return r=r[0],r._private.hasPie};yt.hasStripe=function(r){return r=r[0],r._private.hasStripe};yt.drawPie=function(r,e,t,a){e=e[0],a=a||e.position();var n=e.cy().style(),i=e.pstyle("pie-size"),s=e.pstyle("pie-hole"),o=e.pstyle("pie-start-angle").pfValue,l=a.x,u=a.y,v=e.width(),f=e.height(),c=Math.min(v,f)/2,h,d=0,y=this.usePaths();if(y&&(l=0,u=0),i.units==="%"?c=c*i.pfValue:i.pfValue!==void 0&&(c=i.pfValue/2),s.units==="%"?h=c*s.pfValue:s.pfValue!==void 0&&(h=s.pfValue/2),!(h>=c))for(var g=1;g<=n.pieBackgroundN;g++){var p=e.pstyle("pie-"+g+"-background-size").value,m=e.pstyle("pie-"+g+"-background-color").value,b=e.pstyle("pie-"+g+"-background-opacity").value*t,w=p/100;w+d>1&&(w=1-d);var E=1.5*Math.PI+2*Math.PI*d;E+=o;var C=2*Math.PI*w,x=E+C;p===0||d>=1||d+w>1||(h===0?(r.beginPath(),r.moveTo(l,u),r.arc(l,u,c,E,x),r.closePath()):(r.beginPath(),r.arc(l,u,c,E,x),r.arc(l,u,h,x,E,!0),r.closePath()),this.colorFillStyle(r,m[0],m[1],m[2],b),r.fill(),d+=w)}};yt.drawStripe=function(r,e,t,a){e=e[0],a=a||e.position();var n=e.cy().style(),i=a.x,s=a.y,o=e.width(),l=e.height(),u=0,v=this.usePaths();r.save();var f=e.pstyle("stripe-direction").value,c=e.pstyle("stripe-size");switch(f){case"vertical":break;case"righward":r.rotate(-Math.PI/2);break}var h=o,d=l;c.units==="%"?(h=h*c.pfValue,d=d*c.pfValue):c.pfValue!==void 0&&(h=c.pfValue,d=c.pfValue),v&&(i=0,s=0),s-=h/2,i-=d/2;for(var y=1;y<=n.stripeBackgroundN;y++){var g=e.pstyle("stripe-"+y+"-background-size").value,p=e.pstyle("stripe-"+y+"-background-color").value,m=e.pstyle("stripe-"+y+"-background-opacity").value*t,b=g/100;b+u>1&&(b=1-u),!(g===0||u>=1||u+b>1)&&(r.beginPath(),r.rect(i,s+d*u,h,d*b),r.closePath(),this.colorFillStyle(r,p[0],p[1],p[2],m),r.fill(),u+=b)}r.restore()};var xr={},_y=100;xr.getPixelRatio=function(){var r=this.data.contexts[0];if(this.forcedPixelRatio!=null)return this.forcedPixelRatio;var e=this.cy.window(),t=r.backingStorePixelRatio||r.webkitBackingStorePixelRatio||r.mozBackingStorePixelRatio||r.msBackingStorePixelRatio||r.oBackingStorePixelRatio||r.backingStorePixelRatio||1;return(e.devicePixelRatio||1)/t};xr.paintCache=function(r){for(var e=this.paintCaches=this.paintCaches||[],t=!0,a,n=0;ne.minMbLowQualFrames&&(e.motionBlurPxRatio=e.mbPxRBlurry)),e.clearingMotionBlur&&(e.motionBlurPxRatio=1),e.textureDrawLastFrame&&!f&&(v[e.NODE]=!0,v[e.SELECT_BOX]=!0);var m=t.style(),b=t.zoom(),w=s!==void 0?s:b,E=t.pan(),C={x:E.x,y:E.y},x={zoom:b,pan:{x:E.x,y:E.y}},T=e.prevViewport,k=T===void 0||x.zoom!==T.zoom||x.pan.x!==T.pan.x||x.pan.y!==T.pan.y;!k&&!(y&&!d)&&(e.motionBlurPxRatio=1),o&&(C=o),w*=l,C.x*=l,C.y*=l;var D=e.getCachedZSortedEles();function B(J,z,q,H,Y){var te=J.globalCompositeOperation;J.globalCompositeOperation="destination-out",e.colorFillStyle(J,255,255,255,e.motionBlurTransparency),J.fillRect(z,q,H,Y),J.globalCompositeOperation=te}function P(J,z){var q,H,Y,te;!e.clearingMotionBlur&&(J===u.bufferContexts[e.MOTIONBLUR_BUFFER_NODE]||J===u.bufferContexts[e.MOTIONBLUR_BUFFER_DRAG])?(q={x:E.x*h,y:E.y*h},H=b*h,Y=e.canvasWidth*h,te=e.canvasHeight*h):(q=C,H=w,Y=e.canvasWidth,te=e.canvasHeight),J.setTransform(1,0,0,1,0,0),z==="motionBlur"?B(J,0,0,Y,te):!a&&(z===void 0||z)&&J.clearRect(0,0,Y,te),n||(J.translate(q.x,q.y),J.scale(H,H)),o&&J.translate(o.x,o.y),s&&J.scale(s,s)}if(f||(e.textureDrawLastFrame=!1),f){if(e.textureDrawLastFrame=!0,!e.textureCache){e.textureCache={},e.textureCache.bb=t.mutableElements().boundingBox(),e.textureCache.texture=e.data.bufferCanvases[e.TEXTURE_BUFFER];var A=e.data.bufferContexts[e.TEXTURE_BUFFER];A.setTransform(1,0,0,1,0,0),A.clearRect(0,0,e.canvasWidth*e.textureMult,e.canvasHeight*e.textureMult),e.render({forcedContext:A,drawOnlyNodeLayer:!0,forcedPxRatio:l*e.textureMult});var x=e.textureCache.viewport={zoom:t.zoom(),pan:t.pan(),width:e.canvasWidth,height:e.canvasHeight};x.mpan={x:(0-x.pan.x)/x.zoom,y:(0-x.pan.y)/x.zoom}}v[e.DRAG]=!1,v[e.NODE]=!1;var R=u.contexts[e.NODE],L=e.textureCache.texture,x=e.textureCache.viewport;R.setTransform(1,0,0,1,0,0),c?B(R,0,0,x.width,x.height):R.clearRect(0,0,x.width,x.height);var I=m.core("outside-texture-bg-color").value,M=m.core("outside-texture-bg-opacity").value;e.colorFillStyle(R,I[0],I[1],I[2],M),R.fillRect(0,0,x.width,x.height);var b=t.zoom();P(R,!1),R.clearRect(x.mpan.x,x.mpan.y,x.width/x.zoom/l,x.height/x.zoom/l),R.drawImage(L,x.mpan.x,x.mpan.y,x.width/x.zoom/l,x.height/x.zoom/l)}else e.textureOnViewport&&!a&&(e.textureCache=null);var O=t.extent(),V=e.pinching||e.hoverData.dragging||e.swipePanning||e.data.wheelZooming||e.hoverData.draggingEles||e.cy.animated(),G=e.hideEdgesOnViewport&&V,N=[];if(N[e.NODE]=!v[e.NODE]&&c&&!e.clearedForMotionBlur[e.NODE]||e.clearingMotionBlur,N[e.NODE]&&(e.clearedForMotionBlur[e.NODE]=!0),N[e.DRAG]=!v[e.DRAG]&&c&&!e.clearedForMotionBlur[e.DRAG]||e.clearingMotionBlur,N[e.DRAG]&&(e.clearedForMotionBlur[e.DRAG]=!0),v[e.NODE]||n||i||N[e.NODE]){var F=c&&!N[e.NODE]&&h!==1,R=a||(F?e.data.bufferContexts[e.MOTIONBLUR_BUFFER_NODE]:u.contexts[e.NODE]),U=c&&!F?"motionBlur":void 0;P(R,U),G?e.drawCachedNodes(R,D.nondrag,l,O):e.drawLayeredElements(R,D.nondrag,l,O),e.debug&&e.drawDebugPoints(R,D.nondrag),!n&&!c&&(v[e.NODE]=!1)}if(!i&&(v[e.DRAG]||n||N[e.DRAG])){var F=c&&!N[e.DRAG]&&h!==1,R=a||(F?e.data.bufferContexts[e.MOTIONBLUR_BUFFER_DRAG]:u.contexts[e.DRAG]);P(R,c&&!F?"motionBlur":void 0),G?e.drawCachedNodes(R,D.drag,l,O):e.drawCachedElements(R,D.drag,l,O),e.debug&&e.drawDebugPoints(R,D.drag),!n&&!c&&(v[e.DRAG]=!1)}if(this.drawSelectionRectangle(r,P),c&&h!==1){var Q=u.contexts[e.NODE],K=e.data.bufferCanvases[e.MOTIONBLUR_BUFFER_NODE],j=u.contexts[e.DRAG],re=e.data.bufferCanvases[e.MOTIONBLUR_BUFFER_DRAG],ne=function(z,q,H){z.setTransform(1,0,0,1,0,0),H||!p?z.clearRect(0,0,e.canvasWidth,e.canvasHeight):B(z,0,0,e.canvasWidth,e.canvasHeight);var Y=h;z.drawImage(q,0,0,e.canvasWidth*Y,e.canvasHeight*Y,0,0,e.canvasWidth,e.canvasHeight)};(v[e.NODE]||N[e.NODE])&&(ne(Q,K,N[e.NODE]),v[e.NODE]=!1),(v[e.DRAG]||N[e.DRAG])&&(ne(j,re,N[e.DRAG]),v[e.DRAG]=!1)}e.prevViewport=x,e.clearingMotionBlur&&(e.clearingMotionBlur=!1,e.motionBlurCleared=!0,e.motionBlur=!0),c&&(e.motionBlurTimeout=setTimeout(function(){e.motionBlurTimeout=null,e.clearedForMotionBlur[e.NODE]=!1,e.clearedForMotionBlur[e.DRAG]=!1,e.motionBlur=!1,e.clearingMotionBlur=!f,e.mbFrames=0,v[e.NODE]=!0,v[e.DRAG]=!0,e.redraw()},_y)),a||t.emit("render")};var ha;xr.drawSelectionRectangle=function(r,e){var t=this,a=t.cy,n=t.data,i=a.style(),s=r.drawOnlyNodeLayer,o=r.drawAllLayers,l=n.canvasNeedsRedraw,u=r.forcedContext;if(t.showFps||!s&&l[t.SELECT_BOX]&&!o){var v=u||n.contexts[t.SELECT_BOX];if(e(v),t.selection[4]==1&&(t.hoverData.selecting||t.touchData.selecting)){var f=t.cy.zoom(),c=i.core("selection-box-border-width").value/f;v.lineWidth=c,v.fillStyle="rgba("+i.core("selection-box-color").value[0]+","+i.core("selection-box-color").value[1]+","+i.core("selection-box-color").value[2]+","+i.core("selection-box-opacity").value+")",v.fillRect(t.selection[0],t.selection[1],t.selection[2]-t.selection[0],t.selection[3]-t.selection[1]),c>0&&(v.strokeStyle="rgba("+i.core("selection-box-border-color").value[0]+","+i.core("selection-box-border-color").value[1]+","+i.core("selection-box-border-color").value[2]+","+i.core("selection-box-opacity").value+")",v.strokeRect(t.selection[0],t.selection[1],t.selection[2]-t.selection[0],t.selection[3]-t.selection[1]))}if(n.bgActivePosistion&&!t.hoverData.selecting){var f=t.cy.zoom(),h=n.bgActivePosistion;v.fillStyle="rgba("+i.core("active-bg-color").value[0]+","+i.core("active-bg-color").value[1]+","+i.core("active-bg-color").value[2]+","+i.core("active-bg-opacity").value+")",v.beginPath(),v.arc(h.x,h.y,i.core("active-bg-size").pfValue/f,0,2*Math.PI),v.fill()}var d=t.lastRedrawTime;if(t.showFps&&d){d=Math.round(d);var y=Math.round(1e3/d),g="1 frame = "+d+" ms = "+y+" fps";if(v.setTransform(1,0,0,1,0,0),v.fillStyle="rgba(255, 0, 0, 0.75)",v.strokeStyle="rgba(255, 0, 0, 0.75)",v.font="30px Arial",!ha){var p=v.measureText(g);ha=p.actualBoundingBoxAscent}v.fillText(g,0,ha);var m=60;v.strokeRect(0,ha+10,250,20),v.fillRect(0,ha+10,250*Math.min(y/m,1),20)}o||(l[t.SELECT_BOX]=!1)}};function Hl(r,e,t){var a=r.createShader(e);if(r.shaderSource(a,t),r.compileShader(a),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error(r.getShaderInfoLog(a));return a}function Gy(r,e,t){var a=Hl(r,r.VERTEX_SHADER,e),n=Hl(r,r.FRAGMENT_SHADER,t),i=r.createProgram();if(r.attachShader(i,a),r.attachShader(i,n),r.linkProgram(i),!r.getProgramParameter(i,r.LINK_STATUS))throw new Error("Could not initialize shaders");return i}function Hy(r,e,t){t===void 0&&(t=e);var a=r.makeOffscreenCanvas(e,t),n=a.context=a.getContext("2d");return a.clear=function(){return n.clearRect(0,0,a.width,a.height)},a.clear(),a}function bo(r){var e=r.pixelRatio,t=r.cy.zoom(),a=r.cy.pan();return{zoom:t*e,pan:{x:a.x*e,y:a.y*e}}}function Wy(r){var e=r.pixelRatio,t=r.cy.zoom();return t*e}function $y(r,e,t,a,n){var i=a*t+e.x,s=n*t+e.y;return s=Math.round(r.canvasHeight-s),[i,s]}function Uy(r){return r.pstyle("background-fill").value!=="solid"||r.pstyle("background-image").strValue!=="none"?!1:r.pstyle("border-width").value===0||r.pstyle("border-opacity").value===0?!0:r.pstyle("border-style").value==="solid"}function Ky(r,e){if(r.length!==e.length)return!1;for(var t=0;t>0&255)/255,t[1]=(r>>8&255)/255,t[2]=(r>>16&255)/255,t[3]=(r>>24&255)/255,t}function Xy(r){return r[0]+(r[1]<<8)+(r[2]<<16)+(r[3]<<24)}function Yy(r,e){var t=r.createTexture();return t.buffer=function(a){r.bindTexture(r.TEXTURE_2D,t),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR_MIPMAP_NEAREST),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,a),r.generateMipmap(r.TEXTURE_2D),r.bindTexture(r.TEXTURE_2D,null)},t.deleteTexture=function(){r.deleteTexture(t)},t}function Af(r,e){switch(e){case"float":return[1,r.FLOAT,4];case"vec2":return[2,r.FLOAT,4];case"vec3":return[3,r.FLOAT,4];case"vec4":return[4,r.FLOAT,4];case"int":return[1,r.INT,4];case"ivec2":return[2,r.INT,4]}}function Rf(r,e,t){switch(e){case r.FLOAT:return new Float32Array(t);case r.INT:return new Int32Array(t)}}function Zy(r,e,t,a,n,i){switch(e){case r.FLOAT:return new Float32Array(t.buffer,i*a,n);case r.INT:return new Int32Array(t.buffer,i*a,n)}}function Qy(r,e,t,a){var n=Af(r,e),i=Je(n,2),s=i[0],o=i[1],l=Rf(r,o,a),u=r.createBuffer();return r.bindBuffer(r.ARRAY_BUFFER,u),r.bufferData(r.ARRAY_BUFFER,l,r.STATIC_DRAW),o===r.FLOAT?r.vertexAttribPointer(t,s,o,!1,0,0):o===r.INT&&r.vertexAttribIPointer(t,s,o,0,0),r.enableVertexAttribArray(t),r.bindBuffer(r.ARRAY_BUFFER,null),u}function Fr(r,e,t,a){var n=Af(r,t),i=Je(n,3),s=i[0],o=i[1],l=i[2],u=Rf(r,o,e*s),v=s*l,f=r.createBuffer();r.bindBuffer(r.ARRAY_BUFFER,f),r.bufferData(r.ARRAY_BUFFER,e*v,r.DYNAMIC_DRAW),r.enableVertexAttribArray(a),o===r.FLOAT?r.vertexAttribPointer(a,s,o,!1,v,0):o===r.INT&&r.vertexAttribIPointer(a,s,o,v,0),r.vertexAttribDivisor(a,1),r.bindBuffer(r.ARRAY_BUFFER,null);for(var c=new Array(e),h=0;hs&&(o=s/a,l=a*o,u=n*o),{scale:o,texW:l,texH:u}}},{key:"draw",value:function(t,a,n){var i=this;if(this.locked)throw new Error("can't draw, atlas is locked");var s=this.texSize,o=this.texRows,l=this.texHeight,u=this.getScale(a),v=u.scale,f=u.texW,c=u.texH,h=function(b,w){if(n&&w){var E=w.context,C=b.x,x=b.row,T=C,k=l*x;E.save(),E.translate(T,k),E.scale(v,v),n(E,a),E.restore()}},d=[null,null],y=function(){h(i.freePointer,i.canvas),d[0]={x:i.freePointer.x,y:i.freePointer.row*l,w:f,h:c},d[1]={x:i.freePointer.x+f,y:i.freePointer.row*l,w:0,h:c},i.freePointer.x+=f,i.freePointer.x==s&&(i.freePointer.x=0,i.freePointer.row++)},g=function(){var b=i.scratch,w=i.canvas;b.clear(),h({x:0,row:0},b);var E=s-i.freePointer.x,C=f-E,x=l;{var T=i.freePointer.x,k=i.freePointer.row*l,D=E;w.context.drawImage(b,0,0,D,x,T,k,D,x),d[0]={x:T,y:k,w:D,h:c}}{var B=E,P=(i.freePointer.row+1)*l,A=C;w&&w.context.drawImage(b,B,0,A,x,0,P,A,x),d[1]={x:0,y:P,w:A,h:c}}i.freePointer.x=C,i.freePointer.row++},p=function(){i.freePointer.x=0,i.freePointer.row++};if(this.freePointer.x+f<=s)y();else{if(this.freePointer.row>=o-1)return!1;this.freePointer.x===s?(p(),y()):this.enableWrapping?g():(p(),y())}return this.keyToLocation.set(t,d),this.needsBuffer=!0,d}},{key:"getOffsets",value:function(t){return this.keyToLocation.get(t)}},{key:"isEmpty",value:function(){return this.freePointer.x===0&&this.freePointer.row===0}},{key:"canFit",value:function(t){if(this.locked)return!1;var a=this.texSize,n=this.texRows,i=this.getScale(t),s=i.texW;return this.freePointer.x+s>a?this.freePointer.row1&&arguments[1]!==void 0?arguments[1]:{},i=n.forceRedraw,s=i===void 0?!1:i,o=n.filterEle,l=o===void 0?function(){return!0}:o,u=n.filterType,v=u===void 0?function(){return!0}:u,f=!1,c=!1,h=kr(t),d;try{for(h.s();!(d=h.n()).done;){var y=d.value;if(l(y)){var g=kr(this.renderTypes.values()),p;try{var m=function(){var w=p.value,E=w.type;if(v(E)){var C=a.collections.get(w.collection),x=w.getKey(y),T=Array.isArray(x)?x:[x];if(s)T.forEach(function(P){return C.markKeyForGC(P)}),c=!0;else{var k=w.getID?w.getID(y):y.id(),D=a._key(E,k),B=a.typeAndIdToKey.get(D);B!==void 0&&!Ky(T,B)&&(f=!0,a.typeAndIdToKey.delete(D),B.forEach(function(P){return C.markKeyForGC(P)}))}}};for(g.s();!(p=g.n()).done;)m()}catch(b){g.e(b)}finally{g.f()}}}}catch(b){h.e(b)}finally{h.f()}return c&&(this.gc(),f=!1),f}},{key:"gc",value:function(){var t=kr(this.collections.values()),a;try{for(t.s();!(a=t.n()).done;){var n=a.value;n.gc()}}catch(i){t.e(i)}finally{t.f()}}},{key:"getOrCreateAtlas",value:function(t,a,n,i){var s=this.renderTypes.get(a),o=this.collections.get(s.collection),l=!1,u=o.draw(i,n,function(c){s.drawClipped?(c.save(),c.beginPath(),c.rect(0,0,n.w,n.h),c.clip(),s.drawElement(c,t,n,!0,!0),c.restore()):s.drawElement(c,t,n,!0,!0),l=!0});if(l){var v=s.getID?s.getID(t):t.id(),f=this._key(a,v);this.typeAndIdToKey.has(f)?this.typeAndIdToKey.get(f).push(i):this.typeAndIdToKey.set(f,[i])}return u}},{key:"getAtlasInfo",value:function(t,a){var n=this,i=this.renderTypes.get(a),s=i.getKey(t),o=Array.isArray(s)?s:[s];return o.map(function(l){var u=i.getBoundingBox(t,l),v=n.getOrCreateAtlas(t,a,u,l),f=v.getOffsets(l),c=Je(f,2),h=c[0],d=c[1];return{atlas:v,tex:h,tex1:h,tex2:d,bb:u}})}},{key:"getDebugInfo",value:function(){var t=[],a=kr(this.collections),n;try{for(a.s();!(n=a.n()).done;){var i=Je(n.value,2),s=i[0],o=i[1],l=o.getCounts(),u=l.keyCount,v=l.atlasCount;t.push({type:s,keyCount:u,atlasCount:v})}}catch(f){a.e(f)}finally{a.f()}return t}}])})(),sm=(function(){function r(e){ht(this,r),this.globalOptions=e,this.atlasSize=e.webglTexSize,this.maxAtlasesPerBatch=e.webglTexPerBatch,this.batchAtlases=[]}return gt(r,[{key:"getMaxAtlasesPerBatch",value:function(){return this.maxAtlasesPerBatch}},{key:"getAtlasSize",value:function(){return this.atlasSize}},{key:"getIndexArray",value:function(){return Array.from({length:this.maxAtlasesPerBatch},function(t,a){return a})}},{key:"startBatch",value:function(){this.batchAtlases=[]}},{key:"getAtlasCount",value:function(){return this.batchAtlases.length}},{key:"getAtlases",value:function(){return this.batchAtlases}},{key:"canAddToCurrentBatch",value:function(t){return this.batchAtlases.length===this.maxAtlasesPerBatch?this.batchAtlases.includes(t):!0}},{key:"getAtlasIndexForBatch",value:function(t){var a=this.batchAtlases.indexOf(t);if(a<0){if(this.batchAtlases.length===this.maxAtlasesPerBatch)throw new Error("cannot add more atlases to batch");this.batchAtlases.push(t),a=this.batchAtlases.length-1}return a}}])})(),om=` + float circleSD(vec2 p, float r) { + return distance(vec2(0), p) - r; // signed distance + } +`,um=` + float rectangleSD(vec2 p, vec2 b) { + vec2 d = abs(p)-b; + return distance(vec2(0),max(d,0.0)) + min(max(d.x,d.y),0.0); + } +`,lm=` + float roundRectangleSD(vec2 p, vec2 b, vec4 cr) { + cr.xy = (p.x > 0.0) ? cr.xy : cr.zw; + cr.x = (p.y > 0.0) ? cr.x : cr.y; + vec2 q = abs(p) - b + cr.x; + return min(max(q.x, q.y), 0.0) + distance(vec2(0), max(q, 0.0)) - cr.x; + } +`,vm=` + float ellipseSD(vec2 p, vec2 ab) { + p = abs( p ); // symmetry + + // find root with Newton solver + vec2 q = ab*(p-ab); + float w = (q.x1.0) ? d : -d; + } +`,Ea={SCREEN:{name:"screen",screen:!0},PICKING:{name:"picking",picking:!0}},An={IGNORE:1,USE_BB:2},Cs=0,Kl=1,Xl=2,Ts=3,Gt=4,sn=5,ga=6,pa=7,fm=(function(){function r(e,t,a){ht(this,r),this.r=e,this.gl=t,this.maxInstances=a.webglBatchSize,this.atlasSize=a.webglTexSize,this.bgColor=a.bgColor,this.debug=a.webglDebug,this.batchDebugInfo=[],a.enableWrapping=!0,a.createTextureCanvas=Hy,this.atlasManager=new im(e,a),this.batchManager=new sm(a),this.simpleShapeOptions=new Map,this.program=this._createShaderProgram(Ea.SCREEN),this.pickingProgram=this._createShaderProgram(Ea.PICKING),this.vao=this._createVAO()}return gt(r,[{key:"addAtlasCollection",value:function(t,a){this.atlasManager.addAtlasCollection(t,a)}},{key:"addTextureAtlasRenderType",value:function(t,a){this.atlasManager.addRenderType(t,a)}},{key:"addSimpleShapeRenderType",value:function(t,a){this.simpleShapeOptions.set(t,a)}},{key:"invalidate",value:function(t){var a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=a.type,i=this.atlasManager;return n?i.invalidate(t,{filterType:function(o){return o===n},forceRedraw:!0}):i.invalidate(t)}},{key:"gc",value:function(){this.atlasManager.gc()}},{key:"_createShaderProgram",value:function(t){var a=this.gl,n=`#version 300 es + precision highp float; + + uniform mat3 uPanZoomMatrix; + uniform int uAtlasSize; + + // instanced + in vec2 aPosition; // a vertex from the unit square + + in mat3 aTransform; // used to transform verticies, eg into a bounding box + in int aVertType; // the type of thing we are rendering + + // the z-index that is output when using picking mode + in vec4 aIndex; + + // For textures + in int aAtlasId; // which shader unit/atlas to use + in vec4 aTex; // x/y/w/h of texture in atlas + + // for edges + in vec4 aPointAPointB; + in vec4 aPointCPointD; + in vec2 aLineWidth; // also used for node border width + + // simple shapes + in vec4 aCornerRadius; // for round-rectangle [top-right, bottom-right, top-left, bottom-left] + in vec4 aColor; // also used for edges + in vec4 aBorderColor; // aLineWidth is used for border width + + // output values passed to the fragment shader + out vec2 vTexCoord; + out vec4 vColor; + out vec2 vPosition; + // flat values are not interpolated + flat out int vAtlasId; + flat out int vVertType; + flat out vec2 vTopRight; + flat out vec2 vBotLeft; + flat out vec4 vCornerRadius; + flat out vec4 vBorderColor; + flat out vec2 vBorderWidth; + flat out vec4 vIndex; + + void main(void) { + int vid = gl_VertexID; + vec2 position = aPosition; // TODO make this a vec3, simplifies some code below + + if(aVertType == `.concat(Cs,`) { + float texX = aTex.x; // texture coordinates + float texY = aTex.y; + float texW = aTex.z; + float texH = aTex.w; + + if(vid == 1 || vid == 2 || vid == 4) { + texX += texW; + } + if(vid == 2 || vid == 4 || vid == 5) { + texY += texH; + } + + float d = float(uAtlasSize); + vTexCoord = vec2(texX / d, texY / d); // tex coords must be between 0 and 1 + + gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0); + } + else if(aVertType == `).concat(Gt," || aVertType == ").concat(pa,` + || aVertType == `).concat(sn," || aVertType == ").concat(ga,`) { // simple shapes + + // the bounding box is needed by the fragment shader + vBotLeft = (aTransform * vec3(0, 0, 1)).xy; // flat + vTopRight = (aTransform * vec3(1, 1, 1)).xy; // flat + vPosition = (aTransform * vec3(position, 1)).xy; // will be interpolated + + // calculations are done in the fragment shader, just pass these along + vColor = aColor; + vCornerRadius = aCornerRadius; + vBorderColor = aBorderColor; + vBorderWidth = aLineWidth; + + gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0); + } + else if(aVertType == `).concat(Kl,`) { + vec2 source = aPointAPointB.xy; + vec2 target = aPointAPointB.zw; + + // adjust the geometry so that the line is centered on the edge + position.y = position.y - 0.5; + + // stretch the unit square into a long skinny rectangle + vec2 xBasis = target - source; + vec2 yBasis = normalize(vec2(-xBasis.y, xBasis.x)); + vec2 point = source + xBasis * position.x + yBasis * aLineWidth[0] * position.y; + + gl_Position = vec4(uPanZoomMatrix * vec3(point, 1.0), 1.0); + vColor = aColor; + } + else if(aVertType == `).concat(Xl,`) { + vec2 pointA = aPointAPointB.xy; + vec2 pointB = aPointAPointB.zw; + vec2 pointC = aPointCPointD.xy; + vec2 pointD = aPointCPointD.zw; + + // adjust the geometry so that the line is centered on the edge + position.y = position.y - 0.5; + + vec2 p0, p1, p2, pos; + if(position.x == 0.0) { // The left side of the unit square + p0 = pointA; + p1 = pointB; + p2 = pointC; + pos = position; + } else { // The right side of the unit square, use same approach but flip the geometry upside down + p0 = pointD; + p1 = pointC; + p2 = pointB; + pos = vec2(0.0, -position.y); + } + + vec2 p01 = p1 - p0; + vec2 p12 = p2 - p1; + vec2 p21 = p1 - p2; + + // Find the normal vector. + vec2 tangent = normalize(normalize(p12) + normalize(p01)); + vec2 normal = vec2(-tangent.y, tangent.x); + + // Find the vector perpendicular to p0 -> p1. + vec2 p01Norm = normalize(vec2(-p01.y, p01.x)); + + // Determine the bend direction. + float sigma = sign(dot(p01 + p21, normal)); + float width = aLineWidth[0]; + + if(sign(pos.y) == -sigma) { + // This is an intersecting vertex. Adjust the position so that there's no overlap. + vec2 point = 0.5 * width * normal * -sigma / dot(normal, p01Norm); + gl_Position = vec4(uPanZoomMatrix * vec3(p1 + point, 1.0), 1.0); + } else { + // This is a non-intersecting vertex. Treat it like a mitre join. + vec2 point = 0.5 * width * normal * sigma * dot(normal, p01Norm); + gl_Position = vec4(uPanZoomMatrix * vec3(p1 + point, 1.0), 1.0); + } + + vColor = aColor; + } + else if(aVertType == `).concat(Ts,` && vid < 3) { + // massage the first triangle into an edge arrow + if(vid == 0) + position = vec2(-0.15, -0.3); + if(vid == 1) + position = vec2( 0.0, 0.0); + if(vid == 2) + position = vec2( 0.15, -0.3); + + gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0); + vColor = aColor; + } + else { + gl_Position = vec4(2.0, 0.0, 0.0, 1.0); // discard vertex by putting it outside webgl clip space + } + + vAtlasId = aAtlasId; + vVertType = aVertType; + vIndex = aIndex; + } + `),i=this.batchManager.getIndexArray(),s=`#version 300 es + precision highp float; + + // declare texture unit for each texture atlas in the batch + `.concat(i.map(function(u){return"uniform sampler2D uTexture".concat(u,";")}).join(` + `),` + + uniform vec4 uBGColor; + uniform float uZoom; + + in vec2 vTexCoord; + in vec4 vColor; + in vec2 vPosition; // model coordinates + + flat in int vAtlasId; + flat in vec4 vIndex; + flat in int vVertType; + flat in vec2 vTopRight; + flat in vec2 vBotLeft; + flat in vec4 vCornerRadius; + flat in vec4 vBorderColor; + flat in vec2 vBorderWidth; + + out vec4 outColor; + + `).concat(om,` + `).concat(um,` + `).concat(lm,` + `).concat(vm,` + + vec4 blend(vec4 top, vec4 bot) { // blend colors with premultiplied alpha + return vec4( + top.rgb + (bot.rgb * (1.0 - top.a)), + top.a + (bot.a * (1.0 - top.a)) + ); + } + + vec4 distInterp(vec4 cA, vec4 cB, float d) { // interpolate color using Signed Distance + // scale to the zoom level so that borders don't look blurry when zoomed in + // note 1.5 is an aribitrary value chosen because it looks good + return mix(cA, cB, 1.0 - smoothstep(0.0, 1.5 / uZoom, abs(d))); + } + + void main(void) { + if(vVertType == `).concat(Cs,`) { + // look up the texel from the texture unit + `).concat(i.map(function(u){return"if(vAtlasId == ".concat(u,") outColor = texture(uTexture").concat(u,", vTexCoord);")}).join(` + else `),` + } + else if(vVertType == `).concat(Ts,`) { + // mimics how canvas renderer uses context.globalCompositeOperation = 'destination-out'; + outColor = blend(vColor, uBGColor); + outColor.a = 1.0; // make opaque, masks out line under arrow + } + else if(vVertType == `).concat(Gt,` && vBorderWidth == vec2(0.0)) { // simple rectangle with no border + outColor = vColor; // unit square is already transformed to the rectangle, nothing else needs to be done + } + else if(vVertType == `).concat(Gt," || vVertType == ").concat(pa,` + || vVertType == `).concat(sn," || vVertType == ").concat(ga,`) { // use SDF + + float outerBorder = vBorderWidth[0]; + float innerBorder = vBorderWidth[1]; + float borderPadding = outerBorder * 2.0; + float w = vTopRight.x - vBotLeft.x - borderPadding; + float h = vTopRight.y - vBotLeft.y - borderPadding; + vec2 b = vec2(w/2.0, h/2.0); // half width, half height + vec2 p = vPosition - vec2(vTopRight.x - b[0] - outerBorder, vTopRight.y - b[1] - outerBorder); // translate to center + + float d; // signed distance + if(vVertType == `).concat(Gt,`) { + d = rectangleSD(p, b); + } else if(vVertType == `).concat(pa,` && w == h) { + d = circleSD(p, b.x); // faster than ellipse + } else if(vVertType == `).concat(pa,`) { + d = ellipseSD(p, b); + } else { + d = roundRectangleSD(p, b, vCornerRadius.wzyx); + } + + // use the distance to interpolate a color to smooth the edges of the shape, doesn't need multisampling + // we must smooth colors inwards, because we can't change pixels outside the shape's bounding box + if(d > 0.0) { + if(d > outerBorder) { + discard; + } else { + outColor = distInterp(vBorderColor, vec4(0), d - outerBorder); + } + } else { + if(d > innerBorder) { + vec4 outerColor = outerBorder == 0.0 ? vec4(0) : vBorderColor; + vec4 innerBorderColor = blend(vBorderColor, vColor); + outColor = distInterp(innerBorderColor, outerColor, d); + } + else { + vec4 outerColor; + if(innerBorder == 0.0 && outerBorder == 0.0) { + outerColor = vec4(0); + } else if(innerBorder == 0.0) { + outerColor = vBorderColor; + } else { + outerColor = blend(vBorderColor, vColor); + } + outColor = distInterp(vColor, outerColor, d - innerBorder); + } + } + } + else { + outColor = vColor; + } + + `).concat(t.picking?`if(outColor.a == 0.0) discard; + else outColor = vIndex;`:"",` + } + `),o=Gy(a,n,s);o.aPosition=a.getAttribLocation(o,"aPosition"),o.aIndex=a.getAttribLocation(o,"aIndex"),o.aVertType=a.getAttribLocation(o,"aVertType"),o.aTransform=a.getAttribLocation(o,"aTransform"),o.aAtlasId=a.getAttribLocation(o,"aAtlasId"),o.aTex=a.getAttribLocation(o,"aTex"),o.aPointAPointB=a.getAttribLocation(o,"aPointAPointB"),o.aPointCPointD=a.getAttribLocation(o,"aPointCPointD"),o.aLineWidth=a.getAttribLocation(o,"aLineWidth"),o.aColor=a.getAttribLocation(o,"aColor"),o.aCornerRadius=a.getAttribLocation(o,"aCornerRadius"),o.aBorderColor=a.getAttribLocation(o,"aBorderColor"),o.uPanZoomMatrix=a.getUniformLocation(o,"uPanZoomMatrix"),o.uAtlasSize=a.getUniformLocation(o,"uAtlasSize"),o.uBGColor=a.getUniformLocation(o,"uBGColor"),o.uZoom=a.getUniformLocation(o,"uZoom"),o.uTextures=[];for(var l=0;l1&&arguments[1]!==void 0?arguments[1]:Ea.SCREEN;this.panZoomMatrix=t,this.renderTarget=a,this.batchDebugInfo=[],this.wrappedCount=0,this.simpleCount=0,this.startBatch()}},{key:"startBatch",value:function(){this.instanceCount=0,this.batchManager.startBatch()}},{key:"endFrame",value:function(){this.endBatch()}},{key:"_isVisible",value:function(t,a){return t.visible()?a&&a.isVisible?a.isVisible(t):!0:!1}},{key:"drawTexture",value:function(t,a,n){var i=this.atlasManager,s=this.batchManager,o=i.getRenderTypeOpts(n);if(this._isVisible(t,o)&&!(t.isEdge()&&!this._isValidEdge(t))){if(this.renderTarget.picking&&o.getTexPickingMode){var l=o.getTexPickingMode(t);if(l===An.IGNORE)return;if(l==An.USE_BB){this.drawPickingRectangle(t,a,n);return}}var u=i.getAtlasInfo(t,n),v=kr(u),f;try{for(v.s();!(f=v.n()).done;){var c=f.value,h=c.atlas,d=c.tex1,y=c.tex2;s.canAddToCurrentBatch(h)||this.endBatch();for(var g=s.getAtlasIndexForBatch(h),p=0,m=[[d,!0],[y,!1]];p=this.maxInstances&&this.endBatch()}}}}catch(B){v.e(B)}finally{v.f()}}}},{key:"setTransformMatrix",value:function(t,a,n,i){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,o=0;if(n.shapeProps&&n.shapeProps.padding&&(o=t.pstyle(n.shapeProps.padding).pfValue),i){var l=i.bb,u=i.tex1,v=i.tex2,f=u.w/(u.w+v.w);s||(f=1-f);var c=this._getAdjustedBB(l,o,s,f);this._applyTransformMatrix(a,c,n,t)}else{var h=n.getBoundingBox(t),d=this._getAdjustedBB(h,o,!0,1);this._applyTransformMatrix(a,d,n,t)}}},{key:"_applyTransformMatrix",value:function(t,a,n,i){var s,o;$l(t);var l=n.getRotation?n.getRotation(i):0;if(l!==0){var u=n.getRotationPoint(i),v=u.x,f=u.y;yn(t,t,[v,f]),Ul(t,t,l);var c=n.getRotationOffset(i);s=c.x+(a.xOffset||0),o=c.y+(a.yOffset||0)}else s=a.x1,o=a.y1;yn(t,t,[s,o]),Ws(t,t,[a.w,a.h])}},{key:"_getAdjustedBB",value:function(t,a,n,i){var s=t.x1,o=t.y1,l=t.w,u=t.h,v=t.yOffset;a&&(s-=a,o-=a,l+=2*a,u+=2*a);var f=0,c=l*i;return n&&i<1?l=c:!n&&i<1&&(f=l-c,s+=f,l=c),{x1:s,y1:o,w:l,h:u,xOffset:f,yOffset:v}}},{key:"drawPickingRectangle",value:function(t,a,n){var i=this.atlasManager.getRenderTypeOpts(n),s=this.instanceCount;this.vertTypeBuffer.getView(s)[0]=Gt;var o=this.indexBuffer.getView(s);_t(a,o);var l=this.colorBuffer.getView(s);xt([0,0,0],1,l);var u=this.transformBuffer.getMatrixView(s);this.setTransformMatrix(t,u,i),this.simpleCount++,this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}},{key:"drawNode",value:function(t,a,n){var i=this.simpleShapeOptions.get(n);if(this._isVisible(t,i)){var s=i.shapeProps,o=this._getVertTypeForShape(t,s.shape);if(o===void 0||i.isSimple&&!i.isSimple(t)){this.drawTexture(t,a,n);return}var l=this.instanceCount;if(this.vertTypeBuffer.getView(l)[0]=o,o===sn||o===ga){var u=i.getBoundingBox(t),v=this._getCornerRadius(t,s.radius,u),f=this.cornerRadiusBuffer.getView(l);f[0]=v,f[1]=v,f[2]=v,f[3]=v,o===ga&&(f[0]=0,f[2]=0)}var c=this.indexBuffer.getView(l);_t(a,c);var h=t.pstyle(s.color).value,d=t.pstyle(s.opacity).value,y=this.colorBuffer.getView(l);xt(h,d,y);var g=this.lineWidthBuffer.getView(l);if(g[0]=0,g[1]=0,s.border){var p=t.pstyle("border-width").value;if(p>0){var m=t.pstyle("border-color").value,b=t.pstyle("border-opacity").value,w=this.borderColorBuffer.getView(l);xt(m,b,w);var E=t.pstyle("border-position").value;if(E==="inside")g[0]=0,g[1]=-p;else if(E==="outside")g[0]=p,g[1]=0;else{var C=p/2;g[0]=C,g[1]=-C}}}var x=this.transformBuffer.getMatrixView(l);this.setTransformMatrix(t,x,i),this.simpleCount++,this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}}},{key:"_getVertTypeForShape",value:function(t,a){var n=t.pstyle(a).value;switch(n){case"rectangle":return Gt;case"ellipse":return pa;case"roundrectangle":case"round-rectangle":return sn;case"bottom-round-rectangle":return ga;default:return}}},{key:"_getCornerRadius",value:function(t,a,n){var i=n.w,s=n.h;if(t.pstyle(a).value==="auto")return vt(i,s);var o=t.pstyle(a).pfValue,l=i/2,u=s/2;return Math.min(o,u,l)}},{key:"drawEdgeArrow",value:function(t,a,n){if(t.visible()){var i=t._private.rscratch,s,o,l;if(n==="source"?(s=i.arrowStartX,o=i.arrowStartY,l=i.srcArrowAngle):(s=i.arrowEndX,o=i.arrowEndY,l=i.tgtArrowAngle),!(isNaN(s)||s==null||isNaN(o)||o==null||isNaN(l)||l==null)){var u=t.pstyle(n+"-arrow-shape").value;if(u!=="none"){var v=t.pstyle(n+"-arrow-color").value,f=t.pstyle("opacity").value,c=t.pstyle("line-opacity").value,h=f*c,d=t.pstyle("width").pfValue,y=t.pstyle("arrow-scale").value,g=this.r.getArrowWidth(d,y),p=this.instanceCount,m=this.transformBuffer.getMatrixView(p);$l(m),yn(m,m,[s,o]),Ws(m,m,[g,g]),Ul(m,m,l),this.vertTypeBuffer.getView(p)[0]=Ts;var b=this.indexBuffer.getView(p);_t(a,b);var w=this.colorBuffer.getView(p);xt(v,h,w),this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}}}}},{key:"drawEdgeLine",value:function(t,a){if(t.visible()){var n=this._getEdgePoints(t);if(n){var i=t.pstyle("opacity").value,s=t.pstyle("line-opacity").value,o=t.pstyle("width").pfValue,l=t.pstyle("line-color").value,u=i*s;if(n.length/2+this.instanceCount>this.maxInstances&&this.endBatch(),n.length==4){var v=this.instanceCount;this.vertTypeBuffer.getView(v)[0]=Kl;var f=this.indexBuffer.getView(v);_t(a,f);var c=this.colorBuffer.getView(v);xt(l,u,c);var h=this.lineWidthBuffer.getView(v);h[0]=o;var d=this.pointAPointBBuffer.getView(v);d[0]=n[0],d[1]=n[1],d[2]=n[2],d[3]=n[3],this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}else for(var y=0;y=this.maxInstances&&this.endBatch()}}}}},{key:"_isValidEdge",value:function(t){var a=t._private.rscratch;return!(a.badLine||a.allpts==null||isNaN(a.allpts[0]))}},{key:"_getEdgePoints",value:function(t){var a=t._private.rscratch;if(this._isValidEdge(t)){var n=a.allpts;if(n.length==4)return n;var i=this._getNumSegments(t);return this._getCurveSegmentPoints(n,i)}}},{key:"_getNumSegments",value:function(t){var a=15;return Math.min(Math.max(a,5),this.maxInstances)}},{key:"_getCurveSegmentPoints",value:function(t,a){if(t.length==4)return t;for(var n=Array((a+1)*2),i=0;i<=a;i++)if(i==0)n[0]=t[0],n[1]=t[1];else if(i==a)n[i*2]=t[t.length-2],n[i*2+1]=t[t.length-1];else{var s=i/a;this._setCurvePoint(t,s,n,i*2)}return n}},{key:"_setCurvePoint",value:function(t,a,n,i){if(t.length<=2)n[i]=t[0],n[i+1]=t[1];else{for(var s=Array(t.length-2),o=0;o0}},o=function(f){var c=f.pstyle("text-events").strValue==="yes";return c?An.USE_BB:An.IGNORE},l=function(f){var c=f.position(),h=c.x,d=c.y,y=f.outerWidth(),g=f.outerHeight();return{w:y,h:g,x1:h-y/2,y1:d-g/2}};t.drawing.addAtlasCollection("node",{texRows:r.webglTexRowsNodes}),t.drawing.addAtlasCollection("label",{texRows:r.webglTexRows}),t.drawing.addTextureAtlasRenderType("node-body",{collection:"node",getKey:e.getStyleKey,getBoundingBox:e.getElementBox,drawElement:e.drawElement}),t.drawing.addSimpleShapeRenderType("node-body",{getBoundingBox:l,isSimple:Uy,shapeProps:{shape:"shape",color:"background-color",opacity:"background-opacity",radius:"corner-radius",border:!0}}),t.drawing.addSimpleShapeRenderType("node-overlay",{getBoundingBox:l,isVisible:s("overlay"),shapeProps:{shape:"overlay-shape",color:"overlay-color",opacity:"overlay-opacity",padding:"overlay-padding",radius:"overlay-corner-radius"}}),t.drawing.addSimpleShapeRenderType("node-underlay",{getBoundingBox:l,isVisible:s("underlay"),shapeProps:{shape:"underlay-shape",color:"underlay-color",opacity:"underlay-opacity",padding:"underlay-padding",radius:"underlay-corner-radius"}}),t.drawing.addTextureAtlasRenderType("label",{collection:"label",getTexPickingMode:o,getKey:Ss(e.getLabelKey,null),getBoundingBox:ks(e.getLabelBox,null),drawClipped:!0,drawElement:e.drawLabel,getRotation:n(null),getRotationPoint:e.getLabelRotationPoint,getRotationOffset:e.getLabelRotationOffset,isVisible:i("label")}),t.drawing.addTextureAtlasRenderType("edge-source-label",{collection:"label",getTexPickingMode:o,getKey:Ss(e.getSourceLabelKey,"source"),getBoundingBox:ks(e.getSourceLabelBox,"source"),drawClipped:!0,drawElement:e.drawSourceLabel,getRotation:n("source"),getRotationPoint:e.getSourceLabelRotationPoint,getRotationOffset:e.getSourceLabelRotationOffset,isVisible:i("source-label")}),t.drawing.addTextureAtlasRenderType("edge-target-label",{collection:"label",getTexPickingMode:o,getKey:Ss(e.getTargetLabelKey,"target"),getBoundingBox:ks(e.getTargetLabelBox,"target"),drawClipped:!0,drawElement:e.drawTargetLabel,getRotation:n("target"),getRotationPoint:e.getTargetLabelRotationPoint,getRotationOffset:e.getTargetLabelRotationOffset,isVisible:i("target-label")});var u=Fa(function(){console.log("garbage collect flag set"),t.data.gc=!0},1e4);t.onUpdateEleCalcs(function(v,f){var c=!1;f&&f.length>0&&(c|=t.drawing.invalidate(f)),c&&u()}),dm(t)};function cm(r){var e=r.cy.container(),t=e&&e.style&&e.style.backgroundColor||"white";return iv(t)}function Lf(r,e){var t=r._private.rscratch;return Tr(t,"labelWrapCachedLines",e)||[]}var Ss=function(e,t){return function(a){var n=e(a),i=Lf(a,t);return i.length>1?i.map(function(s,o){return"".concat(n,"_").concat(o)}):n}},ks=function(e,t){return function(a,n){var i=e(a);if(typeof n=="string"){var s=n.indexOf("_");if(s>0){var o=Number(n.substring(s+1)),l=Lf(a,t),u=i.h/l.length,v=u*o,f=i.y1+v;return{x1:i.x1,w:i.w,y1:f,h:u,yOffset:v}}}return i}};function dm(r){{var e=r.render;r.render=function(i){i=i||{};var s=r.cy;r.webgl&&(s.zoom()>Sf?(hm(r),e.call(r,i)):(gm(r),Of(r,i,Ea.SCREEN)))}}{var t=r.matchCanvasSize;r.matchCanvasSize=function(i){t.call(r,i),r.pickingFrameBuffer.setFramebufferAttachmentSizes(r.canvasWidth,r.canvasHeight),r.pickingFrameBuffer.needsDraw=!0}}r.findNearestElements=function(i,s,o,l){return xm(r,i,s)};{var a=r.invalidateCachedZSortedEles;r.invalidateCachedZSortedEles=function(){a.call(r),r.pickingFrameBuffer.needsDraw=!0}}{var n=r.notify;r.notify=function(i,s){n.call(r,i,s),i==="viewport"||i==="bounds"?r.pickingFrameBuffer.needsDraw=!0:i==="background"&&r.drawing.invalidate(s,{type:"node-body"})}}}function hm(r){var e=r.data.contexts[r.WEBGL];e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}function gm(r){var e=function(a){a.save(),a.setTransform(1,0,0,1,0,0),a.clearRect(0,0,r.canvasWidth,r.canvasHeight),a.restore()};e(r.data.contexts[r.NODE]),e(r.data.contexts[r.DRAG])}function pm(r){var e=r.canvasWidth,t=r.canvasHeight,a=bo(r),n=a.pan,i=a.zoom,s=Es();yn(s,s,[n.x,n.y]),Ws(s,s,[i,i]);var o=Es();rm(o,e,t);var l=Es();return em(l,o,s),l}function If(r,e){var t=r.canvasWidth,a=r.canvasHeight,n=bo(r),i=n.pan,s=n.zoom;e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t,a),e.translate(i.x,i.y),e.scale(s,s)}function ym(r,e){r.drawSelectionRectangle(e,function(t){return If(r,t)})}function mm(r){var e=r.data.contexts[r.NODE];e.save(),If(r,e),e.strokeStyle="rgba(0, 0, 0, 0.3)",e.beginPath(),e.moveTo(-1e3,0),e.lineTo(1e3,0),e.stroke(),e.beginPath(),e.moveTo(0,-1e3),e.lineTo(0,1e3),e.stroke(),e.restore()}function bm(r){var e=function(n,i,s){for(var o=n.atlasManager.getAtlasCollection(i),l=r.data.contexts[r.NODE],u=o.atlases,v=0;v=0&&w.add(x)}return w}function xm(r,e,t){var a=wm(r,e,t),n=r.getCachedZSortedEles(),i,s,o=kr(a),l;try{for(o.s();!(l=o.n()).done;){var u=l.value,v=n[u];if(!i&&v.isNode()&&(i=v),!s&&v.isEdge()&&(s=v),i&&s)break}}catch(f){o.e(f)}finally{o.f()}return[i,s].filter(Boolean)}function Ds(r,e,t){var a=r.drawing;e+=1,t.isNode()?(a.drawNode(t,e,"node-underlay"),a.drawNode(t,e,"node-body"),a.drawTexture(t,e,"label"),a.drawNode(t,e,"node-overlay")):(a.drawEdgeLine(t,e),a.drawEdgeArrow(t,e,"source"),a.drawEdgeArrow(t,e,"target"),a.drawTexture(t,e,"label"),a.drawTexture(t,e,"edge-source-label"),a.drawTexture(t,e,"edge-target-label"))}function Of(r,e,t){var a;r.webglDebug&&(a=performance.now());var n=r.drawing,i=0;if(t.screen&&r.data.canvasNeedsRedraw[r.SELECT_BOX]&&ym(r,e),r.data.canvasNeedsRedraw[r.NODE]||t.picking){var s=r.data.contexts[r.WEBGL];t.screen?(s.clearColor(0,0,0,0),s.enable(s.BLEND),s.blendFunc(s.ONE,s.ONE_MINUS_SRC_ALPHA)):s.disable(s.BLEND),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),s.viewport(0,0,s.canvas.width,s.canvas.height);var o=pm(r),l=r.getCachedZSortedEles();if(i=l.length,n.startFrame(o,t),t.screen){for(var u=0;u0&&s>0){h.clearRect(0,0,i,s),h.globalCompositeOperation="source-over";var d=this.getCachedZSortedEles();if(r.full)h.translate(-a.x1*u,-a.y1*u),h.scale(u,u),this.drawElements(h,d),h.scale(1/u,1/u),h.translate(a.x1*u,a.y1*u);else{var y=e.pan(),g={x:y.x*u,y:y.y*u};u*=e.zoom(),h.translate(g.x,g.y),h.scale(u,u),this.drawElements(h,d),h.scale(1/u,1/u),h.translate(-g.x,-g.y)}r.bg&&(h.globalCompositeOperation="destination-over",h.fillStyle=r.bg,h.rect(0,0,i,s),h.fill())}return c};function Em(r,e){for(var t=atob(r),a=new ArrayBuffer(t.length),n=new Uint8Array(a),i=0;i"u"?"undefined":ar(OffscreenCanvas))!=="undefined")t=new OffscreenCanvas(r,e);else{var a=this.cy.window(),n=a.document;t=n.createElement("canvas"),t.width=r,t.height=e}return t};[Df,Hr,Jr,mo,It,yt,xr,Mf,mt,Wa,Ff].forEach(function(r){be(ke,r)});var Sm=[{name:"null",impl:df},{name:"base",impl:Cf},{name:"canvas",impl:Cm}],km=[{type:"layout",extensions:Qp},{type:"renderer",extensions:Sm}],qf={},_f={};function Gf(r,e,t){var a=t,n=function(T){Ve("Can not register `"+e+"` for `"+r+"` since `"+T+"` already exists in the prototype and can not be overridden")};if(r==="core"){if(Ra.prototype[e])return n(e);Ra.prototype[e]=t}else if(r==="collection"){if(fr.prototype[e])return n(e);fr.prototype[e]=t}else if(r==="layout"){for(var i=function(T){this.options=T,t.call(this,T),Le(this._private)||(this._private={}),this._private.cy=T.cy,this._private.listeners=[],this.createEmitter()},s=i.prototype=Object.create(t.prototype),o=[],l=0;l r.length) && (a = r.length);\n for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];\n return n;\n}\nfunction _arrayWithHoles(r) {\n if (Array.isArray(r)) return r;\n}\nfunction _arrayWithoutHoles(r) {\n if (Array.isArray(r)) return _arrayLikeToArray(r);\n}\nfunction _classCallCheck(a, n) {\n if (!(a instanceof n)) throw new TypeError(\"Cannot call a class as a function\");\n}\nfunction _defineProperties(e, r) {\n for (var t = 0; t < r.length; t++) {\n var o = r[t];\n o.enumerable = o.enumerable || false, o.configurable = true, \"value\" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);\n }\n}\nfunction _createClass(e, r, t) {\n return r && _defineProperties(e.prototype, r), Object.defineProperty(e, \"prototype\", {\n writable: false\n }), e;\n}\nfunction _createForOfIteratorHelper(r, e) {\n var t = \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"];\n if (!t) {\n if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {\n t && (r = t);\n var n = 0,\n F = function () {};\n return {\n s: F,\n n: function () {\n return n >= r.length ? {\n done: true\n } : {\n done: false,\n value: r[n++]\n };\n },\n e: function (r) {\n throw r;\n },\n f: F\n };\n }\n throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n }\n var o,\n a = true,\n u = false;\n return {\n s: function () {\n t = t.call(r);\n },\n n: function () {\n var r = t.next();\n return a = r.done, r;\n },\n e: function (r) {\n u = true, o = r;\n },\n f: function () {\n try {\n a || null == t.return || t.return();\n } finally {\n if (u) throw o;\n }\n }\n };\n}\nfunction _defineProperty$1(e, r, t) {\n return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n value: t,\n enumerable: true,\n configurable: true,\n writable: true\n }) : e[r] = t, e;\n}\nfunction _iterableToArray(r) {\n if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r);\n}\nfunction _iterableToArrayLimit(r, l) {\n var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"];\n if (null != t) {\n var e,\n n,\n i,\n u,\n a = [],\n f = true,\n o = false;\n try {\n if (i = (t = t.call(r)).next, 0 === l) {\n if (Object(t) !== t) return;\n f = !1;\n } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);\n } catch (r) {\n o = true, n = r;\n } finally {\n try {\n if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;\n } finally {\n if (o) throw n;\n }\n }\n return a;\n }\n}\nfunction _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nfunction _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nfunction _slicedToArray(r, e) {\n return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();\n}\nfunction _toConsumableArray(r) {\n return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();\n}\nfunction _toPrimitive(t, r) {\n if (\"object\" != typeof t || !t) return t;\n var e = t[Symbol.toPrimitive];\n if (undefined !== e) {\n var i = e.call(t, r);\n if (\"object\" != typeof i) return i;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (String )(t);\n}\nfunction _toPropertyKey(t) {\n var i = _toPrimitive(t, \"string\");\n return \"symbol\" == typeof i ? i : i + \"\";\n}\nfunction _typeof(o) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n return typeof o;\n } : function (o) {\n return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n }, _typeof(o);\n}\nfunction _unsupportedIterableToArray(r, a) {\n if (r) {\n if (\"string\" == typeof r) return _arrayLikeToArray(r, a);\n var t = {}.toString.call(r).slice(8, -1);\n return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : undefined;\n }\n}\n\nvar _window = typeof window === 'undefined' ? null : window; // eslint-disable-line no-undef\n\nvar navigator = _window ? _window.navigator : null;\n_window ? _window.document : null;\nvar typeofstr = _typeof('');\nvar typeofobj = _typeof({});\nvar typeoffn = _typeof(function () {});\nvar typeofhtmlele = typeof HTMLElement === \"undefined\" ? \"undefined\" : _typeof(HTMLElement);\nvar instanceStr = function instanceStr(obj) {\n return obj && obj.instanceString && fn$6(obj.instanceString) ? obj.instanceString() : null;\n};\n\nvar string = function string(obj) {\n return obj != null && _typeof(obj) == typeofstr;\n};\nvar fn$6 = function fn(obj) {\n return obj != null && _typeof(obj) === typeoffn;\n};\nvar array = function array(obj) {\n return !elementOrCollection(obj) && (Array.isArray ? Array.isArray(obj) : obj != null && obj instanceof Array);\n};\nvar plainObject = function plainObject(obj) {\n return obj != null && _typeof(obj) === typeofobj && !array(obj) && obj.constructor === Object;\n};\nvar object = function object(obj) {\n return obj != null && _typeof(obj) === typeofobj;\n};\nvar number$1 = function number(obj) {\n return obj != null && _typeof(obj) === _typeof(1) && !isNaN(obj);\n};\nvar integer = function integer(obj) {\n return number$1(obj) && Math.floor(obj) === obj;\n};\nvar htmlElement = function htmlElement(obj) {\n if ('undefined' === typeofhtmlele) {\n return undefined;\n } else {\n return null != obj && obj instanceof HTMLElement;\n }\n};\nvar elementOrCollection = function elementOrCollection(obj) {\n return element(obj) || collection(obj);\n};\nvar element = function element(obj) {\n return instanceStr(obj) === 'collection' && obj._private.single;\n};\nvar collection = function collection(obj) {\n return instanceStr(obj) === 'collection' && !obj._private.single;\n};\nvar core = function core(obj) {\n return instanceStr(obj) === 'core';\n};\nvar stylesheet = function stylesheet(obj) {\n return instanceStr(obj) === 'stylesheet';\n};\nvar event = function event(obj) {\n return instanceStr(obj) === 'event';\n};\nvar emptyString = function emptyString(obj) {\n if (obj === undefined || obj === null) {\n // null is empty\n return true;\n } else if (obj === '' || obj.match(/^\\s+$/)) {\n return true; // empty string is empty\n }\n return false; // otherwise, we don't know what we've got\n};\nvar domElement = function domElement(obj) {\n if (typeof HTMLElement === 'undefined') {\n return false; // we're not in a browser so it doesn't matter\n } else {\n return obj instanceof HTMLElement;\n }\n};\nvar boundingBox = function boundingBox(obj) {\n return plainObject(obj) && number$1(obj.x1) && number$1(obj.x2) && number$1(obj.y1) && number$1(obj.y2);\n};\nvar promise = function promise(obj) {\n return object(obj) && fn$6(obj.then);\n};\nvar ms = function ms() {\n return navigator && navigator.userAgent.match(/msie|trident|edge/i);\n}; // probably a better way to detect this...\n\nvar memoize = function memoize(fn, keyFn) {\n if (!keyFn) {\n keyFn = function keyFn() {\n if (arguments.length === 1) {\n return arguments[0];\n } else if (arguments.length === 0) {\n return 'undefined';\n }\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n return args.join('$');\n };\n }\n var _memoizedFn = function memoizedFn() {\n var self = this;\n var args = arguments;\n var ret;\n var k = keyFn.apply(self, args);\n var cache = _memoizedFn.cache;\n if (!(ret = cache[k])) {\n ret = cache[k] = fn.apply(self, args);\n }\n return ret;\n };\n _memoizedFn.cache = {};\n return _memoizedFn;\n};\n\nvar camel2dash = memoize(function (str) {\n return str.replace(/([A-Z])/g, function (v) {\n return '-' + v.toLowerCase();\n });\n});\nvar dash2camel = memoize(function (str) {\n return str.replace(/(-\\w)/g, function (v) {\n return v[1].toUpperCase();\n });\n});\nvar prependCamel = memoize(function (prefix, str) {\n return prefix + str[0].toUpperCase() + str.substring(1);\n}, function (prefix, str) {\n return prefix + '$' + str;\n});\nvar capitalize = function capitalize(str) {\n if (emptyString(str)) {\n return str;\n }\n return str.charAt(0).toUpperCase() + str.substring(1);\n};\nvar endsWith = function endsWith(string, suffix) {\n return string.slice(-1 * suffix.length) === suffix;\n};\n\nvar number = '(?:[-+]?(?:(?:\\\\d+|\\\\d*\\\\.\\\\d+)(?:[Ee][+-]?\\\\d+)?))';\nvar rgba = 'rgb[a]?\\\\((' + number + '[%]?)\\\\s*,\\\\s*(' + number + '[%]?)\\\\s*,\\\\s*(' + number + '[%]?)(?:\\\\s*,\\\\s*(' + number + '))?\\\\)';\nvar rgbaNoBackRefs = 'rgb[a]?\\\\((?:' + number + '[%]?)\\\\s*,\\\\s*(?:' + number + '[%]?)\\\\s*,\\\\s*(?:' + number + '[%]?)(?:\\\\s*,\\\\s*(?:' + number + '))?\\\\)';\nvar hsla = 'hsl[a]?\\\\((' + number + ')\\\\s*,\\\\s*(' + number + '[%])\\\\s*,\\\\s*(' + number + '[%])(?:\\\\s*,\\\\s*(' + number + '))?\\\\)';\nvar hslaNoBackRefs = 'hsl[a]?\\\\((?:' + number + ')\\\\s*,\\\\s*(?:' + number + '[%])\\\\s*,\\\\s*(?:' + number + '[%])(?:\\\\s*,\\\\s*(?:' + number + '))?\\\\)';\nvar hex3 = '\\\\#[0-9a-fA-F]{3}';\nvar hex6 = '\\\\#[0-9a-fA-F]{6}';\n\nvar ascending = function ascending(a, b) {\n if (a < b) {\n return -1;\n } else if (a > b) {\n return 1;\n } else {\n return 0;\n }\n};\nvar descending = function descending(a, b) {\n return -1 * ascending(a, b);\n};\n\nvar extend = Object.assign != null ? Object.assign.bind(Object) : function (tgt) {\n var args = arguments;\n for (var i = 1; i < args.length; i++) {\n var obj = args[i];\n if (obj == null) {\n continue;\n }\n var keys = Object.keys(obj);\n for (var j = 0; j < keys.length; j++) {\n var k = keys[j];\n tgt[k] = obj[k];\n }\n }\n return tgt;\n};\n\n// get [r, g, b] from #abc or #aabbcc\nvar hex2tuple = function hex2tuple(hex) {\n if (!(hex.length === 4 || hex.length === 7) || hex[0] !== '#') {\n return;\n }\n var shortHex = hex.length === 4;\n var r, g, b;\n var base = 16;\n if (shortHex) {\n r = parseInt(hex[1] + hex[1], base);\n g = parseInt(hex[2] + hex[2], base);\n b = parseInt(hex[3] + hex[3], base);\n } else {\n r = parseInt(hex[1] + hex[2], base);\n g = parseInt(hex[3] + hex[4], base);\n b = parseInt(hex[5] + hex[6], base);\n }\n return [r, g, b];\n};\n\n// get [r, g, b, a] from hsl(0, 0, 0) or hsla(0, 0, 0, 0)\nvar hsl2tuple = function hsl2tuple(hsl) {\n var ret;\n var h, s, l, a, r, g, b;\n function hue2rgb(p, q, t) {\n if (t < 0) t += 1;\n if (t > 1) t -= 1;\n if (t < 1 / 6) return p + (q - p) * 6 * t;\n if (t < 1 / 2) return q;\n if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;\n return p;\n }\n var m = new RegExp('^' + hsla + '$').exec(hsl);\n if (m) {\n // get hue\n h = parseInt(m[1]);\n if (h < 0) {\n h = (360 - -1 * h % 360) % 360;\n } else if (h > 360) {\n h = h % 360;\n }\n h /= 360; // normalise on [0, 1]\n\n s = parseFloat(m[2]);\n if (s < 0 || s > 100) {\n return;\n } // saturation is [0, 100]\n s = s / 100; // normalise on [0, 1]\n\n l = parseFloat(m[3]);\n if (l < 0 || l > 100) {\n return;\n } // lightness is [0, 100]\n l = l / 100; // normalise on [0, 1]\n\n a = m[4];\n if (a !== undefined) {\n a = parseFloat(a);\n if (a < 0 || a > 1) {\n return;\n } // alpha is [0, 1]\n }\n\n // now, convert to rgb\n // code from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript\n if (s === 0) {\n r = g = b = Math.round(l * 255); // achromatic\n } else {\n var q = l < 0.5 ? l * (1 + s) : l + s - l * s;\n var p = 2 * l - q;\n r = Math.round(255 * hue2rgb(p, q, h + 1 / 3));\n g = Math.round(255 * hue2rgb(p, q, h));\n b = Math.round(255 * hue2rgb(p, q, h - 1 / 3));\n }\n ret = [r, g, b, a];\n }\n return ret;\n};\n\n// get [r, g, b, a] from rgb(0, 0, 0) or rgba(0, 0, 0, 0)\nvar rgb2tuple = function rgb2tuple(rgb) {\n var ret;\n var m = new RegExp('^' + rgba + '$').exec(rgb);\n if (m) {\n ret = [];\n var isPct = [];\n for (var i = 1; i <= 3; i++) {\n var channel = m[i];\n if (channel[channel.length - 1] === '%') {\n isPct[i] = true;\n }\n channel = parseFloat(channel);\n if (isPct[i]) {\n channel = channel / 100 * 255; // normalise to [0, 255]\n }\n if (channel < 0 || channel > 255) {\n return;\n } // invalid channel value\n\n ret.push(Math.floor(channel));\n }\n var atLeastOneIsPct = isPct[1] || isPct[2] || isPct[3];\n var allArePct = isPct[1] && isPct[2] && isPct[3];\n if (atLeastOneIsPct && !allArePct) {\n return;\n } // must all be percent values if one is\n\n var alpha = m[4];\n if (alpha !== undefined) {\n alpha = parseFloat(alpha);\n if (alpha < 0 || alpha > 1) {\n return;\n } // invalid alpha value\n\n ret.push(alpha);\n }\n }\n return ret;\n};\nvar colorname2tuple = function colorname2tuple(color) {\n return colors[color.toLowerCase()];\n};\nvar color2tuple = function color2tuple(color) {\n return (array(color) ? color : null) || colorname2tuple(color) || hex2tuple(color) || rgb2tuple(color) || hsl2tuple(color);\n};\nvar colors = {\n // special colour names\n transparent: [0, 0, 0, 0],\n // NB alpha === 0\n\n // regular colours\n aliceblue: [240, 248, 255],\n antiquewhite: [250, 235, 215],\n aqua: [0, 255, 255],\n aquamarine: [127, 255, 212],\n azure: [240, 255, 255],\n beige: [245, 245, 220],\n bisque: [255, 228, 196],\n black: [0, 0, 0],\n blanchedalmond: [255, 235, 205],\n blue: [0, 0, 255],\n blueviolet: [138, 43, 226],\n brown: [165, 42, 42],\n burlywood: [222, 184, 135],\n cadetblue: [95, 158, 160],\n chartreuse: [127, 255, 0],\n chocolate: [210, 105, 30],\n coral: [255, 127, 80],\n cornflowerblue: [100, 149, 237],\n cornsilk: [255, 248, 220],\n crimson: [220, 20, 60],\n cyan: [0, 255, 255],\n darkblue: [0, 0, 139],\n darkcyan: [0, 139, 139],\n darkgoldenrod: [184, 134, 11],\n darkgray: [169, 169, 169],\n darkgreen: [0, 100, 0],\n darkgrey: [169, 169, 169],\n darkkhaki: [189, 183, 107],\n darkmagenta: [139, 0, 139],\n darkolivegreen: [85, 107, 47],\n darkorange: [255, 140, 0],\n darkorchid: [153, 50, 204],\n darkred: [139, 0, 0],\n darksalmon: [233, 150, 122],\n darkseagreen: [143, 188, 143],\n darkslateblue: [72, 61, 139],\n darkslategray: [47, 79, 79],\n darkslategrey: [47, 79, 79],\n darkturquoise: [0, 206, 209],\n darkviolet: [148, 0, 211],\n deeppink: [255, 20, 147],\n deepskyblue: [0, 191, 255],\n dimgray: [105, 105, 105],\n dimgrey: [105, 105, 105],\n dodgerblue: [30, 144, 255],\n firebrick: [178, 34, 34],\n floralwhite: [255, 250, 240],\n forestgreen: [34, 139, 34],\n fuchsia: [255, 0, 255],\n gainsboro: [220, 220, 220],\n ghostwhite: [248, 248, 255],\n gold: [255, 215, 0],\n goldenrod: [218, 165, 32],\n gray: [128, 128, 128],\n grey: [128, 128, 128],\n green: [0, 128, 0],\n greenyellow: [173, 255, 47],\n honeydew: [240, 255, 240],\n hotpink: [255, 105, 180],\n indianred: [205, 92, 92],\n indigo: [75, 0, 130],\n ivory: [255, 255, 240],\n khaki: [240, 230, 140],\n lavender: [230, 230, 250],\n lavenderblush: [255, 240, 245],\n lawngreen: [124, 252, 0],\n lemonchiffon: [255, 250, 205],\n lightblue: [173, 216, 230],\n lightcoral: [240, 128, 128],\n lightcyan: [224, 255, 255],\n lightgoldenrodyellow: [250, 250, 210],\n lightgray: [211, 211, 211],\n lightgreen: [144, 238, 144],\n lightgrey: [211, 211, 211],\n lightpink: [255, 182, 193],\n lightsalmon: [255, 160, 122],\n lightseagreen: [32, 178, 170],\n lightskyblue: [135, 206, 250],\n lightslategray: [119, 136, 153],\n lightslategrey: [119, 136, 153],\n lightsteelblue: [176, 196, 222],\n lightyellow: [255, 255, 224],\n lime: [0, 255, 0],\n limegreen: [50, 205, 50],\n linen: [250, 240, 230],\n magenta: [255, 0, 255],\n maroon: [128, 0, 0],\n mediumaquamarine: [102, 205, 170],\n mediumblue: [0, 0, 205],\n mediumorchid: [186, 85, 211],\n mediumpurple: [147, 112, 219],\n mediumseagreen: [60, 179, 113],\n mediumslateblue: [123, 104, 238],\n mediumspringgreen: [0, 250, 154],\n mediumturquoise: [72, 209, 204],\n mediumvioletred: [199, 21, 133],\n midnightblue: [25, 25, 112],\n mintcream: [245, 255, 250],\n mistyrose: [255, 228, 225],\n moccasin: [255, 228, 181],\n navajowhite: [255, 222, 173],\n navy: [0, 0, 128],\n oldlace: [253, 245, 230],\n olive: [128, 128, 0],\n olivedrab: [107, 142, 35],\n orange: [255, 165, 0],\n orangered: [255, 69, 0],\n orchid: [218, 112, 214],\n palegoldenrod: [238, 232, 170],\n palegreen: [152, 251, 152],\n paleturquoise: [175, 238, 238],\n palevioletred: [219, 112, 147],\n papayawhip: [255, 239, 213],\n peachpuff: [255, 218, 185],\n peru: [205, 133, 63],\n pink: [255, 192, 203],\n plum: [221, 160, 221],\n powderblue: [176, 224, 230],\n purple: [128, 0, 128],\n red: [255, 0, 0],\n rosybrown: [188, 143, 143],\n royalblue: [65, 105, 225],\n saddlebrown: [139, 69, 19],\n salmon: [250, 128, 114],\n sandybrown: [244, 164, 96],\n seagreen: [46, 139, 87],\n seashell: [255, 245, 238],\n sienna: [160, 82, 45],\n silver: [192, 192, 192],\n skyblue: [135, 206, 235],\n slateblue: [106, 90, 205],\n slategray: [112, 128, 144],\n slategrey: [112, 128, 144],\n snow: [255, 250, 250],\n springgreen: [0, 255, 127],\n steelblue: [70, 130, 180],\n tan: [210, 180, 140],\n teal: [0, 128, 128],\n thistle: [216, 191, 216],\n tomato: [255, 99, 71],\n turquoise: [64, 224, 208],\n violet: [238, 130, 238],\n wheat: [245, 222, 179],\n white: [255, 255, 255],\n whitesmoke: [245, 245, 245],\n yellow: [255, 255, 0],\n yellowgreen: [154, 205, 50]\n};\n\n// sets the value in a map (map may not be built)\nvar setMap = function setMap(options) {\n var obj = options.map;\n var keys = options.keys;\n var l = keys.length;\n for (var i = 0; i < l; i++) {\n var key = keys[i];\n if (plainObject(key)) {\n throw Error('Tried to set map with object key');\n }\n if (i < keys.length - 1) {\n // extend the map if necessary\n if (obj[key] == null) {\n obj[key] = {};\n }\n obj = obj[key];\n } else {\n // set the value\n obj[key] = options.value;\n }\n }\n};\n\n// gets the value in a map even if it's not built in places\nvar getMap = function getMap(options) {\n var obj = options.map;\n var keys = options.keys;\n var l = keys.length;\n for (var i = 0; i < l; i++) {\n var key = keys[i];\n if (plainObject(key)) {\n throw Error('Tried to get map with object key');\n }\n obj = obj[key];\n if (obj == null) {\n return obj;\n }\n }\n return obj;\n};\n\nvar commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\nfunction getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\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\nvar isObject_1;\nvar hasRequiredIsObject;\n\nfunction requireIsObject () {\n\tif (hasRequiredIsObject) return isObject_1;\n\thasRequiredIsObject = 1;\n\tfunction isObject(value) {\n\t var type = typeof value;\n\t return value != null && (type == 'object' || type == 'function');\n\t}\n\n\tisObject_1 = isObject;\n\treturn isObject_1;\n}\n\n/** Detect free variable `global` from Node.js. */\n\nvar _freeGlobal;\nvar hasRequired_freeGlobal;\n\nfunction require_freeGlobal () {\n\tif (hasRequired_freeGlobal) return _freeGlobal;\n\thasRequired_freeGlobal = 1;\n\tvar freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;\n\n\t_freeGlobal = freeGlobal;\n\treturn _freeGlobal;\n}\n\nvar _root;\nvar hasRequired_root;\n\nfunction require_root () {\n\tif (hasRequired_root) return _root;\n\thasRequired_root = 1;\n\tvar freeGlobal = require_freeGlobal();\n\n\t/** Detect free variable `self`. */\n\tvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n\t/** Used as a reference to the global object. */\n\tvar root = freeGlobal || freeSelf || Function('return this')();\n\n\t_root = root;\n\treturn _root;\n}\n\nvar now_1;\nvar hasRequiredNow;\n\nfunction requireNow () {\n\tif (hasRequiredNow) return now_1;\n\thasRequiredNow = 1;\n\tvar root = require_root();\n\n\t/**\n\t * Gets the timestamp of the number of milliseconds that have elapsed since\n\t * the Unix epoch (1 January 1970 00:00:00 UTC).\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 2.4.0\n\t * @category Date\n\t * @returns {number} Returns the timestamp.\n\t * @example\n\t *\n\t * _.defer(function(stamp) {\n\t * console.log(_.now() - stamp);\n\t * }, _.now());\n\t * // => Logs the number of milliseconds it took for the deferred invocation.\n\t */\n\tvar now = function() {\n\t return root.Date.now();\n\t};\n\n\tnow_1 = now;\n\treturn now_1;\n}\n\n/** Used to match a single whitespace character. */\n\nvar _trimmedEndIndex;\nvar hasRequired_trimmedEndIndex;\n\nfunction require_trimmedEndIndex () {\n\tif (hasRequired_trimmedEndIndex) return _trimmedEndIndex;\n\thasRequired_trimmedEndIndex = 1;\n\tvar reWhitespace = /\\s/;\n\n\t/**\n\t * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n\t * character of `string`.\n\t *\n\t * @private\n\t * @param {string} string The string to inspect.\n\t * @returns {number} Returns the index of the last non-whitespace character.\n\t */\n\tfunction trimmedEndIndex(string) {\n\t var index = string.length;\n\n\t while (index-- && reWhitespace.test(string.charAt(index))) {}\n\t return index;\n\t}\n\n\t_trimmedEndIndex = trimmedEndIndex;\n\treturn _trimmedEndIndex;\n}\n\nvar _baseTrim;\nvar hasRequired_baseTrim;\n\nfunction require_baseTrim () {\n\tif (hasRequired_baseTrim) return _baseTrim;\n\thasRequired_baseTrim = 1;\n\tvar trimmedEndIndex = require_trimmedEndIndex();\n\n\t/** Used to match leading whitespace. */\n\tvar reTrimStart = /^\\s+/;\n\n\t/**\n\t * The base implementation of `_.trim`.\n\t *\n\t * @private\n\t * @param {string} string The string to trim.\n\t * @returns {string} Returns the trimmed string.\n\t */\n\tfunction baseTrim(string) {\n\t return string\n\t ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n\t : string;\n\t}\n\n\t_baseTrim = baseTrim;\n\treturn _baseTrim;\n}\n\nvar _Symbol;\nvar hasRequired_Symbol;\n\nfunction require_Symbol () {\n\tif (hasRequired_Symbol) return _Symbol;\n\thasRequired_Symbol = 1;\n\tvar root = require_root();\n\n\t/** Built-in value references. */\n\tvar Symbol = root.Symbol;\n\n\t_Symbol = Symbol;\n\treturn _Symbol;\n}\n\nvar _getRawTag;\nvar hasRequired_getRawTag;\n\nfunction require_getRawTag () {\n\tif (hasRequired_getRawTag) return _getRawTag;\n\thasRequired_getRawTag = 1;\n\tvar Symbol = require_Symbol();\n\n\t/** Used for built-in method references. */\n\tvar objectProto = Object.prototype;\n\n\t/** Used to check objects for own properties. */\n\tvar hasOwnProperty = objectProto.hasOwnProperty;\n\n\t/**\n\t * Used to resolve the\n\t * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n\t * of values.\n\t */\n\tvar nativeObjectToString = objectProto.toString;\n\n\t/** Built-in value references. */\n\tvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n\t/**\n\t * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n\t *\n\t * @private\n\t * @param {*} value The value to query.\n\t * @returns {string} Returns the raw `toStringTag`.\n\t */\n\tfunction getRawTag(value) {\n\t var isOwn = hasOwnProperty.call(value, symToStringTag),\n\t tag = value[symToStringTag];\n\n\t try {\n\t value[symToStringTag] = undefined;\n\t var unmasked = true;\n\t } catch (e) {}\n\n\t var result = nativeObjectToString.call(value);\n\t if (unmasked) {\n\t if (isOwn) {\n\t value[symToStringTag] = tag;\n\t } else {\n\t delete value[symToStringTag];\n\t }\n\t }\n\t return result;\n\t}\n\n\t_getRawTag = getRawTag;\n\treturn _getRawTag;\n}\n\n/** Used for built-in method references. */\n\nvar _objectToString;\nvar hasRequired_objectToString;\n\nfunction require_objectToString () {\n\tif (hasRequired_objectToString) return _objectToString;\n\thasRequired_objectToString = 1;\n\tvar objectProto = Object.prototype;\n\n\t/**\n\t * Used to resolve the\n\t * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n\t * of values.\n\t */\n\tvar nativeObjectToString = objectProto.toString;\n\n\t/**\n\t * Converts `value` to a string using `Object.prototype.toString`.\n\t *\n\t * @private\n\t * @param {*} value The value to convert.\n\t * @returns {string} Returns the converted string.\n\t */\n\tfunction objectToString(value) {\n\t return nativeObjectToString.call(value);\n\t}\n\n\t_objectToString = objectToString;\n\treturn _objectToString;\n}\n\nvar _baseGetTag;\nvar hasRequired_baseGetTag;\n\nfunction require_baseGetTag () {\n\tif (hasRequired_baseGetTag) return _baseGetTag;\n\thasRequired_baseGetTag = 1;\n\tvar Symbol = require_Symbol(),\n\t getRawTag = require_getRawTag(),\n\t objectToString = require_objectToString();\n\n\t/** `Object#toString` result references. */\n\tvar nullTag = '[object Null]',\n\t undefinedTag = '[object Undefined]';\n\n\t/** Built-in value references. */\n\tvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n\t/**\n\t * The base implementation of `getTag` without fallbacks for buggy environments.\n\t *\n\t * @private\n\t * @param {*} value The value to query.\n\t * @returns {string} Returns the `toStringTag`.\n\t */\n\tfunction baseGetTag(value) {\n\t if (value == null) {\n\t return value === undefined ? undefinedTag : nullTag;\n\t }\n\t return (symToStringTag && symToStringTag in Object(value))\n\t ? getRawTag(value)\n\t : objectToString(value);\n\t}\n\n\t_baseGetTag = baseGetTag;\n\treturn _baseGetTag;\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\nvar isObjectLike_1;\nvar hasRequiredIsObjectLike;\n\nfunction requireIsObjectLike () {\n\tif (hasRequiredIsObjectLike) return isObjectLike_1;\n\thasRequiredIsObjectLike = 1;\n\tfunction isObjectLike(value) {\n\t return value != null && typeof value == 'object';\n\t}\n\n\tisObjectLike_1 = isObjectLike;\n\treturn isObjectLike_1;\n}\n\nvar isSymbol_1;\nvar hasRequiredIsSymbol;\n\nfunction requireIsSymbol () {\n\tif (hasRequiredIsSymbol) return isSymbol_1;\n\thasRequiredIsSymbol = 1;\n\tvar baseGetTag = require_baseGetTag(),\n\t isObjectLike = requireIsObjectLike();\n\n\t/** `Object#toString` result references. */\n\tvar symbolTag = '[object Symbol]';\n\n\t/**\n\t * Checks if `value` is classified as a `Symbol` primitive or object.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 4.0.0\n\t * @category Lang\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n\t * @example\n\t *\n\t * _.isSymbol(Symbol.iterator);\n\t * // => true\n\t *\n\t * _.isSymbol('abc');\n\t * // => false\n\t */\n\tfunction isSymbol(value) {\n\t return typeof value == 'symbol' ||\n\t (isObjectLike(value) && baseGetTag(value) == symbolTag);\n\t}\n\n\tisSymbol_1 = isSymbol;\n\treturn isSymbol_1;\n}\n\nvar toNumber_1;\nvar hasRequiredToNumber;\n\nfunction requireToNumber () {\n\tif (hasRequiredToNumber) return toNumber_1;\n\thasRequiredToNumber = 1;\n\tvar baseTrim = require_baseTrim(),\n\t isObject = requireIsObject(),\n\t isSymbol = requireIsSymbol();\n\n\t/** Used as references for various `Number` constants. */\n\tvar NAN = 0 / 0;\n\n\t/** Used to detect bad signed hexadecimal string values. */\n\tvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n\t/** Used to detect binary string values. */\n\tvar reIsBinary = /^0b[01]+$/i;\n\n\t/** Used to detect octal string values. */\n\tvar reIsOctal = /^0o[0-7]+$/i;\n\n\t/** Built-in method references without a dependency on `root`. */\n\tvar freeParseInt = parseInt;\n\n\t/**\n\t * Converts `value` to a number.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 4.0.0\n\t * @category Lang\n\t * @param {*} value The value to process.\n\t * @returns {number} Returns the number.\n\t * @example\n\t *\n\t * _.toNumber(3.2);\n\t * // => 3.2\n\t *\n\t * _.toNumber(Number.MIN_VALUE);\n\t * // => 5e-324\n\t *\n\t * _.toNumber(Infinity);\n\t * // => Infinity\n\t *\n\t * _.toNumber('3.2');\n\t * // => 3.2\n\t */\n\tfunction toNumber(value) {\n\t if (typeof value == 'number') {\n\t return value;\n\t }\n\t if (isSymbol(value)) {\n\t return NAN;\n\t }\n\t if (isObject(value)) {\n\t var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n\t value = isObject(other) ? (other + '') : other;\n\t }\n\t if (typeof value != 'string') {\n\t return value === 0 ? value : +value;\n\t }\n\t value = baseTrim(value);\n\t var isBinary = reIsBinary.test(value);\n\t return (isBinary || reIsOctal.test(value))\n\t ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n\t : (reIsBadHex.test(value) ? NAN : +value);\n\t}\n\n\ttoNumber_1 = toNumber;\n\treturn toNumber_1;\n}\n\nvar debounce_1;\nvar hasRequiredDebounce;\n\nfunction requireDebounce () {\n\tif (hasRequiredDebounce) return debounce_1;\n\thasRequiredDebounce = 1;\n\tvar isObject = requireIsObject(),\n\t now = requireNow(),\n\t toNumber = requireToNumber();\n\n\t/** Error message constants. */\n\tvar FUNC_ERROR_TEXT = 'Expected a function';\n\n\t/* Built-in method references for those with the same name as other `lodash` methods. */\n\tvar nativeMax = Math.max,\n\t nativeMin = Math.min;\n\n\t/**\n\t * Creates a debounced function that delays invoking `func` until after `wait`\n\t * milliseconds have elapsed since the last time the debounced function was\n\t * invoked. The debounced function comes with a `cancel` method to cancel\n\t * delayed `func` invocations and a `flush` method to immediately invoke them.\n\t * Provide `options` to indicate whether `func` should be invoked on the\n\t * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n\t * with the last arguments provided to the debounced function. Subsequent\n\t * calls to the debounced function return the result of the last `func`\n\t * invocation.\n\t *\n\t * **Note:** If `leading` and `trailing` options are `true`, `func` is\n\t * invoked on the trailing edge of the timeout only if the debounced function\n\t * is invoked more than once during the `wait` timeout.\n\t *\n\t * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n\t * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n\t *\n\t * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n\t * for details over the differences between `_.debounce` and `_.throttle`.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 0.1.0\n\t * @category Function\n\t * @param {Function} func The function to debounce.\n\t * @param {number} [wait=0] The number of milliseconds to delay.\n\t * @param {Object} [options={}] The options object.\n\t * @param {boolean} [options.leading=false]\n\t * Specify invoking on the leading edge of the timeout.\n\t * @param {number} [options.maxWait]\n\t * The maximum time `func` is allowed to be delayed before it's invoked.\n\t * @param {boolean} [options.trailing=true]\n\t * Specify invoking on the trailing edge of the timeout.\n\t * @returns {Function} Returns the new debounced function.\n\t * @example\n\t *\n\t * // Avoid costly calculations while the window size is in flux.\n\t * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n\t *\n\t * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n\t * jQuery(element).on('click', _.debounce(sendMail, 300, {\n\t * 'leading': true,\n\t * 'trailing': false\n\t * }));\n\t *\n\t * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n\t * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n\t * var source = new EventSource('/stream');\n\t * jQuery(source).on('message', debounced);\n\t *\n\t * // Cancel the trailing debounced invocation.\n\t * jQuery(window).on('popstate', debounced.cancel);\n\t */\n\tfunction debounce(func, wait, options) {\n\t var lastArgs,\n\t lastThis,\n\t maxWait,\n\t result,\n\t timerId,\n\t lastCallTime,\n\t lastInvokeTime = 0,\n\t leading = false,\n\t maxing = false,\n\t trailing = true;\n\n\t if (typeof func != 'function') {\n\t throw new TypeError(FUNC_ERROR_TEXT);\n\t }\n\t wait = toNumber(wait) || 0;\n\t if (isObject(options)) {\n\t leading = !!options.leading;\n\t maxing = 'maxWait' in options;\n\t maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n\t trailing = 'trailing' in options ? !!options.trailing : trailing;\n\t }\n\n\t function invokeFunc(time) {\n\t var args = lastArgs,\n\t thisArg = lastThis;\n\n\t lastArgs = lastThis = undefined;\n\t lastInvokeTime = time;\n\t result = func.apply(thisArg, args);\n\t return result;\n\t }\n\n\t function leadingEdge(time) {\n\t // Reset any `maxWait` timer.\n\t lastInvokeTime = time;\n\t // Start the timer for the trailing edge.\n\t timerId = setTimeout(timerExpired, wait);\n\t // Invoke the leading edge.\n\t return leading ? invokeFunc(time) : result;\n\t }\n\n\t function remainingWait(time) {\n\t var timeSinceLastCall = time - lastCallTime,\n\t timeSinceLastInvoke = time - lastInvokeTime,\n\t timeWaiting = wait - timeSinceLastCall;\n\n\t return maxing\n\t ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n\t : timeWaiting;\n\t }\n\n\t function shouldInvoke(time) {\n\t var timeSinceLastCall = time - lastCallTime,\n\t timeSinceLastInvoke = time - lastInvokeTime;\n\n\t // Either this is the first call, activity has stopped and we're at the\n\t // trailing edge, the system time has gone backwards and we're treating\n\t // it as the trailing edge, or we've hit the `maxWait` limit.\n\t return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n\t (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n\t }\n\n\t function timerExpired() {\n\t var time = now();\n\t if (shouldInvoke(time)) {\n\t return trailingEdge(time);\n\t }\n\t // Restart the timer.\n\t timerId = setTimeout(timerExpired, remainingWait(time));\n\t }\n\n\t function trailingEdge(time) {\n\t timerId = undefined;\n\n\t // Only invoke if we have `lastArgs` which means `func` has been\n\t // debounced at least once.\n\t if (trailing && lastArgs) {\n\t return invokeFunc(time);\n\t }\n\t lastArgs = lastThis = undefined;\n\t return result;\n\t }\n\n\t function cancel() {\n\t if (timerId !== undefined) {\n\t clearTimeout(timerId);\n\t }\n\t lastInvokeTime = 0;\n\t lastArgs = lastCallTime = lastThis = timerId = undefined;\n\t }\n\n\t function flush() {\n\t return timerId === undefined ? result : trailingEdge(now());\n\t }\n\n\t function debounced() {\n\t var time = now(),\n\t isInvoking = shouldInvoke(time);\n\n\t lastArgs = arguments;\n\t lastThis = this;\n\t lastCallTime = time;\n\n\t if (isInvoking) {\n\t if (timerId === undefined) {\n\t return leadingEdge(lastCallTime);\n\t }\n\t if (maxing) {\n\t // Handle invocations in a tight loop.\n\t clearTimeout(timerId);\n\t timerId = setTimeout(timerExpired, wait);\n\t return invokeFunc(lastCallTime);\n\t }\n\t }\n\t if (timerId === undefined) {\n\t timerId = setTimeout(timerExpired, wait);\n\t }\n\t return result;\n\t }\n\t debounced.cancel = cancel;\n\t debounced.flush = flush;\n\t return debounced;\n\t}\n\n\tdebounce_1 = debounce;\n\treturn debounce_1;\n}\n\nvar debounceExports = requireDebounce();\nvar debounce = /*@__PURE__*/getDefaultExportFromCjs(debounceExports);\n\nvar performance$1 = _window ? _window.performance : null;\nvar pnow = performance$1 && performance$1.now ? function () {\n return performance$1.now();\n} : function () {\n return Date.now();\n};\nvar raf = function () {\n if (_window) {\n if (_window.requestAnimationFrame) {\n return function (fn) {\n _window.requestAnimationFrame(fn);\n };\n } else if (_window.mozRequestAnimationFrame) {\n return function (fn) {\n _window.mozRequestAnimationFrame(fn);\n };\n } else if (_window.webkitRequestAnimationFrame) {\n return function (fn) {\n _window.webkitRequestAnimationFrame(fn);\n };\n } else if (_window.msRequestAnimationFrame) {\n return function (fn) {\n _window.msRequestAnimationFrame(fn);\n };\n }\n }\n return function (fn) {\n if (fn) {\n setTimeout(function () {\n fn(pnow());\n }, 1000 / 60);\n }\n };\n}();\nvar requestAnimationFrame = function requestAnimationFrame(fn) {\n return raf(fn);\n};\nvar performanceNow = pnow;\n\nvar DEFAULT_HASH_SEED = 9261;\nvar K = 65599; // 37 also works pretty well\nvar DEFAULT_HASH_SEED_ALT = 5381;\nvar hashIterableInts = function hashIterableInts(iterator) {\n var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED;\n // sdbm/string-hash\n var hash = seed;\n var entry;\n for (;;) {\n entry = iterator.next();\n if (entry.done) {\n break;\n }\n hash = hash * K + entry.value | 0;\n }\n return hash;\n};\nvar hashInt = function hashInt(num) {\n var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED;\n // sdbm/string-hash\n return seed * K + num | 0;\n};\nvar hashIntAlt = function hashIntAlt(num) {\n var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED_ALT;\n // djb2/string-hash\n return (seed << 5) + seed + num | 0;\n};\nvar combineHashes = function combineHashes(hash1, hash2) {\n return hash1 * 0x200000 + hash2;\n};\nvar combineHashesArray = function combineHashesArray(hashes) {\n return hashes[0] * 0x200000 + hashes[1];\n};\nvar hashArrays = function hashArrays(hashes1, hashes2) {\n return [hashInt(hashes1[0], hashes2[0]), hashIntAlt(hashes1[1], hashes2[1])];\n};\nvar hashIntsArray = function hashIntsArray(ints, seed) {\n var entry = {\n value: 0,\n done: false\n };\n var i = 0;\n var length = ints.length;\n var iterator = {\n next: function next() {\n if (i < length) {\n entry.value = ints[i++];\n } else {\n entry.done = true;\n }\n return entry;\n }\n };\n return hashIterableInts(iterator, seed);\n};\nvar hashString = function hashString(str, seed) {\n var entry = {\n value: 0,\n done: false\n };\n var i = 0;\n var length = str.length;\n var iterator = {\n next: function next() {\n if (i < length) {\n entry.value = str.charCodeAt(i++);\n } else {\n entry.done = true;\n }\n return entry;\n }\n };\n return hashIterableInts(iterator, seed);\n};\nvar hashStrings = function hashStrings() {\n return hashStringsArray(arguments);\n};\nvar hashStringsArray = function hashStringsArray(strs) {\n var hash;\n for (var i = 0; i < strs.length; i++) {\n var str = strs[i];\n if (i === 0) {\n hash = hashString(str);\n } else {\n hash = hashString(str, hash);\n }\n }\n return hash;\n};\n\nfunction rotatePoint(x, y, centerX, centerY, angleDegrees) {\n var angleRadians = angleDegrees * Math.PI / 180;\n var rotatedX = Math.cos(angleRadians) * (x - centerX) - Math.sin(angleRadians) * (y - centerY) + centerX;\n var rotatedY = Math.sin(angleRadians) * (x - centerX) + Math.cos(angleRadians) * (y - centerY) + centerY;\n return {\n x: rotatedX,\n y: rotatedY\n };\n}\nvar movePointByBoxAspect = function movePointByBoxAspect(x, y, boxX, boxY, skewX, skewY) {\n return {\n x: (x - boxX) * skewX + boxX,\n y: (y - boxY) * skewY + boxY\n };\n};\nfunction rotatePosAndSkewByBox(pos, box, angleDegrees) {\n if (angleDegrees === 0) return pos;\n var centerX = (box.x1 + box.x2) / 2;\n var centerY = (box.y1 + box.y2) / 2;\n var skewX = box.w / box.h;\n var skewY = 1 / skewX;\n var rotated = rotatePoint(pos.x, pos.y, centerX, centerY, angleDegrees);\n var skewed = movePointByBoxAspect(rotated.x, rotated.y, centerX, centerY, skewX, skewY);\n return {\n x: skewed.x,\n y: skewed.y\n };\n}\n\nvar warningsEnabled = true;\nvar warnSupported = console.warn != null;\nvar traceSupported = console.trace != null;\nvar MAX_INT$1 = Number.MAX_SAFE_INTEGER || 9007199254740991;\nvar trueify = function trueify() {\n return true;\n};\nvar falsify = function falsify() {\n return false;\n};\nvar zeroify = function zeroify() {\n return 0;\n};\nvar noop$1 = function noop() {};\nvar error = function error(msg) {\n throw new Error(msg);\n};\nvar warnings = function warnings(enabled) {\n if (enabled !== undefined) {\n warningsEnabled = !!enabled;\n } else {\n return warningsEnabled;\n }\n};\nvar warn = function warn(msg) {\n if (!warnings()) {\n return;\n }\n if (warnSupported) {\n console.warn(msg);\n } else {\n console.log(msg);\n if (traceSupported) {\n console.trace();\n }\n }\n};\nvar clone = function clone(obj) {\n return extend({}, obj);\n};\n\n// gets a shallow copy of the argument\nvar copy = function copy(obj) {\n if (obj == null) {\n return obj;\n }\n if (array(obj)) {\n return obj.slice();\n } else if (plainObject(obj)) {\n return clone(obj);\n } else {\n return obj;\n }\n};\nvar copyArray = function copyArray(arr) {\n return arr.slice();\n};\nvar uuid = function uuid(a, b /* placeholders */) {\n for (\n // loop :)\n b = a = '';\n // b - result , a - numeric letiable\n a++ < 36;\n //\n b += a * 51 & 52 // if \"a\" is not 9 or 14 or 19 or 24\n ?\n // return a random number or 4\n (a ^ 15 // if \"a\" is not 15\n ?\n // generate a random number from 0 to 15\n 8 ^ Math.random() * (a ^ 20 ? 16 : 4) // unless \"a\" is 20, in which case a random number from 8 to 11\n : 4 // otherwise 4\n ).toString(16) : '-' // in other cases (if \"a\" is 9,14,19,24) insert \"-\"\n );\n return b;\n};\nvar _staticEmptyObject = {};\nvar staticEmptyObject = function staticEmptyObject() {\n return _staticEmptyObject;\n};\nvar defaults$g = function defaults(_defaults) {\n var keys = Object.keys(_defaults);\n return function (opts) {\n var filledOpts = {};\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var optVal = opts == null ? undefined : opts[key];\n filledOpts[key] = optVal === undefined ? _defaults[key] : optVal;\n }\n return filledOpts;\n };\n};\nvar removeFromArray = function removeFromArray(arr, ele, oneCopy) {\n for (var i = arr.length - 1; i >= 0; i--) {\n if (arr[i] === ele) {\n arr.splice(i, 1);\n }\n }\n};\nvar clearArray = function clearArray(arr) {\n arr.splice(0, arr.length);\n};\nvar push = function push(arr, otherArr) {\n for (var i = 0; i < otherArr.length; i++) {\n var el = otherArr[i];\n arr.push(el);\n }\n};\nvar getPrefixedProperty = function getPrefixedProperty(obj, propName, prefix) {\n if (prefix) {\n propName = prependCamel(prefix, propName); // e.g. (labelWidth, source) => sourceLabelWidth\n }\n return obj[propName];\n};\nvar setPrefixedProperty = function setPrefixedProperty(obj, propName, prefix, value) {\n if (prefix) {\n propName = prependCamel(prefix, propName); // e.g. (labelWidth, source) => sourceLabelWidth\n }\n obj[propName] = value;\n};\n\n/* global Map */\nvar ObjectMap = /*#__PURE__*/function () {\n function ObjectMap() {\n _classCallCheck(this, ObjectMap);\n this._obj = {};\n }\n return _createClass(ObjectMap, [{\n key: \"set\",\n value: function set(key, val) {\n this._obj[key] = val;\n return this;\n }\n }, {\n key: \"delete\",\n value: function _delete(key) {\n this._obj[key] = undefined;\n return this;\n }\n }, {\n key: \"clear\",\n value: function clear() {\n this._obj = {};\n }\n }, {\n key: \"has\",\n value: function has(key) {\n return this._obj[key] !== undefined;\n }\n }, {\n key: \"get\",\n value: function get(key) {\n return this._obj[key];\n }\n }]);\n}();\nvar Map$1 = typeof Map !== 'undefined' ? Map : ObjectMap;\n\n/* global Set */\n\nvar undef = \"undefined\" ;\nvar ObjectSet = /*#__PURE__*/function () {\n function ObjectSet(arrayOrObjectSet) {\n _classCallCheck(this, ObjectSet);\n this._obj = Object.create(null);\n this.size = 0;\n if (arrayOrObjectSet != null) {\n var arr;\n if (arrayOrObjectSet.instanceString != null && arrayOrObjectSet.instanceString() === this.instanceString()) {\n arr = arrayOrObjectSet.toArray();\n } else {\n arr = arrayOrObjectSet;\n }\n for (var i = 0; i < arr.length; i++) {\n this.add(arr[i]);\n }\n }\n }\n return _createClass(ObjectSet, [{\n key: \"instanceString\",\n value: function instanceString() {\n return 'set';\n }\n }, {\n key: \"add\",\n value: function add(val) {\n var o = this._obj;\n if (o[val] !== 1) {\n o[val] = 1;\n this.size++;\n }\n }\n }, {\n key: \"delete\",\n value: function _delete(val) {\n var o = this._obj;\n if (o[val] === 1) {\n o[val] = 0;\n this.size--;\n }\n }\n }, {\n key: \"clear\",\n value: function clear() {\n this._obj = Object.create(null);\n }\n }, {\n key: \"has\",\n value: function has(val) {\n return this._obj[val] === 1;\n }\n }, {\n key: \"toArray\",\n value: function toArray() {\n var _this = this;\n return Object.keys(this._obj).filter(function (key) {\n return _this.has(key);\n });\n }\n }, {\n key: \"forEach\",\n value: function forEach(callback, thisArg) {\n return this.toArray().forEach(callback, thisArg);\n }\n }]);\n}();\nvar Set$1 = (typeof Set === \"undefined\" ? \"undefined\" : _typeof(Set)) !== undef ? Set : ObjectSet;\n\n// represents a node or an edge\nvar Element = function Element(cy, params) {\n var restore = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n if (cy === undefined || params === undefined || !core(cy)) {\n error('An element must have a core reference and parameters set');\n return;\n }\n var group = params.group;\n\n // try to automatically infer the group if unspecified\n if (group == null) {\n if (params.data && params.data.source != null && params.data.target != null) {\n group = 'edges';\n } else {\n group = 'nodes';\n }\n }\n\n // validate group\n if (group !== 'nodes' && group !== 'edges') {\n error('An element must be of type `nodes` or `edges`; you specified `' + group + '`');\n return;\n }\n\n // make the element array-like, just like a collection\n this.length = 1;\n this[0] = this;\n\n // NOTE: when something is added here, add also to ele.json()\n var _p = this._private = {\n cy: cy,\n single: true,\n // indicates this is an element\n data: params.data || {},\n // data object\n position: params.position || {\n x: 0,\n y: 0\n },\n // (x, y) position pair\n autoWidth: undefined,\n // width and height of nodes calculated by the renderer when set to special 'auto' value\n autoHeight: undefined,\n autoPadding: undefined,\n compoundBoundsClean: false,\n // whether the compound dimensions need to be recalculated the next time dimensions are read\n listeners: [],\n // array of bound listeners\n group: group,\n // string; 'nodes' or 'edges'\n style: {},\n // properties as set by the style\n rstyle: {},\n // properties for style sent from the renderer to the core\n styleCxts: [],\n // applied style contexts from the styler\n styleKeys: {},\n // per-group keys of style property values\n removed: true,\n // whether it's inside the vis; true if removed (set true here since we call restore)\n selected: params.selected ? true : false,\n // whether it's selected\n selectable: params.selectable === undefined ? true : params.selectable ? true : false,\n // whether it's selectable\n locked: params.locked ? true : false,\n // whether the element is locked (cannot be moved)\n grabbed: false,\n // whether the element is grabbed by the mouse; renderer sets this privately\n grabbable: params.grabbable === undefined ? true : params.grabbable ? true : false,\n // whether the element can be grabbed\n pannable: params.pannable === undefined ? group === 'edges' ? true : false : params.pannable ? true : false,\n // whether the element has passthrough panning enabled\n active: false,\n // whether the element is active from user interaction\n classes: new Set$1(),\n // map ( className => true )\n animation: {\n // object for currently-running animations\n current: [],\n queue: []\n },\n rscratch: {},\n // object in which the renderer can store information\n scratch: params.scratch || {},\n // scratch objects\n edges: [],\n // array of connected edges\n children: [],\n // array of children\n parent: params.parent && params.parent.isNode() ? params.parent : null,\n // parent ref\n traversalCache: {},\n // cache of output of traversal functions\n backgrounding: false,\n // whether background images are loading\n bbCache: null,\n // cache of the current bounding box\n bbCacheShift: {\n x: 0,\n y: 0\n },\n // shift applied to cached bb to be applied on next get\n bodyBounds: null,\n // bounds cache of element body, w/o overlay\n overlayBounds: null,\n // bounds cache of element body, including overlay\n labelBounds: {\n // bounds cache of labels\n all: null,\n source: null,\n target: null,\n main: null\n },\n arrowBounds: {\n // bounds cache of edge arrows\n source: null,\n target: null,\n 'mid-source': null,\n 'mid-target': null\n }\n };\n if (_p.position.x == null) {\n _p.position.x = 0;\n }\n if (_p.position.y == null) {\n _p.position.y = 0;\n }\n\n // renderedPosition overrides if specified\n if (params.renderedPosition) {\n var rpos = params.renderedPosition;\n var pan = cy.pan();\n var zoom = cy.zoom();\n _p.position = {\n x: (rpos.x - pan.x) / zoom,\n y: (rpos.y - pan.y) / zoom\n };\n }\n var classes = [];\n if (array(params.classes)) {\n classes = params.classes;\n } else if (string(params.classes)) {\n classes = params.classes.split(/\\s+/);\n }\n for (var i = 0, l = classes.length; i < l; i++) {\n var cls = classes[i];\n if (!cls || cls === '') {\n continue;\n }\n _p.classes.add(cls);\n }\n this.createEmitter();\n if (restore === undefined || restore) {\n this.restore();\n }\n var bypass = params.style || params.css;\n if (bypass) {\n warn('Setting a `style` bypass at element creation should be done only when absolutely necessary. Try to use the stylesheet instead.');\n this.style(bypass);\n }\n};\n\nvar defineSearch = function defineSearch(params) {\n params = {\n bfs: params.bfs || !params.dfs,\n dfs: params.dfs || !params.bfs\n };\n\n // from pseudocode on wikipedia\n return function searchFn(roots, fn, directed) {\n var options;\n if (plainObject(roots) && !elementOrCollection(roots)) {\n options = roots;\n roots = options.roots || options.root;\n fn = options.visit;\n directed = options.directed;\n }\n directed = arguments.length === 2 && !fn$6(fn) ? fn : directed;\n fn = fn$6(fn) ? fn : function () {};\n var cy = this._private.cy;\n var v = roots = string(roots) ? this.filter(roots) : roots;\n var Q = [];\n var connectedNodes = [];\n var connectedBy = {};\n var id2depth = {};\n var V = {};\n var j = 0;\n var found;\n var _this$byGroup = this.byGroup(),\n nodes = _this$byGroup.nodes,\n edges = _this$byGroup.edges;\n\n // enqueue v\n for (var i = 0; i < v.length; i++) {\n var vi = v[i];\n var viId = vi.id();\n if (vi.isNode()) {\n Q.unshift(vi);\n if (params.bfs) {\n V[viId] = true;\n connectedNodes.push(vi);\n }\n id2depth[viId] = 0;\n }\n }\n var _loop = function _loop() {\n var v = params.bfs ? Q.shift() : Q.pop();\n var vId = v.id();\n if (params.dfs) {\n if (V[vId]) {\n return 0; // continue\n }\n V[vId] = true;\n connectedNodes.push(v);\n }\n var depth = id2depth[vId];\n var prevEdge = connectedBy[vId];\n var src = prevEdge != null ? prevEdge.source() : null;\n var tgt = prevEdge != null ? prevEdge.target() : null;\n var prevNode = prevEdge == null ? undefined : v.same(src) ? tgt[0] : src[0];\n var ret;\n ret = fn(v, prevEdge, prevNode, j++, depth);\n if (ret === true) {\n found = v;\n return 1; // break\n }\n if (ret === false) {\n return 1; // break\n }\n var vwEdges = v.connectedEdges().filter(function (e) {\n return (!directed || e.source().same(v)) && edges.has(e);\n });\n for (var _i2 = 0; _i2 < vwEdges.length; _i2++) {\n var e = vwEdges[_i2];\n var w = e.connectedNodes().filter(function (n) {\n return !n.same(v) && nodes.has(n);\n });\n var wId = w.id();\n if (w.length !== 0 && !V[wId]) {\n w = w[0];\n Q.push(w);\n if (params.bfs) {\n V[wId] = true;\n connectedNodes.push(w);\n }\n connectedBy[wId] = e;\n id2depth[wId] = id2depth[vId] + 1;\n }\n }\n },\n _ret;\n while (Q.length !== 0) {\n _ret = _loop();\n if (_ret === 0) continue;\n if (_ret === 1) break;\n }\n var connectedEles = cy.collection();\n for (var _i = 0; _i < connectedNodes.length; _i++) {\n var node = connectedNodes[_i];\n var edge = connectedBy[node.id()];\n if (edge != null) {\n connectedEles.push(edge);\n }\n connectedEles.push(node);\n }\n return {\n path: cy.collection(connectedEles),\n found: cy.collection(found)\n };\n };\n};\n\n// search, spanning trees, etc\nvar elesfn$v = {\n breadthFirstSearch: defineSearch({\n bfs: true\n }),\n depthFirstSearch: defineSearch({\n dfs: true\n })\n};\n\n// nice, short mathematical alias\nelesfn$v.bfs = elesfn$v.breadthFirstSearch;\nelesfn$v.dfs = elesfn$v.depthFirstSearch;\n\nvar heap$2 = {exports: {}};\n\nvar heap$1 = heap$2.exports;\n\nvar hasRequiredHeap$1;\n\nfunction requireHeap$1 () {\n\tif (hasRequiredHeap$1) return heap$2.exports;\n\thasRequiredHeap$1 = 1;\n\t(function (module, exports) {\n\t\t// Generated by CoffeeScript 1.8.0\n\t\t(function() {\n\t\t var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;\n\n\t\t floor = Math.floor, min = Math.min;\n\n\n\t\t /*\n\t\t Default comparison function to be used\n\t\t */\n\n\t\t defaultCmp = function(x, y) {\n\t\t if (x < y) {\n\t\t return -1;\n\t\t }\n\t\t if (x > y) {\n\t\t return 1;\n\t\t }\n\t\t return 0;\n\t\t };\n\n\n\t\t /*\n\t\t Insert item x in list a, and keep it sorted assuming a is sorted.\n\t\t \n\t\t If x is already in a, insert it to the right of the rightmost x.\n\t\t \n\t\t Optional args lo (default 0) and hi (default a.length) bound the slice\n\t\t of a to be searched.\n\t\t */\n\n\t\t insort = function(a, x, lo, hi, cmp) {\n\t\t var mid;\n\t\t if (lo == null) {\n\t\t lo = 0;\n\t\t }\n\t\t if (cmp == null) {\n\t\t cmp = defaultCmp;\n\t\t }\n\t\t if (lo < 0) {\n\t\t throw new Error('lo must be non-negative');\n\t\t }\n\t\t if (hi == null) {\n\t\t hi = a.length;\n\t\t }\n\t\t while (lo < hi) {\n\t\t mid = floor((lo + hi) / 2);\n\t\t if (cmp(x, a[mid]) < 0) {\n\t\t hi = mid;\n\t\t } else {\n\t\t lo = mid + 1;\n\t\t }\n\t\t }\n\t\t return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);\n\t\t };\n\n\n\t\t /*\n\t\t Push item onto heap, maintaining the heap invariant.\n\t\t */\n\n\t\t heappush = function(array, item, cmp) {\n\t\t if (cmp == null) {\n\t\t cmp = defaultCmp;\n\t\t }\n\t\t array.push(item);\n\t\t return _siftdown(array, 0, array.length - 1, cmp);\n\t\t };\n\n\n\t\t /*\n\t\t Pop the smallest item off the heap, maintaining the heap invariant.\n\t\t */\n\n\t\t heappop = function(array, cmp) {\n\t\t var lastelt, returnitem;\n\t\t if (cmp == null) {\n\t\t cmp = defaultCmp;\n\t\t }\n\t\t lastelt = array.pop();\n\t\t if (array.length) {\n\t\t returnitem = array[0];\n\t\t array[0] = lastelt;\n\t\t _siftup(array, 0, cmp);\n\t\t } else {\n\t\t returnitem = lastelt;\n\t\t }\n\t\t return returnitem;\n\t\t };\n\n\n\t\t /*\n\t\t Pop and return the current smallest value, and add the new item.\n\t\t \n\t\t This is more efficient than heappop() followed by heappush(), and can be\n\t\t more appropriate when using a fixed size heap. Note that the value\n\t\t returned may be larger than item! That constrains reasonable use of\n\t\t this routine unless written as part of a conditional replacement:\n\t\t if item > array[0]\n\t\t item = heapreplace(array, item)\n\t\t */\n\n\t\t heapreplace = function(array, item, cmp) {\n\t\t var returnitem;\n\t\t if (cmp == null) {\n\t\t cmp = defaultCmp;\n\t\t }\n\t\t returnitem = array[0];\n\t\t array[0] = item;\n\t\t _siftup(array, 0, cmp);\n\t\t return returnitem;\n\t\t };\n\n\n\t\t /*\n\t\t Fast version of a heappush followed by a heappop.\n\t\t */\n\n\t\t heappushpop = function(array, item, cmp) {\n\t\t var _ref;\n\t\t if (cmp == null) {\n\t\t cmp = defaultCmp;\n\t\t }\n\t\t if (array.length && cmp(array[0], item) < 0) {\n\t\t _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];\n\t\t _siftup(array, 0, cmp);\n\t\t }\n\t\t return item;\n\t\t };\n\n\n\t\t /*\n\t\t Transform list into a heap, in-place, in O(array.length) time.\n\t\t */\n\n\t\t heapify = function(array, cmp) {\n\t\t var i, _i, _len, _ref1, _results, _results1;\n\t\t if (cmp == null) {\n\t\t cmp = defaultCmp;\n\t\t }\n\t\t _ref1 = (function() {\n\t\t _results1 = [];\n\t\t for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }\n\t\t return _results1;\n\t\t }).apply(this).reverse();\n\t\t _results = [];\n\t\t for (_i = 0, _len = _ref1.length; _i < _len; _i++) {\n\t\t i = _ref1[_i];\n\t\t _results.push(_siftup(array, i, cmp));\n\t\t }\n\t\t return _results;\n\t\t };\n\n\n\t\t /*\n\t\t Update the position of the given item in the heap.\n\t\t This function should be called every time the item is being modified.\n\t\t */\n\n\t\t updateItem = function(array, item, cmp) {\n\t\t var pos;\n\t\t if (cmp == null) {\n\t\t cmp = defaultCmp;\n\t\t }\n\t\t pos = array.indexOf(item);\n\t\t if (pos === -1) {\n\t\t return;\n\t\t }\n\t\t _siftdown(array, 0, pos, cmp);\n\t\t return _siftup(array, pos, cmp);\n\t\t };\n\n\n\t\t /*\n\t\t Find the n largest elements in a dataset.\n\t\t */\n\n\t\t nlargest = function(array, n, cmp) {\n\t\t var elem, result, _i, _len, _ref;\n\t\t if (cmp == null) {\n\t\t cmp = defaultCmp;\n\t\t }\n\t\t result = array.slice(0, n);\n\t\t if (!result.length) {\n\t\t return result;\n\t\t }\n\t\t heapify(result, cmp);\n\t\t _ref = array.slice(n);\n\t\t for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n\t\t elem = _ref[_i];\n\t\t heappushpop(result, elem, cmp);\n\t\t }\n\t\t return result.sort(cmp).reverse();\n\t\t };\n\n\n\t\t /*\n\t\t Find the n smallest elements in a dataset.\n\t\t */\n\n\t\t nsmallest = function(array, n, cmp) {\n\t\t var elem, los, result, _i, _j, _len, _ref, _ref1, _results;\n\t\t if (cmp == null) {\n\t\t cmp = defaultCmp;\n\t\t }\n\t\t if (n * 10 <= array.length) {\n\t\t result = array.slice(0, n).sort(cmp);\n\t\t if (!result.length) {\n\t\t return result;\n\t\t }\n\t\t los = result[result.length - 1];\n\t\t _ref = array.slice(n);\n\t\t for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n\t\t elem = _ref[_i];\n\t\t if (cmp(elem, los) < 0) {\n\t\t insort(result, elem, 0, null, cmp);\n\t\t result.pop();\n\t\t los = result[result.length - 1];\n\t\t }\n\t\t }\n\t\t return result;\n\t\t }\n\t\t heapify(array, cmp);\n\t\t _results = [];\n\t\t for (_j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; 0 <= _ref1 ? ++_j : --_j) {\n\t\t _results.push(heappop(array, cmp));\n\t\t }\n\t\t return _results;\n\t\t };\n\n\t\t _siftdown = function(array, startpos, pos, cmp) {\n\t\t var newitem, parent, parentpos;\n\t\t if (cmp == null) {\n\t\t cmp = defaultCmp;\n\t\t }\n\t\t newitem = array[pos];\n\t\t while (pos > startpos) {\n\t\t parentpos = (pos - 1) >> 1;\n\t\t parent = array[parentpos];\n\t\t if (cmp(newitem, parent) < 0) {\n\t\t array[pos] = parent;\n\t\t pos = parentpos;\n\t\t continue;\n\t\t }\n\t\t break;\n\t\t }\n\t\t return array[pos] = newitem;\n\t\t };\n\n\t\t _siftup = function(array, pos, cmp) {\n\t\t var childpos, endpos, newitem, rightpos, startpos;\n\t\t if (cmp == null) {\n\t\t cmp = defaultCmp;\n\t\t }\n\t\t endpos = array.length;\n\t\t startpos = pos;\n\t\t newitem = array[pos];\n\t\t childpos = 2 * pos + 1;\n\t\t while (childpos < endpos) {\n\t\t rightpos = childpos + 1;\n\t\t if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {\n\t\t childpos = rightpos;\n\t\t }\n\t\t array[pos] = array[childpos];\n\t\t pos = childpos;\n\t\t childpos = 2 * pos + 1;\n\t\t }\n\t\t array[pos] = newitem;\n\t\t return _siftdown(array, startpos, pos, cmp);\n\t\t };\n\n\t\t Heap = (function() {\n\t\t Heap.push = heappush;\n\n\t\t Heap.pop = heappop;\n\n\t\t Heap.replace = heapreplace;\n\n\t\t Heap.pushpop = heappushpop;\n\n\t\t Heap.heapify = heapify;\n\n\t\t Heap.updateItem = updateItem;\n\n\t\t Heap.nlargest = nlargest;\n\n\t\t Heap.nsmallest = nsmallest;\n\n\t\t function Heap(cmp) {\n\t\t this.cmp = cmp != null ? cmp : defaultCmp;\n\t\t this.nodes = [];\n\t\t }\n\n\t\t Heap.prototype.push = function(x) {\n\t\t return heappush(this.nodes, x, this.cmp);\n\t\t };\n\n\t\t Heap.prototype.pop = function() {\n\t\t return heappop(this.nodes, this.cmp);\n\t\t };\n\n\t\t Heap.prototype.peek = function() {\n\t\t return this.nodes[0];\n\t\t };\n\n\t\t Heap.prototype.contains = function(x) {\n\t\t return this.nodes.indexOf(x) !== -1;\n\t\t };\n\n\t\t Heap.prototype.replace = function(x) {\n\t\t return heapreplace(this.nodes, x, this.cmp);\n\t\t };\n\n\t\t Heap.prototype.pushpop = function(x) {\n\t\t return heappushpop(this.nodes, x, this.cmp);\n\t\t };\n\n\t\t Heap.prototype.heapify = function() {\n\t\t return heapify(this.nodes, this.cmp);\n\t\t };\n\n\t\t Heap.prototype.updateItem = function(x) {\n\t\t return updateItem(this.nodes, x, this.cmp);\n\t\t };\n\n\t\t Heap.prototype.clear = function() {\n\t\t return this.nodes = [];\n\t\t };\n\n\t\t Heap.prototype.empty = function() {\n\t\t return this.nodes.length === 0;\n\t\t };\n\n\t\t Heap.prototype.size = function() {\n\t\t return this.nodes.length;\n\t\t };\n\n\t\t Heap.prototype.clone = function() {\n\t\t var heap;\n\t\t heap = new Heap();\n\t\t heap.nodes = this.nodes.slice(0);\n\t\t return heap;\n\t\t };\n\n\t\t Heap.prototype.toArray = function() {\n\t\t return this.nodes.slice(0);\n\t\t };\n\n\t\t Heap.prototype.insert = Heap.prototype.push;\n\n\t\t Heap.prototype.top = Heap.prototype.peek;\n\n\t\t Heap.prototype.front = Heap.prototype.peek;\n\n\t\t Heap.prototype.has = Heap.prototype.contains;\n\n\t\t Heap.prototype.copy = Heap.prototype.clone;\n\n\t\t return Heap;\n\n\t\t })();\n\n\t\t (function(root, factory) {\n\t\t {\n\t\t return module.exports = factory();\n\t\t }\n\t\t })(this, function() {\n\t\t return Heap;\n\t\t });\n\n\t\t}).call(heap$1); \n\t} (heap$2));\n\treturn heap$2.exports;\n}\n\nvar heap;\nvar hasRequiredHeap;\n\nfunction requireHeap () {\n\tif (hasRequiredHeap) return heap;\n\thasRequiredHeap = 1;\n\theap = requireHeap$1();\n\treturn heap;\n}\n\nvar heapExports = requireHeap();\nvar Heap = /*@__PURE__*/getDefaultExportFromCjs(heapExports);\n\nvar dijkstraDefaults = defaults$g({\n root: null,\n weight: function weight(edge) {\n return 1;\n },\n directed: false\n});\nvar elesfn$u = {\n dijkstra: function dijkstra(options) {\n if (!plainObject(options)) {\n var args = arguments;\n options = {\n root: args[0],\n weight: args[1],\n directed: args[2]\n };\n }\n var _dijkstraDefaults = dijkstraDefaults(options),\n root = _dijkstraDefaults.root,\n weight = _dijkstraDefaults.weight,\n directed = _dijkstraDefaults.directed;\n var eles = this;\n var weightFn = weight;\n var source = string(root) ? this.filter(root)[0] : root[0];\n var dist = {};\n var prev = {};\n var knownDist = {};\n var _this$byGroup = this.byGroup(),\n nodes = _this$byGroup.nodes,\n edges = _this$byGroup.edges;\n edges.unmergeBy(function (ele) {\n return ele.isLoop();\n });\n var getDist = function getDist(node) {\n return dist[node.id()];\n };\n var setDist = function setDist(node, d) {\n dist[node.id()] = d;\n Q.updateItem(node);\n };\n var Q = new Heap(function (a, b) {\n return getDist(a) - getDist(b);\n });\n for (var i = 0; i < nodes.length; i++) {\n var node = nodes[i];\n dist[node.id()] = node.same(source) ? 0 : Infinity;\n Q.push(node);\n }\n var distBetween = function distBetween(u, v) {\n var uvs = (directed ? u.edgesTo(v) : u.edgesWith(v)).intersect(edges);\n var smallestDistance = Infinity;\n var smallestEdge;\n for (var _i = 0; _i < uvs.length; _i++) {\n var edge = uvs[_i];\n var _weight = weightFn(edge);\n if (_weight < smallestDistance || !smallestEdge) {\n smallestDistance = _weight;\n smallestEdge = edge;\n }\n }\n return {\n edge: smallestEdge,\n dist: smallestDistance\n };\n };\n while (Q.size() > 0) {\n var u = Q.pop();\n var smalletsDist = getDist(u);\n var uid = u.id();\n knownDist[uid] = smalletsDist;\n if (smalletsDist === Infinity) {\n continue;\n }\n var neighbors = u.neighborhood().intersect(nodes);\n for (var _i2 = 0; _i2 < neighbors.length; _i2++) {\n var v = neighbors[_i2];\n var vid = v.id();\n var vDist = distBetween(u, v);\n var alt = smalletsDist + vDist.dist;\n if (alt < getDist(v)) {\n setDist(v, alt);\n prev[vid] = {\n node: u,\n edge: vDist.edge\n };\n }\n } // for\n } // while\n\n return {\n distanceTo: function distanceTo(node) {\n var target = string(node) ? nodes.filter(node)[0] : node[0];\n return knownDist[target.id()];\n },\n pathTo: function pathTo(node) {\n var target = string(node) ? nodes.filter(node)[0] : node[0];\n var S = [];\n var u = target;\n var uid = u.id();\n if (target.length > 0) {\n S.unshift(target);\n while (prev[uid]) {\n var p = prev[uid];\n S.unshift(p.edge);\n S.unshift(p.node);\n u = p.node;\n uid = u.id();\n }\n }\n return eles.spawn(S);\n }\n };\n }\n};\n\nvar elesfn$t = {\n // kruskal's algorithm (finds min spanning tree, assuming undirected graph)\n // implemented from pseudocode from wikipedia\n kruskal: function kruskal(weightFn) {\n weightFn = weightFn || function (edge) {\n return 1;\n };\n var _this$byGroup = this.byGroup(),\n nodes = _this$byGroup.nodes,\n edges = _this$byGroup.edges;\n var numNodes = nodes.length;\n var forest = new Array(numNodes);\n var A = nodes; // assumes byGroup() creates new collections that can be safely mutated\n\n var findSetIndex = function findSetIndex(ele) {\n for (var i = 0; i < forest.length; i++) {\n var eles = forest[i];\n if (eles.has(ele)) {\n return i;\n }\n }\n };\n\n // start with one forest per node\n for (var i = 0; i < numNodes; i++) {\n forest[i] = this.spawn(nodes[i]);\n }\n var S = edges.sort(function (a, b) {\n return weightFn(a) - weightFn(b);\n });\n for (var _i = 0; _i < S.length; _i++) {\n var edge = S[_i];\n var u = edge.source()[0];\n var v = edge.target()[0];\n var setUIndex = findSetIndex(u);\n var setVIndex = findSetIndex(v);\n var setU = forest[setUIndex];\n var setV = forest[setVIndex];\n if (setUIndex !== setVIndex) {\n A.merge(edge);\n\n // combine forests for u and v\n setU.merge(setV);\n forest.splice(setVIndex, 1);\n }\n }\n return A;\n }\n};\n\nvar aStarDefaults = defaults$g({\n root: null,\n goal: null,\n weight: function weight(edge) {\n return 1;\n },\n heuristic: function heuristic(edge) {\n return 0;\n },\n directed: false\n});\nvar elesfn$s = {\n // Implemented from pseudocode from wikipedia\n aStar: function aStar(options) {\n var cy = this.cy();\n var _aStarDefaults = aStarDefaults(options),\n root = _aStarDefaults.root,\n goal = _aStarDefaults.goal,\n heuristic = _aStarDefaults.heuristic,\n directed = _aStarDefaults.directed,\n weight = _aStarDefaults.weight;\n root = cy.collection(root)[0];\n goal = cy.collection(goal)[0];\n var sid = root.id();\n var tid = goal.id();\n var gScore = {};\n var fScore = {};\n var closedSetIds = {};\n var openSet = new Heap(function (a, b) {\n return fScore[a.id()] - fScore[b.id()];\n });\n var openSetIds = new Set$1();\n var cameFrom = {};\n var cameFromEdge = {};\n var addToOpenSet = function addToOpenSet(ele, id) {\n openSet.push(ele);\n openSetIds.add(id);\n };\n var cMin, cMinId;\n var popFromOpenSet = function popFromOpenSet() {\n cMin = openSet.pop();\n cMinId = cMin.id();\n openSetIds[\"delete\"](cMinId);\n };\n var isInOpenSet = function isInOpenSet(id) {\n return openSetIds.has(id);\n };\n addToOpenSet(root, sid);\n gScore[sid] = 0;\n fScore[sid] = heuristic(root);\n\n // Counter\n var steps = 0;\n\n // Main loop\n while (openSet.size() > 0) {\n popFromOpenSet();\n steps++;\n\n // If we've found our goal, then we are done\n if (cMinId === tid) {\n var path = [];\n var pathNode = goal;\n var pathNodeId = tid;\n var pathEdge = cameFromEdge[pathNodeId];\n for (;;) {\n path.unshift(pathNode);\n if (pathEdge != null) {\n path.unshift(pathEdge);\n }\n pathNode = cameFrom[pathNodeId];\n if (pathNode == null) {\n break;\n }\n pathNodeId = pathNode.id();\n pathEdge = cameFromEdge[pathNodeId];\n }\n return {\n found: true,\n distance: gScore[cMinId],\n path: this.spawn(path),\n steps: steps\n };\n }\n\n // Add cMin to processed nodes\n closedSetIds[cMinId] = true;\n\n // Update scores for neighbors of cMin\n // Take into account if graph is directed or not\n var vwEdges = cMin._private.edges;\n for (var i = 0; i < vwEdges.length; i++) {\n var e = vwEdges[i];\n\n // edge must be in set of calling eles\n if (!this.hasElementWithId(e.id())) {\n continue;\n }\n\n // cMin must be the source of edge if directed\n if (directed && e.data('source') !== cMinId) {\n continue;\n }\n var wSrc = e.source();\n var wTgt = e.target();\n var w = wSrc.id() !== cMinId ? wSrc : wTgt;\n var wid = w.id();\n\n // node must be in set of calling eles\n if (!this.hasElementWithId(wid)) {\n continue;\n }\n\n // if node is in closedSet, ignore it\n if (closedSetIds[wid]) {\n continue;\n }\n\n // New tentative score for node w\n var tempScore = gScore[cMinId] + weight(e);\n\n // Update gScore for node w if:\n // w not present in openSet\n // OR\n // tentative gScore is less than previous value\n\n // w not in openSet\n if (!isInOpenSet(wid)) {\n gScore[wid] = tempScore;\n fScore[wid] = tempScore + heuristic(w);\n addToOpenSet(w, wid);\n cameFrom[wid] = cMin;\n cameFromEdge[wid] = e;\n continue;\n }\n\n // w already in openSet, but with greater gScore\n if (tempScore < gScore[wid]) {\n gScore[wid] = tempScore;\n fScore[wid] = tempScore + heuristic(w);\n cameFrom[wid] = cMin;\n cameFromEdge[wid] = e;\n }\n } // End of neighbors update\n } // End of main loop\n\n // If we've reached here, then we've not reached our goal\n return {\n found: false,\n distance: undefined,\n path: undefined,\n steps: steps\n };\n }\n}; // elesfn\n\nvar floydWarshallDefaults = defaults$g({\n weight: function weight(edge) {\n return 1;\n },\n directed: false\n});\nvar elesfn$r = {\n // Implemented from pseudocode from wikipedia\n floydWarshall: function floydWarshall(options) {\n var cy = this.cy();\n var _floydWarshallDefault = floydWarshallDefaults(options),\n weight = _floydWarshallDefault.weight,\n directed = _floydWarshallDefault.directed;\n var weightFn = weight;\n var _this$byGroup = this.byGroup(),\n nodes = _this$byGroup.nodes,\n edges = _this$byGroup.edges;\n var N = nodes.length;\n var Nsq = N * N;\n var indexOf = function indexOf(node) {\n return nodes.indexOf(node);\n };\n var atIndex = function atIndex(i) {\n return nodes[i];\n };\n\n // Initialize distance matrix\n var dist = new Array(Nsq);\n for (var n = 0; n < Nsq; n++) {\n var j = n % N;\n var i = (n - j) / N;\n if (i === j) {\n dist[n] = 0;\n } else {\n dist[n] = Infinity;\n }\n }\n\n // Initialize matrix used for path reconstruction\n // Initialize distance matrix\n var next = new Array(Nsq);\n var edgeNext = new Array(Nsq);\n\n // Process edges\n for (var _i = 0; _i < edges.length; _i++) {\n var edge = edges[_i];\n var src = edge.source()[0];\n var tgt = edge.target()[0];\n if (src === tgt) {\n continue;\n } // exclude loops\n\n var s = indexOf(src);\n var t = indexOf(tgt);\n var st = s * N + t; // source to target index\n var _weight = weightFn(edge);\n\n // Check if already process another edge between same 2 nodes\n if (dist[st] > _weight) {\n dist[st] = _weight;\n next[st] = t;\n edgeNext[st] = edge;\n }\n\n // If undirected graph, process 'reversed' edge\n if (!directed) {\n var ts = t * N + s; // target to source index\n\n if (!directed && dist[ts] > _weight) {\n dist[ts] = _weight;\n next[ts] = s;\n edgeNext[ts] = edge;\n }\n }\n }\n\n // Main loop\n for (var k = 0; k < N; k++) {\n for (var _i2 = 0; _i2 < N; _i2++) {\n var ik = _i2 * N + k;\n for (var _j = 0; _j < N; _j++) {\n var ij = _i2 * N + _j;\n var kj = k * N + _j;\n if (dist[ik] + dist[kj] < dist[ij]) {\n dist[ij] = dist[ik] + dist[kj];\n next[ij] = next[ik];\n }\n }\n }\n }\n var getArgEle = function getArgEle(ele) {\n return (string(ele) ? cy.filter(ele) : ele)[0];\n };\n var indexOfArgEle = function indexOfArgEle(ele) {\n return indexOf(getArgEle(ele));\n };\n var res = {\n distance: function distance(from, to) {\n var i = indexOfArgEle(from);\n var j = indexOfArgEle(to);\n return dist[i * N + j];\n },\n path: function path(from, to) {\n var i = indexOfArgEle(from);\n var j = indexOfArgEle(to);\n var fromNode = atIndex(i);\n if (i === j) {\n return fromNode.collection();\n }\n if (next[i * N + j] == null) {\n return cy.collection();\n }\n var path = cy.collection();\n var prev = i;\n var edge;\n path.merge(fromNode);\n while (i !== j) {\n prev = i;\n i = next[i * N + j];\n edge = edgeNext[prev * N + i];\n path.merge(edge);\n path.merge(atIndex(i));\n }\n return path;\n }\n };\n return res;\n } // floydWarshall\n}; // elesfn\n\nvar bellmanFordDefaults = defaults$g({\n weight: function weight(edge) {\n return 1;\n },\n directed: false,\n root: null\n});\nvar elesfn$q = {\n // Implemented from pseudocode from wikipedia\n bellmanFord: function bellmanFord(options) {\n var _this = this;\n var _bellmanFordDefaults = bellmanFordDefaults(options),\n weight = _bellmanFordDefaults.weight,\n directed = _bellmanFordDefaults.directed,\n root = _bellmanFordDefaults.root;\n var weightFn = weight;\n var eles = this;\n var cy = this.cy();\n var _this$byGroup = this.byGroup(),\n edges = _this$byGroup.edges,\n nodes = _this$byGroup.nodes;\n var numNodes = nodes.length;\n var infoMap = new Map$1();\n var hasNegativeWeightCycle = false;\n var negativeWeightCycles = [];\n root = cy.collection(root)[0]; // in case selector passed\n\n edges.unmergeBy(function (edge) {\n return edge.isLoop();\n });\n var numEdges = edges.length;\n var getInfo = function getInfo(node) {\n var obj = infoMap.get(node.id());\n if (!obj) {\n obj = {};\n infoMap.set(node.id(), obj);\n }\n return obj;\n };\n var getNodeFromTo = function getNodeFromTo(to) {\n return (string(to) ? cy.$(to) : to)[0];\n };\n var distanceTo = function distanceTo(to) {\n return getInfo(getNodeFromTo(to)).dist;\n };\n var pathTo = function pathTo(to) {\n var thisStart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : root;\n var end = getNodeFromTo(to);\n var path = [];\n var node = end;\n for (;;) {\n if (node == null) {\n return _this.spawn();\n }\n var _getInfo = getInfo(node),\n edge = _getInfo.edge,\n pred = _getInfo.pred;\n path.unshift(node[0]);\n if (node.same(thisStart) && path.length > 0) {\n break;\n }\n if (edge != null) {\n path.unshift(edge);\n }\n node = pred;\n }\n return eles.spawn(path);\n };\n\n // Initializations { dist, pred, edge }\n for (var i = 0; i < numNodes; i++) {\n var node = nodes[i];\n var info = getInfo(node);\n if (node.same(root)) {\n info.dist = 0;\n } else {\n info.dist = Infinity;\n }\n info.pred = null;\n info.edge = null;\n }\n\n // Edges relaxation\n var replacedEdge = false;\n var checkForEdgeReplacement = function checkForEdgeReplacement(node1, node2, edge, info1, info2, weight) {\n var dist = info1.dist + weight;\n if (dist < info2.dist && !edge.same(info1.edge)) {\n info2.dist = dist;\n info2.pred = node1;\n info2.edge = edge;\n replacedEdge = true;\n }\n };\n for (var _i = 1; _i < numNodes; _i++) {\n replacedEdge = false;\n for (var e = 0; e < numEdges; e++) {\n var edge = edges[e];\n var src = edge.source();\n var tgt = edge.target();\n var _weight = weightFn(edge);\n var srcInfo = getInfo(src);\n var tgtInfo = getInfo(tgt);\n checkForEdgeReplacement(src, tgt, edge, srcInfo, tgtInfo, _weight);\n\n // If undirected graph, we need to take into account the 'reverse' edge\n if (!directed) {\n checkForEdgeReplacement(tgt, src, edge, tgtInfo, srcInfo, _weight);\n }\n }\n if (!replacedEdge) {\n break;\n }\n }\n if (replacedEdge) {\n // Check for negative weight cycles\n var negativeWeightCycleIds = [];\n for (var _e = 0; _e < numEdges; _e++) {\n var _edge = edges[_e];\n var _src = _edge.source();\n var _tgt = _edge.target();\n var _weight2 = weightFn(_edge);\n var srcDist = getInfo(_src).dist;\n var tgtDist = getInfo(_tgt).dist;\n if (srcDist + _weight2 < tgtDist || !directed && tgtDist + _weight2 < srcDist) {\n if (!hasNegativeWeightCycle) {\n warn('Graph contains a negative weight cycle for Bellman-Ford');\n hasNegativeWeightCycle = true;\n }\n if (options.findNegativeWeightCycles !== false) {\n var negativeNodes = [];\n if (srcDist + _weight2 < tgtDist) {\n negativeNodes.push(_src);\n }\n if (!directed && tgtDist + _weight2 < srcDist) {\n negativeNodes.push(_tgt);\n }\n var numNegativeNodes = negativeNodes.length;\n for (var n = 0; n < numNegativeNodes; n++) {\n var start = negativeNodes[n];\n var cycle = [start];\n cycle.push(getInfo(start).edge);\n var _node = getInfo(start).pred;\n while (cycle.indexOf(_node) === -1) {\n cycle.push(_node);\n cycle.push(getInfo(_node).edge);\n _node = getInfo(_node).pred;\n }\n cycle = cycle.slice(cycle.indexOf(_node));\n var smallestId = cycle[0].id();\n var smallestIndex = 0;\n for (var c = 2; c < cycle.length; c += 2) {\n if (cycle[c].id() < smallestId) {\n smallestId = cycle[c].id();\n smallestIndex = c;\n }\n }\n cycle = cycle.slice(smallestIndex).concat(cycle.slice(0, smallestIndex));\n cycle.push(cycle[0]);\n var cycleId = cycle.map(function (el) {\n return el.id();\n }).join(\",\");\n if (negativeWeightCycleIds.indexOf(cycleId) === -1) {\n negativeWeightCycles.push(eles.spawn(cycle));\n negativeWeightCycleIds.push(cycleId);\n }\n }\n } else {\n break;\n }\n }\n }\n }\n return {\n distanceTo: distanceTo,\n pathTo: pathTo,\n hasNegativeWeightCycle: hasNegativeWeightCycle,\n negativeWeightCycles: negativeWeightCycles\n };\n } // bellmanFord\n}; // elesfn\n\nvar sqrt2 = Math.sqrt(2);\n\n// Function which colapses 2 (meta) nodes into one\n// Updates the remaining edge lists\n// Receives as a paramater the edge which causes the collapse\nvar collapse = function collapse(edgeIndex, nodeMap, remainingEdges) {\n if (remainingEdges.length === 0) {\n error(\"Karger-Stein must be run on a connected (sub)graph\");\n }\n var edgeInfo = remainingEdges[edgeIndex];\n var sourceIn = edgeInfo[1];\n var targetIn = edgeInfo[2];\n var partition1 = nodeMap[sourceIn];\n var partition2 = nodeMap[targetIn];\n var newEdges = remainingEdges; // re-use array\n\n // Delete all edges between partition1 and partition2\n for (var i = newEdges.length - 1; i >= 0; i--) {\n var edge = newEdges[i];\n var src = edge[1];\n var tgt = edge[2];\n if (nodeMap[src] === partition1 && nodeMap[tgt] === partition2 || nodeMap[src] === partition2 && nodeMap[tgt] === partition1) {\n newEdges.splice(i, 1);\n }\n }\n\n // All edges pointing to partition2 should now point to partition1\n for (var _i = 0; _i < newEdges.length; _i++) {\n var _edge = newEdges[_i];\n if (_edge[1] === partition2) {\n // Check source\n newEdges[_i] = _edge.slice(); // copy\n newEdges[_i][1] = partition1;\n } else if (_edge[2] === partition2) {\n // Check target\n newEdges[_i] = _edge.slice(); // copy\n newEdges[_i][2] = partition1;\n }\n }\n\n // Move all nodes from partition2 to partition1\n for (var _i2 = 0; _i2 < nodeMap.length; _i2++) {\n if (nodeMap[_i2] === partition2) {\n nodeMap[_i2] = partition1;\n }\n }\n return newEdges;\n};\n\n// Contracts a graph until we reach a certain number of meta nodes\nvar contractUntil = function contractUntil(metaNodeMap, remainingEdges, size, sizeLimit) {\n while (size > sizeLimit) {\n // Choose an edge randomly\n var edgeIndex = Math.floor(Math.random() * remainingEdges.length);\n\n // Collapse graph based on edge\n remainingEdges = collapse(edgeIndex, metaNodeMap, remainingEdges);\n size--;\n }\n return remainingEdges;\n};\nvar elesfn$p = {\n // Computes the minimum cut of an undirected graph\n // Returns the correct answer with high probability\n kargerStein: function kargerStein() {\n var _this = this;\n var _this$byGroup = this.byGroup(),\n nodes = _this$byGroup.nodes,\n edges = _this$byGroup.edges;\n edges.unmergeBy(function (edge) {\n return edge.isLoop();\n });\n var numNodes = nodes.length;\n var numEdges = edges.length;\n var numIter = Math.ceil(Math.pow(Math.log(numNodes) / Math.LN2, 2));\n var stopSize = Math.floor(numNodes / sqrt2);\n if (numNodes < 2) {\n error('At least 2 nodes are required for Karger-Stein algorithm');\n return undefined;\n }\n\n // Now store edge destination as indexes\n // Format for each edge (edge index, source node index, target node index)\n var edgeIndexes = [];\n for (var i = 0; i < numEdges; i++) {\n var e = edges[i];\n edgeIndexes.push([i, nodes.indexOf(e.source()), nodes.indexOf(e.target())]);\n }\n\n // We will store the best cut found here\n var minCutSize = Infinity;\n var minCutEdgeIndexes = [];\n var minCutNodeMap = new Array(numNodes);\n\n // Initial meta node partition\n var metaNodeMap = new Array(numNodes);\n var metaNodeMap2 = new Array(numNodes);\n var copyNodesMap = function copyNodesMap(from, to) {\n for (var _i3 = 0; _i3 < numNodes; _i3++) {\n to[_i3] = from[_i3];\n }\n };\n\n // Main loop\n for (var iter = 0; iter <= numIter; iter++) {\n // Reset meta node partition\n for (var _i4 = 0; _i4 < numNodes; _i4++) {\n metaNodeMap[_i4] = _i4;\n }\n\n // Contract until stop point (stopSize nodes)\n var edgesState = contractUntil(metaNodeMap, edgeIndexes.slice(), numNodes, stopSize);\n var edgesState2 = edgesState.slice(); // copy\n\n // Create a copy of the colapsed nodes state\n copyNodesMap(metaNodeMap, metaNodeMap2);\n\n // Run 2 iterations starting in the stop state\n var res1 = contractUntil(metaNodeMap, edgesState, stopSize, 2);\n var res2 = contractUntil(metaNodeMap2, edgesState2, stopSize, 2);\n\n // Is any of the 2 results the best cut so far?\n if (res1.length <= res2.length && res1.length < minCutSize) {\n minCutSize = res1.length;\n minCutEdgeIndexes = res1;\n copyNodesMap(metaNodeMap, minCutNodeMap);\n } else if (res2.length <= res1.length && res2.length < minCutSize) {\n minCutSize = res2.length;\n minCutEdgeIndexes = res2;\n copyNodesMap(metaNodeMap2, minCutNodeMap);\n }\n } // end of main loop\n\n // Construct result\n var cut = this.spawn(minCutEdgeIndexes.map(function (e) {\n return edges[e[0]];\n }));\n var partition1 = this.spawn();\n var partition2 = this.spawn();\n\n // traverse metaNodeMap for best cut\n var witnessNodePartition = minCutNodeMap[0];\n for (var _i5 = 0; _i5 < minCutNodeMap.length; _i5++) {\n var partitionId = minCutNodeMap[_i5];\n var node = nodes[_i5];\n if (partitionId === witnessNodePartition) {\n partition1.merge(node);\n } else {\n partition2.merge(node);\n }\n }\n\n // construct components corresponding to each disjoint subset of nodes\n var constructComponent = function constructComponent(subset) {\n var component = _this.spawn();\n subset.forEach(function (node) {\n component.merge(node);\n node.connectedEdges().forEach(function (edge) {\n // ensure edge is within calling collection and edge is not in cut\n if (_this.contains(edge) && !cut.contains(edge)) {\n component.merge(edge);\n }\n });\n });\n return component;\n };\n var components = [constructComponent(partition1), constructComponent(partition2)];\n var ret = {\n cut: cut,\n components: components,\n // n.b. partitions are included to be compatible with the old api spec\n // (could be removed in a future major version)\n partition1: partition1,\n partition2: partition2\n };\n return ret;\n }\n}; // elesfn\n\nvar _Math$hypot;\nvar copyPosition = function copyPosition(p) {\n return {\n x: p.x,\n y: p.y\n };\n};\nvar modelToRenderedPosition$1 = function modelToRenderedPosition(p, zoom, pan) {\n return {\n x: p.x * zoom + pan.x,\n y: p.y * zoom + pan.y\n };\n};\nvar renderedToModelPosition = function renderedToModelPosition(p, zoom, pan) {\n return {\n x: (p.x - pan.x) / zoom,\n y: (p.y - pan.y) / zoom\n };\n};\nvar array2point = function array2point(arr) {\n return {\n x: arr[0],\n y: arr[1]\n };\n};\nvar min = function min(arr) {\n var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;\n var min = Infinity;\n for (var i = begin; i < end; i++) {\n var val = arr[i];\n if (isFinite(val)) {\n min = Math.min(val, min);\n }\n }\n return min;\n};\nvar max = function max(arr) {\n var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;\n var max = -Infinity;\n for (var i = begin; i < end; i++) {\n var val = arr[i];\n if (isFinite(val)) {\n max = Math.max(val, max);\n }\n }\n return max;\n};\nvar mean = function mean(arr) {\n var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;\n var total = 0;\n var n = 0;\n for (var i = begin; i < end; i++) {\n var val = arr[i];\n if (isFinite(val)) {\n total += val;\n n++;\n }\n }\n return total / n;\n};\nvar median = function median(arr) {\n var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;\n var copy = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;\n var sort = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n var includeHoles = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;\n if (copy) {\n arr = arr.slice(begin, end);\n } else {\n if (end < arr.length) {\n arr.splice(end, arr.length - end);\n }\n if (begin > 0) {\n arr.splice(0, begin);\n }\n }\n\n // all non finite (e.g. Infinity, NaN) elements must be -Infinity so they go to the start\n var off = 0; // offset from non-finite values\n for (var i = arr.length - 1; i >= 0; i--) {\n var v = arr[i];\n if (includeHoles) {\n if (!isFinite(v)) {\n arr[i] = -Infinity;\n off++;\n }\n } else {\n // just remove it if we don't want to consider holes\n arr.splice(i, 1);\n }\n }\n if (sort) {\n arr.sort(function (a, b) {\n return a - b;\n }); // requires copy = true if you don't want to change the orig\n }\n var len = arr.length;\n var mid = Math.floor(len / 2);\n if (len % 2 !== 0) {\n return arr[mid + 1 + off];\n } else {\n return (arr[mid - 1 + off] + arr[mid + off]) / 2;\n }\n};\nvar deg2rad = function deg2rad(deg) {\n return Math.PI * deg / 180;\n};\nvar getAngleFromDisp = function getAngleFromDisp(dispX, dispY) {\n return Math.atan2(dispY, dispX) - Math.PI / 2;\n};\nvar log2 = Math.log2 || function (n) {\n return Math.log(n) / Math.log(2);\n};\nvar signum = function signum(x) {\n if (x > 0) {\n return 1;\n } else if (x < 0) {\n return -1;\n } else {\n return 0;\n }\n};\nvar dist = function dist(p1, p2) {\n return Math.sqrt(sqdist(p1, p2));\n};\nvar sqdist = function sqdist(p1, p2) {\n var dx = p2.x - p1.x;\n var dy = p2.y - p1.y;\n return dx * dx + dy * dy;\n};\nvar inPlaceSumNormalize = function inPlaceSumNormalize(v) {\n var length = v.length;\n\n // First, get sum of all elements\n var total = 0;\n for (var i = 0; i < length; i++) {\n total += v[i];\n }\n\n // Now, divide each by the sum of all elements\n for (var _i = 0; _i < length; _i++) {\n v[_i] = v[_i] / total;\n }\n return v;\n};\n\n// from http://en.wikipedia.org/wiki/B\u00E9zier_curve#Quadratic_curves\nvar qbezierAt = function qbezierAt(p0, p1, p2, t) {\n return (1 - t) * (1 - t) * p0 + 2 * (1 - t) * t * p1 + t * t * p2;\n};\nvar qbezierPtAt = function qbezierPtAt(p0, p1, p2, t) {\n return {\n x: qbezierAt(p0.x, p1.x, p2.x, t),\n y: qbezierAt(p0.y, p1.y, p2.y, t)\n };\n};\nvar lineAt = function lineAt(p0, p1, t, d) {\n var vec = {\n x: p1.x - p0.x,\n y: p1.y - p0.y\n };\n var vecDist = dist(p0, p1);\n var normVec = {\n x: vec.x / vecDist,\n y: vec.y / vecDist\n };\n t = t == null ? 0 : t;\n d = d != null ? d : t * vecDist;\n return {\n x: p0.x + normVec.x * d,\n y: p0.y + normVec.y * d\n };\n};\nvar bound = function bound(min, val, max) {\n return Math.max(min, Math.min(max, val));\n};\n\n// makes a full bb (x1, y1, x2, y2, w, h) from implicit params\nvar makeBoundingBox = function makeBoundingBox(bb) {\n if (bb == null) {\n return {\n x1: Infinity,\n y1: Infinity,\n x2: -Infinity,\n y2: -Infinity,\n w: 0,\n h: 0\n };\n } else if (bb.x1 != null && bb.y1 != null) {\n if (bb.x2 != null && bb.y2 != null && bb.x2 >= bb.x1 && bb.y2 >= bb.y1) {\n return {\n x1: bb.x1,\n y1: bb.y1,\n x2: bb.x2,\n y2: bb.y2,\n w: bb.x2 - bb.x1,\n h: bb.y2 - bb.y1\n };\n } else if (bb.w != null && bb.h != null && bb.w >= 0 && bb.h >= 0) {\n return {\n x1: bb.x1,\n y1: bb.y1,\n x2: bb.x1 + bb.w,\n y2: bb.y1 + bb.h,\n w: bb.w,\n h: bb.h\n };\n }\n }\n};\nvar copyBoundingBox = function copyBoundingBox(bb) {\n return {\n x1: bb.x1,\n x2: bb.x2,\n w: bb.w,\n y1: bb.y1,\n y2: bb.y2,\n h: bb.h\n };\n};\nvar clearBoundingBox = function clearBoundingBox(bb) {\n bb.x1 = Infinity;\n bb.y1 = Infinity;\n bb.x2 = -Infinity;\n bb.y2 = -Infinity;\n bb.w = 0;\n bb.h = 0;\n};\nvar updateBoundingBox = function updateBoundingBox(bb1, bb2) {\n // update bb1 with bb2 bounds\n\n bb1.x1 = Math.min(bb1.x1, bb2.x1);\n bb1.x2 = Math.max(bb1.x2, bb2.x2);\n bb1.w = bb1.x2 - bb1.x1;\n bb1.y1 = Math.min(bb1.y1, bb2.y1);\n bb1.y2 = Math.max(bb1.y2, bb2.y2);\n bb1.h = bb1.y2 - bb1.y1;\n};\nvar expandBoundingBoxByPoint = function expandBoundingBoxByPoint(bb, x, y) {\n bb.x1 = Math.min(bb.x1, x);\n bb.x2 = Math.max(bb.x2, x);\n bb.w = bb.x2 - bb.x1;\n bb.y1 = Math.min(bb.y1, y);\n bb.y2 = Math.max(bb.y2, y);\n bb.h = bb.y2 - bb.y1;\n};\nvar expandBoundingBox = function expandBoundingBox(bb) {\n var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n bb.x1 -= padding;\n bb.x2 += padding;\n bb.y1 -= padding;\n bb.y2 += padding;\n bb.w = bb.x2 - bb.x1;\n bb.h = bb.y2 - bb.y1;\n return bb;\n};\nvar expandBoundingBoxSides = function expandBoundingBoxSides(bb) {\n var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [0];\n var top, right, bottom, left;\n if (padding.length === 1) {\n top = right = bottom = left = padding[0];\n } else if (padding.length === 2) {\n top = bottom = padding[0];\n left = right = padding[1];\n } else if (padding.length === 4) {\n var _padding = _slicedToArray(padding, 4);\n top = _padding[0];\n right = _padding[1];\n bottom = _padding[2];\n left = _padding[3];\n }\n bb.x1 -= left;\n bb.x2 += right;\n bb.y1 -= top;\n bb.y2 += bottom;\n bb.w = bb.x2 - bb.x1;\n bb.h = bb.y2 - bb.y1;\n return bb;\n};\n\n// assign the values of bb2 into bb1\nvar assignBoundingBox = function assignBoundingBox(bb1, bb2) {\n bb1.x1 = bb2.x1;\n bb1.y1 = bb2.y1;\n bb1.x2 = bb2.x2;\n bb1.y2 = bb2.y2;\n bb1.w = bb1.x2 - bb1.x1;\n bb1.h = bb1.y2 - bb1.y1;\n};\nvar boundingBoxesIntersect = function boundingBoxesIntersect(bb1, bb2) {\n // case: one bb to right of other\n if (bb1.x1 > bb2.x2) {\n return false;\n }\n if (bb2.x1 > bb1.x2) {\n return false;\n }\n\n // case: one bb to left of other\n if (bb1.x2 < bb2.x1) {\n return false;\n }\n if (bb2.x2 < bb1.x1) {\n return false;\n }\n\n // case: one bb above other\n if (bb1.y2 < bb2.y1) {\n return false;\n }\n if (bb2.y2 < bb1.y1) {\n return false;\n }\n\n // case: one bb below other\n if (bb1.y1 > bb2.y2) {\n return false;\n }\n if (bb2.y1 > bb1.y2) {\n return false;\n }\n\n // otherwise, must have some overlap\n return true;\n};\nvar inBoundingBox = function inBoundingBox(bb, x, y) {\n return bb.x1 <= x && x <= bb.x2 && bb.y1 <= y && y <= bb.y2;\n};\nvar pointInBoundingBox = function pointInBoundingBox(bb, pt) {\n return inBoundingBox(bb, pt.x, pt.y);\n};\nvar boundingBoxInBoundingBox = function boundingBoxInBoundingBox(bb1, bb2) {\n return inBoundingBox(bb1, bb2.x1, bb2.y1) && inBoundingBox(bb1, bb2.x2, bb2.y2);\n};\nvar hypot = (_Math$hypot = Math.hypot) !== null && _Math$hypot !== undefined ? _Math$hypot : function (x, y) {\n return Math.sqrt(x * x + y * y);\n};\nfunction inflatePolygon(polygon, d) {\n if (polygon.length < 3) {\n throw new Error('Need at least 3 vertices');\n }\n // Helpers\n var add = function add(a, b) {\n return {\n x: a.x + b.x,\n y: a.y + b.y\n };\n };\n var sub = function sub(a, b) {\n return {\n x: a.x - b.x,\n y: a.y - b.y\n };\n };\n var scale = function scale(v, s) {\n return {\n x: v.x * s,\n y: v.y * s\n };\n };\n var cross = function cross(u, v) {\n return u.x * v.y - u.y * v.x;\n };\n var normalize = function normalize(v) {\n var len = hypot(v.x, v.y);\n return len === 0 ? {\n x: 0,\n y: 0\n } : {\n x: v.x / len,\n y: v.y / len\n };\n };\n // Signed area (positive = CCW)\n var signedArea = function signedArea(pts) {\n var A = 0;\n for (var i = 0; i < pts.length; i++) {\n var p = pts[i],\n q = pts[(i + 1) % pts.length];\n A += p.x * q.y - q.x * p.y;\n }\n return A / 2;\n };\n // Line\u2013line intersection (infinite lines)\n var intersectLines = function intersectLines(p1, p2, p3, p4) {\n var r = sub(p2, p1);\n var s = sub(p4, p3);\n var denom = cross(r, s);\n if (Math.abs(denom) < 1e-9) {\n // Parallel or nearly so \u2014 fallback to midpoint\n return add(p1, scale(r, 0.5));\n }\n var t = cross(sub(p3, p1), s) / denom;\n return add(p1, scale(r, t));\n };\n\n // Make a shallow copy and enforce CCW\n var pts = polygon.map(function (p) {\n return {\n x: p.x,\n y: p.y\n };\n });\n if (signedArea(pts) < 0) pts.reverse();\n var n = pts.length;\n // Compute outward normals for each edge\n var normals = [];\n for (var i = 0; i < n; i++) {\n var p = pts[i],\n q = pts[(i + 1) % n];\n var edge = sub(q, p);\n // For CCW polygon, inward normal = (-edge.y, edge.x)\n // so outward normal = (edge.y, -edge.x)\n var out = normalize({\n x: edge.y,\n y: -edge.x\n });\n normals.push(out);\n }\n\n // Build offset edges\n var offsetEdges = normals.map(function (nrm, i) {\n var p1 = add(pts[i], scale(nrm, d));\n var p2 = add(pts[(i + 1) % n], scale(nrm, d));\n return {\n p1: p1,\n p2: p2\n };\n });\n\n // Intersect consecutive offset edges\n var inflated = [];\n for (var _i2 = 0; _i2 < n; _i2++) {\n var prevEdge = offsetEdges[(_i2 - 1 + n) % n];\n var currEdge = offsetEdges[_i2];\n var ip = intersectLines(prevEdge.p1, prevEdge.p2, currEdge.p1, currEdge.p2);\n inflated.push(ip);\n }\n return inflated;\n}\nfunction miterBox(pts, centerX, centerY, width, height, strokeWidth) {\n var tpts = transformPoints(pts, centerX, centerY, width, height);\n var offsetPoints = inflatePolygon(tpts, strokeWidth);\n var bb = makeBoundingBox();\n offsetPoints.forEach(function (pt) {\n return expandBoundingBoxByPoint(bb, pt.x, pt.y);\n });\n return bb;\n}\nvar roundRectangleIntersectLine = function roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding) {\n var radius = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 'auto';\n var cornerRadius = radius === 'auto' ? getRoundRectangleRadius(width, height) : radius;\n var halfWidth = width / 2;\n var halfHeight = height / 2;\n cornerRadius = Math.min(cornerRadius, halfWidth, halfHeight);\n var doWidth = cornerRadius !== halfWidth,\n doHeight = cornerRadius !== halfHeight;\n\n // Check intersections with straight line segments\n var straightLineIntersections;\n\n // Top segment, left to right\n if (doWidth) {\n var topStartX = nodeX - halfWidth + cornerRadius - padding;\n var topStartY = nodeY - halfHeight - padding;\n var topEndX = nodeX + halfWidth - cornerRadius + padding;\n var topEndY = topStartY;\n straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, topStartX, topStartY, topEndX, topEndY, false);\n if (straightLineIntersections.length > 0) {\n return straightLineIntersections;\n }\n }\n\n // Right segment, top to bottom\n if (doHeight) {\n var rightStartX = nodeX + halfWidth + padding;\n var rightStartY = nodeY - halfHeight + cornerRadius - padding;\n var rightEndX = rightStartX;\n var rightEndY = nodeY + halfHeight - cornerRadius + padding;\n straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, rightStartX, rightStartY, rightEndX, rightEndY, false);\n if (straightLineIntersections.length > 0) {\n return straightLineIntersections;\n }\n }\n\n // Bottom segment, left to right\n if (doWidth) {\n var bottomStartX = nodeX - halfWidth + cornerRadius - padding;\n var bottomStartY = nodeY + halfHeight + padding;\n var bottomEndX = nodeX + halfWidth - cornerRadius + padding;\n var bottomEndY = bottomStartY;\n straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, bottomStartX, bottomStartY, bottomEndX, bottomEndY, false);\n if (straightLineIntersections.length > 0) {\n return straightLineIntersections;\n }\n }\n\n // Left segment, top to bottom\n if (doHeight) {\n var leftStartX = nodeX - halfWidth - padding;\n var leftStartY = nodeY - halfHeight + cornerRadius - padding;\n var leftEndX = leftStartX;\n var leftEndY = nodeY + halfHeight - cornerRadius + padding;\n straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, leftStartX, leftStartY, leftEndX, leftEndY, false);\n if (straightLineIntersections.length > 0) {\n return straightLineIntersections;\n }\n }\n\n // Check intersections with arc segments\n var arcIntersections;\n\n // Top Left\n {\n var topLeftCenterX = nodeX - halfWidth + cornerRadius;\n var topLeftCenterY = nodeY - halfHeight + cornerRadius;\n arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, topLeftCenterX, topLeftCenterY, cornerRadius + padding);\n\n // Ensure the intersection is on the desired quarter of the circle\n if (arcIntersections.length > 0 && arcIntersections[0] <= topLeftCenterX && arcIntersections[1] <= topLeftCenterY) {\n return [arcIntersections[0], arcIntersections[1]];\n }\n }\n\n // Top Right\n {\n var topRightCenterX = nodeX + halfWidth - cornerRadius;\n var topRightCenterY = nodeY - halfHeight + cornerRadius;\n arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, topRightCenterX, topRightCenterY, cornerRadius + padding);\n\n // Ensure the intersection is on the desired quarter of the circle\n if (arcIntersections.length > 0 && arcIntersections[0] >= topRightCenterX && arcIntersections[1] <= topRightCenterY) {\n return [arcIntersections[0], arcIntersections[1]];\n }\n }\n\n // Bottom Right\n {\n var bottomRightCenterX = nodeX + halfWidth - cornerRadius;\n var bottomRightCenterY = nodeY + halfHeight - cornerRadius;\n arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, bottomRightCenterX, bottomRightCenterY, cornerRadius + padding);\n\n // Ensure the intersection is on the desired quarter of the circle\n if (arcIntersections.length > 0 && arcIntersections[0] >= bottomRightCenterX && arcIntersections[1] >= bottomRightCenterY) {\n return [arcIntersections[0], arcIntersections[1]];\n }\n }\n\n // Bottom Left\n {\n var bottomLeftCenterX = nodeX - halfWidth + cornerRadius;\n var bottomLeftCenterY = nodeY + halfHeight - cornerRadius;\n arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, bottomLeftCenterX, bottomLeftCenterY, cornerRadius + padding);\n\n // Ensure the intersection is on the desired quarter of the circle\n if (arcIntersections.length > 0 && arcIntersections[0] <= bottomLeftCenterX && arcIntersections[1] >= bottomLeftCenterY) {\n return [arcIntersections[0], arcIntersections[1]];\n }\n }\n return []; // if nothing\n};\nvar inLineVicinity = function inLineVicinity(x, y, lx1, ly1, lx2, ly2, tolerance) {\n var t = tolerance;\n var x1 = Math.min(lx1, lx2);\n var x2 = Math.max(lx1, lx2);\n var y1 = Math.min(ly1, ly2);\n var y2 = Math.max(ly1, ly2);\n return x1 - t <= x && x <= x2 + t && y1 - t <= y && y <= y2 + t;\n};\nvar inBezierVicinity = function inBezierVicinity(x, y, x1, y1, x2, y2, x3, y3, tolerance) {\n var bb = {\n x1: Math.min(x1, x3, x2) - tolerance,\n x2: Math.max(x1, x3, x2) + tolerance,\n y1: Math.min(y1, y3, y2) - tolerance,\n y2: Math.max(y1, y3, y2) + tolerance\n };\n\n // if outside the rough bounding box for the bezier, then it can't be a hit\n if (x < bb.x1 || x > bb.x2 || y < bb.y1 || y > bb.y2) {\n // console.log('bezier out of rough bb')\n return false;\n } else {\n // console.log('do more expensive check');\n return true;\n }\n};\nvar solveQuadratic = function solveQuadratic(a, b, c, val) {\n c -= val;\n var r = b * b - 4 * a * c;\n if (r < 0) {\n return [];\n }\n var sqrtR = Math.sqrt(r);\n var denom = 2 * a;\n var root1 = (-b + sqrtR) / denom;\n var root2 = (-b - sqrtR) / denom;\n return [root1, root2];\n};\nvar solveCubic = function solveCubic(a, b, c, d, result) {\n // Solves a cubic function, returns root in form [r1, i1, r2, i2, r3, i3], where\n // r is the real component, i is the imaginary component\n\n // An implementation of the Cardano method from the year 1545\n // http://en.wikipedia.org/wiki/Cubic_function#The_nature_of_the_roots\n\n var epsilon = 0.00001;\n\n // avoid division by zero while keeping the overall expression close in value\n if (a === 0) {\n a = epsilon;\n }\n b /= a;\n c /= a;\n d /= a;\n var discriminant, q, r, dum1, s, t, term1, r13;\n q = (3.0 * c - b * b) / 9.0;\n r = -(27.0 * d) + b * (9.0 * c - 2.0 * (b * b));\n r /= 54.0;\n discriminant = q * q * q + r * r;\n result[1] = 0;\n term1 = b / 3.0;\n if (discriminant > 0) {\n s = r + Math.sqrt(discriminant);\n s = s < 0 ? -Math.pow(-s, 1.0 / 3.0) : Math.pow(s, 1.0 / 3.0);\n t = r - Math.sqrt(discriminant);\n t = t < 0 ? -Math.pow(-t, 1.0 / 3.0) : Math.pow(t, 1.0 / 3.0);\n result[0] = -term1 + s + t;\n term1 += (s + t) / 2.0;\n result[4] = result[2] = -term1;\n term1 = Math.sqrt(3.0) * (-t + s) / 2;\n result[3] = term1;\n result[5] = -term1;\n return;\n }\n result[5] = result[3] = 0;\n if (discriminant === 0) {\n r13 = r < 0 ? -Math.pow(-r, 1.0 / 3.0) : Math.pow(r, 1.0 / 3.0);\n result[0] = -term1 + 2.0 * r13;\n result[4] = result[2] = -(r13 + term1);\n return;\n }\n q = -q;\n dum1 = q * q * q;\n dum1 = Math.acos(r / Math.sqrt(dum1));\n r13 = 2.0 * Math.sqrt(q);\n result[0] = -term1 + r13 * Math.cos(dum1 / 3.0);\n result[2] = -term1 + r13 * Math.cos((dum1 + 2.0 * Math.PI) / 3.0);\n result[4] = -term1 + r13 * Math.cos((dum1 + 4.0 * Math.PI) / 3.0);\n return;\n};\nvar sqdistToQuadraticBezier = function sqdistToQuadraticBezier(x, y, x1, y1, x2, y2, x3, y3) {\n // Find minimum distance by using the minimum of the distance\n // function between the given point and the curve\n\n // This gives the coefficients of the resulting cubic equation\n // whose roots tell us where a possible minimum is\n // (Coefficients are divided by 4)\n\n var a = 1.0 * x1 * x1 - 4 * x1 * x2 + 2 * x1 * x3 + 4 * x2 * x2 - 4 * x2 * x3 + x3 * x3 + y1 * y1 - 4 * y1 * y2 + 2 * y1 * y3 + 4 * y2 * y2 - 4 * y2 * y3 + y3 * y3;\n var b = 1.0 * 9 * x1 * x2 - 3 * x1 * x1 - 3 * x1 * x3 - 6 * x2 * x2 + 3 * x2 * x3 + 9 * y1 * y2 - 3 * y1 * y1 - 3 * y1 * y3 - 6 * y2 * y2 + 3 * y2 * y3;\n var c = 1.0 * 3 * x1 * x1 - 6 * x1 * x2 + x1 * x3 - x1 * x + 2 * x2 * x2 + 2 * x2 * x - x3 * x + 3 * y1 * y1 - 6 * y1 * y2 + y1 * y3 - y1 * y + 2 * y2 * y2 + 2 * y2 * y - y3 * y;\n var d = 1.0 * x1 * x2 - x1 * x1 + x1 * x - x2 * x + y1 * y2 - y1 * y1 + y1 * y - y2 * y;\n\n // debug(\"coefficients: \" + a / a + \", \" + b / a + \", \" + c / a + \", \" + d / a);\n\n var roots = [];\n\n // Use the cubic solving algorithm\n solveCubic(a, b, c, d, roots);\n var zeroThreshold = 0.0000001;\n var params = [];\n for (var index = 0; index < 6; index += 2) {\n if (Math.abs(roots[index + 1]) < zeroThreshold && roots[index] >= 0 && roots[index] <= 1.0) {\n params.push(roots[index]);\n }\n }\n params.push(1.0);\n params.push(0.0);\n var minDistanceSquared = -1;\n var curX, curY, distSquared;\n for (var i = 0; i < params.length; i++) {\n curX = Math.pow(1.0 - params[i], 2.0) * x1 + 2.0 * (1 - params[i]) * params[i] * x2 + params[i] * params[i] * x3;\n curY = Math.pow(1 - params[i], 2.0) * y1 + 2 * (1.0 - params[i]) * params[i] * y2 + params[i] * params[i] * y3;\n distSquared = Math.pow(curX - x, 2) + Math.pow(curY - y, 2);\n // debug('distance for param ' + params[i] + \": \" + Math.sqrt(distSquared));\n if (minDistanceSquared >= 0) {\n if (distSquared < minDistanceSquared) {\n minDistanceSquared = distSquared;\n }\n } else {\n minDistanceSquared = distSquared;\n }\n }\n return minDistanceSquared;\n};\nvar sqdistToFiniteLine = function sqdistToFiniteLine(x, y, x1, y1, x2, y2) {\n var offset = [x - x1, y - y1];\n var line = [x2 - x1, y2 - y1];\n var lineSq = line[0] * line[0] + line[1] * line[1];\n var hypSq = offset[0] * offset[0] + offset[1] * offset[1];\n var dotProduct = offset[0] * line[0] + offset[1] * line[1];\n var adjSq = dotProduct * dotProduct / lineSq;\n if (dotProduct < 0) {\n return hypSq;\n }\n if (adjSq > lineSq) {\n return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n }\n return hypSq - adjSq;\n};\nvar pointInsidePolygonPoints = function pointInsidePolygonPoints(x, y, points) {\n var x1, y1, x2, y2;\n var y3;\n\n // Intersect with vertical line through (x, y)\n var up = 0;\n // let down = 0;\n for (var i = 0; i < points.length / 2; i++) {\n x1 = points[i * 2];\n y1 = points[i * 2 + 1];\n if (i + 1 < points.length / 2) {\n x2 = points[(i + 1) * 2];\n y2 = points[(i + 1) * 2 + 1];\n } else {\n x2 = points[(i + 1 - points.length / 2) * 2];\n y2 = points[(i + 1 - points.length / 2) * 2 + 1];\n }\n if (x1 == x && x2 == x) ; else if (x1 >= x && x >= x2 || x1 <= x && x <= x2) {\n y3 = (x - x1) / (x2 - x1) * (y2 - y1) + y1;\n if (y3 > y) {\n up++;\n }\n\n // if( y3 < y ){\n // down++;\n // }\n } else {\n continue;\n }\n }\n if (up % 2 === 0) {\n return false;\n } else {\n return true;\n }\n};\nvar pointInsidePolygon = function pointInsidePolygon(x, y, basePoints, centerX, centerY, width, height, direction, padding) {\n var transformedPoints = new Array(basePoints.length);\n\n // Gives negative angle\n var angle;\n if (direction[0] != null) {\n angle = Math.atan(direction[1] / direction[0]);\n if (direction[0] < 0) {\n angle = angle + Math.PI / 2;\n } else {\n angle = -angle - Math.PI / 2;\n }\n } else {\n angle = direction;\n }\n var cos = Math.cos(-angle);\n var sin = Math.sin(-angle);\n\n // console.log(\"base: \" + basePoints);\n for (var i = 0; i < transformedPoints.length / 2; i++) {\n transformedPoints[i * 2] = width / 2 * (basePoints[i * 2] * cos - basePoints[i * 2 + 1] * sin);\n transformedPoints[i * 2 + 1] = height / 2 * (basePoints[i * 2 + 1] * cos + basePoints[i * 2] * sin);\n transformedPoints[i * 2] += centerX;\n transformedPoints[i * 2 + 1] += centerY;\n }\n var points;\n if (padding > 0) {\n var expandedLineSet = expandPolygon(transformedPoints, -padding);\n points = joinLines(expandedLineSet);\n } else {\n points = transformedPoints;\n }\n return pointInsidePolygonPoints(x, y, points);\n};\nvar pointInsideRoundPolygon = function pointInsideRoundPolygon(x, y, basePoints, centerX, centerY, width, height, corners) {\n var cutPolygonPoints = new Array(basePoints.length * 2);\n for (var i = 0; i < corners.length; i++) {\n var corner = corners[i];\n cutPolygonPoints[i * 4 + 0] = corner.startX;\n cutPolygonPoints[i * 4 + 1] = corner.startY;\n cutPolygonPoints[i * 4 + 2] = corner.stopX;\n cutPolygonPoints[i * 4 + 3] = corner.stopY;\n var squaredDistance = Math.pow(corner.cx - x, 2) + Math.pow(corner.cy - y, 2);\n if (squaredDistance <= Math.pow(corner.radius, 2)) {\n return true;\n }\n }\n return pointInsidePolygonPoints(x, y, cutPolygonPoints);\n};\nvar joinLines = function joinLines(lineSet) {\n var vertices = new Array(lineSet.length / 2);\n var currentLineStartX, currentLineStartY, currentLineEndX, currentLineEndY;\n var nextLineStartX, nextLineStartY, nextLineEndX, nextLineEndY;\n for (var i = 0; i < lineSet.length / 4; i++) {\n currentLineStartX = lineSet[i * 4];\n currentLineStartY = lineSet[i * 4 + 1];\n currentLineEndX = lineSet[i * 4 + 2];\n currentLineEndY = lineSet[i * 4 + 3];\n if (i < lineSet.length / 4 - 1) {\n nextLineStartX = lineSet[(i + 1) * 4];\n nextLineStartY = lineSet[(i + 1) * 4 + 1];\n nextLineEndX = lineSet[(i + 1) * 4 + 2];\n nextLineEndY = lineSet[(i + 1) * 4 + 3];\n } else {\n nextLineStartX = lineSet[0];\n nextLineStartY = lineSet[1];\n nextLineEndX = lineSet[2];\n nextLineEndY = lineSet[3];\n }\n var intersection = finiteLinesIntersect(currentLineStartX, currentLineStartY, currentLineEndX, currentLineEndY, nextLineStartX, nextLineStartY, nextLineEndX, nextLineEndY, true);\n vertices[i * 2] = intersection[0];\n vertices[i * 2 + 1] = intersection[1];\n }\n return vertices;\n};\nvar expandPolygon = function expandPolygon(points, pad) {\n var expandedLineSet = new Array(points.length * 2);\n var currentPointX, currentPointY, nextPointX, nextPointY;\n for (var i = 0; i < points.length / 2; i++) {\n currentPointX = points[i * 2];\n currentPointY = points[i * 2 + 1];\n if (i < points.length / 2 - 1) {\n nextPointX = points[(i + 1) * 2];\n nextPointY = points[(i + 1) * 2 + 1];\n } else {\n nextPointX = points[0];\n nextPointY = points[1];\n }\n\n // Current line: [currentPointX, currentPointY] to [nextPointX, nextPointY]\n\n // Assume CCW polygon winding\n\n var offsetX = nextPointY - currentPointY;\n var offsetY = -(nextPointX - currentPointX);\n\n // Normalize\n var offsetLength = Math.sqrt(offsetX * offsetX + offsetY * offsetY);\n var normalizedOffsetX = offsetX / offsetLength;\n var normalizedOffsetY = offsetY / offsetLength;\n expandedLineSet[i * 4] = currentPointX + normalizedOffsetX * pad;\n expandedLineSet[i * 4 + 1] = currentPointY + normalizedOffsetY * pad;\n expandedLineSet[i * 4 + 2] = nextPointX + normalizedOffsetX * pad;\n expandedLineSet[i * 4 + 3] = nextPointY + normalizedOffsetY * pad;\n }\n return expandedLineSet;\n};\nvar intersectLineEllipse = function intersectLineEllipse(x, y, centerX, centerY, ellipseWradius, ellipseHradius) {\n var dispX = centerX - x;\n var dispY = centerY - y;\n dispX /= ellipseWradius;\n dispY /= ellipseHradius;\n var len = Math.sqrt(dispX * dispX + dispY * dispY);\n var newLength = len - 1;\n if (newLength < 0) {\n return [];\n }\n var lenProportion = newLength / len;\n return [(centerX - x) * lenProportion + x, (centerY - y) * lenProportion + y];\n};\nvar checkInEllipse = function checkInEllipse(x, y, width, height, centerX, centerY, padding) {\n x -= centerX;\n y -= centerY;\n x /= width / 2 + padding;\n y /= height / 2 + padding;\n return x * x + y * y <= 1;\n};\n\n// Returns intersections of increasing distance from line's start point\nvar intersectLineCircle = function intersectLineCircle(x1, y1, x2, y2, centerX, centerY, radius) {\n // Calculate d, direction vector of line\n var d = [x2 - x1, y2 - y1]; // Direction vector of line\n var f = [x1 - centerX, y1 - centerY];\n var a = d[0] * d[0] + d[1] * d[1];\n var b = 2 * (f[0] * d[0] + f[1] * d[1]);\n var c = f[0] * f[0] + f[1] * f[1] - radius * radius;\n var discriminant = b * b - 4 * a * c;\n if (discriminant < 0) {\n return [];\n }\n var t1 = (-b + Math.sqrt(discriminant)) / (2 * a);\n var t2 = (-b - Math.sqrt(discriminant)) / (2 * a);\n var tMin = Math.min(t1, t2);\n var tMax = Math.max(t1, t2);\n var inRangeParams = [];\n if (tMin >= 0 && tMin <= 1) {\n inRangeParams.push(tMin);\n }\n if (tMax >= 0 && tMax <= 1) {\n inRangeParams.push(tMax);\n }\n if (inRangeParams.length === 0) {\n return [];\n }\n var nearIntersectionX = inRangeParams[0] * d[0] + x1;\n var nearIntersectionY = inRangeParams[0] * d[1] + y1;\n if (inRangeParams.length > 1) {\n if (inRangeParams[0] == inRangeParams[1]) {\n return [nearIntersectionX, nearIntersectionY];\n } else {\n var farIntersectionX = inRangeParams[1] * d[0] + x1;\n var farIntersectionY = inRangeParams[1] * d[1] + y1;\n return [nearIntersectionX, nearIntersectionY, farIntersectionX, farIntersectionY];\n }\n } else {\n return [nearIntersectionX, nearIntersectionY];\n }\n};\nvar midOfThree = function midOfThree(a, b, c) {\n if (b <= a && a <= c || c <= a && a <= b) {\n return a;\n } else if (a <= b && b <= c || c <= b && b <= a) {\n return b;\n } else {\n return c;\n }\n};\n\n// (x1,y1)=>(x2,y2) intersect with (x3,y3)=>(x4,y4)\nvar finiteLinesIntersect = function finiteLinesIntersect(x1, y1, x2, y2, x3, y3, x4, y4, infiniteLines) {\n var dx13 = x1 - x3;\n var dx21 = x2 - x1;\n var dx43 = x4 - x3;\n var dy13 = y1 - y3;\n var dy21 = y2 - y1;\n var dy43 = y4 - y3;\n var ua_t = dx43 * dy13 - dy43 * dx13;\n var ub_t = dx21 * dy13 - dy21 * dx13;\n var u_b = dy43 * dx21 - dx43 * dy21;\n if (u_b !== 0) {\n var ua = ua_t / u_b;\n var ub = ub_t / u_b;\n var flptThreshold = 0.001;\n var _min = 0 - flptThreshold;\n var _max = 1 + flptThreshold;\n if (_min <= ua && ua <= _max && _min <= ub && ub <= _max) {\n return [x1 + ua * dx21, y1 + ua * dy21];\n } else {\n if (!infiniteLines) {\n return [];\n } else {\n return [x1 + ua * dx21, y1 + ua * dy21];\n }\n }\n } else {\n if (ua_t === 0 || ub_t === 0) {\n // Parallel, coincident lines. Check if overlap\n\n // Check endpoint of second line\n if (midOfThree(x1, x2, x4) === x4) {\n return [x4, y4];\n }\n\n // Check start point of second line\n if (midOfThree(x1, x2, x3) === x3) {\n return [x3, y3];\n }\n\n // Endpoint of first line\n if (midOfThree(x3, x4, x2) === x2) {\n return [x2, y2];\n }\n return [];\n } else {\n // Parallel, non-coincident\n return [];\n }\n }\n};\nvar transformPoints = function transformPoints(points, centerX, centerY, width, height) {\n var ret = [];\n var halfW = width / 2;\n var halfH = height / 2;\n var x = centerX;\n var y = centerY;\n ret.push({\n x: x + halfW * points[0],\n y: y + halfH * points[1]\n });\n for (var i = 1; i < points.length / 2; i++) {\n ret.push({\n x: x + halfW * points[i * 2],\n y: y + halfH * points[i * 2 + 1]\n });\n }\n return ret;\n};\n\n// math.polygonIntersectLine( x, y, basePoints, centerX, centerY, width, height, padding )\n// intersect a node polygon (pts transformed)\n//\n// math.polygonIntersectLine( x, y, basePoints, centerX, centerY )\n// intersect the points (no transform)\nvar polygonIntersectLine = function polygonIntersectLine(x, y, basePoints, centerX, centerY, width, height, padding) {\n var intersections = [];\n var intersection;\n var transformedPoints = new Array(basePoints.length);\n var doTransform = true;\n if (width == null) {\n doTransform = false;\n }\n var points;\n if (doTransform) {\n for (var i = 0; i < transformedPoints.length / 2; i++) {\n transformedPoints[i * 2] = basePoints[i * 2] * width + centerX;\n transformedPoints[i * 2 + 1] = basePoints[i * 2 + 1] * height + centerY;\n }\n if (padding > 0) {\n var expandedLineSet = expandPolygon(transformedPoints, -padding);\n points = joinLines(expandedLineSet);\n } else {\n points = transformedPoints;\n }\n } else {\n points = basePoints;\n }\n var currentX, currentY, nextX, nextY;\n for (var _i3 = 0; _i3 < points.length / 2; _i3++) {\n currentX = points[_i3 * 2];\n currentY = points[_i3 * 2 + 1];\n if (_i3 < points.length / 2 - 1) {\n nextX = points[(_i3 + 1) * 2];\n nextY = points[(_i3 + 1) * 2 + 1];\n } else {\n nextX = points[0];\n nextY = points[1];\n }\n intersection = finiteLinesIntersect(x, y, centerX, centerY, currentX, currentY, nextX, nextY);\n if (intersection.length !== 0) {\n intersections.push(intersection[0], intersection[1]);\n }\n }\n return intersections;\n};\nvar roundPolygonIntersectLine = function roundPolygonIntersectLine(x, y, basePoints, centerX, centerY, width, height, padding, corners) {\n var intersections = [];\n var intersection;\n var lines = new Array(basePoints.length * 2);\n corners.forEach(function (corner, i) {\n if (i === 0) {\n lines[lines.length - 2] = corner.startX;\n lines[lines.length - 1] = corner.startY;\n } else {\n lines[i * 4 - 2] = corner.startX;\n lines[i * 4 - 1] = corner.startY;\n }\n lines[i * 4] = corner.stopX;\n lines[i * 4 + 1] = corner.stopY;\n intersection = intersectLineCircle(x, y, centerX, centerY, corner.cx, corner.cy, corner.radius);\n if (intersection.length !== 0) {\n intersections.push(intersection[0], intersection[1]);\n }\n });\n for (var i = 0; i < lines.length / 4; i++) {\n intersection = finiteLinesIntersect(x, y, centerX, centerY, lines[i * 4], lines[i * 4 + 1], lines[i * 4 + 2], lines[i * 4 + 3], false);\n if (intersection.length !== 0) {\n intersections.push(intersection[0], intersection[1]);\n }\n }\n if (intersections.length > 2) {\n var lowestIntersection = [intersections[0], intersections[1]];\n var lowestSquaredDistance = Math.pow(lowestIntersection[0] - x, 2) + Math.pow(lowestIntersection[1] - y, 2);\n for (var _i4 = 1; _i4 < intersections.length / 2; _i4++) {\n var squaredDistance = Math.pow(intersections[_i4 * 2] - x, 2) + Math.pow(intersections[_i4 * 2 + 1] - y, 2);\n if (squaredDistance <= lowestSquaredDistance) {\n lowestIntersection[0] = intersections[_i4 * 2];\n lowestIntersection[1] = intersections[_i4 * 2 + 1];\n lowestSquaredDistance = squaredDistance;\n }\n }\n return lowestIntersection;\n }\n return intersections;\n};\nvar shortenIntersection = function shortenIntersection(intersection, offset, amount) {\n var disp = [intersection[0] - offset[0], intersection[1] - offset[1]];\n var length = Math.sqrt(disp[0] * disp[0] + disp[1] * disp[1]);\n var lenRatio = (length - amount) / length;\n if (lenRatio < 0) {\n lenRatio = 0.00001;\n }\n return [offset[0] + lenRatio * disp[0], offset[1] + lenRatio * disp[1]];\n};\nvar generateUnitNgonPointsFitToSquare = function generateUnitNgonPointsFitToSquare(sides, rotationRadians) {\n var points = generateUnitNgonPoints(sides, rotationRadians);\n points = fitPolygonToSquare(points);\n return points;\n};\nvar fitPolygonToSquare = function fitPolygonToSquare(points) {\n var x, y;\n var sides = points.length / 2;\n var minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n for (var i = 0; i < sides; i++) {\n x = points[2 * i];\n y = points[2 * i + 1];\n minX = Math.min(minX, x);\n maxX = Math.max(maxX, x);\n minY = Math.min(minY, y);\n maxY = Math.max(maxY, y);\n }\n\n // stretch factors\n var sx = 2 / (maxX - minX);\n var sy = 2 / (maxY - minY);\n for (var _i5 = 0; _i5 < sides; _i5++) {\n x = points[2 * _i5] = points[2 * _i5] * sx;\n y = points[2 * _i5 + 1] = points[2 * _i5 + 1] * sy;\n minX = Math.min(minX, x);\n maxX = Math.max(maxX, x);\n minY = Math.min(minY, y);\n maxY = Math.max(maxY, y);\n }\n if (minY < -1) {\n for (var _i6 = 0; _i6 < sides; _i6++) {\n y = points[2 * _i6 + 1] = points[2 * _i6 + 1] + (-1 - minY);\n }\n }\n return points;\n};\nvar generateUnitNgonPoints = function generateUnitNgonPoints(sides, rotationRadians) {\n var increment = 1.0 / sides * 2 * Math.PI;\n var startAngle = sides % 2 === 0 ? Math.PI / 2.0 + increment / 2.0 : Math.PI / 2.0;\n startAngle += rotationRadians;\n var points = new Array(sides * 2);\n var currentAngle;\n for (var i = 0; i < sides; i++) {\n currentAngle = i * increment + startAngle;\n points[2 * i] = Math.cos(currentAngle); // x\n points[2 * i + 1] = Math.sin(-currentAngle); // y\n }\n return points;\n};\n\n// Set the default radius, unless half of width or height is smaller than default\nvar getRoundRectangleRadius = function getRoundRectangleRadius(width, height) {\n return Math.min(width / 4, height / 4, 8);\n};\n\n// Set the default radius\nvar getRoundPolygonRadius = function getRoundPolygonRadius(width, height) {\n return Math.min(width / 10, height / 10, 8);\n};\nvar getCutRectangleCornerLength = function getCutRectangleCornerLength() {\n return 8;\n};\nvar bezierPtsToQuadCoeff = function bezierPtsToQuadCoeff(p0, p1, p2) {\n return [p0 - 2 * p1 + p2, 2 * (p1 - p0), p0];\n};\n\n// get curve width, height, and control point position offsets as a percentage of node height / width\nvar getBarrelCurveConstants = function getBarrelCurveConstants(width, height) {\n return {\n heightOffset: Math.min(15, 0.05 * height),\n widthOffset: Math.min(100, 0.25 * width),\n ctrlPtOffsetPct: 0.05\n };\n};\n\n// Separating Axis Theorem (SAT) to determine if two polygons intersect. \n// The function takes two polygons as input and returns a boolean value indicating \n// whether the two polygons intersect.\nfunction satPolygonIntersection(poly1, poly2) {\n function getAxes(polygon) {\n var axes = [];\n for (var i = 0; i < polygon.length; i++) {\n var p1 = polygon[i];\n var p2 = polygon[(i + 1) % polygon.length];\n var edge = {\n x: p2.x - p1.x,\n y: p2.y - p1.y\n };\n var normal = {\n x: -edge.y,\n y: edge.x\n };\n var length = Math.sqrt(normal.x * normal.x + normal.y * normal.y);\n axes.push({\n x: normal.x / length,\n y: normal.y / length\n });\n }\n return axes;\n }\n function project(polygon, axis) {\n var min = Infinity;\n var max = -Infinity;\n var _iterator = _createForOfIteratorHelper(polygon),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var point = _step.value;\n var projection = point.x * axis.x + point.y * axis.y;\n min = Math.min(min, projection);\n max = Math.max(max, projection);\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n return {\n min: min,\n max: max\n };\n }\n function overlaps(proj1, proj2) {\n return !(proj1.max < proj2.min || proj2.max < proj1.min);\n }\n var axes = [].concat(_toConsumableArray(getAxes(poly1)), _toConsumableArray(getAxes(poly2)));\n var _iterator2 = _createForOfIteratorHelper(axes),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var axis = _step2.value;\n var proj1 = project(poly1, axis);\n var proj2 = project(poly2, axis);\n if (!overlaps(proj1, proj2)) {\n return false; // No overlap, so the polygons do not intersect\n }\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n return true; // polygons intersect\n}\n\nvar pageRankDefaults = defaults$g({\n dampingFactor: 0.8,\n precision: 0.000001,\n iterations: 200,\n weight: function weight(edge) {\n return 1;\n }\n});\nvar elesfn$o = {\n pageRank: function pageRank(options) {\n var _pageRankDefaults = pageRankDefaults(options),\n dampingFactor = _pageRankDefaults.dampingFactor,\n precision = _pageRankDefaults.precision,\n iterations = _pageRankDefaults.iterations,\n weight = _pageRankDefaults.weight;\n var cy = this._private.cy;\n var _this$byGroup = this.byGroup(),\n nodes = _this$byGroup.nodes,\n edges = _this$byGroup.edges;\n var numNodes = nodes.length;\n var numNodesSqd = numNodes * numNodes;\n var numEdges = edges.length;\n\n // Construct transposed adjacency matrix\n // First lets have a zeroed matrix of the right size\n // We'll also keep track of the sum of each column\n var matrix = new Array(numNodesSqd);\n var columnSum = new Array(numNodes);\n var additionalProb = (1 - dampingFactor) / numNodes;\n\n // Create null matrix\n for (var i = 0; i < numNodes; i++) {\n for (var j = 0; j < numNodes; j++) {\n var n = i * numNodes + j;\n matrix[n] = 0;\n }\n columnSum[i] = 0;\n }\n\n // Now, process edges\n for (var _i = 0; _i < numEdges; _i++) {\n var edge = edges[_i];\n var srcId = edge.data('source');\n var tgtId = edge.data('target');\n\n // Don't include loops in the matrix\n if (srcId === tgtId) {\n continue;\n }\n var s = nodes.indexOfId(srcId);\n var t = nodes.indexOfId(tgtId);\n var w = weight(edge);\n var _n = t * numNodes + s;\n\n // Update matrix\n matrix[_n] += w;\n\n // Update column sum\n columnSum[s] += w;\n }\n\n // Add additional probability based on damping factor\n // Also, take into account columns that have sum = 0\n var p = 1.0 / numNodes + additionalProb; // Shorthand\n\n // Traverse matrix, column by column\n for (var _j = 0; _j < numNodes; _j++) {\n if (columnSum[_j] === 0) {\n // No 'links' out from node jth, assume equal probability for each possible node\n for (var _i2 = 0; _i2 < numNodes; _i2++) {\n var _n2 = _i2 * numNodes + _j;\n matrix[_n2] = p;\n }\n } else {\n // Node jth has outgoing link, compute normalized probabilities\n for (var _i3 = 0; _i3 < numNodes; _i3++) {\n var _n3 = _i3 * numNodes + _j;\n matrix[_n3] = matrix[_n3] / columnSum[_j] + additionalProb;\n }\n }\n }\n\n // Compute dominant eigenvector using power method\n var eigenvector = new Array(numNodes);\n var temp = new Array(numNodes);\n var previous;\n\n // Start with a vector of all 1's\n // Also, initialize a null vector which will be used as shorthand\n for (var _i4 = 0; _i4 < numNodes; _i4++) {\n eigenvector[_i4] = 1;\n }\n for (var iter = 0; iter < iterations; iter++) {\n // Temp array with all 0's\n for (var _i5 = 0; _i5 < numNodes; _i5++) {\n temp[_i5] = 0;\n }\n\n // Multiply matrix with previous result\n for (var _i6 = 0; _i6 < numNodes; _i6++) {\n for (var _j2 = 0; _j2 < numNodes; _j2++) {\n var _n4 = _i6 * numNodes + _j2;\n temp[_i6] += matrix[_n4] * eigenvector[_j2];\n }\n }\n inPlaceSumNormalize(temp);\n previous = eigenvector;\n eigenvector = temp;\n temp = previous;\n var diff = 0;\n // Compute difference (squared module) of both vectors\n for (var _i7 = 0; _i7 < numNodes; _i7++) {\n var delta = previous[_i7] - eigenvector[_i7];\n diff += delta * delta;\n }\n\n // If difference is less than the desired threshold, stop iterating\n if (diff < precision) {\n break;\n }\n }\n\n // Construct result\n var res = {\n rank: function rank(node) {\n node = cy.collection(node)[0];\n return eigenvector[nodes.indexOf(node)];\n }\n };\n return res;\n } // pageRank\n}; // elesfn\n\nvar defaults$f = defaults$g({\n root: null,\n weight: function weight(edge) {\n return 1;\n },\n directed: false,\n alpha: 0\n});\nvar elesfn$n = {\n degreeCentralityNormalized: function degreeCentralityNormalized(options) {\n options = defaults$f(options);\n var cy = this.cy();\n var nodes = this.nodes();\n var numNodes = nodes.length;\n if (!options.directed) {\n var degrees = {};\n var maxDegree = 0;\n for (var i = 0; i < numNodes; i++) {\n var node = nodes[i];\n\n // add current node to the current options object and call degreeCentrality\n options.root = node;\n var currDegree = this.degreeCentrality(options);\n if (maxDegree < currDegree.degree) {\n maxDegree = currDegree.degree;\n }\n degrees[node.id()] = currDegree.degree;\n }\n return {\n degree: function degree(node) {\n if (maxDegree === 0) {\n return 0;\n }\n if (string(node)) {\n // from is a selector string\n node = cy.filter(node);\n }\n return degrees[node.id()] / maxDegree;\n }\n };\n } else {\n var indegrees = {};\n var outdegrees = {};\n var maxIndegree = 0;\n var maxOutdegree = 0;\n for (var _i = 0; _i < numNodes; _i++) {\n var _node = nodes[_i];\n var id = _node.id();\n\n // add current node to the current options object and call degreeCentrality\n options.root = _node;\n var _currDegree = this.degreeCentrality(options);\n if (maxIndegree < _currDegree.indegree) maxIndegree = _currDegree.indegree;\n if (maxOutdegree < _currDegree.outdegree) maxOutdegree = _currDegree.outdegree;\n indegrees[id] = _currDegree.indegree;\n outdegrees[id] = _currDegree.outdegree;\n }\n return {\n indegree: function indegree(node) {\n if (maxIndegree == 0) {\n return 0;\n }\n if (string(node)) {\n // from is a selector string\n node = cy.filter(node);\n }\n return indegrees[node.id()] / maxIndegree;\n },\n outdegree: function outdegree(node) {\n if (maxOutdegree === 0) {\n return 0;\n }\n if (string(node)) {\n // from is a selector string\n node = cy.filter(node);\n }\n return outdegrees[node.id()] / maxOutdegree;\n }\n };\n }\n },\n // degreeCentralityNormalized\n\n // Implemented from the algorithm in Opsahl's paper\n // \"Node centrality in weighted networks: Generalizing degree and shortest paths\"\n // check the heading 2 \"Degree\"\n degreeCentrality: function degreeCentrality(options) {\n options = defaults$f(options);\n var cy = this.cy();\n var callingEles = this;\n var _options = options,\n root = _options.root,\n weight = _options.weight,\n directed = _options.directed,\n alpha = _options.alpha;\n root = cy.collection(root)[0];\n if (!directed) {\n var connEdges = root.connectedEdges().intersection(callingEles);\n var k = connEdges.length;\n var s = 0;\n\n // Now, sum edge weights\n for (var i = 0; i < connEdges.length; i++) {\n s += weight(connEdges[i]);\n }\n return {\n degree: Math.pow(k, 1 - alpha) * Math.pow(s, alpha)\n };\n } else {\n var edges = root.connectedEdges();\n var incoming = edges.filter(function (edge) {\n return edge.target().same(root) && callingEles.has(edge);\n });\n var outgoing = edges.filter(function (edge) {\n return edge.source().same(root) && callingEles.has(edge);\n });\n var k_in = incoming.length;\n var k_out = outgoing.length;\n var s_in = 0;\n var s_out = 0;\n\n // Now, sum incoming edge weights\n for (var _i2 = 0; _i2 < incoming.length; _i2++) {\n s_in += weight(incoming[_i2]);\n }\n\n // Now, sum outgoing edge weights\n for (var _i3 = 0; _i3 < outgoing.length; _i3++) {\n s_out += weight(outgoing[_i3]);\n }\n return {\n indegree: Math.pow(k_in, 1 - alpha) * Math.pow(s_in, alpha),\n outdegree: Math.pow(k_out, 1 - alpha) * Math.pow(s_out, alpha)\n };\n }\n } // degreeCentrality\n}; // elesfn\n\n// nice, short mathematical alias\nelesfn$n.dc = elesfn$n.degreeCentrality;\nelesfn$n.dcn = elesfn$n.degreeCentralityNormalised = elesfn$n.degreeCentralityNormalized;\n\nvar defaults$e = defaults$g({\n harmonic: true,\n weight: function weight() {\n return 1;\n },\n directed: false,\n root: null\n});\nvar elesfn$m = {\n closenessCentralityNormalized: function closenessCentralityNormalized(options) {\n var _defaults = defaults$e(options),\n harmonic = _defaults.harmonic,\n weight = _defaults.weight,\n directed = _defaults.directed;\n var cy = this.cy();\n var closenesses = {};\n var maxCloseness = 0;\n var nodes = this.nodes();\n var fw = this.floydWarshall({\n weight: weight,\n directed: directed\n });\n\n // Compute closeness for every node and find the maximum closeness\n for (var i = 0; i < nodes.length; i++) {\n var currCloseness = 0;\n var node_i = nodes[i];\n for (var j = 0; j < nodes.length; j++) {\n if (i !== j) {\n var d = fw.distance(node_i, nodes[j]);\n if (harmonic) {\n currCloseness += 1 / d;\n } else {\n currCloseness += d;\n }\n }\n }\n if (!harmonic) {\n currCloseness = 1 / currCloseness;\n }\n if (maxCloseness < currCloseness) {\n maxCloseness = currCloseness;\n }\n closenesses[node_i.id()] = currCloseness;\n }\n return {\n closeness: function closeness(node) {\n if (maxCloseness == 0) {\n return 0;\n }\n if (string(node)) {\n // from is a selector string\n node = cy.filter(node)[0].id();\n } else {\n // from is a node\n node = node.id();\n }\n return closenesses[node] / maxCloseness;\n }\n };\n },\n // Implemented from pseudocode from wikipedia\n closenessCentrality: function closenessCentrality(options) {\n var _defaults2 = defaults$e(options),\n root = _defaults2.root,\n weight = _defaults2.weight,\n directed = _defaults2.directed,\n harmonic = _defaults2.harmonic;\n root = this.filter(root)[0];\n\n // we need distance from this node to every other node\n var dijkstra = this.dijkstra({\n root: root,\n weight: weight,\n directed: directed\n });\n var totalDistance = 0;\n var nodes = this.nodes();\n for (var i = 0; i < nodes.length; i++) {\n var n = nodes[i];\n if (!n.same(root)) {\n var d = dijkstra.distanceTo(n);\n if (harmonic) {\n totalDistance += 1 / d;\n } else {\n totalDistance += d;\n }\n }\n }\n return harmonic ? totalDistance : 1 / totalDistance;\n } // closenessCentrality\n}; // elesfn\n\n// nice, short mathematical alias\nelesfn$m.cc = elesfn$m.closenessCentrality;\nelesfn$m.ccn = elesfn$m.closenessCentralityNormalised = elesfn$m.closenessCentralityNormalized;\n\nvar defaults$d = defaults$g({\n weight: null,\n directed: false\n});\nvar elesfn$l = {\n // Implemented from the algorithm in the paper \"On Variants of Shortest-Path Betweenness Centrality and their Generic Computation\" by Ulrik Brandes\n betweennessCentrality: function betweennessCentrality(options) {\n var _defaults = defaults$d(options),\n directed = _defaults.directed,\n weight = _defaults.weight;\n var weighted = weight != null;\n var cy = this.cy();\n\n // starting\n var V = this.nodes();\n var A = {};\n var _C = {};\n var max = 0;\n var C = {\n set: function set(key, val) {\n _C[key] = val;\n if (val > max) {\n max = val;\n }\n },\n get: function get(key) {\n return _C[key];\n }\n };\n\n // A contains the neighborhoods of every node\n for (var i = 0; i < V.length; i++) {\n var v = V[i];\n var vid = v.id();\n if (directed) {\n A[vid] = v.outgoers().nodes(); // get outgoers of every node\n } else {\n A[vid] = v.openNeighborhood().nodes(); // get neighbors of every node\n }\n C.set(vid, 0);\n }\n var _loop = function _loop() {\n var sid = V[s].id();\n var S = []; // stack\n var P = {};\n var g = {};\n var d = {};\n var Q = new Heap(function (a, b) {\n return d[a] - d[b];\n }); // queue\n\n // init dictionaries\n for (var _i = 0; _i < V.length; _i++) {\n var _vid = V[_i].id();\n P[_vid] = [];\n g[_vid] = 0;\n d[_vid] = Infinity;\n }\n g[sid] = 1; // sigma\n d[sid] = 0; // distance to s\n\n Q.push(sid);\n while (!Q.empty()) {\n var _v = Q.pop();\n S.push(_v);\n if (weighted) {\n for (var j = 0; j < A[_v].length; j++) {\n var w = A[_v][j];\n var vEle = cy.getElementById(_v);\n var edge = undefined;\n if (vEle.edgesTo(w).length > 0) {\n edge = vEle.edgesTo(w)[0];\n } else {\n edge = w.edgesTo(vEle)[0];\n }\n var edgeWeight = weight(edge);\n w = w.id();\n if (d[w] > d[_v] + edgeWeight) {\n d[w] = d[_v] + edgeWeight;\n if (Q.nodes.indexOf(w) < 0) {\n //if w is not in Q\n Q.push(w);\n } else {\n // update position if w is in Q\n Q.updateItem(w);\n }\n g[w] = 0;\n P[w] = [];\n }\n if (d[w] == d[_v] + edgeWeight) {\n g[w] = g[w] + g[_v];\n P[w].push(_v);\n }\n }\n } else {\n for (var _j = 0; _j < A[_v].length; _j++) {\n var _w = A[_v][_j].id();\n if (d[_w] == Infinity) {\n Q.push(_w);\n d[_w] = d[_v] + 1;\n }\n if (d[_w] == d[_v] + 1) {\n g[_w] = g[_w] + g[_v];\n P[_w].push(_v);\n }\n }\n }\n }\n var e = {};\n for (var _i2 = 0; _i2 < V.length; _i2++) {\n e[V[_i2].id()] = 0;\n }\n while (S.length > 0) {\n var _w2 = S.pop();\n for (var _j2 = 0; _j2 < P[_w2].length; _j2++) {\n var _v2 = P[_w2][_j2];\n e[_v2] = e[_v2] + g[_v2] / g[_w2] * (1 + e[_w2]);\n }\n if (_w2 != V[s].id()) {\n C.set(_w2, C.get(_w2) + e[_w2]);\n }\n }\n };\n for (var s = 0; s < V.length; s++) {\n _loop();\n }\n var ret = {\n betweenness: function betweenness(node) {\n var id = cy.collection(node).id();\n return C.get(id);\n },\n betweennessNormalized: function betweennessNormalized(node) {\n if (max == 0) {\n return 0;\n }\n var id = cy.collection(node).id();\n return C.get(id) / max;\n }\n };\n\n // alias\n ret.betweennessNormalised = ret.betweennessNormalized;\n return ret;\n } // betweennessCentrality\n}; // elesfn\n\n// nice, short mathematical alias\nelesfn$l.bc = elesfn$l.betweennessCentrality;\n\n// Implemented by Zoe Xi @zoexi for GSOC 2016\n// https://github.com/cytoscape/cytoscape.js-markov-cluster\n\n\n/* eslint-disable no-unused-vars */\nvar defaults$c = defaults$g({\n expandFactor: 2,\n // affects time of computation and cluster granularity to some extent: M * M\n inflateFactor: 2,\n // affects cluster granularity (the greater the value, the more clusters): M(i,j) / E(j)\n multFactor: 1,\n // optional self loops for each node. Use a neutral value to improve cluster computations.\n maxIterations: 20,\n // maximum number of iterations of the MCL algorithm in a single run\n attributes: [\n // attributes/features used to group nodes, ie. similarity values between nodes\n function (edge) {\n return 1;\n }]\n});\n/* eslint-enable */\n\nvar setOptions$3 = function setOptions(options) {\n return defaults$c(options);\n};\n/* eslint-enable */\n\nvar getSimilarity$1 = function getSimilarity(edge, attributes) {\n var total = 0;\n for (var i = 0; i < attributes.length; i++) {\n total += attributes[i](edge);\n }\n return total;\n};\nvar addLoops = function addLoops(M, n, val) {\n for (var i = 0; i < n; i++) {\n M[i * n + i] = val;\n }\n};\nvar normalize = function normalize(M, n) {\n var sum;\n for (var col = 0; col < n; col++) {\n sum = 0;\n for (var row = 0; row < n; row++) {\n sum += M[row * n + col];\n }\n for (var _row = 0; _row < n; _row++) {\n M[_row * n + col] = M[_row * n + col] / sum;\n }\n }\n};\n\n// TODO: blocked matrix multiplication?\nvar mmult = function mmult(A, B, n) {\n var C = new Array(n * n);\n for (var i = 0; i < n; i++) {\n for (var j = 0; j < n; j++) {\n C[i * n + j] = 0;\n }\n for (var k = 0; k < n; k++) {\n for (var _j = 0; _j < n; _j++) {\n C[i * n + _j] += A[i * n + k] * B[k * n + _j];\n }\n }\n }\n return C;\n};\nvar expand = function expand(M, n, expandFactor /** power **/) {\n var _M = M.slice(0);\n for (var p = 1; p < expandFactor; p++) {\n M = mmult(M, _M, n);\n }\n return M;\n};\nvar inflate = function inflate(M, n, inflateFactor /** r **/) {\n var _M = new Array(n * n);\n\n // M(i,j) ^ inflatePower\n for (var i = 0; i < n * n; i++) {\n _M[i] = Math.pow(M[i], inflateFactor);\n }\n normalize(_M, n);\n return _M;\n};\nvar hasConverged = function hasConverged(M, _M, n2, roundFactor) {\n // Check that both matrices have the same elements (i,j)\n for (var i = 0; i < n2; i++) {\n var v1 = Math.round(M[i] * Math.pow(10, roundFactor)) / Math.pow(10, roundFactor); // truncate to 'roundFactor' decimal places\n var v2 = Math.round(_M[i] * Math.pow(10, roundFactor)) / Math.pow(10, roundFactor);\n if (v1 !== v2) {\n return false;\n }\n }\n return true;\n};\nvar assign$2 = function assign(M, n, nodes, cy) {\n var clusters = [];\n for (var i = 0; i < n; i++) {\n var cluster = [];\n for (var j = 0; j < n; j++) {\n // Row-wise attractors and elements that they attract belong in same cluster\n if (Math.round(M[i * n + j] * 1000) / 1000 > 0) {\n cluster.push(nodes[j]);\n }\n }\n if (cluster.length !== 0) {\n clusters.push(cy.collection(cluster));\n }\n }\n return clusters;\n};\nvar isDuplicate = function isDuplicate(c1, c2) {\n for (var i = 0; i < c1.length; i++) {\n if (!c2[i] || c1[i].id() !== c2[i].id()) {\n return false;\n }\n }\n return true;\n};\nvar removeDuplicates = function removeDuplicates(clusters) {\n for (var i = 0; i < clusters.length; i++) {\n for (var j = 0; j < clusters.length; j++) {\n if (i != j && isDuplicate(clusters[i], clusters[j])) {\n clusters.splice(j, 1);\n }\n }\n }\n return clusters;\n};\nvar markovClustering = function markovClustering(options) {\n var nodes = this.nodes();\n var edges = this.edges();\n var cy = this.cy();\n\n // Set parameters of algorithm:\n var opts = setOptions$3(options);\n\n // Map each node to its position in node array\n var id2position = {};\n for (var i = 0; i < nodes.length; i++) {\n id2position[nodes[i].id()] = i;\n }\n\n // Generate stochastic matrix M from input graph G (should be symmetric/undirected)\n var n = nodes.length,\n n2 = n * n;\n var M = new Array(n2),\n _M;\n for (var _i = 0; _i < n2; _i++) {\n M[_i] = 0;\n }\n for (var e = 0; e < edges.length; e++) {\n var edge = edges[e];\n var _i2 = id2position[edge.source().id()];\n var j = id2position[edge.target().id()];\n var sim = getSimilarity$1(edge, opts.attributes);\n M[_i2 * n + j] += sim; // G should be symmetric and undirected\n M[j * n + _i2] += sim;\n }\n\n // Begin Markov cluster algorithm\n\n // Step 1: Add self loops to each node, ie. add multFactor to matrix diagonal\n addLoops(M, n, opts.multFactor);\n\n // Step 2: M = normalize( M );\n normalize(M, n);\n var isStillMoving = true;\n var iterations = 0;\n while (isStillMoving && iterations < opts.maxIterations) {\n isStillMoving = false;\n\n // Step 3:\n _M = expand(M, n, opts.expandFactor);\n\n // Step 4:\n M = inflate(_M, n, opts.inflateFactor);\n\n // Step 5: check to see if ~steady state has been reached\n if (!hasConverged(M, _M, n2, 4)) {\n isStillMoving = true;\n }\n iterations++;\n }\n\n // Build clusters from matrix\n var clusters = assign$2(M, n, nodes, cy);\n\n // Remove duplicate clusters due to symmetry of graph and M matrix\n clusters = removeDuplicates(clusters);\n return clusters;\n};\nvar markovClustering$1 = {\n markovClustering: markovClustering,\n mcl: markovClustering\n};\n\n// Common distance metrics for clustering algorithms\n// https://en.wikipedia.org/wiki/Hierarchical_clustering#Metric\n\nvar identity$1 = function identity(x) {\n return x;\n};\nvar absDiff = function absDiff(p, q) {\n return Math.abs(q - p);\n};\nvar addAbsDiff = function addAbsDiff(total, p, q) {\n return total + absDiff(p, q);\n};\nvar addSquaredDiff = function addSquaredDiff(total, p, q) {\n return total + Math.pow(q - p, 2);\n};\nvar sqrt = function sqrt(x) {\n return Math.sqrt(x);\n};\nvar maxAbsDiff = function maxAbsDiff(currentMax, p, q) {\n return Math.max(currentMax, absDiff(p, q));\n};\nvar getDistance = function getDistance(length, getP, getQ, init, visit) {\n var post = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : identity$1;\n var ret = init;\n var p, q;\n for (var dim = 0; dim < length; dim++) {\n p = getP(dim);\n q = getQ(dim);\n ret = visit(ret, p, q);\n }\n return post(ret);\n};\nvar distances = {\n euclidean: function euclidean(length, getP, getQ) {\n if (length >= 2) {\n return getDistance(length, getP, getQ, 0, addSquaredDiff, sqrt);\n } else {\n // for single attr case, more efficient to avoid sqrt\n return getDistance(length, getP, getQ, 0, addAbsDiff);\n }\n },\n squaredEuclidean: function squaredEuclidean(length, getP, getQ) {\n return getDistance(length, getP, getQ, 0, addSquaredDiff);\n },\n manhattan: function manhattan(length, getP, getQ) {\n return getDistance(length, getP, getQ, 0, addAbsDiff);\n },\n max: function max(length, getP, getQ) {\n return getDistance(length, getP, getQ, -Infinity, maxAbsDiff);\n }\n};\n\n// in case the user accidentally doesn't use camel case\ndistances['squared-euclidean'] = distances['squaredEuclidean'];\ndistances['squaredeuclidean'] = distances['squaredEuclidean'];\nfunction clusteringDistance (method, length, getP, getQ, nodeP, nodeQ) {\n var impl;\n if (fn$6(method)) {\n impl = method;\n } else {\n impl = distances[method] || distances.euclidean;\n }\n if (length === 0 && fn$6(method)) {\n return impl(nodeP, nodeQ);\n } else {\n return impl(length, getP, getQ, nodeP, nodeQ);\n }\n}\n\nvar defaults$b = defaults$g({\n k: 2,\n m: 2,\n sensitivityThreshold: 0.0001,\n distance: 'euclidean',\n maxIterations: 10,\n attributes: [],\n testMode: false,\n testCentroids: null\n});\nvar setOptions$2 = function setOptions(options) {\n return defaults$b(options);\n};\n\nvar getDist = function getDist(type, node, centroid, attributes, mode) {\n var noNodeP = mode !== 'kMedoids';\n var getP = noNodeP ? function (i) {\n return centroid[i];\n } : function (i) {\n return attributes[i](centroid);\n };\n var getQ = function getQ(i) {\n return attributes[i](node);\n };\n var nodeP = centroid;\n var nodeQ = node;\n return clusteringDistance(type, attributes.length, getP, getQ, nodeP, nodeQ);\n};\nvar randomCentroids = function randomCentroids(nodes, k, attributes) {\n var ndim = attributes.length;\n var min = new Array(ndim);\n var max = new Array(ndim);\n var centroids = new Array(k);\n var centroid = null;\n\n // Find min, max values for each attribute dimension\n for (var i = 0; i < ndim; i++) {\n min[i] = nodes.min(attributes[i]).value;\n max[i] = nodes.max(attributes[i]).value;\n }\n\n // Build k centroids, each represented as an n-dim feature vector\n for (var c = 0; c < k; c++) {\n centroid = [];\n for (var _i = 0; _i < ndim; _i++) {\n centroid[_i] = Math.random() * (max[_i] - min[_i]) + min[_i]; // random initial value\n }\n centroids[c] = centroid;\n }\n return centroids;\n};\nvar classify = function classify(node, centroids, distance, attributes, type) {\n var min = Infinity;\n var index = 0;\n for (var i = 0; i < centroids.length; i++) {\n var dist = getDist(distance, node, centroids[i], attributes, type);\n if (dist < min) {\n min = dist;\n index = i;\n }\n }\n return index;\n};\nvar buildCluster = function buildCluster(centroid, nodes, assignment) {\n var cluster = [];\n var node = null;\n for (var n = 0; n < nodes.length; n++) {\n node = nodes[n];\n if (assignment[node.id()] === centroid) {\n //console.log(\"Node \" + node.id() + \" is associated with medoid #: \" + m);\n cluster.push(node);\n }\n }\n return cluster;\n};\nvar haveValuesConverged = function haveValuesConverged(v1, v2, sensitivityThreshold) {\n return Math.abs(v2 - v1) <= sensitivityThreshold;\n};\nvar haveMatricesConverged = function haveMatricesConverged(v1, v2, sensitivityThreshold) {\n for (var i = 0; i < v1.length; i++) {\n for (var j = 0; j < v1[i].length; j++) {\n var diff = Math.abs(v1[i][j] - v2[i][j]);\n if (diff > sensitivityThreshold) {\n return false;\n }\n }\n }\n return true;\n};\nvar seenBefore = function seenBefore(node, medoids, n) {\n for (var i = 0; i < n; i++) {\n if (node === medoids[i]) return true;\n }\n return false;\n};\nvar randomMedoids = function randomMedoids(nodes, k) {\n var medoids = new Array(k);\n\n // For small data sets, the probability of medoid conflict is greater,\n // so we need to check to see if we've already seen or chose this node before.\n if (nodes.length < 50) {\n // Randomly select k medoids from the n nodes\n for (var i = 0; i < k; i++) {\n var node = nodes[Math.floor(Math.random() * nodes.length)];\n\n // If we've already chosen this node to be a medoid, don't choose it again (for small data sets).\n // Instead choose a different random node.\n while (seenBefore(node, medoids, i)) {\n node = nodes[Math.floor(Math.random() * nodes.length)];\n }\n medoids[i] = node;\n }\n } else {\n // Relatively large data set, so pretty safe to not check and just select random nodes\n for (var _i2 = 0; _i2 < k; _i2++) {\n medoids[_i2] = nodes[Math.floor(Math.random() * nodes.length)];\n }\n }\n return medoids;\n};\nvar findCost = function findCost(potentialNewMedoid, cluster, attributes) {\n var cost = 0;\n for (var n = 0; n < cluster.length; n++) {\n cost += getDist('manhattan', cluster[n], potentialNewMedoid, attributes, 'kMedoids');\n }\n return cost;\n};\nvar kMeans = function kMeans(options) {\n var cy = this.cy();\n var nodes = this.nodes();\n var node = null;\n\n // Set parameters of algorithm: # of clusters, distance metric, etc.\n var opts = setOptions$2(options);\n\n // Begin k-means algorithm\n var clusters = new Array(opts.k);\n var assignment = {};\n var centroids;\n\n // Step 1: Initialize centroid positions\n if (opts.testMode) {\n if (typeof opts.testCentroids === 'number') {\n // TODO: implement a seeded random number generator.\n opts.testCentroids;\n centroids = randomCentroids(nodes, opts.k, opts.attributes);\n } else if (_typeof(opts.testCentroids) === 'object') {\n centroids = opts.testCentroids;\n } else {\n centroids = randomCentroids(nodes, opts.k, opts.attributes);\n }\n } else {\n centroids = randomCentroids(nodes, opts.k, opts.attributes);\n }\n var isStillMoving = true;\n var iterations = 0;\n while (isStillMoving && iterations < opts.maxIterations) {\n // Step 2: Assign nodes to the nearest centroid\n for (var n = 0; n < nodes.length; n++) {\n node = nodes[n];\n // Determine which cluster this node belongs to: node id => cluster #\n assignment[node.id()] = classify(node, centroids, opts.distance, opts.attributes, 'kMeans');\n }\n\n // Step 3: For each of the k clusters, update its centroid\n isStillMoving = false;\n for (var c = 0; c < opts.k; c++) {\n // Get all nodes that belong to this cluster\n var cluster = buildCluster(c, nodes, assignment);\n if (cluster.length === 0) {\n // If cluster is empty, break out early & move to next cluster\n continue;\n }\n\n // Update centroids by calculating avg of all nodes within the cluster.\n var ndim = opts.attributes.length;\n var centroid = centroids[c]; // [ dim_1, dim_2, dim_3, ... , dim_n ]\n var newCentroid = new Array(ndim);\n var sum = new Array(ndim);\n for (var d = 0; d < ndim; d++) {\n sum[d] = 0.0;\n for (var i = 0; i < cluster.length; i++) {\n node = cluster[i];\n sum[d] += opts.attributes[d](node);\n }\n newCentroid[d] = sum[d] / cluster.length;\n\n // Check to see if algorithm has converged, i.e. when centroids no longer change\n if (!haveValuesConverged(newCentroid[d], centroid[d], opts.sensitivityThreshold)) {\n isStillMoving = true;\n }\n }\n centroids[c] = newCentroid;\n clusters[c] = cy.collection(cluster);\n }\n iterations++;\n }\n return clusters;\n};\nvar kMedoids = function kMedoids(options) {\n var cy = this.cy();\n var nodes = this.nodes();\n var node = null;\n var opts = setOptions$2(options);\n\n // Begin k-medoids algorithm\n var clusters = new Array(opts.k);\n var medoids;\n var assignment = {};\n var curCost;\n var minCosts = new Array(opts.k); // minimum cost configuration for each cluster\n\n // Step 1: Initialize k medoids\n if (opts.testMode) {\n if (typeof opts.testCentroids === 'number') ; else if (_typeof(opts.testCentroids) === 'object') {\n medoids = opts.testCentroids;\n } else {\n medoids = randomMedoids(nodes, opts.k);\n }\n } else {\n medoids = randomMedoids(nodes, opts.k);\n }\n var isStillMoving = true;\n var iterations = 0;\n while (isStillMoving && iterations < opts.maxIterations) {\n // Step 2: Assign nodes to the nearest medoid\n for (var n = 0; n < nodes.length; n++) {\n node = nodes[n];\n // Determine which cluster this node belongs to: node id => cluster #\n assignment[node.id()] = classify(node, medoids, opts.distance, opts.attributes, 'kMedoids');\n }\n isStillMoving = false;\n // Step 3: For each medoid m, and for each node associated with mediod m,\n // select the node with the lowest configuration cost as new medoid.\n for (var m = 0; m < medoids.length; m++) {\n // Get all nodes that belong to this medoid\n var cluster = buildCluster(m, nodes, assignment);\n if (cluster.length === 0) {\n // If cluster is empty, break out early & move to next cluster\n continue;\n }\n minCosts[m] = findCost(medoids[m], cluster, opts.attributes); // original cost\n\n // Select different medoid if its configuration has the lowest cost\n for (var _n = 0; _n < cluster.length; _n++) {\n curCost = findCost(cluster[_n], cluster, opts.attributes);\n if (curCost < minCosts[m]) {\n minCosts[m] = curCost;\n medoids[m] = cluster[_n];\n isStillMoving = true;\n }\n }\n clusters[m] = cy.collection(cluster);\n }\n iterations++;\n }\n return clusters;\n};\nvar updateCentroids = function updateCentroids(centroids, nodes, U, weight, opts) {\n var numerator, denominator;\n for (var n = 0; n < nodes.length; n++) {\n for (var c = 0; c < centroids.length; c++) {\n weight[n][c] = Math.pow(U[n][c], opts.m);\n }\n }\n for (var _c = 0; _c < centroids.length; _c++) {\n for (var dim = 0; dim < opts.attributes.length; dim++) {\n numerator = 0;\n denominator = 0;\n for (var _n2 = 0; _n2 < nodes.length; _n2++) {\n numerator += weight[_n2][_c] * opts.attributes[dim](nodes[_n2]);\n denominator += weight[_n2][_c];\n }\n centroids[_c][dim] = numerator / denominator;\n }\n }\n};\nvar updateMembership = function updateMembership(U, _U, centroids, nodes, opts) {\n // Save previous step\n for (var i = 0; i < U.length; i++) {\n _U[i] = U[i].slice();\n }\n var sum, numerator, denominator;\n var pow = 2 / (opts.m - 1);\n for (var c = 0; c < centroids.length; c++) {\n for (var n = 0; n < nodes.length; n++) {\n sum = 0;\n for (var k = 0; k < centroids.length; k++) {\n // against all other centroids\n numerator = getDist(opts.distance, nodes[n], centroids[c], opts.attributes, 'cmeans');\n denominator = getDist(opts.distance, nodes[n], centroids[k], opts.attributes, 'cmeans');\n sum += Math.pow(numerator / denominator, pow);\n }\n U[n][c] = 1 / sum;\n }\n }\n};\nvar assign$1 = function assign(nodes, U, opts, cy) {\n var clusters = new Array(opts.k);\n for (var c = 0; c < clusters.length; c++) {\n clusters[c] = [];\n }\n var max;\n var index;\n for (var n = 0; n < U.length; n++) {\n // for each node (U is N x C matrix)\n max = -Infinity;\n index = -1;\n // Determine which cluster the node is most likely to belong in\n for (var _c2 = 0; _c2 < U[0].length; _c2++) {\n if (U[n][_c2] > max) {\n max = U[n][_c2];\n index = _c2;\n }\n }\n clusters[index].push(nodes[n]);\n }\n\n // Turn every array into a collection of nodes\n for (var _c3 = 0; _c3 < clusters.length; _c3++) {\n clusters[_c3] = cy.collection(clusters[_c3]);\n }\n return clusters;\n};\nvar fuzzyCMeans = function fuzzyCMeans(options) {\n var cy = this.cy();\n var nodes = this.nodes();\n var opts = setOptions$2(options);\n\n // Begin fuzzy c-means algorithm\n var clusters;\n var centroids;\n var U;\n var _U;\n var weight;\n\n // Step 1: Initialize letiables.\n _U = new Array(nodes.length);\n for (var i = 0; i < nodes.length; i++) {\n // N x C matrix\n _U[i] = new Array(opts.k);\n }\n U = new Array(nodes.length);\n for (var _i3 = 0; _i3 < nodes.length; _i3++) {\n // N x C matrix\n U[_i3] = new Array(opts.k);\n }\n for (var _i4 = 0; _i4 < nodes.length; _i4++) {\n var total = 0;\n for (var j = 0; j < opts.k; j++) {\n U[_i4][j] = Math.random();\n total += U[_i4][j];\n }\n for (var _j = 0; _j < opts.k; _j++) {\n U[_i4][_j] = U[_i4][_j] / total;\n }\n }\n centroids = new Array(opts.k);\n for (var _i5 = 0; _i5 < opts.k; _i5++) {\n centroids[_i5] = new Array(opts.attributes.length);\n }\n weight = new Array(nodes.length);\n for (var _i6 = 0; _i6 < nodes.length; _i6++) {\n // N x C matrix\n weight[_i6] = new Array(opts.k);\n }\n // end init FCM\n\n var isStillMoving = true;\n var iterations = 0;\n while (isStillMoving && iterations < opts.maxIterations) {\n isStillMoving = false;\n\n // Step 2: Calculate the centroids for each step.\n updateCentroids(centroids, nodes, U, weight, opts);\n\n // Step 3: Update the partition matrix U.\n updateMembership(U, _U, centroids, nodes, opts);\n\n // Step 4: Check for convergence.\n if (!haveMatricesConverged(U, _U, opts.sensitivityThreshold)) {\n isStillMoving = true;\n }\n iterations++;\n }\n\n // Assign nodes to clusters with highest probability.\n clusters = assign$1(nodes, U, opts, cy);\n return {\n clusters: clusters,\n degreeOfMembership: U\n };\n};\nvar kClustering = {\n kMeans: kMeans,\n kMedoids: kMedoids,\n fuzzyCMeans: fuzzyCMeans,\n fcm: fuzzyCMeans\n};\n\n// Implemented by Zoe Xi @zoexi for GSOC 2016\n// https://github.com/cytoscape/cytoscape.js-hierarchical\n\nvar defaults$a = defaults$g({\n distance: 'euclidean',\n // distance metric to compare nodes\n linkage: 'min',\n // linkage criterion : how to determine the distance between clusters of nodes\n mode: 'threshold',\n // mode:'threshold' => clusters must be threshold distance apart\n threshold: Infinity,\n // the distance threshold\n // mode:'dendrogram' => the nodes are organised as leaves in a tree (siblings are close), merging makes clusters\n addDendrogram: false,\n // whether to add the dendrogram to the graph for viz\n dendrogramDepth: 0,\n // depth at which dendrogram branches are merged into the returned clusters\n attributes: [] // array of attr functions\n});\nvar linkageAliases = {\n 'single': 'min',\n 'complete': 'max'\n};\nvar setOptions$1 = function setOptions(options) {\n var opts = defaults$a(options);\n var preferredAlias = linkageAliases[opts.linkage];\n if (preferredAlias != null) {\n opts.linkage = preferredAlias;\n }\n return opts;\n};\nvar mergeClosest = function mergeClosest(clusters, index, dists, mins, opts) {\n // Find two closest clusters from cached mins\n var minKey = 0;\n var min = Infinity;\n var dist;\n var attrs = opts.attributes;\n var getDist = function getDist(n1, n2) {\n return clusteringDistance(opts.distance, attrs.length, function (i) {\n return attrs[i](n1);\n }, function (i) {\n return attrs[i](n2);\n }, n1, n2);\n };\n for (var i = 0; i < clusters.length; i++) {\n var key = clusters[i].key;\n var _dist = dists[key][mins[key]];\n if (_dist < min) {\n minKey = key;\n min = _dist;\n }\n }\n if (opts.mode === 'threshold' && min >= opts.threshold || opts.mode === 'dendrogram' && clusters.length === 1) {\n return false;\n }\n var c1 = index[minKey];\n var c2 = index[mins[minKey]];\n var merged;\n\n // Merge two closest clusters\n if (opts.mode === 'dendrogram') {\n merged = {\n left: c1,\n right: c2,\n key: c1.key\n };\n } else {\n merged = {\n value: c1.value.concat(c2.value),\n key: c1.key\n };\n }\n clusters[c1.index] = merged;\n clusters.splice(c2.index, 1);\n index[c1.key] = merged;\n\n // Update distances with new merged cluster\n for (var _i = 0; _i < clusters.length; _i++) {\n var cur = clusters[_i];\n if (c1.key === cur.key) {\n dist = Infinity;\n } else if (opts.linkage === 'min') {\n dist = dists[c1.key][cur.key];\n if (dists[c1.key][cur.key] > dists[c2.key][cur.key]) {\n dist = dists[c2.key][cur.key];\n }\n } else if (opts.linkage === 'max') {\n dist = dists[c1.key][cur.key];\n if (dists[c1.key][cur.key] < dists[c2.key][cur.key]) {\n dist = dists[c2.key][cur.key];\n }\n } else if (opts.linkage === 'mean') {\n dist = (dists[c1.key][cur.key] * c1.size + dists[c2.key][cur.key] * c2.size) / (c1.size + c2.size);\n } else {\n if (opts.mode === 'dendrogram') dist = getDist(cur.value, c1.value);else dist = getDist(cur.value[0], c1.value[0]);\n }\n dists[c1.key][cur.key] = dists[cur.key][c1.key] = dist; // distance matrix is symmetric\n }\n\n // Update cached mins\n for (var _i2 = 0; _i2 < clusters.length; _i2++) {\n var key1 = clusters[_i2].key;\n if (mins[key1] === c1.key || mins[key1] === c2.key) {\n var _min = key1;\n for (var j = 0; j < clusters.length; j++) {\n var key2 = clusters[j].key;\n if (dists[key1][key2] < dists[key1][_min]) {\n _min = key2;\n }\n }\n mins[key1] = _min;\n }\n clusters[_i2].index = _i2;\n }\n\n // Clean up meta data used for clustering\n c1.key = c2.key = c1.index = c2.index = null;\n return true;\n};\nvar _getAllChildren = function getAllChildren(root, arr, cy) {\n if (!root) return;\n if (root.value) {\n arr.push(root.value);\n } else {\n if (root.left) _getAllChildren(root.left, arr);\n if (root.right) _getAllChildren(root.right, arr);\n }\n};\nvar _buildDendrogram = function buildDendrogram(root, cy) {\n if (!root) return '';\n if (root.left && root.right) {\n var leftStr = _buildDendrogram(root.left, cy);\n var rightStr = _buildDendrogram(root.right, cy);\n var node = cy.add({\n group: 'nodes',\n data: {\n id: leftStr + ',' + rightStr\n }\n });\n cy.add({\n group: 'edges',\n data: {\n source: leftStr,\n target: node.id()\n }\n });\n cy.add({\n group: 'edges',\n data: {\n source: rightStr,\n target: node.id()\n }\n });\n return node.id();\n } else if (root.value) {\n return root.value.id();\n }\n};\nvar _buildClustersFromTree = function buildClustersFromTree(root, k, cy) {\n if (!root) return [];\n var left = [],\n right = [],\n leaves = [];\n if (k === 0) {\n // don't cut tree, simply return all nodes as 1 single cluster\n if (root.left) _getAllChildren(root.left, left);\n if (root.right) _getAllChildren(root.right, right);\n leaves = left.concat(right);\n return [cy.collection(leaves)];\n } else if (k === 1) {\n // cut at root\n\n if (root.value) {\n // leaf node\n return [cy.collection(root.value)];\n } else {\n if (root.left) _getAllChildren(root.left, left);\n if (root.right) _getAllChildren(root.right, right);\n return [cy.collection(left), cy.collection(right)];\n }\n } else {\n if (root.value) {\n return [cy.collection(root.value)];\n } else {\n if (root.left) left = _buildClustersFromTree(root.left, k - 1, cy);\n if (root.right) right = _buildClustersFromTree(root.right, k - 1, cy);\n return left.concat(right);\n }\n }\n};\n\nvar hierarchicalClustering = function hierarchicalClustering(options) {\n var cy = this.cy();\n var nodes = this.nodes();\n\n // Set parameters of algorithm: linkage type, distance metric, etc.\n var opts = setOptions$1(options);\n var attrs = opts.attributes;\n var getDist = function getDist(n1, n2) {\n return clusteringDistance(opts.distance, attrs.length, function (i) {\n return attrs[i](n1);\n }, function (i) {\n return attrs[i](n2);\n }, n1, n2);\n };\n\n // Begin hierarchical algorithm\n var clusters = [];\n var dists = []; // distances between each pair of clusters\n var mins = []; // closest cluster for each cluster\n var index = []; // hash of all clusters by key\n\n // In agglomerative (bottom-up) clustering, each node starts as its own cluster\n for (var n = 0; n < nodes.length; n++) {\n var cluster = {\n value: opts.mode === 'dendrogram' ? nodes[n] : [nodes[n]],\n key: n,\n index: n\n };\n clusters[n] = cluster;\n index[n] = cluster;\n dists[n] = [];\n mins[n] = 0;\n }\n\n // Calculate the distance between each pair of clusters\n for (var i = 0; i < clusters.length; i++) {\n for (var j = 0; j <= i; j++) {\n var dist = undefined;\n if (opts.mode === 'dendrogram') {\n // modes store cluster values differently\n dist = i === j ? Infinity : getDist(clusters[i].value, clusters[j].value);\n } else {\n dist = i === j ? Infinity : getDist(clusters[i].value[0], clusters[j].value[0]);\n }\n dists[i][j] = dist;\n dists[j][i] = dist;\n if (dist < dists[i][mins[i]]) {\n mins[i] = j; // Cache mins: closest cluster to cluster i is cluster j\n }\n }\n }\n\n // Find the closest pair of clusters and merge them into a single cluster.\n // Update distances between new cluster and each of the old clusters, and loop until threshold reached.\n var merged = mergeClosest(clusters, index, dists, mins, opts);\n while (merged) {\n merged = mergeClosest(clusters, index, dists, mins, opts);\n }\n var retClusters;\n\n // Dendrogram mode builds the hierarchy and adds intermediary nodes + edges\n // in addition to returning the clusters.\n if (opts.mode === 'dendrogram') {\n retClusters = _buildClustersFromTree(clusters[0], opts.dendrogramDepth, cy);\n if (opts.addDendrogram) _buildDendrogram(clusters[0], cy);\n } else {\n // Regular mode simply returns the clusters\n\n retClusters = new Array(clusters.length);\n clusters.forEach(function (cluster, i) {\n // Clean up meta data used for clustering\n cluster.key = cluster.index = null;\n retClusters[i] = cy.collection(cluster.value);\n });\n }\n return retClusters;\n};\nvar hierarchicalClustering$1 = {\n hierarchicalClustering: hierarchicalClustering,\n hca: hierarchicalClustering\n};\n\n// Implemented by Zoe Xi @zoexi for GSOC 2016\n// https://github.com/cytoscape/cytoscape.js-affinity-propagation\n\nvar defaults$9 = defaults$g({\n distance: 'euclidean',\n // distance metric to compare attributes between two nodes\n preference: 'median',\n // suitability of a data point to serve as an exemplar\n damping: 0.8,\n // damping factor between [0.5, 1)\n maxIterations: 1000,\n // max number of iterations to run\n minIterations: 100,\n // min number of iterations to run in order for clustering to stop\n attributes: [// functions to quantify the similarity between any two points\n // e.g. node => node.data('weight')\n ]\n});\nvar setOptions = function setOptions(options) {\n var dmp = options.damping;\n var pref = options.preference;\n if (!(0.5 <= dmp && dmp < 1)) {\n error(\"Damping must range on [0.5, 1). Got: \".concat(dmp));\n }\n var validPrefs = ['median', 'mean', 'min', 'max'];\n if (!(validPrefs.some(function (v) {\n return v === pref;\n }) || number$1(pref))) {\n error(\"Preference must be one of [\".concat(validPrefs.map(function (p) {\n return \"'\".concat(p, \"'\");\n }).join(', '), \"] or a number. Got: \").concat(pref));\n }\n return defaults$9(options);\n};\n\nvar getSimilarity = function getSimilarity(type, n1, n2, attributes) {\n var attr = function attr(n, i) {\n return attributes[i](n);\n };\n\n // nb negative because similarity should have an inverse relationship to distance\n return -clusteringDistance(type, attributes.length, function (i) {\n return attr(n1, i);\n }, function (i) {\n return attr(n2, i);\n }, n1, n2);\n};\nvar getPreference = function getPreference(S, preference) {\n // larger preference = greater # of clusters\n var p = null;\n if (preference === 'median') {\n p = median(S);\n } else if (preference === 'mean') {\n p = mean(S);\n } else if (preference === 'min') {\n p = min(S);\n } else if (preference === 'max') {\n p = max(S);\n } else {\n // Custom preference number, as set by user\n p = preference;\n }\n return p;\n};\nvar findExemplars = function findExemplars(n, R, A) {\n var indices = [];\n for (var i = 0; i < n; i++) {\n if (R[i * n + i] + A[i * n + i] > 0) {\n indices.push(i);\n }\n }\n return indices;\n};\nvar assignClusters = function assignClusters(n, S, exemplars) {\n var clusters = [];\n for (var i = 0; i < n; i++) {\n var index = -1;\n var max = -Infinity;\n for (var ei = 0; ei < exemplars.length; ei++) {\n var e = exemplars[ei];\n if (S[i * n + e] > max) {\n index = e;\n max = S[i * n + e];\n }\n }\n if (index > 0) {\n clusters.push(index);\n }\n }\n for (var _ei = 0; _ei < exemplars.length; _ei++) {\n clusters[exemplars[_ei]] = exemplars[_ei];\n }\n return clusters;\n};\nvar assign = function assign(n, S, exemplars) {\n var clusters = assignClusters(n, S, exemplars);\n for (var ei = 0; ei < exemplars.length; ei++) {\n var ii = [];\n for (var c = 0; c < clusters.length; c++) {\n if (clusters[c] === exemplars[ei]) {\n ii.push(c);\n }\n }\n var maxI = -1;\n var maxSum = -Infinity;\n for (var i = 0; i < ii.length; i++) {\n var sum = 0;\n for (var j = 0; j < ii.length; j++) {\n sum += S[ii[j] * n + ii[i]];\n }\n if (sum > maxSum) {\n maxI = i;\n maxSum = sum;\n }\n }\n exemplars[ei] = ii[maxI];\n }\n clusters = assignClusters(n, S, exemplars);\n return clusters;\n};\nvar affinityPropagation = function affinityPropagation(options) {\n var cy = this.cy();\n var nodes = this.nodes();\n var opts = setOptions(options);\n\n // Map each node to its position in node array\n var id2position = {};\n for (var i = 0; i < nodes.length; i++) {\n id2position[nodes[i].id()] = i;\n }\n\n // Begin affinity propagation algorithm\n\n var n; // number of data points\n var n2; // size of matrices\n var S; // similarity matrix (1D array)\n var p; // preference/suitability of a data point to serve as an exemplar\n var R; // responsibility matrix (1D array)\n var A; // availability matrix (1D array)\n\n n = nodes.length;\n n2 = n * n;\n\n // Initialize and build S similarity matrix\n S = new Array(n2);\n for (var _i = 0; _i < n2; _i++) {\n S[_i] = -Infinity; // for cases where two data points shouldn't be linked together\n }\n for (var _i2 = 0; _i2 < n; _i2++) {\n for (var j = 0; j < n; j++) {\n if (_i2 !== j) {\n S[_i2 * n + j] = getSimilarity(opts.distance, nodes[_i2], nodes[j], opts.attributes);\n }\n }\n }\n\n // Place preferences on the diagonal of S\n p = getPreference(S, opts.preference);\n for (var _i3 = 0; _i3 < n; _i3++) {\n S[_i3 * n + _i3] = p;\n }\n\n // Initialize R responsibility matrix\n R = new Array(n2);\n for (var _i4 = 0; _i4 < n2; _i4++) {\n R[_i4] = 0.0;\n }\n\n // Initialize A availability matrix\n A = new Array(n2);\n for (var _i5 = 0; _i5 < n2; _i5++) {\n A[_i5] = 0.0;\n }\n var old = new Array(n);\n var Rp = new Array(n);\n var se = new Array(n);\n for (var _i6 = 0; _i6 < n; _i6++) {\n old[_i6] = 0.0;\n Rp[_i6] = 0.0;\n se[_i6] = 0;\n }\n var e = new Array(n * opts.minIterations);\n for (var _i7 = 0; _i7 < e.length; _i7++) {\n e[_i7] = 0;\n }\n var iter;\n for (iter = 0; iter < opts.maxIterations; iter++) {\n // main algorithmic loop\n\n // Update R responsibility matrix\n for (var _i8 = 0; _i8 < n; _i8++) {\n var max = -Infinity,\n max2 = -Infinity,\n maxI = -1,\n AS = 0.0;\n for (var _j = 0; _j < n; _j++) {\n old[_j] = R[_i8 * n + _j];\n AS = A[_i8 * n + _j] + S[_i8 * n + _j];\n if (AS >= max) {\n max2 = max;\n max = AS;\n maxI = _j;\n } else if (AS > max2) {\n max2 = AS;\n }\n }\n for (var _j2 = 0; _j2 < n; _j2++) {\n R[_i8 * n + _j2] = (1 - opts.damping) * (S[_i8 * n + _j2] - max) + opts.damping * old[_j2];\n }\n R[_i8 * n + maxI] = (1 - opts.damping) * (S[_i8 * n + maxI] - max2) + opts.damping * old[maxI];\n }\n\n // Update A availability matrix\n for (var _i9 = 0; _i9 < n; _i9++) {\n var sum = 0;\n for (var _j3 = 0; _j3 < n; _j3++) {\n old[_j3] = A[_j3 * n + _i9];\n Rp[_j3] = Math.max(0, R[_j3 * n + _i9]);\n sum += Rp[_j3];\n }\n sum -= Rp[_i9];\n Rp[_i9] = R[_i9 * n + _i9];\n sum += Rp[_i9];\n for (var _j4 = 0; _j4 < n; _j4++) {\n A[_j4 * n + _i9] = (1 - opts.damping) * Math.min(0, sum - Rp[_j4]) + opts.damping * old[_j4];\n }\n A[_i9 * n + _i9] = (1 - opts.damping) * (sum - Rp[_i9]) + opts.damping * old[_i9];\n }\n\n // Check for convergence\n var K = 0;\n for (var _i10 = 0; _i10 < n; _i10++) {\n var E = A[_i10 * n + _i10] + R[_i10 * n + _i10] > 0 ? 1 : 0;\n e[iter % opts.minIterations * n + _i10] = E;\n K += E;\n }\n if (K > 0 && (iter >= opts.minIterations - 1 || iter == opts.maxIterations - 1)) {\n var _sum = 0;\n for (var _i11 = 0; _i11 < n; _i11++) {\n se[_i11] = 0;\n for (var _j5 = 0; _j5 < opts.minIterations; _j5++) {\n se[_i11] += e[_j5 * n + _i11];\n }\n if (se[_i11] === 0 || se[_i11] === opts.minIterations) {\n _sum++;\n }\n }\n if (_sum === n) {\n // then we have convergence\n break;\n }\n }\n }\n\n // Identify exemplars (cluster centers)\n var exemplarsIndices = findExemplars(n, R, A);\n\n // Assign nodes to clusters\n var clusterIndices = assign(n, S, exemplarsIndices);\n var clusters = {};\n for (var c = 0; c < exemplarsIndices.length; c++) {\n clusters[exemplarsIndices[c]] = [];\n }\n for (var _i12 = 0; _i12 < nodes.length; _i12++) {\n var pos = id2position[nodes[_i12].id()];\n var clusterIndex = clusterIndices[pos];\n if (clusterIndex != null) {\n // the node may have not been assigned a cluster if no valid attributes were specified\n clusters[clusterIndex].push(nodes[_i12]);\n }\n }\n var retClusters = new Array(exemplarsIndices.length);\n for (var _c = 0; _c < exemplarsIndices.length; _c++) {\n retClusters[_c] = cy.collection(clusters[exemplarsIndices[_c]]);\n }\n return retClusters;\n};\nvar affinityPropagation$1 = {\n affinityPropagation: affinityPropagation,\n ap: affinityPropagation\n};\n\nvar hierholzerDefaults = defaults$g({\n root: undefined,\n directed: false\n});\nvar elesfn$k = {\n hierholzer: function hierholzer(options) {\n if (!plainObject(options)) {\n var args = arguments;\n options = {\n root: args[0],\n directed: args[1]\n };\n }\n var _hierholzerDefaults = hierholzerDefaults(options),\n root = _hierholzerDefaults.root,\n directed = _hierholzerDefaults.directed;\n var eles = this;\n var dflag = false;\n var oddIn;\n var oddOut;\n var startVertex;\n if (root) startVertex = string(root) ? this.filter(root)[0].id() : root[0].id();\n var nodes = {};\n var edges = {};\n if (directed) {\n eles.forEach(function (ele) {\n var id = ele.id();\n if (ele.isNode()) {\n var ind = ele.indegree(true);\n var outd = ele.outdegree(true);\n var d1 = ind - outd;\n var d2 = outd - ind;\n if (d1 == 1) {\n if (oddIn) dflag = true;else oddIn = id;\n } else if (d2 == 1) {\n if (oddOut) dflag = true;else oddOut = id;\n } else if (d2 > 1 || d1 > 1) {\n dflag = true;\n }\n nodes[id] = [];\n ele.outgoers().forEach(function (e) {\n if (e.isEdge()) nodes[id].push(e.id());\n });\n } else {\n edges[id] = [undefined, ele.target().id()];\n }\n });\n } else {\n eles.forEach(function (ele) {\n var id = ele.id();\n if (ele.isNode()) {\n var d = ele.degree(true);\n if (d % 2) {\n if (!oddIn) oddIn = id;else if (!oddOut) oddOut = id;else dflag = true;\n }\n nodes[id] = [];\n ele.connectedEdges().forEach(function (e) {\n return nodes[id].push(e.id());\n });\n } else {\n edges[id] = [ele.source().id(), ele.target().id()];\n }\n });\n }\n var result = {\n found: false,\n trail: undefined\n };\n if (dflag) return result;else if (oddOut && oddIn) {\n if (directed) {\n if (startVertex && oddOut != startVertex) {\n return result;\n }\n startVertex = oddOut;\n } else {\n if (startVertex && oddOut != startVertex && oddIn != startVertex) {\n return result;\n } else if (!startVertex) {\n startVertex = oddOut;\n }\n }\n } else {\n if (!startVertex) startVertex = eles[0].id();\n }\n var walk = function walk(v) {\n var currentNode = v;\n var subtour = [v];\n var adj, adjTail, adjHead;\n while (nodes[currentNode].length) {\n adj = nodes[currentNode].shift();\n adjTail = edges[adj][0];\n adjHead = edges[adj][1];\n if (currentNode != adjHead) {\n nodes[adjHead] = nodes[adjHead].filter(function (e) {\n return e != adj;\n });\n currentNode = adjHead;\n } else if (!directed && currentNode != adjTail) {\n nodes[adjTail] = nodes[adjTail].filter(function (e) {\n return e != adj;\n });\n currentNode = adjTail;\n }\n subtour.unshift(adj);\n subtour.unshift(currentNode);\n }\n return subtour;\n };\n var trail = [];\n var subtour = [];\n subtour = walk(startVertex);\n while (subtour.length != 1) {\n if (nodes[subtour[0]].length == 0) {\n trail.unshift(eles.getElementById(subtour.shift()));\n trail.unshift(eles.getElementById(subtour.shift()));\n } else {\n subtour = walk(subtour.shift()).concat(subtour);\n }\n }\n trail.unshift(eles.getElementById(subtour.shift())); // final node\n\n for (var d in nodes) {\n if (nodes[d].length) {\n return result;\n }\n }\n result.found = true;\n result.trail = this.spawn(trail, true);\n return result;\n }\n};\n\nvar hopcroftTarjanBiconnected = function hopcroftTarjanBiconnected() {\n var eles = this;\n var nodes = {};\n var id = 0;\n var edgeCount = 0;\n var components = [];\n var stack = [];\n var visitedEdges = {};\n var buildComponent = function buildComponent(x, y) {\n var i = stack.length - 1;\n var cutset = [];\n var component = eles.spawn();\n while (stack[i].x != x || stack[i].y != y) {\n cutset.push(stack.pop().edge);\n i--;\n }\n cutset.push(stack.pop().edge);\n cutset.forEach(function (edge) {\n var connectedNodes = edge.connectedNodes().intersection(eles);\n component.merge(edge);\n connectedNodes.forEach(function (node) {\n var nodeId = node.id();\n var connectedEdges = node.connectedEdges().intersection(eles);\n component.merge(node);\n if (!nodes[nodeId].cutVertex) {\n component.merge(connectedEdges);\n } else {\n component.merge(connectedEdges.filter(function (edge) {\n return edge.isLoop();\n }));\n }\n });\n });\n components.push(component);\n };\n var _biconnectedSearch = function biconnectedSearch(root, currentNode, parent) {\n if (root === parent) edgeCount += 1;\n nodes[currentNode] = {\n id: id,\n low: id++,\n cutVertex: false\n };\n var edges = eles.getElementById(currentNode).connectedEdges().intersection(eles);\n if (edges.size() === 0) {\n components.push(eles.spawn(eles.getElementById(currentNode)));\n } else {\n var sourceId, targetId, otherNodeId, edgeId;\n edges.forEach(function (edge) {\n sourceId = edge.source().id();\n targetId = edge.target().id();\n otherNodeId = sourceId === currentNode ? targetId : sourceId;\n if (otherNodeId !== parent) {\n edgeId = edge.id();\n if (!visitedEdges[edgeId]) {\n visitedEdges[edgeId] = true;\n stack.push({\n x: currentNode,\n y: otherNodeId,\n edge: edge\n });\n }\n if (!(otherNodeId in nodes)) {\n _biconnectedSearch(root, otherNodeId, currentNode);\n nodes[currentNode].low = Math.min(nodes[currentNode].low, nodes[otherNodeId].low);\n if (nodes[currentNode].id <= nodes[otherNodeId].low) {\n nodes[currentNode].cutVertex = true;\n buildComponent(currentNode, otherNodeId);\n }\n } else {\n nodes[currentNode].low = Math.min(nodes[currentNode].low, nodes[otherNodeId].id);\n }\n }\n });\n }\n };\n eles.forEach(function (ele) {\n if (ele.isNode()) {\n var nodeId = ele.id();\n if (!(nodeId in nodes)) {\n edgeCount = 0;\n _biconnectedSearch(nodeId, nodeId);\n nodes[nodeId].cutVertex = edgeCount > 1;\n }\n }\n });\n var cutVertices = Object.keys(nodes).filter(function (id) {\n return nodes[id].cutVertex;\n }).map(function (id) {\n return eles.getElementById(id);\n });\n return {\n cut: eles.spawn(cutVertices),\n components: components\n };\n};\nvar hopcroftTarjanBiconnected$1 = {\n hopcroftTarjanBiconnected: hopcroftTarjanBiconnected,\n htbc: hopcroftTarjanBiconnected,\n htb: hopcroftTarjanBiconnected,\n hopcroftTarjanBiconnectedComponents: hopcroftTarjanBiconnected\n};\n\nvar tarjanStronglyConnected = function tarjanStronglyConnected() {\n var eles = this;\n var nodes = {};\n var index = 0;\n var components = [];\n var stack = [];\n var cut = eles.spawn(eles);\n var _stronglyConnectedSearch = function stronglyConnectedSearch(sourceNodeId) {\n stack.push(sourceNodeId);\n nodes[sourceNodeId] = {\n index: index,\n low: index++,\n explored: false\n };\n var connectedEdges = eles.getElementById(sourceNodeId).connectedEdges().intersection(eles);\n connectedEdges.forEach(function (edge) {\n var targetNodeId = edge.target().id();\n if (targetNodeId !== sourceNodeId) {\n if (!(targetNodeId in nodes)) {\n _stronglyConnectedSearch(targetNodeId);\n }\n if (!nodes[targetNodeId].explored) {\n nodes[sourceNodeId].low = Math.min(nodes[sourceNodeId].low, nodes[targetNodeId].low);\n }\n }\n });\n if (nodes[sourceNodeId].index === nodes[sourceNodeId].low) {\n var componentNodes = eles.spawn();\n for (;;) {\n var nodeId = stack.pop();\n componentNodes.merge(eles.getElementById(nodeId));\n nodes[nodeId].low = nodes[sourceNodeId].index;\n nodes[nodeId].explored = true;\n if (nodeId === sourceNodeId) {\n break;\n }\n }\n var componentEdges = componentNodes.edgesWith(componentNodes);\n var component = componentNodes.merge(componentEdges);\n components.push(component);\n cut = cut.difference(component);\n }\n };\n eles.forEach(function (ele) {\n if (ele.isNode()) {\n var nodeId = ele.id();\n if (!(nodeId in nodes)) {\n _stronglyConnectedSearch(nodeId);\n }\n }\n });\n return {\n cut: cut,\n components: components\n };\n};\nvar tarjanStronglyConnected$1 = {\n tarjanStronglyConnected: tarjanStronglyConnected,\n tsc: tarjanStronglyConnected,\n tscc: tarjanStronglyConnected,\n tarjanStronglyConnectedComponents: tarjanStronglyConnected\n};\n\nvar elesfn$j = {};\n[elesfn$v, elesfn$u, elesfn$t, elesfn$s, elesfn$r, elesfn$q, elesfn$p, elesfn$o, elesfn$n, elesfn$m, elesfn$l, markovClustering$1, kClustering, hierarchicalClustering$1, affinityPropagation$1, elesfn$k, hopcroftTarjanBiconnected$1, tarjanStronglyConnected$1].forEach(function (props) {\n extend(elesfn$j, props);\n});\n\n/*!\nEmbeddable Minimum Strictly-Compliant Promises/A+ 1.1.1 Thenable\nCopyright (c) 2013-2014 Ralf S. Engelschall (http://engelschall.com)\nLicensed under The MIT License (http://opensource.org/licenses/MIT)\n*/\n\n/* promise states [Promises/A+ 2.1] */\nvar STATE_PENDING = 0; /* [Promises/A+ 2.1.1] */\nvar STATE_FULFILLED = 1; /* [Promises/A+ 2.1.2] */\nvar STATE_REJECTED = 2; /* [Promises/A+ 2.1.3] */\n\n/* promise object constructor */\nvar _api = function api(executor) {\n /* optionally support non-constructor/plain-function call */\n if (!(this instanceof _api)) return new _api(executor);\n\n /* initialize object */\n this.id = 'Thenable/1.0.7';\n this.state = STATE_PENDING; /* initial state */\n this.fulfillValue = undefined; /* initial value */ /* [Promises/A+ 1.3, 2.1.2.2] */\n this.rejectReason = undefined; /* initial reason */ /* [Promises/A+ 1.5, 2.1.3.2] */\n this.onFulfilled = []; /* initial handlers */\n this.onRejected = []; /* initial handlers */\n\n /* provide optional information-hiding proxy */\n this.proxy = {\n then: this.then.bind(this)\n };\n\n /* support optional executor function */\n if (typeof executor === 'function') executor.call(this, this.fulfill.bind(this), this.reject.bind(this));\n};\n\n/* promise API methods */\n_api.prototype = {\n /* promise resolving methods */\n fulfill: function fulfill(value) {\n return deliver(this, STATE_FULFILLED, 'fulfillValue', value);\n },\n reject: function reject(value) {\n return deliver(this, STATE_REJECTED, 'rejectReason', value);\n },\n /* \"The then Method\" [Promises/A+ 1.1, 1.2, 2.2] */\n then: function then(onFulfilled, onRejected) {\n var curr = this;\n var next = new _api(); /* [Promises/A+ 2.2.7] */\n curr.onFulfilled.push(resolver(onFulfilled, next, 'fulfill')); /* [Promises/A+ 2.2.2/2.2.6] */\n curr.onRejected.push(resolver(onRejected, next, 'reject')); /* [Promises/A+ 2.2.3/2.2.6] */\n execute(curr);\n return next.proxy; /* [Promises/A+ 2.2.7, 3.3] */\n }\n};\n\n/* deliver an action */\nvar deliver = function deliver(curr, state, name, value) {\n if (curr.state === STATE_PENDING) {\n curr.state = state; /* [Promises/A+ 2.1.2.1, 2.1.3.1] */\n curr[name] = value; /* [Promises/A+ 2.1.2.2, 2.1.3.2] */\n execute(curr);\n }\n return curr;\n};\n\n/* execute all handlers */\nvar execute = function execute(curr) {\n if (curr.state === STATE_FULFILLED) execute_handlers(curr, 'onFulfilled', curr.fulfillValue);else if (curr.state === STATE_REJECTED) execute_handlers(curr, 'onRejected', curr.rejectReason);\n};\n\n/* execute particular set of handlers */\nvar execute_handlers = function execute_handlers(curr, name, value) {\n /* global setImmediate: true */\n /* global setTimeout: true */\n\n /* short-circuit processing */\n if (curr[name].length === 0) return;\n\n /* iterate over all handlers, exactly once */\n var handlers = curr[name];\n curr[name] = []; /* [Promises/A+ 2.2.2.3, 2.2.3.3] */\n var func = function func() {\n for (var i = 0; i < handlers.length; i++) handlers[i](value); /* [Promises/A+ 2.2.5] */\n };\n\n /* execute procedure asynchronously */ /* [Promises/A+ 2.2.4, 3.1] */\n if (typeof setImmediate === 'function') setImmediate(func);else setTimeout(func, 0);\n};\n\n/* generate a resolver function */\nvar resolver = function resolver(cb, next, method) {\n return function (value) {\n if (typeof cb !== 'function') /* [Promises/A+ 2.2.1, 2.2.7.3, 2.2.7.4] */\n next[method].call(next, value); /* [Promises/A+ 2.2.7.3, 2.2.7.4] */else {\n var result;\n try {\n result = cb(value);\n } /* [Promises/A+ 2.2.2.1, 2.2.3.1, 2.2.5, 3.2] */ catch (e) {\n next.reject(e); /* [Promises/A+ 2.2.7.2] */\n return;\n }\n _resolve(next, result); /* [Promises/A+ 2.2.7.1] */\n }\n };\n};\n\n/* \"Promise Resolution Procedure\" */ /* [Promises/A+ 2.3] */\nvar _resolve = function resolve(promise, x) {\n /* sanity check arguments */ /* [Promises/A+ 2.3.1] */\n if (promise === x || promise.proxy === x) {\n promise.reject(new TypeError('cannot resolve promise with itself'));\n return;\n }\n\n /* surgically check for a \"then\" method\n (mainly to just call the \"getter\" of \"then\" only once) */\n var then;\n if (_typeof(x) === 'object' && x !== null || typeof x === 'function') {\n try {\n then = x.then;\n } /* [Promises/A+ 2.3.3.1, 3.5] */ catch (e) {\n promise.reject(e); /* [Promises/A+ 2.3.3.2] */\n return;\n }\n }\n\n /* handle own Thenables [Promises/A+ 2.3.2]\n and similar \"thenables\" [Promises/A+ 2.3.3] */\n if (typeof then === 'function') {\n var resolved = false;\n try {\n /* call retrieved \"then\" method */ /* [Promises/A+ 2.3.3.3] */\n then.call(x, /* resolvePromise */ /* [Promises/A+ 2.3.3.3.1] */\n function (y) {\n if (resolved) return;\n resolved = true; /* [Promises/A+ 2.3.3.3.3] */\n if (y === x) /* [Promises/A+ 3.6] */\n promise.reject(new TypeError('circular thenable chain'));else _resolve(promise, y);\n }, /* rejectPromise */ /* [Promises/A+ 2.3.3.3.2] */\n function (r) {\n if (resolved) return;\n resolved = true; /* [Promises/A+ 2.3.3.3.3] */\n promise.reject(r);\n });\n } catch (e) {\n if (!resolved) /* [Promises/A+ 2.3.3.3.3] */\n promise.reject(e); /* [Promises/A+ 2.3.3.3.4] */\n }\n return;\n }\n\n /* handle other values */\n promise.fulfill(x); /* [Promises/A+ 2.3.4, 2.3.3.4] */\n};\n\n// so we always have Promise.all()\n_api.all = function (ps) {\n return new _api(function (resolveAll, rejectAll) {\n var vals = new Array(ps.length);\n var doneCount = 0;\n var fulfill = function fulfill(i, val) {\n vals[i] = val;\n doneCount++;\n if (doneCount === ps.length) {\n resolveAll(vals);\n }\n };\n for (var i = 0; i < ps.length; i++) {\n (function (i) {\n var p = ps[i];\n var isPromise = p != null && p.then != null;\n if (isPromise) {\n p.then(function (val) {\n fulfill(i, val);\n }, function (err) {\n rejectAll(err);\n });\n } else {\n var val = p;\n fulfill(i, val);\n }\n })(i);\n }\n });\n};\n_api.resolve = function (val) {\n return new _api(function (resolve, reject) {\n resolve(val);\n });\n};\n_api.reject = function (val) {\n return new _api(function (resolve, reject) {\n reject(val);\n });\n};\nvar Promise$1 = typeof Promise !== 'undefined' ? Promise : _api; // eslint-disable-line no-undef\n\nvar Animation = function Animation(target, opts, opts2) {\n var isCore = core(target);\n var isEle = !isCore;\n var _p = this._private = extend({\n duration: 1000\n }, opts, opts2);\n _p.target = target;\n _p.style = _p.style || _p.css;\n _p.started = false;\n _p.playing = false;\n _p.hooked = false;\n _p.applying = false;\n _p.progress = 0;\n _p.completes = [];\n _p.frames = [];\n if (_p.complete && fn$6(_p.complete)) {\n _p.completes.push(_p.complete);\n }\n if (isEle) {\n var pos = target.position();\n _p.startPosition = _p.startPosition || {\n x: pos.x,\n y: pos.y\n };\n _p.startStyle = _p.startStyle || target.cy().style().getAnimationStartStyle(target, _p.style);\n }\n if (isCore) {\n var pan = target.pan();\n _p.startPan = {\n x: pan.x,\n y: pan.y\n };\n _p.startZoom = target.zoom();\n }\n\n // for future timeline/animations impl\n this.length = 1;\n this[0] = this;\n};\nvar anifn = Animation.prototype;\nextend(anifn, {\n instanceString: function instanceString() {\n return 'animation';\n },\n hook: function hook() {\n var _p = this._private;\n if (!_p.hooked) {\n // add to target's animation queue\n var q;\n var tAni = _p.target._private.animation;\n if (_p.queue) {\n q = tAni.queue;\n } else {\n q = tAni.current;\n }\n q.push(this);\n\n // add to the animation loop pool\n if (elementOrCollection(_p.target)) {\n _p.target.cy().addToAnimationPool(_p.target);\n }\n _p.hooked = true;\n }\n return this;\n },\n play: function play() {\n var _p = this._private;\n\n // autorewind\n if (_p.progress === 1) {\n _p.progress = 0;\n }\n _p.playing = true;\n _p.started = false; // needs to be started by animation loop\n _p.stopped = false;\n this.hook();\n\n // the animation loop will start the animation...\n\n return this;\n },\n playing: function playing() {\n return this._private.playing;\n },\n apply: function apply() {\n var _p = this._private;\n _p.applying = true;\n _p.started = false; // needs to be started by animation loop\n _p.stopped = false;\n this.hook();\n\n // the animation loop will apply the animation at this progress\n\n return this;\n },\n applying: function applying() {\n return this._private.applying;\n },\n pause: function pause() {\n var _p = this._private;\n _p.playing = false;\n _p.started = false;\n return this;\n },\n stop: function stop() {\n var _p = this._private;\n _p.playing = false;\n _p.started = false;\n _p.stopped = true; // to be removed from animation queues\n\n return this;\n },\n rewind: function rewind() {\n return this.progress(0);\n },\n fastforward: function fastforward() {\n return this.progress(1);\n },\n time: function time(t) {\n var _p = this._private;\n if (t === undefined) {\n return _p.progress * _p.duration;\n } else {\n return this.progress(t / _p.duration);\n }\n },\n progress: function progress(p) {\n var _p = this._private;\n var wasPlaying = _p.playing;\n if (p === undefined) {\n return _p.progress;\n } else {\n if (wasPlaying) {\n this.pause();\n }\n _p.progress = p;\n _p.started = false;\n if (wasPlaying) {\n this.play();\n }\n }\n return this;\n },\n completed: function completed() {\n return this._private.progress === 1;\n },\n reverse: function reverse() {\n var _p = this._private;\n var wasPlaying = _p.playing;\n if (wasPlaying) {\n this.pause();\n }\n _p.progress = 1 - _p.progress;\n _p.started = false;\n var swap = function swap(a, b) {\n var _pa = _p[a];\n if (_pa == null) {\n return;\n }\n _p[a] = _p[b];\n _p[b] = _pa;\n };\n swap('zoom', 'startZoom');\n swap('pan', 'startPan');\n swap('position', 'startPosition');\n\n // swap styles\n if (_p.style) {\n for (var i = 0; i < _p.style.length; i++) {\n var prop = _p.style[i];\n var name = prop.name;\n var startStyleProp = _p.startStyle[name];\n _p.startStyle[name] = prop;\n _p.style[i] = startStyleProp;\n }\n }\n if (wasPlaying) {\n this.play();\n }\n return this;\n },\n promise: function promise(type) {\n var _p = this._private;\n var arr;\n switch (type) {\n case 'frame':\n arr = _p.frames;\n break;\n default:\n case 'complete':\n case 'completed':\n arr = _p.completes;\n }\n return new Promise$1(function (resolve, reject) {\n arr.push(function () {\n resolve();\n });\n });\n }\n});\nanifn.complete = anifn.completed;\nanifn.run = anifn.play;\nanifn.running = anifn.playing;\n\nvar define$3 = {\n animated: function animated() {\n return function animatedImpl() {\n var self = this;\n var selfIsArrayLike = self.length !== undefined;\n var all = selfIsArrayLike ? self : [self]; // put in array if not array-like\n var cy = this._private.cy || this;\n if (!cy.styleEnabled()) {\n return false;\n }\n var ele = all[0];\n if (ele) {\n return ele._private.animation.current.length > 0;\n }\n };\n },\n // animated\n\n clearQueue: function clearQueue() {\n return function clearQueueImpl() {\n var self = this;\n var selfIsArrayLike = self.length !== undefined;\n var all = selfIsArrayLike ? self : [self]; // put in array if not array-like\n var cy = this._private.cy || this;\n if (!cy.styleEnabled()) {\n return this;\n }\n for (var i = 0; i < all.length; i++) {\n var ele = all[i];\n ele._private.animation.queue = [];\n }\n return this;\n };\n },\n // clearQueue\n\n delay: function delay() {\n return function delayImpl(time, complete) {\n var cy = this._private.cy || this;\n if (!cy.styleEnabled()) {\n return this;\n }\n return this.animate({\n delay: time,\n duration: time,\n complete: complete\n });\n };\n },\n // delay\n\n delayAnimation: function delayAnimation() {\n return function delayAnimationImpl(time, complete) {\n var cy = this._private.cy || this;\n if (!cy.styleEnabled()) {\n return this;\n }\n return this.animation({\n delay: time,\n duration: time,\n complete: complete\n });\n };\n },\n // delay\n\n animation: function animation() {\n return function animationImpl(properties, params) {\n var self = this;\n var selfIsArrayLike = self.length !== undefined;\n var all = selfIsArrayLike ? self : [self]; // put in array if not array-like\n var cy = this._private.cy || this;\n var isCore = !selfIsArrayLike;\n var isEles = !isCore;\n if (!cy.styleEnabled()) {\n return this;\n }\n var style = cy.style();\n properties = extend({}, properties, params);\n var propertiesEmpty = Object.keys(properties).length === 0;\n if (propertiesEmpty) {\n return new Animation(all[0], properties); // nothing to animate\n }\n if (properties.duration === undefined) {\n properties.duration = 400;\n }\n switch (properties.duration) {\n case 'slow':\n properties.duration = 600;\n break;\n case 'fast':\n properties.duration = 200;\n break;\n }\n if (isEles) {\n properties.style = style.getPropsList(properties.style || properties.css);\n properties.css = undefined;\n }\n if (isEles && properties.renderedPosition != null) {\n var rpos = properties.renderedPosition;\n var pan = cy.pan();\n var zoom = cy.zoom();\n properties.position = renderedToModelPosition(rpos, zoom, pan);\n }\n\n // override pan w/ panBy if set\n if (isCore && properties.panBy != null) {\n var panBy = properties.panBy;\n var cyPan = cy.pan();\n properties.pan = {\n x: cyPan.x + panBy.x,\n y: cyPan.y + panBy.y\n };\n }\n\n // override pan w/ center if set\n var center = properties.center || properties.centre;\n if (isCore && center != null) {\n var centerPan = cy.getCenterPan(center.eles, properties.zoom);\n if (centerPan != null) {\n properties.pan = centerPan;\n }\n }\n\n // override pan & zoom w/ fit if set\n if (isCore && properties.fit != null) {\n var fit = properties.fit;\n var fitVp = cy.getFitViewport(fit.eles || fit.boundingBox, fit.padding);\n if (fitVp != null) {\n properties.pan = fitVp.pan;\n properties.zoom = fitVp.zoom;\n }\n }\n\n // override zoom (& potentially pan) w/ zoom obj if set\n if (isCore && plainObject(properties.zoom)) {\n var vp = cy.getZoomedViewport(properties.zoom);\n if (vp != null) {\n if (vp.zoomed) {\n properties.zoom = vp.zoom;\n }\n if (vp.panned) {\n properties.pan = vp.pan;\n }\n } else {\n properties.zoom = null; // an inavalid zoom (e.g. no delta) gets automatically destroyed\n }\n }\n return new Animation(all[0], properties);\n };\n },\n // animate\n\n animate: function animate() {\n return function animateImpl(properties, params) {\n var self = this;\n var selfIsArrayLike = self.length !== undefined;\n var all = selfIsArrayLike ? self : [self]; // put in array if not array-like\n var cy = this._private.cy || this;\n if (!cy.styleEnabled()) {\n return this;\n }\n if (params) {\n properties = extend({}, properties, params);\n }\n\n // manually hook and run the animation\n for (var i = 0; i < all.length; i++) {\n var ele = all[i];\n var queue = ele.animated() && (properties.queue === undefined || properties.queue);\n var ani = ele.animation(properties, queue ? {\n queue: true\n } : undefined);\n ani.play();\n }\n return this; // chaining\n };\n },\n // animate\n\n stop: function stop() {\n return function stopImpl(clearQueue, jumpToEnd) {\n var self = this;\n var selfIsArrayLike = self.length !== undefined;\n var all = selfIsArrayLike ? self : [self]; // put in array if not array-like\n var cy = this._private.cy || this;\n if (!cy.styleEnabled()) {\n return this;\n }\n for (var i = 0; i < all.length; i++) {\n var ele = all[i];\n var _p = ele._private;\n var anis = _p.animation.current;\n for (var j = 0; j < anis.length; j++) {\n var ani = anis[j];\n var ani_p = ani._private;\n if (jumpToEnd) {\n // next iteration of the animation loop, the animation\n // will go straight to the end and be removed\n ani_p.duration = 0;\n }\n }\n\n // clear the queue of future animations\n if (clearQueue) {\n _p.animation.queue = [];\n }\n if (!jumpToEnd) {\n _p.animation.current = [];\n }\n }\n\n // we have to notify (the animation loop doesn't do it for us on `stop`)\n cy.notify('draw');\n return this;\n };\n } // stop\n}; // define\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\nvar isArray_1;\nvar hasRequiredIsArray;\n\nfunction requireIsArray () {\n\tif (hasRequiredIsArray) return isArray_1;\n\thasRequiredIsArray = 1;\n\tvar isArray = Array.isArray;\n\n\tisArray_1 = isArray;\n\treturn isArray_1;\n}\n\nvar _isKey;\nvar hasRequired_isKey;\n\nfunction require_isKey () {\n\tif (hasRequired_isKey) return _isKey;\n\thasRequired_isKey = 1;\n\tvar isArray = requireIsArray(),\n\t isSymbol = requireIsSymbol();\n\n\t/** Used to match property names within property paths. */\n\tvar reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n\t reIsPlainProp = /^\\w*$/;\n\n\t/**\n\t * Checks if `value` is a property name and not a property path.\n\t *\n\t * @private\n\t * @param {*} value The value to check.\n\t * @param {Object} [object] The object to query keys on.\n\t * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n\t */\n\tfunction isKey(value, object) {\n\t if (isArray(value)) {\n\t return false;\n\t }\n\t var type = typeof value;\n\t if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n\t value == null || isSymbol(value)) {\n\t return true;\n\t }\n\t return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n\t (object != null && value in Object(object));\n\t}\n\n\t_isKey = isKey;\n\treturn _isKey;\n}\n\nvar isFunction_1;\nvar hasRequiredIsFunction;\n\nfunction requireIsFunction () {\n\tif (hasRequiredIsFunction) return isFunction_1;\n\thasRequiredIsFunction = 1;\n\tvar baseGetTag = require_baseGetTag(),\n\t isObject = requireIsObject();\n\n\t/** `Object#toString` result references. */\n\tvar asyncTag = '[object AsyncFunction]',\n\t funcTag = '[object Function]',\n\t genTag = '[object GeneratorFunction]',\n\t proxyTag = '[object Proxy]';\n\n\t/**\n\t * Checks if `value` is classified as a `Function` object.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 0.1.0\n\t * @category Lang\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n\t * @example\n\t *\n\t * _.isFunction(_);\n\t * // => true\n\t *\n\t * _.isFunction(/abc/);\n\t * // => false\n\t */\n\tfunction isFunction(value) {\n\t if (!isObject(value)) {\n\t return false;\n\t }\n\t // The use of `Object#toString` avoids issues with the `typeof` operator\n\t // in Safari 9 which returns 'object' for typed arrays and other constructors.\n\t var tag = baseGetTag(value);\n\t return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n\t}\n\n\tisFunction_1 = isFunction;\n\treturn isFunction_1;\n}\n\nvar _coreJsData;\nvar hasRequired_coreJsData;\n\nfunction require_coreJsData () {\n\tif (hasRequired_coreJsData) return _coreJsData;\n\thasRequired_coreJsData = 1;\n\tvar root = require_root();\n\n\t/** Used to detect overreaching core-js shims. */\n\tvar coreJsData = root['__core-js_shared__'];\n\n\t_coreJsData = coreJsData;\n\treturn _coreJsData;\n}\n\nvar _isMasked;\nvar hasRequired_isMasked;\n\nfunction require_isMasked () {\n\tif (hasRequired_isMasked) return _isMasked;\n\thasRequired_isMasked = 1;\n\tvar coreJsData = require_coreJsData();\n\n\t/** Used to detect methods masquerading as native. */\n\tvar maskSrcKey = (function() {\n\t var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n\t return uid ? ('Symbol(src)_1.' + uid) : '';\n\t}());\n\n\t/**\n\t * Checks if `func` has its source masked.\n\t *\n\t * @private\n\t * @param {Function} func The function to check.\n\t * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n\t */\n\tfunction isMasked(func) {\n\t return !!maskSrcKey && (maskSrcKey in func);\n\t}\n\n\t_isMasked = isMasked;\n\treturn _isMasked;\n}\n\n/** Used for built-in method references. */\n\nvar _toSource;\nvar hasRequired_toSource;\n\nfunction require_toSource () {\n\tif (hasRequired_toSource) return _toSource;\n\thasRequired_toSource = 1;\n\tvar funcProto = Function.prototype;\n\n\t/** Used to resolve the decompiled source of functions. */\n\tvar funcToString = funcProto.toString;\n\n\t/**\n\t * Converts `func` to its source code.\n\t *\n\t * @private\n\t * @param {Function} func The function to convert.\n\t * @returns {string} Returns the source code.\n\t */\n\tfunction toSource(func) {\n\t if (func != null) {\n\t try {\n\t return funcToString.call(func);\n\t } catch (e) {}\n\t try {\n\t return (func + '');\n\t } catch (e) {}\n\t }\n\t return '';\n\t}\n\n\t_toSource = toSource;\n\treturn _toSource;\n}\n\nvar _baseIsNative;\nvar hasRequired_baseIsNative;\n\nfunction require_baseIsNative () {\n\tif (hasRequired_baseIsNative) return _baseIsNative;\n\thasRequired_baseIsNative = 1;\n\tvar isFunction = requireIsFunction(),\n\t isMasked = require_isMasked(),\n\t isObject = requireIsObject(),\n\t toSource = require_toSource();\n\n\t/**\n\t * Used to match `RegExp`\n\t * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n\t */\n\tvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n\t/** Used to detect host constructors (Safari). */\n\tvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n\t/** Used for built-in method references. */\n\tvar funcProto = Function.prototype,\n\t objectProto = Object.prototype;\n\n\t/** Used to resolve the decompiled source of functions. */\n\tvar funcToString = funcProto.toString;\n\n\t/** Used to check objects for own properties. */\n\tvar hasOwnProperty = objectProto.hasOwnProperty;\n\n\t/** Used to detect if a method is native. */\n\tvar reIsNative = RegExp('^' +\n\t funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n\t .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n\t);\n\n\t/**\n\t * The base implementation of `_.isNative` without bad shim checks.\n\t *\n\t * @private\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is a native function,\n\t * else `false`.\n\t */\n\tfunction baseIsNative(value) {\n\t if (!isObject(value) || isMasked(value)) {\n\t return false;\n\t }\n\t var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n\t return pattern.test(toSource(value));\n\t}\n\n\t_baseIsNative = baseIsNative;\n\treturn _baseIsNative;\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\nvar _getValue;\nvar hasRequired_getValue;\n\nfunction require_getValue () {\n\tif (hasRequired_getValue) return _getValue;\n\thasRequired_getValue = 1;\n\tfunction getValue(object, key) {\n\t return object == null ? undefined : object[key];\n\t}\n\n\t_getValue = getValue;\n\treturn _getValue;\n}\n\nvar _getNative;\nvar hasRequired_getNative;\n\nfunction require_getNative () {\n\tif (hasRequired_getNative) return _getNative;\n\thasRequired_getNative = 1;\n\tvar baseIsNative = require_baseIsNative(),\n\t getValue = require_getValue();\n\n\t/**\n\t * Gets the native function at `key` of `object`.\n\t *\n\t * @private\n\t * @param {Object} object The object to query.\n\t * @param {string} key The key of the method to get.\n\t * @returns {*} Returns the function if it's native, else `undefined`.\n\t */\n\tfunction getNative(object, key) {\n\t var value = getValue(object, key);\n\t return baseIsNative(value) ? value : undefined;\n\t}\n\n\t_getNative = getNative;\n\treturn _getNative;\n}\n\nvar _nativeCreate;\nvar hasRequired_nativeCreate;\n\nfunction require_nativeCreate () {\n\tif (hasRequired_nativeCreate) return _nativeCreate;\n\thasRequired_nativeCreate = 1;\n\tvar getNative = require_getNative();\n\n\t/* Built-in method references that are verified to be native. */\n\tvar nativeCreate = getNative(Object, 'create');\n\n\t_nativeCreate = nativeCreate;\n\treturn _nativeCreate;\n}\n\nvar _hashClear;\nvar hasRequired_hashClear;\n\nfunction require_hashClear () {\n\tif (hasRequired_hashClear) return _hashClear;\n\thasRequired_hashClear = 1;\n\tvar nativeCreate = require_nativeCreate();\n\n\t/**\n\t * Removes all key-value entries from the hash.\n\t *\n\t * @private\n\t * @name clear\n\t * @memberOf Hash\n\t */\n\tfunction hashClear() {\n\t this.__data__ = nativeCreate ? nativeCreate(null) : {};\n\t this.size = 0;\n\t}\n\n\t_hashClear = hashClear;\n\treturn _hashClear;\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\nvar _hashDelete;\nvar hasRequired_hashDelete;\n\nfunction require_hashDelete () {\n\tif (hasRequired_hashDelete) return _hashDelete;\n\thasRequired_hashDelete = 1;\n\tfunction hashDelete(key) {\n\t var result = this.has(key) && delete this.__data__[key];\n\t this.size -= result ? 1 : 0;\n\t return result;\n\t}\n\n\t_hashDelete = hashDelete;\n\treturn _hashDelete;\n}\n\nvar _hashGet;\nvar hasRequired_hashGet;\n\nfunction require_hashGet () {\n\tif (hasRequired_hashGet) return _hashGet;\n\thasRequired_hashGet = 1;\n\tvar nativeCreate = require_nativeCreate();\n\n\t/** Used to stand-in for `undefined` hash values. */\n\tvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n\t/** Used for built-in method references. */\n\tvar objectProto = Object.prototype;\n\n\t/** Used to check objects for own properties. */\n\tvar hasOwnProperty = objectProto.hasOwnProperty;\n\n\t/**\n\t * Gets the hash value for `key`.\n\t *\n\t * @private\n\t * @name get\n\t * @memberOf Hash\n\t * @param {string} key The key of the value to get.\n\t * @returns {*} Returns the entry value.\n\t */\n\tfunction hashGet(key) {\n\t var data = this.__data__;\n\t if (nativeCreate) {\n\t var result = data[key];\n\t return result === HASH_UNDEFINED ? undefined : result;\n\t }\n\t return hasOwnProperty.call(data, key) ? data[key] : undefined;\n\t}\n\n\t_hashGet = hashGet;\n\treturn _hashGet;\n}\n\nvar _hashHas;\nvar hasRequired_hashHas;\n\nfunction require_hashHas () {\n\tif (hasRequired_hashHas) return _hashHas;\n\thasRequired_hashHas = 1;\n\tvar nativeCreate = require_nativeCreate();\n\n\t/** Used for built-in method references. */\n\tvar objectProto = Object.prototype;\n\n\t/** Used to check objects for own properties. */\n\tvar hasOwnProperty = objectProto.hasOwnProperty;\n\n\t/**\n\t * Checks if a hash value for `key` exists.\n\t *\n\t * @private\n\t * @name has\n\t * @memberOf Hash\n\t * @param {string} key The key of the entry to check.\n\t * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n\t */\n\tfunction hashHas(key) {\n\t var data = this.__data__;\n\t return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n\t}\n\n\t_hashHas = hashHas;\n\treturn _hashHas;\n}\n\nvar _hashSet;\nvar hasRequired_hashSet;\n\nfunction require_hashSet () {\n\tif (hasRequired_hashSet) return _hashSet;\n\thasRequired_hashSet = 1;\n\tvar nativeCreate = require_nativeCreate();\n\n\t/** Used to stand-in for `undefined` hash values. */\n\tvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n\t/**\n\t * Sets the hash `key` to `value`.\n\t *\n\t * @private\n\t * @name set\n\t * @memberOf Hash\n\t * @param {string} key The key of the value to set.\n\t * @param {*} value The value to set.\n\t * @returns {Object} Returns the hash instance.\n\t */\n\tfunction hashSet(key, value) {\n\t var data = this.__data__;\n\t this.size += this.has(key) ? 0 : 1;\n\t data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n\t return this;\n\t}\n\n\t_hashSet = hashSet;\n\treturn _hashSet;\n}\n\nvar _Hash;\nvar hasRequired_Hash;\n\nfunction require_Hash () {\n\tif (hasRequired_Hash) return _Hash;\n\thasRequired_Hash = 1;\n\tvar hashClear = require_hashClear(),\n\t hashDelete = require_hashDelete(),\n\t hashGet = require_hashGet(),\n\t hashHas = require_hashHas(),\n\t hashSet = require_hashSet();\n\n\t/**\n\t * Creates a hash object.\n\t *\n\t * @private\n\t * @constructor\n\t * @param {Array} [entries] The key-value pairs to cache.\n\t */\n\tfunction Hash(entries) {\n\t var index = -1,\n\t length = entries == null ? 0 : entries.length;\n\n\t this.clear();\n\t while (++index < length) {\n\t var entry = entries[index];\n\t this.set(entry[0], entry[1]);\n\t }\n\t}\n\n\t// Add methods to `Hash`.\n\tHash.prototype.clear = hashClear;\n\tHash.prototype['delete'] = hashDelete;\n\tHash.prototype.get = hashGet;\n\tHash.prototype.has = hashHas;\n\tHash.prototype.set = hashSet;\n\n\t_Hash = Hash;\n\treturn _Hash;\n}\n\n/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\n\nvar _listCacheClear;\nvar hasRequired_listCacheClear;\n\nfunction require_listCacheClear () {\n\tif (hasRequired_listCacheClear) return _listCacheClear;\n\thasRequired_listCacheClear = 1;\n\tfunction listCacheClear() {\n\t this.__data__ = [];\n\t this.size = 0;\n\t}\n\n\t_listCacheClear = listCacheClear;\n\treturn _listCacheClear;\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\nvar eq_1;\nvar hasRequiredEq;\n\nfunction requireEq () {\n\tif (hasRequiredEq) return eq_1;\n\thasRequiredEq = 1;\n\tfunction eq(value, other) {\n\t return value === other || (value !== value && other !== other);\n\t}\n\n\teq_1 = eq;\n\treturn eq_1;\n}\n\nvar _assocIndexOf;\nvar hasRequired_assocIndexOf;\n\nfunction require_assocIndexOf () {\n\tif (hasRequired_assocIndexOf) return _assocIndexOf;\n\thasRequired_assocIndexOf = 1;\n\tvar eq = requireEq();\n\n\t/**\n\t * Gets the index at which the `key` is found in `array` of key-value pairs.\n\t *\n\t * @private\n\t * @param {Array} array The array to inspect.\n\t * @param {*} key The key to search for.\n\t * @returns {number} Returns the index of the matched value, else `-1`.\n\t */\n\tfunction assocIndexOf(array, key) {\n\t var length = array.length;\n\t while (length--) {\n\t if (eq(array[length][0], key)) {\n\t return length;\n\t }\n\t }\n\t return -1;\n\t}\n\n\t_assocIndexOf = assocIndexOf;\n\treturn _assocIndexOf;\n}\n\nvar _listCacheDelete;\nvar hasRequired_listCacheDelete;\n\nfunction require_listCacheDelete () {\n\tif (hasRequired_listCacheDelete) return _listCacheDelete;\n\thasRequired_listCacheDelete = 1;\n\tvar assocIndexOf = require_assocIndexOf();\n\n\t/** Used for built-in method references. */\n\tvar arrayProto = Array.prototype;\n\n\t/** Built-in value references. */\n\tvar splice = arrayProto.splice;\n\n\t/**\n\t * Removes `key` and its value from the list cache.\n\t *\n\t * @private\n\t * @name delete\n\t * @memberOf ListCache\n\t * @param {string} key The key of the value to remove.\n\t * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n\t */\n\tfunction listCacheDelete(key) {\n\t var data = this.__data__,\n\t index = assocIndexOf(data, key);\n\n\t if (index < 0) {\n\t return false;\n\t }\n\t var lastIndex = data.length - 1;\n\t if (index == lastIndex) {\n\t data.pop();\n\t } else {\n\t splice.call(data, index, 1);\n\t }\n\t --this.size;\n\t return true;\n\t}\n\n\t_listCacheDelete = listCacheDelete;\n\treturn _listCacheDelete;\n}\n\nvar _listCacheGet;\nvar hasRequired_listCacheGet;\n\nfunction require_listCacheGet () {\n\tif (hasRequired_listCacheGet) return _listCacheGet;\n\thasRequired_listCacheGet = 1;\n\tvar assocIndexOf = require_assocIndexOf();\n\n\t/**\n\t * Gets the list cache value for `key`.\n\t *\n\t * @private\n\t * @name get\n\t * @memberOf ListCache\n\t * @param {string} key The key of the value to get.\n\t * @returns {*} Returns the entry value.\n\t */\n\tfunction listCacheGet(key) {\n\t var data = this.__data__,\n\t index = assocIndexOf(data, key);\n\n\t return index < 0 ? undefined : data[index][1];\n\t}\n\n\t_listCacheGet = listCacheGet;\n\treturn _listCacheGet;\n}\n\nvar _listCacheHas;\nvar hasRequired_listCacheHas;\n\nfunction require_listCacheHas () {\n\tif (hasRequired_listCacheHas) return _listCacheHas;\n\thasRequired_listCacheHas = 1;\n\tvar assocIndexOf = require_assocIndexOf();\n\n\t/**\n\t * Checks if a list cache value for `key` exists.\n\t *\n\t * @private\n\t * @name has\n\t * @memberOf ListCache\n\t * @param {string} key The key of the entry to check.\n\t * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n\t */\n\tfunction listCacheHas(key) {\n\t return assocIndexOf(this.__data__, key) > -1;\n\t}\n\n\t_listCacheHas = listCacheHas;\n\treturn _listCacheHas;\n}\n\nvar _listCacheSet;\nvar hasRequired_listCacheSet;\n\nfunction require_listCacheSet () {\n\tif (hasRequired_listCacheSet) return _listCacheSet;\n\thasRequired_listCacheSet = 1;\n\tvar assocIndexOf = require_assocIndexOf();\n\n\t/**\n\t * Sets the list cache `key` to `value`.\n\t *\n\t * @private\n\t * @name set\n\t * @memberOf ListCache\n\t * @param {string} key The key of the value to set.\n\t * @param {*} value The value to set.\n\t * @returns {Object} Returns the list cache instance.\n\t */\n\tfunction listCacheSet(key, value) {\n\t var data = this.__data__,\n\t index = assocIndexOf(data, key);\n\n\t if (index < 0) {\n\t ++this.size;\n\t data.push([key, value]);\n\t } else {\n\t data[index][1] = value;\n\t }\n\t return this;\n\t}\n\n\t_listCacheSet = listCacheSet;\n\treturn _listCacheSet;\n}\n\nvar _ListCache;\nvar hasRequired_ListCache;\n\nfunction require_ListCache () {\n\tif (hasRequired_ListCache) return _ListCache;\n\thasRequired_ListCache = 1;\n\tvar listCacheClear = require_listCacheClear(),\n\t listCacheDelete = require_listCacheDelete(),\n\t listCacheGet = require_listCacheGet(),\n\t listCacheHas = require_listCacheHas(),\n\t listCacheSet = require_listCacheSet();\n\n\t/**\n\t * Creates an list cache object.\n\t *\n\t * @private\n\t * @constructor\n\t * @param {Array} [entries] The key-value pairs to cache.\n\t */\n\tfunction ListCache(entries) {\n\t var index = -1,\n\t length = entries == null ? 0 : entries.length;\n\n\t this.clear();\n\t while (++index < length) {\n\t var entry = entries[index];\n\t this.set(entry[0], entry[1]);\n\t }\n\t}\n\n\t// Add methods to `ListCache`.\n\tListCache.prototype.clear = listCacheClear;\n\tListCache.prototype['delete'] = listCacheDelete;\n\tListCache.prototype.get = listCacheGet;\n\tListCache.prototype.has = listCacheHas;\n\tListCache.prototype.set = listCacheSet;\n\n\t_ListCache = ListCache;\n\treturn _ListCache;\n}\n\nvar _Map;\nvar hasRequired_Map;\n\nfunction require_Map () {\n\tif (hasRequired_Map) return _Map;\n\thasRequired_Map = 1;\n\tvar getNative = require_getNative(),\n\t root = require_root();\n\n\t/* Built-in method references that are verified to be native. */\n\tvar Map = getNative(root, 'Map');\n\n\t_Map = Map;\n\treturn _Map;\n}\n\nvar _mapCacheClear;\nvar hasRequired_mapCacheClear;\n\nfunction require_mapCacheClear () {\n\tif (hasRequired_mapCacheClear) return _mapCacheClear;\n\thasRequired_mapCacheClear = 1;\n\tvar Hash = require_Hash(),\n\t ListCache = require_ListCache(),\n\t Map = require_Map();\n\n\t/**\n\t * Removes all key-value entries from the map.\n\t *\n\t * @private\n\t * @name clear\n\t * @memberOf MapCache\n\t */\n\tfunction mapCacheClear() {\n\t this.size = 0;\n\t this.__data__ = {\n\t 'hash': new Hash,\n\t 'map': new (Map || ListCache),\n\t 'string': new Hash\n\t };\n\t}\n\n\t_mapCacheClear = mapCacheClear;\n\treturn _mapCacheClear;\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\nvar _isKeyable;\nvar hasRequired_isKeyable;\n\nfunction require_isKeyable () {\n\tif (hasRequired_isKeyable) return _isKeyable;\n\thasRequired_isKeyable = 1;\n\tfunction isKeyable(value) {\n\t var type = typeof value;\n\t return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n\t ? (value !== '__proto__')\n\t : (value === null);\n\t}\n\n\t_isKeyable = isKeyable;\n\treturn _isKeyable;\n}\n\nvar _getMapData;\nvar hasRequired_getMapData;\n\nfunction require_getMapData () {\n\tif (hasRequired_getMapData) return _getMapData;\n\thasRequired_getMapData = 1;\n\tvar isKeyable = require_isKeyable();\n\n\t/**\n\t * Gets the data for `map`.\n\t *\n\t * @private\n\t * @param {Object} map The map to query.\n\t * @param {string} key The reference key.\n\t * @returns {*} Returns the map data.\n\t */\n\tfunction getMapData(map, key) {\n\t var data = map.__data__;\n\t return isKeyable(key)\n\t ? data[typeof key == 'string' ? 'string' : 'hash']\n\t : data.map;\n\t}\n\n\t_getMapData = getMapData;\n\treturn _getMapData;\n}\n\nvar _mapCacheDelete;\nvar hasRequired_mapCacheDelete;\n\nfunction require_mapCacheDelete () {\n\tif (hasRequired_mapCacheDelete) return _mapCacheDelete;\n\thasRequired_mapCacheDelete = 1;\n\tvar getMapData = require_getMapData();\n\n\t/**\n\t * Removes `key` and its value from the map.\n\t *\n\t * @private\n\t * @name delete\n\t * @memberOf MapCache\n\t * @param {string} key The key of the value to remove.\n\t * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n\t */\n\tfunction mapCacheDelete(key) {\n\t var result = getMapData(this, key)['delete'](key);\n\t this.size -= result ? 1 : 0;\n\t return result;\n\t}\n\n\t_mapCacheDelete = mapCacheDelete;\n\treturn _mapCacheDelete;\n}\n\nvar _mapCacheGet;\nvar hasRequired_mapCacheGet;\n\nfunction require_mapCacheGet () {\n\tif (hasRequired_mapCacheGet) return _mapCacheGet;\n\thasRequired_mapCacheGet = 1;\n\tvar getMapData = require_getMapData();\n\n\t/**\n\t * Gets the map value for `key`.\n\t *\n\t * @private\n\t * @name get\n\t * @memberOf MapCache\n\t * @param {string} key The key of the value to get.\n\t * @returns {*} Returns the entry value.\n\t */\n\tfunction mapCacheGet(key) {\n\t return getMapData(this, key).get(key);\n\t}\n\n\t_mapCacheGet = mapCacheGet;\n\treturn _mapCacheGet;\n}\n\nvar _mapCacheHas;\nvar hasRequired_mapCacheHas;\n\nfunction require_mapCacheHas () {\n\tif (hasRequired_mapCacheHas) return _mapCacheHas;\n\thasRequired_mapCacheHas = 1;\n\tvar getMapData = require_getMapData();\n\n\t/**\n\t * Checks if a map value for `key` exists.\n\t *\n\t * @private\n\t * @name has\n\t * @memberOf MapCache\n\t * @param {string} key The key of the entry to check.\n\t * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n\t */\n\tfunction mapCacheHas(key) {\n\t return getMapData(this, key).has(key);\n\t}\n\n\t_mapCacheHas = mapCacheHas;\n\treturn _mapCacheHas;\n}\n\nvar _mapCacheSet;\nvar hasRequired_mapCacheSet;\n\nfunction require_mapCacheSet () {\n\tif (hasRequired_mapCacheSet) return _mapCacheSet;\n\thasRequired_mapCacheSet = 1;\n\tvar getMapData = require_getMapData();\n\n\t/**\n\t * Sets the map `key` to `value`.\n\t *\n\t * @private\n\t * @name set\n\t * @memberOf MapCache\n\t * @param {string} key The key of the value to set.\n\t * @param {*} value The value to set.\n\t * @returns {Object} Returns the map cache instance.\n\t */\n\tfunction mapCacheSet(key, value) {\n\t var data = getMapData(this, key),\n\t size = data.size;\n\n\t data.set(key, value);\n\t this.size += data.size == size ? 0 : 1;\n\t return this;\n\t}\n\n\t_mapCacheSet = mapCacheSet;\n\treturn _mapCacheSet;\n}\n\nvar _MapCache;\nvar hasRequired_MapCache;\n\nfunction require_MapCache () {\n\tif (hasRequired_MapCache) return _MapCache;\n\thasRequired_MapCache = 1;\n\tvar mapCacheClear = require_mapCacheClear(),\n\t mapCacheDelete = require_mapCacheDelete(),\n\t mapCacheGet = require_mapCacheGet(),\n\t mapCacheHas = require_mapCacheHas(),\n\t mapCacheSet = require_mapCacheSet();\n\n\t/**\n\t * Creates a map cache object to store key-value pairs.\n\t *\n\t * @private\n\t * @constructor\n\t * @param {Array} [entries] The key-value pairs to cache.\n\t */\n\tfunction MapCache(entries) {\n\t var index = -1,\n\t length = entries == null ? 0 : entries.length;\n\n\t this.clear();\n\t while (++index < length) {\n\t var entry = entries[index];\n\t this.set(entry[0], entry[1]);\n\t }\n\t}\n\n\t// Add methods to `MapCache`.\n\tMapCache.prototype.clear = mapCacheClear;\n\tMapCache.prototype['delete'] = mapCacheDelete;\n\tMapCache.prototype.get = mapCacheGet;\n\tMapCache.prototype.has = mapCacheHas;\n\tMapCache.prototype.set = mapCacheSet;\n\n\t_MapCache = MapCache;\n\treturn _MapCache;\n}\n\nvar memoize_1;\nvar hasRequiredMemoize;\n\nfunction requireMemoize () {\n\tif (hasRequiredMemoize) return memoize_1;\n\thasRequiredMemoize = 1;\n\tvar MapCache = require_MapCache();\n\n\t/** Error message constants. */\n\tvar FUNC_ERROR_TEXT = 'Expected a function';\n\n\t/**\n\t * Creates a function that memoizes the result of `func`. If `resolver` is\n\t * provided, it determines the cache key for storing the result based on the\n\t * arguments provided to the memoized function. By default, the first argument\n\t * provided to the memoized function is used as the map cache key. The `func`\n\t * is invoked with the `this` binding of the memoized function.\n\t *\n\t * **Note:** The cache is exposed as the `cache` property on the memoized\n\t * function. Its creation may be customized by replacing the `_.memoize.Cache`\n\t * constructor with one whose instances implement the\n\t * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n\t * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 0.1.0\n\t * @category Function\n\t * @param {Function} func The function to have its output memoized.\n\t * @param {Function} [resolver] The function to resolve the cache key.\n\t * @returns {Function} Returns the new memoized function.\n\t * @example\n\t *\n\t * var object = { 'a': 1, 'b': 2 };\n\t * var other = { 'c': 3, 'd': 4 };\n\t *\n\t * var values = _.memoize(_.values);\n\t * values(object);\n\t * // => [1, 2]\n\t *\n\t * values(other);\n\t * // => [3, 4]\n\t *\n\t * object.a = 2;\n\t * values(object);\n\t * // => [1, 2]\n\t *\n\t * // Modify the result cache.\n\t * values.cache.set(object, ['a', 'b']);\n\t * values(object);\n\t * // => ['a', 'b']\n\t *\n\t * // Replace `_.memoize.Cache`.\n\t * _.memoize.Cache = WeakMap;\n\t */\n\tfunction memoize(func, resolver) {\n\t if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n\t throw new TypeError(FUNC_ERROR_TEXT);\n\t }\n\t var memoized = function() {\n\t var args = arguments,\n\t key = resolver ? resolver.apply(this, args) : args[0],\n\t cache = memoized.cache;\n\n\t if (cache.has(key)) {\n\t return cache.get(key);\n\t }\n\t var result = func.apply(this, args);\n\t memoized.cache = cache.set(key, result) || cache;\n\t return result;\n\t };\n\t memoized.cache = new (memoize.Cache || MapCache);\n\t return memoized;\n\t}\n\n\t// Expose `MapCache`.\n\tmemoize.Cache = MapCache;\n\n\tmemoize_1 = memoize;\n\treturn memoize_1;\n}\n\nvar _memoizeCapped;\nvar hasRequired_memoizeCapped;\n\nfunction require_memoizeCapped () {\n\tif (hasRequired_memoizeCapped) return _memoizeCapped;\n\thasRequired_memoizeCapped = 1;\n\tvar memoize = requireMemoize();\n\n\t/** Used as the maximum memoize cache size. */\n\tvar MAX_MEMOIZE_SIZE = 500;\n\n\t/**\n\t * A specialized version of `_.memoize` which clears the memoized function's\n\t * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n\t *\n\t * @private\n\t * @param {Function} func The function to have its output memoized.\n\t * @returns {Function} Returns the new memoized function.\n\t */\n\tfunction memoizeCapped(func) {\n\t var result = memoize(func, function(key) {\n\t if (cache.size === MAX_MEMOIZE_SIZE) {\n\t cache.clear();\n\t }\n\t return key;\n\t });\n\n\t var cache = result.cache;\n\t return result;\n\t}\n\n\t_memoizeCapped = memoizeCapped;\n\treturn _memoizeCapped;\n}\n\nvar _stringToPath;\nvar hasRequired_stringToPath;\n\nfunction require_stringToPath () {\n\tif (hasRequired_stringToPath) return _stringToPath;\n\thasRequired_stringToPath = 1;\n\tvar memoizeCapped = require_memoizeCapped();\n\n\t/** Used to match property names within property paths. */\n\tvar rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n\t/** Used to match backslashes in property paths. */\n\tvar reEscapeChar = /\\\\(\\\\)?/g;\n\n\t/**\n\t * Converts `string` to a property path array.\n\t *\n\t * @private\n\t * @param {string} string The string to convert.\n\t * @returns {Array} Returns the property path array.\n\t */\n\tvar stringToPath = memoizeCapped(function(string) {\n\t var result = [];\n\t if (string.charCodeAt(0) === 46 /* . */) {\n\t result.push('');\n\t }\n\t string.replace(rePropName, function(match, number, quote, subString) {\n\t result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n\t });\n\t return result;\n\t});\n\n\t_stringToPath = stringToPath;\n\treturn _stringToPath;\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\nvar _arrayMap;\nvar hasRequired_arrayMap;\n\nfunction require_arrayMap () {\n\tif (hasRequired_arrayMap) return _arrayMap;\n\thasRequired_arrayMap = 1;\n\tfunction arrayMap(array, iteratee) {\n\t var index = -1,\n\t length = array == null ? 0 : array.length,\n\t result = Array(length);\n\n\t while (++index < length) {\n\t result[index] = iteratee(array[index], index, array);\n\t }\n\t return result;\n\t}\n\n\t_arrayMap = arrayMap;\n\treturn _arrayMap;\n}\n\nvar _baseToString;\nvar hasRequired_baseToString;\n\nfunction require_baseToString () {\n\tif (hasRequired_baseToString) return _baseToString;\n\thasRequired_baseToString = 1;\n\tvar Symbol = require_Symbol(),\n\t arrayMap = require_arrayMap(),\n\t isArray = requireIsArray(),\n\t isSymbol = requireIsSymbol();\n\n\t/** Used to convert symbols to primitives and strings. */\n\tvar symbolProto = Symbol ? Symbol.prototype : undefined,\n\t symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n\t/**\n\t * The base implementation of `_.toString` which doesn't convert nullish\n\t * values to empty strings.\n\t *\n\t * @private\n\t * @param {*} value The value to process.\n\t * @returns {string} Returns the string.\n\t */\n\tfunction baseToString(value) {\n\t // Exit early for strings to avoid a performance hit in some environments.\n\t if (typeof value == 'string') {\n\t return value;\n\t }\n\t if (isArray(value)) {\n\t // Recursively convert values (susceptible to call stack limits).\n\t return arrayMap(value, baseToString) + '';\n\t }\n\t if (isSymbol(value)) {\n\t return symbolToString ? symbolToString.call(value) : '';\n\t }\n\t var result = (value + '');\n\t return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;\n\t}\n\n\t_baseToString = baseToString;\n\treturn _baseToString;\n}\n\nvar toString_1;\nvar hasRequiredToString;\n\nfunction requireToString () {\n\tif (hasRequiredToString) return toString_1;\n\thasRequiredToString = 1;\n\tvar baseToString = require_baseToString();\n\n\t/**\n\t * Converts `value` to a string. An empty string is returned for `null`\n\t * and `undefined` values. The sign of `-0` is preserved.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 4.0.0\n\t * @category Lang\n\t * @param {*} value The value to convert.\n\t * @returns {string} Returns the converted string.\n\t * @example\n\t *\n\t * _.toString(null);\n\t * // => ''\n\t *\n\t * _.toString(-0);\n\t * // => '-0'\n\t *\n\t * _.toString([1, 2, 3]);\n\t * // => '1,2,3'\n\t */\n\tfunction toString(value) {\n\t return value == null ? '' : baseToString(value);\n\t}\n\n\ttoString_1 = toString;\n\treturn toString_1;\n}\n\nvar _castPath;\nvar hasRequired_castPath;\n\nfunction require_castPath () {\n\tif (hasRequired_castPath) return _castPath;\n\thasRequired_castPath = 1;\n\tvar isArray = requireIsArray(),\n\t isKey = require_isKey(),\n\t stringToPath = require_stringToPath(),\n\t toString = requireToString();\n\n\t/**\n\t * Casts `value` to a path array if it's not one.\n\t *\n\t * @private\n\t * @param {*} value The value to inspect.\n\t * @param {Object} [object] The object to query keys on.\n\t * @returns {Array} Returns the cast property path array.\n\t */\n\tfunction castPath(value, object) {\n\t if (isArray(value)) {\n\t return value;\n\t }\n\t return isKey(value, object) ? [value] : stringToPath(toString(value));\n\t}\n\n\t_castPath = castPath;\n\treturn _castPath;\n}\n\nvar _toKey;\nvar hasRequired_toKey;\n\nfunction require_toKey () {\n\tif (hasRequired_toKey) return _toKey;\n\thasRequired_toKey = 1;\n\tvar isSymbol = requireIsSymbol();\n\n\t/**\n\t * Converts `value` to a string key if it's not a string or symbol.\n\t *\n\t * @private\n\t * @param {*} value The value to inspect.\n\t * @returns {string|symbol} Returns the key.\n\t */\n\tfunction toKey(value) {\n\t if (typeof value == 'string' || isSymbol(value)) {\n\t return value;\n\t }\n\t var result = (value + '');\n\t return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;\n\t}\n\n\t_toKey = toKey;\n\treturn _toKey;\n}\n\nvar _baseGet;\nvar hasRequired_baseGet;\n\nfunction require_baseGet () {\n\tif (hasRequired_baseGet) return _baseGet;\n\thasRequired_baseGet = 1;\n\tvar castPath = require_castPath(),\n\t toKey = require_toKey();\n\n\t/**\n\t * The base implementation of `_.get` without support for default values.\n\t *\n\t * @private\n\t * @param {Object} object The object to query.\n\t * @param {Array|string} path The path of the property to get.\n\t * @returns {*} Returns the resolved value.\n\t */\n\tfunction baseGet(object, path) {\n\t path = castPath(path, object);\n\n\t var index = 0,\n\t length = path.length;\n\n\t while (object != null && index < length) {\n\t object = object[toKey(path[index++])];\n\t }\n\t return (index && index == length) ? object : undefined;\n\t}\n\n\t_baseGet = baseGet;\n\treturn _baseGet;\n}\n\nvar get_1;\nvar hasRequiredGet;\n\nfunction requireGet () {\n\tif (hasRequiredGet) return get_1;\n\thasRequiredGet = 1;\n\tvar baseGet = require_baseGet();\n\n\t/**\n\t * Gets the value at `path` of `object`. If the resolved value is\n\t * `undefined`, the `defaultValue` is returned in its place.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 3.7.0\n\t * @category Object\n\t * @param {Object} object The object to query.\n\t * @param {Array|string} path The path of the property to get.\n\t * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n\t * @returns {*} Returns the resolved value.\n\t * @example\n\t *\n\t * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n\t *\n\t * _.get(object, 'a[0].b.c');\n\t * // => 3\n\t *\n\t * _.get(object, ['a', '0', 'b', 'c']);\n\t * // => 3\n\t *\n\t * _.get(object, 'a.b.c', 'default');\n\t * // => 'default'\n\t */\n\tfunction get(object, path, defaultValue) {\n\t var result = object == null ? undefined : baseGet(object, path);\n\t return result === undefined ? defaultValue : result;\n\t}\n\n\tget_1 = get;\n\treturn get_1;\n}\n\nvar getExports = requireGet();\nvar get = /*@__PURE__*/getDefaultExportFromCjs(getExports);\n\nvar _defineProperty;\nvar hasRequired_defineProperty;\n\nfunction require_defineProperty () {\n\tif (hasRequired_defineProperty) return _defineProperty;\n\thasRequired_defineProperty = 1;\n\tvar getNative = require_getNative();\n\n\tvar defineProperty = (function() {\n\t try {\n\t var func = getNative(Object, 'defineProperty');\n\t func({}, '', {});\n\t return func;\n\t } catch (e) {}\n\t}());\n\n\t_defineProperty = defineProperty;\n\treturn _defineProperty;\n}\n\nvar _baseAssignValue;\nvar hasRequired_baseAssignValue;\n\nfunction require_baseAssignValue () {\n\tif (hasRequired_baseAssignValue) return _baseAssignValue;\n\thasRequired_baseAssignValue = 1;\n\tvar defineProperty = require_defineProperty();\n\n\t/**\n\t * The base implementation of `assignValue` and `assignMergeValue` without\n\t * value checks.\n\t *\n\t * @private\n\t * @param {Object} object The object to modify.\n\t * @param {string} key The key of the property to assign.\n\t * @param {*} value The value to assign.\n\t */\n\tfunction baseAssignValue(object, key, value) {\n\t if (key == '__proto__' && defineProperty) {\n\t defineProperty(object, key, {\n\t 'configurable': true,\n\t 'enumerable': true,\n\t 'value': value,\n\t 'writable': true\n\t });\n\t } else {\n\t object[key] = value;\n\t }\n\t}\n\n\t_baseAssignValue = baseAssignValue;\n\treturn _baseAssignValue;\n}\n\nvar _assignValue;\nvar hasRequired_assignValue;\n\nfunction require_assignValue () {\n\tif (hasRequired_assignValue) return _assignValue;\n\thasRequired_assignValue = 1;\n\tvar baseAssignValue = require_baseAssignValue(),\n\t eq = requireEq();\n\n\t/** Used for built-in method references. */\n\tvar objectProto = Object.prototype;\n\n\t/** Used to check objects for own properties. */\n\tvar hasOwnProperty = objectProto.hasOwnProperty;\n\n\t/**\n\t * Assigns `value` to `key` of `object` if the existing value is not equivalent\n\t * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n\t * for equality comparisons.\n\t *\n\t * @private\n\t * @param {Object} object The object to modify.\n\t * @param {string} key The key of the property to assign.\n\t * @param {*} value The value to assign.\n\t */\n\tfunction assignValue(object, key, value) {\n\t var objValue = object[key];\n\t if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n\t (value === undefined && !(key in object))) {\n\t baseAssignValue(object, key, value);\n\t }\n\t}\n\n\t_assignValue = assignValue;\n\treturn _assignValue;\n}\n\n/** Used as references for various `Number` constants. */\n\nvar _isIndex;\nvar hasRequired_isIndex;\n\nfunction require_isIndex () {\n\tif (hasRequired_isIndex) return _isIndex;\n\thasRequired_isIndex = 1;\n\tvar MAX_SAFE_INTEGER = 9007199254740991;\n\n\t/** Used to detect unsigned integer values. */\n\tvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n\t/**\n\t * Checks if `value` is a valid array-like index.\n\t *\n\t * @private\n\t * @param {*} value The value to check.\n\t * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n\t * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n\t */\n\tfunction isIndex(value, length) {\n\t var type = typeof value;\n\t length = length == null ? MAX_SAFE_INTEGER : length;\n\n\t return !!length &&\n\t (type == 'number' ||\n\t (type != 'symbol' && reIsUint.test(value))) &&\n\t (value > -1 && value % 1 == 0 && value < length);\n\t}\n\n\t_isIndex = isIndex;\n\treturn _isIndex;\n}\n\nvar _baseSet;\nvar hasRequired_baseSet;\n\nfunction require_baseSet () {\n\tif (hasRequired_baseSet) return _baseSet;\n\thasRequired_baseSet = 1;\n\tvar assignValue = require_assignValue(),\n\t castPath = require_castPath(),\n\t isIndex = require_isIndex(),\n\t isObject = requireIsObject(),\n\t toKey = require_toKey();\n\n\t/**\n\t * The base implementation of `_.set`.\n\t *\n\t * @private\n\t * @param {Object} object The object to modify.\n\t * @param {Array|string} path The path of the property to set.\n\t * @param {*} value The value to set.\n\t * @param {Function} [customizer] The function to customize path creation.\n\t * @returns {Object} Returns `object`.\n\t */\n\tfunction baseSet(object, path, value, customizer) {\n\t if (!isObject(object)) {\n\t return object;\n\t }\n\t path = castPath(path, object);\n\n\t var index = -1,\n\t length = path.length,\n\t lastIndex = length - 1,\n\t nested = object;\n\n\t while (nested != null && ++index < length) {\n\t var key = toKey(path[index]),\n\t newValue = value;\n\n\t if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n\t return object;\n\t }\n\n\t if (index != lastIndex) {\n\t var objValue = nested[key];\n\t newValue = customizer ? customizer(objValue, key, nested) : undefined;\n\t if (newValue === undefined) {\n\t newValue = isObject(objValue)\n\t ? objValue\n\t : (isIndex(path[index + 1]) ? [] : {});\n\t }\n\t }\n\t assignValue(nested, key, newValue);\n\t nested = nested[key];\n\t }\n\t return object;\n\t}\n\n\t_baseSet = baseSet;\n\treturn _baseSet;\n}\n\nvar set_1;\nvar hasRequiredSet;\n\nfunction requireSet () {\n\tif (hasRequiredSet) return set_1;\n\thasRequiredSet = 1;\n\tvar baseSet = require_baseSet();\n\n\t/**\n\t * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,\n\t * it's created. Arrays are created for missing index properties while objects\n\t * are created for all other missing properties. Use `_.setWith` to customize\n\t * `path` creation.\n\t *\n\t * **Note:** This method mutates `object`.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 3.7.0\n\t * @category Object\n\t * @param {Object} object The object to modify.\n\t * @param {Array|string} path The path of the property to set.\n\t * @param {*} value The value to set.\n\t * @returns {Object} Returns `object`.\n\t * @example\n\t *\n\t * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n\t *\n\t * _.set(object, 'a[0].b.c', 4);\n\t * console.log(object.a[0].b.c);\n\t * // => 4\n\t *\n\t * _.set(object, ['x', '0', 'y', 'z'], 5);\n\t * console.log(object.x[0].y.z);\n\t * // => 5\n\t */\n\tfunction set(object, path, value) {\n\t return object == null ? object : baseSet(object, path, value);\n\t}\n\n\tset_1 = set;\n\treturn set_1;\n}\n\nvar setExports = requireSet();\nvar set = /*@__PURE__*/getDefaultExportFromCjs(setExports);\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\nvar _copyArray;\nvar hasRequired_copyArray;\n\nfunction require_copyArray () {\n\tif (hasRequired_copyArray) return _copyArray;\n\thasRequired_copyArray = 1;\n\tfunction copyArray(source, array) {\n\t var index = -1,\n\t length = source.length;\n\n\t array || (array = Array(length));\n\t while (++index < length) {\n\t array[index] = source[index];\n\t }\n\t return array;\n\t}\n\n\t_copyArray = copyArray;\n\treturn _copyArray;\n}\n\nvar toPath_1;\nvar hasRequiredToPath;\n\nfunction requireToPath () {\n\tif (hasRequiredToPath) return toPath_1;\n\thasRequiredToPath = 1;\n\tvar arrayMap = require_arrayMap(),\n\t copyArray = require_copyArray(),\n\t isArray = requireIsArray(),\n\t isSymbol = requireIsSymbol(),\n\t stringToPath = require_stringToPath(),\n\t toKey = require_toKey(),\n\t toString = requireToString();\n\n\t/**\n\t * Converts `value` to a property path array.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 4.0.0\n\t * @category Util\n\t * @param {*} value The value to convert.\n\t * @returns {Array} Returns the new property path array.\n\t * @example\n\t *\n\t * _.toPath('a.b.c');\n\t * // => ['a', 'b', 'c']\n\t *\n\t * _.toPath('a[0].b.c');\n\t * // => ['a', '0', 'b', 'c']\n\t */\n\tfunction toPath(value) {\n\t if (isArray(value)) {\n\t return arrayMap(value, toKey);\n\t }\n\t return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));\n\t}\n\n\ttoPath_1 = toPath;\n\treturn toPath_1;\n}\n\nvar toPathExports = requireToPath();\nvar toPath = /*@__PURE__*/getDefaultExportFromCjs(toPathExports);\n\nvar define$2 = {\n // access data field\n data: function data(params) {\n var defaults = {\n field: 'data',\n bindingEvent: 'data',\n allowBinding: false,\n allowSetting: false,\n allowGetting: false,\n settingEvent: 'data',\n settingTriggersEvent: false,\n triggerFnName: 'trigger',\n immutableKeys: {},\n // key => true if immutable\n updateStyle: false,\n beforeGet: function beforeGet(self) {},\n beforeSet: function beforeSet(self, obj) {},\n onSet: function onSet(self) {},\n canSet: function canSet(self) {\n return true;\n }\n };\n params = extend({}, defaults, params);\n return function dataImpl(name, value) {\n var p = params;\n var self = this;\n var selfIsArrayLike = self.length !== undefined;\n var all = selfIsArrayLike ? self : [self]; // put in array if not array-like\n var single = selfIsArrayLike ? self[0] : self;\n\n // .data('foo', ...)\n if (string(name)) {\n // set or get property\n var isPathLike = name.indexOf('.') !== -1; // there might be a normal field with a dot \n var path = isPathLike && toPath(name);\n\n // .data('foo')\n if (p.allowGetting && value === undefined) {\n // get\n\n var ret;\n if (single) {\n p.beforeGet(single);\n\n // check if it's path and a field with the same name doesn't exist\n if (path && single._private[p.field][name] === undefined) {\n ret = get(single._private[p.field], path);\n } else {\n ret = single._private[p.field][name];\n }\n }\n return ret;\n\n // .data('foo', 'bar')\n } else if (p.allowSetting && value !== undefined) {\n // set\n var valid = !p.immutableKeys[name];\n if (valid) {\n var change = _defineProperty$1({}, name, value);\n p.beforeSet(self, change);\n for (var i = 0, l = all.length; i < l; i++) {\n var ele = all[i];\n if (p.canSet(ele)) {\n if (path && single._private[p.field][name] === undefined) {\n set(ele._private[p.field], path, value);\n } else {\n ele._private[p.field][name] = value;\n }\n }\n }\n\n // update mappers if asked\n if (p.updateStyle) {\n self.updateStyle();\n }\n\n // call onSet callback\n p.onSet(self);\n if (p.settingTriggersEvent) {\n self[p.triggerFnName](p.settingEvent);\n }\n }\n }\n\n // .data({ 'foo': 'bar' })\n } else if (p.allowSetting && plainObject(name)) {\n // extend\n var obj = name;\n var k, v;\n var keys = Object.keys(obj);\n p.beforeSet(self, obj);\n for (var _i = 0; _i < keys.length; _i++) {\n k = keys[_i];\n v = obj[k];\n var _valid = !p.immutableKeys[k];\n if (_valid) {\n for (var j = 0; j < all.length; j++) {\n var _ele = all[j];\n if (p.canSet(_ele)) {\n _ele._private[p.field][k] = v;\n }\n }\n }\n }\n\n // update mappers if asked\n if (p.updateStyle) {\n self.updateStyle();\n }\n\n // call onSet callback\n p.onSet(self);\n if (p.settingTriggersEvent) {\n self[p.triggerFnName](p.settingEvent);\n }\n\n // .data(function(){ ... })\n } else if (p.allowBinding && fn$6(name)) {\n // bind to event\n var fn = name;\n self.on(p.bindingEvent, fn);\n\n // .data()\n } else if (p.allowGetting && name === undefined) {\n // get whole object\n var _ret;\n if (single) {\n p.beforeGet(single);\n _ret = single._private[p.field];\n }\n return _ret;\n }\n return self; // maintain chainability\n }; // function\n },\n // data\n\n // remove data field\n removeData: function removeData(params) {\n var defaults = {\n field: 'data',\n event: 'data',\n triggerFnName: 'trigger',\n triggerEvent: false,\n immutableKeys: {} // key => true if immutable\n };\n params = extend({}, defaults, params);\n return function removeDataImpl(names) {\n var p = params;\n var self = this;\n var selfIsArrayLike = self.length !== undefined;\n var all = selfIsArrayLike ? self : [self]; // put in array if not array-like\n\n // .removeData('foo bar')\n if (string(names)) {\n // then get the list of keys, and delete them\n var keys = names.split(/\\s+/);\n var l = keys.length;\n for (var i = 0; i < l; i++) {\n // delete each non-empty key\n var key = keys[i];\n if (emptyString(key)) {\n continue;\n }\n var valid = !p.immutableKeys[key]; // not valid if immutable\n if (valid) {\n for (var i_a = 0, l_a = all.length; i_a < l_a; i_a++) {\n all[i_a]._private[p.field][key] = undefined;\n }\n }\n }\n if (p.triggerEvent) {\n self[p.triggerFnName](p.event);\n }\n\n // .removeData()\n } else if (names === undefined) {\n // then delete all keys\n\n for (var _i_a = 0, _l_a = all.length; _i_a < _l_a; _i_a++) {\n var _privateFields = all[_i_a]._private[p.field];\n var _keys = Object.keys(_privateFields);\n for (var _i2 = 0; _i2 < _keys.length; _i2++) {\n var _key = _keys[_i2];\n var validKeyToDelete = !p.immutableKeys[_key];\n if (validKeyToDelete) {\n _privateFields[_key] = undefined;\n }\n }\n }\n if (p.triggerEvent) {\n self[p.triggerFnName](p.event);\n }\n }\n return self; // maintain chaining\n }; // function\n } // removeData\n}; // define\n\nvar define$1 = {\n eventAliasesOn: function eventAliasesOn(proto) {\n var p = proto;\n p.addListener = p.listen = p.bind = p.on;\n p.unlisten = p.unbind = p.off = p.removeListener;\n p.trigger = p.emit;\n\n // this is just a wrapper alias of .on()\n p.pon = p.promiseOn = function (events, selector) {\n var self = this;\n var args = Array.prototype.slice.call(arguments, 0);\n return new Promise$1(function (resolve, reject) {\n var callback = function callback(e) {\n self.off.apply(self, offArgs);\n resolve(e);\n };\n var onArgs = args.concat([callback]);\n var offArgs = onArgs.concat([]);\n self.on.apply(self, onArgs);\n });\n };\n }\n}; // define\n\n// use this module to cherry pick functions into your prototype\n// (useful for functions shared between the core and collections, for example)\n\nvar define = {};\n[define$3, define$2, define$1].forEach(function (m) {\n extend(define, m);\n});\n\nvar elesfn$i = {\n animate: define.animate(),\n animation: define.animation(),\n animated: define.animated(),\n clearQueue: define.clearQueue(),\n delay: define.delay(),\n delayAnimation: define.delayAnimation(),\n stop: define.stop()\n};\n\nvar elesfn$h = {\n classes: function classes(_classes) {\n var self = this;\n if (_classes === undefined) {\n var ret = [];\n self[0]._private.classes.forEach(function (cls) {\n return ret.push(cls);\n });\n return ret;\n } else if (!array(_classes)) {\n // extract classes from string\n _classes = (_classes || '').match(/\\S+/g) || [];\n }\n var changed = [];\n var classesSet = new Set$1(_classes);\n\n // check and update each ele\n for (var j = 0; j < self.length; j++) {\n var ele = self[j];\n var _p = ele._private;\n var eleClasses = _p.classes;\n var changedEle = false;\n\n // check if ele has all of the passed classes\n for (var i = 0; i < _classes.length; i++) {\n var cls = _classes[i];\n var eleHasClass = eleClasses.has(cls);\n if (!eleHasClass) {\n changedEle = true;\n break;\n }\n }\n\n // check if ele has classes outside of those passed\n if (!changedEle) {\n changedEle = eleClasses.size !== _classes.length;\n }\n if (changedEle) {\n _p.classes = classesSet;\n changed.push(ele);\n }\n }\n\n // trigger update style on those eles that had class changes\n if (changed.length > 0) {\n this.spawn(changed).updateStyle().emit('class');\n }\n return self;\n },\n addClass: function addClass(classes) {\n return this.toggleClass(classes, true);\n },\n hasClass: function hasClass(className) {\n var ele = this[0];\n return ele != null && ele._private.classes.has(className);\n },\n toggleClass: function toggleClass(classes, toggle) {\n if (!array(classes)) {\n // extract classes from string\n classes = classes.match(/\\S+/g) || [];\n }\n var self = this;\n var toggleUndefd = toggle === undefined;\n var changed = []; // eles who had classes changed\n\n for (var i = 0, il = self.length; i < il; i++) {\n var ele = self[i];\n var eleClasses = ele._private.classes;\n var changedEle = false;\n for (var j = 0; j < classes.length; j++) {\n var cls = classes[j];\n var hasClass = eleClasses.has(cls);\n var changedNow = false;\n if (toggle || toggleUndefd && !hasClass) {\n eleClasses.add(cls);\n changedNow = true;\n } else if (!toggle || toggleUndefd && hasClass) {\n eleClasses[\"delete\"](cls);\n changedNow = true;\n }\n if (!changedEle && changedNow) {\n changed.push(ele);\n changedEle = true;\n }\n } // for j classes\n } // for i eles\n\n // trigger update style on those eles that had class changes\n if (changed.length > 0) {\n this.spawn(changed).updateStyle().emit('class');\n }\n return self;\n },\n removeClass: function removeClass(classes) {\n return this.toggleClass(classes, false);\n },\n flashClass: function flashClass(classes, duration) {\n var self = this;\n if (duration == null) {\n duration = 250;\n } else if (duration === 0) {\n return self; // nothing to do really\n }\n self.addClass(classes);\n setTimeout(function () {\n self.removeClass(classes);\n }, duration);\n return self;\n }\n};\nelesfn$h.className = elesfn$h.classNames = elesfn$h.classes;\n\n// tokens in the query language\nvar tokens = {\n metaChar: '[\\\\!\\\\\"\\\\#\\\\$\\\\%\\\\&\\\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\.\\\\/\\\\:\\\\;\\\\<\\\\=\\\\>\\\\?\\\\@\\\\[\\\\]\\\\^\\\\`\\\\{\\\\|\\\\}\\\\~]',\n // chars we need to escape in let names, etc\n comparatorOp: '=|\\\\!=|>|>=|<|<=|\\\\$=|\\\\^=|\\\\*=',\n // binary comparison op (used in data selectors)\n boolOp: '\\\\?|\\\\!|\\\\^',\n // boolean (unary) operators (used in data selectors)\n string: '\"(?:\\\\\\\\\"|[^\"])*\"' + '|' + \"'(?:\\\\\\\\'|[^'])*'\",\n // string literals (used in data selectors) -- doublequotes | singlequotes\n number: number,\n // number literal (used in data selectors) --- e.g. 0.1234, 1234, 12e123\n meta: 'degree|indegree|outdegree',\n // allowed metadata fields (i.e. allowed functions to use from Collection)\n separator: '\\\\s*,\\\\s*',\n // queries are separated by commas, e.g. edge[foo = 'bar'], node.someClass\n descendant: '\\\\s+',\n child: '\\\\s+>\\\\s+',\n subject: '\\\\$',\n group: 'node|edge|\\\\*',\n directedEdge: '\\\\s+->\\\\s+',\n undirectedEdge: '\\\\s+<->\\\\s+'\n};\ntokens.variable = '(?:[\\\\w-.]|(?:\\\\\\\\' + tokens.metaChar + '))+'; // a variable name can have letters, numbers, dashes, and periods\ntokens.className = '(?:[\\\\w-]|(?:\\\\\\\\' + tokens.metaChar + '))+'; // a class name has the same rules as a variable except it can't have a '.' in the name\ntokens.value = tokens.string + '|' + tokens.number; // a value literal, either a string or number\ntokens.id = tokens.variable; // an element id (follows variable conventions)\n\n(function () {\n var ops, op, i;\n\n // add @ variants to comparatorOp\n ops = tokens.comparatorOp.split('|');\n for (i = 0; i < ops.length; i++) {\n op = ops[i];\n tokens.comparatorOp += '|@' + op;\n }\n\n // add ! variants to comparatorOp\n ops = tokens.comparatorOp.split('|');\n for (i = 0; i < ops.length; i++) {\n op = ops[i];\n if (op.indexOf('!') >= 0) {\n continue;\n } // skip ops that explicitly contain !\n if (op === '=') {\n continue;\n } // skip = b/c != is explicitly defined\n\n tokens.comparatorOp += '|\\\\!' + op;\n }\n})();\n\n/**\n * Make a new query object\n *\n * @prop type {Type} The type enum (int) of the query\n * @prop checks List of checks to make against an ele to test for a match\n */\nvar newQuery = function newQuery() {\n return {\n checks: []\n };\n};\n\n/**\n * A check type enum-like object. Uses integer values for fast match() lookup.\n * The ordering does not matter as long as the ints are unique.\n */\nvar Type = {\n /** E.g. node */\n GROUP: 0,\n /** A collection of elements */\n COLLECTION: 1,\n /** A filter(ele) function */\n FILTER: 2,\n /** E.g. [foo > 1] */\n DATA_COMPARE: 3,\n /** E.g. [foo] */\n DATA_EXIST: 4,\n /** E.g. [?foo] */\n DATA_BOOL: 5,\n /** E.g. [[degree > 2]] */\n META_COMPARE: 6,\n /** E.g. :selected */\n STATE: 7,\n /** E.g. #foo */\n ID: 8,\n /** E.g. .foo */\n CLASS: 9,\n /** E.g. #foo <-> #bar */\n UNDIRECTED_EDGE: 10,\n /** E.g. #foo -> #bar */\n DIRECTED_EDGE: 11,\n /** E.g. $#foo -> #bar */\n NODE_SOURCE: 12,\n /** E.g. #foo -> $#bar */\n NODE_TARGET: 13,\n /** E.g. $#foo <-> #bar */\n NODE_NEIGHBOR: 14,\n /** E.g. #foo > #bar */\n CHILD: 15,\n /** E.g. #foo #bar */\n DESCENDANT: 16,\n /** E.g. $#foo > #bar */\n PARENT: 17,\n /** E.g. $#foo #bar */\n ANCESTOR: 18,\n /** E.g. #foo > $bar > #baz */\n COMPOUND_SPLIT: 19,\n /** Always matches, useful placeholder for subject in `COMPOUND_SPLIT` */\n TRUE: 20\n};\n\nvar stateSelectors = [{\n selector: ':selected',\n matches: function matches(ele) {\n return ele.selected();\n }\n}, {\n selector: ':unselected',\n matches: function matches(ele) {\n return !ele.selected();\n }\n}, {\n selector: ':selectable',\n matches: function matches(ele) {\n return ele.selectable();\n }\n}, {\n selector: ':unselectable',\n matches: function matches(ele) {\n return !ele.selectable();\n }\n}, {\n selector: ':locked',\n matches: function matches(ele) {\n return ele.locked();\n }\n}, {\n selector: ':unlocked',\n matches: function matches(ele) {\n return !ele.locked();\n }\n}, {\n selector: ':visible',\n matches: function matches(ele) {\n return ele.visible();\n }\n}, {\n selector: ':hidden',\n matches: function matches(ele) {\n return !ele.visible();\n }\n}, {\n selector: ':transparent',\n matches: function matches(ele) {\n return ele.transparent();\n }\n}, {\n selector: ':grabbed',\n matches: function matches(ele) {\n return ele.grabbed();\n }\n}, {\n selector: ':free',\n matches: function matches(ele) {\n return !ele.grabbed();\n }\n}, {\n selector: ':removed',\n matches: function matches(ele) {\n return ele.removed();\n }\n}, {\n selector: ':inside',\n matches: function matches(ele) {\n return !ele.removed();\n }\n}, {\n selector: ':grabbable',\n matches: function matches(ele) {\n return ele.grabbable();\n }\n}, {\n selector: ':ungrabbable',\n matches: function matches(ele) {\n return !ele.grabbable();\n }\n}, {\n selector: ':animated',\n matches: function matches(ele) {\n return ele.animated();\n }\n}, {\n selector: ':unanimated',\n matches: function matches(ele) {\n return !ele.animated();\n }\n}, {\n selector: ':parent',\n matches: function matches(ele) {\n return ele.isParent();\n }\n}, {\n selector: ':childless',\n matches: function matches(ele) {\n return ele.isChildless();\n }\n}, {\n selector: ':child',\n matches: function matches(ele) {\n return ele.isChild();\n }\n}, {\n selector: ':orphan',\n matches: function matches(ele) {\n return ele.isOrphan();\n }\n}, {\n selector: ':nonorphan',\n matches: function matches(ele) {\n return ele.isChild();\n }\n}, {\n selector: ':compound',\n matches: function matches(ele) {\n if (ele.isNode()) {\n return ele.isParent();\n } else {\n return ele.source().isParent() || ele.target().isParent();\n }\n }\n}, {\n selector: ':loop',\n matches: function matches(ele) {\n return ele.isLoop();\n }\n}, {\n selector: ':simple',\n matches: function matches(ele) {\n return ele.isSimple();\n }\n}, {\n selector: ':active',\n matches: function matches(ele) {\n return ele.active();\n }\n}, {\n selector: ':inactive',\n matches: function matches(ele) {\n return !ele.active();\n }\n}, {\n selector: ':backgrounding',\n matches: function matches(ele) {\n return ele.backgrounding();\n }\n}, {\n selector: ':nonbackgrounding',\n matches: function matches(ele) {\n return !ele.backgrounding();\n }\n}].sort(function (a, b) {\n // n.b. selectors that are starting substrings of others must have the longer ones first\n return descending(a.selector, b.selector);\n});\nvar lookup = function () {\n var selToFn = {};\n var s;\n for (var i = 0; i < stateSelectors.length; i++) {\n s = stateSelectors[i];\n selToFn[s.selector] = s.matches;\n }\n return selToFn;\n}();\nvar stateSelectorMatches = function stateSelectorMatches(sel, ele) {\n return lookup[sel](ele);\n};\nvar stateSelectorRegex = '(' + stateSelectors.map(function (s) {\n return s.selector;\n}).join('|') + ')';\n\n// when a token like a variable has escaped meta characters, we need to clean the backslashes out\n// so that values get compared properly in Selector.filter()\nvar cleanMetaChars = function cleanMetaChars(str) {\n return str.replace(new RegExp('\\\\\\\\(' + tokens.metaChar + ')', 'g'), function (match, $1) {\n return $1;\n });\n};\nvar replaceLastQuery = function replaceLastQuery(selector, examiningQuery, replacementQuery) {\n selector[selector.length - 1] = replacementQuery;\n};\n\n// NOTE: add new expression syntax here to have it recognised by the parser;\n// - a query contains all adjacent (i.e. no separator in between) expressions;\n// - the current query is stored in selector[i]\n// - you need to check the query objects in match() for it actually filter properly, but that's pretty straight forward\nvar exprs = [{\n name: 'group',\n // just used for identifying when debugging\n query: true,\n regex: '(' + tokens.group + ')',\n populate: function populate(selector, query, _ref) {\n var _ref2 = _slicedToArray(_ref, 1),\n group = _ref2[0];\n query.checks.push({\n type: Type.GROUP,\n value: group === '*' ? group : group + 's'\n });\n }\n}, {\n name: 'state',\n query: true,\n regex: stateSelectorRegex,\n populate: function populate(selector, query, _ref3) {\n var _ref4 = _slicedToArray(_ref3, 1),\n state = _ref4[0];\n query.checks.push({\n type: Type.STATE,\n value: state\n });\n }\n}, {\n name: 'id',\n query: true,\n regex: '\\\\#(' + tokens.id + ')',\n populate: function populate(selector, query, _ref5) {\n var _ref6 = _slicedToArray(_ref5, 1),\n id = _ref6[0];\n query.checks.push({\n type: Type.ID,\n value: cleanMetaChars(id)\n });\n }\n}, {\n name: 'className',\n query: true,\n regex: '\\\\.(' + tokens.className + ')',\n populate: function populate(selector, query, _ref7) {\n var _ref8 = _slicedToArray(_ref7, 1),\n className = _ref8[0];\n query.checks.push({\n type: Type.CLASS,\n value: cleanMetaChars(className)\n });\n }\n}, {\n name: 'dataExists',\n query: true,\n regex: '\\\\[\\\\s*(' + tokens.variable + ')\\\\s*\\\\]',\n populate: function populate(selector, query, _ref9) {\n var _ref10 = _slicedToArray(_ref9, 1),\n variable = _ref10[0];\n query.checks.push({\n type: Type.DATA_EXIST,\n field: cleanMetaChars(variable)\n });\n }\n}, {\n name: 'dataCompare',\n query: true,\n regex: '\\\\[\\\\s*(' + tokens.variable + ')\\\\s*(' + tokens.comparatorOp + ')\\\\s*(' + tokens.value + ')\\\\s*\\\\]',\n populate: function populate(selector, query, _ref11) {\n var _ref12 = _slicedToArray(_ref11, 3),\n variable = _ref12[0],\n comparatorOp = _ref12[1],\n value = _ref12[2];\n var valueIsString = new RegExp('^' + tokens.string + '$').exec(value) != null;\n if (valueIsString) {\n value = value.substring(1, value.length - 1);\n } else {\n value = parseFloat(value);\n }\n query.checks.push({\n type: Type.DATA_COMPARE,\n field: cleanMetaChars(variable),\n operator: comparatorOp,\n value: value\n });\n }\n}, {\n name: 'dataBool',\n query: true,\n regex: '\\\\[\\\\s*(' + tokens.boolOp + ')\\\\s*(' + tokens.variable + ')\\\\s*\\\\]',\n populate: function populate(selector, query, _ref13) {\n var _ref14 = _slicedToArray(_ref13, 2),\n boolOp = _ref14[0],\n variable = _ref14[1];\n query.checks.push({\n type: Type.DATA_BOOL,\n field: cleanMetaChars(variable),\n operator: boolOp\n });\n }\n}, {\n name: 'metaCompare',\n query: true,\n regex: '\\\\[\\\\[\\\\s*(' + tokens.meta + ')\\\\s*(' + tokens.comparatorOp + ')\\\\s*(' + tokens.number + ')\\\\s*\\\\]\\\\]',\n populate: function populate(selector, query, _ref15) {\n var _ref16 = _slicedToArray(_ref15, 3),\n meta = _ref16[0],\n comparatorOp = _ref16[1],\n number = _ref16[2];\n query.checks.push({\n type: Type.META_COMPARE,\n field: cleanMetaChars(meta),\n operator: comparatorOp,\n value: parseFloat(number)\n });\n }\n}, {\n name: 'nextQuery',\n separator: true,\n regex: tokens.separator,\n populate: function populate(selector, query) {\n var currentSubject = selector.currentSubject;\n var edgeCount = selector.edgeCount;\n var compoundCount = selector.compoundCount;\n var lastQ = selector[selector.length - 1];\n if (currentSubject != null) {\n lastQ.subject = currentSubject;\n selector.currentSubject = null;\n }\n lastQ.edgeCount = edgeCount;\n lastQ.compoundCount = compoundCount;\n selector.edgeCount = 0;\n selector.compoundCount = 0;\n\n // go on to next query\n var nextQuery = selector[selector.length++] = newQuery();\n return nextQuery; // this is the new query to be filled by the following exprs\n }\n}, {\n name: 'directedEdge',\n separator: true,\n regex: tokens.directedEdge,\n populate: function populate(selector, query) {\n if (selector.currentSubject == null) {\n // undirected edge\n var edgeQuery = newQuery();\n var source = query;\n var target = newQuery();\n edgeQuery.checks.push({\n type: Type.DIRECTED_EDGE,\n source: source,\n target: target\n });\n\n // the query in the selector should be the edge rather than the source\n replaceLastQuery(selector, query, edgeQuery);\n selector.edgeCount++;\n\n // we're now populating the target query with expressions that follow\n return target;\n } else {\n // source/target\n var srcTgtQ = newQuery();\n var _source = query;\n var _target = newQuery();\n srcTgtQ.checks.push({\n type: Type.NODE_SOURCE,\n source: _source,\n target: _target\n });\n\n // the query in the selector should be the neighbourhood rather than the node\n replaceLastQuery(selector, query, srcTgtQ);\n selector.edgeCount++;\n return _target; // now populating the target with the following expressions\n }\n }\n}, {\n name: 'undirectedEdge',\n separator: true,\n regex: tokens.undirectedEdge,\n populate: function populate(selector, query) {\n if (selector.currentSubject == null) {\n // undirected edge\n var edgeQuery = newQuery();\n var source = query;\n var target = newQuery();\n edgeQuery.checks.push({\n type: Type.UNDIRECTED_EDGE,\n nodes: [source, target]\n });\n\n // the query in the selector should be the edge rather than the source\n replaceLastQuery(selector, query, edgeQuery);\n selector.edgeCount++;\n\n // we're now populating the target query with expressions that follow\n return target;\n } else {\n // neighbourhood\n var nhoodQ = newQuery();\n var node = query;\n var neighbor = newQuery();\n nhoodQ.checks.push({\n type: Type.NODE_NEIGHBOR,\n node: node,\n neighbor: neighbor\n });\n\n // the query in the selector should be the neighbourhood rather than the node\n replaceLastQuery(selector, query, nhoodQ);\n return neighbor; // now populating the neighbor with following expressions\n }\n }\n}, {\n name: 'child',\n separator: true,\n regex: tokens.child,\n populate: function populate(selector, query) {\n if (selector.currentSubject == null) {\n // default: child query\n var parentChildQuery = newQuery();\n var child = newQuery();\n var parent = selector[selector.length - 1];\n parentChildQuery.checks.push({\n type: Type.CHILD,\n parent: parent,\n child: child\n });\n\n // the query in the selector should be the '>' itself\n replaceLastQuery(selector, query, parentChildQuery);\n selector.compoundCount++;\n\n // we're now populating the child query with expressions that follow\n return child;\n } else if (selector.currentSubject === query) {\n // compound split query\n var compound = newQuery();\n var left = selector[selector.length - 1];\n var right = newQuery();\n var subject = newQuery();\n var _child = newQuery();\n var _parent = newQuery();\n\n // set up the root compound q\n compound.checks.push({\n type: Type.COMPOUND_SPLIT,\n left: left,\n right: right,\n subject: subject\n });\n\n // populate the subject and replace the q at the old spot (within left) with TRUE\n subject.checks = query.checks; // take the checks from the left\n query.checks = [{\n type: Type.TRUE\n }]; // checks under left refs the subject implicitly\n\n // set up the right q\n _parent.checks.push({\n type: Type.TRUE\n }); // parent implicitly refs the subject\n right.checks.push({\n type: Type.PARENT,\n // type is swapped on right side queries\n parent: _parent,\n child: _child // empty for now\n });\n replaceLastQuery(selector, left, compound);\n\n // update the ref since we moved things around for `query`\n selector.currentSubject = subject;\n selector.compoundCount++;\n return _child; // now populating the right side's child\n } else {\n // parent query\n // info for parent query\n var _parent2 = newQuery();\n var _child2 = newQuery();\n var pcQChecks = [{\n type: Type.PARENT,\n parent: _parent2,\n child: _child2\n }];\n\n // the parent-child query takes the place of the query previously being populated\n _parent2.checks = query.checks; // the previous query contains the checks for the parent\n query.checks = pcQChecks; // pc query takes over\n\n selector.compoundCount++;\n return _child2; // we're now populating the child\n }\n }\n}, {\n name: 'descendant',\n separator: true,\n regex: tokens.descendant,\n populate: function populate(selector, query) {\n if (selector.currentSubject == null) {\n // default: descendant query\n var ancChQuery = newQuery();\n var descendant = newQuery();\n var ancestor = selector[selector.length - 1];\n ancChQuery.checks.push({\n type: Type.DESCENDANT,\n ancestor: ancestor,\n descendant: descendant\n });\n\n // the query in the selector should be the '>' itself\n replaceLastQuery(selector, query, ancChQuery);\n selector.compoundCount++;\n\n // we're now populating the descendant query with expressions that follow\n return descendant;\n } else if (selector.currentSubject === query) {\n // compound split query\n var compound = newQuery();\n var left = selector[selector.length - 1];\n var right = newQuery();\n var subject = newQuery();\n var _descendant = newQuery();\n var _ancestor = newQuery();\n\n // set up the root compound q\n compound.checks.push({\n type: Type.COMPOUND_SPLIT,\n left: left,\n right: right,\n subject: subject\n });\n\n // populate the subject and replace the q at the old spot (within left) with TRUE\n subject.checks = query.checks; // take the checks from the left\n query.checks = [{\n type: Type.TRUE\n }]; // checks under left refs the subject implicitly\n\n // set up the right q\n _ancestor.checks.push({\n type: Type.TRUE\n }); // ancestor implicitly refs the subject\n right.checks.push({\n type: Type.ANCESTOR,\n // type is swapped on right side queries\n ancestor: _ancestor,\n descendant: _descendant // empty for now\n });\n replaceLastQuery(selector, left, compound);\n\n // update the ref since we moved things around for `query`\n selector.currentSubject = subject;\n selector.compoundCount++;\n return _descendant; // now populating the right side's descendant\n } else {\n // ancestor query\n // info for parent query\n var _ancestor2 = newQuery();\n var _descendant2 = newQuery();\n var adQChecks = [{\n type: Type.ANCESTOR,\n ancestor: _ancestor2,\n descendant: _descendant2\n }];\n\n // the parent-child query takes the place of the query previously being populated\n _ancestor2.checks = query.checks; // the previous query contains the checks for the parent\n query.checks = adQChecks; // pc query takes over\n\n selector.compoundCount++;\n return _descendant2; // we're now populating the child\n }\n }\n}, {\n name: 'subject',\n modifier: true,\n regex: tokens.subject,\n populate: function populate(selector, query) {\n if (selector.currentSubject != null && selector.currentSubject !== query) {\n warn('Redefinition of subject in selector `' + selector.toString() + '`');\n return false;\n }\n selector.currentSubject = query;\n var topQ = selector[selector.length - 1];\n var topChk = topQ.checks[0];\n var topType = topChk == null ? null : topChk.type;\n if (topType === Type.DIRECTED_EDGE) {\n // directed edge with subject on the target\n\n // change to target node check\n topChk.type = Type.NODE_TARGET;\n } else if (topType === Type.UNDIRECTED_EDGE) {\n // undirected edge with subject on the second node\n\n // change to neighbor check\n topChk.type = Type.NODE_NEIGHBOR;\n topChk.node = topChk.nodes[1]; // second node is subject\n topChk.neighbor = topChk.nodes[0];\n\n // clean up unused fields for new type\n topChk.nodes = null;\n }\n }\n}];\nexprs.forEach(function (e) {\n return e.regexObj = new RegExp('^' + e.regex);\n});\n\n/**\n * Of all the expressions, find the first match in the remaining text.\n * @param {string} remaining The remaining text to parse\n * @returns The matched expression and the newly remaining text `{ expr, match, name, remaining }`\n */\nvar consumeExpr = function consumeExpr(remaining) {\n var expr;\n var match;\n var name;\n for (var j = 0; j < exprs.length; j++) {\n var e = exprs[j];\n var n = e.name;\n var m = remaining.match(e.regexObj);\n if (m != null) {\n match = m;\n expr = e;\n name = n;\n var consumed = m[0];\n remaining = remaining.substring(consumed.length);\n break; // we've consumed one expr, so we can return now\n }\n }\n return {\n expr: expr,\n match: match,\n name: name,\n remaining: remaining\n };\n};\n\n/**\n * Consume all the leading whitespace\n * @param {string} remaining The text to consume\n * @returns The text with the leading whitespace removed\n */\nvar consumeWhitespace = function consumeWhitespace(remaining) {\n var match = remaining.match(/^\\s+/);\n if (match) {\n var consumed = match[0];\n remaining = remaining.substring(consumed.length);\n }\n return remaining;\n};\n\n/**\n * Parse the string and store the parsed representation in the Selector.\n * @param {string} selector The selector string\n * @returns `true` if the selector was successfully parsed, `false` otherwise\n */\nvar parse = function parse(selector) {\n var self = this;\n var remaining = self.inputText = selector;\n var currentQuery = self[0] = newQuery();\n self.length = 1;\n remaining = consumeWhitespace(remaining); // get rid of leading whitespace\n\n for (;;) {\n var exprInfo = consumeExpr(remaining);\n if (exprInfo.expr == null) {\n warn('The selector `' + selector + '`is invalid');\n return false;\n } else {\n var args = exprInfo.match.slice(1);\n\n // let the token populate the selector object in currentQuery\n var ret = exprInfo.expr.populate(self, currentQuery, args);\n if (ret === false) {\n return false; // exit if population failed\n } else if (ret != null) {\n currentQuery = ret; // change the current query to be filled if the expr specifies\n }\n }\n remaining = exprInfo.remaining;\n\n // we're done when there's nothing left to parse\n if (remaining.match(/^\\s*$/)) {\n break;\n }\n }\n var lastQ = self[self.length - 1];\n if (self.currentSubject != null) {\n lastQ.subject = self.currentSubject;\n }\n lastQ.edgeCount = self.edgeCount;\n lastQ.compoundCount = self.compoundCount;\n for (var i = 0; i < self.length; i++) {\n var q = self[i];\n\n // in future, this could potentially be allowed if there were operator precedence and detection of invalid combinations\n if (q.compoundCount > 0 && q.edgeCount > 0) {\n warn('The selector `' + selector + '` is invalid because it uses both a compound selector and an edge selector');\n return false;\n }\n if (q.edgeCount > 1) {\n warn('The selector `' + selector + '` is invalid because it uses multiple edge selectors');\n return false;\n } else if (q.edgeCount === 1) {\n warn('The selector `' + selector + '` is deprecated. Edge selectors do not take effect on changes to source and target nodes after an edge is added, for performance reasons. Use a class or data selector on edges instead, updating the class or data of an edge when your app detects a change in source or target nodes.');\n }\n }\n return true; // success\n};\n\n/**\n * Get the selector represented as a string. This value uses default formatting,\n * so things like spacing may differ from the input text passed to the constructor.\n * @returns {string} The selector string\n */\nvar toString = function toString() {\n if (this.toStringCache != null) {\n return this.toStringCache;\n }\n var clean = function clean(obj) {\n if (obj == null) {\n return '';\n } else {\n return obj;\n }\n };\n var cleanVal = function cleanVal(val) {\n if (string(val)) {\n return '\"' + val + '\"';\n } else {\n return clean(val);\n }\n };\n var space = function space(val) {\n return ' ' + val + ' ';\n };\n var checkToString = function checkToString(check, subject) {\n var type = check.type,\n value = check.value;\n switch (type) {\n case Type.GROUP:\n {\n var group = clean(value);\n return group.substring(0, group.length - 1);\n }\n case Type.DATA_COMPARE:\n {\n var field = check.field,\n operator = check.operator;\n return '[' + field + space(clean(operator)) + cleanVal(value) + ']';\n }\n case Type.DATA_BOOL:\n {\n var _operator = check.operator,\n _field = check.field;\n return '[' + clean(_operator) + _field + ']';\n }\n case Type.DATA_EXIST:\n {\n var _field2 = check.field;\n return '[' + _field2 + ']';\n }\n case Type.META_COMPARE:\n {\n var _operator2 = check.operator,\n _field3 = check.field;\n return '[[' + _field3 + space(clean(_operator2)) + cleanVal(value) + ']]';\n }\n case Type.STATE:\n {\n return value;\n }\n case Type.ID:\n {\n return '#' + value;\n }\n case Type.CLASS:\n {\n return '.' + value;\n }\n case Type.PARENT:\n case Type.CHILD:\n {\n return queryToString(check.parent, subject) + space('>') + queryToString(check.child, subject);\n }\n case Type.ANCESTOR:\n case Type.DESCENDANT:\n {\n return queryToString(check.ancestor, subject) + ' ' + queryToString(check.descendant, subject);\n }\n case Type.COMPOUND_SPLIT:\n {\n var lhs = queryToString(check.left, subject);\n var sub = queryToString(check.subject, subject);\n var rhs = queryToString(check.right, subject);\n return lhs + (lhs.length > 0 ? ' ' : '') + sub + rhs;\n }\n case Type.TRUE:\n {\n return '';\n }\n }\n };\n var queryToString = function queryToString(query, subject) {\n return query.checks.reduce(function (str, chk, i) {\n return str + (subject === query && i === 0 ? '$' : '') + checkToString(chk, subject);\n }, '');\n };\n var str = '';\n for (var i = 0; i < this.length; i++) {\n var query = this[i];\n str += queryToString(query, query.subject);\n if (this.length > 1 && i < this.length - 1) {\n str += ', ';\n }\n }\n this.toStringCache = str;\n return str;\n};\nvar parse$1 = {\n parse: parse,\n toString: toString\n};\n\nvar valCmp = function valCmp(fieldVal, operator, value) {\n var matches;\n var isFieldStr = string(fieldVal);\n var isFieldNum = number$1(fieldVal);\n var isValStr = string(value);\n var fieldStr, valStr;\n var caseInsensitive = false;\n var notExpr = false;\n var isIneqCmp = false;\n if (operator.indexOf('!') >= 0) {\n operator = operator.replace('!', '');\n notExpr = true;\n }\n if (operator.indexOf('@') >= 0) {\n operator = operator.replace('@', '');\n caseInsensitive = true;\n }\n if (isFieldStr || isValStr || caseInsensitive) {\n fieldStr = !isFieldStr && !isFieldNum ? '' : '' + fieldVal;\n valStr = '' + value;\n }\n\n // if we're doing a case insensitive comparison, then we're using a STRING comparison\n // even if we're comparing numbers\n if (caseInsensitive) {\n fieldVal = fieldStr = fieldStr.toLowerCase();\n value = valStr = valStr.toLowerCase();\n }\n switch (operator) {\n case '*=':\n matches = fieldStr.indexOf(valStr) >= 0;\n break;\n case '$=':\n matches = fieldStr.indexOf(valStr, fieldStr.length - valStr.length) >= 0;\n break;\n case '^=':\n matches = fieldStr.indexOf(valStr) === 0;\n break;\n case '=':\n matches = fieldVal === value;\n break;\n case '>':\n isIneqCmp = true;\n matches = fieldVal > value;\n break;\n case '>=':\n isIneqCmp = true;\n matches = fieldVal >= value;\n break;\n case '<':\n isIneqCmp = true;\n matches = fieldVal < value;\n break;\n case '<=':\n isIneqCmp = true;\n matches = fieldVal <= value;\n break;\n default:\n matches = false;\n break;\n }\n\n // apply the not op, but null vals for inequalities should always stay non-matching\n if (notExpr && (fieldVal != null || !isIneqCmp)) {\n matches = !matches;\n }\n return matches;\n};\nvar boolCmp = function boolCmp(fieldVal, operator) {\n switch (operator) {\n case '?':\n return fieldVal ? true : false;\n case '!':\n return fieldVal ? false : true;\n case '^':\n return fieldVal === undefined;\n }\n};\nvar existCmp = function existCmp(fieldVal) {\n return fieldVal !== undefined;\n};\nvar data$1 = function data(ele, field) {\n return ele.data(field);\n};\nvar meta = function meta(ele, field) {\n return ele[field]();\n};\n\n/** A lookup of `match(check, ele)` functions by `Type` int */\nvar match = [];\n\n/**\n * Returns whether the query matches for the element\n * @param query The `{ type, value, ... }` query object\n * @param ele The element to compare against\n*/\nvar matches$1 = function matches(query, ele) {\n return query.checks.every(function (chk) {\n return match[chk.type](chk, ele);\n });\n};\nmatch[Type.GROUP] = function (check, ele) {\n var group = check.value;\n return group === '*' || group === ele.group();\n};\nmatch[Type.STATE] = function (check, ele) {\n var stateSelector = check.value;\n return stateSelectorMatches(stateSelector, ele);\n};\nmatch[Type.ID] = function (check, ele) {\n var id = check.value;\n return ele.id() === id;\n};\nmatch[Type.CLASS] = function (check, ele) {\n var cls = check.value;\n return ele.hasClass(cls);\n};\nmatch[Type.META_COMPARE] = function (check, ele) {\n var field = check.field,\n operator = check.operator,\n value = check.value;\n return valCmp(meta(ele, field), operator, value);\n};\nmatch[Type.DATA_COMPARE] = function (check, ele) {\n var field = check.field,\n operator = check.operator,\n value = check.value;\n return valCmp(data$1(ele, field), operator, value);\n};\nmatch[Type.DATA_BOOL] = function (check, ele) {\n var field = check.field,\n operator = check.operator;\n return boolCmp(data$1(ele, field), operator);\n};\nmatch[Type.DATA_EXIST] = function (check, ele) {\n var field = check.field;\n check.operator;\n return existCmp(data$1(ele, field));\n};\nmatch[Type.UNDIRECTED_EDGE] = function (check, ele) {\n var qA = check.nodes[0];\n var qB = check.nodes[1];\n var src = ele.source();\n var tgt = ele.target();\n return matches$1(qA, src) && matches$1(qB, tgt) || matches$1(qB, src) && matches$1(qA, tgt);\n};\nmatch[Type.NODE_NEIGHBOR] = function (check, ele) {\n return matches$1(check.node, ele) && ele.neighborhood().some(function (n) {\n return n.isNode() && matches$1(check.neighbor, n);\n });\n};\nmatch[Type.DIRECTED_EDGE] = function (check, ele) {\n return matches$1(check.source, ele.source()) && matches$1(check.target, ele.target());\n};\nmatch[Type.NODE_SOURCE] = function (check, ele) {\n return matches$1(check.source, ele) && ele.outgoers().some(function (n) {\n return n.isNode() && matches$1(check.target, n);\n });\n};\nmatch[Type.NODE_TARGET] = function (check, ele) {\n return matches$1(check.target, ele) && ele.incomers().some(function (n) {\n return n.isNode() && matches$1(check.source, n);\n });\n};\nmatch[Type.CHILD] = function (check, ele) {\n return matches$1(check.child, ele) && matches$1(check.parent, ele.parent());\n};\nmatch[Type.PARENT] = function (check, ele) {\n return matches$1(check.parent, ele) && ele.children().some(function (c) {\n return matches$1(check.child, c);\n });\n};\nmatch[Type.DESCENDANT] = function (check, ele) {\n return matches$1(check.descendant, ele) && ele.ancestors().some(function (a) {\n return matches$1(check.ancestor, a);\n });\n};\nmatch[Type.ANCESTOR] = function (check, ele) {\n return matches$1(check.ancestor, ele) && ele.descendants().some(function (d) {\n return matches$1(check.descendant, d);\n });\n};\nmatch[Type.COMPOUND_SPLIT] = function (check, ele) {\n return matches$1(check.subject, ele) && matches$1(check.left, ele) && matches$1(check.right, ele);\n};\nmatch[Type.TRUE] = function () {\n return true;\n};\nmatch[Type.COLLECTION] = function (check, ele) {\n var collection = check.value;\n return collection.has(ele);\n};\nmatch[Type.FILTER] = function (check, ele) {\n var filter = check.value;\n return filter(ele);\n};\n\n// filter an existing collection\nvar filter = function filter(collection) {\n var self = this;\n\n // for 1 id #foo queries, just get the element\n if (self.length === 1 && self[0].checks.length === 1 && self[0].checks[0].type === Type.ID) {\n return collection.getElementById(self[0].checks[0].value).collection();\n }\n var selectorFunction = function selectorFunction(element) {\n for (var j = 0; j < self.length; j++) {\n var query = self[j];\n if (matches$1(query, element)) {\n return true;\n }\n }\n return false;\n };\n if (self.text() == null) {\n selectorFunction = function selectorFunction() {\n return true;\n };\n }\n return collection.filter(selectorFunction);\n}; // filter\n\n// does selector match a single element?\nvar matches = function matches(ele) {\n var self = this;\n for (var j = 0; j < self.length; j++) {\n var query = self[j];\n if (matches$1(query, ele)) {\n return true;\n }\n }\n return false;\n}; // matches\n\nvar matching = {\n matches: matches,\n filter: filter\n};\n\nvar Selector = function Selector(selector) {\n this.inputText = selector;\n this.currentSubject = null;\n this.compoundCount = 0;\n this.edgeCount = 0;\n this.length = 0;\n if (selector == null || string(selector) && selector.match(/^\\s*$/)) ; else if (elementOrCollection(selector)) {\n this.addQuery({\n checks: [{\n type: Type.COLLECTION,\n value: selector.collection()\n }]\n });\n } else if (fn$6(selector)) {\n this.addQuery({\n checks: [{\n type: Type.FILTER,\n value: selector\n }]\n });\n } else if (string(selector)) {\n if (!this.parse(selector)) {\n this.invalid = true;\n }\n } else {\n error('A selector must be created from a string; found ');\n }\n};\nvar selfn = Selector.prototype;\n[parse$1, matching].forEach(function (p) {\n return extend(selfn, p);\n});\nselfn.text = function () {\n return this.inputText;\n};\nselfn.size = function () {\n return this.length;\n};\nselfn.eq = function (i) {\n return this[i];\n};\nselfn.sameText = function (otherSel) {\n return !this.invalid && !otherSel.invalid && this.text() === otherSel.text();\n};\nselfn.addQuery = function (q) {\n this[this.length++] = q;\n};\nselfn.selector = selfn.toString;\n\nvar elesfn$g = {\n allAre: function allAre(selector) {\n var selObj = new Selector(selector);\n return this.every(function (ele) {\n return selObj.matches(ele);\n });\n },\n is: function is(selector) {\n var selObj = new Selector(selector);\n return this.some(function (ele) {\n return selObj.matches(ele);\n });\n },\n some: function some(fn, thisArg) {\n for (var i = 0; i < this.length; i++) {\n var ret = !thisArg ? fn(this[i], i, this) : fn.apply(thisArg, [this[i], i, this]);\n if (ret) {\n return true;\n }\n }\n return false;\n },\n every: function every(fn, thisArg) {\n for (var i = 0; i < this.length; i++) {\n var ret = !thisArg ? fn(this[i], i, this) : fn.apply(thisArg, [this[i], i, this]);\n if (!ret) {\n return false;\n }\n }\n return true;\n },\n same: function same(collection) {\n // cheap collection ref check\n if (this === collection) {\n return true;\n }\n collection = this.cy().collection(collection);\n var thisLength = this.length;\n var collectionLength = collection.length;\n\n // cheap length check\n if (thisLength !== collectionLength) {\n return false;\n }\n\n // cheap element ref check\n if (thisLength === 1) {\n return this[0] === collection[0];\n }\n return this.every(function (ele) {\n return collection.hasElementWithId(ele.id());\n });\n },\n anySame: function anySame(collection) {\n collection = this.cy().collection(collection);\n return this.some(function (ele) {\n return collection.hasElementWithId(ele.id());\n });\n },\n allAreNeighbors: function allAreNeighbors(collection) {\n collection = this.cy().collection(collection);\n var nhood = this.neighborhood();\n return collection.every(function (ele) {\n return nhood.hasElementWithId(ele.id());\n });\n },\n contains: function contains(collection) {\n collection = this.cy().collection(collection);\n var self = this;\n return collection.every(function (ele) {\n return self.hasElementWithId(ele.id());\n });\n }\n};\nelesfn$g.allAreNeighbours = elesfn$g.allAreNeighbors;\nelesfn$g.has = elesfn$g.contains;\nelesfn$g.equal = elesfn$g.equals = elesfn$g.same;\n\nvar cache = function cache(fn, name) {\n return function traversalCache(arg1, arg2, arg3, arg4) {\n var selectorOrEles = arg1;\n var eles = this;\n var key;\n if (selectorOrEles == null) {\n key = '';\n } else if (elementOrCollection(selectorOrEles) && selectorOrEles.length === 1) {\n key = selectorOrEles.id();\n }\n if (eles.length === 1 && key) {\n var _p = eles[0]._private;\n var tch = _p.traversalCache = _p.traversalCache || {};\n var ch = tch[name] = tch[name] || [];\n var hash = hashString(key);\n var cacheHit = ch[hash];\n if (cacheHit) {\n return cacheHit;\n } else {\n return ch[hash] = fn.call(eles, arg1, arg2, arg3, arg4);\n }\n } else {\n return fn.call(eles, arg1, arg2, arg3, arg4);\n }\n };\n};\n\nvar elesfn$f = {\n parent: function parent(selector) {\n var parents = [];\n\n // optimisation for single ele call\n if (this.length === 1) {\n var parent = this[0]._private.parent;\n if (parent) {\n return parent;\n }\n }\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n var _parent = ele._private.parent;\n if (_parent) {\n parents.push(_parent);\n }\n }\n return this.spawn(parents, true).filter(selector);\n },\n parents: function parents(selector) {\n var parents = [];\n var eles = this.parent();\n while (eles.nonempty()) {\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n parents.push(ele);\n }\n eles = eles.parent();\n }\n return this.spawn(parents, true).filter(selector);\n },\n commonAncestors: function commonAncestors(selector) {\n var ancestors;\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n var parents = ele.parents();\n ancestors = ancestors || parents;\n ancestors = ancestors.intersect(parents); // current list must be common with current ele parents set\n }\n return ancestors.filter(selector);\n },\n orphans: function orphans(selector) {\n return this.stdFilter(function (ele) {\n return ele.isOrphan();\n }).filter(selector);\n },\n nonorphans: function nonorphans(selector) {\n return this.stdFilter(function (ele) {\n return ele.isChild();\n }).filter(selector);\n },\n children: cache(function (selector) {\n var children = [];\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n var eleChildren = ele._private.children;\n for (var j = 0; j < eleChildren.length; j++) {\n children.push(eleChildren[j]);\n }\n }\n return this.spawn(children, true).filter(selector);\n }, 'children'),\n siblings: function siblings(selector) {\n return this.parent().children().not(this).filter(selector);\n },\n isParent: function isParent() {\n var ele = this[0];\n if (ele) {\n return ele.isNode() && ele._private.children.length !== 0;\n }\n },\n isChildless: function isChildless() {\n var ele = this[0];\n if (ele) {\n return ele.isNode() && ele._private.children.length === 0;\n }\n },\n isChild: function isChild() {\n var ele = this[0];\n if (ele) {\n return ele.isNode() && ele._private.parent != null;\n }\n },\n isOrphan: function isOrphan() {\n var ele = this[0];\n if (ele) {\n return ele.isNode() && ele._private.parent == null;\n }\n },\n descendants: function descendants(selector) {\n var elements = [];\n function add(eles) {\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n elements.push(ele);\n if (ele.children().nonempty()) {\n add(ele.children());\n }\n }\n }\n add(this.children());\n return this.spawn(elements, true).filter(selector);\n }\n};\nfunction forEachCompound(eles, fn, includeSelf, recursiveStep) {\n var q = [];\n var did = new Set$1();\n var cy = eles.cy();\n var hasCompounds = cy.hasCompoundNodes();\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n if (includeSelf) {\n q.push(ele);\n } else if (hasCompounds) {\n recursiveStep(q, did, ele);\n }\n }\n while (q.length > 0) {\n var _ele = q.shift();\n fn(_ele);\n did.add(_ele.id());\n if (hasCompounds) {\n recursiveStep(q, did, _ele);\n }\n }\n return eles;\n}\nfunction addChildren(q, did, ele) {\n if (ele.isParent()) {\n var children = ele._private.children;\n for (var i = 0; i < children.length; i++) {\n var child = children[i];\n if (!did.has(child.id())) {\n q.push(child);\n }\n }\n }\n}\n\n// very efficient version of eles.add( eles.descendants() ).forEach()\n// for internal use\nelesfn$f.forEachDown = function (fn) {\n var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n return forEachCompound(this, fn, includeSelf, addChildren);\n};\nfunction addParent(q, did, ele) {\n if (ele.isChild()) {\n var parent = ele._private.parent;\n if (!did.has(parent.id())) {\n q.push(parent);\n }\n }\n}\nelesfn$f.forEachUp = function (fn) {\n var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n return forEachCompound(this, fn, includeSelf, addParent);\n};\nfunction addParentAndChildren(q, did, ele) {\n addParent(q, did, ele);\n addChildren(q, did, ele);\n}\nelesfn$f.forEachUpAndDown = function (fn) {\n var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n return forEachCompound(this, fn, includeSelf, addParentAndChildren);\n};\n\n// aliases\nelesfn$f.ancestors = elesfn$f.parents;\n\nvar fn$5, elesfn$e;\nfn$5 = elesfn$e = {\n data: define.data({\n field: 'data',\n bindingEvent: 'data',\n allowBinding: true,\n allowSetting: true,\n settingEvent: 'data',\n settingTriggersEvent: true,\n triggerFnName: 'trigger',\n allowGetting: true,\n immutableKeys: {\n 'id': true,\n 'source': true,\n 'target': true,\n 'parent': true\n },\n updateStyle: true\n }),\n removeData: define.removeData({\n field: 'data',\n event: 'data',\n triggerFnName: 'trigger',\n triggerEvent: true,\n immutableKeys: {\n 'id': true,\n 'source': true,\n 'target': true,\n 'parent': true\n },\n updateStyle: true\n }),\n scratch: define.data({\n field: 'scratch',\n bindingEvent: 'scratch',\n allowBinding: true,\n allowSetting: true,\n settingEvent: 'scratch',\n settingTriggersEvent: true,\n triggerFnName: 'trigger',\n allowGetting: true,\n updateStyle: true\n }),\n removeScratch: define.removeData({\n field: 'scratch',\n event: 'scratch',\n triggerFnName: 'trigger',\n triggerEvent: true,\n updateStyle: true\n }),\n rscratch: define.data({\n field: 'rscratch',\n allowBinding: false,\n allowSetting: true,\n settingTriggersEvent: false,\n allowGetting: true\n }),\n removeRscratch: define.removeData({\n field: 'rscratch',\n triggerEvent: false\n }),\n id: function id() {\n var ele = this[0];\n if (ele) {\n return ele._private.data.id;\n }\n }\n};\n\n// aliases\nfn$5.attr = fn$5.data;\nfn$5.removeAttr = fn$5.removeData;\nvar data = elesfn$e;\n\nvar elesfn$d = {};\nfunction defineDegreeFunction(callback) {\n return function (includeLoops) {\n var self = this;\n if (includeLoops === undefined) {\n includeLoops = true;\n }\n if (self.length === 0) {\n return;\n }\n if (self.isNode() && !self.removed()) {\n var degree = 0;\n var node = self[0];\n var connectedEdges = node._private.edges;\n for (var i = 0; i < connectedEdges.length; i++) {\n var edge = connectedEdges[i];\n if (!includeLoops && edge.isLoop()) {\n continue;\n }\n degree += callback(node, edge);\n }\n return degree;\n } else {\n return;\n }\n };\n}\nextend(elesfn$d, {\n degree: defineDegreeFunction(function (node, edge) {\n if (edge.source().same(edge.target())) {\n return 2;\n } else {\n return 1;\n }\n }),\n indegree: defineDegreeFunction(function (node, edge) {\n if (edge.target().same(node)) {\n return 1;\n } else {\n return 0;\n }\n }),\n outdegree: defineDegreeFunction(function (node, edge) {\n if (edge.source().same(node)) {\n return 1;\n } else {\n return 0;\n }\n })\n});\nfunction defineDegreeBoundsFunction(degreeFn, callback) {\n return function (includeLoops) {\n var ret;\n var nodes = this.nodes();\n for (var i = 0; i < nodes.length; i++) {\n var ele = nodes[i];\n var degree = ele[degreeFn](includeLoops);\n if (degree !== undefined && (ret === undefined || callback(degree, ret))) {\n ret = degree;\n }\n }\n return ret;\n };\n}\nextend(elesfn$d, {\n minDegree: defineDegreeBoundsFunction('degree', function (degree, min) {\n return degree < min;\n }),\n maxDegree: defineDegreeBoundsFunction('degree', function (degree, max) {\n return degree > max;\n }),\n minIndegree: defineDegreeBoundsFunction('indegree', function (degree, min) {\n return degree < min;\n }),\n maxIndegree: defineDegreeBoundsFunction('indegree', function (degree, max) {\n return degree > max;\n }),\n minOutdegree: defineDegreeBoundsFunction('outdegree', function (degree, min) {\n return degree < min;\n }),\n maxOutdegree: defineDegreeBoundsFunction('outdegree', function (degree, max) {\n return degree > max;\n })\n});\nextend(elesfn$d, {\n totalDegree: function totalDegree(includeLoops) {\n var total = 0;\n var nodes = this.nodes();\n for (var i = 0; i < nodes.length; i++) {\n total += nodes[i].degree(includeLoops);\n }\n return total;\n }\n});\n\nvar fn$4, elesfn$c;\nvar beforePositionSet = function beforePositionSet(eles, newPos, silent) {\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n if (!ele.locked()) {\n var oldPos = ele._private.position;\n var delta = {\n x: newPos.x != null ? newPos.x - oldPos.x : 0,\n y: newPos.y != null ? newPos.y - oldPos.y : 0\n };\n if (ele.isParent() && !(delta.x === 0 && delta.y === 0)) {\n ele.children().shift(delta, silent);\n }\n ele.dirtyBoundingBoxCache();\n }\n }\n};\nvar positionDef = {\n field: 'position',\n bindingEvent: 'position',\n allowBinding: true,\n allowSetting: true,\n settingEvent: 'position',\n settingTriggersEvent: true,\n triggerFnName: 'emitAndNotify',\n allowGetting: true,\n validKeys: ['x', 'y'],\n beforeGet: function beforeGet(ele) {\n ele.updateCompoundBounds();\n },\n beforeSet: function beforeSet(eles, newPos) {\n beforePositionSet(eles, newPos, false);\n },\n onSet: function onSet(eles) {\n eles.dirtyCompoundBoundsCache();\n },\n canSet: function canSet(ele) {\n return !ele.locked();\n }\n};\nfn$4 = elesfn$c = {\n position: define.data(positionDef),\n // position but no notification to renderer\n silentPosition: define.data(extend({}, positionDef, {\n allowBinding: false,\n allowSetting: true,\n settingTriggersEvent: false,\n allowGetting: false,\n beforeSet: function beforeSet(eles, newPos) {\n beforePositionSet(eles, newPos, true);\n },\n onSet: function onSet(eles) {\n eles.dirtyCompoundBoundsCache();\n }\n })),\n positions: function positions(pos, silent) {\n if (plainObject(pos)) {\n if (silent) {\n this.silentPosition(pos);\n } else {\n this.position(pos);\n }\n } else if (fn$6(pos)) {\n var _fn = pos;\n var cy = this.cy();\n cy.startBatch();\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n var _pos = undefined;\n if (_pos = _fn(ele, i)) {\n if (silent) {\n ele.silentPosition(_pos);\n } else {\n ele.position(_pos);\n }\n }\n }\n cy.endBatch();\n }\n return this; // chaining\n },\n silentPositions: function silentPositions(pos) {\n return this.positions(pos, true);\n },\n shift: function shift(dim, val, silent) {\n var delta;\n if (plainObject(dim)) {\n delta = {\n x: number$1(dim.x) ? dim.x : 0,\n y: number$1(dim.y) ? dim.y : 0\n };\n silent = val;\n } else if (string(dim) && number$1(val)) {\n delta = {\n x: 0,\n y: 0\n };\n delta[dim] = val;\n }\n if (delta != null) {\n var cy = this.cy();\n cy.startBatch();\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n\n // exclude any node that is a descendant of the calling collection\n if (cy.hasCompoundNodes() && ele.isChild() && ele.ancestors().anySame(this)) {\n continue;\n }\n var pos = ele.position();\n var newPos = {\n x: pos.x + delta.x,\n y: pos.y + delta.y\n };\n if (silent) {\n ele.silentPosition(newPos);\n } else {\n ele.position(newPos);\n }\n }\n cy.endBatch();\n }\n return this;\n },\n silentShift: function silentShift(dim, val) {\n if (plainObject(dim)) {\n this.shift(dim, true);\n } else if (string(dim) && number$1(val)) {\n this.shift(dim, val, true);\n }\n return this;\n },\n // get/set the rendered (i.e. on screen) positon of the element\n renderedPosition: function renderedPosition(dim, val) {\n var ele = this[0];\n var cy = this.cy();\n var zoom = cy.zoom();\n var pan = cy.pan();\n var rpos = plainObject(dim) ? dim : undefined;\n var setting = rpos !== undefined || val !== undefined && string(dim);\n if (ele && ele.isNode()) {\n // must have an element and must be a node to return position\n if (setting) {\n for (var i = 0; i < this.length; i++) {\n var _ele = this[i];\n if (val !== undefined) {\n // set one dimension\n _ele.position(dim, (val - pan[dim]) / zoom);\n } else if (rpos !== undefined) {\n // set whole position\n _ele.position(renderedToModelPosition(rpos, zoom, pan));\n }\n }\n } else {\n // getting\n var pos = ele.position();\n rpos = modelToRenderedPosition$1(pos, zoom, pan);\n if (dim === undefined) {\n // then return the whole rendered position\n return rpos;\n } else {\n // then return the specified dimension\n return rpos[dim];\n }\n }\n } else if (!setting) {\n return undefined; // for empty collection case\n }\n return this; // chaining\n },\n // get/set the position relative to the parent\n relativePosition: function relativePosition(dim, val) {\n var ele = this[0];\n var cy = this.cy();\n var ppos = plainObject(dim) ? dim : undefined;\n var setting = ppos !== undefined || val !== undefined && string(dim);\n var hasCompoundNodes = cy.hasCompoundNodes();\n if (ele && ele.isNode()) {\n // must have an element and must be a node to return position\n if (setting) {\n for (var i = 0; i < this.length; i++) {\n var _ele2 = this[i];\n var parent = hasCompoundNodes ? _ele2.parent() : null;\n var hasParent = parent && parent.length > 0;\n var relativeToParent = hasParent;\n if (hasParent) {\n parent = parent[0];\n }\n var origin = relativeToParent ? parent.position() : {\n x: 0,\n y: 0\n };\n if (val !== undefined) {\n // set one dimension\n _ele2.position(dim, val + origin[dim]);\n } else if (ppos !== undefined) {\n // set whole position\n _ele2.position({\n x: ppos.x + origin.x,\n y: ppos.y + origin.y\n });\n }\n }\n } else {\n // getting\n var pos = ele.position();\n var _parent = hasCompoundNodes ? ele.parent() : null;\n var _hasParent = _parent && _parent.length > 0;\n var _relativeToParent = _hasParent;\n if (_hasParent) {\n _parent = _parent[0];\n }\n var _origin = _relativeToParent ? _parent.position() : {\n x: 0,\n y: 0\n };\n ppos = {\n x: pos.x - _origin.x,\n y: pos.y - _origin.y\n };\n if (dim === undefined) {\n // then return the whole rendered position\n return ppos;\n } else {\n // then return the specified dimension\n return ppos[dim];\n }\n }\n } else if (!setting) {\n return undefined; // for empty collection case\n }\n return this; // chaining\n }\n};\n\n// aliases\nfn$4.modelPosition = fn$4.point = fn$4.position;\nfn$4.modelPositions = fn$4.points = fn$4.positions;\nfn$4.renderedPoint = fn$4.renderedPosition;\nfn$4.relativePoint = fn$4.relativePosition;\nvar position = elesfn$c;\n\nvar fn$3, elesfn$b;\nfn$3 = elesfn$b = {};\nelesfn$b.renderedBoundingBox = function (options) {\n var bb = this.boundingBox(options);\n var cy = this.cy();\n var zoom = cy.zoom();\n var pan = cy.pan();\n var x1 = bb.x1 * zoom + pan.x;\n var x2 = bb.x2 * zoom + pan.x;\n var y1 = bb.y1 * zoom + pan.y;\n var y2 = bb.y2 * zoom + pan.y;\n return {\n x1: x1,\n x2: x2,\n y1: y1,\n y2: y2,\n w: x2 - x1,\n h: y2 - y1\n };\n};\nelesfn$b.dirtyCompoundBoundsCache = function () {\n var silent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n var cy = this.cy();\n if (!cy.styleEnabled() || !cy.hasCompoundNodes()) {\n return this;\n }\n this.forEachUp(function (ele) {\n if (ele.isParent()) {\n var _p = ele._private;\n _p.compoundBoundsClean = false;\n _p.bbCache = null;\n if (!silent) {\n ele.emitAndNotify('bounds');\n }\n }\n });\n return this;\n};\nelesfn$b.updateCompoundBounds = function () {\n var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n var cy = this.cy();\n\n // not possible to do on non-compound graphs or with the style disabled\n if (!cy.styleEnabled() || !cy.hasCompoundNodes()) {\n return this;\n }\n\n // save cycles when batching -- but bounds will be stale (or not exist yet)\n if (!force && cy.batching()) {\n return this;\n }\n function update(parent) {\n if (!parent.isParent()) {\n return;\n }\n var _p = parent._private;\n var children = parent.children();\n var includeLabels = parent.pstyle('compound-sizing-wrt-labels').value === 'include';\n var min = {\n width: {\n val: parent.pstyle('min-width').pfValue,\n left: parent.pstyle('min-width-bias-left'),\n right: parent.pstyle('min-width-bias-right')\n },\n height: {\n val: parent.pstyle('min-height').pfValue,\n top: parent.pstyle('min-height-bias-top'),\n bottom: parent.pstyle('min-height-bias-bottom')\n }\n };\n var bb = children.boundingBox({\n includeLabels: includeLabels,\n includeOverlays: false,\n // updating the compound bounds happens outside of the regular\n // cache cycle (i.e. before fired events)\n useCache: false\n });\n var pos = _p.position;\n\n // if children take up zero area then keep position and fall back on stylesheet w/h\n if (bb.w === 0 || bb.h === 0) {\n bb = {\n w: parent.pstyle('width').pfValue,\n h: parent.pstyle('height').pfValue\n };\n bb.x1 = pos.x - bb.w / 2;\n bb.x2 = pos.x + bb.w / 2;\n bb.y1 = pos.y - bb.h / 2;\n bb.y2 = pos.y + bb.h / 2;\n }\n function computeBiasValues(propDiff, propBias, propBiasComplement) {\n var biasDiff = 0;\n var biasComplementDiff = 0;\n var biasTotal = propBias + propBiasComplement;\n if (propDiff > 0 && biasTotal > 0) {\n biasDiff = propBias / biasTotal * propDiff;\n biasComplementDiff = propBiasComplement / biasTotal * propDiff;\n }\n return {\n biasDiff: biasDiff,\n biasComplementDiff: biasComplementDiff\n };\n }\n function computePaddingValues(width, height, paddingObject, relativeTo) {\n // Assuming percentage is number from 0 to 1\n if (paddingObject.units === '%') {\n switch (relativeTo) {\n case 'width':\n return width > 0 ? paddingObject.pfValue * width : 0;\n case 'height':\n return height > 0 ? paddingObject.pfValue * height : 0;\n case 'average':\n return width > 0 && height > 0 ? paddingObject.pfValue * (width + height) / 2 : 0;\n case 'min':\n return width > 0 && height > 0 ? width > height ? paddingObject.pfValue * height : paddingObject.pfValue * width : 0;\n case 'max':\n return width > 0 && height > 0 ? width > height ? paddingObject.pfValue * width : paddingObject.pfValue * height : 0;\n default:\n return 0;\n }\n } else if (paddingObject.units === 'px') {\n return paddingObject.pfValue;\n } else {\n return 0;\n }\n }\n var leftVal = min.width.left.value;\n if (min.width.left.units === 'px' && min.width.val > 0) {\n leftVal = leftVal * 100 / min.width.val;\n }\n var rightVal = min.width.right.value;\n if (min.width.right.units === 'px' && min.width.val > 0) {\n rightVal = rightVal * 100 / min.width.val;\n }\n var topVal = min.height.top.value;\n if (min.height.top.units === 'px' && min.height.val > 0) {\n topVal = topVal * 100 / min.height.val;\n }\n var bottomVal = min.height.bottom.value;\n if (min.height.bottom.units === 'px' && min.height.val > 0) {\n bottomVal = bottomVal * 100 / min.height.val;\n }\n var widthBiasDiffs = computeBiasValues(min.width.val - bb.w, leftVal, rightVal);\n var diffLeft = widthBiasDiffs.biasDiff;\n var diffRight = widthBiasDiffs.biasComplementDiff;\n var heightBiasDiffs = computeBiasValues(min.height.val - bb.h, topVal, bottomVal);\n var diffTop = heightBiasDiffs.biasDiff;\n var diffBottom = heightBiasDiffs.biasComplementDiff;\n _p.autoPadding = computePaddingValues(bb.w, bb.h, parent.pstyle('padding'), parent.pstyle('padding-relative-to').value);\n _p.autoWidth = Math.max(bb.w, min.width.val);\n pos.x = (-diffLeft + bb.x1 + bb.x2 + diffRight) / 2;\n _p.autoHeight = Math.max(bb.h, min.height.val);\n pos.y = (-diffTop + bb.y1 + bb.y2 + diffBottom) / 2;\n }\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n var _p = ele._private;\n if (!_p.compoundBoundsClean || force) {\n update(ele);\n if (!cy.batching()) {\n _p.compoundBoundsClean = true;\n }\n }\n }\n return this;\n};\nvar noninf = function noninf(x) {\n if (x === Infinity || x === -Infinity) {\n return 0;\n }\n return x;\n};\nvar updateBounds = function updateBounds(b, x1, y1, x2, y2) {\n // don't update with zero area boxes\n if (x2 - x1 === 0 || y2 - y1 === 0) {\n return;\n }\n\n // don't update with null dim\n if (x1 == null || y1 == null || x2 == null || y2 == null) {\n return;\n }\n b.x1 = x1 < b.x1 ? x1 : b.x1;\n b.x2 = x2 > b.x2 ? x2 : b.x2;\n b.y1 = y1 < b.y1 ? y1 : b.y1;\n b.y2 = y2 > b.y2 ? y2 : b.y2;\n b.w = b.x2 - b.x1;\n b.h = b.y2 - b.y1;\n};\nvar updateBoundsFromBox = function updateBoundsFromBox(b, b2) {\n if (b2 == null) {\n return b;\n }\n return updateBounds(b, b2.x1, b2.y1, b2.x2, b2.y2);\n};\nvar prefixedProperty = function prefixedProperty(obj, field, prefix) {\n return getPrefixedProperty(obj, field, prefix);\n};\nvar updateBoundsFromArrow = function updateBoundsFromArrow(bounds, ele, prefix) {\n if (ele.cy().headless()) {\n return;\n }\n var _p = ele._private;\n var rstyle = _p.rstyle;\n var halfArW = rstyle.arrowWidth / 2;\n var arrowType = ele.pstyle(prefix + '-arrow-shape').value;\n var x;\n var y;\n if (arrowType !== 'none') {\n if (prefix === 'source') {\n x = rstyle.srcX;\n y = rstyle.srcY;\n } else if (prefix === 'target') {\n x = rstyle.tgtX;\n y = rstyle.tgtY;\n } else {\n x = rstyle.midX;\n y = rstyle.midY;\n }\n\n // always store the individual arrow bounds\n var bbs = _p.arrowBounds = _p.arrowBounds || {};\n var bb = bbs[prefix] = bbs[prefix] || {};\n bb.x1 = x - halfArW;\n bb.y1 = y - halfArW;\n bb.x2 = x + halfArW;\n bb.y2 = y + halfArW;\n bb.w = bb.x2 - bb.x1;\n bb.h = bb.y2 - bb.y1;\n expandBoundingBox(bb, 1);\n updateBounds(bounds, bb.x1, bb.y1, bb.x2, bb.y2);\n }\n};\nvar updateBoundsFromLabel = function updateBoundsFromLabel(bounds, ele, prefix) {\n if (ele.cy().headless()) {\n return;\n }\n var prefixDash;\n if (prefix) {\n prefixDash = prefix + '-';\n } else {\n prefixDash = '';\n }\n var _p = ele._private;\n var rstyle = _p.rstyle;\n var label = ele.pstyle(prefixDash + 'label').strValue;\n if (label) {\n var halign = ele.pstyle('text-halign');\n var valign = ele.pstyle('text-valign');\n var labelWidth = prefixedProperty(rstyle, 'labelWidth', prefix);\n var labelHeight = prefixedProperty(rstyle, 'labelHeight', prefix);\n var labelX = prefixedProperty(rstyle, 'labelX', prefix);\n var labelY = prefixedProperty(rstyle, 'labelY', prefix);\n var marginX = ele.pstyle(prefixDash + 'text-margin-x').pfValue;\n var marginY = ele.pstyle(prefixDash + 'text-margin-y').pfValue;\n var isEdge = ele.isEdge();\n var rotation = ele.pstyle(prefixDash + 'text-rotation');\n var outlineWidth = ele.pstyle('text-outline-width').pfValue;\n var borderWidth = ele.pstyle('text-border-width').pfValue;\n var halfBorderWidth = borderWidth / 2;\n var padding = ele.pstyle('text-background-padding').pfValue;\n var marginOfError = 2; // expand to work around browser dimension inaccuracies\n\n var lh = labelHeight;\n var lw = labelWidth;\n var lw_2 = lw / 2;\n var lh_2 = lh / 2;\n var lx1, lx2, ly1, ly2;\n if (isEdge) {\n lx1 = labelX - lw_2;\n lx2 = labelX + lw_2;\n ly1 = labelY - lh_2;\n ly2 = labelY + lh_2;\n } else {\n switch (halign.value) {\n case 'left':\n lx1 = labelX - lw;\n lx2 = labelX;\n break;\n case 'center':\n lx1 = labelX - lw_2;\n lx2 = labelX + lw_2;\n break;\n case 'right':\n lx1 = labelX;\n lx2 = labelX + lw;\n break;\n }\n switch (valign.value) {\n case 'top':\n ly1 = labelY - lh;\n ly2 = labelY;\n break;\n case 'center':\n ly1 = labelY - lh_2;\n ly2 = labelY + lh_2;\n break;\n case 'bottom':\n ly1 = labelY;\n ly2 = labelY + lh;\n break;\n }\n }\n\n // shift by margin and expand by outline and border\n var leftPad = marginX - Math.max(outlineWidth, halfBorderWidth) - padding - marginOfError;\n var rightPad = marginX + Math.max(outlineWidth, halfBorderWidth) + padding + marginOfError;\n var topPad = marginY - Math.max(outlineWidth, halfBorderWidth) - padding - marginOfError;\n var botPad = marginY + Math.max(outlineWidth, halfBorderWidth) + padding + marginOfError;\n lx1 += leftPad;\n lx2 += rightPad;\n ly1 += topPad;\n ly2 += botPad;\n\n // always store the unrotated label bounds separately\n var bbPrefix = prefix || 'main';\n var bbs = _p.labelBounds;\n var bb = bbs[bbPrefix] = bbs[bbPrefix] || {};\n bb.x1 = lx1;\n bb.y1 = ly1;\n bb.x2 = lx2;\n bb.y2 = ly2;\n bb.w = lx2 - lx1;\n bb.h = ly2 - ly1;\n bb.leftPad = leftPad;\n bb.rightPad = rightPad;\n bb.topPad = topPad;\n bb.botPad = botPad;\n var isAutorotate = isEdge && rotation.strValue === 'autorotate';\n var isPfValue = rotation.pfValue != null && rotation.pfValue !== 0;\n if (isAutorotate || isPfValue) {\n var theta = isAutorotate ? prefixedProperty(_p.rstyle, 'labelAngle', prefix) : rotation.pfValue;\n var cos = Math.cos(theta);\n var sin = Math.sin(theta);\n\n // rotation point (default value for center-center)\n var xo = (lx1 + lx2) / 2;\n var yo = (ly1 + ly2) / 2;\n if (!isEdge) {\n switch (halign.value) {\n case 'left':\n xo = lx2;\n break;\n case 'right':\n xo = lx1;\n break;\n }\n switch (valign.value) {\n case 'top':\n yo = ly2;\n break;\n case 'bottom':\n yo = ly1;\n break;\n }\n }\n var rotate = function rotate(x, y) {\n x = x - xo;\n y = y - yo;\n return {\n x: x * cos - y * sin + xo,\n y: x * sin + y * cos + yo\n };\n };\n var px1y1 = rotate(lx1, ly1);\n var px1y2 = rotate(lx1, ly2);\n var px2y1 = rotate(lx2, ly1);\n var px2y2 = rotate(lx2, ly2);\n lx1 = Math.min(px1y1.x, px1y2.x, px2y1.x, px2y2.x);\n lx2 = Math.max(px1y1.x, px1y2.x, px2y1.x, px2y2.x);\n ly1 = Math.min(px1y1.y, px1y2.y, px2y1.y, px2y2.y);\n ly2 = Math.max(px1y1.y, px1y2.y, px2y1.y, px2y2.y);\n }\n var bbPrefixRot = bbPrefix + 'Rot';\n var bbRot = bbs[bbPrefixRot] = bbs[bbPrefixRot] || {};\n bbRot.x1 = lx1;\n bbRot.y1 = ly1;\n bbRot.x2 = lx2;\n bbRot.y2 = ly2;\n bbRot.w = lx2 - lx1;\n bbRot.h = ly2 - ly1;\n updateBounds(bounds, lx1, ly1, lx2, ly2);\n updateBounds(_p.labelBounds.all, lx1, ly1, lx2, ly2);\n }\n return bounds;\n};\nvar updateBoundsFromOutline = function updateBoundsFromOutline(bounds, ele) {\n if (ele.cy().headless()) {\n return;\n }\n var outlineOpacity = ele.pstyle('outline-opacity').value;\n var outlineWidth = ele.pstyle('outline-width').value;\n var outlineOffset = ele.pstyle('outline-offset').value;\n var expansion = outlineWidth + outlineOffset;\n updateBoundsFromMiter(bounds, ele, outlineOpacity, expansion, 'outside', expansion / 2);\n};\nvar updateBoundsFromMiter = function updateBoundsFromMiter(bounds, ele, opacity, expansionSize, expansionPosition, useFallbackValue) {\n if (opacity === 0 || expansionSize <= 0 || expansionPosition === 'inside') {\n return;\n }\n var cy = ele.cy();\n var shape = ele.pstyle('shape').value;\n var rshape = cy.renderer().nodeShapes[shape];\n var _ele$position = ele.position(),\n x = _ele$position.x,\n y = _ele$position.y;\n var w = ele.width();\n var h = ele.height();\n if (rshape.hasMiterBounds) {\n if (expansionPosition === 'center') {\n expansionSize /= 2;\n }\n var mbb = rshape.miterBounds(x, y, w, h, expansionSize);\n updateBoundsFromBox(bounds, mbb);\n } else if (useFallbackValue != null && useFallbackValue > 0) {\n expandBoundingBoxSides(bounds, [useFallbackValue, useFallbackValue, useFallbackValue, useFallbackValue]);\n }\n};\nvar updateBoundsFromMiterBorder = function updateBoundsFromMiterBorder(bounds, ele) {\n if (ele.cy().headless()) {\n return;\n }\n var borderOpacity = ele.pstyle('border-opacity').value;\n var borderWidth = ele.pstyle('border-width').pfValue;\n var borderPosition = ele.pstyle('border-position').value;\n updateBoundsFromMiter(bounds, ele, borderOpacity, borderWidth, borderPosition);\n};\n\n// get the bounding box of the elements (in raw model position)\nvar boundingBoxImpl = function boundingBoxImpl(ele, options) {\n var cy = ele._private.cy;\n var styleEnabled = cy.styleEnabled();\n var headless = cy.headless();\n var bounds = makeBoundingBox();\n var _p = ele._private;\n var isNode = ele.isNode();\n var isEdge = ele.isEdge();\n var ex1, ex2, ey1, ey2; // extrema of body / lines\n var x, y; // node pos\n var rstyle = _p.rstyle;\n var manualExpansion = isNode && styleEnabled ? ele.pstyle('bounds-expansion').pfValue : [0];\n\n // must use `display` prop only, as reading `compound.width()` causes recursion\n // (other factors like width values will be considered later in this function anyway)\n var isDisplayed = function isDisplayed(ele) {\n return ele.pstyle('display').value !== 'none';\n };\n var displayed = !styleEnabled || isDisplayed(ele)\n\n // must take into account connected nodes b/c of implicit edge hiding on display:none node\n && (!isEdge || isDisplayed(ele.source()) && isDisplayed(ele.target()));\n if (displayed) {\n // displayed suffices, since we will find zero area eles anyway\n var overlayOpacity = 0;\n var overlayPadding = 0;\n if (styleEnabled && options.includeOverlays) {\n overlayOpacity = ele.pstyle('overlay-opacity').value;\n if (overlayOpacity !== 0) {\n overlayPadding = ele.pstyle('overlay-padding').value;\n }\n }\n var underlayOpacity = 0;\n var underlayPadding = 0;\n if (styleEnabled && options.includeUnderlays) {\n underlayOpacity = ele.pstyle('underlay-opacity').value;\n if (underlayOpacity !== 0) {\n underlayPadding = ele.pstyle('underlay-padding').value;\n }\n }\n var padding = Math.max(overlayPadding, underlayPadding);\n var w = 0;\n var wHalf = 0;\n if (styleEnabled) {\n w = ele.pstyle('width').pfValue;\n wHalf = w / 2;\n }\n if (isNode && options.includeNodes) {\n var pos = ele.position();\n x = pos.x;\n y = pos.y;\n var _w = ele.outerWidth();\n var halfW = _w / 2;\n var h = ele.outerHeight();\n var halfH = h / 2;\n\n // handle node dimensions\n /////////////////////////\n\n ex1 = x - halfW;\n ex2 = x + halfW;\n ey1 = y - halfH;\n ey2 = y + halfH;\n updateBounds(bounds, ex1, ey1, ex2, ey2);\n if (styleEnabled) {\n updateBoundsFromOutline(bounds, ele);\n }\n if (styleEnabled && options.includeOutlines && !headless) {\n updateBoundsFromOutline(bounds, ele);\n }\n if (styleEnabled) {\n updateBoundsFromMiterBorder(bounds, ele);\n }\n } else if (isEdge && options.includeEdges) {\n if (styleEnabled && !headless) {\n var curveStyle = ele.pstyle('curve-style').strValue;\n\n // handle edge dimensions (rough box estimate)\n //////////////////////////////////////////////\n\n ex1 = Math.min(rstyle.srcX, rstyle.midX, rstyle.tgtX);\n ex2 = Math.max(rstyle.srcX, rstyle.midX, rstyle.tgtX);\n ey1 = Math.min(rstyle.srcY, rstyle.midY, rstyle.tgtY);\n ey2 = Math.max(rstyle.srcY, rstyle.midY, rstyle.tgtY);\n\n // take into account edge width\n ex1 -= wHalf;\n ex2 += wHalf;\n ey1 -= wHalf;\n ey2 += wHalf;\n updateBounds(bounds, ex1, ey1, ex2, ey2);\n\n // precise edges\n ////////////////\n\n if (curveStyle === 'haystack') {\n var hpts = rstyle.haystackPts;\n if (hpts && hpts.length === 2) {\n ex1 = hpts[0].x;\n ey1 = hpts[0].y;\n ex2 = hpts[1].x;\n ey2 = hpts[1].y;\n if (ex1 > ex2) {\n var temp = ex1;\n ex1 = ex2;\n ex2 = temp;\n }\n if (ey1 > ey2) {\n var _temp = ey1;\n ey1 = ey2;\n ey2 = _temp;\n }\n updateBounds(bounds, ex1 - wHalf, ey1 - wHalf, ex2 + wHalf, ey2 + wHalf);\n }\n } else if (curveStyle === 'bezier' || curveStyle === 'unbundled-bezier' || endsWith(curveStyle, 'segments') || endsWith(curveStyle, 'taxi')) {\n var pts;\n switch (curveStyle) {\n case 'bezier':\n case 'unbundled-bezier':\n pts = rstyle.bezierPts;\n break;\n case 'segments':\n case 'taxi':\n case 'round-segments':\n case 'round-taxi':\n pts = rstyle.linePts;\n break;\n }\n if (pts != null) {\n for (var j = 0; j < pts.length; j++) {\n var pt = pts[j];\n ex1 = pt.x - wHalf;\n ex2 = pt.x + wHalf;\n ey1 = pt.y - wHalf;\n ey2 = pt.y + wHalf;\n updateBounds(bounds, ex1, ey1, ex2, ey2);\n }\n }\n } // bezier-like or segment-like edge\n } else {\n // headless or style disabled\n\n // fallback on source and target positions\n //////////////////////////////////////////\n\n var n1 = ele.source();\n var n1pos = n1.position();\n var n2 = ele.target();\n var n2pos = n2.position();\n ex1 = n1pos.x;\n ex2 = n2pos.x;\n ey1 = n1pos.y;\n ey2 = n2pos.y;\n if (ex1 > ex2) {\n var _temp2 = ex1;\n ex1 = ex2;\n ex2 = _temp2;\n }\n if (ey1 > ey2) {\n var _temp3 = ey1;\n ey1 = ey2;\n ey2 = _temp3;\n }\n\n // take into account edge width\n ex1 -= wHalf;\n ex2 += wHalf;\n ey1 -= wHalf;\n ey2 += wHalf;\n updateBounds(bounds, ex1, ey1, ex2, ey2);\n } // headless or style disabled\n } // edges\n\n // handle edge arrow size\n /////////////////////////\n\n if (styleEnabled && options.includeEdges && isEdge) {\n updateBoundsFromArrow(bounds, ele, 'mid-source');\n updateBoundsFromArrow(bounds, ele, 'mid-target');\n updateBoundsFromArrow(bounds, ele, 'source');\n updateBoundsFromArrow(bounds, ele, 'target');\n }\n\n // ghost\n ////////\n\n if (styleEnabled) {\n var ghost = ele.pstyle('ghost').value === 'yes';\n if (ghost) {\n var gx = ele.pstyle('ghost-offset-x').pfValue;\n var gy = ele.pstyle('ghost-offset-y').pfValue;\n updateBounds(bounds, bounds.x1 + gx, bounds.y1 + gy, bounds.x2 + gx, bounds.y2 + gy);\n }\n }\n\n // always store the body bounds separately from the labels\n var bbBody = _p.bodyBounds = _p.bodyBounds || {};\n assignBoundingBox(bbBody, bounds);\n expandBoundingBoxSides(bbBody, manualExpansion);\n expandBoundingBox(bbBody, 1); // expand to work around browser dimension inaccuracies\n\n // overlay\n //////////\n\n if (styleEnabled) {\n ex1 = bounds.x1;\n ex2 = bounds.x2;\n ey1 = bounds.y1;\n ey2 = bounds.y2;\n updateBounds(bounds, ex1 - padding, ey1 - padding, ex2 + padding, ey2 + padding);\n }\n\n // always store the body bounds separately from the labels\n var bbOverlay = _p.overlayBounds = _p.overlayBounds || {};\n assignBoundingBox(bbOverlay, bounds);\n expandBoundingBoxSides(bbOverlay, manualExpansion);\n expandBoundingBox(bbOverlay, 1); // expand to work around browser dimension inaccuracies\n\n // handle label dimensions\n //////////////////////////\n\n var bbLabels = _p.labelBounds = _p.labelBounds || {};\n if (bbLabels.all != null) {\n clearBoundingBox(bbLabels.all);\n } else {\n bbLabels.all = makeBoundingBox();\n }\n if (styleEnabled && options.includeLabels) {\n if (options.includeMainLabels) {\n updateBoundsFromLabel(bounds, ele, null);\n }\n if (isEdge) {\n if (options.includeSourceLabels) {\n updateBoundsFromLabel(bounds, ele, 'source');\n }\n if (options.includeTargetLabels) {\n updateBoundsFromLabel(bounds, ele, 'target');\n }\n }\n } // style enabled for labels\n } // if displayed\n\n bounds.x1 = noninf(bounds.x1);\n bounds.y1 = noninf(bounds.y1);\n bounds.x2 = noninf(bounds.x2);\n bounds.y2 = noninf(bounds.y2);\n bounds.w = noninf(bounds.x2 - bounds.x1);\n bounds.h = noninf(bounds.y2 - bounds.y1);\n if (bounds.w > 0 && bounds.h > 0 && displayed) {\n expandBoundingBoxSides(bounds, manualExpansion);\n\n // expand bounds by 1 because antialiasing can increase the visual/effective size by 1 on all sides\n expandBoundingBox(bounds, 1);\n }\n return bounds;\n};\nvar getKey = function getKey(opts) {\n var i = 0;\n var tf = function tf(val) {\n return (val ? 1 : 0) << i++;\n };\n var key = 0;\n key += tf(opts.incudeNodes);\n key += tf(opts.includeEdges);\n key += tf(opts.includeLabels);\n key += tf(opts.includeMainLabels);\n key += tf(opts.includeSourceLabels);\n key += tf(opts.includeTargetLabels);\n key += tf(opts.includeOverlays);\n key += tf(opts.includeOutlines);\n return key;\n};\nvar getBoundingBoxPosKey = function getBoundingBoxPosKey(ele) {\n var r = function r(x) {\n return Math.round(x);\n };\n if (ele.isEdge()) {\n var p1 = ele.source().position();\n var p2 = ele.target().position();\n return hashIntsArray([r(p1.x), r(p1.y), r(p2.x), r(p2.y)]);\n } else {\n var p = ele.position();\n return hashIntsArray([r(p.x), r(p.y)]);\n }\n};\nvar cachedBoundingBoxImpl = function cachedBoundingBoxImpl(ele, opts) {\n var _p = ele._private;\n var bb;\n var isEdge = ele.isEdge();\n var key = opts == null ? defBbOptsKey : getKey(opts);\n var usingDefOpts = key === defBbOptsKey;\n if (_p.bbCache == null) {\n bb = boundingBoxImpl(ele, defBbOpts);\n _p.bbCache = bb;\n _p.bbCachePosKey = getBoundingBoxPosKey(ele);\n } else {\n bb = _p.bbCache;\n }\n\n // not using def opts => need to build up bb from combination of sub bbs\n if (!usingDefOpts) {\n var isNode = ele.isNode();\n bb = makeBoundingBox();\n if (opts.includeNodes && isNode || opts.includeEdges && !isNode) {\n if (opts.includeOverlays) {\n updateBoundsFromBox(bb, _p.overlayBounds);\n } else {\n updateBoundsFromBox(bb, _p.bodyBounds);\n }\n }\n if (opts.includeLabels) {\n if (opts.includeMainLabels && (!isEdge || opts.includeSourceLabels && opts.includeTargetLabels)) {\n updateBoundsFromBox(bb, _p.labelBounds.all);\n } else {\n if (opts.includeMainLabels) {\n updateBoundsFromBox(bb, _p.labelBounds.mainRot);\n }\n if (opts.includeSourceLabels) {\n updateBoundsFromBox(bb, _p.labelBounds.sourceRot);\n }\n if (opts.includeTargetLabels) {\n updateBoundsFromBox(bb, _p.labelBounds.targetRot);\n }\n }\n }\n bb.w = bb.x2 - bb.x1;\n bb.h = bb.y2 - bb.y1;\n }\n return bb;\n};\nvar defBbOpts = {\n includeNodes: true,\n includeEdges: true,\n includeLabels: true,\n includeMainLabels: true,\n includeSourceLabels: true,\n includeTargetLabels: true,\n includeOverlays: true,\n includeUnderlays: true,\n includeOutlines: true,\n useCache: true\n};\nvar defBbOptsKey = getKey(defBbOpts);\nvar filledBbOpts = defaults$g(defBbOpts);\nelesfn$b.boundingBox = function (options) {\n var bounds;\n var useCache = options === undefined || options.useCache === undefined || options.useCache === true;\n var isDirty = memoize(function (ele) {\n var _p = ele._private;\n return _p.bbCache == null || _p.styleDirty || _p.bbCachePosKey !== getBoundingBoxPosKey(ele);\n }, function (ele) {\n return ele.id();\n });\n\n // the main usecase is ele.boundingBox() for a single element with no/def options\n // specified s.t. the cache is used, so check for this case to make it faster by\n // avoiding the overhead of the rest of the function\n if (useCache && this.length === 1 && !isDirty(this[0])) {\n if (options === undefined) {\n options = defBbOpts;\n } else {\n options = filledBbOpts(options);\n }\n bounds = cachedBoundingBoxImpl(this[0], options);\n } else {\n bounds = makeBoundingBox();\n options = options || defBbOpts;\n var opts = filledBbOpts(options);\n var eles = this;\n var cy = eles.cy();\n var styleEnabled = cy.styleEnabled();\n\n // cache the isDirty state for all eles, edges first since they depend on node state\n this.edges().forEach(isDirty);\n this.nodes().forEach(isDirty);\n if (styleEnabled) {\n this.recalculateRenderedStyle(useCache);\n }\n this.updateCompoundBounds(!useCache);\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n if (isDirty(ele)) {\n ele.dirtyBoundingBoxCache();\n }\n updateBoundsFromBox(bounds, cachedBoundingBoxImpl(ele, opts));\n }\n }\n bounds.x1 = noninf(bounds.x1);\n bounds.y1 = noninf(bounds.y1);\n bounds.x2 = noninf(bounds.x2);\n bounds.y2 = noninf(bounds.y2);\n bounds.w = noninf(bounds.x2 - bounds.x1);\n bounds.h = noninf(bounds.y2 - bounds.y1);\n return bounds;\n};\nelesfn$b.dirtyBoundingBoxCache = function () {\n for (var i = 0; i < this.length; i++) {\n var _p = this[i]._private;\n _p.bbCache = null;\n _p.bbCachePosKey = null;\n _p.bodyBounds = null;\n _p.overlayBounds = null;\n _p.labelBounds.all = null;\n _p.labelBounds.source = null;\n _p.labelBounds.target = null;\n _p.labelBounds.main = null;\n _p.labelBounds.sourceRot = null;\n _p.labelBounds.targetRot = null;\n _p.labelBounds.mainRot = null;\n _p.arrowBounds.source = null;\n _p.arrowBounds.target = null;\n _p.arrowBounds['mid-source'] = null;\n _p.arrowBounds['mid-target'] = null;\n }\n this.emitAndNotify('bounds');\n return this;\n};\n\n// private helper to get bounding box for custom node positions\n// - good for perf in certain cases but currently requires dirtying the rendered style\n// - would be better to not modify the nodes but the nodes are read directly everywhere in the renderer...\n// - try to use for only things like discrete layouts where the node position would change anyway\nelesfn$b.boundingBoxAt = function (fn) {\n var nodes = this.nodes();\n var cy = this.cy();\n var hasCompoundNodes = cy.hasCompoundNodes();\n var parents = cy.collection();\n if (hasCompoundNodes) {\n parents = nodes.filter(function (node) {\n return node.isParent();\n });\n nodes = nodes.not(parents);\n }\n if (plainObject(fn)) {\n var obj = fn;\n fn = function fn() {\n return obj;\n };\n }\n var storeOldPos = function storeOldPos(node, i) {\n return node._private.bbAtOldPos = fn(node, i);\n };\n var getOldPos = function getOldPos(node) {\n return node._private.bbAtOldPos;\n };\n cy.startBatch();\n nodes.forEach(storeOldPos).silentPositions(fn);\n if (hasCompoundNodes) {\n parents.dirtyCompoundBoundsCache();\n parents.dirtyBoundingBoxCache();\n parents.updateCompoundBounds(true); // force update b/c we're inside a batch cycle\n }\n var bb = copyBoundingBox(this.boundingBox({\n useCache: false\n }));\n nodes.silentPositions(getOldPos);\n if (hasCompoundNodes) {\n parents.dirtyCompoundBoundsCache();\n parents.dirtyBoundingBoxCache();\n parents.updateCompoundBounds(true); // force update b/c we're inside a batch cycle\n }\n cy.endBatch();\n return bb;\n};\nfn$3.boundingbox = fn$3.bb = fn$3.boundingBox;\nfn$3.renderedBoundingbox = fn$3.renderedBoundingBox;\nvar bounds = elesfn$b;\n\nvar fn$2, elesfn$a;\nfn$2 = elesfn$a = {};\nvar defineDimFns = function defineDimFns(opts) {\n opts.uppercaseName = capitalize(opts.name);\n opts.autoName = 'auto' + opts.uppercaseName;\n opts.labelName = 'label' + opts.uppercaseName;\n opts.outerName = 'outer' + opts.uppercaseName;\n opts.uppercaseOuterName = capitalize(opts.outerName);\n fn$2[opts.name] = function dimImpl() {\n var ele = this[0];\n var _p = ele._private;\n var cy = _p.cy;\n var styleEnabled = cy._private.styleEnabled;\n if (ele) {\n if (styleEnabled) {\n if (ele.isParent()) {\n ele.updateCompoundBounds();\n return _p[opts.autoName] || 0;\n }\n var d = ele.pstyle(opts.name);\n switch (d.strValue) {\n case 'label':\n ele.recalculateRenderedStyle();\n return _p.rstyle[opts.labelName] || 0;\n default:\n return d.pfValue;\n }\n } else {\n return 1;\n }\n }\n };\n fn$2['outer' + opts.uppercaseName] = function outerDimImpl() {\n var ele = this[0];\n var _p = ele._private;\n var cy = _p.cy;\n var styleEnabled = cy._private.styleEnabled;\n if (ele) {\n if (styleEnabled) {\n var dim = ele[opts.name]();\n var borderPos = ele.pstyle('border-position').value;\n var border;\n if (borderPos === 'center') {\n border = ele.pstyle('border-width').pfValue; // n.b. 1/2 each side\n } else if (borderPos === 'outside') {\n border = 2 * ele.pstyle('border-width').pfValue;\n } else {\n // 'inside'\n border = 0;\n }\n var padding = 2 * ele.padding();\n return dim + border + padding;\n } else {\n return 1;\n }\n }\n };\n fn$2['rendered' + opts.uppercaseName] = function renderedDimImpl() {\n var ele = this[0];\n if (ele) {\n var d = ele[opts.name]();\n return d * this.cy().zoom();\n }\n };\n fn$2['rendered' + opts.uppercaseOuterName] = function renderedOuterDimImpl() {\n var ele = this[0];\n if (ele) {\n var od = ele[opts.outerName]();\n return od * this.cy().zoom();\n }\n };\n};\ndefineDimFns({\n name: 'width'\n});\ndefineDimFns({\n name: 'height'\n});\nelesfn$a.padding = function () {\n var ele = this[0];\n var _p = ele._private;\n if (ele.isParent()) {\n ele.updateCompoundBounds();\n if (_p.autoPadding !== undefined) {\n return _p.autoPadding;\n } else {\n return ele.pstyle('padding').pfValue;\n }\n } else {\n return ele.pstyle('padding').pfValue;\n }\n};\nelesfn$a.paddedHeight = function () {\n var ele = this[0];\n return ele.height() + 2 * ele.padding();\n};\nelesfn$a.paddedWidth = function () {\n var ele = this[0];\n return ele.width() + 2 * ele.padding();\n};\nvar widthHeight = elesfn$a;\n\nvar ifEdge = function ifEdge(ele, getValue) {\n if (ele.isEdge() && ele.takesUpSpace()) {\n return getValue(ele);\n }\n};\nvar ifEdgeRenderedPosition = function ifEdgeRenderedPosition(ele, getPoint) {\n if (ele.isEdge() && ele.takesUpSpace()) {\n var cy = ele.cy();\n return modelToRenderedPosition$1(getPoint(ele), cy.zoom(), cy.pan());\n }\n};\nvar ifEdgeRenderedPositions = function ifEdgeRenderedPositions(ele, getPoints) {\n if (ele.isEdge() && ele.takesUpSpace()) {\n var cy = ele.cy();\n var pan = cy.pan();\n var zoom = cy.zoom();\n return getPoints(ele).map(function (p) {\n return modelToRenderedPosition$1(p, zoom, pan);\n });\n }\n};\nvar controlPoints = function controlPoints(ele) {\n return ele.renderer().getControlPoints(ele);\n};\nvar segmentPoints = function segmentPoints(ele) {\n return ele.renderer().getSegmentPoints(ele);\n};\nvar sourceEndpoint = function sourceEndpoint(ele) {\n return ele.renderer().getSourceEndpoint(ele);\n};\nvar targetEndpoint = function targetEndpoint(ele) {\n return ele.renderer().getTargetEndpoint(ele);\n};\nvar midpoint = function midpoint(ele) {\n return ele.renderer().getEdgeMidpoint(ele);\n};\nvar pts = {\n controlPoints: {\n get: controlPoints,\n mult: true\n },\n segmentPoints: {\n get: segmentPoints,\n mult: true\n },\n sourceEndpoint: {\n get: sourceEndpoint\n },\n targetEndpoint: {\n get: targetEndpoint\n },\n midpoint: {\n get: midpoint\n }\n};\nvar renderedName = function renderedName(name) {\n return 'rendered' + name[0].toUpperCase() + name.substr(1);\n};\nvar edgePoints = Object.keys(pts).reduce(function (obj, name) {\n var spec = pts[name];\n var rName = renderedName(name);\n obj[name] = function () {\n return ifEdge(this, spec.get);\n };\n if (spec.mult) {\n obj[rName] = function () {\n return ifEdgeRenderedPositions(this, spec.get);\n };\n } else {\n obj[rName] = function () {\n return ifEdgeRenderedPosition(this, spec.get);\n };\n }\n return obj;\n}, {});\n\nvar dimensions = extend({}, position, bounds, widthHeight, edgePoints);\n\n/*!\nEvent object based on jQuery events, MIT license\n\nhttps://jquery.org/license/\nhttps://tldrlegal.com/license/mit-license\nhttps://github.com/jquery/jquery/blob/master/src/event.js\n*/\n\nvar Event = function Event(src, props) {\n this.recycle(src, props);\n};\nfunction returnFalse() {\n return false;\n}\nfunction returnTrue() {\n return true;\n}\n\n// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html\nEvent.prototype = {\n instanceString: function instanceString() {\n return 'event';\n },\n recycle: function recycle(src, props) {\n this.isImmediatePropagationStopped = this.isPropagationStopped = this.isDefaultPrevented = returnFalse;\n if (src != null && src.preventDefault) {\n // Browser Event object\n this.type = src.type;\n\n // Events bubbling up the document may have been marked as prevented\n // by a handler lower down the tree; reflect the correct value.\n this.isDefaultPrevented = src.defaultPrevented ? returnTrue : returnFalse;\n } else if (src != null && src.type) {\n // Plain object containing all event details\n props = src;\n } else {\n // Event string\n this.type = src;\n }\n\n // Put explicitly provided properties onto the event object\n if (props != null) {\n // more efficient to manually copy fields we use\n this.originalEvent = props.originalEvent;\n this.type = props.type != null ? props.type : this.type;\n this.cy = props.cy;\n this.target = props.target;\n this.position = props.position;\n this.renderedPosition = props.renderedPosition;\n this.namespace = props.namespace;\n this.layout = props.layout;\n }\n if (this.cy != null && this.position != null && this.renderedPosition == null) {\n // create a rendered position based on the passed position\n var pos = this.position;\n var zoom = this.cy.zoom();\n var pan = this.cy.pan();\n this.renderedPosition = {\n x: pos.x * zoom + pan.x,\n y: pos.y * zoom + pan.y\n };\n }\n\n // Create a timestamp if incoming event doesn't have one\n this.timeStamp = src && src.timeStamp || Date.now();\n },\n preventDefault: function preventDefault() {\n this.isDefaultPrevented = returnTrue;\n var e = this.originalEvent;\n if (!e) {\n return;\n }\n\n // if preventDefault exists run it on the original event\n if (e.preventDefault) {\n e.preventDefault();\n }\n },\n stopPropagation: function stopPropagation() {\n this.isPropagationStopped = returnTrue;\n var e = this.originalEvent;\n if (!e) {\n return;\n }\n\n // if stopPropagation exists run it on the original event\n if (e.stopPropagation) {\n e.stopPropagation();\n }\n },\n stopImmediatePropagation: function stopImmediatePropagation() {\n this.isImmediatePropagationStopped = returnTrue;\n this.stopPropagation();\n },\n isDefaultPrevented: returnFalse,\n isPropagationStopped: returnFalse,\n isImmediatePropagationStopped: returnFalse\n};\n\nvar eventRegex = /^([^.]+)(\\.(?:[^.]+))?$/; // regex for matching event strings (e.g. \"click.namespace\")\nvar universalNamespace = '.*'; // matches as if no namespace specified and prevents users from unbinding accidentally\n\nvar defaults$8 = {\n qualifierCompare: function qualifierCompare(q1, q2) {\n return q1 === q2;\n },\n eventMatches: function eventMatches(/*context, listener, eventObj*/\n ) {\n return true;\n },\n addEventFields: function addEventFields(/*context, evt*/\n ) {},\n callbackContext: function callbackContext(context /*, listener, eventObj*/) {\n return context;\n },\n beforeEmit: function beforeEmit(/* context, listener, eventObj */\n ) {},\n afterEmit: function afterEmit(/* context, listener, eventObj */\n ) {},\n bubble: function bubble(/*context*/\n ) {\n return false;\n },\n parent: function parent(/*context*/\n ) {\n return null;\n },\n context: null\n};\nvar defaultsKeys = Object.keys(defaults$8);\nvar emptyOpts = {};\nfunction Emitter() {\n var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : emptyOpts;\n var context = arguments.length > 1 ? arguments[1] : undefined;\n // micro-optimisation vs Object.assign() -- reduces Element instantiation time\n for (var i = 0; i < defaultsKeys.length; i++) {\n var key = defaultsKeys[i];\n this[key] = opts[key] || defaults$8[key];\n }\n this.context = context || this.context;\n this.listeners = [];\n this.emitting = 0;\n}\nvar p = Emitter.prototype;\nvar forEachEvent = function forEachEvent(self, handler, events, qualifier, callback, conf, confOverrides) {\n if (fn$6(qualifier)) {\n callback = qualifier;\n qualifier = null;\n }\n if (confOverrides) {\n if (conf == null) {\n conf = confOverrides;\n } else {\n conf = extend({}, conf, confOverrides);\n }\n }\n var eventList = array(events) ? events : events.split(/\\s+/);\n for (var i = 0; i < eventList.length; i++) {\n var evt = eventList[i];\n if (emptyString(evt)) {\n continue;\n }\n var match = evt.match(eventRegex); // type[.namespace]\n\n if (match) {\n var type = match[1];\n var namespace = match[2] ? match[2] : null;\n var ret = handler(self, evt, type, namespace, qualifier, callback, conf);\n if (ret === false) {\n break;\n } // allow exiting early\n }\n }\n};\nvar makeEventObj = function makeEventObj(self, obj) {\n self.addEventFields(self.context, obj);\n return new Event(obj.type, obj);\n};\nvar forEachEventObj = function forEachEventObj(self, handler, events) {\n if (event(events)) {\n handler(self, events);\n return;\n } else if (plainObject(events)) {\n handler(self, makeEventObj(self, events));\n return;\n }\n var eventList = array(events) ? events : events.split(/\\s+/);\n for (var i = 0; i < eventList.length; i++) {\n var evt = eventList[i];\n if (emptyString(evt)) {\n continue;\n }\n var match = evt.match(eventRegex); // type[.namespace]\n\n if (match) {\n var type = match[1];\n var namespace = match[2] ? match[2] : null;\n var eventObj = makeEventObj(self, {\n type: type,\n namespace: namespace,\n target: self.context\n });\n handler(self, eventObj);\n }\n }\n};\np.on = p.addListener = function (events, qualifier, callback, conf, confOverrides) {\n forEachEvent(this, function (self, event, type, namespace, qualifier, callback, conf) {\n if (fn$6(callback)) {\n self.listeners.push({\n event: event,\n // full event string\n callback: callback,\n // callback to run\n type: type,\n // the event type (e.g. 'click')\n namespace: namespace,\n // the event namespace (e.g. \".foo\")\n qualifier: qualifier,\n // a restriction on whether to match this emitter\n conf: conf // additional configuration\n });\n }\n }, events, qualifier, callback, conf, confOverrides);\n return this;\n};\np.one = function (events, qualifier, callback, conf) {\n return this.on(events, qualifier, callback, conf, {\n one: true\n });\n};\np.removeListener = p.off = function (events, qualifier, callback, conf) {\n var _this = this;\n if (this.emitting !== 0) {\n this.listeners = copyArray(this.listeners);\n }\n var listeners = this.listeners;\n var _loop = function _loop(i) {\n var listener = listeners[i];\n forEachEvent(_this, function (self, event, type, namespace, qualifier, callback /*, conf*/) {\n if ((listener.type === type || events === '*') && (!namespace && listener.namespace !== '.*' || listener.namespace === namespace) && (!qualifier || self.qualifierCompare(listener.qualifier, qualifier)) && (!callback || listener.callback === callback)) {\n listeners.splice(i, 1);\n return false;\n }\n }, events, qualifier, callback, conf);\n };\n for (var i = listeners.length - 1; i >= 0; i--) {\n _loop(i);\n }\n return this;\n};\np.removeAllListeners = function () {\n return this.removeListener('*');\n};\np.emit = p.trigger = function (events, extraParams, manualCallback) {\n var listeners = this.listeners;\n var numListenersBeforeEmit = listeners.length;\n this.emitting++;\n if (!array(extraParams)) {\n extraParams = [extraParams];\n }\n forEachEventObj(this, function (self, eventObj) {\n if (manualCallback != null) {\n listeners = [{\n event: eventObj.event,\n type: eventObj.type,\n namespace: eventObj.namespace,\n callback: manualCallback\n }];\n numListenersBeforeEmit = listeners.length;\n }\n var _loop2 = function _loop2() {\n var listener = listeners[i];\n if (listener.type === eventObj.type && (!listener.namespace || listener.namespace === eventObj.namespace || listener.namespace === universalNamespace) && self.eventMatches(self.context, listener, eventObj)) {\n var args = [eventObj];\n if (extraParams != null) {\n push(args, extraParams);\n }\n self.beforeEmit(self.context, listener, eventObj);\n if (listener.conf && listener.conf.one) {\n self.listeners = self.listeners.filter(function (l) {\n return l !== listener;\n });\n }\n var context = self.callbackContext(self.context, listener, eventObj);\n var ret = listener.callback.apply(context, args);\n self.afterEmit(self.context, listener, eventObj);\n if (ret === false) {\n eventObj.stopPropagation();\n eventObj.preventDefault();\n }\n } // if listener matches\n };\n for (var i = 0; i < numListenersBeforeEmit; i++) {\n _loop2();\n } // for listener\n\n if (self.bubble(self.context) && !eventObj.isPropagationStopped()) {\n self.parent(self.context).emit(eventObj, extraParams);\n }\n }, events);\n this.emitting--;\n return this;\n};\n\nvar emitterOptions$1 = {\n qualifierCompare: function qualifierCompare(selector1, selector2) {\n if (selector1 == null || selector2 == null) {\n return selector1 == null && selector2 == null;\n } else {\n return selector1.sameText(selector2);\n }\n },\n eventMatches: function eventMatches(ele, listener, eventObj) {\n var selector = listener.qualifier;\n if (selector != null) {\n return ele !== eventObj.target && element(eventObj.target) && selector.matches(eventObj.target);\n }\n return true;\n },\n addEventFields: function addEventFields(ele, evt) {\n evt.cy = ele.cy();\n evt.target = ele;\n },\n callbackContext: function callbackContext(ele, listener, eventObj) {\n return listener.qualifier != null ? eventObj.target : ele;\n },\n beforeEmit: function beforeEmit(context, listener /*, eventObj*/) {\n if (listener.conf && listener.conf.once) {\n listener.conf.onceCollection.removeListener(listener.event, listener.qualifier, listener.callback);\n }\n },\n bubble: function bubble() {\n return true;\n },\n parent: function parent(ele) {\n return ele.isChild() ? ele.parent() : ele.cy();\n }\n};\nvar argSelector$1 = function argSelector(arg) {\n if (string(arg)) {\n return new Selector(arg);\n } else {\n return arg;\n }\n};\nvar elesfn$9 = {\n createEmitter: function createEmitter() {\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n var _p = ele._private;\n if (!_p.emitter) {\n _p.emitter = new Emitter(emitterOptions$1, ele);\n }\n }\n return this;\n },\n emitter: function emitter() {\n return this._private.emitter;\n },\n on: function on(events, selector, callback) {\n var argSel = argSelector$1(selector);\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n ele.emitter().on(events, argSel, callback);\n }\n return this;\n },\n removeListener: function removeListener(events, selector, callback) {\n var argSel = argSelector$1(selector);\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n ele.emitter().removeListener(events, argSel, callback);\n }\n return this;\n },\n removeAllListeners: function removeAllListeners() {\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n ele.emitter().removeAllListeners();\n }\n return this;\n },\n one: function one(events, selector, callback) {\n var argSel = argSelector$1(selector);\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n ele.emitter().one(events, argSel, callback);\n }\n return this;\n },\n once: function once(events, selector, callback) {\n var argSel = argSelector$1(selector);\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n ele.emitter().on(events, argSel, callback, {\n once: true,\n onceCollection: this\n });\n }\n },\n emit: function emit(events, extraParams) {\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n ele.emitter().emit(events, extraParams);\n }\n return this;\n },\n emitAndNotify: function emitAndNotify(event, extraParams) {\n // for internal use only\n if (this.length === 0) {\n return;\n } // empty collections don't need to notify anything\n\n // notify renderer\n this.cy().notify(event, this);\n this.emit(event, extraParams);\n return this;\n }\n};\ndefine.eventAliasesOn(elesfn$9);\n\nvar elesfn$8 = {\n nodes: function nodes(selector) {\n return this.filter(function (ele) {\n return ele.isNode();\n }).filter(selector);\n },\n edges: function edges(selector) {\n return this.filter(function (ele) {\n return ele.isEdge();\n }).filter(selector);\n },\n // internal helper to get nodes and edges as separate collections with single iteration over elements\n byGroup: function byGroup() {\n var nodes = this.spawn();\n var edges = this.spawn();\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n if (ele.isNode()) {\n nodes.push(ele);\n } else {\n edges.push(ele);\n }\n }\n return {\n nodes: nodes,\n edges: edges\n };\n },\n filter: function filter(_filter, thisArg) {\n if (_filter === undefined) {\n // check this first b/c it's the most common/performant case\n return this;\n } else if (string(_filter) || elementOrCollection(_filter)) {\n return new Selector(_filter).filter(this);\n } else if (fn$6(_filter)) {\n var filterEles = this.spawn();\n var eles = this;\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n var include = thisArg ? _filter.apply(thisArg, [ele, i, eles]) : _filter(ele, i, eles);\n if (include) {\n filterEles.push(ele);\n }\n }\n return filterEles;\n }\n return this.spawn(); // if not handled by above, give 'em an empty collection\n },\n not: function not(toRemove) {\n if (!toRemove) {\n return this;\n } else {\n if (string(toRemove)) {\n toRemove = this.filter(toRemove);\n }\n var elements = this.spawn();\n for (var i = 0; i < this.length; i++) {\n var element = this[i];\n var remove = toRemove.has(element);\n if (!remove) {\n elements.push(element);\n }\n }\n return elements;\n }\n },\n absoluteComplement: function absoluteComplement() {\n var cy = this.cy();\n return cy.mutableElements().not(this);\n },\n intersect: function intersect(other) {\n // if a selector is specified, then filter by it instead\n if (string(other)) {\n var selector = other;\n return this.filter(selector);\n }\n var elements = this.spawn();\n var col1 = this;\n var col2 = other;\n var col1Smaller = this.length < other.length;\n var colS = col1Smaller ? col1 : col2;\n var colL = col1Smaller ? col2 : col1;\n for (var i = 0; i < colS.length; i++) {\n var ele = colS[i];\n if (colL.has(ele)) {\n elements.push(ele);\n }\n }\n return elements;\n },\n xor: function xor(other) {\n var cy = this._private.cy;\n if (string(other)) {\n other = cy.$(other);\n }\n var elements = this.spawn();\n var col1 = this;\n var col2 = other;\n var add = function add(col, other) {\n for (var i = 0; i < col.length; i++) {\n var ele = col[i];\n var id = ele._private.data.id;\n var inOther = other.hasElementWithId(id);\n if (!inOther) {\n elements.push(ele);\n }\n }\n };\n add(col1, col2);\n add(col2, col1);\n return elements;\n },\n diff: function diff(other) {\n var cy = this._private.cy;\n if (string(other)) {\n other = cy.$(other);\n }\n var left = this.spawn();\n var right = this.spawn();\n var both = this.spawn();\n var col1 = this;\n var col2 = other;\n var add = function add(col, other, retEles) {\n for (var i = 0; i < col.length; i++) {\n var ele = col[i];\n var id = ele._private.data.id;\n var inOther = other.hasElementWithId(id);\n if (inOther) {\n both.merge(ele);\n } else {\n retEles.push(ele);\n }\n }\n };\n add(col1, col2, left);\n add(col2, col1, right);\n return {\n left: left,\n right: right,\n both: both\n };\n },\n add: function add(toAdd) {\n var cy = this._private.cy;\n if (!toAdd) {\n return this;\n }\n if (string(toAdd)) {\n var selector = toAdd;\n toAdd = cy.mutableElements().filter(selector);\n }\n var elements = this.spawnSelf();\n for (var i = 0; i < toAdd.length; i++) {\n var ele = toAdd[i];\n var add = !this.has(ele);\n if (add) {\n elements.push(ele);\n }\n }\n return elements;\n },\n // in place merge on calling collection\n merge: function merge(toAdd) {\n var _p = this._private;\n var cy = _p.cy;\n if (!toAdd) {\n return this;\n }\n if (toAdd && string(toAdd)) {\n var selector = toAdd;\n toAdd = cy.mutableElements().filter(selector);\n }\n var map = _p.map;\n for (var i = 0; i < toAdd.length; i++) {\n var toAddEle = toAdd[i];\n var id = toAddEle._private.data.id;\n var add = !map.has(id);\n if (add) {\n var index = this.length++;\n this[index] = toAddEle;\n map.set(id, {\n ele: toAddEle,\n index: index\n });\n }\n }\n return this; // chaining\n },\n unmergeAt: function unmergeAt(i) {\n var ele = this[i];\n var id = ele.id();\n var _p = this._private;\n var map = _p.map;\n\n // remove ele\n this[i] = undefined;\n map[\"delete\"](id);\n var unmergedLastEle = i === this.length - 1;\n\n // replace empty spot with last ele in collection\n if (this.length > 1 && !unmergedLastEle) {\n var lastEleI = this.length - 1;\n var lastEle = this[lastEleI];\n var lastEleId = lastEle._private.data.id;\n this[lastEleI] = undefined;\n this[i] = lastEle;\n map.set(lastEleId, {\n ele: lastEle,\n index: i\n });\n }\n\n // the collection is now 1 ele smaller\n this.length--;\n return this;\n },\n // remove single ele in place in calling collection\n unmergeOne: function unmergeOne(ele) {\n ele = ele[0];\n var _p = this._private;\n var id = ele._private.data.id;\n var map = _p.map;\n var entry = map.get(id);\n if (!entry) {\n return this; // no need to remove\n }\n var i = entry.index;\n this.unmergeAt(i);\n return this;\n },\n // remove eles in place on calling collection\n unmerge: function unmerge(toRemove) {\n var cy = this._private.cy;\n if (!toRemove) {\n return this;\n }\n if (toRemove && string(toRemove)) {\n var selector = toRemove;\n toRemove = cy.mutableElements().filter(selector);\n }\n for (var i = 0; i < toRemove.length; i++) {\n this.unmergeOne(toRemove[i]);\n }\n return this; // chaining\n },\n unmergeBy: function unmergeBy(toRmFn) {\n for (var i = this.length - 1; i >= 0; i--) {\n var ele = this[i];\n if (toRmFn(ele)) {\n this.unmergeAt(i);\n }\n }\n return this;\n },\n map: function map(mapFn, thisArg) {\n var arr = [];\n var eles = this;\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n var ret = thisArg ? mapFn.apply(thisArg, [ele, i, eles]) : mapFn(ele, i, eles);\n arr.push(ret);\n }\n return arr;\n },\n reduce: function reduce(fn, initialValue) {\n var val = initialValue;\n var eles = this;\n for (var i = 0; i < eles.length; i++) {\n val = fn(val, eles[i], i, eles);\n }\n return val;\n },\n max: function max(valFn, thisArg) {\n var max = -Infinity;\n var maxEle;\n var eles = this;\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n var val = thisArg ? valFn.apply(thisArg, [ele, i, eles]) : valFn(ele, i, eles);\n if (val > max) {\n max = val;\n maxEle = ele;\n }\n }\n return {\n value: max,\n ele: maxEle\n };\n },\n min: function min(valFn, thisArg) {\n var min = Infinity;\n var minEle;\n var eles = this;\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n var val = thisArg ? valFn.apply(thisArg, [ele, i, eles]) : valFn(ele, i, eles);\n if (val < min) {\n min = val;\n minEle = ele;\n }\n }\n return {\n value: min,\n ele: minEle\n };\n }\n};\n\n// aliases\nvar fn$1 = elesfn$8;\nfn$1['u'] = fn$1['|'] = fn$1['+'] = fn$1.union = fn$1.or = fn$1.add;\nfn$1['\\\\'] = fn$1['!'] = fn$1['-'] = fn$1.difference = fn$1.relativeComplement = fn$1.subtract = fn$1.not;\nfn$1['n'] = fn$1['&'] = fn$1['.'] = fn$1.and = fn$1.intersection = fn$1.intersect;\nfn$1['^'] = fn$1['(+)'] = fn$1['(-)'] = fn$1.symmetricDifference = fn$1.symdiff = fn$1.xor;\nfn$1.fnFilter = fn$1.filterFn = fn$1.stdFilter = fn$1.filter;\nfn$1.complement = fn$1.abscomp = fn$1.absoluteComplement;\n\nvar elesfn$7 = {\n isNode: function isNode() {\n return this.group() === 'nodes';\n },\n isEdge: function isEdge() {\n return this.group() === 'edges';\n },\n isLoop: function isLoop() {\n return this.isEdge() && this.source()[0] === this.target()[0];\n },\n isSimple: function isSimple() {\n return this.isEdge() && this.source()[0] !== this.target()[0];\n },\n group: function group() {\n var ele = this[0];\n if (ele) {\n return ele._private.group;\n }\n }\n};\n\n/**\n * Elements are drawn in a specific order based on compound depth (low to high), the element type (nodes above edges),\n * and z-index (low to high). These styles affect how this applies:\n *\n * z-compound-depth: May be `bottom | orphan | auto | top`. The first drawn is `bottom`, then `orphan` which is the\n * same depth as the root of the compound graph, followed by the default value `auto` which draws in order from\n * root to leaves of the compound graph. The last drawn is `top`.\n * z-index-compare: May be `auto | manual`. The default value is `auto` which always draws edges under nodes.\n * `manual` ignores this convention and draws based on the `z-index` value setting.\n * z-index: An integer value that affects the relative draw order of elements. In general, an element with a higher\n * `z-index` will be drawn on top of an element with a lower `z-index`.\n */\nvar zIndexSort = function zIndexSort(a, b) {\n var cy = a.cy();\n var hasCompoundNodes = cy.hasCompoundNodes();\n function getDepth(ele) {\n var style = ele.pstyle('z-compound-depth');\n if (style.value === 'auto') {\n return hasCompoundNodes ? ele.zDepth() : 0;\n } else if (style.value === 'bottom') {\n return -1;\n } else if (style.value === 'top') {\n return MAX_INT$1;\n }\n // 'orphan'\n return 0;\n }\n var depthDiff = getDepth(a) - getDepth(b);\n if (depthDiff !== 0) {\n return depthDiff;\n }\n function getEleDepth(ele) {\n var style = ele.pstyle('z-index-compare');\n if (style.value === 'auto') {\n return ele.isNode() ? 1 : 0;\n }\n // 'manual'\n return 0;\n }\n var eleDiff = getEleDepth(a) - getEleDepth(b);\n if (eleDiff !== 0) {\n return eleDiff;\n }\n var zDiff = a.pstyle('z-index').value - b.pstyle('z-index').value;\n if (zDiff !== 0) {\n return zDiff;\n }\n // compare indices in the core (order added to graph w/ last on top)\n return a.poolIndex() - b.poolIndex();\n};\n\nvar elesfn$6 = {\n forEach: function forEach(fn, thisArg) {\n if (fn$6(fn)) {\n var N = this.length;\n for (var i = 0; i < N; i++) {\n var ele = this[i];\n var ret = thisArg ? fn.apply(thisArg, [ele, i, this]) : fn(ele, i, this);\n if (ret === false) {\n break;\n } // exit each early on return false\n }\n }\n return this;\n },\n toArray: function toArray() {\n var array = [];\n for (var i = 0; i < this.length; i++) {\n array.push(this[i]);\n }\n return array;\n },\n slice: function slice(start, end) {\n var array = [];\n var thisSize = this.length;\n if (end == null) {\n end = thisSize;\n }\n if (start == null) {\n start = 0;\n }\n if (start < 0) {\n start = thisSize + start;\n }\n if (end < 0) {\n end = thisSize + end;\n }\n for (var i = start; i >= 0 && i < end && i < thisSize; i++) {\n array.push(this[i]);\n }\n return this.spawn(array);\n },\n size: function size() {\n return this.length;\n },\n eq: function eq(i) {\n return this[i] || this.spawn();\n },\n first: function first() {\n return this[0] || this.spawn();\n },\n last: function last() {\n return this[this.length - 1] || this.spawn();\n },\n empty: function empty() {\n return this.length === 0;\n },\n nonempty: function nonempty() {\n return !this.empty();\n },\n sort: function sort(sortFn) {\n if (!fn$6(sortFn)) {\n return this;\n }\n var sorted = this.toArray().sort(sortFn);\n return this.spawn(sorted);\n },\n sortByZIndex: function sortByZIndex() {\n return this.sort(zIndexSort);\n },\n zDepth: function zDepth() {\n var ele = this[0];\n if (!ele) {\n return undefined;\n }\n\n // let cy = ele.cy();\n var _p = ele._private;\n var group = _p.group;\n if (group === 'nodes') {\n var depth = _p.data.parent ? ele.parents().size() : 0;\n if (!ele.isParent()) {\n return MAX_INT$1 - 1; // childless nodes always on top\n }\n return depth;\n } else {\n var src = _p.source;\n var tgt = _p.target;\n var srcDepth = src.zDepth();\n var tgtDepth = tgt.zDepth();\n return Math.max(srcDepth, tgtDepth, 0); // depth of deepest parent\n }\n }\n};\nelesfn$6.each = elesfn$6.forEach;\nvar defineSymbolIterator = function defineSymbolIterator() {\n var typeofUndef = \"undefined\" ;\n var isIteratorSupported = (typeof Symbol === \"undefined\" ? \"undefined\" : _typeof(Symbol)) != typeofUndef && _typeof(Symbol.iterator) != typeofUndef;\n if (isIteratorSupported) {\n elesfn$6[Symbol.iterator] = function () {\n var _this = this;\n var entry = {\n value: undefined,\n done: false\n };\n var i = 0;\n var length = this.length;\n return _defineProperty$1({\n next: function next() {\n if (i < length) {\n entry.value = _this[i++];\n } else {\n entry.value = undefined;\n entry.done = true;\n }\n return entry;\n }\n }, Symbol.iterator, function () {\n return this;\n });\n };\n }\n};\ndefineSymbolIterator();\n\nvar getLayoutDimensionOptions = defaults$g({\n nodeDimensionsIncludeLabels: false\n});\nvar elesfn$5 = {\n // Calculates and returns node dimensions { x, y } based on options given\n layoutDimensions: function layoutDimensions(options) {\n options = getLayoutDimensionOptions(options);\n var dims;\n if (!this.takesUpSpace()) {\n dims = {\n w: 0,\n h: 0\n };\n } else if (options.nodeDimensionsIncludeLabels) {\n var bbDim = this.boundingBox();\n dims = {\n w: bbDim.w,\n h: bbDim.h\n };\n } else {\n dims = {\n w: this.outerWidth(),\n h: this.outerHeight()\n };\n }\n\n // sanitise the dimensions for external layouts (avoid division by zero)\n if (dims.w === 0 || dims.h === 0) {\n dims.w = dims.h = 1;\n }\n return dims;\n },\n // using standard layout options, apply position function (w/ or w/o animation)\n layoutPositions: function layoutPositions(layout, options, fn) {\n var nodes = this.nodes().filter(function (n) {\n return !n.isParent();\n });\n var cy = this.cy();\n var layoutEles = options.eles; // nodes & edges\n var getMemoizeKey = function getMemoizeKey(node) {\n return node.id();\n };\n var fnMem = memoize(fn, getMemoizeKey); // memoized version of position function\n\n layout.emit({\n type: 'layoutstart',\n layout: layout\n });\n layout.animations = [];\n var calculateSpacing = function calculateSpacing(spacing, nodesBb, pos) {\n var center = {\n x: nodesBb.x1 + nodesBb.w / 2,\n y: nodesBb.y1 + nodesBb.h / 2\n };\n var spacingVector = {\n // scale from center of bounding box (not necessarily 0,0)\n x: (pos.x - center.x) * spacing,\n y: (pos.y - center.y) * spacing\n };\n return {\n x: center.x + spacingVector.x,\n y: center.y + spacingVector.y\n };\n };\n var useSpacingFactor = options.spacingFactor && options.spacingFactor !== 1;\n var spacingBb = function spacingBb() {\n if (!useSpacingFactor) {\n return null;\n }\n var bb = makeBoundingBox();\n for (var i = 0; i < nodes.length; i++) {\n var node = nodes[i];\n var pos = fnMem(node, i);\n expandBoundingBoxByPoint(bb, pos.x, pos.y);\n }\n return bb;\n };\n var bb = spacingBb();\n var getFinalPos = memoize(function (node, i) {\n var newPos = fnMem(node, i);\n if (useSpacingFactor) {\n var spacing = Math.abs(options.spacingFactor);\n newPos = calculateSpacing(spacing, bb, newPos);\n }\n if (options.transform != null) {\n newPos = options.transform(node, newPos);\n }\n return newPos;\n }, getMemoizeKey);\n if (options.animate) {\n for (var i = 0; i < nodes.length; i++) {\n var node = nodes[i];\n var newPos = getFinalPos(node, i);\n var animateNode = options.animateFilter == null || options.animateFilter(node, i);\n if (animateNode) {\n var ani = node.animation({\n position: newPos,\n duration: options.animationDuration,\n easing: options.animationEasing\n });\n layout.animations.push(ani);\n } else {\n node.position(newPos);\n }\n }\n if (options.fit) {\n var fitAni = cy.animation({\n fit: {\n boundingBox: layoutEles.boundingBoxAt(getFinalPos),\n padding: options.padding\n },\n duration: options.animationDuration,\n easing: options.animationEasing\n });\n layout.animations.push(fitAni);\n } else if (options.zoom !== undefined && options.pan !== undefined) {\n var zoomPanAni = cy.animation({\n zoom: options.zoom,\n pan: options.pan,\n duration: options.animationDuration,\n easing: options.animationEasing\n });\n layout.animations.push(zoomPanAni);\n }\n layout.animations.forEach(function (ani) {\n return ani.play();\n });\n layout.one('layoutready', options.ready);\n layout.emit({\n type: 'layoutready',\n layout: layout\n });\n Promise$1.all(layout.animations.map(function (ani) {\n return ani.promise();\n })).then(function () {\n layout.one('layoutstop', options.stop);\n layout.emit({\n type: 'layoutstop',\n layout: layout\n });\n });\n } else {\n nodes.positions(getFinalPos);\n if (options.fit) {\n cy.fit(options.eles, options.padding);\n }\n if (options.zoom != null) {\n cy.zoom(options.zoom);\n }\n if (options.pan) {\n cy.pan(options.pan);\n }\n layout.one('layoutready', options.ready);\n layout.emit({\n type: 'layoutready',\n layout: layout\n });\n layout.one('layoutstop', options.stop);\n layout.emit({\n type: 'layoutstop',\n layout: layout\n });\n }\n return this; // chaining\n },\n layout: function layout(options) {\n var cy = this.cy();\n return cy.makeLayout(extend({}, options, {\n eles: this\n }));\n }\n};\n\n// aliases:\nelesfn$5.createLayout = elesfn$5.makeLayout = elesfn$5.layout;\n\nfunction styleCache(key, fn, ele) {\n var _p = ele._private;\n var cache = _p.styleCache = _p.styleCache || [];\n var val;\n if ((val = cache[key]) != null) {\n return val;\n } else {\n val = cache[key] = fn(ele);\n return val;\n }\n}\nfunction cacheStyleFunction(key, fn) {\n key = hashString(key);\n return function cachedStyleFunction(ele) {\n return styleCache(key, fn, ele);\n };\n}\nfunction cachePrototypeStyleFunction(key, fn) {\n key = hashString(key);\n var selfFn = function selfFn(ele) {\n return fn.call(ele);\n };\n return function cachedPrototypeStyleFunction() {\n var ele = this[0];\n if (ele) {\n return styleCache(key, selfFn, ele);\n }\n };\n}\nvar elesfn$4 = {\n recalculateRenderedStyle: function recalculateRenderedStyle(useCache) {\n var cy = this.cy();\n var renderer = cy.renderer();\n var styleEnabled = cy.styleEnabled();\n if (renderer && styleEnabled) {\n renderer.recalculateRenderedStyle(this, useCache);\n }\n return this;\n },\n dirtyStyleCache: function dirtyStyleCache() {\n var cy = this.cy();\n var dirty = function dirty(ele) {\n return ele._private.styleCache = null;\n };\n if (cy.hasCompoundNodes()) {\n var eles;\n eles = this.spawnSelf().merge(this.descendants()).merge(this.parents());\n eles.merge(eles.connectedEdges());\n eles.forEach(dirty);\n } else {\n this.forEach(function (ele) {\n dirty(ele);\n ele.connectedEdges().forEach(dirty);\n });\n }\n return this;\n },\n // fully updates (recalculates) the style for the elements\n updateStyle: function updateStyle(notifyRenderer) {\n var cy = this._private.cy;\n if (!cy.styleEnabled()) {\n return this;\n }\n if (cy.batching()) {\n var bEles = cy._private.batchStyleEles;\n bEles.merge(this);\n return this; // chaining and exit early when batching\n }\n var hasCompounds = cy.hasCompoundNodes();\n var updatedEles = this;\n notifyRenderer = notifyRenderer || notifyRenderer === undefined ? true : false;\n if (hasCompounds) {\n // then add everything up and down for compound selector checks\n updatedEles = this.spawnSelf().merge(this.descendants()).merge(this.parents());\n }\n\n // let changedEles = style.apply( updatedEles );\n var changedEles = updatedEles;\n if (notifyRenderer) {\n changedEles.emitAndNotify('style'); // let renderer know we changed style\n } else {\n changedEles.emit('style'); // just fire the event\n }\n updatedEles.forEach(function (ele) {\n return ele._private.styleDirty = true;\n });\n return this; // chaining\n },\n // private: clears dirty flag and recalculates style\n cleanStyle: function cleanStyle() {\n var cy = this.cy();\n if (!cy.styleEnabled()) {\n return;\n }\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n if (ele._private.styleDirty) {\n // n.b. this flag should be set before apply() to avoid potential infinite recursion\n ele._private.styleDirty = false;\n cy.style().apply(ele);\n }\n }\n },\n // get the internal parsed style object for the specified property\n parsedStyle: function parsedStyle(property) {\n var includeNonDefault = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n var ele = this[0];\n var cy = ele.cy();\n if (!cy.styleEnabled()) {\n return;\n }\n if (ele) {\n // this.cleanStyle();\n\n // Inline the important part of cleanStyle(), for raw performance\n if (ele._private.styleDirty) {\n // n.b. this flag should be set before apply() to avoid potential infinite recursion\n ele._private.styleDirty = false;\n cy.style().apply(ele);\n }\n var overriddenStyle = ele._private.style[property];\n if (overriddenStyle != null) {\n return overriddenStyle;\n } else if (includeNonDefault) {\n return cy.style().getDefaultProperty(property);\n } else {\n return null;\n }\n }\n },\n numericStyle: function numericStyle(property) {\n var ele = this[0];\n if (!ele.cy().styleEnabled()) {\n return;\n }\n if (ele) {\n var pstyle = ele.pstyle(property);\n return pstyle.pfValue !== undefined ? pstyle.pfValue : pstyle.value;\n }\n },\n numericStyleUnits: function numericStyleUnits(property) {\n var ele = this[0];\n if (!ele.cy().styleEnabled()) {\n return;\n }\n if (ele) {\n return ele.pstyle(property).units;\n }\n },\n // get the specified css property as a rendered value (i.e. on-screen value)\n // or get the whole rendered style if no property specified (NB doesn't allow setting)\n renderedStyle: function renderedStyle(property) {\n var cy = this.cy();\n if (!cy.styleEnabled()) {\n return this;\n }\n var ele = this[0];\n if (ele) {\n return cy.style().getRenderedStyle(ele, property);\n }\n },\n // read the calculated css style of the element or override the style (via a bypass)\n style: function style(name, value) {\n var cy = this.cy();\n if (!cy.styleEnabled()) {\n return this;\n }\n var updateTransitions = false;\n var style = cy.style();\n if (plainObject(name)) {\n // then extend the bypass\n var props = name;\n style.applyBypass(this, props, updateTransitions);\n this.emitAndNotify('style'); // let the renderer know we've updated style\n } else if (string(name)) {\n if (value === undefined) {\n // then get the property from the style\n var ele = this[0];\n if (ele) {\n return style.getStylePropertyValue(ele, name);\n } else {\n // empty collection => can't get any value\n return;\n }\n } else {\n // then set the bypass with the property value\n style.applyBypass(this, name, value, updateTransitions);\n this.emitAndNotify('style'); // let the renderer know we've updated style\n }\n } else if (name === undefined) {\n var _ele = this[0];\n if (_ele) {\n return style.getRawStyle(_ele);\n } else {\n // empty collection => can't get any value\n return;\n }\n }\n return this; // chaining\n },\n removeStyle: function removeStyle(names) {\n var cy = this.cy();\n if (!cy.styleEnabled()) {\n return this;\n }\n var updateTransitions = false;\n var style = cy.style();\n var eles = this;\n if (names === undefined) {\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n style.removeAllBypasses(ele, updateTransitions);\n }\n } else {\n names = names.split(/\\s+/);\n for (var _i = 0; _i < eles.length; _i++) {\n var _ele2 = eles[_i];\n style.removeBypasses(_ele2, names, updateTransitions);\n }\n }\n this.emitAndNotify('style'); // let the renderer know we've updated style\n\n return this; // chaining\n },\n show: function show() {\n this.css('display', 'element');\n return this; // chaining\n },\n hide: function hide() {\n this.css('display', 'none');\n return this; // chaining\n },\n effectiveOpacity: function effectiveOpacity() {\n var cy = this.cy();\n if (!cy.styleEnabled()) {\n return 1;\n }\n var hasCompoundNodes = cy.hasCompoundNodes();\n var ele = this[0];\n if (ele) {\n var _p = ele._private;\n var parentOpacity = ele.pstyle('opacity').value;\n if (!hasCompoundNodes) {\n return parentOpacity;\n }\n var parents = !_p.data.parent ? null : ele.parents();\n if (parents) {\n for (var i = 0; i < parents.length; i++) {\n var parent = parents[i];\n var opacity = parent.pstyle('opacity').value;\n parentOpacity = opacity * parentOpacity;\n }\n }\n return parentOpacity;\n }\n },\n transparent: function transparent() {\n var cy = this.cy();\n if (!cy.styleEnabled()) {\n return false;\n }\n var ele = this[0];\n var hasCompoundNodes = ele.cy().hasCompoundNodes();\n if (ele) {\n if (!hasCompoundNodes) {\n return ele.pstyle('opacity').value === 0;\n } else {\n return ele.effectiveOpacity() === 0;\n }\n }\n },\n backgrounding: function backgrounding() {\n var cy = this.cy();\n if (!cy.styleEnabled()) {\n return false;\n }\n var ele = this[0];\n return ele._private.backgrounding ? true : false;\n }\n};\nfunction checkCompound(ele, parentOk) {\n var _p = ele._private;\n var parents = _p.data.parent ? ele.parents() : null;\n if (parents) {\n for (var i = 0; i < parents.length; i++) {\n var parent = parents[i];\n if (!parentOk(parent)) {\n return false;\n }\n }\n }\n return true;\n}\nfunction defineDerivedStateFunction(specs) {\n var ok = specs.ok;\n var edgeOkViaNode = specs.edgeOkViaNode || specs.ok;\n var parentOk = specs.parentOk || specs.ok;\n return function () {\n var cy = this.cy();\n if (!cy.styleEnabled()) {\n return true;\n }\n var ele = this[0];\n var hasCompoundNodes = cy.hasCompoundNodes();\n if (ele) {\n var _p = ele._private;\n if (!ok(ele)) {\n return false;\n }\n if (ele.isNode()) {\n return !hasCompoundNodes || checkCompound(ele, parentOk);\n } else {\n var src = _p.source;\n var tgt = _p.target;\n return edgeOkViaNode(src) && (!hasCompoundNodes || checkCompound(src, edgeOkViaNode)) && (src === tgt || edgeOkViaNode(tgt) && (!hasCompoundNodes || checkCompound(tgt, edgeOkViaNode)));\n }\n }\n };\n}\nvar eleTakesUpSpace = cacheStyleFunction('eleTakesUpSpace', function (ele) {\n return ele.pstyle('display').value === 'element' && ele.width() !== 0 && (ele.isNode() ? ele.height() !== 0 : true);\n});\nelesfn$4.takesUpSpace = cachePrototypeStyleFunction('takesUpSpace', defineDerivedStateFunction({\n ok: eleTakesUpSpace\n}));\nvar eleInteractive = cacheStyleFunction('eleInteractive', function (ele) {\n return ele.pstyle('events').value === 'yes' && ele.pstyle('visibility').value === 'visible' && eleTakesUpSpace(ele);\n});\nvar parentInteractive = cacheStyleFunction('parentInteractive', function (parent) {\n return parent.pstyle('visibility').value === 'visible' && eleTakesUpSpace(parent);\n});\nelesfn$4.interactive = cachePrototypeStyleFunction('interactive', defineDerivedStateFunction({\n ok: eleInteractive,\n parentOk: parentInteractive,\n edgeOkViaNode: eleTakesUpSpace\n}));\nelesfn$4.noninteractive = function () {\n var ele = this[0];\n if (ele) {\n return !ele.interactive();\n }\n};\nvar eleVisible = cacheStyleFunction('eleVisible', function (ele) {\n return ele.pstyle('visibility').value === 'visible' && ele.pstyle('opacity').pfValue !== 0 && eleTakesUpSpace(ele);\n});\nvar edgeVisibleViaNode = eleTakesUpSpace;\nelesfn$4.visible = cachePrototypeStyleFunction('visible', defineDerivedStateFunction({\n ok: eleVisible,\n edgeOkViaNode: edgeVisibleViaNode\n}));\nelesfn$4.hidden = function () {\n var ele = this[0];\n if (ele) {\n return !ele.visible();\n }\n};\nelesfn$4.isBundledBezier = cachePrototypeStyleFunction('isBundledBezier', function () {\n if (!this.cy().styleEnabled()) {\n return false;\n }\n return !this.removed() && this.pstyle('curve-style').value === 'bezier' && this.takesUpSpace();\n});\nelesfn$4.bypass = elesfn$4.css = elesfn$4.style;\nelesfn$4.renderedCss = elesfn$4.renderedStyle;\nelesfn$4.removeBypass = elesfn$4.removeCss = elesfn$4.removeStyle;\nelesfn$4.pstyle = elesfn$4.parsedStyle;\n\nvar elesfn$3 = {};\nfunction defineSwitchFunction(params) {\n return function () {\n var args = arguments;\n var changedEles = [];\n\n // e.g. cy.nodes().select( data, handler )\n if (args.length === 2) {\n var data = args[0];\n var handler = args[1];\n this.on(params.event, data, handler);\n }\n\n // e.g. cy.nodes().select( handler )\n else if (args.length === 1 && fn$6(args[0])) {\n var _handler = args[0];\n this.on(params.event, _handler);\n }\n\n // e.g. cy.nodes().select()\n // e.g. (private) cy.nodes().select(['tapselect'])\n else if (args.length === 0 || args.length === 1 && array(args[0])) {\n var addlEvents = args.length === 1 ? args[0] : null;\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n var able = !params.ableField || ele._private[params.ableField];\n var changed = ele._private[params.field] != params.value;\n if (params.overrideAble) {\n var overrideAble = params.overrideAble(ele);\n if (overrideAble !== undefined) {\n able = overrideAble;\n if (!overrideAble) {\n return this;\n } // to save cycles assume not able for all on override\n }\n }\n if (able) {\n ele._private[params.field] = params.value;\n if (changed) {\n changedEles.push(ele);\n }\n }\n }\n var changedColl = this.spawn(changedEles);\n changedColl.updateStyle(); // change of state => possible change of style\n changedColl.emit(params.event);\n if (addlEvents) {\n changedColl.emit(addlEvents);\n }\n }\n return this;\n };\n}\nfunction defineSwitchSet(params) {\n elesfn$3[params.field] = function () {\n var ele = this[0];\n if (ele) {\n if (params.overrideField) {\n var val = params.overrideField(ele);\n if (val !== undefined) {\n return val;\n }\n }\n return ele._private[params.field];\n }\n };\n elesfn$3[params.on] = defineSwitchFunction({\n event: params.on,\n field: params.field,\n ableField: params.ableField,\n overrideAble: params.overrideAble,\n value: true\n });\n elesfn$3[params.off] = defineSwitchFunction({\n event: params.off,\n field: params.field,\n ableField: params.ableField,\n overrideAble: params.overrideAble,\n value: false\n });\n}\ndefineSwitchSet({\n field: 'locked',\n overrideField: function overrideField(ele) {\n return ele.cy().autolock() ? true : undefined;\n },\n on: 'lock',\n off: 'unlock'\n});\ndefineSwitchSet({\n field: 'grabbable',\n overrideField: function overrideField(ele) {\n return ele.cy().autoungrabify() || ele.pannable() ? false : undefined;\n },\n on: 'grabify',\n off: 'ungrabify'\n});\ndefineSwitchSet({\n field: 'selected',\n ableField: 'selectable',\n overrideAble: function overrideAble(ele) {\n return ele.cy().autounselectify() ? false : undefined;\n },\n on: 'select',\n off: 'unselect'\n});\ndefineSwitchSet({\n field: 'selectable',\n overrideField: function overrideField(ele) {\n return ele.cy().autounselectify() ? false : undefined;\n },\n on: 'selectify',\n off: 'unselectify'\n});\nelesfn$3.deselect = elesfn$3.unselect;\nelesfn$3.grabbed = function () {\n var ele = this[0];\n if (ele) {\n return ele._private.grabbed;\n }\n};\ndefineSwitchSet({\n field: 'active',\n on: 'activate',\n off: 'unactivate'\n});\ndefineSwitchSet({\n field: 'pannable',\n on: 'panify',\n off: 'unpanify'\n});\nelesfn$3.inactive = function () {\n var ele = this[0];\n if (ele) {\n return !ele._private.active;\n }\n};\n\nvar elesfn$2 = {};\n\n// DAG functions\n////////////////\n\nvar defineDagExtremity = function defineDagExtremity(params) {\n return function dagExtremityImpl(selector) {\n var eles = this;\n var ret = [];\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n if (!ele.isNode()) {\n continue;\n }\n var disqualified = false;\n var edges = ele.connectedEdges();\n for (var j = 0; j < edges.length; j++) {\n var edge = edges[j];\n var src = edge.source();\n var tgt = edge.target();\n if (params.noIncomingEdges && tgt === ele && src !== ele || params.noOutgoingEdges && src === ele && tgt !== ele) {\n disqualified = true;\n break;\n }\n }\n if (!disqualified) {\n ret.push(ele);\n }\n }\n return this.spawn(ret, true).filter(selector);\n };\n};\nvar defineDagOneHop = function defineDagOneHop(params) {\n return function (selector) {\n var eles = this;\n var oEles = [];\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n if (!ele.isNode()) {\n continue;\n }\n var edges = ele.connectedEdges();\n for (var j = 0; j < edges.length; j++) {\n var edge = edges[j];\n var src = edge.source();\n var tgt = edge.target();\n if (params.outgoing && src === ele) {\n oEles.push(edge);\n oEles.push(tgt);\n } else if (params.incoming && tgt === ele) {\n oEles.push(edge);\n oEles.push(src);\n }\n }\n }\n return this.spawn(oEles, true).filter(selector);\n };\n};\nvar defineDagAllHops = function defineDagAllHops(params) {\n return function (selector) {\n var eles = this;\n var sEles = [];\n var sElesIds = {};\n for (;;) {\n var next = params.outgoing ? eles.outgoers() : eles.incomers();\n if (next.length === 0) {\n break;\n } // done if none left\n\n var newNext = false;\n for (var i = 0; i < next.length; i++) {\n var n = next[i];\n var nid = n.id();\n if (!sElesIds[nid]) {\n sElesIds[nid] = true;\n sEles.push(n);\n newNext = true;\n }\n }\n if (!newNext) {\n break;\n } // done if touched all outgoers already\n\n eles = next;\n }\n return this.spawn(sEles, true).filter(selector);\n };\n};\nelesfn$2.clearTraversalCache = function () {\n for (var i = 0; i < this.length; i++) {\n this[i]._private.traversalCache = null;\n }\n};\nextend(elesfn$2, {\n // get the root nodes in the DAG\n roots: defineDagExtremity({\n noIncomingEdges: true\n }),\n // get the leaf nodes in the DAG\n leaves: defineDagExtremity({\n noOutgoingEdges: true\n }),\n // normally called children in graph theory\n // these nodes =edges=> outgoing nodes\n outgoers: cache(defineDagOneHop({\n outgoing: true\n }), 'outgoers'),\n // aka DAG descendants\n successors: defineDagAllHops({\n outgoing: true\n }),\n // normally called parents in graph theory\n // these nodes <=edges= incoming nodes\n incomers: cache(defineDagOneHop({\n incoming: true\n }), 'incomers'),\n // aka DAG ancestors\n predecessors: defineDagAllHops({\n })\n});\n\n// Neighbourhood functions\n//////////////////////////\n\nextend(elesfn$2, {\n neighborhood: cache(function (selector) {\n var elements = [];\n var nodes = this.nodes();\n for (var i = 0; i < nodes.length; i++) {\n // for all nodes\n var node = nodes[i];\n var connectedEdges = node.connectedEdges();\n\n // for each connected edge, add the edge and the other node\n for (var j = 0; j < connectedEdges.length; j++) {\n var edge = connectedEdges[j];\n var src = edge.source();\n var tgt = edge.target();\n var otherNode = node === src ? tgt : src;\n\n // need check in case of loop\n if (otherNode.length > 0) {\n elements.push(otherNode[0]); // add node 1 hop away\n }\n\n // add connected edge\n elements.push(edge[0]);\n }\n }\n return this.spawn(elements, true).filter(selector);\n }, 'neighborhood'),\n closedNeighborhood: function closedNeighborhood(selector) {\n return this.neighborhood().add(this).filter(selector);\n },\n openNeighborhood: function openNeighborhood(selector) {\n return this.neighborhood(selector);\n }\n});\n\n// aliases\nelesfn$2.neighbourhood = elesfn$2.neighborhood;\nelesfn$2.closedNeighbourhood = elesfn$2.closedNeighborhood;\nelesfn$2.openNeighbourhood = elesfn$2.openNeighborhood;\n\n// Edge functions\n/////////////////\n\nextend(elesfn$2, {\n source: cache(function sourceImpl(selector) {\n var ele = this[0];\n var src;\n if (ele) {\n src = ele._private.source || ele.cy().collection();\n }\n return src && selector ? src.filter(selector) : src;\n }, 'source'),\n target: cache(function targetImpl(selector) {\n var ele = this[0];\n var tgt;\n if (ele) {\n tgt = ele._private.target || ele.cy().collection();\n }\n return tgt && selector ? tgt.filter(selector) : tgt;\n }, 'target'),\n sources: defineSourceFunction({\n attr: 'source'\n }),\n targets: defineSourceFunction({\n attr: 'target'\n })\n});\nfunction defineSourceFunction(params) {\n return function sourceImpl(selector) {\n var sources = [];\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n var src = ele._private[params.attr];\n if (src) {\n sources.push(src);\n }\n }\n return this.spawn(sources, true).filter(selector);\n };\n}\nextend(elesfn$2, {\n edgesWith: cache(defineEdgesWithFunction(), 'edgesWith'),\n edgesTo: cache(defineEdgesWithFunction({\n thisIsSrc: true\n }), 'edgesTo')\n});\nfunction defineEdgesWithFunction(params) {\n return function edgesWithImpl(otherNodes) {\n var elements = [];\n var cy = this._private.cy;\n var p = params || {};\n\n // get elements if a selector is specified\n if (string(otherNodes)) {\n otherNodes = cy.$(otherNodes);\n }\n for (var h = 0; h < otherNodes.length; h++) {\n var edges = otherNodes[h]._private.edges;\n for (var i = 0; i < edges.length; i++) {\n var edge = edges[i];\n var edgeData = edge._private.data;\n var thisToOther = this.hasElementWithId(edgeData.source) && otherNodes.hasElementWithId(edgeData.target);\n var otherToThis = otherNodes.hasElementWithId(edgeData.source) && this.hasElementWithId(edgeData.target);\n var edgeConnectsThisAndOther = thisToOther || otherToThis;\n if (!edgeConnectsThisAndOther) {\n continue;\n }\n if (p.thisIsSrc || p.thisIsTgt) {\n if (p.thisIsSrc && !thisToOther) {\n continue;\n }\n if (p.thisIsTgt && !otherToThis) {\n continue;\n }\n }\n elements.push(edge);\n }\n }\n return this.spawn(elements, true);\n };\n}\nextend(elesfn$2, {\n connectedEdges: cache(function (selector) {\n var retEles = [];\n var eles = this;\n for (var i = 0; i < eles.length; i++) {\n var node = eles[i];\n if (!node.isNode()) {\n continue;\n }\n var edges = node._private.edges;\n for (var j = 0; j < edges.length; j++) {\n var edge = edges[j];\n retEles.push(edge);\n }\n }\n return this.spawn(retEles, true).filter(selector);\n }, 'connectedEdges'),\n connectedNodes: cache(function (selector) {\n var retEles = [];\n var eles = this;\n for (var i = 0; i < eles.length; i++) {\n var edge = eles[i];\n if (!edge.isEdge()) {\n continue;\n }\n retEles.push(edge.source()[0]);\n retEles.push(edge.target()[0]);\n }\n return this.spawn(retEles, true).filter(selector);\n }, 'connectedNodes'),\n parallelEdges: cache(defineParallelEdgesFunction(), 'parallelEdges'),\n codirectedEdges: cache(defineParallelEdgesFunction({\n codirected: true\n }), 'codirectedEdges')\n});\nfunction defineParallelEdgesFunction(params) {\n var defaults = {\n codirected: false\n };\n params = extend({}, defaults, params);\n return function parallelEdgesImpl(selector) {\n // micro-optimised for renderer\n var elements = [];\n var edges = this.edges();\n var p = params;\n\n // look at all the edges in the collection\n for (var i = 0; i < edges.length; i++) {\n var edge1 = edges[i];\n var edge1_p = edge1._private;\n var src1 = edge1_p.source;\n var srcid1 = src1._private.data.id;\n var tgtid1 = edge1_p.data.target;\n var srcEdges1 = src1._private.edges;\n\n // look at edges connected to the src node of this edge\n for (var j = 0; j < srcEdges1.length; j++) {\n var edge2 = srcEdges1[j];\n var edge2data = edge2._private.data;\n var tgtid2 = edge2data.target;\n var srcid2 = edge2data.source;\n var codirected = tgtid2 === tgtid1 && srcid2 === srcid1;\n var oppdirected = srcid1 === tgtid2 && tgtid1 === srcid2;\n if (p.codirected && codirected || !p.codirected && (codirected || oppdirected)) {\n elements.push(edge2);\n }\n }\n }\n return this.spawn(elements, true).filter(selector);\n };\n}\n\n// Misc functions\n/////////////////\n\nextend(elesfn$2, {\n components: function components(root) {\n var self = this;\n var cy = self.cy();\n var visited = cy.collection();\n var unvisited = root == null ? self.nodes() : root.nodes();\n var components = [];\n if (root != null && unvisited.empty()) {\n // root may contain only edges\n unvisited = root.sources(); // doesn't matter which node to use (undirected), so just use the source sides\n }\n var visitInComponent = function visitInComponent(node, component) {\n visited.merge(node);\n unvisited.unmerge(node);\n component.merge(node);\n };\n if (unvisited.empty()) {\n return self.spawn();\n }\n var _loop = function _loop() {\n // each iteration yields a component\n var cmpt = cy.collection();\n components.push(cmpt);\n var root = unvisited[0];\n visitInComponent(root, cmpt);\n self.bfs({\n directed: false,\n roots: root,\n visit: function visit(v) {\n return visitInComponent(v, cmpt);\n }\n });\n cmpt.forEach(function (node) {\n node.connectedEdges().forEach(function (e) {\n // connectedEdges() usually cached\n if (self.has(e) && cmpt.has(e.source()) && cmpt.has(e.target())) {\n // has() is cheap\n cmpt.merge(e); // forEach() only considers nodes -- sets N at call time\n }\n });\n });\n };\n do {\n _loop();\n } while (unvisited.length > 0);\n return components;\n },\n component: function component() {\n var ele = this[0];\n return ele.cy().mutableElements().components(ele)[0];\n }\n});\nelesfn$2.componentsOf = elesfn$2.components;\n\n// represents a set of nodes, edges, or both together\nvar Collection = function Collection(cy, elements) {\n var unique = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n var removed = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n if (cy === undefined) {\n error('A collection must have a reference to the core');\n return;\n }\n var map = new Map$1();\n var createdElements = false;\n if (!elements) {\n elements = [];\n } else if (elements.length > 0 && plainObject(elements[0]) && !element(elements[0])) {\n createdElements = true;\n\n // make elements from json and restore all at once later\n var eles = [];\n var elesIds = new Set$1();\n for (var i = 0, l = elements.length; i < l; i++) {\n var json = elements[i];\n if (json.data == null) {\n json.data = {};\n }\n var _data = json.data;\n\n // make sure newly created elements have valid ids\n if (_data.id == null) {\n _data.id = uuid();\n } else if (cy.hasElementWithId(_data.id) || elesIds.has(_data.id)) {\n continue; // can't create element if prior id already exists\n }\n var ele = new Element(cy, json, false);\n eles.push(ele);\n elesIds.add(_data.id);\n }\n elements = eles;\n }\n this.length = 0;\n for (var _i = 0, _l = elements.length; _i < _l; _i++) {\n var element$1 = elements[_i][0]; // [0] in case elements is an array of collections, rather than array of elements\n if (element$1 == null) {\n continue;\n }\n var id = element$1._private.data.id;\n if (!unique || !map.has(id)) {\n if (unique) {\n map.set(id, {\n index: this.length,\n ele: element$1\n });\n }\n this[this.length] = element$1;\n this.length++;\n }\n }\n this._private = {\n eles: this,\n cy: cy,\n get map() {\n if (this.lazyMap == null) {\n this.rebuildMap();\n }\n return this.lazyMap;\n },\n set map(m) {\n this.lazyMap = m;\n },\n rebuildMap: function rebuildMap() {\n var m = this.lazyMap = new Map$1();\n var eles = this.eles;\n for (var _i2 = 0; _i2 < eles.length; _i2++) {\n var _ele = eles[_i2];\n m.set(_ele.id(), {\n index: _i2,\n ele: _ele\n });\n }\n }\n };\n if (unique) {\n this._private.map = map;\n }\n\n // restore the elements if we created them from json\n if (createdElements && !removed) {\n this.restore();\n }\n};\n\n// Functions\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n// keep the prototypes in sync (an element has the same functions as a collection)\n// and use elefn and elesfn as shorthands to the prototypes\nvar elesfn$1 = Element.prototype = Collection.prototype = Object.create(Array.prototype);\nelesfn$1.instanceString = function () {\n return 'collection';\n};\nelesfn$1.spawn = function (eles, unique) {\n return new Collection(this.cy(), eles, unique);\n};\nelesfn$1.spawnSelf = function () {\n return this.spawn(this);\n};\nelesfn$1.cy = function () {\n return this._private.cy;\n};\nelesfn$1.renderer = function () {\n return this._private.cy.renderer();\n};\nelesfn$1.element = function () {\n return this[0];\n};\nelesfn$1.collection = function () {\n if (collection(this)) {\n return this;\n } else {\n // an element\n return new Collection(this._private.cy, [this]);\n }\n};\nelesfn$1.unique = function () {\n return new Collection(this._private.cy, this, true);\n};\nelesfn$1.hasElementWithId = function (id) {\n id = '' + id; // id must be string\n\n return this._private.map.has(id);\n};\nelesfn$1.getElementById = function (id) {\n id = '' + id; // id must be string\n\n var cy = this._private.cy;\n var entry = this._private.map.get(id);\n return entry ? entry.ele : new Collection(cy); // get ele or empty collection\n};\nelesfn$1.$id = elesfn$1.getElementById;\nelesfn$1.poolIndex = function () {\n var cy = this._private.cy;\n var eles = cy._private.elements;\n var id = this[0]._private.data.id;\n return eles._private.map.get(id).index;\n};\nelesfn$1.indexOf = function (ele) {\n var id = ele[0]._private.data.id;\n return this._private.map.get(id).index;\n};\nelesfn$1.indexOfId = function (id) {\n id = '' + id; // id must be string\n\n return this._private.map.get(id).index;\n};\nelesfn$1.json = function (obj) {\n var ele = this.element();\n var cy = this.cy();\n if (ele == null && obj) {\n return this;\n } // can't set to no eles\n\n if (ele == null) {\n return undefined;\n } // can't get from no eles\n\n var p = ele._private;\n if (plainObject(obj)) {\n // set\n\n cy.startBatch();\n if (obj.data) {\n ele.data(obj.data);\n var _data2 = p.data;\n if (ele.isEdge()) {\n // source and target are immutable via data()\n var move = false;\n var spec = {};\n var src = obj.data.source;\n var tgt = obj.data.target;\n if (src != null && src != _data2.source) {\n spec.source = '' + src; // id must be string\n move = true;\n }\n if (tgt != null && tgt != _data2.target) {\n spec.target = '' + tgt; // id must be string\n move = true;\n }\n if (move) {\n ele = ele.move(spec);\n }\n } else {\n // parent is immutable via data()\n var newParentValSpecd = 'parent' in obj.data;\n var parent = obj.data.parent;\n if (newParentValSpecd && (parent != null || _data2.parent != null) && parent != _data2.parent) {\n if (parent === undefined) {\n // can't set undefined imperatively, so use null\n parent = null;\n }\n if (parent != null) {\n parent = '' + parent; // id must be string\n }\n ele = ele.move({\n parent: parent\n });\n }\n }\n }\n if (obj.position) {\n ele.position(obj.position);\n }\n\n // ignore group -- immutable\n\n var checkSwitch = function checkSwitch(k, trueFnName, falseFnName) {\n var obj_k = obj[k];\n if (obj_k != null && obj_k !== p[k]) {\n if (obj_k) {\n ele[trueFnName]();\n } else {\n ele[falseFnName]();\n }\n }\n };\n checkSwitch('removed', 'remove', 'restore');\n checkSwitch('selected', 'select', 'unselect');\n checkSwitch('selectable', 'selectify', 'unselectify');\n checkSwitch('locked', 'lock', 'unlock');\n checkSwitch('grabbable', 'grabify', 'ungrabify');\n checkSwitch('pannable', 'panify', 'unpanify');\n if (obj.classes != null) {\n ele.classes(obj.classes);\n }\n cy.endBatch();\n return this;\n } else if (obj === undefined) {\n // get\n\n var json = {\n data: copy(p.data),\n position: copy(p.position),\n group: p.group,\n removed: p.removed,\n selected: p.selected,\n selectable: p.selectable,\n locked: p.locked,\n grabbable: p.grabbable,\n pannable: p.pannable,\n classes: null\n };\n json.classes = '';\n var i = 0;\n p.classes.forEach(function (cls) {\n return json.classes += i++ === 0 ? cls : ' ' + cls;\n });\n return json;\n }\n};\nelesfn$1.jsons = function () {\n var jsons = [];\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n var json = ele.json();\n jsons.push(json);\n }\n return jsons;\n};\nelesfn$1.clone = function () {\n var cy = this.cy();\n var elesArr = [];\n for (var i = 0; i < this.length; i++) {\n var ele = this[i];\n var json = ele.json();\n var clone = new Element(cy, json, false); // NB no restore\n\n elesArr.push(clone);\n }\n return new Collection(cy, elesArr);\n};\nelesfn$1.copy = elesfn$1.clone;\nelesfn$1.restore = function () {\n var notifyRenderer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;\n var addToPool = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n var self = this;\n var cy = self.cy();\n var cy_p = cy._private;\n\n // create arrays of nodes and edges, since we need to\n // restore the nodes first\n var nodes = [];\n var edges = [];\n var elements;\n for (var _i3 = 0, l = self.length; _i3 < l; _i3++) {\n var ele = self[_i3];\n if (addToPool && !ele.removed()) {\n // don't need to handle this ele\n continue;\n }\n\n // keep nodes first in the array and edges after\n if (ele.isNode()) {\n // put to front of array if node\n nodes.push(ele);\n } else {\n // put to end of array if edge\n edges.push(ele);\n }\n }\n elements = nodes.concat(edges);\n var i;\n var removeFromElements = function removeFromElements() {\n elements.splice(i, 1);\n i--;\n };\n\n // now, restore each element\n for (i = 0; i < elements.length; i++) {\n var _ele2 = elements[i];\n var _private = _ele2._private;\n var _data3 = _private.data;\n\n // the traversal cache should start fresh when ele is added\n _ele2.clearTraversalCache();\n\n // set id and validate\n if (!addToPool && !_private.removed) ; else if (_data3.id === undefined) {\n _data3.id = uuid();\n } else if (number$1(_data3.id)) {\n _data3.id = '' + _data3.id; // now it's a string\n } else if (emptyString(_data3.id) || !string(_data3.id)) {\n error('Can not create element with invalid string ID `' + _data3.id + '`');\n\n // can't create element if it has empty string as id or non-string id\n removeFromElements();\n continue;\n } else if (cy.hasElementWithId(_data3.id)) {\n error('Can not create second element with ID `' + _data3.id + '`');\n\n // can't create element if one already has that id\n removeFromElements();\n continue;\n }\n var id = _data3.id; // id is finalised, now let's keep a ref\n\n if (_ele2.isNode()) {\n // extra checks for nodes\n var pos = _private.position;\n\n // make sure the nodes have a defined position\n\n if (pos.x == null) {\n pos.x = 0;\n }\n if (pos.y == null) {\n pos.y = 0;\n }\n }\n if (_ele2.isEdge()) {\n // extra checks for edges\n\n var edge = _ele2;\n var fields = ['source', 'target'];\n var fieldsLength = fields.length;\n var badSourceOrTarget = false;\n for (var j = 0; j < fieldsLength; j++) {\n var field = fields[j];\n var val = _data3[field];\n if (number$1(val)) {\n val = _data3[field] = '' + _data3[field]; // now string\n }\n if (val == null || val === '') {\n // can't create if source or target is not defined properly\n error('Can not create edge `' + id + '` with unspecified ' + field);\n badSourceOrTarget = true;\n } else if (!cy.hasElementWithId(val)) {\n // can't create edge if one of its nodes doesn't exist\n error('Can not create edge `' + id + '` with nonexistant ' + field + ' `' + val + '`');\n badSourceOrTarget = true;\n }\n }\n if (badSourceOrTarget) {\n removeFromElements();\n continue;\n } // can't create this\n\n var src = cy.getElementById(_data3.source);\n var tgt = cy.getElementById(_data3.target);\n\n // only one edge in node if loop\n if (src.same(tgt)) {\n src._private.edges.push(edge);\n } else {\n src._private.edges.push(edge);\n tgt._private.edges.push(edge);\n }\n edge._private.source = src;\n edge._private.target = tgt;\n } // if is edge\n\n // create mock ids / indexes maps for element so it can be used like collections\n _private.map = new Map$1();\n _private.map.set(id, {\n ele: _ele2,\n index: 0\n });\n _private.removed = false;\n if (addToPool) {\n cy.addToPool(_ele2);\n }\n } // for each element\n\n // do compound node sanity checks\n for (var _i4 = 0; _i4 < nodes.length; _i4++) {\n // each node\n var node = nodes[_i4];\n var _data4 = node._private.data;\n if (number$1(_data4.parent)) {\n // then automake string\n _data4.parent = '' + _data4.parent;\n }\n var parentId = _data4.parent;\n var specifiedParent = parentId != null;\n if (specifiedParent || node._private.parent) {\n var parent = node._private.parent ? cy.collection().merge(node._private.parent) : cy.getElementById(parentId);\n if (parent.empty()) {\n // non-existant parent; just remove it\n _data4.parent = undefined;\n } else if (parent[0].removed()) {\n warn('Node added with missing parent, reference to parent removed');\n _data4.parent = undefined;\n node._private.parent = null;\n } else {\n var selfAsParent = false;\n var ancestor = parent;\n while (!ancestor.empty()) {\n if (node.same(ancestor)) {\n // mark self as parent and remove from data\n selfAsParent = true;\n _data4.parent = undefined; // remove parent reference\n\n // exit or we loop forever\n break;\n }\n ancestor = ancestor.parent();\n }\n if (!selfAsParent) {\n // connect with children\n parent[0]._private.children.push(node);\n node._private.parent = parent[0];\n\n // let the core know we have a compound graph\n cy_p.hasCompoundNodes = true;\n }\n } // else\n } // if specified parent\n } // for each node\n\n if (elements.length > 0) {\n var restored = elements.length === self.length ? self : new Collection(cy, elements);\n for (var _i5 = 0; _i5 < restored.length; _i5++) {\n var _ele3 = restored[_i5];\n if (_ele3.isNode()) {\n continue;\n }\n\n // adding an edge invalidates the traversal caches for the parallel edges\n _ele3.parallelEdges().clearTraversalCache();\n\n // adding an edge invalidates the traversal cache for the connected nodes\n _ele3.source().clearTraversalCache();\n _ele3.target().clearTraversalCache();\n }\n var toUpdateStyle;\n if (cy_p.hasCompoundNodes) {\n toUpdateStyle = cy.collection().merge(restored).merge(restored.connectedNodes()).merge(restored.parent());\n } else {\n toUpdateStyle = restored;\n }\n toUpdateStyle.dirtyCompoundBoundsCache().dirtyBoundingBoxCache().updateStyle(notifyRenderer);\n if (notifyRenderer) {\n restored.emitAndNotify('add');\n } else if (addToPool) {\n restored.emit('add');\n }\n }\n return self; // chainability\n};\nelesfn$1.removed = function () {\n var ele = this[0];\n return ele && ele._private.removed;\n};\nelesfn$1.inside = function () {\n var ele = this[0];\n return ele && !ele._private.removed;\n};\nelesfn$1.remove = function () {\n var notifyRenderer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;\n var removeFromPool = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n var self = this;\n var elesToRemove = [];\n var elesToRemoveIds = {};\n var cy = self._private.cy;\n\n // add connected edges\n function addConnectedEdges(node) {\n var edges = node._private.edges;\n for (var i = 0; i < edges.length; i++) {\n add(edges[i]);\n }\n }\n\n // add descendant nodes\n function addChildren(node) {\n var children = node._private.children;\n for (var i = 0; i < children.length; i++) {\n add(children[i]);\n }\n }\n function add(ele) {\n var alreadyAdded = elesToRemoveIds[ele.id()];\n if (removeFromPool && ele.removed() || alreadyAdded) {\n return;\n } else {\n elesToRemoveIds[ele.id()] = true;\n }\n if (ele.isNode()) {\n elesToRemove.push(ele); // nodes are removed last\n\n addConnectedEdges(ele);\n addChildren(ele);\n } else {\n elesToRemove.unshift(ele); // edges are removed first\n }\n }\n\n // make the list of elements to remove\n // (may be removing more than specified due to connected edges etc)\n\n for (var i = 0, l = self.length; i < l; i++) {\n var ele = self[i];\n add(ele);\n }\n function removeEdgeRef(node, edge) {\n var connectedEdges = node._private.edges;\n removeFromArray(connectedEdges, edge);\n\n // removing an edges invalidates the traversal cache for its nodes\n node.clearTraversalCache();\n }\n function removeParallelRef(pllEdge) {\n // removing an edge invalidates the traversal caches for the parallel edges\n pllEdge.clearTraversalCache();\n }\n var alteredParents = [];\n alteredParents.ids = {};\n function removeChildRef(parent, ele) {\n ele = ele[0];\n parent = parent[0];\n var children = parent._private.children;\n var pid = parent.id();\n removeFromArray(children, ele); // remove parent => child ref\n\n ele._private.parent = null; // remove child => parent ref\n\n if (!alteredParents.ids[pid]) {\n alteredParents.ids[pid] = true;\n alteredParents.push(parent);\n }\n }\n self.dirtyCompoundBoundsCache();\n if (removeFromPool) {\n cy.removeFromPool(elesToRemove); // remove from core pool\n }\n for (var _i6 = 0; _i6 < elesToRemove.length; _i6++) {\n var _ele4 = elesToRemove[_i6];\n if (_ele4.isEdge()) {\n // remove references to this edge in its connected nodes\n var src = _ele4.source()[0];\n var tgt = _ele4.target()[0];\n removeEdgeRef(src, _ele4);\n removeEdgeRef(tgt, _ele4);\n var pllEdges = _ele4.parallelEdges();\n for (var j = 0; j < pllEdges.length; j++) {\n var pllEdge = pllEdges[j];\n removeParallelRef(pllEdge);\n if (pllEdge.isBundledBezier()) {\n pllEdge.dirtyBoundingBoxCache();\n }\n }\n } else {\n // remove reference to parent\n var parent = _ele4.parent();\n if (parent.length !== 0) {\n removeChildRef(parent, _ele4);\n }\n }\n if (removeFromPool) {\n // mark as removed\n _ele4._private.removed = true;\n }\n }\n\n // check to see if we have a compound graph or not\n var elesStillInside = cy._private.elements;\n cy._private.hasCompoundNodes = false;\n for (var _i7 = 0; _i7 < elesStillInside.length; _i7++) {\n var _ele5 = elesStillInside[_i7];\n if (_ele5.isParent()) {\n cy._private.hasCompoundNodes = true;\n break;\n }\n }\n var removedElements = new Collection(this.cy(), elesToRemove);\n if (removedElements.size() > 0) {\n // must manually notify since trigger won't do this automatically once removed\n\n if (notifyRenderer) {\n removedElements.emitAndNotify('remove');\n } else if (removeFromPool) {\n removedElements.emit('remove');\n }\n }\n\n // the parents who were modified by the removal need their style updated\n for (var _i8 = 0; _i8 < alteredParents.length; _i8++) {\n var _ele6 = alteredParents[_i8];\n if (!removeFromPool || !_ele6.removed()) {\n _ele6.updateStyle();\n }\n }\n return removedElements;\n};\nelesfn$1.move = function (struct) {\n var cy = this._private.cy;\n var eles = this;\n\n // just clean up refs, caches, etc. in the same way as when removing and then restoring\n // (our calls to remove/restore do not remove from the graph or make events)\n var notifyRenderer = false;\n var modifyPool = false;\n var toString = function toString(id) {\n return id == null ? id : '' + id;\n }; // id must be string\n\n if (struct.source !== undefined || struct.target !== undefined) {\n var srcId = toString(struct.source);\n var tgtId = toString(struct.target);\n var srcExists = srcId != null && cy.hasElementWithId(srcId);\n var tgtExists = tgtId != null && cy.hasElementWithId(tgtId);\n if (srcExists || tgtExists) {\n cy.batch(function () {\n // avoid duplicate style updates\n eles.remove(notifyRenderer, modifyPool); // clean up refs etc.\n eles.emitAndNotify('moveout');\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n var _data5 = ele._private.data;\n if (ele.isEdge()) {\n if (srcExists) {\n _data5.source = srcId;\n }\n if (tgtExists) {\n _data5.target = tgtId;\n }\n }\n }\n eles.restore(notifyRenderer, modifyPool); // make new refs, style, etc.\n });\n eles.emitAndNotify('move');\n }\n } else if (struct.parent !== undefined) {\n // move node to new parent\n var parentId = toString(struct.parent);\n var parentExists = parentId === null || cy.hasElementWithId(parentId);\n if (parentExists) {\n var pidToAssign = parentId === null ? undefined : parentId;\n cy.batch(function () {\n // avoid duplicate style updates\n var updated = eles.remove(notifyRenderer, modifyPool); // clean up refs etc.\n updated.emitAndNotify('moveout');\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n var _data6 = ele._private.data;\n if (ele.isNode()) {\n _data6.parent = pidToAssign;\n }\n }\n updated.restore(notifyRenderer, modifyPool); // make new refs, style, etc.\n });\n eles.emitAndNotify('move');\n }\n }\n return this;\n};\n[elesfn$j, elesfn$i, elesfn$h, elesfn$g, elesfn$f, data, elesfn$d, dimensions, elesfn$9, elesfn$8, elesfn$7, elesfn$6, elesfn$5, elesfn$4, elesfn$3, elesfn$2].forEach(function (props) {\n extend(elesfn$1, props);\n});\n\nvar corefn$9 = {\n add: function add(opts) {\n var elements;\n var cy = this;\n\n // add the elements\n if (elementOrCollection(opts)) {\n var eles = opts;\n if (eles._private.cy === cy) {\n // same instance => just restore\n elements = eles.restore();\n } else {\n // otherwise, copy from json\n var jsons = [];\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n jsons.push(ele.json());\n }\n elements = new Collection(cy, jsons);\n }\n }\n\n // specify an array of options\n else if (array(opts)) {\n var _jsons = opts;\n elements = new Collection(cy, _jsons);\n }\n\n // specify via opts.nodes and opts.edges\n else if (plainObject(opts) && (array(opts.nodes) || array(opts.edges))) {\n var elesByGroup = opts;\n var _jsons2 = [];\n var grs = ['nodes', 'edges'];\n for (var _i = 0, il = grs.length; _i < il; _i++) {\n var group = grs[_i];\n var elesArray = elesByGroup[group];\n if (array(elesArray)) {\n for (var j = 0, jl = elesArray.length; j < jl; j++) {\n var json = extend({\n group: group\n }, elesArray[j]);\n _jsons2.push(json);\n }\n }\n }\n elements = new Collection(cy, _jsons2);\n }\n\n // specify options for one element\n else {\n var _json = opts;\n elements = new Element(cy, _json).collection();\n }\n return elements;\n },\n remove: function remove(collection) {\n if (elementOrCollection(collection)) ; else if (string(collection)) {\n var selector = collection;\n collection = this.$(selector);\n }\n return collection.remove();\n }\n};\n\n/* global Float32Array */\n\n/*! Bezier curve function generator. Copyright Gaetan Renaudeau. MIT License: http://en.wikipedia.org/wiki/MIT_License */\nfunction generateCubicBezier(mX1, mY1, mX2, mY2) {\n var NEWTON_ITERATIONS = 4,\n NEWTON_MIN_SLOPE = 0.001,\n SUBDIVISION_PRECISION = 0.0000001,\n SUBDIVISION_MAX_ITERATIONS = 10,\n kSplineTableSize = 11,\n kSampleStepSize = 1.0 / (kSplineTableSize - 1.0),\n float32ArraySupported = typeof Float32Array !== 'undefined';\n\n /* Must contain four arguments. */\n if (arguments.length !== 4) {\n return false;\n }\n\n /* Arguments must be numbers. */\n for (var i = 0; i < 4; ++i) {\n if (typeof arguments[i] !== \"number\" || isNaN(arguments[i]) || !isFinite(arguments[i])) {\n return false;\n }\n }\n\n /* X values must be in the [0, 1] range. */\n mX1 = Math.min(mX1, 1);\n mX2 = Math.min(mX2, 1);\n mX1 = Math.max(mX1, 0);\n mX2 = Math.max(mX2, 0);\n var mSampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);\n function A(aA1, aA2) {\n return 1.0 - 3.0 * aA2 + 3.0 * aA1;\n }\n function B(aA1, aA2) {\n return 3.0 * aA2 - 6.0 * aA1;\n }\n function C(aA1) {\n return 3.0 * aA1;\n }\n function calcBezier(aT, aA1, aA2) {\n return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;\n }\n function getSlope(aT, aA1, aA2) {\n return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);\n }\n function newtonRaphsonIterate(aX, aGuessT) {\n for (var _i = 0; _i < NEWTON_ITERATIONS; ++_i) {\n var currentSlope = getSlope(aGuessT, mX1, mX2);\n if (currentSlope === 0.0) {\n return aGuessT;\n }\n var currentX = calcBezier(aGuessT, mX1, mX2) - aX;\n aGuessT -= currentX / currentSlope;\n }\n return aGuessT;\n }\n function calcSampleValues() {\n for (var _i2 = 0; _i2 < kSplineTableSize; ++_i2) {\n mSampleValues[_i2] = calcBezier(_i2 * kSampleStepSize, mX1, mX2);\n }\n }\n function binarySubdivide(aX, aA, aB) {\n var currentX,\n currentT,\n i = 0;\n do {\n currentT = aA + (aB - aA) / 2.0;\n currentX = calcBezier(currentT, mX1, mX2) - aX;\n if (currentX > 0.0) {\n aB = currentT;\n } else {\n aA = currentT;\n }\n } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);\n return currentT;\n }\n function getTForX(aX) {\n var intervalStart = 0.0,\n currentSample = 1,\n lastSample = kSplineTableSize - 1;\n for (; currentSample !== lastSample && mSampleValues[currentSample] <= aX; ++currentSample) {\n intervalStart += kSampleStepSize;\n }\n --currentSample;\n var dist = (aX - mSampleValues[currentSample]) / (mSampleValues[currentSample + 1] - mSampleValues[currentSample]),\n guessForT = intervalStart + dist * kSampleStepSize,\n initialSlope = getSlope(guessForT, mX1, mX2);\n if (initialSlope >= NEWTON_MIN_SLOPE) {\n return newtonRaphsonIterate(aX, guessForT);\n } else if (initialSlope === 0.0) {\n return guessForT;\n } else {\n return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize);\n }\n }\n var _precomputed = false;\n function precompute() {\n _precomputed = true;\n if (mX1 !== mY1 || mX2 !== mY2) {\n calcSampleValues();\n }\n }\n var f = function f(aX) {\n if (!_precomputed) {\n precompute();\n }\n if (mX1 === mY1 && mX2 === mY2) {\n return aX;\n }\n if (aX === 0) {\n return 0;\n }\n if (aX === 1) {\n return 1;\n }\n return calcBezier(getTForX(aX), mY1, mY2);\n };\n f.getControlPoints = function () {\n return [{\n x: mX1,\n y: mY1\n }, {\n x: mX2,\n y: mY2\n }];\n };\n var str = \"generateBezier(\" + [mX1, mY1, mX2, mY2] + \")\";\n f.toString = function () {\n return str;\n };\n return f;\n}\n\n/*! Runge-Kutta spring physics function generator. Adapted from Framer.js, copyright Koen Bok. MIT License: http://en.wikipedia.org/wiki/MIT_License */\n/* Given a tension, friction, and duration, a simulation at 60FPS will first run without a defined duration in order to calculate the full path. A second pass\n then adjusts the time delta -- using the relation between actual time and duration -- to calculate the path for the duration-constrained animation. */\nvar generateSpringRK4 = function () {\n function springAccelerationForState(state) {\n return -state.tension * state.x - state.friction * state.v;\n }\n function springEvaluateStateWithDerivative(initialState, dt, derivative) {\n var state = {\n x: initialState.x + derivative.dx * dt,\n v: initialState.v + derivative.dv * dt,\n tension: initialState.tension,\n friction: initialState.friction\n };\n return {\n dx: state.v,\n dv: springAccelerationForState(state)\n };\n }\n function springIntegrateState(state, dt) {\n var a = {\n dx: state.v,\n dv: springAccelerationForState(state)\n },\n b = springEvaluateStateWithDerivative(state, dt * 0.5, a),\n c = springEvaluateStateWithDerivative(state, dt * 0.5, b),\n d = springEvaluateStateWithDerivative(state, dt, c),\n dxdt = 1.0 / 6.0 * (a.dx + 2.0 * (b.dx + c.dx) + d.dx),\n dvdt = 1.0 / 6.0 * (a.dv + 2.0 * (b.dv + c.dv) + d.dv);\n state.x = state.x + dxdt * dt;\n state.v = state.v + dvdt * dt;\n return state;\n }\n return function springRK4Factory(tension, friction, duration) {\n var initState = {\n x: -1,\n v: 0,\n tension: null,\n friction: null\n },\n path = [0],\n time_lapsed = 0,\n tolerance = 1 / 10000,\n DT = 16 / 1000,\n have_duration,\n dt,\n last_state;\n tension = parseFloat(tension) || 500;\n friction = parseFloat(friction) || 20;\n duration = duration || null;\n initState.tension = tension;\n initState.friction = friction;\n have_duration = duration !== null;\n\n /* Calculate the actual time it takes for this animation to complete with the provided conditions. */\n if (have_duration) {\n /* Run the simulation without a duration. */\n time_lapsed = springRK4Factory(tension, friction);\n /* Compute the adjusted time delta. */\n dt = time_lapsed / duration * DT;\n } else {\n dt = DT;\n }\n for (;;) {\n /* Next/step function .*/\n last_state = springIntegrateState(last_state || initState, dt);\n /* Store the position. */\n path.push(1 + last_state.x);\n time_lapsed += 16;\n /* If the change threshold is reached, break. */\n if (!(Math.abs(last_state.x) > tolerance && Math.abs(last_state.v) > tolerance)) {\n break;\n }\n }\n\n /* If duration is not defined, return the actual time required for completing this animation. Otherwise, return a closure that holds the\n computed path and returns a snapshot of the position according to a given percentComplete. */\n return !have_duration ? time_lapsed : function (percentComplete) {\n return path[percentComplete * (path.length - 1) | 0];\n };\n };\n}();\n\nvar cubicBezier = function cubicBezier(t1, p1, t2, p2) {\n var bezier = generateCubicBezier(t1, p1, t2, p2);\n return function (start, end, percent) {\n return start + (end - start) * bezier(percent);\n };\n};\nvar easings = {\n 'linear': function linear(start, end, percent) {\n return start + (end - start) * percent;\n },\n // default easings\n 'ease': cubicBezier(0.25, 0.1, 0.25, 1),\n 'ease-in': cubicBezier(0.42, 0, 1, 1),\n 'ease-out': cubicBezier(0, 0, 0.58, 1),\n 'ease-in-out': cubicBezier(0.42, 0, 0.58, 1),\n // sine\n 'ease-in-sine': cubicBezier(0.47, 0, 0.745, 0.715),\n 'ease-out-sine': cubicBezier(0.39, 0.575, 0.565, 1),\n 'ease-in-out-sine': cubicBezier(0.445, 0.05, 0.55, 0.95),\n // quad\n 'ease-in-quad': cubicBezier(0.55, 0.085, 0.68, 0.53),\n 'ease-out-quad': cubicBezier(0.25, 0.46, 0.45, 0.94),\n 'ease-in-out-quad': cubicBezier(0.455, 0.03, 0.515, 0.955),\n // cubic\n 'ease-in-cubic': cubicBezier(0.55, 0.055, 0.675, 0.19),\n 'ease-out-cubic': cubicBezier(0.215, 0.61, 0.355, 1),\n 'ease-in-out-cubic': cubicBezier(0.645, 0.045, 0.355, 1),\n // quart\n 'ease-in-quart': cubicBezier(0.895, 0.03, 0.685, 0.22),\n 'ease-out-quart': cubicBezier(0.165, 0.84, 0.44, 1),\n 'ease-in-out-quart': cubicBezier(0.77, 0, 0.175, 1),\n // quint\n 'ease-in-quint': cubicBezier(0.755, 0.05, 0.855, 0.06),\n 'ease-out-quint': cubicBezier(0.23, 1, 0.32, 1),\n 'ease-in-out-quint': cubicBezier(0.86, 0, 0.07, 1),\n // expo\n 'ease-in-expo': cubicBezier(0.95, 0.05, 0.795, 0.035),\n 'ease-out-expo': cubicBezier(0.19, 1, 0.22, 1),\n 'ease-in-out-expo': cubicBezier(1, 0, 0, 1),\n // circ\n 'ease-in-circ': cubicBezier(0.6, 0.04, 0.98, 0.335),\n 'ease-out-circ': cubicBezier(0.075, 0.82, 0.165, 1),\n 'ease-in-out-circ': cubicBezier(0.785, 0.135, 0.15, 0.86),\n // user param easings...\n\n 'spring': function spring(tension, friction, duration) {\n if (duration === 0) {\n // can't get a spring w/ duration 0\n return easings.linear; // duration 0 => jump to end so impl doesn't matter\n }\n var spring = generateSpringRK4(tension, friction, duration);\n return function (start, end, percent) {\n return start + (end - start) * spring(percent);\n };\n },\n 'cubic-bezier': cubicBezier\n};\n\nfunction getEasedValue(type, start, end, percent, easingFn) {\n if (percent === 1) {\n return end;\n }\n if (start === end) {\n return end;\n }\n var val = easingFn(start, end, percent);\n if (type == null) {\n return val;\n }\n if (type.roundValue || type.color) {\n val = Math.round(val);\n }\n if (type.min !== undefined) {\n val = Math.max(val, type.min);\n }\n if (type.max !== undefined) {\n val = Math.min(val, type.max);\n }\n return val;\n}\nfunction getValue(prop, spec) {\n if (prop.pfValue != null || prop.value != null) {\n if (prop.pfValue != null && (spec == null || spec.type.units !== '%')) {\n return prop.pfValue;\n } else {\n return prop.value;\n }\n } else {\n return prop;\n }\n}\nfunction ease(startProp, endProp, percent, easingFn, propSpec) {\n var type = propSpec != null ? propSpec.type : null;\n if (percent < 0) {\n percent = 0;\n } else if (percent > 1) {\n percent = 1;\n }\n var start = getValue(startProp, propSpec);\n var end = getValue(endProp, propSpec);\n if (number$1(start) && number$1(end)) {\n return getEasedValue(type, start, end, percent, easingFn);\n } else if (array(start) && array(end)) {\n var easedArr = [];\n for (var i = 0; i < end.length; i++) {\n var si = start[i];\n var ei = end[i];\n if (si != null && ei != null) {\n var val = getEasedValue(type, si, ei, percent, easingFn);\n easedArr.push(val);\n } else {\n easedArr.push(ei);\n }\n }\n return easedArr;\n }\n return undefined;\n}\n\nfunction step$1(self, ani, now, isCore) {\n var isEles = !isCore;\n var _p = self._private;\n var ani_p = ani._private;\n var pEasing = ani_p.easing;\n var startTime = ani_p.startTime;\n var cy = isCore ? self : self.cy();\n var style = cy.style();\n if (!ani_p.easingImpl) {\n if (pEasing == null) {\n // use default\n ani_p.easingImpl = easings['linear'];\n } else {\n // then define w/ name\n var easingVals;\n if (string(pEasing)) {\n var easingProp = style.parse('transition-timing-function', pEasing);\n easingVals = easingProp.value;\n } else {\n // then assume preparsed array\n easingVals = pEasing;\n }\n var name, args;\n if (string(easingVals)) {\n name = easingVals;\n args = [];\n } else {\n name = easingVals[1];\n args = easingVals.slice(2).map(function (n) {\n return +n;\n });\n }\n if (args.length > 0) {\n // create with args\n if (name === 'spring') {\n args.push(ani_p.duration); // need duration to generate spring\n }\n ani_p.easingImpl = easings[name].apply(null, args);\n } else {\n // static impl by name\n ani_p.easingImpl = easings[name];\n }\n }\n }\n var easing = ani_p.easingImpl;\n var percent;\n if (ani_p.duration === 0) {\n percent = 1;\n } else {\n percent = (now - startTime) / ani_p.duration;\n }\n if (ani_p.applying) {\n percent = ani_p.progress;\n }\n if (percent < 0) {\n percent = 0;\n } else if (percent > 1) {\n percent = 1;\n }\n if (ani_p.delay == null) {\n // then update\n\n var startPos = ani_p.startPosition;\n var endPos = ani_p.position;\n if (endPos && isEles && !self.locked()) {\n var newPos = {};\n if (valid(startPos.x, endPos.x)) {\n newPos.x = ease(startPos.x, endPos.x, percent, easing);\n }\n if (valid(startPos.y, endPos.y)) {\n newPos.y = ease(startPos.y, endPos.y, percent, easing);\n }\n self.position(newPos);\n }\n var startPan = ani_p.startPan;\n var endPan = ani_p.pan;\n var pan = _p.pan;\n var animatingPan = endPan != null && isCore;\n if (animatingPan) {\n if (valid(startPan.x, endPan.x)) {\n pan.x = ease(startPan.x, endPan.x, percent, easing);\n }\n if (valid(startPan.y, endPan.y)) {\n pan.y = ease(startPan.y, endPan.y, percent, easing);\n }\n self.emit('pan');\n }\n var startZoom = ani_p.startZoom;\n var endZoom = ani_p.zoom;\n var animatingZoom = endZoom != null && isCore;\n if (animatingZoom) {\n if (valid(startZoom, endZoom)) {\n _p.zoom = bound(_p.minZoom, ease(startZoom, endZoom, percent, easing), _p.maxZoom);\n }\n self.emit('zoom');\n }\n if (animatingPan || animatingZoom) {\n self.emit('viewport');\n }\n var props = ani_p.style;\n if (props && props.length > 0 && isEles) {\n for (var i = 0; i < props.length; i++) {\n var prop = props[i];\n var _name = prop.name;\n var end = prop;\n var start = ani_p.startStyle[_name];\n var propSpec = style.properties[start.name];\n var easedVal = ease(start, end, percent, easing, propSpec);\n style.overrideBypass(self, _name, easedVal);\n } // for props\n\n self.emit('style');\n } // if\n }\n ani_p.progress = percent;\n return percent;\n}\nfunction valid(start, end) {\n if (start == null || end == null) {\n return false;\n }\n if (number$1(start) && number$1(end)) {\n return true;\n } else if (start && end) {\n return true;\n }\n return false;\n}\n\nfunction startAnimation(self, ani, now, isCore) {\n var ani_p = ani._private;\n ani_p.started = true;\n ani_p.startTime = now - ani_p.progress * ani_p.duration;\n}\n\nfunction stepAll(now, cy) {\n var eles = cy._private.aniEles;\n var doneEles = [];\n function stepOne(ele, isCore) {\n var _p = ele._private;\n var current = _p.animation.current;\n var queue = _p.animation.queue;\n var ranAnis = false;\n\n // if nothing currently animating, get something from the queue\n if (current.length === 0) {\n var next = queue.shift();\n if (next) {\n current.push(next);\n }\n }\n var callbacks = function callbacks(_callbacks) {\n for (var j = _callbacks.length - 1; j >= 0; j--) {\n var cb = _callbacks[j];\n cb();\n }\n _callbacks.splice(0, _callbacks.length);\n };\n\n // step and remove if done\n for (var i = current.length - 1; i >= 0; i--) {\n var ani = current[i];\n var ani_p = ani._private;\n if (ani_p.stopped) {\n current.splice(i, 1);\n ani_p.hooked = false;\n ani_p.playing = false;\n ani_p.started = false;\n callbacks(ani_p.frames);\n continue;\n }\n if (!ani_p.playing && !ani_p.applying) {\n continue;\n }\n\n // an apply() while playing shouldn't do anything\n if (ani_p.playing && ani_p.applying) {\n ani_p.applying = false;\n }\n if (!ani_p.started) {\n startAnimation(ele, ani, now);\n }\n step$1(ele, ani, now, isCore);\n if (ani_p.applying) {\n ani_p.applying = false;\n }\n callbacks(ani_p.frames);\n if (ani_p.step != null) {\n ani_p.step(now);\n }\n if (ani.completed()) {\n current.splice(i, 1);\n ani_p.hooked = false;\n ani_p.playing = false;\n ani_p.started = false;\n callbacks(ani_p.completes);\n }\n ranAnis = true;\n }\n if (!isCore && current.length === 0 && queue.length === 0) {\n doneEles.push(ele);\n }\n return ranAnis;\n } // stepElement\n\n // handle all eles\n var ranEleAni = false;\n for (var e = 0; e < eles.length; e++) {\n var ele = eles[e];\n var handledThisEle = stepOne(ele);\n ranEleAni = ranEleAni || handledThisEle;\n } // each element\n\n var ranCoreAni = stepOne(cy, true);\n\n // notify renderer\n if (ranEleAni || ranCoreAni) {\n if (eles.length > 0) {\n cy.notify('draw', eles);\n } else {\n cy.notify('draw');\n }\n }\n\n // remove elements from list of currently animating if its queues are empty\n eles.unmerge(doneEles);\n cy.emit('step');\n} // stepAll\n\nvar corefn$8 = {\n // pull in animation functions\n animate: define.animate(),\n animation: define.animation(),\n animated: define.animated(),\n clearQueue: define.clearQueue(),\n delay: define.delay(),\n delayAnimation: define.delayAnimation(),\n stop: define.stop(),\n addToAnimationPool: function addToAnimationPool(eles) {\n var cy = this;\n if (!cy.styleEnabled()) {\n return;\n } // save cycles when no style used\n\n cy._private.aniEles.merge(eles);\n },\n stopAnimationLoop: function stopAnimationLoop() {\n this._private.animationsRunning = false;\n },\n startAnimationLoop: function startAnimationLoop() {\n var cy = this;\n cy._private.animationsRunning = true;\n if (!cy.styleEnabled()) {\n return;\n } // save cycles when no style used\n\n // NB the animation loop will exec in headless environments if style enabled\n // and explicit cy.destroy() is necessary to stop the loop\n\n function headlessStep() {\n if (!cy._private.animationsRunning) {\n return;\n }\n requestAnimationFrame(function animationStep(now) {\n stepAll(now, cy);\n headlessStep();\n });\n }\n var renderer = cy.renderer();\n if (renderer && renderer.beforeRender) {\n // let the renderer schedule animations\n renderer.beforeRender(function rendererAnimationStep(willDraw, now) {\n stepAll(now, cy);\n }, renderer.beforeRenderPriorities.animations);\n } else {\n // manage the animation loop ourselves\n headlessStep(); // first call\n }\n }\n};\n\nvar emitterOptions = {\n qualifierCompare: function qualifierCompare(selector1, selector2) {\n if (selector1 == null || selector2 == null) {\n return selector1 == null && selector2 == null;\n } else {\n return selector1.sameText(selector2);\n }\n },\n eventMatches: function eventMatches(cy, listener, eventObj) {\n var selector = listener.qualifier;\n if (selector != null) {\n return cy !== eventObj.target && element(eventObj.target) && selector.matches(eventObj.target);\n }\n return true;\n },\n addEventFields: function addEventFields(cy, evt) {\n evt.cy = cy;\n evt.target = cy;\n },\n callbackContext: function callbackContext(cy, listener, eventObj) {\n return listener.qualifier != null ? eventObj.target : cy;\n }\n};\nvar argSelector = function argSelector(arg) {\n if (string(arg)) {\n return new Selector(arg);\n } else {\n return arg;\n }\n};\nvar elesfn = {\n createEmitter: function createEmitter() {\n var _p = this._private;\n if (!_p.emitter) {\n _p.emitter = new Emitter(emitterOptions, this);\n }\n return this;\n },\n emitter: function emitter() {\n return this._private.emitter;\n },\n on: function on(events, selector, callback) {\n this.emitter().on(events, argSelector(selector), callback);\n return this;\n },\n removeListener: function removeListener(events, selector, callback) {\n this.emitter().removeListener(events, argSelector(selector), callback);\n return this;\n },\n removeAllListeners: function removeAllListeners() {\n this.emitter().removeAllListeners();\n return this;\n },\n one: function one(events, selector, callback) {\n this.emitter().one(events, argSelector(selector), callback);\n return this;\n },\n once: function once(events, selector, callback) {\n this.emitter().one(events, argSelector(selector), callback);\n return this;\n },\n emit: function emit(events, extraParams) {\n this.emitter().emit(events, extraParams);\n return this;\n },\n emitAndNotify: function emitAndNotify(event, eles) {\n this.emit(event);\n this.notify(event, eles);\n return this;\n }\n};\ndefine.eventAliasesOn(elesfn);\n\nvar corefn$7 = {\n png: function png(options) {\n var renderer = this._private.renderer;\n options = options || {};\n return renderer.png(options);\n },\n jpg: function jpg(options) {\n var renderer = this._private.renderer;\n options = options || {};\n options.bg = options.bg || '#fff';\n return renderer.jpg(options);\n }\n};\ncorefn$7.jpeg = corefn$7.jpg;\n\nvar corefn$6 = {\n layout: function layout(options) {\n var cy = this;\n if (options == null) {\n error('Layout options must be specified to make a layout');\n return;\n }\n if (options.name == null) {\n error('A `name` must be specified to make a layout');\n return;\n }\n var name = options.name;\n var Layout = cy.extension('layout', name);\n if (Layout == null) {\n error('No such layout `' + name + '` found. Did you forget to import it and `cytoscape.use()` it?');\n return;\n }\n var eles;\n if (string(options.eles)) {\n eles = cy.$(options.eles);\n } else {\n eles = options.eles != null ? options.eles : cy.$();\n }\n var layout = new Layout(extend({}, options, {\n cy: cy,\n eles: eles\n }));\n return layout;\n }\n};\ncorefn$6.createLayout = corefn$6.makeLayout = corefn$6.layout;\n\nvar corefn$5 = {\n notify: function notify(eventName, eventEles) {\n var _p = this._private;\n if (this.batching()) {\n _p.batchNotifications = _p.batchNotifications || {};\n var eles = _p.batchNotifications[eventName] = _p.batchNotifications[eventName] || this.collection();\n if (eventEles != null) {\n eles.merge(eventEles);\n }\n return; // notifications are disabled during batching\n }\n if (!_p.notificationsEnabled) {\n return;\n } // exit on disabled\n\n var renderer = this.renderer();\n\n // exit if destroy() called on core or renderer in between frames #1499 #1528\n if (this.destroyed() || !renderer) {\n return;\n }\n renderer.notify(eventName, eventEles);\n },\n notifications: function notifications(bool) {\n var p = this._private;\n if (bool === undefined) {\n return p.notificationsEnabled;\n } else {\n p.notificationsEnabled = bool ? true : false;\n }\n return this;\n },\n noNotifications: function noNotifications(callback) {\n this.notifications(false);\n callback();\n this.notifications(true);\n },\n batching: function batching() {\n return this._private.batchCount > 0;\n },\n startBatch: function startBatch() {\n var _p = this._private;\n if (_p.batchCount == null) {\n _p.batchCount = 0;\n }\n if (_p.batchCount === 0) {\n _p.batchStyleEles = this.collection();\n _p.batchNotifications = {};\n }\n _p.batchCount++;\n return this;\n },\n endBatch: function endBatch() {\n var _p = this._private;\n if (_p.batchCount === 0) {\n return this;\n }\n _p.batchCount--;\n if (_p.batchCount === 0) {\n // update style for dirty eles\n _p.batchStyleEles.updateStyle();\n var renderer = this.renderer();\n\n // notify the renderer of queued eles and event types\n Object.keys(_p.batchNotifications).forEach(function (eventName) {\n var eles = _p.batchNotifications[eventName];\n if (eles.empty()) {\n renderer.notify(eventName);\n } else {\n renderer.notify(eventName, eles);\n }\n });\n }\n return this;\n },\n batch: function batch(callback) {\n this.startBatch();\n callback();\n this.endBatch();\n return this;\n },\n // for backwards compatibility\n batchData: function batchData(map) {\n var cy = this;\n return this.batch(function () {\n var ids = Object.keys(map);\n for (var i = 0; i < ids.length; i++) {\n var id = ids[i];\n var data = map[id];\n var ele = cy.getElementById(id);\n ele.data(data);\n }\n });\n }\n};\n\nvar rendererDefaults = defaults$g({\n hideEdgesOnViewport: false,\n textureOnViewport: false,\n motionBlur: false,\n motionBlurOpacity: 0.05,\n pixelRatio: undefined,\n desktopTapThreshold: 4,\n touchTapThreshold: 8,\n wheelSensitivity: 1,\n debug: false,\n showFps: false,\n // webgl options\n webgl: false,\n webglDebug: false,\n webglDebugShowAtlases: false,\n // defaults good for mobile\n webglTexSize: 2048,\n webglTexRows: 36,\n webglTexRowsNodes: 18,\n webglBatchSize: 2048,\n webglTexPerBatch: 14,\n webglBgColor: [255, 255, 255]\n});\nvar corefn$4 = {\n renderTo: function renderTo(context, zoom, pan, pxRatio) {\n var r = this._private.renderer;\n r.renderTo(context, zoom, pan, pxRatio);\n return this;\n },\n renderer: function renderer() {\n return this._private.renderer;\n },\n forceRender: function forceRender() {\n this.notify('draw');\n return this;\n },\n resize: function resize() {\n this.invalidateSize();\n this.emitAndNotify('resize');\n return this;\n },\n initRenderer: function initRenderer(options) {\n var cy = this;\n var RendererProto = cy.extension('renderer', options.name);\n if (RendererProto == null) {\n error(\"Can not initialise: No such renderer `\".concat(options.name, \"` found. Did you forget to import it and `cytoscape.use()` it?\"));\n return;\n }\n if (options.wheelSensitivity !== undefined) {\n warn(\"You have set a custom wheel sensitivity. This will make your app zoom unnaturally when using mainstream mice. You should change this value from the default only if you can guarantee that all your users will use the same hardware and OS configuration as your current machine.\");\n }\n var rOpts = rendererDefaults(options);\n rOpts.cy = cy;\n cy._private.renderer = new RendererProto(rOpts);\n this.notify('init');\n },\n destroyRenderer: function destroyRenderer() {\n var cy = this;\n cy.notify('destroy'); // destroy the renderer\n\n var domEle = cy.container();\n if (domEle) {\n domEle._cyreg = null;\n while (domEle.childNodes.length > 0) {\n domEle.removeChild(domEle.childNodes[0]);\n }\n }\n cy._private.renderer = null; // to be extra safe, remove the ref\n cy.mutableElements().forEach(function (ele) {\n var _p = ele._private;\n _p.rscratch = {};\n _p.rstyle = {};\n _p.animation.current = [];\n _p.animation.queue = [];\n });\n },\n onRender: function onRender(fn) {\n return this.on('render', fn);\n },\n offRender: function offRender(fn) {\n return this.off('render', fn);\n }\n};\ncorefn$4.invalidateDimensions = corefn$4.resize;\n\nvar corefn$3 = {\n // get a collection\n // - empty collection on no args\n // - collection of elements in the graph on selector arg\n // - guarantee a returned collection when elements or collection specified\n collection: function collection(eles, opts) {\n if (string(eles)) {\n return this.$(eles);\n } else if (elementOrCollection(eles)) {\n return eles.collection();\n } else if (array(eles)) {\n if (!opts) {\n opts = {};\n }\n return new Collection(this, eles, opts.unique, opts.removed);\n }\n return new Collection(this);\n },\n nodes: function nodes(selector) {\n var nodes = this.$(function (ele) {\n return ele.isNode();\n });\n if (selector) {\n return nodes.filter(selector);\n }\n return nodes;\n },\n edges: function edges(selector) {\n var edges = this.$(function (ele) {\n return ele.isEdge();\n });\n if (selector) {\n return edges.filter(selector);\n }\n return edges;\n },\n // search the graph like jQuery\n $: function $(selector) {\n var eles = this._private.elements;\n if (selector) {\n return eles.filter(selector);\n } else {\n return eles.spawnSelf();\n }\n },\n mutableElements: function mutableElements() {\n return this._private.elements;\n }\n};\n\n// aliases\ncorefn$3.elements = corefn$3.filter = corefn$3.$;\n\nvar styfn$8 = {};\n\n// keys for style blocks, e.g. ttfftt\nvar TRUE = 't';\nvar FALSE = 'f';\n\n// (potentially expensive calculation)\n// apply the style to the element based on\n// - its bypass\n// - what selectors match it\nstyfn$8.apply = function (eles) {\n var self = this;\n var _p = self._private;\n var cy = _p.cy;\n var updatedEles = cy.collection();\n for (var ie = 0; ie < eles.length; ie++) {\n var ele = eles[ie];\n var cxtMeta = self.getContextMeta(ele);\n if (cxtMeta.empty) {\n continue;\n }\n var cxtStyle = self.getContextStyle(cxtMeta);\n var app = self.applyContextStyle(cxtMeta, cxtStyle, ele);\n if (ele._private.appliedInitStyle) {\n self.updateTransitions(ele, app.diffProps);\n } else {\n ele._private.appliedInitStyle = true;\n }\n var hintsDiff = self.updateStyleHints(ele);\n if (hintsDiff) {\n updatedEles.push(ele);\n }\n } // for elements\n\n return updatedEles;\n};\nstyfn$8.getPropertiesDiff = function (oldCxtKey, newCxtKey) {\n var self = this;\n var cache = self._private.propDiffs = self._private.propDiffs || {};\n var dualCxtKey = oldCxtKey + '-' + newCxtKey;\n var cachedVal = cache[dualCxtKey];\n if (cachedVal) {\n return cachedVal;\n }\n var diffProps = [];\n var addedProp = {};\n for (var i = 0; i < self.length; i++) {\n var cxt = self[i];\n var oldHasCxt = oldCxtKey[i] === TRUE;\n var newHasCxt = newCxtKey[i] === TRUE;\n var cxtHasDiffed = oldHasCxt !== newHasCxt;\n var cxtHasMappedProps = cxt.mappedProperties.length > 0;\n if (cxtHasDiffed || newHasCxt && cxtHasMappedProps) {\n var props = undefined;\n if (cxtHasDiffed && cxtHasMappedProps) {\n props = cxt.properties; // suffices b/c mappedProperties is a subset of properties\n } else if (cxtHasDiffed) {\n props = cxt.properties; // need to check them all\n } else if (cxtHasMappedProps) {\n props = cxt.mappedProperties; // only need to check mapped\n }\n for (var j = 0; j < props.length; j++) {\n var prop = props[j];\n var name = prop.name;\n\n // if a later context overrides this property, then the fact that this context has switched/diffed doesn't matter\n // (semi expensive check since it makes this function O(n^2) on context length, but worth it since overall result\n // is cached)\n var laterCxtOverrides = false;\n for (var k = i + 1; k < self.length; k++) {\n var laterCxt = self[k];\n var hasLaterCxt = newCxtKey[k] === TRUE;\n if (!hasLaterCxt) {\n continue;\n } // can't override unless the context is active\n\n laterCxtOverrides = laterCxt.properties[prop.name] != null;\n if (laterCxtOverrides) {\n break;\n } // exit early as long as one later context overrides\n }\n if (!addedProp[name] && !laterCxtOverrides) {\n addedProp[name] = true;\n diffProps.push(name);\n }\n } // for props\n } // if\n } // for contexts\n\n cache[dualCxtKey] = diffProps;\n return diffProps;\n};\nstyfn$8.getContextMeta = function (ele) {\n var self = this;\n var cxtKey = '';\n var diffProps;\n var prevKey = ele._private.styleCxtKey || '';\n\n // get the cxt key\n for (var i = 0; i < self.length; i++) {\n var context = self[i];\n var contextSelectorMatches = context.selector && context.selector.matches(ele); // NB: context.selector may be null for 'core'\n\n if (contextSelectorMatches) {\n cxtKey += TRUE;\n } else {\n cxtKey += FALSE;\n }\n } // for context\n\n diffProps = self.getPropertiesDiff(prevKey, cxtKey);\n ele._private.styleCxtKey = cxtKey;\n return {\n key: cxtKey,\n diffPropNames: diffProps,\n empty: diffProps.length === 0\n };\n};\n\n// gets a computed ele style object based on matched contexts\nstyfn$8.getContextStyle = function (cxtMeta) {\n var cxtKey = cxtMeta.key;\n var self = this;\n var cxtStyles = this._private.contextStyles = this._private.contextStyles || {};\n\n // if already computed style, returned cached copy\n if (cxtStyles[cxtKey]) {\n return cxtStyles[cxtKey];\n }\n var style = {\n _private: {\n key: cxtKey\n }\n };\n for (var i = 0; i < self.length; i++) {\n var cxt = self[i];\n var hasCxt = cxtKey[i] === TRUE;\n if (!hasCxt) {\n continue;\n }\n for (var j = 0; j < cxt.properties.length; j++) {\n var prop = cxt.properties[j];\n style[prop.name] = prop;\n }\n }\n cxtStyles[cxtKey] = style;\n return style;\n};\nstyfn$8.applyContextStyle = function (cxtMeta, cxtStyle, ele) {\n var self = this;\n var diffProps = cxtMeta.diffPropNames;\n var retDiffProps = {};\n var types = self.types;\n for (var i = 0; i < diffProps.length; i++) {\n var diffPropName = diffProps[i];\n var cxtProp = cxtStyle[diffPropName];\n var eleProp = ele.pstyle(diffPropName);\n if (!cxtProp) {\n // no context prop means delete\n if (!eleProp) {\n continue; // no existing prop means nothing needs to be removed\n // nb affects initial application on mapped values like control-point-distances\n } else if (eleProp.bypass) {\n cxtProp = {\n name: diffPropName,\n deleteBypassed: true\n };\n } else {\n cxtProp = {\n name: diffPropName,\n \"delete\": true\n };\n }\n }\n\n // save cycles when the context prop doesn't need to be applied\n if (eleProp === cxtProp) {\n continue;\n }\n\n // save cycles when a mapped context prop doesn't need to be applied\n if (cxtProp.mapped === types.fn // context prop is function mapper\n && eleProp != null // some props can be null even by default (e.g. a prop that overrides another one)\n && eleProp.mapping != null // ele prop is a concrete value from from a mapper\n && eleProp.mapping.value === cxtProp.value // the current prop on the ele is a flat prop value for the function mapper\n ) {\n // NB don't write to cxtProp, as it's shared among eles (stored in stylesheet)\n var mapping = eleProp.mapping; // can write to mapping, as it's a per-ele copy\n var fnValue = mapping.fnValue = cxtProp.value(ele); // temporarily cache the value in case of a miss\n\n if (fnValue === mapping.prevFnValue) {\n continue;\n }\n }\n var retDiffProp = retDiffProps[diffPropName] = {\n prev: eleProp\n };\n self.applyParsedProperty(ele, cxtProp);\n retDiffProp.next = ele.pstyle(diffPropName);\n if (retDiffProp.next && retDiffProp.next.bypass) {\n retDiffProp.next = retDiffProp.next.bypassed;\n }\n }\n return {\n diffProps: retDiffProps\n };\n};\nstyfn$8.updateStyleHints = function (ele) {\n var _p = ele._private;\n var self = this;\n var propNames = self.propertyGroupNames;\n var propGrKeys = self.propertyGroupKeys;\n var propHash = function propHash(ele, propNames, seedKey) {\n return self.getPropertiesHash(ele, propNames, seedKey);\n };\n var oldStyleKey = _p.styleKey;\n if (ele.removed()) {\n return false;\n }\n var isNode = _p.group === 'nodes';\n\n // get the style key hashes per prop group\n // but lazily -- only use non-default prop values to reduce the number of hashes\n //\n\n var overriddenStyles = ele._private.style;\n propNames = Object.keys(overriddenStyles);\n for (var i = 0; i < propGrKeys.length; i++) {\n var grKey = propGrKeys[i];\n _p.styleKeys[grKey] = [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT];\n }\n var updateGrKey1 = function updateGrKey1(val, grKey) {\n return _p.styleKeys[grKey][0] = hashInt(val, _p.styleKeys[grKey][0]);\n };\n var updateGrKey2 = function updateGrKey2(val, grKey) {\n return _p.styleKeys[grKey][1] = hashIntAlt(val, _p.styleKeys[grKey][1]);\n };\n var updateGrKey = function updateGrKey(val, grKey) {\n updateGrKey1(val, grKey);\n updateGrKey2(val, grKey);\n };\n var updateGrKeyWStr = function updateGrKeyWStr(strVal, grKey) {\n for (var j = 0; j < strVal.length; j++) {\n var ch = strVal.charCodeAt(j);\n updateGrKey1(ch, grKey);\n updateGrKey2(ch, grKey);\n }\n };\n\n // - hashing works on 32 bit ints b/c we use bitwise ops\n // - small numbers get cut off (e.g. 0.123 is seen as 0 by the hashing function)\n // - raise up small numbers so more significant digits are seen by hashing\n // - make small numbers larger than a normal value to avoid collisions\n // - works in practice and it's relatively cheap\n var N = 2000000000;\n var cleanNum = function cleanNum(val) {\n return -128 < val && val < 128 && Math.floor(val) !== val ? N - (val * 1024 | 0) : val;\n };\n for (var _i = 0; _i < propNames.length; _i++) {\n var name = propNames[_i];\n var parsedProp = overriddenStyles[name];\n if (parsedProp == null) {\n continue;\n }\n var propInfo = this.properties[name];\n var type = propInfo.type;\n var _grKey = propInfo.groupKey;\n var normalizedNumberVal = undefined;\n if (propInfo.hashOverride != null) {\n normalizedNumberVal = propInfo.hashOverride(ele, parsedProp);\n } else if (parsedProp.pfValue != null) {\n normalizedNumberVal = parsedProp.pfValue;\n }\n\n // might not be a number if it allows enums\n var numberVal = propInfo.enums == null ? parsedProp.value : null;\n var haveNormNum = normalizedNumberVal != null;\n var haveUnitedNum = numberVal != null;\n var haveNum = haveNormNum || haveUnitedNum;\n var units = parsedProp.units;\n\n // numbers are cheaper to hash than strings\n // 1 hash op vs n hash ops (for length n string)\n if (type.number && haveNum && !type.multiple) {\n var v = haveNormNum ? normalizedNumberVal : numberVal;\n updateGrKey(cleanNum(v), _grKey);\n if (!haveNormNum && units != null) {\n updateGrKeyWStr(units, _grKey);\n }\n } else {\n updateGrKeyWStr(parsedProp.strValue, _grKey);\n }\n }\n\n // overall style key\n //\n\n var hash = [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT];\n for (var _i2 = 0; _i2 < propGrKeys.length; _i2++) {\n var _grKey2 = propGrKeys[_i2];\n var grHash = _p.styleKeys[_grKey2];\n hash[0] = hashInt(grHash[0], hash[0]);\n hash[1] = hashIntAlt(grHash[1], hash[1]);\n }\n _p.styleKey = combineHashes(hash[0], hash[1]);\n\n // label dims\n //\n\n var sk = _p.styleKeys;\n _p.labelDimsKey = combineHashesArray(sk.labelDimensions);\n var labelKeys = propHash(ele, ['label'], sk.labelDimensions);\n _p.labelKey = combineHashesArray(labelKeys);\n _p.labelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, labelKeys));\n if (!isNode) {\n var sourceLabelKeys = propHash(ele, ['source-label'], sk.labelDimensions);\n _p.sourceLabelKey = combineHashesArray(sourceLabelKeys);\n _p.sourceLabelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, sourceLabelKeys));\n var targetLabelKeys = propHash(ele, ['target-label'], sk.labelDimensions);\n _p.targetLabelKey = combineHashesArray(targetLabelKeys);\n _p.targetLabelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, targetLabelKeys));\n }\n\n // node\n //\n\n if (isNode) {\n var _p$styleKeys = _p.styleKeys,\n nodeBody = _p$styleKeys.nodeBody,\n nodeBorder = _p$styleKeys.nodeBorder,\n nodeOutline = _p$styleKeys.nodeOutline,\n backgroundImage = _p$styleKeys.backgroundImage,\n compound = _p$styleKeys.compound,\n pie = _p$styleKeys.pie,\n stripe = _p$styleKeys.stripe;\n var nodeKeys = [nodeBody, nodeBorder, nodeOutline, backgroundImage, compound, pie, stripe].filter(function (k) {\n return k != null;\n }).reduce(hashArrays, [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT]);\n _p.nodeKey = combineHashesArray(nodeKeys);\n _p.hasPie = pie != null && pie[0] !== DEFAULT_HASH_SEED && pie[1] !== DEFAULT_HASH_SEED_ALT;\n _p.hasStripe = stripe != null && stripe[0] !== DEFAULT_HASH_SEED && stripe[1] !== DEFAULT_HASH_SEED_ALT;\n }\n return oldStyleKey !== _p.styleKey;\n};\nstyfn$8.clearStyleHints = function (ele) {\n var _p = ele._private;\n _p.styleCxtKey = '';\n _p.styleKeys = {};\n _p.styleKey = null;\n _p.labelKey = null;\n _p.labelStyleKey = null;\n _p.sourceLabelKey = null;\n _p.sourceLabelStyleKey = null;\n _p.targetLabelKey = null;\n _p.targetLabelStyleKey = null;\n _p.nodeKey = null;\n _p.hasPie = null;\n _p.hasStripe = null;\n};\n\n// apply a property to the style (for internal use)\n// returns whether application was successful\n//\n// now, this function flattens the property, and here's how:\n//\n// for parsedProp:{ bypass: true, deleteBypass: true }\n// no property is generated, instead the bypass property in the\n// element's style is replaced by what's pointed to by the `bypassed`\n// field in the bypass property (i.e. restoring the property the\n// bypass was overriding)\n//\n// for parsedProp:{ mapped: truthy }\n// the generated flattenedProp:{ mapping: prop }\n//\n// for parsedProp:{ bypass: true }\n// the generated flattenedProp:{ bypassed: parsedProp }\nstyfn$8.applyParsedProperty = function (ele, parsedProp) {\n var self = this;\n var prop = parsedProp;\n var style = ele._private.style;\n var flatProp;\n var types = self.types;\n var type = self.properties[prop.name].type;\n var propIsBypass = prop.bypass;\n var origProp = style[prop.name];\n var origPropIsBypass = origProp && origProp.bypass;\n var _p = ele._private;\n var flatPropMapping = 'mapping';\n var getVal = function getVal(p) {\n if (p == null) {\n return null;\n } else if (p.pfValue != null) {\n return p.pfValue;\n } else {\n return p.value;\n }\n };\n var checkTriggers = function checkTriggers() {\n var fromVal = getVal(origProp);\n var toVal = getVal(prop);\n self.checkTriggers(ele, prop.name, fromVal, toVal);\n };\n\n // edge sanity checks to prevent the client from making serious mistakes\n if (parsedProp.name === 'curve-style' && ele.isEdge() && (\n // loops must be bundled beziers\n parsedProp.value !== 'bezier' && ele.isLoop() ||\n // edges connected to compound nodes can not be haystacks\n parsedProp.value === 'haystack' && (ele.source().isParent() || ele.target().isParent()))) {\n prop = parsedProp = this.parse(parsedProp.name, 'bezier', propIsBypass);\n }\n if (prop[\"delete\"]) {\n // delete the property and use the default value on falsey value\n style[prop.name] = undefined;\n checkTriggers();\n return true;\n }\n if (prop.deleteBypassed) {\n // delete the property that the\n if (!origProp) {\n checkTriggers();\n return true; // can't delete if no prop\n } else if (origProp.bypass) {\n // delete bypassed\n origProp.bypassed = undefined;\n checkTriggers();\n return true;\n } else {\n return false; // we're unsuccessful deleting the bypassed\n }\n }\n\n // check if we need to delete the current bypass\n if (prop.deleteBypass) {\n // then this property is just here to indicate we need to delete\n if (!origProp) {\n checkTriggers();\n return true; // property is already not defined\n } else if (origProp.bypass) {\n // then replace the bypass property with the original\n // because the bypassed property was already applied (and therefore parsed), we can just replace it (no reapplying necessary)\n style[prop.name] = origProp.bypassed;\n checkTriggers();\n return true;\n } else {\n return false; // we're unsuccessful deleting the bypass\n }\n }\n var printMappingErr = function printMappingErr() {\n warn('Do not assign mappings to elements without corresponding data (i.e. ele `' + ele.id() + '` has no mapping for property `' + prop.name + '` with data field `' + prop.field + '`); try a `[' + prop.field + ']` selector to limit scope to elements with `' + prop.field + '` defined');\n };\n\n // put the property in the style objects\n switch (prop.mapped) {\n // flatten the property if mapped\n case types.mapData:\n {\n // flatten the field (e.g. data.foo.bar)\n var fields = prop.field.split('.');\n var fieldVal = _p.data;\n for (var i = 0; i < fields.length && fieldVal; i++) {\n var field = fields[i];\n fieldVal = fieldVal[field];\n }\n if (fieldVal == null) {\n printMappingErr();\n return false;\n }\n var percent;\n if (!number$1(fieldVal)) {\n // then don't apply and fall back on the existing style\n warn('Do not use continuous mappers without specifying numeric data (i.e. `' + prop.field + ': ' + fieldVal + '` for `' + ele.id() + '` is non-numeric)');\n return false;\n } else {\n var fieldWidth = prop.fieldMax - prop.fieldMin;\n if (fieldWidth === 0) {\n // safety check -- not strictly necessary as no props of zero range should be passed here\n percent = 0;\n } else {\n percent = (fieldVal - prop.fieldMin) / fieldWidth;\n }\n }\n\n // make sure to bound percent value\n if (percent < 0) {\n percent = 0;\n } else if (percent > 1) {\n percent = 1;\n }\n if (type.color) {\n var r1 = prop.valueMin[0];\n var r2 = prop.valueMax[0];\n var g1 = prop.valueMin[1];\n var g2 = prop.valueMax[1];\n var b1 = prop.valueMin[2];\n var b2 = prop.valueMax[2];\n var a1 = prop.valueMin[3] == null ? 1 : prop.valueMin[3];\n var a2 = prop.valueMax[3] == null ? 1 : prop.valueMax[3];\n var clr = [Math.round(r1 + (r2 - r1) * percent), Math.round(g1 + (g2 - g1) * percent), Math.round(b1 + (b2 - b1) * percent), Math.round(a1 + (a2 - a1) * percent)];\n flatProp = {\n // colours are simple, so just create the flat property instead of expensive string parsing\n bypass: prop.bypass,\n // we're a bypass if the mapping property is a bypass\n name: prop.name,\n value: clr,\n strValue: 'rgb(' + clr[0] + ', ' + clr[1] + ', ' + clr[2] + ')'\n };\n } else if (type.number) {\n var calcValue = prop.valueMin + (prop.valueMax - prop.valueMin) * percent;\n flatProp = this.parse(prop.name, calcValue, prop.bypass, flatPropMapping);\n } else {\n return false; // can only map to colours and numbers\n }\n if (!flatProp) {\n // if we can't flatten the property, then don't apply the property and fall back on the existing style\n printMappingErr();\n return false;\n }\n flatProp.mapping = prop; // keep a reference to the mapping\n prop = flatProp; // the flattened (mapped) property is the one we want\n\n break;\n }\n\n // direct mapping\n case types.data:\n {\n // flatten the field (e.g. data.foo.bar)\n var _fields = prop.field.split('.');\n var _fieldVal = _p.data;\n for (var _i3 = 0; _i3 < _fields.length && _fieldVal; _i3++) {\n var _field = _fields[_i3];\n _fieldVal = _fieldVal[_field];\n }\n if (_fieldVal != null) {\n flatProp = this.parse(prop.name, _fieldVal, prop.bypass, flatPropMapping);\n }\n if (!flatProp) {\n // if we can't flatten the property, then don't apply and fall back on the existing style\n printMappingErr();\n return false;\n }\n flatProp.mapping = prop; // keep a reference to the mapping\n prop = flatProp; // the flattened (mapped) property is the one we want\n\n break;\n }\n case types.fn:\n {\n var fn = prop.value;\n var fnRetVal = prop.fnValue != null ? prop.fnValue : fn(ele); // check for cached value before calling function\n\n prop.prevFnValue = fnRetVal;\n if (fnRetVal == null) {\n warn('Custom function mappers may not return null (i.e. `' + prop.name + '` for ele `' + ele.id() + '` is null)');\n return false;\n }\n flatProp = this.parse(prop.name, fnRetVal, prop.bypass, flatPropMapping);\n if (!flatProp) {\n warn('Custom function mappers may not return invalid values for the property type (i.e. `' + prop.name + '` for ele `' + ele.id() + '` is invalid)');\n return false;\n }\n flatProp.mapping = copy(prop); // keep a reference to the mapping\n prop = flatProp; // the flattened (mapped) property is the one we want\n\n break;\n }\n case undefined:\n break;\n // just set the property\n\n default:\n return false;\n // not a valid mapping\n }\n\n // if the property is a bypass property, then link the resultant property to the original one\n if (propIsBypass) {\n if (origPropIsBypass) {\n // then this bypass overrides the existing one\n prop.bypassed = origProp.bypassed; // steal bypassed prop from old bypass\n } else {\n // then link the orig prop to the new bypass\n prop.bypassed = origProp;\n }\n style[prop.name] = prop; // and set\n } else {\n // prop is not bypass\n if (origPropIsBypass) {\n // then keep the orig prop (since it's a bypass) and link to the new prop\n origProp.bypassed = prop;\n } else {\n // then just replace the old prop with the new one\n style[prop.name] = prop;\n }\n }\n checkTriggers();\n return true;\n};\nstyfn$8.cleanElements = function (eles, keepBypasses) {\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n this.clearStyleHints(ele);\n ele.dirtyCompoundBoundsCache();\n ele.dirtyBoundingBoxCache();\n if (!keepBypasses) {\n ele._private.style = {};\n } else {\n var style = ele._private.style;\n var propNames = Object.keys(style);\n for (var j = 0; j < propNames.length; j++) {\n var propName = propNames[j];\n var eleProp = style[propName];\n if (eleProp != null) {\n if (eleProp.bypass) {\n eleProp.bypassed = null;\n } else {\n style[propName] = null;\n }\n }\n }\n }\n }\n};\n\n// updates the visual style for all elements (useful for manual style modification after init)\nstyfn$8.update = function () {\n var cy = this._private.cy;\n var eles = cy.mutableElements();\n eles.updateStyle();\n};\n\n// diffProps : { name => { prev, next } }\nstyfn$8.updateTransitions = function (ele, diffProps) {\n var self = this;\n var _p = ele._private;\n var props = ele.pstyle('transition-property').value;\n var duration = ele.pstyle('transition-duration').pfValue;\n var delay = ele.pstyle('transition-delay').pfValue;\n if (props.length > 0 && duration > 0) {\n var style = {};\n\n // build up the style to animate towards\n var anyPrev = false;\n for (var i = 0; i < props.length; i++) {\n var prop = props[i];\n var styProp = ele.pstyle(prop);\n var diffProp = diffProps[prop];\n if (!diffProp) {\n continue;\n }\n var prevProp = diffProp.prev;\n var fromProp = prevProp;\n var toProp = diffProp.next != null ? diffProp.next : styProp;\n var diff = false;\n var initVal = undefined;\n var initDt = 0.000001; // delta time % value for initVal (allows animating out of init zero opacity)\n\n if (!fromProp) {\n continue;\n }\n\n // consider px values\n if (number$1(fromProp.pfValue) && number$1(toProp.pfValue)) {\n diff = toProp.pfValue - fromProp.pfValue; // nonzero is truthy\n initVal = fromProp.pfValue + initDt * diff;\n\n // consider numerical values\n } else if (number$1(fromProp.value) && number$1(toProp.value)) {\n diff = toProp.value - fromProp.value; // nonzero is truthy\n initVal = fromProp.value + initDt * diff;\n\n // consider colour values\n } else if (array(fromProp.value) && array(toProp.value)) {\n diff = fromProp.value[0] !== toProp.value[0] || fromProp.value[1] !== toProp.value[1] || fromProp.value[2] !== toProp.value[2];\n initVal = fromProp.strValue;\n }\n\n // the previous value is good for an animation only if it's different\n if (diff) {\n style[prop] = toProp.strValue; // to val\n this.applyBypass(ele, prop, initVal); // from val\n anyPrev = true;\n }\n } // end if props allow ani\n\n // can't transition if there's nothing previous to transition from\n if (!anyPrev) {\n return;\n }\n _p.transitioning = true;\n new Promise$1(function (resolve) {\n if (delay > 0) {\n ele.delayAnimation(delay).play().promise().then(resolve);\n } else {\n resolve();\n }\n }).then(function () {\n return ele.animation({\n style: style,\n duration: duration,\n easing: ele.pstyle('transition-timing-function').value,\n queue: false\n }).play().promise();\n }).then(function () {\n // if( !isBypass ){\n self.removeBypasses(ele, props);\n ele.emitAndNotify('style');\n // }\n\n _p.transitioning = false;\n });\n } else if (_p.transitioning) {\n this.removeBypasses(ele, props);\n ele.emitAndNotify('style');\n _p.transitioning = false;\n }\n};\nstyfn$8.checkTrigger = function (ele, name, fromValue, toValue, getTrigger, onTrigger) {\n var prop = this.properties[name];\n var triggerCheck = getTrigger(prop);\n if (ele.removed()) {\n return;\n }\n if (triggerCheck != null && triggerCheck(fromValue, toValue, ele)) {\n onTrigger(prop);\n }\n};\nstyfn$8.checkZOrderTrigger = function (ele, name, fromValue, toValue) {\n var _this = this;\n this.checkTrigger(ele, name, fromValue, toValue, function (prop) {\n return prop.triggersZOrder;\n }, function () {\n _this._private.cy.notify('zorder', ele);\n });\n};\nstyfn$8.checkBoundsTrigger = function (ele, name, fromValue, toValue) {\n this.checkTrigger(ele, name, fromValue, toValue, function (prop) {\n return prop.triggersBounds;\n }, function (prop) {\n ele.dirtyCompoundBoundsCache();\n ele.dirtyBoundingBoxCache();\n });\n};\nstyfn$8.checkConnectedEdgesBoundsTrigger = function (ele, name, fromValue, toValue) {\n this.checkTrigger(ele, name, fromValue, toValue, function (prop) {\n return prop.triggersBoundsOfConnectedEdges;\n }, function (prop) {\n ele.connectedEdges().forEach(function (edge) {\n edge.dirtyBoundingBoxCache();\n });\n });\n};\nstyfn$8.checkParallelEdgesBoundsTrigger = function (ele, name, fromValue, toValue) {\n this.checkTrigger(ele, name, fromValue, toValue, function (prop) {\n return prop.triggersBoundsOfParallelEdges;\n }, function (prop) {\n ele.parallelEdges().forEach(function (pllEdge) {\n pllEdge.dirtyBoundingBoxCache();\n });\n });\n};\nstyfn$8.checkTriggers = function (ele, name, fromValue, toValue) {\n ele.dirtyStyleCache();\n this.checkZOrderTrigger(ele, name, fromValue, toValue);\n this.checkBoundsTrigger(ele, name, fromValue, toValue);\n this.checkConnectedEdgesBoundsTrigger(ele, name, fromValue, toValue);\n this.checkParallelEdgesBoundsTrigger(ele, name, fromValue, toValue);\n};\n\nvar styfn$7 = {};\n\n// bypasses are applied to an existing style on an element, and just tacked on temporarily\n// returns true iff application was successful for at least 1 specified property\nstyfn$7.applyBypass = function (eles, name, value, updateTransitions) {\n var self = this;\n var props = [];\n var isBypass = true;\n\n // put all the properties (can specify one or many) in an array after parsing them\n if (name === '*' || name === '**') {\n // apply to all property names\n\n if (value !== undefined) {\n for (var i = 0; i < self.properties.length; i++) {\n var prop = self.properties[i];\n var _name = prop.name;\n var parsedProp = this.parse(_name, value, true);\n if (parsedProp) {\n props.push(parsedProp);\n }\n }\n }\n } else if (string(name)) {\n // then parse the single property\n var _parsedProp = this.parse(name, value, true);\n if (_parsedProp) {\n props.push(_parsedProp);\n }\n } else if (plainObject(name)) {\n // then parse each property\n var specifiedProps = name;\n updateTransitions = value;\n var names = Object.keys(specifiedProps);\n for (var _i = 0; _i < names.length; _i++) {\n var _name2 = names[_i];\n var _value = specifiedProps[_name2];\n if (_value === undefined) {\n // try camel case name too\n _value = specifiedProps[dash2camel(_name2)];\n }\n if (_value !== undefined) {\n var _parsedProp2 = this.parse(_name2, _value, true);\n if (_parsedProp2) {\n props.push(_parsedProp2);\n }\n }\n }\n } else {\n // can't do anything without well defined properties\n return false;\n }\n\n // we've failed if there are no valid properties\n if (props.length === 0) {\n return false;\n }\n\n // now, apply the bypass properties on the elements\n var ret = false; // return true if at least one succesful bypass applied\n for (var _i2 = 0; _i2 < eles.length; _i2++) {\n // for each ele\n var ele = eles[_i2];\n var diffProps = {};\n var diffProp = undefined;\n for (var j = 0; j < props.length; j++) {\n // for each prop\n var _prop = props[j];\n if (updateTransitions) {\n var prevProp = ele.pstyle(_prop.name);\n diffProp = diffProps[_prop.name] = {\n prev: prevProp\n };\n }\n ret = this.applyParsedProperty(ele, copy(_prop)) || ret;\n if (updateTransitions) {\n diffProp.next = ele.pstyle(_prop.name);\n }\n } // for props\n\n if (ret) {\n this.updateStyleHints(ele);\n }\n if (updateTransitions) {\n this.updateTransitions(ele, diffProps, isBypass);\n }\n } // for eles\n\n return ret;\n};\n\n// only useful in specific cases like animation\nstyfn$7.overrideBypass = function (eles, name, value) {\n name = camel2dash(name);\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n var prop = ele._private.style[name];\n var type = this.properties[name].type;\n var isColor = type.color;\n var isMulti = type.mutiple;\n var oldValue = !prop ? null : prop.pfValue != null ? prop.pfValue : prop.value;\n if (!prop || !prop.bypass) {\n // need a bypass if one doesn't exist\n this.applyBypass(ele, name, value);\n } else {\n prop.value = value;\n if (prop.pfValue != null) {\n prop.pfValue = value;\n }\n if (isColor) {\n prop.strValue = 'rgb(' + value.join(',') + ')';\n } else if (isMulti) {\n prop.strValue = value.join(' ');\n } else {\n prop.strValue = '' + value;\n }\n this.updateStyleHints(ele);\n }\n this.checkTriggers(ele, name, oldValue, value);\n }\n};\nstyfn$7.removeAllBypasses = function (eles, updateTransitions) {\n return this.removeBypasses(eles, this.propertyNames, updateTransitions);\n};\nstyfn$7.removeBypasses = function (eles, props, updateTransitions) {\n var isBypass = true;\n for (var j = 0; j < eles.length; j++) {\n var ele = eles[j];\n var diffProps = {};\n for (var i = 0; i < props.length; i++) {\n var name = props[i];\n var prop = this.properties[name];\n var prevProp = ele.pstyle(prop.name);\n if (!prevProp || !prevProp.bypass) {\n // if a bypass doesn't exist for the prop, nothing needs to be removed\n continue;\n }\n var value = ''; // empty => remove bypass\n var parsedProp = this.parse(name, value, true);\n var diffProp = diffProps[prop.name] = {\n prev: prevProp\n };\n this.applyParsedProperty(ele, parsedProp);\n diffProp.next = ele.pstyle(prop.name);\n } // for props\n\n this.updateStyleHints(ele);\n if (updateTransitions) {\n this.updateTransitions(ele, diffProps, isBypass);\n }\n } // for eles\n};\n\nvar styfn$6 = {};\n\n// gets what an em size corresponds to in pixels relative to a dom element\nstyfn$6.getEmSizeInPixels = function () {\n var px = this.containerCss('font-size');\n if (px != null) {\n return parseFloat(px);\n } else {\n return 1; // for headless\n }\n};\n\n// gets css property from the core container\nstyfn$6.containerCss = function (propName) {\n var cy = this._private.cy;\n var domElement = cy.container();\n var containerWindow = cy.window();\n if (containerWindow && domElement && containerWindow.getComputedStyle) {\n return containerWindow.getComputedStyle(domElement).getPropertyValue(propName);\n }\n};\n\nvar styfn$5 = {};\n\n// gets the rendered style for an element\nstyfn$5.getRenderedStyle = function (ele, prop) {\n if (prop) {\n return this.getStylePropertyValue(ele, prop, true);\n } else {\n return this.getRawStyle(ele, true);\n }\n};\n\n// gets the raw style for an element\nstyfn$5.getRawStyle = function (ele, isRenderedVal) {\n var self = this;\n ele = ele[0]; // insure it's an element\n\n if (ele) {\n var rstyle = {};\n for (var i = 0; i < self.properties.length; i++) {\n var prop = self.properties[i];\n var val = self.getStylePropertyValue(ele, prop.name, isRenderedVal);\n if (val != null) {\n rstyle[prop.name] = val;\n rstyle[dash2camel(prop.name)] = val;\n }\n }\n return rstyle;\n }\n};\nstyfn$5.getIndexedStyle = function (ele, property, subproperty, index) {\n var pstyle = ele.pstyle(property)[subproperty][index];\n return pstyle != null ? pstyle : ele.cy().style().getDefaultProperty(property)[subproperty][0];\n};\nstyfn$5.getStylePropertyValue = function (ele, propName, isRenderedVal) {\n var self = this;\n ele = ele[0]; // insure it's an element\n\n if (ele) {\n var prop = self.properties[propName];\n if (prop.alias) {\n prop = prop.pointsTo;\n }\n var type = prop.type;\n var styleProp = ele.pstyle(prop.name);\n if (styleProp) {\n var value = styleProp.value,\n units = styleProp.units,\n strValue = styleProp.strValue;\n if (isRenderedVal && type.number && value != null && number$1(value)) {\n var zoom = ele.cy().zoom();\n var getRenderedValue = function getRenderedValue(val) {\n return val * zoom;\n };\n var getValueStringWithUnits = function getValueStringWithUnits(val, units) {\n return getRenderedValue(val) + units;\n };\n var isArrayValue = array(value);\n var haveUnits = isArrayValue ? units.every(function (u) {\n return u != null;\n }) : units != null;\n if (haveUnits) {\n if (isArrayValue) {\n return value.map(function (v, i) {\n return getValueStringWithUnits(v, units[i]);\n }).join(' ');\n } else {\n return getValueStringWithUnits(value, units);\n }\n } else {\n if (isArrayValue) {\n return value.map(function (v) {\n return string(v) ? v : '' + getRenderedValue(v);\n }).join(' ');\n } else {\n return '' + getRenderedValue(value);\n }\n }\n } else if (strValue != null) {\n return strValue;\n }\n }\n return null;\n }\n};\nstyfn$5.getAnimationStartStyle = function (ele, aniProps) {\n var rstyle = {};\n for (var i = 0; i < aniProps.length; i++) {\n var aniProp = aniProps[i];\n var name = aniProp.name;\n var styleProp = ele.pstyle(name);\n if (styleProp !== undefined) {\n // then make a prop of it\n if (plainObject(styleProp)) {\n styleProp = this.parse(name, styleProp.strValue);\n } else {\n styleProp = this.parse(name, styleProp);\n }\n }\n if (styleProp) {\n rstyle[name] = styleProp;\n }\n }\n return rstyle;\n};\nstyfn$5.getPropsList = function (propsObj) {\n var self = this;\n var rstyle = [];\n var style = propsObj;\n var props = self.properties;\n if (style) {\n var names = Object.keys(style);\n for (var i = 0; i < names.length; i++) {\n var name = names[i];\n var val = style[name];\n var prop = props[name] || props[camel2dash(name)];\n var styleProp = this.parse(prop.name, val);\n if (styleProp) {\n rstyle.push(styleProp);\n }\n }\n }\n return rstyle;\n};\nstyfn$5.getNonDefaultPropertiesHash = function (ele, propNames, seed) {\n var hash = seed.slice();\n var name, val, strVal, chVal;\n var i, j;\n for (i = 0; i < propNames.length; i++) {\n name = propNames[i];\n val = ele.pstyle(name, false);\n if (val == null) {\n continue;\n } else if (val.pfValue != null) {\n hash[0] = hashInt(chVal, hash[0]);\n hash[1] = hashIntAlt(chVal, hash[1]);\n } else {\n strVal = val.strValue;\n for (j = 0; j < strVal.length; j++) {\n chVal = strVal.charCodeAt(j);\n hash[0] = hashInt(chVal, hash[0]);\n hash[1] = hashIntAlt(chVal, hash[1]);\n }\n }\n }\n return hash;\n};\nstyfn$5.getPropertiesHash = styfn$5.getNonDefaultPropertiesHash;\n\nvar styfn$4 = {};\nstyfn$4.appendFromJson = function (json) {\n var style = this;\n for (var i = 0; i < json.length; i++) {\n var context = json[i];\n var selector = context.selector;\n var props = context.style || context.css;\n var names = Object.keys(props);\n style.selector(selector); // apply selector\n\n for (var j = 0; j < names.length; j++) {\n var name = names[j];\n var value = props[name];\n style.css(name, value); // apply property\n }\n }\n return style;\n};\n\n// accessible cy.style() function\nstyfn$4.fromJson = function (json) {\n var style = this;\n style.resetToDefault();\n style.appendFromJson(json);\n return style;\n};\n\n// get json from cy.style() api\nstyfn$4.json = function () {\n var json = [];\n for (var i = this.defaultLength; i < this.length; i++) {\n var cxt = this[i];\n var selector = cxt.selector;\n var props = cxt.properties;\n var css = {};\n for (var j = 0; j < props.length; j++) {\n var prop = props[j];\n css[prop.name] = prop.strValue;\n }\n json.push({\n selector: !selector ? 'core' : selector.toString(),\n style: css\n });\n }\n return json;\n};\n\nvar styfn$3 = {};\nstyfn$3.appendFromString = function (string) {\n var self = this;\n var style = this;\n var remaining = '' + string;\n var selAndBlockStr;\n var blockRem;\n var propAndValStr;\n\n // remove comments from the style string\n remaining = remaining.replace(/[/][*](\\s|.)+?[*][/]/g, '');\n function removeSelAndBlockFromRemaining() {\n // remove the parsed selector and block from the remaining text to parse\n if (remaining.length > selAndBlockStr.length) {\n remaining = remaining.substr(selAndBlockStr.length);\n } else {\n remaining = '';\n }\n }\n function removePropAndValFromRem() {\n // remove the parsed property and value from the remaining block text to parse\n if (blockRem.length > propAndValStr.length) {\n blockRem = blockRem.substr(propAndValStr.length);\n } else {\n blockRem = '';\n }\n }\n for (;;) {\n var nothingLeftToParse = remaining.match(/^\\s*$/);\n if (nothingLeftToParse) {\n break;\n }\n var selAndBlock = remaining.match(/^\\s*((?:.|\\s)+?)\\s*\\{((?:.|\\s)+?)\\}/);\n if (!selAndBlock) {\n warn('Halting stylesheet parsing: String stylesheet contains more to parse but no selector and block found in: ' + remaining);\n break;\n }\n selAndBlockStr = selAndBlock[0];\n\n // parse the selector\n var selectorStr = selAndBlock[1];\n if (selectorStr !== 'core') {\n var selector = new Selector(selectorStr);\n if (selector.invalid) {\n warn('Skipping parsing of block: Invalid selector found in string stylesheet: ' + selectorStr);\n\n // skip this selector and block\n removeSelAndBlockFromRemaining();\n continue;\n }\n }\n\n // parse the block of properties and values\n var blockStr = selAndBlock[2];\n var invalidBlock = false;\n blockRem = blockStr;\n var props = [];\n for (;;) {\n var _nothingLeftToParse = blockRem.match(/^\\s*$/);\n if (_nothingLeftToParse) {\n break;\n }\n var propAndVal = blockRem.match(/^\\s*(.+?)\\s*:\\s*(.+?)(?:\\s*;|\\s*$)/);\n if (!propAndVal) {\n warn('Skipping parsing of block: Invalid formatting of style property and value definitions found in:' + blockStr);\n invalidBlock = true;\n break;\n }\n propAndValStr = propAndVal[0];\n var propStr = propAndVal[1];\n var valStr = propAndVal[2];\n var prop = self.properties[propStr];\n if (!prop) {\n warn('Skipping property: Invalid property name in: ' + propAndValStr);\n\n // skip this property in the block\n removePropAndValFromRem();\n continue;\n }\n var parsedProp = style.parse(propStr, valStr);\n if (!parsedProp) {\n warn('Skipping property: Invalid property definition in: ' + propAndValStr);\n\n // skip this property in the block\n removePropAndValFromRem();\n continue;\n }\n props.push({\n name: propStr,\n val: valStr\n });\n removePropAndValFromRem();\n }\n if (invalidBlock) {\n removeSelAndBlockFromRemaining();\n break;\n }\n\n // put the parsed block in the style\n style.selector(selectorStr);\n for (var i = 0; i < props.length; i++) {\n var _prop = props[i];\n style.css(_prop.name, _prop.val);\n }\n removeSelAndBlockFromRemaining();\n }\n return style;\n};\nstyfn$3.fromString = function (string) {\n var style = this;\n style.resetToDefault();\n style.appendFromString(string);\n return style;\n};\n\nvar styfn$2 = {};\n(function () {\n var number$1 = number;\n var rgba = rgbaNoBackRefs;\n var hsla = hslaNoBackRefs;\n var hex3$1 = hex3;\n var hex6$1 = hex6;\n var data = function data(prefix) {\n return '^' + prefix + '\\\\s*\\\\(\\\\s*([\\\\w\\\\.]+)\\\\s*\\\\)$';\n };\n var mapData = function mapData(prefix) {\n var mapArg = number$1 + '|\\\\w+|' + rgba + '|' + hsla + '|' + hex3$1 + '|' + hex6$1;\n return '^' + prefix + '\\\\s*\\\\(([\\\\w\\\\.]+)\\\\s*\\\\,\\\\s*(' + number$1 + ')\\\\s*\\\\,\\\\s*(' + number$1 + ')\\\\s*,\\\\s*(' + mapArg + ')\\\\s*\\\\,\\\\s*(' + mapArg + ')\\\\)$';\n };\n var urlRegexes = ['^url\\\\s*\\\\(\\\\s*[\\'\"]?(.+?)[\\'\"]?\\\\s*\\\\)$', '^(none)$', '^(.+)$'];\n\n // each visual style property has a type and needs to be validated according to it\n styfn$2.types = {\n time: {\n number: true,\n min: 0,\n units: 's|ms',\n implicitUnits: 'ms'\n },\n percent: {\n number: true,\n min: 0,\n max: 100,\n units: '%',\n implicitUnits: '%'\n },\n percentages: {\n number: true,\n min: 0,\n max: 100,\n units: '%',\n implicitUnits: '%',\n multiple: true\n },\n zeroOneNumber: {\n number: true,\n min: 0,\n max: 1,\n unitless: true\n },\n zeroOneNumbers: {\n number: true,\n min: 0,\n max: 1,\n unitless: true,\n multiple: true\n },\n nOneOneNumber: {\n number: true,\n min: -1,\n max: 1,\n unitless: true\n },\n nonNegativeInt: {\n number: true,\n min: 0,\n integer: true,\n unitless: true\n },\n nonNegativeNumber: {\n number: true,\n min: 0,\n unitless: true\n },\n position: {\n enums: ['parent', 'origin']\n },\n nodeSize: {\n number: true,\n min: 0,\n enums: ['label']\n },\n number: {\n number: true,\n unitless: true\n },\n numbers: {\n number: true,\n unitless: true,\n multiple: true\n },\n positiveNumber: {\n number: true,\n unitless: true,\n min: 0,\n strictMin: true\n },\n size: {\n number: true,\n min: 0\n },\n bidirectionalSize: {\n number: true\n },\n // allows negative\n bidirectionalSizeMaybePercent: {\n number: true,\n allowPercent: true\n },\n // allows negative\n bidirectionalSizes: {\n number: true,\n multiple: true\n },\n // allows negative\n sizeMaybePercent: {\n number: true,\n min: 0,\n allowPercent: true\n },\n axisDirection: {\n enums: ['horizontal', 'leftward', 'rightward', 'vertical', 'upward', 'downward', 'auto']\n },\n axisDirectionExplicit: {\n enums: ['leftward', 'rightward', 'upward', 'downward']\n },\n axisDirectionPrimary: {\n enums: ['horizontal', 'vertical']\n },\n paddingRelativeTo: {\n enums: ['width', 'height', 'average', 'min', 'max']\n },\n bgWH: {\n number: true,\n min: 0,\n allowPercent: true,\n enums: ['auto'],\n multiple: true\n },\n bgPos: {\n number: true,\n allowPercent: true,\n multiple: true\n },\n bgRelativeTo: {\n enums: ['inner', 'include-padding'],\n multiple: true\n },\n bgRepeat: {\n enums: ['repeat', 'repeat-x', 'repeat-y', 'no-repeat'],\n multiple: true\n },\n bgFit: {\n enums: ['none', 'contain', 'cover'],\n multiple: true\n },\n bgCrossOrigin: {\n enums: ['anonymous', 'use-credentials', 'null'],\n multiple: true\n },\n bgClip: {\n enums: ['none', 'node'],\n multiple: true\n },\n bgContainment: {\n enums: ['inside', 'over'],\n multiple: true\n },\n boxSelection: {\n enums: ['contain', 'overlap', 'none']\n },\n color: {\n color: true\n },\n colors: {\n color: true,\n multiple: true\n },\n fill: {\n enums: ['solid', 'linear-gradient', 'radial-gradient']\n },\n bool: {\n enums: ['yes', 'no']\n },\n bools: {\n enums: ['yes', 'no'],\n multiple: true\n },\n lineStyle: {\n enums: ['solid', 'dotted', 'dashed']\n },\n lineCap: {\n enums: ['butt', 'round', 'square']\n },\n linePosition: {\n enums: ['center', 'inside', 'outside']\n },\n lineJoin: {\n enums: ['round', 'bevel', 'miter']\n },\n borderStyle: {\n enums: ['solid', 'dotted', 'dashed', 'double']\n },\n curveStyle: {\n enums: ['bezier', 'unbundled-bezier', 'haystack', 'segments', 'straight', 'straight-triangle', 'taxi', 'round-segments', 'round-taxi']\n },\n radiusType: {\n enums: ['arc-radius', 'influence-radius'],\n multiple: true\n },\n fontFamily: {\n regex: '^([\\\\w- \\\\\"]+(?:\\\\s*,\\\\s*[\\\\w- \\\\\"]+)*)$'\n },\n fontStyle: {\n enums: ['italic', 'normal', 'oblique']\n },\n fontWeight: {\n enums: ['normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '800', '900', 100, 200, 300, 400, 500, 600, 700, 800, 900]\n },\n textDecoration: {\n enums: ['none', 'underline', 'overline', 'line-through']\n },\n textTransform: {\n enums: ['none', 'uppercase', 'lowercase']\n },\n textWrap: {\n enums: ['none', 'wrap', 'ellipsis']\n },\n textOverflowWrap: {\n enums: ['whitespace', 'anywhere']\n },\n textBackgroundShape: {\n enums: ['rectangle', 'roundrectangle', 'round-rectangle', 'circle']\n },\n nodeShape: {\n enums: ['rectangle', 'roundrectangle', 'round-rectangle', 'cutrectangle', 'cut-rectangle', 'bottomroundrectangle', 'bottom-round-rectangle', 'barrel', 'ellipse', 'triangle', 'round-triangle', 'square', 'pentagon', 'round-pentagon', 'hexagon', 'round-hexagon', 'concavehexagon', 'concave-hexagon', 'heptagon', 'round-heptagon', 'octagon', 'round-octagon', 'tag', 'round-tag', 'star', 'diamond', 'round-diamond', 'vee', 'rhomboid', 'right-rhomboid', 'polygon']\n },\n overlayShape: {\n enums: ['roundrectangle', 'round-rectangle', 'ellipse']\n },\n cornerRadius: {\n number: true,\n min: 0,\n units: 'px|em',\n implicitUnits: 'px',\n enums: ['auto']\n },\n compoundIncludeLabels: {\n enums: ['include', 'exclude']\n },\n arrowShape: {\n enums: ['tee', 'triangle', 'triangle-tee', 'circle-triangle', 'triangle-cross', 'triangle-backcurve', 'vee', 'square', 'circle', 'diamond', 'chevron', 'none']\n },\n arrowFill: {\n enums: ['filled', 'hollow']\n },\n arrowWidth: {\n number: true,\n units: '%|px|em',\n implicitUnits: 'px',\n enums: ['match-line']\n },\n display: {\n enums: ['element', 'none']\n },\n visibility: {\n enums: ['hidden', 'visible']\n },\n zCompoundDepth: {\n enums: ['bottom', 'orphan', 'auto', 'top']\n },\n zIndexCompare: {\n enums: ['auto', 'manual']\n },\n valign: {\n enums: ['top', 'center', 'bottom']\n },\n halign: {\n enums: ['left', 'center', 'right']\n },\n justification: {\n enums: ['left', 'center', 'right', 'auto']\n },\n text: {\n string: true\n },\n data: {\n mapping: true,\n regex: data('data')\n },\n layoutData: {\n mapping: true,\n regex: data('layoutData')\n },\n scratch: {\n mapping: true,\n regex: data('scratch')\n },\n mapData: {\n mapping: true,\n regex: mapData('mapData')\n },\n mapLayoutData: {\n mapping: true,\n regex: mapData('mapLayoutData')\n },\n mapScratch: {\n mapping: true,\n regex: mapData('mapScratch')\n },\n fn: {\n mapping: true,\n fn: true\n },\n url: {\n regexes: urlRegexes,\n singleRegexMatchValue: true\n },\n urls: {\n regexes: urlRegexes,\n singleRegexMatchValue: true,\n multiple: true\n },\n propList: {\n propList: true\n },\n angle: {\n number: true,\n units: 'deg|rad',\n implicitUnits: 'rad'\n },\n textRotation: {\n number: true,\n units: 'deg|rad',\n implicitUnits: 'rad',\n enums: ['none', 'autorotate']\n },\n polygonPointList: {\n number: true,\n multiple: true,\n evenMultiple: true,\n min: -1,\n max: 1,\n unitless: true\n },\n edgeDistances: {\n enums: ['intersection', 'node-position', 'endpoints']\n },\n edgeEndpoint: {\n number: true,\n multiple: true,\n units: '%|px|em|deg|rad',\n implicitUnits: 'px',\n enums: ['inside-to-node', 'outside-to-node', 'outside-to-node-or-label', 'outside-to-line', 'outside-to-line-or-label'],\n singleEnum: true,\n validate: function validate(valArr, unitsArr) {\n switch (valArr.length) {\n case 2:\n // can be % or px only\n return unitsArr[0] !== 'deg' && unitsArr[0] !== 'rad' && unitsArr[1] !== 'deg' && unitsArr[1] !== 'rad';\n case 1:\n // can be enum, deg, or rad only\n return string(valArr[0]) || unitsArr[0] === 'deg' || unitsArr[0] === 'rad';\n default:\n return false;\n }\n }\n },\n easing: {\n regexes: ['^(spring)\\\\s*\\\\(\\\\s*(' + number$1 + ')\\\\s*,\\\\s*(' + number$1 + ')\\\\s*\\\\)$', '^(cubic-bezier)\\\\s*\\\\(\\\\s*(' + number$1 + ')\\\\s*,\\\\s*(' + number$1 + ')\\\\s*,\\\\s*(' + number$1 + ')\\\\s*,\\\\s*(' + number$1 + ')\\\\s*\\\\)$'],\n enums: ['linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out', 'ease-in-sine', 'ease-out-sine', 'ease-in-out-sine', 'ease-in-quad', 'ease-out-quad', 'ease-in-out-quad', 'ease-in-cubic', 'ease-out-cubic', 'ease-in-out-cubic', 'ease-in-quart', 'ease-out-quart', 'ease-in-out-quart', 'ease-in-quint', 'ease-out-quint', 'ease-in-out-quint', 'ease-in-expo', 'ease-out-expo', 'ease-in-out-expo', 'ease-in-circ', 'ease-out-circ', 'ease-in-out-circ']\n },\n gradientDirection: {\n enums: ['to-bottom', 'to-top', 'to-left', 'to-right', 'to-bottom-right', 'to-bottom-left', 'to-top-right', 'to-top-left', 'to-right-bottom', 'to-left-bottom', 'to-right-top', 'to-left-top' // different order\n ]\n },\n boundsExpansion: {\n number: true,\n multiple: true,\n min: 0,\n validate: function validate(valArr) {\n var length = valArr.length;\n return length === 1 || length === 2 || length === 4;\n }\n }\n };\n var diff = {\n zeroNonZero: function zeroNonZero(val1, val2) {\n if ((val1 == null || val2 == null) && val1 !== val2) {\n return true; // null cases could represent any value\n }\n if (val1 == 0 && val2 != 0) {\n return true;\n } else if (val1 != 0 && val2 == 0) {\n return true;\n } else {\n return false;\n }\n },\n any: function any(val1, val2) {\n return val1 != val2;\n },\n emptyNonEmpty: function emptyNonEmpty(str1, str2) {\n var empty1 = emptyString(str1);\n var empty2 = emptyString(str2);\n return empty1 && !empty2 || !empty1 && empty2;\n }\n };\n\n // define visual style properties\n //\n // - n.b. adding a new group of props may require updates to updateStyleHints()\n // - adding new props to an existing group gets handled automatically\n\n var t = styfn$2.types;\n var mainLabel = [{\n name: 'label',\n type: t.text,\n triggersBounds: diff.any,\n triggersZOrder: diff.emptyNonEmpty\n }, {\n name: 'text-rotation',\n type: t.textRotation,\n triggersBounds: diff.any\n }, {\n name: 'text-margin-x',\n type: t.bidirectionalSize,\n triggersBounds: diff.any\n }, {\n name: 'text-margin-y',\n type: t.bidirectionalSize,\n triggersBounds: diff.any\n }];\n var sourceLabel = [{\n name: 'source-label',\n type: t.text,\n triggersBounds: diff.any\n }, {\n name: 'source-text-rotation',\n type: t.textRotation,\n triggersBounds: diff.any\n }, {\n name: 'source-text-margin-x',\n type: t.bidirectionalSize,\n triggersBounds: diff.any\n }, {\n name: 'source-text-margin-y',\n type: t.bidirectionalSize,\n triggersBounds: diff.any\n }, {\n name: 'source-text-offset',\n type: t.size,\n triggersBounds: diff.any\n }];\n var targetLabel = [{\n name: 'target-label',\n type: t.text,\n triggersBounds: diff.any\n }, {\n name: 'target-text-rotation',\n type: t.textRotation,\n triggersBounds: diff.any\n }, {\n name: 'target-text-margin-x',\n type: t.bidirectionalSize,\n triggersBounds: diff.any\n }, {\n name: 'target-text-margin-y',\n type: t.bidirectionalSize,\n triggersBounds: diff.any\n }, {\n name: 'target-text-offset',\n type: t.size,\n triggersBounds: diff.any\n }];\n var labelDimensions = [{\n name: 'font-family',\n type: t.fontFamily,\n triggersBounds: diff.any\n }, {\n name: 'font-style',\n type: t.fontStyle,\n triggersBounds: diff.any\n }, {\n name: 'font-weight',\n type: t.fontWeight,\n triggersBounds: diff.any\n }, {\n name: 'font-size',\n type: t.size,\n triggersBounds: diff.any\n }, {\n name: 'text-transform',\n type: t.textTransform,\n triggersBounds: diff.any\n }, {\n name: 'text-wrap',\n type: t.textWrap,\n triggersBounds: diff.any\n }, {\n name: 'text-overflow-wrap',\n type: t.textOverflowWrap,\n triggersBounds: diff.any\n }, {\n name: 'text-max-width',\n type: t.size,\n triggersBounds: diff.any\n }, {\n name: 'text-outline-width',\n type: t.size,\n triggersBounds: diff.any\n }, {\n name: 'line-height',\n type: t.positiveNumber,\n triggersBounds: diff.any\n }];\n var commonLabel = [{\n name: 'text-valign',\n type: t.valign,\n triggersBounds: diff.any\n }, {\n name: 'text-halign',\n type: t.halign,\n triggersBounds: diff.any\n }, {\n name: 'color',\n type: t.color\n }, {\n name: 'text-outline-color',\n type: t.color\n }, {\n name: 'text-outline-opacity',\n type: t.zeroOneNumber\n }, {\n name: 'text-background-color',\n type: t.color\n }, {\n name: 'text-background-opacity',\n type: t.zeroOneNumber\n }, {\n name: 'text-background-padding',\n type: t.size,\n triggersBounds: diff.any\n }, {\n name: 'text-border-opacity',\n type: t.zeroOneNumber\n }, {\n name: 'text-border-color',\n type: t.color\n }, {\n name: 'text-border-width',\n type: t.size,\n triggersBounds: diff.any\n }, {\n name: 'text-border-style',\n type: t.borderStyle,\n triggersBounds: diff.any\n }, {\n name: 'text-background-shape',\n type: t.textBackgroundShape,\n triggersBounds: diff.any\n }, {\n name: 'text-justification',\n type: t.justification\n }, {\n name: 'box-select-labels',\n type: t.bool,\n triggersBounds: diff.any\n }];\n var behavior = [{\n name: 'events',\n type: t.bool,\n triggersZOrder: diff.any\n }, {\n name: 'text-events',\n type: t.bool,\n triggersZOrder: diff.any\n }, {\n name: 'box-selection',\n type: t.boxSelection,\n triggersZOrder: diff.any\n }];\n var visibility = [{\n name: 'display',\n type: t.display,\n triggersZOrder: diff.any,\n triggersBounds: diff.any,\n triggersBoundsOfConnectedEdges: diff.any,\n triggersBoundsOfParallelEdges: function triggersBoundsOfParallelEdges(fromValue, toValue, ele) {\n if (fromValue === toValue) {\n return false;\n }\n\n // only if edge is bundled bezier (so as not to affect performance of other edges)\n return ele.pstyle('curve-style').value === 'bezier';\n }\n }, {\n name: 'visibility',\n type: t.visibility,\n triggersZOrder: diff.any\n }, {\n name: 'opacity',\n type: t.zeroOneNumber,\n triggersZOrder: diff.zeroNonZero\n }, {\n name: 'text-opacity',\n type: t.zeroOneNumber\n }, {\n name: 'min-zoomed-font-size',\n type: t.size\n }, {\n name: 'z-compound-depth',\n type: t.zCompoundDepth,\n triggersZOrder: diff.any\n }, {\n name: 'z-index-compare',\n type: t.zIndexCompare,\n triggersZOrder: diff.any\n }, {\n name: 'z-index',\n type: t.number,\n triggersZOrder: diff.any\n }];\n var overlay = [{\n name: 'overlay-padding',\n type: t.size,\n triggersBounds: diff.any\n }, {\n name: 'overlay-color',\n type: t.color\n }, {\n name: 'overlay-opacity',\n type: t.zeroOneNumber,\n triggersBounds: diff.zeroNonZero\n }, {\n name: 'overlay-shape',\n type: t.overlayShape,\n triggersBounds: diff.any\n }, {\n name: 'overlay-corner-radius',\n type: t.cornerRadius\n }];\n var underlay = [{\n name: 'underlay-padding',\n type: t.size,\n triggersBounds: diff.any\n }, {\n name: 'underlay-color',\n type: t.color\n }, {\n name: 'underlay-opacity',\n type: t.zeroOneNumber,\n triggersBounds: diff.zeroNonZero\n }, {\n name: 'underlay-shape',\n type: t.overlayShape,\n triggersBounds: diff.any\n }, {\n name: 'underlay-corner-radius',\n type: t.cornerRadius\n }];\n var transition = [{\n name: 'transition-property',\n type: t.propList\n }, {\n name: 'transition-duration',\n type: t.time\n }, {\n name: 'transition-delay',\n type: t.time\n }, {\n name: 'transition-timing-function',\n type: t.easing\n }];\n var nodeSizeHashOverride = function nodeSizeHashOverride(ele, parsedProp) {\n if (parsedProp.value === 'label') {\n return -ele.poolIndex(); // no hash key hits is using label size (hitrate for perf probably low anyway)\n } else {\n return parsedProp.pfValue;\n }\n };\n var nodeBody = [{\n name: 'height',\n type: t.nodeSize,\n triggersBounds: diff.any,\n hashOverride: nodeSizeHashOverride\n }, {\n name: 'width',\n type: t.nodeSize,\n triggersBounds: diff.any,\n hashOverride: nodeSizeHashOverride\n }, {\n name: 'shape',\n type: t.nodeShape,\n triggersBounds: diff.any\n }, {\n name: 'shape-polygon-points',\n type: t.polygonPointList,\n triggersBounds: diff.any\n }, {\n name: 'corner-radius',\n type: t.cornerRadius\n }, {\n name: 'background-color',\n type: t.color\n }, {\n name: 'background-fill',\n type: t.fill\n }, {\n name: 'background-opacity',\n type: t.zeroOneNumber\n }, {\n name: 'background-blacken',\n type: t.nOneOneNumber\n }, {\n name: 'background-gradient-stop-colors',\n type: t.colors\n }, {\n name: 'background-gradient-stop-positions',\n type: t.percentages\n }, {\n name: 'background-gradient-direction',\n type: t.gradientDirection\n }, {\n name: 'padding',\n type: t.sizeMaybePercent,\n triggersBounds: diff.any\n }, {\n name: 'padding-relative-to',\n type: t.paddingRelativeTo,\n triggersBounds: diff.any\n }, {\n name: 'bounds-expansion',\n type: t.boundsExpansion,\n triggersBounds: diff.any\n }];\n var nodeBorder = [{\n name: 'border-color',\n type: t.color\n }, {\n name: 'border-opacity',\n type: t.zeroOneNumber\n }, {\n name: 'border-width',\n type: t.size,\n triggersBounds: diff.any\n }, {\n name: 'border-style',\n type: t.borderStyle\n }, {\n name: 'border-cap',\n type: t.lineCap\n }, {\n name: 'border-join',\n type: t.lineJoin\n }, {\n name: 'border-dash-pattern',\n type: t.numbers\n }, {\n name: 'border-dash-offset',\n type: t.number\n }, {\n name: 'border-position',\n type: t.linePosition\n }];\n var nodeOutline = [{\n name: 'outline-color',\n type: t.color\n }, {\n name: 'outline-opacity',\n type: t.zeroOneNumber\n }, {\n name: 'outline-width',\n type: t.size,\n triggersBounds: diff.any\n }, {\n name: 'outline-style',\n type: t.borderStyle\n }, {\n name: 'outline-offset',\n type: t.size,\n triggersBounds: diff.any\n }];\n var backgroundImage = [{\n name: 'background-image',\n type: t.urls\n }, {\n name: 'background-image-crossorigin',\n type: t.bgCrossOrigin\n }, {\n name: 'background-image-opacity',\n type: t.zeroOneNumbers\n }, {\n name: 'background-image-containment',\n type: t.bgContainment\n }, {\n name: 'background-image-smoothing',\n type: t.bools\n }, {\n name: 'background-position-x',\n type: t.bgPos\n }, {\n name: 'background-position-y',\n type: t.bgPos\n }, {\n name: 'background-width-relative-to',\n type: t.bgRelativeTo\n }, {\n name: 'background-height-relative-to',\n type: t.bgRelativeTo\n }, {\n name: 'background-repeat',\n type: t.bgRepeat\n }, {\n name: 'background-fit',\n type: t.bgFit\n }, {\n name: 'background-clip',\n type: t.bgClip\n }, {\n name: 'background-width',\n type: t.bgWH\n }, {\n name: 'background-height',\n type: t.bgWH\n }, {\n name: 'background-offset-x',\n type: t.bgPos\n }, {\n name: 'background-offset-y',\n type: t.bgPos\n }];\n var compound = [{\n name: 'position',\n type: t.position,\n triggersBounds: diff.any\n }, {\n name: 'compound-sizing-wrt-labels',\n type: t.compoundIncludeLabels,\n triggersBounds: diff.any\n }, {\n name: 'min-width',\n type: t.size,\n triggersBounds: diff.any\n }, {\n name: 'min-width-bias-left',\n type: t.sizeMaybePercent,\n triggersBounds: diff.any\n }, {\n name: 'min-width-bias-right',\n type: t.sizeMaybePercent,\n triggersBounds: diff.any\n }, {\n name: 'min-height',\n type: t.size,\n triggersBounds: diff.any\n }, {\n name: 'min-height-bias-top',\n type: t.sizeMaybePercent,\n triggersBounds: diff.any\n }, {\n name: 'min-height-bias-bottom',\n type: t.sizeMaybePercent,\n triggersBounds: diff.any\n }];\n var edgeLine = [{\n name: 'line-style',\n type: t.lineStyle\n }, {\n name: 'line-color',\n type: t.color\n }, {\n name: 'line-fill',\n type: t.fill\n }, {\n name: 'line-cap',\n type: t.lineCap\n }, {\n name: 'line-opacity',\n type: t.zeroOneNumber\n }, {\n name: 'line-dash-pattern',\n type: t.numbers\n }, {\n name: 'line-dash-offset',\n type: t.number\n }, {\n name: 'line-outline-width',\n type: t.size\n }, {\n name: 'line-outline-color',\n type: t.color\n }, {\n name: 'line-gradient-stop-colors',\n type: t.colors\n }, {\n name: 'line-gradient-stop-positions',\n type: t.percentages\n }, {\n name: 'curve-style',\n type: t.curveStyle,\n triggersBounds: diff.any,\n triggersBoundsOfParallelEdges: function triggersBoundsOfParallelEdges(fromValue, toValue) {\n if (fromValue === toValue) {\n return false;\n } // must have diff\n\n return fromValue === 'bezier' ||\n // remove from bundle\n toValue === 'bezier'; // add to bundle\n }\n }, {\n name: 'haystack-radius',\n type: t.zeroOneNumber,\n triggersBounds: diff.any\n }, {\n name: 'source-endpoint',\n type: t.edgeEndpoint,\n triggersBounds: diff.any\n }, {\n name: 'target-endpoint',\n type: t.edgeEndpoint,\n triggersBounds: diff.any\n }, {\n name: 'control-point-step-size',\n type: t.size,\n triggersBounds: diff.any\n }, {\n name: 'control-point-distances',\n type: t.bidirectionalSizes,\n triggersBounds: diff.any\n }, {\n name: 'control-point-weights',\n type: t.numbers,\n triggersBounds: diff.any\n }, {\n name: 'segment-distances',\n type: t.bidirectionalSizes,\n triggersBounds: diff.any\n }, {\n name: 'segment-weights',\n type: t.numbers,\n triggersBounds: diff.any\n }, {\n name: 'segment-radii',\n type: t.numbers,\n triggersBounds: diff.any\n }, {\n name: 'radius-type',\n type: t.radiusType,\n triggersBounds: diff.any\n }, {\n name: 'taxi-turn',\n type: t.bidirectionalSizeMaybePercent,\n triggersBounds: diff.any\n }, {\n name: 'taxi-turn-min-distance',\n type: t.size,\n triggersBounds: diff.any\n }, {\n name: 'taxi-direction',\n type: t.axisDirection,\n triggersBounds: diff.any\n }, {\n name: 'taxi-radius',\n type: t.number,\n triggersBounds: diff.any\n }, {\n name: 'edge-distances',\n type: t.edgeDistances,\n triggersBounds: diff.any\n }, {\n name: 'arrow-scale',\n type: t.positiveNumber,\n triggersBounds: diff.any\n }, {\n name: 'loop-direction',\n type: t.angle,\n triggersBounds: diff.any\n }, {\n name: 'loop-sweep',\n type: t.angle,\n triggersBounds: diff.any\n }, {\n name: 'source-distance-from-node',\n type: t.size,\n triggersBounds: diff.any\n }, {\n name: 'target-distance-from-node',\n type: t.size,\n triggersBounds: diff.any\n }];\n var ghost = [{\n name: 'ghost',\n type: t.bool,\n triggersBounds: diff.any\n }, {\n name: 'ghost-offset-x',\n type: t.bidirectionalSize,\n triggersBounds: diff.any\n }, {\n name: 'ghost-offset-y',\n type: t.bidirectionalSize,\n triggersBounds: diff.any\n }, {\n name: 'ghost-opacity',\n type: t.zeroOneNumber\n }];\n var core = [{\n name: 'selection-box-color',\n type: t.color\n }, {\n name: 'selection-box-opacity',\n type: t.zeroOneNumber\n }, {\n name: 'selection-box-border-color',\n type: t.color\n }, {\n name: 'selection-box-border-width',\n type: t.size\n }, {\n name: 'active-bg-color',\n type: t.color\n }, {\n name: 'active-bg-opacity',\n type: t.zeroOneNumber\n }, {\n name: 'active-bg-size',\n type: t.size\n }, {\n name: 'outside-texture-bg-color',\n type: t.color\n }, {\n name: 'outside-texture-bg-opacity',\n type: t.zeroOneNumber\n }];\n\n // pie backgrounds for nodes\n var pie = [];\n styfn$2.pieBackgroundN = 16; // because the pie properties are numbered, give access to a constant N (for renderer use)\n pie.push({\n name: 'pie-size',\n type: t.sizeMaybePercent\n });\n pie.push({\n name: 'pie-hole',\n type: t.sizeMaybePercent\n });\n pie.push({\n name: 'pie-start-angle',\n type: t.angle\n });\n for (var i = 1; i <= styfn$2.pieBackgroundN; i++) {\n pie.push({\n name: 'pie-' + i + '-background-color',\n type: t.color\n });\n pie.push({\n name: 'pie-' + i + '-background-size',\n type: t.percent\n });\n pie.push({\n name: 'pie-' + i + '-background-opacity',\n type: t.zeroOneNumber\n });\n }\n\n // stripe backgrounds for nodes\n var stripe = [];\n styfn$2.stripeBackgroundN = 16; // because the stripe properties are numbered, give access to a constant N (for renderer use)\n stripe.push({\n name: 'stripe-size',\n type: t.sizeMaybePercent\n });\n stripe.push({\n name: 'stripe-direction',\n type: t.axisDirectionPrimary\n });\n for (var _i = 1; _i <= styfn$2.stripeBackgroundN; _i++) {\n stripe.push({\n name: 'stripe-' + _i + '-background-color',\n type: t.color\n });\n stripe.push({\n name: 'stripe-' + _i + '-background-size',\n type: t.percent\n });\n stripe.push({\n name: 'stripe-' + _i + '-background-opacity',\n type: t.zeroOneNumber\n });\n }\n\n // edge arrows\n var edgeArrow = [];\n var arrowPrefixes = styfn$2.arrowPrefixes = ['source', 'mid-source', 'target', 'mid-target'];\n [{\n name: 'arrow-shape',\n type: t.arrowShape,\n triggersBounds: diff.any\n }, {\n name: 'arrow-color',\n type: t.color\n }, {\n name: 'arrow-fill',\n type: t.arrowFill\n }, {\n name: 'arrow-width',\n type: t.arrowWidth\n }].forEach(function (prop) {\n arrowPrefixes.forEach(function (prefix) {\n var name = prefix + '-' + prop.name;\n var type = prop.type,\n triggersBounds = prop.triggersBounds;\n edgeArrow.push({\n name: name,\n type: type,\n triggersBounds: triggersBounds\n });\n });\n }, {});\n var props = styfn$2.properties = [].concat(behavior, transition, visibility, overlay, underlay, ghost, commonLabel, labelDimensions, mainLabel, sourceLabel, targetLabel, nodeBody, nodeBorder, nodeOutline, backgroundImage, pie, stripe, compound, edgeLine, edgeArrow, core);\n var propGroups = styfn$2.propertyGroups = {\n // common to all eles\n behavior: behavior,\n transition: transition,\n visibility: visibility,\n overlay: overlay,\n underlay: underlay,\n ghost: ghost,\n // labels\n commonLabel: commonLabel,\n labelDimensions: labelDimensions,\n mainLabel: mainLabel,\n sourceLabel: sourceLabel,\n targetLabel: targetLabel,\n // node props\n nodeBody: nodeBody,\n nodeBorder: nodeBorder,\n nodeOutline: nodeOutline,\n backgroundImage: backgroundImage,\n pie: pie,\n stripe: stripe,\n compound: compound,\n // edge props\n edgeLine: edgeLine,\n edgeArrow: edgeArrow,\n core: core\n };\n var propGroupNames = styfn$2.propertyGroupNames = {};\n var propGroupKeys = styfn$2.propertyGroupKeys = Object.keys(propGroups);\n propGroupKeys.forEach(function (key) {\n propGroupNames[key] = propGroups[key].map(function (prop) {\n return prop.name;\n });\n propGroups[key].forEach(function (prop) {\n return prop.groupKey = key;\n });\n });\n\n // define aliases\n var aliases = styfn$2.aliases = [{\n name: 'content',\n pointsTo: 'label'\n }, {\n name: 'control-point-distance',\n pointsTo: 'control-point-distances'\n }, {\n name: 'control-point-weight',\n pointsTo: 'control-point-weights'\n }, {\n name: 'segment-distance',\n pointsTo: 'segment-distances'\n }, {\n name: 'segment-weight',\n pointsTo: 'segment-weights'\n }, {\n name: 'segment-radius',\n pointsTo: 'segment-radii'\n }, {\n name: 'edge-text-rotation',\n pointsTo: 'text-rotation'\n }, {\n name: 'padding-left',\n pointsTo: 'padding'\n }, {\n name: 'padding-right',\n pointsTo: 'padding'\n }, {\n name: 'padding-top',\n pointsTo: 'padding'\n }, {\n name: 'padding-bottom',\n pointsTo: 'padding'\n }];\n\n // list of property names\n styfn$2.propertyNames = props.map(function (p) {\n return p.name;\n });\n\n // allow access of properties by name ( e.g. style.properties.height )\n for (var _i2 = 0; _i2 < props.length; _i2++) {\n var prop = props[_i2];\n props[prop.name] = prop; // allow lookup by name\n }\n\n // map aliases\n for (var _i3 = 0; _i3 < aliases.length; _i3++) {\n var alias = aliases[_i3];\n var pointsToProp = props[alias.pointsTo];\n var aliasProp = {\n name: alias.name,\n alias: true,\n pointsTo: pointsToProp\n };\n\n // add alias prop for parsing\n props.push(aliasProp);\n props[alias.name] = aliasProp; // allow lookup by name\n }\n})();\nstyfn$2.getDefaultProperty = function (name) {\n return this.getDefaultProperties()[name];\n};\nstyfn$2.getDefaultProperties = function () {\n var _p = this._private;\n if (_p.defaultProperties != null) {\n return _p.defaultProperties;\n }\n var rawProps = extend({\n // core props\n 'selection-box-color': '#ddd',\n 'selection-box-opacity': 0.65,\n 'selection-box-border-color': '#aaa',\n 'selection-box-border-width': 1,\n 'active-bg-color': 'black',\n 'active-bg-opacity': 0.15,\n 'active-bg-size': 30,\n 'outside-texture-bg-color': '#000',\n 'outside-texture-bg-opacity': 0.125,\n // common node/edge props\n 'events': 'yes',\n 'text-events': 'no',\n 'text-valign': 'top',\n 'text-halign': 'center',\n 'text-justification': 'auto',\n 'line-height': 1,\n 'color': '#000',\n 'box-selection': 'contain',\n 'text-outline-color': '#000',\n 'text-outline-width': 0,\n 'text-outline-opacity': 1,\n 'text-opacity': 1,\n 'text-decoration': 'none',\n 'text-transform': 'none',\n 'text-wrap': 'none',\n 'text-overflow-wrap': 'whitespace',\n 'text-max-width': 9999,\n 'text-background-color': '#000',\n 'text-background-opacity': 0,\n 'text-background-shape': 'rectangle',\n 'text-background-padding': 0,\n 'text-border-opacity': 0,\n 'text-border-width': 0,\n 'text-border-style': 'solid',\n 'text-border-color': '#000',\n 'font-family': 'Helvetica Neue, Helvetica, sans-serif',\n 'font-style': 'normal',\n 'font-weight': 'normal',\n 'font-size': 16,\n 'min-zoomed-font-size': 0,\n 'text-rotation': 'none',\n 'source-text-rotation': 'none',\n 'target-text-rotation': 'none',\n 'visibility': 'visible',\n 'display': 'element',\n 'opacity': 1,\n 'z-compound-depth': 'auto',\n 'z-index-compare': 'auto',\n 'z-index': 0,\n 'label': '',\n 'text-margin-x': 0,\n 'text-margin-y': 0,\n 'source-label': '',\n 'source-text-offset': 0,\n 'source-text-margin-x': 0,\n 'source-text-margin-y': 0,\n 'target-label': '',\n 'target-text-offset': 0,\n 'target-text-margin-x': 0,\n 'target-text-margin-y': 0,\n 'overlay-opacity': 0,\n 'overlay-color': '#000',\n 'overlay-padding': 10,\n 'overlay-shape': 'round-rectangle',\n 'overlay-corner-radius': 'auto',\n 'underlay-opacity': 0,\n 'underlay-color': '#000',\n 'underlay-padding': 10,\n 'underlay-shape': 'round-rectangle',\n 'underlay-corner-radius': 'auto',\n 'transition-property': 'none',\n 'transition-duration': 0,\n 'transition-delay': 0,\n 'transition-timing-function': 'linear',\n 'box-select-labels': 'no',\n // node props\n 'background-blacken': 0,\n 'background-color': '#999',\n 'background-fill': 'solid',\n 'background-opacity': 1,\n 'background-image': 'none',\n 'background-image-crossorigin': 'anonymous',\n 'background-image-opacity': 1,\n 'background-image-containment': 'inside',\n 'background-image-smoothing': 'yes',\n 'background-position-x': '50%',\n 'background-position-y': '50%',\n 'background-offset-x': 0,\n 'background-offset-y': 0,\n 'background-width-relative-to': 'include-padding',\n 'background-height-relative-to': 'include-padding',\n 'background-repeat': 'no-repeat',\n 'background-fit': 'none',\n 'background-clip': 'node',\n 'background-width': 'auto',\n 'background-height': 'auto',\n 'border-color': '#000',\n 'border-opacity': 1,\n 'border-width': 0,\n 'border-style': 'solid',\n 'border-dash-pattern': [4, 2],\n 'border-dash-offset': 0,\n 'border-cap': 'butt',\n 'border-join': 'miter',\n 'border-position': 'center',\n 'outline-color': '#999',\n 'outline-opacity': 1,\n 'outline-width': 0,\n 'outline-offset': 0,\n 'outline-style': 'solid',\n 'height': 30,\n 'width': 30,\n 'shape': 'ellipse',\n 'shape-polygon-points': '-1, -1, 1, -1, 1, 1, -1, 1',\n 'corner-radius': 'auto',\n 'bounds-expansion': 0,\n // node gradient\n 'background-gradient-direction': 'to-bottom',\n 'background-gradient-stop-colors': '#999',\n 'background-gradient-stop-positions': '0%',\n // ghost props\n 'ghost': 'no',\n 'ghost-offset-y': 0,\n 'ghost-offset-x': 0,\n 'ghost-opacity': 0,\n // compound props\n 'padding': 0,\n 'padding-relative-to': 'width',\n 'position': 'origin',\n 'compound-sizing-wrt-labels': 'include',\n 'min-width': 0,\n 'min-width-bias-left': 0,\n 'min-width-bias-right': 0,\n 'min-height': 0,\n 'min-height-bias-top': 0,\n 'min-height-bias-bottom': 0\n }, {\n // node pie bg\n 'pie-size': '100%',\n 'pie-hole': 0,\n 'pie-start-angle': '0deg'\n }, [{\n name: 'pie-{{i}}-background-color',\n value: 'black'\n }, {\n name: 'pie-{{i}}-background-size',\n value: '0%'\n }, {\n name: 'pie-{{i}}-background-opacity',\n value: 1\n }].reduce(function (css, prop) {\n for (var i = 1; i <= styfn$2.pieBackgroundN; i++) {\n var name = prop.name.replace('{{i}}', i);\n var val = prop.value;\n css[name] = val;\n }\n return css;\n }, {}), {\n // node stripes bg\n 'stripe-size': '100%',\n 'stripe-direction': 'horizontal'\n }, [{\n name: 'stripe-{{i}}-background-color',\n value: 'black'\n }, {\n name: 'stripe-{{i}}-background-size',\n value: '0%'\n }, {\n name: 'stripe-{{i}}-background-opacity',\n value: 1\n }].reduce(function (css, prop) {\n for (var i = 1; i <= styfn$2.stripeBackgroundN; i++) {\n var name = prop.name.replace('{{i}}', i);\n var val = prop.value;\n css[name] = val;\n }\n return css;\n }, {}), {\n // edge props\n 'line-style': 'solid',\n 'line-color': '#999',\n 'line-fill': 'solid',\n 'line-cap': 'butt',\n 'line-opacity': 1,\n 'line-outline-width': 0,\n 'line-outline-color': '#000',\n 'line-gradient-stop-colors': '#999',\n 'line-gradient-stop-positions': '0%',\n 'control-point-step-size': 40,\n 'control-point-weights': 0.5,\n 'segment-weights': 0.5,\n 'segment-distances': 20,\n 'segment-radii': 15,\n 'radius-type': 'arc-radius',\n 'taxi-turn': '50%',\n 'taxi-radius': 15,\n 'taxi-turn-min-distance': 10,\n 'taxi-direction': 'auto',\n 'edge-distances': 'intersection',\n 'curve-style': 'haystack',\n 'haystack-radius': 0,\n 'arrow-scale': 1,\n 'loop-direction': '-45deg',\n 'loop-sweep': '-90deg',\n 'source-distance-from-node': 0,\n 'target-distance-from-node': 0,\n 'source-endpoint': 'outside-to-node',\n 'target-endpoint': 'outside-to-node',\n 'line-dash-pattern': [6, 3],\n 'line-dash-offset': 0\n }, [{\n name: 'arrow-shape',\n value: 'none'\n }, {\n name: 'arrow-color',\n value: '#999'\n }, {\n name: 'arrow-fill',\n value: 'filled'\n }, {\n name: 'arrow-width',\n value: 1\n }].reduce(function (css, prop) {\n styfn$2.arrowPrefixes.forEach(function (prefix) {\n var name = prefix + '-' + prop.name;\n var val = prop.value;\n css[name] = val;\n });\n return css;\n }, {}));\n var parsedProps = {};\n for (var i = 0; i < this.properties.length; i++) {\n var prop = this.properties[i];\n if (prop.pointsTo) {\n continue;\n }\n var name = prop.name;\n var val = rawProps[name];\n var parsedProp = this.parse(name, val);\n parsedProps[name] = parsedProp;\n }\n _p.defaultProperties = parsedProps;\n return _p.defaultProperties;\n};\nstyfn$2.addDefaultStylesheet = function () {\n this.selector(':parent').css({\n 'shape': 'rectangle',\n 'padding': 10,\n 'background-color': '#eee',\n 'border-color': '#ccc',\n 'border-width': 1\n }).selector('edge').css({\n 'width': 3\n }).selector(':loop').css({\n 'curve-style': 'bezier'\n }).selector('edge:compound').css({\n 'curve-style': 'bezier',\n 'source-endpoint': 'outside-to-line',\n 'target-endpoint': 'outside-to-line'\n }).selector(':selected').css({\n 'background-color': '#0169D9',\n 'line-color': '#0169D9',\n 'source-arrow-color': '#0169D9',\n 'target-arrow-color': '#0169D9',\n 'mid-source-arrow-color': '#0169D9',\n 'mid-target-arrow-color': '#0169D9'\n }).selector(':parent:selected').css({\n 'background-color': '#CCE1F9',\n 'border-color': '#aec8e5'\n }).selector(':active').css({\n 'overlay-color': 'black',\n 'overlay-padding': 10,\n 'overlay-opacity': 0.25\n });\n this.defaultLength = this.length;\n};\n\nvar styfn$1 = {};\n\n// a caching layer for property parsing\nstyfn$1.parse = function (name, value, propIsBypass, propIsFlat) {\n var self = this;\n\n // function values can't be cached in all cases, and there isn't much benefit of caching them anyway\n if (fn$6(value)) {\n return self.parseImplWarn(name, value, propIsBypass, propIsFlat);\n }\n var flatKey = propIsFlat === 'mapping' || propIsFlat === true || propIsFlat === false || propIsFlat == null ? 'dontcare' : propIsFlat;\n var bypassKey = propIsBypass ? 't' : 'f';\n var valueKey = '' + value;\n var argHash = hashStrings(name, valueKey, bypassKey, flatKey);\n var propCache = self.propCache = self.propCache || [];\n var ret;\n if (!(ret = propCache[argHash])) {\n ret = propCache[argHash] = self.parseImplWarn(name, value, propIsBypass, propIsFlat);\n }\n\n // - bypasses can't be shared b/c the value can be changed by animations or otherwise overridden\n // - mappings can't be shared b/c mappings are per-element\n if (propIsBypass || propIsFlat === 'mapping') {\n // need a copy since props are mutated later in their lifecycles\n ret = copy(ret);\n if (ret) {\n ret.value = copy(ret.value); // because it could be an array, e.g. colour\n }\n }\n return ret;\n};\nstyfn$1.parseImplWarn = function (name, value, propIsBypass, propIsFlat) {\n var prop = this.parseImpl(name, value, propIsBypass, propIsFlat);\n if (!prop && value != null) {\n warn(\"The style property `\".concat(name, \": \").concat(value, \"` is invalid\"));\n }\n if (prop && (prop.name === 'width' || prop.name === 'height') && value === 'label') {\n warn('The style value of `label` is deprecated for `' + prop.name + '`');\n }\n return prop;\n};\n\n// parse a property; return null on invalid; return parsed property otherwise\n// fields :\n// - name : the name of the property\n// - value : the parsed, native-typed value of the property\n// - strValue : a string value that represents the property value in valid css\n// - bypass : true iff the property is a bypass property\nstyfn$1.parseImpl = function (name, value, propIsBypass, propIsFlat) {\n var self = this;\n name = camel2dash(name); // make sure the property name is in dash form (e.g. 'property-name' not 'propertyName')\n\n var property = self.properties[name];\n var passedValue = value;\n var types = self.types;\n if (!property) {\n return null;\n } // return null on property of unknown name\n if (value === undefined) {\n return null;\n } // can't assign undefined\n\n // the property may be an alias\n if (property.alias) {\n property = property.pointsTo;\n name = property.name;\n }\n var valueIsString = string(value);\n if (valueIsString) {\n // trim the value to make parsing easier\n value = value.trim();\n }\n var type = property.type;\n if (!type) {\n return null;\n } // no type, no luck\n\n // check if bypass is null or empty string (i.e. indication to delete bypass property)\n if (propIsBypass && (value === '' || value === null)) {\n return {\n name: name,\n value: value,\n bypass: true,\n deleteBypass: true\n };\n }\n\n // check if value is a function used as a mapper\n if (fn$6(value)) {\n return {\n name: name,\n value: value,\n strValue: 'fn',\n mapped: types.fn,\n bypass: propIsBypass\n };\n }\n\n // check if value is mapped\n var data, mapData;\n if (!valueIsString || propIsFlat || value.length < 7 || value[1] !== 'a') ; else if (value.length >= 7 && value[0] === 'd' && (data = new RegExp(types.data.regex).exec(value))) {\n if (propIsBypass) {\n return false;\n } // mappers not allowed in bypass\n\n var mapped = types.data;\n return {\n name: name,\n value: data,\n strValue: '' + value,\n mapped: mapped,\n field: data[1],\n bypass: propIsBypass\n };\n } else if (value.length >= 10 && value[0] === 'm' && (mapData = new RegExp(types.mapData.regex).exec(value))) {\n if (propIsBypass) {\n return false;\n } // mappers not allowed in bypass\n if (type.multiple) {\n return false;\n } // impossible to map to num\n\n var _mapped = types.mapData;\n\n // we can map only if the type is a colour or a number\n if (!(type.color || type.number)) {\n return false;\n }\n var valueMin = this.parse(name, mapData[4]); // parse to validate\n if (!valueMin || valueMin.mapped) {\n return false;\n } // can't be invalid or mapped\n\n var valueMax = this.parse(name, mapData[5]); // parse to validate\n if (!valueMax || valueMax.mapped) {\n return false;\n } // can't be invalid or mapped\n\n // check if valueMin and valueMax are the same\n if (valueMin.pfValue === valueMax.pfValue || valueMin.strValue === valueMax.strValue) {\n warn('`' + name + ': ' + value + '` is not a valid mapper because the output range is zero; converting to `' + name + ': ' + valueMin.strValue + '`');\n return this.parse(name, valueMin.strValue); // can't make much of a mapper without a range\n } else if (type.color) {\n var c1 = valueMin.value;\n var c2 = valueMax.value;\n var same = c1[0] === c2[0] // red\n && c1[1] === c2[1] // green\n && c1[2] === c2[2] // blue\n && (\n // optional alpha\n c1[3] === c2[3] // same alpha outright\n || (c1[3] == null || c1[3] === 1 // full opacity for colour 1?\n ) && (c2[3] == null || c2[3] === 1) // full opacity for colour 2?\n );\n if (same) {\n return false;\n } // can't make a mapper without a range\n }\n return {\n name: name,\n value: mapData,\n strValue: '' + value,\n mapped: _mapped,\n field: mapData[1],\n fieldMin: parseFloat(mapData[2]),\n // min & max are numeric\n fieldMax: parseFloat(mapData[3]),\n valueMin: valueMin.value,\n valueMax: valueMax.value,\n bypass: propIsBypass\n };\n }\n if (type.multiple && propIsFlat !== 'multiple') {\n var vals;\n if (valueIsString) {\n vals = value.split(/\\s+/);\n } else if (array(value)) {\n vals = value;\n } else {\n vals = [value];\n }\n if (type.evenMultiple && vals.length % 2 !== 0) {\n return null;\n }\n var valArr = [];\n var unitsArr = [];\n var pfValArr = [];\n var strVal = '';\n var hasEnum = false;\n for (var i = 0; i < vals.length; i++) {\n var p = self.parse(name, vals[i], propIsBypass, 'multiple');\n hasEnum = hasEnum || string(p.value);\n valArr.push(p.value);\n pfValArr.push(p.pfValue != null ? p.pfValue : p.value);\n unitsArr.push(p.units);\n strVal += (i > 0 ? ' ' : '') + p.strValue;\n }\n if (type.validate && !type.validate(valArr, unitsArr)) {\n return null;\n }\n if (type.singleEnum && hasEnum) {\n if (valArr.length === 1 && string(valArr[0])) {\n return {\n name: name,\n value: valArr[0],\n strValue: valArr[0],\n bypass: propIsBypass\n };\n } else {\n return null;\n }\n }\n return {\n name: name,\n value: valArr,\n pfValue: pfValArr,\n strValue: strVal,\n bypass: propIsBypass,\n units: unitsArr\n };\n }\n\n // several types also allow enums\n var checkEnums = function checkEnums() {\n for (var _i = 0; _i < type.enums.length; _i++) {\n var en = type.enums[_i];\n if (en === value) {\n return {\n name: name,\n value: value,\n strValue: '' + value,\n bypass: propIsBypass\n };\n }\n }\n return null;\n };\n\n // check the type and return the appropriate object\n if (type.number) {\n var units;\n var implicitUnits = 'px'; // not set => px\n\n if (type.units) {\n // use specified units if set\n units = type.units;\n }\n if (type.implicitUnits) {\n implicitUnits = type.implicitUnits;\n }\n if (!type.unitless) {\n if (valueIsString) {\n var unitsRegex = 'px|em' + (type.allowPercent ? '|\\\\%' : '');\n if (units) {\n unitsRegex = units;\n } // only allow explicit units if so set\n var match = value.match('^(' + number + ')(' + unitsRegex + ')?' + '$');\n if (match) {\n value = match[1];\n units = match[2] || implicitUnits;\n }\n } else if (!units || type.implicitUnits) {\n units = implicitUnits; // implicitly px if unspecified\n }\n }\n value = parseFloat(value);\n\n // if not a number and enums not allowed, then the value is invalid\n if (isNaN(value) && type.enums === undefined) {\n return null;\n }\n\n // check if this number type also accepts special keywords in place of numbers\n // (i.e. `left`, `auto`, etc)\n if (isNaN(value) && type.enums !== undefined) {\n value = passedValue;\n return checkEnums();\n }\n\n // check if value must be an integer\n if (type.integer && !integer(value)) {\n return null;\n }\n\n // check value is within range\n if (type.min !== undefined && (value < type.min || type.strictMin && value === type.min) || type.max !== undefined && (value > type.max || type.strictMax && value === type.max)) {\n return null;\n }\n var ret = {\n name: name,\n value: value,\n strValue: '' + value + (units ? units : ''),\n units: units,\n bypass: propIsBypass\n };\n\n // normalise value in pixels\n if (type.unitless || units !== 'px' && units !== 'em') {\n ret.pfValue = value;\n } else {\n ret.pfValue = units === 'px' || !units ? value : this.getEmSizeInPixels() * value;\n }\n\n // normalise value in ms\n if (units === 'ms' || units === 's') {\n ret.pfValue = units === 'ms' ? value : 1000 * value;\n }\n\n // normalise value in rad\n if (units === 'deg' || units === 'rad') {\n ret.pfValue = units === 'rad' ? value : deg2rad(value);\n }\n\n // normalize value in %\n if (units === '%') {\n ret.pfValue = value / 100;\n }\n return ret;\n } else if (type.propList) {\n var props = [];\n var propsStr = '' + value;\n if (propsStr === 'none') ; else {\n // go over each prop\n\n var propsSplit = propsStr.split(/\\s*,\\s*|\\s+/);\n for (var _i2 = 0; _i2 < propsSplit.length; _i2++) {\n var propName = propsSplit[_i2].trim();\n if (self.properties[propName]) {\n props.push(propName);\n } else {\n warn('`' + propName + '` is not a valid property name');\n }\n }\n if (props.length === 0) {\n return null;\n }\n }\n return {\n name: name,\n value: props,\n strValue: props.length === 0 ? 'none' : props.join(' '),\n bypass: propIsBypass\n };\n } else if (type.color) {\n var tuple = color2tuple(value);\n if (!tuple) {\n return null;\n }\n return {\n name: name,\n value: tuple,\n pfValue: tuple,\n strValue: 'rgb(' + tuple[0] + ',' + tuple[1] + ',' + tuple[2] + ')',\n // n.b. no spaces b/c of multiple support\n bypass: propIsBypass\n };\n } else if (type.regex || type.regexes) {\n // first check enums\n if (type.enums) {\n var enumProp = checkEnums();\n if (enumProp) {\n return enumProp;\n }\n }\n var regexes = type.regexes ? type.regexes : [type.regex];\n for (var _i3 = 0; _i3 < regexes.length; _i3++) {\n var regex = new RegExp(regexes[_i3]); // make a regex from the type string\n var m = regex.exec(value);\n if (m) {\n // regex matches\n return {\n name: name,\n value: type.singleRegexMatchValue ? m[1] : m,\n strValue: '' + value,\n bypass: propIsBypass\n };\n }\n }\n return null; // didn't match any\n } else if (type.string) {\n // just return\n return {\n name: name,\n value: '' + value,\n strValue: '' + value,\n bypass: propIsBypass\n };\n } else if (type.enums) {\n // check enums last because it's a combo type in others\n return checkEnums();\n } else {\n return null; // not a type we can handle\n }\n};\n\nvar _Style = function Style(cy) {\n if (!(this instanceof _Style)) {\n return new _Style(cy);\n }\n if (!core(cy)) {\n error('A style must have a core reference');\n return;\n }\n this._private = {\n cy: cy,\n coreStyle: {}\n };\n this.length = 0;\n this.resetToDefault();\n};\nvar styfn = _Style.prototype;\nstyfn.instanceString = function () {\n return 'style';\n};\n\n// remove all contexts\nstyfn.clear = function () {\n var _p = this._private;\n var cy = _p.cy;\n var eles = cy.elements();\n for (var i = 0; i < this.length; i++) {\n this[i] = undefined;\n }\n this.length = 0;\n _p.contextStyles = {};\n _p.propDiffs = {};\n this.cleanElements(eles, true);\n eles.forEach(function (ele) {\n var ele_p = ele[0]._private;\n ele_p.styleDirty = true;\n ele_p.appliedInitStyle = false;\n });\n return this; // chaining\n};\nstyfn.resetToDefault = function () {\n this.clear();\n this.addDefaultStylesheet();\n return this;\n};\n\n// builds a style object for the 'core' selector\nstyfn.core = function (propName) {\n return this._private.coreStyle[propName] || this.getDefaultProperty(propName);\n};\n\n// create a new context from the specified selector string and switch to that context\nstyfn.selector = function (selectorStr) {\n // 'core' is a special case and does not need a selector\n var selector = selectorStr === 'core' ? null : new Selector(selectorStr);\n var i = this.length++; // new context means new index\n this[i] = {\n selector: selector,\n properties: [],\n mappedProperties: [],\n index: i\n };\n return this; // chaining\n};\n\n// add one or many css rules to the current context\nstyfn.css = function () {\n var self = this;\n var args = arguments;\n if (args.length === 1) {\n var map = args[0];\n for (var i = 0; i < self.properties.length; i++) {\n var prop = self.properties[i];\n var mapVal = map[prop.name];\n if (mapVal === undefined) {\n mapVal = map[dash2camel(prop.name)];\n }\n if (mapVal !== undefined) {\n this.cssRule(prop.name, mapVal);\n }\n }\n } else if (args.length === 2) {\n this.cssRule(args[0], args[1]);\n }\n\n // do nothing if args are invalid\n\n return this; // chaining\n};\nstyfn.style = styfn.css;\n\n// add a single css rule to the current context\nstyfn.cssRule = function (name, value) {\n // name-value pair\n var property = this.parse(name, value);\n\n // add property to current context if valid\n if (property) {\n var i = this.length - 1;\n this[i].properties.push(property);\n this[i].properties[property.name] = property; // allow access by name as well\n\n if (property.name.match(/pie-(\\d+)-background-size/) && property.value) {\n this._private.hasPie = true;\n }\n if (property.name.match(/stripe-(\\d+)-background-size/) && property.value) {\n this._private.hasStripe = true;\n }\n if (property.mapped) {\n this[i].mappedProperties.push(property);\n }\n\n // add to core style if necessary\n var currentSelectorIsCore = !this[i].selector;\n if (currentSelectorIsCore) {\n this._private.coreStyle[property.name] = property;\n }\n }\n return this; // chaining\n};\nstyfn.append = function (style) {\n if (stylesheet(style)) {\n style.appendToStyle(this);\n } else if (array(style)) {\n this.appendFromJson(style);\n } else if (string(style)) {\n this.appendFromString(style);\n } // you probably wouldn't want to append a Style, since you'd duplicate the default parts\n\n return this;\n};\n\n// static function\n_Style.fromJson = function (cy, json) {\n var style = new _Style(cy);\n style.fromJson(json);\n return style;\n};\n_Style.fromString = function (cy, string) {\n return new _Style(cy).fromString(string);\n};\n[styfn$8, styfn$7, styfn$6, styfn$5, styfn$4, styfn$3, styfn$2, styfn$1].forEach(function (props) {\n extend(styfn, props);\n});\n_Style.types = styfn.types;\n_Style.properties = styfn.properties;\n_Style.propertyGroups = styfn.propertyGroups;\n_Style.propertyGroupNames = styfn.propertyGroupNames;\n_Style.propertyGroupKeys = styfn.propertyGroupKeys;\n\nvar corefn$2 = {\n style: function style(newStyle) {\n if (newStyle) {\n var s = this.setStyle(newStyle);\n s.update();\n }\n return this._private.style;\n },\n setStyle: function setStyle(style) {\n var _p = this._private;\n if (stylesheet(style)) {\n _p.style = style.generateStyle(this);\n } else if (array(style)) {\n _p.style = _Style.fromJson(this, style);\n } else if (string(style)) {\n _p.style = _Style.fromString(this, style);\n } else {\n _p.style = _Style(this);\n }\n return _p.style;\n },\n // e.g. cy.data() changed => recalc ele mappers\n updateStyle: function updateStyle() {\n this.mutableElements().updateStyle(); // just send to all eles\n }\n};\n\nvar defaultSelectionType = 'single';\nvar corefn$1 = {\n autolock: function autolock(bool) {\n if (bool !== undefined) {\n this._private.autolock = bool ? true : false;\n } else {\n return this._private.autolock;\n }\n return this; // chaining\n },\n autoungrabify: function autoungrabify(bool) {\n if (bool !== undefined) {\n this._private.autoungrabify = bool ? true : false;\n } else {\n return this._private.autoungrabify;\n }\n return this; // chaining\n },\n autounselectify: function autounselectify(bool) {\n if (bool !== undefined) {\n this._private.autounselectify = bool ? true : false;\n } else {\n return this._private.autounselectify;\n }\n return this; // chaining\n },\n selectionType: function selectionType(selType) {\n var _p = this._private;\n if (_p.selectionType == null) {\n _p.selectionType = defaultSelectionType;\n }\n if (selType !== undefined) {\n if (selType === 'additive' || selType === 'single') {\n _p.selectionType = selType;\n }\n } else {\n return _p.selectionType;\n }\n return this;\n },\n panningEnabled: function panningEnabled(bool) {\n if (bool !== undefined) {\n this._private.panningEnabled = bool ? true : false;\n } else {\n return this._private.panningEnabled;\n }\n return this; // chaining\n },\n userPanningEnabled: function userPanningEnabled(bool) {\n if (bool !== undefined) {\n this._private.userPanningEnabled = bool ? true : false;\n } else {\n return this._private.userPanningEnabled;\n }\n return this; // chaining\n },\n zoomingEnabled: function zoomingEnabled(bool) {\n if (bool !== undefined) {\n this._private.zoomingEnabled = bool ? true : false;\n } else {\n return this._private.zoomingEnabled;\n }\n return this; // chaining\n },\n userZoomingEnabled: function userZoomingEnabled(bool) {\n if (bool !== undefined) {\n this._private.userZoomingEnabled = bool ? true : false;\n } else {\n return this._private.userZoomingEnabled;\n }\n return this; // chaining\n },\n boxSelectionEnabled: function boxSelectionEnabled(bool) {\n if (bool !== undefined) {\n this._private.boxSelectionEnabled = bool ? true : false;\n } else {\n return this._private.boxSelectionEnabled;\n }\n return this; // chaining\n },\n pan: function pan() {\n var args = arguments;\n var pan = this._private.pan;\n var dim, val, dims, x, y;\n switch (args.length) {\n case 0:\n // .pan()\n return pan;\n case 1:\n if (string(args[0])) {\n // .pan('x')\n dim = args[0];\n return pan[dim];\n } else if (plainObject(args[0])) {\n // .pan({ x: 0, y: 100 })\n if (!this._private.panningEnabled) {\n return this;\n }\n dims = args[0];\n x = dims.x;\n y = dims.y;\n if (number$1(x)) {\n pan.x = x;\n }\n if (number$1(y)) {\n pan.y = y;\n }\n this.emit('pan viewport');\n }\n break;\n case 2:\n // .pan('x', 100)\n if (!this._private.panningEnabled) {\n return this;\n }\n dim = args[0];\n val = args[1];\n if ((dim === 'x' || dim === 'y') && number$1(val)) {\n pan[dim] = val;\n }\n this.emit('pan viewport');\n break;\n // invalid\n }\n this.notify('viewport');\n return this; // chaining\n },\n panBy: function panBy(arg0, arg1) {\n var args = arguments;\n var pan = this._private.pan;\n var dim, val, dims, x, y;\n if (!this._private.panningEnabled) {\n return this;\n }\n switch (args.length) {\n case 1:\n if (plainObject(arg0)) {\n // .panBy({ x: 0, y: 100 })\n dims = args[0];\n x = dims.x;\n y = dims.y;\n if (number$1(x)) {\n pan.x += x;\n }\n if (number$1(y)) {\n pan.y += y;\n }\n this.emit('pan viewport');\n }\n break;\n case 2:\n // .panBy('x', 100)\n dim = arg0;\n val = arg1;\n if ((dim === 'x' || dim === 'y') && number$1(val)) {\n pan[dim] += val;\n }\n this.emit('pan viewport');\n break;\n // invalid\n }\n this.notify('viewport');\n return this; // chaining\n },\n gc: function gc() {\n this.notify('gc');\n },\n fit: function fit(elements, padding) {\n var viewportState = this.getFitViewport(elements, padding);\n if (viewportState) {\n var _p = this._private;\n _p.zoom = viewportState.zoom;\n _p.pan = viewportState.pan;\n this.emit('pan zoom viewport');\n this.notify('viewport');\n }\n return this; // chaining\n },\n getFitViewport: function getFitViewport(elements, padding) {\n if (number$1(elements) && padding === undefined) {\n // elements is optional\n padding = elements;\n elements = undefined;\n }\n if (!this._private.panningEnabled || !this._private.zoomingEnabled) {\n return;\n }\n var bb;\n if (string(elements)) {\n var sel = elements;\n elements = this.$(sel);\n } else if (boundingBox(elements)) {\n // assume bb\n var bbe = elements;\n bb = {\n x1: bbe.x1,\n y1: bbe.y1,\n x2: bbe.x2,\n y2: bbe.y2\n };\n bb.w = bb.x2 - bb.x1;\n bb.h = bb.y2 - bb.y1;\n } else if (!elementOrCollection(elements)) {\n elements = this.mutableElements();\n }\n if (elementOrCollection(elements) && elements.empty()) {\n return;\n } // can't fit to nothing\n\n bb = bb || elements.boundingBox();\n var w = this.width();\n var h = this.height();\n var zoom;\n padding = number$1(padding) ? padding : 0;\n if (!isNaN(w) && !isNaN(h) && w > 0 && h > 0 && !isNaN(bb.w) && !isNaN(bb.h) && bb.w > 0 && bb.h > 0) {\n zoom = Math.min((w - 2 * padding) / bb.w, (h - 2 * padding) / bb.h);\n\n // crop zoom\n zoom = zoom > this._private.maxZoom ? this._private.maxZoom : zoom;\n zoom = zoom < this._private.minZoom ? this._private.minZoom : zoom;\n var pan = {\n // now pan to middle\n x: (w - zoom * (bb.x1 + bb.x2)) / 2,\n y: (h - zoom * (bb.y1 + bb.y2)) / 2\n };\n return {\n zoom: zoom,\n pan: pan\n };\n }\n return;\n },\n zoomRange: function zoomRange(min, max) {\n var _p = this._private;\n if (max == null) {\n var opts = min;\n min = opts.min;\n max = opts.max;\n }\n if (number$1(min) && number$1(max) && min <= max) {\n _p.minZoom = min;\n _p.maxZoom = max;\n } else if (number$1(min) && max === undefined && min <= _p.maxZoom) {\n _p.minZoom = min;\n } else if (number$1(max) && min === undefined && max >= _p.minZoom) {\n _p.maxZoom = max;\n }\n return this;\n },\n minZoom: function minZoom(zoom) {\n if (zoom === undefined) {\n return this._private.minZoom;\n } else {\n return this.zoomRange({\n min: zoom\n });\n }\n },\n maxZoom: function maxZoom(zoom) {\n if (zoom === undefined) {\n return this._private.maxZoom;\n } else {\n return this.zoomRange({\n max: zoom\n });\n }\n },\n getZoomedViewport: function getZoomedViewport(params) {\n var _p = this._private;\n var currentPan = _p.pan;\n var currentZoom = _p.zoom;\n var pos; // in rendered px\n var zoom;\n var bail = false;\n if (!_p.zoomingEnabled) {\n // zooming disabled\n bail = true;\n }\n if (number$1(params)) {\n // then set the zoom\n zoom = params;\n } else if (plainObject(params)) {\n // then zoom about a point\n zoom = params.level;\n if (params.position != null) {\n pos = modelToRenderedPosition$1(params.position, currentZoom, currentPan);\n } else if (params.renderedPosition != null) {\n pos = params.renderedPosition;\n }\n if (pos != null && !_p.panningEnabled) {\n // panning disabled\n bail = true;\n }\n }\n\n // crop zoom\n zoom = zoom > _p.maxZoom ? _p.maxZoom : zoom;\n zoom = zoom < _p.minZoom ? _p.minZoom : zoom;\n\n // can't zoom with invalid params\n if (bail || !number$1(zoom) || zoom === currentZoom || pos != null && (!number$1(pos.x) || !number$1(pos.y))) {\n return null;\n }\n if (pos != null) {\n // set zoom about position\n var pan1 = currentPan;\n var zoom1 = currentZoom;\n var zoom2 = zoom;\n var pan2 = {\n x: -zoom2 / zoom1 * (pos.x - pan1.x) + pos.x,\n y: -zoom2 / zoom1 * (pos.y - pan1.y) + pos.y\n };\n return {\n zoomed: true,\n panned: true,\n zoom: zoom2,\n pan: pan2\n };\n } else {\n // just set the zoom\n return {\n zoomed: true,\n panned: false,\n zoom: zoom,\n pan: currentPan\n };\n }\n },\n zoom: function zoom(params) {\n if (params === undefined) {\n // get\n return this._private.zoom;\n } else {\n // set\n var vp = this.getZoomedViewport(params);\n var _p = this._private;\n if (vp == null || !vp.zoomed) {\n return this;\n }\n _p.zoom = vp.zoom;\n if (vp.panned) {\n _p.pan.x = vp.pan.x;\n _p.pan.y = vp.pan.y;\n }\n this.emit('zoom' + (vp.panned ? ' pan' : '') + ' viewport');\n this.notify('viewport');\n return this; // chaining\n }\n },\n viewport: function viewport(opts) {\n var _p = this._private;\n var zoomDefd = true;\n var panDefd = true;\n var events = []; // to trigger\n var zoomFailed = false;\n var panFailed = false;\n if (!opts) {\n return this;\n }\n if (!number$1(opts.zoom)) {\n zoomDefd = false;\n }\n if (!plainObject(opts.pan)) {\n panDefd = false;\n }\n if (!zoomDefd && !panDefd) {\n return this;\n }\n if (zoomDefd) {\n var z = opts.zoom;\n if (z < _p.minZoom || z > _p.maxZoom || !_p.zoomingEnabled) {\n zoomFailed = true;\n } else {\n _p.zoom = z;\n events.push('zoom');\n }\n }\n if (panDefd && (!zoomFailed || !opts.cancelOnFailedZoom) && _p.panningEnabled) {\n var p = opts.pan;\n if (number$1(p.x)) {\n _p.pan.x = p.x;\n panFailed = false;\n }\n if (number$1(p.y)) {\n _p.pan.y = p.y;\n panFailed = false;\n }\n if (!panFailed) {\n events.push('pan');\n }\n }\n if (events.length > 0) {\n events.push('viewport');\n this.emit(events.join(' '));\n this.notify('viewport');\n }\n return this; // chaining\n },\n center: function center(elements) {\n var pan = this.getCenterPan(elements);\n if (pan) {\n this._private.pan = pan;\n this.emit('pan viewport');\n this.notify('viewport');\n }\n return this; // chaining\n },\n getCenterPan: function getCenterPan(elements, zoom) {\n if (!this._private.panningEnabled) {\n return;\n }\n if (string(elements)) {\n var selector = elements;\n elements = this.mutableElements().filter(selector);\n } else if (!elementOrCollection(elements)) {\n elements = this.mutableElements();\n }\n if (elements.length === 0) {\n return;\n } // can't centre pan to nothing\n\n var bb = elements.boundingBox();\n var w = this.width();\n var h = this.height();\n zoom = zoom === undefined ? this._private.zoom : zoom;\n var pan = {\n // middle\n x: (w - zoom * (bb.x1 + bb.x2)) / 2,\n y: (h - zoom * (bb.y1 + bb.y2)) / 2\n };\n return pan;\n },\n reset: function reset() {\n if (!this._private.panningEnabled || !this._private.zoomingEnabled) {\n return this;\n }\n this.viewport({\n pan: {\n x: 0,\n y: 0\n },\n zoom: 1\n });\n return this; // chaining\n },\n invalidateSize: function invalidateSize() {\n this._private.sizeCache = null;\n },\n size: function size() {\n var _p = this._private;\n var container = _p.container;\n var cy = this;\n return _p.sizeCache = _p.sizeCache || (container ? function () {\n var style = cy.window().getComputedStyle(container);\n var val = function val(name) {\n return parseFloat(style.getPropertyValue(name));\n };\n return {\n width: container.clientWidth - val('padding-left') - val('padding-right'),\n height: container.clientHeight - val('padding-top') - val('padding-bottom')\n };\n }() : {\n // fallback if no container (not 0 b/c can be used for dividing etc)\n width: 1,\n height: 1\n });\n },\n width: function width() {\n return this.size().width;\n },\n height: function height() {\n return this.size().height;\n },\n extent: function extent() {\n var pan = this._private.pan;\n var zoom = this._private.zoom;\n var rb = this.renderedExtent();\n var b = {\n x1: (rb.x1 - pan.x) / zoom,\n x2: (rb.x2 - pan.x) / zoom,\n y1: (rb.y1 - pan.y) / zoom,\n y2: (rb.y2 - pan.y) / zoom\n };\n b.w = b.x2 - b.x1;\n b.h = b.y2 - b.y1;\n return b;\n },\n renderedExtent: function renderedExtent() {\n var width = this.width();\n var height = this.height();\n return {\n x1: 0,\n y1: 0,\n x2: width,\n y2: height,\n w: width,\n h: height\n };\n },\n multiClickDebounceTime: function multiClickDebounceTime(_int) {\n if (_int) this._private.multiClickDebounceTime = _int;else return this._private.multiClickDebounceTime;\n return this; // chaining\n }\n};\n\n// aliases\ncorefn$1.centre = corefn$1.center;\n\n// backwards compatibility\ncorefn$1.autolockNodes = corefn$1.autolock;\ncorefn$1.autoungrabifyNodes = corefn$1.autoungrabify;\n\nvar fn = {\n data: define.data({\n field: 'data',\n bindingEvent: 'data',\n allowBinding: true,\n allowSetting: true,\n settingEvent: 'data',\n settingTriggersEvent: true,\n triggerFnName: 'trigger',\n allowGetting: true,\n updateStyle: true\n }),\n removeData: define.removeData({\n field: 'data',\n event: 'data',\n triggerFnName: 'trigger',\n triggerEvent: true,\n updateStyle: true\n }),\n scratch: define.data({\n field: 'scratch',\n bindingEvent: 'scratch',\n allowBinding: true,\n allowSetting: true,\n settingEvent: 'scratch',\n settingTriggersEvent: true,\n triggerFnName: 'trigger',\n allowGetting: true,\n updateStyle: true\n }),\n removeScratch: define.removeData({\n field: 'scratch',\n event: 'scratch',\n triggerFnName: 'trigger',\n triggerEvent: true,\n updateStyle: true\n })\n};\n\n// aliases\nfn.attr = fn.data;\nfn.removeAttr = fn.removeData;\n\nvar Core = function Core(opts) {\n var cy = this;\n opts = extend({}, opts);\n var container = opts.container;\n\n // allow for passing a wrapped jquery object\n // e.g. cytoscape({ container: $('#cy') })\n if (container && !htmlElement(container) && htmlElement(container[0])) {\n container = container[0];\n }\n var reg = container ? container._cyreg : null; // e.g. already registered some info (e.g. readies) via jquery\n reg = reg || {};\n if (reg && reg.cy) {\n reg.cy.destroy();\n reg = {}; // old instance => replace reg completely\n }\n var readies = reg.readies = reg.readies || [];\n if (container) {\n container._cyreg = reg;\n } // make sure container assoc'd reg points to this cy\n reg.cy = cy;\n var head = _window !== undefined && container !== undefined && !opts.headless;\n var options = opts;\n options.layout = extend({\n name: head ? 'grid' : 'null'\n }, options.layout);\n options.renderer = extend({\n name: head ? 'canvas' : 'null'\n }, options.renderer);\n var defVal = function defVal(def, val, altVal) {\n if (val !== undefined) {\n return val;\n } else if (altVal !== undefined) {\n return altVal;\n } else {\n return def;\n }\n };\n var _p = this._private = {\n container: container,\n // html dom ele container\n ready: false,\n // whether ready has been triggered\n options: options,\n // cached options\n elements: new Collection(this),\n // elements in the graph\n listeners: [],\n // list of listeners\n aniEles: new Collection(this),\n // elements being animated\n data: options.data || {},\n // data for the core\n scratch: {},\n // scratch object for core\n layout: null,\n renderer: null,\n destroyed: false,\n // whether destroy was called\n notificationsEnabled: true,\n // whether notifications are sent to the renderer\n minZoom: 1e-50,\n maxZoom: 1e50,\n zoomingEnabled: defVal(true, options.zoomingEnabled),\n userZoomingEnabled: defVal(true, options.userZoomingEnabled),\n panningEnabled: defVal(true, options.panningEnabled),\n userPanningEnabled: defVal(true, options.userPanningEnabled),\n boxSelectionEnabled: defVal(true, options.boxSelectionEnabled),\n autolock: defVal(false, options.autolock, options.autolockNodes),\n autoungrabify: defVal(false, options.autoungrabify, options.autoungrabifyNodes),\n autounselectify: defVal(false, options.autounselectify),\n styleEnabled: options.styleEnabled === undefined ? head : options.styleEnabled,\n zoom: number$1(options.zoom) ? options.zoom : 1,\n pan: {\n x: plainObject(options.pan) && number$1(options.pan.x) ? options.pan.x : 0,\n y: plainObject(options.pan) && number$1(options.pan.y) ? options.pan.y : 0\n },\n animation: {\n // object for currently-running animations\n current: [],\n queue: []\n },\n hasCompoundNodes: false,\n multiClickDebounceTime: defVal(250, options.multiClickDebounceTime)\n };\n this.createEmitter();\n\n // set selection type\n this.selectionType(options.selectionType);\n\n // init zoom bounds\n this.zoomRange({\n min: options.minZoom,\n max: options.maxZoom\n });\n var loadExtData = function loadExtData(extData, next) {\n var anyIsPromise = extData.some(promise);\n if (anyIsPromise) {\n return Promise$1.all(extData).then(next); // load all data asynchronously, then exec rest of init\n } else {\n next(extData); // exec synchronously for convenience\n }\n };\n\n // start with the default stylesheet so we have something before loading an external stylesheet\n if (_p.styleEnabled) {\n cy.setStyle([]);\n }\n\n // create the renderer\n var rendererOptions = extend({}, options, options.renderer); // allow rendering hints in top level options\n cy.initRenderer(rendererOptions);\n var setElesAndLayout = function setElesAndLayout(elements, onload, ondone) {\n cy.notifications(false);\n\n // remove old elements\n var oldEles = cy.mutableElements();\n if (oldEles.length > 0) {\n oldEles.remove();\n }\n if (elements != null) {\n if (plainObject(elements) || array(elements)) {\n cy.add(elements);\n }\n }\n cy.one('layoutready', function (e) {\n cy.notifications(true);\n cy.emit(e); // we missed this event by turning notifications off, so pass it on\n\n cy.one('load', onload);\n cy.emitAndNotify('load');\n }).one('layoutstop', function () {\n cy.one('done', ondone);\n cy.emit('done');\n });\n var layoutOpts = extend({}, cy._private.options.layout);\n layoutOpts.eles = cy.elements();\n cy.layout(layoutOpts).run();\n };\n loadExtData([options.style, options.elements], function (thens) {\n var initStyle = thens[0];\n var initEles = thens[1];\n\n // init style\n if (_p.styleEnabled) {\n cy.style().append(initStyle);\n }\n\n // initial load\n setElesAndLayout(initEles, function () {\n // onready\n cy.startAnimationLoop();\n _p.ready = true;\n\n // if a ready callback is specified as an option, the bind it\n if (fn$6(options.ready)) {\n cy.on('ready', options.ready);\n }\n\n // bind all the ready handlers registered before creating this instance\n for (var i = 0; i < readies.length; i++) {\n var fn = readies[i];\n cy.on('ready', fn);\n }\n if (reg) {\n reg.readies = [];\n } // clear b/c we've bound them all and don't want to keep it around in case a new core uses the same div etc\n\n cy.emit('ready');\n }, options.done);\n });\n};\nvar corefn = Core.prototype; // short alias\n\nextend(corefn, {\n instanceString: function instanceString() {\n return 'core';\n },\n isReady: function isReady() {\n return this._private.ready;\n },\n destroyed: function destroyed() {\n return this._private.destroyed;\n },\n ready: function ready(fn) {\n if (this.isReady()) {\n this.emitter().emit('ready', [], fn); // just calls fn as though triggered via ready event\n } else {\n this.on('ready', fn);\n }\n return this;\n },\n destroy: function destroy() {\n var cy = this;\n if (cy.destroyed()) return;\n cy.stopAnimationLoop();\n cy.destroyRenderer();\n this.emit('destroy');\n cy._private.destroyed = true;\n return cy;\n },\n hasElementWithId: function hasElementWithId(id) {\n return this._private.elements.hasElementWithId(id);\n },\n getElementById: function getElementById(id) {\n return this._private.elements.getElementById(id);\n },\n hasCompoundNodes: function hasCompoundNodes() {\n return this._private.hasCompoundNodes;\n },\n headless: function headless() {\n return this._private.renderer.isHeadless();\n },\n styleEnabled: function styleEnabled() {\n return this._private.styleEnabled;\n },\n addToPool: function addToPool(eles) {\n this._private.elements.merge(eles);\n return this; // chaining\n },\n removeFromPool: function removeFromPool(eles) {\n this._private.elements.unmerge(eles);\n return this;\n },\n container: function container() {\n return this._private.container || null;\n },\n window: function window() {\n var container = this._private.container;\n if (container == null) return _window;\n var ownerDocument = this._private.container.ownerDocument;\n if (ownerDocument === undefined || ownerDocument == null) {\n return _window;\n }\n return ownerDocument.defaultView || _window;\n },\n mount: function mount(container) {\n if (container == null) {\n return;\n }\n var cy = this;\n var _p = cy._private;\n var options = _p.options;\n if (!htmlElement(container) && htmlElement(container[0])) {\n container = container[0];\n }\n cy.stopAnimationLoop();\n cy.destroyRenderer();\n _p.container = container;\n _p.styleEnabled = true;\n cy.invalidateSize();\n cy.initRenderer(extend({}, options, options.renderer, {\n // allow custom renderer name to be re-used, otherwise use canvas\n name: options.renderer.name === 'null' ? 'canvas' : options.renderer.name\n }));\n cy.startAnimationLoop();\n cy.style(options.style);\n cy.emit('mount');\n return cy;\n },\n unmount: function unmount() {\n var cy = this;\n cy.stopAnimationLoop();\n cy.destroyRenderer();\n cy.initRenderer({\n name: 'null'\n });\n cy.emit('unmount');\n return cy;\n },\n options: function options() {\n return copy(this._private.options);\n },\n json: function json(obj) {\n var cy = this;\n var _p = cy._private;\n var eles = cy.mutableElements();\n var getFreshRef = function getFreshRef(ele) {\n return cy.getElementById(ele.id());\n };\n if (plainObject(obj)) {\n // set\n\n cy.startBatch();\n if (obj.elements) {\n var idInJson = {};\n var updateEles = function updateEles(jsons, gr) {\n var toAdd = [];\n var toMod = [];\n for (var i = 0; i < jsons.length; i++) {\n var json = jsons[i];\n if (!json.data.id) {\n warn('cy.json() cannot handle elements without an ID attribute');\n continue;\n }\n var id = '' + json.data.id; // id must be string\n var ele = cy.getElementById(id);\n idInJson[id] = true;\n if (ele.length !== 0) {\n // existing element should be updated\n toMod.push({\n ele: ele,\n json: json\n });\n } else {\n // otherwise should be added\n if (gr) {\n json.group = gr;\n toAdd.push(json);\n } else {\n toAdd.push(json);\n }\n }\n }\n cy.add(toAdd);\n for (var _i = 0; _i < toMod.length; _i++) {\n var _toMod$_i = toMod[_i],\n _ele = _toMod$_i.ele,\n _json = _toMod$_i.json;\n _ele.json(_json);\n }\n };\n if (array(obj.elements)) {\n // elements: []\n updateEles(obj.elements);\n } else {\n // elements: { nodes: [], edges: [] }\n var grs = ['nodes', 'edges'];\n for (var i = 0; i < grs.length; i++) {\n var gr = grs[i];\n var elements = obj.elements[gr];\n if (array(elements)) {\n updateEles(elements, gr);\n }\n }\n }\n var parentsToRemove = cy.collection();\n eles.filter(function (ele) {\n return !idInJson[ele.id()];\n }).forEach(function (ele) {\n if (ele.isParent()) {\n parentsToRemove.merge(ele);\n } else {\n ele.remove();\n }\n });\n\n // so that children are not removed w/parent\n parentsToRemove.forEach(function (ele) {\n return ele.children().move({\n parent: null\n });\n });\n\n // intermediate parents may be moved by prior line, so make sure we remove by fresh refs\n parentsToRemove.forEach(function (ele) {\n return getFreshRef(ele).remove();\n });\n }\n if (obj.style) {\n cy.style(obj.style);\n }\n if (obj.zoom != null && obj.zoom !== _p.zoom) {\n cy.zoom(obj.zoom);\n }\n if (obj.pan) {\n if (obj.pan.x !== _p.pan.x || obj.pan.y !== _p.pan.y) {\n cy.pan(obj.pan);\n }\n }\n if (obj.data) {\n cy.data(obj.data);\n }\n var fields = ['minZoom', 'maxZoom', 'zoomingEnabled', 'userZoomingEnabled', 'panningEnabled', 'userPanningEnabled', 'boxSelectionEnabled', 'autolock', 'autoungrabify', 'autounselectify', 'multiClickDebounceTime'];\n for (var _i2 = 0; _i2 < fields.length; _i2++) {\n var f = fields[_i2];\n if (obj[f] != null) {\n cy[f](obj[f]);\n }\n }\n cy.endBatch();\n return this; // chaining\n } else {\n // get\n var flat = !!obj;\n var json = {};\n if (flat) {\n json.elements = this.elements().map(function (ele) {\n return ele.json();\n });\n } else {\n json.elements = {};\n eles.forEach(function (ele) {\n var group = ele.group();\n if (!json.elements[group]) {\n json.elements[group] = [];\n }\n json.elements[group].push(ele.json());\n });\n }\n if (this._private.styleEnabled) {\n json.style = cy.style().json();\n }\n json.data = copy(cy.data());\n var options = _p.options;\n json.zoomingEnabled = _p.zoomingEnabled;\n json.userZoomingEnabled = _p.userZoomingEnabled;\n json.zoom = _p.zoom;\n json.minZoom = _p.minZoom;\n json.maxZoom = _p.maxZoom;\n json.panningEnabled = _p.panningEnabled;\n json.userPanningEnabled = _p.userPanningEnabled;\n json.pan = copy(_p.pan);\n json.boxSelectionEnabled = _p.boxSelectionEnabled;\n json.renderer = copy(options.renderer);\n json.hideEdgesOnViewport = options.hideEdgesOnViewport;\n json.textureOnViewport = options.textureOnViewport;\n json.wheelSensitivity = options.wheelSensitivity;\n json.motionBlur = options.motionBlur;\n json.multiClickDebounceTime = options.multiClickDebounceTime;\n return json;\n }\n }\n});\ncorefn.$id = corefn.getElementById;\n[corefn$9, corefn$8, elesfn, corefn$7, corefn$6, corefn$5, corefn$4, corefn$3, corefn$2, corefn$1, fn].forEach(function (props) {\n extend(corefn, props);\n});\n\n/* eslint-disable no-unused-vars */\nvar defaults$7 = {\n fit: true,\n // whether to fit the viewport to the graph\n directed: false,\n // whether the tree is directed downwards (or edges can point in any direction if false)\n direction: 'downward',\n // determines the direction in which the tree structure is drawn. The possible values are 'downward', 'upward', 'rightward', or 'leftward'.\n padding: 30,\n // padding on fit\n circle: false,\n // put depths in concentric circles if true, put depths top down if false\n grid: false,\n // whether to create an even grid into which the DAG is placed (circle:false only)\n spacingFactor: 1.75,\n // positive spacing factor, larger => more space between nodes (N.B. n/a if causes overlap)\n boundingBox: undefined,\n // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }\n avoidOverlap: true,\n // prevents node overlap, may overflow boundingBox if not enough space\n nodeDimensionsIncludeLabels: false,\n // Excludes the label when calculating node bounding boxes for the layout algorithm\n roots: undefined,\n // the roots of the trees\n depthSort: undefined,\n // a sorting function to order nodes at equal depth. e.g. function(a, b){ return a.data('weight') - b.data('weight') }\n animate: false,\n // whether to transition the node positions\n animationDuration: 500,\n // duration of animation in ms if enabled\n animationEasing: undefined,\n // easing of animation if enabled,\n animateFilter: function animateFilter(node, i) {\n return true;\n },\n // a function that determines whether the node should be animated. All nodes animated by default on animate enabled. Non-animated nodes are positioned immediately when the layout starts\n ready: undefined,\n // callback on layoutready\n stop: undefined,\n // callback on layoutstop\n transform: function transform(node, position) {\n return position;\n } // transform a given node position. Useful for changing flow direction in discrete layouts\n};\nvar deprecatedOptionDefaults = {\n maximal: false,\n // whether to shift nodes down their natural BFS depths in order to avoid upwards edges (DAGS only); setting acyclic to true sets maximal to true also\n acyclic: false // whether the tree is acyclic and thus a node could be shifted (due to the maximal option) multiple times without causing an infinite loop; setting to true sets maximal to true also; if you are uncertain whether a tree is acyclic, set to false to avoid potential infinite loops\n};\n\n/* eslint-enable */\n\nvar getInfo = function getInfo(ele) {\n return ele.scratch('breadthfirst');\n};\nvar setInfo = function setInfo(ele, obj) {\n return ele.scratch('breadthfirst', obj);\n};\nfunction BreadthFirstLayout(options) {\n this.options = extend({}, defaults$7, deprecatedOptionDefaults, options);\n}\nBreadthFirstLayout.prototype.run = function () {\n var options = this.options;\n var cy = options.cy;\n var eles = options.eles;\n var nodes = eles.nodes().filter(function (n) {\n return n.isChildless();\n });\n var graph = eles;\n var directed = options.directed;\n var maximal = options.acyclic || options.maximal || options.maximalAdjustments > 0; // maximalAdjustments for compat. w/ old code; also, setting acyclic to true sets maximal to true\n\n var hasBoundingBox = !!options.boundingBox;\n var bb = makeBoundingBox(hasBoundingBox ? options.boundingBox : structuredClone(cy.extent()));\n var roots;\n if (elementOrCollection(options.roots)) {\n roots = options.roots;\n } else if (array(options.roots)) {\n var rootsArray = [];\n for (var i = 0; i < options.roots.length; i++) {\n var id = options.roots[i];\n var ele = cy.getElementById(id);\n rootsArray.push(ele);\n }\n roots = cy.collection(rootsArray);\n } else if (string(options.roots)) {\n roots = cy.$(options.roots);\n } else {\n if (directed) {\n roots = nodes.roots();\n } else {\n var components = eles.components();\n roots = cy.collection();\n var _loop = function _loop() {\n var comp = components[_i];\n var maxDegree = comp.maxDegree(false);\n var compRoots = comp.filter(function (ele) {\n return ele.degree(false) === maxDegree;\n });\n roots = roots.add(compRoots);\n };\n for (var _i = 0; _i < components.length; _i++) {\n _loop();\n }\n }\n }\n var depths = [];\n var foundByBfs = {};\n var addToDepth = function addToDepth(ele, d) {\n if (depths[d] == null) {\n depths[d] = [];\n }\n var i = depths[d].length;\n depths[d].push(ele);\n setInfo(ele, {\n index: i,\n depth: d\n });\n };\n var changeDepth = function changeDepth(ele, newDepth) {\n var _getInfo = getInfo(ele),\n depth = _getInfo.depth,\n index = _getInfo.index;\n depths[depth][index] = null;\n\n // add only childless nodes\n if (ele.isChildless()) addToDepth(ele, newDepth);\n };\n\n // find the depths of the nodes\n graph.bfs({\n roots: roots,\n directed: options.directed,\n visit: function visit(node, edge, pNode, i, depth) {\n var ele = node[0];\n var id = ele.id();\n\n // add only childless nodes\n if (ele.isChildless()) addToDepth(ele, depth);\n foundByBfs[id] = true;\n }\n });\n\n // check for nodes not found by bfs\n var orphanNodes = [];\n for (var _i2 = 0; _i2 < nodes.length; _i2++) {\n var _ele = nodes[_i2];\n if (foundByBfs[_ele.id()]) {\n continue;\n } else {\n orphanNodes.push(_ele);\n }\n }\n\n // assign the nodes a depth and index\n var assignDepthsAt = function assignDepthsAt(i) {\n var eles = depths[i];\n for (var j = 0; j < eles.length; j++) {\n var _ele2 = eles[j];\n if (_ele2 == null) {\n eles.splice(j, 1);\n j--;\n continue;\n }\n setInfo(_ele2, {\n depth: i,\n index: j\n });\n }\n };\n var adjustMaximally = function adjustMaximally(ele, shifted) {\n var eInfo = getInfo(ele);\n var incomers = ele.incomers().filter(function (el) {\n return el.isNode() && eles.has(el);\n });\n var maxDepth = -1;\n var id = ele.id();\n for (var k = 0; k < incomers.length; k++) {\n var incmr = incomers[k];\n var iInfo = getInfo(incmr);\n maxDepth = Math.max(maxDepth, iInfo.depth);\n }\n if (eInfo.depth <= maxDepth) {\n if (!options.acyclic && shifted[id]) {\n return null;\n }\n var newDepth = maxDepth + 1;\n changeDepth(ele, newDepth);\n shifted[id] = newDepth;\n return true;\n }\n return false;\n };\n\n // for the directed case, try to make the edges all go down (i.e. depth i => depth i + 1)\n if (directed && maximal) {\n var Q = [];\n var shifted = {};\n var enqueue = function enqueue(n) {\n return Q.push(n);\n };\n var dequeue = function dequeue() {\n return Q.shift();\n };\n nodes.forEach(function (n) {\n return Q.push(n);\n });\n while (Q.length > 0) {\n var _ele3 = dequeue();\n var didShift = adjustMaximally(_ele3, shifted);\n if (didShift) {\n _ele3.outgoers().filter(function (el) {\n return el.isNode() && eles.has(el);\n }).forEach(enqueue);\n } else if (didShift === null) {\n warn('Detected double maximal shift for node `' + _ele3.id() + '`. Bailing maximal adjustment due to cycle. Use `options.maximal: true` only on DAGs.');\n break; // exit on failure\n }\n }\n }\n\n // find min distance we need to leave between nodes\n var minDistance = 0;\n if (options.avoidOverlap) {\n for (var _i3 = 0; _i3 < nodes.length; _i3++) {\n var n = nodes[_i3];\n var nbb = n.layoutDimensions(options);\n var w = nbb.w;\n var h = nbb.h;\n minDistance = Math.max(minDistance, w, h);\n }\n }\n\n // get the weighted percent for an element based on its connectivity to other levels\n var cachedWeightedPercent = {};\n var getWeightedPercent = function getWeightedPercent(ele) {\n if (cachedWeightedPercent[ele.id()]) {\n return cachedWeightedPercent[ele.id()];\n }\n var eleDepth = getInfo(ele).depth;\n var neighbors = ele.neighborhood();\n var percent = 0;\n var samples = 0;\n for (var _i4 = 0; _i4 < neighbors.length; _i4++) {\n var neighbor = neighbors[_i4];\n if (neighbor.isEdge() || neighbor.isParent() || !nodes.has(neighbor)) {\n continue;\n }\n var bf = getInfo(neighbor);\n if (bf == null) {\n continue;\n }\n var index = bf.index;\n var depth = bf.depth;\n\n // unassigned neighbours shouldn't affect the ordering\n if (index == null || depth == null) {\n continue;\n }\n var nDepth = depths[depth].length;\n if (depth < eleDepth) {\n // only get influenced by elements above\n percent += index / nDepth;\n samples++;\n }\n }\n samples = Math.max(1, samples);\n percent = percent / samples;\n if (samples === 0) {\n // put lone nodes at the start\n percent = 0;\n }\n cachedWeightedPercent[ele.id()] = percent;\n return percent;\n };\n\n // rearrange the indices in each depth level based on connectivity\n var sortFn = function sortFn(a, b) {\n var apct = getWeightedPercent(a);\n var bpct = getWeightedPercent(b);\n var diff = apct - bpct;\n if (diff === 0) {\n return ascending(a.id(), b.id()); // make sure sort doesn't have don't-care comparisons\n } else {\n return diff;\n }\n };\n if (options.depthSort !== undefined) {\n sortFn = options.depthSort;\n }\n var depthsLen = depths.length;\n\n // sort each level to make connected nodes closer\n for (var _i5 = 0; _i5 < depthsLen; _i5++) {\n depths[_i5].sort(sortFn);\n assignDepthsAt(_i5);\n }\n\n // assign orphan nodes to a new top-level depth\n var orphanDepth = [];\n for (var _i6 = 0; _i6 < orphanNodes.length; _i6++) {\n orphanDepth.push(orphanNodes[_i6]);\n }\n var assignDepths = function assignDepths() {\n for (var _i7 = 0; _i7 < depthsLen; _i7++) {\n assignDepthsAt(_i7);\n }\n };\n\n // add a new top-level depth only when there are orphan nodes\n if (orphanDepth.length) {\n depths.unshift(orphanDepth);\n depthsLen = depths.length;\n assignDepths();\n }\n var biggestDepthSize = 0;\n for (var _i8 = 0; _i8 < depthsLen; _i8++) {\n biggestDepthSize = Math.max(depths[_i8].length, biggestDepthSize);\n }\n var center = {\n x: bb.x1 + bb.w / 2,\n y: bb.y1 + bb.h / 2\n };\n\n // average node size\n var aveNodeSize = nodes.reduce(function (acc, node) {\n return function (box) {\n return {\n w: acc.w === -1 ? box.w : (acc.w + box.w) / 2,\n h: acc.h === -1 ? box.h : (acc.h + box.h) / 2\n };\n }(node.boundingBox({\n includeLabels: options.nodeDimensionsIncludeLabels\n }));\n }, {\n w: -1,\n h: -1\n });\n var distanceY = Math.max(\n // only one depth\n depthsLen === 1 ? 0 :\n // inside a bounding box, no need for top & bottom padding\n hasBoundingBox ? (bb.h - options.padding * 2 - aveNodeSize.h) / (depthsLen - 1) : (bb.h - options.padding * 2 - aveNodeSize.h) / (depthsLen + 1), minDistance);\n var maxDepthSize = depths.reduce(function (max, eles) {\n return Math.max(max, eles.length);\n }, 0);\n var getPositionTopBottom = function getPositionTopBottom(ele) {\n var _getInfo2 = getInfo(ele),\n depth = _getInfo2.depth,\n index = _getInfo2.index;\n if (options.circle) {\n var radiusStepSize = Math.min(bb.w / 2 / depthsLen, bb.h / 2 / depthsLen);\n radiusStepSize = Math.max(radiusStepSize, minDistance);\n var radius = radiusStepSize * depth + radiusStepSize - (depthsLen > 0 && depths[0].length <= 3 ? radiusStepSize / 2 : 0);\n var theta = 2 * Math.PI / depths[depth].length * index;\n if (depth === 0 && depths[0].length === 1) {\n radius = 1;\n }\n return {\n x: center.x + radius * Math.cos(theta),\n y: center.y + radius * Math.sin(theta)\n };\n } else {\n var depthSize = depths[depth].length;\n var distanceX = Math.max(\n // only one depth\n depthSize === 1 ? 0 :\n // inside a bounding box, no need for left & right padding\n hasBoundingBox ? (bb.w - options.padding * 2 - aveNodeSize.w) / ((options.grid ? maxDepthSize : depthSize) - 1) : (bb.w - options.padding * 2 - aveNodeSize.w) / ((options.grid ? maxDepthSize : depthSize) + 1), minDistance);\n var epos = {\n x: center.x + (index + 1 - (depthSize + 1) / 2) * distanceX,\n y: center.y + (depth + 1 - (depthsLen + 1) / 2) * distanceY\n };\n return epos;\n }\n };\n var rotateDegrees = {\n 'downward': 0,\n 'leftward': 90,\n 'upward': 180,\n 'rightward': -90\n };\n if (Object.keys(rotateDegrees).indexOf(options.direction) === -1) {\n error(\"Invalid direction '\".concat(options.direction, \"' specified for breadthfirst layout. Valid values are: \").concat(Object.keys(rotateDegrees).join(', ')));\n }\n var getPosition = function getPosition(ele) {\n return rotatePosAndSkewByBox(getPositionTopBottom(ele), bb, rotateDegrees[options.direction]);\n };\n eles.nodes().layoutPositions(this, options, getPosition);\n return this; // chaining\n};\n\nvar defaults$6 = {\n fit: true,\n // whether to fit the viewport to the graph\n padding: 30,\n // the padding on fit\n boundingBox: undefined,\n // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }\n avoidOverlap: true,\n // prevents node overlap, may overflow boundingBox and radius if not enough space\n nodeDimensionsIncludeLabels: false,\n // Excludes the label when calculating node bounding boxes for the layout algorithm\n spacingFactor: undefined,\n // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up\n radius: undefined,\n // the radius of the circle\n startAngle: 3 / 2 * Math.PI,\n // where nodes start in radians\n sweep: undefined,\n // how many radians should be between the first and last node (defaults to full circle)\n clockwise: true,\n // whether the layout should go clockwise (true) or counterclockwise/anticlockwise (false)\n sort: undefined,\n // a sorting function to order the nodes; e.g. function(a, b){ return a.data('weight') - b.data('weight') }\n animate: false,\n // whether to transition the node positions\n animationDuration: 500,\n // duration of animation in ms if enabled\n animationEasing: undefined,\n // easing of animation if enabled\n animateFilter: function animateFilter(node, i) {\n return true;\n },\n // a function that determines whether the node should be animated. All nodes animated by default on animate enabled. Non-animated nodes are positioned immediately when the layout starts\n ready: undefined,\n // callback on layoutready\n stop: undefined,\n // callback on layoutstop\n transform: function transform(node, position) {\n return position;\n } // transform a given node position. Useful for changing flow direction in discrete layouts \n};\nfunction CircleLayout(options) {\n this.options = extend({}, defaults$6, options);\n}\nCircleLayout.prototype.run = function () {\n var params = this.options;\n var options = params;\n var cy = params.cy;\n var eles = options.eles;\n var clockwise = options.counterclockwise !== undefined ? !options.counterclockwise : options.clockwise;\n var nodes = eles.nodes().not(':parent');\n if (options.sort) {\n nodes = nodes.sort(options.sort);\n }\n var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {\n x1: 0,\n y1: 0,\n w: cy.width(),\n h: cy.height()\n });\n var center = {\n x: bb.x1 + bb.w / 2,\n y: bb.y1 + bb.h / 2\n };\n var sweep = options.sweep === undefined ? 2 * Math.PI - 2 * Math.PI / nodes.length : options.sweep;\n var dTheta = sweep / Math.max(1, nodes.length - 1);\n var r;\n var minDistance = 0;\n for (var i = 0; i < nodes.length; i++) {\n var n = nodes[i];\n var nbb = n.layoutDimensions(options);\n var w = nbb.w;\n var h = nbb.h;\n minDistance = Math.max(minDistance, w, h);\n }\n if (number$1(options.radius)) {\n r = options.radius;\n } else if (nodes.length <= 1) {\n r = 0;\n } else {\n r = Math.min(bb.h, bb.w) / 2 - minDistance;\n }\n\n // calculate the radius\n if (nodes.length > 1 && options.avoidOverlap) {\n // but only if more than one node (can't overlap)\n minDistance *= 1.75; // just to have some nice spacing\n\n var dcos = Math.cos(dTheta) - Math.cos(0);\n var dsin = Math.sin(dTheta) - Math.sin(0);\n var rMin = Math.sqrt(minDistance * minDistance / (dcos * dcos + dsin * dsin)); // s.t. no nodes overlapping\n r = Math.max(rMin, r);\n }\n var getPos = function getPos(ele, i) {\n var theta = options.startAngle + i * dTheta * (clockwise ? 1 : -1);\n var rx = r * Math.cos(theta);\n var ry = r * Math.sin(theta);\n var pos = {\n x: center.x + rx,\n y: center.y + ry\n };\n return pos;\n };\n eles.nodes().layoutPositions(this, options, getPos);\n return this; // chaining\n};\n\nvar defaults$5 = {\n fit: true,\n // whether to fit the viewport to the graph\n padding: 30,\n // the padding on fit\n startAngle: 3 / 2 * Math.PI,\n // where nodes start in radians\n sweep: undefined,\n // how many radians should be between the first and last node (defaults to full circle)\n clockwise: true,\n // whether the layout should go clockwise (true) or counterclockwise/anticlockwise (false)\n equidistant: false,\n // whether levels have an equal radial distance betwen them, may cause bounding box overflow\n minNodeSpacing: 10,\n // min spacing between outside of nodes (used for radius adjustment)\n boundingBox: undefined,\n // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }\n avoidOverlap: true,\n // prevents node overlap, may overflow boundingBox if not enough space\n nodeDimensionsIncludeLabels: false,\n // Excludes the label when calculating node bounding boxes for the layout algorithm\n height: undefined,\n // height of layout area (overrides container height)\n width: undefined,\n // width of layout area (overrides container width)\n spacingFactor: undefined,\n // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up\n concentric: function concentric(node) {\n // returns numeric value for each node, placing higher nodes in levels towards the centre\n return node.degree();\n },\n levelWidth: function levelWidth(nodes) {\n // the variation of concentric values in each level\n return nodes.maxDegree() / 4;\n },\n animate: false,\n // whether to transition the node positions\n animationDuration: 500,\n // duration of animation in ms if enabled\n animationEasing: undefined,\n // easing of animation if enabled\n animateFilter: function animateFilter(node, i) {\n return true;\n },\n // a function that determines whether the node should be animated. All nodes animated by default on animate enabled. Non-animated nodes are positioned immediately when the layout starts\n ready: undefined,\n // callback on layoutready\n stop: undefined,\n // callback on layoutstop\n transform: function transform(node, position) {\n return position;\n } // transform a given node position. Useful for changing flow direction in discrete layouts\n};\nfunction ConcentricLayout(options) {\n this.options = extend({}, defaults$5, options);\n}\nConcentricLayout.prototype.run = function () {\n var params = this.options;\n var options = params;\n var clockwise = options.counterclockwise !== undefined ? !options.counterclockwise : options.clockwise;\n var cy = params.cy;\n var eles = options.eles;\n var nodes = eles.nodes().not(':parent');\n var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {\n x1: 0,\n y1: 0,\n w: cy.width(),\n h: cy.height()\n });\n var center = {\n x: bb.x1 + bb.w / 2,\n y: bb.y1 + bb.h / 2\n };\n var nodeValues = []; // { node, value }\n var maxNodeSize = 0;\n for (var i = 0; i < nodes.length; i++) {\n var node = nodes[i];\n var value = undefined;\n\n // calculate the node value\n value = options.concentric(node);\n nodeValues.push({\n value: value,\n node: node\n });\n\n // for style mapping\n node._private.scratch.concentric = value;\n }\n\n // in case we used the `concentric` in style\n nodes.updateStyle();\n\n // calculate max size now based on potentially updated mappers\n for (var _i = 0; _i < nodes.length; _i++) {\n var _node = nodes[_i];\n var nbb = _node.layoutDimensions(options);\n maxNodeSize = Math.max(maxNodeSize, nbb.w, nbb.h);\n }\n\n // sort node values in descreasing order\n nodeValues.sort(function (a, b) {\n return b.value - a.value;\n });\n var levelWidth = options.levelWidth(nodes);\n\n // put the values into levels\n var levels = [[]];\n var currentLevel = levels[0];\n for (var _i2 = 0; _i2 < nodeValues.length; _i2++) {\n var val = nodeValues[_i2];\n if (currentLevel.length > 0) {\n var diff = Math.abs(currentLevel[0].value - val.value);\n if (diff >= levelWidth) {\n currentLevel = [];\n levels.push(currentLevel);\n }\n }\n currentLevel.push(val);\n }\n\n // create positions from levels\n\n var minDist = maxNodeSize + options.minNodeSpacing; // min dist between nodes\n\n if (!options.avoidOverlap) {\n // then strictly constrain to bb\n var firstLvlHasMulti = levels.length > 0 && levels[0].length > 1;\n var maxR = Math.min(bb.w, bb.h) / 2 - minDist;\n var rStep = maxR / (levels.length + firstLvlHasMulti ? 1 : 0);\n minDist = Math.min(minDist, rStep);\n }\n\n // find the metrics for each level\n var r = 0;\n for (var _i3 = 0; _i3 < levels.length; _i3++) {\n var level = levels[_i3];\n var sweep = options.sweep === undefined ? 2 * Math.PI - 2 * Math.PI / level.length : options.sweep;\n var dTheta = level.dTheta = sweep / Math.max(1, level.length - 1);\n\n // calculate the radius\n if (level.length > 1 && options.avoidOverlap) {\n // but only if more than one node (can't overlap)\n var dcos = Math.cos(dTheta) - Math.cos(0);\n var dsin = Math.sin(dTheta) - Math.sin(0);\n var rMin = Math.sqrt(minDist * minDist / (dcos * dcos + dsin * dsin)); // s.t. no nodes overlapping\n\n r = Math.max(rMin, r);\n }\n level.r = r;\n r += minDist;\n }\n if (options.equidistant) {\n var rDeltaMax = 0;\n var _r = 0;\n for (var _i4 = 0; _i4 < levels.length; _i4++) {\n var _level = levels[_i4];\n var rDelta = _level.r - _r;\n rDeltaMax = Math.max(rDeltaMax, rDelta);\n }\n _r = 0;\n for (var _i5 = 0; _i5 < levels.length; _i5++) {\n var _level2 = levels[_i5];\n if (_i5 === 0) {\n _r = _level2.r;\n }\n _level2.r = _r;\n _r += rDeltaMax;\n }\n }\n\n // calculate the node positions\n var pos = {}; // id => position\n for (var _i6 = 0; _i6 < levels.length; _i6++) {\n var _level3 = levels[_i6];\n var _dTheta = _level3.dTheta;\n var _r2 = _level3.r;\n for (var j = 0; j < _level3.length; j++) {\n var _val = _level3[j];\n var theta = options.startAngle + (clockwise ? 1 : -1) * _dTheta * j;\n var p = {\n x: center.x + _r2 * Math.cos(theta),\n y: center.y + _r2 * Math.sin(theta)\n };\n pos[_val.node.id()] = p;\n }\n }\n\n // position the nodes\n eles.nodes().layoutPositions(this, options, function (ele) {\n var id = ele.id();\n return pos[id];\n });\n return this; // chaining\n};\n\n/*\nThe CoSE layout was written by Gerardo Huck.\nhttps://www.linkedin.com/in/gerardohuck/\n\nBased on the following article:\nhttp://dl.acm.org/citation.cfm?id=1498047\n\nModifications tracked on Github.\n*/\n\nvar DEBUG;\n\n/**\n * @brief : default layout options\n */\nvar defaults$4 = {\n // Called on `layoutready`\n ready: function ready() {},\n // Called on `layoutstop`\n stop: function stop() {},\n // Whether to animate while running the layout\n // true : Animate continuously as the layout is running\n // false : Just show the end result\n // 'end' : Animate with the end result, from the initial positions to the end positions\n animate: true,\n // Easing of the animation for animate:'end'\n animationEasing: undefined,\n // The duration of the animation for animate:'end'\n animationDuration: undefined,\n // A function that determines whether the node should be animated\n // All nodes animated by default on animate enabled\n // Non-animated nodes are positioned immediately when the layout starts\n animateFilter: function animateFilter(node, i) {\n return true;\n },\n // The layout animates only after this many milliseconds for animate:true\n // (prevents flashing on fast runs)\n animationThreshold: 250,\n // Number of iterations between consecutive screen positions update\n refresh: 20,\n // Whether to fit the network view after when done\n fit: true,\n // Padding on fit\n padding: 30,\n // Constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }\n boundingBox: undefined,\n // Excludes the label when calculating node bounding boxes for the layout algorithm\n nodeDimensionsIncludeLabels: false,\n // Randomize the initial positions of the nodes (true) or use existing positions (false)\n randomize: false,\n // Extra spacing between components in non-compound graphs\n componentSpacing: 40,\n // Node repulsion (non overlapping) multiplier\n nodeRepulsion: function nodeRepulsion(node) {\n return 2048;\n },\n // Node repulsion (overlapping) multiplier\n nodeOverlap: 4,\n // Ideal edge (non nested) length\n idealEdgeLength: function idealEdgeLength(edge) {\n return 32;\n },\n // Divisor to compute edge forces\n edgeElasticity: function edgeElasticity(edge) {\n return 32;\n },\n // Nesting factor (multiplier) to compute ideal edge length for nested edges\n nestingFactor: 1.2,\n // Gravity force (constant)\n gravity: 1,\n // Maximum number of iterations to perform\n numIter: 1000,\n // Initial temperature (maximum node displacement)\n initialTemp: 1000,\n // Cooling factor (how the temperature is reduced between consecutive iterations\n coolingFactor: 0.99,\n // Lower temperature threshold (below this point the layout will end)\n minTemp: 1.0\n};\n\n/**\n * @brief : constructor\n * @arg options : object containing layout options\n */\nfunction CoseLayout(options) {\n this.options = extend({}, defaults$4, options);\n this.options.layout = this;\n\n // Exclude any edge that has a source or target node that is not in the set of passed-in nodes\n var nodes = this.options.eles.nodes();\n var edges = this.options.eles.edges();\n var notEdges = edges.filter(function (e) {\n var sourceId = e.source().data('id');\n var targetId = e.target().data('id');\n var hasSource = nodes.some(function (n) {\n return n.data('id') === sourceId;\n });\n var hasTarget = nodes.some(function (n) {\n return n.data('id') === targetId;\n });\n return !hasSource || !hasTarget;\n });\n this.options.eles = this.options.eles.not(notEdges);\n}\n\n/**\n * @brief : runs the layout\n */\nCoseLayout.prototype.run = function () {\n var options = this.options;\n var cy = options.cy;\n var layout = this;\n layout.stopped = false;\n if (options.animate === true || options.animate === false) {\n layout.emit({\n type: 'layoutstart',\n layout: layout\n });\n }\n\n // Set DEBUG - Global variable\n if (true === options.debug) {\n DEBUG = true;\n } else {\n DEBUG = false;\n }\n\n // Initialize layout info\n var layoutInfo = createLayoutInfo(cy, layout, options);\n\n // Show LayoutInfo contents if debugging\n if (DEBUG) {\n printLayoutInfo(layoutInfo);\n }\n\n // If required, randomize node positions\n if (options.randomize) {\n randomizePositions(layoutInfo);\n }\n var startTime = performanceNow();\n var refresh = function refresh() {\n refreshPositions(layoutInfo, cy, options);\n\n // Fit the graph if necessary\n if (true === options.fit) {\n cy.fit(options.padding);\n }\n };\n var mainLoop = function mainLoop(i) {\n if (layout.stopped || i >= options.numIter) {\n // logDebug(\"Layout manually stopped. Stopping computation in step \" + i);\n return false;\n }\n\n // Do one step in the phisical simulation\n step(layoutInfo, options);\n\n // Update temperature\n layoutInfo.temperature = layoutInfo.temperature * options.coolingFactor;\n // logDebug(\"New temperature: \" + layoutInfo.temperature);\n\n if (layoutInfo.temperature < options.minTemp) {\n // logDebug(\"Temperature drop below minimum threshold. Stopping computation in step \" + i);\n return false;\n }\n return true;\n };\n var done = function done() {\n if (options.animate === true || options.animate === false) {\n refresh();\n\n // Layout has finished\n layout.one('layoutstop', options.stop);\n layout.emit({\n type: 'layoutstop',\n layout: layout\n });\n } else {\n var nodes = options.eles.nodes();\n var getScaledPos = getScaleInBoundsFn(layoutInfo, options, nodes);\n nodes.layoutPositions(layout, options, getScaledPos);\n }\n };\n var i = 0;\n var loopRet = true;\n if (options.animate === true) {\n var _frame = function frame() {\n var f = 0;\n while (loopRet && f < options.refresh) {\n loopRet = mainLoop(i);\n i++;\n f++;\n }\n if (!loopRet) {\n // it's done\n separateComponents(layoutInfo, options);\n done();\n } else {\n var now = performanceNow();\n if (now - startTime >= options.animationThreshold) {\n refresh();\n }\n requestAnimationFrame(_frame);\n }\n };\n _frame();\n } else {\n while (loopRet) {\n loopRet = mainLoop(i);\n i++;\n }\n separateComponents(layoutInfo, options);\n done();\n }\n return this; // chaining\n};\n\n/**\n * @brief : called on continuous layouts to stop them before they finish\n */\nCoseLayout.prototype.stop = function () {\n this.stopped = true;\n if (this.thread) {\n this.thread.stop();\n }\n this.emit('layoutstop');\n return this; // chaining\n};\nCoseLayout.prototype.destroy = function () {\n if (this.thread) {\n this.thread.stop();\n }\n return this; // chaining\n};\n\n/**\n * @brief : Creates an object which is contains all the data\n * used in the layout process\n * @arg cy : cytoscape.js object\n * @return : layoutInfo object initialized\n */\nvar createLayoutInfo = function createLayoutInfo(cy, layout, options) {\n // Shortcut\n var edges = options.eles.edges();\n var nodes = options.eles.nodes();\n var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {\n x1: 0,\n y1: 0,\n w: cy.width(),\n h: cy.height()\n });\n var layoutInfo = {\n isCompound: cy.hasCompoundNodes(),\n layoutNodes: [],\n idToIndex: {},\n nodeSize: nodes.size(),\n graphSet: [],\n indexToGraph: [],\n layoutEdges: [],\n edgeSize: edges.size(),\n temperature: options.initialTemp,\n clientWidth: bb.w,\n clientHeight: bb.h,\n boundingBox: bb\n };\n var components = options.eles.components();\n var id2cmptId = {};\n for (var i = 0; i < components.length; i++) {\n var component = components[i];\n for (var j = 0; j < component.length; j++) {\n var node = component[j];\n id2cmptId[node.id()] = i;\n }\n }\n\n // Iterate over all nodes, creating layout nodes\n for (var i = 0; i < layoutInfo.nodeSize; i++) {\n var n = nodes[i];\n var nbb = n.layoutDimensions(options);\n var tempNode = {};\n tempNode.isLocked = n.locked();\n tempNode.id = n.data('id');\n tempNode.parentId = n.data('parent');\n tempNode.cmptId = id2cmptId[n.id()];\n tempNode.children = [];\n tempNode.positionX = n.position('x');\n tempNode.positionY = n.position('y');\n tempNode.offsetX = 0;\n tempNode.offsetY = 0;\n tempNode.height = nbb.w;\n tempNode.width = nbb.h;\n tempNode.maxX = tempNode.positionX + tempNode.width / 2;\n tempNode.minX = tempNode.positionX - tempNode.width / 2;\n tempNode.maxY = tempNode.positionY + tempNode.height / 2;\n tempNode.minY = tempNode.positionY - tempNode.height / 2;\n tempNode.padLeft = parseFloat(n.style('padding'));\n tempNode.padRight = parseFloat(n.style('padding'));\n tempNode.padTop = parseFloat(n.style('padding'));\n tempNode.padBottom = parseFloat(n.style('padding'));\n\n // forces\n tempNode.nodeRepulsion = fn$6(options.nodeRepulsion) ? options.nodeRepulsion(n) : options.nodeRepulsion;\n\n // Add new node\n layoutInfo.layoutNodes.push(tempNode);\n // Add entry to id-index map\n layoutInfo.idToIndex[tempNode.id] = i;\n }\n\n // Inline implementation of a queue, used for traversing the graph in BFS order\n var queue = [];\n var start = 0; // Points to the start the queue\n var end = -1; // Points to the end of the queue\n\n var tempGraph = [];\n\n // Second pass to add child information and\n // initialize queue for hierarchical traversal\n for (var i = 0; i < layoutInfo.nodeSize; i++) {\n var n = layoutInfo.layoutNodes[i];\n var p_id = n.parentId;\n // Check if node n has a parent node\n if (null != p_id) {\n // Add node Id to parent's list of children\n layoutInfo.layoutNodes[layoutInfo.idToIndex[p_id]].children.push(n.id);\n } else {\n // If a node doesn't have a parent, then it's in the root graph\n queue[++end] = n.id;\n tempGraph.push(n.id);\n }\n }\n\n // Add root graph to graphSet\n layoutInfo.graphSet.push(tempGraph);\n\n // Traverse the graph, level by level,\n while (start <= end) {\n // Get the node to visit and remove it from queue\n var node_id = queue[start++];\n var node_ix = layoutInfo.idToIndex[node_id];\n var node = layoutInfo.layoutNodes[node_ix];\n var children = node.children;\n if (children.length > 0) {\n // Add children nodes as a new graph to graph set\n layoutInfo.graphSet.push(children);\n // Add children to que queue to be visited\n for (var i = 0; i < children.length; i++) {\n queue[++end] = children[i];\n }\n }\n }\n\n // Create indexToGraph map\n for (var i = 0; i < layoutInfo.graphSet.length; i++) {\n var graph = layoutInfo.graphSet[i];\n for (var j = 0; j < graph.length; j++) {\n var index = layoutInfo.idToIndex[graph[j]];\n layoutInfo.indexToGraph[index] = i;\n }\n }\n\n // Iterate over all edges, creating Layout Edges\n for (var i = 0; i < layoutInfo.edgeSize; i++) {\n var e = edges[i];\n var tempEdge = {};\n tempEdge.id = e.data('id');\n tempEdge.sourceId = e.data('source');\n tempEdge.targetId = e.data('target');\n\n // Compute ideal length\n var idealLength = fn$6(options.idealEdgeLength) ? options.idealEdgeLength(e) : options.idealEdgeLength;\n var elasticity = fn$6(options.edgeElasticity) ? options.edgeElasticity(e) : options.edgeElasticity;\n\n // Check if it's an inter graph edge\n var sourceIx = layoutInfo.idToIndex[tempEdge.sourceId];\n var targetIx = layoutInfo.idToIndex[tempEdge.targetId];\n var sourceGraph = layoutInfo.indexToGraph[sourceIx];\n var targetGraph = layoutInfo.indexToGraph[targetIx];\n if (sourceGraph != targetGraph) {\n // Find lowest common graph ancestor\n var lca = findLCA(tempEdge.sourceId, tempEdge.targetId, layoutInfo);\n\n // Compute sum of node depths, relative to lca graph\n var lcaGraph = layoutInfo.graphSet[lca];\n var depth = 0;\n\n // Source depth\n var tempNode = layoutInfo.layoutNodes[sourceIx];\n while (-1 === lcaGraph.indexOf(tempNode.id)) {\n tempNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[tempNode.parentId]];\n depth++;\n }\n\n // Target depth\n tempNode = layoutInfo.layoutNodes[targetIx];\n while (-1 === lcaGraph.indexOf(tempNode.id)) {\n tempNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[tempNode.parentId]];\n depth++;\n }\n\n // logDebug('LCA of nodes ' + tempEdge.sourceId + ' and ' + tempEdge.targetId +\n // \". Index: \" + lca + \" Contents: \" + lcaGraph.toString() +\n // \". Depth: \" + depth);\n\n // Update idealLength\n idealLength *= depth * options.nestingFactor;\n }\n tempEdge.idealLength = idealLength;\n tempEdge.elasticity = elasticity;\n layoutInfo.layoutEdges.push(tempEdge);\n }\n\n // Finally, return layoutInfo object\n return layoutInfo;\n};\n\n/**\n * @brief : This function finds the index of the lowest common\n * graph ancestor between 2 nodes in the subtree\n * (from the graph hierarchy induced tree) whose\n * root is graphIx\n *\n * @arg node1: node1's ID\n * @arg node2: node2's ID\n * @arg layoutInfo: layoutInfo object\n *\n */\nvar findLCA = function findLCA(node1, node2, layoutInfo) {\n // Find their common ancester, starting from the root graph\n var res = _findLCA_aux(node1, node2, 0, layoutInfo);\n if (2 > res.count) {\n // If aux function couldn't find the common ancester,\n // then it is the root graph\n return 0;\n } else {\n return res.graph;\n }\n};\n\n/**\n * @brief : Auxiliary function used for LCA computation\n *\n * @arg node1 : node1's ID\n * @arg node2 : node2's ID\n * @arg graphIx : subgraph index\n * @arg layoutInfo : layoutInfo object\n *\n * @return : object of the form {count: X, graph: Y}, where:\n * X is the number of ancestors (max: 2) found in\n * graphIx (and it's subgraphs),\n * Y is the graph index of the lowest graph containing\n * all X nodes\n */\nvar _findLCA_aux = function findLCA_aux(node1, node2, graphIx, layoutInfo) {\n var graph = layoutInfo.graphSet[graphIx];\n // If both nodes belongs to graphIx\n if (-1 < graph.indexOf(node1) && -1 < graph.indexOf(node2)) {\n return {\n count: 2,\n graph: graphIx\n };\n }\n\n // Make recursive calls for all subgraphs\n var c = 0;\n for (var i = 0; i < graph.length; i++) {\n var nodeId = graph[i];\n var nodeIx = layoutInfo.idToIndex[nodeId];\n var children = layoutInfo.layoutNodes[nodeIx].children;\n\n // If the node has no child, skip it\n if (0 === children.length) {\n continue;\n }\n var childGraphIx = layoutInfo.indexToGraph[layoutInfo.idToIndex[children[0]]];\n var result = _findLCA_aux(node1, node2, childGraphIx, layoutInfo);\n if (0 === result.count) {\n // Neither node1 nor node2 are present in this subgraph\n continue;\n } else if (1 === result.count) {\n // One of (node1, node2) is present in this subgraph\n c++;\n if (2 === c) {\n // We've already found both nodes, no need to keep searching\n break;\n }\n } else {\n // Both nodes are present in this subgraph\n return result;\n }\n }\n return {\n count: c,\n graph: graphIx\n };\n};\n\n/**\n * @brief: printsLayoutInfo into js console\n * Only used for debbuging\n */\nvar printLayoutInfo; \n\n/**\n * @brief : Randomizes the position of all nodes\n */\nvar randomizePositions = function randomizePositions(layoutInfo, cy) {\n var width = layoutInfo.clientWidth;\n var height = layoutInfo.clientHeight;\n for (var i = 0; i < layoutInfo.nodeSize; i++) {\n var n = layoutInfo.layoutNodes[i];\n\n // No need to randomize compound nodes or locked nodes\n if (0 === n.children.length && !n.isLocked) {\n n.positionX = Math.random() * width;\n n.positionY = Math.random() * height;\n }\n }\n};\nvar getScaleInBoundsFn = function getScaleInBoundsFn(layoutInfo, options, nodes) {\n var bb = layoutInfo.boundingBox;\n var coseBB = {\n x1: Infinity,\n x2: -Infinity,\n y1: Infinity,\n y2: -Infinity\n };\n if (options.boundingBox) {\n nodes.forEach(function (node) {\n var lnode = layoutInfo.layoutNodes[layoutInfo.idToIndex[node.data('id')]];\n coseBB.x1 = Math.min(coseBB.x1, lnode.positionX);\n coseBB.x2 = Math.max(coseBB.x2, lnode.positionX);\n coseBB.y1 = Math.min(coseBB.y1, lnode.positionY);\n coseBB.y2 = Math.max(coseBB.y2, lnode.positionY);\n });\n coseBB.w = coseBB.x2 - coseBB.x1;\n coseBB.h = coseBB.y2 - coseBB.y1;\n }\n return function (ele, i) {\n var lnode = layoutInfo.layoutNodes[layoutInfo.idToIndex[ele.data('id')]];\n if (options.boundingBox) {\n // then add extra bounding box constraint\n // Handle single node case where coseBB.w or coseBB.h is 0\n var pctX = coseBB.w === 0 ? 0.5 : (lnode.positionX - coseBB.x1) / coseBB.w;\n var pctY = coseBB.h === 0 ? 0.5 : (lnode.positionY - coseBB.y1) / coseBB.h;\n return {\n x: bb.x1 + pctX * bb.w,\n y: bb.y1 + pctY * bb.h\n };\n } else {\n return {\n x: lnode.positionX,\n y: lnode.positionY\n };\n }\n };\n};\n\n/**\n * @brief : Updates the positions of nodes in the network\n * @arg layoutInfo : LayoutInfo object\n * @arg cy : Cytoscape object\n * @arg options : Layout options\n */\nvar refreshPositions = function refreshPositions(layoutInfo, cy, options) {\n // var s = 'Refreshing positions';\n // logDebug(s);\n\n var layout = options.layout;\n var nodes = options.eles.nodes();\n var getScaledPos = getScaleInBoundsFn(layoutInfo, options, nodes);\n nodes.positions(getScaledPos);\n\n // Trigger layoutReady only on first call\n if (true !== layoutInfo.ready) {\n // s = 'Triggering layoutready';\n // logDebug(s);\n layoutInfo.ready = true;\n layout.one('layoutready', options.ready);\n layout.emit({\n type: 'layoutready',\n layout: this\n });\n }\n};\n\n/**\n * @brief : Logs a debug message in JS console, if DEBUG is ON\n */\n// var logDebug = function(text) {\n// if (DEBUG) {\n// console.debug(text);\n// }\n// };\n\n/**\n * @brief : Performs one iteration of the physical simulation\n * @arg layoutInfo : LayoutInfo object already initialized\n * @arg cy : Cytoscape object\n * @arg options : Layout options\n */\nvar step = function step(layoutInfo, options, _step) {\n // var s = \"\\n\\n###############################\";\n // s += \"\\nSTEP: \" + step;\n // s += \"\\n###############################\\n\";\n // logDebug(s);\n\n // Calculate node repulsions\n calculateNodeForces(layoutInfo, options);\n // Calculate edge forces\n calculateEdgeForces(layoutInfo);\n // Calculate gravity forces\n calculateGravityForces(layoutInfo, options);\n // Propagate forces from parent to child\n propagateForces(layoutInfo);\n // Update positions based on calculated forces\n updatePositions(layoutInfo);\n};\n\n/**\n * @brief : Computes the node repulsion forces\n */\nvar calculateNodeForces = function calculateNodeForces(layoutInfo, options) {\n // Go through each of the graphs in graphSet\n // Nodes only repel each other if they belong to the same graph\n // var s = 'calculateNodeForces';\n // logDebug(s);\n for (var i = 0; i < layoutInfo.graphSet.length; i++) {\n var graph = layoutInfo.graphSet[i];\n var numNodes = graph.length;\n\n // s = \"Set: \" + graph.toString();\n // logDebug(s);\n\n // Now get all the pairs of nodes\n // Only get each pair once, (A, B) = (B, A)\n for (var j = 0; j < numNodes; j++) {\n var node1 = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[j]]];\n for (var k = j + 1; k < numNodes; k++) {\n var node2 = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[k]]];\n nodeRepulsion(node1, node2, layoutInfo, options);\n }\n }\n }\n};\nvar randomDistance = function randomDistance(max) {\n return -1 + 2 * max * Math.random();\n};\n\n/**\n * @brief : Compute the node repulsion forces between a pair of nodes\n */\nvar nodeRepulsion = function nodeRepulsion(node1, node2, layoutInfo, options) {\n // var s = \"Node repulsion. Node1: \" + node1.id + \" Node2: \" + node2.id;\n\n var cmptId1 = node1.cmptId;\n var cmptId2 = node2.cmptId;\n if (cmptId1 !== cmptId2 && !layoutInfo.isCompound) {\n return;\n }\n\n // Get direction of line connecting both node centers\n var directionX = node2.positionX - node1.positionX;\n var directionY = node2.positionY - node1.positionY;\n var maxRandDist = 1;\n // s += \"\\ndirectionX: \" + directionX + \", directionY: \" + directionY;\n\n // If both centers are the same, apply a random force\n if (0 === directionX && 0 === directionY) {\n directionX = randomDistance(maxRandDist);\n directionY = randomDistance(maxRandDist);\n }\n var overlap = nodesOverlap(node1, node2, directionX, directionY);\n if (overlap > 0) {\n // s += \"\\nNodes DO overlap.\";\n // s += \"\\nOverlap: \" + overlap;\n // If nodes overlap, repulsion force is proportional\n // to the overlap\n var force = options.nodeOverlap * overlap;\n\n // Compute the module and components of the force vector\n var distance = Math.sqrt(directionX * directionX + directionY * directionY);\n // s += \"\\nDistance: \" + distance;\n var forceX = force * directionX / distance;\n var forceY = force * directionY / distance;\n } else {\n // s += \"\\nNodes do NOT overlap.\";\n // If there's no overlap, force is inversely proportional\n // to squared distance\n\n // Get clipping points for both nodes\n var point1 = findClippingPoint(node1, directionX, directionY);\n var point2 = findClippingPoint(node2, -1 * directionX, -1 * directionY);\n\n // Use clipping points to compute distance\n var distanceX = point2.x - point1.x;\n var distanceY = point2.y - point1.y;\n var distanceSqr = distanceX * distanceX + distanceY * distanceY;\n var distance = Math.sqrt(distanceSqr);\n // s += \"\\nDistance: \" + distance;\n\n // Compute the module and components of the force vector\n var force = (node1.nodeRepulsion + node2.nodeRepulsion) / distanceSqr;\n var forceX = force * distanceX / distance;\n var forceY = force * distanceY / distance;\n }\n\n // Apply force\n if (!node1.isLocked) {\n node1.offsetX -= forceX;\n node1.offsetY -= forceY;\n }\n if (!node2.isLocked) {\n node2.offsetX += forceX;\n node2.offsetY += forceY;\n }\n\n // s += \"\\nForceX: \" + forceX + \" ForceY: \" + forceY;\n // logDebug(s);\n\n return;\n};\n\n/**\n * @brief : Determines whether two nodes overlap or not\n * @return : Amount of overlapping (0 => no overlap)\n */\nvar nodesOverlap = function nodesOverlap(node1, node2, dX, dY) {\n if (dX > 0) {\n var overlapX = node1.maxX - node2.minX;\n } else {\n var overlapX = node2.maxX - node1.minX;\n }\n if (dY > 0) {\n var overlapY = node1.maxY - node2.minY;\n } else {\n var overlapY = node2.maxY - node1.minY;\n }\n if (overlapX >= 0 && overlapY >= 0) {\n return Math.sqrt(overlapX * overlapX + overlapY * overlapY);\n } else {\n return 0;\n }\n};\n\n/**\n * @brief : Finds the point in which an edge (direction dX, dY) intersects\n * the rectangular bounding box of it's source/target node\n */\nvar findClippingPoint = function findClippingPoint(node, dX, dY) {\n // Shorcuts\n var X = node.positionX;\n var Y = node.positionY;\n var H = node.height || 1;\n var W = node.width || 1;\n var dirSlope = dY / dX;\n var nodeSlope = H / W;\n\n // var s = 'Computing clipping point of node ' + node.id +\n // \" . Height: \" + H + \", Width: \" + W +\n // \"\\nDirection \" + dX + \", \" + dY;\n //\n // Compute intersection\n var res = {};\n\n // Case: Vertical direction (up)\n if (0 === dX && 0 < dY) {\n res.x = X;\n // s += \"\\nUp direction\";\n res.y = Y + H / 2;\n return res;\n }\n\n // Case: Vertical direction (down)\n if (0 === dX && 0 > dY) {\n res.x = X;\n res.y = Y + H / 2;\n // s += \"\\nDown direction\";\n\n return res;\n }\n\n // Case: Intersects the right border\n if (0 < dX && -1 * nodeSlope <= dirSlope && dirSlope <= nodeSlope) {\n res.x = X + W / 2;\n res.y = Y + W * dY / 2 / dX;\n // s += \"\\nRightborder\";\n\n return res;\n }\n\n // Case: Intersects the left border\n if (0 > dX && -1 * nodeSlope <= dirSlope && dirSlope <= nodeSlope) {\n res.x = X - W / 2;\n res.y = Y - W * dY / 2 / dX;\n // s += \"\\nLeftborder\";\n\n return res;\n }\n\n // Case: Intersects the top border\n if (0 < dY && (dirSlope <= -1 * nodeSlope || dirSlope >= nodeSlope)) {\n res.x = X + H * dX / 2 / dY;\n res.y = Y + H / 2;\n // s += \"\\nTop border\";\n\n return res;\n }\n\n // Case: Intersects the bottom border\n if (0 > dY && (dirSlope <= -1 * nodeSlope || dirSlope >= nodeSlope)) {\n res.x = X - H * dX / 2 / dY;\n res.y = Y - H / 2;\n // s += \"\\nBottom border\";\n\n return res;\n }\n\n // s += \"\\nClipping point found at \" + res.x + \", \" + res.y;\n // logDebug(s);\n return res;\n};\n\n/**\n * @brief : Calculates all edge forces\n */\nvar calculateEdgeForces = function calculateEdgeForces(layoutInfo, options) {\n // Iterate over all edges\n for (var i = 0; i < layoutInfo.edgeSize; i++) {\n // Get edge, source & target nodes\n var edge = layoutInfo.layoutEdges[i];\n var sourceIx = layoutInfo.idToIndex[edge.sourceId];\n var source = layoutInfo.layoutNodes[sourceIx];\n var targetIx = layoutInfo.idToIndex[edge.targetId];\n var target = layoutInfo.layoutNodes[targetIx];\n\n // Get direction of line connecting both node centers\n var directionX = target.positionX - source.positionX;\n var directionY = target.positionY - source.positionY;\n\n // If both centers are the same, do nothing.\n // A random force has already been applied as node repulsion\n if (0 === directionX && 0 === directionY) {\n continue;\n }\n\n // Get clipping points for both nodes\n var point1 = findClippingPoint(source, directionX, directionY);\n var point2 = findClippingPoint(target, -1 * directionX, -1 * directionY);\n var lx = point2.x - point1.x;\n var ly = point2.y - point1.y;\n var l = Math.sqrt(lx * lx + ly * ly);\n var force = Math.pow(edge.idealLength - l, 2) / edge.elasticity;\n if (0 !== l) {\n var forceX = force * lx / l;\n var forceY = force * ly / l;\n } else {\n var forceX = 0;\n var forceY = 0;\n }\n\n // Add this force to target and source nodes\n if (!source.isLocked) {\n source.offsetX += forceX;\n source.offsetY += forceY;\n }\n if (!target.isLocked) {\n target.offsetX -= forceX;\n target.offsetY -= forceY;\n }\n\n // var s = 'Edge force between nodes ' + source.id + ' and ' + target.id;\n // s += \"\\nDistance: \" + l + \" Force: (\" + forceX + \", \" + forceY + \")\";\n // logDebug(s);\n }\n};\n\n/**\n * @brief : Computes gravity forces for all nodes\n */\nvar calculateGravityForces = function calculateGravityForces(layoutInfo, options) {\n if (options.gravity === 0) {\n return;\n }\n var distThreshold = 1;\n\n // var s = 'calculateGravityForces';\n // logDebug(s);\n for (var i = 0; i < layoutInfo.graphSet.length; i++) {\n var graph = layoutInfo.graphSet[i];\n var numNodes = graph.length;\n\n // s = \"Set: \" + graph.toString();\n // logDebug(s);\n\n // Compute graph center\n if (0 === i) {\n var centerX = layoutInfo.clientHeight / 2;\n var centerY = layoutInfo.clientWidth / 2;\n } else {\n // Get Parent node for this graph, and use its position as center\n var temp = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[0]]];\n var parent = layoutInfo.layoutNodes[layoutInfo.idToIndex[temp.parentId]];\n var centerX = parent.positionX;\n var centerY = parent.positionY;\n }\n // s = \"Center found at: \" + centerX + \", \" + centerY;\n // logDebug(s);\n\n // Apply force to all nodes in graph\n for (var j = 0; j < numNodes; j++) {\n var node = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[j]]];\n // s = \"Node: \" + node.id;\n\n if (node.isLocked) {\n continue;\n }\n var dx = centerX - node.positionX;\n var dy = centerY - node.positionY;\n var d = Math.sqrt(dx * dx + dy * dy);\n if (d > distThreshold) {\n var fx = options.gravity * dx / d;\n var fy = options.gravity * dy / d;\n node.offsetX += fx;\n node.offsetY += fy;\n // s += \": Applied force: \" + fx + \", \" + fy;\n }\n // logDebug(s);\n }\n }\n};\n\n/**\n * @brief : This function propagates the existing offsets from\n * parent nodes to its descendents.\n * @arg layoutInfo : layoutInfo Object\n * @arg cy : cytoscape Object\n * @arg options : Layout options\n */\nvar propagateForces = function propagateForces(layoutInfo, options) {\n // Inline implementation of a queue, used for traversing the graph in BFS order\n var queue = [];\n var start = 0; // Points to the start the queue\n var end = -1; // Points to the end of the queue\n\n // logDebug('propagateForces');\n\n // Start by visiting the nodes in the root graph\n queue.push.apply(queue, layoutInfo.graphSet[0]);\n end += layoutInfo.graphSet[0].length;\n\n // Traverse the graph, level by level,\n while (start <= end) {\n // Get the node to visit and remove it from queue\n var nodeId = queue[start++];\n var nodeIndex = layoutInfo.idToIndex[nodeId];\n var node = layoutInfo.layoutNodes[nodeIndex];\n var children = node.children;\n\n // We only need to process the node if it's compound\n if (0 < children.length && !node.isLocked) {\n var offX = node.offsetX;\n var offY = node.offsetY;\n\n // var s = \"Propagating offset from parent node : \" + node.id +\n // \". OffsetX: \" + offX + \". OffsetY: \" + offY;\n // s += \"\\n Children: \" + children.toString();\n // logDebug(s);\n\n for (var i = 0; i < children.length; i++) {\n var childNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[children[i]]];\n // Propagate offset\n childNode.offsetX += offX;\n childNode.offsetY += offY;\n // Add children to queue to be visited\n queue[++end] = children[i];\n }\n\n // Reset parent offsets\n node.offsetX = 0;\n node.offsetY = 0;\n }\n }\n};\n\n/**\n * @brief : Updates the layout model positions, based on\n * the accumulated forces\n */\nvar updatePositions = function updatePositions(layoutInfo, options) {\n // var s = 'Updating positions';\n // logDebug(s);\n\n // Reset boundaries for compound nodes\n for (var i = 0; i < layoutInfo.nodeSize; i++) {\n var n = layoutInfo.layoutNodes[i];\n if (0 < n.children.length) {\n // logDebug(\"Resetting boundaries of compound node: \" + n.id);\n n.maxX = undefined;\n n.minX = undefined;\n n.maxY = undefined;\n n.minY = undefined;\n }\n }\n for (var i = 0; i < layoutInfo.nodeSize; i++) {\n var n = layoutInfo.layoutNodes[i];\n if (0 < n.children.length || n.isLocked) {\n // No need to set compound or locked node position\n // logDebug(\"Skipping position update of node: \" + n.id);\n continue;\n }\n // s = \"Node: \" + n.id + \" Previous position: (\" +\n // n.positionX + \", \" + n.positionY + \").\";\n\n // Limit displacement in order to improve stability\n var tempForce = limitForce(n.offsetX, n.offsetY, layoutInfo.temperature);\n n.positionX += tempForce.x;\n n.positionY += tempForce.y;\n n.offsetX = 0;\n n.offsetY = 0;\n n.minX = n.positionX - n.width;\n n.maxX = n.positionX + n.width;\n n.minY = n.positionY - n.height;\n n.maxY = n.positionY + n.height;\n // s += \" New Position: (\" + n.positionX + \", \" + n.positionY + \").\";\n // logDebug(s);\n\n // Update ancestry boudaries\n _updateAncestryBoundaries(n, layoutInfo);\n }\n\n // Update size, position of compund nodes\n for (var i = 0; i < layoutInfo.nodeSize; i++) {\n var n = layoutInfo.layoutNodes[i];\n if (0 < n.children.length && !n.isLocked) {\n n.positionX = (n.maxX + n.minX) / 2;\n n.positionY = (n.maxY + n.minY) / 2;\n n.width = n.maxX - n.minX;\n n.height = n.maxY - n.minY;\n // s = \"Updating position, size of compound node \" + n.id;\n // s += \"\\nPositionX: \" + n.positionX + \", PositionY: \" + n.positionY;\n // s += \"\\nWidth: \" + n.width + \", Height: \" + n.height;\n // logDebug(s);\n }\n }\n};\n\n/**\n * @brief : Limits a force (forceX, forceY) to be not\n * greater (in modulo) than max.\n 8 Preserves force direction.\n */\nvar limitForce = function limitForce(forceX, forceY, max) {\n // var s = \"Limiting force: (\" + forceX + \", \" + forceY + \"). Max: \" + max;\n var force = Math.sqrt(forceX * forceX + forceY * forceY);\n if (force > max) {\n var res = {\n x: max * forceX / force,\n y: max * forceY / force\n };\n } else {\n var res = {\n x: forceX,\n y: forceY\n };\n }\n\n // s += \".\\nResult: (\" + res.x + \", \" + res.y + \")\";\n // logDebug(s);\n\n return res;\n};\n\n/**\n * @brief : Function used for keeping track of compound node\n * sizes, since they should bound all their subnodes.\n */\nvar _updateAncestryBoundaries = function updateAncestryBoundaries(node, layoutInfo) {\n // var s = \"Propagating new position/size of node \" + node.id;\n var parentId = node.parentId;\n if (null == parentId) {\n // If there's no parent, we are done\n // s += \". No parent node.\";\n // logDebug(s);\n return;\n }\n\n // Get Parent Node\n var p = layoutInfo.layoutNodes[layoutInfo.idToIndex[parentId]];\n var flag = false;\n\n // MaxX\n if (null == p.maxX || node.maxX + p.padRight > p.maxX) {\n p.maxX = node.maxX + p.padRight;\n flag = true;\n // s += \"\\nNew maxX for parent node \" + p.id + \": \" + p.maxX;\n }\n\n // MinX\n if (null == p.minX || node.minX - p.padLeft < p.minX) {\n p.minX = node.minX - p.padLeft;\n flag = true;\n // s += \"\\nNew minX for parent node \" + p.id + \": \" + p.minX;\n }\n\n // MaxY\n if (null == p.maxY || node.maxY + p.padBottom > p.maxY) {\n p.maxY = node.maxY + p.padBottom;\n flag = true;\n // s += \"\\nNew maxY for parent node \" + p.id + \": \" + p.maxY;\n }\n\n // MinY\n if (null == p.minY || node.minY - p.padTop < p.minY) {\n p.minY = node.minY - p.padTop;\n flag = true;\n // s += \"\\nNew minY for parent node \" + p.id + \": \" + p.minY;\n }\n\n // If updated boundaries, propagate changes upward\n if (flag) {\n // logDebug(s);\n return _updateAncestryBoundaries(p, layoutInfo);\n }\n\n // s += \". No changes in boundaries/position of parent node \" + p.id;\n // logDebug(s);\n return;\n};\nvar separateComponents = function separateComponents(layoutInfo, options) {\n var nodes = layoutInfo.layoutNodes;\n var components = [];\n for (var i = 0; i < nodes.length; i++) {\n var node = nodes[i];\n var cid = node.cmptId;\n var component = components[cid] = components[cid] || [];\n component.push(node);\n }\n var totalA = 0;\n for (var i = 0; i < components.length; i++) {\n var c = components[i];\n if (!c) {\n continue;\n }\n c.x1 = Infinity;\n c.x2 = -Infinity;\n c.y1 = Infinity;\n c.y2 = -Infinity;\n for (var j = 0; j < c.length; j++) {\n var n = c[j];\n c.x1 = Math.min(c.x1, n.positionX - n.width / 2);\n c.x2 = Math.max(c.x2, n.positionX + n.width / 2);\n c.y1 = Math.min(c.y1, n.positionY - n.height / 2);\n c.y2 = Math.max(c.y2, n.positionY + n.height / 2);\n }\n c.w = c.x2 - c.x1;\n c.h = c.y2 - c.y1;\n totalA += c.w * c.h;\n }\n components.sort(function (c1, c2) {\n return c2.w * c2.h - c1.w * c1.h;\n });\n var x = 0;\n var y = 0;\n var usedW = 0;\n var rowH = 0;\n var maxRowW = Math.sqrt(totalA) * layoutInfo.clientWidth / layoutInfo.clientHeight;\n for (var i = 0; i < components.length; i++) {\n var c = components[i];\n if (!c) {\n continue;\n }\n for (var j = 0; j < c.length; j++) {\n var n = c[j];\n if (!n.isLocked) {\n n.positionX += x - c.x1;\n n.positionY += y - c.y1;\n }\n }\n x += c.w + options.componentSpacing;\n usedW += c.w + options.componentSpacing;\n rowH = Math.max(rowH, c.h);\n if (usedW > maxRowW) {\n y += rowH + options.componentSpacing;\n x = 0;\n usedW = 0;\n rowH = 0;\n }\n }\n};\n\nvar defaults$3 = {\n fit: true,\n // whether to fit the viewport to the graph\n padding: 30,\n // padding used on fit\n boundingBox: undefined,\n // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }\n avoidOverlap: true,\n // prevents node overlap, may overflow boundingBox if not enough space\n avoidOverlapPadding: 10,\n // extra spacing around nodes when avoidOverlap: true\n nodeDimensionsIncludeLabels: false,\n // Excludes the label when calculating node bounding boxes for the layout algorithm\n spacingFactor: undefined,\n // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up\n condense: false,\n // uses all available space on false, uses minimal space on true\n rows: undefined,\n // force num of rows in the grid\n cols: undefined,\n // force num of columns in the grid\n position: function position(node) {},\n // returns { row, col } for element\n sort: undefined,\n // a sorting function to order the nodes; e.g. function(a, b){ return a.data('weight') - b.data('weight') }\n animate: false,\n // whether to transition the node positions\n animationDuration: 500,\n // duration of animation in ms if enabled\n animationEasing: undefined,\n // easing of animation if enabled\n animateFilter: function animateFilter(node, i) {\n return true;\n },\n // a function that determines whether the node should be animated. All nodes animated by default on animate enabled. Non-animated nodes are positioned immediately when the layout starts\n ready: undefined,\n // callback on layoutready\n stop: undefined,\n // callback on layoutstop\n transform: function transform(node, position) {\n return position;\n } // transform a given node position. Useful for changing flow direction in discrete layouts \n};\nfunction GridLayout(options) {\n this.options = extend({}, defaults$3, options);\n}\nGridLayout.prototype.run = function () {\n var params = this.options;\n var options = params;\n var cy = params.cy;\n var eles = options.eles;\n var nodes = eles.nodes().not(':parent');\n if (options.sort) {\n nodes = nodes.sort(options.sort);\n }\n var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {\n x1: 0,\n y1: 0,\n w: cy.width(),\n h: cy.height()\n });\n if (bb.h === 0 || bb.w === 0) {\n eles.nodes().layoutPositions(this, options, function (ele) {\n return {\n x: bb.x1,\n y: bb.y1\n };\n });\n } else {\n // width/height * splits^2 = cells where splits is number of times to split width\n var cells = nodes.size();\n var splits = Math.sqrt(cells * bb.h / bb.w);\n var rows = Math.round(splits);\n var cols = Math.round(bb.w / bb.h * splits);\n var small = function small(val) {\n if (val == null) {\n return Math.min(rows, cols);\n } else {\n var min = Math.min(rows, cols);\n if (min == rows) {\n rows = val;\n } else {\n cols = val;\n }\n }\n };\n var large = function large(val) {\n if (val == null) {\n return Math.max(rows, cols);\n } else {\n var max = Math.max(rows, cols);\n if (max == rows) {\n rows = val;\n } else {\n cols = val;\n }\n }\n };\n var oRows = options.rows;\n var oCols = options.cols != null ? options.cols : options.columns;\n\n // if rows or columns were set in options, use those values\n if (oRows != null && oCols != null) {\n rows = oRows;\n cols = oCols;\n } else if (oRows != null && oCols == null) {\n rows = oRows;\n cols = Math.ceil(cells / rows);\n } else if (oRows == null && oCols != null) {\n cols = oCols;\n rows = Math.ceil(cells / cols);\n }\n\n // otherwise use the automatic values and adjust accordingly\n\n // if rounding was up, see if we can reduce rows or columns\n else if (cols * rows > cells) {\n var sm = small();\n var lg = large();\n\n // reducing the small side takes away the most cells, so try it first\n if ((sm - 1) * lg >= cells) {\n small(sm - 1);\n } else if ((lg - 1) * sm >= cells) {\n large(lg - 1);\n }\n } else {\n // if rounding was too low, add rows or columns\n while (cols * rows < cells) {\n var _sm = small();\n var _lg = large();\n\n // try to add to larger side first (adds less in multiplication)\n if ((_lg + 1) * _sm >= cells) {\n large(_lg + 1);\n } else {\n small(_sm + 1);\n }\n }\n }\n var cellWidth = bb.w / cols;\n var cellHeight = bb.h / rows;\n if (options.condense) {\n cellWidth = 0;\n cellHeight = 0;\n }\n if (options.avoidOverlap) {\n for (var i = 0; i < nodes.length; i++) {\n var node = nodes[i];\n var pos = node._private.position;\n if (pos.x == null || pos.y == null) {\n // for bb\n pos.x = 0;\n pos.y = 0;\n }\n var nbb = node.layoutDimensions(options);\n var p = options.avoidOverlapPadding;\n var w = nbb.w + p;\n var h = nbb.h + p;\n cellWidth = Math.max(cellWidth, w);\n cellHeight = Math.max(cellHeight, h);\n }\n }\n var cellUsed = {}; // e.g. 'c-0-2' => true\n\n var used = function used(row, col) {\n return cellUsed['c-' + row + '-' + col] ? true : false;\n };\n var use = function use(row, col) {\n cellUsed['c-' + row + '-' + col] = true;\n };\n\n // to keep track of current cell position\n var row = 0;\n var col = 0;\n var moveToNextCell = function moveToNextCell() {\n col++;\n if (col >= cols) {\n col = 0;\n row++;\n }\n };\n\n // get a cache of all the manual positions\n var id2manPos = {};\n for (var _i = 0; _i < nodes.length; _i++) {\n var _node = nodes[_i];\n var rcPos = options.position(_node);\n if (rcPos && (rcPos.row !== undefined || rcPos.col !== undefined)) {\n // must have at least row or col def'd\n var _pos = {\n row: rcPos.row,\n col: rcPos.col\n };\n if (_pos.col === undefined) {\n // find unused col\n _pos.col = 0;\n while (used(_pos.row, _pos.col)) {\n _pos.col++;\n }\n } else if (_pos.row === undefined) {\n // find unused row\n _pos.row = 0;\n while (used(_pos.row, _pos.col)) {\n _pos.row++;\n }\n }\n id2manPos[_node.id()] = _pos;\n use(_pos.row, _pos.col);\n }\n }\n var getPos = function getPos(element, i) {\n var x, y;\n if (element.locked() || element.isParent()) {\n return false;\n }\n\n // see if we have a manual position set\n var rcPos = id2manPos[element.id()];\n if (rcPos) {\n x = rcPos.col * cellWidth + cellWidth / 2 + bb.x1;\n y = rcPos.row * cellHeight + cellHeight / 2 + bb.y1;\n } else {\n // otherwise set automatically\n\n while (used(row, col)) {\n moveToNextCell();\n }\n x = col * cellWidth + cellWidth / 2 + bb.x1;\n y = row * cellHeight + cellHeight / 2 + bb.y1;\n use(row, col);\n moveToNextCell();\n }\n return {\n x: x,\n y: y\n };\n };\n nodes.layoutPositions(this, options, getPos);\n }\n return this; // chaining\n};\n\n// default layout options\nvar defaults$2 = {\n ready: function ready() {},\n // on layoutready\n stop: function stop() {} // on layoutstop\n};\n\n// constructor\n// options : object containing layout options\nfunction NullLayout(options) {\n this.options = extend({}, defaults$2, options);\n}\n\n// runs the layout\nNullLayout.prototype.run = function () {\n var options = this.options;\n var eles = options.eles; // elements to consider in the layout\n var layout = this;\n\n // cy is automatically populated for us in the constructor\n // (disable eslint for next line as this serves as example layout code to external developers)\n // eslint-disable-next-line no-unused-vars\n options.cy;\n layout.emit('layoutstart');\n\n // puts all nodes at (0, 0)\n // n.b. most layouts would use layoutPositions(), instead of positions() and manual events\n eles.nodes().positions(function () {\n return {\n x: 0,\n y: 0\n };\n });\n\n // trigger layoutready when each node has had its position set at least once\n layout.one('layoutready', options.ready);\n layout.emit('layoutready');\n\n // trigger layoutstop when the layout stops (e.g. finishes)\n layout.one('layoutstop', options.stop);\n layout.emit('layoutstop');\n return this; // chaining\n};\n\n// called on continuous layouts to stop them before they finish\nNullLayout.prototype.stop = function () {\n return this; // chaining\n};\n\nvar defaults$1 = {\n positions: undefined,\n // map of (node id) => (position obj); or function(node){ return somPos; }\n zoom: undefined,\n // the zoom level to set (prob want fit = false if set)\n pan: undefined,\n // the pan level to set (prob want fit = false if set)\n fit: true,\n // whether to fit to viewport\n padding: 30,\n // padding on fit\n spacingFactor: undefined,\n // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up\n animate: false,\n // whether to transition the node positions\n animationDuration: 500,\n // duration of animation in ms if enabled\n animationEasing: undefined,\n // easing of animation if enabled\n animateFilter: function animateFilter(node, i) {\n return true;\n },\n // a function that determines whether the node should be animated. All nodes animated by default on animate enabled. Non-animated nodes are positioned immediately when the layout starts\n ready: undefined,\n // callback on layoutready\n stop: undefined,\n // callback on layoutstop\n transform: function transform(node, position) {\n return position;\n } // transform a given node position. Useful for changing flow direction in discrete layouts\n};\nfunction PresetLayout(options) {\n this.options = extend({}, defaults$1, options);\n}\nPresetLayout.prototype.run = function () {\n var options = this.options;\n var eles = options.eles;\n var nodes = eles.nodes();\n var posIsFn = fn$6(options.positions);\n function getPosition(node) {\n if (options.positions == null) {\n return copyPosition(node.position());\n }\n if (posIsFn) {\n return options.positions(node);\n }\n var pos = options.positions[node._private.data.id];\n if (pos == null) {\n return null;\n }\n return pos;\n }\n nodes.layoutPositions(this, options, function (node, i) {\n var position = getPosition(node);\n if (node.locked() || position == null) {\n return false;\n }\n return position;\n });\n return this; // chaining\n};\n\nvar defaults = {\n fit: true,\n // whether to fit to viewport\n padding: 30,\n // fit padding\n boundingBox: undefined,\n // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }\n animate: false,\n // whether to transition the node positions\n animationDuration: 500,\n // duration of animation in ms if enabled\n animationEasing: undefined,\n // easing of animation if enabled\n animateFilter: function animateFilter(node, i) {\n return true;\n },\n // a function that determines whether the node should be animated. All nodes animated by default on animate enabled. Non-animated nodes are positioned immediately when the layout starts\n ready: undefined,\n // callback on layoutready\n stop: undefined,\n // callback on layoutstop\n transform: function transform(node, position) {\n return position;\n } // transform a given node position. Useful for changing flow direction in discrete layouts \n};\nfunction RandomLayout(options) {\n this.options = extend({}, defaults, options);\n}\nRandomLayout.prototype.run = function () {\n var options = this.options;\n var cy = options.cy;\n var eles = options.eles;\n var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {\n x1: 0,\n y1: 0,\n w: cy.width(),\n h: cy.height()\n });\n var getPos = function getPos(node, i) {\n return {\n x: bb.x1 + Math.round(Math.random() * bb.w),\n y: bb.y1 + Math.round(Math.random() * bb.h)\n };\n };\n eles.nodes().layoutPositions(this, options, getPos);\n return this; // chaining\n};\n\nvar layout = [{\n name: 'breadthfirst',\n impl: BreadthFirstLayout\n}, {\n name: 'circle',\n impl: CircleLayout\n}, {\n name: 'concentric',\n impl: ConcentricLayout\n}, {\n name: 'cose',\n impl: CoseLayout\n}, {\n name: 'grid',\n impl: GridLayout\n}, {\n name: 'null',\n impl: NullLayout\n}, {\n name: 'preset',\n impl: PresetLayout\n}, {\n name: 'random',\n impl: RandomLayout\n}];\n\nfunction NullRenderer(options) {\n this.options = options;\n this.notifications = 0; // for testing\n}\nvar noop = function noop() {};\nvar throwImgErr = function throwImgErr() {\n throw new Error('A headless instance can not render images');\n};\nNullRenderer.prototype = {\n recalculateRenderedStyle: noop,\n notify: function notify() {\n this.notifications++;\n },\n init: noop,\n isHeadless: function isHeadless() {\n return true;\n },\n png: throwImgErr,\n jpg: throwImgErr\n};\n\nvar BRp$f = {};\nBRp$f.arrowShapeWidth = 0.3;\nBRp$f.registerArrowShapes = function () {\n var arrowShapes = this.arrowShapes = {};\n var renderer = this;\n\n // Contract for arrow shapes:\n // 0, 0 is arrow tip\n // (0, 1) is direction towards node\n // (1, 0) is right\n //\n // functional api:\n // collide: check x, y in shape\n // roughCollide: called before collide, no false negatives\n // draw: draw\n // spacing: dist(arrowTip, nodeBoundary)\n // gap: dist(edgeTip, nodeBoundary), edgeTip may != arrowTip\n\n var bbCollide = function bbCollide(x, y, size, angle, translation, edgeWidth, padding) {\n var x1 = translation.x - size / 2 - padding;\n var x2 = translation.x + size / 2 + padding;\n var y1 = translation.y - size / 2 - padding;\n var y2 = translation.y + size / 2 + padding;\n var inside = x1 <= x && x <= x2 && y1 <= y && y <= y2;\n return inside;\n };\n var transform = function transform(x, y, size, angle, translation) {\n var xRotated = x * Math.cos(angle) - y * Math.sin(angle);\n var yRotated = x * Math.sin(angle) + y * Math.cos(angle);\n var xScaled = xRotated * size;\n var yScaled = yRotated * size;\n var xTranslated = xScaled + translation.x;\n var yTranslated = yScaled + translation.y;\n return {\n x: xTranslated,\n y: yTranslated\n };\n };\n var transformPoints = function transformPoints(pts, size, angle, translation) {\n var retPts = [];\n for (var i = 0; i < pts.length; i += 2) {\n var x = pts[i];\n var y = pts[i + 1];\n retPts.push(transform(x, y, size, angle, translation));\n }\n return retPts;\n };\n var pointsToArr = function pointsToArr(pts) {\n var ret = [];\n for (var i = 0; i < pts.length; i++) {\n var p = pts[i];\n ret.push(p.x, p.y);\n }\n return ret;\n };\n var standardGap = function standardGap(edge) {\n return edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').pfValue * 2;\n };\n var defineArrowShape = function defineArrowShape(name, defn) {\n if (string(defn)) {\n defn = arrowShapes[defn];\n }\n arrowShapes[name] = extend({\n name: name,\n points: [-0.15, -0.3, 0.15, -0.3, 0.15, 0.3, -0.15, 0.3],\n collide: function collide(x, y, size, angle, translation, padding) {\n var points = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));\n var inside = pointInsidePolygonPoints(x, y, points);\n return inside;\n },\n roughCollide: bbCollide,\n draw: function draw(context, size, angle, translation) {\n var points = transformPoints(this.points, size, angle, translation);\n renderer.arrowShapeImpl('polygon')(context, points);\n },\n spacing: function spacing(edge) {\n return 0;\n },\n gap: standardGap\n }, defn);\n };\n defineArrowShape('none', {\n collide: falsify,\n roughCollide: falsify,\n draw: noop$1,\n spacing: zeroify,\n gap: zeroify\n });\n defineArrowShape('triangle', {\n points: [-0.15, -0.3, 0, 0, 0.15, -0.3]\n });\n defineArrowShape('arrow', 'triangle');\n defineArrowShape('triangle-backcurve', {\n points: arrowShapes['triangle'].points,\n controlPoint: [0, -0.15],\n roughCollide: bbCollide,\n draw: function draw(context, size, angle, translation, edgeWidth) {\n var ptsTrans = transformPoints(this.points, size, angle, translation);\n var ctrlPt = this.controlPoint;\n var ctrlPtTrans = transform(ctrlPt[0], ctrlPt[1], size, angle, translation);\n renderer.arrowShapeImpl(this.name)(context, ptsTrans, ctrlPtTrans);\n },\n gap: function gap(edge) {\n return standardGap(edge) * 0.8;\n }\n });\n defineArrowShape('triangle-tee', {\n points: [0, 0, 0.15, -0.3, -0.15, -0.3, 0, 0],\n pointsTee: [-0.15, -0.4, -0.15, -0.5, 0.15, -0.5, 0.15, -0.4],\n collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {\n var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));\n var teePts = pointsToArr(transformPoints(this.pointsTee, size + 2 * padding, angle, translation));\n var inside = pointInsidePolygonPoints(x, y, triPts) || pointInsidePolygonPoints(x, y, teePts);\n return inside;\n },\n draw: function draw(context, size, angle, translation, edgeWidth) {\n var triPts = transformPoints(this.points, size, angle, translation);\n var teePts = transformPoints(this.pointsTee, size, angle, translation);\n renderer.arrowShapeImpl(this.name)(context, triPts, teePts);\n }\n });\n defineArrowShape('circle-triangle', {\n radius: 0.15,\n pointsTr: [0, -0.15, 0.15, -0.45, -0.15, -0.45, 0, -0.15],\n collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {\n var t = translation;\n var circleInside = Math.pow(t.x - x, 2) + Math.pow(t.y - y, 2) <= Math.pow((size + 2 * padding) * this.radius, 2);\n var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));\n return pointInsidePolygonPoints(x, y, triPts) || circleInside;\n },\n draw: function draw(context, size, angle, translation, edgeWidth) {\n var triPts = transformPoints(this.pointsTr, size, angle, translation);\n renderer.arrowShapeImpl(this.name)(context, triPts, translation.x, translation.y, this.radius * size);\n },\n spacing: function spacing(edge) {\n return renderer.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.radius;\n }\n });\n defineArrowShape('triangle-cross', {\n points: [0, 0, 0.15, -0.3, -0.15, -0.3, 0, 0],\n baseCrossLinePts: [-0.15, -0.4,\n // first half of the rectangle\n -0.15, -0.4, 0.15, -0.4,\n // second half of the rectangle\n 0.15, -0.4],\n crossLinePts: function crossLinePts(size, edgeWidth) {\n // shift points so that the distance between the cross points matches edge width\n var p = this.baseCrossLinePts.slice();\n var shiftFactor = edgeWidth / size;\n var y0 = 3;\n var y1 = 5;\n p[y0] = p[y0] - shiftFactor;\n p[y1] = p[y1] - shiftFactor;\n return p;\n },\n collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {\n var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));\n var teePts = pointsToArr(transformPoints(this.crossLinePts(size, edgeWidth), size + 2 * padding, angle, translation));\n var inside = pointInsidePolygonPoints(x, y, triPts) || pointInsidePolygonPoints(x, y, teePts);\n return inside;\n },\n draw: function draw(context, size, angle, translation, edgeWidth) {\n var triPts = transformPoints(this.points, size, angle, translation);\n var crossLinePts = transformPoints(this.crossLinePts(size, edgeWidth), size, angle, translation);\n renderer.arrowShapeImpl(this.name)(context, triPts, crossLinePts);\n }\n });\n defineArrowShape('vee', {\n points: [-0.15, -0.3, 0, 0, 0.15, -0.3, 0, -0.15],\n gap: function gap(edge) {\n return standardGap(edge) * 0.525;\n }\n });\n defineArrowShape('circle', {\n radius: 0.15,\n collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {\n var t = translation;\n var inside = Math.pow(t.x - x, 2) + Math.pow(t.y - y, 2) <= Math.pow((size + 2 * padding) * this.radius, 2);\n return inside;\n },\n draw: function draw(context, size, angle, translation, edgeWidth) {\n renderer.arrowShapeImpl(this.name)(context, translation.x, translation.y, this.radius * size);\n },\n spacing: function spacing(edge) {\n return renderer.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.radius;\n }\n });\n defineArrowShape('tee', {\n points: [-0.15, 0, -0.15, -0.1, 0.15, -0.1, 0.15, 0],\n spacing: function spacing(edge) {\n return 1;\n },\n gap: function gap(edge) {\n return 1;\n }\n });\n defineArrowShape('square', {\n points: [-0.15, 0.00, 0.15, 0.00, 0.15, -0.3, -0.15, -0.3]\n });\n defineArrowShape('diamond', {\n points: [-0.15, -0.15, 0, -0.3, 0.15, -0.15, 0, 0],\n gap: function gap(edge) {\n return edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').value;\n }\n });\n defineArrowShape('chevron', {\n points: [0, 0, -0.15, -0.15, -0.1, -0.2, 0, -0.1, 0.1, -0.2, 0.15, -0.15],\n gap: function gap(edge) {\n return 0.95 * edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').value;\n }\n });\n};\n\nvar BRp$e = {};\n\n// Project mouse\nBRp$e.projectIntoViewport = function (clientX, clientY) {\n var cy = this.cy;\n var offsets = this.findContainerClientCoords();\n var offsetLeft = offsets[0];\n var offsetTop = offsets[1];\n var scale = offsets[4];\n var pan = cy.pan();\n var zoom = cy.zoom();\n var x = ((clientX - offsetLeft) / scale - pan.x) / zoom;\n var y = ((clientY - offsetTop) / scale - pan.y) / zoom;\n return [x, y];\n};\nBRp$e.findContainerClientCoords = function () {\n if (this.containerBB) {\n return this.containerBB;\n }\n var container = this.container;\n var rect = container.getBoundingClientRect();\n var style = this.cy.window().getComputedStyle(container);\n var styleValue = function styleValue(name) {\n return parseFloat(style.getPropertyValue(name));\n };\n var padding = {\n left: styleValue('padding-left'),\n right: styleValue('padding-right'),\n top: styleValue('padding-top'),\n bottom: styleValue('padding-bottom')\n };\n var border = {\n left: styleValue('border-left-width'),\n right: styleValue('border-right-width'),\n top: styleValue('border-top-width'),\n bottom: styleValue('border-bottom-width')\n };\n var clientWidth = container.clientWidth;\n var clientHeight = container.clientHeight;\n var paddingHor = padding.left + padding.right;\n var paddingVer = padding.top + padding.bottom;\n var borderHor = border.left + border.right;\n var scale = rect.width / (clientWidth + borderHor);\n var unscaledW = clientWidth - paddingHor;\n var unscaledH = clientHeight - paddingVer;\n var left = rect.left + padding.left + border.left;\n var top = rect.top + padding.top + border.top;\n return this.containerBB = [left, top, unscaledW, unscaledH, scale];\n};\nBRp$e.invalidateContainerClientCoordsCache = function () {\n this.containerBB = null;\n};\nBRp$e.findNearestElement = function (x, y, interactiveElementsOnly, isTouch) {\n return this.findNearestElements(x, y, interactiveElementsOnly, isTouch)[0];\n};\nBRp$e.findNearestElements = function (x, y, interactiveElementsOnly, isTouch) {\n var self = this;\n var r = this;\n var eles = r.getCachedZSortedEles();\n var near = []; // 1 node max, 1 edge max\n var zoom = r.cy.zoom();\n var hasCompounds = r.cy.hasCompoundNodes();\n var edgeThreshold = (isTouch ? 24 : 8) / zoom;\n var nodeThreshold = (isTouch ? 8 : 2) / zoom;\n var labelThreshold = (isTouch ? 8 : 2) / zoom;\n var minSqDist = Infinity;\n var nearEdge;\n var nearNode;\n if (interactiveElementsOnly) {\n eles = eles.interactive;\n }\n function addEle(ele, sqDist) {\n if (ele.isNode()) {\n if (nearNode) {\n return; // can't replace node\n } else {\n nearNode = ele;\n near.push(ele);\n }\n }\n if (ele.isEdge() && (sqDist == null || sqDist < minSqDist)) {\n if (nearEdge) {\n // then replace existing edge\n // can replace only if same z-index\n if (nearEdge.pstyle('z-compound-depth').value === ele.pstyle('z-compound-depth').value && nearEdge.pstyle('z-compound-depth').value === ele.pstyle('z-compound-depth').value) {\n for (var i = 0; i < near.length; i++) {\n if (near[i].isEdge()) {\n near[i] = ele;\n nearEdge = ele;\n minSqDist = sqDist != null ? sqDist : minSqDist;\n break;\n }\n }\n }\n } else {\n near.push(ele);\n nearEdge = ele;\n minSqDist = sqDist != null ? sqDist : minSqDist;\n }\n }\n }\n function checkNode(node) {\n var width = node.outerWidth() + 2 * nodeThreshold;\n var height = node.outerHeight() + 2 * nodeThreshold;\n var hw = width / 2;\n var hh = height / 2;\n var pos = node.position();\n var cornerRadius = node.pstyle('corner-radius').value === 'auto' ? 'auto' : node.pstyle('corner-radius').pfValue;\n var rs = node._private.rscratch;\n if (pos.x - hw <= x && x <= pos.x + hw // bb check x\n && pos.y - hh <= y && y <= pos.y + hh // bb check y\n ) {\n var shape = r.nodeShapes[self.getNodeShape(node)];\n if (shape.checkPoint(x, y, 0, width, height, pos.x, pos.y, cornerRadius, rs)) {\n addEle(node, 0);\n return true;\n }\n }\n }\n function checkEdge(edge) {\n var _p = edge._private;\n var rs = _p.rscratch;\n var styleWidth = edge.pstyle('width').pfValue;\n var scale = edge.pstyle('arrow-scale').value;\n var width = styleWidth / 2 + edgeThreshold; // more like a distance radius from centre\n var widthSq = width * width;\n var width2 = width * 2;\n var src = _p.source;\n var tgt = _p.target;\n var sqDist;\n if (rs.edgeType === 'segments' || rs.edgeType === 'straight' || rs.edgeType === 'haystack') {\n var pts = rs.allpts;\n for (var i = 0; i + 3 < pts.length; i += 2) {\n if (inLineVicinity(x, y, pts[i], pts[i + 1], pts[i + 2], pts[i + 3], width2) && widthSq > (sqDist = sqdistToFiniteLine(x, y, pts[i], pts[i + 1], pts[i + 2], pts[i + 3]))) {\n addEle(edge, sqDist);\n return true;\n }\n }\n } else if (rs.edgeType === 'bezier' || rs.edgeType === 'multibezier' || rs.edgeType === 'self' || rs.edgeType === 'compound') {\n var pts = rs.allpts;\n for (var i = 0; i + 5 < rs.allpts.length; i += 4) {\n if (inBezierVicinity(x, y, pts[i], pts[i + 1], pts[i + 2], pts[i + 3], pts[i + 4], pts[i + 5], width2) && widthSq > (sqDist = sqdistToQuadraticBezier(x, y, pts[i], pts[i + 1], pts[i + 2], pts[i + 3], pts[i + 4], pts[i + 5]))) {\n addEle(edge, sqDist);\n return true;\n }\n }\n }\n\n // if we're close to the edge but didn't hit it, maybe we hit its arrows\n\n var src = src || _p.source;\n var tgt = tgt || _p.target;\n var arSize = self.getArrowWidth(styleWidth, scale);\n var arrows = [{\n name: 'source',\n x: rs.arrowStartX,\n y: rs.arrowStartY,\n angle: rs.srcArrowAngle\n }, {\n name: 'target',\n x: rs.arrowEndX,\n y: rs.arrowEndY,\n angle: rs.tgtArrowAngle\n }, {\n name: 'mid-source',\n x: rs.midX,\n y: rs.midY,\n angle: rs.midsrcArrowAngle\n }, {\n name: 'mid-target',\n x: rs.midX,\n y: rs.midY,\n angle: rs.midtgtArrowAngle\n }];\n for (var i = 0; i < arrows.length; i++) {\n var ar = arrows[i];\n var shape = r.arrowShapes[edge.pstyle(ar.name + '-arrow-shape').value];\n var edgeWidth = edge.pstyle('width').pfValue;\n if (shape.roughCollide(x, y, arSize, ar.angle, {\n x: ar.x,\n y: ar.y\n }, edgeWidth, edgeThreshold) && shape.collide(x, y, arSize, ar.angle, {\n x: ar.x,\n y: ar.y\n }, edgeWidth, edgeThreshold)) {\n addEle(edge);\n return true;\n }\n }\n\n // for compound graphs, hitting edge may actually want a connected node instead (b/c edge may have greater z-index precedence)\n if (hasCompounds && near.length > 0) {\n checkNode(src);\n checkNode(tgt);\n }\n }\n function preprop(obj, name, pre) {\n return getPrefixedProperty(obj, name, pre);\n }\n function checkLabel(ele, prefix) {\n var _p = ele._private;\n var th = labelThreshold;\n var prefixDash;\n if (prefix) {\n prefixDash = prefix + '-';\n } else {\n prefixDash = '';\n }\n ele.boundingBox();\n var bb = _p.labelBounds[prefix || 'main'];\n var text = ele.pstyle(prefixDash + 'label').value;\n var eventsEnabled = ele.pstyle('text-events').strValue === 'yes';\n if (!eventsEnabled || !text) {\n return;\n }\n var lx = preprop(_p.rscratch, 'labelX', prefix);\n var ly = preprop(_p.rscratch, 'labelY', prefix);\n var theta = preprop(_p.rscratch, 'labelAngle', prefix);\n var ox = ele.pstyle(prefixDash + 'text-margin-x').pfValue;\n var oy = ele.pstyle(prefixDash + 'text-margin-y').pfValue;\n var lx1 = bb.x1 - th - ox; // (-ox, -oy) as bb already includes margin\n var lx2 = bb.x2 + th - ox; // and rotation is about (lx, ly)\n var ly1 = bb.y1 - th - oy;\n var ly2 = bb.y2 + th - oy;\n if (theta) {\n var cos = Math.cos(theta);\n var sin = Math.sin(theta);\n var rotate = function rotate(x, y) {\n x = x - lx;\n y = y - ly;\n return {\n x: x * cos - y * sin + lx,\n y: x * sin + y * cos + ly\n };\n };\n var px1y1 = rotate(lx1, ly1);\n var px1y2 = rotate(lx1, ly2);\n var px2y1 = rotate(lx2, ly1);\n var px2y2 = rotate(lx2, ly2);\n var points = [\n // with the margin added after the rotation is applied\n px1y1.x + ox, px1y1.y + oy, px2y1.x + ox, px2y1.y + oy, px2y2.x + ox, px2y2.y + oy, px1y2.x + ox, px1y2.y + oy];\n if (pointInsidePolygonPoints(x, y, points)) {\n addEle(ele);\n return true;\n }\n } else {\n // do a cheaper bb check\n if (inBoundingBox(bb, x, y)) {\n addEle(ele);\n return true;\n }\n }\n }\n for (var i = eles.length - 1; i >= 0; i--) {\n // reverse order for precedence\n var ele = eles[i];\n if (ele.isNode()) {\n checkNode(ele) || checkLabel(ele);\n } else {\n // then edge\n checkEdge(ele) || checkLabel(ele) || checkLabel(ele, 'source') || checkLabel(ele, 'target');\n }\n }\n return near;\n};\n\n// 'Give me everything from this box'\nBRp$e.getAllInBox = function (x1, y1, x2, y2) {\n var eles = this.getCachedZSortedEles().interactive;\n var zoom = this.cy.zoom();\n var labelThreshold = 2 / zoom;\n var box = [];\n var x1c = Math.min(x1, x2);\n var x2c = Math.max(x1, x2);\n var y1c = Math.min(y1, y2);\n var y2c = Math.max(y1, y2);\n x1 = x1c;\n x2 = x2c;\n y1 = y1c;\n y2 = y2c;\n var boxBb = makeBoundingBox({\n x1: x1,\n y1: y1,\n x2: x2,\n y2: y2\n });\n var selectionBox = [{\n x: boxBb.x1,\n y: boxBb.y1\n }, {\n x: boxBb.x2,\n y: boxBb.y1\n }, {\n x: boxBb.x2,\n y: boxBb.y2\n }, {\n x: boxBb.x1,\n y: boxBb.y2\n }];\n var boxEdges = [[selectionBox[0], selectionBox[1]], [selectionBox[1], selectionBox[2]], [selectionBox[2], selectionBox[3]], [selectionBox[3], selectionBox[0]]];\n function preprop(obj, name, pre) {\n return getPrefixedProperty(obj, name, pre);\n }\n function getRotatedLabelBox(ele, prefix) {\n var _p = ele._private;\n var th = labelThreshold;\n var prefixDash = '';\n ele.boundingBox();\n var bb = _p.labelBounds['main'];\n\n // If the bounding box is not available, return null.\n // This indicates that the label box cannot be calculated, which is consistent\n // with the expected behavior of this function. Returning null allows the caller\n // to handle the absence of a bounding box explicitly.\n if (!bb) {\n return null;\n }\n var lx = preprop(_p.rscratch, 'labelX', prefix);\n var ly = preprop(_p.rscratch, 'labelY', prefix);\n var theta = preprop(_p.rscratch, 'labelAngle', prefix);\n var ox = ele.pstyle(prefixDash + 'text-margin-x').pfValue;\n var oy = ele.pstyle(prefixDash + 'text-margin-y').pfValue;\n var lx1 = bb.x1 - th - ox;\n var lx2 = bb.x2 + th - ox;\n var ly1 = bb.y1 - th - oy;\n var ly2 = bb.y2 + th - oy;\n if (theta) {\n var cos = Math.cos(theta);\n var sin = Math.sin(theta);\n var rotate = function rotate(x, y) {\n x = x - lx;\n y = y - ly;\n return {\n x: x * cos - y * sin + lx,\n y: x * sin + y * cos + ly\n };\n };\n return [rotate(lx1, ly1), rotate(lx2, ly1), rotate(lx2, ly2), rotate(lx1, ly2)];\n } else {\n return [{\n x: lx1,\n y: ly1\n }, {\n x: lx2,\n y: ly1\n }, {\n x: lx2,\n y: ly2\n }, {\n x: lx1,\n y: ly2\n }];\n }\n }\n function doLinesIntersect(p1, p2, q1, q2) {\n function ccw(a, b, c) {\n return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x);\n }\n return ccw(p1, q1, q2) !== ccw(p2, q1, q2) && ccw(p1, p2, q1) !== ccw(p1, p2, q2);\n }\n for (var e = 0; e < eles.length; e++) {\n var ele = eles[e];\n if (ele.isNode()) {\n var node = ele;\n var textEvents = node.pstyle('text-events').strValue === 'yes';\n var nodeBoxSelectMode = node.pstyle('box-selection').strValue;\n var labelBoxSelectEnabled = node.pstyle('box-select-labels').strValue === 'yes';\n if (nodeBoxSelectMode === 'none') {\n continue;\n }\n var includeLabels = (nodeBoxSelectMode === 'overlap' || labelBoxSelectEnabled) && textEvents;\n var nodeBb = node.boundingBox({\n includeNodes: true,\n includeEdges: false,\n includeLabels: includeLabels\n });\n if (nodeBoxSelectMode === 'contain') {\n var selected = false;\n if (labelBoxSelectEnabled && textEvents) {\n var rotatedLabelBox = getRotatedLabelBox(node);\n if (rotatedLabelBox && satPolygonIntersection(rotatedLabelBox, selectionBox)) {\n box.push(node);\n selected = true;\n }\n }\n if (!selected && boundingBoxInBoundingBox(boxBb, nodeBb)) {\n box.push(node);\n }\n } else if (nodeBoxSelectMode === 'overlap') {\n if (boundingBoxesIntersect(boxBb, nodeBb)) {\n var nodeBodyBb = node.boundingBox({\n includeNodes: true,\n includeEdges: true,\n includeLabels: false,\n includeMainLabels: false,\n includeSourceLabels: false,\n includeTargetLabels: false\n });\n var nodeBodyCorners = [{\n x: nodeBodyBb.x1,\n y: nodeBodyBb.y1\n }, {\n x: nodeBodyBb.x2,\n y: nodeBodyBb.y1\n }, {\n x: nodeBodyBb.x2,\n y: nodeBodyBb.y2\n }, {\n x: nodeBodyBb.x1,\n y: nodeBodyBb.y2\n }];\n\n // if node body intersects, no need to check label\n if (satPolygonIntersection(nodeBodyCorners, selectionBox)) {\n box.push(node);\n } else {\n // only check label if node body didn't intersect\n var _rotatedLabelBox = getRotatedLabelBox(node);\n if (_rotatedLabelBox && satPolygonIntersection(_rotatedLabelBox, selectionBox)) {\n box.push(node);\n }\n }\n }\n }\n } else {\n var edge = ele;\n var _p = edge._private;\n var rs = _p.rscratch;\n var edgeBoxSelectMode = edge.pstyle('box-selection').strValue;\n if (edgeBoxSelectMode === 'none') {\n continue;\n }\n if (edgeBoxSelectMode === 'contain') {\n if (rs.startX != null && rs.startY != null && !inBoundingBox(boxBb, rs.startX, rs.startY)) {\n continue;\n }\n if (rs.endX != null && rs.endY != null && !inBoundingBox(boxBb, rs.endX, rs.endY)) {\n continue;\n }\n if (rs.edgeType === 'bezier' || rs.edgeType === 'multibezier' || rs.edgeType === 'self' || rs.edgeType === 'compound' || rs.edgeType === 'segments' || rs.edgeType === 'haystack') {\n var pts = _p.rstyle.bezierPts || _p.rstyle.linePts || _p.rstyle.haystackPts;\n var allInside = true;\n for (var i = 0; i < pts.length; i++) {\n if (!pointInBoundingBox(boxBb, pts[i])) {\n allInside = false;\n break;\n }\n }\n if (allInside) {\n box.push(edge);\n }\n } else if (rs.edgeType === 'straight') {\n box.push(edge);\n }\n } else if (edgeBoxSelectMode === 'overlap') {\n var _selected = false;\n\n // Check: either endpoint inside box\n if (rs.startX != null && rs.startY != null && rs.endX != null && rs.endY != null && (inBoundingBox(boxBb, rs.startX, rs.startY) || inBoundingBox(boxBb, rs.endX, rs.endY))) {\n box.push(edge);\n _selected = true;\n }\n\n // Haystack fallback (only check if not already selected)\n else if (!_selected && rs.edgeType === 'haystack') {\n var haystackPts = _p.rstyle.haystackPts;\n for (var _i = 0; _i < haystackPts.length; _i++) {\n if (pointInBoundingBox(boxBb, haystackPts[_i])) {\n box.push(edge);\n _selected = true;\n break;\n }\n }\n }\n\n // Segment intersection check (only if not already selected)\n if (!_selected) {\n var _pts = _p.rstyle.bezierPts || _p.rstyle.linePts || _p.rstyle.haystackPts;\n\n // straight edges\n if ((!_pts || _pts.length < 2) && rs.edgeType === 'straight') {\n if (rs.startX != null && rs.startY != null && rs.endX != null && rs.endY != null) {\n _pts = [{\n x: rs.startX,\n y: rs.startY\n }, {\n x: rs.endX,\n y: rs.endY\n }];\n }\n }\n if (!_pts || _pts.length < 2) continue;\n for (var _i2 = 0; _i2 < _pts.length - 1; _i2++) {\n var segStart = _pts[_i2];\n var segEnd = _pts[_i2 + 1];\n for (var b = 0; b < boxEdges.length; b++) {\n var _boxEdges$b = _slicedToArray(boxEdges[b], 2),\n boxStart = _boxEdges$b[0],\n boxEnd = _boxEdges$b[1];\n if (doLinesIntersect(segStart, segEnd, boxStart, boxEnd)) {\n box.push(edge);\n _selected = true;\n break;\n }\n }\n if (_selected) break;\n }\n }\n }\n }\n }\n return box;\n};\n\nvar BRp$d = {};\nBRp$d.calculateArrowAngles = function (edge) {\n var rs = edge._private.rscratch;\n var isHaystack = rs.edgeType === 'haystack';\n var isBezier = rs.edgeType === 'bezier';\n var isMultibezier = rs.edgeType === 'multibezier';\n var isSegments = rs.edgeType === 'segments';\n var isCompound = rs.edgeType === 'compound';\n var isSelf = rs.edgeType === 'self';\n\n // Displacement gives direction for arrowhead orientation\n var dispX, dispY;\n var startX, startY, endX, endY, midX, midY;\n if (isHaystack) {\n startX = rs.haystackPts[0];\n startY = rs.haystackPts[1];\n endX = rs.haystackPts[2];\n endY = rs.haystackPts[3];\n } else {\n startX = rs.arrowStartX;\n startY = rs.arrowStartY;\n endX = rs.arrowEndX;\n endY = rs.arrowEndY;\n }\n midX = rs.midX;\n midY = rs.midY;\n\n // source\n //\n\n if (isSegments) {\n dispX = startX - rs.segpts[0];\n dispY = startY - rs.segpts[1];\n } else if (isMultibezier || isCompound || isSelf || isBezier) {\n var pts = rs.allpts;\n var bX = qbezierAt(pts[0], pts[2], pts[4], 0.1);\n var bY = qbezierAt(pts[1], pts[3], pts[5], 0.1);\n dispX = startX - bX;\n dispY = startY - bY;\n } else {\n dispX = startX - midX;\n dispY = startY - midY;\n }\n rs.srcArrowAngle = getAngleFromDisp(dispX, dispY);\n\n // mid target\n //\n\n var midX = rs.midX;\n var midY = rs.midY;\n if (isHaystack) {\n midX = (startX + endX) / 2;\n midY = (startY + endY) / 2;\n }\n dispX = endX - startX;\n dispY = endY - startY;\n if (isSegments) {\n var pts = rs.allpts;\n if (pts.length / 2 % 2 === 0) {\n var i2 = pts.length / 2;\n var i1 = i2 - 2;\n dispX = pts[i2] - pts[i1];\n dispY = pts[i2 + 1] - pts[i1 + 1];\n } else if (rs.isRound) {\n dispX = rs.midVector[1];\n dispY = -rs.midVector[0];\n } else {\n var i2 = pts.length / 2 - 1;\n var i1 = i2 - 2;\n dispX = pts[i2] - pts[i1];\n dispY = pts[i2 + 1] - pts[i1 + 1];\n }\n } else if (isMultibezier || isCompound || isSelf) {\n var pts = rs.allpts;\n var cpts = rs.ctrlpts;\n var bp0x, bp0y;\n var bp1x, bp1y;\n if (cpts.length / 2 % 2 === 0) {\n var p0 = pts.length / 2 - 1; // startpt\n var ic = p0 + 2;\n var p1 = ic + 2;\n bp0x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.0);\n bp0y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.0);\n bp1x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.0001);\n bp1y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.0001);\n } else {\n var ic = pts.length / 2 - 1; // ctrpt\n var p0 = ic - 2; // startpt\n var p1 = ic + 2; // endpt\n\n bp0x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.4999);\n bp0y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.4999);\n bp1x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.5);\n bp1y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.5);\n }\n dispX = bp1x - bp0x;\n dispY = bp1y - bp0y;\n }\n rs.midtgtArrowAngle = getAngleFromDisp(dispX, dispY);\n rs.midDispX = dispX;\n rs.midDispY = dispY;\n\n // mid source\n //\n\n dispX *= -1;\n dispY *= -1;\n if (isSegments) {\n var pts = rs.allpts;\n if (pts.length / 2 % 2 === 0) ; else if (!rs.isRound) {\n var i2 = pts.length / 2 - 1;\n var i3 = i2 + 2;\n dispX = -(pts[i3] - pts[i2]);\n dispY = -(pts[i3 + 1] - pts[i2 + 1]);\n }\n }\n rs.midsrcArrowAngle = getAngleFromDisp(dispX, dispY);\n\n // target\n //\n\n if (isSegments) {\n dispX = endX - rs.segpts[rs.segpts.length - 2];\n dispY = endY - rs.segpts[rs.segpts.length - 1];\n } else if (isMultibezier || isCompound || isSelf || isBezier) {\n var pts = rs.allpts;\n var l = pts.length;\n var bX = qbezierAt(pts[l - 6], pts[l - 4], pts[l - 2], 0.9);\n var bY = qbezierAt(pts[l - 5], pts[l - 3], pts[l - 1], 0.9);\n dispX = endX - bX;\n dispY = endY - bY;\n } else {\n dispX = endX - midX;\n dispY = endY - midY;\n }\n rs.tgtArrowAngle = getAngleFromDisp(dispX, dispY);\n};\nBRp$d.getArrowWidth = BRp$d.getArrowHeight = function (edgeWidth, scale) {\n var cache = this.arrowWidthCache = this.arrowWidthCache || {};\n var cachedVal = cache[edgeWidth + ', ' + scale];\n if (cachedVal) {\n return cachedVal;\n }\n cachedVal = Math.max(Math.pow(edgeWidth * 13.37, 0.9), 29) * scale;\n cache[edgeWidth + ', ' + scale] = cachedVal;\n return cachedVal;\n};\n\n/**\n * Explained by Blindman67 at https://stackoverflow.com/a/44856925/11028828\n */\n\n// Declare reused variable to avoid reallocating variables every time the function is called\nvar x,\n y,\n v1 = {},\n v2 = {},\n sinA,\n sinA90,\n radDirection,\n drawDirection,\n angle,\n halfAngle,\n cRadius,\n lenOut,\n radius,\n limit;\nvar startX, startY, stopX, stopY;\nvar lastPoint;\n\n// convert 2 points into vector form, polar form, and normalised\nvar asVec = function asVec(p, pp, v) {\n v.x = pp.x - p.x;\n v.y = pp.y - p.y;\n v.len = Math.sqrt(v.x * v.x + v.y * v.y);\n v.nx = v.x / v.len;\n v.ny = v.y / v.len;\n v.ang = Math.atan2(v.ny, v.nx);\n};\nvar invertVec = function invertVec(originalV, invertedV) {\n invertedV.x = originalV.x * -1;\n invertedV.y = originalV.y * -1;\n invertedV.nx = originalV.nx * -1;\n invertedV.ny = originalV.ny * -1;\n invertedV.ang = originalV.ang > 0 ? -(Math.PI - originalV.ang) : Math.PI + originalV.ang;\n};\nvar calcCornerArc = function calcCornerArc(previousPoint, currentPoint, nextPoint, radiusMax, isArcRadius) {\n //-----------------------------------------\n // Part 1\n previousPoint !== lastPoint ? asVec(currentPoint, previousPoint, v1) : invertVec(v2, v1); // Avoid recalculating vec if it is the invert of the last one calculated\n asVec(currentPoint, nextPoint, v2);\n sinA = v1.nx * v2.ny - v1.ny * v2.nx;\n sinA90 = v1.nx * v2.nx - v1.ny * -v2.ny;\n angle = Math.asin(Math.max(-1, Math.min(1, sinA)));\n if (Math.abs(angle) < 1e-6) {\n x = currentPoint.x;\n y = currentPoint.y;\n cRadius = radius = 0;\n return;\n }\n //-----------------------------------------\n radDirection = 1;\n drawDirection = false;\n if (sinA90 < 0) {\n if (angle < 0) {\n angle = Math.PI + angle;\n } else {\n angle = Math.PI - angle;\n radDirection = -1;\n drawDirection = true;\n }\n } else {\n if (angle > 0) {\n radDirection = -1;\n drawDirection = true;\n }\n }\n if (currentPoint.radius !== undefined) {\n radius = currentPoint.radius;\n } else {\n radius = radiusMax;\n }\n //-----------------------------------------\n // Part 2\n halfAngle = angle / 2;\n //-----------------------------------------\n\n limit = Math.min(v1.len / 2, v2.len / 2);\n if (isArcRadius) {\n //-----------------------------------------\n // Part 3\n lenOut = Math.abs(Math.cos(halfAngle) * radius / Math.sin(halfAngle));\n\n //-----------------------------------------\n // Special part A\n if (lenOut > limit) {\n lenOut = limit;\n cRadius = Math.abs(lenOut * Math.sin(halfAngle) / Math.cos(halfAngle));\n } else {\n cRadius = radius;\n }\n } else {\n lenOut = Math.min(limit, radius);\n cRadius = Math.abs(lenOut * Math.sin(halfAngle) / Math.cos(halfAngle));\n }\n //-----------------------------------------\n\n //-----------------------------------------\n // Part 4\n stopX = currentPoint.x + v2.nx * lenOut;\n stopY = currentPoint.y + v2.ny * lenOut;\n //-----------------------------------------\n // Part 5\n x = stopX - v2.ny * cRadius * radDirection;\n y = stopY + v2.nx * cRadius * radDirection;\n //-----------------------------------------\n // Additional Part : calculate start point E\n startX = currentPoint.x + v1.nx * lenOut;\n startY = currentPoint.y + v1.ny * lenOut;\n\n // Save last point to avoid recalculating vector when not needed\n lastPoint = currentPoint;\n};\n\n/**\n * Draw corner provided by {@link getRoundCorner}\n *\n * @param ctx :CanvasRenderingContext2D\n * @param roundCorner {{cx:number, cy:number, radius:number, endAngle: number, startAngle: number, counterClockwise: boolean}}\n */\nfunction drawPreparedRoundCorner(ctx, roundCorner) {\n if (roundCorner.radius === 0) ctx.lineTo(roundCorner.cx, roundCorner.cy);else ctx.arc(roundCorner.cx, roundCorner.cy, roundCorner.radius, roundCorner.startAngle, roundCorner.endAngle, roundCorner.counterClockwise);\n}\n\n/**\n * Get round corner from a point and its previous and next neighbours in a path\n *\n * @param previousPoint {{x: number, y:number, radius: number?}}\n * @param currentPoint {{x: number, y:number, radius: number?}}\n * @param nextPoint {{x: number, y:number, radius: number?}}\n * @param radiusMax :number\n * @param isArcRadius :boolean\n * @return {{\n * cx:number, cy:number, radius:number,\n * startX:number, startY:number,\n * stopX:number, stopY: number,\n * endAngle: number, startAngle: number, counterClockwise: boolean\n * }}\n */\nfunction getRoundCorner(previousPoint, currentPoint, nextPoint, radiusMax) {\n var isArcRadius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n if (radiusMax === 0 || currentPoint.radius === 0) return {\n cx: currentPoint.x,\n cy: currentPoint.y,\n radius: 0,\n startX: currentPoint.x,\n startY: currentPoint.y,\n stopX: currentPoint.x,\n stopY: currentPoint.y,\n startAngle: undefined,\n endAngle: undefined,\n counterClockwise: undefined\n };\n calcCornerArc(previousPoint, currentPoint, nextPoint, radiusMax, isArcRadius);\n return {\n cx: x,\n cy: y,\n radius: cRadius,\n startX: startX,\n startY: startY,\n stopX: stopX,\n stopY: stopY,\n startAngle: v1.ang + Math.PI / 2 * radDirection,\n endAngle: v2.ang - Math.PI / 2 * radDirection,\n counterClockwise: drawDirection\n };\n}\n\nvar AVOID_IMPOSSIBLE_BEZIER_CONSTANT = 0.01;\nvar AVOID_IMPOSSIBLE_BEZIER_CONSTANT_L = Math.sqrt(2 * AVOID_IMPOSSIBLE_BEZIER_CONSTANT);\nvar BRp$c = {};\nBRp$c.findMidptPtsEtc = function (edge, pairInfo) {\n var posPts = pairInfo.posPts,\n intersectionPts = pairInfo.intersectionPts,\n vectorNormInverse = pairInfo.vectorNormInverse;\n var midptPts;\n\n // n.b. assumes all edges in bezier bundle have same endpoints specified\n var srcManEndpt = edge.pstyle('source-endpoint');\n var tgtManEndpt = edge.pstyle('target-endpoint');\n var haveManualEndPts = srcManEndpt.units != null && tgtManEndpt.units != null;\n var recalcVectorNormInverse = function recalcVectorNormInverse(x1, y1, x2, y2) {\n var dy = y2 - y1;\n var dx = x2 - x1;\n var l = Math.sqrt(dx * dx + dy * dy);\n return {\n x: -dy / l,\n y: dx / l\n };\n };\n var edgeDistances = edge.pstyle('edge-distances').value;\n switch (edgeDistances) {\n case 'node-position':\n midptPts = posPts;\n break;\n case 'intersection':\n midptPts = intersectionPts;\n break;\n case 'endpoints':\n {\n if (haveManualEndPts) {\n var _this$manualEndptToPx = this.manualEndptToPx(edge.source()[0], srcManEndpt),\n _this$manualEndptToPx2 = _slicedToArray(_this$manualEndptToPx, 2),\n x1 = _this$manualEndptToPx2[0],\n y1 = _this$manualEndptToPx2[1];\n var _this$manualEndptToPx3 = this.manualEndptToPx(edge.target()[0], tgtManEndpt),\n _this$manualEndptToPx4 = _slicedToArray(_this$manualEndptToPx3, 2),\n x2 = _this$manualEndptToPx4[0],\n y2 = _this$manualEndptToPx4[1];\n var endPts = {\n x1: x1,\n y1: y1,\n x2: x2,\n y2: y2\n };\n vectorNormInverse = recalcVectorNormInverse(x1, y1, x2, y2);\n midptPts = endPts;\n } else {\n warn(\"Edge \".concat(edge.id(), \" has edge-distances:endpoints specified without manual endpoints specified via source-endpoint and target-endpoint. Falling back on edge-distances:intersection (default).\"));\n midptPts = intersectionPts; // back to default\n }\n break;\n }\n }\n return {\n midptPts: midptPts,\n vectorNormInverse: vectorNormInverse\n };\n};\nBRp$c.findHaystackPoints = function (edges) {\n for (var i = 0; i < edges.length; i++) {\n var edge = edges[i];\n var _p = edge._private;\n var rs = _p.rscratch;\n if (!rs.haystack) {\n var angle = Math.random() * 2 * Math.PI;\n rs.source = {\n x: Math.cos(angle),\n y: Math.sin(angle)\n };\n angle = Math.random() * 2 * Math.PI;\n rs.target = {\n x: Math.cos(angle),\n y: Math.sin(angle)\n };\n }\n var src = _p.source;\n var tgt = _p.target;\n var srcPos = src.position();\n var tgtPos = tgt.position();\n var srcW = src.width();\n var tgtW = tgt.width();\n var srcH = src.height();\n var tgtH = tgt.height();\n var radius = edge.pstyle('haystack-radius').value;\n var halfRadius = radius / 2; // b/c have to half width/height\n\n rs.haystackPts = rs.allpts = [rs.source.x * srcW * halfRadius + srcPos.x, rs.source.y * srcH * halfRadius + srcPos.y, rs.target.x * tgtW * halfRadius + tgtPos.x, rs.target.y * tgtH * halfRadius + tgtPos.y];\n rs.midX = (rs.allpts[0] + rs.allpts[2]) / 2;\n rs.midY = (rs.allpts[1] + rs.allpts[3]) / 2;\n\n // always override as haystack in case set to different type previously\n rs.edgeType = 'haystack';\n rs.haystack = true;\n this.storeEdgeProjections(edge);\n this.calculateArrowAngles(edge);\n this.recalculateEdgeLabelProjections(edge);\n this.calculateLabelAngles(edge);\n }\n};\nBRp$c.findSegmentsPoints = function (edge, pairInfo) {\n // Segments (multiple straight lines)\n\n var rs = edge._private.rscratch;\n var segmentWs = edge.pstyle('segment-weights');\n var segmentDs = edge.pstyle('segment-distances');\n var segmentRs = edge.pstyle('segment-radii');\n var segmentTs = edge.pstyle('radius-type');\n var segmentsN = Math.min(segmentWs.pfValue.length, segmentDs.pfValue.length);\n var lastRadius = segmentRs.pfValue[segmentRs.pfValue.length - 1];\n var lastRadiusType = segmentTs.pfValue[segmentTs.pfValue.length - 1];\n rs.edgeType = 'segments';\n rs.segpts = [];\n rs.radii = [];\n rs.isArcRadius = [];\n for (var s = 0; s < segmentsN; s++) {\n var w = segmentWs.pfValue[s];\n var d = segmentDs.pfValue[s];\n var w1 = 1 - w;\n var w2 = w;\n var _this$findMidptPtsEtc = this.findMidptPtsEtc(edge, pairInfo),\n midptPts = _this$findMidptPtsEtc.midptPts,\n vectorNormInverse = _this$findMidptPtsEtc.vectorNormInverse;\n var adjustedMidpt = {\n x: midptPts.x1 * w1 + midptPts.x2 * w2,\n y: midptPts.y1 * w1 + midptPts.y2 * w2\n };\n rs.segpts.push(adjustedMidpt.x + vectorNormInverse.x * d, adjustedMidpt.y + vectorNormInverse.y * d);\n rs.radii.push(segmentRs.pfValue[s] !== undefined ? segmentRs.pfValue[s] : lastRadius);\n rs.isArcRadius.push((segmentTs.pfValue[s] !== undefined ? segmentTs.pfValue[s] : lastRadiusType) === 'arc-radius');\n }\n};\nBRp$c.findLoopPoints = function (edge, pairInfo, i, edgeIsUnbundled) {\n // Self-edge\n\n var rs = edge._private.rscratch;\n var dirCounts = pairInfo.dirCounts,\n srcPos = pairInfo.srcPos;\n var ctrlptDists = edge.pstyle('control-point-distances');\n var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;\n var loopDir = edge.pstyle('loop-direction').pfValue;\n var loopSwp = edge.pstyle('loop-sweep').pfValue;\n var stepSize = edge.pstyle('control-point-step-size').pfValue;\n rs.edgeType = 'self';\n var j = i;\n var loopDist = stepSize;\n if (edgeIsUnbundled) {\n j = 0;\n loopDist = ctrlptDist;\n }\n var loopAngle = loopDir - Math.PI / 2;\n var outAngle = loopAngle - loopSwp / 2;\n var inAngle = loopAngle + loopSwp / 2;\n\n // increase by step size for overlapping loops, keyed on direction and sweep values\n var dc = String(loopDir + '_' + loopSwp);\n j = dirCounts[dc] === undefined ? dirCounts[dc] = 0 : ++dirCounts[dc];\n rs.ctrlpts = [srcPos.x + Math.cos(outAngle) * 1.4 * loopDist * (j / 3 + 1), srcPos.y + Math.sin(outAngle) * 1.4 * loopDist * (j / 3 + 1), srcPos.x + Math.cos(inAngle) * 1.4 * loopDist * (j / 3 + 1), srcPos.y + Math.sin(inAngle) * 1.4 * loopDist * (j / 3 + 1)];\n};\nBRp$c.findCompoundLoopPoints = function (edge, pairInfo, i, edgeIsUnbundled) {\n // Compound edge\n\n var rs = edge._private.rscratch;\n rs.edgeType = 'compound';\n var srcPos = pairInfo.srcPos,\n tgtPos = pairInfo.tgtPos,\n srcW = pairInfo.srcW,\n srcH = pairInfo.srcH,\n tgtW = pairInfo.tgtW,\n tgtH = pairInfo.tgtH;\n var stepSize = edge.pstyle('control-point-step-size').pfValue;\n var ctrlptDists = edge.pstyle('control-point-distances');\n var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;\n var j = i;\n var loopDist = stepSize;\n if (edgeIsUnbundled) {\n j = 0;\n loopDist = ctrlptDist;\n }\n var loopW = 50;\n var loopaPos = {\n x: srcPos.x - srcW / 2,\n y: srcPos.y - srcH / 2\n };\n var loopbPos = {\n x: tgtPos.x - tgtW / 2,\n y: tgtPos.y - tgtH / 2\n };\n var loopPos = {\n x: Math.min(loopaPos.x, loopbPos.x),\n y: Math.min(loopaPos.y, loopbPos.y)\n };\n\n // avoids cases with impossible beziers\n var minCompoundStretch = 0.5;\n var compoundStretchA = Math.max(minCompoundStretch, Math.log(srcW * AVOID_IMPOSSIBLE_BEZIER_CONSTANT));\n var compoundStretchB = Math.max(minCompoundStretch, Math.log(tgtW * AVOID_IMPOSSIBLE_BEZIER_CONSTANT));\n rs.ctrlpts = [loopPos.x, loopPos.y - (1 + Math.pow(loopW, 1.12) / 100) * loopDist * (j / 3 + 1) * compoundStretchA, loopPos.x - (1 + Math.pow(loopW, 1.12) / 100) * loopDist * (j / 3 + 1) * compoundStretchB, loopPos.y];\n};\nBRp$c.findStraightEdgePoints = function (edge) {\n // Straight edge within bundle\n\n edge._private.rscratch.edgeType = 'straight';\n};\nBRp$c.findBezierPoints = function (edge, pairInfo, i, edgeIsUnbundled, edgeIsSwapped) {\n var rs = edge._private.rscratch;\n var stepSize = edge.pstyle('control-point-step-size').pfValue;\n var ctrlptDists = edge.pstyle('control-point-distances');\n var ctrlptWs = edge.pstyle('control-point-weights');\n var bezierN = ctrlptDists && ctrlptWs ? Math.min(ctrlptDists.value.length, ctrlptWs.value.length) : 1;\n var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;\n var ctrlptWeight = ctrlptWs.value[0];\n\n // (Multi)bezier\n\n var multi = edgeIsUnbundled;\n rs.edgeType = multi ? 'multibezier' : 'bezier';\n rs.ctrlpts = [];\n for (var b = 0; b < bezierN; b++) {\n var normctrlptDist = (0.5 - pairInfo.eles.length / 2 + i) * stepSize * (edgeIsSwapped ? -1 : 1);\n var manctrlptDist = undefined;\n var sign = signum(normctrlptDist);\n if (multi) {\n ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[b] : stepSize; // fall back on step size\n ctrlptWeight = ctrlptWs.value[b];\n }\n if (edgeIsUnbundled) {\n // multi or single unbundled\n manctrlptDist = ctrlptDist;\n } else {\n manctrlptDist = ctrlptDist !== undefined ? sign * ctrlptDist : undefined;\n }\n var distanceFromMidpoint = manctrlptDist !== undefined ? manctrlptDist : normctrlptDist;\n var w1 = 1 - ctrlptWeight;\n var w2 = ctrlptWeight;\n var _this$findMidptPtsEtc2 = this.findMidptPtsEtc(edge, pairInfo),\n midptPts = _this$findMidptPtsEtc2.midptPts,\n vectorNormInverse = _this$findMidptPtsEtc2.vectorNormInverse;\n var adjustedMidpt = {\n x: midptPts.x1 * w1 + midptPts.x2 * w2,\n y: midptPts.y1 * w1 + midptPts.y2 * w2\n };\n rs.ctrlpts.push(adjustedMidpt.x + vectorNormInverse.x * distanceFromMidpoint, adjustedMidpt.y + vectorNormInverse.y * distanceFromMidpoint);\n }\n};\nBRp$c.findTaxiPoints = function (edge, pairInfo) {\n // Taxicab geometry with two turns maximum\n\n var rs = edge._private.rscratch;\n rs.edgeType = 'segments';\n var VERTICAL = 'vertical';\n var HORIZONTAL = 'horizontal';\n var LEFTWARD = 'leftward';\n var RIGHTWARD = 'rightward';\n var DOWNWARD = 'downward';\n var UPWARD = 'upward';\n var AUTO = 'auto';\n var posPts = pairInfo.posPts,\n srcW = pairInfo.srcW,\n srcH = pairInfo.srcH,\n tgtW = pairInfo.tgtW,\n tgtH = pairInfo.tgtH;\n var edgeDistances = edge.pstyle('edge-distances').value;\n var dIncludesNodeBody = edgeDistances !== 'node-position';\n var taxiDir = edge.pstyle('taxi-direction').value;\n var rawTaxiDir = taxiDir; // unprocessed value\n var taxiTurn = edge.pstyle('taxi-turn');\n var turnIsPercent = taxiTurn.units === '%';\n var taxiTurnPfVal = taxiTurn.pfValue;\n var turnIsNegative = taxiTurnPfVal < 0; // i.e. from target side\n var minD = edge.pstyle('taxi-turn-min-distance').pfValue;\n var dw = dIncludesNodeBody ? (srcW + tgtW) / 2 : 0;\n var dh = dIncludesNodeBody ? (srcH + tgtH) / 2 : 0;\n var pdx = posPts.x2 - posPts.x1;\n var pdy = posPts.y2 - posPts.y1;\n\n // take away the effective w/h from the magnitude of the delta value\n var subDWH = function subDWH(dxy, dwh) {\n if (dxy > 0) {\n return Math.max(dxy - dwh, 0);\n } else {\n return Math.min(dxy + dwh, 0);\n }\n };\n var dx = subDWH(pdx, dw);\n var dy = subDWH(pdy, dh);\n var isExplicitDir = false;\n if (rawTaxiDir === AUTO) {\n taxiDir = Math.abs(dx) > Math.abs(dy) ? HORIZONTAL : VERTICAL;\n } else if (rawTaxiDir === UPWARD || rawTaxiDir === DOWNWARD) {\n taxiDir = VERTICAL;\n isExplicitDir = true;\n } else if (rawTaxiDir === LEFTWARD || rawTaxiDir === RIGHTWARD) {\n taxiDir = HORIZONTAL;\n isExplicitDir = true;\n }\n var isVert = taxiDir === VERTICAL;\n var l = isVert ? dy : dx;\n var pl = isVert ? pdy : pdx;\n var sgnL = signum(pl);\n var forcedDir = false;\n if (!(isExplicitDir && (turnIsPercent || turnIsNegative)) // forcing in this case would cause weird growing in the opposite direction\n && (rawTaxiDir === DOWNWARD && pl < 0 || rawTaxiDir === UPWARD && pl > 0 || rawTaxiDir === LEFTWARD && pl > 0 || rawTaxiDir === RIGHTWARD && pl < 0)) {\n sgnL *= -1;\n l = sgnL * Math.abs(l);\n forcedDir = true;\n }\n var d;\n if (turnIsPercent) {\n var p = taxiTurnPfVal < 0 ? 1 + taxiTurnPfVal : taxiTurnPfVal;\n d = p * l;\n } else {\n var k = taxiTurnPfVal < 0 ? l : 0;\n d = k + taxiTurnPfVal * sgnL;\n }\n var getIsTooClose = function getIsTooClose(d) {\n return Math.abs(d) < minD || Math.abs(d) >= Math.abs(l);\n };\n var isTooCloseSrc = getIsTooClose(d);\n var isTooCloseTgt = getIsTooClose(Math.abs(l) - Math.abs(d));\n var isTooClose = isTooCloseSrc || isTooCloseTgt;\n if (isTooClose && !forcedDir) {\n // non-ideal routing\n if (isVert) {\n // vertical fallbacks\n var lShapeInsideSrc = Math.abs(pl) <= srcH / 2;\n var lShapeInsideTgt = Math.abs(pdx) <= tgtW / 2;\n if (lShapeInsideSrc) {\n // horizontal Z-shape (direction not respected)\n var x = (posPts.x1 + posPts.x2) / 2;\n var y1 = posPts.y1,\n y2 = posPts.y2;\n rs.segpts = [x, y1, x, y2];\n } else if (lShapeInsideTgt) {\n // vertical Z-shape (distance not respected)\n var y = (posPts.y1 + posPts.y2) / 2;\n var x1 = posPts.x1,\n x2 = posPts.x2;\n rs.segpts = [x1, y, x2, y];\n } else {\n // L-shape fallback (turn distance not respected, but works well with tree siblings)\n rs.segpts = [posPts.x1, posPts.y2];\n }\n } else {\n // horizontal fallbacks\n var _lShapeInsideSrc = Math.abs(pl) <= srcW / 2;\n var _lShapeInsideTgt = Math.abs(pdy) <= tgtH / 2;\n if (_lShapeInsideSrc) {\n // vertical Z-shape (direction not respected)\n var _y = (posPts.y1 + posPts.y2) / 2;\n var _x = posPts.x1,\n _x2 = posPts.x2;\n rs.segpts = [_x, _y, _x2, _y];\n } else if (_lShapeInsideTgt) {\n // horizontal Z-shape (turn distance not respected)\n var _x3 = (posPts.x1 + posPts.x2) / 2;\n var _y2 = posPts.y1,\n _y3 = posPts.y2;\n rs.segpts = [_x3, _y2, _x3, _y3];\n } else {\n // L-shape (turn distance not respected, but works well for tree siblings)\n rs.segpts = [posPts.x2, posPts.y1];\n }\n }\n } else {\n // ideal routing\n if (isVert) {\n var _y4 = posPts.y1 + d + (dIncludesNodeBody ? srcH / 2 * sgnL : 0);\n var _x4 = posPts.x1,\n _x5 = posPts.x2;\n rs.segpts = [_x4, _y4, _x5, _y4];\n } else {\n // horizontal\n var _x6 = posPts.x1 + d + (dIncludesNodeBody ? srcW / 2 * sgnL : 0);\n var _y5 = posPts.y1,\n _y6 = posPts.y2;\n rs.segpts = [_x6, _y5, _x6, _y6];\n }\n }\n if (rs.isRound) {\n var radius = edge.pstyle('taxi-radius').value;\n var isArcRadius = edge.pstyle('radius-type').value[0] === 'arc-radius';\n rs.radii = new Array(rs.segpts.length / 2).fill(radius);\n rs.isArcRadius = new Array(rs.segpts.length / 2).fill(isArcRadius);\n }\n};\nBRp$c.tryToCorrectInvalidPoints = function (edge, pairInfo) {\n var rs = edge._private.rscratch;\n\n // can only correct beziers for now...\n if (rs.edgeType === 'bezier') {\n var srcPos = pairInfo.srcPos,\n tgtPos = pairInfo.tgtPos,\n srcW = pairInfo.srcW,\n srcH = pairInfo.srcH,\n tgtW = pairInfo.tgtW,\n tgtH = pairInfo.tgtH,\n srcShape = pairInfo.srcShape,\n tgtShape = pairInfo.tgtShape,\n srcCornerRadius = pairInfo.srcCornerRadius,\n tgtCornerRadius = pairInfo.tgtCornerRadius,\n srcRs = pairInfo.srcRs,\n tgtRs = pairInfo.tgtRs;\n var badStart = !number$1(rs.startX) || !number$1(rs.startY);\n var badAStart = !number$1(rs.arrowStartX) || !number$1(rs.arrowStartY);\n var badEnd = !number$1(rs.endX) || !number$1(rs.endY);\n var badAEnd = !number$1(rs.arrowEndX) || !number$1(rs.arrowEndY);\n var minCpADistFactor = 3;\n var arrowW = this.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.arrowShapeWidth;\n var minCpADist = minCpADistFactor * arrowW;\n var startACpDist = dist({\n x: rs.ctrlpts[0],\n y: rs.ctrlpts[1]\n }, {\n x: rs.startX,\n y: rs.startY\n });\n var closeStartACp = startACpDist < minCpADist;\n var endACpDist = dist({\n x: rs.ctrlpts[0],\n y: rs.ctrlpts[1]\n }, {\n x: rs.endX,\n y: rs.endY\n });\n var closeEndACp = endACpDist < minCpADist;\n var overlapping = false;\n if (badStart || badAStart || closeStartACp) {\n overlapping = true;\n\n // project control point along line from src centre to outside the src shape\n // (otherwise intersection will yield nothing)\n var cpD = {\n // delta\n x: rs.ctrlpts[0] - srcPos.x,\n y: rs.ctrlpts[1] - srcPos.y\n };\n var cpL = Math.sqrt(cpD.x * cpD.x + cpD.y * cpD.y); // length of line\n var cpM = {\n // normalised delta\n x: cpD.x / cpL,\n y: cpD.y / cpL\n };\n var radius = Math.max(srcW, srcH);\n var cpProj = {\n // *2 radius guarantees outside shape\n x: rs.ctrlpts[0] + cpM.x * 2 * radius,\n y: rs.ctrlpts[1] + cpM.y * 2 * radius\n };\n var srcCtrlPtIntn = srcShape.intersectLine(srcPos.x, srcPos.y, srcW, srcH, cpProj.x, cpProj.y, 0, srcCornerRadius, srcRs);\n if (closeStartACp) {\n rs.ctrlpts[0] = rs.ctrlpts[0] + cpM.x * (minCpADist - startACpDist);\n rs.ctrlpts[1] = rs.ctrlpts[1] + cpM.y * (minCpADist - startACpDist);\n } else {\n rs.ctrlpts[0] = srcCtrlPtIntn[0] + cpM.x * minCpADist;\n rs.ctrlpts[1] = srcCtrlPtIntn[1] + cpM.y * minCpADist;\n }\n }\n if (badEnd || badAEnd || closeEndACp) {\n overlapping = true;\n\n // project control point along line from tgt centre to outside the tgt shape\n // (otherwise intersection will yield nothing)\n var _cpD = {\n // delta\n x: rs.ctrlpts[0] - tgtPos.x,\n y: rs.ctrlpts[1] - tgtPos.y\n };\n var _cpL = Math.sqrt(_cpD.x * _cpD.x + _cpD.y * _cpD.y); // length of line\n var _cpM = {\n // normalised delta\n x: _cpD.x / _cpL,\n y: _cpD.y / _cpL\n };\n var _radius = Math.max(srcW, srcH);\n var _cpProj = {\n // *2 radius guarantees outside shape\n x: rs.ctrlpts[0] + _cpM.x * 2 * _radius,\n y: rs.ctrlpts[1] + _cpM.y * 2 * _radius\n };\n var tgtCtrlPtIntn = tgtShape.intersectLine(tgtPos.x, tgtPos.y, tgtW, tgtH, _cpProj.x, _cpProj.y, 0, tgtCornerRadius, tgtRs);\n if (closeEndACp) {\n rs.ctrlpts[0] = rs.ctrlpts[0] + _cpM.x * (minCpADist - endACpDist);\n rs.ctrlpts[1] = rs.ctrlpts[1] + _cpM.y * (minCpADist - endACpDist);\n } else {\n rs.ctrlpts[0] = tgtCtrlPtIntn[0] + _cpM.x * minCpADist;\n rs.ctrlpts[1] = tgtCtrlPtIntn[1] + _cpM.y * minCpADist;\n }\n }\n if (overlapping) {\n // recalc endpts\n this.findEndpoints(edge);\n }\n }\n};\nBRp$c.storeAllpts = function (edge) {\n var rs = edge._private.rscratch;\n if (rs.edgeType === 'multibezier' || rs.edgeType === 'bezier' || rs.edgeType === 'self' || rs.edgeType === 'compound') {\n rs.allpts = [];\n rs.allpts.push(rs.startX, rs.startY);\n for (var b = 0; b + 1 < rs.ctrlpts.length; b += 2) {\n // ctrl pt itself\n rs.allpts.push(rs.ctrlpts[b], rs.ctrlpts[b + 1]);\n\n // the midpt between ctrlpts as intermediate destination pts\n if (b + 3 < rs.ctrlpts.length) {\n rs.allpts.push((rs.ctrlpts[b] + rs.ctrlpts[b + 2]) / 2, (rs.ctrlpts[b + 1] + rs.ctrlpts[b + 3]) / 2);\n }\n }\n rs.allpts.push(rs.endX, rs.endY);\n var m, mt;\n if (rs.ctrlpts.length / 2 % 2 === 0) {\n m = rs.allpts.length / 2 - 1;\n rs.midX = rs.allpts[m];\n rs.midY = rs.allpts[m + 1];\n } else {\n m = rs.allpts.length / 2 - 3;\n mt = 0.5;\n rs.midX = qbezierAt(rs.allpts[m], rs.allpts[m + 2], rs.allpts[m + 4], mt);\n rs.midY = qbezierAt(rs.allpts[m + 1], rs.allpts[m + 3], rs.allpts[m + 5], mt);\n }\n } else if (rs.edgeType === 'straight') {\n // need to calc these after endpts\n rs.allpts = [rs.startX, rs.startY, rs.endX, rs.endY];\n\n // default midpt for labels etc\n rs.midX = (rs.startX + rs.endX + rs.arrowStartX + rs.arrowEndX) / 4;\n rs.midY = (rs.startY + rs.endY + rs.arrowStartY + rs.arrowEndY) / 4;\n } else if (rs.edgeType === 'segments') {\n rs.allpts = [];\n rs.allpts.push(rs.startX, rs.startY);\n rs.allpts.push.apply(rs.allpts, rs.segpts);\n rs.allpts.push(rs.endX, rs.endY);\n if (rs.isRound) {\n rs.roundCorners = [];\n for (var i = 2; i + 3 < rs.allpts.length; i += 2) {\n var radius = rs.radii[i / 2 - 1];\n var isArcRadius = rs.isArcRadius[i / 2 - 1];\n rs.roundCorners.push(getRoundCorner({\n x: rs.allpts[i - 2],\n y: rs.allpts[i - 1]\n }, {\n x: rs.allpts[i],\n y: rs.allpts[i + 1],\n radius: radius\n }, {\n x: rs.allpts[i + 2],\n y: rs.allpts[i + 3]\n }, radius, isArcRadius));\n }\n }\n if (rs.segpts.length % 4 === 0) {\n var i2 = rs.segpts.length / 2;\n var i1 = i2 - 2;\n rs.midX = (rs.segpts[i1] + rs.segpts[i2]) / 2;\n rs.midY = (rs.segpts[i1 + 1] + rs.segpts[i2 + 1]) / 2;\n } else {\n var _i = rs.segpts.length / 2 - 1;\n if (!rs.isRound) {\n rs.midX = rs.segpts[_i];\n rs.midY = rs.segpts[_i + 1];\n } else {\n var point = {\n x: rs.segpts[_i],\n y: rs.segpts[_i + 1]\n };\n var corner = rs.roundCorners[_i / 2];\n if (corner.radius === 0) {\n // On collinear points\n var nextPoint = {\n x: rs.segpts[_i + 2],\n y: rs.segpts[_i + 3]\n };\n rs.midX = point.x;\n rs.midY = point.y;\n rs.midVector = [point.y - nextPoint.y, nextPoint.x - point.x];\n } else {\n // On rounded points\n var v = [point.x - corner.cx, point.y - corner.cy];\n var factor = corner.radius / Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2));\n v = v.map(function (c) {\n return c * factor;\n });\n rs.midX = corner.cx + v[0];\n rs.midY = corner.cy + v[1];\n rs.midVector = v;\n }\n }\n }\n }\n};\nBRp$c.checkForInvalidEdgeWarning = function (edge) {\n var rs = edge[0]._private.rscratch;\n if (rs.nodesOverlap || number$1(rs.startX) && number$1(rs.startY) && number$1(rs.endX) && number$1(rs.endY)) {\n rs.loggedErr = false;\n } else {\n if (!rs.loggedErr) {\n rs.loggedErr = true;\n warn('Edge `' + edge.id() + '` has invalid endpoints and so it is impossible to draw. Adjust your edge style (e.g. control points) accordingly or use an alternative edge type. This is expected behaviour when the source node and the target node overlap.');\n }\n }\n};\nBRp$c.findEdgeControlPoints = function (edges) {\n var _this = this;\n if (!edges || edges.length === 0) {\n return;\n }\n var r = this;\n var cy = r.cy;\n var hasCompounds = cy.hasCompoundNodes();\n var hashTable = new Map$1();\n var getKey = function getKey(pairId, edgeIsUnbundled) {\n return [].concat(_toConsumableArray(pairId), [edgeIsUnbundled ? 1 : 0]).join('-');\n };\n var pairIds = [];\n var haystackEdges = [];\n\n // create a table of edge (src, tgt) => list of edges between them\n for (var i = 0; i < edges.length; i++) {\n var edge = edges[i];\n var _p = edge._private;\n var curveStyle = edge.pstyle('curve-style').value;\n\n // ignore edges who are not to be displayed\n // they shouldn't take up space\n if (edge.removed() || !edge.takesUpSpace()) {\n continue;\n }\n if (curveStyle === 'haystack') {\n haystackEdges.push(edge);\n continue;\n }\n var edgeIsUnbundled = curveStyle === 'unbundled-bezier' || endsWith(curveStyle, 'segments') || curveStyle === 'straight' || curveStyle === 'straight-triangle' || endsWith(curveStyle, 'taxi');\n var edgeIsBezier = curveStyle === 'unbundled-bezier' || curveStyle === 'bezier';\n var src = _p.source;\n var tgt = _p.target;\n var srcIndex = src.poolIndex();\n var tgtIndex = tgt.poolIndex();\n var pairId = [srcIndex, tgtIndex].sort();\n var key = getKey(pairId, edgeIsUnbundled);\n var tableEntry = hashTable.get(key);\n if (tableEntry == null) {\n tableEntry = {\n eles: []\n };\n pairIds.push({\n pairId: pairId,\n edgeIsUnbundled: edgeIsUnbundled\n });\n hashTable.set(key, tableEntry);\n }\n tableEntry.eles.push(edge);\n if (edgeIsUnbundled) {\n tableEntry.hasUnbundled = true;\n }\n if (edgeIsBezier) {\n tableEntry.hasBezier = true;\n }\n }\n\n // for each pair (src, tgt), create the ctrl pts\n // Nested for loop is OK; total number of iterations for both loops = edgeCount\n var _loop = function _loop() {\n var _pairIds$p = pairIds[p],\n pairId = _pairIds$p.pairId,\n edgeIsUnbundled = _pairIds$p.edgeIsUnbundled;\n var key = getKey(pairId, edgeIsUnbundled);\n var pairInfo = hashTable.get(key);\n var swappedpairInfo;\n if (!pairInfo.hasUnbundled) {\n var pllEdges = pairInfo.eles[0].parallelEdges().filter(function (e) {\n return e.isBundledBezier();\n });\n clearArray(pairInfo.eles);\n pllEdges.forEach(function (edge) {\n return pairInfo.eles.push(edge);\n });\n\n // for each pair id, the edges should be sorted by index\n pairInfo.eles.sort(function (edge1, edge2) {\n return edge1.poolIndex() - edge2.poolIndex();\n });\n }\n var firstEdge = pairInfo.eles[0];\n var src = firstEdge.source();\n var tgt = firstEdge.target();\n\n // make sure src/tgt distinction is consistent w.r.t. pairId\n if (src.poolIndex() > tgt.poolIndex()) {\n var temp = src;\n src = tgt;\n tgt = temp;\n }\n var srcPos = pairInfo.srcPos = src.position();\n var tgtPos = pairInfo.tgtPos = tgt.position();\n var srcW = pairInfo.srcW = src.outerWidth();\n var srcH = pairInfo.srcH = src.outerHeight();\n var tgtW = pairInfo.tgtW = tgt.outerWidth();\n var tgtH = pairInfo.tgtH = tgt.outerHeight();\n var srcShape = pairInfo.srcShape = r.nodeShapes[_this.getNodeShape(src)];\n var tgtShape = pairInfo.tgtShape = r.nodeShapes[_this.getNodeShape(tgt)];\n var srcCornerRadius = pairInfo.srcCornerRadius = src.pstyle('corner-radius').value === 'auto' ? 'auto' : src.pstyle('corner-radius').pfValue;\n var tgtCornerRadius = pairInfo.tgtCornerRadius = tgt.pstyle('corner-radius').value === 'auto' ? 'auto' : tgt.pstyle('corner-radius').pfValue;\n var tgtRs = pairInfo.tgtRs = tgt._private.rscratch;\n var srcRs = pairInfo.srcRs = src._private.rscratch;\n pairInfo.dirCounts = {\n 'north': 0,\n 'west': 0,\n 'south': 0,\n 'east': 0,\n 'northwest': 0,\n 'southwest': 0,\n 'northeast': 0,\n 'southeast': 0\n };\n for (var _i2 = 0; _i2 < pairInfo.eles.length; _i2++) {\n var _edge = pairInfo.eles[_i2];\n var rs = _edge[0]._private.rscratch;\n var _curveStyle = _edge.pstyle('curve-style').value;\n var _edgeIsUnbundled = _curveStyle === 'unbundled-bezier' || endsWith(_curveStyle, 'segments') || endsWith(_curveStyle, 'taxi');\n\n // whether the normalised pair order is the reverse of the edge's src-tgt order\n var edgeIsSwapped = !src.same(_edge.source());\n if (!pairInfo.calculatedIntersection && src !== tgt && (pairInfo.hasBezier || pairInfo.hasUnbundled)) {\n pairInfo.calculatedIntersection = true;\n\n // pt outside src shape to calc distance/displacement from src to tgt\n var srcOutside = srcShape.intersectLine(srcPos.x, srcPos.y, srcW, srcH, tgtPos.x, tgtPos.y, 0, srcCornerRadius, srcRs);\n var srcIntn = pairInfo.srcIntn = srcOutside;\n\n // pt outside tgt shape to calc distance/displacement from src to tgt\n var tgtOutside = tgtShape.intersectLine(tgtPos.x, tgtPos.y, tgtW, tgtH, srcPos.x, srcPos.y, 0, tgtCornerRadius, tgtRs);\n var tgtIntn = pairInfo.tgtIntn = tgtOutside;\n var intersectionPts = pairInfo.intersectionPts = {\n x1: srcOutside[0],\n x2: tgtOutside[0],\n y1: srcOutside[1],\n y2: tgtOutside[1]\n };\n var posPts = pairInfo.posPts = {\n x1: srcPos.x,\n x2: tgtPos.x,\n y1: srcPos.y,\n y2: tgtPos.y\n };\n var dy = tgtOutside[1] - srcOutside[1];\n var dx = tgtOutside[0] - srcOutside[0];\n var l = Math.sqrt(dx * dx + dy * dy);\n if (number$1(l) && l >= AVOID_IMPOSSIBLE_BEZIER_CONSTANT_L) ; else {\n l = Math.sqrt(Math.max(dx * dx, AVOID_IMPOSSIBLE_BEZIER_CONSTANT) + Math.max(dy * dy, AVOID_IMPOSSIBLE_BEZIER_CONSTANT));\n }\n var vector = pairInfo.vector = {\n x: dx,\n y: dy\n };\n var vectorNorm = pairInfo.vectorNorm = {\n x: vector.x / l,\n y: vector.y / l\n };\n var vectorNormInverse = {\n x: -vectorNorm.y,\n y: vectorNorm.x\n };\n\n // if node shapes overlap, then no ctrl pts to draw\n pairInfo.nodesOverlap = !number$1(l) || tgtShape.checkPoint(srcOutside[0], srcOutside[1], 0, tgtW, tgtH, tgtPos.x, tgtPos.y, tgtCornerRadius, tgtRs) || srcShape.checkPoint(tgtOutside[0], tgtOutside[1], 0, srcW, srcH, srcPos.x, srcPos.y, srcCornerRadius, srcRs);\n pairInfo.vectorNormInverse = vectorNormInverse;\n swappedpairInfo = {\n nodesOverlap: pairInfo.nodesOverlap,\n dirCounts: pairInfo.dirCounts,\n calculatedIntersection: true,\n hasBezier: pairInfo.hasBezier,\n hasUnbundled: pairInfo.hasUnbundled,\n eles: pairInfo.eles,\n srcPos: tgtPos,\n srcRs: tgtRs,\n tgtPos: srcPos,\n tgtRs: srcRs,\n srcW: tgtW,\n srcH: tgtH,\n tgtW: srcW,\n tgtH: srcH,\n srcIntn: tgtIntn,\n tgtIntn: srcIntn,\n srcShape: tgtShape,\n tgtShape: srcShape,\n posPts: {\n x1: posPts.x2,\n y1: posPts.y2,\n x2: posPts.x1,\n y2: posPts.y1\n },\n intersectionPts: {\n x1: intersectionPts.x2,\n y1: intersectionPts.y2,\n x2: intersectionPts.x1,\n y2: intersectionPts.y1\n },\n vector: {\n x: -vector.x,\n y: -vector.y\n },\n vectorNorm: {\n x: -vectorNorm.x,\n y: -vectorNorm.y\n },\n vectorNormInverse: {\n x: -vectorNormInverse.x,\n y: -vectorNormInverse.y\n }\n };\n }\n var passedPairInfo = edgeIsSwapped ? swappedpairInfo : pairInfo;\n rs.nodesOverlap = passedPairInfo.nodesOverlap;\n rs.srcIntn = passedPairInfo.srcIntn;\n rs.tgtIntn = passedPairInfo.tgtIntn;\n rs.isRound = _curveStyle.startsWith('round');\n if (hasCompounds && (src.isParent() || src.isChild() || tgt.isParent() || tgt.isChild()) && (src.parents().anySame(tgt) || tgt.parents().anySame(src) || src.same(tgt) && src.isParent())) {\n _this.findCompoundLoopPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled);\n } else if (src === tgt) {\n _this.findLoopPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled);\n } else if (_curveStyle.endsWith('segments')) {\n _this.findSegmentsPoints(_edge, passedPairInfo);\n } else if (_curveStyle.endsWith('taxi')) {\n _this.findTaxiPoints(_edge, passedPairInfo);\n } else if (_curveStyle === 'straight' || !_edgeIsUnbundled && pairInfo.eles.length % 2 === 1 && _i2 === Math.floor(pairInfo.eles.length / 2)) {\n _this.findStraightEdgePoints(_edge);\n } else {\n _this.findBezierPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled, edgeIsSwapped);\n }\n _this.findEndpoints(_edge);\n _this.tryToCorrectInvalidPoints(_edge, passedPairInfo);\n _this.checkForInvalidEdgeWarning(_edge);\n _this.storeAllpts(_edge);\n _this.storeEdgeProjections(_edge);\n _this.calculateArrowAngles(_edge);\n _this.recalculateEdgeLabelProjections(_edge);\n _this.calculateLabelAngles(_edge);\n } // for pair edges\n };\n for (var p = 0; p < pairIds.length; p++) {\n _loop();\n } // for pair ids\n\n // haystacks avoid the expense of pairInfo stuff (intersections etc.)\n this.findHaystackPoints(haystackEdges);\n};\nfunction getPts(pts) {\n var retPts = [];\n if (pts == null) {\n return;\n }\n for (var i = 0; i < pts.length; i += 2) {\n var x = pts[i];\n var y = pts[i + 1];\n retPts.push({\n x: x,\n y: y\n });\n }\n return retPts;\n}\nBRp$c.getSegmentPoints = function (edge) {\n var rs = edge[0]._private.rscratch;\n this.recalculateRenderedStyle(edge);\n var type = rs.edgeType;\n if (type === 'segments') {\n return getPts(rs.segpts);\n }\n};\nBRp$c.getControlPoints = function (edge) {\n var rs = edge[0]._private.rscratch;\n this.recalculateRenderedStyle(edge);\n var type = rs.edgeType;\n if (type === 'bezier' || type === 'multibezier' || type === 'self' || type === 'compound') {\n return getPts(rs.ctrlpts);\n }\n};\nBRp$c.getEdgeMidpoint = function (edge) {\n var rs = edge[0]._private.rscratch;\n this.recalculateRenderedStyle(edge);\n return {\n x: rs.midX,\n y: rs.midY\n };\n};\n\nvar BRp$b = {};\nBRp$b.manualEndptToPx = function (node, prop) {\n var r = this;\n var npos = node.position();\n var w = node.outerWidth();\n var h = node.outerHeight();\n var rs = node._private.rscratch;\n if (prop.value.length === 2) {\n var p = [prop.pfValue[0], prop.pfValue[1]];\n if (prop.units[0] === '%') {\n p[0] = p[0] * w;\n }\n if (prop.units[1] === '%') {\n p[1] = p[1] * h;\n }\n p[0] += npos.x;\n p[1] += npos.y;\n return p;\n } else {\n var angle = prop.pfValue[0];\n angle = -Math.PI / 2 + angle; // start at 12 o'clock\n\n var l = 2 * Math.max(w, h);\n var _p = [npos.x + Math.cos(angle) * l, npos.y + Math.sin(angle) * l];\n return r.nodeShapes[this.getNodeShape(node)].intersectLine(npos.x, npos.y, w, h, _p[0], _p[1], 0, node.pstyle('corner-radius').value === 'auto' ? 'auto' : node.pstyle('corner-radius').pfValue, rs);\n }\n};\nBRp$b.findEndpoints = function (edge) {\n var _ref, _tgtManEndpt$pfValue, _ref2, _srcManEndpt$pfValue;\n var r = this;\n var intersect;\n var source = edge.source()[0];\n var target = edge.target()[0];\n var srcPos = source.position();\n var tgtPos = target.position();\n var tgtArShape = edge.pstyle('target-arrow-shape').value;\n var srcArShape = edge.pstyle('source-arrow-shape').value;\n var tgtDist = edge.pstyle('target-distance-from-node').pfValue;\n var srcDist = edge.pstyle('source-distance-from-node').pfValue;\n var srcRs = source._private.rscratch;\n var tgtRs = target._private.rscratch;\n var curveStyle = edge.pstyle('curve-style').value;\n var rs = edge._private.rscratch;\n var et = rs.edgeType;\n var taxi = endsWith(curveStyle, 'taxi'); // Covers taxi and round-taxi\n var self = et === 'self' || et === 'compound';\n var bezier = et === 'bezier' || et === 'multibezier' || self;\n var multi = et !== 'bezier';\n var lines = et === 'straight' || et === 'segments';\n var segments = et === 'segments';\n var hasEndpts = bezier || multi || lines;\n var overrideEndpts = self || taxi;\n var srcManEndpt = edge.pstyle('source-endpoint');\n var srcManEndptVal = overrideEndpts ? 'outside-to-node' : srcManEndpt.value;\n var srcCornerRadius = source.pstyle('corner-radius').value === 'auto' ? 'auto' : source.pstyle('corner-radius').pfValue;\n var tgtManEndpt = edge.pstyle('target-endpoint');\n var tgtManEndptVal = overrideEndpts ? 'outside-to-node' : tgtManEndpt.value;\n var tgtCornerRadius = target.pstyle('corner-radius').value === 'auto' ? 'auto' : target.pstyle('corner-radius').pfValue;\n rs.srcManEndpt = srcManEndpt;\n rs.tgtManEndpt = tgtManEndpt;\n var p1; // last known point of edge on target side\n var p2; // last known point of edge on source side\n\n var p1_i; // point to intersect with target shape\n var p2_i; // point to intersect with source shape\n\n var tgtManEndptPt = (_ref = (tgtManEndpt === null || tgtManEndpt === undefined || (_tgtManEndpt$pfValue = tgtManEndpt.pfValue) === null || _tgtManEndpt$pfValue === undefined ? undefined : _tgtManEndpt$pfValue.length) === 2 ? tgtManEndpt.pfValue : null) !== null && _ref !== undefined ? _ref : [0, 0];\n var srcManEndptPt = (_ref2 = (srcManEndpt === null || srcManEndpt === undefined || (_srcManEndpt$pfValue = srcManEndpt.pfValue) === null || _srcManEndpt$pfValue === undefined ? undefined : _srcManEndpt$pfValue.length) === 2 ? srcManEndpt.pfValue : null) !== null && _ref2 !== undefined ? _ref2 : [0, 0];\n if (bezier) {\n var cpStart = [rs.ctrlpts[0], rs.ctrlpts[1]];\n var cpEnd = multi ? [rs.ctrlpts[rs.ctrlpts.length - 2], rs.ctrlpts[rs.ctrlpts.length - 1]] : cpStart;\n p1 = cpEnd;\n p2 = cpStart;\n } else if (lines) {\n var srcArrowFromPt = !segments ? [tgtPos.x + tgtManEndptPt[0], tgtPos.y + tgtManEndptPt[1]] : rs.segpts.slice(0, 2);\n var tgtArrowFromPt = !segments ? [srcPos.x + srcManEndptPt[0], srcPos.y + srcManEndptPt[1]] : rs.segpts.slice(rs.segpts.length - 2);\n p1 = tgtArrowFromPt;\n p2 = srcArrowFromPt;\n }\n if (tgtManEndptVal === 'inside-to-node') {\n intersect = [tgtPos.x, tgtPos.y];\n } else if (tgtManEndpt.units) {\n intersect = this.manualEndptToPx(target, tgtManEndpt);\n } else if (tgtManEndptVal === 'outside-to-line') {\n intersect = rs.tgtIntn; // use cached value from ctrlpt calc\n } else {\n if (tgtManEndptVal === 'outside-to-node' || tgtManEndptVal === 'outside-to-node-or-label') {\n p1_i = p1;\n } else if (tgtManEndptVal === 'outside-to-line' || tgtManEndptVal === 'outside-to-line-or-label') {\n p1_i = [srcPos.x, srcPos.y];\n }\n intersect = r.nodeShapes[this.getNodeShape(target)].intersectLine(tgtPos.x, tgtPos.y, target.outerWidth(), target.outerHeight(), p1_i[0], p1_i[1], 0, tgtCornerRadius, tgtRs);\n if (tgtManEndptVal === 'outside-to-node-or-label' || tgtManEndptVal === 'outside-to-line-or-label') {\n var trs = target._private.rscratch;\n var lw = trs.labelWidth;\n var lh = trs.labelHeight;\n var lx = trs.labelX;\n var ly = trs.labelY;\n var lw2 = lw / 2;\n var lh2 = lh / 2;\n var va = target.pstyle('text-valign').value;\n if (va === 'top') {\n ly -= lh2;\n } else if (va === 'bottom') {\n ly += lh2;\n }\n var ha = target.pstyle('text-halign').value;\n if (ha === 'left') {\n lx -= lw2;\n } else if (ha === 'right') {\n lx += lw2;\n }\n var labelIntersect = polygonIntersectLine(p1_i[0], p1_i[1], [lx - lw2, ly - lh2, lx + lw2, ly - lh2, lx + lw2, ly + lh2, lx - lw2, ly + lh2], tgtPos.x, tgtPos.y);\n if (labelIntersect.length > 0) {\n var refPt = srcPos;\n var intSqdist = sqdist(refPt, array2point(intersect));\n var labIntSqdist = sqdist(refPt, array2point(labelIntersect));\n var minSqDist = intSqdist;\n if (labIntSqdist < intSqdist) {\n intersect = labelIntersect;\n minSqDist = labIntSqdist;\n }\n if (labelIntersect.length > 2) {\n var labInt2SqDist = sqdist(refPt, {\n x: labelIntersect[2],\n y: labelIntersect[3]\n });\n if (labInt2SqDist < minSqDist) {\n intersect = [labelIntersect[2], labelIntersect[3]];\n }\n }\n }\n }\n }\n var arrowEnd = shortenIntersection(intersect, p1, r.arrowShapes[tgtArShape].spacing(edge) + tgtDist);\n var edgeEnd = shortenIntersection(intersect, p1, r.arrowShapes[tgtArShape].gap(edge) + tgtDist);\n rs.endX = edgeEnd[0];\n rs.endY = edgeEnd[1];\n rs.arrowEndX = arrowEnd[0];\n rs.arrowEndY = arrowEnd[1];\n if (srcManEndptVal === 'inside-to-node') {\n intersect = [srcPos.x, srcPos.y];\n } else if (srcManEndpt.units) {\n intersect = this.manualEndptToPx(source, srcManEndpt);\n } else if (srcManEndptVal === 'outside-to-line') {\n intersect = rs.srcIntn; // use cached value from ctrlpt calc\n } else {\n if (srcManEndptVal === 'outside-to-node' || srcManEndptVal === 'outside-to-node-or-label') {\n p2_i = p2;\n } else if (srcManEndptVal === 'outside-to-line' || srcManEndptVal === 'outside-to-line-or-label') {\n p2_i = [tgtPos.x, tgtPos.y];\n }\n intersect = r.nodeShapes[this.getNodeShape(source)].intersectLine(srcPos.x, srcPos.y, source.outerWidth(), source.outerHeight(), p2_i[0], p2_i[1], 0, srcCornerRadius, srcRs);\n if (srcManEndptVal === 'outside-to-node-or-label' || srcManEndptVal === 'outside-to-line-or-label') {\n var srs = source._private.rscratch;\n var _lw = srs.labelWidth;\n var _lh = srs.labelHeight;\n var _lx = srs.labelX;\n var _ly = srs.labelY;\n var _lw2 = _lw / 2;\n var _lh2 = _lh / 2;\n var _va = source.pstyle('text-valign').value;\n if (_va === 'top') {\n _ly -= _lh2;\n } else if (_va === 'bottom') {\n _ly += _lh2;\n }\n var _ha = source.pstyle('text-halign').value;\n if (_ha === 'left') {\n _lx -= _lw2;\n } else if (_ha === 'right') {\n _lx += _lw2;\n }\n var _labelIntersect = polygonIntersectLine(p2_i[0], p2_i[1], [_lx - _lw2, _ly - _lh2, _lx + _lw2, _ly - _lh2, _lx + _lw2, _ly + _lh2, _lx - _lw2, _ly + _lh2], srcPos.x, srcPos.y);\n if (_labelIntersect.length > 0) {\n var _refPt = tgtPos;\n var _intSqdist = sqdist(_refPt, array2point(intersect));\n var _labIntSqdist = sqdist(_refPt, array2point(_labelIntersect));\n var _minSqDist = _intSqdist;\n if (_labIntSqdist < _intSqdist) {\n intersect = [_labelIntersect[0], _labelIntersect[1]];\n _minSqDist = _labIntSqdist;\n }\n if (_labelIntersect.length > 2) {\n var _labInt2SqDist = sqdist(_refPt, {\n x: _labelIntersect[2],\n y: _labelIntersect[3]\n });\n if (_labInt2SqDist < _minSqDist) {\n intersect = [_labelIntersect[2], _labelIntersect[3]];\n }\n }\n }\n }\n }\n var arrowStart = shortenIntersection(intersect, p2, r.arrowShapes[srcArShape].spacing(edge) + srcDist);\n var edgeStart = shortenIntersection(intersect, p2, r.arrowShapes[srcArShape].gap(edge) + srcDist);\n rs.startX = edgeStart[0];\n rs.startY = edgeStart[1];\n rs.arrowStartX = arrowStart[0];\n rs.arrowStartY = arrowStart[1];\n if (hasEndpts) {\n if (!number$1(rs.startX) || !number$1(rs.startY) || !number$1(rs.endX) || !number$1(rs.endY)) {\n rs.badLine = true;\n } else {\n rs.badLine = false;\n }\n }\n};\nBRp$b.getSourceEndpoint = function (edge) {\n var rs = edge[0]._private.rscratch;\n this.recalculateRenderedStyle(edge);\n switch (rs.edgeType) {\n case 'haystack':\n return {\n x: rs.haystackPts[0],\n y: rs.haystackPts[1]\n };\n default:\n return {\n x: rs.arrowStartX,\n y: rs.arrowStartY\n };\n }\n};\nBRp$b.getTargetEndpoint = function (edge) {\n var rs = edge[0]._private.rscratch;\n this.recalculateRenderedStyle(edge);\n switch (rs.edgeType) {\n case 'haystack':\n return {\n x: rs.haystackPts[2],\n y: rs.haystackPts[3]\n };\n default:\n return {\n x: rs.arrowEndX,\n y: rs.arrowEndY\n };\n }\n};\n\nvar BRp$a = {};\nfunction pushBezierPts(r, edge, pts) {\n var qbezierAt$1 = function qbezierAt$1(p1, p2, p3, t) {\n return qbezierAt(p1, p2, p3, t);\n };\n var _p = edge._private;\n var bpts = _p.rstyle.bezierPts;\n for (var i = 0; i < r.bezierProjPcts.length; i++) {\n var p = r.bezierProjPcts[i];\n bpts.push({\n x: qbezierAt$1(pts[0], pts[2], pts[4], p),\n y: qbezierAt$1(pts[1], pts[3], pts[5], p)\n });\n }\n}\nBRp$a.storeEdgeProjections = function (edge) {\n var _p = edge._private;\n var rs = _p.rscratch;\n var et = rs.edgeType;\n\n // clear the cached points state\n _p.rstyle.bezierPts = null;\n _p.rstyle.linePts = null;\n _p.rstyle.haystackPts = null;\n if (et === 'multibezier' || et === 'bezier' || et === 'self' || et === 'compound') {\n _p.rstyle.bezierPts = [];\n for (var i = 0; i + 5 < rs.allpts.length; i += 4) {\n pushBezierPts(this, edge, rs.allpts.slice(i, i + 6));\n }\n } else if (et === 'segments') {\n var lpts = _p.rstyle.linePts = [];\n for (var i = 0; i + 1 < rs.allpts.length; i += 2) {\n lpts.push({\n x: rs.allpts[i],\n y: rs.allpts[i + 1]\n });\n }\n } else if (et === 'haystack') {\n var hpts = rs.haystackPts;\n _p.rstyle.haystackPts = [{\n x: hpts[0],\n y: hpts[1]\n }, {\n x: hpts[2],\n y: hpts[3]\n }];\n }\n _p.rstyle.arrowWidth = this.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.arrowShapeWidth;\n};\nBRp$a.recalculateEdgeProjections = function (edges) {\n this.findEdgeControlPoints(edges);\n};\n\nvar BRp$9 = {};\nBRp$9.recalculateNodeLabelProjection = function (node) {\n var content = node.pstyle('label').strValue;\n if (emptyString(content)) {\n return;\n }\n var textX, textY;\n var _p = node._private;\n var nodeWidth = node.width();\n var nodeHeight = node.height();\n var padding = node.padding();\n var nodePos = node.position();\n var textHalign = node.pstyle('text-halign').strValue;\n var textValign = node.pstyle('text-valign').strValue;\n var rs = _p.rscratch;\n var rstyle = _p.rstyle;\n switch (textHalign) {\n case 'left':\n textX = nodePos.x - nodeWidth / 2 - padding;\n break;\n case 'right':\n textX = nodePos.x + nodeWidth / 2 + padding;\n break;\n default:\n // e.g. center\n textX = nodePos.x;\n }\n switch (textValign) {\n case 'top':\n textY = nodePos.y - nodeHeight / 2 - padding;\n break;\n case 'bottom':\n textY = nodePos.y + nodeHeight / 2 + padding;\n break;\n default:\n // e.g. middle\n textY = nodePos.y;\n }\n rs.labelX = textX;\n rs.labelY = textY;\n rstyle.labelX = textX;\n rstyle.labelY = textY;\n this.calculateLabelAngles(node);\n this.applyLabelDimensions(node);\n};\nvar lineAngleFromDelta = function lineAngleFromDelta(dx, dy) {\n var angle = Math.atan(dy / dx);\n if (dx === 0 && angle < 0) {\n angle = angle * -1;\n }\n return angle;\n};\nvar lineAngle = function lineAngle(p0, p1) {\n var dx = p1.x - p0.x;\n var dy = p1.y - p0.y;\n return lineAngleFromDelta(dx, dy);\n};\nvar bezierAngle = function bezierAngle(p0, p1, p2, t) {\n var t0 = bound(0, t - 0.001, 1);\n var t1 = bound(0, t + 0.001, 1);\n var lp0 = qbezierPtAt(p0, p1, p2, t0);\n var lp1 = qbezierPtAt(p0, p1, p2, t1);\n return lineAngle(lp0, lp1);\n};\nBRp$9.recalculateEdgeLabelProjections = function (edge) {\n var p;\n var _p = edge._private;\n var rs = _p.rscratch;\n var r = this;\n var content = {\n mid: edge.pstyle('label').strValue,\n source: edge.pstyle('source-label').strValue,\n target: edge.pstyle('target-label').strValue\n };\n if (content.mid || content.source || content.target) ; else {\n return; // no labels => no calcs\n }\n\n // add center point to style so bounding box calculations can use it\n //\n p = {\n x: rs.midX,\n y: rs.midY\n };\n var setRs = function setRs(propName, prefix, value) {\n setPrefixedProperty(_p.rscratch, propName, prefix, value);\n setPrefixedProperty(_p.rstyle, propName, prefix, value);\n };\n setRs('labelX', null, p.x);\n setRs('labelY', null, p.y);\n var midAngle = lineAngleFromDelta(rs.midDispX, rs.midDispY);\n setRs('labelAutoAngle', null, midAngle);\n var _createControlPointInfo = function createControlPointInfo() {\n if (_createControlPointInfo.cache) {\n return _createControlPointInfo.cache;\n } // use cache so only 1x per edge\n\n var ctrlpts = [];\n\n // store each ctrlpt info init\n for (var i = 0; i + 5 < rs.allpts.length; i += 4) {\n var p0 = {\n x: rs.allpts[i],\n y: rs.allpts[i + 1]\n };\n var p1 = {\n x: rs.allpts[i + 2],\n y: rs.allpts[i + 3]\n }; // ctrlpt\n var p2 = {\n x: rs.allpts[i + 4],\n y: rs.allpts[i + 5]\n };\n ctrlpts.push({\n p0: p0,\n p1: p1,\n p2: p2,\n startDist: 0,\n length: 0,\n segments: []\n });\n }\n var bpts = _p.rstyle.bezierPts;\n var nProjs = r.bezierProjPcts.length;\n function addSegment(cp, p0, p1, t0, t1) {\n var length = dist(p0, p1);\n var prevSegment = cp.segments[cp.segments.length - 1];\n var segment = {\n p0: p0,\n p1: p1,\n t0: t0,\n t1: t1,\n startDist: prevSegment ? prevSegment.startDist + prevSegment.length : 0,\n length: length\n };\n cp.segments.push(segment);\n cp.length += length;\n }\n\n // update each ctrlpt with segment info\n for (var _i = 0; _i < ctrlpts.length; _i++) {\n var cp = ctrlpts[_i];\n var prevCp = ctrlpts[_i - 1];\n if (prevCp) {\n cp.startDist = prevCp.startDist + prevCp.length;\n }\n addSegment(cp, cp.p0, bpts[_i * nProjs], 0, r.bezierProjPcts[0]); // first\n\n for (var j = 0; j < nProjs - 1; j++) {\n addSegment(cp, bpts[_i * nProjs + j], bpts[_i * nProjs + j + 1], r.bezierProjPcts[j], r.bezierProjPcts[j + 1]);\n }\n addSegment(cp, bpts[_i * nProjs + nProjs - 1], cp.p2, r.bezierProjPcts[nProjs - 1], 1); // last\n }\n return _createControlPointInfo.cache = ctrlpts;\n };\n var calculateEndProjection = function calculateEndProjection(prefix) {\n var angle;\n var isSrc = prefix === 'source';\n if (!content[prefix]) {\n return;\n }\n var offset = edge.pstyle(prefix + '-text-offset').pfValue;\n switch (rs.edgeType) {\n case 'self':\n case 'compound':\n case 'bezier':\n case 'multibezier':\n {\n var cps = _createControlPointInfo();\n var selected;\n var startDist = 0;\n var totalDist = 0;\n\n // find the segment we're on\n for (var i = 0; i < cps.length; i++) {\n var _cp = cps[isSrc ? i : cps.length - 1 - i];\n for (var j = 0; j < _cp.segments.length; j++) {\n var _seg = _cp.segments[isSrc ? j : _cp.segments.length - 1 - j];\n var lastSeg = i === cps.length - 1 && j === _cp.segments.length - 1;\n startDist = totalDist;\n totalDist += _seg.length;\n if (totalDist >= offset || lastSeg) {\n selected = {\n cp: _cp,\n segment: _seg\n };\n break;\n }\n }\n if (selected) {\n break;\n }\n }\n var cp = selected.cp;\n var seg = selected.segment;\n var tSegment = (offset - startDist) / seg.length;\n var segDt = seg.t1 - seg.t0;\n var t = isSrc ? seg.t0 + segDt * tSegment : seg.t1 - segDt * tSegment;\n t = bound(0, t, 1);\n p = qbezierPtAt(cp.p0, cp.p1, cp.p2, t);\n angle = bezierAngle(cp.p0, cp.p1, cp.p2, t);\n break;\n }\n case 'straight':\n case 'segments':\n case 'haystack':\n {\n var d = 0,\n di,\n d0;\n var p0, p1;\n var l = rs.allpts.length;\n for (var _i2 = 0; _i2 + 3 < l; _i2 += 2) {\n if (isSrc) {\n p0 = {\n x: rs.allpts[_i2],\n y: rs.allpts[_i2 + 1]\n };\n p1 = {\n x: rs.allpts[_i2 + 2],\n y: rs.allpts[_i2 + 3]\n };\n } else {\n p0 = {\n x: rs.allpts[l - 2 - _i2],\n y: rs.allpts[l - 1 - _i2]\n };\n p1 = {\n x: rs.allpts[l - 4 - _i2],\n y: rs.allpts[l - 3 - _i2]\n };\n }\n di = dist(p0, p1);\n d0 = d;\n d += di;\n if (d >= offset) {\n break;\n }\n }\n var pD = offset - d0;\n var _t = pD / di;\n _t = bound(0, _t, 1);\n p = lineAt(p0, p1, _t);\n angle = lineAngle(p0, p1);\n break;\n }\n }\n setRs('labelX', prefix, p.x);\n setRs('labelY', prefix, p.y);\n setRs('labelAutoAngle', prefix, angle);\n };\n calculateEndProjection('source');\n calculateEndProjection('target');\n this.applyLabelDimensions(edge);\n};\nBRp$9.applyLabelDimensions = function (ele) {\n this.applyPrefixedLabelDimensions(ele);\n if (ele.isEdge()) {\n this.applyPrefixedLabelDimensions(ele, 'source');\n this.applyPrefixedLabelDimensions(ele, 'target');\n }\n};\nBRp$9.applyPrefixedLabelDimensions = function (ele, prefix) {\n var _p = ele._private;\n var text = this.getLabelText(ele, prefix);\n var cacheKey = hashString(text, ele._private.labelDimsKey);\n\n // save recalc if the label is the same as before\n if (getPrefixedProperty(_p.rscratch, 'prefixedLabelDimsKey', prefix) === cacheKey) {\n return; // then the label dimensions + text are the same\n }\n\n // save the key\n setPrefixedProperty(_p.rscratch, 'prefixedLabelDimsKey', prefix, cacheKey);\n var labelDims = this.calculateLabelDimensions(ele, text);\n var lineHeight = ele.pstyle('line-height').pfValue;\n var textWrap = ele.pstyle('text-wrap').strValue;\n var lines = getPrefixedProperty(_p.rscratch, 'labelWrapCachedLines', prefix) || [];\n var numLines = textWrap !== 'wrap' ? 1 : Math.max(lines.length, 1);\n var normPerLineHeight = labelDims.height / numLines;\n var labelLineHeight = normPerLineHeight * lineHeight;\n var width = labelDims.width;\n var height = labelDims.height + (numLines - 1) * (lineHeight - 1) * normPerLineHeight;\n setPrefixedProperty(_p.rstyle, 'labelWidth', prefix, width);\n setPrefixedProperty(_p.rscratch, 'labelWidth', prefix, width);\n setPrefixedProperty(_p.rstyle, 'labelHeight', prefix, height);\n setPrefixedProperty(_p.rscratch, 'labelHeight', prefix, height);\n setPrefixedProperty(_p.rscratch, 'labelLineHeight', prefix, labelLineHeight);\n};\nBRp$9.getLabelText = function (ele, prefix) {\n var _p = ele._private;\n var pfd = prefix ? prefix + '-' : '';\n var text = ele.pstyle(pfd + 'label').strValue;\n var textTransform = ele.pstyle('text-transform').value;\n var rscratch = function rscratch(propName, value) {\n if (value) {\n setPrefixedProperty(_p.rscratch, propName, prefix, value);\n return value;\n } else {\n return getPrefixedProperty(_p.rscratch, propName, prefix);\n }\n };\n\n // for empty text, skip all processing\n if (!text) {\n return '';\n }\n if (textTransform == 'none') ; else if (textTransform == 'uppercase') {\n text = text.toUpperCase();\n } else if (textTransform == 'lowercase') {\n text = text.toLowerCase();\n }\n var wrapStyle = ele.pstyle('text-wrap').value;\n if (wrapStyle === 'wrap') {\n var labelKey = rscratch('labelKey');\n\n // save recalc if the label is the same as before\n if (labelKey != null && rscratch('labelWrapKey') === labelKey) {\n return rscratch('labelWrapCachedText');\n }\n var zwsp = \"\\u200B\";\n var lines = text.split('\\n');\n var maxW = ele.pstyle('text-max-width').pfValue;\n var overflow = ele.pstyle('text-overflow-wrap').value;\n var overflowAny = overflow === 'anywhere';\n var wrappedLines = [];\n var separatorRegex = /[\\s\\u200b]+|$/g; // Include end of string to add last word\n\n for (var l = 0; l < lines.length; l++) {\n var line = lines[l];\n var lineDims = this.calculateLabelDimensions(ele, line);\n var lineW = lineDims.width;\n if (overflowAny) {\n var processedLine = line.split('').join(zwsp);\n line = processedLine;\n }\n if (lineW > maxW) {\n // line is too long\n var separatorMatches = line.matchAll(separatorRegex);\n var subline = '';\n var previousIndex = 0;\n // Add fake match\n var _iterator = _createForOfIteratorHelper(separatorMatches),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var separatorMatch = _step.value;\n var wordSeparator = separatorMatch[0];\n var word = line.substring(previousIndex, separatorMatch.index);\n previousIndex = separatorMatch.index + wordSeparator.length;\n var testLine = subline.length === 0 ? word : subline + word + wordSeparator;\n var testDims = this.calculateLabelDimensions(ele, testLine);\n var testW = testDims.width;\n if (testW <= maxW) {\n // word fits on current line\n subline += word + wordSeparator;\n } else {\n // word starts new line\n if (subline) {\n wrappedLines.push(subline);\n }\n subline = word + wordSeparator;\n }\n }\n\n // if there's remaining text, put it in a wrapped line\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n if (!subline.match(/^[\\s\\u200b]+$/)) {\n wrappedLines.push(subline);\n }\n } else {\n // line is already short enough\n wrappedLines.push(line);\n }\n } // for\n\n rscratch('labelWrapCachedLines', wrappedLines);\n text = rscratch('labelWrapCachedText', wrappedLines.join('\\n'));\n rscratch('labelWrapKey', labelKey);\n } else if (wrapStyle === 'ellipsis') {\n var _maxW = ele.pstyle('text-max-width').pfValue;\n var ellipsized = '';\n var ellipsis = \"\\u2026\";\n var incLastCh = false;\n if (this.calculateLabelDimensions(ele, text).width < _maxW) {\n // the label already fits\n return text;\n }\n for (var i = 0; i < text.length; i++) {\n var widthWithNextCh = this.calculateLabelDimensions(ele, ellipsized + text[i] + ellipsis).width;\n if (widthWithNextCh > _maxW) {\n break;\n }\n ellipsized += text[i];\n if (i === text.length - 1) {\n incLastCh = true;\n }\n }\n if (!incLastCh) {\n ellipsized += ellipsis;\n }\n return ellipsized;\n } // if ellipsize\n\n return text;\n};\nBRp$9.getLabelJustification = function (ele) {\n var justification = ele.pstyle('text-justification').strValue;\n var textHalign = ele.pstyle('text-halign').strValue;\n if (justification === 'auto') {\n if (ele.isNode()) {\n switch (textHalign) {\n case 'left':\n return 'right';\n case 'right':\n return 'left';\n default:\n return 'center';\n }\n } else {\n return 'center';\n }\n } else {\n return justification;\n }\n};\nBRp$9.calculateLabelDimensions = function (ele, text) {\n var r = this;\n var containerWindow = r.cy.window();\n var document = containerWindow.document;\n var padding = 0; // add padding around text dims, as the measurement isn't that accurate\n var fStyle = ele.pstyle('font-style').strValue;\n var size = ele.pstyle('font-size').pfValue;\n var family = ele.pstyle('font-family').strValue;\n var weight = ele.pstyle('font-weight').strValue;\n var canvas = this.labelCalcCanvas;\n var c2d = this.labelCalcCanvasContext;\n if (!canvas) {\n canvas = this.labelCalcCanvas = document.createElement('canvas');\n c2d = this.labelCalcCanvasContext = canvas.getContext('2d');\n var ds = canvas.style;\n ds.position = 'absolute';\n ds.left = '-9999px';\n ds.top = '-9999px';\n ds.zIndex = '-1';\n ds.visibility = 'hidden';\n ds.pointerEvents = 'none';\n }\n c2d.font = \"\".concat(fStyle, \" \").concat(weight, \" \").concat(size, \"px \").concat(family);\n var width = 0;\n var height = 0;\n var lines = text.split('\\n');\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i];\n var metrics = c2d.measureText(line);\n var w = Math.ceil(metrics.width);\n var h = size;\n width = Math.max(w, width);\n height += h;\n }\n width += padding;\n height += padding;\n return {\n width: width,\n height: height\n };\n};\nBRp$9.calculateLabelAngle = function (ele, prefix) {\n var _p = ele._private;\n var rs = _p.rscratch;\n var isEdge = ele.isEdge();\n var prefixDash = prefix ? prefix + '-' : '';\n var rot = ele.pstyle(prefixDash + 'text-rotation');\n var rotStr = rot.strValue;\n if (rotStr === 'none') {\n return 0;\n } else if (isEdge && rotStr === 'autorotate') {\n return rs.labelAutoAngle;\n } else if (rotStr === 'autorotate') {\n return 0;\n } else {\n return rot.pfValue;\n }\n};\nBRp$9.calculateLabelAngles = function (ele) {\n var r = this;\n var isEdge = ele.isEdge();\n var _p = ele._private;\n var rs = _p.rscratch;\n rs.labelAngle = r.calculateLabelAngle(ele);\n if (isEdge) {\n rs.sourceLabelAngle = r.calculateLabelAngle(ele, 'source');\n rs.targetLabelAngle = r.calculateLabelAngle(ele, 'target');\n }\n};\n\nvar BRp$8 = {};\nvar TOO_SMALL_CUT_RECT = 28;\nvar warnedCutRect = false;\nBRp$8.getNodeShape = function (node) {\n var r = this;\n var shape = node.pstyle('shape').value;\n if (shape === 'cutrectangle' && (node.width() < TOO_SMALL_CUT_RECT || node.height() < TOO_SMALL_CUT_RECT)) {\n if (!warnedCutRect) {\n warn('The `cutrectangle` node shape can not be used at small sizes so `rectangle` is used instead');\n warnedCutRect = true;\n }\n return 'rectangle';\n }\n if (node.isParent()) {\n if (shape === 'rectangle' || shape === 'roundrectangle' || shape === 'round-rectangle' || shape === 'cutrectangle' || shape === 'cut-rectangle' || shape === 'barrel') {\n return shape;\n } else {\n return 'rectangle';\n }\n }\n if (shape === 'polygon') {\n var points = node.pstyle('shape-polygon-points').value;\n return r.nodeShapes.makePolygon(points).name;\n }\n return shape;\n};\n\nvar BRp$7 = {};\nBRp$7.registerCalculationListeners = function () {\n var cy = this.cy;\n var elesToUpdate = cy.collection();\n var r = this;\n var enqueue = function enqueue(eles) {\n var dirtyStyleCaches = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n elesToUpdate.merge(eles);\n if (dirtyStyleCaches) {\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n var _p = ele._private;\n var rstyle = _p.rstyle;\n rstyle.clean = false;\n rstyle.cleanConnected = false;\n }\n }\n };\n r.binder(cy).on('bounds.* dirty.*', function onDirtyBounds(e) {\n var ele = e.target;\n enqueue(ele);\n }).on('style.* background.*', function onDirtyStyle(e) {\n var ele = e.target;\n enqueue(ele, false);\n });\n var updateEleCalcs = function updateEleCalcs(willDraw) {\n if (willDraw) {\n var fns = r.onUpdateEleCalcsFns;\n\n // because we need to have up-to-date style (e.g. stylesheet mappers)\n // before calculating rendered style (and pstyle might not be called yet)\n elesToUpdate.cleanStyle();\n for (var i = 0; i < elesToUpdate.length; i++) {\n var ele = elesToUpdate[i];\n var rstyle = ele._private.rstyle;\n if (ele.isNode() && !rstyle.cleanConnected) {\n enqueue(ele.connectedEdges());\n rstyle.cleanConnected = true;\n }\n }\n if (fns) {\n for (var _i = 0; _i < fns.length; _i++) {\n var fn = fns[_i];\n fn(willDraw, elesToUpdate);\n }\n }\n r.recalculateRenderedStyle(elesToUpdate);\n elesToUpdate = cy.collection();\n }\n };\n r.flushRenderedStyleQueue = function () {\n updateEleCalcs(true);\n };\n r.beforeRender(updateEleCalcs, r.beforeRenderPriorities.eleCalcs);\n};\nBRp$7.onUpdateEleCalcs = function (fn) {\n var fns = this.onUpdateEleCalcsFns = this.onUpdateEleCalcsFns || [];\n fns.push(fn);\n};\nBRp$7.recalculateRenderedStyle = function (eles, useCache) {\n var isCleanConnected = function isCleanConnected(ele) {\n return ele._private.rstyle.cleanConnected;\n };\n if (eles.length === 0) {\n return;\n }\n var edges = [];\n var nodes = [];\n\n // the renderer can't be used for calcs when destroyed, e.g. ele.boundingBox()\n if (this.destroyed) {\n return;\n }\n\n // use cache by default for perf\n if (useCache === undefined) {\n useCache = true;\n }\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n var _p = ele._private;\n var rstyle = _p.rstyle;\n\n // an edge may be implicitly dirty b/c of one of its connected nodes\n // (and a request for recalc may come in between frames)\n if (ele.isEdge() && (!isCleanConnected(ele.source()) || !isCleanConnected(ele.target()))) {\n rstyle.clean = false;\n }\n if (ele.isEdge() && ele.isBundledBezier()) {\n if (ele.parallelEdges().some(function (ele) {\n return !ele._private.rstyle.clean && ele.isBundledBezier();\n })) {\n rstyle.clean = false;\n }\n }\n\n // only update if dirty and in graph\n if (useCache && rstyle.clean || ele.removed()) {\n continue;\n }\n\n // only update if not display: none\n if (ele.pstyle('display').value === 'none') {\n continue;\n }\n if (_p.group === 'nodes') {\n nodes.push(ele);\n } else {\n // edges\n edges.push(ele);\n }\n rstyle.clean = true;\n }\n\n // update node data from projections\n for (var _i2 = 0; _i2 < nodes.length; _i2++) {\n var _ele = nodes[_i2];\n var _p2 = _ele._private;\n var _rstyle = _p2.rstyle;\n var pos = _ele.position();\n this.recalculateNodeLabelProjection(_ele);\n _rstyle.nodeX = pos.x;\n _rstyle.nodeY = pos.y;\n _rstyle.nodeW = _ele.pstyle('width').pfValue;\n _rstyle.nodeH = _ele.pstyle('height').pfValue;\n }\n this.recalculateEdgeProjections(edges);\n\n // update edge data from projections\n for (var _i3 = 0; _i3 < edges.length; _i3++) {\n var _ele2 = edges[_i3];\n var _p3 = _ele2._private;\n var _rstyle2 = _p3.rstyle;\n var rs = _p3.rscratch;\n\n // update rstyle positions\n _rstyle2.srcX = rs.arrowStartX;\n _rstyle2.srcY = rs.arrowStartY;\n _rstyle2.tgtX = rs.arrowEndX;\n _rstyle2.tgtY = rs.arrowEndY;\n _rstyle2.midX = rs.midX;\n _rstyle2.midY = rs.midY;\n _rstyle2.labelAngle = rs.labelAngle;\n _rstyle2.sourceLabelAngle = rs.sourceLabelAngle;\n _rstyle2.targetLabelAngle = rs.targetLabelAngle;\n }\n};\n\nvar BRp$6 = {};\nBRp$6.updateCachedGrabbedEles = function () {\n var eles = this.cachedZSortedEles;\n if (!eles) {\n // just let this be recalculated on the next z sort tick\n return;\n }\n eles.drag = [];\n eles.nondrag = [];\n var grabTargets = [];\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n var rs = ele._private.rscratch;\n if (ele.grabbed() && !ele.isParent()) {\n grabTargets.push(ele);\n } else if (rs.inDragLayer) {\n eles.drag.push(ele);\n } else {\n eles.nondrag.push(ele);\n }\n }\n\n // put the grab target nodes last so it's on top of its neighbourhood\n for (var i = 0; i < grabTargets.length; i++) {\n var ele = grabTargets[i];\n eles.drag.push(ele);\n }\n};\nBRp$6.invalidateCachedZSortedEles = function () {\n this.cachedZSortedEles = null;\n};\nBRp$6.getCachedZSortedEles = function (forceRecalc) {\n if (forceRecalc || !this.cachedZSortedEles) {\n var eles = this.cy.mutableElements().toArray();\n eles.sort(zIndexSort);\n eles.interactive = eles.filter(function (ele) {\n return ele.interactive();\n });\n this.cachedZSortedEles = eles;\n this.updateCachedGrabbedEles();\n } else {\n eles = this.cachedZSortedEles;\n }\n return eles;\n};\n\nvar BRp$5 = {};\n[BRp$e, BRp$d, BRp$c, BRp$b, BRp$a, BRp$9, BRp$8, BRp$7, BRp$6].forEach(function (props) {\n extend(BRp$5, props);\n});\n\nvar BRp$4 = {};\nBRp$4.getCachedImage = function (url, crossOrigin, onLoad) {\n var r = this;\n var imageCache = r.imageCache = r.imageCache || {};\n var cache = imageCache[url];\n if (cache) {\n if (!cache.image.complete) {\n cache.image.addEventListener('load', onLoad);\n }\n return cache.image;\n } else {\n cache = imageCache[url] = imageCache[url] || {};\n var image = cache.image = new Image(); // eslint-disable-line no-undef\n\n image.addEventListener('load', onLoad);\n image.addEventListener('error', function () {\n image.error = true;\n });\n\n // #1582 safari doesn't load data uris with crossOrigin properly\n // https://bugs.webkit.org/show_bug.cgi?id=123978\n var dataUriPrefix = 'data:';\n var isDataUri = url.substring(0, dataUriPrefix.length).toLowerCase() === dataUriPrefix;\n if (!isDataUri) {\n // if crossorigin is 'null'(stringified), then manually set it to null \n crossOrigin = crossOrigin === 'null' ? null : crossOrigin;\n image.crossOrigin = crossOrigin; // prevent tainted canvas\n }\n image.src = url;\n return image;\n }\n};\n\nvar BRp$3 = {};\n\n/* global document, ResizeObserver, MutationObserver */\n\nBRp$3.registerBinding = function (target, event, handler, useCapture) {\n // eslint-disable-line no-unused-vars\n var args = Array.prototype.slice.apply(arguments, [1]); // copy\n\n if (Array.isArray(target)) {\n var res = [];\n for (var i = 0; i < target.length; i++) {\n var t = target[i];\n if (t !== undefined) {\n var b = this.binder(t);\n res.push(b.on.apply(b, args));\n }\n }\n return res;\n }\n var b = this.binder(target);\n return b.on.apply(b, args);\n};\nBRp$3.binder = function (tgt) {\n var r = this;\n var containerWindow = r.cy.window();\n var tgtIsDom = tgt === containerWindow || tgt === containerWindow.document || tgt === containerWindow.document.body || domElement(tgt);\n if (r.supportsPassiveEvents == null) {\n // from https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection\n var supportsPassive = false;\n try {\n var opts = Object.defineProperty({}, 'passive', {\n get: function get() {\n supportsPassive = true;\n return true;\n }\n });\n containerWindow.addEventListener('test', null, opts);\n } catch (err) {\n // not supported\n }\n r.supportsPassiveEvents = supportsPassive;\n }\n var on = function on(event, handler, useCapture) {\n var args = Array.prototype.slice.call(arguments);\n if (tgtIsDom && r.supportsPassiveEvents) {\n // replace useCapture w/ opts obj\n args[2] = {\n capture: useCapture != null ? useCapture : false,\n passive: false,\n once: false\n };\n }\n r.bindings.push({\n target: tgt,\n args: args\n });\n (tgt.addEventListener || tgt.on).apply(tgt, args);\n return this;\n };\n return {\n on: on,\n addEventListener: on,\n addListener: on,\n bind: on\n };\n};\nBRp$3.nodeIsDraggable = function (node) {\n return node && node.isNode() && !node.locked() && node.grabbable();\n};\nBRp$3.nodeIsGrabbable = function (node) {\n return this.nodeIsDraggable(node) && node.interactive();\n};\nBRp$3.load = function () {\n var r = this;\n var containerWindow = r.cy.window();\n var isSelected = function isSelected(ele) {\n return ele.selected();\n };\n var getShadowRoot = function getShadowRoot(element) {\n var rootNode = element.getRootNode();\n // Check if the root node is a shadow root\n if (rootNode && rootNode.nodeType === 11 && rootNode.host !== undefined) {\n return rootNode;\n }\n };\n var triggerEvents = function triggerEvents(target, names, e, position) {\n if (target == null) {\n target = r.cy;\n }\n for (var i = 0; i < names.length; i++) {\n var name = names[i];\n target.emit({\n originalEvent: e,\n type: name,\n position: position\n });\n }\n };\n var isMultSelKeyDown = function isMultSelKeyDown(e) {\n return e.shiftKey || e.metaKey || e.ctrlKey; // maybe e.altKey\n };\n var allowPanningPassthrough = function allowPanningPassthrough(down, downs) {\n var allowPassthrough = true;\n if (r.cy.hasCompoundNodes() && down && down.pannable()) {\n // a grabbable compound node below the ele => no passthrough panning\n for (var i = 0; downs && i < downs.length; i++) {\n var down = downs[i];\n\n //if any parent node in event hierarchy isn't pannable, reject passthrough\n if (down.isNode() && down.isParent() && !down.pannable()) {\n allowPassthrough = false;\n break;\n }\n }\n } else {\n allowPassthrough = true;\n }\n return allowPassthrough;\n };\n var setGrabbed = function setGrabbed(ele) {\n ele[0]._private.grabbed = true;\n };\n var setFreed = function setFreed(ele) {\n ele[0]._private.grabbed = false;\n };\n var setInDragLayer = function setInDragLayer(ele) {\n ele[0]._private.rscratch.inDragLayer = true;\n };\n var setOutDragLayer = function setOutDragLayer(ele) {\n ele[0]._private.rscratch.inDragLayer = false;\n };\n var setGrabTarget = function setGrabTarget(ele) {\n ele[0]._private.rscratch.isGrabTarget = true;\n };\n var removeGrabTarget = function removeGrabTarget(ele) {\n ele[0]._private.rscratch.isGrabTarget = false;\n };\n var addToDragList = function addToDragList(ele, opts) {\n var list = opts.addToList;\n var listHasEle = list.has(ele);\n if (!listHasEle && ele.grabbable() && !ele.locked()) {\n list.merge(ele);\n setGrabbed(ele);\n }\n };\n\n // helper function to determine which child nodes and inner edges\n // of a compound node to be dragged as well as the grabbed and selected nodes\n var addDescendantsToDrag = function addDescendantsToDrag(node, opts) {\n if (!node.cy().hasCompoundNodes()) {\n return;\n }\n if (opts.inDragLayer == null && opts.addToList == null) {\n return;\n } // nothing to do\n\n var innerNodes = node.descendants();\n if (opts.inDragLayer) {\n innerNodes.forEach(setInDragLayer);\n innerNodes.connectedEdges().forEach(setInDragLayer);\n }\n if (opts.addToList) {\n addToDragList(innerNodes, opts);\n }\n };\n\n // adds the given nodes and its neighbourhood to the drag layer\n var addNodesToDrag = function addNodesToDrag(nodes, opts) {\n opts = opts || {};\n var hasCompoundNodes = nodes.cy().hasCompoundNodes();\n if (opts.inDragLayer) {\n nodes.forEach(setInDragLayer);\n nodes.neighborhood().stdFilter(function (ele) {\n return !hasCompoundNodes || ele.isEdge();\n }).forEach(setInDragLayer);\n }\n if (opts.addToList) {\n nodes.forEach(function (ele) {\n addToDragList(ele, opts);\n });\n }\n addDescendantsToDrag(nodes, opts); // always add to drag\n\n // also add nodes and edges related to the topmost ancestor\n updateAncestorsInDragLayer(nodes, {\n inDragLayer: opts.inDragLayer\n });\n r.updateCachedGrabbedEles();\n };\n var addNodeToDrag = addNodesToDrag;\n var freeDraggedElements = function freeDraggedElements(grabbedEles) {\n if (!grabbedEles) {\n return;\n }\n\n // just go over all elements rather than doing a bunch of (possibly expensive) traversals\n r.getCachedZSortedEles().forEach(function (ele) {\n setFreed(ele);\n setOutDragLayer(ele);\n removeGrabTarget(ele);\n });\n r.updateCachedGrabbedEles();\n };\n\n // helper function to determine which ancestor nodes and edges should go\n // to the drag layer (or should be removed from drag layer).\n var updateAncestorsInDragLayer = function updateAncestorsInDragLayer(node, opts) {\n if (opts.inDragLayer == null && opts.addToList == null) {\n return;\n } // nothing to do\n\n if (!node.cy().hasCompoundNodes()) {\n return;\n }\n\n // find top-level parent\n var parent = node.ancestors().orphans();\n\n // no parent node: no nodes to add to the drag layer\n if (parent.same(node)) {\n return;\n }\n var nodes = parent.descendants().spawnSelf().merge(parent).unmerge(node).unmerge(node.descendants());\n var edges = nodes.connectedEdges();\n if (opts.inDragLayer) {\n edges.forEach(setInDragLayer);\n nodes.forEach(setInDragLayer);\n }\n if (opts.addToList) {\n nodes.forEach(function (ele) {\n addToDragList(ele, opts);\n });\n }\n };\n var blurActiveDomElement = function blurActiveDomElement() {\n if (document.activeElement != null && document.activeElement.blur != null) {\n document.activeElement.blur();\n }\n };\n var haveMutationsApi = typeof MutationObserver !== 'undefined';\n var haveResizeObserverApi = typeof ResizeObserver !== 'undefined';\n\n // watch for when the cy container is removed from the dom\n if (haveMutationsApi) {\n r.removeObserver = new MutationObserver(function (mutns) {\n // eslint-disable-line no-undef\n for (var i = 0; i < mutns.length; i++) {\n var mutn = mutns[i];\n var rNodes = mutn.removedNodes;\n if (rNodes) {\n for (var j = 0; j < rNodes.length; j++) {\n var rNode = rNodes[j];\n if (rNode === r.container) {\n r.destroy();\n break;\n }\n }\n }\n }\n });\n if (r.container.parentNode) {\n r.removeObserver.observe(r.container.parentNode, {\n childList: true\n });\n }\n } else {\n r.registerBinding(r.container, 'DOMNodeRemoved', function (e) {\n // eslint-disable-line no-unused-vars\n r.destroy();\n });\n }\n var onResize = debounce(function () {\n r.cy.resize();\n }, 100);\n if (haveMutationsApi) {\n r.styleObserver = new MutationObserver(onResize); // eslint-disable-line no-undef\n\n r.styleObserver.observe(r.container, {\n attributes: true\n });\n }\n\n // auto resize\n r.registerBinding(containerWindow, 'resize', onResize); // eslint-disable-line no-undef\n\n if (haveResizeObserverApi) {\n r.resizeObserver = new ResizeObserver(onResize); // eslint-disable-line no-undef\n\n r.resizeObserver.observe(r.container);\n }\n var forEachUp = function forEachUp(domEle, fn) {\n while (domEle != null) {\n fn(domEle);\n domEle = domEle.parentNode;\n }\n };\n var invalidateCoords = function invalidateCoords() {\n r.invalidateContainerClientCoordsCache();\n };\n forEachUp(r.container, function (domEle) {\n r.registerBinding(domEle, 'transitionend', invalidateCoords);\n r.registerBinding(domEle, 'animationend', invalidateCoords);\n r.registerBinding(domEle, 'scroll', invalidateCoords);\n });\n\n // stop right click menu from appearing on cy\n r.registerBinding(r.container, 'contextmenu', function (e) {\n e.preventDefault();\n });\n var inBoxSelection = function inBoxSelection() {\n return r.selection[4] !== 0;\n };\n var eventInContainer = function eventInContainer(e) {\n // save cycles if mouse events aren't to be captured\n var containerPageCoords = r.findContainerClientCoords();\n var x = containerPageCoords[0];\n var y = containerPageCoords[1];\n var width = containerPageCoords[2];\n var height = containerPageCoords[3];\n var positions = e.touches ? e.touches : [e];\n var atLeastOnePosInside = false;\n for (var i = 0; i < positions.length; i++) {\n var p = positions[i];\n if (x <= p.clientX && p.clientX <= x + width && y <= p.clientY && p.clientY <= y + height) {\n atLeastOnePosInside = true;\n break;\n }\n }\n if (!atLeastOnePosInside) {\n return false;\n }\n var container = r.container;\n var target = e.target;\n var tParent = target.parentNode;\n var containerIsTarget = false;\n while (tParent) {\n if (tParent === container) {\n containerIsTarget = true;\n break;\n }\n tParent = tParent.parentNode;\n }\n if (!containerIsTarget) {\n return false;\n } // if target is outisde cy container, then this event is not for us\n\n return true;\n };\n\n // Primary key\n r.registerBinding(r.container, 'mousedown', function mousedownHandler(e) {\n if (!eventInContainer(e)) {\n return;\n }\n\n // during left mouse button gestures, ignore other buttons\n if (r.hoverData.which === 1 && e.which !== 1) {\n return;\n }\n e.preventDefault();\n blurActiveDomElement();\n r.hoverData.capture = true;\n r.hoverData.which = e.which;\n var cy = r.cy;\n var gpos = [e.clientX, e.clientY];\n var pos = r.projectIntoViewport(gpos[0], gpos[1]);\n var select = r.selection;\n var nears = r.findNearestElements(pos[0], pos[1], true, false);\n var near = nears[0];\n var draggedElements = r.dragData.possibleDragElements;\n r.hoverData.mdownPos = pos;\n r.hoverData.mdownGPos = gpos;\n var makeEvent = function makeEvent(type) {\n return {\n originalEvent: e,\n type: type,\n position: {\n x: pos[0],\n y: pos[1]\n }\n };\n };\n var checkForTaphold = function checkForTaphold() {\n r.hoverData.tapholdCancelled = false;\n clearTimeout(r.hoverData.tapholdTimeout);\n r.hoverData.tapholdTimeout = setTimeout(function () {\n if (r.hoverData.tapholdCancelled) {\n return;\n } else {\n var ele = r.hoverData.down;\n if (ele) {\n ele.emit(makeEvent('taphold'));\n } else {\n cy.emit(makeEvent('taphold'));\n }\n }\n }, r.tapholdDuration);\n };\n\n // Right click button\n if (e.which == 3) {\n r.hoverData.cxtStarted = true;\n var cxtEvt = {\n originalEvent: e,\n type: 'cxttapstart',\n position: {\n x: pos[0],\n y: pos[1]\n }\n };\n if (near) {\n near.activate();\n near.emit(cxtEvt);\n r.hoverData.down = near;\n } else {\n cy.emit(cxtEvt);\n }\n r.hoverData.downTime = new Date().getTime();\n r.hoverData.cxtDragged = false;\n\n // Primary button\n } else if (e.which == 1) {\n if (near) {\n near.activate();\n }\n\n // Element dragging\n {\n // If something is under the cursor and it is draggable, prepare to grab it\n if (near != null) {\n if (r.nodeIsGrabbable(near)) {\n var triggerGrab = function triggerGrab(ele) {\n ele.emit(makeEvent('grab'));\n };\n setGrabTarget(near);\n if (!near.selected()) {\n draggedElements = r.dragData.possibleDragElements = cy.collection();\n addNodeToDrag(near, {\n addToList: draggedElements\n });\n near.emit(makeEvent('grabon')).emit(makeEvent('grab'));\n } else {\n draggedElements = r.dragData.possibleDragElements = cy.collection();\n var selectedNodes = cy.$(function (ele) {\n return ele.isNode() && ele.selected() && r.nodeIsGrabbable(ele);\n });\n addNodesToDrag(selectedNodes, {\n addToList: draggedElements\n });\n near.emit(makeEvent('grabon'));\n selectedNodes.forEach(triggerGrab);\n }\n r.redrawHint('eles', true);\n r.redrawHint('drag', true);\n }\n }\n r.hoverData.down = near;\n r.hoverData.downs = nears;\n r.hoverData.downTime = new Date().getTime();\n }\n triggerEvents(near, ['mousedown', 'tapstart', 'vmousedown'], e, {\n x: pos[0],\n y: pos[1]\n });\n if (near == null) {\n select[4] = 1;\n r.data.bgActivePosistion = {\n x: pos[0],\n y: pos[1]\n };\n r.redrawHint('select', true);\n r.redraw();\n } else if (near.pannable()) {\n select[4] = 1; // for future pan\n }\n checkForTaphold();\n }\n\n // Initialize selection box coordinates\n select[0] = select[2] = pos[0];\n select[1] = select[3] = pos[1];\n }, false);\n var shadowRoot = getShadowRoot(r.container);\n r.registerBinding([containerWindow, shadowRoot], 'mousemove', function mousemoveHandler(e) {\n // eslint-disable-line no-undef\n var capture = r.hoverData.capture;\n if (!capture && !eventInContainer(e)) {\n return;\n }\n var preventDefault = false;\n var cy = r.cy;\n var zoom = cy.zoom();\n var gpos = [e.clientX, e.clientY];\n var pos = r.projectIntoViewport(gpos[0], gpos[1]);\n var mdownPos = r.hoverData.mdownPos;\n var mdownGPos = r.hoverData.mdownGPos;\n var select = r.selection;\n var near = null;\n if (!r.hoverData.draggingEles && !r.hoverData.dragging && !r.hoverData.selecting) {\n near = r.findNearestElement(pos[0], pos[1], true, false);\n }\n var last = r.hoverData.last;\n var down = r.hoverData.down;\n var disp = [pos[0] - select[2], pos[1] - select[3]];\n var draggedElements = r.dragData.possibleDragElements;\n var isOverThresholdDrag;\n if (mdownGPos) {\n var dx = gpos[0] - mdownGPos[0];\n var dx2 = dx * dx;\n var dy = gpos[1] - mdownGPos[1];\n var dy2 = dy * dy;\n var dist2 = dx2 + dy2;\n r.hoverData.isOverThresholdDrag = isOverThresholdDrag = dist2 >= r.desktopTapThreshold2;\n }\n var multSelKeyDown = isMultSelKeyDown(e);\n if (isOverThresholdDrag) {\n r.hoverData.tapholdCancelled = true;\n }\n var updateDragDelta = function updateDragDelta() {\n var dragDelta = r.hoverData.dragDelta = r.hoverData.dragDelta || [];\n if (dragDelta.length === 0) {\n dragDelta.push(disp[0]);\n dragDelta.push(disp[1]);\n } else {\n dragDelta[0] += disp[0];\n dragDelta[1] += disp[1];\n }\n };\n preventDefault = true;\n triggerEvents(near, ['mousemove', 'vmousemove', 'tapdrag'], e, {\n x: pos[0],\n y: pos[1]\n });\n var makeEvent = function makeEvent(type) {\n return {\n originalEvent: e,\n type: type,\n position: {\n x: pos[0],\n y: pos[1]\n }\n };\n };\n var goIntoBoxMode = function goIntoBoxMode() {\n r.data.bgActivePosistion = undefined;\n if (!r.hoverData.selecting) {\n cy.emit(makeEvent('boxstart'));\n }\n select[4] = 1;\n r.hoverData.selecting = true;\n r.redrawHint('select', true);\n r.redraw();\n };\n\n // trigger context drag if rmouse down\n if (r.hoverData.which === 3) {\n // but only if over threshold\n if (isOverThresholdDrag) {\n var cxtEvt = makeEvent('cxtdrag');\n if (down) {\n down.emit(cxtEvt);\n } else {\n cy.emit(cxtEvt);\n }\n r.hoverData.cxtDragged = true;\n if (!r.hoverData.cxtOver || near !== r.hoverData.cxtOver) {\n if (r.hoverData.cxtOver) {\n r.hoverData.cxtOver.emit(makeEvent('cxtdragout'));\n }\n r.hoverData.cxtOver = near;\n if (near) {\n near.emit(makeEvent('cxtdragover'));\n }\n }\n }\n\n // Check if we are drag panning the entire graph\n } else if (r.hoverData.dragging) {\n preventDefault = true;\n if (cy.panningEnabled() && cy.userPanningEnabled()) {\n var deltaP;\n if (r.hoverData.justStartedPan) {\n var mdPos = r.hoverData.mdownPos;\n deltaP = {\n x: (pos[0] - mdPos[0]) * zoom,\n y: (pos[1] - mdPos[1]) * zoom\n };\n r.hoverData.justStartedPan = false;\n } else {\n deltaP = {\n x: disp[0] * zoom,\n y: disp[1] * zoom\n };\n }\n cy.panBy(deltaP);\n cy.emit(makeEvent('dragpan'));\n r.hoverData.dragged = true;\n }\n\n // Needs reproject due to pan changing viewport\n pos = r.projectIntoViewport(e.clientX, e.clientY);\n\n // Checks primary button down & out of time & mouse not moved much\n } else if (select[4] == 1 && (down == null || down.pannable())) {\n if (isOverThresholdDrag) {\n if (!r.hoverData.dragging && cy.boxSelectionEnabled() && (multSelKeyDown || !cy.panningEnabled() || !cy.userPanningEnabled())) {\n goIntoBoxMode();\n } else if (!r.hoverData.selecting && cy.panningEnabled() && cy.userPanningEnabled()) {\n var allowPassthrough = allowPanningPassthrough(down, r.hoverData.downs);\n if (allowPassthrough) {\n r.hoverData.dragging = true;\n r.hoverData.justStartedPan = true;\n select[4] = 0;\n r.data.bgActivePosistion = array2point(mdownPos);\n r.redrawHint('select', true);\n r.redraw();\n }\n }\n if (down && down.pannable() && down.active()) {\n down.unactivate();\n }\n }\n } else {\n if (down && down.pannable() && down.active()) {\n down.unactivate();\n }\n if ((!down || !down.grabbed()) && near != last) {\n if (last) {\n triggerEvents(last, ['mouseout', 'tapdragout'], e, {\n x: pos[0],\n y: pos[1]\n });\n }\n if (near) {\n triggerEvents(near, ['mouseover', 'tapdragover'], e, {\n x: pos[0],\n y: pos[1]\n });\n }\n r.hoverData.last = near;\n }\n if (down) {\n if (isOverThresholdDrag) {\n // then we can take action\n\n if (cy.boxSelectionEnabled() && multSelKeyDown) {\n // then selection overrides\n if (down && down.grabbed()) {\n freeDraggedElements(draggedElements);\n down.emit(makeEvent('freeon'));\n draggedElements.emit(makeEvent('free'));\n if (r.dragData.didDrag) {\n down.emit(makeEvent('dragfreeon'));\n draggedElements.emit(makeEvent('dragfree'));\n }\n }\n goIntoBoxMode();\n } else if (down && down.grabbed() && r.nodeIsDraggable(down)) {\n // drag node\n var justStartedDrag = !r.dragData.didDrag;\n if (justStartedDrag) {\n r.redrawHint('eles', true);\n }\n r.dragData.didDrag = true; // indicate that we actually did drag the node\n\n // now, add the elements to the drag layer if not done already\n if (!r.hoverData.draggingEles) {\n addNodesToDrag(draggedElements, {\n inDragLayer: true\n });\n }\n var totalShift = {\n x: 0,\n y: 0\n };\n if (number$1(disp[0]) && number$1(disp[1])) {\n totalShift.x += disp[0];\n totalShift.y += disp[1];\n if (justStartedDrag) {\n var dragDelta = r.hoverData.dragDelta;\n if (dragDelta && number$1(dragDelta[0]) && number$1(dragDelta[1])) {\n totalShift.x += dragDelta[0];\n totalShift.y += dragDelta[1];\n }\n }\n }\n r.hoverData.draggingEles = true;\n draggedElements.silentShift(totalShift).emit(makeEvent('position')).emit(makeEvent('drag'));\n r.redrawHint('drag', true);\n r.redraw();\n }\n } else {\n // otherwise save drag delta for when we actually start dragging so the relative grab pos is constant\n updateDragDelta();\n }\n }\n\n // prevent the dragging from triggering text selection on the page\n preventDefault = true;\n }\n select[2] = pos[0];\n select[3] = pos[1];\n if (preventDefault) {\n if (e.stopPropagation) e.stopPropagation();\n if (e.preventDefault) e.preventDefault();\n return false;\n }\n }, false);\n var clickTimeout, didDoubleClick, prevClickTimeStamp;\n r.registerBinding(containerWindow, 'mouseup', function mouseupHandler(e) {\n // eslint-disable-line no-undef\n // during left mouse button gestures, ignore other buttons\n if (r.hoverData.which === 1 && e.which !== 1 && r.hoverData.capture) {\n return;\n }\n var capture = r.hoverData.capture;\n if (!capture) {\n return;\n }\n r.hoverData.capture = false;\n var cy = r.cy;\n var pos = r.projectIntoViewport(e.clientX, e.clientY);\n var select = r.selection;\n var near = r.findNearestElement(pos[0], pos[1], true, false);\n var draggedElements = r.dragData.possibleDragElements;\n var down = r.hoverData.down;\n var multSelKeyDown = isMultSelKeyDown(e);\n if (r.data.bgActivePosistion) {\n r.redrawHint('select', true);\n r.redraw();\n }\n r.hoverData.tapholdCancelled = true;\n r.data.bgActivePosistion = undefined; // not active bg now\n\n if (down) {\n down.unactivate();\n }\n var makeEvent = function makeEvent(type) {\n return {\n originalEvent: e,\n type: type,\n position: {\n x: pos[0],\n y: pos[1]\n }\n };\n };\n if (r.hoverData.which === 3) {\n var cxtEvt = makeEvent('cxttapend');\n if (down) {\n down.emit(cxtEvt);\n } else {\n cy.emit(cxtEvt);\n }\n if (!r.hoverData.cxtDragged) {\n var cxtTap = makeEvent('cxttap');\n if (down) {\n down.emit(cxtTap);\n } else {\n cy.emit(cxtTap);\n }\n }\n r.hoverData.cxtDragged = false;\n r.hoverData.which = null;\n } else if (r.hoverData.which === 1) {\n triggerEvents(near, ['mouseup', 'tapend', 'vmouseup'], e, {\n x: pos[0],\n y: pos[1]\n });\n if (!r.dragData.didDrag &&\n // didn't move a node around\n !r.hoverData.dragged &&\n // didn't pan\n !r.hoverData.selecting &&\n // not box selection\n !r.hoverData.isOverThresholdDrag // didn't move too much\n ) {\n triggerEvents(down, [\"click\", \"tap\", \"vclick\"], e, {\n x: pos[0],\n y: pos[1]\n });\n didDoubleClick = false;\n if (e.timeStamp - prevClickTimeStamp <= cy.multiClickDebounceTime()) {\n clickTimeout && clearTimeout(clickTimeout);\n didDoubleClick = true;\n prevClickTimeStamp = null;\n triggerEvents(down, [\"dblclick\", \"dbltap\", \"vdblclick\"], e, {\n x: pos[0],\n y: pos[1]\n });\n } else {\n clickTimeout = setTimeout(function () {\n if (didDoubleClick) return;\n triggerEvents(down, [\"oneclick\", \"onetap\", \"voneclick\"], e, {\n x: pos[0],\n y: pos[1]\n });\n }, cy.multiClickDebounceTime());\n prevClickTimeStamp = e.timeStamp;\n }\n }\n\n // Deselect all elements if nothing is currently under the mouse cursor and we aren't dragging something\n if (down == null // not mousedown on node\n && !r.dragData.didDrag // didn't move the node around\n && !r.hoverData.selecting // not box selection\n && !r.hoverData.dragged // didn't pan\n && !isMultSelKeyDown(e)) {\n cy.$(isSelected).unselect(['tapunselect']);\n if (draggedElements.length > 0) {\n r.redrawHint('eles', true);\n }\n r.dragData.possibleDragElements = draggedElements = cy.collection();\n }\n\n // Single selection\n if (near == down && !r.dragData.didDrag && !r.hoverData.selecting) {\n if (near != null && near._private.selectable) {\n if (r.hoverData.dragging) ; else if (cy.selectionType() === 'additive' || multSelKeyDown) {\n if (near.selected()) {\n near.unselect(['tapunselect']);\n } else {\n near.select(['tapselect']);\n }\n } else {\n if (!multSelKeyDown) {\n cy.$(isSelected).unmerge(near).unselect(['tapunselect']);\n near.select(['tapselect']);\n }\n }\n r.redrawHint('eles', true);\n }\n }\n if (r.hoverData.selecting) {\n var box = cy.collection(r.getAllInBox(select[0], select[1], select[2], select[3]));\n r.redrawHint('select', true);\n if (box.length > 0) {\n r.redrawHint('eles', true);\n }\n cy.emit(makeEvent('boxend'));\n var eleWouldBeSelected = function eleWouldBeSelected(ele) {\n return ele.selectable() && !ele.selected();\n };\n if (cy.selectionType() === 'additive') {\n box.emit(makeEvent('box')).stdFilter(eleWouldBeSelected).select().emit(makeEvent('boxselect'));\n } else {\n if (!multSelKeyDown) {\n cy.$(isSelected).unmerge(box).unselect();\n }\n box.emit(makeEvent('box')).stdFilter(eleWouldBeSelected).select().emit(makeEvent('boxselect'));\n }\n\n // always need redraw in case eles unselectable\n r.redraw();\n }\n\n // Cancel drag pan\n if (r.hoverData.dragging) {\n r.hoverData.dragging = false;\n r.redrawHint('select', true);\n r.redrawHint('eles', true);\n r.redraw();\n }\n if (!select[4]) {\n r.redrawHint('drag', true);\n r.redrawHint('eles', true);\n var downWasGrabbed = down && down.grabbed();\n freeDraggedElements(draggedElements);\n if (downWasGrabbed) {\n down.emit(makeEvent('freeon'));\n draggedElements.emit(makeEvent('free'));\n if (r.dragData.didDrag) {\n down.emit(makeEvent('dragfreeon'));\n draggedElements.emit(makeEvent('dragfree'));\n }\n }\n }\n } // else not right mouse\n\n select[4] = 0;\n r.hoverData.down = null;\n r.hoverData.cxtStarted = false;\n r.hoverData.draggingEles = false;\n r.hoverData.selecting = false;\n r.hoverData.isOverThresholdDrag = false;\n r.dragData.didDrag = false;\n r.hoverData.dragged = false;\n r.hoverData.dragDelta = [];\n r.hoverData.mdownPos = null;\n r.hoverData.mdownGPos = null;\n r.hoverData.which = null;\n }, false);\n var wheelDeltas = []; // log of first N wheel deltas\n var wheelDeltaN = 4; // how many events to log\n var inaccurateScrollDevice;\n var inaccurateScrollFactor = 100000; // base of inaccurate wheel deltas (e.g. base 5 could yield wheels of 10, 25, 50, etc.)\n\n var allAreDivisibleBy = function allAreDivisibleBy(list, factor) {\n for (var i = 0; i < list.length; i++) {\n if (list[i] % factor !== 0) {\n return false;\n }\n }\n return true;\n };\n var allAreSameMagnitude = function allAreSameMagnitude(list) {\n var firstMag = Math.abs(list[0]);\n for (var i = 1; i < list.length; i++) {\n if (Math.abs(list[i]) !== firstMag) {\n return false;\n }\n }\n return true;\n };\n var wheelHandler = function wheelHandler(e) {\n var clamp = false;\n var delta = e.deltaY;\n if (delta == null) {\n // compatibility with old browsers\n if (e.wheelDeltaY != null) {\n delta = e.wheelDeltaY / 4;\n } else if (e.wheelDelta != null) {\n delta = e.wheelDelta / 4;\n }\n }\n if (delta === 0) {\n return; // no change in zoom (Bug: Zoom becomes erratic on rapid scroll due to deltaY: 0 event #3394)\n }\n if (inaccurateScrollDevice == null) {\n if (wheelDeltas.length >= wheelDeltaN) {\n // use log to determine if inaccurate\n var wds = wheelDeltas;\n inaccurateScrollDevice = allAreDivisibleBy(wds, 5);\n if (!inaccurateScrollDevice) {\n // check for all large values of exact same magnitude\n var firstMag = Math.abs(wds[0]);\n inaccurateScrollDevice = allAreSameMagnitude(wds) && firstMag > 5;\n }\n if (inaccurateScrollDevice) {\n for (var i = 0; i < wds.length; i++) {\n inaccurateScrollFactor = Math.min(Math.abs(wds[i]), inaccurateScrollFactor);\n }\n }\n\n // console.log('Sampled wheel deltas:', wds);\n // console.log('inaccurateScrollDevice:', inaccurateScrollDevice);\n // console.log('inaccurateScrollFactor:', inaccurateScrollFactor);\n } else {\n // clamp and log until we reach N\n wheelDeltas.push(delta);\n clamp = true;\n // console.log('Clamping initial wheel events until we get a good sample');\n }\n } else if (inaccurateScrollDevice) {\n // keep updating\n inaccurateScrollFactor = Math.min(Math.abs(delta), inaccurateScrollFactor);\n // console.log('Keep updating inaccurateScrollFactor beyond sample in case we did not get the smallest possible val:', inaccurateScrollFactor);\n }\n if (r.scrollingPage) {\n return;\n } // while scrolling, ignore wheel-to-zoom\n\n var cy = r.cy;\n var zoom = cy.zoom();\n var pan = cy.pan();\n var pos = r.projectIntoViewport(e.clientX, e.clientY);\n var rpos = [pos[0] * zoom + pan.x, pos[1] * zoom + pan.y];\n if (r.hoverData.draggingEles || r.hoverData.dragging || r.hoverData.cxtStarted || inBoxSelection()) {\n // if pan dragging or cxt dragging, wheel movements make no zoom\n e.preventDefault();\n return;\n }\n if (cy.panningEnabled() && cy.userPanningEnabled() && cy.zoomingEnabled() && cy.userZoomingEnabled()) {\n e.preventDefault();\n r.data.wheelZooming = true;\n clearTimeout(r.data.wheelTimeout);\n r.data.wheelTimeout = setTimeout(function () {\n r.data.wheelZooming = false;\n r.redrawHint('eles', true);\n r.redraw();\n }, 150);\n var diff;\n if (clamp && Math.abs(delta) > 5) {\n delta = signum(delta) * 5;\n }\n diff = delta / -250;\n if (inaccurateScrollDevice) {\n diff /= inaccurateScrollFactor;\n diff *= 3;\n }\n diff = diff * r.wheelSensitivity;\n\n // console.log(`delta = ${delta}, diff = ${diff}, mode = ${e.deltaMode}`)\n\n var needsWheelFix = e.deltaMode === 1;\n if (needsWheelFix) {\n // fixes slow wheel events on ff/linux and ff/windows\n diff *= 33;\n }\n var newZoom = cy.zoom() * Math.pow(10, diff);\n if (e.type === 'gesturechange') {\n newZoom = r.gestureStartZoom * e.scale;\n }\n cy.zoom({\n level: newZoom,\n renderedPosition: {\n x: rpos[0],\n y: rpos[1]\n }\n });\n cy.emit({\n type: e.type === 'gesturechange' ? 'pinchzoom' : 'scrollzoom',\n originalEvent: e,\n position: {\n x: pos[0],\n y: pos[1]\n }\n });\n }\n };\n\n // Functions to help with whether mouse wheel should trigger zooming\n // --\n r.registerBinding(r.container, 'wheel', wheelHandler, true);\n\n // disable nonstandard wheel events\n // r.registerBinding(r.container, 'mousewheel', wheelHandler, true);\n // r.registerBinding(r.container, 'DOMMouseScroll', wheelHandler, true);\n // r.registerBinding(r.container, 'MozMousePixelScroll', wheelHandler, true); // older firefox\n\n r.registerBinding(containerWindow, 'scroll', function scrollHandler(e) {\n // eslint-disable-line no-unused-vars\n r.scrollingPage = true;\n clearTimeout(r.scrollingPageTimeout);\n r.scrollingPageTimeout = setTimeout(function () {\n r.scrollingPage = false;\n }, 250);\n }, true);\n\n // desktop safari pinch to zoom start\n r.registerBinding(r.container, 'gesturestart', function gestureStartHandler(e) {\n r.gestureStartZoom = r.cy.zoom();\n if (!r.hasTouchStarted) {\n // don't affect touch devices like iphone\n e.preventDefault();\n }\n }, true);\n r.registerBinding(r.container, 'gesturechange', function (e) {\n if (!r.hasTouchStarted) {\n // don't affect touch devices like iphone\n wheelHandler(e);\n }\n }, true);\n\n // Functions to help with handling mouseout/mouseover on the Cytoscape container\n // Handle mouseout on Cytoscape container\n r.registerBinding(r.container, 'mouseout', function mouseOutHandler(e) {\n var pos = r.projectIntoViewport(e.clientX, e.clientY);\n r.cy.emit({\n originalEvent: e,\n type: 'mouseout',\n position: {\n x: pos[0],\n y: pos[1]\n }\n });\n }, false);\n r.registerBinding(r.container, 'mouseover', function mouseOverHandler(e) {\n var pos = r.projectIntoViewport(e.clientX, e.clientY);\n r.cy.emit({\n originalEvent: e,\n type: 'mouseover',\n position: {\n x: pos[0],\n y: pos[1]\n }\n });\n }, false);\n var f1x1, f1y1, f2x1, f2y1; // starting points for pinch-to-zoom\n var distance1, distance1Sq; // initial distance between finger 1 and finger 2 for pinch-to-zoom\n var center1, modelCenter1; // center point on start pinch to zoom\n var offsetLeft, offsetTop;\n var containerWidth, containerHeight;\n var twoFingersStartInside;\n var distance = function distance(x1, y1, x2, y2) {\n return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));\n };\n var distanceSq = function distanceSq(x1, y1, x2, y2) {\n return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n };\n var touchstartHandler;\n r.registerBinding(r.container, 'touchstart', touchstartHandler = function touchstartHandler(e) {\n r.hasTouchStarted = true;\n if (!eventInContainer(e)) {\n return;\n }\n blurActiveDomElement();\n r.touchData.capture = true;\n r.data.bgActivePosistion = undefined;\n var cy = r.cy;\n var now = r.touchData.now;\n var earlier = r.touchData.earlier;\n if (e.touches[0]) {\n var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);\n now[0] = pos[0];\n now[1] = pos[1];\n }\n if (e.touches[1]) {\n var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);\n now[2] = pos[0];\n now[3] = pos[1];\n }\n if (e.touches[2]) {\n var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);\n now[4] = pos[0];\n now[5] = pos[1];\n }\n var makeEvent = function makeEvent(type) {\n return {\n originalEvent: e,\n type: type,\n position: {\n x: now[0],\n y: now[1]\n }\n };\n };\n\n // record starting points for pinch-to-zoom\n if (e.touches[1]) {\n r.touchData.singleTouchMoved = true;\n freeDraggedElements(r.dragData.touchDragEles);\n var offsets = r.findContainerClientCoords();\n offsetLeft = offsets[0];\n offsetTop = offsets[1];\n containerWidth = offsets[2];\n containerHeight = offsets[3];\n f1x1 = e.touches[0].clientX - offsetLeft;\n f1y1 = e.touches[0].clientY - offsetTop;\n f2x1 = e.touches[1].clientX - offsetLeft;\n f2y1 = e.touches[1].clientY - offsetTop;\n twoFingersStartInside = 0 <= f1x1 && f1x1 <= containerWidth && 0 <= f2x1 && f2x1 <= containerWidth && 0 <= f1y1 && f1y1 <= containerHeight && 0 <= f2y1 && f2y1 <= containerHeight;\n var pan = cy.pan();\n var zoom = cy.zoom();\n distance1 = distance(f1x1, f1y1, f2x1, f2y1);\n distance1Sq = distanceSq(f1x1, f1y1, f2x1, f2y1);\n center1 = [(f1x1 + f2x1) / 2, (f1y1 + f2y1) / 2];\n modelCenter1 = [(center1[0] - pan.x) / zoom, (center1[1] - pan.y) / zoom];\n\n // consider context tap\n var cxtDistThreshold = 200;\n var cxtDistThresholdSq = cxtDistThreshold * cxtDistThreshold;\n if (distance1Sq < cxtDistThresholdSq && !e.touches[2]) {\n var near1 = r.findNearestElement(now[0], now[1], true, true);\n var near2 = r.findNearestElement(now[2], now[3], true, true);\n if (near1 && near1.isNode()) {\n near1.activate().emit(makeEvent('cxttapstart'));\n r.touchData.start = near1;\n } else if (near2 && near2.isNode()) {\n near2.activate().emit(makeEvent('cxttapstart'));\n r.touchData.start = near2;\n } else {\n cy.emit(makeEvent('cxttapstart'));\n }\n if (r.touchData.start) {\n r.touchData.start._private.grabbed = false;\n }\n r.touchData.cxt = true;\n r.touchData.cxtDragged = false;\n r.data.bgActivePosistion = undefined;\n r.redraw();\n return;\n }\n }\n if (e.touches[2]) {\n // ignore\n\n // safari on ios pans the page otherwise (normally you should be able to preventdefault on touchmove...)\n if (cy.boxSelectionEnabled()) {\n e.preventDefault();\n }\n } else if (e.touches[1]) ; else if (e.touches[0]) {\n var nears = r.findNearestElements(now[0], now[1], true, true);\n var near = nears[0];\n if (near != null) {\n near.activate();\n r.touchData.start = near;\n r.touchData.starts = nears;\n if (r.nodeIsGrabbable(near)) {\n var draggedEles = r.dragData.touchDragEles = cy.collection();\n var selectedNodes = null;\n r.redrawHint('eles', true);\n r.redrawHint('drag', true);\n if (near.selected()) {\n // reset drag elements, since near will be added again\n\n selectedNodes = cy.$(function (ele) {\n return ele.selected() && r.nodeIsGrabbable(ele);\n });\n addNodesToDrag(selectedNodes, {\n addToList: draggedEles\n });\n } else {\n addNodeToDrag(near, {\n addToList: draggedEles\n });\n }\n setGrabTarget(near);\n near.emit(makeEvent('grabon'));\n if (selectedNodes) {\n selectedNodes.forEach(function (n) {\n n.emit(makeEvent('grab'));\n });\n } else {\n near.emit(makeEvent('grab'));\n }\n }\n }\n triggerEvents(near, ['touchstart', 'tapstart', 'vmousedown'], e, {\n x: now[0],\n y: now[1]\n });\n if (near == null) {\n r.data.bgActivePosistion = {\n x: pos[0],\n y: pos[1]\n };\n r.redrawHint('select', true);\n r.redraw();\n }\n\n // Tap, taphold\n // -----\n\n r.touchData.singleTouchMoved = false;\n r.touchData.singleTouchStartTime = +new Date();\n clearTimeout(r.touchData.tapholdTimeout);\n r.touchData.tapholdTimeout = setTimeout(function () {\n if (r.touchData.singleTouchMoved === false && !r.pinching // if pinching, then taphold unselect shouldn't take effect\n && !r.touchData.selecting // box selection shouldn't allow taphold through\n ) {\n triggerEvents(r.touchData.start, ['taphold'], e, {\n x: now[0],\n y: now[1]\n });\n }\n }, r.tapholdDuration);\n }\n if (e.touches.length >= 1) {\n var sPos = r.touchData.startPosition = [null, null, null, null, null, null];\n for (var i = 0; i < now.length; i++) {\n sPos[i] = earlier[i] = now[i];\n }\n var touch0 = e.touches[0];\n r.touchData.startGPosition = [touch0.clientX, touch0.clientY];\n }\n }, false);\n var touchmoveHandler;\n r.registerBinding(containerWindow, 'touchmove', touchmoveHandler = function touchmoveHandler(e) {\n // eslint-disable-line no-undef\n var capture = r.touchData.capture;\n if (!capture && !eventInContainer(e)) {\n return;\n }\n var select = r.selection;\n var cy = r.cy;\n var now = r.touchData.now;\n var earlier = r.touchData.earlier;\n var zoom = cy.zoom();\n if (e.touches[0]) {\n var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);\n now[0] = pos[0];\n now[1] = pos[1];\n }\n if (e.touches[1]) {\n var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);\n now[2] = pos[0];\n now[3] = pos[1];\n }\n if (e.touches[2]) {\n var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);\n now[4] = pos[0];\n now[5] = pos[1];\n }\n var makeEvent = function makeEvent(type) {\n return {\n originalEvent: e,\n type: type,\n position: {\n x: now[0],\n y: now[1]\n }\n };\n };\n var startGPos = r.touchData.startGPosition;\n var isOverThresholdDrag;\n if (capture && e.touches[0] && startGPos) {\n var disp = [];\n for (var j = 0; j < now.length; j++) {\n disp[j] = now[j] - earlier[j];\n }\n var dx = e.touches[0].clientX - startGPos[0];\n var dx2 = dx * dx;\n var dy = e.touches[0].clientY - startGPos[1];\n var dy2 = dy * dy;\n var dist2 = dx2 + dy2;\n isOverThresholdDrag = dist2 >= r.touchTapThreshold2;\n }\n\n // context swipe cancelling\n if (capture && r.touchData.cxt) {\n e.preventDefault();\n var f1x2 = e.touches[0].clientX - offsetLeft,\n f1y2 = e.touches[0].clientY - offsetTop;\n var f2x2 = e.touches[1].clientX - offsetLeft,\n f2y2 = e.touches[1].clientY - offsetTop;\n // var distance2 = distance( f1x2, f1y2, f2x2, f2y2 );\n var distance2Sq = distanceSq(f1x2, f1y2, f2x2, f2y2);\n var factorSq = distance2Sq / distance1Sq;\n var distThreshold = 150;\n var distThresholdSq = distThreshold * distThreshold;\n var factorThreshold = 1.5;\n var factorThresholdSq = factorThreshold * factorThreshold;\n\n // cancel ctx gestures if the distance b/t the fingers increases\n if (factorSq >= factorThresholdSq || distance2Sq >= distThresholdSq) {\n r.touchData.cxt = false;\n r.data.bgActivePosistion = undefined;\n r.redrawHint('select', true);\n var cxtEvt = makeEvent('cxttapend');\n if (r.touchData.start) {\n r.touchData.start.unactivate().emit(cxtEvt);\n r.touchData.start = null;\n } else {\n cy.emit(cxtEvt);\n }\n }\n }\n\n // context swipe\n if (capture && r.touchData.cxt) {\n var cxtEvt = makeEvent('cxtdrag');\n r.data.bgActivePosistion = undefined;\n r.redrawHint('select', true);\n if (r.touchData.start) {\n r.touchData.start.emit(cxtEvt);\n } else {\n cy.emit(cxtEvt);\n }\n if (r.touchData.start) {\n r.touchData.start._private.grabbed = false;\n }\n r.touchData.cxtDragged = true;\n var near = r.findNearestElement(now[0], now[1], true, true);\n if (!r.touchData.cxtOver || near !== r.touchData.cxtOver) {\n if (r.touchData.cxtOver) {\n r.touchData.cxtOver.emit(makeEvent('cxtdragout'));\n }\n r.touchData.cxtOver = near;\n if (near) {\n near.emit(makeEvent('cxtdragover'));\n }\n }\n\n // box selection\n } else if (capture && e.touches[2] && cy.boxSelectionEnabled()) {\n e.preventDefault();\n r.data.bgActivePosistion = undefined;\n this.lastThreeTouch = +new Date();\n if (!r.touchData.selecting) {\n cy.emit(makeEvent('boxstart'));\n }\n r.touchData.selecting = true;\n r.touchData.didSelect = true;\n select[4] = 1;\n if (!select || select.length === 0 || select[0] === undefined) {\n select[0] = (now[0] + now[2] + now[4]) / 3;\n select[1] = (now[1] + now[3] + now[5]) / 3;\n select[2] = (now[0] + now[2] + now[4]) / 3 + 1;\n select[3] = (now[1] + now[3] + now[5]) / 3 + 1;\n } else {\n select[2] = (now[0] + now[2] + now[4]) / 3;\n select[3] = (now[1] + now[3] + now[5]) / 3;\n }\n r.redrawHint('select', true);\n r.redraw();\n\n // pinch to zoom\n } else if (capture && e.touches[1] && !r.touchData.didSelect // don't allow box selection to degrade to pinch-to-zoom\n && cy.zoomingEnabled() && cy.panningEnabled() && cy.userZoomingEnabled() && cy.userPanningEnabled()) {\n // two fingers => pinch to zoom\n e.preventDefault();\n r.data.bgActivePosistion = undefined;\n r.redrawHint('select', true);\n var draggedEles = r.dragData.touchDragEles;\n if (draggedEles) {\n r.redrawHint('drag', true);\n for (var i = 0; i < draggedEles.length; i++) {\n var de_p = draggedEles[i]._private;\n de_p.grabbed = false;\n de_p.rscratch.inDragLayer = false;\n }\n }\n var _start = r.touchData.start;\n\n // (x2, y2) for fingers 1 and 2\n var f1x2 = e.touches[0].clientX - offsetLeft,\n f1y2 = e.touches[0].clientY - offsetTop;\n var f2x2 = e.touches[1].clientX - offsetLeft,\n f2y2 = e.touches[1].clientY - offsetTop;\n var distance2 = distance(f1x2, f1y2, f2x2, f2y2);\n // var distance2Sq = distanceSq( f1x2, f1y2, f2x2, f2y2 );\n // var factor = Math.sqrt( distance2Sq ) / Math.sqrt( distance1Sq );\n var factor = distance2 / distance1;\n if (twoFingersStartInside) {\n // delta finger1\n var df1x = f1x2 - f1x1;\n var df1y = f1y2 - f1y1;\n\n // delta finger 2\n var df2x = f2x2 - f2x1;\n var df2y = f2y2 - f2y1;\n\n // translation is the normalised vector of the two fingers movement\n // i.e. so pinching cancels out and moving together pans\n var tx = (df1x + df2x) / 2;\n var ty = (df1y + df2y) / 2;\n\n // now calculate the zoom\n var zoom1 = cy.zoom();\n var zoom2 = zoom1 * factor;\n var pan1 = cy.pan();\n\n // the model center point converted to the current rendered pos\n var ctrx = modelCenter1[0] * zoom1 + pan1.x;\n var ctry = modelCenter1[1] * zoom1 + pan1.y;\n var pan2 = {\n x: -zoom2 / zoom1 * (ctrx - pan1.x - tx) + ctrx,\n y: -zoom2 / zoom1 * (ctry - pan1.y - ty) + ctry\n };\n\n // remove dragged eles\n if (_start && _start.active()) {\n var draggedEles = r.dragData.touchDragEles;\n freeDraggedElements(draggedEles);\n r.redrawHint('drag', true);\n r.redrawHint('eles', true);\n _start.unactivate().emit(makeEvent('freeon'));\n draggedEles.emit(makeEvent('free'));\n if (r.dragData.didDrag) {\n _start.emit(makeEvent('dragfreeon'));\n draggedEles.emit(makeEvent('dragfree'));\n }\n }\n cy.viewport({\n zoom: zoom2,\n pan: pan2,\n cancelOnFailedZoom: true\n });\n cy.emit(makeEvent('pinchzoom'));\n distance1 = distance2;\n f1x1 = f1x2;\n f1y1 = f1y2;\n f2x1 = f2x2;\n f2y1 = f2y2;\n r.pinching = true;\n }\n\n // Re-project\n if (e.touches[0]) {\n var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);\n now[0] = pos[0];\n now[1] = pos[1];\n }\n if (e.touches[1]) {\n var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);\n now[2] = pos[0];\n now[3] = pos[1];\n }\n if (e.touches[2]) {\n var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);\n now[4] = pos[0];\n now[5] = pos[1];\n }\n } else if (e.touches[0] && !r.touchData.didSelect // don't allow box selection to degrade to single finger events like panning\n ) {\n var start = r.touchData.start;\n var last = r.touchData.last;\n var near;\n if (!r.hoverData.draggingEles && !r.swipePanning) {\n near = r.findNearestElement(now[0], now[1], true, true);\n }\n if (capture && start != null) {\n e.preventDefault();\n }\n\n // dragging nodes\n if (capture && start != null && r.nodeIsDraggable(start)) {\n if (isOverThresholdDrag) {\n // then dragging can happen\n var draggedEles = r.dragData.touchDragEles;\n var justStartedDrag = !r.dragData.didDrag;\n if (justStartedDrag) {\n addNodesToDrag(draggedEles, {\n inDragLayer: true\n });\n }\n r.dragData.didDrag = true;\n var totalShift = {\n x: 0,\n y: 0\n };\n if (number$1(disp[0]) && number$1(disp[1])) {\n totalShift.x += disp[0];\n totalShift.y += disp[1];\n if (justStartedDrag) {\n r.redrawHint('eles', true);\n var dragDelta = r.touchData.dragDelta;\n if (dragDelta && number$1(dragDelta[0]) && number$1(dragDelta[1])) {\n totalShift.x += dragDelta[0];\n totalShift.y += dragDelta[1];\n }\n }\n }\n r.hoverData.draggingEles = true;\n draggedEles.silentShift(totalShift).emit(makeEvent('position')).emit(makeEvent('drag'));\n r.redrawHint('drag', true);\n if (r.touchData.startPosition[0] == earlier[0] && r.touchData.startPosition[1] == earlier[1]) {\n r.redrawHint('eles', true);\n }\n r.redraw();\n } else {\n // otherwise keep track of drag delta for later\n var dragDelta = r.touchData.dragDelta = r.touchData.dragDelta || [];\n if (dragDelta.length === 0) {\n dragDelta.push(disp[0]);\n dragDelta.push(disp[1]);\n } else {\n dragDelta[0] += disp[0];\n dragDelta[1] += disp[1];\n }\n }\n }\n\n // touchmove\n {\n triggerEvents(start || near, ['touchmove', 'tapdrag', 'vmousemove'], e, {\n x: now[0],\n y: now[1]\n });\n if ((!start || !start.grabbed()) && near != last) {\n if (last) {\n last.emit(makeEvent('tapdragout'));\n }\n if (near) {\n near.emit(makeEvent('tapdragover'));\n }\n }\n r.touchData.last = near;\n }\n\n // check to cancel taphold\n if (capture) {\n for (var i = 0; i < now.length; i++) {\n if (now[i] && r.touchData.startPosition[i] && isOverThresholdDrag) {\n r.touchData.singleTouchMoved = true;\n }\n }\n }\n\n // panning\n if (capture && (start == null || start.pannable()) && cy.panningEnabled() && cy.userPanningEnabled()) {\n var allowPassthrough = allowPanningPassthrough(start, r.touchData.starts);\n if (allowPassthrough) {\n e.preventDefault();\n if (!r.data.bgActivePosistion) {\n r.data.bgActivePosistion = array2point(r.touchData.startPosition);\n }\n if (r.swipePanning) {\n cy.panBy({\n x: disp[0] * zoom,\n y: disp[1] * zoom\n });\n cy.emit(makeEvent('dragpan'));\n } else if (isOverThresholdDrag) {\n r.swipePanning = true;\n cy.panBy({\n x: dx * zoom,\n y: dy * zoom\n });\n cy.emit(makeEvent('dragpan'));\n if (start) {\n start.unactivate();\n r.redrawHint('select', true);\n r.touchData.start = null;\n }\n }\n }\n\n // Re-project\n var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);\n now[0] = pos[0];\n now[1] = pos[1];\n }\n }\n for (var j = 0; j < now.length; j++) {\n earlier[j] = now[j];\n }\n\n // the active bg indicator should be removed when making a swipe that is neither for dragging nodes or panning\n if (capture && e.touches.length > 0 && !r.hoverData.draggingEles && !r.swipePanning && r.data.bgActivePosistion != null) {\n r.data.bgActivePosistion = undefined;\n r.redrawHint('select', true);\n r.redraw();\n }\n }, false);\n var touchcancelHandler;\n r.registerBinding(containerWindow, 'touchcancel', touchcancelHandler = function touchcancelHandler(e) {\n // eslint-disable-line no-unused-vars\n var start = r.touchData.start;\n r.touchData.capture = false;\n if (start) {\n start.unactivate();\n }\n });\n var touchendHandler, didDoubleTouch, touchTimeout, prevTouchTimeStamp;\n r.registerBinding(containerWindow, 'touchend', touchendHandler = function touchendHandler(e) {\n // eslint-disable-line no-unused-vars\n var start = r.touchData.start;\n var capture = r.touchData.capture;\n if (capture) {\n if (e.touches.length === 0) {\n r.touchData.capture = false;\n }\n e.preventDefault();\n } else {\n return;\n }\n var select = r.selection;\n r.swipePanning = false;\n r.hoverData.draggingEles = false;\n var cy = r.cy;\n var zoom = cy.zoom();\n var now = r.touchData.now;\n var earlier = r.touchData.earlier;\n if (e.touches[0]) {\n var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);\n now[0] = pos[0];\n now[1] = pos[1];\n }\n if (e.touches[1]) {\n var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);\n now[2] = pos[0];\n now[3] = pos[1];\n }\n if (e.touches[2]) {\n var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);\n now[4] = pos[0];\n now[5] = pos[1];\n }\n var makeEvent = function makeEvent(type) {\n return {\n originalEvent: e,\n type: type,\n position: {\n x: now[0],\n y: now[1]\n }\n };\n };\n if (start) {\n start.unactivate();\n }\n var ctxTapend;\n if (r.touchData.cxt) {\n ctxTapend = makeEvent('cxttapend');\n if (start) {\n start.emit(ctxTapend);\n } else {\n cy.emit(ctxTapend);\n }\n if (!r.touchData.cxtDragged) {\n var ctxTap = makeEvent('cxttap');\n if (start) {\n start.emit(ctxTap);\n } else {\n cy.emit(ctxTap);\n }\n }\n if (r.touchData.start) {\n r.touchData.start._private.grabbed = false;\n }\n r.touchData.cxt = false;\n r.touchData.start = null;\n r.redraw();\n return;\n }\n\n // no more box selection if we don't have three fingers\n if (!e.touches[2] && cy.boxSelectionEnabled() && r.touchData.selecting) {\n r.touchData.selecting = false;\n var box = cy.collection(r.getAllInBox(select[0], select[1], select[2], select[3]));\n select[0] = undefined;\n select[1] = undefined;\n select[2] = undefined;\n select[3] = undefined;\n select[4] = 0;\n r.redrawHint('select', true);\n cy.emit(makeEvent('boxend'));\n var eleWouldBeSelected = function eleWouldBeSelected(ele) {\n return ele.selectable() && !ele.selected();\n };\n box.emit(makeEvent('box')).stdFilter(eleWouldBeSelected).select().emit(makeEvent('boxselect'));\n if (box.nonempty()) {\n r.redrawHint('eles', true);\n }\n r.redraw();\n }\n if (start != null) {\n start.unactivate();\n }\n if (e.touches[2]) {\n r.data.bgActivePosistion = undefined;\n r.redrawHint('select', true);\n } else if (e.touches[1]) ; else if (e.touches[0]) ; else if (!e.touches[0]) {\n r.data.bgActivePosistion = undefined;\n r.redrawHint('select', true);\n var draggedEles = r.dragData.touchDragEles;\n if (start != null) {\n var startWasGrabbed = start._private.grabbed;\n freeDraggedElements(draggedEles);\n r.redrawHint('drag', true);\n r.redrawHint('eles', true);\n if (startWasGrabbed) {\n start.emit(makeEvent('freeon'));\n draggedEles.emit(makeEvent('free'));\n if (r.dragData.didDrag) {\n start.emit(makeEvent('dragfreeon'));\n draggedEles.emit(makeEvent('dragfree'));\n }\n }\n triggerEvents(start, ['touchend', 'tapend', 'vmouseup', 'tapdragout'], e, {\n x: now[0],\n y: now[1]\n });\n start.unactivate();\n r.touchData.start = null;\n } else {\n var near = r.findNearestElement(now[0], now[1], true, true);\n triggerEvents(near, ['touchend', 'tapend', 'vmouseup', 'tapdragout'], e, {\n x: now[0],\n y: now[1]\n });\n }\n var dx = r.touchData.startPosition[0] - now[0];\n var dx2 = dx * dx;\n var dy = r.touchData.startPosition[1] - now[1];\n var dy2 = dy * dy;\n var dist2 = dx2 + dy2;\n var rdist2 = dist2 * zoom * zoom;\n\n // Tap event, roughly same as mouse click event for touch\n if (!r.touchData.singleTouchMoved) {\n if (!start) {\n cy.$(':selected').unselect(['tapunselect']);\n }\n triggerEvents(start, ['tap', 'vclick'], e, {\n x: now[0],\n y: now[1]\n });\n didDoubleTouch = false;\n if (e.timeStamp - prevTouchTimeStamp <= cy.multiClickDebounceTime()) {\n touchTimeout && clearTimeout(touchTimeout);\n didDoubleTouch = true;\n prevTouchTimeStamp = null;\n triggerEvents(start, ['dbltap', 'vdblclick'], e, {\n x: now[0],\n y: now[1]\n });\n } else {\n touchTimeout = setTimeout(function () {\n if (didDoubleTouch) return;\n triggerEvents(start, ['onetap', 'voneclick'], e, {\n x: now[0],\n y: now[1]\n });\n }, cy.multiClickDebounceTime());\n prevTouchTimeStamp = e.timeStamp;\n }\n }\n\n // Prepare to select the currently touched node, only if it hasn't been dragged past a certain distance\n if (start != null && !r.dragData.didDrag // didn't drag nodes around\n && start._private.selectable && rdist2 < r.touchTapThreshold2 && !r.pinching // pinch to zoom should not affect selection\n ) {\n if (cy.selectionType() === 'single') {\n cy.$(isSelected).unmerge(start).unselect(['tapunselect']);\n start.select(['tapselect']);\n } else {\n if (start.selected()) {\n start.unselect(['tapunselect']);\n } else {\n start.select(['tapselect']);\n }\n }\n r.redrawHint('eles', true);\n }\n r.touchData.singleTouchMoved = true;\n }\n for (var j = 0; j < now.length; j++) {\n earlier[j] = now[j];\n }\n r.dragData.didDrag = false; // reset for next touchstart\n\n if (e.touches.length === 0) {\n r.touchData.dragDelta = [];\n r.touchData.startPosition = [null, null, null, null, null, null];\n r.touchData.startGPosition = null;\n r.touchData.didSelect = false;\n }\n if (e.touches.length < 2) {\n if (e.touches.length === 1) {\n // the old start global pos'n may not be the same finger that remains\n r.touchData.startGPosition = [e.touches[0].clientX, e.touches[0].clientY];\n }\n r.pinching = false;\n r.redrawHint('eles', true);\n r.redraw();\n }\n\n //r.redraw();\n }, false);\n\n // fallback compatibility layer for ms pointer events\n if (typeof TouchEvent === 'undefined') {\n var pointers = [];\n var makeTouch = function makeTouch(e) {\n return {\n clientX: e.clientX,\n clientY: e.clientY,\n force: 1,\n identifier: e.pointerId,\n pageX: e.pageX,\n pageY: e.pageY,\n radiusX: e.width / 2,\n radiusY: e.height / 2,\n screenX: e.screenX,\n screenY: e.screenY,\n target: e.target\n };\n };\n var makePointer = function makePointer(e) {\n return {\n event: e,\n touch: makeTouch(e)\n };\n };\n var addPointer = function addPointer(e) {\n pointers.push(makePointer(e));\n };\n var removePointer = function removePointer(e) {\n for (var i = 0; i < pointers.length; i++) {\n var p = pointers[i];\n if (p.event.pointerId === e.pointerId) {\n pointers.splice(i, 1);\n return;\n }\n }\n };\n var updatePointer = function updatePointer(e) {\n var p = pointers.filter(function (p) {\n return p.event.pointerId === e.pointerId;\n })[0];\n p.event = e;\n p.touch = makeTouch(e);\n };\n var addTouchesToEvent = function addTouchesToEvent(e) {\n e.touches = pointers.map(function (p) {\n return p.touch;\n });\n };\n var pointerIsMouse = function pointerIsMouse(e) {\n return e.pointerType === 'mouse' || e.pointerType === 4;\n };\n r.registerBinding(r.container, 'pointerdown', function (e) {\n if (pointerIsMouse(e)) {\n return;\n } // mouse already handled\n\n e.preventDefault();\n addPointer(e);\n addTouchesToEvent(e);\n touchstartHandler(e);\n });\n r.registerBinding(r.container, 'pointerup', function (e) {\n if (pointerIsMouse(e)) {\n return;\n } // mouse already handled\n\n removePointer(e);\n addTouchesToEvent(e);\n touchendHandler(e);\n });\n r.registerBinding(r.container, 'pointercancel', function (e) {\n if (pointerIsMouse(e)) {\n return;\n } // mouse already handled\n\n removePointer(e);\n addTouchesToEvent(e);\n touchcancelHandler(e);\n });\n r.registerBinding(r.container, 'pointermove', function (e) {\n if (pointerIsMouse(e)) {\n return;\n } // mouse already handled\n\n e.preventDefault();\n updatePointer(e);\n addTouchesToEvent(e);\n touchmoveHandler(e);\n });\n }\n};\n\nvar BRp$2 = {};\nBRp$2.generatePolygon = function (name, points) {\n return this.nodeShapes[name] = {\n renderer: this,\n name: name,\n points: points,\n draw: function draw(context, centerX, centerY, width, height, cornerRadius) {\n this.renderer.nodeShapeImpl('polygon', context, centerX, centerY, width, height, this.points);\n },\n intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {\n return polygonIntersectLine(x, y, this.points, nodeX, nodeY, width / 2, height / 2, padding);\n },\n checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {\n return pointInsidePolygon(x, y, this.points, centerX, centerY, width, height, [0, -1], padding);\n },\n hasMiterBounds: name !== 'rectangle',\n miterBounds: function miterBounds(centerX, centerY, width, height, strokeWidth, strokePosition) {\n return miterBox(this.points, centerX, centerY, width, height, strokeWidth);\n }\n };\n};\nBRp$2.generateEllipse = function () {\n return this.nodeShapes['ellipse'] = {\n renderer: this,\n name: 'ellipse',\n draw: function draw(context, centerX, centerY, width, height, cornerRadius) {\n this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height);\n },\n intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {\n return intersectLineEllipse(x, y, nodeX, nodeY, width / 2 + padding, height / 2 + padding);\n },\n checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {\n return checkInEllipse(x, y, width, height, centerX, centerY, padding);\n }\n };\n};\nBRp$2.generateRoundPolygon = function (name, points) {\n return this.nodeShapes[name] = {\n renderer: this,\n name: name,\n points: points,\n getOrCreateCorners: function getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, field) {\n if (rs[field] !== undefined && rs[field + '-cx'] === centerX && rs[field + '-cy'] === centerY) {\n return rs[field];\n }\n rs[field] = new Array(points.length / 2);\n rs[field + '-cx'] = centerX;\n rs[field + '-cy'] = centerY;\n var halfW = width / 2;\n var halfH = height / 2;\n cornerRadius = cornerRadius === 'auto' ? getRoundPolygonRadius(width, height) : cornerRadius;\n var p = new Array(points.length / 2);\n for (var _i = 0; _i < points.length / 2; _i++) {\n p[_i] = {\n x: centerX + halfW * points[_i * 2],\n y: centerY + halfH * points[_i * 2 + 1]\n };\n }\n var i,\n p1,\n p2,\n p3,\n len = p.length;\n p1 = p[len - 1];\n // for each point\n for (i = 0; i < len; i++) {\n p2 = p[i % len];\n p3 = p[(i + 1) % len];\n rs[field][i] = getRoundCorner(p1, p2, p3, cornerRadius);\n p1 = p2;\n p2 = p3;\n }\n return rs[field];\n },\n draw: function draw(context, centerX, centerY, width, height, cornerRadius, rs) {\n this.renderer.nodeShapeImpl('round-polygon', context, centerX, centerY, width, height, this.points, this.getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, 'drawCorners'));\n },\n intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius, rs) {\n return roundPolygonIntersectLine(x, y, this.points, nodeX, nodeY, width, height, padding, this.getOrCreateCorners(nodeX, nodeY, width, height, cornerRadius, rs, 'corners'));\n },\n checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius, rs) {\n return pointInsideRoundPolygon(x, y, this.points, centerX, centerY, width, height, this.getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, 'corners'));\n }\n };\n};\nBRp$2.generateRoundRectangle = function () {\n return this.nodeShapes['round-rectangle'] = this.nodeShapes['roundrectangle'] = {\n renderer: this,\n name: 'round-rectangle',\n points: generateUnitNgonPointsFitToSquare(4, 0),\n draw: function draw(context, centerX, centerY, width, height, cornerRadius) {\n this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, this.points, cornerRadius);\n },\n intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {\n return roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding, cornerRadius);\n },\n checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {\n var halfWidth = width / 2;\n var halfHeight = height / 2;\n cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(width, height) : cornerRadius;\n cornerRadius = Math.min(halfWidth, halfHeight, cornerRadius);\n var diam = cornerRadius * 2;\n\n // Check hBox\n if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - diam, [0, -1], padding)) {\n return true;\n }\n\n // Check vBox\n if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - diam, height, [0, -1], padding)) {\n return true;\n }\n\n // Check top left quarter circle\n if (checkInEllipse(x, y, diam, diam, centerX - halfWidth + cornerRadius, centerY - halfHeight + cornerRadius, padding)) {\n return true;\n }\n\n // Check top right quarter circle\n if (checkInEllipse(x, y, diam, diam, centerX + halfWidth - cornerRadius, centerY - halfHeight + cornerRadius, padding)) {\n return true;\n }\n\n // Check bottom right quarter circle\n if (checkInEllipse(x, y, diam, diam, centerX + halfWidth - cornerRadius, centerY + halfHeight - cornerRadius, padding)) {\n return true;\n }\n\n // Check bottom left quarter circle\n if (checkInEllipse(x, y, diam, diam, centerX - halfWidth + cornerRadius, centerY + halfHeight - cornerRadius, padding)) {\n return true;\n }\n return false;\n }\n };\n};\nBRp$2.generateCutRectangle = function () {\n return this.nodeShapes['cut-rectangle'] = this.nodeShapes['cutrectangle'] = {\n renderer: this,\n name: 'cut-rectangle',\n cornerLength: getCutRectangleCornerLength(),\n points: generateUnitNgonPointsFitToSquare(4, 0),\n draw: function draw(context, centerX, centerY, width, height, cornerRadius) {\n this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, null, cornerRadius);\n },\n generateCutTrianglePts: function generateCutTrianglePts(width, height, centerX, centerY, cornerRadius) {\n var cl = cornerRadius === 'auto' ? this.cornerLength : cornerRadius;\n var hh = height / 2;\n var hw = width / 2;\n var xBegin = centerX - hw;\n var xEnd = centerX + hw;\n var yBegin = centerY - hh;\n var yEnd = centerY + hh;\n\n // points are in clockwise order, inner (imaginary) triangle pt on [4, 5]\n return {\n topLeft: [xBegin, yBegin + cl, xBegin + cl, yBegin, xBegin + cl, yBegin + cl],\n topRight: [xEnd - cl, yBegin, xEnd, yBegin + cl, xEnd - cl, yBegin + cl],\n bottomRight: [xEnd, yEnd - cl, xEnd - cl, yEnd, xEnd - cl, yEnd - cl],\n bottomLeft: [xBegin + cl, yEnd, xBegin, yEnd - cl, xBegin + cl, yEnd - cl]\n };\n },\n intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {\n var cPts = this.generateCutTrianglePts(width + 2 * padding, height + 2 * padding, nodeX, nodeY, cornerRadius);\n var pts = [].concat.apply([], [cPts.topLeft.splice(0, 4), cPts.topRight.splice(0, 4), cPts.bottomRight.splice(0, 4), cPts.bottomLeft.splice(0, 4)]);\n return polygonIntersectLine(x, y, pts, nodeX, nodeY);\n },\n checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {\n var cl = cornerRadius === 'auto' ? this.cornerLength : cornerRadius;\n // Check hBox\n if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - 2 * cl, [0, -1], padding)) {\n return true;\n }\n\n // Check vBox\n if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - 2 * cl, height, [0, -1], padding)) {\n return true;\n }\n var cutTrianglePts = this.generateCutTrianglePts(width, height, centerX, centerY);\n return pointInsidePolygonPoints(x, y, cutTrianglePts.topLeft) || pointInsidePolygonPoints(x, y, cutTrianglePts.topRight) || pointInsidePolygonPoints(x, y, cutTrianglePts.bottomRight) || pointInsidePolygonPoints(x, y, cutTrianglePts.bottomLeft);\n }\n };\n};\nBRp$2.generateBarrel = function () {\n return this.nodeShapes['barrel'] = {\n renderer: this,\n name: 'barrel',\n points: generateUnitNgonPointsFitToSquare(4, 0),\n draw: function draw(context, centerX, centerY, width, height, cornerRadius) {\n this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height);\n },\n intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {\n // use two fixed t values for the bezier curve approximation\n\n var t0 = 0.15;\n var t1 = 0.5;\n var t2 = 0.85;\n var bPts = this.generateBarrelBezierPts(width + 2 * padding, height + 2 * padding, nodeX, nodeY);\n var approximateBarrelCurvePts = function approximateBarrelCurvePts(pts) {\n // approximate curve pts based on the two t values\n var m0 = qbezierPtAt({\n x: pts[0],\n y: pts[1]\n }, {\n x: pts[2],\n y: pts[3]\n }, {\n x: pts[4],\n y: pts[5]\n }, t0);\n var m1 = qbezierPtAt({\n x: pts[0],\n y: pts[1]\n }, {\n x: pts[2],\n y: pts[3]\n }, {\n x: pts[4],\n y: pts[5]\n }, t1);\n var m2 = qbezierPtAt({\n x: pts[0],\n y: pts[1]\n }, {\n x: pts[2],\n y: pts[3]\n }, {\n x: pts[4],\n y: pts[5]\n }, t2);\n return [pts[0], pts[1], m0.x, m0.y, m1.x, m1.y, m2.x, m2.y, pts[4], pts[5]];\n };\n var pts = [].concat(approximateBarrelCurvePts(bPts.topLeft), approximateBarrelCurvePts(bPts.topRight), approximateBarrelCurvePts(bPts.bottomRight), approximateBarrelCurvePts(bPts.bottomLeft));\n return polygonIntersectLine(x, y, pts, nodeX, nodeY);\n },\n generateBarrelBezierPts: function generateBarrelBezierPts(width, height, centerX, centerY) {\n var hh = height / 2;\n var hw = width / 2;\n var xBegin = centerX - hw;\n var xEnd = centerX + hw;\n var yBegin = centerY - hh;\n var yEnd = centerY + hh;\n var curveConstants = getBarrelCurveConstants(width, height);\n var hOffset = curveConstants.heightOffset;\n var wOffset = curveConstants.widthOffset;\n var ctrlPtXOffset = curveConstants.ctrlPtOffsetPct * width;\n\n // points are in clockwise order, inner (imaginary) control pt on [4, 5]\n var pts = {\n topLeft: [xBegin, yBegin + hOffset, xBegin + ctrlPtXOffset, yBegin, xBegin + wOffset, yBegin],\n topRight: [xEnd - wOffset, yBegin, xEnd - ctrlPtXOffset, yBegin, xEnd, yBegin + hOffset],\n bottomRight: [xEnd, yEnd - hOffset, xEnd - ctrlPtXOffset, yEnd, xEnd - wOffset, yEnd],\n bottomLeft: [xBegin + wOffset, yEnd, xBegin + ctrlPtXOffset, yEnd, xBegin, yEnd - hOffset]\n };\n pts.topLeft.isTop = true;\n pts.topRight.isTop = true;\n pts.bottomLeft.isBottom = true;\n pts.bottomRight.isBottom = true;\n return pts;\n },\n checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {\n var curveConstants = getBarrelCurveConstants(width, height);\n var hOffset = curveConstants.heightOffset;\n var wOffset = curveConstants.widthOffset;\n\n // Check hBox\n if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - 2 * hOffset, [0, -1], padding)) {\n return true;\n }\n\n // Check vBox\n if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - 2 * wOffset, height, [0, -1], padding)) {\n return true;\n }\n var barrelCurvePts = this.generateBarrelBezierPts(width, height, centerX, centerY);\n var getCurveT = function getCurveT(x, y, curvePts) {\n var x0 = curvePts[4];\n var x1 = curvePts[2];\n var x2 = curvePts[0];\n var y0 = curvePts[5];\n // var y1 = curvePts[ 3 ];\n var y2 = curvePts[1];\n var xMin = Math.min(x0, x2);\n var xMax = Math.max(x0, x2);\n var yMin = Math.min(y0, y2);\n var yMax = Math.max(y0, y2);\n if (xMin <= x && x <= xMax && yMin <= y && y <= yMax) {\n var coeff = bezierPtsToQuadCoeff(x0, x1, x2);\n var roots = solveQuadratic(coeff[0], coeff[1], coeff[2], x);\n var validRoots = roots.filter(function (r) {\n return 0 <= r && r <= 1;\n });\n if (validRoots.length > 0) {\n return validRoots[0];\n }\n }\n return null;\n };\n var curveRegions = Object.keys(barrelCurvePts);\n for (var i = 0; i < curveRegions.length; i++) {\n var corner = curveRegions[i];\n var cornerPts = barrelCurvePts[corner];\n var t = getCurveT(x, y, cornerPts);\n if (t == null) {\n continue;\n }\n var y0 = cornerPts[5];\n var y1 = cornerPts[3];\n var y2 = cornerPts[1];\n var bezY = qbezierAt(y0, y1, y2, t);\n if (cornerPts.isTop && bezY <= y) {\n return true;\n }\n if (cornerPts.isBottom && y <= bezY) {\n return true;\n }\n }\n return false;\n }\n };\n};\nBRp$2.generateBottomRoundrectangle = function () {\n return this.nodeShapes['bottom-round-rectangle'] = this.nodeShapes['bottomroundrectangle'] = {\n renderer: this,\n name: 'bottom-round-rectangle',\n points: generateUnitNgonPointsFitToSquare(4, 0),\n draw: function draw(context, centerX, centerY, width, height, cornerRadius) {\n this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, this.points, cornerRadius);\n },\n intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {\n var topStartX = nodeX - (width / 2 + padding);\n var topStartY = nodeY - (height / 2 + padding);\n var topEndY = topStartY;\n var topEndX = nodeX + (width / 2 + padding);\n var topIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, topStartX, topStartY, topEndX, topEndY, false);\n if (topIntersections.length > 0) {\n return topIntersections;\n }\n return roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding, cornerRadius);\n },\n checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {\n cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(width, height) : cornerRadius;\n var diam = 2 * cornerRadius;\n\n // Check hBox\n if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - diam, [0, -1], padding)) {\n return true;\n }\n\n // Check vBox\n if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - diam, height, [0, -1], padding)) {\n return true;\n }\n\n // check non-rounded top side\n var outerWidth = width / 2 + 2 * padding;\n var outerHeight = height / 2 + 2 * padding;\n var points = [centerX - outerWidth, centerY - outerHeight, centerX - outerWidth, centerY, centerX + outerWidth, centerY, centerX + outerWidth, centerY - outerHeight];\n if (pointInsidePolygonPoints(x, y, points)) {\n return true;\n }\n\n // Check bottom right quarter circle\n if (checkInEllipse(x, y, diam, diam, centerX + width / 2 - cornerRadius, centerY + height / 2 - cornerRadius, padding)) {\n return true;\n }\n\n // Check bottom left quarter circle\n if (checkInEllipse(x, y, diam, diam, centerX - width / 2 + cornerRadius, centerY + height / 2 - cornerRadius, padding)) {\n return true;\n }\n return false;\n }\n };\n};\nBRp$2.registerNodeShapes = function () {\n var nodeShapes = this.nodeShapes = {};\n var renderer = this;\n this.generateEllipse();\n this.generatePolygon('triangle', generateUnitNgonPointsFitToSquare(3, 0));\n this.generateRoundPolygon('round-triangle', generateUnitNgonPointsFitToSquare(3, 0));\n this.generatePolygon('rectangle', generateUnitNgonPointsFitToSquare(4, 0));\n nodeShapes['square'] = nodeShapes['rectangle'];\n this.generateRoundRectangle();\n this.generateCutRectangle();\n this.generateBarrel();\n this.generateBottomRoundrectangle();\n {\n var diamondPoints = [0, 1, 1, 0, 0, -1, -1, 0];\n this.generatePolygon('diamond', diamondPoints);\n this.generateRoundPolygon('round-diamond', diamondPoints);\n }\n this.generatePolygon('pentagon', generateUnitNgonPointsFitToSquare(5, 0));\n this.generateRoundPolygon('round-pentagon', generateUnitNgonPointsFitToSquare(5, 0));\n this.generatePolygon('hexagon', generateUnitNgonPointsFitToSquare(6, 0));\n this.generateRoundPolygon('round-hexagon', generateUnitNgonPointsFitToSquare(6, 0));\n this.generatePolygon('heptagon', generateUnitNgonPointsFitToSquare(7, 0));\n this.generateRoundPolygon('round-heptagon', generateUnitNgonPointsFitToSquare(7, 0));\n this.generatePolygon('octagon', generateUnitNgonPointsFitToSquare(8, 0));\n this.generateRoundPolygon('round-octagon', generateUnitNgonPointsFitToSquare(8, 0));\n var star5Points = new Array(20);\n {\n var outerPoints = generateUnitNgonPoints(5, 0);\n var innerPoints = generateUnitNgonPoints(5, Math.PI / 5);\n\n // Outer radius is 1; inner radius of star is smaller\n var innerRadius = 0.5 * (3 - Math.sqrt(5));\n innerRadius *= 1.57;\n for (var i = 0; i < innerPoints.length / 2; i++) {\n innerPoints[i * 2] *= innerRadius;\n innerPoints[i * 2 + 1] *= innerRadius;\n }\n for (var i = 0; i < 20 / 4; i++) {\n star5Points[i * 4] = outerPoints[i * 2];\n star5Points[i * 4 + 1] = outerPoints[i * 2 + 1];\n star5Points[i * 4 + 2] = innerPoints[i * 2];\n star5Points[i * 4 + 3] = innerPoints[i * 2 + 1];\n }\n }\n star5Points = fitPolygonToSquare(star5Points);\n this.generatePolygon('star', star5Points);\n this.generatePolygon('vee', [-1, -1, 0, -0.333, 1, -1, 0, 1]);\n this.generatePolygon('rhomboid', [-1, -1, 0.333, -1, 1, 1, -0.333, 1]);\n this.generatePolygon('right-rhomboid', [-0.333, -1, 1, -1, 0.333, 1, -1, 1]);\n this.nodeShapes['concavehexagon'] = this.generatePolygon('concave-hexagon', [-1, -0.95, -0.75, 0, -1, 0.95, 1, 0.95, 0.75, 0, 1, -0.95]);\n {\n var tagPoints = [-1, -1, 0.25, -1, 1, 0, 0.25, 1, -1, 1];\n this.generatePolygon('tag', tagPoints);\n this.generateRoundPolygon('round-tag', tagPoints);\n }\n nodeShapes.makePolygon = function (points) {\n // use caching on user-specified polygons so they are as fast as native shapes\n\n var key = points.join('$');\n var name = 'polygon-' + key;\n var shape;\n if (shape = this[name]) {\n // got cached shape\n return shape;\n }\n\n // create and cache new shape\n return renderer.generatePolygon(name, points);\n };\n};\n\nvar BRp$1 = {};\nBRp$1.timeToRender = function () {\n return this.redrawTotalTime / this.redrawCount;\n};\nBRp$1.redraw = function (options) {\n options = options || staticEmptyObject();\n var r = this;\n if (r.averageRedrawTime === undefined) {\n r.averageRedrawTime = 0;\n }\n if (r.lastRedrawTime === undefined) {\n r.lastRedrawTime = 0;\n }\n if (r.lastDrawTime === undefined) {\n r.lastDrawTime = 0;\n }\n r.requestedFrame = true;\n r.renderOptions = options;\n};\nBRp$1.beforeRender = function (fn, priority) {\n // the renderer can't add tick callbacks when destroyed\n if (this.destroyed) {\n return;\n }\n if (priority == null) {\n error('Priority is not optional for beforeRender');\n }\n var cbs = this.beforeRenderCallbacks;\n cbs.push({\n fn: fn,\n priority: priority\n });\n\n // higher priority callbacks executed first\n cbs.sort(function (a, b) {\n return b.priority - a.priority;\n });\n};\nvar beforeRenderCallbacks = function beforeRenderCallbacks(r, willDraw, startTime) {\n var cbs = r.beforeRenderCallbacks;\n for (var i = 0; i < cbs.length; i++) {\n cbs[i].fn(willDraw, startTime);\n }\n};\nBRp$1.startRenderLoop = function () {\n var r = this;\n var cy = r.cy;\n if (r.renderLoopStarted) {\n return;\n } else {\n r.renderLoopStarted = true;\n }\n var _renderFn = function renderFn(requestTime) {\n if (r.destroyed) {\n return;\n }\n if (cy.batching()) ; else if (r.requestedFrame && !r.skipFrame) {\n beforeRenderCallbacks(r, true, requestTime);\n var startTime = performanceNow();\n r.render(r.renderOptions);\n var endTime = r.lastDrawTime = performanceNow();\n if (r.averageRedrawTime === undefined) {\n r.averageRedrawTime = endTime - startTime;\n }\n if (r.redrawCount === undefined) {\n r.redrawCount = 0;\n }\n r.redrawCount++;\n if (r.redrawTotalTime === undefined) {\n r.redrawTotalTime = 0;\n }\n var duration = endTime - startTime;\n r.redrawTotalTime += duration;\n r.lastRedrawTime = duration;\n\n // use a weighted average with a bias from the previous average so we don't spike so easily\n r.averageRedrawTime = r.averageRedrawTime / 2 + duration / 2;\n r.requestedFrame = false;\n } else {\n beforeRenderCallbacks(r, false, requestTime);\n }\n r.skipFrame = false;\n requestAnimationFrame(_renderFn);\n };\n requestAnimationFrame(_renderFn);\n};\n\nvar BaseRenderer = function BaseRenderer(options) {\n this.init(options);\n};\nvar BR = BaseRenderer;\nvar BRp = BR.prototype;\nBRp.clientFunctions = ['redrawHint', 'render', 'renderTo', 'matchCanvasSize', 'nodeShapeImpl', 'arrowShapeImpl'];\nBRp.init = function (options) {\n var r = this;\n r.options = options;\n r.cy = options.cy;\n var ctr = r.container = options.cy.container();\n var containerWindow = r.cy.window();\n\n // prepend a stylesheet in the head such that\n if (containerWindow) {\n var document = containerWindow.document;\n var head = document.head;\n var stylesheetId = '__________cytoscape_stylesheet';\n var className = '__________cytoscape_container';\n var stylesheetAlreadyExists = document.getElementById(stylesheetId) != null;\n if (ctr.className.indexOf(className) < 0) {\n ctr.className = (ctr.className || '') + ' ' + className;\n }\n if (!stylesheetAlreadyExists) {\n var stylesheet = document.createElement('style');\n stylesheet.id = stylesheetId;\n stylesheet.textContent = '.' + className + ' { position: relative; }';\n head.insertBefore(stylesheet, head.children[0]); // first so lowest priority\n }\n var computedStyle = containerWindow.getComputedStyle(ctr);\n var position = computedStyle.getPropertyValue('position');\n if (position === 'static') {\n warn('A Cytoscape container has style position:static and so can not use UI extensions properly');\n }\n }\n r.selection = [undefined, undefined, undefined, undefined, 0]; // Coordinates for selection box, plus enabled flag\n\n r.bezierProjPcts = [0.05, 0.225, 0.4, 0.5, 0.6, 0.775, 0.95];\n\n //--Pointer-related data\n r.hoverData = {\n down: null,\n last: null,\n downTime: null,\n triggerMode: null,\n dragging: false,\n initialPan: [null, null],\n capture: false\n };\n r.dragData = {\n possibleDragElements: []\n };\n r.touchData = {\n start: null,\n capture: false,\n // These 3 fields related to tap, taphold events\n startPosition: [null, null, null, null, null, null],\n singleTouchStartTime: null,\n singleTouchMoved: true,\n now: [null, null, null, null, null, null],\n earlier: [null, null, null, null, null, null]\n };\n r.redraws = 0;\n r.showFps = options.showFps;\n r.debug = options.debug;\n r.webgl = options.webgl;\n r.hideEdgesOnViewport = options.hideEdgesOnViewport;\n r.textureOnViewport = options.textureOnViewport;\n r.wheelSensitivity = options.wheelSensitivity;\n r.motionBlurEnabled = options.motionBlur; // on by default\n r.forcedPixelRatio = number$1(options.pixelRatio) ? options.pixelRatio : null;\n r.motionBlur = options.motionBlur; // for initial kick off\n r.motionBlurOpacity = options.motionBlurOpacity;\n r.motionBlurTransparency = 1 - r.motionBlurOpacity;\n r.motionBlurPxRatio = 1;\n r.mbPxRBlurry = 1; //0.8;\n r.minMbLowQualFrames = 4;\n r.fullQualityMb = false;\n r.clearedForMotionBlur = [];\n r.desktopTapThreshold = options.desktopTapThreshold;\n r.desktopTapThreshold2 = options.desktopTapThreshold * options.desktopTapThreshold;\n r.touchTapThreshold = options.touchTapThreshold;\n r.touchTapThreshold2 = options.touchTapThreshold * options.touchTapThreshold;\n r.tapholdDuration = 500;\n r.bindings = [];\n r.beforeRenderCallbacks = [];\n r.beforeRenderPriorities = {\n // higher priority execs before lower one\n animations: 400,\n eleCalcs: 300,\n eleTxrDeq: 200,\n lyrTxrDeq: 150,\n lyrTxrSkip: 100\n };\n r.registerNodeShapes();\n r.registerArrowShapes();\n r.registerCalculationListeners();\n};\nBRp.notify = function (eventName, eles) {\n var r = this;\n var cy = r.cy;\n\n // the renderer can't be notified after it's destroyed\n if (this.destroyed) {\n return;\n }\n if (eventName === 'init') {\n r.load();\n return;\n }\n if (eventName === 'destroy') {\n r.destroy();\n return;\n }\n if (eventName === 'add' || eventName === 'remove' || eventName === 'move' && cy.hasCompoundNodes() || eventName === 'load' || eventName === 'zorder' || eventName === 'mount') {\n r.invalidateCachedZSortedEles();\n }\n if (eventName === 'viewport') {\n r.redrawHint('select', true);\n }\n if (eventName === 'gc') {\n r.redrawHint('gc', true);\n }\n if (eventName === 'load' || eventName === 'resize' || eventName === 'mount') {\n r.invalidateContainerClientCoordsCache();\n r.matchCanvasSize(r.container);\n }\n r.redrawHint('eles', true);\n r.redrawHint('drag', true);\n this.startRenderLoop();\n this.redraw();\n};\nBRp.destroy = function () {\n var r = this;\n r.destroyed = true;\n r.cy.stopAnimationLoop();\n for (var i = 0; i < r.bindings.length; i++) {\n var binding = r.bindings[i];\n var b = binding;\n var tgt = b.target;\n (tgt.off || tgt.removeEventListener).apply(tgt, b.args);\n }\n r.bindings = [];\n r.beforeRenderCallbacks = [];\n r.onUpdateEleCalcsFns = [];\n if (r.removeObserver) {\n r.removeObserver.disconnect();\n }\n if (r.styleObserver) {\n r.styleObserver.disconnect();\n }\n if (r.resizeObserver) {\n r.resizeObserver.disconnect();\n }\n if (r.labelCalcDiv) {\n try {\n document.body.removeChild(r.labelCalcDiv); // eslint-disable-line no-undef\n } catch (e) {\n // ie10 issue #1014\n }\n }\n};\nBRp.isHeadless = function () {\n return false;\n};\n[BRp$f, BRp$5, BRp$4, BRp$3, BRp$2, BRp$1].forEach(function (props) {\n extend(BRp, props);\n});\n\nvar fullFpsTime = 1000 / 60; // assume 60 frames per second\n\nvar defs = {\n setupDequeueing: function setupDequeueing(opts) {\n return function setupDequeueingImpl() {\n var self = this;\n var r = this.renderer;\n if (self.dequeueingSetup) {\n return;\n } else {\n self.dequeueingSetup = true;\n }\n var queueRedraw = debounce(function () {\n r.redrawHint('eles', true);\n r.redrawHint('drag', true);\n r.redraw();\n }, opts.deqRedrawThreshold);\n var dequeue = function dequeue(willDraw, frameStartTime) {\n var startTime = performanceNow();\n var avgRenderTime = r.averageRedrawTime;\n var renderTime = r.lastRedrawTime;\n var deqd = [];\n var extent = r.cy.extent();\n var pixelRatio = r.getPixelRatio();\n\n // if we aren't in a tick that causes a draw, then the rendered style\n // queue won't automatically be flushed before dequeueing starts\n if (!willDraw) {\n r.flushRenderedStyleQueue();\n }\n while (true) {\n // eslint-disable-line no-constant-condition\n var now = performanceNow();\n var duration = now - startTime;\n var frameDuration = now - frameStartTime;\n if (renderTime < fullFpsTime) {\n // if we're rendering faster than the ideal fps, then do dequeueing\n // during all of the remaining frame time\n\n var timeAvailable = fullFpsTime - (willDraw ? avgRenderTime : 0);\n if (frameDuration >= opts.deqFastCost * timeAvailable) {\n break;\n }\n } else {\n if (willDraw) {\n if (duration >= opts.deqCost * renderTime || duration >= opts.deqAvgCost * avgRenderTime) {\n break;\n }\n } else if (frameDuration >= opts.deqNoDrawCost * fullFpsTime) {\n break;\n }\n }\n var thisDeqd = opts.deq(self, pixelRatio, extent);\n if (thisDeqd.length > 0) {\n for (var i = 0; i < thisDeqd.length; i++) {\n deqd.push(thisDeqd[i]);\n }\n } else {\n break;\n }\n }\n\n // callbacks on dequeue\n if (deqd.length > 0) {\n opts.onDeqd(self, deqd);\n if (!willDraw && opts.shouldRedraw(self, deqd, pixelRatio, extent)) {\n queueRedraw();\n }\n }\n };\n var priority = opts.priority || noop$1;\n r.beforeRender(dequeue, priority(self));\n };\n }\n};\n\n// Allows lookups for (ele, lvl) => cache.\n// Uses keys so elements may share the same cache.\nvar ElementTextureCacheLookup = /*#__PURE__*/function () {\n function ElementTextureCacheLookup(getKey) {\n var doesEleInvalidateKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : falsify;\n _classCallCheck(this, ElementTextureCacheLookup);\n this.idsByKey = new Map$1();\n this.keyForId = new Map$1();\n this.cachesByLvl = new Map$1();\n this.lvls = [];\n this.getKey = getKey;\n this.doesEleInvalidateKey = doesEleInvalidateKey;\n }\n return _createClass(ElementTextureCacheLookup, [{\n key: \"getIdsFor\",\n value: function getIdsFor(key) {\n if (key == null) {\n error(\"Can not get id list for null key\");\n }\n var idsByKey = this.idsByKey;\n var ids = this.idsByKey.get(key);\n if (!ids) {\n ids = new Set$1();\n idsByKey.set(key, ids);\n }\n return ids;\n }\n }, {\n key: \"addIdForKey\",\n value: function addIdForKey(key, id) {\n if (key != null) {\n this.getIdsFor(key).add(id);\n }\n }\n }, {\n key: \"deleteIdForKey\",\n value: function deleteIdForKey(key, id) {\n if (key != null) {\n this.getIdsFor(key)[\"delete\"](id);\n }\n }\n }, {\n key: \"getNumberOfIdsForKey\",\n value: function getNumberOfIdsForKey(key) {\n if (key == null) {\n return 0;\n } else {\n return this.getIdsFor(key).size;\n }\n }\n }, {\n key: \"updateKeyMappingFor\",\n value: function updateKeyMappingFor(ele) {\n var id = ele.id();\n var prevKey = this.keyForId.get(id);\n var currKey = this.getKey(ele);\n this.deleteIdForKey(prevKey, id);\n this.addIdForKey(currKey, id);\n this.keyForId.set(id, currKey);\n }\n }, {\n key: \"deleteKeyMappingFor\",\n value: function deleteKeyMappingFor(ele) {\n var id = ele.id();\n var prevKey = this.keyForId.get(id);\n this.deleteIdForKey(prevKey, id);\n this.keyForId[\"delete\"](id);\n }\n }, {\n key: \"keyHasChangedFor\",\n value: function keyHasChangedFor(ele) {\n var id = ele.id();\n var prevKey = this.keyForId.get(id);\n var newKey = this.getKey(ele);\n return prevKey !== newKey;\n }\n }, {\n key: \"isInvalid\",\n value: function isInvalid(ele) {\n return this.keyHasChangedFor(ele) || this.doesEleInvalidateKey(ele);\n }\n }, {\n key: \"getCachesAt\",\n value: function getCachesAt(lvl) {\n var cachesByLvl = this.cachesByLvl,\n lvls = this.lvls;\n var caches = cachesByLvl.get(lvl);\n if (!caches) {\n caches = new Map$1();\n cachesByLvl.set(lvl, caches);\n lvls.push(lvl);\n }\n return caches;\n }\n }, {\n key: \"getCache\",\n value: function getCache(key, lvl) {\n return this.getCachesAt(lvl).get(key);\n }\n }, {\n key: \"get\",\n value: function get(ele, lvl) {\n var key = this.getKey(ele);\n var cache = this.getCache(key, lvl);\n\n // getting for an element may need to add to the id list b/c eles can share keys\n if (cache != null) {\n this.updateKeyMappingFor(ele);\n }\n return cache;\n }\n }, {\n key: \"getForCachedKey\",\n value: function getForCachedKey(ele, lvl) {\n var key = this.keyForId.get(ele.id()); // n.b. use cached key, not newly computed key\n var cache = this.getCache(key, lvl);\n return cache;\n }\n }, {\n key: \"hasCache\",\n value: function hasCache(key, lvl) {\n return this.getCachesAt(lvl).has(key);\n }\n }, {\n key: \"has\",\n value: function has(ele, lvl) {\n var key = this.getKey(ele);\n return this.hasCache(key, lvl);\n }\n }, {\n key: \"setCache\",\n value: function setCache(key, lvl, cache) {\n cache.key = key;\n this.getCachesAt(lvl).set(key, cache);\n }\n }, {\n key: \"set\",\n value: function set(ele, lvl, cache) {\n var key = this.getKey(ele);\n this.setCache(key, lvl, cache);\n this.updateKeyMappingFor(ele);\n }\n }, {\n key: \"deleteCache\",\n value: function deleteCache(key, lvl) {\n this.getCachesAt(lvl)[\"delete\"](key);\n }\n }, {\n key: \"delete\",\n value: function _delete(ele, lvl) {\n var key = this.getKey(ele);\n this.deleteCache(key, lvl);\n }\n }, {\n key: \"invalidateKey\",\n value: function invalidateKey(key) {\n var _this = this;\n this.lvls.forEach(function (lvl) {\n return _this.deleteCache(key, lvl);\n });\n }\n\n // returns true if no other eles reference the invalidated cache (n.b. other eles may need the cache with the same key)\n }, {\n key: \"invalidate\",\n value: function invalidate(ele) {\n var id = ele.id();\n var key = this.keyForId.get(id); // n.b. use stored key rather than current (potential key)\n\n this.deleteKeyMappingFor(ele);\n var entireKeyInvalidated = this.doesEleInvalidateKey(ele);\n if (entireKeyInvalidated) {\n // clear mapping for current key\n this.invalidateKey(key);\n }\n return entireKeyInvalidated || this.getNumberOfIdsForKey(key) === 0;\n }\n }]);\n}();\n\nvar minTxrH = 25; // the size of the texture cache for small height eles (special case)\nvar txrStepH = 50; // the min size of the regular cache, and the size it increases with each step up\nvar minLvl$1 = -4; // when scaling smaller than that we don't need to re-render\nvar maxLvl$1 = 3; // when larger than this scale just render directly (caching is not helpful)\nvar maxZoom$1 = 7.99; // beyond this zoom level, layered textures are not used\nvar eleTxrSpacing = 8; // spacing between elements on textures to avoid blitting overlaps\nvar defTxrWidth = 1024; // default/minimum texture width\nvar maxTxrW = 1024; // the maximum width of a texture\nvar maxTxrH = 1024; // the maximum height of a texture\nvar minUtility = 0.2; // if usage of texture is less than this, it is retired\nvar maxFullness = 0.8; // fullness of texture after which queue removal is checked\nvar maxFullnessChecks = 10; // dequeued after this many checks\nvar deqCost$1 = 0.15; // % of add'l rendering cost allowed for dequeuing ele caches each frame\nvar deqAvgCost$1 = 0.1; // % of add'l rendering cost compared to average overall redraw time\nvar deqNoDrawCost$1 = 0.9; // % of avg frame time that can be used for dequeueing when not drawing\nvar deqFastCost$1 = 0.9; // % of frame time to be used when >60fps\nvar deqRedrawThreshold$1 = 100; // time to batch redraws together from dequeueing to allow more dequeueing calcs to happen in the meanwhile\nvar maxDeqSize$1 = 1; // number of eles to dequeue and render at higher texture in each batch\n\nvar getTxrReasons = {\n dequeue: 'dequeue',\n downscale: 'downscale',\n highQuality: 'highQuality'\n};\nvar initDefaults = defaults$g({\n getKey: null,\n doesEleInvalidateKey: falsify,\n drawElement: null,\n getBoundingBox: null,\n getRotationPoint: null,\n getRotationOffset: null,\n isVisible: trueify,\n allowEdgeTxrCaching: true,\n allowParentTxrCaching: true\n});\nvar ElementTextureCache = function ElementTextureCache(renderer, initOptions) {\n var self = this;\n self.renderer = renderer;\n self.onDequeues = [];\n var opts = initDefaults(initOptions);\n extend(self, opts);\n self.lookup = new ElementTextureCacheLookup(opts.getKey, opts.doesEleInvalidateKey);\n self.setupDequeueing();\n};\nvar ETCp = ElementTextureCache.prototype;\nETCp.reasons = getTxrReasons;\n\n// the list of textures in which new subtextures for elements can be placed\nETCp.getTextureQueue = function (txrH) {\n var self = this;\n self.eleImgCaches = self.eleImgCaches || {};\n return self.eleImgCaches[txrH] = self.eleImgCaches[txrH] || [];\n};\n\n// the list of usused textures which can be recycled (in use in texture queue)\nETCp.getRetiredTextureQueue = function (txrH) {\n var self = this;\n var rtxtrQs = self.eleImgCaches.retired = self.eleImgCaches.retired || {};\n var rtxtrQ = rtxtrQs[txrH] = rtxtrQs[txrH] || [];\n return rtxtrQ;\n};\n\n// queue of element draw requests at different scale levels\nETCp.getElementQueue = function () {\n var self = this;\n var q = self.eleCacheQueue = self.eleCacheQueue || new Heap(function (a, b) {\n return b.reqs - a.reqs;\n });\n return q;\n};\n\n// queue of element draw requests at different scale levels (element id lookup)\nETCp.getElementKeyToQueue = function () {\n var self = this;\n var k2q = self.eleKeyToCacheQueue = self.eleKeyToCacheQueue || {};\n return k2q;\n};\nETCp.getElement = function (ele, bb, pxRatio, lvl, reason) {\n var self = this;\n var r = this.renderer;\n var zoom = r.cy.zoom();\n var lookup = this.lookup;\n if (!bb || bb.w === 0 || bb.h === 0 || isNaN(bb.w) || isNaN(bb.h) || !ele.visible() || ele.removed()) {\n return null;\n }\n if (!self.allowEdgeTxrCaching && ele.isEdge() || !self.allowParentTxrCaching && ele.isParent()) {\n return null;\n }\n if (lvl == null) {\n lvl = Math.ceil(log2(zoom * pxRatio));\n }\n if (lvl < minLvl$1) {\n lvl = minLvl$1;\n } else if (zoom >= maxZoom$1 || lvl > maxLvl$1) {\n return null;\n }\n var scale = Math.pow(2, lvl);\n var eleScaledH = bb.h * scale;\n var eleScaledW = bb.w * scale;\n var scaledLabelShown = r.eleTextBiggerThanMin(ele, scale);\n if (!this.isVisible(ele, scaledLabelShown)) {\n return null;\n }\n var eleCache = lookup.get(ele, lvl);\n\n // if this get was on an unused/invalidated cache, then restore the texture usage metric\n if (eleCache && eleCache.invalidated) {\n eleCache.invalidated = false;\n eleCache.texture.invalidatedWidth -= eleCache.width;\n }\n if (eleCache) {\n return eleCache;\n }\n var txrH; // which texture height this ele belongs to\n\n if (eleScaledH <= minTxrH) {\n txrH = minTxrH;\n } else if (eleScaledH <= txrStepH) {\n txrH = txrStepH;\n } else {\n txrH = Math.ceil(eleScaledH / txrStepH) * txrStepH;\n }\n if (eleScaledH > maxTxrH || eleScaledW > maxTxrW) {\n return null; // caching large elements is not efficient\n }\n var txrQ = self.getTextureQueue(txrH);\n\n // first try the second last one in case it has space at the end\n var txr = txrQ[txrQ.length - 2];\n var addNewTxr = function addNewTxr() {\n return self.recycleTexture(txrH, eleScaledW) || self.addTexture(txrH, eleScaledW);\n };\n\n // try the last one if there is no second last one\n if (!txr) {\n txr = txrQ[txrQ.length - 1];\n }\n\n // if the last one doesn't exist, we need a first one\n if (!txr) {\n txr = addNewTxr();\n }\n\n // if there's no room in the current texture, we need a new one\n if (txr.width - txr.usedWidth < eleScaledW) {\n txr = addNewTxr();\n }\n var scalableFrom = function scalableFrom(otherCache) {\n return otherCache && otherCache.scaledLabelShown === scaledLabelShown;\n };\n var deqing = reason && reason === getTxrReasons.dequeue;\n var highQualityReq = reason && reason === getTxrReasons.highQuality;\n var downscaleReq = reason && reason === getTxrReasons.downscale;\n var higherCache; // the nearest cache with a higher level\n for (var l = lvl + 1; l <= maxLvl$1; l++) {\n var c = lookup.get(ele, l);\n if (c) {\n higherCache = c;\n break;\n }\n }\n var oneUpCache = higherCache && higherCache.level === lvl + 1 ? higherCache : null;\n var downscale = function downscale() {\n txr.context.drawImage(oneUpCache.texture.canvas, oneUpCache.x, 0, oneUpCache.width, oneUpCache.height, txr.usedWidth, 0, eleScaledW, eleScaledH);\n };\n\n // reset ele area in texture\n txr.context.setTransform(1, 0, 0, 1, 0, 0);\n txr.context.clearRect(txr.usedWidth, 0, eleScaledW, txrH);\n if (scalableFrom(oneUpCache)) {\n // then we can relatively cheaply rescale the existing image w/o rerendering\n downscale();\n } else if (scalableFrom(higherCache)) {\n // then use the higher cache for now and queue the next level down\n // to cheaply scale towards the smaller level\n\n if (highQualityReq) {\n for (var _l = higherCache.level; _l > lvl; _l--) {\n oneUpCache = self.getElement(ele, bb, pxRatio, _l, getTxrReasons.downscale);\n }\n downscale();\n } else {\n self.queueElement(ele, higherCache.level - 1);\n return higherCache;\n }\n } else {\n var lowerCache; // the nearest cache with a lower level\n if (!deqing && !highQualityReq && !downscaleReq) {\n for (var _l2 = lvl - 1; _l2 >= minLvl$1; _l2--) {\n var _c = lookup.get(ele, _l2);\n if (_c) {\n lowerCache = _c;\n break;\n }\n }\n }\n if (scalableFrom(lowerCache)) {\n // then use the lower quality cache for now and queue the better one for later\n\n self.queueElement(ele, lvl);\n return lowerCache;\n }\n txr.context.translate(txr.usedWidth, 0);\n txr.context.scale(scale, scale);\n this.drawElement(txr.context, ele, bb, scaledLabelShown, false);\n txr.context.scale(1 / scale, 1 / scale);\n txr.context.translate(-txr.usedWidth, 0);\n }\n eleCache = {\n x: txr.usedWidth,\n texture: txr,\n level: lvl,\n scale: scale,\n width: eleScaledW,\n height: eleScaledH,\n scaledLabelShown: scaledLabelShown\n };\n txr.usedWidth += Math.ceil(eleScaledW + eleTxrSpacing);\n txr.eleCaches.push(eleCache);\n lookup.set(ele, lvl, eleCache);\n self.checkTextureFullness(txr);\n return eleCache;\n};\nETCp.invalidateElements = function (eles) {\n for (var i = 0; i < eles.length; i++) {\n this.invalidateElement(eles[i]);\n }\n};\nETCp.invalidateElement = function (ele) {\n var self = this;\n var lookup = self.lookup;\n var caches = [];\n var invalid = lookup.isInvalid(ele);\n if (!invalid) {\n return; // override the invalidation request if the element key has not changed\n }\n for (var lvl = minLvl$1; lvl <= maxLvl$1; lvl++) {\n var cache = lookup.getForCachedKey(ele, lvl);\n if (cache) {\n caches.push(cache);\n }\n }\n var noOtherElesUseCache = lookup.invalidate(ele);\n if (noOtherElesUseCache) {\n for (var i = 0; i < caches.length; i++) {\n var _cache = caches[i];\n var txr = _cache.texture;\n\n // remove space from the texture it belongs to\n txr.invalidatedWidth += _cache.width;\n\n // mark the cache as invalidated\n _cache.invalidated = true;\n\n // retire the texture if its utility is low\n self.checkTextureUtility(txr);\n }\n }\n\n // remove from queue since the old req was for the old state\n self.removeFromQueue(ele);\n};\nETCp.checkTextureUtility = function (txr) {\n // invalidate all entries in the cache if the cache size is small\n if (txr.invalidatedWidth >= minUtility * txr.width) {\n this.retireTexture(txr);\n }\n};\nETCp.checkTextureFullness = function (txr) {\n // if texture has been mostly filled and passed over several times, remove\n // it from the queue so we don't need to waste time looking at it to put new things\n\n var self = this;\n var txrQ = self.getTextureQueue(txr.height);\n if (txr.usedWidth / txr.width > maxFullness && txr.fullnessChecks >= maxFullnessChecks) {\n removeFromArray(txrQ, txr);\n } else {\n txr.fullnessChecks++;\n }\n};\nETCp.retireTexture = function (txr) {\n var self = this;\n var txrH = txr.height;\n var txrQ = self.getTextureQueue(txrH);\n var lookup = this.lookup;\n\n // retire the texture from the active / searchable queue:\n\n removeFromArray(txrQ, txr);\n txr.retired = true;\n\n // remove the refs from the eles to the caches:\n\n var eleCaches = txr.eleCaches;\n for (var i = 0; i < eleCaches.length; i++) {\n var eleCache = eleCaches[i];\n lookup.deleteCache(eleCache.key, eleCache.level);\n }\n clearArray(eleCaches);\n\n // add the texture to a retired queue so it can be recycled in future:\n\n var rtxtrQ = self.getRetiredTextureQueue(txrH);\n rtxtrQ.push(txr);\n};\nETCp.addTexture = function (txrH, minW) {\n var self = this;\n var txrQ = self.getTextureQueue(txrH);\n var txr = {};\n txrQ.push(txr);\n txr.eleCaches = [];\n txr.height = txrH;\n txr.width = Math.max(defTxrWidth, minW);\n txr.usedWidth = 0;\n txr.invalidatedWidth = 0;\n txr.fullnessChecks = 0;\n txr.canvas = self.renderer.makeOffscreenCanvas(txr.width, txr.height);\n txr.context = txr.canvas.getContext('2d');\n return txr;\n};\nETCp.recycleTexture = function (txrH, minW) {\n var self = this;\n var txrQ = self.getTextureQueue(txrH);\n var rtxtrQ = self.getRetiredTextureQueue(txrH);\n for (var i = 0; i < rtxtrQ.length; i++) {\n var txr = rtxtrQ[i];\n if (txr.width >= minW) {\n txr.retired = false;\n txr.usedWidth = 0;\n txr.invalidatedWidth = 0;\n txr.fullnessChecks = 0;\n clearArray(txr.eleCaches);\n txr.context.setTransform(1, 0, 0, 1, 0, 0);\n txr.context.clearRect(0, 0, txr.width, txr.height);\n removeFromArray(rtxtrQ, txr);\n txrQ.push(txr);\n return txr;\n }\n }\n};\nETCp.queueElement = function (ele, lvl) {\n var self = this;\n var q = self.getElementQueue();\n var k2q = self.getElementKeyToQueue();\n var key = this.getKey(ele);\n var existingReq = k2q[key];\n if (existingReq) {\n // use the max lvl b/c in between lvls are cheap to make\n existingReq.level = Math.max(existingReq.level, lvl);\n existingReq.eles.merge(ele);\n existingReq.reqs++;\n q.updateItem(existingReq);\n } else {\n var req = {\n eles: ele.spawn().merge(ele),\n level: lvl,\n reqs: 1,\n key: key\n };\n q.push(req);\n k2q[key] = req;\n }\n};\nETCp.dequeue = function (pxRatio /*, extent*/) {\n var self = this;\n var q = self.getElementQueue();\n var k2q = self.getElementKeyToQueue();\n var dequeued = [];\n var lookup = self.lookup;\n for (var i = 0; i < maxDeqSize$1; i++) {\n if (q.size() > 0) {\n var req = q.pop();\n var key = req.key;\n var ele = req.eles[0]; // all eles have the same key\n var cacheExists = lookup.hasCache(ele, req.level);\n\n // clear out the key to req lookup\n k2q[key] = null;\n\n // dequeueing isn't necessary with an existing cache\n if (cacheExists) {\n continue;\n }\n dequeued.push(req);\n var bb = self.getBoundingBox(ele);\n self.getElement(ele, bb, pxRatio, req.level, getTxrReasons.dequeue);\n } else {\n break;\n }\n }\n return dequeued;\n};\nETCp.removeFromQueue = function (ele) {\n var self = this;\n var q = self.getElementQueue();\n var k2q = self.getElementKeyToQueue();\n var key = this.getKey(ele);\n var req = k2q[key];\n if (req != null) {\n if (req.eles.length === 1) {\n // remove if last ele in the req\n // bring to front of queue\n req.reqs = MAX_INT$1;\n q.updateItem(req);\n q.pop(); // remove from queue\n\n k2q[key] = null; // remove from lookup map\n } else {\n // otherwise just remove ele from req\n req.eles.unmerge(ele);\n }\n }\n};\nETCp.onDequeue = function (fn) {\n this.onDequeues.push(fn);\n};\nETCp.offDequeue = function (fn) {\n removeFromArray(this.onDequeues, fn);\n};\nETCp.setupDequeueing = defs.setupDequeueing({\n deqRedrawThreshold: deqRedrawThreshold$1,\n deqCost: deqCost$1,\n deqAvgCost: deqAvgCost$1,\n deqNoDrawCost: deqNoDrawCost$1,\n deqFastCost: deqFastCost$1,\n deq: function deq(self, pxRatio, extent) {\n return self.dequeue(pxRatio, extent);\n },\n onDeqd: function onDeqd(self, deqd) {\n for (var i = 0; i < self.onDequeues.length; i++) {\n var fn = self.onDequeues[i];\n fn(deqd);\n }\n },\n shouldRedraw: function shouldRedraw(self, deqd, pxRatio, extent) {\n for (var i = 0; i < deqd.length; i++) {\n var eles = deqd[i].eles;\n for (var j = 0; j < eles.length; j++) {\n var bb = eles[j].boundingBox();\n if (boundingBoxesIntersect(bb, extent)) {\n return true;\n }\n }\n }\n return false;\n },\n priority: function priority(self) {\n return self.renderer.beforeRenderPriorities.eleTxrDeq;\n }\n});\n\nvar defNumLayers = 1; // default number of layers to use\nvar minLvl = -4; // when scaling smaller than that we don't need to re-render\nvar maxLvl = 2; // when larger than this scale just render directly (caching is not helpful)\nvar maxZoom = 3.99; // beyond this zoom level, layered textures are not used\nvar deqRedrawThreshold = 50; // time to batch redraws together from dequeueing to allow more dequeueing calcs to happen in the meanwhile\nvar refineEleDebounceTime = 50; // time to debounce sharper ele texture updates\nvar deqCost = 0.15; // % of add'l rendering cost allowed for dequeuing ele caches each frame\nvar deqAvgCost = 0.1; // % of add'l rendering cost compared to average overall redraw time\nvar deqNoDrawCost = 0.9; // % of avg frame time that can be used for dequeueing when not drawing\nvar deqFastCost = 0.9; // % of frame time to be used when >60fps\nvar maxDeqSize = 1; // number of eles to dequeue and render at higher texture in each batch\nvar invalidThreshold = 250; // time threshold for disabling b/c of invalidations\nvar maxLayerArea = 4000 * 4000; // layers can't be bigger than this\nvar maxLayerDim = 32767; // maximum size for the width/height of layer canvases\nvar useHighQualityEleTxrReqs = true; // whether to use high quality ele txr requests (generally faster and cheaper in the longterm)\n\n// var log = function(){ console.log.apply( console, arguments ); };\n\nvar LayeredTextureCache = function LayeredTextureCache(renderer) {\n var self = this;\n var r = self.renderer = renderer;\n var cy = r.cy;\n self.layersByLevel = {}; // e.g. 2 => [ layer1, layer2, ..., layerN ]\n\n self.firstGet = true;\n self.lastInvalidationTime = performanceNow() - 2 * invalidThreshold;\n self.skipping = false;\n self.eleTxrDeqs = cy.collection();\n self.scheduleElementRefinement = debounce(function () {\n self.refineElementTextures(self.eleTxrDeqs);\n self.eleTxrDeqs.unmerge(self.eleTxrDeqs);\n }, refineEleDebounceTime);\n r.beforeRender(function (willDraw, now) {\n if (now - self.lastInvalidationTime <= invalidThreshold) {\n self.skipping = true;\n } else {\n self.skipping = false;\n }\n }, r.beforeRenderPriorities.lyrTxrSkip);\n var qSort = function qSort(a, b) {\n return b.reqs - a.reqs;\n };\n self.layersQueue = new Heap(qSort);\n self.setupDequeueing();\n};\nvar LTCp = LayeredTextureCache.prototype;\nvar layerIdPool = 0;\nvar MAX_INT = Math.pow(2, 53) - 1;\nLTCp.makeLayer = function (bb, lvl) {\n var scale = Math.pow(2, lvl);\n var w = Math.ceil(bb.w * scale);\n var h = Math.ceil(bb.h * scale);\n var canvas = this.renderer.makeOffscreenCanvas(w, h);\n var layer = {\n id: layerIdPool = ++layerIdPool % MAX_INT,\n bb: bb,\n level: lvl,\n width: w,\n height: h,\n canvas: canvas,\n context: canvas.getContext('2d'),\n eles: [],\n elesQueue: [],\n reqs: 0\n };\n\n // log('make layer %s with w %s and h %s and lvl %s', layer.id, layer.width, layer.height, layer.level);\n\n var cxt = layer.context;\n var dx = -layer.bb.x1;\n var dy = -layer.bb.y1;\n\n // do the transform on creation to save cycles (it's the same for all eles)\n cxt.scale(scale, scale);\n cxt.translate(dx, dy);\n return layer;\n};\nLTCp.getLayers = function (eles, pxRatio, lvl) {\n var self = this;\n var r = self.renderer;\n var cy = r.cy;\n var zoom = cy.zoom();\n var firstGet = self.firstGet;\n self.firstGet = false;\n\n // log('--\\nget layers with %s eles', eles.length);\n //log eles.map(function(ele){ return ele.id() }) );\n\n if (lvl == null) {\n lvl = Math.ceil(log2(zoom * pxRatio));\n if (lvl < minLvl) {\n lvl = minLvl;\n } else if (zoom >= maxZoom || lvl > maxLvl) {\n return null;\n }\n }\n self.validateLayersElesOrdering(lvl, eles);\n var layersByLvl = self.layersByLevel;\n var scale = Math.pow(2, lvl);\n var layers = layersByLvl[lvl] = layersByLvl[lvl] || [];\n var bb;\n var lvlComplete = self.levelIsComplete(lvl, eles);\n var tmpLayers;\n var checkTempLevels = function checkTempLevels() {\n var canUseAsTmpLvl = function canUseAsTmpLvl(l) {\n self.validateLayersElesOrdering(l, eles);\n if (self.levelIsComplete(l, eles)) {\n tmpLayers = layersByLvl[l];\n return true;\n }\n };\n var checkLvls = function checkLvls(dir) {\n if (tmpLayers) {\n return;\n }\n for (var l = lvl + dir; minLvl <= l && l <= maxLvl; l += dir) {\n if (canUseAsTmpLvl(l)) {\n break;\n }\n }\n };\n checkLvls(1);\n checkLvls(-1);\n\n // remove the invalid layers; they will be replaced as needed later in this function\n for (var i = layers.length - 1; i >= 0; i--) {\n var layer = layers[i];\n if (layer.invalid) {\n removeFromArray(layers, layer);\n }\n }\n };\n if (!lvlComplete) {\n // if the current level is incomplete, then use the closest, best quality layerset temporarily\n // and later queue the current layerset so we can get the proper quality level soon\n\n checkTempLevels();\n } else {\n // log('level complete, using existing layers\\n--');\n return layers;\n }\n var getBb = function getBb() {\n if (!bb) {\n bb = makeBoundingBox();\n for (var i = 0; i < eles.length; i++) {\n updateBoundingBox(bb, eles[i].boundingBox());\n }\n }\n return bb;\n };\n var makeLayer = function makeLayer(opts) {\n opts = opts || {};\n var after = opts.after;\n getBb();\n var w = Math.ceil(bb.w * scale);\n var h = Math.ceil(bb.h * scale);\n if (w > maxLayerDim || h > maxLayerDim) {\n return null;\n }\n var area = w * h;\n if (area > maxLayerArea) {\n return null;\n }\n var layer = self.makeLayer(bb, lvl);\n if (after != null) {\n var index = layers.indexOf(after) + 1;\n layers.splice(index, 0, layer);\n } else if (opts.insert === undefined || opts.insert) {\n // no after specified => first layer made so put at start\n layers.unshift(layer);\n }\n\n // if( tmpLayers ){\n //self.queueLayer( layer );\n // }\n\n return layer;\n };\n if (self.skipping && !firstGet) {\n // log('skip layers');\n return null;\n }\n\n // log('do layers');\n\n var layer = null;\n var maxElesPerLayer = eles.length / defNumLayers;\n var allowLazyQueueing = !firstGet;\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n var rs = ele._private.rscratch;\n var caches = rs.imgLayerCaches = rs.imgLayerCaches || {};\n\n // log('look at ele', ele.id());\n\n var existingLayer = caches[lvl];\n if (existingLayer) {\n // reuse layer for later eles\n // log('reuse layer for', ele.id());\n layer = existingLayer;\n continue;\n }\n if (!layer || layer.eles.length >= maxElesPerLayer || !boundingBoxInBoundingBox(layer.bb, ele.boundingBox())) {\n // log('make new layer for ele %s', ele.id());\n\n layer = makeLayer({\n insert: true,\n after: layer\n });\n\n // if now layer can be built then we can't use layers at this level\n if (!layer) {\n return null;\n }\n\n // log('new layer with id %s', layer.id);\n }\n if (tmpLayers || allowLazyQueueing) {\n // log('queue ele %s in layer %s', ele.id(), layer.id);\n self.queueLayer(layer, ele);\n } else {\n // log('draw ele %s in layer %s', ele.id(), layer.id);\n self.drawEleInLayer(layer, ele, lvl, pxRatio);\n }\n layer.eles.push(ele);\n caches[lvl] = layer;\n }\n\n // log('--');\n\n if (tmpLayers) {\n // then we only queued the current layerset and can't draw it yet\n return tmpLayers;\n }\n if (allowLazyQueueing) {\n // log('lazy queue level', lvl);\n return null;\n }\n return layers;\n};\n\n// a layer may want to use an ele cache of a higher level to avoid blurriness\n// so the layer level might not equal the ele level\nLTCp.getEleLevelForLayerLevel = function (lvl, pxRatio) {\n return lvl;\n};\nLTCp.drawEleInLayer = function (layer, ele, lvl, pxRatio) {\n var self = this;\n var r = this.renderer;\n var context = layer.context;\n var bb = ele.boundingBox();\n if (bb.w === 0 || bb.h === 0 || !ele.visible()) {\n return;\n }\n lvl = self.getEleLevelForLayerLevel(lvl, pxRatio);\n {\n r.setImgSmoothing(context, false);\n }\n {\n r.drawCachedElement(context, ele, null, null, lvl, useHighQualityEleTxrReqs);\n }\n {\n r.setImgSmoothing(context, true);\n }\n};\nLTCp.levelIsComplete = function (lvl, eles) {\n var self = this;\n var layers = self.layersByLevel[lvl];\n if (!layers || layers.length === 0) {\n return false;\n }\n var numElesInLayers = 0;\n for (var i = 0; i < layers.length; i++) {\n var layer = layers[i];\n\n // if there are any eles needed to be drawn yet, the level is not complete\n if (layer.reqs > 0) {\n return false;\n }\n\n // if the layer is invalid, the level is not complete\n if (layer.invalid) {\n return false;\n }\n numElesInLayers += layer.eles.length;\n }\n\n // we should have exactly the number of eles passed in to be complete\n if (numElesInLayers !== eles.length) {\n return false;\n }\n return true;\n};\nLTCp.validateLayersElesOrdering = function (lvl, eles) {\n var layers = this.layersByLevel[lvl];\n if (!layers) {\n return;\n }\n\n // if in a layer the eles are not in the same order, then the layer is invalid\n // (i.e. there is an ele in between the eles in the layer)\n\n for (var i = 0; i < layers.length; i++) {\n var layer = layers[i];\n var offset = -1;\n\n // find the offset\n for (var j = 0; j < eles.length; j++) {\n if (layer.eles[0] === eles[j]) {\n offset = j;\n break;\n }\n }\n if (offset < 0) {\n // then the layer has nonexistent elements and is invalid\n this.invalidateLayer(layer);\n continue;\n }\n\n // the eles in the layer must be in the same continuous order, else the layer is invalid\n\n var o = offset;\n for (var j = 0; j < layer.eles.length; j++) {\n if (layer.eles[j] !== eles[o + j]) {\n // log('invalidate based on ordering', layer.id);\n\n this.invalidateLayer(layer);\n break;\n }\n }\n }\n};\nLTCp.updateElementsInLayers = function (eles, update) {\n var self = this;\n var isEles = element(eles[0]);\n\n // collect udpated elements (cascaded from the layers) and update each\n // layer itself along the way\n for (var i = 0; i < eles.length; i++) {\n var req = isEles ? null : eles[i];\n var ele = isEles ? eles[i] : eles[i].ele;\n var rs = ele._private.rscratch;\n var caches = rs.imgLayerCaches = rs.imgLayerCaches || {};\n for (var l = minLvl; l <= maxLvl; l++) {\n var layer = caches[l];\n if (!layer) {\n continue;\n }\n\n // if update is a request from the ele cache, then it affects only\n // the matching level\n if (req && self.getEleLevelForLayerLevel(layer.level) !== req.level) {\n continue;\n }\n update(layer, ele, req);\n }\n }\n};\nLTCp.haveLayers = function () {\n var self = this;\n var haveLayers = false;\n for (var l = minLvl; l <= maxLvl; l++) {\n var layers = self.layersByLevel[l];\n if (layers && layers.length > 0) {\n haveLayers = true;\n break;\n }\n }\n return haveLayers;\n};\nLTCp.invalidateElements = function (eles) {\n var self = this;\n if (eles.length === 0) {\n return;\n }\n self.lastInvalidationTime = performanceNow();\n\n // log('update invalidate layer time from eles');\n\n if (eles.length === 0 || !self.haveLayers()) {\n return;\n }\n self.updateElementsInLayers(eles, function invalAssocLayers(layer, ele, req) {\n self.invalidateLayer(layer);\n });\n};\nLTCp.invalidateLayer = function (layer) {\n // log('update invalidate layer time');\n\n this.lastInvalidationTime = performanceNow();\n if (layer.invalid) {\n return;\n } // save cycles\n\n var lvl = layer.level;\n var eles = layer.eles;\n var layers = this.layersByLevel[lvl];\n\n // log('invalidate layer', layer.id );\n\n removeFromArray(layers, layer);\n // layer.eles = [];\n\n layer.elesQueue = [];\n layer.invalid = true;\n if (layer.replacement) {\n layer.replacement.invalid = true;\n }\n for (var i = 0; i < eles.length; i++) {\n var caches = eles[i]._private.rscratch.imgLayerCaches;\n if (caches) {\n caches[lvl] = null;\n }\n }\n};\nLTCp.refineElementTextures = function (eles) {\n var self = this;\n\n // log('refine', eles.length);\n\n self.updateElementsInLayers(eles, function refineEachEle(layer, ele, req) {\n var rLyr = layer.replacement;\n if (!rLyr) {\n rLyr = layer.replacement = self.makeLayer(layer.bb, layer.level);\n rLyr.replaces = layer;\n rLyr.eles = layer.eles;\n\n // log('make replacement layer %s for %s with level %s', rLyr.id, layer.id, rLyr.level);\n }\n if (!rLyr.reqs) {\n for (var i = 0; i < rLyr.eles.length; i++) {\n self.queueLayer(rLyr, rLyr.eles[i]);\n }\n\n // log('queue replacement layer refinement', rLyr.id);\n }\n });\n};\nLTCp.enqueueElementRefinement = function (ele) {\n this.eleTxrDeqs.merge(ele);\n this.scheduleElementRefinement();\n};\nLTCp.queueLayer = function (layer, ele) {\n var self = this;\n var q = self.layersQueue;\n var elesQ = layer.elesQueue;\n var hasId = elesQ.hasId = elesQ.hasId || {};\n\n // if a layer is going to be replaced, queuing is a waste of time\n if (layer.replacement) {\n return;\n }\n if (ele) {\n if (hasId[ele.id()]) {\n return;\n }\n elesQ.push(ele);\n hasId[ele.id()] = true;\n }\n if (layer.reqs) {\n layer.reqs++;\n q.updateItem(layer);\n } else {\n layer.reqs = 1;\n q.push(layer);\n }\n};\nLTCp.dequeue = function (pxRatio) {\n var self = this;\n var q = self.layersQueue;\n var deqd = [];\n var eleDeqs = 0;\n while (eleDeqs < maxDeqSize) {\n if (q.size() === 0) {\n break;\n }\n var layer = q.peek();\n\n // if a layer has been or will be replaced, then don't waste time with it\n if (layer.replacement) {\n // log('layer %s in queue skipped b/c it already has a replacement', layer.id);\n q.pop();\n continue;\n }\n\n // if this is a replacement layer that has been superceded, then forget it\n if (layer.replaces && layer !== layer.replaces.replacement) {\n // log('layer is no longer the most uptodate replacement; dequeued', layer.id)\n q.pop();\n continue;\n }\n if (layer.invalid) {\n // log('replacement layer %s is invalid; dequeued', layer.id);\n q.pop();\n continue;\n }\n var ele = layer.elesQueue.shift();\n if (ele) {\n // log('dequeue layer %s', layer.id);\n\n self.drawEleInLayer(layer, ele, layer.level, pxRatio);\n eleDeqs++;\n }\n if (deqd.length === 0) {\n // we need only one entry in deqd to queue redrawing etc\n deqd.push(true);\n }\n\n // if the layer has all its eles done, then remove from the queue\n if (layer.elesQueue.length === 0) {\n q.pop();\n layer.reqs = 0;\n\n // log('dequeue of layer %s complete', layer.id);\n\n // when a replacement layer is dequeued, it replaces the old layer in the level\n if (layer.replaces) {\n self.applyLayerReplacement(layer);\n }\n self.requestRedraw();\n }\n }\n return deqd;\n};\nLTCp.applyLayerReplacement = function (layer) {\n var self = this;\n var layersInLevel = self.layersByLevel[layer.level];\n var replaced = layer.replaces;\n var index = layersInLevel.indexOf(replaced);\n\n // if the replaced layer is not in the active list for the level, then replacing\n // refs would be a mistake (i.e. overwriting the true active layer)\n if (index < 0 || replaced.invalid) {\n // log('replacement layer would have no effect', layer.id);\n return;\n }\n layersInLevel[index] = layer; // replace level ref\n\n // replace refs in eles\n for (var i = 0; i < layer.eles.length; i++) {\n var _p = layer.eles[i]._private;\n var cache = _p.imgLayerCaches = _p.imgLayerCaches || {};\n if (cache) {\n cache[layer.level] = layer;\n }\n }\n\n // log('apply replacement layer %s over %s', layer.id, replaced.id);\n\n self.requestRedraw();\n};\nLTCp.requestRedraw = debounce(function () {\n var r = this.renderer;\n r.redrawHint('eles', true);\n r.redrawHint('drag', true);\n r.redraw();\n}, 100);\nLTCp.setupDequeueing = defs.setupDequeueing({\n deqRedrawThreshold: deqRedrawThreshold,\n deqCost: deqCost,\n deqAvgCost: deqAvgCost,\n deqNoDrawCost: deqNoDrawCost,\n deqFastCost: deqFastCost,\n deq: function deq(self, pxRatio) {\n return self.dequeue(pxRatio);\n },\n onDeqd: noop$1,\n shouldRedraw: trueify,\n priority: function priority(self) {\n return self.renderer.beforeRenderPriorities.lyrTxrDeq;\n }\n});\n\nvar CRp$b = {};\nvar impl;\nfunction polygon(context, points) {\n for (var i = 0; i < points.length; i++) {\n var pt = points[i];\n context.lineTo(pt.x, pt.y);\n }\n}\nfunction triangleBackcurve(context, points, controlPoint) {\n var firstPt;\n for (var i = 0; i < points.length; i++) {\n var pt = points[i];\n if (i === 0) {\n firstPt = pt;\n }\n context.lineTo(pt.x, pt.y);\n }\n context.quadraticCurveTo(controlPoint.x, controlPoint.y, firstPt.x, firstPt.y);\n}\nfunction triangleTee(context, trianglePoints, teePoints) {\n if (context.beginPath) {\n context.beginPath();\n }\n var triPts = trianglePoints;\n for (var i = 0; i < triPts.length; i++) {\n var pt = triPts[i];\n context.lineTo(pt.x, pt.y);\n }\n var teePts = teePoints;\n var firstTeePt = teePoints[0];\n context.moveTo(firstTeePt.x, firstTeePt.y);\n for (var i = 1; i < teePts.length; i++) {\n var pt = teePts[i];\n context.lineTo(pt.x, pt.y);\n }\n if (context.closePath) {\n context.closePath();\n }\n}\nfunction circleTriangle(context, trianglePoints, rx, ry, r) {\n if (context.beginPath) {\n context.beginPath();\n }\n context.arc(rx, ry, r, 0, Math.PI * 2, false);\n var triPts = trianglePoints;\n var firstTrPt = triPts[0];\n context.moveTo(firstTrPt.x, firstTrPt.y);\n for (var i = 0; i < triPts.length; i++) {\n var pt = triPts[i];\n context.lineTo(pt.x, pt.y);\n }\n if (context.closePath) {\n context.closePath();\n }\n}\nfunction circle$1(context, rx, ry, r) {\n context.arc(rx, ry, r, 0, Math.PI * 2, false);\n}\nCRp$b.arrowShapeImpl = function (name) {\n return (impl || (impl = {\n 'polygon': polygon,\n 'triangle-backcurve': triangleBackcurve,\n 'triangle-tee': triangleTee,\n 'circle-triangle': circleTriangle,\n 'triangle-cross': triangleTee,\n 'circle': circle$1\n }))[name];\n};\n\nvar CRp$a = {};\nCRp$a.drawElement = function (context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity) {\n var r = this;\n if (ele.isNode()) {\n r.drawNode(context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity);\n } else {\n r.drawEdge(context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity);\n }\n};\nCRp$a.drawElementOverlay = function (context, ele) {\n var r = this;\n if (ele.isNode()) {\n r.drawNodeOverlay(context, ele);\n } else {\n r.drawEdgeOverlay(context, ele);\n }\n};\nCRp$a.drawElementUnderlay = function (context, ele) {\n var r = this;\n if (ele.isNode()) {\n r.drawNodeUnderlay(context, ele);\n } else {\n r.drawEdgeUnderlay(context, ele);\n }\n};\nCRp$a.drawCachedElementPortion = function (context, ele, eleTxrCache, pxRatio, lvl, reason, getRotation, getOpacity) {\n var r = this;\n var bb = eleTxrCache.getBoundingBox(ele);\n if (bb.w === 0 || bb.h === 0) {\n return;\n } // ignore zero size case\n\n var eleCache = eleTxrCache.getElement(ele, bb, pxRatio, lvl, reason);\n if (eleCache != null) {\n var opacity = getOpacity(r, ele);\n if (opacity === 0) {\n return;\n }\n var theta = getRotation(r, ele);\n var x1 = bb.x1,\n y1 = bb.y1,\n w = bb.w,\n h = bb.h;\n var x, y, sx, sy, smooth;\n if (theta !== 0) {\n var rotPt = eleTxrCache.getRotationPoint(ele);\n sx = rotPt.x;\n sy = rotPt.y;\n context.translate(sx, sy);\n context.rotate(theta);\n smooth = r.getImgSmoothing(context);\n if (!smooth) {\n r.setImgSmoothing(context, true);\n }\n var off = eleTxrCache.getRotationOffset(ele);\n x = off.x;\n y = off.y;\n } else {\n x = x1;\n y = y1;\n }\n var oldGlobalAlpha;\n if (opacity !== 1) {\n oldGlobalAlpha = context.globalAlpha;\n context.globalAlpha = oldGlobalAlpha * opacity;\n }\n context.drawImage(eleCache.texture.canvas, eleCache.x, 0, eleCache.width, eleCache.height, x, y, w, h);\n if (opacity !== 1) {\n context.globalAlpha = oldGlobalAlpha;\n }\n if (theta !== 0) {\n context.rotate(-theta);\n context.translate(-sx, -sy);\n if (!smooth) {\n r.setImgSmoothing(context, false);\n }\n }\n } else {\n eleTxrCache.drawElement(context, ele); // direct draw fallback\n }\n};\nvar getZeroRotation = function getZeroRotation() {\n return 0;\n};\nvar getLabelRotation = function getLabelRotation(r, ele) {\n return r.getTextAngle(ele, null);\n};\nvar getSourceLabelRotation = function getSourceLabelRotation(r, ele) {\n return r.getTextAngle(ele, 'source');\n};\nvar getTargetLabelRotation = function getTargetLabelRotation(r, ele) {\n return r.getTextAngle(ele, 'target');\n};\nvar getOpacity = function getOpacity(r, ele) {\n return ele.effectiveOpacity();\n};\nvar getTextOpacity = function getTextOpacity(e, ele) {\n return ele.pstyle('text-opacity').pfValue * ele.effectiveOpacity();\n};\nCRp$a.drawCachedElement = function (context, ele, pxRatio, extent, lvl, requestHighQuality) {\n var r = this;\n var _r$data = r.data,\n eleTxrCache = _r$data.eleTxrCache,\n lblTxrCache = _r$data.lblTxrCache,\n slbTxrCache = _r$data.slbTxrCache,\n tlbTxrCache = _r$data.tlbTxrCache;\n var bb = ele.boundingBox();\n var reason = requestHighQuality === true ? eleTxrCache.reasons.highQuality : null;\n if (bb.w === 0 || bb.h === 0 || !ele.visible()) {\n return;\n }\n if (!extent || boundingBoxesIntersect(bb, extent)) {\n var isEdge = ele.isEdge();\n var badLine = ele.element()._private.rscratch.badLine;\n r.drawElementUnderlay(context, ele);\n r.drawCachedElementPortion(context, ele, eleTxrCache, pxRatio, lvl, reason, getZeroRotation, getOpacity);\n if (!isEdge || !badLine) {\n r.drawCachedElementPortion(context, ele, lblTxrCache, pxRatio, lvl, reason, getLabelRotation, getTextOpacity);\n }\n if (isEdge && !badLine) {\n r.drawCachedElementPortion(context, ele, slbTxrCache, pxRatio, lvl, reason, getSourceLabelRotation, getTextOpacity);\n r.drawCachedElementPortion(context, ele, tlbTxrCache, pxRatio, lvl, reason, getTargetLabelRotation, getTextOpacity);\n }\n r.drawElementOverlay(context, ele);\n }\n};\nCRp$a.drawElements = function (context, eles) {\n var r = this;\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n r.drawElement(context, ele);\n }\n};\nCRp$a.drawCachedElements = function (context, eles, pxRatio, extent) {\n var r = this;\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n r.drawCachedElement(context, ele, pxRatio, extent);\n }\n};\nCRp$a.drawCachedNodes = function (context, eles, pxRatio, extent) {\n var r = this;\n for (var i = 0; i < eles.length; i++) {\n var ele = eles[i];\n if (!ele.isNode()) {\n continue;\n }\n r.drawCachedElement(context, ele, pxRatio, extent);\n }\n};\nCRp$a.drawLayeredElements = function (context, eles, pxRatio, extent) {\n var r = this;\n var layers = r.data.lyrTxrCache.getLayers(eles, pxRatio);\n if (layers) {\n for (var i = 0; i < layers.length; i++) {\n var layer = layers[i];\n var bb = layer.bb;\n if (bb.w === 0 || bb.h === 0) {\n continue;\n }\n context.drawImage(layer.canvas, bb.x1, bb.y1, bb.w, bb.h);\n }\n } else {\n // fall back on plain caching if no layers\n r.drawCachedElements(context, eles, pxRatio, extent);\n }\n};\n\nvar CRp$9 = {};\nCRp$9.drawEdge = function (context, edge, shiftToOriginWithBb) {\n var drawLabel = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;\n var shouldDrawOverlay = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n var shouldDrawOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;\n var r = this;\n var rs = edge._private.rscratch;\n if (shouldDrawOpacity && !edge.visible()) {\n return;\n }\n\n // if bezier ctrl pts can not be calculated, then die\n if (rs.badLine || rs.allpts == null || isNaN(rs.allpts[0])) {\n // isNaN in case edge is impossible and browser bugs (e.g. safari)\n return;\n }\n var bb;\n if (shiftToOriginWithBb) {\n bb = shiftToOriginWithBb;\n context.translate(-bb.x1, -bb.y1);\n }\n var opacity = shouldDrawOpacity ? edge.pstyle('opacity').value : 1;\n var lineOpacity = shouldDrawOpacity ? edge.pstyle('line-opacity').value : 1;\n var curveStyle = edge.pstyle('curve-style').value;\n var lineStyle = edge.pstyle('line-style').value;\n var edgeWidth = edge.pstyle('width').pfValue;\n var lineCap = edge.pstyle('line-cap').value;\n var lineOutlineWidth = edge.pstyle('line-outline-width').value;\n var lineOutlineColor = edge.pstyle('line-outline-color').value;\n var effectiveLineOpacity = opacity * lineOpacity;\n // separate arrow opacity would require arrow-opacity property\n var effectiveArrowOpacity = opacity * lineOpacity;\n var drawLine = function drawLine() {\n var strokeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveLineOpacity;\n if (curveStyle === 'straight-triangle') {\n r.eleStrokeStyle(context, edge, strokeOpacity);\n r.drawEdgeTrianglePath(edge, context, rs.allpts);\n } else {\n context.lineWidth = edgeWidth;\n context.lineCap = lineCap;\n r.eleStrokeStyle(context, edge, strokeOpacity);\n r.drawEdgePath(edge, context, rs.allpts, lineStyle);\n context.lineCap = 'butt'; // reset for other drawing functions\n }\n };\n var drawLineOutline = function drawLineOutline() {\n var strokeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveLineOpacity;\n context.lineWidth = edgeWidth + lineOutlineWidth;\n context.lineCap = lineCap;\n if (lineOutlineWidth > 0) {\n r.colorStrokeStyle(context, lineOutlineColor[0], lineOutlineColor[1], lineOutlineColor[2], strokeOpacity);\n } else {\n // do not draw any lineOutline\n context.lineCap = 'butt'; // reset for other drawing functions\n return;\n }\n if (curveStyle === 'straight-triangle') {\n r.drawEdgeTrianglePath(edge, context, rs.allpts);\n } else {\n r.drawEdgePath(edge, context, rs.allpts, lineStyle);\n context.lineCap = 'butt'; // reset for other drawing functions\n }\n };\n var drawOverlay = function drawOverlay() {\n if (!shouldDrawOverlay) {\n return;\n }\n r.drawEdgeOverlay(context, edge);\n };\n var drawUnderlay = function drawUnderlay() {\n if (!shouldDrawOverlay) {\n return;\n }\n r.drawEdgeUnderlay(context, edge);\n };\n var drawArrows = function drawArrows() {\n var arrowOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveArrowOpacity;\n r.drawArrowheads(context, edge, arrowOpacity);\n };\n var drawText = function drawText() {\n r.drawElementText(context, edge, null, drawLabel);\n };\n context.lineJoin = 'round';\n var ghost = edge.pstyle('ghost').value === 'yes';\n if (ghost) {\n var gx = edge.pstyle('ghost-offset-x').pfValue;\n var gy = edge.pstyle('ghost-offset-y').pfValue;\n var ghostOpacity = edge.pstyle('ghost-opacity').value;\n var effectiveGhostOpacity = effectiveLineOpacity * ghostOpacity;\n context.translate(gx, gy);\n drawLine(effectiveGhostOpacity);\n drawArrows(effectiveGhostOpacity);\n context.translate(-gx, -gy);\n } else {\n drawLineOutline();\n }\n drawUnderlay();\n drawLine();\n drawArrows();\n drawOverlay();\n drawText();\n if (shiftToOriginWithBb) {\n context.translate(bb.x1, bb.y1);\n }\n};\nvar drawEdgeOverlayUnderlay = function drawEdgeOverlayUnderlay(overlayOrUnderlay) {\n if (!['overlay', 'underlay'].includes(overlayOrUnderlay)) {\n throw new Error('Invalid state');\n }\n return function (context, edge) {\n if (!edge.visible()) {\n return;\n }\n var opacity = edge.pstyle(\"\".concat(overlayOrUnderlay, \"-opacity\")).value;\n if (opacity === 0) {\n return;\n }\n var r = this;\n var usePaths = r.usePaths();\n var rs = edge._private.rscratch;\n var padding = edge.pstyle(\"\".concat(overlayOrUnderlay, \"-padding\")).pfValue;\n var width = 2 * padding;\n var color = edge.pstyle(\"\".concat(overlayOrUnderlay, \"-color\")).value;\n context.lineWidth = width;\n if (rs.edgeType === 'self' && !usePaths) {\n context.lineCap = 'butt';\n } else {\n context.lineCap = 'round';\n }\n r.colorStrokeStyle(context, color[0], color[1], color[2], opacity);\n r.drawEdgePath(edge, context, rs.allpts, 'solid');\n };\n};\nCRp$9.drawEdgeOverlay = drawEdgeOverlayUnderlay('overlay');\nCRp$9.drawEdgeUnderlay = drawEdgeOverlayUnderlay('underlay');\nCRp$9.drawEdgePath = function (edge, context, pts, type) {\n var rs = edge._private.rscratch;\n var canvasCxt = context;\n var path;\n var pathCacheHit = false;\n var usePaths = this.usePaths();\n var lineDashPattern = edge.pstyle('line-dash-pattern').pfValue;\n var lineDashOffset = edge.pstyle('line-dash-offset').pfValue;\n if (usePaths) {\n var pathCacheKey = pts.join('$');\n var keyMatches = rs.pathCacheKey && rs.pathCacheKey === pathCacheKey;\n if (keyMatches) {\n path = context = rs.pathCache;\n pathCacheHit = true;\n } else {\n path = context = new Path2D();\n rs.pathCacheKey = pathCacheKey;\n rs.pathCache = path;\n }\n }\n if (canvasCxt.setLineDash) {\n // for very outofdate browsers\n switch (type) {\n case 'dotted':\n canvasCxt.setLineDash([1, 1]);\n break;\n case 'dashed':\n canvasCxt.setLineDash(lineDashPattern);\n canvasCxt.lineDashOffset = lineDashOffset;\n break;\n case 'solid':\n canvasCxt.setLineDash([]);\n break;\n }\n }\n if (!pathCacheHit && !rs.badLine) {\n if (context.beginPath) {\n context.beginPath();\n }\n context.moveTo(pts[0], pts[1]);\n switch (rs.edgeType) {\n case 'bezier':\n case 'self':\n case 'compound':\n case 'multibezier':\n for (var i = 2; i + 3 < pts.length; i += 4) {\n context.quadraticCurveTo(pts[i], pts[i + 1], pts[i + 2], pts[i + 3]);\n }\n break;\n case 'straight':\n case 'haystack':\n for (var _i = 2; _i + 1 < pts.length; _i += 2) {\n context.lineTo(pts[_i], pts[_i + 1]);\n }\n break;\n case 'segments':\n if (rs.isRound) {\n var _iterator = _createForOfIteratorHelper(rs.roundCorners),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var corner = _step.value;\n drawPreparedRoundCorner(context, corner);\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n context.lineTo(pts[pts.length - 2], pts[pts.length - 1]);\n } else {\n for (var _i2 = 2; _i2 + 1 < pts.length; _i2 += 2) {\n context.lineTo(pts[_i2], pts[_i2 + 1]);\n }\n }\n break;\n }\n }\n context = canvasCxt;\n if (usePaths) {\n context.stroke(path);\n } else {\n context.stroke();\n }\n\n // reset any line dashes\n if (context.setLineDash) {\n // for very outofdate browsers\n context.setLineDash([]);\n }\n};\nCRp$9.drawEdgeTrianglePath = function (edge, context, pts) {\n // use line stroke style for triangle fill style\n context.fillStyle = context.strokeStyle;\n var edgeWidth = edge.pstyle('width').pfValue;\n for (var i = 0; i + 1 < pts.length; i += 2) {\n var vector = [pts[i + 2] - pts[i], pts[i + 3] - pts[i + 1]];\n var length = Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]);\n var normal = [vector[1] / length, -vector[0] / length];\n var triangleHead = [normal[0] * edgeWidth / 2, normal[1] * edgeWidth / 2];\n context.beginPath();\n context.moveTo(pts[i] - triangleHead[0], pts[i + 1] - triangleHead[1]);\n context.lineTo(pts[i] + triangleHead[0], pts[i + 1] + triangleHead[1]);\n context.lineTo(pts[i + 2], pts[i + 3]);\n context.closePath();\n context.fill();\n }\n};\nCRp$9.drawArrowheads = function (context, edge, opacity) {\n var rs = edge._private.rscratch;\n var isHaystack = rs.edgeType === 'haystack';\n if (!isHaystack) {\n this.drawArrowhead(context, edge, 'source', rs.arrowStartX, rs.arrowStartY, rs.srcArrowAngle, opacity);\n }\n this.drawArrowhead(context, edge, 'mid-target', rs.midX, rs.midY, rs.midtgtArrowAngle, opacity);\n this.drawArrowhead(context, edge, 'mid-source', rs.midX, rs.midY, rs.midsrcArrowAngle, opacity);\n if (!isHaystack) {\n this.drawArrowhead(context, edge, 'target', rs.arrowEndX, rs.arrowEndY, rs.tgtArrowAngle, opacity);\n }\n};\nCRp$9.drawArrowhead = function (context, edge, prefix, x, y, angle, opacity) {\n if (isNaN(x) || x == null || isNaN(y) || y == null || isNaN(angle) || angle == null) {\n return;\n }\n var self = this;\n var arrowShape = edge.pstyle(prefix + '-arrow-shape').value;\n if (arrowShape === 'none') {\n return;\n }\n var arrowClearFill = edge.pstyle(prefix + '-arrow-fill').value === 'hollow' ? 'both' : 'filled';\n var arrowFill = edge.pstyle(prefix + '-arrow-fill').value;\n var edgeWidth = edge.pstyle('width').pfValue;\n var pArrowWidth = edge.pstyle(prefix + '-arrow-width');\n var arrowWidth = pArrowWidth.value === 'match-line' ? edgeWidth : pArrowWidth.pfValue;\n if (pArrowWidth.units === '%') arrowWidth *= edgeWidth;\n var edgeOpacity = edge.pstyle('opacity').value;\n if (opacity === undefined) {\n opacity = edgeOpacity;\n }\n var gco = context.globalCompositeOperation;\n if (opacity !== 1 || arrowFill === 'hollow') {\n // then extra clear is needed\n context.globalCompositeOperation = 'destination-out';\n self.colorFillStyle(context, 255, 255, 255, 1);\n self.colorStrokeStyle(context, 255, 255, 255, 1);\n self.drawArrowShape(edge, context, arrowClearFill, edgeWidth, arrowShape, arrowWidth, x, y, angle);\n context.globalCompositeOperation = gco;\n } // otherwise, the opaque arrow clears it for free :)\n\n var color = edge.pstyle(prefix + '-arrow-color').value;\n self.colorFillStyle(context, color[0], color[1], color[2], opacity);\n self.colorStrokeStyle(context, color[0], color[1], color[2], opacity);\n self.drawArrowShape(edge, context, arrowFill, edgeWidth, arrowShape, arrowWidth, x, y, angle);\n};\nCRp$9.drawArrowShape = function (edge, context, fill, edgeWidth, shape, shapeWidth, x, y, angle) {\n var r = this;\n var usePaths = this.usePaths() && shape !== 'triangle-cross';\n var pathCacheHit = false;\n var path;\n var canvasContext = context;\n var translation = {\n x: x,\n y: y\n };\n var scale = edge.pstyle('arrow-scale').value;\n var size = this.getArrowWidth(edgeWidth, scale);\n var shapeImpl = r.arrowShapes[shape];\n if (usePaths) {\n var cache = r.arrowPathCache = r.arrowPathCache || [];\n var key = hashString(shape);\n var cachedPath = cache[key];\n if (cachedPath != null) {\n path = context = cachedPath;\n pathCacheHit = true;\n } else {\n path = context = new Path2D();\n cache[key] = path;\n }\n }\n if (!pathCacheHit) {\n if (context.beginPath) {\n context.beginPath();\n }\n if (usePaths) {\n // store in the path cache with values easily manipulated later\n shapeImpl.draw(context, 1, 0, {\n x: 0,\n y: 0\n }, 1);\n } else {\n shapeImpl.draw(context, size, angle, translation, edgeWidth);\n }\n if (context.closePath) {\n context.closePath();\n }\n }\n context = canvasContext;\n if (usePaths) {\n // set transform to arrow position/orientation\n context.translate(x, y);\n context.rotate(angle);\n context.scale(size, size);\n }\n if (fill === 'filled' || fill === 'both') {\n if (usePaths) {\n context.fill(path);\n } else {\n context.fill();\n }\n }\n if (fill === 'hollow' || fill === 'both') {\n context.lineWidth = shapeWidth / (usePaths ? size : 1);\n context.lineJoin = 'miter';\n if (usePaths) {\n context.stroke(path);\n } else {\n context.stroke();\n }\n }\n if (usePaths) {\n // reset transform by applying inverse\n context.scale(1 / size, 1 / size);\n context.rotate(-angle);\n context.translate(-x, -y);\n }\n};\n\nvar CRp$8 = {};\nCRp$8.safeDrawImage = function (context, img, ix, iy, iw, ih, x, y, w, h) {\n // detect problematic cases for old browsers with bad images (cheaper than try-catch)\n if (iw <= 0 || ih <= 0 || w <= 0 || h <= 0) {\n return;\n }\n try {\n context.drawImage(img, ix, iy, iw, ih, x, y, w, h);\n } catch (e) {\n warn(e);\n }\n};\nCRp$8.drawInscribedImage = function (context, img, node, index, nodeOpacity) {\n var r = this;\n var pos = node.position();\n var nodeX = pos.x;\n var nodeY = pos.y;\n var styleObj = node.cy().style();\n var getIndexedStyle = styleObj.getIndexedStyle.bind(styleObj);\n var fit = getIndexedStyle(node, 'background-fit', 'value', index);\n var repeat = getIndexedStyle(node, 'background-repeat', 'value', index);\n var nodeW = node.width();\n var nodeH = node.height();\n var paddingX2 = node.padding() * 2;\n var nodeTW = nodeW + (getIndexedStyle(node, 'background-width-relative-to', 'value', index) === 'inner' ? 0 : paddingX2);\n var nodeTH = nodeH + (getIndexedStyle(node, 'background-height-relative-to', 'value', index) === 'inner' ? 0 : paddingX2);\n var rs = node._private.rscratch;\n var clip = getIndexedStyle(node, 'background-clip', 'value', index);\n var shouldClip = clip === 'node';\n var imgOpacity = getIndexedStyle(node, 'background-image-opacity', 'value', index) * nodeOpacity;\n var smooth = getIndexedStyle(node, 'background-image-smoothing', 'value', index);\n var cornerRadius = node.pstyle('corner-radius').value;\n if (cornerRadius !== 'auto') cornerRadius = node.pstyle('corner-radius').pfValue;\n var imgW = img.width || img.cachedW;\n var imgH = img.height || img.cachedH;\n\n // workaround for broken browsers like ie\n if (null == imgW || null == imgH) {\n document.body.appendChild(img); // eslint-disable-line no-undef\n\n imgW = img.cachedW = img.width || img.offsetWidth;\n imgH = img.cachedH = img.height || img.offsetHeight;\n document.body.removeChild(img); // eslint-disable-line no-undef\n }\n var w = imgW;\n var h = imgH;\n if (getIndexedStyle(node, 'background-width', 'value', index) !== 'auto') {\n if (getIndexedStyle(node, 'background-width', 'units', index) === '%') {\n w = getIndexedStyle(node, 'background-width', 'pfValue', index) * nodeTW;\n } else {\n w = getIndexedStyle(node, 'background-width', 'pfValue', index);\n }\n }\n if (getIndexedStyle(node, 'background-height', 'value', index) !== 'auto') {\n if (getIndexedStyle(node, 'background-height', 'units', index) === '%') {\n h = getIndexedStyle(node, 'background-height', 'pfValue', index) * nodeTH;\n } else {\n h = getIndexedStyle(node, 'background-height', 'pfValue', index);\n }\n }\n if (w === 0 || h === 0) {\n return; // no point in drawing empty image (and chrome is broken in this case)\n }\n if (fit === 'contain') {\n var scale = Math.min(nodeTW / w, nodeTH / h);\n w *= scale;\n h *= scale;\n } else if (fit === 'cover') {\n var scale = Math.max(nodeTW / w, nodeTH / h);\n w *= scale;\n h *= scale;\n }\n var x = nodeX - nodeTW / 2; // left\n var posXUnits = getIndexedStyle(node, 'background-position-x', 'units', index);\n var posXPfVal = getIndexedStyle(node, 'background-position-x', 'pfValue', index);\n if (posXUnits === '%') {\n x += (nodeTW - w) * posXPfVal;\n } else {\n x += posXPfVal;\n }\n var offXUnits = getIndexedStyle(node, 'background-offset-x', 'units', index);\n var offXPfVal = getIndexedStyle(node, 'background-offset-x', 'pfValue', index);\n if (offXUnits === '%') {\n x += (nodeTW - w) * offXPfVal;\n } else {\n x += offXPfVal;\n }\n var y = nodeY - nodeTH / 2; // top\n var posYUnits = getIndexedStyle(node, 'background-position-y', 'units', index);\n var posYPfVal = getIndexedStyle(node, 'background-position-y', 'pfValue', index);\n if (posYUnits === '%') {\n y += (nodeTH - h) * posYPfVal;\n } else {\n y += posYPfVal;\n }\n var offYUnits = getIndexedStyle(node, 'background-offset-y', 'units', index);\n var offYPfVal = getIndexedStyle(node, 'background-offset-y', 'pfValue', index);\n if (offYUnits === '%') {\n y += (nodeTH - h) * offYPfVal;\n } else {\n y += offYPfVal;\n }\n if (rs.pathCache) {\n x -= nodeX;\n y -= nodeY;\n nodeX = 0;\n nodeY = 0;\n }\n var gAlpha = context.globalAlpha;\n context.globalAlpha = imgOpacity;\n var smoothingEnabled = r.getImgSmoothing(context);\n var isSmoothingSwitched = false;\n if (smooth === 'no' && smoothingEnabled) {\n r.setImgSmoothing(context, false);\n isSmoothingSwitched = true;\n } else if (smooth === 'yes' && !smoothingEnabled) {\n r.setImgSmoothing(context, true);\n isSmoothingSwitched = true;\n }\n if (repeat === 'no-repeat') {\n if (shouldClip) {\n context.save();\n if (rs.pathCache) {\n context.clip(rs.pathCache);\n } else {\n r.nodeShapes[r.getNodeShape(node)].draw(context, nodeX, nodeY, nodeTW, nodeTH, cornerRadius, rs);\n context.clip();\n }\n }\n r.safeDrawImage(context, img, 0, 0, imgW, imgH, x, y, w, h);\n if (shouldClip) {\n context.restore();\n }\n } else {\n var pattern = context.createPattern(img, repeat);\n context.fillStyle = pattern;\n r.nodeShapes[r.getNodeShape(node)].draw(context, nodeX, nodeY, nodeTW, nodeTH, cornerRadius, rs);\n context.translate(x, y);\n context.fill();\n context.translate(-x, -y);\n }\n context.globalAlpha = gAlpha;\n if (isSmoothingSwitched) {\n r.setImgSmoothing(context, smoothingEnabled);\n }\n};\n\nvar CRp$7 = {};\nCRp$7.eleTextBiggerThanMin = function (ele, scale) {\n if (!scale) {\n var zoom = ele.cy().zoom();\n var pxRatio = this.getPixelRatio();\n var lvl = Math.ceil(log2(zoom * pxRatio)); // the effective texture level\n\n scale = Math.pow(2, lvl);\n }\n var computedSize = ele.pstyle('font-size').pfValue * scale;\n var minSize = ele.pstyle('min-zoomed-font-size').pfValue;\n if (computedSize < minSize) {\n return false;\n }\n return true;\n};\nCRp$7.drawElementText = function (context, ele, shiftToOriginWithBb, force, prefix) {\n var useEleOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;\n var r = this;\n if (force == null) {\n if (useEleOpacity && !r.eleTextBiggerThanMin(ele)) {\n return;\n }\n } else if (force === false) {\n return;\n }\n if (ele.isNode()) {\n var label = ele.pstyle('label');\n if (!label || !label.value) {\n return;\n }\n var justification = r.getLabelJustification(ele);\n context.textAlign = justification;\n context.textBaseline = 'bottom';\n } else {\n var badLine = ele.element()._private.rscratch.badLine;\n var _label = ele.pstyle('label');\n var srcLabel = ele.pstyle('source-label');\n var tgtLabel = ele.pstyle('target-label');\n if (badLine || (!_label || !_label.value) && (!srcLabel || !srcLabel.value) && (!tgtLabel || !tgtLabel.value)) {\n return;\n }\n context.textAlign = 'center';\n context.textBaseline = 'bottom';\n }\n var applyRotation = !shiftToOriginWithBb;\n var bb;\n if (shiftToOriginWithBb) {\n bb = shiftToOriginWithBb;\n context.translate(-bb.x1, -bb.y1);\n }\n if (prefix == null) {\n r.drawText(context, ele, null, applyRotation, useEleOpacity);\n if (ele.isEdge()) {\n r.drawText(context, ele, 'source', applyRotation, useEleOpacity);\n r.drawText(context, ele, 'target', applyRotation, useEleOpacity);\n }\n } else {\n r.drawText(context, ele, prefix, applyRotation, useEleOpacity);\n }\n if (shiftToOriginWithBb) {\n context.translate(bb.x1, bb.y1);\n }\n};\nCRp$7.getFontCache = function (context) {\n var cache;\n this.fontCaches = this.fontCaches || [];\n for (var i = 0; i < this.fontCaches.length; i++) {\n cache = this.fontCaches[i];\n if (cache.context === context) {\n return cache;\n }\n }\n cache = {\n context: context\n };\n this.fontCaches.push(cache);\n return cache;\n};\n\n// set up canvas context with font\n// returns transformed text string\nCRp$7.setupTextStyle = function (context, ele) {\n var useEleOpacity = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n // Font style\n var labelStyle = ele.pstyle('font-style').strValue;\n var labelSize = ele.pstyle('font-size').pfValue + 'px';\n var labelFamily = ele.pstyle('font-family').strValue;\n var labelWeight = ele.pstyle('font-weight').strValue;\n var opacity = useEleOpacity ? ele.effectiveOpacity() * ele.pstyle('text-opacity').value : 1;\n var outlineOpacity = ele.pstyle('text-outline-opacity').value * opacity;\n var color = ele.pstyle('color').value;\n var outlineColor = ele.pstyle('text-outline-color').value;\n context.font = labelStyle + ' ' + labelWeight + ' ' + labelSize + ' ' + labelFamily;\n context.lineJoin = 'round'; // so text outlines aren't jagged\n\n this.colorFillStyle(context, color[0], color[1], color[2], opacity);\n this.colorStrokeStyle(context, outlineColor[0], outlineColor[1], outlineColor[2], outlineOpacity);\n};\nfunction circle(ctx, x, y, width, height) {\n var diameter = Math.min(width, height);\n var radius = diameter / 2;\n var centerX = x + width / 2;\n var centerY = y + height / 2;\n ctx.beginPath();\n ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);\n ctx.closePath();\n}\nfunction roundRect(ctx, x, y, width, height) {\n var radius = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 5;\n var r = Math.min(radius, width / 2, height / 2); // prevent overflow\n ctx.beginPath();\n ctx.moveTo(x + r, y);\n ctx.lineTo(x + width - r, y);\n ctx.quadraticCurveTo(x + width, y, x + width, y + r);\n ctx.lineTo(x + width, y + height - r);\n ctx.quadraticCurveTo(x + width, y + height, x + width - r, y + height);\n ctx.lineTo(x + r, y + height);\n ctx.quadraticCurveTo(x, y + height, x, y + height - r);\n ctx.lineTo(x, y + r);\n ctx.quadraticCurveTo(x, y, x + r, y);\n ctx.closePath();\n}\nCRp$7.getTextAngle = function (ele, prefix) {\n var theta;\n var _p = ele._private;\n var rscratch = _p.rscratch;\n var pdash = prefix ? prefix + '-' : '';\n var rotation = ele.pstyle(pdash + 'text-rotation');\n if (rotation.strValue === 'autorotate') {\n var textAngle = getPrefixedProperty(rscratch, 'labelAngle', prefix);\n theta = ele.isEdge() ? textAngle : 0;\n } else if (rotation.strValue === 'none') {\n theta = 0;\n } else {\n theta = rotation.pfValue;\n }\n return theta;\n};\nCRp$7.drawText = function (context, ele, prefix) {\n var applyRotation = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;\n var useEleOpacity = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n var _p = ele._private;\n var rscratch = _p.rscratch;\n var parentOpacity = useEleOpacity ? ele.effectiveOpacity() : 1;\n if (useEleOpacity && (parentOpacity === 0 || ele.pstyle('text-opacity').value === 0)) {\n return;\n }\n\n // use 'main' as an alias for the main label (i.e. null prefix)\n if (prefix === 'main') {\n prefix = null;\n }\n var textX = getPrefixedProperty(rscratch, 'labelX', prefix);\n var textY = getPrefixedProperty(rscratch, 'labelY', prefix);\n var orgTextX, orgTextY; // used for rotation\n var text = this.getLabelText(ele, prefix);\n if (text != null && text !== '' && !isNaN(textX) && !isNaN(textY)) {\n this.setupTextStyle(context, ele, useEleOpacity);\n var pdash = prefix ? prefix + '-' : '';\n var textW = getPrefixedProperty(rscratch, 'labelWidth', prefix);\n var textH = getPrefixedProperty(rscratch, 'labelHeight', prefix);\n var marginX = ele.pstyle(pdash + 'text-margin-x').pfValue;\n var marginY = ele.pstyle(pdash + 'text-margin-y').pfValue;\n var isEdge = ele.isEdge();\n var halign = ele.pstyle('text-halign').value;\n var valign = ele.pstyle('text-valign').value;\n if (isEdge) {\n halign = 'center';\n valign = 'center';\n }\n textX += marginX;\n textY += marginY;\n var theta;\n if (!applyRotation) {\n theta = 0;\n } else {\n theta = this.getTextAngle(ele, prefix);\n }\n if (theta !== 0) {\n orgTextX = textX;\n orgTextY = textY;\n context.translate(orgTextX, orgTextY);\n context.rotate(theta);\n textX = 0;\n textY = 0;\n }\n switch (valign) {\n case 'top':\n break;\n case 'center':\n textY += textH / 2;\n break;\n case 'bottom':\n textY += textH;\n break;\n }\n var backgroundOpacity = ele.pstyle('text-background-opacity').value;\n var borderOpacity = ele.pstyle('text-border-opacity').value;\n var textBorderWidth = ele.pstyle('text-border-width').pfValue;\n var backgroundPadding = ele.pstyle('text-background-padding').pfValue;\n var styleShape = ele.pstyle('text-background-shape').strValue;\n var rounded = styleShape === 'round-rectangle' || styleShape === 'roundrectangle';\n var circled = styleShape === 'circle';\n var roundRadius = 2;\n if (backgroundOpacity > 0 || textBorderWidth > 0 && borderOpacity > 0) {\n var textFill = context.fillStyle;\n var textStroke = context.strokeStyle;\n var textLineWidth = context.lineWidth;\n var textBackgroundColor = ele.pstyle('text-background-color').value;\n var textBorderColor = ele.pstyle('text-border-color').value;\n var textBorderStyle = ele.pstyle('text-border-style').value;\n var doFill = backgroundOpacity > 0;\n var doStroke = textBorderWidth > 0 && borderOpacity > 0;\n var bgX = textX - backgroundPadding;\n switch (halign) {\n case 'left':\n bgX -= textW;\n break;\n case 'center':\n bgX -= textW / 2;\n break;\n }\n var bgY = textY - textH - backgroundPadding;\n var bgW = textW + 2 * backgroundPadding;\n var bgH = textH + 2 * backgroundPadding;\n if (doFill) {\n context.fillStyle = \"rgba(\".concat(textBackgroundColor[0], \",\").concat(textBackgroundColor[1], \",\").concat(textBackgroundColor[2], \",\").concat(backgroundOpacity * parentOpacity, \")\");\n }\n if (doStroke) {\n context.strokeStyle = \"rgba(\".concat(textBorderColor[0], \",\").concat(textBorderColor[1], \",\").concat(textBorderColor[2], \",\").concat(borderOpacity * parentOpacity, \")\");\n context.lineWidth = textBorderWidth;\n if (context.setLineDash) {\n switch (textBorderStyle) {\n case 'dotted':\n context.setLineDash([1, 1]);\n break;\n case 'dashed':\n context.setLineDash([4, 2]);\n break;\n case 'double':\n context.lineWidth = textBorderWidth / 4;\n context.setLineDash([]);\n break;\n case 'solid':\n default:\n context.setLineDash([]);\n break;\n }\n }\n }\n if (rounded) {\n context.beginPath();\n roundRect(context, bgX, bgY, bgW, bgH, roundRadius);\n } else if (circled) {\n context.beginPath();\n circle(context, bgX, bgY, bgW, bgH);\n } else {\n context.beginPath();\n context.rect(bgX, bgY, bgW, bgH);\n }\n if (doFill) context.fill();\n if (doStroke) context.stroke();\n\n // Double border pass for 'double' style\n if (doStroke && textBorderStyle === 'double') {\n var whiteWidth = textBorderWidth / 2;\n context.beginPath();\n if (rounded) {\n roundRect(context, bgX + whiteWidth, bgY + whiteWidth, bgW - 2 * whiteWidth, bgH - 2 * whiteWidth, roundRadius);\n } else {\n context.rect(bgX + whiteWidth, bgY + whiteWidth, bgW - 2 * whiteWidth, bgH - 2 * whiteWidth);\n }\n context.stroke();\n }\n context.fillStyle = textFill;\n context.strokeStyle = textStroke;\n context.lineWidth = textLineWidth;\n if (context.setLineDash) context.setLineDash([]);\n }\n var lineWidth = 2 * ele.pstyle('text-outline-width').pfValue; // *2 b/c the stroke is drawn centred on the middle\n\n if (lineWidth > 0) {\n context.lineWidth = lineWidth;\n }\n if (ele.pstyle('text-wrap').value === 'wrap') {\n var lines = getPrefixedProperty(rscratch, 'labelWrapCachedLines', prefix);\n var lineHeight = getPrefixedProperty(rscratch, 'labelLineHeight', prefix);\n var halfTextW = textW / 2;\n var justification = this.getLabelJustification(ele);\n if (justification === 'auto') ; else if (halign === 'left') {\n // auto justification : right\n if (justification === 'left') {\n textX += -textW;\n } else if (justification === 'center') {\n textX += -halfTextW;\n } // else same as auto\n } else if (halign === 'center') {\n // auto justfication : center\n if (justification === 'left') {\n textX += -halfTextW;\n } else if (justification === 'right') {\n textX += halfTextW;\n } // else same as auto\n } else if (halign === 'right') {\n // auto justification : left\n if (justification === 'center') {\n textX += halfTextW;\n } else if (justification === 'right') {\n textX += textW;\n } // else same as auto\n }\n switch (valign) {\n case 'top':\n textY -= (lines.length - 1) * lineHeight;\n break;\n case 'center':\n case 'bottom':\n textY -= (lines.length - 1) * lineHeight;\n break;\n }\n for (var l = 0; l < lines.length; l++) {\n if (lineWidth > 0) {\n context.strokeText(lines[l], textX, textY);\n }\n context.fillText(lines[l], textX, textY);\n textY += lineHeight;\n }\n } else {\n if (lineWidth > 0) {\n context.strokeText(text, textX, textY);\n }\n context.fillText(text, textX, textY);\n }\n if (theta !== 0) {\n context.rotate(-theta);\n context.translate(-orgTextX, -orgTextY);\n }\n }\n};\n\n/* global Path2D */\n\nvar CRp$6 = {};\nCRp$6.drawNode = function (context, node, shiftToOriginWithBb) {\n var drawLabel = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;\n var shouldDrawOverlay = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n var shouldDrawOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;\n var r = this;\n var nodeWidth, nodeHeight;\n var _p = node._private;\n var rs = _p.rscratch;\n var pos = node.position();\n if (!number$1(pos.x) || !number$1(pos.y)) {\n return; // can't draw node with undefined position\n }\n if (shouldDrawOpacity && !node.visible()) {\n return;\n }\n var eleOpacity = shouldDrawOpacity ? node.effectiveOpacity() : 1;\n var usePaths = r.usePaths();\n var path;\n var pathCacheHit = false;\n var padding = node.padding();\n nodeWidth = node.width() + 2 * padding;\n nodeHeight = node.height() + 2 * padding;\n\n //\n // setup shift\n\n var bb;\n if (shiftToOriginWithBb) {\n bb = shiftToOriginWithBb;\n context.translate(-bb.x1, -bb.y1);\n }\n\n //\n // load bg image\n\n var bgImgProp = node.pstyle('background-image');\n var urls = bgImgProp.value;\n var urlDefined = new Array(urls.length);\n var image = new Array(urls.length);\n var numImages = 0;\n for (var i = 0; i < urls.length; i++) {\n var url = urls[i];\n var defd = urlDefined[i] = url != null && url !== 'none';\n if (defd) {\n var bgImgCrossOrigin = node.cy().style().getIndexedStyle(node, 'background-image-crossorigin', 'value', i);\n numImages++;\n\n // get image, and if not loaded then ask to redraw when later loaded\n image[i] = r.getCachedImage(url, bgImgCrossOrigin, function () {\n _p.backgroundTimestamp = Date.now();\n node.emitAndNotify('background');\n });\n }\n }\n\n //\n // setup styles\n\n var darkness = node.pstyle('background-blacken').value;\n var borderWidth = node.pstyle('border-width').pfValue;\n var bgOpacity = node.pstyle('background-opacity').value * eleOpacity;\n var borderColor = node.pstyle('border-color').value;\n var borderStyle = node.pstyle('border-style').value;\n var borderJoin = node.pstyle('border-join').value;\n var borderCap = node.pstyle('border-cap').value;\n var borderPosition = node.pstyle('border-position').value;\n var borderPattern = node.pstyle('border-dash-pattern').pfValue;\n var borderOffset = node.pstyle('border-dash-offset').pfValue;\n var borderOpacity = node.pstyle('border-opacity').value * eleOpacity;\n var outlineWidth = node.pstyle('outline-width').pfValue;\n var outlineColor = node.pstyle('outline-color').value;\n var outlineStyle = node.pstyle('outline-style').value;\n var outlineOpacity = node.pstyle('outline-opacity').value * eleOpacity;\n var outlineOffset = node.pstyle('outline-offset').value;\n var cornerRadius = node.pstyle('corner-radius').value;\n if (cornerRadius !== 'auto') cornerRadius = node.pstyle('corner-radius').pfValue;\n var setupShapeColor = function setupShapeColor() {\n var bgOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : bgOpacity;\n r.eleFillStyle(context, node, bgOpy);\n };\n var setupBorderColor = function setupBorderColor() {\n var bdrOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : borderOpacity;\n r.colorStrokeStyle(context, borderColor[0], borderColor[1], borderColor[2], bdrOpy);\n };\n var setupOutlineColor = function setupOutlineColor() {\n var otlnOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : outlineOpacity;\n r.colorStrokeStyle(context, outlineColor[0], outlineColor[1], outlineColor[2], otlnOpy);\n };\n\n //\n // setup shape\n\n var getPath = function getPath(width, height, shape, points) {\n var pathCache = r.nodePathCache = r.nodePathCache || [];\n var key = hashStrings(shape === 'polygon' ? shape + ',' + points.join(',') : shape, '' + height, '' + width, '' + cornerRadius);\n var cachedPath = pathCache[key];\n var path;\n var cacheHit = false;\n if (cachedPath != null) {\n path = cachedPath;\n cacheHit = true;\n rs.pathCache = path;\n } else {\n path = new Path2D();\n pathCache[key] = rs.pathCache = path;\n }\n return {\n path: path,\n cacheHit: cacheHit\n };\n };\n var styleShape = node.pstyle('shape').strValue;\n var shapePts = node.pstyle('shape-polygon-points').pfValue;\n if (usePaths) {\n context.translate(pos.x, pos.y);\n var shapePath = getPath(nodeWidth, nodeHeight, styleShape, shapePts);\n path = shapePath.path;\n pathCacheHit = shapePath.cacheHit;\n }\n var drawShape = function drawShape() {\n if (!pathCacheHit) {\n var npos = pos;\n if (usePaths) {\n npos = {\n x: 0,\n y: 0\n };\n }\n r.nodeShapes[r.getNodeShape(node)].draw(path || context, npos.x, npos.y, nodeWidth, nodeHeight, cornerRadius, rs);\n }\n if (usePaths) {\n context.fill(path);\n } else {\n context.fill();\n }\n };\n var drawImages = function drawImages() {\n var nodeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : eleOpacity;\n var inside = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n var prevBging = _p.backgrounding;\n var totalCompleted = 0;\n for (var _i = 0; _i < image.length; _i++) {\n var bgContainment = node.cy().style().getIndexedStyle(node, 'background-image-containment', 'value', _i);\n if (inside && bgContainment === 'over' || !inside && bgContainment === 'inside') {\n totalCompleted++;\n continue;\n }\n if (urlDefined[_i] && image[_i].complete && !image[_i].error) {\n totalCompleted++;\n r.drawInscribedImage(context, image[_i], node, _i, nodeOpacity);\n }\n }\n _p.backgrounding = !(totalCompleted === numImages);\n if (prevBging !== _p.backgrounding) {\n // update style b/c :backgrounding state changed\n node.updateStyle(false);\n }\n };\n var drawPie = function drawPie() {\n var redrawShape = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n var pieOpacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : eleOpacity;\n if (r.hasPie(node)) {\n r.drawPie(context, node, pieOpacity);\n\n // redraw/restore path if steps after pie need it\n if (redrawShape) {\n if (!usePaths) {\n r.nodeShapes[r.getNodeShape(node)].draw(context, pos.x, pos.y, nodeWidth, nodeHeight, cornerRadius, rs);\n }\n }\n }\n };\n var drawStripe = function drawStripe() {\n var redrawShape = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n var stripeOpacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : eleOpacity;\n if (r.hasStripe(node)) {\n context.save();\n if (usePaths) {\n context.clip(rs.pathCache);\n } else {\n r.nodeShapes[r.getNodeShape(node)].draw(context, pos.x, pos.y, nodeWidth, nodeHeight, cornerRadius, rs);\n context.clip();\n }\n r.drawStripe(context, node, stripeOpacity);\n context.restore();\n\n // redraw/restore path if steps after stripes need it\n if (redrawShape) {\n if (!usePaths) {\n r.nodeShapes[r.getNodeShape(node)].draw(context, pos.x, pos.y, nodeWidth, nodeHeight, cornerRadius, rs);\n }\n }\n }\n };\n var darken = function darken() {\n var darkenOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : eleOpacity;\n var opacity = (darkness > 0 ? darkness : -darkness) * darkenOpacity;\n var c = darkness > 0 ? 0 : 255;\n if (darkness !== 0) {\n r.colorFillStyle(context, c, c, c, opacity);\n if (usePaths) {\n context.fill(path);\n } else {\n context.fill();\n }\n }\n };\n var drawBorder = function drawBorder() {\n if (borderWidth > 0) {\n context.lineWidth = borderWidth;\n context.lineCap = borderCap;\n context.lineJoin = borderJoin;\n if (context.setLineDash) {\n // for very outofdate browsers\n switch (borderStyle) {\n case 'dotted':\n context.setLineDash([1, 1]);\n break;\n case 'dashed':\n context.setLineDash(borderPattern);\n context.lineDashOffset = borderOffset;\n break;\n case 'solid':\n case 'double':\n context.setLineDash([]);\n break;\n }\n }\n if (borderPosition !== 'center') {\n context.save();\n context.lineWidth *= 2;\n if (borderPosition === 'inside') {\n usePaths ? context.clip(path) : context.clip();\n } else {\n var region = new Path2D();\n region.rect(-nodeWidth / 2 - borderWidth, -nodeHeight / 2 - borderWidth, nodeWidth + 2 * borderWidth, nodeHeight + 2 * borderWidth);\n region.addPath(path);\n context.clip(region, 'evenodd');\n }\n usePaths ? context.stroke(path) : context.stroke();\n context.restore();\n } else {\n usePaths ? context.stroke(path) : context.stroke();\n }\n if (borderStyle === 'double') {\n context.lineWidth = borderWidth / 3;\n var gco = context.globalCompositeOperation;\n context.globalCompositeOperation = 'destination-out';\n if (usePaths) {\n context.stroke(path);\n } else {\n context.stroke();\n }\n context.globalCompositeOperation = gco;\n }\n\n // reset in case we changed the border style\n if (context.setLineDash) {\n // for very outofdate browsers\n context.setLineDash([]);\n }\n }\n };\n var drawOutline = function drawOutline() {\n if (outlineWidth > 0) {\n context.lineWidth = outlineWidth;\n context.lineCap = 'butt';\n if (context.setLineDash) {\n // for very outofdate browsers\n switch (outlineStyle) {\n case 'dotted':\n context.setLineDash([1, 1]);\n break;\n case 'dashed':\n context.setLineDash([4, 2]);\n break;\n case 'solid':\n case 'double':\n context.setLineDash([]);\n break;\n }\n }\n var npos = pos;\n if (usePaths) {\n npos = {\n x: 0,\n y: 0\n };\n }\n var shape = r.getNodeShape(node);\n var bWidth = borderWidth;\n if (borderPosition === 'inside') bWidth = 0;\n if (borderPosition === 'outside') bWidth *= 2;\n var scaleX = (nodeWidth + bWidth + (outlineWidth + outlineOffset)) / nodeWidth;\n var scaleY = (nodeHeight + bWidth + (outlineWidth + outlineOffset)) / nodeHeight;\n var sWidth = nodeWidth * scaleX;\n var sHeight = nodeHeight * scaleY;\n var points = r.nodeShapes[shape].points;\n var _path;\n if (usePaths) {\n var outlinePath = getPath(sWidth, sHeight, shape, points);\n _path = outlinePath.path;\n }\n\n // draw the outline path, either by using expanded points or by scaling \n // the dimensions, depending on shape\n if (shape === \"ellipse\") {\n r.drawEllipsePath(_path || context, npos.x, npos.y, sWidth, sHeight);\n } else if (['round-diamond', 'round-heptagon', 'round-hexagon', 'round-octagon', 'round-pentagon', 'round-polygon', 'round-triangle', 'round-tag'].includes(shape)) {\n var sMult = 0;\n var offsetX = 0;\n var offsetY = 0;\n if (shape === 'round-diamond') {\n sMult = (bWidth + outlineOffset + outlineWidth) * 1.4;\n } else if (shape === 'round-heptagon') {\n sMult = (bWidth + outlineOffset + outlineWidth) * 1.075;\n offsetY = -(bWidth / 2 + outlineOffset + outlineWidth) / 35;\n } else if (shape === 'round-hexagon') {\n sMult = (bWidth + outlineOffset + outlineWidth) * 1.12;\n } else if (shape === 'round-pentagon') {\n sMult = (bWidth + outlineOffset + outlineWidth) * 1.13;\n offsetY = -(bWidth / 2 + outlineOffset + outlineWidth) / 15;\n } else if (shape === 'round-tag') {\n sMult = (bWidth + outlineOffset + outlineWidth) * 1.12;\n offsetX = (bWidth / 2 + outlineWidth + outlineOffset) * .07;\n } else if (shape === 'round-triangle') {\n sMult = (bWidth + outlineOffset + outlineWidth) * (Math.PI / 2);\n offsetY = -(bWidth + outlineOffset / 2 + outlineWidth) / Math.PI;\n }\n if (sMult !== 0) {\n scaleX = (nodeWidth + sMult) / nodeWidth;\n sWidth = nodeWidth * scaleX;\n if (!['round-hexagon', 'round-tag'].includes(shape)) {\n scaleY = (nodeHeight + sMult) / nodeHeight;\n sHeight = nodeHeight * scaleY;\n }\n }\n cornerRadius = cornerRadius === 'auto' ? getRoundPolygonRadius(sWidth, sHeight) : cornerRadius;\n var halfW = sWidth / 2;\n var halfH = sHeight / 2;\n var radius = cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2;\n var p = new Array(points.length / 2);\n var corners = new Array(points.length / 2);\n for (var _i2 = 0; _i2 < points.length / 2; _i2++) {\n p[_i2] = {\n x: npos.x + offsetX + halfW * points[_i2 * 2],\n y: npos.y + offsetY + halfH * points[_i2 * 2 + 1]\n };\n }\n var _i3,\n p1,\n p2,\n p3,\n len = p.length;\n p1 = p[len - 1];\n // for each point\n for (_i3 = 0; _i3 < len; _i3++) {\n p2 = p[_i3 % len];\n p3 = p[(_i3 + 1) % len];\n corners[_i3] = getRoundCorner(p1, p2, p3, radius);\n p1 = p2;\n p2 = p3;\n }\n r.drawRoundPolygonPath(_path || context, npos.x + offsetX, npos.y + offsetY, nodeWidth * scaleX, nodeHeight * scaleY, points, corners);\n } else if (['roundrectangle', 'round-rectangle'].includes(shape)) {\n cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(sWidth, sHeight) : cornerRadius;\n r.drawRoundRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2);\n } else if (['cutrectangle', 'cut-rectangle'].includes(shape)) {\n cornerRadius = cornerRadius === 'auto' ? getCutRectangleCornerLength() : cornerRadius;\n r.drawCutRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, null, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 4);\n } else if (['bottomroundrectangle', 'bottom-round-rectangle'].includes(shape)) {\n cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(sWidth, sHeight) : cornerRadius;\n r.drawBottomRoundRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2);\n } else if (shape === \"barrel\") {\n r.drawBarrelPath(_path || context, npos.x, npos.y, sWidth, sHeight);\n } else if (shape.startsWith(\"polygon\") || ['rhomboid', 'right-rhomboid', 'round-tag', 'tag', 'vee'].includes(shape)) {\n var pad = (bWidth + outlineWidth + outlineOffset) / nodeWidth;\n points = joinLines(expandPolygon(points, pad));\n r.drawPolygonPath(_path || context, npos.x, npos.y, nodeWidth, nodeHeight, points);\n } else {\n var _pad = (bWidth + outlineWidth + outlineOffset) / nodeWidth;\n points = joinLines(expandPolygon(points, -_pad));\n r.drawPolygonPath(_path || context, npos.x, npos.y, nodeWidth, nodeHeight, points);\n }\n if (usePaths) {\n context.stroke(_path);\n } else {\n context.stroke();\n }\n if (outlineStyle === 'double') {\n context.lineWidth = bWidth / 3;\n var gco = context.globalCompositeOperation;\n context.globalCompositeOperation = 'destination-out';\n if (usePaths) {\n context.stroke(_path);\n } else {\n context.stroke();\n }\n context.globalCompositeOperation = gco;\n }\n\n // reset in case we changed the border style\n if (context.setLineDash) {\n // for very outofdate browsers\n context.setLineDash([]);\n }\n }\n };\n var drawOverlay = function drawOverlay() {\n if (shouldDrawOverlay) {\n r.drawNodeOverlay(context, node, pos, nodeWidth, nodeHeight);\n }\n };\n var drawUnderlay = function drawUnderlay() {\n if (shouldDrawOverlay) {\n r.drawNodeUnderlay(context, node, pos, nodeWidth, nodeHeight);\n }\n };\n var drawText = function drawText() {\n r.drawElementText(context, node, null, drawLabel);\n };\n var ghost = node.pstyle('ghost').value === 'yes';\n if (ghost) {\n var gx = node.pstyle('ghost-offset-x').pfValue;\n var gy = node.pstyle('ghost-offset-y').pfValue;\n var ghostOpacity = node.pstyle('ghost-opacity').value;\n var effGhostOpacity = ghostOpacity * eleOpacity;\n context.translate(gx, gy);\n setupOutlineColor();\n drawOutline();\n setupShapeColor(ghostOpacity * bgOpacity);\n drawShape();\n drawImages(effGhostOpacity, true);\n setupBorderColor(ghostOpacity * borderOpacity);\n drawBorder();\n drawPie(darkness !== 0 || borderWidth !== 0);\n drawStripe(darkness !== 0 || borderWidth !== 0);\n drawImages(effGhostOpacity, false);\n darken(effGhostOpacity);\n context.translate(-gx, -gy);\n }\n if (usePaths) {\n context.translate(-pos.x, -pos.y);\n }\n drawUnderlay();\n if (usePaths) {\n context.translate(pos.x, pos.y);\n }\n setupOutlineColor();\n drawOutline();\n setupShapeColor();\n drawShape();\n drawImages(eleOpacity, true);\n setupBorderColor();\n drawBorder();\n drawPie(darkness !== 0 || borderWidth !== 0);\n drawStripe(darkness !== 0 || borderWidth !== 0);\n drawImages(eleOpacity, false);\n darken();\n if (usePaths) {\n context.translate(-pos.x, -pos.y);\n }\n drawText();\n drawOverlay();\n\n //\n // clean up shift\n\n if (shiftToOriginWithBb) {\n context.translate(bb.x1, bb.y1);\n }\n};\nvar drawNodeOverlayUnderlay = function drawNodeOverlayUnderlay(overlayOrUnderlay) {\n if (!['overlay', 'underlay'].includes(overlayOrUnderlay)) {\n throw new Error('Invalid state');\n }\n return function (context, node, pos, nodeWidth, nodeHeight) {\n var r = this;\n if (!node.visible()) {\n return;\n }\n var padding = node.pstyle(\"\".concat(overlayOrUnderlay, \"-padding\")).pfValue;\n var opacity = node.pstyle(\"\".concat(overlayOrUnderlay, \"-opacity\")).value;\n var color = node.pstyle(\"\".concat(overlayOrUnderlay, \"-color\")).value;\n var shape = node.pstyle(\"\".concat(overlayOrUnderlay, \"-shape\")).value;\n var radius = node.pstyle(\"\".concat(overlayOrUnderlay, \"-corner-radius\")).value;\n if (opacity > 0) {\n pos = pos || node.position();\n if (nodeWidth == null || nodeHeight == null) {\n var _padding = node.padding();\n nodeWidth = node.width() + 2 * _padding;\n nodeHeight = node.height() + 2 * _padding;\n }\n r.colorFillStyle(context, color[0], color[1], color[2], opacity);\n r.nodeShapes[shape].draw(context, pos.x, pos.y, nodeWidth + padding * 2, nodeHeight + padding * 2, radius);\n context.fill();\n }\n };\n};\nCRp$6.drawNodeOverlay = drawNodeOverlayUnderlay('overlay');\nCRp$6.drawNodeUnderlay = drawNodeOverlayUnderlay('underlay');\n\n// does the node have at least one pie piece?\nCRp$6.hasPie = function (node) {\n node = node[0]; // ensure ele ref\n\n return node._private.hasPie;\n};\nCRp$6.hasStripe = function (node) {\n node = node[0]; // ensure ele ref\n\n return node._private.hasStripe;\n};\nCRp$6.drawPie = function (context, node, nodeOpacity, pos) {\n node = node[0]; // ensure ele ref\n pos = pos || node.position();\n var cyStyle = node.cy().style();\n var pieSize = node.pstyle('pie-size');\n var hole = node.pstyle('pie-hole');\n var overallStartAngle = node.pstyle('pie-start-angle').pfValue;\n var x = pos.x;\n var y = pos.y;\n var nodeW = node.width();\n var nodeH = node.height();\n var radius = Math.min(nodeW, nodeH) / 2; // must fit in node\n var holeRadius;\n var lastPercent = 0; // what % to continue drawing pie slices from on [0, 1]\n var usePaths = this.usePaths();\n if (usePaths) {\n x = 0;\n y = 0;\n }\n if (pieSize.units === '%') {\n radius = radius * pieSize.pfValue;\n } else if (pieSize.pfValue !== undefined) {\n radius = pieSize.pfValue / 2; // diameter in pixels => radius\n }\n if (hole.units === '%') {\n holeRadius = radius * hole.pfValue;\n } else if (hole.pfValue !== undefined) {\n holeRadius = hole.pfValue / 2; // diameter in pixels => radius\n }\n if (holeRadius >= radius) {\n return; // the pie would be invisible anyway\n }\n for (var i = 1; i <= cyStyle.pieBackgroundN; i++) {\n // 1..N\n var size = node.pstyle('pie-' + i + '-background-size').value;\n var color = node.pstyle('pie-' + i + '-background-color').value;\n var opacity = node.pstyle('pie-' + i + '-background-opacity').value * nodeOpacity;\n var percent = size / 100; // map integer range [0, 100] to [0, 1]\n\n // percent can't push beyond 1\n if (percent + lastPercent > 1) {\n percent = 1 - lastPercent;\n }\n var angleStart = 1.5 * Math.PI + 2 * Math.PI * lastPercent; // start at 12 o'clock and go clockwise\n angleStart += overallStartAngle; // shift by the overall pie start angle\n var angleDelta = 2 * Math.PI * percent;\n var angleEnd = angleStart + angleDelta;\n\n // ignore if\n // - zero size\n // - we're already beyond the full circle\n // - adding the current slice would go beyond the full circle\n if (size === 0 || lastPercent >= 1 || lastPercent + percent > 1) {\n continue;\n }\n if (holeRadius === 0) {\n // make a pie slice\n context.beginPath();\n context.moveTo(x, y);\n context.arc(x, y, radius, angleStart, angleEnd);\n context.closePath();\n } else {\n // make a pie slice that's like the above but with a hole in the middle\n context.beginPath();\n context.arc(x, y, radius, angleStart, angleEnd);\n context.arc(x, y, holeRadius, angleEnd, angleStart, true); // true for anticlockwise\n context.closePath();\n }\n this.colorFillStyle(context, color[0], color[1], color[2], opacity);\n context.fill();\n lastPercent += percent;\n }\n};\nCRp$6.drawStripe = function (context, node, nodeOpacity, pos) {\n node = node[0]; // ensure ele ref\n pos = pos || node.position();\n var cyStyle = node.cy().style();\n var x = pos.x;\n var y = pos.y;\n var nodeW = node.width();\n var nodeH = node.height();\n var lastPercent = 0; // what % to continue drawing pie slices from on [0, 1]\n var usePaths = this.usePaths();\n context.save();\n var direction = node.pstyle('stripe-direction').value;\n var stripeSize = node.pstyle('stripe-size');\n switch (direction) {\n case 'vertical':\n break;\n // default\n case 'righward':\n context.rotate(-Math.PI / 2);\n break;\n }\n var stripeW = nodeW;\n var stripeH = nodeH;\n if (stripeSize.units === '%') {\n stripeW = stripeW * stripeSize.pfValue;\n stripeH = stripeH * stripeSize.pfValue;\n } else if (stripeSize.pfValue !== undefined) {\n stripeW = stripeSize.pfValue;\n stripeH = stripeSize.pfValue;\n }\n if (usePaths) {\n x = 0;\n y = 0;\n }\n\n // shift up from the centre of the node to the top-left corner\n y -= stripeW / 2;\n x -= stripeH / 2;\n for (var i = 1; i <= cyStyle.stripeBackgroundN; i++) {\n // 1..N\n var size = node.pstyle('stripe-' + i + '-background-size').value;\n var color = node.pstyle('stripe-' + i + '-background-color').value;\n var opacity = node.pstyle('stripe-' + i + '-background-opacity').value * nodeOpacity;\n var percent = size / 100; // map integer range [0, 100] to [0, 1]\n\n // percent can't push beyond 1\n if (percent + lastPercent > 1) {\n percent = 1 - lastPercent;\n }\n\n // ignore if\n // - zero size\n // - we're already beyond the full chart\n // - adding the current slice would go beyond the full chart\n if (size === 0 || lastPercent >= 1 || lastPercent + percent > 1) {\n continue;\n }\n\n // draw rect for the current stripe\n context.beginPath();\n context.rect(x, y + stripeH * lastPercent, stripeW, stripeH * percent);\n context.closePath();\n this.colorFillStyle(context, color[0], color[1], color[2], opacity);\n context.fill();\n lastPercent += percent;\n }\n context.restore();\n};\n\nvar CRp$5 = {};\nvar motionBlurDelay = 100;\n\n// var isFirefox = typeof InstallTrigger !== 'undefined';\n\nCRp$5.getPixelRatio = function () {\n var context = this.data.contexts[0];\n if (this.forcedPixelRatio != null) {\n return this.forcedPixelRatio;\n }\n var containerWindow = this.cy.window();\n var backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;\n return (containerWindow.devicePixelRatio || 1) / backingStore; // eslint-disable-line no-undef\n};\nCRp$5.paintCache = function (context) {\n var caches = this.paintCaches = this.paintCaches || [];\n var needToCreateCache = true;\n var cache;\n for (var i = 0; i < caches.length; i++) {\n cache = caches[i];\n if (cache.context === context) {\n needToCreateCache = false;\n break;\n }\n }\n if (needToCreateCache) {\n cache = {\n context: context\n };\n caches.push(cache);\n }\n return cache;\n};\nCRp$5.createGradientStyleFor = function (context, shapeStyleName, ele, fill, opacity) {\n var gradientStyle;\n var usePaths = this.usePaths();\n var colors = ele.pstyle(shapeStyleName + '-gradient-stop-colors').value,\n positions = ele.pstyle(shapeStyleName + '-gradient-stop-positions').pfValue;\n if (fill === 'radial-gradient') {\n if (ele.isEdge()) {\n var start = ele.sourceEndpoint(),\n end = ele.targetEndpoint(),\n mid = ele.midpoint();\n var d1 = dist(start, mid);\n var d2 = dist(end, mid);\n gradientStyle = context.createRadialGradient(mid.x, mid.y, 0, mid.x, mid.y, Math.max(d1, d2));\n } else {\n var pos = usePaths ? {\n x: 0,\n y: 0\n } : ele.position(),\n width = ele.paddedWidth(),\n height = ele.paddedHeight();\n gradientStyle = context.createRadialGradient(pos.x, pos.y, 0, pos.x, pos.y, Math.max(width, height));\n }\n } else {\n if (ele.isEdge()) {\n var _start = ele.sourceEndpoint(),\n _end = ele.targetEndpoint();\n gradientStyle = context.createLinearGradient(_start.x, _start.y, _end.x, _end.y);\n } else {\n var _pos = usePaths ? {\n x: 0,\n y: 0\n } : ele.position(),\n _width = ele.paddedWidth(),\n _height = ele.paddedHeight(),\n halfWidth = _width / 2,\n halfHeight = _height / 2;\n var direction = ele.pstyle('background-gradient-direction').value;\n switch (direction) {\n case 'to-bottom':\n gradientStyle = context.createLinearGradient(_pos.x, _pos.y - halfHeight, _pos.x, _pos.y + halfHeight);\n break;\n case 'to-top':\n gradientStyle = context.createLinearGradient(_pos.x, _pos.y + halfHeight, _pos.x, _pos.y - halfHeight);\n break;\n case 'to-left':\n gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y, _pos.x - halfWidth, _pos.y);\n break;\n case 'to-right':\n gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y, _pos.x + halfWidth, _pos.y);\n break;\n case 'to-bottom-right':\n case 'to-right-bottom':\n gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y - halfHeight, _pos.x + halfWidth, _pos.y + halfHeight);\n break;\n case 'to-top-right':\n case 'to-right-top':\n gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y + halfHeight, _pos.x + halfWidth, _pos.y - halfHeight);\n break;\n case 'to-bottom-left':\n case 'to-left-bottom':\n gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y - halfHeight, _pos.x - halfWidth, _pos.y + halfHeight);\n break;\n case 'to-top-left':\n case 'to-left-top':\n gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y + halfHeight, _pos.x - halfWidth, _pos.y - halfHeight);\n break;\n }\n }\n }\n if (!gradientStyle) return null; // invalid gradient style\n\n var hasPositions = positions.length === colors.length;\n var length = colors.length;\n for (var i = 0; i < length; i++) {\n gradientStyle.addColorStop(hasPositions ? positions[i] : i / (length - 1), 'rgba(' + colors[i][0] + ',' + colors[i][1] + ',' + colors[i][2] + ',' + opacity + ')');\n }\n return gradientStyle;\n};\nCRp$5.gradientFillStyle = function (context, ele, fill, opacity) {\n var gradientStyle = this.createGradientStyleFor(context, 'background', ele, fill, opacity);\n if (!gradientStyle) return null; // error\n context.fillStyle = gradientStyle;\n};\nCRp$5.colorFillStyle = function (context, r, g, b, a) {\n context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';\n // turn off for now, seems context does its own caching\n\n // var cache = this.paintCache(context);\n\n // var fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';\n\n // if( cache.fillStyle !== fillStyle ){\n // context.fillStyle = cache.fillStyle = fillStyle;\n // }\n};\nCRp$5.eleFillStyle = function (context, ele, opacity) {\n var backgroundFill = ele.pstyle('background-fill').value;\n if (backgroundFill === 'linear-gradient' || backgroundFill === 'radial-gradient') {\n this.gradientFillStyle(context, ele, backgroundFill, opacity);\n } else {\n var backgroundColor = ele.pstyle('background-color').value;\n this.colorFillStyle(context, backgroundColor[0], backgroundColor[1], backgroundColor[2], opacity);\n }\n};\nCRp$5.gradientStrokeStyle = function (context, ele, fill, opacity) {\n var gradientStyle = this.createGradientStyleFor(context, 'line', ele, fill, opacity);\n if (!gradientStyle) return null; // error\n context.strokeStyle = gradientStyle;\n};\nCRp$5.colorStrokeStyle = function (context, r, g, b, a) {\n context.strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';\n // turn off for now, seems context does its own caching\n\n // var cache = this.paintCache(context);\n\n // var strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';\n\n // if( cache.strokeStyle !== strokeStyle ){\n // context.strokeStyle = cache.strokeStyle = strokeStyle;\n // }\n};\nCRp$5.eleStrokeStyle = function (context, ele, opacity) {\n var lineFill = ele.pstyle('line-fill').value;\n if (lineFill === 'linear-gradient' || lineFill === 'radial-gradient') {\n this.gradientStrokeStyle(context, ele, lineFill, opacity);\n } else {\n var lineColor = ele.pstyle('line-color').value;\n this.colorStrokeStyle(context, lineColor[0], lineColor[1], lineColor[2], opacity);\n }\n};\n\n// Resize canvas\nCRp$5.matchCanvasSize = function (container) {\n var r = this;\n var data = r.data;\n var bb = r.findContainerClientCoords();\n var width = bb[2];\n var height = bb[3];\n var pixelRatio = r.getPixelRatio();\n var mbPxRatio = r.motionBlurPxRatio;\n if (container === r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_NODE] || container === r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_DRAG]) {\n pixelRatio = mbPxRatio;\n }\n var canvasWidth = width * pixelRatio;\n var canvasHeight = height * pixelRatio;\n var canvas;\n if (canvasWidth === r.canvasWidth && canvasHeight === r.canvasHeight) {\n return; // save cycles if same\n }\n r.fontCaches = null; // resizing resets the style\n\n var canvasContainer = data.canvasContainer;\n canvasContainer.style.width = width + 'px';\n canvasContainer.style.height = height + 'px';\n for (var i = 0; i < r.CANVAS_LAYERS; i++) {\n canvas = data.canvases[i];\n canvas.width = canvasWidth;\n canvas.height = canvasHeight;\n canvas.style.width = width + 'px';\n canvas.style.height = height + 'px';\n }\n for (var i = 0; i < r.BUFFER_COUNT; i++) {\n canvas = data.bufferCanvases[i];\n canvas.width = canvasWidth;\n canvas.height = canvasHeight;\n canvas.style.width = width + 'px';\n canvas.style.height = height + 'px';\n }\n r.textureMult = 1;\n if (pixelRatio <= 1) {\n canvas = data.bufferCanvases[r.TEXTURE_BUFFER];\n r.textureMult = 2;\n canvas.width = canvasWidth * r.textureMult;\n canvas.height = canvasHeight * r.textureMult;\n }\n r.canvasWidth = canvasWidth;\n r.canvasHeight = canvasHeight;\n r.pixelRatio = pixelRatio;\n};\nCRp$5.renderTo = function (cxt, zoom, pan, pxRatio) {\n this.render({\n forcedContext: cxt,\n forcedZoom: zoom,\n forcedPan: pan,\n drawAllLayers: true,\n forcedPxRatio: pxRatio\n });\n};\nCRp$5.clearCanvas = function () {\n var r = this;\n var data = r.data;\n function clear(context) {\n context.clearRect(0, 0, r.canvasWidth, r.canvasHeight);\n }\n clear(data.contexts[r.NODE]);\n clear(data.contexts[r.DRAG]);\n};\nCRp$5.render = function (options) {\n var r = this;\n options = options || staticEmptyObject();\n var cy = r.cy;\n var forcedContext = options.forcedContext;\n var drawAllLayers = options.drawAllLayers;\n var drawOnlyNodeLayer = options.drawOnlyNodeLayer;\n var forcedZoom = options.forcedZoom;\n var forcedPan = options.forcedPan;\n var pixelRatio = options.forcedPxRatio === undefined ? this.getPixelRatio() : options.forcedPxRatio;\n var data = r.data;\n var needDraw = data.canvasNeedsRedraw;\n var textureDraw = r.textureOnViewport && !forcedContext && (r.pinching || r.hoverData.dragging || r.swipePanning || r.data.wheelZooming);\n var motionBlur = options.motionBlur !== undefined ? options.motionBlur : r.motionBlur;\n var mbPxRatio = r.motionBlurPxRatio;\n var hasCompoundNodes = cy.hasCompoundNodes();\n var inNodeDragGesture = r.hoverData.draggingEles;\n var inBoxSelection = r.hoverData.selecting || r.touchData.selecting ? true : false;\n motionBlur = motionBlur && !forcedContext && r.motionBlurEnabled && !inBoxSelection;\n var motionBlurFadeEffect = motionBlur;\n if (!forcedContext) {\n if (r.prevPxRatio !== pixelRatio) {\n r.invalidateContainerClientCoordsCache();\n r.matchCanvasSize(r.container);\n r.redrawHint('eles', true);\n r.redrawHint('drag', true);\n }\n r.prevPxRatio = pixelRatio;\n }\n if (!forcedContext && r.motionBlurTimeout) {\n clearTimeout(r.motionBlurTimeout);\n }\n if (motionBlur) {\n if (r.mbFrames == null) {\n r.mbFrames = 0;\n }\n r.mbFrames++;\n if (r.mbFrames < 3) {\n // need several frames before even high quality motionblur\n motionBlurFadeEffect = false;\n }\n\n // go to lower quality blurry frames when several m/b frames have been rendered (avoids flashing)\n if (r.mbFrames > r.minMbLowQualFrames) {\n //r.fullQualityMb = false;\n r.motionBlurPxRatio = r.mbPxRBlurry;\n }\n }\n if (r.clearingMotionBlur) {\n r.motionBlurPxRatio = 1;\n }\n\n // b/c drawToContext() may be async w.r.t. redraw(), keep track of last texture frame\n // because a rogue async texture frame would clear needDraw\n if (r.textureDrawLastFrame && !textureDraw) {\n needDraw[r.NODE] = true;\n needDraw[r.SELECT_BOX] = true;\n }\n var style = cy.style();\n var zoom = cy.zoom();\n var effectiveZoom = forcedZoom !== undefined ? forcedZoom : zoom;\n var pan = cy.pan();\n var effectivePan = {\n x: pan.x,\n y: pan.y\n };\n var vp = {\n zoom: zoom,\n pan: {\n x: pan.x,\n y: pan.y\n }\n };\n var prevVp = r.prevViewport;\n var viewportIsDiff = prevVp === undefined || vp.zoom !== prevVp.zoom || vp.pan.x !== prevVp.pan.x || vp.pan.y !== prevVp.pan.y;\n\n // we want the low quality motionblur only when the viewport is being manipulated etc (where it's not noticed)\n if (!viewportIsDiff && !(inNodeDragGesture && !hasCompoundNodes)) {\n r.motionBlurPxRatio = 1;\n }\n if (forcedPan) {\n effectivePan = forcedPan;\n }\n\n // apply pixel ratio\n\n effectiveZoom *= pixelRatio;\n effectivePan.x *= pixelRatio;\n effectivePan.y *= pixelRatio;\n var eles = r.getCachedZSortedEles();\n function mbclear(context, x, y, w, h) {\n var gco = context.globalCompositeOperation;\n context.globalCompositeOperation = 'destination-out';\n r.colorFillStyle(context, 255, 255, 255, r.motionBlurTransparency);\n context.fillRect(x, y, w, h);\n context.globalCompositeOperation = gco;\n }\n function setContextTransform(context, clear) {\n var ePan, eZoom, w, h;\n if (!r.clearingMotionBlur && (context === data.bufferContexts[r.MOTIONBLUR_BUFFER_NODE] || context === data.bufferContexts[r.MOTIONBLUR_BUFFER_DRAG])) {\n ePan = {\n x: pan.x * mbPxRatio,\n y: pan.y * mbPxRatio\n };\n eZoom = zoom * mbPxRatio;\n w = r.canvasWidth * mbPxRatio;\n h = r.canvasHeight * mbPxRatio;\n } else {\n ePan = effectivePan;\n eZoom = effectiveZoom;\n w = r.canvasWidth;\n h = r.canvasHeight;\n }\n context.setTransform(1, 0, 0, 1, 0, 0);\n if (clear === 'motionBlur') {\n mbclear(context, 0, 0, w, h);\n } else if (!forcedContext && (clear === undefined || clear)) {\n context.clearRect(0, 0, w, h);\n }\n if (!drawAllLayers) {\n context.translate(ePan.x, ePan.y);\n context.scale(eZoom, eZoom);\n }\n if (forcedPan) {\n context.translate(forcedPan.x, forcedPan.y);\n }\n if (forcedZoom) {\n context.scale(forcedZoom, forcedZoom);\n }\n }\n if (!textureDraw) {\n r.textureDrawLastFrame = false;\n }\n if (textureDraw) {\n r.textureDrawLastFrame = true;\n if (!r.textureCache) {\n r.textureCache = {};\n r.textureCache.bb = cy.mutableElements().boundingBox();\n r.textureCache.texture = r.data.bufferCanvases[r.TEXTURE_BUFFER];\n var cxt = r.data.bufferContexts[r.TEXTURE_BUFFER];\n cxt.setTransform(1, 0, 0, 1, 0, 0);\n cxt.clearRect(0, 0, r.canvasWidth * r.textureMult, r.canvasHeight * r.textureMult);\n r.render({\n forcedContext: cxt,\n drawOnlyNodeLayer: true,\n forcedPxRatio: pixelRatio * r.textureMult\n });\n var vp = r.textureCache.viewport = {\n zoom: cy.zoom(),\n pan: cy.pan(),\n width: r.canvasWidth,\n height: r.canvasHeight\n };\n vp.mpan = {\n x: (0 - vp.pan.x) / vp.zoom,\n y: (0 - vp.pan.y) / vp.zoom\n };\n }\n needDraw[r.DRAG] = false;\n needDraw[r.NODE] = false;\n var context = data.contexts[r.NODE];\n var texture = r.textureCache.texture;\n var vp = r.textureCache.viewport;\n context.setTransform(1, 0, 0, 1, 0, 0);\n if (motionBlur) {\n mbclear(context, 0, 0, vp.width, vp.height);\n } else {\n context.clearRect(0, 0, vp.width, vp.height);\n }\n var outsideBgColor = style.core('outside-texture-bg-color').value;\n var outsideBgOpacity = style.core('outside-texture-bg-opacity').value;\n r.colorFillStyle(context, outsideBgColor[0], outsideBgColor[1], outsideBgColor[2], outsideBgOpacity);\n context.fillRect(0, 0, vp.width, vp.height);\n var zoom = cy.zoom();\n setContextTransform(context, false);\n context.clearRect(vp.mpan.x, vp.mpan.y, vp.width / vp.zoom / pixelRatio, vp.height / vp.zoom / pixelRatio);\n context.drawImage(texture, vp.mpan.x, vp.mpan.y, vp.width / vp.zoom / pixelRatio, vp.height / vp.zoom / pixelRatio);\n } else if (r.textureOnViewport && !forcedContext) {\n // clear the cache since we don't need it\n r.textureCache = null;\n }\n var extent = cy.extent();\n var vpManip = r.pinching || r.hoverData.dragging || r.swipePanning || r.data.wheelZooming || r.hoverData.draggingEles || r.cy.animated();\n var hideEdges = r.hideEdgesOnViewport && vpManip;\n var needMbClear = [];\n needMbClear[r.NODE] = !needDraw[r.NODE] && motionBlur && !r.clearedForMotionBlur[r.NODE] || r.clearingMotionBlur;\n if (needMbClear[r.NODE]) {\n r.clearedForMotionBlur[r.NODE] = true;\n }\n needMbClear[r.DRAG] = !needDraw[r.DRAG] && motionBlur && !r.clearedForMotionBlur[r.DRAG] || r.clearingMotionBlur;\n if (needMbClear[r.DRAG]) {\n r.clearedForMotionBlur[r.DRAG] = true;\n }\n if (needDraw[r.NODE] || drawAllLayers || drawOnlyNodeLayer || needMbClear[r.NODE]) {\n var useBuffer = motionBlur && !needMbClear[r.NODE] && mbPxRatio !== 1;\n var context = forcedContext || (useBuffer ? r.data.bufferContexts[r.MOTIONBLUR_BUFFER_NODE] : data.contexts[r.NODE]);\n var clear = motionBlur && !useBuffer ? 'motionBlur' : undefined;\n setContextTransform(context, clear);\n if (hideEdges) {\n r.drawCachedNodes(context, eles.nondrag, pixelRatio, extent);\n } else {\n r.drawLayeredElements(context, eles.nondrag, pixelRatio, extent);\n }\n if (r.debug) {\n r.drawDebugPoints(context, eles.nondrag);\n }\n if (!drawAllLayers && !motionBlur) {\n needDraw[r.NODE] = false;\n }\n }\n if (!drawOnlyNodeLayer && (needDraw[r.DRAG] || drawAllLayers || needMbClear[r.DRAG])) {\n var useBuffer = motionBlur && !needMbClear[r.DRAG] && mbPxRatio !== 1;\n var context = forcedContext || (useBuffer ? r.data.bufferContexts[r.MOTIONBLUR_BUFFER_DRAG] : data.contexts[r.DRAG]);\n setContextTransform(context, motionBlur && !useBuffer ? 'motionBlur' : undefined);\n if (hideEdges) {\n r.drawCachedNodes(context, eles.drag, pixelRatio, extent);\n } else {\n r.drawCachedElements(context, eles.drag, pixelRatio, extent);\n }\n if (r.debug) {\n r.drawDebugPoints(context, eles.drag);\n }\n if (!drawAllLayers && !motionBlur) {\n needDraw[r.DRAG] = false;\n }\n }\n this.drawSelectionRectangle(options, setContextTransform);\n\n // motionblur: blit rendered blurry frames\n if (motionBlur && mbPxRatio !== 1) {\n var cxtNode = data.contexts[r.NODE];\n var txtNode = r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_NODE];\n var cxtDrag = data.contexts[r.DRAG];\n var txtDrag = r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_DRAG];\n var drawMotionBlur = function drawMotionBlur(cxt, txt, needClear) {\n cxt.setTransform(1, 0, 0, 1, 0, 0);\n if (needClear || !motionBlurFadeEffect) {\n cxt.clearRect(0, 0, r.canvasWidth, r.canvasHeight);\n } else {\n mbclear(cxt, 0, 0, r.canvasWidth, r.canvasHeight);\n }\n var pxr = mbPxRatio;\n cxt.drawImage(txt,\n // img\n 0, 0,\n // sx, sy\n r.canvasWidth * pxr, r.canvasHeight * pxr,\n // sw, sh\n 0, 0,\n // x, y\n r.canvasWidth, r.canvasHeight // w, h\n );\n };\n if (needDraw[r.NODE] || needMbClear[r.NODE]) {\n drawMotionBlur(cxtNode, txtNode, needMbClear[r.NODE]);\n needDraw[r.NODE] = false;\n }\n if (needDraw[r.DRAG] || needMbClear[r.DRAG]) {\n drawMotionBlur(cxtDrag, txtDrag, needMbClear[r.DRAG]);\n needDraw[r.DRAG] = false;\n }\n }\n r.prevViewport = vp;\n if (r.clearingMotionBlur) {\n r.clearingMotionBlur = false;\n r.motionBlurCleared = true;\n r.motionBlur = true;\n }\n if (motionBlur) {\n r.motionBlurTimeout = setTimeout(function () {\n r.motionBlurTimeout = null;\n r.clearedForMotionBlur[r.NODE] = false;\n r.clearedForMotionBlur[r.DRAG] = false;\n r.motionBlur = false;\n r.clearingMotionBlur = !textureDraw;\n r.mbFrames = 0;\n needDraw[r.NODE] = true;\n needDraw[r.DRAG] = true;\n r.redraw();\n }, motionBlurDelay);\n }\n if (!forcedContext) {\n cy.emit('render');\n }\n};\nvar fpsHeight;\nCRp$5.drawSelectionRectangle = function (options, setContextTransform) {\n var r = this;\n var cy = r.cy;\n var data = r.data;\n var style = cy.style();\n var drawOnlyNodeLayer = options.drawOnlyNodeLayer;\n var drawAllLayers = options.drawAllLayers;\n var needDraw = data.canvasNeedsRedraw;\n var forcedContext = options.forcedContext;\n if (r.showFps || !drawOnlyNodeLayer && needDraw[r.SELECT_BOX] && !drawAllLayers) {\n var context = forcedContext || data.contexts[r.SELECT_BOX];\n setContextTransform(context);\n if (r.selection[4] == 1 && (r.hoverData.selecting || r.touchData.selecting)) {\n var zoom = r.cy.zoom();\n var borderWidth = style.core('selection-box-border-width').value / zoom;\n context.lineWidth = borderWidth;\n context.fillStyle = 'rgba(' + style.core('selection-box-color').value[0] + ',' + style.core('selection-box-color').value[1] + ',' + style.core('selection-box-color').value[2] + ',' + style.core('selection-box-opacity').value + ')';\n context.fillRect(r.selection[0], r.selection[1], r.selection[2] - r.selection[0], r.selection[3] - r.selection[1]);\n if (borderWidth > 0) {\n context.strokeStyle = 'rgba(' + style.core('selection-box-border-color').value[0] + ',' + style.core('selection-box-border-color').value[1] + ',' + style.core('selection-box-border-color').value[2] + ',' + style.core('selection-box-opacity').value + ')';\n context.strokeRect(r.selection[0], r.selection[1], r.selection[2] - r.selection[0], r.selection[3] - r.selection[1]);\n }\n }\n if (data.bgActivePosistion && !r.hoverData.selecting) {\n var zoom = r.cy.zoom();\n var pos = data.bgActivePosistion;\n context.fillStyle = 'rgba(' + style.core('active-bg-color').value[0] + ',' + style.core('active-bg-color').value[1] + ',' + style.core('active-bg-color').value[2] + ',' + style.core('active-bg-opacity').value + ')';\n context.beginPath();\n context.arc(pos.x, pos.y, style.core('active-bg-size').pfValue / zoom, 0, 2 * Math.PI);\n context.fill();\n }\n var timeToRender = r.lastRedrawTime;\n if (r.showFps && timeToRender) {\n timeToRender = Math.round(timeToRender);\n var fps = Math.round(1000 / timeToRender);\n var text = '1 frame = ' + timeToRender + ' ms = ' + fps + ' fps';\n context.setTransform(1, 0, 0, 1, 0, 0);\n context.fillStyle = 'rgba(255, 0, 0, 0.75)';\n context.strokeStyle = 'rgba(255, 0, 0, 0.75)';\n // context.lineWidth = 1;\n context.font = '30px Arial';\n if (!fpsHeight) {\n var dims = context.measureText(text);\n fpsHeight = dims.actualBoundingBoxAscent;\n }\n context.fillText(text, 0, fpsHeight);\n var maxFps = 60;\n context.strokeRect(0, fpsHeight + 10, 250, 20);\n context.fillRect(0, fpsHeight + 10, 250 * Math.min(fps / maxFps, 1), 20);\n }\n if (!drawAllLayers) {\n needDraw[r.SELECT_BOX] = false;\n }\n }\n};\n\n/**\n * Notes:\n * - All colors have premultiplied alpha. Very important for textues and \n * blending to work correctly.\n */\n\nfunction compileShader(gl, type, source) {\n var shader = gl.createShader(type);\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n throw new Error(gl.getShaderInfoLog(shader));\n }\n // console.log(gl.getShaderInfoLog(shader));\n return shader;\n}\nfunction createProgram(gl, vertexSource, fragementSource) {\n var vertexShader = compileShader(gl, gl.VERTEX_SHADER, vertexSource);\n var fragmentShader = compileShader(gl, gl.FRAGMENT_SHADER, fragementSource);\n var program = gl.createProgram();\n gl.attachShader(program, vertexShader);\n gl.attachShader(program, fragmentShader);\n gl.linkProgram(program);\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n throw new Error('Could not initialize shaders');\n }\n return program;\n}\n\n/**\n * Creates an offscren canvas with a 2D context, for the\n * canvas renderer to use for drawing textures.\n */\nfunction createTextureCanvas(r, width, height) {\n if (height === undefined) {\n height = width;\n }\n var canvas = r.makeOffscreenCanvas(width, height);\n var ctx = canvas.context = canvas.getContext('2d');\n canvas.clear = function () {\n return ctx.clearRect(0, 0, canvas.width, canvas.height);\n };\n canvas.clear();\n return canvas;\n}\n\n/**\n * Returns the current pan & zoom values, scaled by the pixel ratio.\n */\nfunction getEffectivePanZoom(r) {\n var pixelRatio = r.pixelRatio;\n var zoom = r.cy.zoom();\n var pan = r.cy.pan();\n return {\n zoom: zoom * pixelRatio,\n pan: {\n x: pan.x * pixelRatio,\n y: pan.y * pixelRatio\n }\n };\n}\n\n/**\n * Returns the zoom value, scaled by the pixel ratio.\n */\nfunction getEffectiveZoom(r) {\n var pixelRatio = r.pixelRatio;\n var zoom = r.cy.zoom();\n return zoom * pixelRatio;\n}\nfunction modelToRenderedPosition(r, pan, zoom, x, y) {\n var rx = x * zoom + pan.x;\n var ry = y * zoom + pan.y;\n ry = Math.round(r.canvasHeight - ry); // adjust for webgl\n return [rx, ry];\n}\nfunction isSimpleShape(node) {\n // the actual shape is checked in ElementDrawingWebGL._getVertTypeForShape()\n // no need to check it twice, this just checks other visual properties\n if (node.pstyle('background-fill').value !== 'solid') return false;\n if (node.pstyle('background-image').strValue !== 'none') return false;\n if (node.pstyle('border-width').value === 0) return true;\n if (node.pstyle('border-opacity').value === 0) return true;\n // we have a border but it must be simple\n if (node.pstyle('border-style').value !== 'solid') return false;\n // TODO ignoring 'border-cap', 'border-join' and 'border-position' for now\n return true;\n}\nfunction arrayEqual(a1, a2) {\n if (a1.length !== a2.length) {\n return false;\n }\n for (var i = 0; i < a1.length; i++) {\n if (a1[i] !== a2[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Takes color & opacity style values and converts them to WebGL format. \n * Alpha is premultiplied.\n */\nfunction toWebGLColor(color, opacity, outArray) {\n var r = color[0] / 255;\n var g = color[1] / 255;\n var b = color[2] / 255;\n var a = opacity;\n var arr = outArray || new Array(4);\n arr[0] = r * a;\n arr[1] = g * a;\n arr[2] = b * a;\n arr[3] = a;\n return arr;\n}\nfunction indexToVec4(index, outArray) {\n var arr = outArray || new Array(4);\n arr[0] = (index >> 0 & 0xFF) / 0xFF;\n arr[1] = (index >> 8 & 0xFF) / 0xFF;\n arr[2] = (index >> 16 & 0xFF) / 0xFF;\n arr[3] = (index >> 24 & 0xFF) / 0xFF;\n return arr;\n}\nfunction vec4ToIndex(vec4) {\n return vec4[0] + (vec4[1] << 8) + (vec4[2] << 16) + (vec4[3] << 24);\n}\nfunction createTexture(gl, debugID) {\n var texture = gl.createTexture();\n texture.buffer = function (offscreenCanvas) {\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);\n\n // very important, this tells webgl to premultiply colors by the alpha channel\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, offscreenCanvas);\n gl.generateMipmap(gl.TEXTURE_2D);\n gl.bindTexture(gl.TEXTURE_2D, null);\n };\n texture.deleteTexture = function () {\n gl.deleteTexture(texture);\n };\n return texture;\n}\nfunction getTypeInfo(gl, glslType) {\n switch (glslType) {\n case 'float':\n return [1, gl.FLOAT, 4];\n case 'vec2':\n return [2, gl.FLOAT, 4];\n case 'vec3':\n return [3, gl.FLOAT, 4];\n case 'vec4':\n return [4, gl.FLOAT, 4];\n case 'int':\n return [1, gl.INT, 4];\n case 'ivec2':\n return [2, gl.INT, 4];\n }\n}\nfunction createTypedArray(gl, glType, dataOrSize) {\n switch (glType) {\n case gl.FLOAT:\n return new Float32Array(dataOrSize);\n case gl.INT:\n return new Int32Array(dataOrSize);\n }\n}\nfunction createTypedArrayView(gl, glType, array, stride, size, i) {\n switch (glType) {\n case gl.FLOAT:\n return new Float32Array(array.buffer, i * stride, size);\n case gl.INT:\n return new Int32Array(array.buffer, i * stride, size);\n }\n}\n\n/** @param {WebGLRenderingContext} gl */\nfunction createBufferStaticDraw(gl, type, attributeLoc, dataArray) {\n var _getTypeInfo = getTypeInfo(gl, type),\n _getTypeInfo2 = _slicedToArray(_getTypeInfo, 2),\n size = _getTypeInfo2[0],\n glType = _getTypeInfo2[1];\n var data = createTypedArray(gl, glType, dataArray);\n var buffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);\n if (glType === gl.FLOAT) {\n gl.vertexAttribPointer(attributeLoc, size, glType, false, 0, 0);\n } else if (glType === gl.INT) {\n gl.vertexAttribIPointer(attributeLoc, size, glType, 0, 0);\n }\n gl.enableVertexAttribArray(attributeLoc);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n return buffer;\n}\n\n/** \n * Creates a float buffer with gl.DYNAMIC_DRAW.\n * The returned buffer object contains functions to easily set instance data and buffer the data before a draw call.\n * @param {WebGLRenderingContext} gl \n */\nfunction createBufferDynamicDraw(gl, instances, type, attributeLoc) {\n var _getTypeInfo3 = getTypeInfo(gl, type),\n _getTypeInfo4 = _slicedToArray(_getTypeInfo3, 3),\n size = _getTypeInfo4[0],\n glType = _getTypeInfo4[1],\n bytes = _getTypeInfo4[2];\n var dataArray = createTypedArray(gl, glType, instances * size);\n var stride = size * bytes;\n var buffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n gl.bufferData(gl.ARRAY_BUFFER, instances * stride, gl.DYNAMIC_DRAW);\n gl.enableVertexAttribArray(attributeLoc);\n if (glType === gl.FLOAT) {\n gl.vertexAttribPointer(attributeLoc, size, glType, false, stride, 0);\n } else if (glType === gl.INT) {\n gl.vertexAttribIPointer(attributeLoc, size, glType, stride, 0);\n }\n gl.vertexAttribDivisor(attributeLoc, 1);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n\n // use array views to set values directly into the buffer array\n var views = new Array(instances);\n for (var i = 0; i < instances; i++) {\n views[i] = createTypedArrayView(gl, glType, dataArray, stride, size, i);\n }\n buffer.dataArray = dataArray;\n buffer.stride = stride;\n buffer.size = size;\n buffer.getView = function (i) {\n return views[i];\n };\n buffer.setPoint = function (i, x, y) {\n var view = views[i];\n view[0] = x;\n view[1] = y;\n };\n buffer.bufferSubData = function (count) {\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n if (count) {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataArray, 0, count * size);\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataArray);\n }\n };\n return buffer;\n}\n\n/** \n * Creates a buffer of 3x3 matrix data for use as attribute data.\n * @param {WebGLRenderingContext} gl \n */\nfunction create3x3MatrixBufferDynamicDraw(gl, instances, attributeLoc) {\n var matrixSize = 9; // 3x3 matrix\n var matrixData = new Float32Array(instances * matrixSize);\n\n // use matrix views to set values directly into the matrixData array\n var matrixViews = new Array(instances);\n for (var i = 0; i < instances; i++) {\n var byteOffset = i * matrixSize * 4; // 4 bytes per float\n matrixViews[i] = new Float32Array(matrixData.buffer, byteOffset, matrixSize); // array view\n }\n var buffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n gl.bufferData(gl.ARRAY_BUFFER, matrixData.byteLength, gl.DYNAMIC_DRAW);\n\n // each row of the matrix needs to be a separate attribute\n for (var _i = 0; _i < 3; _i++) {\n var loc = attributeLoc + _i;\n gl.enableVertexAttribArray(loc);\n gl.vertexAttribPointer(loc, 3, gl.FLOAT, false, 3 * 12, _i * 12);\n gl.vertexAttribDivisor(loc, 1);\n }\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n buffer.getMatrixView = function (i) {\n return matrixViews[i];\n };\n\n // TODO this is too slow, use getMatrixView and pass the view directly to the glmatrix library\n buffer.setData = function (matrix, i) {\n matrixViews[i].set(matrix, 0);\n };\n buffer.bufferSubData = function () {\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, matrixData);\n };\n return buffer;\n}\n\n/** \n * Creates a Frame Buffer to use for offscreen rendering.\n * @param {WebGLRenderingContext} gl \n */\nfunction createPickingFrameBuffer(gl) {\n // Create and bind the framebuffer\n var fb = gl.createFramebuffer();\n gl.bindFramebuffer(gl.FRAMEBUFFER, fb);\n\n // Create a texture to render to\n var targetTexture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, targetTexture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n\n // attach the texture as the first color attachment\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, targetTexture, 0);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n fb.setFramebufferAttachmentSizes = function (width, height) {\n gl.bindTexture(gl.TEXTURE_2D, targetTexture);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n };\n return fb;\n}\n\n/**\n * Common utilities\n * @module glMatrix\n */\n// Configuration Constants\nvar ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;\nif (!Math.hypot) Math.hypot = function () {\n var y = 0,\n i = arguments.length;\n\n while (i--) {\n y += arguments[i] * arguments[i];\n }\n\n return Math.sqrt(y);\n};\n\n/**\n * 3x3 Matrix\n * @module mat3\n */\n\n/**\n * Creates a new identity mat3\n *\n * @returns {mat3} a new 3x3 matrix\n */\n\nfunction create() {\n var out = new ARRAY_TYPE(9);\n\n if (ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n }\n\n out[0] = 1;\n out[4] = 1;\n out[8] = 1;\n return out;\n}\n/**\n * Set a mat3 to the identity matrix\n *\n * @param {mat3} out the receiving matrix\n * @returns {mat3} out\n */\n\nfunction identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 1;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\n * Multiplies two mat3's\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\n\nfunction multiply(out, a, b) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n var b00 = b[0],\n b01 = b[1],\n b02 = b[2];\n var b10 = b[3],\n b11 = b[4],\n b12 = b[5];\n var b20 = b[6],\n b21 = b[7],\n b22 = b[8];\n out[0] = b00 * a00 + b01 * a10 + b02 * a20;\n out[1] = b00 * a01 + b01 * a11 + b02 * a21;\n out[2] = b00 * a02 + b01 * a12 + b02 * a22;\n out[3] = b10 * a00 + b11 * a10 + b12 * a20;\n out[4] = b10 * a01 + b11 * a11 + b12 * a21;\n out[5] = b10 * a02 + b11 * a12 + b12 * a22;\n out[6] = b20 * a00 + b21 * a10 + b22 * a20;\n out[7] = b20 * a01 + b21 * a11 + b22 * a21;\n out[8] = b20 * a02 + b21 * a12 + b22 * a22;\n return out;\n}\n/**\n * Translate a mat3 by the given vector\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to translate\n * @param {ReadonlyVec2} v vector to translate by\n * @returns {mat3} out\n */\n\nfunction translate(out, a, v) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n x = v[0],\n y = v[1];\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a10;\n out[4] = a11;\n out[5] = a12;\n out[6] = x * a00 + y * a10 + a20;\n out[7] = x * a01 + y * a11 + a21;\n out[8] = x * a02 + y * a12 + a22;\n return out;\n}\n/**\n * Rotates a mat3 by the given angle\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat3} out\n */\n\nfunction rotate(out, a, rad) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n s = Math.sin(rad),\n c = Math.cos(rad);\n out[0] = c * a00 + s * a10;\n out[1] = c * a01 + s * a11;\n out[2] = c * a02 + s * a12;\n out[3] = c * a10 - s * a00;\n out[4] = c * a11 - s * a01;\n out[5] = c * a12 - s * a02;\n out[6] = a20;\n out[7] = a21;\n out[8] = a22;\n return out;\n}\n/**\n * Scales the mat3 by the dimensions in the given vec2\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to rotate\n * @param {ReadonlyVec2} v the vec2 to scale the matrix by\n * @returns {mat3} out\n **/\n\nfunction scale(out, a, v) {\n var x = v[0],\n y = v[1];\n out[0] = x * a[0];\n out[1] = x * a[1];\n out[2] = x * a[2];\n out[3] = y * a[3];\n out[4] = y * a[4];\n out[5] = y * a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\n * Generates a 2D projection matrix with the given bounds\n *\n * @param {mat3} out mat3 frustum matrix will be written into\n * @param {number} width Width of your gl context\n * @param {number} height Height of gl context\n * @returns {mat3} out\n */\n\nfunction projection(out, width, height) {\n out[0] = 2 / width;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = -2 / height;\n out[5] = 0;\n out[6] = -1;\n out[7] = 1;\n out[8] = 1;\n return out;\n}\n\n// A \"texture atlas\" is a big canvas, and sections of it are used as textures for nodes/labels.\n\n/**\n * A single square texture atlas (also known as a \"sprite sheet\").\n */\nvar Atlas = /*#__PURE__*/function () {\n function Atlas(r, texSize, texRows, createTextureCanvas) {\n _classCallCheck(this, Atlas);\n this.debugID = Math.floor(Math.random() * 10000);\n this.r = r;\n this.texSize = texSize;\n this.texRows = texRows;\n this.texHeight = Math.floor(texSize / texRows);\n this.enableWrapping = true; // hardcoded for now, can be made an option\n\n this.locked = false; // once an atlas is locked it can no longer be drawn to\n this.texture = null; // WebGLTexture object\n this.needsBuffer = true;\n\n // a \"location\" is an pointer into the atlas with a 'row' and 'x' fields\n this.freePointer = {\n x: 0,\n row: 0\n };\n\n // map from the style key to the row/x where the texture starts\n // if the texture wraps then there's a second location\n this.keyToLocation = new Map(); // styleKey -> [ location, location ]\n\n this.canvas = createTextureCanvas(r, texSize, texSize);\n this.scratch = createTextureCanvas(r, texSize, this.texHeight, 'scratch');\n }\n return _createClass(Atlas, [{\n key: \"lock\",\n value: function lock() {\n this.locked = true;\n }\n }, {\n key: \"getKeys\",\n value: function getKeys() {\n return new Set(this.keyToLocation.keys());\n }\n }, {\n key: \"getScale\",\n value: function getScale(_ref) {\n var w = _ref.w,\n h = _ref.h;\n var texHeight = this.texHeight,\n maxTexWidth = this.texSize;\n // try to fit to the height of a row\n var scale = texHeight / h; // TODO what about pixelRatio?\n var texW = w * scale;\n var texH = h * scale;\n // if the scaled width is too wide then scale to fit max width instead\n if (texW > maxTexWidth) {\n scale = maxTexWidth / w;\n texW = w * scale;\n texH = h * scale;\n }\n return {\n scale: scale,\n texW: texW,\n texH: texH\n };\n }\n }, {\n key: \"draw\",\n value: function draw(key, bb, doDrawing) {\n var _this = this;\n if (this.locked) throw new Error('can\\'t draw, atlas is locked');\n var texSize = this.texSize,\n texRows = this.texRows,\n texHeight = this.texHeight;\n var _this$getScale = this.getScale(bb),\n scale = _this$getScale.scale,\n texW = _this$getScale.texW,\n texH = _this$getScale.texH;\n var drawAt = function drawAt(location, canvas) {\n if (doDrawing && canvas) {\n var context = canvas.context;\n var x = location.x,\n row = location.row;\n var xOffset = x;\n var yOffset = texHeight * row;\n context.save();\n context.translate(xOffset, yOffset);\n context.scale(scale, scale);\n doDrawing(context, bb);\n context.restore();\n }\n };\n var locations = [null, null];\n var drawNormal = function drawNormal() {\n // don't need to wrap, draw directly on the canvas\n drawAt(_this.freePointer, _this.canvas);\n locations[0] = {\n x: _this.freePointer.x,\n y: _this.freePointer.row * texHeight,\n w: texW,\n h: texH\n };\n locations[1] = {\n // create a second location with a width of 0, for convenience\n x: _this.freePointer.x + texW,\n y: _this.freePointer.row * texHeight,\n w: 0,\n h: texH\n };\n\n // move the pointer to the end of the texture\n _this.freePointer.x += texW;\n if (_this.freePointer.x == texSize) {\n _this.freePointer.x = 0;\n _this.freePointer.row++;\n }\n };\n var drawWrapped = function drawWrapped() {\n var scratch = _this.scratch,\n canvas = _this.canvas;\n\n // Draw to the scratch canvas\n scratch.clear();\n drawAt({\n x: 0,\n row: 0\n }, scratch);\n var firstTexW = texSize - _this.freePointer.x;\n var secondTexW = texW - firstTexW;\n var h = texHeight;\n {\n // copy first part of scratch to the first texture\n var dx = _this.freePointer.x;\n var dy = _this.freePointer.row * texHeight;\n var w = firstTexW;\n canvas.context.drawImage(scratch, 0, 0, w, h, dx, dy, w, h);\n locations[0] = {\n x: dx,\n y: dy,\n w: w,\n h: texH\n };\n }\n {\n // copy second part of scratch to the second texture\n var sx = firstTexW;\n var _dy = (_this.freePointer.row + 1) * texHeight;\n var _w = secondTexW;\n if (canvas) {\n canvas.context.drawImage(scratch, sx, 0, _w, h, 0, _dy, _w, h);\n }\n locations[1] = {\n x: 0,\n y: _dy,\n w: _w,\n h: texH\n };\n }\n _this.freePointer.x = secondTexW;\n _this.freePointer.row++;\n };\n var moveToStartOfNextRow = function moveToStartOfNextRow() {\n _this.freePointer.x = 0;\n _this.freePointer.row++;\n };\n if (this.freePointer.x + texW <= texSize) {\n // There's enough space in the current row\n drawNormal();\n } else if (this.freePointer.row >= texRows - 1) {\n // Need to move to the next row, but there are no more rows, atlas is full.\n return false;\n } else if (this.freePointer.x === texSize) {\n // happen to be right at end of current row\n moveToStartOfNextRow();\n drawNormal();\n } else if (this.enableWrapping) {\n // draw part of the texture to the end of the curent row, then wrap to the next row\n drawWrapped();\n } else {\n // move to the start of the next row, then draw normally\n moveToStartOfNextRow();\n drawNormal();\n }\n this.keyToLocation.set(key, locations);\n this.needsBuffer = true;\n return locations;\n }\n }, {\n key: \"getOffsets\",\n value: function getOffsets(key) {\n return this.keyToLocation.get(key);\n }\n }, {\n key: \"isEmpty\",\n value: function isEmpty() {\n return this.freePointer.x === 0 && this.freePointer.row === 0;\n }\n }, {\n key: \"canFit\",\n value: function canFit(bb) {\n if (this.locked) return false;\n var texSize = this.texSize,\n texRows = this.texRows;\n var _this$getScale2 = this.getScale(bb),\n texW = _this$getScale2.texW;\n if (this.freePointer.x + texW > texSize) {\n // need to wrap\n return this.freePointer.row < texRows - 1; // return true if there's a row to wrap to\n }\n return true;\n }\n\n // called on every frame\n }, {\n key: \"bufferIfNeeded\",\n value: function bufferIfNeeded(gl) {\n if (!this.texture) {\n this.texture = createTexture(gl, this.debugID);\n }\n if (this.needsBuffer) {\n this.texture.buffer(this.canvas);\n this.needsBuffer = false;\n if (this.locked) {\n this.canvas = null;\n this.scratch = null;\n }\n }\n }\n }, {\n key: \"dispose\",\n value: function dispose() {\n if (this.texture) {\n this.texture.deleteTexture();\n this.texture = null;\n }\n this.canvas = null;\n this.scratch = null;\n this.locked = true;\n }\n }]);\n}();\n\n/**\n * A collection of texture atlases, all of the same \"render type\". \n * ('node-body' is an example of a render type.)\n * An AtlasCollection can also be notified when a texture is no longer needed, \n * and it can garbage collect the unused textures.\n */\nvar AtlasCollection = /*#__PURE__*/function () {\n function AtlasCollection(r, texSize, texRows, createTextureCanvas) {\n _classCallCheck(this, AtlasCollection);\n this.r = r;\n this.texSize = texSize;\n this.texRows = texRows;\n this.createTextureCanvas = createTextureCanvas;\n this.atlases = [];\n this.styleKeyToAtlas = new Map();\n this.markedKeys = new Set(); // marked for garbage collection\n }\n return _createClass(AtlasCollection, [{\n key: \"getKeys\",\n value: function getKeys() {\n return new Set(this.styleKeyToAtlas.keys());\n }\n }, {\n key: \"_createAtlas\",\n value: function _createAtlas() {\n var r = this.r,\n texSize = this.texSize,\n texRows = this.texRows,\n createTextureCanvas = this.createTextureCanvas;\n return new Atlas(r, texSize, texRows, createTextureCanvas);\n }\n }, {\n key: \"_getScratchCanvas\",\n value: function _getScratchCanvas() {\n if (!this.scratch) {\n var r = this.r,\n texSize = this.texSize,\n texRows = this.texRows,\n createTextureCanvas = this.createTextureCanvas;\n var texHeight = Math.floor(texSize / texRows);\n this.scratch = createTextureCanvas(r, texSize, texHeight, 'scratch');\n }\n return this.scratch;\n }\n }, {\n key: \"draw\",\n value: function draw(key, bb, doDrawing) {\n var atlas = this.styleKeyToAtlas.get(key);\n if (!atlas) {\n // check for space at the end of the last atlas\n atlas = this.atlases[this.atlases.length - 1];\n if (!atlas || !atlas.canFit(bb)) {\n if (atlas) atlas.lock();\n // create a new atlas\n atlas = this._createAtlas();\n this.atlases.push(atlas);\n }\n atlas.draw(key, bb, doDrawing);\n this.styleKeyToAtlas.set(key, atlas);\n }\n return atlas;\n }\n }, {\n key: \"getAtlas\",\n value: function getAtlas(key) {\n return this.styleKeyToAtlas.get(key);\n }\n }, {\n key: \"hasAtlas\",\n value: function hasAtlas(key) {\n return this.styleKeyToAtlas.has(key);\n }\n }, {\n key: \"markKeyForGC\",\n value: function markKeyForGC(key) {\n this.markedKeys.add(key);\n }\n }, {\n key: \"gc\",\n value: function gc() {\n var _this2 = this;\n var markedKeys = this.markedKeys;\n if (markedKeys.size === 0) {\n console.log('nothing to garbage collect');\n return;\n }\n var newAtlases = [];\n var newStyleKeyToAtlas = new Map();\n var newAtlas = null;\n var _iterator = _createForOfIteratorHelper(this.atlases),\n _step;\n try {\n var _loop = function _loop() {\n var atlas = _step.value;\n var keys = atlas.getKeys();\n var keysToCollect = intersection(markedKeys, keys);\n if (keysToCollect.size === 0) {\n // this atlas can still be used\n newAtlases.push(atlas);\n keys.forEach(function (k) {\n return newStyleKeyToAtlas.set(k, atlas);\n });\n return 1; // continue\n }\n if (!newAtlas) {\n newAtlas = _this2._createAtlas();\n newAtlases.push(newAtlas);\n }\n var _iterator2 = _createForOfIteratorHelper(keys),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var key = _step2.value;\n if (!keysToCollect.has(key)) {\n var _atlas$getOffsets = atlas.getOffsets(key),\n _atlas$getOffsets2 = _slicedToArray(_atlas$getOffsets, 2),\n s1 = _atlas$getOffsets2[0],\n s2 = _atlas$getOffsets2[1];\n if (!newAtlas.canFit({\n w: s1.w + s2.w,\n h: s1.h\n })) {\n newAtlas.lock();\n newAtlas = _this2._createAtlas();\n newAtlases.push(newAtlas);\n }\n if (atlas.canvas) {\n // if the texture can't be copied then it will have to be redrawn on the next frame\n _this2._copyTextureToNewAtlas(key, atlas, newAtlas);\n newStyleKeyToAtlas.set(key, newAtlas);\n }\n }\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n atlas.dispose();\n };\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n if (_loop()) continue;\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n this.atlases = newAtlases;\n this.styleKeyToAtlas = newStyleKeyToAtlas;\n this.markedKeys = new Set();\n }\n }, {\n key: \"_copyTextureToNewAtlas\",\n value: function _copyTextureToNewAtlas(key, oldAtlas, newAtlas) {\n var _oldAtlas$getOffsets = oldAtlas.getOffsets(key),\n _oldAtlas$getOffsets2 = _slicedToArray(_oldAtlas$getOffsets, 2),\n s1 = _oldAtlas$getOffsets2[0],\n s2 = _oldAtlas$getOffsets2[1];\n if (s2.w === 0) {\n // the texture does not wrap, draw directly to new atlas\n newAtlas.draw(key, s1, function (context) {\n context.drawImage(oldAtlas.canvas, s1.x, s1.y, s1.w, s1.h, 0, 0, s1.w, s1.h);\n });\n } else {\n // the texture wraps, first draw both parts to a scratch canvas\n var scratch = this._getScratchCanvas();\n scratch.clear();\n scratch.context.drawImage(oldAtlas.canvas, s1.x, s1.y, s1.w, s1.h, 0, 0, s1.w, s1.h);\n scratch.context.drawImage(oldAtlas.canvas, s2.x, s2.y, s2.w, s2.h, s1.w, 0, s2.w, s2.h);\n\n // now draw the scratch to the new atlas\n var w = s1.w + s2.w;\n var h = s1.h;\n newAtlas.draw(key, {\n w: w,\n h: h\n }, function (context) {\n context.drawImage(scratch, 0, 0, w, h, 0, 0, w, h // the destination context has already been translated to the correct position\n );\n });\n }\n }\n }, {\n key: \"getCounts\",\n value: function getCounts() {\n return {\n keyCount: this.styleKeyToAtlas.size,\n atlasCount: new Set(this.styleKeyToAtlas.values()).size\n };\n }\n }]);\n}();\nfunction intersection(set1, set2) {\n // TODO why no Set.intersection in node 16???\n if (set1.intersection) return set1.intersection(set2);else return new Set(_toConsumableArray(set1).filter(function (x) {\n return set2.has(x);\n }));\n}\n\n/**\n * Used to manage batches of Atlases for drawing nodes and labels.\n * Supports different types of AtlasCollections for different render types,\n * for example 'node-body' and 'node-label' would be different render types.\n * Render types are kept separate because they will likely need to be garbage collected\n * separately and its not entierly guaranteed that their style keys won't collide.\n */\nvar AtlasManager = /*#__PURE__*/function () {\n function AtlasManager(r, globalOptions) {\n _classCallCheck(this, AtlasManager);\n this.r = r;\n this.globalOptions = globalOptions;\n this.atlasSize = globalOptions.webglTexSize;\n this.maxAtlasesPerBatch = globalOptions.webglTexPerBatch;\n this.renderTypes = new Map(); // renderType:string -> renderTypeOptions\n this.collections = new Map(); // collectionName:string -> AtlasCollection\n\n this.typeAndIdToKey = new Map(); // [renderType,id] => Array